Kitxuuu commited on
Commit
4017fd7
·
verified ·
1 Parent(s): 75bf70b

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/__pycache__/constants.cpython-312.pyc +0 -0
  2. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/base-images/aixcc_build_all.sh +59 -0
  3. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/CHANGELOG +3 -0
  4. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/affected_fuzz_targets_test.py +113 -0
  5. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/build_fuzzers.py +217 -0
  6. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/build_fuzzers_test.py +403 -0
  7. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment_test.py +268 -0
  8. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/config_utils_test.py +200 -0
  9. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/continuous_integration.py +375 -0
  10. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/continuous_integration_test.py +88 -0
  11. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/docker.py +127 -0
  12. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/docker_test.py +119 -0
  13. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/example_cifuzz.yml +33 -0
  14. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/filestore_utils.py +48 -0
  15. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/http_utils_test.py +71 -0
  16. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/logs.py +25 -0
  17. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/requirements.txt +4 -0
  18. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/run_cifuzz.py +89 -0
  19. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/run_fuzzers_entrypoint.py +97 -0
  20. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/workspace_utils.py +85 -0
local-test-tika-full-01-vuln_1/fuzz-tooling/infra/__pycache__/constants.cpython-312.pyc ADDED
Binary file (802 Bytes). View file
 
