Beispiel #1
0
    def test__git_push_no_url_success(self, git_mock):

        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)

            step_implementer._Git__git_push(None)

            git_mock.push.assert_called_once_with('--tag',
                                                  _out=Any(IOBase),
                                                  _err=Any(IOBase),
                                                  _tee='err')
Beispiel #2
0
    def test_decrypt_additional_sops_args(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(additional_sops_args=['--aws-profile=foo'])

        sops_decryptor.decrypt(config_value)
        sops_mock.assert_called_once_with(
            '--decrypt',
            '--extract=["tssc-config"]["global-environment-defaults"]["DEV"]["kube-api-token"]',
            None,
            encrypted_config_file_path,
            '--aws-profile=foo',
            _in=None,
            _out=Any(StringIO),
            _err=Any(StringIO))
    def test_pom_file_valid_old_empty_jar(self, mvn_mock):
        artifact_id = 'my-app'
        version = '42.1'
        package = 'jar'
        with TempDirectory() as temp_dir:
            temp_dir.write(
                'pom.xml',
                bytes(
                    '''<project>
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.mycompany.app</groupId>
        <artifactId>{artifact_id}</artifactId>
        <version>{version}</version>
    </project>'''.format(artifact_id=artifact_id, version=version), 'utf-8'))
            pom_file_path = os.path.join(temp_dir.path, 'pom.xml')
            config = {
                'tssc-config': {
                    'package': {
                        'implementer': 'Maven',
                        'config': {
                            'pom-file': str(pom_file_path)
                        }
                    }
                }
            }
            artifact_file_name = '{artifact_id}-{version}.{package}'.format(
                artifact_id=artifact_id, version=version, package=package)
            expected_step_results = {
                'tssc-results': {
                    'package': {
                        'artifacts': [{
                            'path':
                            os.path.join(temp_dir.path, 'target',
                                         artifact_file_name),
                            'artifact-id':
                            artifact_id,
                            'group-id':
                            'com.mycompany.app',
                            'package-type':
                            package,
                            'pom-path':
                            str(pom_file_path)
                        }]
                    }
                }
            }

            mvn_mock.side_effect = create_mvn_side_effect(
                pom_file_path, 'target', [artifact_file_name])
            run_step_test_with_result_validation(temp_dir, 'package', config,
                                                 expected_step_results)
            settings_file_path = temp_dir.path + "/tssc-working/package/settings.xml"
            mvn_mock.assert_called_once_with('clean',
                                             'install',
                                             '-f',
                                             pom_file_path,
                                             '-s',
                                             settings_file_path,
                                             _out=Any(IOBase),
                                             _err=Any(IOBase))
Beispiel #4
0
    def test__git_push_no_url_success(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,
            )

            step_implementer._Git__git_push(None)

            git_mock.push.assert_called_once_with('--tag',
                                                  _out=Any(IOBase),
                                                  _err=Any(IOBase),
                                                  _tee='err')
Beispiel #5
0
    def test__git_tag_success(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
            )

            step_implementer._Git__git_tag(git_tag_value)

            git_mock.tag.assert_called_once_with(
                git_tag_value,
                '-f',
                _out=Any(IOBase),
                _err=Any(IOBase),
                _tee='err'
            )
    def test_value_decyrpt(self, sops_mock):
        encrypted_config_file_path = os.path.join(
            os.path.dirname(__file__), 'decryptors', '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'
            ])

        DecryptionUtils.register_config_value_decryptor(SOPS())

        sops_mock.side_effect = create_sops_side_effect('mock decrypted value')
        decrypted_value = config_value.value
        sops_mock.assert_called_once_with(
            '--decrypt',
            '--extract=["tssc-config"]["global-environment-defaults"]["DEV"]["kube-api-token"]',
            None,
            encrypted_config_file_path,
            _in=None,
            _out=Any(StringIO),
            _err=Any(StringIO))
        self.assertEqual(decrypted_value, 'mock decrypted value')
