diff --git a/scanpipe/models.py b/scanpipe/models.py index 501759d1e3..6f3c5f550c 100644 --- a/scanpipe/models.py +++ b/scanpipe/models.py @@ -73,6 +73,7 @@ from commoncode.fileutils import parent_directory from cyclonedx import model as cyclonedx_model from cyclonedx.model import component as cyclonedx_component +from cyclonedx.model import contact as cyclonedx_contact from cyclonedx.model import license as cyclonedx_license from extractcode import EXTRACT_SUFFIX from licensedcode.cache import build_spdx_license_expression @@ -3666,6 +3667,42 @@ class AbstractPackage(models.Model): class Meta: abstract = True + def extract_from_parties(self, roles): + """ + Extract parties matching the given roles, deduplicated by name. + + Args: + roles: Tuple of role strings to filter by. + + Returns: + List of party dicts matching the specified roles, unique by name. + + """ + seen_names = set() + results = [] + for party in self.parties or []: + if party.get("role") in roles: + name = party.get("name") + if name and name not in seen_names: + seen_names.add(name) + results.append(party) + return results + + def get_author_names(self, roles=("author", "maintainer")): + """ + Return a sorted list of party names matching the specified roles. + + Args: + roles: Tuple of role strings to filter by. + Defaults to ("author", "maintainer"). + + Returns: + Sorted list of party names. + + """ + parties = self.extract_from_parties(roles=roles) + return sorted(party["name"] for party in parties) + class DiscoveredPackage( ProjectRelatedModel, @@ -3952,6 +3989,14 @@ def as_cyclonedx(self): if (hash_value := getattr(self, field_name)) ] + authors = [ + cyclonedx_contact.OrganizationalContact( + name=party.get("name", ""), + email=party.get("email", ""), + ) + for party in self.extract_from_parties(roles=("author", "maintainer")) + ] + # Those fields are not supported natively by CycloneDX but are required to # load the BOM without major data loss. # See https://github.com/nexB/aboutcode-cyclonedx-taxonomy @@ -4012,6 +4057,7 @@ def as_cyclonedx(self): properties=properties, external_references=external_references, evidence=evidence, + authors=authors, ) diff --git a/scanpipe/pipes/ort.py b/scanpipe/pipes/ort.py index 44f2278c72..7034daef07 100644 --- a/scanpipe/pipes/ort.py +++ b/scanpipe/pipes/ort.py @@ -136,12 +136,6 @@ def to_ort_package_list_yml(project): dependencies = [] for package in project.discoveredpackages.all(): - authors = { - party.get("name").strip() - for party in package.parties - if party.get("role") in ("author", "maintainer") and party.get("name") - } - dependency = Dependency( id=f"{project_type or package.type}::{package.name}:{package.version}", purl=package.purl, @@ -150,7 +144,7 @@ def to_ort_package_list_yml(project): vcs=Vcs(url=package.vcs_url), description=package.description, homepageUrl=package.homepage_url, - authors=sorted(authors), + authors=package.get_author_names(), ) dependencies.append(dependency) diff --git a/scanpipe/tests/__init__.py b/scanpipe/tests/__init__.py index ea38174917..7fd00efbe5 100644 --- a/scanpipe/tests/__init__.py +++ b/scanpipe/tests/__init__.py @@ -196,6 +196,42 @@ def make_mock_response(url, content=b"\x00", status_code=200, headers=None): "extra_data": {}, } +parties_data1 = [ + { + "name": "AboutCode and others", + "role": "author", + "type": "person", + "email": "info@aboutcode.org", + "url": None, + }, + # Duplicate on purpose + { + "name": "AboutCode and others", + "role": "author", + "type": "person", + "email": "info@aboutcode.org", + "url": None, + }, + { + "name": "Debian X Strike Force", + "role": "maintainer", + "email": "debian-x@lists.debian.org", + }, + { + "name": "JBoss.org Community", + "role": "developer", + "type": "person", + "email": None, + }, + { + "url": "http://www.apache.org/", + "name": "The Apache Software Foundation", + "role": "owner", + "type": "organization", + "email": None, + }, +] + package_data1 = { "type": "deb", "namespace": "debian", diff --git a/scanpipe/tests/data/cyclonedx/asgiref-3.3.0.cdx.json b/scanpipe/tests/data/cyclonedx/asgiref-3.3.0.cdx.json index d354df7e99..7fd66899ef 100644 --- a/scanpipe/tests/data/cyclonedx/asgiref-3.3.0.cdx.json +++ b/scanpipe/tests/data/cyclonedx/asgiref-3.3.0.cdx.json @@ -26,6 +26,12 @@ }, "components": [ { + "authors": [ + { + "email": "foundation@djangoproject.com", + "name": "Django Software Foundation" + } + ], "bom-ref": "pkg:pypi/asgiref@3.3.0?uuid=078ee2a1-aa92-4f80-8032-8af0b3c26663", "copyright": "", "description": "ASGI specs, helper code, and adapters\nasgiref\n=======\n\n.. image:: https://api.travis-ci.org/django/asgiref.svg\n :target: https://travis-ci.org/django/asgiref\n\n.. image:: https://img.shields.io/pypi/v/asgiref.svg\n :target: https://pypi.python.org/pypi/asgiref\n\nASGI is a standard for Python asynchronous web apps and servers to communicate\nwith each other, and positioned as an asynchronous successor to WSGI. You can\nread more at https://asgi.readthedocs.io/en/latest/\n\nThis package includes ASGI base libraries, such as:\n\n* Sync-to-async and async-to-sync function wrappers, ``asgiref.sync``\n* Server base classes, ``asgiref.server``\n* A WSGI-to-ASGI adapter, in ``asgiref.wsgi``\n\n\nFunction wrappers\n-----------------\n\nThese allow you to wrap or decorate async or sync functions to call them from\nthe other style (so you can call async functions from a synchronous thread,\nor vice-versa).\n\nIn particular:\n\n* AsyncToSync lets a synchronous subthread stop and wait while the async\n function is called on the main thread's event loop, and then control is\n returned to the thread when the async function is finished.\n\n* SyncToAsync lets async code call a synchronous function, which is run in\n a threadpool and control returned to the async coroutine when the synchronous\n function completes.\n\nThe idea is to make it easier to call synchronous APIs from async code and\nasynchronous APIs from synchronous code so it's easier to transition code from\none style to the other. In the case of Channels, we wrap the (synchronous)\nDjango view system with SyncToAsync to allow it to run inside the (asynchronous)\nASGI server.\n\nNote that exactly what threads things run in is very specific, and aimed to\nkeep maximum compatibility with old synchronous code. See\n\"Synchronous code & Threads\" below for a full explanation. By default,\n``sync_to_async`` will run all synchronous code in the program in the same\nthread for safety reasons; you can disable this for more performance with\n``@sync_to_async(thread_sensitive=False)``, but make sure that your code does\nnot rely on anything bound to threads (like database connections) when you do.\n\n\nThreadlocal replacement\n-----------------------\n\nThis is a drop-in replacement for ``threading.local`` that works with both\nthreads and asyncio Tasks. Even better, it will proxy values through from a\ntask-local context to a thread-local context when you use ``sync_to_async``\nto run things in a threadpool, and vice-versa for ``async_to_sync``.\n\nIf you instead want true thread- and task-safety, you can set\n``thread_critical`` on the Local object to ensure this instead.\n\n\nServer base classes\n-------------------\n\nIncludes a ``StatelessServer`` class which provides all the hard work of\nwriting a stateless server (as in, does not handle direct incoming sockets\nbut instead consumes external streams or sockets to work out what is happening).\n\nAn example of such a server would be a chatbot server that connects out to\na central chat server and provides a \"connection scope\" per user chatting to\nit. There's only one actual connection, but the server has to separate things\ninto several scopes for easier writing of the code.\n\nYou can see an example of this being used in `frequensgi `_.\n\n\nWSGI-to-ASGI adapter\n--------------------\n\nAllows you to wrap a WSGI application so it appears as a valid ASGI application.\n\nSimply wrap it around your WSGI application like so::\n\n asgi_application = WsgiToAsgi(wsgi_application)\n\nThe WSGI application will be run in a synchronous threadpool, and the wrapped\nASGI application will be one that accepts ``http`` class messages.\n\nPlease note that not all extended features of WSGI may be supported (such as\nfile handles for incoming POST bodies).\n\n\nDependencies\n------------\n\n``asgiref`` requires Python 3.5 or higher.\n\n\nContributing\n------------\n\nPlease refer to the\n`main Channels contributing docs `_.\n\n\nTesting\n'''''''\n\nTo run tests, make sure you have installed the ``tests`` extra with the package::\n\n cd asgiref/\n pip install -e .[tests]\n pytest\n\n\nBuilding the documentation\n''''''''''''''''''''''''''\n\nThe documentation uses `Sphinx `_::\n\n cd asgiref/docs/\n pip install sphinx\n\nTo build the docs, you can use the default tools::\n\n sphinx-build -b html . _build/html # or `make html`, if you've got make set up\n cd _build/html\n python -m http.server\n\n...or you can use ``sphinx-autobuild`` to run a server and rebuild/reload\nyour documentation changes automatically::\n\n pip install sphinx-autobuild\n sphinx-autobuild . _build/html\n\n\nImplementation Details\n----------------------\n\nSynchronous code & threads\n''''''''''''''''''''''''''\n\nThe ``asgiref.sync`` module provides two wrappers that let you go between\nasynchronous and synchronous code at will, while taking care of the rough edges\nfor you.\n\nUnfortunately, the rough edges are numerous, and the code has to work especially\nhard to keep things in the same thread as much as possible. Notably, the\nrestrictions we are working with are:\n\n* All synchronous code called through ``SyncToAsync`` and marked with\n ``thread_sensitive`` should run in the same thread as each other (and if the\n outer layer of the program is synchronous, the main thread)\n\n* If a thread already has a running async loop, ``AsyncToSync`` can't run things\n on that loop if it's blocked on synchronous code that is above you in the\n call stack.\n\nThe first compromise you get to might be that ``thread_sensitive`` code should\njust run in the same thread and not spawn in a sub-thread, fulfilling the first\nrestriction, but that immediately runs you into the second restriction.\n\nThe only real solution is to essentially have a variant of ThreadPoolExecutor\nthat executes any ``thread_sensitive`` code on the outermost synchronous\nthread - either the main thread, or a single spawned subthread.\n\nThis means you now have two basic states:\n\n* If the outermost layer of your program is synchronous, then all async code\n run through ``AsyncToSync`` will run in a per-call event loop in arbitary\n sub-threads, while all ``thread_sensitive`` code will run in the main thread.\n\n* If the outermost layer of your program is asynchronous, then all async code\n runs on the main thread's event loop, and all ``thread_sensitive`` synchronous\n code will run in a single shared sub-thread.\n\nCruicially, this means that in both cases there is a thread which is a shared\nresource that all ``thread_sensitive`` code must run on, and there is a chance\nthat this thread is currently blocked on its own ``AsyncToSync`` call. Thus,\n``AsyncToSync`` needs to act as an executor for thread code while it's blocking.\n\nThe ``CurrentThreadExecutor`` class provides this functionality; rather than\nsimply waiting on a Future, you can call its ``run_until_future`` method and\nit will run submitted code until that Future is done. This means that code\ninside the call can then run code on your thread.\n\n\nMaintenance and Security\n------------------------\n\nTo report security issues, please contact security@djangoproject.com. For GPG\nsignatures and more security process information, see\nhttps://docs.djangoproject.com/en/dev/internals/security/.\n\nTo report bugs or request new features, please open a new GitHub issue.\n\nThis repository is part of the Channels project. For the shepherd and maintenance team, please see the\n`main Channels readme `_.", @@ -75,6 +81,12 @@ "version": "3.3.0" }, { + "authors": [ + { + "email": "foundation@djangoproject.com", + "name": "Django Software Foundation" + } + ], "bom-ref": "pkg:pypi/asgiref@3.3.0?uuid=e62e0385-a279-4d5a-b2a5-7f0cfb21d7bd", "copyright": "", "description": "ASGI specs, helper code, and adapters\nasgiref\n=======\n\n.. image:: https://api.travis-ci.org/django/asgiref.svg\n :target: https://travis-ci.org/django/asgiref\n\n.. image:: https://img.shields.io/pypi/v/asgiref.svg\n :target: https://pypi.python.org/pypi/asgiref\n\nASGI is a standard for Python asynchronous web apps and servers to communicate\nwith each other, and positioned as an asynchronous successor to WSGI. You can\nread more at https://asgi.readthedocs.io/en/latest/\n\nThis package includes ASGI base libraries, such as:\n\n* Sync-to-async and async-to-sync function wrappers, ``asgiref.sync``\n* Server base classes, ``asgiref.server``\n* A WSGI-to-ASGI adapter, in ``asgiref.wsgi``\n\n\nFunction wrappers\n-----------------\n\nThese allow you to wrap or decorate async or sync functions to call them from\nthe other style (so you can call async functions from a synchronous thread,\nor vice-versa).\n\nIn particular:\n\n* AsyncToSync lets a synchronous subthread stop and wait while the async\n function is called on the main thread's event loop, and then control is\n returned to the thread when the async function is finished.\n\n* SyncToAsync lets async code call a synchronous function, which is run in\n a threadpool and control returned to the async coroutine when the synchronous\n function completes.\n\nThe idea is to make it easier to call synchronous APIs from async code and\nasynchronous APIs from synchronous code so it's easier to transition code from\none style to the other. In the case of Channels, we wrap the (synchronous)\nDjango view system with SyncToAsync to allow it to run inside the (asynchronous)\nASGI server.\n\nNote that exactly what threads things run in is very specific, and aimed to\nkeep maximum compatibility with old synchronous code. See\n\"Synchronous code & Threads\" below for a full explanation. By default,\n``sync_to_async`` will run all synchronous code in the program in the same\nthread for safety reasons; you can disable this for more performance with\n``@sync_to_async(thread_sensitive=False)``, but make sure that your code does\nnot rely on anything bound to threads (like database connections) when you do.\n\n\nThreadlocal replacement\n-----------------------\n\nThis is a drop-in replacement for ``threading.local`` that works with both\nthreads and asyncio Tasks. Even better, it will proxy values through from a\ntask-local context to a thread-local context when you use ``sync_to_async``\nto run things in a threadpool, and vice-versa for ``async_to_sync``.\n\nIf you instead want true thread- and task-safety, you can set\n``thread_critical`` on the Local object to ensure this instead.\n\n\nServer base classes\n-------------------\n\nIncludes a ``StatelessServer`` class which provides all the hard work of\nwriting a stateless server (as in, does not handle direct incoming sockets\nbut instead consumes external streams or sockets to work out what is happening).\n\nAn example of such a server would be a chatbot server that connects out to\na central chat server and provides a \"connection scope\" per user chatting to\nit. There's only one actual connection, but the server has to separate things\ninto several scopes for easier writing of the code.\n\nYou can see an example of this being used in `frequensgi `_.\n\n\nWSGI-to-ASGI adapter\n--------------------\n\nAllows you to wrap a WSGI application so it appears as a valid ASGI application.\n\nSimply wrap it around your WSGI application like so::\n\n asgi_application = WsgiToAsgi(wsgi_application)\n\nThe WSGI application will be run in a synchronous threadpool, and the wrapped\nASGI application will be one that accepts ``http`` class messages.\n\nPlease note that not all extended features of WSGI may be supported (such as\nfile handles for incoming POST bodies).\n\n\nDependencies\n------------\n\n``asgiref`` requires Python 3.5 or higher.\n\n\nContributing\n------------\n\nPlease refer to the\n`main Channels contributing docs `_.\n\n\nTesting\n'''''''\n\nTo run tests, make sure you have installed the ``tests`` extra with the package::\n\n cd asgiref/\n pip install -e .[tests]\n pytest\n\n\nBuilding the documentation\n''''''''''''''''''''''''''\n\nThe documentation uses `Sphinx `_::\n\n cd asgiref/docs/\n pip install sphinx\n\nTo build the docs, you can use the default tools::\n\n sphinx-build -b html . _build/html # or `make html`, if you've got make set up\n cd _build/html\n python -m http.server\n\n...or you can use ``sphinx-autobuild`` to run a server and rebuild/reload\nyour documentation changes automatically::\n\n pip install sphinx-autobuild\n sphinx-autobuild . _build/html\n\n\nImplementation Details\n----------------------\n\nSynchronous code & threads\n''''''''''''''''''''''''''\n\nThe ``asgiref.sync`` module provides two wrappers that let you go between\nasynchronous and synchronous code at will, while taking care of the rough edges\nfor you.\n\nUnfortunately, the rough edges are numerous, and the code has to work especially\nhard to keep things in the same thread as much as possible. Notably, the\nrestrictions we are working with are:\n\n* All synchronous code called through ``SyncToAsync`` and marked with\n ``thread_sensitive`` should run in the same thread as each other (and if the\n outer layer of the program is synchronous, the main thread)\n\n* If a thread already has a running async loop, ``AsyncToSync`` can't run things\n on that loop if it's blocked on synchronous code that is above you in the\n call stack.\n\nThe first compromise you get to might be that ``thread_sensitive`` code should\njust run in the same thread and not spawn in a sub-thread, fulfilling the first\nrestriction, but that immediately runs you into the second restriction.\n\nThe only real solution is to essentially have a variant of ThreadPoolExecutor\nthat executes any ``thread_sensitive`` code on the outermost synchronous\nthread - either the main thread, or a single spawned subthread.\n\nThis means you now have two basic states:\n\n* If the outermost layer of your program is synchronous, then all async code\n run through ``AsyncToSync`` will run in a per-call event loop in arbitary\n sub-threads, while all ``thread_sensitive`` code will run in the main thread.\n\n* If the outermost layer of your program is asynchronous, then all async code\n runs on the main thread's event loop, and all ``thread_sensitive`` synchronous\n code will run in a single shared sub-thread.\n\nCruicially, this means that in both cases there is a thread which is a shared\nresource that all ``thread_sensitive`` code must run on, and there is a chance\nthat this thread is currently blocked on its own ``AsyncToSync`` call. Thus,\n``AsyncToSync`` needs to act as an executor for thread code while it's blocking.\n\nThe ``CurrentThreadExecutor`` class provides this functionality; rather than\nsimply waiting on a Future, you can call its ``run_until_future`` method and\nit will run submitted code until that Future is done. This means that code\ninside the call can then run code on your thread.\n\n\nMaintenance and Security\n------------------------\n\nTo report security issues, please contact security@djangoproject.com. For GPG\nsignatures and more security process information, see\nhttps://docs.djangoproject.com/en/dev/internals/security/.\n\nTo report bugs or request new features, please open a new GitHub issue.\n\nThis repository is part of the Channels project. For the shepherd and maintenance team, please see the\n`main Channels readme `_.", diff --git a/scanpipe/tests/test_models.py b/scanpipe/tests/test_models.py index b78a8a4294..c707928a1c 100644 --- a/scanpipe/tests/test_models.py +++ b/scanpipe/tests/test_models.py @@ -90,6 +90,7 @@ from scanpipe.tests import mocked_now from scanpipe.tests import package_data1 from scanpipe.tests import package_data2 +from scanpipe.tests import parties_data1 from scanpipe.tests.pipelines.do_nothing import DoNothing scanpipe_app = apps.get_app_config("scanpipe") @@ -2592,6 +2593,47 @@ def test_scanpipe_discovered_package_model_spdx_id(self): expected = f"SPDXRef-scancodeio-discoveredpackage-{package1.uuid}" self.assertEqual(expected, package1.spdx_id) + def test_scanpipe_discovered_package_model_extract_from_parties(self): + package1 = make_package(self.project1, "pkg:type/a", parties=parties_data1) + + expected = [ + { + "name": "Debian X Strike Force", + "role": "maintainer", + "email": "debian-x@lists.debian.org", + } + ] + self.assertEqual(expected, package1.extract_from_parties(roles=["maintainer"])) + + expected = [ + { + "name": "AboutCode and others", + "role": "author", + "type": "person", + "email": "info@aboutcode.org", + "url": None, + } + ] + self.assertEqual(expected, package1.extract_from_parties(roles=["author"])) + + def test_scanpipe_discovered_package_model_get_author_names(self): + package1 = make_package(self.project1, "pkg:type/a", parties=parties_data1) + + expected = ["AboutCode and others", "Debian X Strike Force"] + self.assertEqual(expected, package1.get_author_names()) + + roles = ["maintainer"] + expected = ["Debian X Strike Force"] + self.assertEqual(expected, package1.get_author_names(roles)) + + roles = ["author"] + expected = ["AboutCode and others"] + self.assertEqual(expected, package1.get_author_names(roles)) + + roles = ["maintainer", "developer"] + expected = ["Debian X Strike Force", "JBoss.org Community"] + self.assertEqual(expected, package1.get_author_names(roles)) + def test_scanpipe_model_create_user_creates_auth_token(self): basic_user = User.objects.create_user(username="basic_user") self.assertTrue(basic_user.auth_token.key)