Exemple #1
0
    def test_detach_sign_with_pgp_key_failure(self, gpg_mock):
        gpg_mock.side_effect = sh.ErrorReturnCode('gpg', b'mock stdout',
                                                  b'mock error')

        with self.assertRaisesRegex(
                RuntimeError,
                re.compile(
                    r'Error performing detached signature of file \(/mock/file-to-detach-sign.txt\)'
                    r' with PGP key \(355C137F36628365E42F6D79AF9B11B55E8305E1\):'
                    r".*RAN: gpg"
                    r".*STDOUT:"
                    r".*mock stdout"
                    r".*STDERR:"
                    r".*mock error", re.DOTALL)):
            detach_sign_with_pgp_key(
                file_to_sign_path='/mock/file-to-detach-sign.txt',
                pgp_private_key_fingerprint=
                '355C137F36628365E42F6D79AF9B11B55E8305E1',
                output_signature_path='/mock/file-to-detach-sign.sig')

        gpg_mock.assert_called_once_with(
            '--armor', '--local-user',
            '355C137F36628365E42F6D79AF9B11B55E8305E1', '--output',
            '/mock/file-to-detach-sign.sig', '--detach-sign',
            '/mock/file-to-detach-sign.txt')
Exemple #2
0
    def test__git_push_error(self, git_mock):
        url = 'www.xyz.com'

        with TempDirectory() as temp_dir:
            parent_work_dir_path = os.path.join(temp_dir.path, 'working')

            artifact_config = {
                'container-image-version': {
                    'description': '',
                    'value': '1.0-69442c8'
                }
            }
            workflow_result = self.setup_previous_result(
                parent_work_dir_path, artifact_config)

            step_config = {}
            step_implementer = self.create_step_implementer(
                step_config=step_config,
                workflow_result=workflow_result,
                parent_work_dir_path=parent_work_dir_path)

            git_mock.push.side_effect = sh.ErrorReturnCode(
                'git', b'mock out', b'mock error')

            with self.assertRaisesRegex(StepRunnerException,
                                        "Error invoking git push"):
                step_implementer._Git__git_push(url)
Exemple #3
0
    def test_import_pgp_key_gpg_import_fail(self, gpg_mock):
        gpg_mock.side_effect = sh.ErrorReturnCode('gpg', b'mock stdout',
                                                  b'mock error')

        pgp_private_key = TestImportPGPKey.TEST_FAKE_PRIVATE_KEY

        with self.assertRaisesRegex(
                RuntimeError,
                re.compile(
                    r"Error importing pgp private key:"
                    r".*RAN: gpg"
                    r".*STDOUT:"
                    r".*mock stdout"
                    r".*STDERR:"
                    r".*mock error", re.DOTALL)):
            import_pgp_key(pgp_private_key=pgp_private_key)

        gpg_mock.assert_called_once_with('--import',
                                         '--fingerprint',
                                         '--with-colons',
                                         '--import-options=import-show',
                                         _in=pgp_private_key,
                                         _out=Any(IOBase),
                                         _err_to_out=True,
                                         _tee='out')
Exemple #4
0
    def test__git_tag_error(self, git_mock):
        git_tag_value = "1.0+69442c8"

        with TempDirectory() as temp_dir:
            work_dir_path = os.path.join(temp_dir.path, 'working')

            artifact_config = {
                'container-image-version': {'description': '', 'value': '1.0-69442c8'}
            }
            workflow_result = self.setup_previous_result(work_dir_path, artifact_config)

            step_config = {}
            step_implementer = self.create_step_implementer(
                step_config=step_config,
                workflow_result=workflow_result,
                work_dir_path=work_dir_path
            )

            git_mock.tag.side_effect = sh.ErrorReturnCode('git', b'mock out', b'mock error')

            with self.assertRaisesRegex(
                StepRunnerException,
                "Error pushing git tag"
            ):
                step_implementer._Git__git_tag(git_tag_value)