local-test-tika-full-01-vuln_1/fuzz-tooling/infra/base-images/aixcc_build_all.sh ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash -eux
2
+
3
+ if [ "$1" = "--cache-from" ]; then
4
+ PULL_CACHE=1
5
+ shift
6
+ CACHE_TAG="${1//\//-}" # s/\//-/g -> for branch names that contain slashes
7
+ shift
8
+ elif [ "$1" = "--cache-to" ]; then
9
+ PUSH_CACHE=1
10
+ shift
11
+ CACHE_TAG="${1//\//-}" # s/\//-/g -> for branch names that contain slashes
12
+ shift
13
+ fi
14
+
15
+ ARG_TAG="$1"
16
+ shift
17
+
18
+ BASE_IMAGES=(
19
+ "ghcr.io/aixcc-finals/base-image infra/base-images/base-image"
20
+ "ghcr.io/aixcc-finals/base-clang infra/base-images/base-clang"
21
+ "ghcr.io/aixcc-finals/base-builder infra/base-images/base-builder"
22
+ "ghcr.io/aixcc-finals/base-builder-go infra/base-images/base-builder-go"
23
+ "ghcr.io/aixcc-finals/base-builder-jvm infra/base-images/base-builder-jvm"
24
+ "ghcr.io/aixcc-finals/base-builder-python infra/base-images/base-builder-python"
25
+ "ghcr.io/aixcc-finals/base-builder-rust infra/base-images/base-builder-rust"
26
+ "ghcr.io/aixcc-finals/base-builder-ruby infra/base-images/base-builder-ruby"
27
+ "ghcr.io/aixcc-finals/base-builder-swift infra/base-images/base-builder-swift"
28
+ "ghcr.io/aixcc-finals/base-runner infra/base-images/base-runner"
29
+ "ghcr.io/aixcc-finals/base-runner-debug infra/base-images/base-runner-debug"
30
+ )
31
+
32
+ for tuple in "${BASE_IMAGES[@]}"; do
33
+ read -r image path <<< "$tuple"
34
+
35
+ if [ "${PULL_CACHE+x}" ]; then
36
+
37
+ docker buildx build \
38
+ --build-arg IMG_TAG="${ARG_TAG}" \
39
+ --cache-from=type=registry,ref="${image}:${CACHE_TAG}" \
40
+ --tag "${image}:${ARG_TAG}" --push "$@" "${path}"
41
+
42
+ elif [ "${PUSH_CACHE+x}" ]; then
43
+
44
+ docker buildx build \
45
+ --build-arg IMG_TAG="${ARG_TAG}" \
46
+ --cache-from=type=registry,ref="${image}:${CACHE_TAG}" \
47
+ --cache-to=type=registry,ref="${image}:${CACHE_TAG}",mode=max \
48
+ --tag "${image}:${ARG_TAG}" --push "$@" "${path}"
49
+
50
+ else
51
+
52
+ docker buildx build \
53
+ --build-arg IMG_TAG="${ARG_TAG}" \
54
+ --tag "${image}:${ARG_TAG}" --push "$@" "${path}"
55
+
56
+ fi
57
+
58
+ done
59
+
local-test-tika-full-01-vuln_1/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-tika-full-01-vuln_1/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-tika-full-01-vuln_1/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-tika-full-01-vuln_1/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-tika-full-01-vuln_1/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-tika-full-01-vuln_1/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-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/continuous_integration.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Implementations for various CI systems."""
15
+
16
+ import os
17
+ import collections
18
+ import sys
19
+ import logging
20
+
21
+ # pylint: disable=wrong-import-position,import-error
22
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
23
+ import build_specified_commit
24
+ import docker
25
+ import helper
26
+ import repo_manager
27
+ import retry
28
+ import utils
29
+ import workspace_utils
30
+
31
+ # pylint: disable=too-few-public-methods
32
+
33
+ BuildPreparationResult = collections.namedtuple(
34
+ 'BuildPreparationResult', ['success', 'image_repo_path', 'repo_manager'])
35
+
36
+ _IMAGE_BUILD_TRIES = 3
37
+ _IMAGE_BUILD_BACKOFF = 2
38
+
39
+
40
+ def fix_git_repo_for_diff(repo_manager_obj):
41
+ """Fixes git repos cloned by the "checkout" action so that diffing works on
42
+ them."""
43
+ command = [
44
+ 'git', 'symbolic-ref', 'refs/remotes/origin/HEAD',
45
+ 'refs/remotes/origin/master'
46
+ ]
47
+ return utils.execute(command, location=repo_manager_obj.repo_dir)
48
+
49
+
50
+ class BaseCi:
51
+ """Class representing common CI functionality."""
52
+
53
+ def __init__(self, config):
54
+ self.config = config
55
+ self.workspace = workspace_utils.Workspace(config)
56
+ self._repo_dir = None
57
+
58
+ @property
59
+ def repo_dir(self):
60
+ """Returns the source repo path, if it has been checked out. None is
61
+ returned otherwise."""
62
+ raise NotImplementedError('Child class must implement method.')
63
+
64
+ def prepare_for_fuzzer_build(self):
65
+ """Builds the fuzzer builder image and gets the source code we need to
66
+ fuzz."""
67
+ raise NotImplementedError('Child class must implement method.')
68
+
69
+ def get_diff_base(self):
70
+ """Returns the base to diff against with git to get the change under
71
+ test."""
72
+ if self.config.base_ref:
73
+ logging.debug('Diffing against base_ref: %s.', self.config.base_ref)
74
+ return self.config.base_ref
75
+ if self.config.base_commit:
76
+ logging.debug('Diffing against base_commit: %s.', self.config.base_commit)
77
+ return self.config.base_commit
78
+ # TODO(metzman): Do we want this at all? What purpose does it serve? I guess
79
+ # it is a decent fallback when there is no base_commit or base_ref.
80
+ logging.debug('Diffing against origin.')
81
+ return 'origin'
82
+
83
+ def get_changed_code_under_test(self, repo_manager_obj):
84
+ """Returns the changed files that need to be tested."""
85
+ if self.config.base_ref:
86
+ repo_manager_obj.fetch_branch(self.config.base_ref)
87
+ fix_git_repo_for_diff(repo_manager_obj)
88
+ base = self.get_diff_base()
89
+ logging.info('Diffing against %s.', base)
90
+ # git diff <commit>... is equivalent to
91
+ # git diff $(git merge-base <commit> HEAD)
92
+ return repo_manager_obj.get_git_diff(base + '...')
93
+
94
+ def get_build_command(self, host_repo_path, image_repo_path):
95
+ """Returns the command for building the project that is run inside the
96
+ project builder container."""
97
+ raise NotImplementedError('Child class must implement method.')
98
+
99
+ def _build_external_project_docker_image(self, manager):
100
+ """Helper for child classes that builds an external project's docker image.
101
+ Returns a BuildPreparationResult indicating failure or success."""
102
+ build_integration_abs_path = os.path.join(
103
+ manager.repo_dir, self.config.build_integration_path)
104
+ if not build_external_project_docker_image(manager.repo_dir,
105
+ build_integration_abs_path):
106
+ logging.error('Failed to build external project.')
107
+ return get_build_preparation_failure()
108
+ image_repo_path = os.path.join('/src', self.config.project_repo_name)
109
+ return BuildPreparationResult(success=True,
110
+ image_repo_path=image_repo_path,
111
+ repo_manager=manager)
112
+
113
+ def _make_repo_storage_dir(self):
114
+ os.makedirs(self.workspace.repo_storage, exist_ok=True)
115
+
116
+ def _clone_repo_and_checkout(self, repo_url, repo_name):
117
+ """Helper for child classes that clones the git repo specified by |repo_url|
118
+ to |repo_name|, checks out the specified commit, and returns the
119
+ |manager|."""
120
+ self._make_repo_storage_dir()
121
+ # Checkout project's repo in the shared volume.
122
+ manager = repo_manager.clone_repo_and_get_manager(
123
+ repo_url,
124
+ self.workspace.repo_storage,
125
+ repo_name=repo_name,
126
+ username=self.config.actor,
127
+ password=self.config.token)
128
+ self._checkout_specified_commit(manager)
129
+ return manager
130
+
131
+ def _checkout_specified_commit(self, manager):
132
+ checkout_specified_commit(manager, self.config.pr_ref, self.config.git_sha)
133
+
134
+ def _detect_main_repo(self):
135
+ """Helper for child classes that detects the main repo and returns a tuple
136
+ containing the inffered url and path to the repo in the image."""
137
+ inferred_url, image_repo_path = build_specified_commit.detect_main_repo(
138
+ self.config.oss_fuzz_project_name,
139
+ repo_name=self.config.project_repo_name)
140
+ if not inferred_url or not image_repo_path:
141
+ logging.error('Could not detect repo.')
142
+ return inferred_url, image_repo_path
143
+
144
+ def _create_repo_manager_for_project_src_path(self):
145
+ """Returns a repo manager for |project_src_path|."""
146
+ return repo_manager.RepoManager(self.config.project_src_path)
147
+
148
+
149
+ def get_build_command():
150
+ """Returns the command to build the project inside the project builder
151
+ container."""
152
+ return 'compile'
153
+
154
+
155
+ def get_replace_repo_and_build_command(host_repo_path, image_repo_path):
156
+ """Returns the command to replace the repo located at |image_repo_path| with
157
+ |host_repo_path| and build the project inside the project builder
158
+ container."""
159
+ rm_path = os.path.join(image_repo_path, '*')
160
+ image_src_path = os.path.dirname(image_repo_path)
161
+ build_command = get_build_command()
162
+ command = (f'cd / && rm -rf {rm_path} && cp -r {host_repo_path} '
163
+ f'{image_src_path} && cd - && {build_command}')
164
+ return command
165
+
166
+
167
+ def get_ci(config):
168
+ """Determines what kind of CI is being used and returns the object
169
+ representing that system."""
170
+
171
+ if config.platform == config.Platform.EXTERNAL_GENERIC_CI:
172
+ # Non-OSS-Fuzz projects must bring their own source and their own build
173
+ # integration (which is relative to that source).
174
+ return ExternalGeneric(config)
175
+ if config.platform == config.Platform.EXTERNAL_GITHUB:
176
+ # Non-OSS-Fuzz projects must bring their own source and their own build
177
+ # integration (which is relative to that source).
178
+ return ExternalGithub(config)
179
+
180
+ if config.platform == config.Platform.INTERNAL_GENERIC_CI:
181
+ # Builds of OSS-Fuzz projects not hosted on Github must bring their own
182
+ # source since the checkout logic CIFuzz implements is github-specific.
183
+ # TODO(metzman): Consider moving Github-actions builds of OSS-Fuzz projects
184
+ # to this system to reduce implementation complexity.
185
+ return InternalGeneric(config)
186
+
187
+ return InternalGithub(config)
188
+
189
+
190
+ def checkout_specified_commit(repo_manager_obj, pr_ref, git_sha):
191
+ """Checks out the specified commit or pull request using
192
+ |repo_manager_obj|."""
193
+ try:
194
+ if pr_ref:
195
+ repo_manager_obj.checkout_pr(pr_ref)
196
+ else:
197
+ repo_manager_obj.checkout_commit(git_sha)
198
+ except (RuntimeError, ValueError):
199
+ logging.error(
200
+ 'Can not check out requested state %s. '
201
+ 'Using current repo state.', pr_ref or git_sha)
202
+
203
+
204
+ class GithubCiMixin:
205
+ """Mixin for Github based CI systems."""
206
+
207
+ def __init__(self, config):
208
+ super().__init__(config)
209
+ # Unlike in other classes, here _repo_dir is the parent directory of the
210
+ # repo, not its actual directory.
211
+ self._repo_dir = self.workspace.repo_storage
212
+
213
+ @property
214
+ def repo_dir(self):
215
+ """Returns the source repo path, if it has been checked out. None is
216
+ returned otherwise."""
217
+ if not os.path.exists(self._repo_dir):
218
+ logging.warning('Repo dir: %s does not exist.', self._repo_dir)
219
+ return None
220
+
221
+ # Note: this assumes there is only one repo checked out here.
222
+ listing = os.listdir(self._repo_dir)
223
+ if len(listing) != 1:
224
+ raise RuntimeError('Invalid repo directory.')
225
+
226
+ repo_path = os.path.join(self._repo_dir, listing[0])
227
+ if not os.path.isdir(repo_path):
228
+ raise RuntimeError('Repo is not a directory.')
229
+
230
+ return repo_path
231
+
232
+
233
+ class InternalGithub(GithubCiMixin, BaseCi):
234
+ """Class representing CI for an OSS-Fuzz project on Github Actions."""
235
+
236
+ def _copy_repo_from_image(self, image_repo_path):
237
+ self._make_repo_storage_dir()
238
+ repo_name = os.path.basename(image_repo_path)
239
+ host_repo_path = os.path.join(self._repo_dir, repo_name)
240
+ bash_command = f'cp -r {image_repo_path} {host_repo_path}'
241
+ docker_args, _ = docker.get_base_docker_run_args(
242
+ self.workspace, self.config.sanitizer, self.config.language,
243
+ self.config.architecture, self.config.docker_in_docker)
244
+ docker_args.extend([
245
+ docker.get_project_image_name(self.config.oss_fuzz_project_name),
246
+ '/bin/bash', '-c', bash_command
247
+ ])
248
+ if not helper.docker_run(docker_args):
249
+ raise RuntimeError('Failed to copy repo.')
250
+ return repo_manager.RepoManager(host_repo_path)
251
+
252
+ def prepare_for_fuzzer_build(self):
253
+ """Builds the fuzzer builder image, checks out the pull request/commit and
254
+ returns the BuildPreparationResult."""
255
+ logging.info('InternalGithub: preparing for fuzzer build.')
256
+ assert self.config.pr_ref or self.config.git_sha
257
+ # _detect_main_repo builds the image as a side effect.
258
+ _, image_repo_path = self._detect_main_repo()
259
+ if not image_repo_path:
260
+ return get_build_preparation_failure()
261
+
262
+ # Use the same name used in the docker image so we can overwrite it.
263
+ manager = self._copy_repo_from_image(image_repo_path)
264
+ self._checkout_specified_commit(manager)
265
+ return BuildPreparationResult(success=True,
266
+ image_repo_path=image_repo_path,
267
+ repo_manager=manager)
268
+
269
+ def get_build_command(self, host_repo_path, image_repo_path): # pylint: disable=no-self-use
270
+ """Returns the command for building the project that is run inside the
271
+ project builder container. Command also replaces |image_repo_path| with
272
+ |host_repo_path|."""
273
+ return get_replace_repo_and_build_command(host_repo_path, image_repo_path)
274
+
275
+
276
+ def get_build_preparation_failure():
277
+ """Returns a BuildPreparationResult indicating failure."""
278
+ return BuildPreparationResult(success=False,
279
+ image_repo_path=None,
280
+ repo_manager=None)
281
+
282
+
283
+ class InternalGeneric(BaseCi):
284
+ """Class representing CI for an OSS-Fuzz project on a CI other than Github
285
+ actions."""
286
+
287
+ def __init__(self, config):
288
+ super().__init__(config)
289
+ self._repo_dir = config.project_src_path
290
+
291
+ @property
292
+ def repo_dir(self):
293
+ """Returns the source repo path, if it has been checked out. None is
294
+ returned otherwise."""
295
+ return self._repo_dir
296
+
297
+ def prepare_for_fuzzer_build(self):
298
+ """Builds the project builder image for an OSS-Fuzz project outside of
299
+ GitHub actions. Returns the repo_manager. Does not checkout source code
300
+ since external projects are expected to bring their own source code to
301
+ CIFuzz."""
302
+ logging.info('InternalGeneric: preparing for fuzzer build.')
303
+ # detect_main_repo builds the image as a side effect.
304
+ _, image_repo_path = self._detect_main_repo()
305
+
306
+ if not image_repo_path:
307
+ return get_build_preparation_failure()
308
+
309
+ manager = self._create_repo_manager_for_project_src_path()
310
+ return BuildPreparationResult(success=True,
311
+ image_repo_path=image_repo_path,
312
+ repo_manager=manager)
313
+
314
+ def get_build_command(self, host_repo_path, image_repo_path): # pylint: disable=no-self-use
315
+ """Returns the command for building the project that is run inside the
316
+ project builder container. Command also replaces |image_repo_path| with
317
+ |host_repo_path|."""
318
+ return get_replace_repo_and_build_command(host_repo_path, image_repo_path)
319
+
320
+
321
+ @retry.wrap(_IMAGE_BUILD_TRIES, _IMAGE_BUILD_BACKOFF)
322
+ def build_external_project_docker_image(project_src, build_integration_path):
323
+ """Builds the project builder image for an external (non-OSS-Fuzz) project.
324
+ Returns True on success."""
325
+ dockerfile_path = os.path.join(build_integration_path, 'Dockerfile')
326
+ command = [
327
+ '-t', docker.EXTERNAL_PROJECT_IMAGE, '-f', dockerfile_path, project_src
328
+ ]
329
+ return helper.docker_build(command)
330
+
331
+
332
+ class ExternalGeneric(BaseCi):
333
+ """CI implementation for generic CI for external (non-OSS-Fuzz) projects."""
334
+
335
+ def __init__(self, config):
336
+ super().__init__(config)
337
+ self._repo_dir = config.project_src_path
338
+
339
+ @property
340
+ def repo_dir(self):
341
+ """Returns the source repo path, if it has been checked out. None is
342
+ returned otherwise."""
343
+ return self._repo_dir
344
+
345
+ def prepare_for_fuzzer_build(self):
346
+ logging.info('ExternalGeneric: preparing for fuzzer build.')
347
+ manager = self._create_repo_manager_for_project_src_path()
348
+ return self._build_external_project_docker_image(manager)
349
+
350
+ def get_build_command(self, host_repo_path, image_repo_path): # pylint: disable=no-self-use
351
+ """Returns the command for building the project that is run inside the
352
+ project builder container."""
353
+ return get_build_command()
354
+
355
+
356
+ class ExternalGithub(GithubCiMixin, BaseCi):
357
+ """Class representing CI for a non-OSS-Fuzz project on Github Actions."""
358
+
359
+ def prepare_for_fuzzer_build(self):
360
+ """Builds the project builder image for a non-OSS-Fuzz project on GitHub
361
+ actions. Sets the repo manager. Does not checkout source code since external
362
+ projects are expected to bring their own source code to CIFuzz. Returns True
363
+ on success."""
364
+ logging.info('ExternalGithub: preparing for fuzzer build.')
365
+ # Checkout before building, so we don't need to rely on copying the source
366
+ # from the image.
367
+ # TODO(metzman): Figure out if we want second copy at all.
368
+ manager = self._clone_repo_and_checkout(self.config.git_url,
369
+ self.config.project_repo_name)
370
+ return self._build_external_project_docker_image(manager)
371
+
372
+ def get_build_command(self, host_repo_path, image_repo_path): # pylint: disable=no-self-use
373
+ """Returns the command for building the project that is run inside the
374
+ project builder container."""
375
+ return get_build_command()
local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/continuous_integration_test.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 continuous_integration_module."""
15
+ import os
16
+ import sys
17
+ import unittest
18
+ from unittest import mock
19
+
20
+ import continuous_integration
21
+ import docker
22
+
23
+ # pylint: disable=wrong-import-position,import-error
24
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
25
+
26
+ import repo_manager
27
+
28
+ # pylint: disable=no-self-use
29
+
30
+
31
+ class FixGitRepoForDiffTest(unittest.TestCase):
32
+ """Tests for fix_git_repo_for_diff."""
33
+
34
+ @mock.patch('utils.execute')
35
+ def test_fix_git_repo_for_diff(self, mock_execute):
36
+ """Tests that fix_git_repo_for_diff works as intended."""
37
+ repo_dir = '/dir'
38
+ repo_manager_obj = repo_manager.RepoManager(repo_dir)
39
+ continuous_integration.fix_git_repo_for_diff(repo_manager_obj)
40
+ expected_command = [
41
+ 'git', 'symbolic-ref', 'refs/remotes/origin/HEAD',
42
+ 'refs/remotes/origin/master'
43
+ ]
44
+
45
+ mock_execute.assert_called_with(expected_command, location=repo_dir)
46
+
47
+
48
+ class GetBuildCommand(unittest.TestCase):
49
+ """Tests for get_build_command."""
50
+
51
+ def test_build_command(self):
52
+ """Tests that get_build_command works as intended."""
53
+ self.assertEqual(continuous_integration.get_build_command(), 'compile')
54
+
55
+
56
+ class GetReplaceRepoAndBuildCommand(unittest.TestCase):
57
+ """Tests for get_replace_repo_and_build_command."""
58
+
59
+ def test_get_replace_repo_and_build_command(self):
60
+ """Tests that get_replace_repo_and_build_command works as intended."""
61
+ host_repo_path = '/path/on/host/to/repo'
62
+ image_repo_path = '/src/repo'
63
+ command = continuous_integration.get_replace_repo_and_build_command(
64
+ host_repo_path, image_repo_path)
65
+ expected_command = ('cd / && rm -rf /src/repo/* && '
66
+ 'cp -r /path/on/host/to/repo /src && cd - '
67
+ '&& compile')
68
+ self.assertEqual(command, expected_command)
69
+
70
+
71
+ class BuildExternalProjetDockerImage(unittest.TestCase):
72
+ """Tests for build_external_project_docker_image."""
73
+
74
+ @mock.patch('helper.docker_build')
75
+ def test_build_external_project_docker_image(self, mock_docker_build):
76
+ """Tests that build_external_project_docker_image works as intended."""
77
+ build_integration_path = '.clusterfuzzlite'
78
+ project_src = '/path/to/project/src'
79
+ continuous_integration.build_external_project_docker_image(
80
+ project_src, build_integration_path)
81
+
82
+ mock_docker_build.assert_called_with([
83
+ '-t', docker.EXTERNAL_PROJECT_IMAGE, '-f',
84
+ os.path.join('.clusterfuzzlite', 'Dockerfile'), project_src
85
+ ])
86
+
87
+
88
+ # TODO(metzman): Write tests for the rest of continuous_integration.py.
local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/docker.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 docker."""
15
+ import logging
16
+ import os
17
+ import sys
18
+ import uuid
19
+
20
+ # pylint: disable=wrong-import-position,import-error
21
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
22
+
23
+ import constants
24
+ import utils
25
+ import environment
26
+
27
+ BASE_BUILDER_TAG = 'ghcr.io/aixcc-finals/base-builder'
28
+ PROJECT_TAG_PREFIX = 'gcr.io/oss-fuzz/'
29
+
30
+ # Default fuzz configuration.
31
+ _DEFAULT_DOCKER_RUN_ARGS = [
32
+ '-e', 'FUZZING_ENGINE=' + constants.DEFAULT_ENGINE, '-e', 'CIFUZZ=True'
33
+ ]
34
+
35
+ UNIQUE_ID_SUFFIX = '-' + uuid.uuid4().hex
36
+
37
+ # TODO(metzman): Make run_fuzzers able to delete this image.
38
+ EXTERNAL_PROJECT_IMAGE = 'external-cfl-project' + UNIQUE_ID_SUFFIX
39
+
40
+ _DEFAULT_DOCKER_RUN_COMMAND = [
41
+ 'docker',
42
+ 'run',
43
+ '--rm',
44
+ '--privileged',
45
+ ]
46
+
47
+
48
+ def get_docker_env_vars(env_mapping):
49
+ """Returns a list of docker arguments that sets each key in |env_mapping| as
50
+ an env var and the value of that key in |env_mapping| as the value."""
51
+ env_var_args = []
52
+ for env_var, env_var_val in env_mapping.items():
53
+ env_var_args.extend(['-e', f'{env_var}={env_var_val}'])
54
+ return env_var_args
55
+
56
+
57
+ def get_project_image_name(project):
58
+ """Returns the name of the project builder image for |project_name|."""
59
+ # TODO(jonathanmetzman): We may need unique names to support parallel fuzzing
60
+ # for CIFuzz (like CFL supports). Don't do this for now because no one has
61
+ # asked for it and build_specified_commit would need to be modified to support
62
+ # this.
63
+ if project:
64
+ return PROJECT_TAG_PREFIX + project
65
+
66
+ return EXTERNAL_PROJECT_IMAGE
67
+
68
+
69
+ def delete_images(images):
70
+ """Deletes |images|."""
71
+ command = ['docker', 'rmi', '-f'] + images
72
+ utils.execute(command)
73
+ utils.execute(['docker', 'builder', 'prune', '-f'])
74
+
75
+
76
+ def get_base_docker_run_args(workspace,
77
+ sanitizer=constants.DEFAULT_SANITIZER,
78
+ language=constants.DEFAULT_LANGUAGE,
79
+ architecture=constants.DEFAULT_ARCHITECTURE,
80
+ docker_in_docker=False):
81
+ """Returns arguments that should be passed to every invocation of 'docker
82
+ run'."""
83
+ docker_args = _DEFAULT_DOCKER_RUN_ARGS.copy()
84
+ env_mapping = {
85
+ 'SANITIZER': sanitizer,
86
+ 'ARCHITECTURE': architecture,
87
+ 'FUZZING_LANGUAGE': language,
88
+ 'OUT': workspace.out
89
+ }
90
+ docker_args += get_docker_env_vars(env_mapping)
91
+ docker_container = environment.get('CFL_CONTAINER_ID',
92
+ utils.get_container_name())
93
+ logging.info('Docker container: %s.', docker_container)
94
+ if docker_container and not docker_in_docker:
95
+ # Don't map specific volumes if in a docker container, it breaks when
96
+ # running a sibling container.
97
+ docker_args += ['--volumes-from', docker_container]
98
+ else:
99
+ docker_args += _get_args_mapping_host_path_to_container(workspace.workspace)
100
+ return docker_args, docker_container
101
+
102
+
103
+ def get_base_docker_run_command(workspace,
104
+ sanitizer=constants.DEFAULT_SANITIZER,
105
+ language=constants.DEFAULT_LANGUAGE,
106
+ architecture=constants.DEFAULT_ARCHITECTURE,
107
+ docker_in_docker=False):
108
+ """Returns part of the command that should be used everytime 'docker run' is
109
+ invoked."""
110
+ docker_args, docker_container = get_base_docker_run_args(
111
+ workspace,
112
+ sanitizer,
113
+ language,
114
+ architecture,
115
+ docker_in_docker=docker_in_docker)
116
+ command = _DEFAULT_DOCKER_RUN_COMMAND.copy() + docker_args
117
+ return command, docker_container
118
+
119
+
120
+ def _get_args_mapping_host_path_to_container(host_path, container_path=None):
121
+ """Get arguments to docker run that will map |host_path| a path on the host to
122
+ a path in the container. If |container_path| is specified, that path is mapped
123
+ to. If not, then |host_path| is mapped to itself in the container."""
124
+ # WARNING: Do not use this function when running in production (and
125
+ # --volumes-from) is used for mapping volumes. It will break production.
126
+ container_path = host_path if container_path is None else container_path
127
+ return ['-v', f'{host_path}:{container_path}']
local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/docker_test.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 the functionality of the docker module."""
15
+ import unittest
16
+ from unittest import mock
17
+
18
+ import docker
19
+ import test_helpers
20
+ import workspace_utils
21
+
22
+ CONTAINER_NAME = 'example-container'
23
+ config = test_helpers.create_run_config(oss_fuzz_project_name='project',
24
+ workspace='/workspace')
25
+ config.workspace = '/workspace'
26
+ WORKSPACE = workspace_utils.Workspace(config)
27
+ SANITIZER = 'example-sanitizer'
28
+ LANGUAGE = 'example-language'
29
+
30
+
31
+ class GetProjectImageTest(unittest.TestCase):
32
+ """Tests for get_project_image."""
33
+
34
+ def test_get_project_image(self):
35
+ """Tests that get_project_image_name works as intended."""
36
+ project = 'my-project'
37
+ self.assertEqual(docker.get_project_image_name(project),
38
+ 'gcr.io/oss-fuzz/my-project')
39
+
40
+
41
+ class GetDeleteImagesTest(unittest.TestCase):
42
+ """Tests for delete_images."""
43
+
44
+ @mock.patch('utils.execute')
45
+ def test_delete_images(self, mock_execute): # pylint: disable=no-self-use
46
+ """Tests that get_project_image_name works as intended."""
47
+ images = ['image']
48
+ docker.delete_images(images)
49
+ expected_calls = [
50
+ mock.call(['docker', 'rmi', '-f'] + images),
51
+ mock.call(['docker', 'builder', 'prune', '-f'])
52
+ ]
53
+
54
+ mock_execute.assert_has_calls(expected_calls)
55
+
56
+
57
+ class GetBaseDockerRunArgsTest(unittest.TestCase):
58
+ """Tests get_base_docker_run_args."""
59
+
60
+ @mock.patch('utils.get_container_name', return_value=CONTAINER_NAME)
61
+ def test_get_base_docker_run_args_container(self, _):
62
+ """Tests that get_base_docker_run_args works as intended when inside a
63
+ container."""
64
+ docker_args, docker_container = docker.get_base_docker_run_args(
65
+ WORKSPACE, SANITIZER, LANGUAGE)
66
+ self.assertEqual(docker_container, CONTAINER_NAME)
67
+ expected_docker_args = []
68
+ expected_docker_args = [
69
+ '-e',
70
+ 'FUZZING_ENGINE=libfuzzer',
71
+ '-e',
72
+ 'CIFUZZ=True',
73
+ '-e',
74
+ f'SANITIZER={SANITIZER}',
75
+ '-e',
76
+ 'ARCHITECTURE=x86_64',
77
+ '-e',
78
+ f'FUZZING_LANGUAGE={LANGUAGE}',
79
+ '-e',
80
+ f'OUT={WORKSPACE.out}',
81
+ '--volumes-from',
82
+ CONTAINER_NAME,
83
+ ]
84
+ self.assertEqual(docker_args, expected_docker_args)
85
+
86
+ @mock.patch('utils.get_container_name', return_value=None)
87
+ def test_get_base_docker_run_args_no_container(self, _):
88
+ """Tests that get_base_docker_run_args works as intended when not inside a
89
+ container."""
90
+ docker_args, docker_container = docker.get_base_docker_run_args(
91
+ WORKSPACE, SANITIZER, LANGUAGE)
92
+ self.assertEqual(docker_container, None)
93
+ expected_docker_args = [
94
+ '-e', 'FUZZING_ENGINE=libfuzzer', '-e', 'CIFUZZ=True', '-e',
95
+ f'SANITIZER={SANITIZER}', '-e', 'ARCHITECTURE=x86_64', '-e',
96
+ f'FUZZING_LANGUAGE={LANGUAGE}', '-e', f'OUT={WORKSPACE.out}', '-v',
97
+ f'{WORKSPACE.workspace}:{WORKSPACE.workspace}'
98
+ ]
99
+ self.assertEqual(docker_args, expected_docker_args)
100
+
101
+
102
+ class GetBaseDockerRunCommandTest(unittest.TestCase):
103
+ """Tests get_base_docker_run_args."""
104
+
105
+ @mock.patch('utils.get_container_name', return_value=None)
106
+ def test_get_base_docker_run_command_no_container(self, _):
107
+ """Tests that get_base_docker_run_args works as intended when not inside a
108
+ container."""
109
+ docker_args, docker_container = docker.get_base_docker_run_command(
110
+ WORKSPACE, SANITIZER, LANGUAGE)
111
+ self.assertEqual(docker_container, None)
112
+ expected_docker_command = [
113
+ 'docker', 'run', '--rm', '--privileged', '-e',
114
+ 'FUZZING_ENGINE=libfuzzer', '-e', 'CIFUZZ=True', '-e',
115
+ f'SANITIZER={SANITIZER}', '-e', 'ARCHITECTURE=x86_64', '-e',
116
+ f'FUZZING_LANGUAGE={LANGUAGE}', '-e', f'OUT={WORKSPACE.out}', '-v',
117
+ f'{WORKSPACE.workspace}:{WORKSPACE.workspace}'
118
+ ]
119
+ self.assertEqual(docker_args, expected_docker_command)
local-test-tika-full-01-vuln_1/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-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/filestore_utils.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
+ """External filestore interface. Cannot be depended on by filestore code."""
15
+ import filestore
16
+ import filestore.filesystem
17
+ import filestore.git
18
+ import filestore.github_actions
19
+ import filestore.gsutil
20
+ import filestore.no_filestore
21
+ import filestore.gitlab
22
+
23
+ FILESTORE_MAPPING = {
24
+ 'filesystem': filestore.filesystem.FilesystemFilestore,
25
+ 'gsutil': filestore.gsutil.GSUtilFilestore,
26
+ 'github-actions': filestore.github_actions.GithubActionsFilestore,
27
+ 'git': filestore.git.GitFilestore,
28
+ # TODO(metzman): Change to "no-filestore"
29
+ 'no_filestore': filestore.no_filestore.NoFilestore,
30
+ 'gitlab': filestore.gitlab.GitlabFilestore,
31
+ }
32
+
33
+
34
+ def get_filestore(config):
35
+ """Returns the correct filestore object based on the platform in |config|.
36
+ Raises an exception if there is no correct filestore for the platform."""
37
+ if config.platform == config.Platform.EXTERNAL_GITHUB:
38
+ ci_filestore = filestore.github_actions.GithubActionsFilestore(config)
39
+ if not config.git_store_repo:
40
+ return ci_filestore
41
+
42
+ return filestore.git.GitFilestore(config, ci_filestore)
43
+
44
+ filestore_cls = FILESTORE_MAPPING.get(config.filestore)
45
+ if filestore_cls is None:
46
+ raise filestore.FilestoreError(
47
+ f'Filestore: {config.filestore} doesn\'t exist.')
48
+ return filestore_cls(config)
local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/http_utils_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 http_utils.py"""
15
+
16
+ import unittest
17
+ from unittest import mock
18
+
19
+ from pyfakefs import fake_filesystem_unittest
20
+
21
+ import http_utils
22
+
23
+ mock_get_response = mock.MagicMock(status_code=200, content=b'')
24
+
25
+
26
+ class DownloadUrlTest(unittest.TestCase):
27
+ """Tests that download_url works."""
28
+ URL = 'https://example.com/file'
29
+ FILE_PATH = '/tmp/file'
30
+
31
+ @mock.patch('time.sleep')
32
+ @mock.patch('requests.get', return_value=mock_get_response)
33
+ def test_download_url_no_error(self, mock_urlretrieve, _):
34
+ """Tests that download_url works when there is no error."""
35
+ self.assertTrue(http_utils.download_url(self.URL, self.FILE_PATH))
36
+ self.assertEqual(1, mock_urlretrieve.call_count)
37
+
38
+ @mock.patch('time.sleep')
39
+ @mock.patch('logging.error')
40
+ @mock.patch('requests.get',
41
+ return_value=mock.MagicMock(status_code=404, content=b''))
42
+ def test_download_url_http_error(self, mock_get, mock_error, _):
43
+ """Tests that download_url doesn't retry when there is an HTTP error."""
44
+ self.assertFalse(http_utils.download_url(self.URL, self.FILE_PATH))
45
+ mock_error.assert_called_with(
46
+ 'Unable to download from: %s. Code: %d. Content: %s.', self.URL, 404,
47
+ b'')
48
+ self.assertEqual(1, mock_get.call_count)
49
+
50
+ @mock.patch('time.sleep')
51
+ @mock.patch('requests.get', side_effect=ConnectionResetError)
52
+ def test_download_url_connection_error(self, mock_get, mock_sleep):
53
+ """Tests that download_url doesn't retry when there is an HTTP error."""
54
+ self.assertFalse(http_utils.download_url(self.URL, self.FILE_PATH))
55
+ self.assertEqual(4, mock_get.call_count)
56
+ self.assertEqual(3, mock_sleep.call_count)
57
+
58
+
59
+ class DownloadAndUnpackZipTest(fake_filesystem_unittest.TestCase):
60
+ """Tests download_and_unpack_zip."""
61
+
62
+ def setUp(self):
63
+ self.setUpPyfakefs()
64
+
65
+ @mock.patch('requests.get', return_value=mock_get_response)
66
+ def test_bad_zip_download(self, _):
67
+ """Tests download_and_unpack_zip returns none when a bad zip is passed."""
68
+ self.fs.create_file('/url_tmp.zip', contents='Test file.')
69
+ self.assertFalse(
70
+ http_utils.download_and_unpack_zip('/not/a/real/url',
71
+ '/extract-directory'))
local-test-tika-full-01-vuln_1/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-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ clusterfuzz==2.5.9
2
+ requests==2.28.0
3
+ protobuf==3.20.2
4
+ gsutil==5.20
local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/run_cifuzz.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Script for running CIFuzz end-to-end. This is meant to work outside any
15
+ docker image. This cannot depend on any CIFuzz code or third party packages."""
16
+ import os
17
+ import subprocess
18
+ import sys
19
+ import tempfile
20
+ import logging
21
+
22
+ INFRA_DIR = os.path.dirname(os.path.dirname(__file__))
23
+ DEFAULT_ENVS = [('DRY_RUN', '0'), ('SANITIZER', 'address')]
24
+ BASE_CIFUZZ_DOCKER_TAG = 'ghcr.io/aixcc-finals'
25
+
26
+
27
+ def set_default_env_var_if_unset(env_var, default_value):
28
+ """Sets the value of |env_var| in the environment to |default_value| if it was
29
+ not already set."""
30
+ if env_var not in os.environ:
31
+ os.environ[env_var] = default_value
32
+
33
+
34
+ def docker_run(name, workspace, project_src_path):
35
+ """Runs a CIFuzz docker container with |name|."""
36
+ command = [
37
+ 'docker', 'run', '--name', name, '--rm', '-e', 'PROJECT_SRC_PATH', '-e',
38
+ 'OSS_FUZZ_PROJECT_NAME', '-e', 'WORKSPACE', '-e', 'REPOSITORY', '-e',
39
+ 'DRY_RUN', '-e', 'CI', '-e', 'SANITIZER', '-e', 'GIT_SHA', '-e',
40
+ 'FILESTORE', '-e', 'NO_CLUSTERFUZZ_DEPLOYMENT'
41
+ ]
42
+ if project_src_path:
43
+ command += ['-v', f'{project_src_path}:{project_src_path}']
44
+ command += [
45
+ '-v', '/var/run/docker.sock:/var/run/docker.sock', '-v',
46
+ f'{workspace}:{workspace}', f'{BASE_CIFUZZ_DOCKER_TAG}/{name}'
47
+ ]
48
+ print('Running docker command:', command)
49
+ subprocess.run(command, check=True)
50
+
51
+
52
+ def docker_build(image):
53
+ """Builds the CIFuzz |image|. Only suitable for building CIFuzz images."""
54
+ command = [
55
+ 'docker', 'build', '-t', f'{BASE_CIFUZZ_DOCKER_TAG}/{image}', '--file',
56
+ f'{image}.Dockerfile', '.'
57
+ ]
58
+ subprocess.run(command, check=True, cwd=INFRA_DIR)
59
+
60
+
61
+ def main():
62
+ """Builds and runs fuzzers using CIFuzz."""
63
+ for env_var, default_value in DEFAULT_ENVS:
64
+ set_default_env_var_if_unset(env_var, default_value)
65
+
66
+ repository = os.getenv('REPOSITORY')
67
+ assert repository
68
+
69
+ project_src_path = os.getenv('PROJECT_SRC_PATH')
70
+
71
+ with tempfile.TemporaryDirectory() as temp_dir:
72
+ if 'WORKSPACE' not in os.environ:
73
+ os.environ['WORKSPACE'] = temp_dir
74
+
75
+ workspace = os.environ['WORKSPACE']
76
+
77
+ docker_build('build_fuzzers')
78
+ docker_run('build_fuzzers', workspace, project_src_path)
79
+ docker_build('run_fuzzers')
80
+ try:
81
+ docker_run('run_fuzzers', workspace, project_src_path)
82
+ except subprocess.CalledProcessError:
83
+ logging.error('run_fuzzers failed.')
84
+ return 1
85
+ return 0
86
+
87
+
88
+ if __name__ == '__main__':
89
+ sys.exit(main())
local-test-tika-full-01-vuln_1/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-tika-full-01-vuln_1/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)