diff --git a/api/collection_submission_actions/serializers.py b/api/collection_submission_actions/serializers.py index 20db9754229..8f6a61bc31d 100644 --- a/api/collection_submission_actions/serializers.py +++ b/api/collection_submission_actions/serializers.py @@ -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 @@ -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() diff --git a/api/collections/serializers.py b/api/collections/serializers.py index 80d16e1bd84..b6d6d340949 100644 --- a/api/collections/serializers.py +++ b/api/collections/serializers.py @@ -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 @@ -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( @@ -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: @@ -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: diff --git a/api/draft_registrations/serializers.py b/api/draft_registrations/serializers.py index f08426d32a7..652785380f9 100644 --- a/api/draft_registrations/serializers.py +++ b/api/draft_registrations/serializers.py @@ -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 @@ -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', @@ -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 diff --git a/api/registrations/serializers.py b/api/registrations/serializers.py index 62e53422d93..fd68d720687 100644 --- a/api/registrations/serializers.py +++ b/api/registrations/serializers.py @@ -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( diff --git a/api_tests/collections/test_collection_license_provider.py b/api_tests/collections/test_collection_license_provider.py new file mode 100644 index 00000000000..673f453905b --- /dev/null +++ b/api_tests/collections/test_collection_license_provider.py @@ -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 diff --git a/api_tests/draft_registrations/views/test_draft_registration_license_provider.py b/api_tests/draft_registrations/views/test_draft_registration_license_provider.py new file mode 100644 index 00000000000..2f869e3b26d --- /dev/null +++ b/api_tests/draft_registrations/views/test_draft_registration_license_provider.py @@ -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.' diff --git a/api_tests/providers/tasks/test_bulk_upload.py b/api_tests/providers/tasks/test_bulk_upload.py index 4ebc5ac8c53..8a7dade653c 100644 --- a/api_tests/providers/tasks/test_bulk_upload.py +++ b/api_tests/providers/tasks/test_bulk_upload.py @@ -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'] } @@ -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'] } @@ -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'] } @@ -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'] } diff --git a/api_tests/registrations/views/test_registration_detail.py b/api_tests/registrations/views/test_registration_detail.py index dfbfc91f4b3..bb3b8afa968 100644 --- a/api_tests/registrations/views/test_registration_detail.py +++ b/api_tests/registrations/views/test_registration_detail.py @@ -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}/' diff --git a/api_tests/registrations/views/test_registration_license_provider.py b/api_tests/registrations/views/test_registration_license_provider.py new file mode 100644 index 00000000000..3882e3673a5 --- /dev/null +++ b/api_tests/registrations/views/test_registration_license_provider.py @@ -0,0 +1,168 @@ +import pytest + +from api.base.settings.defaults import API_BASE +from osf.models import NodeLicense +from osf_tests.factories import ( + AuthUserFactory, + EmbargoFactory, + RegistrationFactory, + RegistrationProviderFactory, + ProjectFactory, + NodeLicenseRecordFactory, +) + + +def license_payload(registration_id, license_id, year='2026', holders=None): + return { + 'data': { + 'type': 'registrations', + 'id': registration_id, + 'attributes': { + 'node_license': { + 'year': year, + 'copyright_holders': holders or ['Someone'], + }, + }, + 'relationships': { + 'license': {'data': {'type': 'licenses', 'id': license_id}}, + }, + }, + } + + +@pytest.mark.django_db +class TestRegistrationLicenseEnforcedByProvider: + + @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 no_license(self): + return NodeLicense.objects.get(license_id='NONE') + + @pytest.fixture() + def provider(self, cc0): + provider = RegistrationProviderFactory() + provider.licenses_acceptable.add(cc0) + return provider + + @pytest.fixture() + def registration(self, user, provider, cc0): + reg = RegistrationFactory(creator=user, provider=provider, is_public=True) + reg.node_license = NodeLicenseRecordFactory(node_license=cc0) + reg.save() + return reg + + def url(self, registration): + return f'/{API_BASE}registrations/{registration._id}/' + + def test_accepted_license_saves(self, app, user, registration, cc0): + res = app.patch_json_api( + self.url(registration), + license_payload(registration._id, cc0._id, year='2030'), + auth=user.auth, + ) + assert res.status_code == 200 + assert res.json['data']['attributes']['node_license']['year'] == '2030' + + def test_unaccepted_license_rejected(self, app, user, registration, provider, mit): + res = app.patch_json_api( + self.url(registration), + license_payload(registration._id, 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}." + registration.refresh_from_db() + assert registration.node_license.node_license != mit + + def test_no_license_always_rejected_for_registrations(self, app, user, registration, provider, no_license): + # rejected when the provider does not list it... + res = app.patch_json_api( + self.url(registration), + license_payload(registration._id, no_license._id), + auth=user.auth, + expect_errors=True, + ) + assert res.status_code == 400 + assert 'is not accepted by' in res.json['errors'][0]['detail'] + assert 'Registrations require a license' in res.json['errors'][0]['detail'] + + # ...and also when it does + provider.licenses_acceptable.add(no_license) + res = app.patch_json_api( + self.url(registration), + license_payload(registration._id, 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'] + registration.refresh_from_db() + assert registration.node_license.node_license != no_license + + def test_null_node_license_has_clear_message(self, app, user, registration): + res = app.patch_json_api( + self.url(registration), + {'data': {'type': 'registrations', 'id': registration._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.' + + def test_null_license_relationship_rejected(self, app, user, registration): + res = app.patch_json_api( + self.url(registration), + {'data': {'type': 'registrations', 'id': registration._id, 'relationships': {'license': {'data': None}}}}, + auth=user.auth, + expect_errors=True, + ) + assert res.status_code == 400 + registration.refresh_from_db() + assert registration.node_license is not None + + def test_provider_without_restrictions_accepts_any_license(self, app, user, registration, provider, mit): + provider.licenses_acceptable.clear() + res = app.patch_json_api( + self.url(registration), + license_payload(registration._id, mit._id), + auth=user.auth, + ) + assert res.status_code == 200 + + def test_embargoed_registration_enforced(self, app, user, provider, cc0, mit): + reg = RegistrationFactory(creator=user, provider=provider, embargo=EmbargoFactory(user=user), is_public=False) + reg.node_license = NodeLicenseRecordFactory(node_license=cc0) + reg.save() + res = app.patch_json_api( + self.url(reg), + license_payload(reg._id, mit._id), + auth=user.auth, + expect_errors=True, + ) + assert res.status_code == 400 + + res = app.patch_json_api( + self.url(reg), + license_payload(reg._id, cc0._id), + auth=user.auth, + ) + assert res.status_code == 200 + + def test_registering_still_works_with_unaccepted_license(self, user, provider, mit): + project = ProjectFactory(creator=user) + project.node_license = NodeLicenseRecordFactory(node_license=mit) + project.save() + reg = RegistrationFactory(project=project, creator=user, provider=provider) + assert reg.node_license.node_license == mit diff --git a/osf/exceptions.py b/osf/exceptions.py index ec591545e40..f13bac22198 100644 --- a/osf/exceptions.py +++ b/osf/exceptions.py @@ -42,6 +42,11 @@ class NodeStateError(NodeError): pass +class LicenseNotAcceptedError(NodeStateError): + """Raised when a license is not in the provider's list of accepted licenses""" + pass + + class UserStateError(OSFError): """Raised when the user's state is not suitable for the requested action diff --git a/osf/models/collection_submission.py b/osf/models/collection_submission.py index d15c3dbaf0f..56a8b336eaf 100644 --- a/osf/models/collection_submission.py +++ b/osf/models/collection_submission.py @@ -11,6 +11,7 @@ from .mixins import TaxonomizableMixin from osf.utils.permissions import ADMIN from website.util import api_v2_url +from website.project.licenses import validate_object_license_for_collection_provider from website.search.exceptions import SearchUnavailableError from osf.utils.workflows import CollectionSubmissionsTriggers, CollectionSubmissionStates @@ -204,6 +205,8 @@ def _validate_accept(self, event_data): if not is_moderator: raise PermissionsError(f'{user} must have moderator permissions.') + validate_object_license_for_collection_provider(self.guid.referent, self.collection.provider) + def _notify_accepted(self, event_data): if self.collection.provider: logo_context = {} @@ -395,6 +398,8 @@ def _validate_resubmit(self, event_data): if not is_admin: raise PermissionsError(f'{user} must have admin permissions.') + validate_object_license_for_collection_provider(self.guid.referent, self.collection.provider) + def _validate_cancel(self, event_data): user = event_data.kwargs.get('user') force = event_data.kwargs.get('force') diff --git a/osf_tests/test_licenses_provider_validation.py b/osf_tests/test_licenses_provider_validation.py new file mode 100644 index 00000000000..a0a108cc434 --- /dev/null +++ b/osf_tests/test_licenses_provider_validation.py @@ -0,0 +1,56 @@ +import pytest + +from framework.auth import Auth +from osf.exceptions import LicenseNotAcceptedError +from osf.models import NodeLicense +from osf_tests.factories import ( + AuthUserFactory, + DraftRegistrationFactory, + RegistrationProviderFactory, +) +from website.project.licenses import validate_license_for_provider + + +@pytest.mark.django_db +class TestValidateLicenseForProvider: + + @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') + + def test_empty_list_accepts_anything(self, mit): + validate_license_for_provider(RegistrationProviderFactory(), mit) + + def test_accepted(self, cc0): + provider = RegistrationProviderFactory() + provider.licenses_acceptable.add(cc0) + validate_license_for_provider(provider, cc0) + + def test_not_accepted(self, cc0, mit): + provider = RegistrationProviderFactory() + provider.licenses_acceptable.add(cc0) + with pytest.raises(LicenseNotAcceptedError, match='is not accepted by'): + validate_license_for_provider(provider, mit) + + def test_draft_registration_enforced(self, cc0, mit): + user = AuthUserFactory() + provider = RegistrationProviderFactory() + provider.licenses_acceptable.add(cc0) + draft = DraftRegistrationFactory(initiator=user, provider=provider) + auth = Auth(user) + draft.set_node_license({'id': cc0.license_id, 'year': '2026', 'copyrightHolders': ['A']}, auth) + with pytest.raises(LicenseNotAcceptedError): + draft.set_node_license({'id': mit.license_id, 'year': '2026', 'copyrightHolders': ['A']}, auth) + + def test_no_license_rejected_for_registration_even_if_provider_lists_it(self, cc0): + user = AuthUserFactory() + no_license = NodeLicense.objects.get(license_id='NONE') + provider = RegistrationProviderFactory() + provider.licenses_acceptable.add(cc0, no_license) + draft = DraftRegistrationFactory(initiator=user, provider=provider) + with pytest.raises(LicenseNotAcceptedError, match='Registrations require a license'): + draft.set_node_license({'id': 'NONE', 'year': '2026', 'copyrightHolders': ['A']}, Auth(user)) diff --git a/website/project/licenses/__init__.py b/website/project/licenses/__init__.py index 07095936cfe..6944e01fa0a 100644 --- a/website/project/licenses/__init__.py +++ b/website/project/licenses/__init__.py @@ -4,6 +4,42 @@ from framework import exceptions as framework_exceptions from osf import exceptions as osf_exceptions from osf.utils import permissions +from osf.utils.workflows import CollectionSubmissionStates + + +NO_LICENSE_ID = 'NONE' + + +def validate_license_for_provider(provider, node_license): + if not provider or not node_license: + return + acceptable = provider.licenses_acceptable + if acceptable.exists() and not acceptable.filter(id=node_license.id).exists(): + raise osf_exceptions.LicenseNotAcceptedError( + f"The license '{node_license.name}' is not accepted by {provider.name}.", + ) + + +def validate_license_for_collections(node, node_license): + CollectionSubmission = apps.get_model('osf.CollectionSubmission') + submissions = CollectionSubmission.objects.filter( + guid___id=node._id, + machine_state__in=[CollectionSubmissionStates.PENDING.value, CollectionSubmissionStates.ACCEPTED.value], + collection__provider__licenses_acceptable__isnull=False, + ).select_related('collection__provider').distinct() + for submission in submissions: + validate_license_for_provider(submission.collection.provider, node_license) + + +def validate_object_license_for_collection_provider(obj, provider): + if not provider or not provider.licenses_acceptable.exists(): + return + license_record = getattr(obj, 'license', None) + if not license_record: + raise osf_exceptions.LicenseNotAcceptedError( + f'A license accepted by {provider.name} is required.', + ) + validate_license_for_provider(provider, license_record.node_license) def set_license(node, license_detail, auth, node_type='node', ignore_permission=False): @@ -37,6 +73,15 @@ def set_license(node, license_detail, auth, node_type='node', ignore_permission= if node_type == 'preprint': if node.provider.licenses_acceptable.exists() and not node.provider.licenses_acceptable.filter(id=node_license.id): raise framework_exceptions.PermissionsError(f'Invalid license chosen for {node.provider.name}') + elif isinstance(node, (apps.get_model('osf.Registration'), apps.get_model('osf.DraftRegistration'))): + provider = getattr(node, 'provider', None) + if node_license.license_id == NO_LICENSE_ID: + raise osf_exceptions.LicenseNotAcceptedError( + f"The license '{node_license.name}' is not accepted by {provider.name if provider else 'registrations'}. " + 'Registrations require a license.', + ) + validate_license_for_provider(provider, node_license) + validate_license_for_collections(node, node_license) for required_property in node_license.properties: if not license_detail.get(required_property):