Exemple #5
0
    def test_audit_attestation_fail(self, audit_results_mock):


        step_config = {
                'workflow-policy-uri': "https://foo.bar"
        }

        step_implementer = self.create_step_implementer(
            step_config=step_config
        )
        audit_results_mock.return_value = "pass"
        audit_results_mock.side_effect = sh.ErrorReturnCode('opa', b'mock out', b'mock error')

        result_message, result_return_code = step_implementer._OpenPolicyAgent__audit_attestation(
            workflow_attestation_file_path = "workflow_attestation_file_path",
            workflow_policy_file_path = "workflow_policy_file_path",
            workflow_policy_query =  "fooquery"
        )

        self.assertRegex(result_message, re.compile(
                r"Error evaluating query against data:"
                r".*RAN: opa"
                r".*STDOUT:"
                r".*mock out"
                r".*STDERR:"
                r".*mock error",
                re.DOTALL
            ))

        self.assertEqual(result_return_code, 1)
    def test___import_pgp_key_gpg_import_fail(self, gpg_mock):
        gpg_mock.side_effect = sh.ErrorReturnCode('gpg', b'mock stdout',
                                                  b'mock error')

        pgp_private_key = TestStepImplementerSignContainerImagePodman.TEST_FAKE_PRIVATE_KEY

        with self.assertRaisesRegex(
                StepRunnerException,
                re.compile(
                    r"Error importing pgp private key:"
                    r".*RAN: gpg"
                    r".*STDOUT:"
                    r".*mock stdout"
                    r".*STDERR:"
                    r".*mock error", re.DOTALL)):
            PodmanSign._PodmanSign__import_pgp_key(
                pgp_private_key=pgp_private_key)

        gpg_mock.assert_called_once_with('--import',
                                         '--fingerprint',
                                         '--with-colons',
                                         '--import-options=import-show',
                                         _in=pgp_private_key,
                                         _out=Any(IOBase),
                                         _err_to_out=True,
                                         _tee='out')
    def test_write_effective_pom_fail(self, mvn_mock):
        pom_file_path = 'input/pom.xml'
        effective_pom_path = 'output/effective-pom.xml'

        mvn_mock.side_effect = sh.ErrorReturnCode('mvn', b'mock stdout', b'mock error')

        with self.assertRaisesRegex(
            StepRunnerException,
            re.compile(
                rf"Error generating effective pom for '{pom_file_path}' to '{effective_pom_path}'"
                r".*RAN: mvn"
                r".*STDOUT:"
                r".*mock stdout"
                r".*STDERR:"
                r".*mock error",
                re.DOTALL
            )
        ):
            write_effective_pom(
                pom_file_path=pom_file_path,
                output_path=effective_pom_path
            )
            mvn_mock.assert_any_call(
                'help:effective-pom',
                f'-f={pom_file_path}',
                f'-Doutput={effective_pom_path}'
            )
Exemple #8
0
    def test_push_container_signature_specify_curl_implementer_failure(
            self, curl_mock):
        """Test for curl failure"""
        with TempDirectory() as temp_dir:
            config = TestStepImplementerSignContainerImageCurlPush.generate_config(
            )

            signature_file_path = 'signature-1'
            temp_dir.write(signature_file_path, b'bogus signature')
            container_image_signature_file_path = os.path.join(
                temp_dir.path, signature_file_path)

            container_image_signature_name = 'jkeam/hello-node@sha256=2cbdb73c9177e63e85d267f738e' \
                '99e368db3f806eab4c541f5c6b719e69f1a2b/signature-1'
            temp_dir.makedir('tssc-results')
            temp_dir.write(
                'tssc-results/tssc-results.yml',
                bytes(
                    f'''tssc-results:
                  sign-container-image:
                    container-image-signature-file-path: {container_image_signature_file_path}
                    container-image-signature-name: {container_image_signature_name}
                ''', 'utf-8'))

            curl_mock.side_effect = sh.ErrorReturnCode(
                'CurlPush', b'mock stdout', b'mock error about curl runtime')
            with self.assertRaisesRegex(
                    RuntimeError,
                    r'Unexpected error curling signature file to signature server.*'
            ):
                self.run_step_test_with_result_validation(
                    temp_dir,
                    'sign-container-image',
                    config,
                    expected_step_results=None)
    def test_create_container_image_specify_buildah_implementer_with_invalid_dockerfile(
            self, buildah_mock):
        with TempDirectory() as temp_dir:
            application_name = 'foo'
            service_name = 'bar'
            temp_dir.write('Dockerfile', b'Invalid Dockerfile')
            config = {
                'tssc-config': {
                    'global-defaults': {
                        'application-name': application_name,
                        'service-name': service_name
                    },
                    'create-container-image': {
                        'implementer': 'Buildah',
                        'config': {
                            'context': temp_dir.path
                        }
                    }
                }
            }

            sh.buildah.bud.side_effect = sh.ErrorReturnCode(
                'buildah bud', b'mock stdout',
                b'mock error about invalid dockerfile')
            with self.assertRaisesRegex(
                    RuntimeError,
                    r'Issue invoking buildah bud with given image specification file \(Dockerfile\)'
            ):
                run_step_test_with_result_validation(temp_dir,
                                                     'create-container-image',
                                                     config, {})
