Kitxuuu commited on
Commit
316148b
·
verified ·
1 Parent(s): 11276f1

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. local-test-tika-full-01-vuln_6/fuzz-tooling/infra/base-images/aixcc_build_all.sh +59 -0
  2. local-test-tika-full-01-vuln_6/fuzz-tooling/infra/base-images/all.sh +28 -0
  3. local-test-tika-full-01-vuln_6/fuzz-tooling/infra/ci/build.py +292 -0
  4. local-test-tika-full-01-vuln_6/fuzz-tooling/infra/ci/requirements.txt +9 -0
  5. local-test-tika-full-01-vuln_6/fuzz-tooling/infra/cifuzz/build-images.sh +34 -0
  6. local-test-tika-full-01-vuln_6/fuzz-tooling/infra/cifuzz/build_fuzzers_test.py +403 -0
  7. local-test-tika-full-01-vuln_6/fuzz-tooling/infra/cifuzz/cifuzz_combined_entrypoint.py +40 -0
  8. local-test-tika-full-01-vuln_6/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment.py +385 -0
  9. local-test-tika-full-01-vuln_6/fuzz-tooling/infra/cifuzz/continuous_integration.py +375 -0
  10. local-test-tika-full-01-vuln_6/fuzz-tooling/infra/cifuzz/continuous_integration_test.py +88 -0
  11. local-test-tika-full-01-vuln_6/fuzz-tooling/infra/cifuzz/docker_test.py +119 -0
  12. local-test-tika-full-01-vuln_6/fuzz-tooling/infra/cifuzz/http_utils_test.py +71 -0
  13. local-test-tika-full-01-vuln_6/fuzz-tooling/infra/cifuzz/requirements.txt +4 -0
  14. local-test-tika-full-01-vuln_6/fuzz-tooling/infra/cifuzz/run_cifuzz.py +89 -0
  15. local-test-tika-full-01-vuln_6/fuzz-tooling/infra/cifuzz/test_helpers.py +117 -0
  16. local-test-tika-full-01-vuln_6/fuzz-tooling/infra/cifuzz/workspace_utils.py +85 -0
  17. local-test-tika-full-01-vuln_6/fuzz-tooling/infra/tools/hold_back_images.py +128 -0
  18. local-test-tika-full-01-vuln_6/fuzz-tooling/tools/vscode-extension/src/commands/cmdBuildFuzzerFromWorkspaceCFLite.ts +49 -0
  19. local-test-tika-full-01-vuln_6/fuzz-tooling/tools/vscode-extension/src/commands/cmdSetOSSFuzzPath.ts +59 -0
  20. local-test-tika-full-01-vuln_6/fuzz-tooling/tools/vscode-extension/src/commands/cmdTestFuzzer.ts +90 -0