Beispiel #7
0
    def test_success_with_no_tls(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'

            run_maven(mvn_output_file_path=mvn_output_file_path,
                      settings_file=settings_file,
                      pom_file=pom_file,
                      phases_and_goals=phases_and_goals,
                      tls_verify=False)

            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',
                '-Dmaven.wagon.http.ssl.insecure=true',
                '-Dmaven.wagon.http.ssl.allowall=true',
                '-Dmaven.wagon.http.ssl.ignore.validity.dates=true',
                _out=Any(StringIO),
                _err=Any(StringIO))
Beispiel #8
0
    def test_success_with_multiple_profile(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'

            run_maven(mvn_output_file_path=mvn_output_file_path,
                      settings_file=settings_file,
                      pom_file=pom_file,
                      phases_and_goals=phases_and_goals,
                      profiles=['fake-profile1', 'fake-profile2'])

            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',
                                             '-P',
                                             'fake-profile1,fake-profile2',
                                             '--no-transfer-progress',
                                             _out=Any(StringIO),
                                             _err=Any(StringIO))
Beispiel #9
0
    def test___buildah_mount_container_error(self, buildah_mock):
        buildah_unshare_comand = 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"Unexpected runtime error mounting container \({container_name}\):"
                    r".*RAN: buildah"
                    r".*STDOUT:"
                    r".*mock out"
                    r".*STDERR:"
                    r".*mock error", re.DOTALL)):
            OpenSCAPGeneric._OpenSCAPGeneric__buildah_mount_container(
                buildah_unshare_comand=buildah_unshare_comand,
                container_id=container_name)

        buildah_mock.bake('unshare').bake(
            'buildah', 'mount').assert_called_once_with('--storage-driver',
                                                        'vfs',
                                                        container_name,
                                                        _out=Any(IOBase),
                                                        _err=Any(IOBase),
                                                        _tee='err')
Beispiel #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')
Beispiel #11
0
    def test_decrypt_parent_source_dict(self, sops_mock):
        encrypted_config_file_path = os.path.join(
            os.path.dirname(__file__), 'files', 'tssc-config-secret-stuff.yml')

        encrypted_config = parse_yaml_or_json_file(encrypted_config_file_path)
        encrypted_config_json = json.dumps(encrypted_config)

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

        sops_decryptor = SOPS()

        sops_decryptor.decrypt(config_value)
        sops_mock.assert_called_once_with(
            '--decrypt',
            '--extract=["tssc-config"]["global-environment-defaults"]["DEV"]["kube-api-token"]',
            '--input-type=json',
            '/dev/stdin',
            _in=encrypted_config_json,
            _out=Any(StringIO),
            _err=Any(StringIO))