Exemple #10
0
    def test___buildah_import_image_from_tar_error(self, buildah_mock):
        image_tar_file = "/does/not/matter.tar"
        container_name = "test"

        buildah_mock.side_effect = sh.ErrorReturnCode('buildah', b'mock out',
                                                      b'mock error')

        with self.assertRaisesRegex(
                RuntimeError,
                re.compile(
                    rf"Unexpected runtime error importing the image \({image_tar_file}\):"
                    r".*RAN: buildah"
                    r".*STDOUT:"
                    r".*mock out"
                    r".*STDERR:"
                    r".*mock error", re.DOTALL)):
            OpenSCAPGeneric._OpenSCAPGeneric__buildah_import_image_from_tar(
                image_tar_file=image_tar_file, container_name=container_name)

        buildah_mock.assert_called_once_with(
            'from',
            '--storage-driver',
            'vfs',
            '--name',
            container_name,
            f"docker-archive:{image_tar_file}",
            _out=Any(IOBase),
            _err=Any(IOBase),
            _tee='err')
Exemple #11
0
        def mvn_side_effect(*args, **kwargs):
            if 'clean' in args:
                if os.path.exists(target_dir_path):
                    os.rmdir(target_dir_path)

            if 'install' in args:
                os.mkdir(target_dir_path)

                for artifact_name in artifact_names:
                    artifact_path = os.path.join(
                        target_dir_path,
                        artifact_name
                    )
                    Path(artifact_path).touch()

            if 'test' in args:
                if raise_error_on_tests:
                    raise sh.ErrorReturnCode('mvn', b'mock out', b'mock error')

                os.makedirs(target_dir_path, exist_ok=True)

                for artifact_name in artifact_names:
                    artifact_path = os.path.join(
                        target_dir_path,
                        artifact_name
                    )
                    Path(artifact_path).touch()
    def test___sign_image_podman_image_sign_fail(self, podman_mock):
        with TempDirectory() as temp_dir:
            pgp_private_key_fingerprint = 'abc123'
            image_signatures_directory = os.path.join(temp_dir.path, 'signatures')
            container_image_tag = 'does/not/matter:v0.42.0'

            podman_mock.image.side_effect = sh.ErrorReturnCode('podman', b'mock stdout', b'mock error signing image')

            with self.assertRaisesRegex(
                StepRunnerException,
                re.compile(
                    rf"Error signing image \({container_image_tag}\):"
                    r".*RAN: podman"
                    r".*STDOUT:"
                    r".*mock stdout"
                    r".*STDERR:"
                    r".*mock error signing image",
                    re.DOTALL
                )
            ):
                PodmanSign._PodmanSign__sign_image(
                    pgp_private_key_fingerprint=pgp_private_key_fingerprint,
                    image_signatures_directory=image_signatures_directory,
                    container_image_tag=container_image_tag
                )

            podman_mock.image.assert_called_once_with(
                'sign',
                f'--sign-by={pgp_private_key_fingerprint}',
                f'--directory={image_signatures_directory}',
                f'docker://{container_image_tag}',
                _out=Any(IOBase),
                _err_to_out=True,
                _tee='out'
            )
Exemple #13
0
    def test__git_url_url_from_git_config_error(self, git_mock):
        with TempDirectory() as temp_dir:
            results_dir_path = os.path.join(temp_dir.path,
                                            'step-runner-results')
            results_file_name = 'step-runner-results.yml'
            work_dir_path = os.path.join(temp_dir.path, 'working')

            step_config = {}

            artifact_config = {
                'container-image-version': {
                    'description': '',
                    'value': '1.0-69442c8'
                }
            }

            self.setup_previous_result(work_dir_path, artifact_config)

            step_implementer = self.create_step_implementer(
                step_config=step_config,
                results_dir_path=results_dir_path,
                results_file_name=results_file_name,
                work_dir_path=work_dir_path,
            )

            git_mock.config.side_effect = sh.ErrorReturnCode(
                'git', b'mock out', b'mock error')

            with self.assertRaisesRegex(
                    StepRunnerException,
                    "Error invoking git config --get remote.origin.url:"):
                step_implementer._Git__git_url()
