Kitxuuu commited on
Commit
ef9e7b0
·
verified ·
1 Parent(s): ed5b9d1

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/CHANGELOG +3 -0
  2. local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/affected_fuzz_targets_test.py +113 -0
  3. local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/build_fuzzers.py +217 -0
  4. local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/build_fuzzers_test.py +403 -0
  5. local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/cloudbuild.yaml +52 -0
  6. local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment_test.py +268 -0
  7. local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/config_utils_test.py +200 -0
  8. local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/environment.py +51 -0
  9. local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/example_cifuzz.yml +33 -0
  10. local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/filestore_utils_test.py +50 -0
  11. local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/generate_coverage_report.py +48 -0
  12. local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/generate_coverage_report_test.py +71 -0
  13. local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/get_coverage.py +208 -0
  14. local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/get_coverage_test.py +253 -0
  15. local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/http_utils.py +118 -0
  16. local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/logs.py +25 -0
  17. local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/run_fuzzers.py +321 -0
  18. local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/run_fuzzers_entrypoint.py +97 -0
  19. local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/run_fuzzers_test.py +475 -0
  20. local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/workspace_utils.py +85 -0
local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/CHANGELOG ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ Next Release:
2
+
3
+ Improve detection of changed files better by fixing https://github.com/google/oss-fuzz/issues/7011
local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/affected_fuzz_targets_test.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests for affected_fuzz_targets.py"""
15
+ import os
16
+ import shutil
17
+ import tempfile
18
+ import unittest
19
+ from unittest import mock
20
+
21
+ import parameterized
22
+
23
+ import affected_fuzz_targets
24
+ import clusterfuzz_deployment
25
+ import get_coverage
26
+ import test_helpers
27
+ import workspace_utils
28
+
29
+ # pylint: disable=protected-access
30
+
31
+ # NOTE: This integration test relies on
32
+ # https://github.com/google/oss-fuzz/tree/master/projects/example project.
33
+ EXAMPLE_PROJECT = 'example'
34
+
35
+ EXAMPLE_FILE_CHANGED = 'test.txt'
36
+
37
+ TEST_DATA_OUT_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
38
+ 'test_data', 'build-out')
39
+
40
+
41
+ class RemoveUnaffectedFuzzTargetsTest(unittest.TestCase):
42
+ """Tests remove_unaffected_fuzzers."""
43
+
44
+ TEST_FUZZER_1 = os.path.join(TEST_DATA_OUT_PATH, 'example_crash_fuzzer')
45
+ TEST_FUZZER_2 = os.path.join(TEST_DATA_OUT_PATH, 'example_nocrash_fuzzer')
46
+
47
+ # yapf: disable
48
+ @parameterized.parameterized.expand([
49
+ # Tests specific affected fuzzers are kept.
50
+ ([[EXAMPLE_FILE_CHANGED], None], 2,),
51
+
52
+ # Tests specific affected fuzzer is kept.
53
+ ([[EXAMPLE_FILE_CHANGED], ['not/a/real/file']], 1),
54
+
55
+ # Tests all fuzzers are kept if none are deemed affected.
56
+ ([None, None], 2),
57
+
58
+ # Tests that multiple fuzzers are kept if multiple fuzzers are affected.
59
+ ([[EXAMPLE_FILE_CHANGED], [EXAMPLE_FILE_CHANGED]], 2),
60
+ ])
61
+ # yapf: enable
62
+ def test_remove_unaffected_fuzz_targets(self, side_effect, expected_dir_len):
63
+ """Tests that remove_unaffected_fuzzers has the intended effect."""
64
+ config = test_helpers.create_run_config(
65
+ cfl_platform='github',
66
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
67
+ workspace='/workspace')
68
+ workspace = workspace_utils.Workspace(config)
69
+ deployment = clusterfuzz_deployment.get_clusterfuzz_deployment(
70
+ config, workspace)
71
+ # We can't use fakefs in this test because this test executes
72
+ # utils.is_fuzz_target_local. This function relies on the executable bit
73
+ # being set, which doesn't work properly in fakefs.
74
+ with tempfile.TemporaryDirectory() as tmp_dir, mock.patch(
75
+ 'get_coverage.OSSFuzzCoverage.get_files_covered_by_target'
76
+ ) as mock_get_files:
77
+ with mock.patch('get_coverage._get_oss_fuzz_fuzzer_stats_dir_url',
78
+ return_value=1):
79
+ mock_get_files.side_effect = side_effect
80
+ shutil.copy(self.TEST_FUZZER_1, tmp_dir)
81
+ shutil.copy(self.TEST_FUZZER_2, tmp_dir)
82
+
83
+ affected_fuzz_targets.remove_unaffected_fuzz_targets(
84
+ deployment, tmp_dir, [EXAMPLE_FILE_CHANGED], '')
85
+ self.assertEqual(expected_dir_len, len(os.listdir(tmp_dir)))
86
+
87
+
88
+ class IsFuzzTargetAffectedTest(unittest.TestCase):
89
+ """Tests for is_fuzz_target_affected."""
90
+
91
+ def setUp(self):
92
+ self.fuzz_target_path = '/fuzz_target'
93
+
94
+ def test_relative_paths(self):
95
+ """Tests that is_fuzz_target_affected works as intended when the covered
96
+ files are relative paths."""
97
+ with mock.patch.object(
98
+ get_coverage.FilesystemCoverage,
99
+ 'get_files_covered_by_target',
100
+ ) as get_files_covered_by_target:
101
+ get_files_covered_by_target.return_value = [
102
+ '/work/build/../../src/systemd/src/basic/alloc-util.c'
103
+ ]
104
+ coverage = get_coverage.FilesystemCoverage('/', '/')
105
+
106
+ self.assertTrue(
107
+ affected_fuzz_targets.is_fuzz_target_affected(
108
+ coverage, self.fuzz_target_path,
109
+ ['/src/systemd/src/basic/alloc-util.c']))
110
+
111
+
112
+ if __name__ == '__main__':
113
+ unittest.main()
local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/build_fuzzers.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Module used by CI tools in order to interact with fuzzers. This module helps
15
+ CI tools to build fuzzers."""
16
+
17
+ import logging
18
+ import os
19
+ import sys
20
+
21
+ import affected_fuzz_targets
22
+ import base_runner_utils
23
+ import clusterfuzz_deployment
24
+ import continuous_integration
25
+ import docker
26
+ import logs
27
+ import workspace_utils
28
+
29
+ # pylint: disable=wrong-import-position,import-error
30
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
31
+ import helper
32
+ import utils
33
+
34
+ logs.init()
35
+
36
+
37
+ def check_project_src_path(project_src_path):
38
+ """Returns True if |project_src_path| exists."""
39
+ if not os.path.exists(project_src_path):
40
+ logging.error(
41
+ 'PROJECT_SRC_PATH: %s does not exist. '
42
+ 'Are you mounting it correctly?', project_src_path)
43
+ return False
44
+ return True
45
+
46
+
47
+ # pylint: disable=too-many-arguments
48
+
49
+
50
+ class Builder: # pylint: disable=too-many-instance-attributes
51
+ """Class for fuzzer builders."""
52
+
53
+ def __init__(self, config, ci_system):
54
+ self.config = config
55
+ self.ci_system = ci_system
56
+ self.workspace = workspace_utils.Workspace(config)
57
+ self.workspace.initialize_dir(self.workspace.out)
58
+ self.workspace.initialize_dir(self.workspace.work)
59
+ self.clusterfuzz_deployment = (
60
+ clusterfuzz_deployment.get_clusterfuzz_deployment(
61
+ self.config, self.workspace))
62
+ self.image_repo_path = None
63
+ self.host_repo_path = None
64
+ self.repo_manager = None
65
+
66
+ def build_image_and_checkout_src(self):
67
+ """Builds the project builder image and checkout source code for the patch
68
+ we want to fuzz (if necessary). Returns True on success."""
69
+ result = self.ci_system.prepare_for_fuzzer_build()
70
+ if not result.success:
71
+ return False
72
+ self.image_repo_path = result.image_repo_path
73
+ self.repo_manager = result.repo_manager
74
+ if self.config.output_sarif:
75
+ self.workspace.make_repo_for_sarif(self.repo_manager)
76
+ logging.info('repo_dir: %s.', self.repo_manager.repo_dir)
77
+ self.host_repo_path = self.repo_manager.repo_dir
78
+ return True
79
+
80
+ def build_fuzzers(self):
81
+ """Moves the source code we want to fuzz into the project builder and builds
82
+ the fuzzers from that source code. Returns True on success."""
83
+ docker_args, docker_container = docker.get_base_docker_run_args(
84
+ self.workspace, self.config.sanitizer, self.config.language,
85
+ self.config.architecture, self.config.docker_in_docker)
86
+ if not docker_container:
87
+ docker_args.extend(
88
+ _get_docker_build_fuzzers_args_not_container(self.host_repo_path))
89
+
90
+ build_command = self.ci_system.get_build_command(self.host_repo_path,
91
+ self.image_repo_path)
92
+
93
+ # Set extra environment variables so that they are visible to the build.
94
+ for key in self.config.extra_environment_variables:
95
+ # Don't specify their value in case they get echoed.
96
+ docker_args.extend(['-e', key])
97
+
98
+ docker_args.extend([
99
+ docker.get_project_image_name(self.config.oss_fuzz_project_name),
100
+ '/bin/bash',
101
+ '-c',
102
+ build_command,
103
+ ])
104
+ logging.info('Building with %s sanitizer.', self.config.sanitizer)
105
+
106
+ # TODO(metzman): Stop using helper.docker_run so we can get rid of
107
+ # docker.get_base_docker_run_args and merge its contents into
108
+ # docker.get_base_docker_run_command.
109
+ if not helper.docker_run(docker_args):
110
+ logging.error('Building fuzzers failed.')
111
+ return False
112
+
113
+ return True
114
+
115
+ def upload_build(self):
116
+ """Upload build."""
117
+ if self.config.upload_build:
118
+ self.clusterfuzz_deployment.upload_build(
119
+ self.repo_manager.get_current_commit())
120
+
121
+ return True
122
+
123
+ def check_fuzzer_build(self):
124
+ """Checks the fuzzer build. Returns True on success or if config specifies
125
+ to skip check."""
126
+ if not self.config.bad_build_check:
127
+ return True
128
+
129
+ return check_fuzzer_build(self.config)
130
+
131
+ def build(self):
132
+ """Builds the image, checkouts the source (if needed), builds the fuzzers
133
+ and then removes the unaffectted fuzzers. Returns True on success."""
134
+ methods = [
135
+ self.build_image_and_checkout_src,
136
+ self.build_fuzzers,
137
+ self.remove_unaffected_fuzz_targets,
138
+ self.upload_build,
139
+ self.check_fuzzer_build,
140
+ ]
141
+ for method in methods:
142
+ if not method():
143
+ return False
144
+ return True
145
+
146
+ def remove_unaffected_fuzz_targets(self):
147
+ """Removes the fuzzers unaffected by the patch."""
148
+ if self.config.keep_unaffected_fuzz_targets:
149
+ logging.info('Not removing unaffected fuzz targets.')
150
+ return True
151
+
152
+ logging.info('Removing unaffected fuzz targets.')
153
+ changed_files = self.ci_system.get_changed_code_under_test(
154
+ self.repo_manager)
155
+ affected_fuzz_targets.remove_unaffected_fuzz_targets(
156
+ self.clusterfuzz_deployment, self.workspace.out, changed_files,
157
+ self.image_repo_path)
158
+ return True
159
+
160
+
161
+ def build_fuzzers(config):
162
+ """Builds all of the fuzzers for a specific OSS-Fuzz project.
163
+
164
+ Args:
165
+ config: The configuration object for building fuzzers.
166
+
167
+ Returns:
168
+ True if build succeeded.
169
+ """
170
+ # Do some quick validation.
171
+ if config.project_src_path and not check_project_src_path(
172
+ config.project_src_path):
173
+ return False
174
+
175
+ # Get the builder and then build the fuzzers.
176
+ ci_system = continuous_integration.get_ci(config)
177
+ logging.info('ci_system: %s.', ci_system)
178
+ builder = Builder(config, ci_system)
179
+ return builder.build()
180
+
181
+
182
+ def check_fuzzer_build(config):
183
+ """Checks the integrity of the built fuzzers.
184
+
185
+ Args:
186
+ config: The config object.
187
+
188
+ Returns:
189
+ True if fuzzers pass OSS-Fuzz's build check.
190
+ """
191
+ workspace = workspace_utils.Workspace(config)
192
+ if not os.path.exists(workspace.out):
193
+ logging.error('Invalid out directory: %s.', workspace.out)
194
+ return False
195
+ if not os.listdir(workspace.out):
196
+ logging.error('No fuzzers found in out directory: %s.', workspace.out)
197
+ return False
198
+
199
+ env = base_runner_utils.get_env(config, workspace)
200
+ if config.allowed_broken_targets_percentage is not None:
201
+ env['ALLOWED_BROKEN_TARGETS_PERCENTAGE'] = (
202
+ config.allowed_broken_targets_percentage)
203
+
204
+ stdout, stderr, retcode = utils.execute('test_all.py', env=env)
205
+ print(f'Build check: stdout: {stdout}\nstderr: {stderr}')
206
+ if retcode == 0:
207
+ logging.info('Build check passed.')
208
+ return True
209
+ logging.error('Build check failed.')
210
+ return False
211
+
212
+
213
+ def _get_docker_build_fuzzers_args_not_container(host_repo_path):
214
+ """Returns arguments to the docker build arguments that are needed to use
215
+ |host_repo_path| when the host of the OSS-Fuzz builder container is not
216
+ another container."""
217
+ return ['-v', f'{host_repo_path}:{host_repo_path}']
local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/build_fuzzers_test.py ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests the functionality of the cifuzz module."""
15
+ import os
16
+ import shutil
17
+ import sys
18
+ import tempfile
19
+ import unittest
20
+ from unittest import mock
21
+
22
+ import parameterized
23
+
24
+ # pylint: disable=wrong-import-position
25
+ INFRA_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
26
+ sys.path.append(INFRA_DIR)
27
+
28
+ OSS_FUZZ_DIR = os.path.dirname(INFRA_DIR)
29
+
30
+ import build_fuzzers
31
+ import continuous_integration
32
+ import repo_manager
33
+ import test_helpers
34
+
35
+ # NOTE: This integration test relies on
36
+ # https://github.com/google/oss-fuzz/tree/master/projects/example project.
37
+ EXAMPLE_PROJECT = 'example'
38
+
39
+ # Location of data used for testing.
40
+ TEST_DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
41
+ 'test_data')
42
+
43
+ # An example fuzzer that triggers an crash.
44
+ # Binary is a copy of the example project's do_stuff_fuzzer and can be
45
+ # generated by running "python3 infra/helper.py build_fuzzers example".
46
+ EXAMPLE_CRASH_FUZZER = 'example_crash_fuzzer'
47
+
48
+ # An example fuzzer that does not trigger a crash.
49
+ # Binary is a modified version of example project's do_stuff_fuzzer. It is
50
+ # created by removing the bug in my_api.cpp.
51
+ EXAMPLE_NOCRASH_FUZZER = 'example_nocrash_fuzzer'
52
+
53
+ # A fuzzer to be built in build_fuzzers integration tests.
54
+ EXAMPLE_BUILD_FUZZER = 'do_stuff_fuzzer'
55
+
56
+ # pylint: disable=no-self-use,protected-access,too-few-public-methods,unused-argument
57
+
58
+
59
+ def docker_command_has_env_var_arg(command, env_var_arg):
60
+ """Returns True if a docker command has a specific env var argument."""
61
+ for idx, element in enumerate(command):
62
+ if idx == 0:
63
+ # We're looking for the variable which can't be the first argument.
64
+ continue
65
+
66
+ if element == env_var_arg and command[idx - 1] == '-e':
67
+ return True
68
+ return False
69
+
70
+
71
+ class BuildFuzzersTest(unittest.TestCase):
72
+ """Unit tests for build_fuzzers."""
73
+
74
+ @mock.patch('build_specified_commit.detect_main_repo',
75
+ return_value=('example.com', '/path'))
76
+ @mock.patch('repo_manager._clone', return_value=None)
77
+ @mock.patch('continuous_integration.checkout_specified_commit')
78
+ @mock.patch('helper.docker_run', return_value=False) # We want to quit early.
79
+ def test_cifuzz_env_var(self, mock_docker_run, _, __, ___):
80
+ """Tests that the CIFUZZ env var is set."""
81
+
82
+ with tempfile.TemporaryDirectory() as tmp_dir:
83
+ build_fuzzers.build_fuzzers(
84
+ test_helpers.create_build_config(
85
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
86
+ project_repo_name=EXAMPLE_PROJECT,
87
+ workspace=tmp_dir,
88
+ pr_ref='refs/pull/1757/merge'))
89
+
90
+ docker_run_command = mock_docker_run.call_args_list[0][0][0]
91
+
92
+ self.assertTrue(
93
+ docker_command_has_env_var_arg(docker_run_command, 'CIFUZZ=True'))
94
+
95
+ @mock.patch('build_specified_commit.detect_main_repo',
96
+ return_value=('example.com', '/path'))
97
+ @mock.patch('repo_manager._clone', return_value=None)
98
+ @mock.patch('continuous_integration.checkout_specified_commit')
99
+ @mock.patch('helper.docker_run', return_value=False) # We want to quit early.
100
+ def test_extra_env_var(self, mock_docker_run, _, __, ___):
101
+ """Tests that the CIFUZZ env var is set."""
102
+
103
+ extra_env_var = 'CFL_EXTRA_TOKEN'
104
+ with tempfile.TemporaryDirectory() as tmp_dir:
105
+ with mock.patch.dict(os.environ, {extra_env_var: 'BLAH'}):
106
+ build_fuzzers.build_fuzzers(
107
+ test_helpers.create_build_config(
108
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
109
+ project_repo_name=EXAMPLE_PROJECT,
110
+ workspace=tmp_dir,
111
+ pr_ref='refs/pull/1757/merge'))
112
+
113
+ docker_run_command = mock_docker_run.call_args_list[0][0][0]
114
+ self.assertTrue(
115
+ docker_command_has_env_var_arg(docker_run_command, extra_env_var))
116
+
117
+
118
+ class InternalGithubBuildTest(unittest.TestCase):
119
+ """Tests for building OSS-Fuzz projects on GitHub actions."""
120
+ PROJECT_REPO_NAME = 'myproject'
121
+ SANITIZER = 'address'
122
+ GIT_SHA = 'fake'
123
+ PR_REF = 'fake'
124
+
125
+ def _create_builder(self, tmp_dir, oss_fuzz_project_name='myproject'):
126
+ """Creates an InternalGithubBuilder and returns it."""
127
+ config = test_helpers.create_build_config(
128
+ oss_fuzz_project_name=oss_fuzz_project_name,
129
+ project_repo_name=self.PROJECT_REPO_NAME,
130
+ workspace=tmp_dir,
131
+ sanitizer=self.SANITIZER,
132
+ git_sha=self.GIT_SHA,
133
+ pr_ref=self.PR_REF,
134
+ cfl_platform='github')
135
+ cfl_platform = continuous_integration.get_ci(config)
136
+ builder = build_fuzzers.Builder(config, cfl_platform)
137
+ builder.repo_manager = repo_manager.RepoManager('/fake')
138
+ return builder
139
+
140
+ @mock.patch('helper.docker_run', return_value=True)
141
+ @mock.patch('continuous_integration.checkout_specified_commit',
142
+ side_effect=None)
143
+ def test_correct_host_repo_path(self, _, __):
144
+ """Tests that the correct self.host_repo_path is set by
145
+ build_image_and_checkout_src. Specifically, we want the name of the
146
+ directory the repo is in to match the name used in the docker
147
+ image/container, so that it will replace the host's copy properly."""
148
+ image_repo_path = '/src/repo_dir'
149
+ with tempfile.TemporaryDirectory() as tmp_dir, mock.patch(
150
+ 'build_specified_commit.detect_main_repo',
151
+ return_value=('inferred_url', image_repo_path)):
152
+ builder = self._create_builder(tmp_dir)
153
+ builder.build_image_and_checkout_src()
154
+
155
+ self.assertEqual(os.path.basename(builder.host_repo_path),
156
+ os.path.basename(image_repo_path))
157
+
158
+ @mock.patch('clusterfuzz_deployment.ClusterFuzzLite.upload_build',
159
+ return_value=True)
160
+ def test_upload_build_disabled(self, mock_upload_build):
161
+ """Test upload build (disabled)."""
162
+ with tempfile.TemporaryDirectory() as tmp_dir:
163
+ builder = self._create_builder(tmp_dir)
164
+ builder.upload_build()
165
+
166
+ mock_upload_build.assert_not_called()
167
+
168
+ @mock.patch('repo_manager.RepoManager.get_current_commit',
169
+ return_value='commit')
170
+ @mock.patch('clusterfuzz_deployment.ClusterFuzzLite.upload_build',
171
+ return_value=True)
172
+ def test_upload_build(self, mock_upload_build, mock_get_current_commit):
173
+ """Test upload build."""
174
+ with tempfile.TemporaryDirectory() as tmp_dir:
175
+ builder = self._create_builder(tmp_dir, oss_fuzz_project_name='')
176
+ builder.config.upload_build = True
177
+ builder.upload_build()
178
+
179
+ mock_upload_build.assert_called_with('commit')
180
+
181
+
182
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
183
+ 'INTEGRATION_TESTS=1 not set')
184
+ class BuildFuzzersIntegrationTest(unittest.TestCase):
185
+ """Integration tests for build_fuzzers."""
186
+
187
+ def setUp(self):
188
+ self.temp_dir_ctx_manager = test_helpers.docker_temp_dir()
189
+ self.workspace = self.temp_dir_ctx_manager.__enter__()
190
+ self.out_dir = os.path.join(self.workspace, 'build-out')
191
+ test_helpers.patch_environ(self)
192
+
193
+ base_runner_path = os.path.join(INFRA_DIR, 'base-images', 'base-runner')
194
+ os.environ['PATH'] = os.environ['PATH'] + os.pathsep + base_runner_path
195
+
196
+ def tearDown(self):
197
+ self.temp_dir_ctx_manager.__exit__(None, None, None)
198
+
199
+ def test_external_github_project(self):
200
+ """Tests building fuzzers from an external project on Github."""
201
+ project_repo_name = 'external-project'
202
+ git_url = 'https://github.com/jonathanmetzman/cifuzz-external-example.git'
203
+ # This test is dependant on the state of
204
+ # github.com/jonathanmetzman/cifuzz-external-example.
205
+ config = test_helpers.create_build_config(
206
+ project_repo_name=project_repo_name,
207
+ workspace=self.workspace,
208
+ git_url=git_url,
209
+ git_sha='HEAD',
210
+ cfl_platform='github',
211
+ base_commit='HEAD^1')
212
+ self.assertTrue(build_fuzzers.build_fuzzers(config))
213
+ self.assertTrue(
214
+ os.path.exists(os.path.join(self.out_dir, EXAMPLE_BUILD_FUZZER)))
215
+
216
+ def test_external_generic_project(self):
217
+ """Tests building fuzzers from an external project not on Github."""
218
+ project_repo_name = 'cifuzz-external-example'
219
+ git_url = 'https://github.com/jonathanmetzman/cifuzz-external-example.git'
220
+ # This test is dependant on the state of
221
+ # github.com/jonathanmetzman/cifuzz-external-example.
222
+ manager = repo_manager.clone_repo_and_get_manager(
223
+ 'https://github.com/jonathanmetzman/cifuzz-external-example',
224
+ self.workspace)
225
+ project_src_path = manager.repo_dir
226
+ config = test_helpers.create_build_config(
227
+ project_repo_name=project_repo_name,
228
+ workspace=self.workspace,
229
+ git_url=git_url,
230
+ filestore='no_filestore',
231
+ git_sha='HEAD',
232
+ project_src_path=project_src_path,
233
+ base_commit='HEAD^1')
234
+ self.assertTrue(build_fuzzers.build_fuzzers(config))
235
+ self.assertTrue(
236
+ os.path.exists(os.path.join(self.out_dir, EXAMPLE_BUILD_FUZZER)))
237
+
238
+ def test_valid_commit(self):
239
+ """Tests building fuzzers with valid inputs."""
240
+ config = test_helpers.create_build_config(
241
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
242
+ project_repo_name='oss-fuzz',
243
+ workspace=self.workspace,
244
+ git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523',
245
+ base_commit='da0746452433dc18bae699e355a9821285d863c8',
246
+ cfl_platform='github')
247
+ self.assertTrue(build_fuzzers.build_fuzzers(config))
248
+ self.assertTrue(
249
+ os.path.exists(os.path.join(self.out_dir, EXAMPLE_BUILD_FUZZER)))
250
+
251
+ def test_valid_pull_request(self):
252
+ """Tests building fuzzers with valid pull request."""
253
+ config = test_helpers.create_build_config(
254
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
255
+ project_repo_name='oss-fuzz',
256
+ workspace=self.workspace,
257
+ pr_ref='refs/pull/1757/merge',
258
+ base_ref='master',
259
+ cfl_platform='github')
260
+ self.assertTrue(build_fuzzers.build_fuzzers(config))
261
+ self.assertTrue(
262
+ os.path.exists(os.path.join(self.out_dir, EXAMPLE_BUILD_FUZZER)))
263
+
264
+ def test_invalid_pull_request(self):
265
+ """Tests building fuzzers with invalid pull request."""
266
+ config = test_helpers.create_build_config(
267
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
268
+ project_repo_name='oss-fuzz',
269
+ workspace=self.workspace,
270
+ pr_ref='ref-1/merge',
271
+ base_ref='master',
272
+ cfl_platform='github')
273
+ self.assertTrue(build_fuzzers.build_fuzzers(config))
274
+
275
+ def test_invalid_oss_fuzz_project_name(self):
276
+ """Tests building fuzzers with invalid project name."""
277
+ config = test_helpers.create_build_config(
278
+ oss_fuzz_project_name='not_a_valid_project',
279
+ project_repo_name='oss-fuzz',
280
+ workspace=self.workspace,
281
+ git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')
282
+ self.assertFalse(build_fuzzers.build_fuzzers(config))
283
+
284
+ def test_invalid_repo_name(self):
285
+ """Tests building fuzzers with invalid repo name."""
286
+ config = test_helpers.create_build_config(
287
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
288
+ project_repo_name='not-real-repo',
289
+ workspace=self.workspace,
290
+ git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')
291
+ self.assertFalse(build_fuzzers.build_fuzzers(config))
292
+
293
+ def test_invalid_git_sha(self):
294
+ """Tests building fuzzers with invalid commit SHA."""
295
+ config = test_helpers.create_build_config(
296
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
297
+ project_repo_name='oss-fuzz',
298
+ workspace=self.workspace,
299
+ git_sha='',
300
+ cfl_platform='github')
301
+ with self.assertRaises(AssertionError):
302
+ build_fuzzers.build_fuzzers(config)
303
+
304
+ def test_invalid_workspace(self):
305
+ """Tests building fuzzers with invalid workspace."""
306
+ config = test_helpers.create_build_config(
307
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
308
+ project_repo_name='oss-fuzz',
309
+ workspace=os.path.join(self.workspace, 'not', 'a', 'dir'),
310
+ git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')
311
+ self.assertFalse(build_fuzzers.build_fuzzers(config))
312
+
313
+
314
+ class CheckFuzzerBuildTest(unittest.TestCase):
315
+ """Tests the check_fuzzer_build function in the cifuzz module."""
316
+
317
+ SANITIZER = 'address'
318
+ LANGUAGE = 'c++'
319
+
320
+ def setUp(self):
321
+ self.temp_dir_obj = tempfile.TemporaryDirectory()
322
+ workspace_path = os.path.join(self.temp_dir_obj.name, 'workspace')
323
+ self.config = test_helpers.create_build_config(
324
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
325
+ sanitizer=self.SANITIZER,
326
+ language=self.LANGUAGE,
327
+ workspace=workspace_path,
328
+ pr_ref='refs/pull/1757/merge')
329
+ self.workspace = test_helpers.create_workspace(workspace_path)
330
+ shutil.copytree(TEST_DATA_PATH, workspace_path)
331
+ test_helpers.patch_environ(self, runner=True)
332
+
333
+ def tearDown(self):
334
+ self.temp_dir_obj.cleanup()
335
+
336
+ def test_correct_fuzzer_build(self):
337
+ """Checks check_fuzzer_build function returns True for valid fuzzers."""
338
+ self.assertTrue(build_fuzzers.check_fuzzer_build(self.config))
339
+
340
+ def test_not_a_valid_path(self):
341
+ """Tests that False is returned when a nonexistent path is given."""
342
+ self.config.workspace = 'not/a/valid/path'
343
+ self.assertFalse(build_fuzzers.check_fuzzer_build(self.config))
344
+
345
+ def test_no_valid_fuzzers(self):
346
+ """Tests that False is returned when an empty directory is given."""
347
+ with tempfile.TemporaryDirectory() as tmp_dir:
348
+ self.config.workspace = tmp_dir
349
+ os.mkdir(os.path.join(self.config.workspace, 'build-out'))
350
+ self.assertFalse(build_fuzzers.check_fuzzer_build(self.config))
351
+
352
+ @mock.patch('utils.execute', return_value=(None, None, 0))
353
+ def test_allow_broken_fuzz_targets_percentage(self, mock_execute):
354
+ """Tests that ALLOWED_BROKEN_TARGETS_PERCENTAGE is set when running
355
+ docker if passed to check_fuzzer_build."""
356
+ percentage = '0'
357
+ self.config.allowed_broken_targets_percentage = percentage
358
+ build_fuzzers.check_fuzzer_build(self.config)
359
+ self.assertEqual(
360
+ mock_execute.call_args[1]['env']['ALLOWED_BROKEN_TARGETS_PERCENTAGE'],
361
+ percentage)
362
+
363
+
364
+ @unittest.skip('Test is too long to be run with presubmit.')
365
+ class BuildSantizerIntegrationTest(unittest.TestCase):
366
+ """Integration tests for the build_fuzzers.
367
+ Note: This test relies on "curl" being an OSS-Fuzz project."""
368
+ PROJECT_NAME = 'curl'
369
+ PR_REF = 'fake_pr'
370
+
371
+ @classmethod
372
+ def _create_config(cls, tmp_dir, sanitizer):
373
+ return test_helpers.create_build_config(
374
+ oss_fuzz_project_name=cls.PROJECT_NAME,
375
+ project_repo_name=cls.PROJECT_NAME,
376
+ workspace=tmp_dir,
377
+ pr_ref=cls.PR_REF,
378
+ sanitizer=sanitizer)
379
+
380
+ @parameterized.parameterized.expand([('memory',), ('undefined',)])
381
+ def test_valid_project_curl(self, sanitizer):
382
+ """Tests that MSAN can be detected from project.yaml"""
383
+ with tempfile.TemporaryDirectory() as tmp_dir:
384
+ self.assertTrue(
385
+ build_fuzzers.build_fuzzers(self._create_config(tmp_dir, sanitizer)))
386
+
387
+
388
+ class GetDockerBuildFuzzersArgsNotContainerTest(unittest.TestCase):
389
+ """Tests that _get_docker_build_fuzzers_args_not_container works as
390
+ intended."""
391
+
392
+ def test_get_docker_build_fuzzers_args_no_container(self):
393
+ """Tests that _get_docker_build_fuzzers_args_not_container works
394
+ as intended."""
395
+ host_repo_path = '/host/repo'
396
+ result = build_fuzzers._get_docker_build_fuzzers_args_not_container(
397
+ host_repo_path)
398
+ expected_result = ['-v', '/host/repo:/host/repo']
399
+ self.assertEqual(result, expected_result)
400
+
401
+
402
+ if __name__ == '__main__':
403
+ unittest.main()
local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/cloudbuild.yaml ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TODO(metzman): Get rid of cifuzz-build-fuzzers and cifuzz-run-fuzzers.
2
+ steps:
3
+ - name: 'gcr.io/cloud-builders/docker'
4
+ args:
5
+ - build
6
+ - '-t'
7
+ - ghcr.io/aixcc-finals/cifuzz-base
8
+ - '-t'
9
+ - ghcr.io/aixcc-finals/cifuzz-base:v1
10
+ - '-f'
11
+ - infra/cifuzz/cifuzz-base/Dockerfile
12
+ - .
13
+ - name: 'gcr.io/cloud-builders/docker'
14
+ args:
15
+ - build
16
+ - '-t'
17
+ - ghcr.io/aixcc-finals/cifuzz-build-fuzzers
18
+ - '-t'
19
+ - ghcr.io/aixcc-finals/cifuzz-build-fuzzers:v1
20
+ - '-t'
21
+ - ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers
22
+ - '-t'
23
+ - ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers:v1
24
+ - '-f'
25
+ - infra/build_fuzzers.Dockerfile
26
+ - infra
27
+ - name: 'gcr.io/cloud-builders/docker'
28
+ args:
29
+ - build
30
+ - '-t'
31
+ - ghcr.io/aixcc-finals/cifuzz-run-fuzzers
32
+ - '-t'
33
+ - ghcr.io/aixcc-finals/cifuzz-run-fuzzers:v1
34
+ - '-t'
35
+ - ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers
36
+ - '-t'
37
+ - ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers:v1
38
+ - '-f'
39
+ - infra/run_fuzzers.Dockerfile
40
+ - infra
41
+ images:
42
+ - ghcr.io/aixcc-finals/cifuzz-base
43
+ - ghcr.io/aixcc-finals/cifuzz-base:v1
44
+ - ghcr.io/aixcc-finals/cifuzz-run-fuzzers
45
+ - ghcr.io/aixcc-finals/cifuzz-run-fuzzers:v1
46
+ - ghcr.io/aixcc-finals/cifuzz-build-fuzzers
47
+ - ghcr.io/aixcc-finals/cifuzz-build-fuzzers:v1
48
+ - ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers
49
+ - ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers:v1
50
+ - ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers
51
+ - ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers:v1
52
+ timeout: 1800s
local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment_test.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests for clusterfuzz_deployment.py"""
15
+
16
+ import os
17
+ import unittest
18
+ from unittest import mock
19
+
20
+ import parameterized
21
+ from pyfakefs import fake_filesystem_unittest
22
+
23
+ import clusterfuzz_deployment
24
+ import config_utils
25
+ import test_helpers
26
+ import workspace_utils
27
+
28
+ # NOTE: This integration test relies on
29
+ # https://github.com/google/oss-fuzz/tree/master/projects/example project.
30
+ EXAMPLE_PROJECT = 'example'
31
+
32
+ # An example fuzzer that triggers an error.
33
+ EXAMPLE_FUZZER = 'example_crash_fuzzer'
34
+
35
+ WORKSPACE = '/workspace'
36
+ EXPECTED_LATEST_BUILD_PATH = os.path.join(WORKSPACE, 'cifuzz-prev-build')
37
+
38
+ # pylint: disable=unused-argument
39
+
40
+
41
+ def _create_config(**kwargs):
42
+ """Creates a config object and then sets every attribute that is a key in
43
+ |kwargs| to the corresponding value. Asserts that each key in |kwargs| is an
44
+ attribute of Config."""
45
+ defaults = {
46
+ 'cfl_platform': 'github',
47
+ 'oss_fuzz_project_name': EXAMPLE_PROJECT,
48
+ 'workspace': WORKSPACE,
49
+ }
50
+ for default_key, default_value in defaults.items():
51
+ if default_key not in kwargs:
52
+ kwargs[default_key] = default_value
53
+
54
+ return test_helpers.create_run_config(**kwargs)
55
+
56
+
57
+ def _create_deployment(**kwargs):
58
+ config = _create_config(**kwargs)
59
+ workspace = workspace_utils.Workspace(config)
60
+ return clusterfuzz_deployment.get_clusterfuzz_deployment(config, workspace)
61
+
62
+
63
+ class OSSFuzzTest(fake_filesystem_unittest.TestCase):
64
+ """Tests OSSFuzz."""
65
+
66
+ def setUp(self):
67
+ self.setUpPyfakefs()
68
+ self.deployment = _create_deployment()
69
+ self.corpus_dir = os.path.join(self.deployment.workspace.corpora,
70
+ EXAMPLE_FUZZER)
71
+
72
+ @mock.patch('http_utils.download_and_unpack_zip', return_value=True)
73
+ def test_download_corpus(self, mock_download_and_unpack_zip):
74
+ """Tests that we can download a corpus for a valid project."""
75
+ self.deployment.download_corpus(EXAMPLE_FUZZER, self.corpus_dir)
76
+ expected_url = ('https://storage.googleapis.com/example-backup.'
77
+ 'clusterfuzz-external.appspot.com/corpus/libFuzzer/'
78
+ 'example_crash_fuzzer/public.zip')
79
+ call_args, _ = mock_download_and_unpack_zip.call_args
80
+ self.assertEqual(call_args, (expected_url, self.corpus_dir))
81
+ self.assertTrue(os.path.exists(self.corpus_dir))
82
+
83
+ @mock.patch('http_utils.download_and_unpack_zip', return_value=False)
84
+ def test_download_corpus_fail(self, _):
85
+ """Tests that when downloading fails, an empty corpus directory is still
86
+ returned."""
87
+ self.deployment.download_corpus(EXAMPLE_FUZZER, self.corpus_dir)
88
+ self.assertEqual(os.listdir(self.corpus_dir), [])
89
+
90
+ def test_get_latest_build_name(self):
91
+ """Tests that the latest build name can be retrieved from GCS."""
92
+ latest_build_name = self.deployment.get_latest_build_name()
93
+ self.assertTrue(latest_build_name.endswith('.zip'))
94
+ self.assertTrue('address' in latest_build_name)
95
+
96
+ @parameterized.parameterized.expand([
97
+ ('upload_build', ('commit',),
98
+ 'Not uploading latest build because on OSS-Fuzz.'),
99
+ ('upload_corpus', ('target', 'corpus-dir'),
100
+ 'Not uploading corpus because on OSS-Fuzz.'),
101
+ ('upload_crashes', tuple(), 'Not uploading crashes because on OSS-Fuzz.'),
102
+ ])
103
+ def test_noop_methods(self, method, method_args, expected_message):
104
+ """Tests that certain methods are noops for OSS-Fuzz."""
105
+ with mock.patch('logging.info') as mock_info:
106
+ method = getattr(self.deployment, method)
107
+ self.assertIsNone(method(*method_args))
108
+ mock_info.assert_called_with(expected_message)
109
+
110
+ @mock.patch('http_utils.download_and_unpack_zip', return_value=True)
111
+ def test_download_latest_build(self, mock_download_and_unpack_zip):
112
+ """Tests that downloading the latest build works as intended under normal
113
+ circumstances."""
114
+ self.assertEqual(self.deployment.download_latest_build(),
115
+ EXPECTED_LATEST_BUILD_PATH)
116
+ expected_url = ('https://storage.googleapis.com/clusterfuzz-builds/example/'
117
+ 'example-address-202008030600.zip')
118
+ mock_download_and_unpack_zip.assert_called_with(expected_url,
119
+ EXPECTED_LATEST_BUILD_PATH)
120
+
121
+ @mock.patch('http_utils.download_and_unpack_zip', return_value=False)
122
+ def test_download_latest_build_fail(self, _):
123
+ """Tests that download_latest_build returns None when it fails to download a
124
+ build."""
125
+ self.assertIsNone(self.deployment.download_latest_build())
126
+
127
+
128
+ class ClusterFuzzLiteTest(fake_filesystem_unittest.TestCase):
129
+ """Tests for ClusterFuzzLite."""
130
+
131
+ def setUp(self):
132
+ self.setUpPyfakefs()
133
+ self.deployment = _create_deployment(mode='batch',
134
+ oss_fuzz_project_name='',
135
+ cloud_bucket='gs://bucket')
136
+ self.corpus_dir = os.path.join(self.deployment.workspace.corpora,
137
+ EXAMPLE_FUZZER)
138
+
139
+ @mock.patch('filestore.github_actions.GithubActionsFilestore.download_corpus',
140
+ return_value=True)
141
+ def test_download_corpus(self, mock_download_corpus):
142
+ """Tests that download_corpus works for a valid project."""
143
+ self.deployment.download_corpus(EXAMPLE_FUZZER, self.corpus_dir)
144
+ mock_download_corpus.assert_called_with('example_crash_fuzzer',
145
+ self.corpus_dir)
146
+ self.assertTrue(os.path.exists(self.corpus_dir))
147
+
148
+ @mock.patch('filestore.github_actions.GithubActionsFilestore.download_corpus',
149
+ side_effect=Exception)
150
+ def test_download_corpus_fail(self, _):
151
+ """Tests that when downloading fails, an empty corpus directory is still
152
+ returned."""
153
+ self.deployment.download_corpus(EXAMPLE_FUZZER, self.corpus_dir)
154
+ self.assertEqual(os.listdir(self.corpus_dir), [])
155
+
156
+ @mock.patch('filestore.github_actions.GithubActionsFilestore.download_build',
157
+ side_effect=[False, True])
158
+ @mock.patch('repo_manager.RepoManager.get_commit_list',
159
+ return_value=['commit1', 'commit2'])
160
+ @mock.patch('continuous_integration.GithubCiMixin.repo_dir',
161
+ return_value='/path/to/repo')
162
+ def test_download_latest_build(self, mock_repo_dir, mock_get_commit_list,
163
+ mock_download_build):
164
+ """Tests that downloading the latest build works as intended under normal
165
+ circumstances."""
166
+ self.assertEqual(self.deployment.download_latest_build(),
167
+ EXPECTED_LATEST_BUILD_PATH)
168
+ expected_artifact_name = 'address-commit2'
169
+ mock_download_build.assert_called_with(expected_artifact_name,
170
+ EXPECTED_LATEST_BUILD_PATH)
171
+
172
+ @mock.patch('filestore.github_actions.GithubActionsFilestore.download_build',
173
+ side_effect=Exception)
174
+ @mock.patch('repo_manager.RepoManager.get_commit_list',
175
+ return_value=['commit1', 'commit2'])
176
+ @mock.patch('continuous_integration.GithubCiMixin.repo_dir',
177
+ return_value='/path/to/repo')
178
+ def test_download_latest_build_fail(self, mock_repo_dir, mock_get_commit_list,
179
+ _):
180
+ """Tests that download_latest_build returns None when it fails to download a
181
+ build."""
182
+ self.assertIsNone(self.deployment.download_latest_build())
183
+
184
+ @mock.patch('filestore.github_actions.GithubActionsFilestore.upload_build')
185
+ def test_upload_build(self, mock_upload_build):
186
+ """Tests that upload_build works as intended."""
187
+ self.deployment.upload_build('commit')
188
+ mock_upload_build.assert_called_with('address-commit',
189
+ '/workspace/build-out')
190
+
191
+
192
+ class NoClusterFuzzDeploymentTest(fake_filesystem_unittest.TestCase):
193
+ """Tests for NoClusterFuzzDeployment."""
194
+
195
+ def setUp(self):
196
+ self.setUpPyfakefs()
197
+ config = test_helpers.create_run_config(workspace=WORKSPACE,
198
+ cfl_platform='other',
199
+ filestore='no_filestore',
200
+ no_clusterfuzz_deployment=True)
201
+ workspace = workspace_utils.Workspace(config)
202
+ self.deployment = clusterfuzz_deployment.get_clusterfuzz_deployment(
203
+ config, workspace)
204
+
205
+ self.corpus_dir = os.path.join(workspace.corpora, EXAMPLE_FUZZER)
206
+
207
+ @mock.patch('logging.info')
208
+ def test_download_corpus(self, mock_info):
209
+ """Tests that download corpus returns the path to the empty corpus
210
+ directory."""
211
+ self.deployment.download_corpus(EXAMPLE_FUZZER, self.corpus_dir)
212
+ mock_info.assert_called_with(
213
+ 'Not downloading corpus because no ClusterFuzz deployment.')
214
+ self.assertTrue(os.path.exists(self.corpus_dir))
215
+
216
+ @parameterized.parameterized.expand([
217
+ ('upload_build', ('commit',),
218
+ 'Not uploading latest build because no ClusterFuzz deployment.'),
219
+ ('upload_corpus', ('target', 'corpus-dir'),
220
+ 'Not uploading corpus because no ClusterFuzz deployment.'),
221
+ ('upload_crashes', tuple(),
222
+ 'Not uploading crashes because no ClusterFuzz deployment.'),
223
+ ('download_latest_build', tuple(),
224
+ 'Not downloading latest build because no ClusterFuzz deployment.')
225
+ ])
226
+ def test_noop_methods(self, method, method_args, expected_message):
227
+ """Tests that certain methods are noops for NoClusterFuzzDeployment."""
228
+ with mock.patch('logging.info') as mock_info:
229
+ method = getattr(self.deployment, method)
230
+ self.assertIsNone(method(*method_args))
231
+ mock_info.assert_called_with(expected_message)
232
+
233
+
234
+ class GetClusterFuzzDeploymentTest(unittest.TestCase):
235
+ """Tests for get_clusterfuzz_deployment."""
236
+
237
+ def setUp(self):
238
+ test_helpers.patch_environ(self)
239
+ os.environ['GITHUB_REPOSITORY'] = 'owner/myproject'
240
+
241
+ @parameterized.parameterized.expand([
242
+ (config_utils.BaseConfig.Platform.INTERNAL_GENERIC_CI,
243
+ clusterfuzz_deployment.OSSFuzz),
244
+ (config_utils.BaseConfig.Platform.INTERNAL_GITHUB,
245
+ clusterfuzz_deployment.OSSFuzz),
246
+ (config_utils.BaseConfig.Platform.EXTERNAL_GENERIC_CI,
247
+ clusterfuzz_deployment.ClusterFuzzLite),
248
+ (config_utils.BaseConfig.Platform.EXTERNAL_GITHUB,
249
+ clusterfuzz_deployment.ClusterFuzzLite),
250
+ ])
251
+ def test_get_clusterfuzz_deployment(self, platform, expected_deployment_cls):
252
+ """Tests that get_clusterfuzz_deployment returns the correct value."""
253
+ with mock.patch('config_utils.BaseConfig.platform',
254
+ return_value=platform,
255
+ new_callable=mock.PropertyMock):
256
+ with mock.patch('filestore_utils.get_filestore', return_value=None):
257
+ with mock.patch('platform_config.github._get_event_data',
258
+ return_value={}):
259
+ config = _create_config()
260
+ workspace = workspace_utils.Workspace(config)
261
+
262
+ self.assertIsInstance(
263
+ clusterfuzz_deployment.get_clusterfuzz_deployment(
264
+ config, workspace), expected_deployment_cls)
265
+
266
+
267
+ if __name__ == '__main__':
268
+ unittest.main()
local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/config_utils_test.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests for config_utils."""
15
+ import os
16
+ import unittest
17
+ from unittest import mock
18
+
19
+ import config_utils
20
+ import constants
21
+ import test_helpers
22
+
23
+ # pylint: disable=no-self-use,protected-access
24
+
25
+
26
+ class BaseConfigTest(unittest.TestCase):
27
+ """Tests for BaseConfig."""
28
+
29
+ def setUp(self):
30
+ test_helpers.patch_environ(self)
31
+
32
+ def _create_config(self):
33
+ return config_utils.BuildFuzzersConfig()
34
+
35
+ def test_language_default(self):
36
+ """Tests that the correct default language is set."""
37
+ config = self._create_config()
38
+ self.assertEqual(config.language, 'c++')
39
+
40
+ def test_language(self):
41
+ """Tests that the correct language is set."""
42
+ language = 'python'
43
+ os.environ['LANGUAGE'] = language
44
+ config = self._create_config()
45
+ self.assertEqual(config.language, language)
46
+
47
+ def test_is_coverage(self):
48
+ """Tests that is_coverage is set correctly."""
49
+ # Test it is set when it is supposed to be.
50
+ os.environ['SANITIZER'] = 'coverage'
51
+ config = self._create_config()
52
+ self.assertTrue(config.is_coverage)
53
+
54
+ # Test it is not set when it is not supposed to be.
55
+ os.environ['SANITIZER'] = 'address'
56
+ config = self._create_config()
57
+ self.assertFalse(config.is_coverage)
58
+
59
+ @mock.patch('logging.error')
60
+ def test_validate_no_workspace(self, mock_error):
61
+ """Tests that validate returns False if GITHUB_WORKSPACE isn't set."""
62
+ os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example'
63
+ config = self._create_config()
64
+ self.assertFalse(config.validate())
65
+ mock_error.assert_called_with('Must set WORKSPACE.')
66
+
67
+ @mock.patch('logging.error')
68
+ def test_validate_invalid_language(self, mock_error):
69
+ """Tests that validate returns False if GITHUB_WORKSPACE isn't set."""
70
+ os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example'
71
+ os.environ['WORKSPACE'] = '/workspace'
72
+ os.environ['LANGUAGE'] = 'invalid-language'
73
+ config = self._create_config()
74
+ self.assertFalse(config.validate())
75
+ mock_error.assert_called_with('Invalid LANGUAGE: %s. Must be one of: %s.',
76
+ os.environ['LANGUAGE'], constants.LANGUAGES)
77
+
78
+ @mock.patch('logging.error')
79
+ def test_validate_invalid_sanitizer(self, mock_error):
80
+ """Tests that validate returns False if GITHUB_WORKSPACE isn't set."""
81
+ os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example'
82
+ os.environ['WORKSPACE'] = '/workspace'
83
+ os.environ['SANITIZER'] = 'invalid-sanitizer'
84
+ config = self._create_config()
85
+ self.assertFalse(config.validate())
86
+ mock_error.assert_called_with('Invalid SANITIZER: %s. Must be one of: %s.',
87
+ os.environ['SANITIZER'],
88
+ config_utils.SANITIZERS)
89
+
90
+ def test_validate(self):
91
+ """Tests that validate returns True if config is valid."""
92
+ os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example'
93
+ os.environ['WORKSPACE'] = '/workspace'
94
+ os.environ['REPOSITORY'] = 'repo'
95
+ config = self._create_config()
96
+ self.assertTrue(config.validate())
97
+
98
+
99
+ class BuildFuzzersConfigTest(unittest.TestCase):
100
+ """Tests for BuildFuzzersConfig."""
101
+
102
+ def setUp(self):
103
+ test_helpers.patch_environ(self)
104
+
105
+ def _create_config(self):
106
+ return config_utils.BuildFuzzersConfig()
107
+
108
+ @mock.patch('platform_config.github._get_event_data', return_value={})
109
+ def test_github_base_ref(self, _):
110
+ """Tests that base_ref is set properly."""
111
+ expected_base_ref = 'expected_base_ref'
112
+ os.environ['GITHUB_BASE_REF'] = expected_base_ref
113
+ os.environ['CFL_PLATFORM'] = 'github'
114
+ os.environ['GITHUB_REPOSITORY'] = 'owner/repo'
115
+ config = self._create_config()
116
+ self.assertEqual(config.base_ref, expected_base_ref)
117
+
118
+ def test_base_ref(self):
119
+ """Tests that base_ref is set properly."""
120
+ expected_base_ref = 'expected_base_ref'
121
+ os.environ['GIT_BASE_REF'] = expected_base_ref
122
+ config = self._create_config()
123
+ self.assertEqual(config.base_ref, expected_base_ref)
124
+
125
+ def test_keep_unaffected_defaults_to_true(self):
126
+ """Tests that keep_unaffected_fuzz_targets defaults to true."""
127
+ config = self._create_config()
128
+ self.assertTrue(config.keep_unaffected_fuzz_targets)
129
+
130
+ def test_keep_unaffected_defaults_to_false_when_pr(self):
131
+ """Tests that keep_unaffected_fuzz_targets defaults to false when from a
132
+ pr."""
133
+ os.environ['GIT_BASE_REF'] = 'base-ref'
134
+ config = self._create_config()
135
+ self.assertFalse(config.keep_unaffected_fuzz_targets)
136
+
137
+
138
+ class RunFuzzersConfigTest(unittest.TestCase):
139
+ """Tests for RunFuzzersConfig."""
140
+
141
+ def setUp(self):
142
+ test_helpers.patch_environ(self)
143
+
144
+ def _create_config(self):
145
+ return config_utils.RunFuzzersConfig()
146
+
147
+ def test_coverage(self):
148
+ """Tests that mode is overriden properly based on is_coverage."""
149
+ # Test that it is overriden when it is supposed to be.
150
+ os.environ['SANITIZER'] = 'coverage'
151
+ os.environ['MODE'] = 'code-change'
152
+ config = self._create_config()
153
+ self.assertEqual(config.mode, 'coverage')
154
+
155
+ # Test that it isn't overriden when it isn't supposed to be.
156
+ os.environ['SANITIZER'] = 'address'
157
+ mode = 'code-change'
158
+ os.environ['MODE'] = mode
159
+ config = self._create_config()
160
+ self.assertEqual(config.mode, mode)
161
+
162
+ def test_run_config_validate(self):
163
+ """Tests that _run_config_validate returns True when the config is valid."""
164
+ self.assertTrue(self._create_config()._run_config_validate())
165
+
166
+ @mock.patch('logging.error')
167
+ def test_run_config_invalid_mode(self, mock_error):
168
+ """Tests that _run_config_validate returns False when mode is invalid."""
169
+ fake_mode = 'fake-mode'
170
+ os.environ['MODE'] = fake_mode
171
+ self.assertFalse(self._create_config()._run_config_validate())
172
+ mock_error.assert_called_with('Invalid MODE: %s. Must be one of %s.',
173
+ fake_mode,
174
+ config_utils.RunFuzzersConfig.MODES)
175
+
176
+
177
+ class GetSanitizerTest(unittest.TestCase):
178
+ """Tests for _get_sanitizer."""
179
+
180
+ def setUp(self):
181
+ test_helpers.patch_environ(self)
182
+ self.sanitizer = 'memory'
183
+
184
+ def test_default_value(self):
185
+ """Tests that the default value returned by _get_sanitizer is correct."""
186
+ self.assertEqual(config_utils._get_sanitizer(), 'address')
187
+
188
+ def test_normal_case(self):
189
+ """Tests that _get_sanitizer returns the correct value in normal cases."""
190
+ os.environ['SANITIZER'] = self.sanitizer
191
+ self.assertEqual(config_utils._get_sanitizer(), self.sanitizer)
192
+
193
+ def test_capitalization(self):
194
+ """Tests that that _get_sanitizer handles capitalization properly."""
195
+ os.environ['SANITIZER'] = self.sanitizer.upper()
196
+ self.assertEqual(config_utils._get_sanitizer(), self.sanitizer)
197
+
198
+
199
+ if __name__ == '__main__':
200
+ unittest.main()
local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/environment.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Module for dealing with env vars."""
15
+
16
+ import ast
17
+ import os
18
+
19
+
20
+ def _eval_value(value_string):
21
+ """Returns evaluated value."""
22
+ try:
23
+ return ast.literal_eval(value_string)
24
+ except: # pylint: disable=bare-except
25
+ # String fallback.
26
+ return value_string
27
+
28
+
29
+ def get(env_var, default_value=None):
30
+ """Returns an environment variable value."""
31
+ value_string = os.getenv(env_var)
32
+ if value_string is None:
33
+ return default_value
34
+
35
+ return _eval_value(value_string)
36
+
37
+
38
+ def get_bool(env_var, default_value=None):
39
+ """Returns a boolean environment variable value. This is needed because a lot
40
+ of CIFuzz users specified 'false' for dry-run. So we need to special case
41
+ this."""
42
+ value = get(env_var, default_value)
43
+ if not isinstance(value, str):
44
+ return bool(value)
45
+
46
+ lower_value = value.lower()
47
+ allowed_values = {'true', 'false'}
48
+ if lower_value not in allowed_values:
49
+ raise Exception(f'Bool env var {env_var} value {value} is invalid. '
50
+ f'Must be one of {allowed_values}.')
51
+ return lower_value == 'true'
local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/example_cifuzz.yml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: CIFuzz
2
+ on: [pull_request]
3
+ permissions: {}
4
+ jobs:
5
+ Fuzzing:
6
+ runs-on: ubuntu-latest
7
+ permissions:
8
+ security-events: write
9
+ steps:
10
+ - name: Build Fuzzers
11
+ id: build
12
+ uses: google/oss-fuzz/infra/cifuzz/actions/build_fuzzers@master
13
+ with:
14
+ oss-fuzz-project-name: 'example'
15
+ - name: Run Fuzzers
16
+ uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@master
17
+ with:
18
+ oss-fuzz-project-name: 'example'
19
+ fuzz-seconds: 600
20
+ output-sarif: true
21
+ - name: Upload Crash
22
+ uses: actions/upload-artifact@v3
23
+ if: failure() && steps.build.outcome == 'success'
24
+ with:
25
+ name: artifacts
26
+ path: ./out/artifacts
27
+ - name: Upload Sarif
28
+ if: always() && steps.build.outcome == 'success'
29
+ uses: github/codeql-action/upload-sarif@v2
30
+ with:
31
+ # Path to SARIF file relative to the root of the repository
32
+ sarif_file: cifuzz-sarif/results.sarif
33
+ checkout_path: cifuzz-sarif
local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/filestore_utils_test.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests for filestore_utils."""
15
+ import unittest
16
+ from unittest import mock
17
+
18
+ import parameterized
19
+
20
+ import platform_config
21
+ import filestore
22
+ from filestore import github_actions
23
+ import filestore_utils
24
+ import test_helpers
25
+
26
+
27
+ class GetFilestoreTest(unittest.TestCase):
28
+ """Tests for get_filestore."""
29
+
30
+ @parameterized.parameterized.expand([
31
+ ({
32
+ 'cfl_platform': 'github',
33
+ }, github_actions.GithubActionsFilestore),
34
+ ])
35
+ def test_get_filestore(self, config_kwargs, filestore_cls):
36
+ """Tests that get_filestore returns the right filestore given a certain
37
+ platform."""
38
+ run_config = test_helpers.create_run_config(**config_kwargs)
39
+ filestore_impl = filestore_utils.get_filestore(run_config)
40
+ self.assertIsInstance(filestore_impl, filestore_cls)
41
+
42
+ @mock.patch('config_utils.BaseConfig.platform', return_value='other')
43
+ @mock.patch('config_utils._get_platform_config',
44
+ return_value=platform_config.BasePlatformConfig())
45
+ def test_get_filestore_unsupported_platform(self, _, __):
46
+ """Tests that get_filestore exceptions given a platform it doesn't
47
+ support."""
48
+ run_config = test_helpers.create_run_config()
49
+ with self.assertRaises(filestore.FilestoreError):
50
+ filestore_utils.get_filestore(run_config)
local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/generate_coverage_report.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Module for generating coverage reports."""
15
+ import os
16
+
17
+ import base_runner_utils
18
+ import fuzz_target
19
+ import utils
20
+
21
+
22
+ def run_coverage_command(config, workspace):
23
+ """Runs the coverage command in base-runner to generate a coverage report."""
24
+ env = base_runner_utils.get_env(config, workspace)
25
+ env['HTTP_PORT'] = ''
26
+ env['COVERAGE_EXTRA_ARGS'] = ''
27
+ env['CORPUS_DIR'] = workspace.corpora
28
+ env['COVERAGE_OUTPUT_DIR'] = workspace.coverage_report
29
+ command = 'coverage'
30
+ return utils.execute(command, env=env)
31
+
32
+
33
+ def download_corpora(fuzz_target_paths, clusterfuzz_deployment):
34
+ """Downloads corpora for fuzz targets in |fuzz_target_paths| using
35
+ |clusterfuzz_deployment| to download corpora from ClusterFuzz/OSS-Fuzz."""
36
+ for target_path in fuzz_target_paths:
37
+ target_name = os.path.basename(target_path)
38
+ corpus_dir = fuzz_target.get_fuzz_target_corpus_dir(
39
+ clusterfuzz_deployment.workspace, target_name)
40
+ clusterfuzz_deployment.download_corpus(target_name, corpus_dir)
41
+
42
+
43
+ def generate_coverage_report(fuzz_target_paths, workspace,
44
+ clusterfuzz_deployment, config):
45
+ """Generates a coverage report using Clang's source based coverage."""
46
+ download_corpora(fuzz_target_paths, clusterfuzz_deployment)
47
+ run_coverage_command(config, workspace)
48
+ clusterfuzz_deployment.upload_coverage()
local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/generate_coverage_report_test.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests for generate_coverage_report."""
15
+
16
+ import unittest
17
+ from unittest import mock
18
+
19
+ import generate_coverage_report
20
+ import test_helpers
21
+
22
+ OUT_DIR = '/outdir'
23
+ PROJECT = 'example-project'
24
+ SANITIZER = 'coverage'
25
+
26
+
27
+ class TestRunCoverageCommand(unittest.TestCase):
28
+ """Tests run_coverage_command"""
29
+
30
+ def setUp(self):
31
+ test_helpers.patch_environ(self, empty=True)
32
+
33
+ @mock.patch('utils.execute')
34
+ def test_run_coverage_command(self, mock_execute): # pylint: disable=no-self-use
35
+ """Tests that run_coverage_command works as intended."""
36
+ config = test_helpers.create_run_config(oss_fuzz_project_name=PROJECT,
37
+ sanitizer=SANITIZER)
38
+ workspace = test_helpers.create_workspace()
39
+ generate_coverage_report.run_coverage_command(config, workspace)
40
+ expected_command = 'coverage'
41
+ expected_env = {
42
+ 'SANITIZER': config.sanitizer,
43
+ 'FUZZING_LANGUAGE': config.language,
44
+ 'OUT': workspace.out,
45
+ 'CIFUZZ': 'True',
46
+ 'FUZZING_ENGINE': 'libfuzzer',
47
+ 'ARCHITECTURE': 'x86_64',
48
+ 'FUZZER_ARGS': '-rss_limit_mb=2560 -timeout=25',
49
+ 'HTTP_PORT': '',
50
+ 'COVERAGE_EXTRA_ARGS': '',
51
+ 'CORPUS_DIR': workspace.corpora,
52
+ 'COVERAGE_OUTPUT_DIR': workspace.coverage_report
53
+ }
54
+ mock_execute.assert_called_with(expected_command, env=expected_env)
55
+
56
+
57
+ class DownloadCorporaTest(unittest.TestCase):
58
+ """Tests for download_corpora."""
59
+
60
+ def test_download_corpora(self): # pylint: disable=no-self-use
61
+ """Tests that download_corpora works as intended."""
62
+ clusterfuzz_deployment = mock.Mock()
63
+ clusterfuzz_deployment.workspace = test_helpers.create_workspace()
64
+ fuzz_target_paths = ['/path/to/fuzzer1', '/path/to/fuzzer2']
65
+ expected_calls = [
66
+ mock.call('fuzzer1', '/workspace/cifuzz-corpus/fuzzer1'),
67
+ mock.call('fuzzer2', '/workspace/cifuzz-corpus/fuzzer2')
68
+ ]
69
+ generate_coverage_report.download_corpora(fuzz_target_paths,
70
+ clusterfuzz_deployment)
71
+ clusterfuzz_deployment.download_corpus.assert_has_calls(expected_calls)
local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/get_coverage.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Module for determining coverage of fuzz targets."""
15
+ import json
16
+ import logging
17
+ import os
18
+ import sys
19
+
20
+ import http_utils
21
+
22
+ # pylint: disable=wrong-import-position,import-error
23
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
24
+ import utils
25
+
26
+ # The path to get OSS-Fuzz project's latest report json file.`
27
+ OSS_FUZZ_LATEST_COVERAGE_INFO_PATH = 'oss-fuzz-coverage/latest_report_info/'
28
+
29
+
30
+ # pylint: disable=too-few-public-methods
31
+ class CoverageError(Exception):
32
+ """Exceptions for project coverage."""
33
+
34
+
35
+ class BaseCoverage:
36
+ """Gets coverage data for a project."""
37
+
38
+ def __init__(self, repo_path):
39
+ self.repo_path = _normalize_repo_path(repo_path)
40
+
41
+ def get_files_covered_by_target(self, target):
42
+ """Returns a list of source files covered by the specific fuzz target.
43
+
44
+ Args:
45
+ target: The name of the fuzz target whose coverage is requested.
46
+
47
+ Returns:
48
+ A list of files that the fuzz target covers or None.
49
+ """
50
+ target_cov = self.get_target_coverage(target)
51
+ if not target_cov:
52
+ logging.info('No coverage available for %s.', target)
53
+ return None
54
+
55
+ coverage_per_file = get_coverage_per_file(target_cov)
56
+ if not coverage_per_file:
57
+ logging.info('No files found in coverage report.')
58
+ return None
59
+
60
+ affected_file_list = []
61
+ for file_cov in coverage_per_file:
62
+ norm_file_path = os.path.normpath(file_cov['filename'])
63
+ if not norm_file_path.startswith(self.repo_path):
64
+ # Exclude files outside of the main repo.
65
+ continue
66
+
67
+ if not is_file_covered(file_cov):
68
+ # Don't consider a file affected if code in it is never executed.
69
+ continue
70
+
71
+ # TODO(metzman): It's weird to me that we access file_cov['filename']
72
+ # again and not norm_file_path, figure out if this makes sense.
73
+ relative_path = utils.remove_prefix(file_cov['filename'], self.repo_path)
74
+ affected_file_list.append(relative_path)
75
+
76
+ return affected_file_list
77
+
78
+ def get_target_coverage(self, target):
79
+ """Get the coverage report for a specific fuzz target.
80
+
81
+ Args:
82
+ target: The name of the fuzz target whose coverage is requested.
83
+
84
+ Returns:
85
+ The target's coverage json dict or None on failure.
86
+ """
87
+ raise NotImplementedError('Child class must implement method.')
88
+
89
+
90
+ class OSSFuzzCoverage(BaseCoverage):
91
+ """Gets coverage data for a project from OSS-Fuzz."""
92
+
93
+ def __init__(self, repo_path, oss_fuzz_project_name):
94
+ """Constructor for OSSFuzzCoverage."""
95
+ super().__init__(repo_path)
96
+ self.oss_fuzz_project_name = oss_fuzz_project_name
97
+ self.fuzzer_stats_url = _get_oss_fuzz_fuzzer_stats_dir_url(
98
+ self.oss_fuzz_project_name)
99
+ if self.fuzzer_stats_url is None:
100
+ raise CoverageError('Could not get latest coverage.')
101
+
102
+ def get_target_coverage(self, target):
103
+ """Get the coverage report for a specific fuzz target.
104
+
105
+ Args:
106
+ target: The name of the fuzz target whose coverage is requested.
107
+
108
+ Returns:
109
+ The target's coverage json dict or None on failure.
110
+ """
111
+ if not self.fuzzer_stats_url:
112
+ return None
113
+
114
+ target_url = utils.url_join(self.fuzzer_stats_url, target + '.json')
115
+ return http_utils.get_json_from_url(target_url)
116
+
117
+
118
+ def _get_oss_fuzz_latest_cov_report_info(oss_fuzz_project_name):
119
+ """Gets and returns a dictionary containing the latest coverage report info
120
+ for |project|."""
121
+ latest_report_info_url = utils.url_join(utils.GCS_BASE_URL,
122
+ OSS_FUZZ_LATEST_COVERAGE_INFO_PATH,
123
+ oss_fuzz_project_name + '.json')
124
+ latest_cov_info = http_utils.get_json_from_url(latest_report_info_url)
125
+ if latest_cov_info is None:
126
+ logging.error('Could not get the coverage report json from url: %s.',
127
+ latest_report_info_url)
128
+ return None
129
+ return latest_cov_info
130
+
131
+
132
+ def _get_oss_fuzz_fuzzer_stats_dir_url(oss_fuzz_project_name):
133
+ """Gets latest coverage report info for a specific OSS-Fuzz project from
134
+ GCS.
135
+
136
+ Args:
137
+ oss_fuzz_project_name: The name of the project.
138
+
139
+ Returns:
140
+ The projects coverage report info in json dict or None on failure.
141
+ """
142
+ latest_cov_info = _get_oss_fuzz_latest_cov_report_info(oss_fuzz_project_name)
143
+
144
+ if not latest_cov_info:
145
+ return None
146
+
147
+ if 'fuzzer_stats_dir' not in latest_cov_info:
148
+ logging.error('fuzzer_stats_dir not in latest coverage info.')
149
+ return None
150
+
151
+ fuzzer_stats_dir_gs_url = latest_cov_info['fuzzer_stats_dir']
152
+ fuzzer_stats_dir_url = utils.gs_url_to_https(fuzzer_stats_dir_gs_url)
153
+ return fuzzer_stats_dir_url
154
+
155
+
156
+ class FilesystemCoverage(BaseCoverage):
157
+ """Class that gets a project's coverage from the filesystem."""
158
+
159
+ def __init__(self, repo_path, project_coverage_dir):
160
+ super().__init__(repo_path)
161
+ self.project_coverage_dir = project_coverage_dir
162
+
163
+ def get_target_coverage(self, target):
164
+ """Get the coverage report for a specific fuzz target.
165
+
166
+ Args:
167
+ target: The name of the fuzz target whose coverage is requested.
168
+
169
+ Returns:
170
+ The target's coverage json dict or None on failure.
171
+ """
172
+ logging.info('Getting coverage for %s from filesystem.', target)
173
+ fuzzer_stats_json_path = os.path.join(self.project_coverage_dir,
174
+ 'fuzzer_stats', target + '.json')
175
+ if not os.path.exists(fuzzer_stats_json_path):
176
+ logging.warning('%s does not exist.', fuzzer_stats_json_path)
177
+ return None
178
+
179
+ with open(fuzzer_stats_json_path) as fuzzer_stats_json_file_handle:
180
+ try:
181
+ return json.load(fuzzer_stats_json_file_handle)
182
+ except json.decoder.JSONDecodeError as err:
183
+ logging.error('Could not decode: %s. Error: %s.',
184
+ fuzzer_stats_json_path, err)
185
+ return None
186
+
187
+
188
+ def is_file_covered(file_cov):
189
+ """Returns whether the file is covered."""
190
+ return file_cov['summary']['regions']['covered']
191
+
192
+
193
+ def get_coverage_per_file(target_cov):
194
+ """Returns the coverage per file within |target_cov|."""
195
+ try:
196
+ return target_cov['data'][0]['files']
197
+ except (IndexError, TypeError, KeyError):
198
+ logging.error('target_cov: %s is malformed.', target_cov)
199
+ return None
200
+
201
+
202
+ def _normalize_repo_path(repo_path):
203
+ """Normalizes and returns |repo_path| to make sure cases like /src/curl and
204
+ /src/curl/ are both handled."""
205
+ repo_path = os.path.normpath(repo_path)
206
+ if not repo_path.endswith('/'):
207
+ repo_path += '/'
208
+ return repo_path
local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/get_coverage_test.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests for get_coverage.py"""
15
+ import os
16
+ import json
17
+ import unittest
18
+ from unittest import mock
19
+
20
+ import parameterized
21
+ from pyfakefs import fake_filesystem_unittest
22
+ import pytest
23
+
24
+ import get_coverage
25
+
26
+ # pylint: disable=protected-access
27
+
28
+ TEST_DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
29
+ 'test_data')
30
+
31
+ PROJECT_NAME = 'curl'
32
+ REPO_PATH = '/src/curl'
33
+ FUZZ_TARGET = 'curl_fuzzer'
34
+ PROJECT_COV_JSON_FILENAME = 'example_curl_cov.json'
35
+ FUZZ_TARGET_COV_JSON_FILENAME = 'example_curl_fuzzer_cov.json'
36
+ INVALID_TARGET = 'not-a-fuzz-target'
37
+
38
+ with open(os.path.join(TEST_DATA_PATH,
39
+ PROJECT_COV_JSON_FILENAME),) as cov_file_handle:
40
+ PROJECT_COV_INFO = json.loads(cov_file_handle.read())
41
+
42
+
43
+ class GetOssFuzzFuzzerStatsDirUrlTest(unittest.TestCase):
44
+ """Tests _get_oss_fuzz_fuzzer_stats_dir_url."""
45
+
46
+ @mock.patch('http_utils.get_json_from_url',
47
+ return_value={
48
+ 'fuzzer_stats_dir':
49
+ 'gs://oss-fuzz-coverage/systemd/fuzzer_stats/20210303'
50
+ })
51
+ def test_get_valid_project(self, mock_get_json_from_url):
52
+ """Tests that a project's coverage report can be downloaded and parsed.
53
+
54
+ NOTE: This test relies on the PROJECT_NAME repo's coverage report.
55
+ The "example" project was not used because it has no coverage reports.
56
+ """
57
+ result = get_coverage._get_oss_fuzz_fuzzer_stats_dir_url(PROJECT_NAME)
58
+ (url,), _ = mock_get_json_from_url.call_args
59
+ self.assertEqual(
60
+ 'https://storage.googleapis.com/oss-fuzz-coverage/'
61
+ 'latest_report_info/curl.json', url)
62
+
63
+ expected_result = (
64
+ 'https://storage.googleapis.com/oss-fuzz-coverage/systemd/fuzzer_stats/'
65
+ '20210303')
66
+ self.assertEqual(result, expected_result)
67
+
68
+ def test_get_invalid_project(self):
69
+ """Tests that passing a bad project returns None."""
70
+ self.assertIsNone(
71
+ get_coverage._get_oss_fuzz_fuzzer_stats_dir_url('not-a-proj'))
72
+
73
+
74
+ class OSSFuzzCoverageGetTargetCoverageTest(unittest.TestCase):
75
+ """Tests OSSFuzzCoverage.get_target_coverage."""
76
+
77
+ def setUp(self):
78
+ with mock.patch('get_coverage._get_oss_fuzz_latest_cov_report_info',
79
+ return_value=PROJECT_COV_INFO):
80
+ self.oss_fuzz_coverage = get_coverage.OSSFuzzCoverage(
81
+ REPO_PATH, PROJECT_NAME)
82
+
83
+ @mock.patch('http_utils.get_json_from_url', return_value={})
84
+ def test_valid_target(self, mock_get_json_from_url):
85
+ """Tests that a target's coverage report can be downloaded and parsed."""
86
+ self.oss_fuzz_coverage.get_target_coverage(FUZZ_TARGET)
87
+ (url,), _ = mock_get_json_from_url.call_args
88
+ self.assertEqual(
89
+ 'https://storage.googleapis.com/oss-fuzz-coverage/'
90
+ 'curl/fuzzer_stats/20200226/curl_fuzzer.json', url)
91
+
92
+ def test_invalid_target(self):
93
+ """Tests that passing an invalid target coverage report returns None."""
94
+ self.assertIsNone(
95
+ self.oss_fuzz_coverage.get_target_coverage(INVALID_TARGET))
96
+
97
+ @mock.patch('get_coverage._get_oss_fuzz_latest_cov_report_info',
98
+ return_value=None)
99
+ def test_invalid_project_json(self, _): # pylint: disable=no-self-use
100
+ """Tests an invalid project JSON results in None being returned."""
101
+ with pytest.raises(get_coverage.CoverageError):
102
+ get_coverage.OSSFuzzCoverage(REPO_PATH, PROJECT_NAME)
103
+
104
+
105
+ def _get_expected_curl_covered_file_list():
106
+ """Returns the expected covered file list for
107
+ FUZZ_TARGET_COV_JSON_FILENAME."""
108
+ curl_files_list_path = os.path.join(TEST_DATA_PATH,
109
+ 'example_curl_file_list.json')
110
+ with open(curl_files_list_path) as file_handle:
111
+ return json.loads(file_handle.read())
112
+
113
+
114
+ def _get_example_curl_coverage():
115
+ """Returns the contents of the fuzzer stats JSON file for
116
+ FUZZ_TARGET_COV_JSON_FILENAME."""
117
+ with open(os.path.join(TEST_DATA_PATH,
118
+ FUZZ_TARGET_COV_JSON_FILENAME)) as file_handle:
119
+ return json.loads(file_handle.read())
120
+
121
+
122
+ class OSSFuzzCoverageGetFilesCoveredByTargetTest(unittest.TestCase):
123
+ """Tests OSSFuzzCoverage.get_files_covered_by_target."""
124
+
125
+ def setUp(self):
126
+ with mock.patch('get_coverage._get_oss_fuzz_latest_cov_report_info',
127
+ return_value=PROJECT_COV_INFO):
128
+ self.oss_fuzz_coverage = get_coverage.OSSFuzzCoverage(
129
+ REPO_PATH, PROJECT_NAME)
130
+
131
+ @parameterized.parameterized.expand([({
132
+ 'data': []
133
+ },), ({
134
+ 'data': [[]]
135
+ },), ({
136
+ 'data': [{}]
137
+ },)])
138
+ def test_malformed_cov_data(self, coverage_data):
139
+ """Tests that covered files can be retrieved from a coverage report."""
140
+ with mock.patch('get_coverage.OSSFuzzCoverage.get_target_coverage',
141
+ return_value=coverage_data):
142
+ self.oss_fuzz_coverage.get_files_covered_by_target(FUZZ_TARGET)
143
+
144
+ def test_valid_target(self):
145
+ """Tests that covered files can be retrieved from a coverage report."""
146
+ fuzzer_cov_data = _get_example_curl_coverage()
147
+ with mock.patch('get_coverage.OSSFuzzCoverage.get_target_coverage',
148
+ return_value=fuzzer_cov_data):
149
+ file_list = self.oss_fuzz_coverage.get_files_covered_by_target(
150
+ FUZZ_TARGET)
151
+
152
+ expected_file_list = _get_expected_curl_covered_file_list()
153
+ self.assertCountEqual(file_list, expected_file_list)
154
+
155
+ def test_invalid_target(self):
156
+ """Tests passing invalid fuzz target returns None."""
157
+ self.assertIsNone(
158
+ self.oss_fuzz_coverage.get_files_covered_by_target(INVALID_TARGET))
159
+
160
+
161
+ class FilesystemCoverageGetFilesCoveredByTargetTest(
162
+ fake_filesystem_unittest.TestCase):
163
+ """Tests FilesystemCoverage.get_files_covered_by_target."""
164
+
165
+ def setUp(self):
166
+ _fuzzer_cov_data = _get_example_curl_coverage()
167
+ self._expected_file_list = _get_expected_curl_covered_file_list()
168
+ self.coverage_path = '/coverage'
169
+ self.filesystem_coverage = get_coverage.FilesystemCoverage(
170
+ REPO_PATH, self.coverage_path)
171
+ self.setUpPyfakefs()
172
+ self.fs.create_file(os.path.join(self.coverage_path, 'fuzzer_stats',
173
+ FUZZ_TARGET + '.json'),
174
+ contents=json.dumps(_fuzzer_cov_data))
175
+
176
+ def test_valid_target(self):
177
+ """Tests that covered files can be retrieved from a coverage report."""
178
+ file_list = self.filesystem_coverage.get_files_covered_by_target(
179
+ FUZZ_TARGET)
180
+ self.assertCountEqual(file_list, self._expected_file_list)
181
+
182
+ def test_invalid_target(self):
183
+ """Tests passing invalid fuzz target returns None."""
184
+ self.assertIsNone(
185
+ self.filesystem_coverage.get_files_covered_by_target(INVALID_TARGET))
186
+
187
+
188
+ class IsFileCoveredTest(unittest.TestCase):
189
+ """Tests for is_file_covered."""
190
+
191
+ def test_is_file_covered_covered(self):
192
+ """Tests that is_file_covered returns True for a covered file."""
193
+ file_coverage = {
194
+ 'filename': '/src/systemd/src/basic/locale-util.c',
195
+ 'summary': {
196
+ 'regions': {
197
+ 'count': 204,
198
+ 'covered': 200,
199
+ 'notcovered': 200,
200
+ 'percent': 98.03
201
+ }
202
+ }
203
+ }
204
+ self.assertTrue(get_coverage.is_file_covered(file_coverage))
205
+
206
+ def test_is_file_covered_not_covered(self):
207
+ """Tests that is_file_covered returns False for a not covered file."""
208
+ file_coverage = {
209
+ 'filename': '/src/systemd/src/basic/locale-util.c',
210
+ 'summary': {
211
+ 'regions': {
212
+ 'count': 204,
213
+ 'covered': 0,
214
+ 'notcovered': 0,
215
+ 'percent': 0
216
+ }
217
+ }
218
+ }
219
+ self.assertFalse(get_coverage.is_file_covered(file_coverage))
220
+
221
+
222
+ class GetOssFuzzLatestCovReportInfo(unittest.TestCase):
223
+ """Tests that _get_oss_fuzz_latest_cov_report_info works as
224
+ intended."""
225
+
226
+ PROJECT = 'project'
227
+ LATEST_REPORT_INFO_URL = ('https://storage.googleapis.com/oss-fuzz-coverage/'
228
+ 'latest_report_info/project.json')
229
+
230
+ @mock.patch('logging.error')
231
+ @mock.patch('http_utils.get_json_from_url', return_value={'coverage': 1})
232
+ def test_get_oss_fuzz_latest_cov_report_info(self, mock_get_json_from_url,
233
+ mock_error):
234
+ """Tests that _get_oss_fuzz_latest_cov_report_info works as intended."""
235
+ result = get_coverage._get_oss_fuzz_latest_cov_report_info(self.PROJECT)
236
+ self.assertEqual(result, {'coverage': 1})
237
+ mock_error.assert_not_called()
238
+ mock_get_json_from_url.assert_called_with(self.LATEST_REPORT_INFO_URL)
239
+
240
+ @mock.patch('logging.error')
241
+ @mock.patch('http_utils.get_json_from_url', return_value=None)
242
+ def test_get_oss_fuzz_latest_cov_report_info_fail(self, _, mock_error):
243
+ """Tests that _get_oss_fuzz_latest_cov_report_info works as intended when we
244
+ can't get latest report info."""
245
+ result = get_coverage._get_oss_fuzz_latest_cov_report_info('project')
246
+ self.assertIsNone(result)
247
+ mock_error.assert_called_with(
248
+ 'Could not get the coverage report json from url: %s.',
249
+ self.LATEST_REPORT_INFO_URL)
250
+
251
+
252
+ if __name__ == '__main__':
253
+ unittest.main()
local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/http_utils.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Utility module for HTTP."""
15
+ import json
16
+ import logging
17
+ import os
18
+ import sys
19
+ import tempfile
20
+ import zipfile
21
+
22
+ import requests
23
+
24
+ # pylint: disable=wrong-import-position,import-error
25
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
26
+ import retry
27
+
28
+ _DOWNLOAD_URL_RETRIES = 3
29
+ _DOWNLOAD_URL_BACKOFF = 1
30
+ _HTTP_REQUEST_TIMEOUT = 10
31
+
32
+
33
+ def download_and_unpack_zip(url, extract_directory, headers=None):
34
+ """Downloads and unpacks a zip file from an HTTP URL.
35
+
36
+ Args:
37
+ url: A url to the zip file to be downloaded and unpacked.
38
+ extract_directory: The path where the zip file should be extracted to.
39
+ headers: (Optional) HTTP headers to send with the download request.
40
+
41
+ Returns:
42
+ True on success.
43
+ """
44
+ if headers is None:
45
+ headers = {}
46
+
47
+ if not os.path.exists(extract_directory):
48
+ logging.error('Extract directory: %s does not exist.', extract_directory)
49
+ return False
50
+
51
+ # Gives the temporary zip file a unique identifier in the case that
52
+ # that download_and_unpack_zip is done in parallel.
53
+ with tempfile.NamedTemporaryFile(suffix='.zip') as tmp_file:
54
+ if not download_url(url, tmp_file.name, headers=headers):
55
+ return False
56
+
57
+ try:
58
+ with zipfile.ZipFile(tmp_file.name, 'r') as zip_file:
59
+ zip_file.extractall(extract_directory)
60
+ except zipfile.BadZipFile:
61
+ logging.error('Error unpacking zip from %s. Bad Zipfile.', url)
62
+ return False
63
+
64
+ return True
65
+
66
+
67
+ def download_url(*args, **kwargs):
68
+ """Wrapper around _download_url that returns False if _download_url
69
+ exceptions."""
70
+ try:
71
+ return _download_url(*args, **kwargs)
72
+ except Exception: # pylint: disable=broad-except
73
+ return False
74
+
75
+
76
+ def get_json_from_url(url):
77
+ """Gets a json object from a specified HTTP URL.
78
+
79
+ Args:
80
+ url: The url of the json to be downloaded.
81
+
82
+ Returns:
83
+ A dictionary deserialized from JSON or None on failure.
84
+ """
85
+ try:
86
+ return requests.get(url, timeout=_HTTP_REQUEST_TIMEOUT).json()
87
+ except (ValueError, TypeError, json.JSONDecodeError,
88
+ requests.exceptions.ReadTimeout) as err:
89
+ logging.error('Loading json from url %s failed with: %s.', url, str(err))
90
+ return None
91
+
92
+
93
+ @retry.wrap(_DOWNLOAD_URL_RETRIES, _DOWNLOAD_URL_BACKOFF)
94
+ def _download_url(url, filename, headers=None):
95
+ """Downloads the file located at |url|, using HTTP to |filename|.
96
+
97
+ Args:
98
+ url: A url to a file to download.
99
+ filename: The path the file should be downloaded to.
100
+ headers: (Optional) HTTP headers to send with the download request.
101
+
102
+ Returns:
103
+ True on success.
104
+ """
105
+ if headers is None:
106
+ headers = {}
107
+
108
+ response = requests.get(url, headers=headers)
109
+
110
+ if response.status_code != 200:
111
+ logging.error('Unable to download from: %s. Code: %d. Content: %s.', url,
112
+ response.status_code, response.content)
113
+ return False
114
+
115
+ with open(filename, 'wb') as file_handle:
116
+ file_handle.write(response.content)
117
+
118
+ return True
local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/logs.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Log helpers."""
15
+
16
+ import logging
17
+ import os
18
+
19
+
20
+ def init():
21
+ """Initialize logging."""
22
+ log_level = logging.DEBUG if os.getenv('CIFUZZ_DEBUG') else logging.INFO
23
+ logging.basicConfig(
24
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
25
+ level=log_level)
local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/run_fuzzers.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Module for running fuzzers."""
15
+ import enum
16
+ import logging
17
+ import os
18
+ import sys
19
+ import time
20
+
21
+ import clusterfuzz_deployment
22
+ import fuzz_target
23
+ import generate_coverage_report
24
+ import workspace_utils
25
+ import sarif_utils
26
+
27
+ # pylint: disable=wrong-import-position,import-error
28
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
29
+
30
+ import utils
31
+
32
+
33
+ class RunFuzzersResult(enum.Enum):
34
+ """Enum result from running fuzzers."""
35
+ ERROR = 0
36
+ BUG_FOUND = 1
37
+ NO_BUG_FOUND = 2
38
+
39
+
40
+ class BaseFuzzTargetRunner:
41
+ """Base class for fuzzer runners."""
42
+
43
+ def __init__(self, config):
44
+ self.config = config
45
+ self.workspace = workspace_utils.Workspace(config)
46
+ self.clusterfuzz_deployment = (
47
+ clusterfuzz_deployment.get_clusterfuzz_deployment(
48
+ self.config, self.workspace))
49
+
50
+ # Set by the initialize method.
51
+ self.fuzz_target_paths = None
52
+
53
+ def get_fuzz_targets(self):
54
+ """Returns fuzz targets in out directory."""
55
+ return utils.get_fuzz_targets(self.workspace.out)
56
+
57
+ def initialize(self):
58
+ """Initialization method. Must be called before calling run_fuzz_targets.
59
+ Returns True on success."""
60
+ # Use a separate initialization function so we can return False on failure
61
+ # instead of exceptioning like we need to do if this were done in the
62
+ # __init__ method.
63
+
64
+ logging.info('Using %s sanitizer.', self.config.sanitizer)
65
+
66
+ # TODO(metzman) Add a check to ensure we aren't over time limit.
67
+ if not self.config.fuzz_seconds or self.config.fuzz_seconds < 1:
68
+ logging.error(
69
+ 'Fuzz_seconds argument must be greater than 1, but was: %s.',
70
+ self.config.fuzz_seconds)
71
+ return False
72
+
73
+ if not os.path.exists(self.workspace.out):
74
+ logging.error('Out directory: %s does not exist.', self.workspace.out)
75
+ return False
76
+
77
+ if not os.path.exists(self.workspace.artifacts):
78
+ os.makedirs(self.workspace.artifacts)
79
+ elif (not os.path.isdir(self.workspace.artifacts) or
80
+ os.listdir(self.workspace.artifacts)):
81
+ logging.error('Artifacts path: %s exists and is not an empty directory.',
82
+ self.workspace.artifacts)
83
+ return False
84
+
85
+ self.fuzz_target_paths = self.get_fuzz_targets()
86
+ logging.info('Fuzz targets: %s', self.fuzz_target_paths)
87
+ if not self.fuzz_target_paths:
88
+ logging.error('No fuzz targets were found in out directory: %s.',
89
+ self.workspace.out)
90
+ return False
91
+
92
+ return True
93
+
94
+ def cleanup_after_fuzz_target_run(self, fuzz_target_obj): # pylint: disable=no-self-use
95
+ """Cleans up after running |fuzz_target_obj|."""
96
+ raise NotImplementedError('Child class must implement method.')
97
+
98
+ def run_fuzz_target(self, fuzz_target_obj): # pylint: disable=no-self-use
99
+ """Fuzzes with |fuzz_target_obj| and returns the result."""
100
+ raise NotImplementedError('Child class must implement method.')
101
+
102
+ @property
103
+ def quit_on_bug_found(self):
104
+ """Property that is checked to determine if fuzzing should quit after first
105
+ bug is found."""
106
+ raise NotImplementedError('Child class must implement method.')
107
+
108
+ def create_fuzz_target_obj(self, target_path, run_seconds):
109
+ """Returns a fuzz target object."""
110
+ return fuzz_target.FuzzTarget(target_path, run_seconds, self.workspace,
111
+ self.clusterfuzz_deployment, self.config)
112
+
113
+ def run_fuzz_targets(self):
114
+ """Runs fuzz targets. Returns True if a bug was found."""
115
+ fuzzers_left_to_run = len(self.fuzz_target_paths)
116
+
117
+ # Make a copy since we will mutate it.
118
+ fuzz_seconds = self.config.fuzz_seconds
119
+
120
+ min_seconds_per_fuzzer = fuzz_seconds // fuzzers_left_to_run
121
+ bug_found = False
122
+ for target_path in self.fuzz_target_paths:
123
+ # By doing this, we can ensure that every fuzz target runs for at least
124
+ # min_seconds_per_fuzzer, but that other fuzzers will have longer to run
125
+ # if one ends early.
126
+ run_seconds = max(fuzz_seconds // fuzzers_left_to_run,
127
+ min_seconds_per_fuzzer)
128
+
129
+ target = self.create_fuzz_target_obj(target_path, run_seconds)
130
+ start_time = time.time()
131
+ result = self.run_fuzz_target(target)
132
+ self.cleanup_after_fuzz_target_run(target)
133
+
134
+ # It's OK if this goes negative since we take max when determining
135
+ # run_seconds.
136
+ fuzz_seconds -= time.time() - start_time
137
+
138
+ fuzzers_left_to_run -= 1
139
+ if not result.testcase or not result.stacktrace:
140
+ logging.info('Fuzzer %s finished running without reportable crashes.',
141
+ target.target_name)
142
+ continue
143
+
144
+ bug_found = True
145
+ if self.quit_on_bug_found:
146
+ logging.info('Bug found. Stopping fuzzing.')
147
+ break
148
+
149
+ # pylint: disable=undefined-loop-variable
150
+ if not target_path:
151
+ logging.error('Ran no fuzz targets.')
152
+ elif self.config.output_sarif:
153
+ # TODO(metzman): Handle multiple crashes.
154
+ write_fuzz_result_to_sarif(result, target_path, self.workspace)
155
+ self.clusterfuzz_deployment.upload_crashes()
156
+ return bug_found
157
+
158
+
159
+ def write_fuzz_result_to_sarif(fuzz_result, target_path, workspace):
160
+ """Write results of fuzzing to SARIF."""
161
+ logging.info('Writing sarif results.')
162
+ sarif_utils.write_stacktrace_to_sarif(fuzz_result.stacktrace, target_path,
163
+ workspace)
164
+
165
+
166
+ class PruneTargetRunner(BaseFuzzTargetRunner):
167
+ """Runner that prunes corpora."""
168
+
169
+ @property
170
+ def quit_on_bug_found(self):
171
+ return False
172
+
173
+ def run_fuzz_target(self, fuzz_target_obj):
174
+ """Prunes with |fuzz_target_obj| and returns the result."""
175
+ result = fuzz_target_obj.prune()
176
+ logging.debug('Corpus path contents: %s.', os.listdir(result.corpus_path))
177
+ self.clusterfuzz_deployment.upload_corpus(fuzz_target_obj.target_name,
178
+ result.corpus_path,
179
+ replace=True)
180
+ return result
181
+
182
+ def cleanup_after_fuzz_target_run(self, fuzz_target_obj): # pylint: disable=no-self-use
183
+ """Cleans up after pruning with |fuzz_target_obj|."""
184
+ fuzz_target_obj.free_disk_if_needed()
185
+
186
+
187
+ NON_FUZZ_TARGETS_FOR_COVERAGE = {
188
+ 'llvm-symbolizer',
189
+ 'jazzer_agent_deploy.jar',
190
+ 'jazzer_driver',
191
+ 'jazzer_driver_with_sanitizer',
192
+ }
193
+
194
+
195
+ def is_coverage_fuzz_target(file_path):
196
+ """Returns whether |file_path| is a fuzz target binary for the purposes of a
197
+ coverage report. Inspired by infra/base-images/base-runner/coverage."""
198
+ if not os.path.isfile(file_path):
199
+ return False
200
+ if not utils.is_executable(file_path):
201
+ return False
202
+ filename = os.path.basename(file_path)
203
+ return filename not in NON_FUZZ_TARGETS_FOR_COVERAGE
204
+
205
+
206
+ def get_coverage_fuzz_targets(out):
207
+ """Returns a list of fuzz targets in |out| for coverage."""
208
+ # We only want fuzz targets from the root because during the coverage build,
209
+ # a lot of the image's filesystem is copied into /out for the purpose of
210
+ # generating coverage reports.
211
+ fuzz_targets = []
212
+ for filename in os.listdir(out):
213
+ file_path = os.path.join(out, filename)
214
+ if is_coverage_fuzz_target(file_path):
215
+ fuzz_targets.append(file_path)
216
+ return fuzz_targets
217
+
218
+
219
+ class CoverageTargetRunner(BaseFuzzTargetRunner):
220
+ """Runner that runs the 'coverage' command."""
221
+
222
+ @property
223
+ def quit_on_bug_found(self):
224
+ raise NotImplementedError('Not implemented for CoverageTargetRunner.')
225
+
226
+ def get_fuzz_targets(self):
227
+ """Returns fuzz targets in out directory."""
228
+ return get_coverage_fuzz_targets(self.workspace.out)
229
+
230
+ def run_fuzz_targets(self):
231
+ """Generates a coverage report. Always returns False since it never finds
232
+ any bugs."""
233
+ generate_coverage_report.generate_coverage_report(
234
+ self.fuzz_target_paths, self.workspace, self.clusterfuzz_deployment,
235
+ self.config)
236
+ return False
237
+
238
+ def run_fuzz_target(self, fuzz_target_obj): # pylint: disable=no-self-use
239
+ """Fuzzes with |fuzz_target_obj| and returns the result."""
240
+ raise NotImplementedError('Not implemented for CoverageTargetRunner.')
241
+
242
+ def cleanup_after_fuzz_target_run(self, fuzz_target_obj): # pylint: disable=no-self-use
243
+ """Cleans up after running |fuzz_target_obj|."""
244
+ raise NotImplementedError('Not implemented for CoverageTargetRunner.')
245
+
246
+
247
+ class CiFuzzTargetRunner(BaseFuzzTargetRunner):
248
+ """Runner for fuzz targets used in CI (patch-fuzzing) context."""
249
+
250
+ @property
251
+ def quit_on_bug_found(self):
252
+ return True
253
+
254
+ def cleanup_after_fuzz_target_run(self, fuzz_target_obj): # pylint: disable=no-self-use
255
+ """Cleans up after running |fuzz_target_obj|."""
256
+ fuzz_target_obj.free_disk_if_needed()
257
+
258
+ def run_fuzz_target(self, fuzz_target_obj): # pylint: disable=no-self-use
259
+ return fuzz_target_obj.fuzz()
260
+
261
+
262
+ class BatchFuzzTargetRunner(BaseFuzzTargetRunner):
263
+ """Runner for fuzz targets used in batch fuzzing context."""
264
+
265
+ @property
266
+ def quit_on_bug_found(self):
267
+ return False
268
+
269
+ def run_fuzz_target(self, fuzz_target_obj):
270
+ """Fuzzes with |fuzz_target_obj| and returns the result."""
271
+ result = fuzz_target_obj.fuzz(batch=True)
272
+ logging.debug('Corpus path contents: %s.', os.listdir(result.corpus_path))
273
+ self.clusterfuzz_deployment.upload_corpus(fuzz_target_obj.target_name,
274
+ result.corpus_path)
275
+ return result
276
+
277
+ def cleanup_after_fuzz_target_run(self, fuzz_target_obj):
278
+ """Cleans up after running |fuzz_target_obj|."""
279
+ # This must be done after we upload the corpus, otherwise it will be deleted
280
+ # before we get a chance to upload it. We can't delete the fuzz target
281
+ # because it is needed when we upload the build.
282
+ fuzz_target_obj.free_disk_if_needed(delete_fuzz_target=False)
283
+
284
+
285
+ _MODE_RUNNER_MAPPING = {
286
+ 'batch': BatchFuzzTargetRunner,
287
+ 'coverage': CoverageTargetRunner,
288
+ 'prune': PruneTargetRunner,
289
+ 'code-change': CiFuzzTargetRunner,
290
+ }
291
+
292
+
293
+ def get_fuzz_target_runner(config):
294
+ """Returns a fuzz target runner object based on the mode of
295
+ |config|."""
296
+ runner = _MODE_RUNNER_MAPPING[config.mode](config)
297
+ logging.info('run fuzzers MODE is: %s. Runner: %s.', config.mode, runner)
298
+ return runner
299
+
300
+
301
+ def run_fuzzers(config): # pylint: disable=too-many-locals
302
+ """Runs fuzzers for a specific OSS-Fuzz project.
303
+
304
+ Args:
305
+ config: A RunFuzzTargetsConfig.
306
+
307
+ Returns:
308
+ A RunFuzzersResult enum value indicating what happened during fuzzing.
309
+ """
310
+ fuzz_target_runner = get_fuzz_target_runner(config)
311
+ if not fuzz_target_runner.initialize():
312
+ # We didn't fuzz at all because of internal (CIFuzz) errors. And we didn't
313
+ # find any bugs.
314
+ return RunFuzzersResult.ERROR
315
+
316
+ if not fuzz_target_runner.run_fuzz_targets():
317
+ # We fuzzed successfully, but didn't find any bugs (in the fuzz target).
318
+ return RunFuzzersResult.NO_BUG_FOUND
319
+
320
+ # We fuzzed successfully and found bug(s) in the fuzz targets.
321
+ return RunFuzzersResult.BUG_FOUND
local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/run_fuzzers_entrypoint.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Runs a specific OSS-Fuzz project's fuzzers for CI tools."""
15
+ import logging
16
+ import sys
17
+
18
+ import config_utils
19
+ import docker
20
+ import logs
21
+ import run_fuzzers
22
+
23
+ # pylint: disable=c-extension-no-member
24
+ # pylint gets confused because of the relative import of cifuzz.
25
+
26
+ logs.init()
27
+
28
+
29
+ def delete_unneeded_docker_images(config):
30
+ """Deletes unneeded docker images if running in an environment with low
31
+ disk space."""
32
+ if not config.low_disk_space:
33
+ return
34
+ logging.info('Deleting builder docker images to save disk space.')
35
+ project_image = docker.get_project_image_name(config.oss_fuzz_project_name)
36
+ images = [
37
+ project_image,
38
+ docker.BASE_BUILDER_TAG,
39
+ docker.BASE_BUILDER_TAG + '-go',
40
+ docker.BASE_BUILDER_TAG + '-javascript',
41
+ docker.BASE_BUILDER_TAG + '-jvm',
42
+ docker.BASE_BUILDER_TAG + '-python',
43
+ docker.BASE_BUILDER_TAG + '-rust',
44
+ docker.BASE_BUILDER_TAG + '-ruby',
45
+ docker.BASE_BUILDER_TAG + '-swift',
46
+ ]
47
+ docker.delete_images(images)
48
+
49
+
50
+ def run_fuzzers_entrypoint():
51
+ """This is the entrypoint for the run_fuzzers github action.
52
+ This action can be added to any OSS-Fuzz project's workflow that uses
53
+ Github."""
54
+ config = config_utils.RunFuzzersConfig()
55
+ # The default return code when an error occurs.
56
+ returncode = 1
57
+ if config.dry_run:
58
+ # Sets the default return code on error to success.
59
+ returncode = 0
60
+
61
+ delete_unneeded_docker_images(config)
62
+ # Run the specified project's fuzzers from the build.
63
+ result = run_fuzzers.run_fuzzers(config)
64
+ if result == run_fuzzers.RunFuzzersResult.ERROR:
65
+ logging.error('Error occurred while running in workspace %s.',
66
+ config.workspace)
67
+ return returncode
68
+ if result == run_fuzzers.RunFuzzersResult.BUG_FOUND:
69
+ logging.info('Bug found.')
70
+ if not config.dry_run:
71
+ # Return 2 when a bug was found by a fuzzer causing the CI to fail.
72
+ return 2
73
+ return 0
74
+
75
+
76
+ def main():
77
+ """Runs project's fuzzers for CI tools.
78
+ This is the entrypoint for the run_fuzzers github action.
79
+
80
+ NOTE: libFuzzer binaries must be located in the $WORKSPACE/build-out
81
+ directory in order for this action to be used. This action will only fuzz the
82
+ binaries that are located in that directory. It is recommended that you add
83
+ the build_fuzzers action preceding this one.
84
+
85
+ NOTE: Any crash report will be in the filepath:
86
+ ${GITHUB_WORKSPACE}/out/testcase
87
+ This can be used in parallel with the upload-artifact action to surface the
88
+ logs.
89
+
90
+ Returns:
91
+ 0 on success or nonzero on failure.
92
+ """
93
+ return run_fuzzers_entrypoint()
94
+
95
+
96
+ if __name__ == '__main__':
97
+ sys.exit(main())
local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/run_fuzzers_test.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests for running fuzzers."""
15
+ import json
16
+ import os
17
+ import shutil
18
+ import stat
19
+ import sys
20
+ import tempfile
21
+ import unittest
22
+ from unittest import mock
23
+
24
+ import parameterized
25
+ from pyfakefs import fake_filesystem_unittest
26
+
27
+ import build_fuzzers
28
+ import fuzz_target
29
+ import run_fuzzers
30
+
31
+ # pylint: disable=wrong-import-position
32
+ INFRA_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
33
+ sys.path.append(INFRA_DIR)
34
+
35
+ import helper
36
+ import test_helpers
37
+
38
+ # NOTE: This integration test relies on
39
+ # https://github.com/google/oss-fuzz/tree/master/projects/example project.
40
+ EXAMPLE_PROJECT = 'example'
41
+
42
+ # Location of files used for testing.
43
+ TEST_DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
44
+ 'test_data')
45
+
46
+ MEMORY_FUZZER_DIR = os.path.join(TEST_DATA_PATH, 'memory')
47
+ MEMORY_FUZZER = 'curl_fuzzer_memory'
48
+
49
+ UNDEFINED_FUZZER_DIR = os.path.join(TEST_DATA_PATH, 'undefined')
50
+ UNDEFINED_FUZZER = 'curl_fuzzer_undefined'
51
+
52
+ FUZZ_SECONDS = 10
53
+
54
+
55
+ class RunFuzzerIntegrationTestMixin: # pylint: disable=too-few-public-methods,invalid-name
56
+ """Mixin for integration test classes that runbuild_fuzzers on builds of a
57
+ specific sanitizer."""
58
+ # These must be defined by children.
59
+ FUZZER_DIR = None
60
+ FUZZER = None
61
+
62
+ def setUp(self):
63
+ """Patch the environ so that we can execute runner scripts."""
64
+ test_helpers.patch_environ(self, runner=True)
65
+
66
+ def _test_run_with_sanitizer(self, fuzzer_dir, sanitizer):
67
+ """Calls run_fuzzers on fuzzer_dir and |sanitizer| and asserts
68
+ the run succeeded and that no bug was found."""
69
+ with test_helpers.temp_dir_copy(fuzzer_dir) as fuzzer_dir_copy:
70
+ config = test_helpers.create_run_config(fuzz_seconds=FUZZ_SECONDS,
71
+ workspace=fuzzer_dir_copy,
72
+ oss_fuzz_project_name='curl',
73
+ sanitizer=sanitizer)
74
+ result = run_fuzzers.run_fuzzers(config)
75
+ self.assertEqual(result, run_fuzzers.RunFuzzersResult.NO_BUG_FOUND)
76
+
77
+
78
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
79
+ 'INTEGRATION_TESTS=1 not set')
80
+ class RunMemoryFuzzerIntegrationTest(RunFuzzerIntegrationTestMixin,
81
+ unittest.TestCase):
82
+ """Integration test for build_fuzzers with an MSAN build."""
83
+ FUZZER_DIR = MEMORY_FUZZER_DIR
84
+ FUZZER = MEMORY_FUZZER
85
+
86
+ def test_run_with_memory_sanitizer(self):
87
+ """Tests run_fuzzers with a valid MSAN build."""
88
+ self._test_run_with_sanitizer(self.FUZZER_DIR, 'memory')
89
+
90
+
91
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
92
+ 'INTEGRATION_TESTS=1 not set')
93
+ class RunUndefinedFuzzerIntegrationTest(RunFuzzerIntegrationTestMixin,
94
+ unittest.TestCase):
95
+ """Integration test for build_fuzzers with an UBSAN build."""
96
+ FUZZER_DIR = UNDEFINED_FUZZER_DIR
97
+ FUZZER = UNDEFINED_FUZZER
98
+
99
+ def test_run_with_undefined_sanitizer(self):
100
+ """Tests run_fuzzers with a valid UBSAN build."""
101
+ self._test_run_with_sanitizer(self.FUZZER_DIR, 'undefined')
102
+
103
+
104
+ class BaseFuzzTargetRunnerTest(unittest.TestCase):
105
+ """Tests BaseFuzzTargetRunner."""
106
+
107
+ def _create_runner(self, **kwargs): # pylint: disable=no-self-use
108
+ defaults = {
109
+ 'fuzz_seconds': FUZZ_SECONDS,
110
+ 'oss_fuzz_project_name': EXAMPLE_PROJECT
111
+ }
112
+ for default_key, default_value in defaults.items():
113
+ if default_key not in kwargs:
114
+ kwargs[default_key] = default_value
115
+
116
+ config = test_helpers.create_run_config(**kwargs)
117
+ return run_fuzzers.BaseFuzzTargetRunner(config)
118
+
119
+ def _test_initialize_fail(self, expected_error_args, **create_runner_kwargs):
120
+ with mock.patch('logging.error') as mock_error:
121
+ runner = self._create_runner(**create_runner_kwargs)
122
+ self.assertFalse(runner.initialize())
123
+ mock_error.assert_called_with(*expected_error_args)
124
+
125
+ @parameterized.parameterized.expand([(0,), (None,), (-1,)])
126
+ def test_initialize_invalid_fuzz_seconds(self, fuzz_seconds):
127
+ """Tests initialize fails with an invalid fuzz seconds."""
128
+ expected_error_args = ('Fuzz_seconds argument must be greater than 1, '
129
+ 'but was: %s.', fuzz_seconds)
130
+ with tempfile.TemporaryDirectory() as tmp_dir:
131
+ out_path = os.path.join(tmp_dir, 'build-out')
132
+ os.mkdir(out_path)
133
+ with mock.patch('utils.get_fuzz_targets') as mock_get_fuzz_targets:
134
+ mock_get_fuzz_targets.return_value = [
135
+ os.path.join(out_path, 'fuzz_target')
136
+ ]
137
+ self._test_initialize_fail(expected_error_args,
138
+ fuzz_seconds=fuzz_seconds,
139
+ workspace=tmp_dir)
140
+
141
+ def test_initialize_no_out_dir(self):
142
+ """Tests initialize fails with no out dir."""
143
+ with tempfile.TemporaryDirectory() as tmp_dir:
144
+ out_path = os.path.join(tmp_dir, 'build-out')
145
+ expected_error_args = ('Out directory: %s does not exist.', out_path)
146
+ self._test_initialize_fail(expected_error_args, workspace=tmp_dir)
147
+
148
+ def test_initialize_nonempty_artifacts(self):
149
+ """Tests initialize with a file artifacts path."""
150
+ with tempfile.TemporaryDirectory() as tmp_dir:
151
+ out_path = os.path.join(tmp_dir, 'build-out')
152
+ os.mkdir(out_path)
153
+ os.makedirs(os.path.join(tmp_dir, 'out'))
154
+ artifacts_path = os.path.join(tmp_dir, 'out', 'artifacts')
155
+ with open(artifacts_path, 'w') as artifacts_handle:
156
+ artifacts_handle.write('fake')
157
+ expected_error_args = (
158
+ 'Artifacts path: %s exists and is not an empty directory.',
159
+ artifacts_path)
160
+ self._test_initialize_fail(expected_error_args, workspace=tmp_dir)
161
+
162
+ def test_initialize_bad_artifacts(self):
163
+ """Tests initialize with a non-empty artifacts path."""
164
+ with tempfile.TemporaryDirectory() as tmp_dir:
165
+ out_path = os.path.join(tmp_dir, 'build-out')
166
+ os.mkdir(out_path)
167
+ artifacts_path = os.path.join(tmp_dir, 'out', 'artifacts')
168
+ os.makedirs(artifacts_path)
169
+ artifact_path = os.path.join(artifacts_path, 'artifact')
170
+ with open(artifact_path, 'w') as artifact_handle:
171
+ artifact_handle.write('fake')
172
+ expected_error_args = (
173
+ 'Artifacts path: %s exists and is not an empty directory.',
174
+ artifacts_path)
175
+ self._test_initialize_fail(expected_error_args, workspace=tmp_dir)
176
+
177
+ @mock.patch('utils.get_fuzz_targets')
178
+ @mock.patch('logging.error')
179
+ def test_initialize_empty_artifacts(self, mock_log_error,
180
+ mock_get_fuzz_targets):
181
+ """Tests initialize with an empty artifacts dir."""
182
+ mock_get_fuzz_targets.return_value = ['fuzz-target']
183
+ with tempfile.TemporaryDirectory() as tmp_dir:
184
+ out_path = os.path.join(tmp_dir, 'build-out')
185
+ os.mkdir(out_path)
186
+ artifacts_path = os.path.join(tmp_dir, 'out', 'artifacts')
187
+ os.makedirs(artifacts_path)
188
+ runner = self._create_runner(workspace=tmp_dir)
189
+ self.assertTrue(runner.initialize())
190
+ mock_log_error.assert_not_called()
191
+ self.assertTrue(os.path.isdir(artifacts_path))
192
+
193
+ @mock.patch('utils.get_fuzz_targets')
194
+ @mock.patch('logging.error')
195
+ def test_initialize_no_artifacts(self, mock_log_error, mock_get_fuzz_targets):
196
+ """Tests initialize with no artifacts dir (the expected setting)."""
197
+ mock_get_fuzz_targets.return_value = ['fuzz-target']
198
+ with tempfile.TemporaryDirectory() as tmp_dir:
199
+ out_path = os.path.join(tmp_dir, 'build-out')
200
+ os.mkdir(out_path)
201
+ runner = self._create_runner(workspace=tmp_dir)
202
+ self.assertTrue(runner.initialize())
203
+ mock_log_error.assert_not_called()
204
+ self.assertTrue(os.path.isdir(os.path.join(tmp_dir, 'out', 'artifacts')))
205
+
206
+ def test_initialize_no_fuzz_targets(self):
207
+ """Tests initialize with no fuzz targets."""
208
+ with tempfile.TemporaryDirectory() as tmp_dir:
209
+ out_path = os.path.join(tmp_dir, 'build-out')
210
+ os.makedirs(out_path)
211
+ expected_error_args = ('No fuzz targets were found in out directory: %s.',
212
+ out_path)
213
+ self._test_initialize_fail(expected_error_args, workspace=tmp_dir)
214
+
215
+
216
+ class CiFuzzTargetRunnerTest(fake_filesystem_unittest.TestCase):
217
+ """Tests that CiFuzzTargetRunner works as intended."""
218
+
219
+ def setUp(self):
220
+ self.setUpPyfakefs()
221
+
222
+ @mock.patch('clusterfuzz_deployment.OSSFuzz.upload_crashes')
223
+ @mock.patch('utils.get_fuzz_targets')
224
+ @mock.patch('run_fuzzers.CiFuzzTargetRunner.run_fuzz_target')
225
+ @mock.patch('run_fuzzers.CiFuzzTargetRunner.create_fuzz_target_obj')
226
+ def test_run_fuzz_targets_quits(self, mock_create_fuzz_target_obj,
227
+ mock_run_fuzz_target, mock_get_fuzz_targets,
228
+ mock_upload_crashes):
229
+ """Tests that run_fuzz_targets quits on the first crash it finds."""
230
+ workspace = 'workspace'
231
+ out_path = os.path.join(workspace, 'build-out')
232
+ self.fs.create_dir(out_path)
233
+ config = test_helpers.create_run_config(
234
+ fuzz_seconds=FUZZ_SECONDS,
235
+ workspace=workspace,
236
+ oss_fuzz_project_name=EXAMPLE_PROJECT)
237
+ runner = run_fuzzers.CiFuzzTargetRunner(config)
238
+
239
+ mock_get_fuzz_targets.return_value = ['target1', 'target2']
240
+ runner.initialize()
241
+ testcase = os.path.join(workspace, 'testcase')
242
+ self.fs.create_file(testcase)
243
+ stacktrace = 'stacktrace'
244
+ corpus_dir = 'corpus'
245
+ self.fs.create_dir(corpus_dir)
246
+ mock_run_fuzz_target.return_value = fuzz_target.FuzzResult(
247
+ testcase, stacktrace, corpus_dir)
248
+ magic_mock = mock.MagicMock()
249
+ magic_mock.target_name = 'target1'
250
+ mock_create_fuzz_target_obj.return_value = magic_mock
251
+ self.assertTrue(runner.run_fuzz_targets())
252
+ self.assertEqual(mock_run_fuzz_target.call_count, 1)
253
+ self.assertEqual(mock_upload_crashes.call_count, 1)
254
+
255
+
256
+ class BatchFuzzTargetRunnerTest(fake_filesystem_unittest.TestCase):
257
+ """Tests that BatchFuzzTargetRunnerTest works as intended."""
258
+ WORKSPACE = 'workspace'
259
+ STACKTRACE = 'stacktrace'
260
+ CORPUS_DIR = 'corpus'
261
+
262
+ def setUp(self):
263
+ self.setUpPyfakefs()
264
+ out_dir = os.path.join(self.WORKSPACE, 'build-out')
265
+ self.fs.create_dir(out_dir)
266
+ self.testcase1 = os.path.join(out_dir, 'testcase-aaa')
267
+ self.fs.create_file(self.testcase1)
268
+ self.testcase2 = os.path.join(out_dir, 'testcase-bbb')
269
+ self.fs.create_file(self.testcase2)
270
+ self.config = test_helpers.create_run_config(fuzz_seconds=FUZZ_SECONDS,
271
+ workspace=self.WORKSPACE,
272
+ cfl_platform='github')
273
+
274
+ @mock.patch('utils.get_fuzz_targets', return_value=['target1', 'target2'])
275
+ @mock.patch('clusterfuzz_deployment.ClusterFuzzLite.upload_crashes')
276
+ @mock.patch('run_fuzzers.BatchFuzzTargetRunner.run_fuzz_target')
277
+ @mock.patch('run_fuzzers.BatchFuzzTargetRunner.create_fuzz_target_obj')
278
+ def test_run_fuzz_targets_quits(self, mock_create_fuzz_target_obj,
279
+ mock_run_fuzz_target, mock_upload_crashes, _):
280
+ """Tests that run_fuzz_targets doesn't quit on the first crash it finds."""
281
+ runner = run_fuzzers.BatchFuzzTargetRunner(self.config)
282
+ runner.initialize()
283
+
284
+ call_count = 0
285
+
286
+ def mock_run_fuzz_target_impl(_):
287
+ nonlocal call_count
288
+ if call_count == 0:
289
+ testcase = self.testcase1
290
+ elif call_count == 1:
291
+ testcase = self.testcase2
292
+ assert call_count != 2
293
+ call_count += 1
294
+ if not os.path.exists(self.CORPUS_DIR):
295
+ self.fs.create_dir(self.CORPUS_DIR)
296
+ return fuzz_target.FuzzResult(testcase, self.STACKTRACE, self.CORPUS_DIR)
297
+
298
+ mock_run_fuzz_target.side_effect = mock_run_fuzz_target_impl
299
+ magic_mock = mock.MagicMock()
300
+ magic_mock.target_name = 'target1'
301
+ mock_create_fuzz_target_obj.return_value = magic_mock
302
+ self.assertTrue(runner.run_fuzz_targets())
303
+ self.assertEqual(mock_run_fuzz_target.call_count, 2)
304
+ self.assertEqual(mock_upload_crashes.call_count, 1)
305
+
306
+
307
+ class GetCoverageTargetsTest(unittest.TestCase):
308
+ """Tests for get_coverage_fuzz_targets."""
309
+
310
+ def test_get_fuzz_targets(self):
311
+ """Tests that get_coverage_fuzz_targets returns expected targets."""
312
+ with tempfile.TemporaryDirectory() as temp_dir:
313
+ # Setup.
314
+ fuzz_target_path = os.path.join(temp_dir, 'fuzz-target')
315
+ with open(fuzz_target_path, 'w') as file_handle:
316
+ file_handle.write('')
317
+ fuzz_target_st = os.stat(fuzz_target_path)
318
+ os.chmod(fuzz_target_path, fuzz_target_st.st_mode | stat.S_IEXEC)
319
+ non_fuzz_target1 = os.path.join(temp_dir, 'non-fuzz-target1')
320
+ with open(non_fuzz_target1, 'w') as file_handle:
321
+ file_handle.write('LLVMFuzzerTestOneInput')
322
+ subdir = os.path.join(temp_dir, 'subdir')
323
+ os.mkdir(subdir)
324
+ non_fuzz_target2 = os.path.join(subdir, 'non-fuzz-target1')
325
+ with open(non_fuzz_target2, 'w') as file_handle:
326
+ file_handle.write('LLVMFuzzerTestOneInput')
327
+
328
+ self.assertEqual(run_fuzzers.get_coverage_fuzz_targets(temp_dir),
329
+ [fuzz_target_path])
330
+
331
+
332
+ @unittest.skip('TODO(metzman): Fix this test')
333
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
334
+ 'INTEGRATION_TESTS=1 not set')
335
+ class CoverageReportIntegrationTest(unittest.TestCase):
336
+ """Integration tests for coverage reports."""
337
+ SANITIZER = 'coverage'
338
+
339
+ def setUp(self):
340
+ test_helpers.patch_environ(self, runner=True)
341
+
342
+ @mock.patch('filestore.github_actions._upload_artifact_with_upload_js')
343
+ def test_coverage_report(self, _):
344
+ """Tests generation of coverage reports end-to-end, from building to
345
+ generation."""
346
+
347
+ with test_helpers.docker_temp_dir() as temp_dir:
348
+ shared = os.path.join(temp_dir, 'shared')
349
+ os.mkdir(shared)
350
+ copy_command = ('cp -r /opt/code_coverage /shared && '
351
+ 'cp $(which llvm-profdata) /shared && '
352
+ 'cp $(which llvm-cov) /shared')
353
+ assert helper.docker_run([
354
+ '-v', f'{shared}:/shared', 'ghcr.io/aixcc-finals/base-runner', 'bash',
355
+ '-c', copy_command
356
+ ])
357
+
358
+ os.environ['CODE_COVERAGE_SRC'] = os.path.join(shared, 'code_coverage')
359
+ os.environ['PATH'] += os.pathsep + shared
360
+ # Do coverage build.
361
+ build_config = test_helpers.create_build_config(
362
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
363
+ project_repo_name='oss-fuzz',
364
+ workspace=temp_dir,
365
+ git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523',
366
+ base_commit='da0746452433dc18bae699e355a9821285d863c8',
367
+ sanitizer=self.SANITIZER,
368
+ cfl_platform='github',
369
+ # Needed for test not to fail because of permissions issues.
370
+ bad_build_check=False)
371
+ self.assertTrue(build_fuzzers.build_fuzzers(build_config))
372
+
373
+ # TODO(metzman): Get rid of this here and make 'compile' do this.
374
+ chmod_command = ('chmod -R +r /out && '
375
+ 'find /out -type d -exec chmod +x {} +')
376
+
377
+ assert helper.docker_run([
378
+ '-v', f'{os.path.join(temp_dir, "build-out")}:/out',
379
+ 'ghcr.io/aixcc-finals/base-builder', 'bash', '-c', chmod_command
380
+ ])
381
+
382
+ # Generate report.
383
+ run_config = test_helpers.create_run_config(fuzz_seconds=FUZZ_SECONDS,
384
+ workspace=temp_dir,
385
+ sanitizer=self.SANITIZER,
386
+ mode='coverage',
387
+ cfl_platform='github')
388
+ result = run_fuzzers.run_fuzzers(run_config)
389
+ self.assertEqual(result, run_fuzzers.RunFuzzersResult.NO_BUG_FOUND)
390
+ expected_summary_path = os.path.join(
391
+ TEST_DATA_PATH, 'example_coverage_report_summary.json')
392
+ with open(expected_summary_path) as file_handle:
393
+ expected_summary = json.loads(file_handle.read())
394
+ actual_summary_path = os.path.join(temp_dir, 'cifuzz-coverage',
395
+ 'report', 'linux', 'summary.json')
396
+ with open(actual_summary_path) as file_handle:
397
+ actual_summary = json.loads(file_handle.read())
398
+ self.assertEqual(expected_summary, actual_summary)
399
+
400
+
401
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
402
+ 'INTEGRATION_TESTS=1 not set')
403
+ class RunAddressFuzzersIntegrationTest(RunFuzzerIntegrationTestMixin,
404
+ unittest.TestCase):
405
+ """Integration tests for build_fuzzers with an ASAN build."""
406
+
407
+ BUILD_DIR_NAME = 'cifuzz-latest-build'
408
+
409
+ def test_new_bug_found(self):
410
+ """Tests run_fuzzers with a valid ASAN build."""
411
+ # Set the first return value to True, then the second to False to
412
+ # emulate a bug existing in the current PR but not on the downloaded
413
+ # OSS-Fuzz build.
414
+ with mock.patch('fuzz_target.FuzzTarget.is_reproducible',
415
+ side_effect=[True, False]):
416
+ with tempfile.TemporaryDirectory() as tmp_dir:
417
+ workspace = os.path.join(tmp_dir, 'workspace')
418
+ shutil.copytree(TEST_DATA_PATH, workspace)
419
+ config = test_helpers.create_run_config(
420
+ fuzz_seconds=FUZZ_SECONDS,
421
+ workspace=workspace,
422
+ oss_fuzz_project_name=EXAMPLE_PROJECT)
423
+ result = run_fuzzers.run_fuzzers(config)
424
+ self.assertEqual(result, run_fuzzers.RunFuzzersResult.BUG_FOUND)
425
+
426
+ @mock.patch('fuzz_target.FuzzTarget.is_reproducible',
427
+ side_effect=[True, True])
428
+ def test_old_bug_found(self, _):
429
+ """Tests run_fuzzers with a bug found in OSS-Fuzz before."""
430
+ with tempfile.TemporaryDirectory() as tmp_dir:
431
+ workspace = os.path.join(tmp_dir, 'workspace')
432
+ shutil.copytree(TEST_DATA_PATH, workspace)
433
+ config = test_helpers.create_run_config(
434
+ fuzz_seconds=FUZZ_SECONDS,
435
+ workspace=workspace,
436
+ oss_fuzz_project_name=EXAMPLE_PROJECT)
437
+ result = run_fuzzers.run_fuzzers(config)
438
+ self.assertEqual(result, run_fuzzers.RunFuzzersResult.NO_BUG_FOUND)
439
+
440
+ def test_invalid_build(self):
441
+ """Tests run_fuzzers with an invalid ASAN build."""
442
+ with tempfile.TemporaryDirectory() as tmp_dir:
443
+ out_path = os.path.join(tmp_dir, 'build-out')
444
+ os.mkdir(out_path)
445
+ config = test_helpers.create_run_config(
446
+ fuzz_seconds=FUZZ_SECONDS,
447
+ workspace=tmp_dir,
448
+ oss_fuzz_project_name=EXAMPLE_PROJECT)
449
+ result = run_fuzzers.run_fuzzers(config)
450
+ self.assertEqual(result, run_fuzzers.RunFuzzersResult.ERROR)
451
+
452
+
453
+ class GetFuzzTargetRunnerTest(unittest.TestCase):
454
+ """Tests for get_fuzz_fuzz_target_runner."""
455
+
456
+ @parameterized.parameterized.expand([
457
+ ('batch', run_fuzzers.BatchFuzzTargetRunner),
458
+ ('code-change', run_fuzzers.CiFuzzTargetRunner),
459
+ ('coverage', run_fuzzers.CoverageTargetRunner)
460
+ ])
461
+ def test_get_fuzz_target_runner(self, mode, fuzz_target_runner_cls):
462
+ """Tests that get_fuzz_target_runner returns the correct runner based on the
463
+ specified mode."""
464
+ with tempfile.TemporaryDirectory() as tmp_dir:
465
+ run_config = test_helpers.create_run_config(
466
+ fuzz_seconds=FUZZ_SECONDS,
467
+ workspace=tmp_dir,
468
+ oss_fuzz_project_name='example',
469
+ mode=mode)
470
+ runner = run_fuzzers.get_fuzz_target_runner(run_config)
471
+ self.assertTrue(isinstance(runner, fuzz_target_runner_cls))
472
+
473
+
474
+ if __name__ == '__main__':
475
+ unittest.main()
local-test-zookeeper-delta-02/fuzz-tooling/infra/cifuzz/workspace_utils.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Module for representing the workspace directory which CIFuzz uses."""
15
+
16
+ import os
17
+ import shutil
18
+
19
+
20
+ class Workspace:
21
+ """Class representing the workspace directory."""
22
+
23
+ def __init__(self, config):
24
+ self.workspace = config.workspace
25
+
26
+ def initialize_dir(self, directory): # pylint: disable=no-self-use
27
+ """Creates directory if it doesn't already exist, otherwise does nothing."""
28
+ os.makedirs(directory, exist_ok=True)
29
+
30
+ @property
31
+ def repo_storage(self):
32
+ """The parent directory for repo storage."""
33
+ return os.path.join(self.workspace, 'storage')
34
+
35
+ @property
36
+ def out(self):
37
+ """The out directory used for storing the fuzzer build built by
38
+ build_fuzzers."""
39
+ # Don't use 'out' because it needs to be used by artifacts.
40
+ return os.path.join(self.workspace, 'build-out')
41
+
42
+ @property
43
+ def work(self):
44
+ """The directory used as the work directory for the fuzzer build/run."""
45
+ return os.path.join(self.workspace, 'work')
46
+
47
+ @property
48
+ def artifacts(self):
49
+ """The directory used to store artifacts for download by CI-system users."""
50
+ # This is hardcoded by a lot of clients, so we need to use this.
51
+ return os.path.join(self.workspace, 'out', 'artifacts')
52
+
53
+ @property
54
+ def clusterfuzz_build(self):
55
+ """The directory where builds from ClusterFuzz are stored."""
56
+ return os.path.join(self.workspace, 'cifuzz-prev-build')
57
+
58
+ @property
59
+ def clusterfuzz_coverage(self):
60
+ """The directory where builds from ClusterFuzz are stored."""
61
+ return os.path.join(self.workspace, 'cifuzz-prev-coverage')
62
+
63
+ @property
64
+ def coverage_report(self):
65
+ """The directory where coverage reports generated by cifuzz are put."""
66
+ return os.path.join(self.workspace, 'cifuzz-coverage')
67
+
68
+ @property
69
+ def corpora(self):
70
+ """The directory where corpora from ClusterFuzz are stored."""
71
+ return os.path.join(self.workspace, 'cifuzz-corpus')
72
+
73
+ @property
74
+ def pruned_corpora(self):
75
+ """The directory where pruned corpora are stored."""
76
+ return os.path.join(self.workspace, 'cifuzz-pruned-corpus')
77
+
78
+ @property
79
+ def sarif(self):
80
+ """The directory where sarif files are stored."""
81
+ return os.path.join(self.workspace, 'cifuzz-sarif')
82
+
83
+ def make_repo_for_sarif(self, repo_manager):
84
+ """Copies the repo over for the sarif upload GitHub action."""
85
+ return shutil.copytree(repo_manager.repo_dir, self.sarif, symlinks=True)