Beispiel #12
0
    def test_push_container_signature_specify_podman_implementer_success(
            self, gpg_mock, podman_mock):
        """Test for signature signing success"""
        with TempDirectory() as temp_dir:
            config = TestStepImplementerSignContainerImagePodmanSign.generate_config(
            )
            config_dict = config['tssc-config']['sign-container-image'][
                'config']
            key = config_dict['container-image-signer-pgp-private-key']
            image_name = TestStepImplementerSignContainerImagePodmanSign.generate_results(
                temp_dir)

            signature_dir = os.path.join(temp_dir.path, 'tssc-working',
                                         'sign-container-image',
                                         'image-signature', 'hello-node')
            signature_file = os.path.join(signature_dir, 'signature-1')
            temp_dir.makedir(signature_dir)
            temp_dir.write(signature_file, b'signature')
            gpg_mock.side_effect = TestStepImplementerSignContainerImagePodmanSign.gpg_side_effect
            fingerprint = 'DD7208BA0A6359F65B906B29CF4AC14A3D109637'

            expected_step_results = {
                'tssc-results': {
                    'push-container-image': {
                        'container-image-tag': image_name
                    },
                    'sign-container-image': {
                        'container-image-signature-file-path':
                        signature_file,
                        'container-image-signature-name':
                        'hello-node/signature-1',
                        'container-image-signature-private-key-fingerprint':
                        fingerprint
                    }
                }
            }

            self.run_step_test_with_result_validation(temp_dir,
                                                      'sign-container-image',
                                                      config,
                                                      expected_step_results)
            gpg_mock.assert_called_once_with('--import',
                                             '--fingerprint',
                                             '--with-colons',
                                             '--import-options=import-show',
                                             _in=key,
                                             _out=Any(IOBase),
                                             _err_to_out=True,
                                             _tee='out')

            podman_mock.image('sign',
                              f'--sign-by={fingerprint}',
                              f'--directory={signature_dir}',
                              f'docker://{image_name}',
                              _out=Any(IOBase),
                              _err_to_out=True,
                              _tee='out')
    def test_run_step_pass(self, skopeo_mock):
        with TempDirectory() as temp_dir:
            parent_work_dir_path = os.path.join(temp_dir.path, 'working')

            image_tar_file = 'fake-image.tar'
            image_version = '1.0-69442c8'
            image_tag = f'fake-registry.xyz/fake-org/fake-app-fake-service:{image_version}'
            step_config = {
                'destination-url': 'fake-registry.xyz',
                'service-name': 'fake-service',
                'application-name': 'fake-app',
                'organization': 'fake-org',
                'container-image-version': image_version,
                'image-tar-file': image_tar_file
            }
            step_implementer = self.create_step_implementer(
                step_config=step_config,
                step_name='push-container-image',
                implementer='Skopeo',
                parent_work_dir_path=parent_work_dir_path,
            )

            result = step_implementer._run_step()

            expected_step_result = StepResult(
                step_name='push-container-image',
                sub_step_name='Skopeo',
                sub_step_implementer_name='Skopeo')
            expected_step_result.add_artifact(
                name='container-image-registry-uri', value='fake-registry.xyz')
            expected_step_result.add_artifact(
                name='container-image-registry-organization', value='fake-org')
            expected_step_result.add_artifact(
                name='container-image-repository',
                value='fake-app-fake-service')
            expected_step_result.add_artifact(name='container-image-name',
                                              value='fake-app-fake-service')
            expected_step_result.add_artifact(name='container-image-version',
                                              value=image_version)
            expected_step_result.add_artifact(
                name='container-image-tag',
                value=
                'fake-registry.xyz/fake-org/fake-app-fake-service:1.0-69442c8')
            self.assertEqual(result.get_step_result_dict(),
                             expected_step_result.get_step_result_dict())

            containers_config_auth_file = os.path.join(Path.home(),
                                                       '.skopeo-auth.json')
            skopeo_mock.copy.assert_called_once_with(
                "--src-tls-verify=true",
                "--dest-tls-verify=true",
                f"--authfile={containers_config_auth_file}",
                f'docker-archive:{image_tar_file}',
                f'docker://{image_tag}',
                _out=Any(IOBase),
                _err=Any(IOBase),
                _tee='err')
Beispiel #14
0
    def test_run_script_shell_argument(self, mock_open, redirect_callback_mock,
                                       npm_shell_command_mock):

        # When I use run_npm() to run 'command with:args'
        run_npm('/my/output/file', 'mycommand')

        # Then it should run a shell command, `npm command with:args`
        npm_shell_command_mock.assert_any_call('mycommand',
                                               _out=Any(StringIO),
                                               _err=Any(StringIO))
Beispiel #15
0
    def test_run_script_shell_argument_env_vars(self, mock_open,
                                                redirect_callback_mock,
                                                npm_shell_command_mock):

        # When I use run_npm() to run 'command with:args with:envs'
        run_npm('/my/output/file', 'mycommand', {
            "KEY1": "VALUE1",
            "KEY2": "VALUE2"
        })

        # Then it should run a shell command, `npm command with:args`
        npm_shell_command_mock.assert_any_call('mycommand',
                                               _out=Any(StringIO),
                                               _err=Any(StringIO),
                                               _env=Any(Dict))
Beispiel #16
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')
Beispiel #17
0
    def test___get_oscap_document_type_sds(self, oscap_mock):
        oscap_input_file = '/does/not/matter.xml'

        sh.oscap.info.side_effect = create_sh_side_effect(mock_stdout="""
Document type: Source Data Stream
Imported: 2020-10-07T05:34:29

Stream: scap_org.open-scap_datastream_from_xccdf_com.redhat.rhsa-all.xml-xccdf12
Generated: (null)
Version: 1.2
Checklists:
	Ref-Id: scap_org.open-scap_cref_com.redhat.rhsa-all.xml-xccdf12
		Status: incomplete
		Resolved: true
		Profiles:
		Referenced check files:
			com.redhat.rhsa-all.xml
				system: http://oval.mitre.org/XMLSchema/oval-definitions-5
Checks:
	Ref-Id: scap_org.open-scap_cref_com.redhat.rhsa-all.xml
No dictionaries.""")

        oscap_document_type = OpenSCAPGeneric._OpenSCAPGeneric__get_oscap_document_type(
            oscap_input_file=oscap_input_file)

        sh.oscap.info.assert_called_once_with(oscap_input_file,
                                              _out=Any(IOBase))

        self.assertEqual(oscap_document_type, 'Source Data Stream')
