Esempio n. 1
0
    def test_make_request(self, ClientSession: AsyncMock):
        request = ClientSession.return_value.request
        fake_response = request.return_value.__aenter__.return_value
        fake_response.json.return_value = {"result": "fake"}
        api = AsyncErrataAPI("https://errata.example.com")

        actual = get_event_loop().run_until_complete(
            api._make_request("HEAD", "/api/path"))
        request.assert_called_once_with("HEAD",
                                        "https://errata.example.com/api/path",
                                        headers=api._headers)
        fake_response.raise_for_status.assert_called_once_with()
        fake_response.json.assert_awaited_once_with()
        self.assertEqual(actual, {"result": "fake"})

        headers = {"X-Test-Header": "Test Value"}
        request.reset_mock()
        fake_response.read.return_value = b"daedbeef"
        fake_response.raise_for_status.reset_mock()
        actual = get_event_loop().run_until_complete(
            api._make_request("GET",
                              "/api/path",
                              headers=headers,
                              parse_json=False))
        request.assert_called_once_with("GET",
                                        "https://errata.example.com/api/path",
                                        headers=headers)
        fake_response.raise_for_status.assert_called_once_with()
        fake_response.read.assert_awaited_once_with()
        self.assertEqual(actual, b"daedbeef")
Esempio n. 2
0
 def test_login(self, SecurityContext: Mock, ClientSession: Mock):
     client_ctx = SecurityContext.return_value
     client_ctx.step.return_value = b"faketoken"
     api = AsyncErrataAPI("https://errata.example.com")
     get_event_loop().run_until_complete(api.login())
     client_ctx.step.assert_called_once_with(b"")
     self.assertEqual(
         api._headers["Authorization"],
         'Negotiate ' + base64.b64encode(b"faketoken").decode())
Esempio n. 3
0
 def test_get_cves(self, _make_request: Mock, ClientSession: Mock):
     api = AsyncErrataAPI("https://errata.example.com")
     api.get_advisory = AsyncMock(
         return_value={"content": {
             "content": {
                 "cve": "A B C"
             }
         }})
     actual = get_event_loop().run_until_complete(api.get_cves(1))
     api.get_advisory.assert_awaited_once_with(1)
     self.assertEqual(actual, ["A", "B", "C"])
Esempio n. 4
0
 def test_create_delete_cve_package_exclusion(self, _make_request: Mock,
                                              ClientSession: Mock):
     api = AsyncErrataAPI("https://errata.example.com")
     _make_request.return_value = b""
     actual = get_event_loop().run_until_complete(
         api.delete_cve_package_exclusion(100))
     _make_request.assert_awaited_once_with(
         ANY,
         'DELETE',
         '/api/v1/cve_package_exclusion/100',
         parse_json=False)
     self.assertEqual(actual, None)
Esempio n. 5
0
async def get_flaws(runtime, advisory, bug_tracker, flaw_bug_tracker, noop):
    # get attached bugs from advisory
    advisory_bug_ids = bug_tracker.advisory_bug_ids(advisory)
    if not advisory_bug_ids:
        runtime.logger.info(f'Found 0 {bug_tracker.type} bugs attached')
        return []

    attached_tracker_bugs: List[Bug] = bug_tracker.get_tracker_bugs(advisory_bug_ids, verbose=runtime.debug)
    runtime.logger.info(f'Found {len(attached_tracker_bugs)} {bug_tracker.type} tracker bugs attached: '
                        f'{sorted([b.id for b in attached_tracker_bugs])}')
    if not attached_tracker_bugs:
        return []

    # validate and get target_release
    current_target_release = Bug.get_target_release(attached_tracker_bugs)
    tracker_flaws, flaw_id_bugs = bug_tracker.get_corresponding_flaw_bugs(
        attached_tracker_bugs,
        flaw_bug_tracker,
        strict=True
    )
    runtime.logger.info(f'Found {len(flaw_id_bugs)} {flaw_bug_tracker.type} corresponding flaw bugs:'
                        f' {sorted(flaw_id_bugs.keys())}')

    # current_target_release is digit.digit.[z|0]
    # if current_target_release is GA then run first-fix bug filtering
    # for GA not every flaw bug is considered first-fix
    # for z-stream every flaw bug is considered first-fix
    if current_target_release[-1] == 'z':
        runtime.logger.info("Detected z-stream target release, every flaw bug is considered first-fix")
        first_fix_flaw_bugs = list(flaw_id_bugs.values())
    else:
        runtime.logger.info("Detected GA release, applying first-fix filtering..")
        first_fix_flaw_bugs = [
            flaw_bug for flaw_bug in flaw_id_bugs.values()
            if is_first_fix_any(flaw_bug_tracker, flaw_bug, current_target_release)
        ]

    runtime.logger.info(f'{len(first_fix_flaw_bugs)} out of {len(flaw_id_bugs)} flaw bugs considered "first-fix"')
    if not first_fix_flaw_bugs:
        return []

    runtime.logger.info('Associating CVEs with builds')
    errata_config = runtime.gitdata.load_data(key='erratatool').data
    errata_api = AsyncErrataAPI(errata_config.get("server", constants.errata_url))
    try:
        await errata_api.login()
        await associate_builds_with_cves(errata_api, advisory, attached_tracker_bugs, tracker_flaws, flaw_id_bugs, noop)
    except ValueError as e:
        runtime.logger.warn(f"Error associating builds with cves: {e}")
    finally:
        await errata_api.close()
    return first_fix_flaw_bugs