Exemple #14
0
    def test_buildah_error(self, buildah_mock):
        buildah_unshare_command = sh.buildah.bake('unshare')
        container_name = "test"

        buildah_mock.bake('unshare').bake(
            'buildah',
            'mount').side_effect = sh.ErrorReturnCode('buildah mount',
                                                      b'mock out',
                                                      b'mock error')

        with self.assertRaisesRegex(
                RuntimeError,
                re.compile(
                    rf"Error mounting container \({container_name}\):"
                    r".*RAN: buildah"
                    r".*STDOUT:"
                    r".*mock out"
                    r".*STDERR:"
                    r".*mock error", re.DOTALL)):
            mount_container(buildah_unshare_command=buildah_unshare_command,
                            container_id=container_name)

        buildah_mock.bake('unshare').bake(
            'buildah', 'mount').assert_called_once_with(container_name,
                                                        _out=Any(IOBase),
                                                        _err=Any(IOBase),
                                                        _tee='err')
    def test__run_step_fail_buildah_push_error(self, buildah_mock):
        with TempDirectory() as temp_dir:
            results_dir_path = os.path.join(temp_dir.path,
                                            'step-runner-results')
            results_file_name = 'step-runner-results.yml'
            work_dir_path = os.path.join(temp_dir.path, 'working')
            temp_dir.write('Dockerfile', b'''testing''')

            application_name = 'app-name'
            service_name = 'service-name'
            image_tag_version = '1.0-123abc'
            step_config = {
                'containers-config-auth-file': 'buildah-auth.json',
                'imagespecfile': 'Dockerfile',
                'context': temp_dir.path,
                'tl-sverify': 'true',
                'format': 'oci',
                'service-name': service_name,
                'application-name': application_name
            }

            step_implementer = self.create_step_implementer(
                step_config=step_config,
                step_name='create-container-image',
                implementer='Buildah',
                results_dir_path=results_dir_path,
                results_file_name=results_file_name,
                work_dir_path=work_dir_path,
            )

            artifact_config = {
                'container-image-version': {
                    'description': '',
                    'value': image_tag_version
                },
            }
            self.setup_previous_result(work_dir_path, artifact_config)

            buildah_mock.push.side_effect = sh.ErrorReturnCode(
                'buildah', b'mock out', b'mock error')

            result = step_implementer._run_step()

            image_tar_path = os.path.join(
                work_dir_path, 'create-container-image',
                f'image-{application_name}-{service_name}-{image_tag_version}.tar'
            )
            self.assertFalse(result.success)
            self.assertRegex(
                result.message,
                re.compile(
                    rf'Issue invoking buildah push to tar file \({image_tar_path}\):'
                    r'.*RAN: buildah'
                    r'.*STDOUT:'
                    r'.*mock out'
                    r'.*STDERR:'
                    r'.*mock error', re.DOTALL))
Exemple #16
0
    def test_container_image_static_compliance_scan_specify_openscap_implementer_buildah_error(
            self, buildah_mock):

        git_tag = 'git_tag'

        with TempDirectory() as temp_dir:
            temp_dir.makedir('tssc-results')

            image_tar_file_path = f'{temp_dir.path}//image.tar'
            temp_dir.write(
                'tssc-results/tssc-results.yml',
                bytes(
                    f'''tssc-results:
                  tag-source:
                    tag: {git_tag}
                  create-container-image:
                    image-tar-file: {image_tar_file_path}
                ''', 'utf-8'))

            config = {
                'tssc-config': {
                    'global-defaults': {
                        'application-name': 'ref-app-quarkus',
                        'service-name': 'backend',
                        'organization': 'tssc-team'
                    },
                    'container-image-static-compliance-scan': {
                        'implementer': 'OpenSCAP',
                        'config': {
                            'destination-url':
                            'quay-quay-enterprise.apps.tssc.rht-set.com',
                            'log-level':
                            'info',
                            'scap-input-file':
                            '/usr/share/xml/scap/ssg/content/ssg-jre-oval.xml',
                            'scan-output-absolute-path':
                            '/tmp/scap_output.txt',
                            'scan-report-absolute-path':
                            '/tmp/scap_compliance_report.html'
                        }
                    }
                }
            }

            result1 = MagicMock()
            result1.stdout = b"test"
            buildah_mock.side_effect = [
                result1,
                sh.ErrorReturnCode('buildah', b'stdout', b'stderror')
            ]

            with self.assertRaisesRegex(RuntimeError,
                                        r"Unexpected runtime error"):
                run_step_test_with_result_validation(
                    temp_dir, 'container-image-static-compliance-scan', config,
                    {})
    def test_fail_buildah_bud_error(self, buildah_mock, mock_determine_container_image_build_tag_info):
        with TempDirectory() as temp_dir:
            parent_work_dir_path = os.path.join(temp_dir.path, 'working')
            temp_dir.write('Containerfile',b'''testing''')

            artifact_config = {
                'container-image-version': {'description': '', 'value': '1.0-123abc'},
            }
            workflow_result = self.setup_previous_result(parent_work_dir_path, artifact_config)

            image_spec_file = 'Containerfile'
            step_config = {
                'imagespecfile': image_spec_file,
                'context': temp_dir.path,
                'tls-verify': True,
                'format': 'oci',
                'service-name': 'mock-service',
                'application-name': 'mock-app'
            }
            step_implementer = self.create_step_implementer(
                step_config=step_config,
                step_name='create-container-image',
                implementer='Buildah',
                workflow_result=workflow_result,
                parent_work_dir_path=parent_work_dir_path
            )

            # setup sideeffects
            mock_determine_container_image_build_tag_info.return_value=[
                'localhost/mock-org/mock-app-mock-service:1.0-123abc',
                'mock-org/mock-app-mock-service:1.0-123abc',
                'localhost',
                'mock-app-mock-service',
                '1.0-123abc'
            ]

            # run step with mock failure
            buildah_mock.bud.side_effect = sh.ErrorReturnCode('buildah', b'mock out', b'mock error')
            result = step_implementer._run_step()

             # verify step result
            self.assertFalse(result.success)
            self.assertRegex(
                result.message,
                re.compile(
                    r'Issue invoking buildah bud with given image '
                    rf'specification file \({image_spec_file}\):'
                    r'.*RAN: buildah'
                    r'.*STDOUT:'
                    r'.*mock out'
                    r'.*STDERR:'
                    r'.*mock error',
                    re.DOTALL
                )
            )