Beispiel #18
0
    def test___get_oscap_document_type_xccdf(self, oscap_mock):
        oscap_input_file = '/does/not/matter.xml'

        sh.oscap.info.side_effect = create_sh_side_effect(mock_stdout="""
Document type: XCCDF Checklist
Checklist version: 1.1
Imported: 2020-02-11T13:41:07
Status: draft
Generated: 2020-02-11
Resolved: true
Profiles:
	Title: Protection Profile for General Purpose Operating Systems
		Id: ospp
	Title: PCI-DSS v3.2.1 Control Baseline for Red Hat Enterprise Linux 8
		Id: pci-dss
	Title: [DRAFT] DISA STIG for Red Hat Enterprise Linux 8
		Id: stig
	Title: Australian Cyber Security Centre (ACSC) Essential Eight
		Id: e8
Referenced check files:
	ssg-rhel8-oval.xml
		system: http://oval.mitre.org/XMLSchema/oval-definitions-5
	ssg-rhel8-ocil.xml
		system: http://scap.nist.gov/schema/ocil/2
	https://www.redhat.com/security/data/oval/com.redhat.rhsa-RHEL8.xml
		system: http://oval.mitre.org/XMLSchema/oval-definitions-5""")

        oscap_document_type = OpenSCAPGeneric._OpenSCAPGeneric__get_oscap_document_type(
            oscap_input_file=oscap_input_file)

        sh.oscap.info.assert_called_once_with(oscap_input_file,
                                              _out=Any(IOBase))

        self.assertEqual(oscap_document_type, 'XCCDF Checklist')
    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___sign_image_podman_image_sign_to_many_sigs(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 = TestStepImplementerSignContainerImagePodman.\
                create_podman_image_sign_side_effect(num_signatures=2)

            with self.assertRaisesRegex(
                StepRunnerException,
                re.compile(
                    r"Unexpected number of signature files, expected 1: \['.*', '.*'\]",
                    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'
            )
    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'
            )
Beispiel #22
0
    def test_audit_attestation_pass(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"

        workflow_attestation_file_path = "workflow_attestation_file_path"
        workflow_policy_file_path = "workflow_policy_file_path"
        workflow_policy_query =  "fooquery"

        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"
        )

        audit_results_mock.assert_called_once_with(
            'eval',
            '--fail-defined',
            '-d',
            workflow_attestation_file_path,
            '-i',
            workflow_policy_file_path,
            workflow_policy_query,
            _out=Any(IOBase),
            _err_to_out=True,
            _tee='out'
        )
Beispiel #23
0
    def test___import_pgp_key_fail_get_fingerprint(self, gpg_mock):
        pgp_private_key=TestStepImplementerSignContainerImagePodman.TEST_FAKE_PRIVATE_KEY

        with self.assertRaisesRegex(
            StepRunnerException,
            re.compile(
                r"Error getting PGP fingerprint for PGP key"
                r" to sign container image\(s\) with. See stdout and stderr for more info.",
                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'
        )
Beispiel #24
0
    def test___buildah_import_image_from_tar_success(self, buildah_mock):
        image_tar_file = "/does/not/matter.tar"
        container_name = "test"

        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')
    def test_success_with_report_dir_deployed_host_urls_not_list(
        self,
        mock_gather_evidence,
        mock_write_working_file,
        mock_run_npm_step
    ):
        with TempDirectory() as test_dir:
            # setup test
            parent_work_dir_path = os.path.join(test_dir.path, 'working')
            step_config = {
                'deployed-host-urls': 'https://mock.ploigos.org/mock-app-1',
                'npm-envs':
                {
                    'VAR1': 'VAL1',
                    'VAR2': 'VAL2'
                },
                'test-reports-dir': '/mock/test-results-dir',
                "target-host-env-var-name": "APP_ROUTE"

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

            # run test
            actual_step_result = step_implementer._run_step()

            # verify results
            expected_step_result = StepResult(
                step_name='unit-test',
                sub_step_name='NpmXunitIntegrationTest',
                sub_step_implementer_name='NpmXunitIntegrationTest'
            )
            expected_step_result.add_artifact(
                description="Standard out and standard error from npm.",
                name='npm-output',
                value='/mock/npm_output.txt'
            )
            expected_step_result.add_artifact(
                description="Test report generated when running tests.",
                name='test-report',
                value='/mock/test-results-dir'
            )
            self.assertEqual(actual_step_result, expected_step_result)

            mock_run_npm_step.assert_called_once_with(
                npm_output_file_path='/mock/npm_output.txt',
                step_implementer_additional_envs={
                    'APP_ROUTE': 'https://mock.ploigos.org/mock-app-1'}
            )
            mock_gather_evidence.assert_called_once_with(
                step_result=Any(StepResult),
                test_report_dirs='/mock/test-results-dir'
            )

            self.assertEqual(step_implementer.npm_args, ['run', 'test:uat'])
Beispiel #26
0
    def test_run_shell_command(self, os_path_exists_mock, tox_shell_command_mock):

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

            # Given an ToxTest step implementer
            tox_test = self.create_given_step_implementer(ToxTest, parent_work_dir_path=working_dir_path)

            # When I run the step
            tox_test.run_step()

            # Then it should run a shell command, 'tox test'
            tox_shell_command_mock.assert_any_call(
                ('-q', '-e', 'test',),
                _out=Any(StringIO),
                _err=Any(StringIO)
            )
Beispiel #27
0
    def test_run_shell_command(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 an NpmPackage step implementer
            npm_test = self.create_given_step_implementer(
                NpmPackage, parent_work_dir_path=working_dir_path)

            # When I run the step
            npm_test.run_step()

            # Then it should run a shell command, 'npm test'
            npm_shell_command_mock.assert_any_call('install',
                                                   _out=Any(StringIO),
                                                   _err=Any(StringIO))
    def test_run_step_pass_nofips(self, curl_mock):
        with TempDirectory() as temp_dir:
            work_dir_path = os.path.join(temp_dir.path, 'working')
            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'

            step_config = {
                'container-image-signature-server-url': 'https://sigserver/signatures',
                'container-image-signature-server-username': '******',
                'container-image-signature-server-password': '******',
                'with-fips': False
            }

            # Previous (fake) results
            artifact_config = {
                'container-image-signature-file-path': {'value': container_image_signature_file_path},
                'container-image-signature-name': {'value': container_image_signature_name},
            }
            workflow_result = self.setup_previous_result(work_dir_path, artifact_config)

            # Actual results
            step_implementer = self.create_step_implementer(
                step_config=step_config,
                step_name='sign-container-image',
                implementer='CurlPush',
                workflow_result=workflow_result,
                work_dir_path=work_dir_path
            )

            result = step_implementer._run_step()

            # # Expected results
            expected_step_result = StepResult(step_name='sign-container-image', sub_step_name='CurlPush',
                                              sub_step_implementer_name='CurlPush')
            expected_step_result.add_artifact(name='container-image-signature-url', value=f'https://sigserver/signatures/{container_image_signature_name}')
            expected_step_result.add_artifact(name='container-image-signature-file-sha1', value='d9ba1fc747829392883c48adfe4bb688239dc8b2')
            expected_step_result.add_artifact(name='container-image-signature-file-md5', value='b66c5c3d4ab37a50e69a05d72ba302fa')

            self.assertEqual(expected_step_result.get_step_result_dict(), result.get_step_result_dict())
            curl_mock.assert_called_once_with(
                '-sSfv',
                '-X', 'PUT',
                '--user', "admin:adminPassword",
                '--upload-file', container_image_signature_file_path,
                '--header', StringRegexParam(r'X-Checksum-Sha1:.+'),
                '--header', StringRegexParam(r'X-Checksum-MD5:.+'),
                f"https://sigserver/signatures/{container_image_signature_name}",
                _out=Any(IOBase),
                _err_to_out=True,
                _tee='out'
            )
Beispiel #29
0
    def test_upload_to_rekor(self, rekor_mock, create_mock):
        with TempDirectory() as temp_dir:
            parent_work_dir_path = os.path.join(temp_dir.path, 'working')
            signer_pgp_public_key_path = os.path.join(
                os.path.dirname(__file__), '../../helpers', 'files',
                'ploigos-step-runner-tests-public.key')

            step_config = {
                'rekor-server-url': self.TEST_REKOR_SERVER_URL,
                'signer-pgp-private-key': self.TEST_PGP_SIGNER_PRIVATE_KEY
            }

            step_implementer = self.create_step_implementer(
                step_config=step_config,
                parent_work_dir_path=parent_work_dir_path,
                artifact_to_sign_uri_config_key=self.TEST_ARTIFACT_TO_SIGN_URI)

            artifact_data_file = os.path.join(parent_work_dir_path,
                                              'automated-governance',
                                              'automated-governance.json')
            artifact_data_file_path = Path(artifact_data_file)
            WorkflowResult().write_results_to_json_file(
                artifact_data_file_path)
            rekor_entry_path_name = os.path.join(parent_work_dir_path,
                                                 'automated-governance',
                                                 'entry.json')

            def create_mock_side_effect(signer_pgp_public_key_path,
                                        signer_pgp_private_key_user,
                                        extra_data_file):
                return self.TEST_REKOR_ENTRY

            def rekor_mock_side_effect(*args, **kwargs):
                return 'Created entry at: ' + args[
                    2] + '/api/v1/log/entries/' + self.TEST_REKOR_UUID

            create_mock.side_effect = create_mock_side_effect
            rekor_mock.side_effect = rekor_mock_side_effect

            rekor_entry_path = Path(rekor_entry_path_name)
            rekor_entry_path.touch()

            result_uuid = step_implementer._upload_to_rekor(
                rekor_server=self.TEST_REKOR_SERVER_URL,
                rekor_entry=self.TEST_REKOR_ENTRY)

            rekor_mock.assert_called_once_with('upload',
                                               '--rekor_server',
                                               self.TEST_REKOR_SERVER_URL,
                                               '--entry',
                                               rekor_entry_path_name,
                                               _out=Any(IOBase),
                                               _err_to_out=True,
                                               _tee='out')
            self.assertEqual(result_uuid, self.TEST_REKOR_UUID)
Beispiel #30
0
    def test_fail_with_report_dir(
        self,
        mock_gather_evidence,
        mock_get_test_report_dir,
        mock_write_working_file,
        mock_run_maven_step
    ):
        with TempDirectory() as test_dir:
            # setup test
            parent_work_dir_path = os.path.join(test_dir.path, 'working')
            pom_file = os.path.join(test_dir.path, 'mock-pom.xml')
            step_config = {
                'pom-file': pom_file
            }
            step_implementer = self.create_step_implementer(
                step_config=step_config,
                parent_work_dir_path=parent_work_dir_path,
            )

            # setup mocks
            mock_run_maven_step.side_effect = StepRunnerException('mock error')

            # run test
            actual_step_result = step_implementer._run_step()

            # verify results
            expected_step_result = StepResult(
                step_name='unit-test',
                sub_step_name='MavenTest',
                sub_step_implementer_name='MavenTest'
            )
            expected_step_result.success = False
            expected_step_result.message = "Error running maven. " \
                "More details maybe found in report artifacts: " \
                "mock error"
            expected_step_result.add_artifact(
                description="Standard out and standard error from maven.",
                name='maven-output',
                value='/mock/mvn_output.txt'
            )
            expected_step_result.add_artifact(
                description="Test report generated when running unit tests.",
                name='test-report',
                value='/mock/test-results-dir'
            )
            self.assertEqual(actual_step_result, expected_step_result)

            mock_run_maven_step.assert_called_once_with(
                mvn_output_file_path='/mock/mvn_output.txt'
            )
            mock_gather_evidence.assert_called_once_with(
                step_result=Any(StepResult),
                test_report_dir='/mock/test-results-dir'
            )