diff --git a/.github/workflows/cifuzz.yaml b/.github/workflows/cifuzz.yaml new file mode 100644 index 00000000..202ce966 --- /dev/null +++ b/.github/workflows/cifuzz.yaml @@ -0,0 +1,20 @@ +name: CIFuzz +on: + pull_request: + branches: + - main +jobs: + Fuzzing: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Restore Go cache + uses: actions/cache@v1 + with: + path: /home/runner/work/_temp/_github_home/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + - name: Smoke test Fuzzers + run: make fuzz-smoketest diff --git a/.gitignore b/.gitignore index 5a3a724f..1b9460a7 100644 --- a/.gitignore +++ b/.gitignore @@ -13,8 +13,9 @@ # Dependency directories (remove the comment below to include it) # vendor/ -testbin/ bin/ config/release/ config/crd/bases/gitrepositories.yaml config/crd/bases/buckets.yaml + +build/ diff --git a/Makefile b/Makefile index eff702b0..6c2167ec 100644 --- a/Makefile +++ b/Makefile @@ -22,7 +22,7 @@ ENVTEST_ARCH ?= amd64 all: manager # Download the envtest binaries to testbin -ENVTEST_ASSETS_DIR=$(shell pwd)/testbin +ENVTEST_ASSETS_DIR=$(shell pwd)/build/testbin ENVTEST_KUBERNETES_VERSION?=latest install-envtest: setup-envtest mkdir -p ${ENVTEST_ASSETS_DIR} @@ -147,3 +147,22 @@ GOBIN=$(PROJECT_DIR)/bin go install $(2) ;\ rm -rf $$TMP_DIR ;\ } endef + +# Build fuzzers +fuzz-build: + rm -rf $(shell pwd)/build/fuzz/ + mkdir -p $(shell pwd)/build/fuzz/out/ + + docker build . --tag local-fuzzing:latest -f tests/fuzz/Dockerfile.builder + docker run --rm \ + -e FUZZING_LANGUAGE=go -e SANITIZER=address \ + -e CIFUZZ_DEBUG='True' -e OSS_FUZZ_PROJECT_NAME=fluxcd \ + -v "$(shell pwd)/build/fuzz/out":/out \ + local-fuzzing:latest + +fuzz-smoketest: fuzz-build + docker run --rm \ + -v "$(shell pwd)/build/fuzz/out":/out \ + -v "$(shell pwd)/tests/fuzz/oss_fuzz_run.sh":/runner.sh \ + local-fuzzing:latest \ + bash -c "/runner.sh" diff --git a/controllers/suite_test.go b/controllers/suite_test.go index fe89e937..7d3c82ae 100644 --- a/controllers/suite_test.go +++ b/controllers/suite_test.go @@ -69,7 +69,7 @@ var ( debugMode = os.Getenv("DEBUG_TEST") != "" ) -func TestMain(m *testing.M) { +func runInContext(registerControllers func(*testenv.Environment), run func() error, crdPath string) error { var err error utilruntime.Must(sourcev1.AddToScheme(scheme.Scheme)) utilruntime.Must(kustomizev1.AddToScheme(scheme.Scheme)) @@ -78,9 +78,7 @@ func TestMain(m *testing.M) { controllerLog.SetLogger(zap.New(zap.WriteTo(os.Stderr), zap.UseDevMode(false))) } - testEnv = testenv.New(testenv.WithCRDPath( - filepath.Join("..", "config", "crd", "bases"), - )) + testEnv = testenv.New(testenv.WithCRDPath(crdPath)) testServer, err = testserver.NewTempArtifactServer() if err != nil { @@ -89,18 +87,7 @@ func TestMain(m *testing.M) { fmt.Println("Starting the test storage server") testServer.Start() - controllerName := "kustomize-controller" - testEventsH = controller.MakeEvents(testEnv, controllerName, nil) - testMetricsH = controller.MustMakeMetrics(testEnv) - reconciler := &KustomizationReconciler{ - ControllerName: controllerName, - Client: testEnv, - EventRecorder: testEventsH.EventRecorder, - MetricsRecorder: testMetricsH.MetricsRecorder, - } - if err := (reconciler).SetupWithManager(testEnv, KustomizationReconcilerOptions{MaxConcurrentReconciles: 4}); err != nil { - panic(fmt.Sprintf("Failed to start GitRepositoryReconciler: %v", err)) - } + registerControllers(testEnv) go func() { fmt.Println("Starting the test environment") @@ -129,7 +116,7 @@ func TestMain(m *testing.M) { panic(fmt.Sprintf("Failed to create k8s client: %v", err)) } - code := m.Run() + runErr := run() if debugMode { events := &corev1.EventList{} @@ -152,6 +139,30 @@ func TestMain(m *testing.M) { panic(fmt.Sprintf("Failed to remove storage server dir: %v", err)) } + return runErr +} + +func TestMain(m *testing.M) { + code := 0 + + runInContext(func(testEnv *testenv.Environment) { + controllerName := "kustomize-controller" + testEventsH = controller.MakeEvents(testEnv, controllerName, nil) + testMetricsH = controller.MustMakeMetrics(testEnv) + reconciler := &KustomizationReconciler{ + ControllerName: controllerName, + Client: testEnv, + EventRecorder: testEventsH.EventRecorder, + MetricsRecorder: testMetricsH.MetricsRecorder, + } + if err := (reconciler).SetupWithManager(testEnv, KustomizationReconcilerOptions{MaxConcurrentReconciles: 4}); err != nil { + panic(fmt.Sprintf("Failed to start KustomizationReconciler: %v", err)) + } + }, func() error { + code = m.Run() + return nil + }, filepath.Join("..", "config", "crd", "bases")) + os.Exit(code) } diff --git a/tests/fuzz/Dockerfile.builder b/tests/fuzz/Dockerfile.builder new file mode 100644 index 00000000..4c04ccce --- /dev/null +++ b/tests/fuzz/Dockerfile.builder @@ -0,0 +1,6 @@ +FROM gcr.io/oss-fuzz-base/base-builder-go + +COPY ./ $GOPATH/src/github.com/fluxcd/kustomize-controller/ +COPY ./tests/fuzz/oss_fuzz_build.sh $SRC/build.sh + +WORKDIR $SRC diff --git a/tests/fuzz/README.md b/tests/fuzz/README.md new file mode 100644 index 00000000..f2d23396 --- /dev/null +++ b/tests/fuzz/README.md @@ -0,0 +1,45 @@ +# fuzz testing + +Flux is part of Google's [oss fuzz] program which provides continuous fuzzing for +open source projects. + +The long running fuzzing execution is configured in the [oss-fuzz repository]. +Shorter executions are done on a per-PR basis, configured as a [github workflow]. + +For fuzzers to be called, they must be compiled within [oss_fuzz_build.sh](./oss_fuzz_build.sh). + +### Testing locally + +Build fuzzers: + +```bash +make fuzz-build +``` +All fuzzers will be built into `./build/fuzz/out`. + +Smoke test fuzzers: + +```bash +make fuzz-smoketest +``` + +The smoke test runs each fuzzer once to ensure they are fully functional. + +Run fuzzer locally: +```bash +./build/fuzz/out/fuzz_conditions_match +``` + +Run fuzzer inside a container: + +```bash + docker run --rm -ti \ + -v "$(pwd)/build/fuzz/out":/out \ + gcr.io/oss-fuzz/fluxcd \ + /out/fuzz_conditions_match +``` + + +[oss fuzz]: https://github.com/google/oss-fuzz +[oss-fuzz repository]: https://github.com/google/oss-fuzz/tree/master/projects/fluxcd +[github workflow]: .github/workflows/cifuzz.yaml diff --git a/tests/fuzz/age_fuzzer.go b/tests/fuzz/age_fuzzer.go new file mode 100644 index 00000000..004effb3 --- /dev/null +++ b/tests/fuzz/age_fuzzer.go @@ -0,0 +1,47 @@ +//go:build gofuzz +// +build gofuzz + +/* +Copyright 2022 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package age + +import ( + fuzz "github.com/AdaLogics/go-fuzz-headers" +) + +// FuzzAge implements a fuzzer that targets functions within age/keysource.go. +func FuzzAge(data []byte) int { + f := fuzz.NewConsumer(data) + masterKey := MasterKey{} + + if err := f.GenerateStruct(&masterKey); err != nil { + return 0 + } + + _ = masterKey.Encrypt(data) + _ = masterKey.EncryptIfNeeded(data) + + receipts, err := f.GetString() + if err != nil { + return 0 + } + + _, _ = MasterKeysFromRecipients(receipts) + _, _ = MasterKeyFromRecipient(receipts) + + return 1 +} diff --git a/tests/fuzz/controllers_fuzzer.go b/tests/fuzz/controllers_fuzzer.go new file mode 100644 index 00000000..01f47c38 --- /dev/null +++ b/tests/fuzz/controllers_fuzzer.go @@ -0,0 +1,441 @@ +//go:build gofuzz +// +build gofuzz + +/* +Copyright 2021 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package controllers + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "strings" + "sync" + "time" + + "embed" + "io/fs" + + securejoin "github.com/cyphar/filepath-securejoin" + kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta2" + "github.com/fluxcd/kustomize-controller/controllers" + "github.com/fluxcd/pkg/apis/meta" + "github.com/fluxcd/pkg/runtime/testenv" + sourcev1 "github.com/fluxcd/source-controller/api/v1beta1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + + fuzz "github.com/AdaLogics/go-fuzz-headers" +) + +var doOnce sync.Once + +const defaultBinVersion = "1.23" + +func envtestBinVersion() string { + if binVersion := os.Getenv("ENVTEST_BIN_VERSION"); binVersion != "" { + return binVersion + } + return defaultBinVersion +} + +//go:embed testdata/crd/*.yaml +//go:embed testdata/sops/pgp.asc +//go:embed testdata/sops/age.txt +var testFiles embed.FS + +// ensureDependencies ensure that: +// a) setup-envtest is installed and a specific version of envtest is deployed. +// b) the embedded crd files are exported onto the "runner container". +// +// The steps above are important as the fuzzers tend to be built in an +// environment (or container) and executed in other. +func ensureDependencies() error { + // only install dependencies when running inside a container + if _, err := os.Stat("/.dockerenv"); os.IsNotExist(err) { + return nil + } + + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + binVersion := envtestBinVersion() + cmd := exec.Command("/usr/bin/bash", "-c", fmt.Sprintf(`go install sigs.k8s.io/controller-runtime/tools/setup-envtest@latest && \ + /root/go/bin/setup-envtest use -p path %s`, binVersion)) + + cmd.Env = append(os.Environ(), "GOPATH=/root/go") + assetsPath, err := cmd.Output() + if err != nil { + return err + } + os.Setenv("KUBEBUILDER_ASSETS", string(assetsPath)) + } + + // Output all embedded testdata files + // "testdata/sops" does not need to be saved in disk + // as it is being consumed directly from the embed.FS. + embedDirs := []string{"testdata/crd"} + for _, dir := range embedDirs { + err := os.MkdirAll(dir, 0o755) + if err != nil { + return fmt.Errorf("mkdir %s: %v", dir, err) + } + + templates, err := fs.ReadDir(testFiles, dir) + if err != nil { + return fmt.Errorf("reading embedded dir: %v", err) + } + + for _, template := range templates { + fileName := fmt.Sprintf("%s/%s", dir, template.Name()) + fmt.Println(fileName) + + data, err := testFiles.ReadFile(fileName) + if err != nil { + return fmt.Errorf("reading embedded file %s: %v", fileName, err) + } + + os.WriteFile(fileName, data, 0o644) + if err != nil { + return fmt.Errorf("writing %s: %v", fileName, err) + } + } + } + + return nil +} + +// FuzzControllers implements a fuzzer that targets the Kustomize controller. +// +// The test must ensure a valid test state around Kubernetes objects, as the +// focus is to ensure the controller behaves properly, not Kubernetes nor +// testing infrastructure. +func FuzzControllers(data []byte) int { + // Fuzzing has to be deterministic, so that input A can be + // associated with crash B consistently. The current approach + // taken by go-fuzz-headers to achieve that uses the data input + // as a buffer which is used until its end (i.e. EOF). + // + // The problem with this approach is when the test setup requires + // a higher amount of input than the available in the buffer, + // resulting in an invalid test state. + // + // This is currently being countered by openning two consumers on + // the data input, and requiring at least a length of 1000 to + // run the tests. + // + // During the migration to the native fuzz feature in go we should + // review this approach. + if len(data) < 1000 { + return 0 + } + fmt.Printf("Data input length: %d\n", len(data)) + + f := fuzz.NewConsumer(data) + ff := fuzz.NewConsumer(data) + + doOnce.Do(func() { + if err := ensureDependencies(); err != nil { + panic(fmt.Sprintf("Failed to ensure dependencies: %v", err)) + } + }) + + err := runInContext(func(testEnv *testenv.Environment) { + controllerName := "kustomize-controller" + reconciler := &controllers.KustomizationReconciler{ + ControllerName: controllerName, + Client: testEnv, + } + if err := (reconciler).SetupWithManager(testEnv, controllers.KustomizationReconcilerOptions{MaxConcurrentReconciles: 1}); err != nil { + panic(fmt.Sprintf("Failed to start GitRepositoryReconciler: %v", err)) + } + }, func() error { + dname, err := os.MkdirTemp("", "artifact-dir") + if err != nil { + return err + } + defer os.RemoveAll(dname) + + if err = createFiles(ff, dname); err != nil { + return err + } + + namespaceName, err := randStringRange(f, 1, 63) + if err != nil { + return err + } + + namespace, err := createNamespaceForFuzzing(namespaceName) + if err != nil { + return err + } + defer k8sClient.Delete(context.Background(), namespace) + + fmt.Println("createKubeConfigSecretForFuzzing...") + secret, err := createKubeConfigSecretForFuzzing(namespaceName) + if err != nil { + fmt.Println(err) + return err + } + defer k8sClient.Delete(context.Background(), secret) + + artifactFile, err := randStringRange(f, 1, 63) + if err != nil { + return err + } + fmt.Println("createArtifact...") + artifactChecksum, err := createArtifact(testServer, dname, artifactFile) + if err != nil { + fmt.Println(err) + return err + } + repName, err := randStringRange(f, 1, 63) + if err != nil { + return err + } + repositoryName := types.NamespacedName{ + Name: repName, + Namespace: namespaceName, + } + fmt.Println("ApplyGitRepository...") + err = applyGitRepository(repositoryName, artifactFile, "main/"+artifactChecksum) + if err != nil { + return err + } + pgpKey, err := testFiles.ReadFile("testdata/sops/pgp.asc") + if err != nil { + return err + } + ageKey, err := testFiles.ReadFile("testdata/sops/age.txt") + if err != nil { + return err + } + sskName, err := randStringRange(f, 1, 63) + if err != nil { + return err + } + sopsSecretKey := types.NamespacedName{ + Name: sskName, + Namespace: namespaceName, + } + + sopsSecret := &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: sopsSecretKey.Name, + Namespace: sopsSecretKey.Namespace, + }, + StringData: map[string]string{ + "pgp.asc": string(pgpKey), + "age.agekey": string(ageKey), + }, + } + + if err = k8sClient.Create(context.Background(), sopsSecret); err != nil { + return err + } + defer k8sClient.Delete(context.Background(), sopsSecret) + + kkName, err := randStringRange(f, 1, 63) + if err != nil { + return err + } + kustomizationKey := types.NamespacedName{ + Name: kkName, + Namespace: namespaceName, + } + kustomization := &kustomizev1.Kustomization{ + ObjectMeta: metav1.ObjectMeta{ + Name: kustomizationKey.Name, + Namespace: kustomizationKey.Namespace, + }, + Spec: kustomizev1.KustomizationSpec{ + Path: "./", + KubeConfig: &kustomizev1.KubeConfig{ + SecretRef: meta.LocalObjectReference{ + Name: "kubeconfig", + }, + }, + SourceRef: kustomizev1.CrossNamespaceSourceReference{ + Name: repositoryName.Name, + Namespace: repositoryName.Namespace, + Kind: sourcev1.GitRepositoryKind, + }, + Decryption: &kustomizev1.Decryption{ + Provider: "sops", + SecretRef: &meta.LocalObjectReference{ + Name: sopsSecretKey.Name, + }, + }, + TargetNamespace: namespaceName, + }, + } + + if err = k8sClient.Create(context.TODO(), kustomization); err != nil { + return err + } + + // ensure reconciliation of the kustomization above took place before moving on + time.Sleep(10 * time.Second) + + if err = k8sClient.Delete(context.TODO(), kustomization); err != nil { + return err + } + + // ensure the deferred deletion of all objects (namespace, secret, sopSecret) and + // the kustomization above were reconciled before moving on. This avoids unneccessary + // errors whilst tearing down the testing infrastructure. + time.Sleep(10 * time.Second) + + return nil + }, "testdata/crd") + + if err != nil { + fmt.Println(err) + return 0 + } + + return 1 +} + +// Allows the fuzzer to create a random lowercase string within a given range +func randStringRange(f *fuzz.ConsumeFuzzer, minLen, maxLen int) (string, error) { + stringLength, err := f.GetInt() + if err != nil { + return "", err + } + len := stringLength % maxLen + if len < minLen { + len += minLen + } + return f.GetStringFrom(string(letterRunes), len) +} + +// Creates a namespace and returns the created object. +func createNamespaceForFuzzing(name string) (*corev1.Namespace, error) { + namespace := &corev1.Namespace{ + ObjectMeta: metav1.ObjectMeta{Name: name}, + } + err := k8sClient.Create(context.Background(), namespace) + if err != nil { + return namespace, err + } + return namespace, nil +} + +// Creates a secret and returns the created object. +func createKubeConfigSecretForFuzzing(namespace string) (*corev1.Secret, error) { + secret := &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: "kubeconfig", + Namespace: namespace, + }, + Data: map[string][]byte{ + "value.yaml": kubeConfig, + }, + } + err := k8sClient.Create(context.Background(), secret) + if err != nil { + return secret, err + } + return secret, nil +} + +// Creates pseudo-random files in rootDir. +// Will create subdirs and place the files there. +// It is the callers responsibility to ensure that +// rootDir exists. +// +// Original source: +// https://github.com/AdaLogics/go-fuzz-headers/blob/9f22f86e471065b8d56861991dc885e27b1ae7de/consumer.go#L345 +// +// The change assures that as long as the f buffer has +// enough length to set numberOfFiles and the first fileName, +// this is returned without errors. +// Effectively making subDir and FileContent optional. +func createFiles(f *fuzz.ConsumeFuzzer, rootDir string) error { + noOfCreatedFiles := 0 + numberOfFiles, err := f.GetInt() + if err != nil { + return err + } + maxNoFiles := numberOfFiles % 10000 // + + for i := 0; i <= maxNoFiles; i++ { + fileName, err := f.GetString() + if err != nil { + if noOfCreatedFiles > 0 { + return nil + } else { + return errors.New("Could not get fileName") + } + } + if fileName == "" { + continue + } + + // leave subDir empty if no more strings are available. + subDir, _ := f.GetString() + + // Avoid going outside the root dir + if strings.Contains(subDir, "../") || (len(subDir) > 0 && subDir[0] == 47) || strings.Contains(subDir, "\\") { + continue // continue as this is not a permanent error + } + + dirPath, err := securejoin.SecureJoin(rootDir, subDir) + if err != nil { + continue // some errors here are not permanent, so we can try again with different values + } + + err = os.MkdirAll(dirPath, 0o755) + if err != nil { + if noOfCreatedFiles > 0 { + return nil + } else { + return errors.New("Could not create the subDir") + } + } + fullFilePath, err := securejoin.SecureJoin(dirPath, fileName) + if err != nil { + continue // potentially not a permanent error + } + + // leave fileContents empty if no more bytes are available, + // afterall empty files is a valid test case. + fileContents, _ := f.GetBytes() + + createdFile, err := os.Create(fullFilePath) + if err != nil { + createdFile.Close() + continue // some errors here are not permanent, so we can try again with different values + } + + _, err = createdFile.Write(fileContents) + if err != nil { + createdFile.Close() + if noOfCreatedFiles > 0 { + return nil + } else { + return errors.New("Could not write the file") + } + } + + createdFile.Close() + noOfCreatedFiles++ + } + return nil +} diff --git a/tests/fuzz/go.mod b/tests/fuzz/go.mod new file mode 100644 index 00000000..b36e2425 --- /dev/null +++ b/tests/fuzz/go.mod @@ -0,0 +1,5 @@ +module github.com/fluxcd/kustomize-controller/tests/fuzz +// This module is used only to avoid polluting the main module +// with fuzz dependencies. + +go 1.17 diff --git a/tests/fuzz/oss_fuzz_build.sh b/tests/fuzz/oss_fuzz_build.sh new file mode 100755 index 00000000..b5e37931 --- /dev/null +++ b/tests/fuzz/oss_fuzz_build.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash + +# Copyright 2022 The Flux authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -euxo pipefail + +GOPATH="${GOPATH:-/root/go}" +GO_SRC="${GOPATH}/src" +PROJECT_PATH="github.com/fluxcd/kustomize-controller" + +cd "${GO_SRC}" + +# Move fuzzer to their respective directories. +# This removes dependency noises from the modules' go.mod and go.sum files. +mv "${PROJECT_PATH}/tests/fuzz/age_fuzzer.go" "${PROJECT_PATH}/internal/sops/age/" +mv "${PROJECT_PATH}/tests/fuzz/pgp_fuzzer.go" "${PROJECT_PATH}/internal/sops/pgp/" + +# Some private functions within suite_test.go are extremly useful for testing. +# Instead of duplicating them here, or refactoring them away, this simply renames +# the file to make it available to "non-testing code". +# This is a temporary fix, which will cease once the implementation is migrated to +# the built-in fuzz support in golang 1.18. +cp "${PROJECT_PATH}/controllers/suite_test.go" "${PROJECT_PATH}/tests/fuzz/fuzzer_helper.go" +sed -i 's;KustomizationReconciler;abc.KustomizationReconciler;g' "${PROJECT_PATH}/tests/fuzz/fuzzer_helper.go" +sed -i 's;import (;import(\n abc "github.com/fluxcd/kustomize-controller/controllers";g' "${PROJECT_PATH}/tests/fuzz/fuzzer_helper.go" + +pushd "${PROJECT_PATH}" + +go mod tidy + +compile_go_fuzzer "${PROJECT_PATH}/internal/sops/age/" FuzzAge fuzz_age +compile_go_fuzzer "${PROJECT_PATH}/internal/sops/pgp/" FuzzPgp fuzz_pgp + +popd + +pushd "${PROJECT_PATH}/tests/fuzz" + +# Setup files to be embedded into controllers_fuzzer.go's testFiles variable. +mkdir -p testdata/crd +mkdir -p testdata/sops +cp ../../config/crd/bases/*.yaml testdata/crd +cp ../../controllers/testdata/sops/age.txt testdata/sops +cp ../../controllers/testdata/sops/pgp.asc testdata/sops + +go mod tidy + +compile_go_fuzzer "${PROJECT_PATH}/tests/fuzz/" FuzzControllers fuzz_controllers + +popd diff --git a/tests/fuzz/oss_fuzz_run.sh b/tests/fuzz/oss_fuzz_run.sh new file mode 100755 index 00000000..4c87f489 --- /dev/null +++ b/tests/fuzz/oss_fuzz_run.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash + +# Copyright 2022 The Flux authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -euxo pipefail + +# run each fuzzer once to ensure they are working properly +find /out -type f -name "fuzz*" -exec echo {} -runs=1 \; | bash -e diff --git a/tests/fuzz/pgp_fuzzer.go b/tests/fuzz/pgp_fuzzer.go new file mode 100644 index 00000000..504b2d75 --- /dev/null +++ b/tests/fuzz/pgp_fuzzer.go @@ -0,0 +1,39 @@ +//go:build gofuzz +// +build gofuzz + +/* +Copyright 2022 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package pgp + +import ( + fuzz "github.com/AdaLogics/go-fuzz-headers" +) + +// FuzzPgp implements a fuzzer that targets functions within pgp/keysource.go. +func FuzzPgp(data []byte) int { + f := fuzz.NewConsumer(data) + masterKey := MasterKey{} + + if err := f.GenerateStruct(&masterKey); err != nil { + return 0 + } + + _ = masterKey.Encrypt(data) + _ = masterKey.EncryptIfNeeded(data) + + return 1 +}