Esempio n. 6
0
    def test_get_cve_package_exclusions(self, _make_request: Mock,
                                        ClientSession: Mock):
        api = AsyncErrataAPI("https://errata.example.com")
        _make_request.side_effect = lambda _0, _1, _2, params: {
            1: {
                "data": [{
                    "id": 1
                }, {
                    "id": 2
                }, {
                    "id": 3
                }]
            },
            2: {
                "data": [{
                    "id": 4
                }, {
                    "id": 5
                }]
            },
            3: {
                "data": []
            }
        }[params['page[number]']]

        async def _call():
            items = []
            async for item in api.get_cve_package_exclusions(1):
                items.append(item)
            return items

        actual = get_event_loop().run_until_complete(_call())
        _make_request.assert_awaited_with(ANY,
                                          'GET',
                                          '/api/v1/cve_package_exclusion',
                                          params={
                                              'filter[errata_id]': '1',
                                              'page[number]': 3,
                                              'page[size]': 300
                                          })
        self.assertEqual(actual, [{
            'id': 1
        }, {
            'id': 2
        }, {
            'id': 3
        }, {
            'id': 4
        }, {
            'id': 5
        }])
Esempio n. 7
0
    def test_get_advisory(self, _make_request: Mock, ClientSession: Mock):
        api = AsyncErrataAPI("https://errata.example.com")
        _make_request.return_value = {"result": "fake"}

        actual = get_event_loop().run_until_complete(api.get_advisory(1))
        _make_request.assert_awaited_once_with(ANY, "GET", "/api/v1/erratum/1")
        self.assertEqual(actual, {"result": "fake"})

        _make_request.reset_mock()
        actual = get_event_loop().run_until_complete(
            api.get_advisory("RHBA-2021:0001"))
        _make_request.assert_awaited_once_with(
            ANY, "GET", "/api/v1/erratum/RHBA-2021%3A0001")
        self.assertEqual(actual, {"result": "fake"})
Esempio n. 8
0
 def test_create_cve_package_exclusion(self, _make_request: Mock,
                                       ClientSession: Mock):
     api = AsyncErrataAPI("https://errata.example.com")
     _make_request.return_value = {"result": "fake"}
     actual = get_event_loop().run_until_complete(
         api.create_cve_package_exclusion(1, "CVE-1", "a"))
     _make_request.assert_awaited_once_with(ANY,
                                            'POST',
                                            '/api/v1/cve_package_exclusion',
                                            json={
                                                'cve': 'CVE-1',
                                                'errata': 1,
                                                'package': 'a'
                                            })
     self.assertEqual(actual, {"result": "fake"})
Esempio n. 9
0
 def __init__(self,
              runtime: Runtime,
              use_jira: bool = False,
              output: str = 'text'):
     self.runtime = runtime
     self.use_jira = use_jira
     bug_tracker_cls = JIRABugTracker if use_jira else BugzillaBugTracker
     self.config = bug_tracker_cls.get_config(runtime)
     self.bug_tracker = bug_tracker_cls(self.config)
     self.target_releases: List[str] = self.config['target_release']
     self.product: str = self.config['product']
     self.et_data: Dict[str, Any] = runtime.gitdata.load_data(
         key='erratatool').data
     self.errata_api = AsyncErrataAPI(
         self.et_data.get("server", constants.errata_url))
     self.problems: List[str] = []
     self.output = output
Esempio n. 10
0
 def test_get_builds(self, _make_request: Mock, ClientSession: Mock):
     api = AsyncErrataAPI("https://errata.example.com")
     _make_request.return_value = {
         "ProductVersion1": {
             "builds": [{
                 "a-1.0.0-1": {},
                 "b-1.0.0-1": {}
             }]
         },
         "ProductVersion2": {
             "builds": [{
                 "c-1.0.0-1": {}
             }]
         }
     }
     actual = get_event_loop().run_until_complete(api.get_builds(1))
     _make_request.assert_awaited_once_with(
         ANY, "GET", "/api/v1/erratum/1/builds_list")
     self.assertEqual(actual, _make_request.return_value)
Esempio n. 11
0
 def test_close(self, ClientSession: Mock):
     api = AsyncErrataAPI("https://errata.example.com")
     get_event_loop().run_until_complete(api.close())
     ClientSession.return_value.close.assert_called_once()