Exemple #18
0
    def test_run_step_fail_mvn_error(self, mvn_mock):
        with TempDirectory() as temp_dir:
            results_dir_path = os.path.join(temp_dir.path,
                                            'step-runner-results')
            results_file_name = 'step-runner-results.yml'
            work_dir_path = os.path.join(temp_dir.path, 'working')
            temp_dir.write(
                'pom.xml', b'''<project>
                <modelVersion>4.0.0</modelVersion>
                <groupId>com.mycompany.app</groupId>
                <artifactId>my-app</artifactId>
                <version>1.0</version>
            </project>''')
            pom_file_path = os.path.join(temp_dir.path, 'pom.xml')

            step_config = {'pom-file': pom_file_path}

            step_implementer = self.create_step_implementer(
                step_config=step_config,
                step_name='package',
                implementer='Maven',
                results_dir_path=results_dir_path,
                results_file_name=results_file_name,
                work_dir_path=work_dir_path,
            )

            mvn_mock.side_effect = sh.ErrorReturnCode('mvn', b'mock out',
                                                      b'mock error')

            result = step_implementer._run_step()

            expected_step_result = StepResult(
                step_name='package',
                sub_step_name='Maven',
                sub_step_implementer_name='Maven')
            mvn_output_file_path = os.path.join(work_dir_path, 'package',
                                                'mvn_test_output.txt')
            expected_step_result.add_artifact(
                description=
                "Standard out and standard error from 'mvn install'.",
                name='maven-output',
                value=mvn_output_file_path)
            expected_step_result.success = False

            self.assertEqual(result.success, expected_step_result.success)
            self.assertRegex(
                result.message,
                re.compile(
                    r"Package failures. See 'maven-output' report artifacts for details:"
                    r".*RAN: mvn"
                    r".*STDOUT:"
                    r".*mock out"
                    r".*STDERR:"
                    r".*mock error", re.DOTALL))
            self.assertEqual(result.artifacts, expected_step_result.artifacts)
    def test_configlint_bad_sh_call(self, configlint_mock):
        with TempDirectory() as temp_dir:
            yml_file = ''
            temp_dir.write('config-file-to-validate.yml', yml_file.encode())
            file_to_validate_file_path = str(
                os.path.join(temp_dir.path, 'config-file-to-validate.yml'))

            # write results thus far
            tssc_results = f"""---
tssc-results:
    validate-environment-configuration:
        'options':
            'yml_path': '{file_to_validate_file_path}'
"""
            temp_dir.write('tssc-results/tssc-results.yml',
                           tssc_results.encode())

            configlint_rules_content = ''
            temp_dir.write('config-lint.rules',
                           configlint_rules_content.encode())
            rules = os.path.join(temp_dir.path, 'config-lint.rules')
            config = {
                'tssc-config': {
                    'validate-environment-configuration': {
                        'implementer': 'Configlint',
                        'config': {
                            'rules': rules
                        }
                    }
                }
            }
            runtime_args = {}
            expected_step_results = {
                'tssc-results': {
                    'validate-environment-configuration': {
                        'result': {
                            'success': True,
                            'message': 'configlint step completed'
                        },
                        'options': {
                            'yml_path': file_to_validate_file_path
                        },
                        'report-artifacts': []
                    }
                }
            }
            sh.config_lint.side_effect = sh.ErrorReturnCode(
                'config_lint', b'mock stdout', b'mock error')
            with self.assertRaisesRegex(RuntimeError,
                                        r'Error invoking config-lint: .*'):
                self.run_step_test_with_result_validation(
                    temp_dir, 'validate-environment-configuration', config,
                    expected_step_results, runtime_args)
    def test_push_container_image_specify_skopeo_implementer_skopeo_error(self, skopeo_mock):
        with TempDirectory() as temp_dir:
            source = 'quay.io/tssc/tssc-base:latest'
            destination = '{path}/image.tar'.format(path=temp_dir.path)
            version = '1.0-69442c8'
            temp_dir.makedir('tssc-results')
            temp_dir.write(
                'tssc-results/tssc-results.yml',
                bytes(
                    '''tssc-results:
                  generate-metadata:
                    image-tag: {version}
                  create-container-image:
                    image-tar-file: image.tar
                '''.format(version=version),
                    'utf-8')
                )

            application_name = 'foo'
            service_name = 'bar'
            organization = 'xyzzy'
            config = {
                'tssc-config': {
                    'global-defaults': {
                        'application-name': application_name,
                        'service-name': service_name,
                        'organization': organization
                    },
                    'push-container-image': {
                        'implementer': 'Skopeo',
                        'config': {
                            'source' : source,
                            'destination-url' : destination
                        }
                    }
                },
                'generate-metadata': {
                        'implementer': 'Maven',
                        'config' : {}
                    }
            }
            expected_step_results = {'tssc-results': {'create-container-image': {'image-tar-file': 'image.tar'},'generate-metadata': {'image-tag': version},
                                     'push-container-image': {'image-tag':"docker://{destination}:{version}".format(destination=destination, version=version)}}}

            sh.skopeo.copy.side_effect = sh.ErrorReturnCode('skopeo', b'mock stdout', b'mock error about skopeo runtime')
            with self.assertRaisesRegex(
                    RuntimeError,
                    r'Error invoking .*'):
                    run_step_test_with_result_validation(temp_dir, 'push-container-image', config, expected_step_results)