local-test-tika-full-01-vuln_6/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_6/fuzz-tooling/infra/base-images/all.sh ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash -eux
2
+ # Copyright 2016 Google Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ ################################################################################
17
+
18
+ docker build --pull -t ghcr.io/aixcc-finals/base-image "$@" infra/base-images/base-image
19
+ docker build -t ghcr.io/aixcc-finals/base-clang "$@" infra/base-images/base-clang
20
+ docker build -t ghcr.io/aixcc-finals/base-builder "$@" infra/base-images/base-builder
21
+ docker build -t ghcr.io/aixcc-finals/base-builder-go "$@" infra/base-images/base-builder-go
22
+ docker build -t ghcr.io/aixcc-finals/base-builder-jvm "$@" infra/base-images/base-builder-jvm
23
+ docker build -t ghcr.io/aixcc-finals/base-builder-python "$@" infra/base-images/base-builder-python
24
+ docker build -t ghcr.io/aixcc-finals/base-builder-rust "$@" infra/base-images/base-builder-rust
25
+ docker build -t ghcr.io/aixcc-finals/base-builder-ruby "$@" infra/base-images/base-builder-ruby
26
+ docker build -t ghcr.io/aixcc-finals/base-builder-swift "$@" infra/base-images/base-builder-swift
27
+ docker build -t ghcr.io/aixcc-finals/base-runner "$@" infra/base-images/base-runner
28
+ docker build -t ghcr.io/aixcc-finals/base-runner-debug "$@" infra/base-images/base-runner-debug
local-test-tika-full-01-vuln_6/fuzz-tooling/infra/ci/build.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Copyright 2019 Google Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ ################################################################################
17
+ """Build modified projects."""
18
+
19
+ from __future__ import print_function
20
+
21
+ import enum
22
+ import os
23
+ import re
24
+ import sys
25
+ import subprocess
26
+ import yaml
27
+
28
+ # pylint: disable=wrong-import-position,import-error
29
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
30
+
31
+ import constants
32
+
33
+ CANARY_PROJECT = 'skcms'
34
+
35
+ DEFAULT_ARCHITECTURES = ['x86_64']
36
+ DEFAULT_ENGINES = ['afl', 'honggfuzz', 'libfuzzer', 'centipede']
37
+ DEFAULT_SANITIZERS = ['address', 'undefined']
38
+
39
+
40
+ def get_changed_files_output():
41
+ """Returns the output of a git command that discovers changed files."""
42
+ branch_commit_hash = subprocess.check_output(
43
+ ['git', 'merge-base', 'HEAD', 'origin/HEAD']).strip().decode()
44
+
45
+ return subprocess.check_output(
46
+ ['git', 'diff', '--name-only', branch_commit_hash + '..']).decode()
47
+
48
+
49
+ def get_modified_buildable_projects():
50
+ """Returns a list of all the projects modified in this commit that have a
51
+ build.sh file."""
52
+ git_output = get_changed_files_output()
53
+ projects_regex = '.*projects/(?P<name>.*)/.*\n'
54
+ modified_projects = set(re.findall(projects_regex, git_output))
55
+ projects_dir = os.path.join(get_oss_fuzz_root(), 'projects')
56
+ # Filter out projects without Dockerfile files since new projects and reverted
57
+ # projects frequently don't have them. In these cases we don't want Travis's
58
+ # builds to fail.
59
+ modified_buildable_projects = []
60
+ for project in modified_projects:
61
+ if not os.path.exists(os.path.join(projects_dir, project, 'Dockerfile')):
62
+ print('Project {0} does not have Dockerfile. skipping build.'.format(
63
+ project))
64
+ continue
65
+ modified_buildable_projects.append(project)
66
+ return modified_buildable_projects
67
+
68
+
69
+ def get_oss_fuzz_root():
70
+ """Get the absolute path of the root of the oss-fuzz checkout."""
71
+ script_path = os.path.realpath(__file__)
72
+ return os.path.abspath(
73
+ os.path.dirname(os.path.dirname(os.path.dirname(script_path))))
74
+
75
+
76
+ def execute_helper_command(helper_command):
77
+ """Execute |helper_command| using helper.py."""
78
+ root = get_oss_fuzz_root()
79
+ script_path = os.path.join(root, 'infra', 'helper.py')
80
+ command = ['python', script_path] + helper_command
81
+ print('Running command: %s' % ' '.join(command))
82
+ subprocess.check_call(command)
83
+
84
+
85
+ def build_fuzzers(project, engine, sanitizer, architecture):
86
+ """Execute helper.py's build_fuzzers command on |project|. Build the fuzzers
87
+ with |engine| and |sanitizer| for |architecture|."""
88
+ execute_helper_command([
89
+ 'build_fuzzers', project, '--engine', engine, '--sanitizer', sanitizer,
90
+ '--architecture', architecture
91
+ ])
92
+
93
+
94
+ def check_build(project, engine, sanitizer, architecture):
95
+ """Execute helper.py's check_build command on |project|, assuming it was most
96
+ recently built with |engine| and |sanitizer| for |architecture|."""
97
+ execute_helper_command([
98
+ 'check_build', project, '--engine', engine, '--sanitizer', sanitizer,
99
+ '--architecture', architecture
100
+ ])
101
+
102
+
103
+ def should_build_coverage(project_yaml):
104
+ """Returns True if a coverage build should be done based on project.yaml
105
+ contents."""
106
+ # Enable coverage builds on projects that use engines. Those that don't use
107
+ # engines shouldn't get coverage builds.
108
+ engines = project_yaml.get('fuzzing_engines', DEFAULT_ENGINES)
109
+ engineless = 'none' in engines
110
+ if engineless:
111
+ assert_message = ('Forbidden to specify multiple engines for '
112
+ '"fuzzing_engines" if "none" is specified.')
113
+ assert len(engines) == 1, assert_message
114
+ return False
115
+ if 'wycheproof' in engines:
116
+ return False
117
+
118
+ language = project_yaml.get('language')
119
+ if language not in constants.LANGUAGES_WITH_COVERAGE_SUPPORT:
120
+ print(('Project is written in "{language}", '
121
+ 'coverage is not supported yet.').format(language=language))
122
+ return False
123
+
124
+ return True
125
+
126
+
127
+ def flatten_options(option_list):
128
+ """Generator that flattens |option_list| (a list of sanitizers, architectures
129
+ or fuzzing engines) by returning each element in the list that isn't a
130
+ dictionary. For elements that are dictionaries, the sole key is returned."""
131
+ result = []
132
+ for option in option_list:
133
+ if isinstance(option, dict):
134
+ keys = list(option.keys())
135
+ assert len(keys) == 1
136
+ result.append(keys[0])
137
+ continue
138
+ result.append(option)
139
+ print(result)
140
+ return result
141
+
142
+
143
+ def should_build(project_yaml):
144
+ """Returns True on if the build specified is enabled in the project.yaml."""
145
+
146
+ if os.getenv('SANITIZER') == 'coverage':
147
+ # This assumes we only do coverage builds with libFuzzer on x86_64.
148
+ return should_build_coverage(project_yaml)
149
+
150
+ def is_enabled(env_var, yaml_name, defaults):
151
+ """Is the value of |env_var| enabled in |project_yaml| (in the |yaml_name|
152
+ section)? Uses |defaults| if |yaml_name| section is unspecified."""
153
+ return os.getenv(env_var) in flatten_options(
154
+ project_yaml.get(yaml_name, defaults))
155
+
156
+ return (is_enabled('ENGINE', 'fuzzing_engines', DEFAULT_ENGINES) and
157
+ is_enabled('SANITIZER', 'sanitizers', DEFAULT_SANITIZERS) and
158
+ is_enabled('ARCHITECTURE', 'architectures', DEFAULT_ARCHITECTURES))
159
+
160
+
161
+ def build_project(project):
162
+ """Do the build of |project| that is specified by the environment variables -
163
+ SANITIZER, ENGINE, and ARCHITECTURE."""
164
+ root = get_oss_fuzz_root()
165
+ project_yaml_path = os.path.join(root, 'projects', project, 'project.yaml')
166
+ with open(project_yaml_path) as file_handle:
167
+ project_yaml = yaml.safe_load(file_handle)
168
+
169
+ if project_yaml.get('disabled', False):
170
+ print('Project {0} is disabled, skipping build.'.format(project))
171
+ return
172
+
173
+ engine = os.getenv('ENGINE')
174
+ sanitizer = os.getenv('SANITIZER')
175
+ architecture = os.getenv('ARCHITECTURE')
176
+
177
+ if not should_build(project_yaml):
178
+ print(('Specified build: engine: {0}, sanitizer: {1}, architecture: {2} '
179
+ 'not enabled for this project: {3}. Skipping build.').format(
180
+ engine, sanitizer, architecture, project))
181
+
182
+ return
183
+
184
+ print('Building project', project)
185
+ build_fuzzers(project, engine, sanitizer, architecture)
186
+
187
+ run_tests = project_yaml.get('run_tests', True)
188
+ if engine != 'none' and sanitizer != 'coverage' and run_tests:
189
+ check_build(project, engine, sanitizer, architecture)
190
+
191
+
192
+ class BuildModifiedProjectsResult(enum.Enum):
193
+ """Enum containing the return values of build_modified_projects()."""
194
+ NONE_BUILT = 0
195
+ BUILD_SUCCESS = 1
196
+ BUILD_FAIL = 2
197
+
198
+
199
+ def build_modified_projects():
200
+ """Build modified projects. Returns BuildModifiedProjectsResult.NONE_BUILT if
201
+ no builds were attempted. Returns BuildModifiedProjectsResult.BUILD_SUCCESS if
202
+ all attempts succeed, otherwise returns
203
+ BuildModifiedProjectsResult.BUILD_FAIL."""
204
+ projects = get_modified_buildable_projects()
205
+ if not projects:
206
+ return BuildModifiedProjectsResult.NONE_BUILT
207
+
208
+ failed_projects = []
209
+ for project in projects:
210
+ try:
211
+ build_project(project)
212
+ except subprocess.CalledProcessError:
213
+ failed_projects.append(project)
214
+
215
+ if failed_projects:
216
+ print('Failed projects:', ' '.join(failed_projects))
217
+ return BuildModifiedProjectsResult.BUILD_FAIL
218
+
219
+ return BuildModifiedProjectsResult.BUILD_SUCCESS
220
+
221
+
222
+ def is_infra_changed():
223
+ """Returns True if the infra directory was changed."""
224
+ git_output = get_changed_files_output()
225
+ infra_code_regex = '.*infra/.*\n'
226
+ return re.search(infra_code_regex, git_output) is not None
227
+
228
+
229
+ def build_base_images():
230
+ """Builds base images."""
231
+ # TODO(jonathanmetzman): Investigate why caching fails so often and
232
+ # when we improve it, build base-clang as well. Also, move this function
233
+ # to a helper command when we can support base-clang.
234
+ execute_helper_command(['pull_images'])
235
+ images = [
236
+ 'base-image',
237
+ 'base-builder',
238
+ 'base-builder-go',
239
+ 'base-builder-javascript',
240
+ 'base-builder-jvm',
241
+ 'base-builder-python',
242
+ 'base-builder-rust',
243
+ 'base-builder-swift',
244
+ 'base-builder-ruby',
245
+ 'base-runner',
246
+ ]
247
+ for image in images:
248
+ try:
249
+ execute_helper_command(['build_image', image, '--no-pull', '--cache'])
250
+ except subprocess.CalledProcessError:
251
+ return 1
252
+
253
+ return 0
254
+
255
+
256
+ def build_canary_project():
257
+ """Builds a specific project when infra/ is changed to verify that infra/
258
+ changes don't break things. Returns False if build was attempted but
259
+ failed."""
260
+
261
+ try:
262
+ build_project('skcms')
263
+ except subprocess.CalledProcessError:
264
+ return False
265
+
266
+ return True
267
+
268
+
269
+ def main():
270
+ """Build modified projects or canary project."""
271
+ os.environ['OSS_FUZZ_CI'] = '1'
272
+ infra_changed = is_infra_changed()
273
+ if infra_changed:
274
+ print('Pulling and building base images first.')
275
+ if build_base_images():
276
+ return 1
277
+
278
+ result = build_modified_projects()
279
+ if result == BuildModifiedProjectsResult.BUILD_FAIL:
280
+ return 1
281
+
282
+ # It's unnecessary to build the canary if we've built any projects already.
283
+ no_projects_built = result == BuildModifiedProjectsResult.NONE_BUILT
284
+ should_build_canary = no_projects_built and infra_changed
285
+ if should_build_canary and not build_canary_project():
286
+ return 1
287
+
288
+ return 0
289
+
290
+
291
+ if __name__ == '__main__':
292
+ sys.exit(main())
local-test-tika-full-01-vuln_6/fuzz-tooling/infra/ci/requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Requirements for submitting code changes to infra/ (needed by presubmit.py).
2
+ parameterized==0.7.4
3
+ pyfakefs==4.5.6
4
+ pylint==2.5.3
5
+ pytest==7.1.2
6
+ pytest-xdist==2.5.0
7
+ PyYAML==6.0
8
+ requests==2.31.0
9
+ yapf==0.32.0
local-test-tika-full-01-vuln_6/fuzz-tooling/infra/cifuzz/build-images.sh ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #! /bin/bash -eux
2
+ # Copyright 2021 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # Script for building the docker images for cifuzz.
17
+
18
+ CIFUZZ_DIR=$(dirname "$0")
19
+ CIFUZZ_DIR=$(realpath $CIFUZZ_DIR)
20
+ INFRA_DIR=$(realpath $CIFUZZ_DIR/..)
21
+ OSS_FUZZ_ROOT=$(realpath $INFRA_DIR/..)
22
+
23
+ # Build cifuzz-base.
24
+ docker build --tag ghcr.io/aixcc-finals/cifuzz-base --file $CIFUZZ_DIR/cifuzz-base/Dockerfile $OSS_FUZZ_ROOT
25
+
26
+ # Build run-fuzzers and build-fuzzers images.
27
+ docker build \
28
+ --tag ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers-test:v1 \
29
+ --tag ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers:v1 \
30
+ --file $INFRA_DIR/build_fuzzers.Dockerfile $INFRA_DIR
31
+ docker build \
32
+ --tag ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers:v1 \
33
+ --tag ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers-test:v1 \
34
+ --file $INFRA_DIR/run_fuzzers.Dockerfile $INFRA_DIR
local-test-tika-full-01-vuln_6/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_6/fuzz-tooling/infra/cifuzz/cifuzz_combined_entrypoint.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Builds fuzzers and runs fuzzers. Entrypoint used for external users"""
15
+ import logging
16
+ import sys
17
+
18
+ import build_fuzzers_entrypoint
19
+ import run_fuzzers_entrypoint
20
+
21
+
22
+ def main():
23
+ """Builds and runs fuzzers for CI tools.
24
+
25
+ NOTE: Any crash report will be in the filepath: $WORKSPACE/out/testcase
26
+ This can be used with GitHub's upload-artifact action to surface the logs.
27
+
28
+ Required environment variables:
29
+ Returns:
30
+ 0 on success or 1 on failure.
31
+ """
32
+ logging.debug("Using cifuzz_combined_entrypoint.")
33
+ result = build_fuzzers_entrypoint.build_fuzzers_entrypoint()
34
+ if result != 0:
35
+ return result
36
+ return run_fuzzers_entrypoint.run_fuzzers_entrypoint()
37
+
38
+
39
+ if __name__ == '__main__':
40
+ sys.exit(main())
local-test-tika-full-01-vuln_6/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 interacting with the ClusterFuzz deployment."""
15
+ import logging
16
+ import os
17
+ import sys
18
+ import urllib.error
19
+ import urllib.request
20
+
21
+ import config_utils
22
+ import continuous_integration
23
+ import filestore_utils
24
+ import http_utils
25
+ import get_coverage
26
+ import repo_manager
27
+
28
+ # pylint: disable=wrong-import-position,import-error
29
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
30
+ import utils
31
+
32
+
33
+ class BaseClusterFuzzDeployment:
34
+ """Base class for ClusterFuzz deployments."""
35
+
36
+ def __init__(self, config, workspace):
37
+ self.config = config
38
+ self.workspace = workspace
39
+ self.ci_system = continuous_integration.get_ci(config)
40
+
41
+ def download_latest_build(self):
42
+ """Downloads the latest build from ClusterFuzz.
43
+
44
+ Returns:
45
+ A path to where the OSS-Fuzz build was stored, or None if it wasn't.
46
+ """
47
+ raise NotImplementedError('Child class must implement method.')
48
+
49
+ def upload_build(self, commit):
50
+ """Uploads the build with the given commit sha to the filestore."""
51
+ raise NotImplementedError('Child class must implement method.')
52
+
53
+ def download_corpus(self, target_name, corpus_dir):
54
+ """Downloads the corpus for |target_name| from ClusterFuzz to |corpus_dir|.
55
+
56
+ Returns:
57
+ A path to where the OSS-Fuzz build was stored, or None if it wasn't.
58
+ """
59
+ raise NotImplementedError('Child class must implement method.')
60
+
61
+ def upload_crashes(self):
62
+ """Uploads crashes in |crashes_dir| to filestore."""
63
+ raise NotImplementedError('Child class must implement method.')
64
+
65
+ def upload_corpus(self, target_name, corpus_dir, replace=False): # pylint: disable=no-self-use,unused-argument
66
+ """Uploads the corpus for |target_name| to filestore."""
67
+ raise NotImplementedError('Child class must implement method.')
68
+
69
+ def upload_coverage(self):
70
+ """Uploads the coverage report to the filestore."""
71
+ raise NotImplementedError('Child class must implement method.')
72
+
73
+ def get_coverage(self, repo_path):
74
+ """Returns the project coverage object for the project."""
75
+ raise NotImplementedError('Child class must implement method.')
76
+
77
+
78
+ def _make_empty_dir_if_nonexistent(path):
79
+ """Makes an empty directory at |path| if it does not exist."""
80
+ os.makedirs(path, exist_ok=True)
81
+
82
+
83
+ class ClusterFuzzLite(BaseClusterFuzzDeployment):
84
+ """Class representing a deployment of ClusterFuzzLite."""
85
+
86
+ COVERAGE_NAME = 'latest'
87
+ LATEST_BUILD_WINDOW = 3
88
+
89
+ def __init__(self, config, workspace):
90
+ super().__init__(config, workspace)
91
+ self.filestore = filestore_utils.get_filestore(self.config)
92
+
93
+ def download_latest_build(self):
94
+ if os.path.exists(self.workspace.clusterfuzz_build):
95
+ # This path is necessary because download_latest_build can be called
96
+ # multiple times.That is the case because it is called only when we need
97
+ # to see if a bug is novel, i.e. until we want to check a bug is novel we
98
+ # don't want to waste time calling this, but therefore this method can be
99
+ # called if multiple bugs are found.
100
+ return self.workspace.clusterfuzz_build
101
+
102
+ repo_dir = self.ci_system.repo_dir
103
+ if not repo_dir:
104
+ raise RuntimeError('Repo checkout does not exist.')
105
+
106
+ _make_empty_dir_if_nonexistent(self.workspace.clusterfuzz_build)
107
+ repo = repo_manager.RepoManager(repo_dir)
108
+
109
+ diff_base = self.ci_system.get_diff_base()
110
+ if not diff_base:
111
+ diff_base = 'HEAD^'
112
+
113
+ # Builds are stored by commit, so try the latest |LATEST_BUILD_WINDOW|
114
+ # commits before the current diff base.
115
+ # TODO(ochang): If API usage becomes an issue, this can be optimized by the
116
+ # filestore accepting a list of filenames to try.
117
+ try:
118
+ # TODO(metzman): Why do we default to 'origin', we should avoid going down
119
+ # this path entirely and not need to catch an exception.
120
+ commit_list = repo.get_commit_list(diff_base,
121
+ limit=self.LATEST_BUILD_WINDOW)
122
+ except ValueError as error:
123
+ logging.error('Can\'t get commit list: %s', error)
124
+ return None
125
+
126
+ for old_commit in commit_list:
127
+ logging.info('Trying to downloading previous build %s.', old_commit)
128
+ build_name = self._get_build_name(old_commit)
129
+ try:
130
+ if self.filestore.download_build(build_name,
131
+ self.workspace.clusterfuzz_build):
132
+ logging.info('Done downloading previous build.')
133
+ return self.workspace.clusterfuzz_build
134
+
135
+ logging.info('Build for %s does not exist.', old_commit)
136
+ except Exception as err: # pylint: disable=broad-except
137
+ logging.error('Could not download build for %s because of: %s',
138
+ old_commit, err)
139
+
140
+ return None
141
+
142
+ def download_corpus(self, target_name, corpus_dir):
143
+ _make_empty_dir_if_nonexistent(corpus_dir)
144
+ logging.info('Downloading corpus for %s to %s.', target_name, corpus_dir)
145
+ corpus_name = self._get_corpus_name(target_name)
146
+ try:
147
+ self.filestore.download_corpus(corpus_name, corpus_dir)
148
+ logging.info('Done downloading corpus. Contains %d elements.',
149
+ len(os.listdir(corpus_dir)))
150
+ except Exception as err: # pylint: disable=broad-except
151
+ logging.error('Failed to download corpus for target: %s. Error: %s',
152
+ target_name, str(err))
153
+ return corpus_dir
154
+
155
+ def _get_build_name(self, name):
156
+ return f'{self.config.sanitizer}-{name}'
157
+
158
+ def _get_corpus_name(self, target_name): # pylint: disable=no-self-use
159
+ """Returns the name of the corpus artifact."""
160
+ return target_name
161
+
162
+ def upload_corpus(self, target_name, corpus_dir, replace=False):
163
+ """Upload the corpus produced by |target_name|."""
164
+ logging.info('Uploading corpus in %s for %s.', corpus_dir, target_name)
165
+ name = self._get_corpus_name(target_name)
166
+ try:
167
+ self.filestore.upload_corpus(name, corpus_dir, replace=replace)
168
+ logging.info('Done uploading corpus.')
169
+ except Exception as err: # pylint: disable=broad-except
170
+ logging.error('Failed to upload corpus for target: %s. Error: %s.',
171
+ target_name, err)
172
+
173
+ def upload_build(self, commit):
174
+ """Upload the build produced by CIFuzz as the latest build."""
175
+ logging.info('Uploading latest build in %s.', self.workspace.out)
176
+ build_name = self._get_build_name(commit)
177
+ try:
178
+ result = self.filestore.upload_build(build_name, self.workspace.out)
179
+ logging.info('Done uploading latest build.')
180
+ return result
181
+ except Exception as err: # pylint: disable=broad-except
182
+ logging.error('Failed to upload latest build: %s. Error: %s',
183
+ self.workspace.out, err)
184
+
185
+ def upload_crashes(self):
186
+ """Uploads crashes."""
187
+ artifact_dirs = os.listdir(self.workspace.artifacts)
188
+ if not artifact_dirs:
189
+ logging.info('No crashes in %s. Not uploading.', self.workspace.artifacts)
190
+ return
191
+
192
+ for crash_target in artifact_dirs:
193
+ artifact_dir = os.path.join(self.workspace.artifacts, crash_target)
194
+ if not os.path.isdir(artifact_dir):
195
+ logging.warning('%s is not an expected artifact directory, skipping.',
196
+ crash_target)
197
+ continue
198
+
199
+ logging.info('Uploading crashes in %s.', artifact_dir)
200
+ try:
201
+ self.filestore.upload_crashes(crash_target, artifact_dir)
202
+ logging.info('Done uploading crashes.')
203
+ except Exception as err: # pylint: disable=broad-except
204
+ logging.error('Failed to upload crashes. Error: %s', err)
205
+
206
+ def upload_coverage(self):
207
+ """Uploads the coverage report to the filestore."""
208
+ self.filestore.upload_coverage(self.COVERAGE_NAME,
209
+ self.workspace.coverage_report)
210
+
211
+ def get_coverage(self, repo_path):
212
+ """Returns the project coverage object for the project."""
213
+ _make_empty_dir_if_nonexistent(self.workspace.clusterfuzz_coverage)
214
+ try:
215
+ if not self.filestore.download_coverage(
216
+ self.COVERAGE_NAME, self.workspace.clusterfuzz_coverage):
217
+ logging.error('Could not download coverage.')
218
+ return None
219
+ return get_coverage.FilesystemCoverage(
220
+ repo_path, self.workspace.clusterfuzz_coverage)
221
+ except Exception as err: # pylint: disable=broad-except
222
+ logging.error('Could not get coverage: %s.', err)
223
+ return None
224
+
225
+
226
+ class OSSFuzz(BaseClusterFuzzDeployment):
227
+ """The OSS-Fuzz ClusterFuzz deployment."""
228
+
229
+ # Location of clusterfuzz builds on GCS.
230
+ CLUSTERFUZZ_BUILDS = 'clusterfuzz-builds'
231
+
232
+ # Zip file name containing the corpus.
233
+ CORPUS_ZIP_NAME = 'public.zip'
234
+
235
+ def get_latest_build_name(self):
236
+ """Gets the name of the latest OSS-Fuzz build of a project.
237
+
238
+ Returns:
239
+ A string with the latest build version or None.
240
+ """
241
+ version_file = (
242
+ f'{self.config.oss_fuzz_project_name}-{self.config.sanitizer}'
243
+ '-latest.version')
244
+ version_url = utils.url_join(utils.GCS_BASE_URL, self.CLUSTERFUZZ_BUILDS,
245
+ self.config.oss_fuzz_project_name,
246
+ version_file)
247
+ try:
248
+ response = urllib.request.urlopen(version_url)
249
+ except urllib.error.HTTPError:
250
+ logging.error('Error getting latest build version for %s from: %s.',
251
+ self.config.oss_fuzz_project_name, version_url)
252
+ return None
253
+ return response.read().decode()
254
+
255
+ def download_latest_build(self):
256
+ """Downloads the latest OSS-Fuzz build from GCS.
257
+
258
+ Returns:
259
+ A path to where the OSS-Fuzz build was stored, or None if it wasn't.
260
+ """
261
+ if os.path.exists(self.workspace.clusterfuzz_build):
262
+ # This function can be called multiple times, don't download the build
263
+ # again.
264
+ return self.workspace.clusterfuzz_build
265
+
266
+ _make_empty_dir_if_nonexistent(self.workspace.clusterfuzz_build)
267
+
268
+ latest_build_name = self.get_latest_build_name()
269
+ if not latest_build_name:
270
+ return None
271
+
272
+ logging.info('Downloading latest build.')
273
+ oss_fuzz_build_url = utils.url_join(utils.GCS_BASE_URL,
274
+ self.CLUSTERFUZZ_BUILDS,
275
+ self.config.oss_fuzz_project_name,
276
+ latest_build_name)
277
+ if http_utils.download_and_unpack_zip(oss_fuzz_build_url,
278
+ self.workspace.clusterfuzz_build):
279
+ logging.info('Done downloading latest build.')
280
+ return self.workspace.clusterfuzz_build
281
+
282
+ return None
283
+
284
+ def upload_build(self, commit): # pylint: disable=no-self-use
285
+ """Noop Implementation of upload_build."""
286
+ logging.info('Not uploading latest build because on OSS-Fuzz.')
287
+
288
+ def upload_corpus(self, target_name, corpus_dir, replace=False): # pylint: disable=no-self-use,unused-argument
289
+ """Noop Implementation of upload_corpus."""
290
+ logging.info('Not uploading corpus because on OSS-Fuzz.')
291
+
292
+ def upload_crashes(self): # pylint: disable=no-self-use
293
+ """Noop Implementation of upload_crashes."""
294
+ logging.info('Not uploading crashes because on OSS-Fuzz.')
295
+
296
+ def download_corpus(self, target_name, corpus_dir):
297
+ """Downloads the latest OSS-Fuzz corpus for the target.
298
+
299
+ Returns:
300
+ The local path to to corpus or None if download failed.
301
+ """
302
+ _make_empty_dir_if_nonexistent(corpus_dir)
303
+ project_qualified_fuzz_target_name = target_name
304
+ qualified_name_prefix = self.config.oss_fuzz_project_name + '_'
305
+ if not target_name.startswith(qualified_name_prefix):
306
+ project_qualified_fuzz_target_name = qualified_name_prefix + target_name
307
+
308
+ corpus_url = (f'{utils.GCS_BASE_URL}{self.config.oss_fuzz_project_name}'
309
+ '-backup.clusterfuzz-external.appspot.com/corpus/'
310
+ f'libFuzzer/{project_qualified_fuzz_target_name}/'
311
+ f'{self.CORPUS_ZIP_NAME}')
312
+ logging.info('Downloading corpus from OSS-Fuzz: %s', corpus_url)
313
+
314
+ if not http_utils.download_and_unpack_zip(corpus_url, corpus_dir):
315
+ logging.warning('Failed to download corpus for %s.', target_name)
316
+ return corpus_dir
317
+
318
+ def upload_coverage(self):
319
+ """Noop Implementation of upload_coverage_report."""
320
+ logging.info('Not uploading coverage report because on OSS-Fuzz.')
321
+
322
+ def get_coverage(self, repo_path):
323
+ """Returns the project coverage object for the project."""
324
+ try:
325
+ return get_coverage.OSSFuzzCoverage(repo_path,
326
+ self.config.oss_fuzz_project_name)
327
+ except get_coverage.CoverageError:
328
+ return None
329
+
330
+
331
+ class NoClusterFuzzDeployment(BaseClusterFuzzDeployment):
332
+ """ClusterFuzzDeployment implementation used when there is no deployment of
333
+ ClusterFuzz to use."""
334
+
335
+ def upload_build(self, commit): # pylint: disable=no-self-use
336
+ """Noop Implementation of upload_build."""
337
+ logging.info('Not uploading latest build because no ClusterFuzz '
338
+ 'deployment.')
339
+
340
+ def upload_corpus(self, target_name, corpus_dir, replace=False): # pylint: disable=no-self-use,unused-argument
341
+ """Noop Implementation of upload_corpus."""
342
+ logging.info('Not uploading corpus because no ClusterFuzz deployment.')
343
+
344
+ def upload_crashes(self): # pylint: disable=no-self-use
345
+ """Noop Implementation of upload_crashes."""
346
+ logging.info('Not uploading crashes because no ClusterFuzz deployment.')
347
+
348
+ def download_corpus(self, target_name, corpus_dir):
349
+ """Noop Implementation of download_corpus."""
350
+ logging.info('Not downloading corpus because no ClusterFuzz deployment.')
351
+ return _make_empty_dir_if_nonexistent(corpus_dir)
352
+
353
+ def download_latest_build(self): # pylint: disable=no-self-use
354
+ """Noop Implementation of download_latest_build."""
355
+ logging.info(
356
+ 'Not downloading latest build because no ClusterFuzz deployment.')
357
+
358
+ def upload_coverage(self):
359
+ """Noop Implementation of upload_coverage."""
360
+ logging.info(
361
+ 'Not uploading coverage report because no ClusterFuzz deployment.')
362
+
363
+ def get_coverage(self, repo_path):
364
+ """Noop Implementation of get_coverage."""
365
+ logging.info(
366
+ 'Not getting project coverage because no ClusterFuzz deployment.')
367
+
368
+
369
+ _PLATFORM_CLUSTERFUZZ_DEPLOYMENT_MAPPING = {
370
+ config_utils.BaseConfig.Platform.INTERNAL_GENERIC_CI: OSSFuzz,
371
+ config_utils.BaseConfig.Platform.INTERNAL_GITHUB: OSSFuzz,
372
+ config_utils.BaseConfig.Platform.EXTERNAL_GENERIC_CI: ClusterFuzzLite,
373
+ config_utils.BaseConfig.Platform.EXTERNAL_GITHUB: ClusterFuzzLite,
374
+ }
375
+
376
+
377
+ def get_clusterfuzz_deployment(config, workspace):
378
+ """Returns object reprsenting deployment of ClusterFuzz used by |config|."""
379
+ deployment_cls = _PLATFORM_CLUSTERFUZZ_DEPLOYMENT_MAPPING[config.platform]
380
+ if config.no_clusterfuzz_deployment:
381
+ logging.info('Overriding ClusterFuzzDeployment. Using None.')
382
+ deployment_cls = NoClusterFuzzDeployment
383
+ result = deployment_cls(config, workspace)
384
+ logging.info('ClusterFuzzDeployment: %s.', result)
385
+ return result
local-test-tika-full-01-vuln_6/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_6/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_6/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_6/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_6/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_6/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_6/fuzz-tooling/infra/cifuzz/test_helpers.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Contains convenient helpers for writing tests."""
15
+
16
+ import contextlib
17
+ import os
18
+ import sys
19
+ import shutil
20
+ import tempfile
21
+ from unittest import mock
22
+
23
+ import config_utils
24
+ import docker
25
+ import workspace_utils
26
+
27
+ INFRA_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
28
+ # pylint: disable=wrong-import-position,import-error
29
+ sys.path.append(INFRA_DIR)
30
+
31
+ import helper
32
+
33
+
34
+ # TODO(metzman): Get rid of these decorators.
35
+ @mock.patch('config_utils._is_dry_run', return_value=True)
36
+ @mock.patch('platform_config.BasePlatformConfig.project_src_path',
37
+ return_value=None)
38
+ @mock.patch('os.path.basename', return_value=None)
39
+ def _create_config(config_cls, _, __, ___, **kwargs):
40
+ """Creates a config object from |config_cls| and then sets every attribute
41
+ that is a key in |kwargs| to the corresponding value. Asserts that each key in
42
+ |kwargs| is an attribute of config."""
43
+ with mock.patch('config_utils.BaseConfig.validate', return_value=True):
44
+ config = config_cls()
45
+ for key, value in kwargs.items():
46
+ assert hasattr(config, key), 'Config doesn\'t have attribute: ' + key
47
+ setattr(config, key, value)
48
+
49
+ return config
50
+
51
+
52
+ def create_build_config(**kwargs):
53
+ """Wrapper around _create_config for build configs."""
54
+ return _create_config(config_utils.BuildFuzzersConfig, **kwargs)
55
+
56
+
57
+ def create_run_config(**kwargs):
58
+ """Wrapper around _create_config for run configs."""
59
+ return _create_config(config_utils.RunFuzzersConfig, **kwargs)
60
+
61
+
62
+ def create_workspace(workspace_path='/workspace'):
63
+ """Returns a workspace located at |workspace_path| ('/workspace' by
64
+ default)."""
65
+ config = create_run_config(workspace=workspace_path)
66
+ return workspace_utils.Workspace(config)
67
+
68
+
69
+ def patch_environ(testcase_obj, env=None, empty=False, runner=False):
70
+ """Patch environment. |testcase_obj| is the unittest.TestCase that contains
71
+ tests. |env|, if specified, is a dictionary of environment variables to start
72
+ from. If |empty| is True then the new patched environment will be empty. If
73
+ |runner| is True then the necessary environment variables will be set to run
74
+ the scripts from base-runner."""
75
+ if env is None:
76
+ env = {}
77
+
78
+ patcher = mock.patch.dict(os.environ, env)
79
+ testcase_obj.addCleanup(patcher.stop)
80
+ patcher.start()
81
+ if empty:
82
+ for key in os.environ.copy():
83
+ del os.environ[key]
84
+
85
+ if runner:
86
+ # Add the scripts for base-runner to the path since the wont be in
87
+ # /usr/local/bin on host machines during testing.
88
+ base_runner_dir = os.path.join(INFRA_DIR, 'base-images', 'base-runner')
89
+ os.environ['PATH'] = (os.environ.get('PATH', '') + os.pathsep +
90
+ base_runner_dir)
91
+ if 'GOPATH' not in os.environ:
92
+ # A GOPATH must be set or else the coverage script fails, even for getting
93
+ # the coverage of non-Go programs.
94
+ os.environ['GOPATH'] = '/root/go'
95
+
96
+
97
+ @contextlib.contextmanager
98
+ def temp_dir_copy(directory):
99
+ """Context manager that yields a temporary copy of |directory|."""
100
+ with tempfile.TemporaryDirectory() as temp_dir:
101
+ temp_copy_path = os.path.join(temp_dir, os.path.basename(directory))
102
+ shutil.copytree(directory, temp_copy_path)
103
+ yield temp_copy_path
104
+
105
+
106
+ @contextlib.contextmanager
107
+ def docker_temp_dir():
108
+ """Returns a temporary a directory that is useful for use with docker. On
109
+ cleanup this contextmanager uses docker to delete the directory's contents so
110
+ that if anything is owned by root it can be deleted (which
111
+ tempfile.TemporaryDirectory() cannot do) by non-root users."""
112
+ with tempfile.TemporaryDirectory() as temp_dir:
113
+ yield temp_dir
114
+ helper.docker_run([
115
+ '-v', f'{temp_dir}:/temp_dir', '-t', docker.BASE_BUILDER_TAG,
116
+ '/bin/bash', '-c', 'rm -rf /temp_dir/*'
117
+ ])
local-test-tika-full-01-vuln_6/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)
local-test-tika-full-01-vuln_6/fuzz-tooling/infra/tools/hold_back_images.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Copyright 2022 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ ################################################################################
17
+ """Script for pinning builder images for projects that break on upgrades. Works
18
+ with projects that use language builders."""
19
+ import argparse
20
+ import logging
21
+ import os
22
+ import re
23
+ import sys
24
+ import subprocess
25
+
26
+ ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
27
+ PROJECTS_DIR = os.path.join(ROOT_DIR, 'projects')
28
+
29
+ IMAGE_DIGEST_REGEX = re.compile(r'\[(.+)\]\n')
30
+ FROM_LINE_REGEX = re.compile(
31
+ r'FROM (ghcr.io\/aixcc-finals\/base-builder[\-a-z0-9]*)(\@?.*)')
32
+
33
+
34
+ def get_latest_docker_image_digest(image):
35
+ """Returns a pinnable version of the latest |image|. This version will have a
36
+ SHA."""
37
+ subprocess.run(['docker', 'pull', image], check=True)
38
+ subprocess.run(['docker', 'pull', image], stdout=subprocess.PIPE, check=True)
39
+
40
+ command = [
41
+ 'docker', 'image', 'inspect', '--format', '{{.RepoDigests}}', image
42
+ ]
43
+ output = subprocess.run(command, check=True,
44
+ stdout=subprocess.PIPE).stdout.decode('utf-8')
45
+ return IMAGE_DIGEST_REGEX.match(output).groups(1)[0]
46
+
47
+
48
+ def get_args():
49
+ """Returns parsed arguments."""
50
+ parser = argparse.ArgumentParser(sys.argv[0],
51
+ description='Hold back builder images.')
52
+ parser.add_argument('projects', help='Projects.', nargs='+')
53
+
54
+ parser.add_argument('--hold-image-digest',
55
+ required=False,
56
+ nargs='?',
57
+ default=None,
58
+ help='Image to hold on to.')
59
+
60
+ parser.add_argument('--update-held',
61
+ action='store_true',
62
+ default=False,
63
+ help='Update held images.')
64
+
65
+ parser.add_argument('--issue-number',
66
+ required=False,
67
+ nargs='?',
68
+ default=None,
69
+ help='Issue to reference.')
70
+
71
+ args = parser.parse_args()
72
+ return args
73
+
74
+
75
+ def get_hold_image_digest(line, hold_image_digest, update_held):
76
+ """Returns the image digest for the |line| we want to pin. If the image is
77
+ already pinned then it is only updated if |update_held. If |hold_image_digest
78
+ is specified then it is returned, otherwise the latest pinnable version is
79
+ returned."""
80
+ matches = FROM_LINE_REGEX.match(line).groups()
81
+ if matches[1] and not update_held:
82
+ return None, False
83
+ initial_image = matches[0]
84
+ if hold_image_digest:
85
+ return hold_image_digest, True
86
+ return get_latest_docker_image_digest(initial_image), True
87
+
88
+
89
+ def hold_image(project, hold_image_digest, update_held, issue_number):
90
+ """Rewrites the Dockerfile of |project| to pin the base-builder image on
91
+ upgrade."""
92
+ dockerfile_path = os.path.join(PROJECTS_DIR, project, 'Dockerfile')
93
+ with open(dockerfile_path, 'r') as dockerfile_handle:
94
+ dockerfile = dockerfile_handle.readlines()
95
+ for idx, line in enumerate(dockerfile[:]):
96
+ if not line.startswith('FROM ghcr.io/aixcc-finals/base-builder'):
97
+ continue
98
+
99
+ hold_image_digest, should_hold = get_hold_image_digest(
100
+ line.strip(), hold_image_digest, update_held)
101
+ if not should_hold:
102
+ logging.error('Not holding back %s.', project)
103
+ break
104
+ dockerfile[idx] = f'FROM {hold_image_digest}\n'
105
+ if issue_number:
106
+ comment = ('# Held back because of github.com/google/oss-fuzz/pull/'
107
+ f'{issue_number}\n# Please fix failure and upgrade.\n')
108
+ dockerfile.insert(idx, comment)
109
+ break
110
+ else:
111
+ # This path is taken when we don't break out of the loop.
112
+ assert None, f'Could not find FROM line in {project}'
113
+ dockerfile = ''.join(dockerfile)
114
+ with open(dockerfile_path, 'w') as dockerfile_handle:
115
+ dockerfile_handle.write(dockerfile)
116
+
117
+
118
+ def main():
119
+ """Script for pinning builder images for projects that break on upgrades."""
120
+ args = get_args()
121
+ for project in args.projects:
122
+ hold_image(project, args.hold_image_digest, args.update_held,
123
+ args.issue_number)
124
+ return 0
125
+
126
+
127
+ if __name__ == '__main__':
128
+ sys.exit(main())
local-test-tika-full-01-vuln_6/fuzz-tooling/tools/vscode-extension/src/commands/cmdBuildFuzzerFromWorkspaceCFLite.ts ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ // Copyright 2023 Google LLC
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // http://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+ //
16
+ ////////////////////////////////////////////////////////////////////////////////
17
+
18
+ import {commandHistory} from '../commandUtils';
19
+ import {setStatusText} from '../utils';
20
+ import {buildFuzzersFromWorkspaceClusterfuzzLite} from '../ossfuzzWrappers';
21
+
22
+ export async function cmdInputCollectorBuildFuzzersFromWorkspaceCFLite() {
23
+ // Create an history object
24
+ const args = new Object({
25
+ toClean: false,
26
+ });
27
+
28
+ const commandObject = new Object({
29
+ commandType: 'oss-fuzz.WSBuildFuzzers',
30
+ Arguments: args,
31
+ dispatcherFunc: cmdDispatchbuildFuzzersFromWorkspaceClusterfuzzLite,
32
+ });
33
+ console.log('L1: ' + commandHistory.length);
34
+ commandHistory.push(commandObject);
35
+
36
+ await cmdDispatchbuildFuzzersFromWorkspaceClusterfuzzLite(args);
37
+ return true;
38
+ }
39
+
40
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
41
+ async function cmdDispatchbuildFuzzersFromWorkspaceClusterfuzzLite(_args: any) {
42
+ await setStatusText('[CFLite] Building fuzzers: starting');
43
+ const res = await buildFuzzersFromWorkspaceClusterfuzzLite();
44
+ if (res) {
45
+ await setStatusText('[CFLite] Building fuzzers: finished');
46
+ } else {
47
+ await setStatusText('[CFLite] Building fuzzers: failed');
48
+ }
49
+ }
local-test-tika-full-01-vuln_6/fuzz-tooling/tools/vscode-extension/src/commands/cmdSetOSSFuzzPath.ts ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 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
+ //
15
+ ////////////////////////////////////////////////////////////////////////////////
16
+
17
+ import * as vscode from 'vscode';
18
+
19
+ import {println} from '../logger';
20
+ import {extensionConfig} from '../config';
21
+
22
+ // Set the oss-fuzz path.
23
+ export async function setOssFuzzPath() {
24
+ println('Setting path');
25
+ const newOssFuzzPath = await vscode.window.showInputBox({
26
+ value: '',
27
+ placeHolder: 'Type path',
28
+ });
29
+ if (!newOssFuzzPath) {
30
+ println('Failed getting path');
31
+ return;
32
+ }
33
+
34
+ const fpathh = vscode.Uri.file(newOssFuzzPath);
35
+ let isValid = false;
36
+ try {
37
+ if (await vscode.workspace.fs.readDirectory(fpathh)) {
38
+ println('Is a directory');
39
+ const helperPathURI = vscode.Uri.file(
40
+ newOssFuzzPath + '/infra/helper.py'
41
+ );
42
+ if (await vscode.workspace.fs.readFile(helperPathURI)) {
43
+ println('Found helper file');
44
+ isValid = true;
45
+ }
46
+ isValid = true;
47
+ } else {
48
+ isValid = false;
49
+ }
50
+ } catch {
51
+ isValid = false;
52
+ }
53
+
54
+ if (isValid) {
55
+ extensionConfig.ossFuzzPepositoryWorkPath = newOssFuzzPath;
56
+ } else {
57
+ println('Not setting OSS-Fuzz path');
58
+ }
59
+ }
local-test-tika-full-01-vuln_6/fuzz-tooling/tools/vscode-extension/src/commands/cmdTestFuzzer.ts ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 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
+ //
15
+ ////////////////////////////////////////////////////////////////////////////////
16
+
17
+ import * as vscode from 'vscode';
18
+ import {println} from '../logger';
19
+ import {runFuzzerHandler, buildFuzzersFromWorkspace} from '../ossfuzzWrappers';
20
+ import {setStatusText} from '../utils';
21
+ import {commandHistory} from '../commandUtils';
22
+ import {extensionConfig} from '../config';
23
+
24
+ /**
25
+ * Does an end-to-end test of a project/fuzzer. This is done by
26
+ * first building the project and then running the fuzzer.
27
+ * @param context
28
+ * @returns
29
+ */
30
+
31
+ export async function cmdInputCollectorTestFuzzer() {
32
+ setStatusText('Testing specific fuzzer: getting input');
33
+ // Get the project name and fuzzer name to test.
34
+ const ossFuzzProjectNameInput = await vscode.window.showInputBox({
35
+ value: '',
36
+ placeHolder: 'The OSS-Fuzz project name',
37
+ });
38
+ if (!ossFuzzProjectNameInput) {
39
+ println('Did not get a ossFuzzTargetProject');
40
+ return;
41
+ }
42
+ println('Project name: ' + ossFuzzProjectNameInput);
43
+
44
+ // Get the fuzzer to run
45
+ const fuzzerNameInput = await vscode.window.showInputBox({
46
+ value: '',
47
+ placeHolder: 'Type a fuzzer name',
48
+ });
49
+ if (!fuzzerNameInput) {
50
+ println('Failed to get fuzzer name');
51
+ return;
52
+ }
53
+
54
+ // Create the args object for the dispatcher
55
+ const args = new Object({
56
+ projectName: ossFuzzProjectNameInput.toString(),
57
+ fuzzerName: fuzzerNameInput.toString(),
58
+ });
59
+
60
+ // Create a dispatcher object.
61
+ const commandObject = new Object({
62
+ commandType: 'oss-fuzz.TestFuzzer',
63
+ Arguments: args,
64
+ dispatcherFunc: cmdDispatchTestFuzzerHandler,
65
+ });
66
+ commandHistory.push(commandObject);
67
+
68
+ await cmdDispatchTestFuzzerHandler(args);
69
+ }
70
+
71
+ async function cmdDispatchTestFuzzerHandler(args: any) {
72
+ // Build the project
73
+ setStatusText('Test specific fuzzer: building fuzzers in workspace');
74
+ if (!(await buildFuzzersFromWorkspace(args.projectName, '', false))) {
75
+ println('Build projects');
76
+ return;
77
+ }
78
+
79
+ // Run the fuzzer for 10 seconds
80
+ println('Running fuzzer');
81
+ setStatusText('Test specific fuzzer: running fuzzer ' + args.fuzzerName);
82
+ await runFuzzerHandler(
83
+ args.projectName,
84
+ args.fuzzerName,
85
+ extensionConfig.numberOfSecondsForTestRuns.toString(),
86
+ ''
87
+ );
88
+ setStatusText('Test specific fuzzer: test completed of ' + args.fuzzerName);
89
+ return;
90
+ }