Exemple #21
0
    def test__run_step_fail_buildah_bud_error(self, buildah_mock):
        with TempDirectory() as temp_dir:
            work_dir_path = os.path.join(temp_dir.path, 'working')
            temp_dir.write('Dockerfile', b'''testing''')

            artifact_config = {
                'container-image-version': {
                    'description': '',
                    'value': '1.0-123abc'
                },
            }
            workflow_result = self.setup_previous_result(
                work_dir_path, artifact_config)

            image_spec_file = 'Dockerfile'
            step_config = {
                'containers-config-auth-file': 'buildah-auth.json',
                'imagespecfile': image_spec_file,
                'context': temp_dir.path,
                'tls-verify': True,
                'format': 'oci',
                'service-name': 'service-name',
                'application-name': 'app-name'
            }
            step_implementer = self.create_step_implementer(
                step_config=step_config,
                step_name='create-container-image',
                implementer='Buildah',
                workflow_result=workflow_result,
                work_dir_path=work_dir_path)

            buildah_mock.bud.side_effect = sh.ErrorReturnCode(
                'buildah', b'mock out', b'mock error')

            result = step_implementer._run_step()

            self.assertFalse(result.success)
            self.assertRegex(
                result.message,
                re.compile(
                    r'Issue invoking buildah bud with given image '
                    rf'specification file \({image_spec_file}\):'
                    r'.*RAN: buildah'
                    r'.*STDOUT:'
                    r'.*mock out'
                    r'.*STDERR:'
                    r'.*mock error', re.DOTALL))
Exemple #22
0
    def test_success_false_when_shell_command_fails(self, os_path_exists_mock, npm_shell_command_mock):

        # Given a working directory
        with TempDirectory() as temp_dir:
            working_dir_path = os.path.join(temp_dir.path, 'working')

            # Given the 'npm' shell command exits with an error code
            npm_shell_command_mock.side_effect = sh.ErrorReturnCode('npm', b'mock stdout', b'mock error')

            # Given an NpmTest step implementer
            npm_test = self.create_given_step_implementer(NpmTest, parent_work_dir_path=working_dir_path)

            # When I run the step
            step_result = npm_test.run_step()

            # Then the StepResult should have success = False
            self.assertEqual(step_result.success, False)
Exemple #23
0
    def test_push_container_signature_specify_podman_implementer_pgp_failure(
            self, gpg_mock):
        """Test for pgp key load failure"""
        with TempDirectory() as temp_dir:
            config = TestStepImplementerSignContainerImagePodmanSign.generate_config(
            )
            TestStepImplementerSignContainerImagePodmanSign.generate_results(
                temp_dir)

            gpg_mock.side_effect = sh.ErrorReturnCode(
                'PodmanSign', b'mock stdout', b'mock error about curl runtime')
            with self.assertRaisesRegex(
                    RuntimeError,
                    r'Unexpected error importing pgp private key'):
                self.run_step_test_with_result_validation(
                    temp_dir,
                    'sign-container-image',
                    config,
                    expected_step_results=None)
    def test_run_step_pass(self, config_lint_mock):
        with TempDirectory() as temp_dir:
            results_dir_path = os.path.join(temp_dir.path,
                                            'step-runner-results')
            results_file_name = 'step-runner-results.yml'
            work_dir_path = os.path.join(temp_dir.path, 'working')
            test_file_name = 'file.txt'
            test_file_path = os.path.join(temp_dir.path, test_file_name)
            temp_dir.write(test_file_path, b'ignored')
            step_config = {
                'rules': test_file_path,
                'configlint-yml-path': test_file_path
            }

            step_implementer = self.create_step_implementer(
                step_config=step_config,
                step_name='validate-environment-configuration',
                implementer='Configlint',
                results_dir_path=results_dir_path,
                results_file_name=results_file_name,
                work_dir_path=work_dir_path,
            )

            config_lint_mock.side_effect = sh.ErrorReturnCode(
                'config_lint', b'mock out', b'mock error')
            result = step_implementer._run_step()

            expected_step_result = StepResult(
                step_name='validate-environment-configuration',
                sub_step_name='Configlint',
                sub_step_implementer_name='Configlint')

            expected_step_result.success = False
            expected_step_result.message = 'Unexpected Error invoking config-lint.'
            expected_step_result.add_artifact(
                name='configlint-result-set',
                value=
                f'{work_dir_path}/validate-environment-configuration/configlint_results_file.txt'
            )
            expected_step_result.add_artifact(name='configlint-yml-path',
                                              value=test_file_path)
            self.assertEqual(expected_step_result.get_step_result_dict(),
                             result.get_step_result_dict())
Exemple #25
0
    def test_success_failure(self, mock_open, redirect_mock, mvn_mock):
        with TempDirectory() as temp_dir:
            mvn_output_file_path = os.path.join(temp_dir.path,
                                                'maven_output.txt')
            settings_file = '/fake/settings.xml'
            pom_file = '/fake/pom.xml'
            phases_and_goals = 'fake'

            mvn_mock.side_effect = sh.ErrorReturnCode('mvn', b'mock stdout',
                                                      b'mock error')

            with self.assertRaisesRegex(
                    StepRunnerException,
                    re.compile(
                        r"Error running maven."
                        r".*RAN: mvn"
                        r".*STDOUT:"
                        r".*mock stdout"
                        r".*STDERR:"
                        r".*mock error", re.DOTALL)):
                run_maven(
                    mvn_output_file_path=mvn_output_file_path,
                    settings_file=settings_file,
                    pom_file=pom_file,
                    phases_and_goals=phases_and_goals,
                )

                mock_open.assert_called_with(mvn_output_file_path, 'w')
                redirect_mock.assert_has_calls([
                    call([sys.stdout, mock_open.return_value]),
                    call([sys.stderr, mock_open.return_value])
                ])

                mvn_mock.assert_called_once_with('fake',
                                                 '-f',
                                                 '/fake/pom.xml',
                                                 '-s',
                                                 '/fake/settings.xml',
                                                 '--no-transfer-progress',
                                                 _out=Any(StringIO),
                                                 _err=Any(StringIO))
Exemple #26
0
    def test_buildah_login_fail(self, which_mock, container_command_mock):
        which_mock.side_effect = create_which_side_effect(
            cmd='buildah', cmd_path='/mock/buildah')

        with self.assertRaisesRegex(
                RuntimeError,
                re.compile(
                    r"Failed to login to container registry \(registry.example.xyz\)"
                    r" with username \(example\):"
                    r".*RAN: buildah login"
                    r".*STDOUT:"
                    r".*mock stdout"
                    r".*STDERR:"
                    r".*mock stderr login error", re.DOTALL)):
            container_command_mock.bake().login.bake(
            ).side_effect = sh.ErrorReturnCode('buildah login', b'mock stdout',
                                               b'mock stderr login error')
            container_registry_login(
                container_registry_uri='registry.example.xyz',
                container_registry_username='******',
                container_registry_password='******')
Exemple #27
0
    def test_write_effective_pom_fail_not_absolute_path(self, mvn_mock):
        pom_file_path = 'input/pom.xml'
        effective_pom_path = 'output/effective-pom.xml'

        mvn_mock.side_effect = sh.ErrorReturnCode('mvn', b'mock stdout',
                                                  b'mock error')

        with self.assertRaisesRegex(
                StepRunnerException,
                re.compile(
                    rf"Given output path \({effective_pom_path}\) is not absolute which will mean "
                    rf"your output file will actually end up being relative to the pom file "
                    rf"\({pom_file_path}\) rather than your expected root. Rather then handling this, "
                    rf"just give this function an absolute path. "
                    rf"If you are a user seeing this, a programmer messed up somewhere, "
                    rf"report an issue.", re.DOTALL)):
            write_effective_pom(pom_file_path=pom_file_path,
                                output_path=effective_pom_path)
            mvn_mock.assert_any_call('help:effective-pom',
                                     f'-f={pom_file_path}',
                                     f'-Doutput={effective_pom_path}')
 def test_sonar_bad_sonar_scanner_results(self, sonar_mock):
     with TempDirectory() as temp_dir:
         tssc_results = '''tssc-results:
             generate-metadata:
                 version: 1.0-123abc
         '''
         temp_dir.write('tssc-results/tssc-results.yml',
                        tssc_results.encode())
         sonar_properties = '''
             used to test existence of file
         '''
         temp_dir.write('sonar-project.properties',
                        sonar_properties.encode())
         properties = os.path.join(temp_dir.path,
                                   'sonar-project.properties')
         config = {
             'tssc-config': {
                 'global-defaults': {
                     'application-name': 'tssc',
                     'service-name': 'tssc-reference-testcase'
                 },
                 'static-code-analysis': {
                     'implementer': 'SonarQube',
                     'config': {
                         'url':
                         'https://sonarqube-sonarqube.apps.tssc.rht-set.com',
                         'properties': properties
                     }
                 }
             }
         }
         expected_step_results = {}
         sh.sonar_scanner.side_effect = sh.ErrorReturnCode(
             'sonar_scanner', b'mock stdout', b'mock error')
         with self.assertRaisesRegex(RuntimeError,
                                     'Error invoking sonarscanner'):
             run_step_test_with_result_validation(temp_dir,
                                                  'static-code-analysis',
                                                  config,
                                                  expected_step_results)
Exemple #29
0
    def test_failure_pull_no_auth(self, mock_buildah):
        # setup mock
        mock_buildah.pull.side_effect = sh.ErrorReturnCode(
            'buildah pull', b'mock out', b'mock error')

        # run test
        with self.assertRaisesRegex(
                RuntimeError,
                re.compile(
                    "Error pulling container image \(mock.io/mock/awesome-image:latest\) for inspection:"
                    r".*RAN: buildah pull"
                    r".*STDOUT:"
                    r".*mock out"
                    r".*STDERR:"
                    r".*mock error", re.DOTALL)):
            inspect_container_image(
                container_image_uri='mock.io/mock/awesome-image:latest')

        # validate
        mock_buildah.pull.assert_called_once_with(
            'mock.io/mock/awesome-image:latest')
        mock_buildah.inspect.assert_not_called()
Exemple #30
0
    def test_decrypt_sops_error(self, sops_mock):
        encrypted_config_file_path = os.path.join(
            os.path.dirname(__file__), 'files', 'tssc-config-secret-stuff.yml')

        config_value = ConfigValue(
            value=
            'ENC[AES256_GCM,data:UGKfnzsSrciR7GXZJhOCMmFrz3Y6V3pZsd3P,iv:yuReqA+n+rRXVHMc+2US5t7yPx54sooZSXWV4KLjDIs=,tag:jueP7/ZWLfYrEuhh+4eS8g==,type:str]',
            parent_source=encrypted_config_file_path,
            path_parts=[
                'tssc-config', 'global-environment-defaults', 'DEV',
                'kube-api-token'
            ])

        sops_decryptor = SOPS()

        sh.sops.side_effect = sh.ErrorReturnCode(
            'sops', b'mock stdout', b'mock error about issue running sops')
        with self.assertRaisesRegex(
                RuntimeError,
                r"Error invoking sops when trying to decrypt config value \(ConfigValue\(.*\)\):"
        ):
            sops_decryptor.decrypt(config_value)