From 032909173e3eb1a7c0da4cbe7169a93f20667ffe Mon Sep 17 00:00:00 2001 From: Mustafa Gezen Date: Fri, 17 Feb 2023 19:35:58 +0100 Subject: [PATCH 1/3] Delete Apollo from this repo --- apollo/README.md | 2 + apollo/cmd/apollo/BUILD.bazel | 21 - apollo/cmd/apollo/ci/BUILD.bazel | 21 - apollo/cmd/apollo/ci/Chart.yaml | 6 - apollo/cmd/apollo/ci/deploy.jsonnet | 48 - apollo/cmd/apollo/ci/values.yaml | 3 - apollo/cmd/apollo/main.go | 67 - apollo/cmd/apollostarter/BUILD.bazel | 24 - apollo/cmd/apollostarter/ci/BUILD.bazel | 20 - apollo/cmd/apollostarter/ci/Chart.yaml | 6 - apollo/cmd/apollostarter/ci/deploy.jsonnet | 46 - apollo/cmd/apollostarter/ci/values.yaml | 1 - apollo/cmd/apollostarter/main.go | 153 -- apollo/cmd/apolloworker/BUILD.bazel | 27 - apollo/cmd/apolloworker/ci/BUILD.bazel | 20 - apollo/cmd/apolloworker/ci/Chart.yaml | 6 - apollo/cmd/apolloworker/ci/deploy.jsonnet | 46 - apollo/cmd/apolloworker/ci/values.yaml | 1 - apollo/cmd/apolloworker/main.go | 143 -- apollo/db/BUILD.bazel | 19 - apollo/db/connector/BUILD.bazel | 14 - apollo/db/connector/connector.go | 50 - apollo/db/convert.go | 155 -- apollo/db/db.go | 251 --- apollo/db/mock/BUILD.bazel | 14 - apollo/db/mock/mock.go | 774 -------- apollo/db/psql/BUILD.bazel | 15 - apollo/db/psql/psql.go | 797 -------- apollo/impl/v1/BUILD.bazel | 26 - apollo/impl/v1/advisory.go | 185 -- apollo/impl/v1/server.go | 98 - ...20210702021142_create_short_codes.down.sql | 33 - .../20210702021142_create_short_codes.up.sql | 40 - .../20210702021143_create_products.down.sql | 33 - .../20210702021143_create_products.up.sql | 51 - .../20210702041656_create_advisories.down.sql | 33 - .../20210702041656_create_advisories.up.sql | 52 - .../20210702041659_create_cves.down.sql | 33 - .../migrate/20210702041659_create_cves.up.sql | 41 - .../20210702041701_create_fixes.down.sql | 33 - .../20210702041701_create_fixes.up.sql | 40 - ...041756_create_advisory_references.down.sql | 33 - ...02041756_create_advisory_references.up.sql | 38 - ...02041956_create_affected_products.down.sql | 33 - ...0702041956_create_affected_products.up.sql | 42 - ...702043031_create_build_references.down.sql | 33 - ...10702043031_create_build_references.up.sql | 43 - ...0210703202420_create_mirror_state.down.sql | 33 - .../20210703202420_create_mirror_state.up.sql | 38 - ...210711014759_create_advisory_cves.down.sql | 33 - ...20210711014759_create_advisory_cves.up.sql | 39 - ...10711020255_create_advisory_fixes.down.sql | 33 - ...0210711020255_create_advisory_fixes.up.sql | 39 - ..._create_ignored_upstream_packages.down.sql | 33 - ...53_create_ignored_upstream_packages.up.sql | 38 - ...210717040945_create_advisory_rpms.down.sql | 33 - ...20210717040945_create_advisory_rpms.up.sql | 40 - ...20210803052113_updateinfo_history.down.sql | 33 - .../20210803052113_updateinfo_history.up.sql | 37 - ..._create_reboot_suggested_packages.down.sql | 1 - ...38_create_reboot_suggested_packages.up.sql | 6 - .../20220921231425_add_indexes.down.sql | 9 - .../migrate/20220921231425_add_indexes.up.sql | 9 - ...0221020182658_add_content_to_cves.down.sql | 1 - .../20221020182658_add_content_to_cves.up.sql | 1 - apollo/migrate/BUILD | 5 - apollo/proto/v1/BUILD.bazel | 65 - apollo/proto/v1/advisory.proto | 112 -- apollo/proto/v1/affected_product.proto | 41 - apollo/proto/v1/apollo.proto | 161 -- apollo/proto/v1/build.proto | 13 - apollo/proto/v1/cve.proto | 28 - apollo/proto/v1/fix.proto | 14 - apollo/proto/v1/short_code.proto | 29 - apollo/seed.sql | 82 - apollo/ui/BUILD.bazel | 60 - apollo/ui/deploy.jsonnet | 25 - apollo/ui/server/index.mjs | 61 - apollo/ui/src/api.ts | 39 - apollo/ui/src/components/Overview.tsx | 520 ------ apollo/ui/src/components/Root.tsx | 150 -- apollo/ui/src/components/ShowErrata.tsx | 343 ---- apollo/ui/src/entrypoint.tsx | 61 - apollo/ui/src/enumToText.tsx | 182 -- apollo/ui/src/styles.ts | 34 - apollo/ui/src/theme.ts | 52 - apollo/worker/BUILD.bazel | 15 - apollo/worker/worker.go | 82 - apollo/workflow/BUILD.bazel | 59 - apollo/workflow/autocreate_advisory.go | 231 --- apollo/workflow/autocreate_advisory_test.go | 31 - apollo/workflow/collect_cve_data.go | 81 - apollo/workflow/common.go | 31 - apollo/workflow/downstream_check.go | 203 --- apollo/workflow/downstream_check_test.go | 462 ----- apollo/workflow/poll_mirror_cve.go | 212 --- apollo/workflow/poll_mirror_cve_test.go | 118 -- apollo/workflow/poll_mirror_errata.go | 304 ---- apollo/workflow/poll_mirror_errata_test.go | 141 -- apollo/workflow/testdata/CVE-2021-3602.json | 112 -- apollo/workflow/testdata/RHBA-2021-2593.html | 1153 ------------ apollo/workflow/testdata/RHSA-2021-2595.html | 1154 ------------ apollo/workflow/testdata/RHSA-2022-1642.html | 1597 ----------------- apollo/workflow/update_cve_state.go | 194 -- apollo/workflow/update_cve_state_test.go | 249 --- apollo/workflow/workflow.go | 452 ----- apollo/workflow/workflow_test.go | 119 -- 107 files changed, 2 insertions(+), 13201 deletions(-) create mode 100644 apollo/README.md delete mode 100644 apollo/cmd/apollo/BUILD.bazel delete mode 100644 apollo/cmd/apollo/ci/BUILD.bazel delete mode 100644 apollo/cmd/apollo/ci/Chart.yaml delete mode 100644 apollo/cmd/apollo/ci/deploy.jsonnet delete mode 100644 apollo/cmd/apollo/ci/values.yaml delete mode 100644 apollo/cmd/apollo/main.go delete mode 100644 apollo/cmd/apollostarter/BUILD.bazel delete mode 100644 apollo/cmd/apollostarter/ci/BUILD.bazel delete mode 100644 apollo/cmd/apollostarter/ci/Chart.yaml delete mode 100644 apollo/cmd/apollostarter/ci/deploy.jsonnet delete mode 100644 apollo/cmd/apollostarter/ci/values.yaml delete mode 100644 apollo/cmd/apollostarter/main.go delete mode 100644 apollo/cmd/apolloworker/BUILD.bazel delete mode 100644 apollo/cmd/apolloworker/ci/BUILD.bazel delete mode 100644 apollo/cmd/apolloworker/ci/Chart.yaml delete mode 100644 apollo/cmd/apolloworker/ci/deploy.jsonnet delete mode 100644 apollo/cmd/apolloworker/ci/values.yaml delete mode 100644 apollo/cmd/apolloworker/main.go delete mode 100644 apollo/db/BUILD.bazel delete mode 100644 apollo/db/connector/BUILD.bazel delete mode 100644 apollo/db/connector/connector.go delete mode 100644 apollo/db/convert.go delete mode 100644 apollo/db/db.go delete mode 100644 apollo/db/mock/BUILD.bazel delete mode 100644 apollo/db/mock/mock.go delete mode 100644 apollo/db/psql/BUILD.bazel delete mode 100644 apollo/db/psql/psql.go delete mode 100644 apollo/impl/v1/BUILD.bazel delete mode 100644 apollo/impl/v1/advisory.go delete mode 100644 apollo/impl/v1/server.go delete mode 100644 apollo/migrate/20210702021142_create_short_codes.down.sql delete mode 100644 apollo/migrate/20210702021142_create_short_codes.up.sql delete mode 100644 apollo/migrate/20210702021143_create_products.down.sql delete mode 100644 apollo/migrate/20210702021143_create_products.up.sql delete mode 100644 apollo/migrate/20210702041656_create_advisories.down.sql delete mode 100644 apollo/migrate/20210702041656_create_advisories.up.sql delete mode 100644 apollo/migrate/20210702041659_create_cves.down.sql delete mode 100644 apollo/migrate/20210702041659_create_cves.up.sql delete mode 100644 apollo/migrate/20210702041701_create_fixes.down.sql delete mode 100644 apollo/migrate/20210702041701_create_fixes.up.sql delete mode 100644 apollo/migrate/20210702041756_create_advisory_references.down.sql delete mode 100644 apollo/migrate/20210702041756_create_advisory_references.up.sql delete mode 100644 apollo/migrate/20210702041956_create_affected_products.down.sql delete mode 100644 apollo/migrate/20210702041956_create_affected_products.up.sql delete mode 100644 apollo/migrate/20210702043031_create_build_references.down.sql delete mode 100644 apollo/migrate/20210702043031_create_build_references.up.sql delete mode 100644 apollo/migrate/20210703202420_create_mirror_state.down.sql delete mode 100644 apollo/migrate/20210703202420_create_mirror_state.up.sql delete mode 100644 apollo/migrate/20210711014759_create_advisory_cves.down.sql delete mode 100644 apollo/migrate/20210711014759_create_advisory_cves.up.sql delete mode 100644 apollo/migrate/20210711020255_create_advisory_fixes.down.sql delete mode 100644 apollo/migrate/20210711020255_create_advisory_fixes.up.sql delete mode 100644 apollo/migrate/20210713031253_create_ignored_upstream_packages.down.sql delete mode 100644 apollo/migrate/20210713031253_create_ignored_upstream_packages.up.sql delete mode 100644 apollo/migrate/20210717040945_create_advisory_rpms.down.sql delete mode 100644 apollo/migrate/20210717040945_create_advisory_rpms.up.sql delete mode 100644 apollo/migrate/20210803052113_updateinfo_history.down.sql delete mode 100644 apollo/migrate/20210803052113_updateinfo_history.up.sql delete mode 100644 apollo/migrate/20220913121538_create_reboot_suggested_packages.down.sql delete mode 100644 apollo/migrate/20220913121538_create_reboot_suggested_packages.up.sql delete mode 100644 apollo/migrate/20220921231425_add_indexes.down.sql delete mode 100644 apollo/migrate/20220921231425_add_indexes.up.sql delete mode 100644 apollo/migrate/20221020182658_add_content_to_cves.down.sql delete mode 100644 apollo/migrate/20221020182658_add_content_to_cves.up.sql delete mode 100644 apollo/migrate/BUILD delete mode 100644 apollo/proto/v1/BUILD.bazel delete mode 100644 apollo/proto/v1/advisory.proto delete mode 100644 apollo/proto/v1/affected_product.proto delete mode 100644 apollo/proto/v1/apollo.proto delete mode 100644 apollo/proto/v1/build.proto delete mode 100644 apollo/proto/v1/cve.proto delete mode 100644 apollo/proto/v1/fix.proto delete mode 100644 apollo/proto/v1/short_code.proto delete mode 100644 apollo/seed.sql delete mode 100644 apollo/ui/BUILD.bazel delete mode 100644 apollo/ui/deploy.jsonnet delete mode 100644 apollo/ui/server/index.mjs delete mode 100644 apollo/ui/src/api.ts delete mode 100644 apollo/ui/src/components/Overview.tsx delete mode 100644 apollo/ui/src/components/Root.tsx delete mode 100644 apollo/ui/src/components/ShowErrata.tsx delete mode 100644 apollo/ui/src/entrypoint.tsx delete mode 100644 apollo/ui/src/enumToText.tsx delete mode 100644 apollo/ui/src/styles.ts delete mode 100644 apollo/ui/src/theme.ts delete mode 100644 apollo/worker/BUILD.bazel delete mode 100644 apollo/worker/worker.go delete mode 100644 apollo/workflow/BUILD.bazel delete mode 100644 apollo/workflow/autocreate_advisory.go delete mode 100644 apollo/workflow/autocreate_advisory_test.go delete mode 100644 apollo/workflow/collect_cve_data.go delete mode 100644 apollo/workflow/common.go delete mode 100644 apollo/workflow/downstream_check.go delete mode 100644 apollo/workflow/downstream_check_test.go delete mode 100644 apollo/workflow/poll_mirror_cve.go delete mode 100644 apollo/workflow/poll_mirror_cve_test.go delete mode 100644 apollo/workflow/poll_mirror_errata.go delete mode 100644 apollo/workflow/poll_mirror_errata_test.go delete mode 100644 apollo/workflow/testdata/CVE-2021-3602.json delete mode 100644 apollo/workflow/testdata/RHBA-2021-2593.html delete mode 100644 apollo/workflow/testdata/RHSA-2021-2595.html delete mode 100644 apollo/workflow/testdata/RHSA-2022-1642.html delete mode 100644 apollo/workflow/update_cve_state.go delete mode 100644 apollo/workflow/update_cve_state_test.go delete mode 100644 apollo/workflow/workflow.go delete mode 100644 apollo/workflow/workflow_test.go diff --git a/apollo/README.md b/apollo/README.md new file mode 100644 index 0000000..27f2231 --- /dev/null +++ b/apollo/README.md @@ -0,0 +1,2 @@ +# Apollo has moved +Apollo v3 lives in distro-tools at https://github.com/resf/distro-tools diff --git a/apollo/cmd/apollo/BUILD.bazel b/apollo/cmd/apollo/BUILD.bazel deleted file mode 100644 index afe84b0..0000000 --- a/apollo/cmd/apollo/BUILD.bazel +++ /dev/null @@ -1,21 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library") - -go_library( - name = "apollo_lib", - srcs = ["main.go"], - importpath = "peridot.resf.org/apollo/cmd/apollo", - visibility = ["//visibility:private"], - deps = [ - "//apollo/db/connector", - "//apollo/impl/v1:impl", - "//utils", - "//vendor/github.com/sirupsen/logrus", - "//vendor/github.com/spf13/cobra", - ], -) - -go_binary( - name = "apollo", - embed = [":apollo_lib"], - visibility = ["//visibility:public"], -) diff --git a/apollo/cmd/apollo/ci/BUILD.bazel b/apollo/cmd/apollo/ci/BUILD.bazel deleted file mode 100644 index 410353c..0000000 --- a/apollo/cmd/apollo/ci/BUILD.bazel +++ /dev/null @@ -1,21 +0,0 @@ -load("//rules_resf:defs.bzl", "RESFDEPLOY_OUTS_MIGRATE", "container", "peridot_k8s") - -container( - base = "//bases/bazel/go", - files = [ - "//apollo/cmd/apollo", - ], - image_name = "apollo", - tars_to_layer = [ - "//apollo/migrate", - ], -) - -peridot_k8s( - name = "apollo", - src = "deploy.jsonnet", - outs = RESFDEPLOY_OUTS_MIGRATE, - chart_yaml = "Chart.yaml", - values_yaml = "values.yaml", - deps = ["//ci"], -) diff --git a/apollo/cmd/apollo/ci/Chart.yaml b/apollo/cmd/apollo/ci/Chart.yaml deleted file mode 100644 index e4fc115..0000000 --- a/apollo/cmd/apollo/ci/Chart.yaml +++ /dev/null @@ -1,6 +0,0 @@ -apiVersion: v2 -name: apollo -description: Helm chart for apollo -type: application -version: 0.0.1 -appVersion: "0.0.1" diff --git a/apollo/cmd/apollo/ci/deploy.jsonnet b/apollo/cmd/apollo/ci/deploy.jsonnet deleted file mode 100644 index a3a2b46..0000000 --- a/apollo/cmd/apollo/ci/deploy.jsonnet +++ /dev/null @@ -1,48 +0,0 @@ -local resfdeploy = import 'ci/resfdeploy.jsonnet'; -local db = import 'ci/db.jsonnet'; -local kubernetes = import 'ci/kubernetes.jsonnet'; -local temporal = import 'ci/temporal.jsonnet'; -local utils = import 'ci/utils.jsonnet'; - -resfdeploy.new({ - name: 'apollo', - replicas: 1, - dbname: 'apollo', - backend: true, - migrate: true, - legacyDb: true, - command: '/bundle/apollo', - image: kubernetes.tag('apollo'), - tag: kubernetes.version, - dsn: { - name: 'APOLLO_DATABASE_URL', - value: db.dsn_legacy('apollo'), - }, - requests: if kubernetes.prod() then { - cpu: '0.5', - memory: '512M', - }, - ports: [ - { - name: 'http', - containerPort: 9100, - protocol: 'TCP', - expose: true, - }, - { - name: 'grpc', - containerPort: 9101, - protocol: 'TCP', - }, - ], - health: { - port: 9100, - }, - env: [ - { - name: 'APOLLO_PRODUCTION', - value: if kubernetes.dev() then 'false' else 'true', - }, - $.dsn, - ] + temporal.kube_env('APOLLO'), -}) diff --git a/apollo/cmd/apollo/ci/values.yaml b/apollo/cmd/apollo/ci/values.yaml deleted file mode 100644 index 724e8ce..0000000 --- a/apollo/cmd/apollo/ci/values.yaml +++ /dev/null @@ -1,3 +0,0 @@ -# Ports under requires ingressHost to be set during deploy -http: - ingressHost: null diff --git a/apollo/cmd/apollo/main.go b/apollo/cmd/apollo/main.go deleted file mode 100644 index 001dab6..0000000 --- a/apollo/cmd/apollo/main.go +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package main - -import ( - "github.com/sirupsen/logrus" - "github.com/spf13/cobra" - apolloconnector "peridot.resf.org/apollo/db/connector" - apolloimpl "peridot.resf.org/apollo/impl/v1" - "peridot.resf.org/utils" -) - -var root = &cobra.Command{ - Use: "apollo", - Run: mn, -} - -var cnf = utils.NewFlagConfig() - -func init() { - cnf.DefaultPort = 9100 - - cnf.DatabaseName = utils.Pointer[string]("apollo") - cnf.Name = *cnf.DatabaseName - - root.PersistentFlags().String("homepage", "https://errata.build.resf.org", "Frontend root URL") - utils.AddFlags(root.PersistentFlags(), cnf) -} - -func mn(_ *cobra.Command, _ []string) { - apolloimpl.NewServer(apolloconnector.MustAuto()).Run() -} - -func main() { - utils.Main() - if err := root.Execute(); err != nil { - logrus.Fatal(err) - } -} diff --git a/apollo/cmd/apollostarter/BUILD.bazel b/apollo/cmd/apollostarter/BUILD.bazel deleted file mode 100644 index be4f65c..0000000 --- a/apollo/cmd/apollostarter/BUILD.bazel +++ /dev/null @@ -1,24 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library") - -go_library( - name = "apollostarter_lib", - srcs = ["main.go"], - importpath = "peridot.resf.org/apollo/cmd/apollostarter", - visibility = ["//visibility:private"], - deps = [ - "//apollo/db/connector", - "//apollo/worker", - "//proto:common", - "//temporalutils", - "//utils", - "//vendor/github.com/sirupsen/logrus", - "//vendor/github.com/spf13/cobra", - "//vendor/go.temporal.io/sdk/client", - ], -) - -go_binary( - name = "apollostarter", - embed = [":apollostarter_lib"], - visibility = ["//visibility:public"], -) diff --git a/apollo/cmd/apollostarter/ci/BUILD.bazel b/apollo/cmd/apollostarter/ci/BUILD.bazel deleted file mode 100644 index 7b4f2dc..0000000 --- a/apollo/cmd/apollostarter/ci/BUILD.bazel +++ /dev/null @@ -1,20 +0,0 @@ -load("//rules_resf:defs.bzl", "RESFDEPLOY_OUTS_MIGRATE", "container", "peridot_k8s") - -container( - base = "//bases/bazel/go", - files = [ - "//apollo/cmd/apollostarter", - ], - image_name = "apollostarter", -) - -peridot_k8s( - name = "apollostarter", - src = "deploy.jsonnet", - outs = RESFDEPLOY_OUTS_MIGRATE, - chart_yaml = "Chart.yaml", - values_yaml = "values.yaml", - deps = [ - "//ci", - ], -) diff --git a/apollo/cmd/apollostarter/ci/Chart.yaml b/apollo/cmd/apollostarter/ci/Chart.yaml deleted file mode 100644 index 7611f47..0000000 --- a/apollo/cmd/apollostarter/ci/Chart.yaml +++ /dev/null @@ -1,6 +0,0 @@ -apiVersion: v2 -name: apollostarter -description: Helm chart for apollostarter -type: application -version: 0.0.1 -appVersion: "0.0.1" diff --git a/apollo/cmd/apollostarter/ci/deploy.jsonnet b/apollo/cmd/apollostarter/ci/deploy.jsonnet deleted file mode 100644 index eb8ad81..0000000 --- a/apollo/cmd/apollostarter/ci/deploy.jsonnet +++ /dev/null @@ -1,46 +0,0 @@ -local resfdeploy = import 'ci/resfdeploy.jsonnet'; -local db = import 'ci/db.jsonnet'; -local kubernetes = import 'ci/kubernetes.jsonnet'; -local temporal = import 'ci/temporal.jsonnet'; -local utils = import 'ci/utils.jsonnet'; - -local site = std.extVar('site'); - -resfdeploy.new({ - name: 'apollostarter', - replicas: 1, - dbname: 'apollo', - backend: true, - migrate: true, - migrate_command: ['/bin/sh'], - migrate_args: ['-c', 'exit 0'], - legacyDb: true, - command: '/bundle/apollostarter', - image: kubernetes.tag('apollostarter'), - tag: kubernetes.version, - dsn: { - name: 'APOLLOSTARTER_DATABASE_URL', - value: db.dsn_legacy('apollo', false, 'apollostarter'), - }, - requests: if kubernetes.prod() then { - cpu: '1', - memory: '2G', - }, - ports: [ - { - name: 'http', - containerPort: 31209, - protocol: 'TCP', - }, - ], - health: { - port: 31209, - }, - env: [ - { - name: 'APOLLOSTARTER_PRODUCTION', - value: if kubernetes.dev() then 'false' else 'true', - }, - $.dsn, - ] + temporal.kube_env('APOLLOSTARTER'), -}) diff --git a/apollo/cmd/apollostarter/ci/values.yaml b/apollo/cmd/apollostarter/ci/values.yaml deleted file mode 100644 index f5e3403..0000000 --- a/apollo/cmd/apollostarter/ci/values.yaml +++ /dev/null @@ -1 +0,0 @@ -temporalHostPort: workflow-temporal-frontend.workflow.svc.cluster.local:7233 diff --git a/apollo/cmd/apollostarter/main.go b/apollo/cmd/apollostarter/main.go deleted file mode 100644 index 979b9ba..0000000 --- a/apollo/cmd/apollostarter/main.go +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package main - -import ( - "context" - "github.com/sirupsen/logrus" - "github.com/spf13/cobra" - "go.temporal.io/sdk/client" - "log" - apolloconnector "peridot.resf.org/apollo/db/connector" - "peridot.resf.org/apollo/worker" - commonpb "peridot.resf.org/common" - "peridot.resf.org/temporalutils" - "peridot.resf.org/utils" -) - -var root = &cobra.Command{ - Use: "apollostarter", - Run: mn, -} - -var cnf = utils.NewFlagConfig() - -func init() { - cnf.DefaultPort = 31209 - - cnf.DatabaseName = utils.Pointer[string]("apollo") - cnf.Name = "apollostarter" - - temporalutils.AddFlags(root.PersistentFlags()) - utils.AddFlags(root.PersistentFlags(), cnf) -} - -func mn(_ *cobra.Command, _ []string) { - c, err := temporalutils.NewClient(client.Options{}) - if err != nil { - logrus.Fatalln("unable to create Temporal client", err) - } - defer c.Close() - - db := apolloconnector.MustAuto() - - w, err := worker.NewWorker(&worker.NewWorkerInput{ - Temporal: c, - Database: db, - TaskQueue: "apollo-v1-main-queue", - }) - defer w.Client.Close() - - // Poll Red Hat for new CVEs and advisories every two hours - cveWfOpts := client.StartWorkflowOptions{ - ID: "cron_cve_mirror", - TaskQueue: w.TaskQueue, - CronSchedule: "0 */2 * * *", - } - _, err = w.Client.ExecuteWorkflow(context.Background(), cveWfOpts, w.WorkflowController.PollRedHatCVEsWorkflow) - if err != nil { - log.Fatalf("unable to start cve workflow: %v", err) - } - errataWfOpts := client.StartWorkflowOptions{ - ID: "cron_errata_mirror", - TaskQueue: w.TaskQueue, - CronSchedule: "0 */2 * * *", - } - _, err = w.Client.ExecuteWorkflow(context.Background(), errataWfOpts, w.WorkflowController.PollRedHatErrataWorkflow) - if err != nil { - log.Fatalf("unable to start errata workflow: %v", err) - } - - // Poll unresolved CVE status and update every hour - cveStatusWfOpts := client.StartWorkflowOptions{ - ID: "cron_cve_status", - TaskQueue: w.TaskQueue, - CronSchedule: "0 */1 * * *", - } - _, err = w.Client.ExecuteWorkflow(context.Background(), cveStatusWfOpts, w.WorkflowController.UpdateCVEStateWorkflow) - if err != nil { - log.Fatalf("unable to start cve status workflow: %v", err) - } - - // Check if CVE is fixed downstream every 10 minutes - cveDownstreamWfOpts := client.StartWorkflowOptions{ - ID: "cron_cve_downstream", - TaskQueue: w.TaskQueue, - CronSchedule: "*/10 * * * *", - } - _, err = w.Client.ExecuteWorkflow(context.Background(), cveDownstreamWfOpts, w.WorkflowController.DownstreamCVECheckWorkflow) - if err != nil { - log.Fatalf("unable to start cve downstream workflow: %v", err) - } - - // Auto create advisory for fixed CVEs every 30 minutes - cveAdvisoryWfOpts := client.StartWorkflowOptions{ - ID: "cron_cve_advisory", - TaskQueue: w.TaskQueue, - CronSchedule: "*/10 * * * *", - } - _, err = w.Client.ExecuteWorkflow(context.Background(), cveAdvisoryWfOpts, w.WorkflowController.AutoCreateAdvisoryWorkflow) - if err != nil { - log.Fatalf("unable to start cve advisory workflow: %v", err) - } - - // only added so we get a health endpoint - s := utils.NewGRPCServer( - nil, - func(r *utils.Register) { - err := commonpb.RegisterHealthCheckServiceHandlerFromEndpoint(r.Context, r.Mux, r.Endpoint, r.Options) - if err != nil { - logrus.Fatalf("could not register health service: %v", err) - } - }, - func(r *utils.RegisterServer) { - commonpb.RegisterHealthCheckServiceServer(r.Server, &utils.HealthServer{}) - }, - ) - s.WaitGroup.Wait() -} - -func main() { - utils.Main() - if err := root.Execute(); err != nil { - log.Fatal(err) - } -} diff --git a/apollo/cmd/apolloworker/BUILD.bazel b/apollo/cmd/apolloworker/BUILD.bazel deleted file mode 100644 index ccffae5..0000000 --- a/apollo/cmd/apolloworker/BUILD.bazel +++ /dev/null @@ -1,27 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library") - -go_library( - name = "apolloworker_lib", - srcs = ["main.go"], - importpath = "peridot.resf.org/apollo/cmd/apolloworker", - visibility = ["//visibility:private"], - deps = [ - "//apollo/db/connector", - "//apollo/rherrata", - "//apollo/rhsecurity", - "//apollo/worker", - "//apollo/workflow", - "//proto:common", - "//temporalutils", - "//utils", - "//vendor/github.com/sirupsen/logrus", - "//vendor/github.com/spf13/cobra", - "//vendor/go.temporal.io/sdk/client", - ], -) - -go_binary( - name = "apolloworker", - embed = [":apolloworker_lib"], - visibility = ["//visibility:public"], -) diff --git a/apollo/cmd/apolloworker/ci/BUILD.bazel b/apollo/cmd/apolloworker/ci/BUILD.bazel deleted file mode 100644 index bcf52c9..0000000 --- a/apollo/cmd/apolloworker/ci/BUILD.bazel +++ /dev/null @@ -1,20 +0,0 @@ -load("//rules_resf:defs.bzl", "RESFDEPLOY_OUTS_MIGRATE", "container", "peridot_k8s") - -container( - base = "//bases/bazel/go", - files = [ - "//apollo/cmd/apolloworker", - ], - image_name = "apolloworker", -) - -peridot_k8s( - name = "apolloworker", - src = "deploy.jsonnet", - outs = RESFDEPLOY_OUTS_MIGRATE, - chart_yaml = "Chart.yaml", - values_yaml = "values.yaml", - deps = [ - "//ci", - ], -) diff --git a/apollo/cmd/apolloworker/ci/Chart.yaml b/apollo/cmd/apolloworker/ci/Chart.yaml deleted file mode 100644 index a48eb17..0000000 --- a/apollo/cmd/apolloworker/ci/Chart.yaml +++ /dev/null @@ -1,6 +0,0 @@ -apiVersion: v2 -name: apolloworker -description: Helm chart for apolloworker -type: application -version: 0.0.1 -appVersion: "0.0.1" diff --git a/apollo/cmd/apolloworker/ci/deploy.jsonnet b/apollo/cmd/apolloworker/ci/deploy.jsonnet deleted file mode 100644 index 3b88202..0000000 --- a/apollo/cmd/apolloworker/ci/deploy.jsonnet +++ /dev/null @@ -1,46 +0,0 @@ -local resfdeploy = import 'ci/resfdeploy.jsonnet'; -local db = import 'ci/db.jsonnet'; -local kubernetes = import 'ci/kubernetes.jsonnet'; -local temporal = import 'ci/temporal.jsonnet'; -local utils = import 'ci/utils.jsonnet'; - -local site = std.extVar('site'); - -resfdeploy.new({ - name: 'apolloworker', - replicas: 1, - dbname: 'apollo', - backend: true, - migrate: true, - migrate_command: ['/bin/sh'], - migrate_args: ['-c', 'exit 0'], - legacyDb: true, - command: '/bundle/apolloworker', - image: kubernetes.tag('apolloworker'), - tag: kubernetes.version, - dsn: { - name: 'APOLLOWORKER_DATABASE_URL', - value: db.dsn_legacy('apollo', false, 'apolloworker'), - }, - requests: if kubernetes.prod() then { - cpu: '1', - memory: '2G', - }, - ports: [ - { - name: 'http', - containerPort: 29209, - protocol: 'TCP', - }, - ], - health: { - port: 29209, - }, - env: [ - { - name: 'APOLLOWORKER_PRODUCTION', - value: if kubernetes.dev() then 'false' else 'true', - }, - $.dsn, - ] + temporal.kube_env('APOLLOWORKER'), -}) diff --git a/apollo/cmd/apolloworker/ci/values.yaml b/apollo/cmd/apolloworker/ci/values.yaml deleted file mode 100644 index f5e3403..0000000 --- a/apollo/cmd/apolloworker/ci/values.yaml +++ /dev/null @@ -1 +0,0 @@ -temporalHostPort: workflow-temporal-frontend.workflow.svc.cluster.local:7233 diff --git a/apollo/cmd/apolloworker/main.go b/apollo/cmd/apolloworker/main.go deleted file mode 100644 index bd843c4..0000000 --- a/apollo/cmd/apolloworker/main.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package main - -import ( - "github.com/sirupsen/logrus" - "github.com/spf13/cobra" - "go.temporal.io/sdk/client" - "log" - apolloconnector "peridot.resf.org/apollo/db/connector" - "peridot.resf.org/apollo/rherrata" - "peridot.resf.org/apollo/rhsecurity" - "peridot.resf.org/apollo/worker" - "peridot.resf.org/apollo/workflow" - commonpb "peridot.resf.org/common" - "peridot.resf.org/temporalutils" - "peridot.resf.org/utils" - "sync" -) - -var root = &cobra.Command{ - Use: "apolloworker", - Run: mn, -} - -var cnf = utils.NewFlagConfig() - -func init() { - cnf.DefaultPort = 29209 - - cnf.DatabaseName = utils.Pointer[string]("apollo") - cnf.Name = "apolloworker" - - pflags := root.PersistentFlags() - pflags.String("vendor", "Rocky Enterprise Software Foundation", "Vendor name that is publishing the advisories") - - temporalutils.AddFlags(root.PersistentFlags()) - utils.AddFlags(root.PersistentFlags(), cnf) -} - -func mn(_ *cobra.Command, _ []string) { - c, err := temporalutils.NewClient(client.Options{}) - if err != nil { - logrus.Fatalln("unable to create Temporal client", err) - } - defer c.Close() - - db := apolloconnector.MustAuto() - - options := []workflow.Option{ - workflow.WithSecurityAPI(rhsecurity.NewAPIClient(rhsecurity.NewConfiguration()).DefaultApi), - workflow.WithErrataAPI(rherrata.NewClient()), - } - - w, err := worker.NewWorker( - &worker.NewWorkerInput{ - Temporal: c, - Database: db, - TaskQueue: "apollo-v1-main-queue", - }, - options..., - ) - defer w.Client.Close() - - w.Worker.RegisterWorkflow(w.WorkflowController.AutoCreateAdvisoryWorkflow) - w.Worker.RegisterWorkflow(w.WorkflowController.DownstreamCVECheckWorkflow) - w.Worker.RegisterWorkflow(w.WorkflowController.PollRedHatCVEsWorkflow) - w.Worker.RegisterWorkflow(w.WorkflowController.PollRedHatErrataWorkflow) - w.Worker.RegisterWorkflow(w.WorkflowController.UpdateCVEStateWorkflow) - - w.Worker.RegisterActivity(w.WorkflowController.AutoCreateAdvisoryActivity) - w.Worker.RegisterActivity(w.WorkflowController.GetAllShortCodesActivity) - w.Worker.RegisterActivity(w.WorkflowController.DownstreamCVECheckActivity) - w.Worker.RegisterActivity(w.WorkflowController.PollCVEProcessShortCodeActivity) - w.Worker.RegisterActivity(w.WorkflowController.ProcessRedHatErrataShortCodeActivity) - w.Worker.RegisterActivity(w.WorkflowController.UpdateCVEStateActivity) - - w.Worker.RegisterWorkflow(w.WorkflowController.CollectCVEDataWorkflow) - w.Worker.RegisterActivity(w.WorkflowController.CollectCVEDataActivity) - - var wg sync.WaitGroup - wg.Add(2) - - go func() { - w.Run() - wg.Done() - }() - - go func() { - // only added so we get a health endpoint - s := utils.NewGRPCServer( - nil, - func(r *utils.Register) { - err := commonpb.RegisterHealthCheckServiceHandlerFromEndpoint(r.Context, r.Mux, r.Endpoint, r.Options) - if err != nil { - logrus.Fatalf("could not register health service: %v", err) - } - }, - func(r *utils.RegisterServer) { - commonpb.RegisterHealthCheckServiceServer(r.Server, &utils.HealthServer{}) - }, - ) - s.WaitGroup.Wait() - wg.Done() - }() - - wg.Wait() -} - -func main() { - utils.Main() - if err := root.Execute(); err != nil { - log.Fatal(err) - } -} diff --git a/apollo/db/BUILD.bazel b/apollo/db/BUILD.bazel deleted file mode 100644 index 092b064..0000000 --- a/apollo/db/BUILD.bazel +++ /dev/null @@ -1,19 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "db", - srcs = [ - "convert.go", - "db.go", - ], - importpath = "peridot.resf.org/apollo/db", - visibility = ["//visibility:public"], - deps = [ - "//apollo/proto/v1:pb", - "//utils", - "//vendor/github.com/jmoiron/sqlx/types", - "//vendor/github.com/lib/pq", - "@org_golang_google_protobuf//types/known/timestamppb:go_default_library", - "@org_golang_google_protobuf//types/known/wrapperspb:go_default_library", - ], -) diff --git a/apollo/db/connector/BUILD.bazel b/apollo/db/connector/BUILD.bazel deleted file mode 100644 index d1dee1c..0000000 --- a/apollo/db/connector/BUILD.bazel +++ /dev/null @@ -1,14 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "connector", - srcs = ["connector.go"], - importpath = "peridot.resf.org/apollo/db/connector", - visibility = ["//visibility:public"], - deps = [ - "//apollo/db", - "//apollo/db/psql", - "//utils", - "//vendor/github.com/sirupsen/logrus", - ], -) diff --git a/apollo/db/connector/connector.go b/apollo/db/connector/connector.go deleted file mode 100644 index 08ae7c1..0000000 --- a/apollo/db/connector/connector.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package apolloconnector - -import ( - "github.com/sirupsen/logrus" - apollodb "peridot.resf.org/apollo/db" - apollopsql "peridot.resf.org/apollo/db/psql" - "peridot.resf.org/utils" -) - -// MustAuto automatically returns the correct access interface or fatally fails -func MustAuto() apollodb.Access { - dbType := utils.GetDbType() - switch dbType { - case utils.DbPostgres: - return apollopsql.New() - default: - logrus.Fatal("invalid database url supplied") - return nil - } -} diff --git a/apollo/db/convert.go b/apollo/db/convert.go deleted file mode 100644 index fe204d4..0000000 --- a/apollo/db/convert.go +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package apollodb - -import ( - "fmt" - "google.golang.org/protobuf/types/known/timestamppb" - "google.golang.org/protobuf/types/known/wrapperspb" - apollopb "peridot.resf.org/apollo/pb" - "strings" -) - -func DTOAdvisoryToPB(sc *Advisory) *apollopb.Advisory { - var errataType string - switch apollopb.Advisory_Type(sc.Type) { - case apollopb.Advisory_TYPE_SECURITY: - errataType = "SA" - break - case apollopb.Advisory_TYPE_BUGFIX: - errataType = "BA" - break - case apollopb.Advisory_TYPE_ENHANCEMENT: - errataType = "EA" - break - default: - errataType = "UNK" - break - } - - var publishedAt *timestamppb.Timestamp - if sc.PublishedAt.Valid { - publishedAt = timestamppb.New(sc.PublishedAt.Time) - } - - ret := &apollopb.Advisory{ - Type: apollopb.Advisory_Type(sc.Type), - ShortCode: sc.ShortCodeCode, - Name: fmt.Sprintf("%s%s-%d:%d", sc.ShortCodeCode, errataType, sc.Year, sc.Num), - Synopsis: sc.Synopsis, - Severity: apollopb.Advisory_Severity(sc.Severity), - Topic: sc.Topic, - Description: sc.Description, - AffectedProducts: sc.AffectedProducts, - Fixes: nil, - Cves: []*apollopb.CVE{}, - References: sc.References, - PublishedAt: publishedAt, - Rpms: nil, - RebootSuggested: sc.RebootSuggested, - } - if sc.Solution.Valid { - ret.Solution = &wrapperspb.StringValue{Value: sc.Solution.String} - } - for _, cve := range sc.Cves { - split := strings.SplitN(cve, ":::", 6) - ret.Cves = append(ret.Cves, &apollopb.CVE{ - Name: split[2], - SourceBy: wrapperspb.String(split[0]), - SourceLink: wrapperspb.String(split[1]), - Cvss3ScoringVector: wrapperspb.String(split[3]), - Cvss3BaseScore: wrapperspb.String(split[4]), - Cwe: wrapperspb.String(split[5]), - }) - } - if len(sc.Fixes) > 0 { - ret.Fixes = []*apollopb.Fix{} - } - for _, fix := range sc.Fixes { - split := strings.SplitN(fix, ":::", 4) - ret.Fixes = append(ret.Fixes, &apollopb.Fix{ - Ticket: wrapperspb.String(split[0]), - SourceBy: wrapperspb.String(split[1]), - SourceLink: wrapperspb.String(split[2]), - Description: wrapperspb.String(split[3]), - }) - } - if len(sc.RPMs) > 0 { - ret.Rpms = map[string]*apollopb.RPMs{} - } - for _, rpm := range sc.RPMs { - split := strings.SplitN(rpm, ":::", 2) - nvra := split[0] - productName := split[1] - if ret.Rpms[productName] == nil { - ret.Rpms[productName] = &apollopb.RPMs{} - } - - ret.Rpms[productName].Nvras = append(ret.Rpms[productName].Nvras, nvra) - } - - return ret -} - -func DTOListAdvisoriesToPB(scs []*Advisory) []*apollopb.Advisory { - var ret []*apollopb.Advisory - - for _, v := range scs { - ret = append(ret, DTOAdvisoryToPB(v)) - } - - return ret -} - -func DTOCVEToPB(cve *CVE) *apollopb.CVE { - ret := &apollopb.CVE{ - Name: cve.ID, - } - - if cve.SourceBy.Valid { - ret.SourceBy = wrapperspb.String(cve.SourceBy.String) - } - if cve.SourceLink.Valid { - ret.SourceLink = wrapperspb.String(cve.SourceLink.String) - } - - return ret -} - -func DTOListCVEsToPB(cves []*CVE) []*apollopb.CVE { - var ret []*apollopb.CVE - - for _, v := range cves { - ret = append(ret, DTOCVEToPB(v)) - } - - return ret -} diff --git a/apollo/db/db.go b/apollo/db/db.go deleted file mode 100644 index 3785ac9..0000000 --- a/apollo/db/db.go +++ /dev/null @@ -1,251 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package apollodb - -import ( - "database/sql" - "github.com/jmoiron/sqlx/types" - "github.com/lib/pq" - apollopb "peridot.resf.org/apollo/pb" - "peridot.resf.org/utils" - "time" -) - -// ShortCode is the DTO struct for `resf.apollo.ShortCode` -type ShortCode struct { - Code string `json:"code" db:"code"` - Mode int8 `json:"mode" db:"mode"` - CreatedAt *time.Time `json:"createdAt" db:"created_at"` - ArchivedAt sql.NullTime `json:"archivedAt" db:"archived_at"` -} - -// Advisory is the DTO struct for `resf.apollo.Advisory` -type Advisory struct { - ID int64 `db:"id"` - CreatedAt *time.Time `db:"created_at"` - - Year int `db:"year"` - Num int `db:"num"` - - Synopsis string `db:"synopsis"` - Topic string `db:"topic"` - Severity int `db:"severity"` - Type int `db:"type"` - Description string `db:"description"` - Solution sql.NullString `db:"solution"` - - RedHatIssuedAt sql.NullTime `db:"redhat_issued_at"` - ShortCodeCode string `db:"short_code_code"` - RebootSuggested bool `db:"reboot_suggested"` - PublishedAt sql.NullTime `db:"published_at"` - - AffectedProducts pq.StringArray `db:"affected_products"` - Fixes pq.StringArray `db:"fixes"` - Cves pq.StringArray `db:"cves"` - CveIds pq.StringArray `db:"cve_ids"` - References pq.StringArray `db:"references"` - RPMs pq.StringArray `db:"rpms"` - BuildArtifacts pq.StringArray `db:"build_artifacts"` - - // Only used for list/search queries - Total int64 `json:"total" db:"total"` -} - -// CVE is the DTO struct for `resf.apollo.CVE` -type CVE struct { - ID string `db:"id"` - CreatedAt *time.Time `db:"created_at"` - - AdvisoryId sql.NullInt64 `db:"advisory_id"` - ShortCode string `db:"short_code_code"` - - SourceBy sql.NullString `db:"source_by"` - SourceLink sql.NullString `db:"source_link"` - - Content types.NullJSONText `db:"content"` - - AffectedProductId sql.NullInt64 `db:"affected_product_id"` -} - -// AffectedProduct is the DTO struct for `resf.apollo.AffectedProduct` -type AffectedProduct struct { - ID int64 `db:"id"` - ProductID int64 `db:"product_id"` - CveID sql.NullString `db:"cve_id"` - State int `db:"state"` - Version string `db:"version"` - Package string `db:"package"` - Advisory sql.NullString `db:"advisory"` -} - -// Product is the DTO struct for `resf.apollo.Product` -type Product struct { - ID int64 `db:"id"` - Name string `db:"name"` - - CurrentFullVersion string `db:"current_full_version"` - RedHatMajorVersion sql.NullInt32 `db:"redhat_major_version"` - ShortCode string `db:"short_code_code"` - Archs pq.StringArray `db:"archs"` - MirrorFromDate sql.NullTime `json:"mirrorFromDate" db:"mirror_from_date"` - RedHatProductPrefix sql.NullString `json:"redHatProductPrefix" db:"redhat_product_prefix"` - Cpe sql.NullString `json:"cpe" db:"cpe"` - EolAt sql.NullTime `json:"eolAt" db:"eol_at"` - - BuildSystem string `json:"buildSystem" db:"build_system"` - BuildSystemEndpoint string `json:"buildSystemEndpoint" db:"build_system_endpoint"` - KojiCompose sql.NullString `json:"kojiCompose" db:"koji_compose"` - KojiModuleCompose sql.NullString `json:"kojiModuleCompose" db:"koji_module_compose"` - PeridotProjectID sql.NullString `json:"peridotProjectID" db:"peridot_project_id"` -} - -type BuildReference struct { - ID int64 `db:"id"` - AffectedProductId int64 `db:"affected_product_id"` - Rpm string `db:"rpm"` - SrcRpm string `db:"src_rpm"` - CveID string `db:"cve_id"` - Sha256Sum string `db:"sha256_sum"` - KojiID sql.NullString `db:"koji_id"` - PeridotID sql.NullString `db:"peridot_id"` -} - -type Fix struct { - ID int64 `db:"id"` - Ticket sql.NullString `db:"ticket"` - SourceBy sql.NullString `db:"source_by"` - SourceLink sql.NullString `db:"source_link"` - Description sql.NullString `db:"description"` -} - -type AdvisoryReference struct { - ID int64 `db:"advisory_reference"` - URL string `db:"url"` - AdvisoryId int64 `db:"advisory_id"` -} - -type MirrorState struct { - ShortCode string `db:"short_code_code"` - LastSync sql.NullTime `db:"last_sync"` - ErrataAfter sql.NullTime `db:"errata_after"` -} - -type AdvisoryCVE struct { - AdvisoryID int64 `db:"advisory_id"` - CveID string `db:"cve_id"` -} - -type AdvisoryFix struct { - AdvisoryID int64 `db:"advisory_id"` - FixID int64 `db:"fix_id"` -} - -type IgnoredUpstreamPackage struct { - ID int64 `db:"id"` - ProductID int64 `db:"product_id"` - Package string `db:"package"` -} - -type RebootSuggestedPackage struct { - CreatedAt *time.Time `db:"created_at"` - Name string `db:"name"` -} - -type AdvisoryRPM struct { - AdvisoryID int64 `db:"advisory_id"` - Name string `db:"name"` - ProductID int64 `db:"product_id"` -} - -type Access interface { - GetAllShortCodes() ([]*ShortCode, error) - GetShortCodeByCode(code string) (*ShortCode, error) - CreateShortCode(code string, mode apollopb.ShortCode_Mode) (*ShortCode, error) - - GetAllAdvisories(filters *apollopb.AdvisoryFilters, page int32, limit int32) ([]*Advisory, error) - // Advisory is a broad entity with lots of fields - // mustafa: It is in my opinion better to accept the same struct - // to create and update it. - // Obviously fields like ID and CreatedAt cannot be overridden - // The Create and Update methods for advisory do not return - // the following fields: - // - AffectedProducts - // - Fixes - // - Cves - // - References - CreateAdvisory(advisory *Advisory) (*Advisory, error) - // Update cannot override the RedHatIssuedAt field for mirrored advisories - UpdateAdvisory(advisory *Advisory) (*Advisory, error) - GetAdvisoryByCodeAndYearAndNum(code string, year int, num int) (*Advisory, error) - - GetAllUnresolvedCVEs() ([]*CVE, error) - GetPendingAffectedProducts() ([]*AffectedProduct, error) - GetAllCVEsFixedDownstream() ([]*CVE, error) - GetCVEByID(id string) (*CVE, error) - GetAllCVEs() ([]*CVE, error) - CreateCVE(cveId string, shortCode string, sourceBy *string, sourceLink *string, content types.NullJSONText) (*CVE, error) - SetCVEContent(cveId string, content types.JSONText) error - - GetProductsByShortCode(code string) ([]*Product, error) - GetProductByNameAndShortCode(product string, code string) (*Product, error) - GetProductByID(id int64) (*Product, error) - CreateProduct(name string, currentFullVersion string, redHatMajorVersion *int32, code string, archs []string) (*Product, error) - - GetAllAffectedProductsByCVE(cve string) ([]*AffectedProduct, error) - GetAffectedProductByCVEAndPackage(cve string, pkg string) (*AffectedProduct, error) - GetAffectedProductByAdvisory(advisory string) (*AffectedProduct, error) - GetAffectedProductByID(id int64) (*AffectedProduct, error) - CreateAffectedProduct(productId int64, cveId string, state int, version string, pkg string, advisory *string) (*AffectedProduct, error) - UpdateAffectedProductStateAndPackageAndAdvisory(id int64, state int, pkg string, advisory *string) error - DeleteAffectedProduct(id int64) error - - CreateFix(ticket string, sourceBy string, sourceLink string, description string) (int64, error) - - // This will return nil rather than an error if no rows are found - GetMirrorState(code string) (*MirrorState, error) - UpdateMirrorState(code string, lastSync *time.Time) error - UpdateMirrorStateErrata(code string, lastSync *time.Time) error - GetMaxLastSync() (*time.Time, error) - - CreateBuildReference(affectedProductId int64, rpm string, srcRpm string, cveId string, sha256Sum string, kojiId *string, peridotId *string) (*BuildReference, error) - CreateAdvisoryReference(advisoryId int64, url string) error - - GetAllIgnoredPackagesByProductID(productID int64) ([]string, error) - GetAllRebootSuggestedPackages() ([]string, error) - - // These add methods is treated like an upsert. They're only added if one doesn't exist - AddAdvisoryFix(advisoryId int64, fixId int64) error - AddAdvisoryCVE(advisoryId int64, cveId string) error - AddAdvisoryRPM(advisoryId int64, name string, productID int64) error - - Begin() (utils.Tx, error) - UseTransaction(tx utils.Tx) Access -} diff --git a/apollo/db/mock/BUILD.bazel b/apollo/db/mock/BUILD.bazel deleted file mode 100644 index 3e9340e..0000000 --- a/apollo/db/mock/BUILD.bazel +++ /dev/null @@ -1,14 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "mock", - srcs = ["mock.go"], - importpath = "peridot.resf.org/apollo/db/mock", - visibility = ["//visibility:public"], - deps = [ - "//apollo/db", - "//apollo/proto/v1:pb", - "//utils", - "//vendor/github.com/jmoiron/sqlx/types", - ], -) diff --git a/apollo/db/mock/mock.go b/apollo/db/mock/mock.go deleted file mode 100644 index 8bc4607..0000000 --- a/apollo/db/mock/mock.go +++ /dev/null @@ -1,774 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package apollomock - -import ( - "database/sql" - "fmt" - "github.com/jmoiron/sqlx/types" - apollodb "peridot.resf.org/apollo/db" - apollopb "peridot.resf.org/apollo/pb" - "peridot.resf.org/utils" - "time" -) - -type Access struct { - ShortCodes []*apollodb.ShortCode - Advisories []*apollodb.Advisory - Cves []*apollodb.CVE - Fixes []*apollodb.Fix - AdvisoryReferences []*apollodb.AdvisoryReference - Products []*apollodb.Product - AffectedProducts []*apollodb.AffectedProduct - BuildReferences []*apollodb.BuildReference - MirrorStates []*apollodb.MirrorState - AdvisoryCVEs []*apollodb.AdvisoryCVE - AdvisoryFixes []*apollodb.AdvisoryFix - IgnoredUpstreamPackages []*apollodb.IgnoredUpstreamPackage - RebootSuggestedPackages []*apollodb.RebootSuggestedPackage - AdvisoryRPMs []*apollodb.AdvisoryRPM -} - -func New() *Access { - return &Access{ - ShortCodes: []*apollodb.ShortCode{}, - Advisories: []*apollodb.Advisory{}, - Cves: []*apollodb.CVE{}, - Fixes: []*apollodb.Fix{}, - AdvisoryReferences: []*apollodb.AdvisoryReference{}, - Products: []*apollodb.Product{}, - AffectedProducts: []*apollodb.AffectedProduct{}, - BuildReferences: []*apollodb.BuildReference{}, - MirrorStates: []*apollodb.MirrorState{}, - AdvisoryCVEs: []*apollodb.AdvisoryCVE{}, - AdvisoryFixes: []*apollodb.AdvisoryFix{}, - IgnoredUpstreamPackages: []*apollodb.IgnoredUpstreamPackage{}, - RebootSuggestedPackages: []*apollodb.RebootSuggestedPackage{}, - AdvisoryRPMs: []*apollodb.AdvisoryRPM{}, - } -} - -func (a *Access) GetAllShortCodes() ([]*apollodb.ShortCode, error) { - return a.ShortCodes, nil -} - -func (a *Access) GetShortCodeByCode(code string) (*apollodb.ShortCode, error) { - for _, val := range a.ShortCodes { - if val.Code == code { - return val, nil - } - } - - return nil, sql.ErrNoRows -} - -func (a *Access) CreateShortCode(code string, mode apollopb.ShortCode_Mode) (*apollodb.ShortCode, error) { - now := time.Now() - - shortCode := apollodb.ShortCode{ - Code: code, - Mode: int8(mode), - CreatedAt: &now, - ArchivedAt: sql.NullTime{}, - } - a.ShortCodes = append(a.ShortCodes, &shortCode) - - return &shortCode, nil -} - -func (a *Access) getAdvisoriesWithJoin(filter func(*apollodb.Advisory) bool) []*apollodb.Advisory { - var advisories []*apollodb.Advisory - for _, val := range a.Advisories { - if filter(val) { - advisories = append(advisories, val) - } - } - - if len(advisories) == 0 { - return advisories - } - - for _, advisory := range advisories { - advisory.AffectedProducts = []string{} - advisory.Fixes = []string{} - advisory.Cves = []string{} - advisory.References = []string{} - advisory.RPMs = []string{} - advisory.BuildArtifacts = []string{} - - for _, advisoryCve := range a.AdvisoryCVEs { - if advisoryCve.AdvisoryID != advisory.ID { - continue - } - - for _, buildReference := range a.BuildReferences { - if buildReference.CveID == advisoryCve.CveID { - advisory.BuildArtifacts = append(advisory.BuildArtifacts, fmt.Sprintf("%s:::%s", buildReference.Rpm, buildReference.SrcRpm)) - } - } - - for _, cve := range a.Cves { - if cve.ID == advisoryCve.CveID { - cveString := fmt.Sprintf("%s:::%s:::%s", cve.SourceBy.String, cve.SourceLink.String, cve.ID) - if !utils.StrContains(cveString, advisory.Cves) { - advisory.Cves = append(advisory.Cves, cveString) - } - } - } - for _, val := range a.AffectedProducts { - if val.CveID.String == advisoryCve.CveID { - for _, product := range a.Products { - if val.ProductID == product.ID { - if !utils.StrContains(product.Name, advisory.AffectedProducts) { - advisory.AffectedProducts = append(advisory.AffectedProducts, product.Name) - } - } - } - } - } - } - - for _, advisoryFix := range a.AdvisoryFixes { - if advisoryFix.AdvisoryID != advisory.ID { - continue - } - - for _, fix := range a.Fixes { - if fix.ID == advisoryFix.FixID { - if !utils.StrContains(fix.Ticket.String, advisory.Fixes) { - advisory.Fixes = append(advisory.Fixes, fix.Ticket.String) - } - } - } - } - - for _, advisoryReference := range a.AdvisoryReferences { - if advisoryReference.AdvisoryId != advisory.ID { - continue - } - - if !utils.StrContains(advisoryReference.URL, advisory.References) { - advisory.References = append(advisory.References, advisoryReference.URL) - } - } - - for _, advisoryRPM := range a.AdvisoryRPMs { - if advisoryRPM.AdvisoryID != advisory.ID { - continue - } - - if !utils.StrContains(advisoryRPM.Name, advisory.RPMs) { - advisory.RPMs = append(advisory.RPMs, advisoryRPM.Name) - } - } - } - - return advisories -} - -func (a *Access) GetAllAdvisories(filters *apollopb.AdvisoryFilters, page int32, limit int32) ([]*apollodb.Advisory, error) { - return a.getAdvisoriesWithJoin(func(advisory *apollodb.Advisory) bool { - if filters.Product != nil { - if !utils.StrContains(filters.Product.Value, advisory.AffectedProducts) { - return false - } - } - if advisory.PublishedAt.Valid { - if filters.Before != nil { - if advisory.PublishedAt.Time.After(filters.Before.AsTime()) { - return false - } - } - if filters.After != nil { - if advisory.PublishedAt.Time.Before(filters.After.AsTime()) { - return false - } - } - } - if filters.IncludeUnpublished != nil { - if !filters.IncludeUnpublished.Value && !advisory.PublishedAt.Valid { - return false - } - } else { - if !advisory.PublishedAt.Valid { - return false - } - } - - if advisory.Fixes != nil && len(advisory.Fixes) < 1 { - return false - } - - return true - }), nil -} - -func (a *Access) GetAdvisoryByCodeAndYearAndNum(code string, year int, num int) (*apollodb.Advisory, error) { - advisories := a.getAdvisoriesWithJoin(func(advisory *apollodb.Advisory) bool { - if advisory.ShortCodeCode == code && advisory.Year == year && advisory.Num == num { - return true - } - - return false - }) - - if len(advisories) == 0 { - return nil, sql.ErrNoRows - } - - advisory := advisories[0] - - if advisory.Fixes != nil && len(advisory.Fixes) < 1 { - return nil, fmt.Errorf("Expected advisory fixes. Was empty.") - } - - return advisory, nil -} - -func (a *Access) CreateAdvisory(advisory *apollodb.Advisory) (*apollodb.Advisory, error) { - var lastId int64 = 1 - if len(a.Advisories) > 0 { - lastId = a.Advisories[len(a.Advisories)-1].ID + 1 - } - - now := time.Now() - ret := &apollodb.Advisory{ - ID: lastId, - CreatedAt: &now, - Year: advisory.Year, - Num: advisory.Num, - Synopsis: advisory.Synopsis, - Topic: advisory.Topic, - Severity: advisory.Severity, - Type: advisory.Type, - Description: advisory.Description, - Solution: advisory.Solution, - RedHatIssuedAt: advisory.RedHatIssuedAt, - ShortCodeCode: advisory.ShortCodeCode, - PublishedAt: advisory.PublishedAt, - } - - return ret, nil -} - -func (a *Access) UpdateAdvisory(advisory *apollodb.Advisory) (*apollodb.Advisory, error) { - for _, val := range a.Advisories { - if val.ID == advisory.ID { - val.Year = advisory.Year - val.Num = advisory.Num - val.Synopsis = advisory.Synopsis - val.Topic = advisory.Topic - val.Severity = advisory.Severity - val.Type = advisory.Type - val.Description = advisory.Description - val.Solution = advisory.Solution - val.ShortCodeCode = advisory.ShortCodeCode - val.PublishedAt = advisory.PublishedAt - - return val, nil - } - } - - return nil, sql.ErrNoRows -} - -func (a *Access) GetAllUnresolvedCVEs() ([]*apollodb.CVE, error) { - var cves []*apollodb.CVE - var addedCVEIds []string - - for _, cve := range a.Cves { - for _, affectedProduct := range a.AffectedProducts { - if affectedProduct.CveID.String == cve.ID { - switch affectedProduct.State { - case - int(apollopb.AffectedProduct_STATE_UNDER_INVESTIGATION_UPSTREAM), - int(apollopb.AffectedProduct_STATE_UNDER_INVESTIGATION_DOWNSTREAM), - int(apollopb.AffectedProduct_STATE_AFFECTED_UPSTREAM), - int(apollopb.AffectedProduct_STATE_AFFECTED_DOWNSTREAM): - nCve := *cve - nCve.AffectedProductId = sql.NullInt64{Valid: true, Int64: affectedProduct.ID} - cves = append(cves, &nCve) - break - } - } - } - } - for _, cve := range a.Cves { - if !utils.StrContains(cve.ID, addedCVEIds) { - cves = append(cves, cve) - } - } - - return cves, nil -} - -func (a *Access) GetPendingAffectedProducts() ([]*apollodb.AffectedProduct, error) { - var ret []*apollodb.AffectedProduct - - for _, affectedProduct := range a.AffectedProducts { - if affectedProduct.State == int(apollopb.AffectedProduct_STATE_FIXED_UPSTREAM) { - ret = append(ret, affectedProduct) - } - } - - return ret, nil -} - -func (a *Access) GetAllCVEsFixedDownstream() ([]*apollodb.CVE, error) { - var cves []*apollodb.CVE - - for _, cve := range a.Cves { - for _, affectedProduct := range a.AffectedProducts { - if affectedProduct.CveID.String == cve.ID { - if affectedProduct.State == int(apollopb.AffectedProduct_STATE_FIXED_DOWNSTREAM) { - nCve := *cve - nCve.AffectedProductId = sql.NullInt64{Valid: true, Int64: affectedProduct.ID} - cves = append(cves, &nCve) - break - } - } - } - } - - return cves, nil -} - -func (a *Access) GetCVEByID(id string) (*apollodb.CVE, error) { - for _, cve := range a.Cves { - if cve.ID == id { - return cve, nil - } - } - - return nil, sql.ErrNoRows -} - -func (a *Access) GetAllCVEs() ([]*apollodb.CVE, error) { - return a.Cves, nil -} - -func (a *Access) CreateCVE(cveId string, shortCode string, sourceBy *string, sourceLink *string, content types.NullJSONText) (*apollodb.CVE, error) { - var sby sql.NullString - var sl sql.NullString - - if sourceBy != nil { - sby.String = *sourceBy - sby.Valid = true - } - - if sourceLink != nil { - sl.String = *sourceLink - sl.Valid = true - } - - now := time.Now() - cve := &apollodb.CVE{ - ID: cveId, - CreatedAt: &now, - AdvisoryId: sql.NullInt64{}, - ShortCode: shortCode, - SourceBy: sby, - SourceLink: sl, - Content: content, - } - a.Cves = append(a.Cves, cve) - - return cve, nil -} - -func (a *Access) SetCVEContent(cveId string, content types.JSONText) error { - for _, cve := range a.Cves { - if cve.ID == cveId { - cve.Content = types.NullJSONText{Valid: true, JSONText: content} - return nil - } - } - - return sql.ErrNoRows -} - -func (a *Access) GetProductsByShortCode(code string) ([]*apollodb.Product, error) { - var products []*apollodb.Product - - for _, product := range a.Products { - if product.ShortCode == code { - products = append(products, product) - } - } - - return products, nil -} - -func (a *Access) GetProductByNameAndShortCode(name string, code string) (*apollodb.Product, error) { - for _, product := range a.Products { - if product.Name == name && product.ShortCode == code { - return product, nil - } - } - - return nil, sql.ErrNoRows -} - -func (a *Access) GetProductByID(id int64) (*apollodb.Product, error) { - for _, product := range a.Products { - if product.ID == id { - return product, nil - } - } - - return nil, sql.ErrNoRows -} - -func (a *Access) CreateProduct(name string, currentFullVersion string, redHatMajorVersion *int32, code string, archs []string) (*apollodb.Product, error) { - var lastId int64 = 1 - if len(a.Products) > 0 { - lastId = a.Products[len(a.Products)-1].ID + 1 - } - - var rhmv sql.NullInt32 - if redHatMajorVersion != nil { - rhmv.Int32 = *redHatMajorVersion - rhmv.Valid = true - } - - product := &apollodb.Product{ - ID: lastId, - Name: name, - CurrentFullVersion: currentFullVersion, - RedHatMajorVersion: rhmv, - ShortCode: code, - Archs: archs, - MirrorFromDate: sql.NullTime{}, - RedHatProductPrefix: sql.NullString{}, - } - a.Products = append(a.Products, product) - - return product, nil -} - -func (a *Access) GetAllAffectedProductsByCVE(cve string) ([]*apollodb.AffectedProduct, error) { - var affectedProducts []*apollodb.AffectedProduct - - for _, affectedProduct := range a.AffectedProducts { - if affectedProduct.CveID.String == cve { - affectedProducts = append(affectedProducts, affectedProduct) - } - } - - return affectedProducts, nil -} - -func (a *Access) GetAffectedProductByCVEAndPackage(cve string, pkg string) (*apollodb.AffectedProduct, error) { - for _, affectedProduct := range a.AffectedProducts { - if affectedProduct.CveID.String == cve && affectedProduct.Package == pkg { - return affectedProduct, nil - } - } - - return nil, sql.ErrNoRows -} - -func (a *Access) GetAffectedProductByAdvisory(advisory string) (*apollodb.AffectedProduct, error) { - for _, affectedProduct := range a.AffectedProducts { - if affectedProduct.Advisory.String == advisory { - return affectedProduct, nil - } - } - - return nil, sql.ErrNoRows -} - -func (a *Access) GetAffectedProductByID(id int64) (*apollodb.AffectedProduct, error) { - for _, affectedProduct := range a.AffectedProducts { - if affectedProduct.ID == id { - return affectedProduct, nil - } - } - - return nil, sql.ErrNoRows -} - -func (a *Access) CreateAffectedProduct(productId int64, cveId string, state int, version string, pkg string, advisory *string) (*apollodb.AffectedProduct, error) { - var lastId int64 = 1 - if len(a.AffectedProducts) > 0 { - lastId = a.AffectedProducts[len(a.AffectedProducts)-1].ID + 1 - } - - var adv sql.NullString - if advisory != nil { - adv.String = *advisory - adv.Valid = true - } - - affectedProduct := &apollodb.AffectedProduct{ - ID: lastId, - ProductID: productId, - CveID: sql.NullString{Valid: true, String: cveId}, - State: state, - Version: version, - Package: pkg, - Advisory: adv, - } - a.AffectedProducts = append(a.AffectedProducts, affectedProduct) - - return affectedProduct, nil -} - -func (a *Access) UpdateAffectedProductStateAndPackageAndAdvisory(id int64, state int, pkg string, advisory *string) error { - for _, affectedProduct := range a.AffectedProducts { - if affectedProduct.ID == id { - affectedProduct.State = state - affectedProduct.Package = pkg - - var adv sql.NullString - if advisory != nil { - adv.String = *advisory - adv.Valid = true - } - affectedProduct.Advisory = adv - - return nil - } - } - - return sql.ErrNoRows -} - -func (a *Access) DeleteAffectedProduct(id int64) error { - var index *int - for i, affectedProduct := range a.AffectedProducts { - if affectedProduct.ID == id { - index = &i - } - } - if index == nil { - return sql.ErrNoRows - } - - a.AffectedProducts = append(a.AffectedProducts[:*index], a.AffectedProducts[*index+1:]...) - - return nil -} - -func (a *Access) CreateFix(ticket string, sourceBy string, sourceLink string, description string) (int64, error) { - var lastId int64 = 1 - if len(a.Fixes) > 0 { - lastId = a.Fixes[len(a.Fixes)-1].ID + 1 - } - - fix := &apollodb.Fix{ - ID: lastId, - Ticket: sql.NullString{Valid: true, String: ticket}, - SourceBy: sql.NullString{Valid: true, String: sourceBy}, - SourceLink: sql.NullString{Valid: true, String: sourceLink}, - Description: sql.NullString{Valid: true, String: description}, - } - a.Fixes = append(a.Fixes, fix) - - return lastId, nil -} - -func (a *Access) GetMirrorState(code string) (*apollodb.MirrorState, error) { - var lastSync *apollodb.MirrorState - - for _, mirrorState := range a.MirrorStates { - if mirrorState.ShortCode == code { - if mirrorState.LastSync.Valid { - lastSync = mirrorState - } - } - } - - if lastSync == nil { - return nil, sql.ErrNoRows - } - - return lastSync, nil -} - -func (a *Access) UpdateMirrorState(code string, lastSync *time.Time) error { - for _, mirrorState := range a.MirrorStates { - if mirrorState.ShortCode == code { - mirrorState.LastSync.Time = *lastSync - mirrorState.LastSync.Valid = true - - return nil - } - } - - mirrorState := &apollodb.MirrorState{ - ShortCode: code, - LastSync: sql.NullTime{Valid: true, Time: *lastSync}, - } - a.MirrorStates = append(a.MirrorStates, mirrorState) - - return nil -} - -func (a *Access) UpdateMirrorStateErrata(code string, lastSync *time.Time) error { - for _, mirrorState := range a.MirrorStates { - if mirrorState.ShortCode == code { - mirrorState.ErrataAfter.Time = *lastSync - mirrorState.ErrataAfter.Valid = true - - return nil - } - } - - mirrorState := &apollodb.MirrorState{ - ShortCode: code, - ErrataAfter: sql.NullTime{Valid: true, Time: *lastSync}, - } - a.MirrorStates = append(a.MirrorStates, mirrorState) - - return nil -} - -func (a *Access) GetMaxLastSync() (*time.Time, error) { - var maxLastSync *time.Time - - for _, mirrorState := range a.MirrorStates { - if mirrorState.LastSync.Valid { - if maxLastSync == nil || mirrorState.LastSync.Time.After(*maxLastSync) { - maxLastSync = &mirrorState.LastSync.Time - } - } - } - - if maxLastSync == nil { - return nil, sql.ErrNoRows - } - - return maxLastSync, nil -} - -func (a *Access) CreateBuildReference(affectedProductId int64, rpm string, srcRpm string, cveId string, sha256Sum string, kojiId *string, peridotId *string) (*apollodb.BuildReference, error) { - var lastId int64 = 1 - if len(a.BuildReferences) > 0 { - lastId = a.BuildReferences[len(a.BuildReferences)-1].ID + 1 - } - - buildReference := &apollodb.BuildReference{ - ID: lastId, - AffectedProductId: affectedProductId, - Rpm: rpm, - SrcRpm: srcRpm, - CveID: cveId, - Sha256Sum: sha256Sum, - } - if kojiId != nil { - buildReference.KojiID = sql.NullString{Valid: true, String: *kojiId} - } - if peridotId != nil { - buildReference.PeridotID = sql.NullString{Valid: true, String: *peridotId} - } - - a.BuildReferences = append(a.BuildReferences, buildReference) - - return buildReference, nil -} - -func (a *Access) CreateAdvisoryReference(advisoryId int64, url string) error { - var lastId int64 = 1 - if len(a.AdvisoryReferences) > 0 { - lastId = a.AdvisoryReferences[len(a.AdvisoryReferences)-1].ID + 1 - } - - advisoryReference := &apollodb.AdvisoryReference{ - ID: lastId, - URL: url, - AdvisoryId: advisoryId, - } - a.AdvisoryReferences = append(a.AdvisoryReferences, advisoryReference) - - return nil -} - -func (a *Access) GetAllIgnoredPackagesByProductID(productID int64) ([]string, error) { - var packages []string - - for _, ignoredPackage := range a.IgnoredUpstreamPackages { - if ignoredPackage.ProductID == productID { - packages = append(packages, ignoredPackage.Package) - } - } - - return packages, nil -} - -func (a *Access) GetAllRebootSuggestedPackages() ([]string, error) { - var packages []string - - for _, p := range a.RebootSuggestedPackages { - packages = append(packages, p.Name) - } - - return packages, nil -} - -func (a *Access) AddAdvisoryFix(advisoryId int64, fixId int64) error { - advisoryFix := &apollodb.AdvisoryFix{ - AdvisoryID: advisoryId, - FixID: fixId, - } - a.AdvisoryFixes = append(a.AdvisoryFixes, advisoryFix) - - return nil -} - -func (a *Access) AddAdvisoryCVE(advisoryId int64, cveId string) error { - advisoryCVE := &apollodb.AdvisoryCVE{ - AdvisoryID: advisoryId, - CveID: cveId, - } - a.AdvisoryCVEs = append(a.AdvisoryCVEs, advisoryCVE) - - return nil -} - -func (a *Access) AddAdvisoryRPM(advisoryId int64, name string, productID int64) error { - advisoryRPM := &apollodb.AdvisoryRPM{ - AdvisoryID: advisoryId, - Name: name, - ProductID: productID, - } - a.AdvisoryRPMs = append(a.AdvisoryRPMs, advisoryRPM) - - return nil -} - -func (a *Access) Begin() (utils.Tx, error) { - return &utils.MockTx{}, nil -} - -func (a *Access) UseTransaction(_ utils.Tx) apollodb.Access { - return a -} diff --git a/apollo/db/psql/BUILD.bazel b/apollo/db/psql/BUILD.bazel deleted file mode 100644 index 243f0ef..0000000 --- a/apollo/db/psql/BUILD.bazel +++ /dev/null @@ -1,15 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "psql", - srcs = ["psql.go"], - importpath = "peridot.resf.org/apollo/db/psql", - visibility = ["//visibility:public"], - deps = [ - "//apollo/db", - "//apollo/proto/v1:pb", - "//utils", - "//vendor/github.com/jmoiron/sqlx", - "//vendor/github.com/jmoiron/sqlx/types", - ], -) diff --git a/apollo/db/psql/psql.go b/apollo/db/psql/psql.go deleted file mode 100644 index e5ab41a..0000000 --- a/apollo/db/psql/psql.go +++ /dev/null @@ -1,797 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package apollopsql - -import ( - "database/sql" - "github.com/jmoiron/sqlx/types" - apollodb "peridot.resf.org/apollo/db" - apollopb "peridot.resf.org/apollo/pb" - "time" - - "github.com/jmoiron/sqlx" - "peridot.resf.org/utils" -) - -type Access struct { - db *sqlx.DB - query utils.SqlQuery -} - -func New() *Access { - pgx := utils.PgInitx() - return &Access{ - db: pgx, - query: pgx, - } -} - -func (a *Access) GetAllShortCodes() ([]*apollodb.ShortCode, error) { - var shortCodes []*apollodb.ShortCode - err := a.query.Select( - &shortCodes, - ` - select - code, - mode, - created_at, - archived_at - from short_codes - order by created_at desc - `, - ) - if err != nil { - return nil, err - } - - return shortCodes, nil -} - -func (a *Access) GetShortCodeByCode(code string) (*apollodb.ShortCode, error) { - var shortCode apollodb.ShortCode - err := a.query.Get(&shortCode, "select code, mode, created_at from short_codes where code = $1", code) - if err != nil { - return nil, err - } - - return &shortCode, nil -} - -func (a *Access) CreateShortCode(code string, mode apollopb.ShortCode_Mode) (*apollodb.ShortCode, error) { - var shortCode apollodb.ShortCode - err := a.query.Get(&shortCode, "insert into short_codes (code, mode) values ($1, $2) returning code, mode, created_at", code, int(mode)) - if err != nil { - return nil, err - } - - return &shortCode, nil -} - -func (a *Access) GetAllAdvisories(filters *apollopb.AdvisoryFilters, page int32, limit int32) ([]*apollodb.Advisory, error) { - if filters == nil { - filters = &apollopb.AdvisoryFilters{} - } - - var advisories []*apollodb.Advisory - err := a.query.Select( - &advisories, - ` - select - a.id, - a.created_at, - a.year, - a.num, - a.synopsis, - a.topic, - a.severity, - a.type, - a.description, - a.solution, - a.redhat_issued_at, - a.short_code_code, - a.reboot_suggested, - a.published_at, - array_remove(array_agg(distinct p.name), NULL) as affected_products, - (select array_agg(distinct(f.ticket || ':::' || f.source_by || ':::' || f.source_link || ':::' || f.description)) from advisory_fixes adf inner join fixes f on f.id = adf.fix_id where adf.advisory_id = a.id) as fixes, - (select array_agg(distinct( - case when c.content is null then c.source_by || ':::' || c.source_link || ':::' || c.id || ':::::::::' - else c.source_by || ':::' || c.source_link || ':::' || c.id || ':::' || jsonb_extract_path_text(c.content, 'cvss3', 'cvss3_scoring_vector') || ':::' || jsonb_extract_path_text(c.content, 'cvss3', 'cvss3_base_score') || ':::' || jsonb_extract_path_text(c.content, 'cwe') - end - )) from advisory_cves ac inner join cves c on c.id = ac.cve_id where ac.advisory_id = a.id) as cves, - (select array_agg(distinct(url)) from advisory_references where advisory_id = a.id) as references, - case when $4 :: bool = true then array(select distinct concat(rpm, ':::', src_rpm) from build_references where affected_product_id in (select id from affected_products where advisory = 'RH' || (case when a.type=1 then 'SA' when a.type=2 then 'BA' else 'EA' end) || '-' || a.year || ':' || a.num)) - else array [] :: text[] - end as build_artifacts, - case when $7 :: bool = true then array(select distinct(ar.name || ':::' || p.name) from advisory_rpms ar inner join products p on p.id = ar.product_id where advisory_id = a.id) - else array [] :: text[] - end as rpms, - count(a.*) over() as total - from advisories a - inner join affected_products ap on ap.advisory = 'RH' || (case when a.type=1 then 'SA' when a.type=2 then 'BA' else 'EA' end) || '-' || a.year || ':' || a.num - inner join products p on ap.product_id = p.id - where - ($1 :: text is null or p.name = $1 :: text) - and ($2 :: timestamp is null or a.published_at < $2 :: timestamp) - and ($3 :: timestamp is null or a.published_at > $3 :: timestamp) - and (a.published_at is not null or $4 :: bool = true) - and ($5 :: text is null or exists (select cve_id from advisory_cves where advisory_id = a.id and cve_id ilike '%' || $5 :: text || '%')) - and ($6 :: text is null or a.synopsis ilike '%' || $6 :: text || '%') - and ($8 :: text is null or ((a.synopsis ilike '%' || $8 :: text || '%') or (a.topic ilike '%' || $8 :: text || '%') or (a.description ilike '%' || $8 :: text || '%') or (a.solution ilike '%' || $8 :: text || '%') or exists (select cve_id from advisory_cves where advisory_id = a.id and cve_id ilike '%' || $8 :: text || '%') or (a.short_code_code || (case when a.type=1 then 'SA' when a.type=2 then 'BA' else 'EA' end) || '-' || a.year || ':' || a.num ilike '%' || $8 :: text || '%'))) - and ($9 :: numeric = 0 or a.severity = $9 :: numeric) - and ($10 :: numeric = 0 or a.type = $10 :: numeric) - group by a.id - order by a.published_at desc - limit $11 offset $12 - `, - utils.StringValueToNullString(filters.Product), - utils.TimestampToNullTime(filters.Before), - utils.TimestampToNullTime(filters.After), - utils.BoolValueP(filters.IncludeUnpublished), - utils.StringValueToNullString(filters.Cve), - utils.StringValueToNullString(filters.Synopsis), - utils.BoolValueP(filters.IncludeRpms), - utils.StringValueToNullString(filters.Keyword), - int32(filters.Severity), - int32(filters.Type), - utils.UnlimitedLimit(limit), - utils.GetOffset(page, limit), - ) - if err != nil { - return nil, err - } - - return advisories, nil -} - -func (a *Access) GetAdvisoryByCodeAndYearAndNum(code string, year int, num int) (*apollodb.Advisory, error) { - var advisory apollodb.Advisory - err := a.query.Get( - &advisory, - ` - select - a.id, - a.created_at, - a.year, - a.num, - a.synopsis, - a.topic, - a.severity, - a.type, - a.description, - a.solution, - a.redhat_issued_at, - a.short_code_code, - a.reboot_suggested, - a.published_at, - array_remove(array_agg(distinct p.name), NULL) as affected_products, - (select array_agg(distinct(f.ticket || ':::' || f.source_by || ':::' || f.source_link || ':::' || f.description)) from advisory_fixes adf inner join fixes f on f.id = adf.fix_id where adf.advisory_id = a.id) as fixes, - (select array_agg(distinct( - case when c.content is null then c.source_by || ':::' || c.source_link || ':::' || c.id || ':::::::::' - else c.source_by || ':::' || c.source_link || ':::' || c.id || ':::' || jsonb_extract_path_text(c.content, 'cvss3', 'cvss3_scoring_vector') || ':::' || jsonb_extract_path_text(c.content, 'cvss3', 'cvss3_base_score') || ':::' || jsonb_extract_path_text(c.content, 'cwe') - end - )) from advisory_cves ac inner join cves c on c.id = ac.cve_id where ac.advisory_id = a.id) as cves, - (select array_agg(distinct(url)) from advisory_references where advisory_id = a.id) as references, - (select array_agg(distinct(ar.name || ':::' || p.name)) from advisory_rpms ar inner join products p on p.id = ar.product_id where advisory_id = a.id) as rpms - from advisories a - inner join affected_products ap on ap.advisory = 'RH' || (case when a.type=1 then 'SA' when a.type=2 then 'BA' else 'EA' end) || '-' || a.year || ':' || a.num - inner join products p on ap.product_id = p.id - where - a.year = $1 - and a.num = $2 - and a.short_code_code = $3 - group by a.id - `, - year, - num, - code, - ) - if err != nil { - return nil, err - } - - return &advisory, nil -} - -func (a *Access) CreateAdvisory(advisory *apollodb.Advisory) (*apollodb.Advisory, error) { - var ret apollodb.Advisory - - var redHatIssuedAt *time.Time - var publishedAt *time.Time - - if advisory.RedHatIssuedAt.Valid { - redHatIssuedAt = &advisory.RedHatIssuedAt.Time - } - if advisory.PublishedAt.Valid { - publishedAt = &advisory.PublishedAt.Time - } - - err := a.query.Get( - &ret, - ` - insert into advisories - (year, num, synopsis, topic, severity, type, description, solution, - redhat_issued_at, short_code_code, reboot_suggested, published_at) - values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) - returning - id, - created_at, - year, - num, - synopsis, - topic, - severity, - type, - description, - solution, - redhat_issued_at, - short_code_code, - reboot_suggested, - published_at - `, - advisory.Year, - advisory.Num, - advisory.Synopsis, - advisory.Topic, - advisory.Severity, - advisory.Type, - advisory.Description, - advisory.Solution, - redHatIssuedAt, - advisory.ShortCodeCode, - advisory.RebootSuggested, - publishedAt, - ) - if err != nil { - return nil, err - } - - return &ret, nil -} - -func (a *Access) UpdateAdvisory(advisory *apollodb.Advisory) (*apollodb.Advisory, error) { - var ret apollodb.Advisory - - var publishedAt *time.Time - - if advisory.PublishedAt.Valid { - publishedAt = &advisory.PublishedAt.Time - } - - err := a.query.Get( - &ret, - ` - update advisories - set - year = $1, - num = $2, - synopsis = $3, - topic = $4, - severity = $5, - type = $6, - description = $7, - solution = $8, - short_code_code = $9, - reboot_suggested = $10, - published_at = $11 - where - id = $12 - returning - id, - created_at, - year, - num, - synopsis, - topic, - severity, - type, - description, - solution, - redhat_issued_at, - short_code_code, - reboot_suggested, - published_at - `, - advisory.Year, - advisory.Num, - advisory.Synopsis, - advisory.Topic, - advisory.Severity, - advisory.Type, - advisory.Description, - advisory.Solution, - advisory.ShortCodeCode, - advisory.RebootSuggested, - publishedAt, - advisory.ID, - ) - if err != nil { - return nil, err - } - - return &ret, nil -} - -func (a *Access) GetAllUnresolvedCVEs() ([]*apollodb.CVE, error) { - var cves []*apollodb.CVE - err := a.query.Select( - &cves, - ` - select - c.id, - c.created_at, - c.short_code_code, - c.source_by, - c.source_link, - c.content, - ap.id as affected_product_id - from cves c - left join affected_products ap on ap.cve_id = c.id - where (ap.state is null or ap.state in (1, 2, 8, 9)) - `, - ) - if err != nil { - return nil, err - } - - return cves, nil -} - -func (a *Access) GetPendingAffectedProducts() ([]*apollodb.AffectedProduct, error) { - var ret []*apollodb.AffectedProduct - err := a.query.Select( - &ret, - ` - select - ap.id, - ap.product_id, - ap.cve_id, - ap.state, - ap.version, - ap.package, - ap.advisory - from affected_products ap - where ap.state = 3 - `, - ) - if err != nil { - return nil, err - } - - return ret, nil -} - -func (a *Access) GetAllCVEsFixedDownstream() ([]*apollodb.CVE, error) { - var cves []*apollodb.CVE - err := a.query.Select( - &cves, - ` - select - c.id, - c.created_at, - c.short_code_code, - c.source_by, - c.source_link, - c.content, - ap.id as affected_product_id - from cves c - inner join affected_products ap on ap.cve_id = c.id - where - ap.state = 4 - `, - ) - if err != nil { - return nil, err - } - - return cves, nil -} - -func (a *Access) GetCVEByID(id string) (*apollodb.CVE, error) { - var cve apollodb.CVE - err := a.query.Get(&cve, "select id, created_at, short_code_code, source_by, source_link, content from cves where id = $1", id) - if err != nil { - return nil, err - } - - return &cve, nil -} - -func (a *Access) GetAllCVEs() ([]*apollodb.CVE, error) { - var cves []*apollodb.CVE - err := a.query.Select(&cves, "select id, created_at, short_code_code, source_by, source_link, content from cves") - if err != nil { - return nil, err - } - - return cves, nil -} - -func (a *Access) CreateCVE(cveId string, shortCode string, sourceBy *string, sourceLink *string, content types.NullJSONText) (*apollodb.CVE, error) { - var cve apollodb.CVE - err := a.query.Get(&cve, "insert into cves (id, short_code_code, source_by, source_link, content) values ($1, $2, $3, $4, $5) returning id, created_at, short_code_code, source_by, source_link, content", cveId, shortCode, sourceBy, sourceLink, content) - if err != nil { - return nil, err - } - - return &cve, nil -} - -func (a *Access) SetCVEContent(cveId string, content types.JSONText) error { - _, err := a.query.Exec("update cves set content = $1 where id = $2", content, cveId) - return err -} - -func (a *Access) GetProductsByShortCode(code string) ([]*apollodb.Product, error) { - var products []*apollodb.Product - err := a.query.Select( - &products, - ` - select - id, - name, - current_full_version, - redhat_major_version, - short_code_code, - archs, - mirror_from_date, - redhat_product_prefix, - cpe, - eol_at, - build_system, - build_system_endpoint, - koji_compose, - koji_module_compose, - peridot_project_id - from products - where - short_code_code = $1 - and (eol_at < now() or eol_at is null) - `, - code, - ) - if err != nil { - return nil, err - } - - return products, nil -} - -func (a *Access) GetProductByNameAndShortCode(name string, code string) (*apollodb.Product, error) { - var product apollodb.Product - err := a.query.Get( - &product, - ` - select - id, - name, - current_full_version, - redhat_major_version, - short_code_code, - archs, - mirror_from_date, - redhat_product_prefix, - cpe, - eol_at, - build_system, - build_system_endpoint, - koji_compose, - koji_module_compose, - peridot_project_id - from products - where - name = $1 - and short_code_code = $2 - `, - name, - code, - ) - if err != nil { - return nil, err - } - - return &product, nil -} - -func (a *Access) GetProductByID(id int64) (*apollodb.Product, error) { - var product apollodb.Product - err := a.query.Get( - &product, - ` - select - id, - name, - current_full_version, - redhat_major_version, - short_code_code, - archs, - mirror_from_date, - redhat_product_prefix, - cpe, - eol_at, - build_system, - build_system_endpoint, - koji_compose, - koji_module_compose, - peridot_project_id - from products - where - id = $1 - `, - id, - ) - if err != nil { - return nil, err - } - - return &product, nil -} - -func (a *Access) CreateProduct(name string, currentFullVersion string, redHatMajorVersion *int32, code string, archs []string) (*apollodb.Product, error) { - var product apollodb.Product - err := a.query.Get(&product, "insert into products (name, current_full_version, redhat_major_version, short_code_code, archs) values ($1, $2, $3, $4) returning id, name, current_full_version, redhat_major_version, short_code_code, archs", name, currentFullVersion, redHatMajorVersion, code, archs) - if err != nil { - return nil, err - } - - return &product, nil -} - -func (a *Access) GetAllAffectedProductsByCVE(cve string) ([]*apollodb.AffectedProduct, error) { - var affectedProducts []*apollodb.AffectedProduct - err := a.query.Select(&affectedProducts, "select id, product_id, cve_id, state, version, package, advisory from affected_products where cve_id = $1", cve) - if err != nil { - return nil, err - } - - return affectedProducts, nil -} - -func (a *Access) GetAffectedProductByCVEAndPackage(cve string, pkg string) (*apollodb.AffectedProduct, error) { - var affectedProduct apollodb.AffectedProduct - err := a.query.Get(&affectedProduct, "select id, product_id, cve_id, state, version, package, advisory from affected_products where cve_id = $1 and package = $2", cve, pkg) - if err != nil { - return nil, err - } - - return &affectedProduct, nil -} - -func (a *Access) GetAffectedProductByAdvisory(advisory string) (*apollodb.AffectedProduct, error) { - var affectedProduct apollodb.AffectedProduct - err := a.query.Get(&affectedProduct, "select id, product_id, cve_id, state, version, package, advisory from affected_products where advisory = $1", advisory) - if err != nil { - return nil, err - } - - return &affectedProduct, nil -} - -func (a *Access) GetAffectedProductByID(id int64) (*apollodb.AffectedProduct, error) { - var affectedProduct apollodb.AffectedProduct - err := a.query.Get(&affectedProduct, "select id, product_id, cve_id, state, version, package, advisory from affected_products where id = $1", id) - if err != nil { - return nil, err - } - - return &affectedProduct, nil -} - -func (a *Access) CreateAffectedProduct(productId int64, cveId string, state int, version string, pkg string, advisory *string) (*apollodb.AffectedProduct, error) { - var affectedProduct apollodb.AffectedProduct - err := a.query.Get(&affectedProduct, "insert into affected_products (product_id, cve_id, state, version, package, advisory) values ($1, $2, $3, $4, $5, $6) returning id, product_id, cve_id, state, version, package, advisory", productId, cveId, state, version, pkg, advisory) - if err != nil { - return nil, err - } - - return &affectedProduct, nil -} - -func (a *Access) UpdateAffectedProductStateAndPackageAndAdvisory(id int64, state int, pkg string, advisory *string) error { - _, err := a.query.Exec( - ` - update affected_products - set - state = $1, - package = $2, - advisory = $3 - where id = $4 - `, - state, - pkg, - advisory, - id, - ) - return err -} - -func (a *Access) DeleteAffectedProduct(id int64) error { - _, err := a.query.Exec( - ` - delete from affected_products - where id = $1 - `, - id, - ) - return err -} - -func (a *Access) CreateFix(ticket string, sourceBy string, sourceLink, description string) (int64, error) { - var id int64 - err := a.query.Get(&id, "insert into fixes (ticket, source_by, source_link, description) values ($1, $2, $3, $4) returning id", ticket, sourceBy, sourceLink, description) - return id, err -} - -func (a *Access) GetMirrorState(code string) (*apollodb.MirrorState, error) { - var lastSync apollodb.MirrorState - err := a.query.Get(&lastSync, "select short_code_code, last_sync, errata_after from mirror_state where short_code_code = $1", code) - if err != nil { - if err == sql.ErrNoRows { - return nil, nil - } - - return nil, err - } - - return &lastSync, nil -} - -func (a *Access) UpdateMirrorState(code string, lastSync *time.Time) error { - _, err := a.query.Exec( - ` - insert into mirror_state (short_code_code, last_sync) - values ($1, $2) - on conflict (short_code_code) do - update - set last_sync = EXCLUDED.last_sync - `, - code, - lastSync, - ) - return err -} - -func (a *Access) UpdateMirrorStateErrata(code string, lastSync *time.Time) error { - _, err := a.query.Exec( - ` - insert into mirror_state (short_code_code, errata_after) - values ($1, $2) - on conflict (short_code_code) do - update - set errata_after = EXCLUDED.errata_after - `, - code, - lastSync, - ) - return err -} - -func (a *Access) GetMaxLastSync() (*time.Time, error) { - var lastSync time.Time - err := a.query.Get(&lastSync, "select max(last_sync) from mirror_state") - if err != nil { - return nil, err - } - - return &lastSync, nil -} - -func (a *Access) CreateBuildReference(affectedProductId int64, rpm string, srcRpm string, cveId string, sha256Sum string, kojiId *string, peridotId *string) (*apollodb.BuildReference, error) { - var buildReference apollodb.BuildReference - err := a.query.Get( - &buildReference, - ` - insert into build_references - (affected_product_id, rpm, src_rpm, cve_id, sha256_sum, koji_id, peridot_id) - values ($1, $2, $3, $4, $5, $6, $7) - returning id, affected_product_id, rpm, src_rpm, cve_id, sha256_sum, koji_id, peridot_id - `, - affectedProductId, - rpm, - srcRpm, - cveId, - sha256Sum, - kojiId, - peridotId, - ) - if err != nil { - return nil, err - } - - return &buildReference, nil -} - -func (a *Access) CreateAdvisoryReference(advisoryId int64, url string) error { - _, err := a.query.Exec("insert into advisory_references (advisory_id, url) values ($1, $2)", advisoryId, url) - return err -} - -func (a *Access) GetAllIgnoredPackagesByProductID(productID int64) ([]string, error) { - var packages []string - err := a.query.Select(&packages, "select package from ignored_upstream_packages where product_id = $1", productID) - if err != nil { - return nil, err - } - - return packages, nil -} - -func (a *Access) GetAllRebootSuggestedPackages() ([]string, error) { - var packages []string - err := a.query.Select(&packages, "select name from reboot_suggested_packages") - if err != nil { - return nil, err - } - - return packages, nil -} - -func (a *Access) AddAdvisoryFix(advisoryId int64, fixId int64) error { - _, err := a.query.Exec("insert into advisory_fixes (advisory_id, fix_id) values ($1, $2) on conflict do nothing", advisoryId, fixId) - if err != nil { - return err - } - - return nil -} - -func (a *Access) AddAdvisoryCVE(advisoryId int64, cveId string) error { - _, err := a.query.Exec("insert into advisory_cves (advisory_id, cve_id) values ($1, $2) on conflict do nothing", advisoryId, cveId) - if err != nil { - return err - } - - return nil -} - -func (a *Access) AddAdvisoryRPM(advisoryId int64, name string, productID int64) error { - _, err := a.query.Exec("insert into advisory_rpms (advisory_id, name, product_id) values ($1, $2, $3) on conflict do nothing", advisoryId, name, productID) - if err != nil { - return err - } - - return nil -} - -func (a *Access) Begin() (utils.Tx, error) { - tx, err := a.db.Beginx() - if err != nil { - return nil, err - } - - return tx, nil -} - -func (a *Access) UseTransaction(tx utils.Tx) apollodb.Access { - newAccess := *a - newAccess.query = tx - - return &newAccess -} diff --git a/apollo/impl/v1/BUILD.bazel b/apollo/impl/v1/BUILD.bazel deleted file mode 100644 index a666e6c..0000000 --- a/apollo/impl/v1/BUILD.bazel +++ /dev/null @@ -1,26 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "impl", - srcs = [ - "advisory.go", - "server.go", - ], - importpath = "peridot.resf.org/apollo/impl/v1", - visibility = ["//visibility:public"], - deps = [ - "//apollo/db", - "//apollo/proto/v1:pb", - "//apollo/rpmutils", - "//proto:common", - "//utils", - "//vendor/github.com/gorilla/feeds", - "//vendor/github.com/sirupsen/logrus", - "//vendor/github.com/spf13/viper", - "@go_googleapis//google/api:httpbody_go_proto", - "@org_golang_google_grpc//:go_default_library", - "@org_golang_google_grpc//codes", - "@org_golang_google_grpc//status", - "@org_golang_google_protobuf//types/known/timestamppb:go_default_library", - ], -) diff --git a/apollo/impl/v1/advisory.go b/apollo/impl/v1/advisory.go deleted file mode 100644 index 238976c..0000000 --- a/apollo/impl/v1/advisory.go +++ /dev/null @@ -1,185 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package apolloimpl - -import ( - "context" - "database/sql" - "fmt" - "github.com/gorilla/feeds" - "github.com/sirupsen/logrus" - "google.golang.org/genproto/googleapis/api/httpbody" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - "google.golang.org/protobuf/types/known/timestamppb" - apollodb "peridot.resf.org/apollo/db" - apollopb "peridot.resf.org/apollo/pb" - "peridot.resf.org/apollo/rpmutils" - "peridot.resf.org/utils" - "strconv" - "time" -) - -// ListAdvisories returns advisories with given filters -func (s *Server) ListAdvisories(_ context.Context, req *apollopb.ListAdvisoriesRequest) (*apollopb.ListAdvisoriesResponse, error) { - if err := req.ValidateAll(); err != nil { - return nil, err - } - if req.Filters != nil { - req.Filters.IncludeUnpublished = nil - } - - page := utils.MinPage(req.Page) - limit := utils.MinLimit(req.Limit) - ret, err := s.db.GetAllAdvisories(req.Filters, page, limit) - if err != nil { - s.log.Errorf("could not get advisories, error: %s", err) - return nil, status.Error(codes.Internal, "failed to list advisories") - } - total := int64(0) - if len(ret) > 0 { - total = ret[0].Total - } - - var lastUpdatedPb *timestamppb.Timestamp - lastUpdated, err := s.db.GetMaxLastSync() - if err != nil && err != sql.ErrNoRows { - s.log.Errorf("could not get last sync time, error: %s", err) - return nil, status.Error(codes.Internal, "failed to get last updated") - } - if lastUpdated != nil { - lastUpdatedPb = timestamppb.New(*lastUpdated) - } - - return &apollopb.ListAdvisoriesResponse{ - Advisories: apollodb.DTOListAdvisoriesToPB(ret), - Total: total, - Page: page, - Size: limit, - LastUpdated: lastUpdatedPb, - }, nil -} - -// ListAdvisoriesRSS returns advisories in RSS format. Only returns latest 25 published advisories -func (s *Server) ListAdvisoriesRSS(_ context.Context, req *apollopb.ListAdvisoriesRSSRequest) (*httpbody.HttpBody, error) { - if err := req.ValidateAll(); err != nil { - return nil, err - } - if req.Filters == nil { - req.Filters = &apollopb.AdvisoryFilters{} - } - req.Filters.IncludeUnpublished = nil - - ret, err := s.db.GetAllAdvisories(req.Filters, 0, 25) - if err != nil { - s.log.Errorf("could not get advisories, error: %s", err) - return nil, status.Error(codes.Internal, "failed to list advisories") - } - total := int64(0) - if len(ret) > 0 { - total = ret[0].Total - } - - var updated time.Time - if total != 0 { - updated = ret[0].PublishedAt.Time - } - - feed := &feeds.Feed{ - Title: "Apollo Security RSS Feed", - Link: &feeds.Link{Href: s.homepage}, - Description: "Security advisories issued using Apollo Errata Management", - Author: &feeds.Author{ - Name: "Rocky Enterprise Software Foundation, Inc.", - Email: "releng@rockylinux.org", - }, - Updated: updated, - Items: []*feeds.Item{}, - Copyright: "(C) Rocky Enterprise Software Foundation, Inc. 2022. All rights reserved. CVE sources are copyright of their respective owners.", - } - if s.rssFeedTitle != "" { - feed.Title = s.rssFeedTitle - } - if s.rssFeedDescription != "" { - feed.Description = s.rssFeedDescription - } - for _, a := range ret { - dtoToPB := apollodb.DTOAdvisoryToPB(a) - item := &feeds.Item{ - Title: fmt.Sprintf("%s: %s", dtoToPB.Name, a.Synopsis), - Link: &feeds.Link{Href: fmt.Sprintf("%s/%s", s.homepage, dtoToPB.Name)}, - Description: a.Topic, - Id: fmt.Sprintf("%d", a.ID), - Created: a.PublishedAt.Time, - } - feed.Items = append(feed.Items, item) - } - - rss, err := feed.ToRss() - if err != nil { - s.log.Errorf("could not generate RSS feed, error: %s", err) - return nil, status.Error(codes.Internal, "failed to generate RSS feed") - } - - return &httpbody.HttpBody{ - ContentType: "application/rss+xml", - Data: []byte(rss), - }, nil -} - -// GetAdvisory returns a single advisory by name -func (s *Server) GetAdvisory(_ context.Context, req *apollopb.GetAdvisoryRequest) (*apollopb.GetAdvisoryResponse, error) { - if err := req.ValidateAll(); err != nil { - return nil, err - } - advisoryId := rpmutils.AdvisoryId().FindStringSubmatch(req.Id) - code := advisoryId[1] - year, err := strconv.Atoi(advisoryId[3]) - if err != nil { - return nil, status.Error(codes.InvalidArgument, "invalid year") - } - num, err := strconv.Atoi(advisoryId[4]) - if err != nil { - return nil, status.Error(codes.InvalidArgument, "invalid num") - } - - advisory, err := s.db.GetAdvisoryByCodeAndYearAndNum(code, year, num) - if err != nil { - logrus.Error(err) - } - if err != nil || !advisory.PublishedAt.Valid { - return nil, utils.CouldNotFindObject - } - - return &apollopb.GetAdvisoryResponse{ - Advisory: apollodb.DTOAdvisoryToPB(advisory), - }, nil -} diff --git a/apollo/impl/v1/server.go b/apollo/impl/v1/server.go deleted file mode 100644 index 6116763..0000000 --- a/apollo/impl/v1/server.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package apolloimpl - -import ( - "context" - "github.com/sirupsen/logrus" - "github.com/spf13/viper" - "google.golang.org/grpc" - apollodb "peridot.resf.org/apollo/db" - apollopb "peridot.resf.org/apollo/pb" - commonpb "peridot.resf.org/common" - "peridot.resf.org/utils" -) - -type Server struct { - apollopb.UnimplementedApolloServiceServer - - log *logrus.Logger - db apollodb.Access - rssFeedTitle string - rssFeedDescription string - homepage string -} - -// NewServer creates a new Apollo server. -func NewServer(db apollodb.Access) *Server { - return &Server{ - log: logrus.New(), - db: db, - rssFeedTitle: "RESF Errata Feed", - rssFeedDescription: "Advisories issued by the Rocky Enterprise Software Foundation", - homepage: viper.GetString("homepage"), - } -} - -func (s *Server) interceptor(ctx context.Context, req interface{}, usi *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { - n := utils.EndInterceptor - - return n(ctx, req, usi, handler) -} - -func (s *Server) Run() { - res := utils.NewGRPCServer( - &utils.GRPCOptions{ - Interceptor: s.interceptor, - }, - func(r *utils.Register) { - endpoints := []utils.GrpcEndpointRegister{ - commonpb.RegisterHealthCheckServiceHandlerFromEndpoint, - apollopb.RegisterApolloServiceHandlerFromEndpoint, - } - - for _, endpoint := range endpoints { - err := endpoint(r.Context, r.Mux, r.Endpoint, r.Options) - if err != nil { - s.log.Fatalf("could not register handler - %v", err) - } - } - }, - func(r *utils.RegisterServer) { - commonpb.RegisterHealthCheckServiceServer(r.Server, &utils.HealthServer{}) - - apollopb.RegisterApolloServiceServer(r.Server, s) - }, - ) - - defer res.Cancel() - res.WaitGroup.Wait() -} diff --git a/apollo/migrate/20210702021142_create_short_codes.down.sql b/apollo/migrate/20210702021142_create_short_codes.down.sql deleted file mode 100644 index 0784b84..0000000 --- a/apollo/migrate/20210702021142_create_short_codes.down.sql +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -drop table short_codes; diff --git a/apollo/migrate/20210702021142_create_short_codes.up.sql b/apollo/migrate/20210702021142_create_short_codes.up.sql deleted file mode 100644 index 35cd61b..0000000 --- a/apollo/migrate/20210702021142_create_short_codes.up.sql +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -create table short_codes -( - code text not null primary key, - mode numeric not null, - - created_at timestamp default now() not null, - archived_at timestamp -); diff --git a/apollo/migrate/20210702021143_create_products.down.sql b/apollo/migrate/20210702021143_create_products.down.sql deleted file mode 100644 index 402433a..0000000 --- a/apollo/migrate/20210702021143_create_products.down.sql +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -drop table products; diff --git a/apollo/migrate/20210702021143_create_products.up.sql b/apollo/migrate/20210702021143_create_products.up.sql deleted file mode 100644 index 16f79a7..0000000 --- a/apollo/migrate/20210702021143_create_products.up.sql +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -create table products -( - id bigserial primary key, - name text not null, - current_full_version text not null, - redhat_major_version numeric, - short_code_code text references short_codes (code) not null, - archs text[] not null, - mirror_from_date timestamp, - redhat_product_prefix text, - cpe text, - eol_at timestamp, - - build_system text not null, - build_system_endpoint text not null, - koji_compose text, - koji_module_compose text, - peridot_project_id text -) diff --git a/apollo/migrate/20210702041656_create_advisories.down.sql b/apollo/migrate/20210702041656_create_advisories.down.sql deleted file mode 100644 index 234d97c..0000000 --- a/apollo/migrate/20210702041656_create_advisories.down.sql +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -drop table advisories; diff --git a/apollo/migrate/20210702041656_create_advisories.up.sql b/apollo/migrate/20210702041656_create_advisories.up.sql deleted file mode 100644 index eb65c45..0000000 --- a/apollo/migrate/20210702041656_create_advisories.up.sql +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -create table advisories -( - id bigserial primary key not null, - created_at timestamp default now() not null, - - year numeric not null, - num numeric not null, - - synopsis text not null, - topic text not null, - severity numeric not null, - type numeric not null, - description text not null, - solution text null, - - redhat_issued_at timestamp null, - short_code_code text references short_codes (code) not null, - reboot_suggested bool default false not null, - published_at timestamp null -) diff --git a/apollo/migrate/20210702041659_create_cves.down.sql b/apollo/migrate/20210702041659_create_cves.down.sql deleted file mode 100644 index 32c3efe..0000000 --- a/apollo/migrate/20210702041659_create_cves.down.sql +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -drop table cves; diff --git a/apollo/migrate/20210702041659_create_cves.up.sql b/apollo/migrate/20210702041659_create_cves.up.sql deleted file mode 100644 index eb99444..0000000 --- a/apollo/migrate/20210702041659_create_cves.up.sql +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -create table cves -( - id text primary key, - created_at timestamp default now() not null, - short_code_code text references short_codes (code) not null, - - source_by text, - source_link text -) diff --git a/apollo/migrate/20210702041701_create_fixes.down.sql b/apollo/migrate/20210702041701_create_fixes.down.sql deleted file mode 100644 index c85852f..0000000 --- a/apollo/migrate/20210702041701_create_fixes.down.sql +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -drop table fixes; diff --git a/apollo/migrate/20210702041701_create_fixes.up.sql b/apollo/migrate/20210702041701_create_fixes.up.sql deleted file mode 100644 index e108b73..0000000 --- a/apollo/migrate/20210702041701_create_fixes.up.sql +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -create table fixes -( - id bigserial primary key, - ticket text, - source_by text, - source_link text, - description text -) diff --git a/apollo/migrate/20210702041756_create_advisory_references.down.sql b/apollo/migrate/20210702041756_create_advisory_references.down.sql deleted file mode 100644 index ff6cfee..0000000 --- a/apollo/migrate/20210702041756_create_advisory_references.down.sql +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -drop table advisory_references; diff --git a/apollo/migrate/20210702041756_create_advisory_references.up.sql b/apollo/migrate/20210702041756_create_advisory_references.up.sql deleted file mode 100644 index 07d2af2..0000000 --- a/apollo/migrate/20210702041756_create_advisory_references.up.sql +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -create table advisory_references -( - id bigserial primary key, - url text not null, - advisory_id bigint references advisories (id) not null -) diff --git a/apollo/migrate/20210702041956_create_affected_products.down.sql b/apollo/migrate/20210702041956_create_affected_products.down.sql deleted file mode 100644 index 17e83b4..0000000 --- a/apollo/migrate/20210702041956_create_affected_products.down.sql +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -drop table affected_products; diff --git a/apollo/migrate/20210702041956_create_affected_products.up.sql b/apollo/migrate/20210702041956_create_affected_products.up.sql deleted file mode 100644 index 28b49a7..0000000 --- a/apollo/migrate/20210702041956_create_affected_products.up.sql +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -create table affected_products -( - id bigserial primary key, - product_id bigint references products (id) not null, - cve_id text references cves (id) not null, - state numeric not null, - version text not null, - package text not null, - advisory text -) diff --git a/apollo/migrate/20210702043031_create_build_references.down.sql b/apollo/migrate/20210702043031_create_build_references.down.sql deleted file mode 100644 index a8694e9..0000000 --- a/apollo/migrate/20210702043031_create_build_references.down.sql +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -drop table build_references; diff --git a/apollo/migrate/20210702043031_create_build_references.up.sql b/apollo/migrate/20210702043031_create_build_references.up.sql deleted file mode 100644 index ae81e88..0000000 --- a/apollo/migrate/20210702043031_create_build_references.up.sql +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -create table build_references -( - id bigserial primary key, - affected_product_id bigint references affected_products (id), - rpm text not null, - src_rpm text not null, - cve_id text references cves (id) not null, - sha256_sum text not null, - koji_id text, - peridot_id text -) diff --git a/apollo/migrate/20210703202420_create_mirror_state.down.sql b/apollo/migrate/20210703202420_create_mirror_state.down.sql deleted file mode 100644 index 4be55bc..0000000 --- a/apollo/migrate/20210703202420_create_mirror_state.down.sql +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -drop table mirror_state; diff --git a/apollo/migrate/20210703202420_create_mirror_state.up.sql b/apollo/migrate/20210703202420_create_mirror_state.up.sql deleted file mode 100644 index 49f66d9..0000000 --- a/apollo/migrate/20210703202420_create_mirror_state.up.sql +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -create table mirror_state -( - short_code_code text references short_codes (code) primary key, - last_sync timestamp, - errata_after timestamp -); diff --git a/apollo/migrate/20210711014759_create_advisory_cves.down.sql b/apollo/migrate/20210711014759_create_advisory_cves.down.sql deleted file mode 100644 index 9282aab..0000000 --- a/apollo/migrate/20210711014759_create_advisory_cves.down.sql +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -drop table advisory_cves; diff --git a/apollo/migrate/20210711014759_create_advisory_cves.up.sql b/apollo/migrate/20210711014759_create_advisory_cves.up.sql deleted file mode 100644 index 2a7d310..0000000 --- a/apollo/migrate/20210711014759_create_advisory_cves.up.sql +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -create table advisory_cves -( - advisory_id bigint references advisories (id) not null, - cve_id text references cves (id) not null, - - unique (advisory_id, cve_id) -) diff --git a/apollo/migrate/20210711020255_create_advisory_fixes.down.sql b/apollo/migrate/20210711020255_create_advisory_fixes.down.sql deleted file mode 100644 index a8fdf81..0000000 --- a/apollo/migrate/20210711020255_create_advisory_fixes.down.sql +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -drop table advisory_fixes; diff --git a/apollo/migrate/20210711020255_create_advisory_fixes.up.sql b/apollo/migrate/20210711020255_create_advisory_fixes.up.sql deleted file mode 100644 index 86d8774..0000000 --- a/apollo/migrate/20210711020255_create_advisory_fixes.up.sql +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -create table advisory_fixes -( - advisory_id bigint references advisories (id) not null, - fix_id bigint references fixes (id) not null, - - unique (advisory_id, fix_id) -) diff --git a/apollo/migrate/20210713031253_create_ignored_upstream_packages.down.sql b/apollo/migrate/20210713031253_create_ignored_upstream_packages.down.sql deleted file mode 100644 index d03308b..0000000 --- a/apollo/migrate/20210713031253_create_ignored_upstream_packages.down.sql +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -drop table ignored_upstream_packages; diff --git a/apollo/migrate/20210713031253_create_ignored_upstream_packages.up.sql b/apollo/migrate/20210713031253_create_ignored_upstream_packages.up.sql deleted file mode 100644 index 6f94701..0000000 --- a/apollo/migrate/20210713031253_create_ignored_upstream_packages.up.sql +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -create table ignored_upstream_packages -( - id bigserial primary key, - product_id bigint references products (id) not null, - package text not null -); diff --git a/apollo/migrate/20210717040945_create_advisory_rpms.down.sql b/apollo/migrate/20210717040945_create_advisory_rpms.down.sql deleted file mode 100644 index 0e7bb62..0000000 --- a/apollo/migrate/20210717040945_create_advisory_rpms.down.sql +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -drop table advisory_rpms; diff --git a/apollo/migrate/20210717040945_create_advisory_rpms.up.sql b/apollo/migrate/20210717040945_create_advisory_rpms.up.sql deleted file mode 100644 index 198441a..0000000 --- a/apollo/migrate/20210717040945_create_advisory_rpms.up.sql +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -create table advisory_rpms -( - advisory_id bigint references advisories (id) not null, - name text not null, - product_id bigint references products (id) not null, - - unique (advisory_id, name) -) diff --git a/apollo/migrate/20210803052113_updateinfo_history.down.sql b/apollo/migrate/20210803052113_updateinfo_history.down.sql deleted file mode 100644 index ec500aa..0000000 --- a/apollo/migrate/20210803052113_updateinfo_history.down.sql +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -drop table updateinfo_history; diff --git a/apollo/migrate/20210803052113_updateinfo_history.up.sql b/apollo/migrate/20210803052113_updateinfo_history.up.sql deleted file mode 100644 index 80fd989..0000000 --- a/apollo/migrate/20210803052113_updateinfo_history.up.sql +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -create table updateinfo_history -( - repo text primary key, - xml text not null -); diff --git a/apollo/migrate/20220913121538_create_reboot_suggested_packages.down.sql b/apollo/migrate/20220913121538_create_reboot_suggested_packages.down.sql deleted file mode 100644 index 66b788f..0000000 --- a/apollo/migrate/20220913121538_create_reboot_suggested_packages.down.sql +++ /dev/null @@ -1 +0,0 @@ -drop table reboot_suggested_packages; diff --git a/apollo/migrate/20220913121538_create_reboot_suggested_packages.up.sql b/apollo/migrate/20220913121538_create_reboot_suggested_packages.up.sql deleted file mode 100644 index d3fd23c..0000000 --- a/apollo/migrate/20220913121538_create_reboot_suggested_packages.up.sql +++ /dev/null @@ -1,6 +0,0 @@ -create table reboot_suggested_packages -( - created_at timestamp default now() not null, - - name text unique not null -) diff --git a/apollo/migrate/20220921231425_add_indexes.down.sql b/apollo/migrate/20220921231425_add_indexes.down.sql deleted file mode 100644 index 458b43b..0000000 --- a/apollo/migrate/20220921231425_add_indexes.down.sql +++ /dev/null @@ -1,9 +0,0 @@ -drop index affected_products_advisoryx; -drop index affected_products_product_idx; -drop index advisory_fixes_advisory_idx; -drop index advisory_fixes_fix_idx; -drop index advisory_cves_advisory_idx; -drop index advisory_cves_cve_idx; -drop index advisory_references_advisory_idx; -drop index advisory_rpms_advisory_idx; -drop index advisory_rpms_product_idx; diff --git a/apollo/migrate/20220921231425_add_indexes.up.sql b/apollo/migrate/20220921231425_add_indexes.up.sql deleted file mode 100644 index 1232742..0000000 --- a/apollo/migrate/20220921231425_add_indexes.up.sql +++ /dev/null @@ -1,9 +0,0 @@ -create index affected_products_advisoryx on affected_products (advisory); -create index affected_products_product_idx on affected_products (product_id); -create index advisory_fixes_advisory_idx on advisory_fixes (advisory_id); -create index advisory_fixes_fix_idx on advisory_fixes (fix_id); -create index advisory_cves_advisory_idx on advisory_cves (advisory_id); -create index advisory_cves_cve_idx on advisory_cves (cve_id); -create index advisory_references_advisory_idx on advisory_references (advisory_id); -create index advisory_rpms_advisory_idx on advisory_rpms (advisory_id); -create index advisory_rpms_product_idx on advisory_rpms (product_id); diff --git a/apollo/migrate/20221020182658_add_content_to_cves.down.sql b/apollo/migrate/20221020182658_add_content_to_cves.down.sql deleted file mode 100644 index 41914a8..0000000 --- a/apollo/migrate/20221020182658_add_content_to_cves.down.sql +++ /dev/null @@ -1 +0,0 @@ -alter table cves drop column content; diff --git a/apollo/migrate/20221020182658_add_content_to_cves.up.sql b/apollo/migrate/20221020182658_add_content_to_cves.up.sql deleted file mode 100644 index 557265d..0000000 --- a/apollo/migrate/20221020182658_add_content_to_cves.up.sql +++ /dev/null @@ -1 +0,0 @@ -alter table cves add column content jsonb; diff --git a/apollo/migrate/BUILD b/apollo/migrate/BUILD deleted file mode 100644 index 57d1df0..0000000 --- a/apollo/migrate/BUILD +++ /dev/null @@ -1,5 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load("//rules_resf:defs.bzl", "migration_tar") - -migration_tar() diff --git a/apollo/proto/v1/BUILD.bazel b/apollo/proto/v1/BUILD.bazel deleted file mode 100644 index 75b73f5..0000000 --- a/apollo/proto/v1/BUILD.bazel +++ /dev/null @@ -1,65 +0,0 @@ -load("@rules_proto//proto:defs.bzl", "proto_library") -load("@io_bazel_rules_go//go:def.bzl", "go_library") -load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library") -load("@com_github_grpc_ecosystem_grpc_gateway_v2//protoc-gen-openapiv2:defs.bzl", "protoc_gen_openapiv2") -load("@openapi_tools_generator_bazel//:defs.bzl", "openapi_generator") - -proto_library( - name = "apollopb_proto", - srcs = [ - "advisory.proto", - "affected_product.proto", - "apollo.proto", - "build.proto", - "cve.proto", - "fix.proto", - "short_code.proto", - ], - visibility = ["//visibility:public"], - deps = [ - "@com_envoyproxy_protoc_gen_validate//validate:validate_proto", - "@com_google_protobuf//:timestamp_proto", - "@com_google_protobuf//:wrappers_proto", - "@go_googleapis//google/api:annotations_proto", - "@go_googleapis//google/api:httpbody_proto", - ], -) - -go_proto_library( - name = "apollopb_go_proto", - compilers = [ - "//:go_apiv2", - "//:go_grpc", - "//:go_validate", - "@com_github_grpc_ecosystem_grpc_gateway_v2//protoc-gen-grpc-gateway:go_gen_grpc_gateway", - ], - importpath = "peridot.resf.org/apollo/pb", - proto = ":apollopb_proto", - visibility = ["//visibility:public"], - deps = [ - "@com_envoyproxy_protoc_gen_validate//validate:validate_go_proto", - "@go_googleapis//google/api:annotations_go_proto", - "@go_googleapis//google/api:httpbody_go_proto", - ], -) - -go_library( - name = "pb", - embed = [":apollopb_go_proto"], - importpath = "peridot.resf.org/apollo/pb", - visibility = ["//visibility:public"], -) - -protoc_gen_openapiv2( - name = "openapi", - proto = ":apollopb_proto", - simple_operation_ids = True, - single_output = True, -) - -openapi_generator( - name = "client_typescript", - generator = "typescript-fetch", - spec = ":openapi", - visibility = ["//visibility:public"], -) diff --git a/apollo/proto/v1/advisory.proto b/apollo/proto/v1/advisory.proto deleted file mode 100644 index 7dc1a27..0000000 --- a/apollo/proto/v1/advisory.proto +++ /dev/null @@ -1,112 +0,0 @@ -syntax = "proto3"; - -package resf.apollo.v1; - -import "google/protobuf/timestamp.proto"; -import "google/protobuf/wrappers.proto"; -import "apollo/proto/v1/cve.proto"; -import "apollo/proto/v1/fix.proto"; - -option go_package = "peridot.resf.org/apollo/pb;apollopb"; - -message RPMs { - repeated string nvras = 1; -} - -// Advisory -// -// Product advisory -message Advisory { - enum Type { - TYPE_UNKNOWN = 0; - TYPE_SECURITY = 1; - TYPE_BUGFIX = 2; - TYPE_ENHANCEMENT = 3; - } - - // Type - // - // Type of advisory - Type type = 1; - - // Short code - // - // Errata prefix or short code - // Example: RLBA, RLEA, RLSA - string short_code = 2; - - // Name - // - // Full errata name - // Example: RLBA-2021:0001, RLSA-2021:0002 - string name = 3; - - // Synopsis - // - // Short description of advisory - string synopsis = 4; - - enum Severity { - SEVERITY_UNKNOWN = 0; - SEVERITY_LOW = 1; - SEVERITY_MODERATE = 2; - SEVERITY_IMPORTANT = 3; - SEVERITY_CRITICAL = 4; - } - - // Severity - // - // Severity of advisory. Used only for security advisories - Severity severity = 5; - - // Topic - // - // Topic of advisory - // Example: An update for the go-toolset:rhel8 module is now available for Rocky Linux 8. - string topic = 6; - - // Description - // - // Description of advisory. Contains information about changes and package. - string description = 7; - - // Solution - // - // How to solve the advisory. Contains information about how to apply the advisory changes - google.protobuf.StringValue solution = 8; - - // Affected products - // - // A list of affected products - repeated string affected_products = 9; - - // Fixes - // - // A list of tickets from upstream bug trackers - repeated Fix fixes = 10; - - // CVEs - // - // A list of CVEs assigned to this advisory - repeated CVE cves = 11; - - // References - // - // General references used in this advisory - repeated string references = 12; - - // Published at - // - // Timestamp the advisory is published at - google.protobuf.Timestamp published_at = 13; - - // RPMs - // - // Affected RPMs - map rpms = 14; - - // Reboot suggested - // - // Whether a system reboot should be suggested after applying this advisory - bool reboot_suggested = 15; -} diff --git a/apollo/proto/v1/affected_product.proto b/apollo/proto/v1/affected_product.proto deleted file mode 100644 index ca3458c..0000000 --- a/apollo/proto/v1/affected_product.proto +++ /dev/null @@ -1,41 +0,0 @@ -syntax = "proto3"; - -package resf.apollo.v1; - -import "google/protobuf/wrappers.proto"; - -option go_package = "peridot.resf.org/apollo/pb;apollopb"; - -message AffectedProduct { - int64 product_id = 1; - google.protobuf.StringValue cve_id = 2; - string version = 3; - - enum State { - STATE_UNKNOWN = 0; - // CVE only affects downstream - STATE_UNDER_INVESTIGATION_DOWNSTREAM = 1; - // CVE affecting upstream and a fix still hasn't been issued - STATE_UNDER_INVESTIGATION_UPSTREAM = 2; - // CVE has been fixed upstream - STATE_FIXED_UPSTREAM = 3; - // CVE has been fixed downstream - // At this stage the CVE can be included in errata - STATE_FIXED_DOWNSTREAM = 4; - // CVE will NOT be fixed upstream - STATE_WILL_NOT_FIX_UPSTREAM = 5; - // CVE will NOT be fixed downstream - // This will probably never happen with Core, but may happen for SIGs - STATE_WILL_NOT_FIX_DOWNSTREAM = 6; - // CVE is out of support scope - STATE_OUT_OF_SUPPORT_SCOPE = 7; - // CVE affects product and upstream is working on a fix - STATE_AFFECTED_UPSTREAM = 8; - // CVE affects product and a fix is being worked out - STATE_AFFECTED_DOWNSTREAM = 9; - } - State state = 4; - - string package = 5; - google.protobuf.StringValue advisory = 6; -} diff --git a/apollo/proto/v1/apollo.proto b/apollo/proto/v1/apollo.proto deleted file mode 100644 index 7923444..0000000 --- a/apollo/proto/v1/apollo.proto +++ /dev/null @@ -1,161 +0,0 @@ -syntax = "proto3"; - -package resf.apollo.v1; - -import "google/api/annotations.proto"; -import "google/api/httpbody.proto"; -import "google/protobuf/wrappers.proto"; -import "google/protobuf/timestamp.proto"; -import "validate/validate.proto"; -import "apollo/proto/v1/advisory.proto"; - -option go_package = "peridot.resf.org/apollo/pb;apollopb"; - -service ApolloService { - // ListAdvisories - // - // Return a list of advisories by given filters. - // No filters returns all advisories - // This method is paginated - rpc ListAdvisories (ListAdvisoriesRequest) returns (ListAdvisoriesResponse) { - option (google.api.http) = { - get: "/v2/advisories" - }; - } - - // ListAdvisoriesRSS - // - // Same as ListAdvisories but returns an RSS feed - // Only returns 25 latest advisories - // Supports filters - rpc ListAdvisoriesRSS (ListAdvisoriesRSSRequest) returns (google.api.HttpBody) { - option (google.api.http) = { - get: "/v2/advisories:rss" - }; - } - - // GetAdvisory - // - // Returns an advisory with given ID if found, else returns NotFound - rpc GetAdvisory (GetAdvisoryRequest) returns (GetAdvisoryResponse) { - option (google.api.http) = { - get: "/v2/advisories/{id=*}" - }; - } -} - -message AdvisoryFilters { - // Product - // - // The product to fetch advisories for - // For example: Rocky Linux 8 - google.protobuf.StringValue product = 1; - - // Before - // - // Advisories published before timestamp - google.protobuf.Timestamp before = 2; - - // After - // - // Advisories published after timestamp - google.protobuf.Timestamp after = 3; - - // Include unpublished - // - // Whether to include unpublished advisories - // apollo/impl never respects this, but internal services - // may rely on this - google.protobuf.BoolValue include_unpublished = 4; - - // CVE - // - // Only return advisories with given CVE - google.protobuf.StringValue cve = 5; - - // Synopsis - // - // Only return advisories if synopsis contains given text - google.protobuf.StringValue synopsis = 6; - - // Include RPMs - // - // Includes RPMs in list response (slow) - google.protobuf.BoolValue include_rpms = 7; - - // Keyword - // - // Searches all fields for given keyword - google.protobuf.StringValue keyword = 8; - - // Severity - // - // Only return advisories with given severity - Advisory.Severity severity = 9; - - // Type - // - // Only return advisories with given type - Advisory.Type type = 10; -} - -// ListAdvisoriesRequest -// -// Request body for `ListAdvisories` -// All fields are optional -message ListAdvisoriesRequest { - // Filters for the given query - // No filters returns all advisories - AdvisoryFilters filters = 1; - - int32 page = 2; - int32 limit = 3 [(validate.rules).int32.lte = 100]; -} - -// ListAdvisoriesResponse -// -// Response body for `ListAdvisories` -message ListAdvisoriesResponse { - repeated Advisory advisories = 1; - - // Total packages from server - int64 total = 2; - - // Limit from request - int32 size = 3; - - // Current page - int32 page = 4; - - // Last updated - google.protobuf.Timestamp last_updated = 5; -} - -// ListAdvisoriesRSSRequest -// Request body for `ListAdvisoriesRSS` -// All fields are optional -message ListAdvisoriesRSSRequest { - // Filters for the given query - // No filters returns all advisories - AdvisoryFilters filters = 1; -} - -// GetAdvisoryRequest -// -// Request body for `GetAdvisory` -message GetAdvisoryRequest { - // ID - // - // Errata ID - // Example: RLSA:2021-1515 - string id = 1 [(validate.rules).string = { - pattern: "^(.+)([SEB]A)-([0-9]{4}):([0-9]+)$", - }]; -} - -// GetAdvisoryResponse -// -// Response body for `GetAdvisory` -message GetAdvisoryResponse { - Advisory advisory = 1; -} diff --git a/apollo/proto/v1/build.proto b/apollo/proto/v1/build.proto deleted file mode 100644 index 1ff48c5..0000000 --- a/apollo/proto/v1/build.proto +++ /dev/null @@ -1,13 +0,0 @@ -syntax = "proto3"; - -package resf.apollo.v1; - -option go_package = "peridot.resf.org/apollo/pb;apollopb"; - -enum BuildStatus { - BUILD_STATUS_UNKNOWN = 0; - BUILD_STATUS_FIXED = 1; - BUILD_STATUS_NOT_FIXED = 2; - BUILD_STATUS_WILL_NOT_FIX = 3; - BUILD_STATUS_SKIP = 4; -} diff --git a/apollo/proto/v1/cve.proto b/apollo/proto/v1/cve.proto deleted file mode 100644 index f9c8aae..0000000 --- a/apollo/proto/v1/cve.proto +++ /dev/null @@ -1,28 +0,0 @@ -syntax = "proto3"; - -package resf.apollo.v1; - -import "google/protobuf/wrappers.proto"; - -option go_package = "peridot.resf.org/apollo/pb;apollopb"; - -message CVE { - string name = 1; - - google.protobuf.StringValue source_by = 2; - google.protobuf.StringValue source_link = 3; - - google.protobuf.StringValue cvss3_scoring_vector = 4; - google.protobuf.StringValue cvss3_base_score = 5; - google.protobuf.StringValue cwe = 6; -} - -message ListUnresolvedCVEsRequest {} -message ListUnresolvedCVEsResponse { - repeated CVE cves = 1; -} - -message ListFixedCVEsRequest {} -message ListFixedCVEsResponse { - repeated CVE cves = 1; -} diff --git a/apollo/proto/v1/fix.proto b/apollo/proto/v1/fix.proto deleted file mode 100644 index 6c0e69e..0000000 --- a/apollo/proto/v1/fix.proto +++ /dev/null @@ -1,14 +0,0 @@ -syntax = "proto3"; - -package resf.apollo.v1; - -import "google/protobuf/wrappers.proto"; - -option go_package = "peridot.resf.org/apollo/pb;apollopb"; - -message Fix { - google.protobuf.StringValue ticket = 1; - google.protobuf.StringValue source_by = 2; - google.protobuf.StringValue source_link = 3; - google.protobuf.StringValue description = 4; -} diff --git a/apollo/proto/v1/short_code.proto b/apollo/proto/v1/short_code.proto deleted file mode 100644 index 8f7c9d4..0000000 --- a/apollo/proto/v1/short_code.proto +++ /dev/null @@ -1,29 +0,0 @@ -syntax = "proto3"; - -package resf.apollo.v1; - -option go_package = "peridot.resf.org/apollo/pb;apollopb"; - -message ShortCode { - // Code - // - // Full short code - string code = 1; - - enum Mode { - MODE_UNKNOWN = 0; - MODE_PUBLISH = 1; - MODE_MIRROR = 2; - } - // Mode - // - // Mode for short code - // Currently only publish and mirror is supported - Mode mode = 2; - - // Archived - // - // Whether the short code is archived or not - // An archived short code CANNOT be used to issue errata - bool archived = 3; -} diff --git a/apollo/seed.sql b/apollo/seed.sql deleted file mode 100644 index 8181889..0000000 --- a/apollo/seed.sql +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -insert into short_codes (code, mode) -values ('RL', 2); -insert into short_codes (code, mode) -values ('RK', 1); ---insert into products (id, name, current_full_version, redhat_major_version, short_code_code, archs, mirror_from_date, redhat_product_prefix, cpe) ---values (1, 'Rocky Linux 9', '9.0', 9, 'RL', array ['x86_64', 'aarch64', 'ppc64le', 's390x'], '2022-05-15'::timestamp, 'Rocky Linux', 'cpe:/o:redhat:enterprise_linux:9'); -insert into products (id, name, current_full_version, redhat_major_version, short_code_code, archs, mirror_from_date, redhat_product_prefix, cpe, build_system, build_system_endpoint, koji_compose, koji_module_compose) -values (2, 'Rocky Linux 8', '8.6', 8, 'RL', array ['x86_64', 'aarch64'], '2022-05-15'::timestamp, 'Rocky Linux', 'cpe:/o:redhat:enterprise_linux:8', 'koji', 'https://koji.rockylinux.org/kojihub', 'dist-rocky8-compose', 'dist-rocky8-module-compose'); ---insert into ignored_upstream_packages (product_id, package) ---values --- (1, 'tfm-rubygem-unicode*'), --- (1, 'katello-host-tools*'), --- (1, 'openssl-ibmca*'), --- (1, 'insights-client*'), --- (1, 'tfm-rubygem-unicode-display_width*'), --- (1, 'pulp*'), --- (1, 'satellite*'), --- (1, 'tfm-rubygem-unf_ext*'), --- (1, 'foreman*'), --- (1, 'kpatch*'), --- (1, 'rhc-worker-playbook*'); -insert into ignored_upstream_packages (product_id, package) -values - (2, 'tfm-rubygem-unicode*'), - (2, 'katello-host-tools*'), - (2, 'openssl-ibmca*'), - (2, 'insights-client*'), - (2, 'tfm-rubygem-unicode-display_width*'), - (2, 'pulp*'), - (2, 'satellite*'), - (2, 'tfm-rubygem-unf_ext*'), - (2, 'foreman*'), - (2, 'kpatch*'), - (2, 'rhc-worker-playbook*'); -insert into reboot_suggested_packages (name) -values - ('kernel'), - ('kernel-PAE'), - ('kernel-rt'), - ('kernel-smp'), - ('kernel-xen'), - ('linux-firmware'), - ('*-firmware-*'), - ('dbus'), - ('glibc'), - ('hal'), - ('systemd'), - ('udev'), - ('gnutls'), - ('openssl-libs'); diff --git a/apollo/ui/BUILD.bazel b/apollo/ui/BUILD.bazel deleted file mode 100644 index b5738d1..0000000 --- a/apollo/ui/BUILD.bazel +++ /dev/null @@ -1,60 +0,0 @@ -load("//rules_resf:defs.bzl", "RESFDEPLOY_OUTS_BASE", "container", "peridot_k8s", "resf_frontend") - -package(default_visibility = ["//visibility:public"]) - -server_deps = ["//common/frontend_server"] - -server_entrypoint = "server/index.mjs" - -server_srcs = glob(["server/**/*.mjs"]) - -resf_frontend( - name = "apollo", - srcs = glob([ - "src/**/*.tsx", - "src/**/*.ts", - ]), - entrypoint = "apollo/ui/src/entrypoint.tsx", - index_html = "//rules_resf/internal/resf_bundle:index_no_mobile.hbs", - server_deps = server_deps, - server_entrypoint = server_entrypoint, - server_srcs = server_srcs, - tailwind_config = "//rules_resf/internal/resf_bundle:tailwind.config.nopreflight.js", - title = "Rocky Enterprise Software Foundation Product Errata", - deps = [ - "//apollo/proto/v1:client_typescript", - "//common/mui", - "//common/ui", - "//tailwind:css", - "@npm//@chakra-ui/react", - "@npm//@chakra-ui/icons", - "@npm//@emotion/unitless", - "@npm//framer-motion", - "@npm//framesync", - "@npm//popmotion", - "@npm//style-value-types", - "@npm//await-to-js", - "@npm//react", - "@npm//react-dom", - "@npm//react-router", - "@npm//react-router-dom", - ], -) - -container( - base = "//bases/bazel/node", - files = [ - ":apollo.bundle", - ], - frontend = True, - image_name = "apollo-frontend", - server_entrypoint = server_entrypoint, - server_files = server_srcs + server_deps, -) - -peridot_k8s( - name = "apollo-frontend", - src = "deploy.jsonnet", - outs = RESFDEPLOY_OUTS_BASE, - deps = ["//ci"], -) diff --git a/apollo/ui/deploy.jsonnet b/apollo/ui/deploy.jsonnet deleted file mode 100644 index 9b9b8bb..0000000 --- a/apollo/ui/deploy.jsonnet +++ /dev/null @@ -1,25 +0,0 @@ -local resfdeploy = import 'ci/resfdeploy.jsonnet'; -local kubernetes = import 'ci/kubernetes.jsonnet'; -local frontend = import 'ci/frontend.jsonnet'; - -local tag = std.extVar('tag'); - -resfdeploy.new({ - name: 'apollo-frontend', - backend: false, - migrate: false, - image: kubernetes.tag($.name), - tag: tag, - env: frontend.server_env, - ports: [ - { - name: 'http', - containerPort: 8086, - protocol: 'TCP', - expose: true, - }, - ], - health: { - port: 8086, - }, -}) diff --git a/apollo/ui/server/index.mjs b/apollo/ui/server/index.mjs deleted file mode 100644 index 80976ed..0000000 --- a/apollo/ui/server/index.mjs +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -import server from '../../../common/frontend_server/index.mjs'; -import { - svcNameHttp, - endpointHttp, - NS, -} from '../../../common/frontend_server/upstream.mjs'; - -export default async function run(webpackConfig) { - const devFrontendUrl = 'http://errata.pdot.localhost:9007'; - const envPublicUrl = process.env['APOLLO_FRONTEND_HTTP_PUBLIC_URL']; - const frontendUrl = process.env['RESF_NS'] ? envPublicUrl : devFrontendUrl; - - server({ - baseURL: frontendUrl, - apis: { - '/api': { - prodApiUrl: endpointHttp(svcNameHttp('apollo'), NS('apollo')), - devApiUrl: `https://apollo-dev.internal.pdev.resf.localhost`, - }, - }, - port: 9007, - disableAuth: true, - webpackConfig, - }).then(); -} - -if (process.env.NODE_ENV === 'production') { - run().then(); -} diff --git a/apollo/ui/src/api.ts b/apollo/ui/src/api.ts deleted file mode 100644 index 058442f..0000000 --- a/apollo/ui/src/api.ts +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -import * as apollo from 'bazel-bin/apollo/proto/v1/client_typescript'; - -export const api = new apollo.ApolloServiceApi( - new apollo.Configuration({ - basePath: '/api', // Points to frontend API proxy - }) -); diff --git a/apollo/ui/src/components/Overview.tsx b/apollo/ui/src/components/Overview.tsx deleted file mode 100644 index b7a6dd8..0000000 --- a/apollo/ui/src/components/Overview.tsx +++ /dev/null @@ -1,520 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -import { - AddIcon, - ArrowLeftIcon, - ArrowRightIcon, - MinusIcon, - SearchIcon, -} from '@chakra-ui/icons'; -import { - Alert, - AlertDescription, - AlertIcon, - AlertTitle, - Box, - ButtonGroup, - FormControl, - FormLabel, - HStack, - IconButton, - Input, - InputGroup, - InputLeftElement, - Link, - Select, - Spinner, - Stack, - Table, - TableColumnHeaderProps, - TableContainer, - Tbody, - Td, - Text, - Th, - Thead, - Tr, - useColorModeValue, -} from '@chakra-ui/react'; -import { - severityToBadge, - severityToText, - typeToText, -} from 'apollo/ui/src/enumToText'; -import { - ListAdvisoriesFiltersSeverityEnum, - ListAdvisoriesFiltersTypeEnum, -} from 'bazel-bin/apollo/proto/v1/client_typescript'; -import { - V1Advisory, - V1AdvisoryType, -} from 'bazel-bin/apollo/proto/v1/client_typescript/models'; -import { reqap } from 'common/ui/reqap'; -import React, { useEffect, useState } from 'react'; -import { Link as RouterLink } from 'react-router-dom'; - -import { api } from '../api'; -import { COLOR_RESF_GREEN } from '../styles'; - -export const Overview = () => { - const inputBackground = useColorModeValue('white', undefined); - - const tableBg = useColorModeValue('white', 'gray.800'); - const pagerButtonScheme = useColorModeValue('blackAlpha', 'gray'); - const linkBlue = useColorModeValue('blue.600', 'blue.300'); - const linkPurple = useColorModeValue('purple.600', 'purple.300'); - - const [advisories, setAdvisories] = useState(); - const [lastUpdated, setLastUpdated] = useState(); - const [total, setTotal] = useState(0); - const [isLoading, setIsLoading] = useState(true); - const [isError, setIsError] = useState(false); - - // Request State - const [page, setPage] = useState(0); - const [pageSize, setPageSize] = useState(25); - const [filtersKeyword, setFiltersKeyword] = useState(); - const [filterBefore, setFilterBefore] = useState(); - const [filterAfter, setFilterAfter] = useState(); - const [filterProduct, setFilterProduct] = useState(''); - const [filtersType, setFiltersType] = - useState(); - const [filtersSeverity, setFiltersSeverity] = - useState(); - - useEffect(() => { - const fetch = async () => { - setIsLoading(true); - const [err, res] = await reqap(() => - api.listAdvisories({ - page, - limit: pageSize, - filtersKeyword, - filtersBefore: filterBefore, - filtersAfter: filterAfter, - filtersProduct: filterProduct, - filtersSeverity: filtersSeverity - ? ListAdvisoriesFiltersSeverityEnum[filtersSeverity] - : undefined, - filtersType: filtersType - ? ListAdvisoriesFiltersTypeEnum[filtersType] - : undefined, - }) - ); - - setIsLoading(false); - - if (err || !res) { - setIsError(true); - setAdvisories(undefined); - return; - } - - setIsError(false); - - if (res) { - setAdvisories(res.advisories); - setLastUpdated(res.lastUpdated); - setTotal(parseInt(res.total || '0')); - } - }; - - const timer = setTimeout(() => fetch(), 500); - - return () => clearTimeout(timer); - }, [ - pageSize, - page, - filtersKeyword, - filterBefore, - filterAfter, - filtersSeverity, - filterProduct, - filtersType, - ]); - - // TODO: Figure out why sticky isn't sticking - const stickyProps: TableColumnHeaderProps = { - position: 'sticky', - top: '0px', - zIndex: '10', - scope: 'col', - }; - - const lastPage = total < pageSize ? 0 : Math.ceil(total / pageSize) - 1; - - return ( - - - - - - - setFiltersKeyword(e.target.value)} - /> - - - - Type - - - {filtersType === 'Security' && ( - - Severity - - - )} - - Product - - - - - - From - { - const newVal = e.currentTarget.value; - console.log(newVal); - - if (!newVal) { - setFilterAfter(undefined); - } - - const asDate = new Date(newVal); - if (!(asDate instanceof Date) || isNaN(asDate.getTime())) { - // Check value parses as a date - return; - } - - const [year, month, date] = newVal.split('-').map(Number); - - setFilterAfter(new Date(year, month - 1, date)); - }} - /> - - - To - { - const newVal = e.currentTarget.value; - - if (!newVal) { - setFilterBefore(undefined); - } - - const asDate = new Date(newVal); - if (!(asDate instanceof Date) || isNaN(asDate.getTime())) { - // Check value parses as a date - return; - } - - const [year, month, date] = newVal.split('-').map(Number); - - setFilterBefore( - new Date(year, month - 1, date, 23, 59, 59, 59) // Set to 1ms prior to midnight to be inclusive of selected date - ); - }} - /> - - - - - - Last updated {lastUpdated?.toLocaleString() || 'never'} - - - - Displaying {(page * pageSize + 1).toLocaleString()}- - {Math.min(total, page * pageSize + pageSize).toLocaleString()} of{' '} - {total.toLocaleString()} - - - } - disabled={page <= 0} - onClick={() => setPage(0)} - /> - } - disabled={page <= 0} - onClick={() => setPage((old) => old - 1)} - /> - - {(page + 1).toLocaleString()} / {(lastPage + 1).toLocaleString()} - - } - disabled={page >= lastPage} - onClick={() => setPage((old) => old + 1)} - /> - } - disabled={page >= lastPage} - onClick={() => setPage(lastPage)} - /> - - - - {isLoading ? ( - - ) : isError ? ( - - - Something has gone wrong - Failed to load errata - - ) : ( - - - - - - - - - - - - - - {!advisories?.length && ( - - - - )} - {advisories?.map((a, idx) => ( - - - - - - - - - ))} - -
- AdvisorySynopsisType / SeverityProductsIssue Date
- No rows found -
- {severityToBadge(a.severity, a.type)} - - - {a.name} - - - {a.synopsis?.replace( - /^(Critical|Important|Moderate|Low): /, - '' - )} - - {typeToText(a.type)} - {a.type === V1AdvisoryType.Security - ? ` / ${severityToText(a.severity)}` - : ''} - {a.affectedProducts?.join(', ')} - {Intl.DateTimeFormat(undefined, { - day: '2-digit', - month: 'short', - year: 'numeric', - }).format(a.publishedAt)} -
-
-
- )} - - - Rows per page: - - - -
- ); -}; diff --git a/apollo/ui/src/components/Root.tsx b/apollo/ui/src/components/Root.tsx deleted file mode 100644 index a6117a3..0000000 --- a/apollo/ui/src/components/Root.tsx +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -import { MoonIcon, SunIcon } from '@chakra-ui/icons'; -import { - Box, - HStack, - Text, - Link as ChakraLink, - useColorMode, - IconButton, - useColorModeValue, - DarkMode, -} from '@chakra-ui/react'; -import { RESFLogo } from 'common/ui/RESFLogo'; -import React from 'react'; -import { Route, Switch } from 'react-router'; -import { Link } from 'react-router-dom'; - -import { COLOR_RESF_BLUE, COLOR_RESF_GREEN } from '../styles'; -import { Overview } from './Overview'; -import { ShowErrata } from './ShowErrata'; - -export const Root = () => { - const { colorMode, toggleColorMode } = useColorMode(); - - const SwitchIcon = useColorModeValue(MoonIcon, SunIcon); - const bodyBg = useColorModeValue('gray.100', 'gray.900'); - - return ( - - - - - - - Product Errata - - - - - } - /> - - - - - - - - - - - - - - - RSS - - - - ); -}; diff --git a/apollo/ui/src/components/ShowErrata.tsx b/apollo/ui/src/components/ShowErrata.tsx deleted file mode 100644 index a1efd7e..0000000 --- a/apollo/ui/src/components/ShowErrata.tsx +++ /dev/null @@ -1,343 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -import { - Alert, - AlertDescription, - AlertIcon, - AlertTitle, - Box, - Breadcrumb, - BreadcrumbItem, - BreadcrumbLink, - Heading, - HStack, - Link, - ListItem, - Spinner, - Tab, - TabList, - TabPanel, - TabPanels, - Tabs, - Text, - UnorderedList, - useColorModeValue, - VStack, -} from '@chakra-ui/react'; -import { - severityToBadge, - severityToText, - typeToText, -} from 'apollo/ui/src/enumToText'; -import { - V1Advisory, - V1AdvisoryType, -} from 'bazel-bin/apollo/proto/v1/client_typescript'; -import { reqap } from 'common/ui/reqap'; -import React, { useState } from 'react'; -import { RouteComponentProps } from 'react-router'; -import { Link as RouterLink } from 'react-router-dom'; - -import { api } from '../api'; -import { COLOR_RESF_GREEN } from '../styles'; - -interface ShowErrataParams { - id: string; -} - -export interface ShowErrataProps - extends RouteComponentProps {} - -export const ShowErrata = (props: ShowErrataProps) => { - const id = props.match.params.id; - - const cardBg = useColorModeValue('white', 'gray.800'); - const sideBg = useColorModeValue('gray.100', 'gray.700'); - const linkBlue = useColorModeValue('blue.600', 'blue.300'); - const linkPurple = useColorModeValue('purple.600', 'purple.300'); - - const [errata, setErrata] = useState(); - const [isLoading, setIsLoading] = useState(true); - const [isError, setIsError] = useState(false); - - React.useEffect(() => { - const fetch = async () => { - setIsLoading(true); - - const [err, res] = await reqap(() => api.getAdvisory({ id })); - - setIsLoading(false); - - if (err || !res) { - setIsError(true); - setErrata(undefined); - return; - } - - setIsError(false); - - setErrata(res.advisory); - }; - - fetch(); - }, [id]); - - return ( - - - - - Product Errata - - - - {id} - - - {isLoading ? ( - - ) : isError ? ( - - - Something has gone wrong - Failed to load errata - - ) : ( - errata && ( - <> - - {severityToBadge(errata.severity, errata.type, 40)} - - - - {errata.name} - - - {errata.synopsis} - - - - - Erratum - Affected Packages - - - - - - Topic - - {errata.topic?.split('\n').map((p, i) => ( - - {p} - - ))} - - Description - - {errata.description?.split('\n').map((p, i) => ( - - {p} - - ))} - - - - {Object.keys(errata.rpms || {}).map((product) => ( -
- - {product} - - - SRPMs - - - {errata.rpms?.[product]?.nvras - ?.filter((x) => x.indexOf('.src.rpm') !== -1) - .map((x) => ( - {x} - ))} - - - RPMs - - - {errata.rpms?.[product]?.nvras - ?.filter((x) => x.indexOf('.src.rpm') === -1) - .map((x) => ( - {x} - ))} - -
- ))} -
-
-
- - - Issued: {errata.publishedAt?.toLocaleDateString()} - - - Type: {typeToText(errata.type)} - - {errata.type === V1AdvisoryType.Security && ( - - Severity: {severityToText(errata.severity)} - - )} - - - Affected Product - {(errata.affectedProducts?.length || 0) > 1 ? 's' : ''} - - - {errata.affectedProducts?.map((x, idx) => ( - {x} - ))} - - - - Fixes - - {errata.fixes?.map((x, idx) => ( - - - {x.sourceBy} - {x.ticket} - - - ))} - - - - CVEs - - {!!errata.cves?.length ? ( - errata.cves?.map((x, idx) => { - let text = `${x.name}${ - x.sourceBy !== '' && ` (Source: ${x.sourceBy})` - }`; - - return ( - - {x.sourceLink === '' ? ( - {text} - ) : ( - - {text} - - )} - - ); - }) - ) : ( - No CVEs - )} - - - - References - - {!!errata.references?.length ? ( - errata.references?.map((x, idx) => ( - {x} - )) - ) : ( - No references - )} - - - -
-
- - ) - )} -
- ); -}; diff --git a/apollo/ui/src/entrypoint.tsx b/apollo/ui/src/entrypoint.tsx deleted file mode 100644 index 6b351e3..0000000 --- a/apollo/ui/src/entrypoint.tsx +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -import 'tailwind/tailwind.css'; - -import { ChakraProvider, ColorModeScript } from '@chakra-ui/react'; -import React from 'react'; -import ReactDOM from 'react-dom'; -import { BrowserRouter } from 'react-router-dom'; - -import { Root } from './components/Root'; -import theme from './theme'; - -export const app = () => { - ReactDOM.render( - <> - - - - - - - , - document.getElementById('root') - ); -}; - -app(); - -if (module.hot) { - module.hot.accept(app); -} diff --git a/apollo/ui/src/enumToText.tsx b/apollo/ui/src/enumToText.tsx deleted file mode 100644 index 8fcb848..0000000 --- a/apollo/ui/src/enumToText.tsx +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -import { Box, Tag, TagProps, Tooltip } from '@chakra-ui/react'; -import { - AdvisorySeverity, - V1AdvisoryType, -} from 'bazel-bin/apollo/proto/v1/client_typescript'; -import React from 'react'; - -export const severityToText = (severity?: AdvisorySeverity): string => { - switch (severity) { - case AdvisorySeverity.Critical: - return 'Critical'; - case AdvisorySeverity.Important: - return 'Important'; - case AdvisorySeverity.Moderate: - return 'Moderate'; - case AdvisorySeverity.Low: - return 'Low'; - default: - return 'None'; - } -}; - -export const severityToBadge = ( - severity: AdvisorySeverity | undefined, - type: V1AdvisoryType | undefined, - size: number = 20 -): React.ReactNode => { - return ( - - { - { - [AdvisorySeverity.Critical]: ( - - - - - - - ), - [AdvisorySeverity.Important]: ( - - - - - - - ), - [AdvisorySeverity.Moderate]: ( - - - - - ), - [AdvisorySeverity.Low]: ( - - - - - - - ), - [AdvisorySeverity.Unknown]: ( - - - - - - - - ), - }[severity || AdvisorySeverity.Unknown] - } - - ); -}; - -export const typeToText = (type?: V1AdvisoryType): string => { - switch (type) { - case V1AdvisoryType.Bugfix: - return 'Bug Fix'; - case V1AdvisoryType.Security: - return 'Security'; - case V1AdvisoryType.Enhancement: - return 'Enhancement'; - default: - return 'Unknown'; - } -}; diff --git a/apollo/ui/src/styles.ts b/apollo/ui/src/styles.ts deleted file mode 100644 index 2008bb7..0000000 --- a/apollo/ui/src/styles.ts +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -export const COLOR_RESF_GREEN = '#10B981'; -export const COLOR_RESF_BLUE = '#1054B9'; diff --git a/apollo/ui/src/theme.ts b/apollo/ui/src/theme.ts deleted file mode 100644 index d4b9e50..0000000 --- a/apollo/ui/src/theme.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) All respective contributors to the Peridot Project. All rights reserved. - * Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. - * Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors - * may be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -import { extendTheme, type Theme, type ThemeConfig } from '@chakra-ui/react'; - -const config: ThemeConfig = { - initialColorMode: 'system', -}; - -const styles: Theme['styles'] = { - global: (props) => ({ - ':root': { - colorScheme: props.colorMode, - }, - }), -}; - -const theme = extendTheme({ - config, - styles, -}); - -export default theme; diff --git a/apollo/worker/BUILD.bazel b/apollo/worker/BUILD.bazel deleted file mode 100644 index e240224..0000000 --- a/apollo/worker/BUILD.bazel +++ /dev/null @@ -1,15 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "worker", - srcs = ["worker.go"], - importpath = "peridot.resf.org/apollo/worker", - visibility = ["//visibility:public"], - deps = [ - "//apollo/db", - "//apollo/workflow", - "//vendor/github.com/sirupsen/logrus", - "//vendor/go.temporal.io/sdk/client", - "//vendor/go.temporal.io/sdk/worker", - ], -) diff --git a/apollo/worker/worker.go b/apollo/worker/worker.go deleted file mode 100644 index 07de405..0000000 --- a/apollo/worker/worker.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package worker - -import ( - "github.com/sirupsen/logrus" - "go.temporal.io/sdk/client" - "go.temporal.io/sdk/worker" - apollodb "peridot.resf.org/apollo/db" - "peridot.resf.org/apollo/workflow" -) - -type Worker struct { - Client client.Client - TaskQueue string - WorkflowController *workflow.Controller - Worker worker.Worker - - log *logrus.Logger -} - -type NewWorkerInput struct { - Temporal client.Client - Database apollodb.Access - TaskQueue string -} - -func NewWorker(input *NewWorkerInput, workflowOpts ...workflow.Option) (*Worker, error) { - log := logrus.New() - - controller, err := workflow.NewController(&workflow.NewControllerInput{ - Temporal: input.Temporal, - Database: input.Database, - MainQueue: input.TaskQueue, - }, workflowOpts...) - if err != nil { - return nil, err - } - - return &Worker{ - Client: input.Temporal, - TaskQueue: input.TaskQueue, - WorkflowController: controller, - Worker: worker.New(input.Temporal, input.TaskQueue, worker.Options{}), - log: log, - }, nil -} - -func (w *Worker) Run() { - err := w.Worker.Run(worker.InterruptCh()) - if err != nil { - w.log.Fatalf("could not run worker: %v", err) - } -} diff --git a/apollo/workflow/BUILD.bazel b/apollo/workflow/BUILD.bazel deleted file mode 100644 index 0828990..0000000 --- a/apollo/workflow/BUILD.bazel +++ /dev/null @@ -1,59 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -go_library( - name = "workflow", - srcs = [ - "autocreate_advisory.go", - "collect_cve_data.go", - "common.go", - "downstream_check.go", - "poll_mirror_cve.go", - "poll_mirror_errata.go", - "update_cve_state.go", - "workflow.go", - ], - importpath = "peridot.resf.org/apollo/workflow", - visibility = ["//visibility:public"], - deps = [ - "//apollo/db", - "//apollo/proto/v1:pb", - "//apollo/rherrata", - "//apollo/rhsecurity", - "//apollo/rpmutils", - "//koji", - "//utils", - "//vendor/github.com/gobwas/glob", - "//vendor/github.com/jmoiron/sqlx/types", - "//vendor/github.com/pkg/errors", - "//vendor/github.com/sirupsen/logrus", - "//vendor/github.com/spf13/viper", - "//vendor/go.temporal.io/sdk/activity", - "//vendor/go.temporal.io/sdk/client", - "//vendor/go.temporal.io/sdk/workflow", - ], -) - -go_test( - name = "workflow_test", - srcs = [ - "autocreate_advisory_test.go", - "downstream_check_test.go", - "poll_mirror_cve_test.go", - "poll_mirror_errata_test.go", - "update_cve_state_test.go", - "workflow_test.go", - ], - data = glob(["testdata/**"]), - embed = [":workflow"], - deps = [ - "//apollo/db", - "//apollo/db/mock", - "//apollo/proto/v1:pb", - "//apollo/rherrata", - "//apollo/rhsecurity", - "//apollo/rhsecuritymock", - "//koji", - "//vendor/github.com/stretchr/testify/require", - "//vendor/go.temporal.io/sdk/testsuite", - ], -) diff --git a/apollo/workflow/autocreate_advisory.go b/apollo/workflow/autocreate_advisory.go deleted file mode 100644 index f5e1d4a..0000000 --- a/apollo/workflow/autocreate_advisory.go +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package workflow - -import ( - "database/sql" - "fmt" - "github.com/sirupsen/logrus" - "go.temporal.io/sdk/workflow" - apollodb "peridot.resf.org/apollo/db" - "peridot.resf.org/apollo/rpmutils" - "strconv" - "strings" - "time" -) - -func (c *Controller) AutoCreateAdvisoryActivity() error { - cves, err := c.db.GetAllCVEsFixedDownstream() - if err != nil { - c.log.Errorf("Could not get cves fixed downstream: %v", err) - return fmt.Errorf("could not get cves fixed downstream") - } - - rebootSuggestedPackages, err := c.db.GetAllRebootSuggestedPackages() - if err != nil { - c.log.Errorf("Could not get reboot suggested packages: %v", err) - return fmt.Errorf("could not get reboot suggested packages") - } - - for _, cve := range cves { - beginTx, err := c.db.Begin() - if err != nil { - logrus.Errorf("could not begin tx: %v", err) - continue - } - tx := c.db.UseTransaction(beginTx) - - affectedProducts, err := tx.GetAllAffectedProductsByCVE(cve.ID) - if err != nil { - logrus.Errorf("Could not get affected products for %s: %v", cve.ID, err) - _ = beginTx.Rollback() - continue - } - - var existingAdvisory *apollodb.Advisory - didSkip := false - - for _, affectedProduct := range affectedProducts { - if !affectedProduct.Advisory.Valid { - continue - } - product, err := c.db.GetProductByID(affectedProduct.ProductID) - if err != nil { - c.log.Errorf("could not get product by id %d: %v", affectedProduct.ProductID, err) - return fmt.Errorf("could not get product by id %d", affectedProduct.ProductID) - } - - advisorySplit := strings.Split(affectedProduct.Advisory.String, "-") - numYearSplit := strings.Split(advisorySplit[1], ":") - - year, err := strconv.Atoi(numYearSplit[0]) - if err != nil { - logrus.Errorf("invalid year %s", numYearSplit[0]) - continue - } - num, err := strconv.Atoi(numYearSplit[1]) - if err != nil { - logrus.Errorf("invalid num %s", numYearSplit[1]) - continue - } - - existingAdvisory, err = tx.GetAdvisoryByCodeAndYearAndNum(product.ShortCode, year, num) - if err != nil { - if err == sql.ErrNoRows { - errata, err := c.errata.GetErrata(affectedProduct.Advisory.String) - if err != nil { - logrus.Errorf("could not get errata from Red Hat: %v", err) - didSkip = true - break - } - - for i, _ := range errata.Topic { - errata.Topic[i] = strings.Replace(errata.Topic[i], "Red Hat Enterprise Linux", product.RedHatProductPrefix.String, -1) - errata.Topic[i] = strings.Replace(errata.Topic[i], "Red Hat", c.vendor, -1) - } - for i, _ := range errata.Description { - errata.Description[i] = strings.Replace(errata.Description[i], "Red Hat Enterprise Linux", product.RedHatProductPrefix.String, -1) - errata.Description[i] = strings.Replace(errata.Description[i], "Red Hat", c.vendor, -1) - } - - var packageName string - if !rpmutils.Module().MatchString(affectedProduct.Package) { - packageName = affectedProduct.Package - } - - newAdvisory := &apollodb.Advisory{ - Year: year, - Num: num, - Synopsis: errata.Synopsis, - Topic: strings.Join(errata.Topic, "\n"), - Severity: int(errata.Severity), - Type: int(errata.Type), - Description: strings.Join(errata.Description, "\n"), - RedHatIssuedAt: sql.NullTime{Valid: true, Time: errata.IssuedAt}, - ShortCodeCode: product.ShortCode, - PublishedAt: sql.NullTime{}, - } - if packageName != "" { - match, err := c.checkForRebootSuggestedPackage(rebootSuggestedPackages, packageName) - if err != nil { - c.log.Errorf("could not check for reboot suggested package: %v", err) - return fmt.Errorf("could not check for reboot suggested package") - } - if match { - newAdvisory.RebootSuggested = true - } - } - - newAdvisory, err = tx.CreateAdvisory(newAdvisory) - if err != nil { - logrus.Errorf("Could not create new advisory: %v", err) - didSkip = true - break - } - existingAdvisory = newAdvisory - - for _, fix := range errata.Fixes { - sourceLink := fmt.Sprintf("https://bugzilla.redhat.com/show_bug.cgi?id=%s", fix.BugzillaID) - id, err := tx.CreateFix(fix.BugzillaID, "Red Hat", sourceLink, fix.Description) - if err != nil { - logrus.Errorf("Could not create fix for BZ#%s", fix.BugzillaID) - didSkip = true - break - } - err = tx.AddAdvisoryFix(existingAdvisory.ID, id) - if err != nil { - logrus.Errorf("Could not add fix BZ#%s to advisory %d", fix.BugzillaID, existingAdvisory.ID) - didSkip = true - break - } - } - if didSkip { - break - } - for _, reference := range errata.References { - // Skip redhat.com references - if strings.Contains(reference, "redhat.com") { - continue - } - - err := tx.CreateAdvisoryReference(existingAdvisory.ID, reference) - if err != nil { - logrus.Errorf("Could not reference %s", reference) - didSkip = true - break - } - } - if didSkip { - break - } - } else { - logrus.Errorf("Could not reach database to retrieve advisory: %v", err) - didSkip = true - break - } - } - - if didSkip { - break - } - - err = tx.AddAdvisoryCVE(existingAdvisory.ID, cve.ID) - if err != nil { - logrus.Errorf("Could not add %s to advisory %d", cve.ID, existingAdvisory.ID) - didSkip = true - break - } - } - - if didSkip { - _ = beginTx.Rollback() - continue - } - - err = beginTx.Commit() - if err != nil { - logrus.Errorf("Could not commit database transaction: %v", err) - continue - } - - logrus.Infof("Created/updated advisory %s-%d:%d for %s", existingAdvisory.ShortCodeCode, existingAdvisory.Year, existingAdvisory.Num, cve.ID) - } - - return nil -} - -func (c *Controller) AutoCreateAdvisoryWorkflow(ctx workflow.Context) error { - activityCtx := workflow.WithActivityOptions(ctx, workflow.ActivityOptions{ - ScheduleToStartTimeout: 5 * time.Minute, - StartToCloseTimeout: time.Hour, - }) - return workflow.ExecuteActivity(activityCtx, c.AutoCreateAdvisoryActivity).Get(ctx, nil) -} diff --git a/apollo/workflow/autocreate_advisory_test.go b/apollo/workflow/autocreate_advisory_test.go deleted file mode 100644 index 42e7e2c..0000000 --- a/apollo/workflow/autocreate_advisory_test.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package workflow diff --git a/apollo/workflow/collect_cve_data.go b/apollo/workflow/collect_cve_data.go deleted file mode 100644 index e83cff1..0000000 --- a/apollo/workflow/collect_cve_data.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package workflow - -import ( - "context" - "encoding/json" - "github.com/pkg/errors" - "go.temporal.io/sdk/workflow" - "strings" - "time" -) - -func (c *Controller) CollectCVEDataActivity(ctx context.Context) error { - cves, err := c.db.GetAllCVEs() - if err != nil { - return errors.Wrap(err, "could not get cves") - } - - // Go through each CVE and set CVE content by fetching from rhsecurity - for _, cve := range cves { - if cve.Content.Valid { - continue - } - if !strings.HasPrefix(cve.ID, "CVE") { - continue - } - - cveRh, _, err := c.security.GetCveExecute(c.security.GetCve(ctx, cve.ID)) - if err != nil { - return errors.Wrap(err, "could not get cve") - } - - cveBytes, err := json.Marshal(cveRh) - if err != nil { - return errors.Wrap(err, "could not marshal cve") - } - err = c.db.SetCVEContent(cve.ID, cveBytes) - if err != nil { - return errors.Wrap(err, "could not set cve content") - } - } - - return nil -} - -func (c *Controller) CollectCVEDataWorkflow(ctx workflow.Context) error { - activityCtx := workflow.WithActivityOptions(ctx, workflow.ActivityOptions{ - ScheduleToStartTimeout: 5 * time.Minute, - StartToCloseTimeout: 12 * time.Hour, - }) - return workflow.ExecuteActivity(activityCtx, c.CollectCVEDataActivity).Get(ctx, nil) -} diff --git a/apollo/workflow/common.go b/apollo/workflow/common.go deleted file mode 100644 index 42e7e2c..0000000 --- a/apollo/workflow/common.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package workflow diff --git a/apollo/workflow/downstream_check.go b/apollo/workflow/downstream_check.go deleted file mode 100644 index 705bd11..0000000 --- a/apollo/workflow/downstream_check.go +++ /dev/null @@ -1,203 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package workflow - -import ( - "context" - "fmt" - "github.com/sirupsen/logrus" - "go.temporal.io/sdk/activity" - "go.temporal.io/sdk/workflow" - apollodb "peridot.resf.org/apollo/db" - apollopb "peridot.resf.org/apollo/pb" - "peridot.resf.org/apollo/rpmutils" - "peridot.resf.org/utils" - "strings" - "time" -) - -func (c *Controller) DownstreamCVECheckActivity(ctx context.Context) error { - go func() { - for { - activity.RecordHeartbeat(ctx) - time.Sleep(10 * time.Second) - } - }() - - pendingProducts, err := c.db.GetPendingAffectedProducts() - if err != nil { - logrus.Errorf("could not get fixed cves: %v", err) - return fmt.Errorf("could not get fixed cves") - } - - for _, affectedProduct := range pendingProducts { - if !affectedProduct.CveID.Valid { - continue - } - - err = func() error { - willNotFixOnly := true - allFixed := true - - switch affectedProduct.State { - case - int(apollopb.AffectedProduct_STATE_WILL_NOT_FIX_UPSTREAM), - int(apollopb.AffectedProduct_STATE_OUT_OF_SUPPORT_SCOPE): - return nil - case - int(apollopb.AffectedProduct_STATE_UNDER_INVESTIGATION_UPSTREAM), - int(apollopb.AffectedProduct_STATE_AFFECTED_UPSTREAM): - allFixed = false - willNotFixOnly = false - return nil - } - - product, err := c.db.GetProductByID(affectedProduct.ProductID) - if err != nil { - logrus.Errorf("could not get product with id %d: %v", affectedProduct.ProductID, err) - return err - } - - ignoredUpstreamPackages, err := c.db.GetAllIgnoredPackagesByProductID(product.ID) - if err != nil { - logrus.Errorf("could not get ignored packages: %v", err) - return err - } - - beginTx, err := c.db.Begin() - if err != nil { - logrus.Errorf("could not begin transaction: %v", err) - return err - } - tx := c.db.UseTransaction(beginTx) - - skipProduct := false - defer func(skipProduct *bool, affectedProduct apollodb.AffectedProduct) { - if *skipProduct { - logrus.Infof("%s: Skipping package for now", affectedProduct.Package) - _ = beginTx.Rollback() - } - }(&skipProduct, *affectedProduct) - - cve, err := c.db.GetCVEByID(affectedProduct.CveID.String) - if err != nil { - return err - } - - nvrOnly := strings.Replace(affectedProduct.Package, ":", "-", 1) - if rpmutils.Module().MatchString(nvrOnly) { - if !affectedProduct.Advisory.Valid { - skipProduct = true - } - - redHatAdvisory, err := c.errata.GetErrata(affectedProduct.Advisory.String) - if err != nil { - logrus.Errorf("Could not get Red Hat Advisory: %v", err) - skipProduct = true - } - - for _, arch := range product.Archs { - redHatProductName := affectedProductNameForArchAndVersion(arch, product.RedHatMajorVersion.Int32) - affected := redHatAdvisory.AffectedProducts[redHatProductName] - if affected == nil { - continue - } - srpms := affected.SRPMs - for _, srpm := range srpms { - status := c.checkKojiForBuild(tx, ignoredUpstreamPackages, srpm, affectedProduct, cve) - if status == apollopb.BuildStatus_BUILD_STATUS_SKIP { - skipProduct = true - break - } else if status == apollopb.BuildStatus_BUILD_STATUS_FIXED { - willNotFixOnly = false - } else if status == apollopb.BuildStatus_BUILD_STATUS_NOT_FIXED { - allFixed = false - willNotFixOnly = false - } - } - break - } - if skipProduct { - logrus.Errorf("%s has not been fixed for NVR %s", cve.ID, nvrOnly) - } - } else { - nvrOnly = rpmutils.Epoch().ReplaceAllString(affectedProduct.Package, "") - status := c.checkKojiForBuild(tx, ignoredUpstreamPackages, nvrOnly, affectedProduct, cve) - if status == apollopb.BuildStatus_BUILD_STATUS_SKIP { - skipProduct = true - } else if status == apollopb.BuildStatus_BUILD_STATUS_FIXED { - willNotFixOnly = false - } else if status == apollopb.BuildStatus_BUILD_STATUS_NOT_FIXED { - allFixed = false - willNotFixOnly = false - } - } - - if !skipProduct { - newState := apollopb.AffectedProduct_STATE_FIXED_UPSTREAM - if allFixed { - newState = apollopb.AffectedProduct_STATE_FIXED_DOWNSTREAM - } - if willNotFixOnly { - newState = apollopb.AffectedProduct_STATE_WILL_NOT_FIX_UPSTREAM - } - err := tx.UpdateAffectedProductStateAndPackageAndAdvisory(affectedProduct.ID, int(newState), affectedProduct.Package, utils.NullStringToPointer(affectedProduct.Advisory)) - if err != nil { - logrus.Errorf("Could not save new CVE state: %v", err) - return err - } - err = beginTx.Commit() - if err != nil { - logrus.Errorf("could not commit transaction: %v", err) - return err - } - - logrus.Infof("%s is now set to %s", cve.ID, newState.String()) - } - - return nil - }() - if err != nil { - return err - } - } - - return nil -} - -func (c *Controller) DownstreamCVECheckWorkflow(ctx workflow.Context) error { - activityCtx := workflow.WithActivityOptions(ctx, workflow.ActivityOptions{ - ScheduleToStartTimeout: 30 * time.Minute, - StartToCloseTimeout: 6 * time.Hour, - HeartbeatTimeout: 30 * time.Second, - }) - return workflow.ExecuteActivity(activityCtx, c.DownstreamCVECheckActivity).Get(ctx, nil) -} diff --git a/apollo/workflow/downstream_check_test.go b/apollo/workflow/downstream_check_test.go deleted file mode 100644 index e04e734..0000000 --- a/apollo/workflow/downstream_check_test.go +++ /dev/null @@ -1,462 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package workflow - -import ( - "github.com/stretchr/testify/require" - "go.temporal.io/sdk/testsuite" - "io/ioutil" - apollopb "peridot.resf.org/apollo/pb" - "peridot.resf.org/apollo/rherrata" - "peridot.resf.org/koji" - "testing" -) - -func getDownstreamCheckEnv() *testsuite.TestWorkflowEnvironment { - env := getPollRedHatErrataEnv() - env.RegisterActivity(controller.UpdateCVEStateActivity) - env.RegisterActivity(controller.DownstreamCVECheckActivity) - - return env -} - -func TestInstance_CheckIfCVEResolvedDownstream_RHBA20212593_NotFixedDownstream(t *testing.T) { - resetDb() - - errataMock.Advisories.Response.Docs = []*rherrata.CompactErrata{ - { - Name: "RHBA-2021:2593", - Description: "", - Synopsis: "", - Severity: "None", - Type: "Bug Fix", - AffectedPackages: []string{ - "cmake-3.18.2-11.el8_4.src.rpm", - "cmake-3.18.2-11.el8_4.x86_64.rpm", - "cmake-data-3.18.2-11.el8_4.noarch.rpm", - "cmake-debuginfo-3.18.2-11.el8_4.i686.rpm", - "cmake-debuginfo-3.18.2-11.el8_4.x86_64.rpm", - "cmake-debugsource-3.18.2-11.el8_4.i686.rpm", - "cmake-debugsource-3.18.2-11.el8_4.x86_64.rpm", - "cmake-doc-3.18.2-11.el8_4.noarch.rpm", - "cmake-filesystem-3.18.2-11.el8_4.i686.rpm", - "cmake-filesystem-3.18.2-11.el8_4.x86_64.rpm", - "cmake-gui-3.18.2-11.el8_4.x86_64.rpm", - "cmake-gui-debuginfo-3.18.2-11.el8_4.i686.rpm", - "cmake-gui-debuginfo-3.18.2-11.el8_4.x86_64.rpm", - "cmake-rpm-macros-3.18.2-11.el8_4.noarch.rpm", - }, - CVEs: []string{}, - Fixes: []string{}, - PublicationDate: "2021-06-29T00:00:00Z", - }, - } - - env := getDownstreamCheckEnv() - env.ExecuteWorkflow(controller.PollRedHatErrataWorkflow) - require.Nil(t, env.GetWorkflowError()) - - env = getDownstreamCheckEnv() - env.ExecuteWorkflow(controller.DownstreamCVECheckWorkflow) - require.Nil(t, env.GetWorkflowError()) - - affectedProducts, _ := controller.db.GetAllAffectedProductsByCVE("RHBA-2021:2593") - require.Len(t, affectedProducts, 1) - require.Equal(t, "cmake-3.18.2-11.el8_4", affectedProducts[0].Package) - require.Equal(t, int(apollopb.AffectedProduct_STATE_FIXED_UPSTREAM), affectedProducts[0].State) -} - -func TestInstance_CheckIfCVEResolvedDownstream_RHBA20212593_FixedDownstream(t *testing.T) { - resetDb() - - htmlFile, err := ioutil.ReadFile("testdata/RHBA-2021-2593.html") - require.Nil(t, err) - - errataMock.HTMLResponses["RHBA-2021:2593"] = string(htmlFile[:]) - - errataMock.Advisories.Response.Docs = []*rherrata.CompactErrata{ - { - Name: "RHBA-2021:2593", - Description: "", - Synopsis: "", - Severity: "None", - Type: "Bug Fix", - AffectedPackages: []string{ - "cmake-3.18.2-11.el8_4.src.rpm", - "cmake-3.18.2-11.el8_4.x86_64.rpm", - "cmake-data-3.18.2-11.el8_4.noarch.rpm", - "cmake-debuginfo-3.18.2-11.el8_4.i686.rpm", - "cmake-debuginfo-3.18.2-11.el8_4.x86_64.rpm", - "cmake-debugsource-3.18.2-11.el8_4.i686.rpm", - "cmake-debugsource-3.18.2-11.el8_4.x86_64.rpm", - "cmake-doc-3.18.2-11.el8_4.noarch.rpm", - "cmake-filesystem-3.18.2-11.el8_4.i686.rpm", - "cmake-filesystem-3.18.2-11.el8_4.x86_64.rpm", - "cmake-gui-3.18.2-11.el8_4.x86_64.rpm", - "cmake-gui-debuginfo-3.18.2-11.el8_4.i686.rpm", - "cmake-gui-debuginfo-3.18.2-11.el8_4.x86_64.rpm", - "cmake-rpm-macros-3.18.2-11.el8_4.noarch.rpm", - }, - CVEs: []string{}, - Fixes: []string{}, - PublicationDate: "2021-06-29T00:00:00Z", - }, - } - - env := getDownstreamCheckEnv() - env.ExecuteWorkflow(controller.PollRedHatErrataWorkflow) - require.Nil(t, env.GetWorkflowError()) - - env = getDownstreamCheckEnv() - env.ExecuteWorkflow(controller.UpdateCVEStateWorkflow) - require.Nil(t, env.GetWorkflowError()) - - kojiMock.Tagged = []*koji.Build{ - { - BuildId: 10, - CompletionTime: "", - CompletionTs: 0, - CreationEventId: 0, - CreationTime: "", - CreationTs: 0, - Epoch: "", - Extra: &koji.ListBuildsExtra{ - Source: &koji.ListBuildsExtraSource{ - OriginalUrl: "git+https://git.rockylinux.org/staging/rpms/cmake.git?#aa313111d4efd7cc6c36d41cd9fc29874d1e0740", - }, - }, - Name: "cmake", - Nvr: "cmake-3.18.2-11.el8_4", - OwnerId: 0, - OwnerName: "distrobuild", - PackageId: 0, - PackageName: "cmake", - Release: "11.el8_4", - Source: "", - StartTime: "", - StartTs: 0, - State: 0, - TaskId: 0, - Version: "3.18.2", - VolumeId: 0, - VolumeName: "", - TagId: 0, - TagName: "", - }, - } - - kojiMock.RPMs = []*koji.RPM{ - { - Arch: "src", - BuildId: 10, - Name: "cmake", - Nvr: "cmake-3.18.2-11.el8_4", - Release: "11.el8_4", - Version: "3.18.2", - }, - { - Arch: "x86_64", - BuildId: 10, - Name: "cmake", - Nvr: "cmake-3.18.2-11.el8_4", - Release: "11.el8_4", - Version: "3.18.2", - }, - { - Arch: "x86_64", - BuildId: 10, - Name: "cmake-gui", - Nvr: "cmake-gui-3.18.2-11.el8_4", - Release: "11.el8_4", - Version: "3.18.2", - }, - { - Arch: "noarch", - BuildId: 10, - Name: "cmake-doc", - Nvr: "cmake-doc-3.18.2-11.el8_4", - Release: "11.el8_4", - Version: "3.18.2", - }, - { - Arch: "noarch", - BuildId: 10, - Name: "cmake-rpm-macros", - Nvr: "cmake-rpm-macros-3.18.2-11.el8_4", - Release: "11.el8_4", - Version: "3.18.2", - }, - { - Arch: "noarch", - BuildId: 10, - Name: "cmake-data", - Nvr: "cmake-data-3.18.2-11.el8_4", - Release: "11.el8_4", - Version: "3.18.2", - }, - { - Arch: "i686", - BuildId: 10, - Name: "cmake-debuginfo", - Nvr: "cmake-debuginfo-3.18.2-11.el8_4", - Release: "11.el8_4", - Version: "3.18.2", - }, - { - Arch: "x86_64", - BuildId: 10, - Name: "cmake-debuginfo", - Nvr: "cmake-debuginfo-3.18.2-11.el8_4", - Release: "11.el8_4", - Version: "3.18.2", - }, - { - Arch: "i686", - BuildId: 10, - Name: "cmake-debugsource", - Nvr: "cmake-debugsource-3.18.2-11.el8_4", - Release: "11.el8_4", - Version: "3.18.2", - }, - { - Arch: "x86_64", - BuildId: 10, - Name: "cmake-debugsource", - Nvr: "cmake-debugsource-3.18.2-11.el8_4", - Release: "11.el8_4", - Version: "3.18.2", - }, - { - Arch: "i686", - BuildId: 10, - Name: "cmake-filesystem", - Nvr: "cmake-filesystem-3.18.2-11.el8_4", - Release: "11.el8_4", - Version: "3.18.2", - }, - { - Arch: "x86_64", - BuildId: 10, - Name: "cmake-filesystem", - Nvr: "cmake-filesystem-3.18.2-11.el8_4", - Release: "11.el8_4", - Version: "3.18.2", - }, - { - Arch: "i686", - BuildId: 10, - Name: "cmake-gui-debuginfo", - Nvr: "cmake-gui-debuginfo-3.18.2-11.el8_4", - Release: "11.el8_4", - Version: "3.18.2", - }, - { - Arch: "x86_64", - BuildId: 10, - Name: "cmake-gui-debuginfo", - Nvr: "cmake-gui-debuginfo-3.18.2-11.el8_4", - Release: "11.el8_4", - Version: "3.18.2", - }, - } - - env = getDownstreamCheckEnv() - env.ExecuteWorkflow(controller.DownstreamCVECheckWorkflow) - require.Nil(t, env.GetWorkflowError()) - - affectedProducts, _ := controller.db.GetAllAffectedProductsByCVE("RHBA-2021:2593") - require.Len(t, affectedProducts, 1) - require.Equal(t, "cmake-3.18.2-11.el8_4", affectedProducts[0].Package) - require.Equal(t, int(apollopb.AffectedProduct_STATE_FIXED_DOWNSTREAM), affectedProducts[0].State) - - require.Len(t, mockDb.BuildReferences, 14) - require.Equal(t, "10", mockDb.BuildReferences[0].KojiID.String) -} - -/*func TestInstance_CheckIfCVEResolvedDownstream_RHSA20221642_FixedDownstream(t *testing.T) { - resetDb() - - htmlFile, err := ioutil.ReadFile("testdata/RHSA-2022-1642.html") - require.Nil(t, err) - - errataMock.HTMLResponses["RHSA-2022:1642"] = string(htmlFile[:]) - - errataMock.Advisories.Response.Docs = []*rherrata.CompactErrata{ - { - Name: "RHSA-2022:1642", - Description: "", - Synopsis: "", - Severity: "Important", - Type: "Security", - AffectedPackages: []string{ - "zlib-1.2.11-18.el8_5.src.rpm", - "zlib-1.2.11-18.el8_5.i686.rpm", - "zlib-1.2.11-18.el8_5.x86_64.rpm", - "zlib-debuginfo-1.2.11-18.el8_5.i686.rpm", - "zlib-debuginfo-1.2.11-18.el8_5.x86_64.rpm", - "zlib-debugsource-1.2.11-18.el8_5.i686.rpm", - "zlib-debugsource-1.2.11-18.el8_5.x86_64.rpm", - "zlib-devel-1.2.11-18.el8_5.i686.rpm", - "zlib-devel-1.2.11-18.el8_5.x86_64.rpm", - }, - CVEs: []string{ - "CVE-2018-25032", - }, - Fixes: []string{}, - PublicationDate: "2022-04-28T00:00:00Z", - }, - } - - env := getDownstreamCheckEnv() - env.ExecuteWorkflow(controller.PollRedHatErrataWorkflow) - require.Nil(t, env.GetWorkflowError()) - - kojiMock.Tagged = []*koji.Build{ - { - BuildId: 10, - CompletionTime: "", - CompletionTs: 0, - CreationEventId: 0, - CreationTime: "", - CreationTs: 0, - Epoch: "", - Extra: &koji.ListBuildsExtra{ - Source: &koji.ListBuildsExtraSource{ - OriginalUrl: "git+https://git.rockylinux.org/staging/rpms/zlib.git?#cc63be52ed1ba4f25d2015fd014558a3e7e19b08", - }, - }, - Name: "zlib", - Nvr: "zlib-1.2.11-18.el8_5", - OwnerId: 0, - OwnerName: "distrobuild", - PackageId: 0, - PackageName: "zlib", - Release: "18.el8_5", - Source: "", - StartTime: "", - StartTs: 0, - State: 0, - TaskId: 0, - Version: "1.2.11", - VolumeId: 0, - VolumeName: "", - TagId: 0, - TagName: "", - }, - } - - kojiMock.RPMs = []*koji.RPM{ - { - Arch: "src", - BuildId: 10, - Name: "zlib", - Nvr: "zlib-1.2.11-18.el8_5", - Release: "18.el8_5", - Version: "1.2.11", - }, - { - Arch: "i686", - BuildId: 10, - Name: "zlib", - Nvr: "zlib-1.2.11-18.el8_5", - Release: "18.el8_5", - Version: "1.2.11", - }, - { - Arch: "x86_64", - BuildId: 10, - Name: "zlib", - Nvr: "zlib-1.2.11-18.el8_5", - Release: "18.el8_5", - Version: "1.2.11", - }, - { - Arch: "i686", - BuildId: 10, - Name: "zlib-debuginfo", - Nvr: "zlib-debuginfo-1.2.11-18.el8_5", - Release: "18.el8_5", - Version: "1.2.11", - }, - { - Arch: "x86_64", - BuildId: 10, - Name: "zlib-debuginfo", - Nvr: "zlib-debuginfo-1.2.11-18.el8_5", - Release: "18.el8_5", - Version: "1.2.11", - }, - { - Arch: "i686", - BuildId: 10, - Name: "zlib-debugsource", - Nvr: "zlib-debugsource-1.2.11-18.el8_5", - Release: "18.el8_5", - Version: "1.2.11", - }, - { - Arch: "x86_64", - BuildId: 10, - Name: "zlib-debugsource", - Nvr: "zlib-debugsource-1.2.11-18.el8_5", - Release: "18.el8_5", - Version: "1.2.11", - }, - { - Arch: "i686", - BuildId: 10, - Name: "zlib-devel", - Nvr: "zlib-devel-1.2.11-18.el8_5", - Release: "18.el8_5", - Version: "1.2.11", - }, - { - Arch: "x86_64", - BuildId: 10, - Name: "zlib-devel", - Nvr: "zlib-devel-1.2.11-18.el8_5", - Release: "18.el8_5", - Version: "1.2.11", - }, - } - - env = getDownstreamCheckEnv() - env.ExecuteWorkflow(controller.DownstreamCVECheckWorkflow) - require.Nil(t, env.GetWorkflowError()) - - affectedProducts, _ := controller.db.GetAllAffectedProductsByCVE("RHSA-2022:1642") - require.Len(t, affectedProducts, 1) - require.Equal(t, "zlib-1.2.11-18.el8_5", affectedProducts[0].Package) - require.Equal(t, int(apollopb.AffectedProduct_STATE_FIXED_DOWNSTREAM), affectedProducts[0].State) - - require.Len(t, mockDb.BuildReferences, 14) - require.Equal(t, "10", mockDb.BuildReferences[0].KojiID) -}*/ diff --git a/apollo/workflow/poll_mirror_cve.go b/apollo/workflow/poll_mirror_cve.go deleted file mode 100644 index abb4d83..0000000 --- a/apollo/workflow/poll_mirror_cve.go +++ /dev/null @@ -1,212 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package workflow - -import ( - "context" - "database/sql" - "encoding/json" - "fmt" - "github.com/jmoiron/sqlx/types" - "github.com/pkg/errors" - "go.temporal.io/sdk/activity" - "go.temporal.io/sdk/workflow" - apollodb "peridot.resf.org/apollo/db" - apollopb "peridot.resf.org/apollo/pb" - "peridot.resf.org/utils" - "strings" - "time" -) - -type ShortCodesRes struct { - ShortCodes []*apollodb.ShortCode `json:"short_codes"` -} - -func (c *Controller) pollCVEProcessProduct(ctx context.Context, product *apollodb.Product, shortCode *apollodb.ShortCode) error { - // Skip if the product doesn't define a valid Red Hat version - if !product.RedHatMajorVersion.Valid { - return nil - } - // Skip if product doesn't have correct Red Hat prefix - if !strings.HasPrefix(product.Name, product.RedHatProductPrefix.String) { - return nil - } - - var lastSync *time.Time - mirrorState, err := c.db.GetMirrorState(shortCode.Code) - if err != nil { - if err != sql.ErrNoRows { - c.log.Errorf("could not get last sync for code %s: %v", shortCode.Code, err) - // The cron will retry this - return nil - } - } else { - if mirrorState != nil && mirrorState.LastSync.Valid { - lastSync = &mirrorState.LastSync.Time - } - } - if lastSync == nil { - now := time.Now() - if product.MirrorFromDate.Valid { - now = product.MirrorFromDate.Time - } - lastSync = &now - } - - req := c.security.GetCves(ctx) - req = req.Product(productName(product.RedHatMajorVersion.Int32)) - if lastSync != nil { - req = req.After(lastSync.Format("2006-01-02")) - } - - page := 1 - for { - reqNew := req.Page(float32(page)) - cves, _, err := c.security.GetCvesExecute(reqNew) - if err != nil { - c.log.Errorf("could not get cves: %v", err) - return fmt.Errorf("could not get cves") - } - if len(cves) == 0 { - break - } - - for _, cve := range cves { - _, err := c.db.GetCVEByID(cve.CVE) - if err == nil { - continue - } - if err != sql.ErrNoRows { - c.log.Errorf("an unknown error occurred: %v", err) - return fmt.Errorf("an unknown error occurred") - } - - cveRh, _, err := c.security.GetCveExecute(c.security.GetCve(ctx, cve.CVE)) - if err != nil { - return errors.Wrap(err, "could not get cve") - } - cveBytes, err := json.Marshal(cveRh) - if err != nil { - return fmt.Errorf("could not marshal cve: %v", err) - } - - sourceBy := "Red Hat" - _, err = c.db.CreateCVE(cve.CVE, shortCode.Code, &sourceBy, &cve.ResourceUrl, types.NullJSONText{Valid: true, JSONText: cveBytes}) - if err != nil { - c.log.Errorf("could not create cve: %v", err) - return fmt.Errorf("could not create cve") - } - c.log.Infof("Added %s to %s with state NewFromUpstream", cve.CVE, shortCode.Code) - } - page++ - } - - err = c.db.UpdateMirrorState(shortCode.Code, utils.Pointer[time.Time](time.Now())) - if err != nil { - c.log.Errorf("could not update mirroring state: %v", err) - } - - return nil -} - -func (c *Controller) PollCVEProcessShortCodeActivity(ctx context.Context, shortCode *apollodb.ShortCode) error { - go func() { - for { - activity.RecordHeartbeat(ctx) - time.Sleep(10 * time.Second) - } - }() - - if int32(shortCode.Mode) != int32(apollopb.ShortCode_MODE_MIRROR) { - // This is not a mirrored short code, continue - return nil - } - - allProducts, err := c.db.GetProductsByShortCode(shortCode.Code) - if err != nil { - c.log.Errorf("could not get all products for code %s: %v", shortCode.Code, err) - // Returning nil since the cron will retry this - // We can set up an alert on the Grafana side to alert us - // if this happens too often - return nil - } - - for _, product := range allProducts { - err := c.pollCVEProcessProduct(ctx, product, shortCode) - if err != nil { - return err - } - } - - return nil -} - -func (c *Controller) GetAllShortCodesActivity() (*ShortCodesRes, error) { - s, err := c.db.GetAllShortCodes() - if err != nil { - return nil, err - } - - return &ShortCodesRes{ - ShortCodes: s, - }, nil -} - -func (c *Controller) PollRedHatCVEsWorkflow(ctx workflow.Context) error { - shortCodeCtx := workflow.WithActivityOptions(ctx, workflow.ActivityOptions{ - ScheduleToStartTimeout: time.Minute, - StartToCloseTimeout: time.Minute, - }) - var shortCodeRes ShortCodesRes - err := workflow.ExecuteActivity(shortCodeCtx, c.GetAllShortCodesActivity).Get(ctx, &shortCodeRes) - if err != nil { - return err - } - - var futures []workflow.Future - for _, shortCode := range shortCodeRes.ShortCodes { - activityCtx := workflow.WithActivityOptions(ctx, workflow.ActivityOptions{ - ScheduleToStartTimeout: 5 * time.Minute, - StartToCloseTimeout: 12 * time.Hour, - HeartbeatTimeout: 30 * time.Second, - }) - futures = append(futures, workflow.ExecuteActivity(activityCtx, c.PollCVEProcessShortCodeActivity, shortCode)) - } - - for _, future := range futures { - err := future.Get(ctx, nil) - if err != nil { - return err - } - } - - return nil -} diff --git a/apollo/workflow/poll_mirror_cve_test.go b/apollo/workflow/poll_mirror_cve_test.go deleted file mode 100644 index 70972b9..0000000 --- a/apollo/workflow/poll_mirror_cve_test.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package workflow - -import ( - "github.com/stretchr/testify/require" - "go.temporal.io/sdk/testsuite" - "peridot.resf.org/apollo/rhsecurity" - "testing" -) - -func getPollRedHatCVEsEnv() *testsuite.TestWorkflowEnvironment { - env := testWfSuite.NewTestWorkflowEnvironment() - env.RegisterActivity(controller.GetAllShortCodesActivity) - env.RegisterActivity(controller.PollCVEProcessShortCodeActivity) - - return env -} - -func TestInstance_PollRedHatForNewCVEs_AddNewCVE(t *testing.T) { - resetDb() - - securityMock.Cves[1] = []*rhsecurity.CVE{ - { - CVE: "CVE-2021-3602", - Severity: "moderate", - PublicDate: "2021-07-15T14:00:00Z", - Advisories: []string{}, - Bugzilla: "1969264", - BugzillaDescription: "CVE-2021-3602 buildah: Host environment variables leaked in build container when using chroot isolation", - CvssScore: nil, - CvssScoringVector: nil, - CWE: "CWE-200", - AffectedPackages: nil, - ResourceUrl: "https://access.redhat.com/hydra/rest/securitydata/cve/CVE-2021-3602.json", - Cvss3ScoringVector: "CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:C/C:H/I:N/A:N", - Cvss3Score: "5.6", - }, - } - securityMock.ActiveCVE = &rhsecurity.CVEDetailed{} - require.Nil(t, readTestDataJson("testdata/CVE-2021-3602.json", securityMock.ActiveCVE)) - - env := getPollRedHatCVEsEnv() - env.ExecuteWorkflow(controller.PollRedHatCVEsWorkflow) - require.Nil(t, env.GetWorkflowError()) - - cves, _ := controller.db.GetAllUnresolvedCVEs() - require.Len(t, cves, 1) - require.Equal(t, "CVE-2021-3602", cves[0].ID) -} - -func TestPollRedHatForNewCVEs_SkipExistingCVE(t *testing.T) { - resetDb() - - securityMock.Cves[1] = []*rhsecurity.CVE{ - { - CVE: "CVE-2021-3602", - Severity: "moderate", - PublicDate: "2021-07-15T14:00:00Z", - Advisories: []string{}, - Bugzilla: "1969264", - BugzillaDescription: "CVE-2021-3602 buildah: Host environment variables leaked in build container when using chroot isolation", - CvssScore: nil, - CvssScoringVector: nil, - CWE: "CWE-200", - AffectedPackages: nil, - ResourceUrl: "https://access.redhat.com/hydra/rest/securitydata/cve/CVE-2021-3602.json", - Cvss3ScoringVector: "CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:C/C:H/I:N/A:N", - Cvss3Score: "5.6", - }, - } - securityMock.ActiveCVE = &rhsecurity.CVEDetailed{} - require.Nil(t, readTestDataJson("testdata/CVE-2021-3602.json", securityMock.ActiveCVE)) - - env := getPollRedHatCVEsEnv() - env.ExecuteWorkflow(controller.PollRedHatCVEsWorkflow) - require.Nil(t, env.GetWorkflowError()) - - cves, _ := controller.db.GetAllUnresolvedCVEs() - require.Len(t, cves, 1) - require.Equal(t, "CVE-2021-3602", cves[0].ID) - - env = getPollRedHatCVEsEnv() - env.ExecuteWorkflow(controller.PollRedHatCVEsWorkflow) - require.Nil(t, env.GetWorkflowError()) - - cves, _ = controller.db.GetAllUnresolvedCVEs() - require.Len(t, cves, 1) - require.Equal(t, "CVE-2021-3602", cves[0].ID) -} diff --git a/apollo/workflow/poll_mirror_errata.go b/apollo/workflow/poll_mirror_errata.go deleted file mode 100644 index f0fe044..0000000 --- a/apollo/workflow/poll_mirror_errata.go +++ /dev/null @@ -1,304 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package workflow - -import ( - "context" - "database/sql" - "encoding/json" - "fmt" - "github.com/jmoiron/sqlx/types" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - "go.temporal.io/sdk/activity" - "go.temporal.io/sdk/workflow" - apollodb "peridot.resf.org/apollo/db" - apollopb "peridot.resf.org/apollo/pb" - "peridot.resf.org/apollo/rpmutils" - "peridot.resf.org/utils" - "strconv" - "strings" - "time" -) - -func (c *Controller) processErrataShortCodeProduct(shortCode *apollodb.ShortCode, product *apollodb.Product) error { - if !product.RedHatMajorVersion.Valid { - return nil - } - if !strings.HasPrefix(product.Name, product.RedHatProductPrefix.String) { - return nil - } - - ignoredUpstreamPackages, err := c.db.GetAllIgnoredPackagesByProductID(product.ID) - if err != nil { - logrus.Errorf("could not get ignored packages: %v", err) - return fmt.Errorf("could not get ignored packages") - } - - var lastSync *time.Time - mirrorState, err := c.db.GetMirrorState(shortCode.Code) - if err == nil { - if mirrorState.ErrataAfter.Valid { - lastSync = &mirrorState.ErrataAfter.Time - } - } - - advisories, err := c.errata.GetAdvisories(product.CurrentFullVersion, lastSync) - if err != nil { - logrus.Errorf("Could not get Red Hat Advisories: %v", err) - return fmt.Errorf("could not get Red Hat Advisories") - } - - var newLastSync *time.Time - - parentBeginTx, err := c.db.Begin() - if err != nil { - return fmt.Errorf("could not begin transaction: %v", err) - } - parentTx := c.db.UseTransaction(parentBeginTx) - rollbackParent := true - defer func() { - if rollbackParent { - _ = parentBeginTx.Rollback() - } - }() - - for _, advisory := range advisories { - if newLastSync == nil { - parsedTime, err := time.Parse(time.RFC3339, advisory.PublicationDate) - if err == nil { - newLastSync = &parsedTime - _ = parentTx.UpdateMirrorStateErrata(shortCode.Code, newLastSync) - } - } - - advisoryId := rpmutils.AdvisoryId().FindStringSubmatch(advisory.Name) - if len(advisoryId) < 5 { - logrus.Errorf("Invalid advisory %s", advisory.Name) - return nil - } - code := advisoryId[1] - year, err := strconv.Atoi(advisoryId[3]) - if err != nil { - logrus.Errorf("Invalid advisory %s", advisory.Name) - return nil - } - num, err := strconv.Atoi(advisoryId[4]) - if err != nil { - logrus.Errorf("Invalid advisory %s", advisory.Name) - return nil - } - - beginTx, err := c.db.Begin() - if err != nil { - logrus.Errorf("Could not begin tx: %v", err) - return fmt.Errorf("could not begin tx") - } - tx := c.db.UseTransaction(beginTx) - - _, err = tx.GetAdvisoryByCodeAndYearAndNum(code, year, num) - if err != nil { - if err == sql.ErrNoRows { - // If security then just add CVEs, the rest should be automatic - if strings.HasPrefix(advisory.Name, "RHSA") { - for _, cve := range advisory.CVEs { - _, err := tx.GetCVEByID(cve) - if err == nil { - continue - } - if err != sql.ErrNoRows { - logrus.Errorf("an unknown error occurred: %v", err) - _ = beginTx.Rollback() - return fmt.Errorf("an unknown error occurred") - } - - sourceBy := "Red Hat" - resourceUrl := fmt.Sprintf("https://access.redhat.com/hydra/rest/securitydata/cve/%s.json", cve) - - cveRh, _, err := c.security.GetCveExecute(c.security.GetCve(context.TODO(), cve)) - if err != nil { - return errors.Wrap(err, "could not get cve") - } - cveBytes, err := json.Marshal(cveRh) - if err != nil { - return fmt.Errorf("could not marshal cve: %v", err) - } - - _, err = tx.CreateCVE(cve, shortCode.Code, &sourceBy, &resourceUrl, types.NullJSONText{Valid: true, JSONText: cveBytes}) - if err != nil { - logrus.Errorf("could not create cve: %v", err) - _ = beginTx.Rollback() - return fmt.Errorf("could not create cve") - } - logrus.Infof("Added %s to %s (%s)", cve, shortCode.Code, advisory.Name) - } - } else if strings.HasPrefix(advisory.Name, "RHBA") || strings.HasPrefix(advisory.Name, "RHEA") { - _, err := tx.GetAffectedProductByAdvisory(advisory.Name) - if err != nil { - if err == sql.ErrNoRows { - _, err := tx.GetCVEByID(advisory.Name) - if err == nil { - continue - } - if err != sql.ErrNoRows { - logrus.Errorf("an unknown error occurred: %v", err) - _ = beginTx.Rollback() - return fmt.Errorf("an unknown error occurred") - } - - sourceBy := "Red Hat" - resourceUrl := fmt.Sprintf("https://access.redhat.com/errata/%s", advisory.Name) - _, err = tx.CreateCVE(advisory.Name, product.ShortCode, &sourceBy, &resourceUrl, types.NullJSONText{}) - if err != nil { - _ = beginTx.Rollback() - return fmt.Errorf("could not create cve: %v", err) - } - - for _, srpm := range advisory.AffectedPackages { - if !strings.Contains(srpm, ".src.rpm") { - continue - } - - pkg := strings.Replace(srpm, ".src.rpm", "", 1) - - nvr := rpmutils.NVR().FindStringSubmatch(pkg) - var packageName string - if len(nvr) >= 2 { - packageName = nvr[1] - } else { - packageName = pkg - } - if utils.StrContains(packageName, ignoredUpstreamPackages) { - continue - } - dist := fmt.Sprintf("el%d", product.RedHatMajorVersion.Int32) - if !strings.Contains(pkg, dist) { - continue - } - if strings.Contains(pkg, dist+"sat") { - continue - } - _, err := tx.CreateAffectedProduct(product.ID, advisory.Name, int(apollopb.AffectedProduct_STATE_FIXED_UPSTREAM), product.CurrentFullVersion, pkg, &advisory.Name) - if err != nil { - _ = beginTx.Rollback() - return fmt.Errorf("could not create affected product for srpm: %v", err) - } - } - logrus.Infof("Added %s to %s", advisory.Name, shortCode.Code) - } else { - _ = beginTx.Rollback() - return fmt.Errorf("Could not get affected product by advisory: %v", err) - } - } - } - } else { - _ = beginTx.Rollback() - logrus.Errorf("Could not fetch advisory: %v", err) - return err - } - } - - err = beginTx.Commit() - if err != nil { - logrus.Errorf("Could not commit new advisory tx: %v", err) - return err - } - } - - rollbackParent = false - err = parentBeginTx.Commit() - if err != nil { - logrus.Errorf("Could not commit parent tx: %v", err) - return err - } - - return nil -} - -func (c *Controller) ProcessRedHatErrataShortCodeActivity(ctx context.Context, shortCode *apollodb.ShortCode) error { - go func() { - for { - activity.RecordHeartbeat(ctx) - time.Sleep(10 * time.Second) - } - }() - - if int32(shortCode.Mode) != int32(apollopb.ShortCode_MODE_MIRROR) { - // This is not a mirrored short code, continue - return nil - } - - allProducts, err := c.db.GetProductsByShortCode(shortCode.Code) - if err != nil { - logrus.Errorf("could not get all products for code %s: %v", shortCode.Code, err) - return fmt.Errorf("could not get all products for code %s", shortCode.Code) - } - - for _, product := range allProducts { - err := c.processErrataShortCodeProduct(shortCode, product) - if err != nil { - return err - } - } - - return nil -} - -func (c *Controller) PollRedHatErrataWorkflow(ctx workflow.Context) error { - shortCodeCtx := workflow.WithActivityOptions(ctx, workflow.ActivityOptions{ - ScheduleToStartTimeout: time.Minute, - StartToCloseTimeout: time.Minute, - }) - var shortCodeRes ShortCodesRes - err := workflow.ExecuteActivity(shortCodeCtx, c.GetAllShortCodesActivity).Get(ctx, &shortCodeRes) - if err != nil { - return err - } - - var futures []workflow.Future - for _, shortCode := range shortCodeRes.ShortCodes { - activityCtx := workflow.WithActivityOptions(ctx, workflow.ActivityOptions{ - ScheduleToStartTimeout: 5 * time.Minute, - StartToCloseTimeout: 12 * time.Hour, - HeartbeatTimeout: 30 * time.Second, - }) - futures = append(futures, workflow.ExecuteActivity(activityCtx, c.ProcessRedHatErrataShortCodeActivity, shortCode)) - } - - for _, future := range futures { - err := future.Get(ctx, nil) - if err != nil { - return err - } - } - - return nil -} diff --git a/apollo/workflow/poll_mirror_errata_test.go b/apollo/workflow/poll_mirror_errata_test.go deleted file mode 100644 index 0efc745..0000000 --- a/apollo/workflow/poll_mirror_errata_test.go +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package workflow - -import ( - "github.com/stretchr/testify/require" - "go.temporal.io/sdk/testsuite" - apollopb "peridot.resf.org/apollo/pb" - "peridot.resf.org/apollo/rherrata" - "testing" -) - -func getPollRedHatErrataEnv() *testsuite.TestWorkflowEnvironment { - env := testWfSuite.NewTestWorkflowEnvironment() - env.RegisterActivity(controller.GetAllShortCodesActivity) - env.RegisterActivity(controller.ProcessRedHatErrataShortCodeActivity) - - return env -} - -func TestInstance_ScanRedHatErrata_RHSA20212595_Security_CVE(t *testing.T) { - resetDb() - - errataMock.Advisories.Response.Docs = []*rherrata.CompactErrata{ - { - Name: "RHSA-2021:2595", - Description: "", - Synopsis: "", - Severity: "Moderate", - Type: "Security", - AffectedPackages: []string{ - "389-ds-base-1.4.3.16-16.module+el8.4.0+11446+fc96bc48.src.rpm", - "389-ds-base-1.4.3.16-16.module+el8.4.0+11446+fc96bc48.x86_64.rpm", - "389-ds-base-debuginfo-1.4.3.16-16.module+el8.4.0+11446+fc96bc48.x86_64.rpm", - "389-ds-base-debugsource-1.4.3.16-16.module+el8.4.0+11446+fc96bc48.x86_64.rpm", - "389-ds-base-devel-1.4.3.16-16.module+el8.4.0+11446+fc96bc48.x86_64.rpm", - "389-ds-base-legacy-tools-1.4.3.16-16.module+el8.4.0+11446+fc96bc48.x86_64.rpm", - "389-ds-base-legacy-tools-debuginfo-1.4.3.16-16.module+el8.4.0+11446+fc96bc48.x86_64.rpm", - "389-ds-base-libs-1.4.3.16-16.module+el8.4.0+11446+fc96bc48.x86_64.rpm", - "389-ds-base-libs-debuginfo-1.4.3.16-16.module+el8.4.0+11446+fc96bc48.x86_64.rpm", - "389-ds-base-snmp-1.4.3.16-16.module+el8.4.0+11446+fc96bc48.x86_64.rpm", - "389-ds-base-snmp-debuginfo-1.4.3.16-16.module+el8.4.0+11446+fc96bc48.x86_64.rpm", - "python3-lib389-1.4.3.16-16.module+el8.4.0+11446+fc96bc48.noarch.rpm", - }, - CVEs: []string{ - "CVE-2021-3514", - }, - Fixes: []string{ - "1952907", - "1960720", - "1968588", - "1970791", - "1972721", - "1972738", - }, - PublicationDate: "2021-06-29T00:00:00Z", - }, - } - - env := getPollRedHatErrataEnv() - env.ExecuteWorkflow(controller.PollRedHatErrataWorkflow) - require.Nil(t, env.GetWorkflowError()) - - cves, _ := controller.db.GetAllUnresolvedCVEs() - require.Len(t, cves, 1) - require.Equal(t, "CVE-2021-3514", cves[0].ID) -} - -func TestInstance_ScanRedHatErrata_BugFix_Erratum(t *testing.T) { - resetDb() - - errataMock.Advisories.Response.Docs = []*rherrata.CompactErrata{ - { - Name: "RHBA-2021:2593", - Description: "", - Synopsis: "", - Severity: "None", - Type: "Bug Fix", - AffectedPackages: []string{ - "cmake-3.18.2-11.el8_4.src.rpm", - "cmake-3.18.2-11.el8_4.x86_64.rpm", - "cmake-data-3.18.2-11.el8_4.noarch.rpm", - "cmake-debuginfo-3.18.2-11.el8_4.i686.rpm", - "cmake-debuginfo-3.18.2-11.el8_4.x86_64.rpm", - "cmake-debugsource-3.18.2-11.el8_4.i686.rpm", - "cmake-debugsource-3.18.2-11.el8_4.x86_64.rpm", - "cmake-doc-3.18.2-11.el8_4.noarch.rpm", - "cmake-filesystem-3.18.2-11.el8_4.i686.rpm", - "cmake-filesystem-3.18.2-11.el8_4.x86_64.rpm", - "cmake-gui-3.18.2-11.el8_4.x86_64.rpm", - "cmake-gui-debuginfo-3.18.2-11.el8_4.i686.rpm", - "cmake-gui-debuginfo-3.18.2-11.el8_4.x86_64.rpm", - "cmake-rpm-macros-3.18.2-11.el8_4.noarch.rpm", - }, - CVEs: []string{}, - Fixes: []string{}, - PublicationDate: "2021-06-29T00:00:00Z", - }, - } - - env := getPollRedHatErrataEnv() - env.ExecuteWorkflow(controller.PollRedHatErrataWorkflow) - require.Nil(t, env.GetWorkflowError()) - - cves := mockDb.Cves - require.Len(t, cves, 1) - require.Equal(t, "RHBA-2021:2593", cves[0].ID) - - affectedProducts, _ := controller.db.GetAllAffectedProductsByCVE(cves[0].ID) - require.Len(t, affectedProducts, 1) - require.Equal(t, "cmake-3.18.2-11.el8_4", affectedProducts[0].Package) - require.Equal(t, int(apollopb.AffectedProduct_STATE_FIXED_UPSTREAM), affectedProducts[0].State) -} diff --git a/apollo/workflow/testdata/CVE-2021-3602.json b/apollo/workflow/testdata/CVE-2021-3602.json deleted file mode 100644 index 6a30594..0000000 --- a/apollo/workflow/testdata/CVE-2021-3602.json +++ /dev/null @@ -1,112 +0,0 @@ -{ - "threat_severity": "Moderate", - "public_date": "2021-07-15T14:00:00Z", - "bugzilla": { - "description": "CVE-2021-3602 buildah: Host environment variables leaked in build container when using chroot isolation", - "id": "1969264", - "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1969264" - }, - "cvss3": { - "cvss3_base_score": "5.6", - "cvss3_scoring_vector": "CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:C/C:H/I:N/A:N", - "status": "verified" - }, - "cwe": "CWE-200", - "details": [ - "An information disclosure flaw was found in Buildah, when building containers using chroot isolation. Running processes in container builds (e.g. Dockerfile RUN commands) can access environment variables from parent and grandparent processes. When run in a container in a CI/CD environment, environment variables may include sensitive information that was shared with the container in order to be used only by Buildah itself (e.g. container registry credentials).", - "An information disclosure flaw was found in Buildah, when building containers using chroot isolation. Running processes in container builds (e.g. Dockerfile RUN commands) can access environment variables from parent and grandparent processes. When run in a container in a CI/CD environment, environment variables may include sensitive information that was shared with the container in order to be used only by Buildah itself (e.g. container registry credentials)." - ], - "statement": "OpenShift Container Platform 4's builder container is not vulnerable to this flaw as it uses OCI isolation (i.e. using runc) and does not use chroot isolation.", - "acknowledgement": "Red Hat would like to thank Blake Burkhart for reporting this issue.", - "affected_release": [ - { - "product_name": "Red Hat Enterprise Linux 8", - "release_date": "2021-11-09T00:00:00Z", - "advisory": "RHSA-2021:4154", - "cpe": "cpe:/a:redhat:enterprise_linux:8", - "package": "container-tools:rhel8-8050020210921082437.faa19cc5" - }, - { - "product_name": "Red Hat Enterprise Linux 8", - "release_date": "2021-11-09T00:00:00Z", - "advisory": "RHSA-2021:4221", - "cpe": "cpe:/a:redhat:enterprise_linux:8", - "package": "container-tools:2.0-8050020210817115648.faa19cc5" - }, - { - "product_name": "Red Hat Enterprise Linux 8", - "release_date": "2021-11-09T00:00:00Z", - "advisory": "RHSA-2021:4222", - "cpe": "cpe:/a:redhat:enterprise_linux:8", - "package": "container-tools:3.0-8050020210915114620.faa19cc5" - } - ], - "package_state": [ - { - "product_name": "Red Hat Enterprise Linux 7", - "fix_state": "Out of support scope", - "package_name": "buildah", - "cpe": "cpe:/o:redhat:enterprise_linux:7" - }, - { - "product_name": "Red Hat Enterprise Linux 7", - "fix_state": "Out of support scope", - "package_name": "podman", - "cpe": "cpe:/o:redhat:enterprise_linux:7" - }, - { - "product_name": "Red Hat Enterprise Linux 9", - "fix_state": "Not affected", - "package_name": "buildah", - "cpe": "cpe:/o:redhat:enterprise_linux:9" - }, - { - "product_name": "Red Hat Enterprise Linux 9", - "fix_state": "Not affected", - "package_name": "podman", - "cpe": "cpe:/o:redhat:enterprise_linux:9" - }, - { - "product_name": "Red Hat OpenShift Container Platform 3.11", - "fix_state": "Will not fix", - "package_name": "podman", - "cpe": "cpe:/a:redhat:openshift:3.11" - }, - { - "product_name": "Red Hat OpenShift Container Platform 4", - "fix_state": "Will not fix", - "package_name": "buildah", - "cpe": "cpe:/a:redhat:openshift:4" - }, - { - "product_name": "Red Hat OpenShift Container Platform 4", - "fix_state": "Not affected", - "package_name": "cri-o", - "cpe": "cpe:/a:redhat:openshift:4" - }, - { - "product_name": "Red Hat OpenShift Container Platform 4", - "fix_state": "Not affected", - "package_name": "openshift4/ose-docker-builder", - "cpe": "cpe:/a:redhat:openshift:4" - }, - { - "product_name": "Red Hat OpenShift Container Platform 4", - "fix_state": "Will not fix", - "package_name": "podman", - "cpe": "cpe:/a:redhat:openshift:4" - }, - { - "product_name": "Red Hat Quay 3", - "fix_state": "Affected", - "package_name": "quay/quay-builder-rhel8", - "cpe": "cpe:/a:redhat:quay:3" - } - ], - "upstream_fix": "buildah 1.16.8, buildah 1.19.9, buildah 1.17.2, buildah 1.21.3", - "references": [ - "https://github.com/containers/buildah/security/advisories/GHSA-7638-r9r3-rmjj" - ], - "name": "CVE-2021-3602", - "csaw": false -} diff --git a/apollo/workflow/testdata/RHBA-2021-2593.html b/apollo/workflow/testdata/RHBA-2021-2593.html deleted file mode 100644 index 38b3015..0000000 --- a/apollo/workflow/testdata/RHBA-2021-2593.html +++ /dev/null @@ -1,1153 +0,0 @@ - diff --git a/apollo/workflow/testdata/RHSA-2021-2595.html b/apollo/workflow/testdata/RHSA-2021-2595.html deleted file mode 100644 index f390d9f..0000000 --- a/apollo/workflow/testdata/RHSA-2021-2595.html +++ /dev/null @@ -1,1154 +0,0 @@ - diff --git a/apollo/workflow/testdata/RHSA-2022-1642.html b/apollo/workflow/testdata/RHSA-2022-1642.html deleted file mode 100644 index 0a50bf7..0000000 --- a/apollo/workflow/testdata/RHSA-2022-1642.html +++ /dev/null @@ -1,1597 +0,0 @@ - - - - - - - - - - - -
-
- - diff --git a/apollo/workflow/update_cve_state.go b/apollo/workflow/update_cve_state.go deleted file mode 100644 index 1437ea0..0000000 --- a/apollo/workflow/update_cve_state.go +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package workflow - -import ( - "context" - "fmt" - "github.com/sirupsen/logrus" - "go.temporal.io/sdk/activity" - "go.temporal.io/sdk/workflow" - apollodb "peridot.resf.org/apollo/db" - apollopb "peridot.resf.org/apollo/pb" - "strings" - "time" -) - -func (c *Controller) UpdateCVEStateActivity(ctx context.Context) error { - go func() { - for { - activity.RecordHeartbeat(ctx) - time.Sleep(10 * time.Second) - } - }() - - cves, err := c.db.GetAllUnresolvedCVEs() - if err != nil { - c.log.Errorf("could not get unresolved cves: %v", err) - return fmt.Errorf("could not get unresolved cves") - } - - shortCodeBuffer := map[string]*apollodb.ShortCode{} - productBuffer := map[string][]*apollodb.Product{} - ignoredPackagesBuffer := map[int64][]string{} - - for _, cve := range cves { - if !strings.HasPrefix(cve.ID, "CVE") { - continue - } - - if shortCodeBuffer[cve.ShortCode] == nil { - shortCode, err := c.db.GetShortCodeByCode(cve.ShortCode) - if err != nil { - logrus.Errorf("could not get short code: %v", err) - continue - } - - shortCodeBuffer[shortCode.Code] = shortCode - } - shortCode := shortCodeBuffer[cve.ShortCode] - - if productBuffer[shortCode.Code] == nil { - products, err := c.db.GetProductsByShortCode(shortCode.Code) - if err != nil { - logrus.Errorf("could not get products for code: %s: %v", shortCode.Code, err) - continue - } - productBuffer[shortCode.Code] = products - } - products := productBuffer[shortCode.Code] - - // Please do not simplify next statement - // During testing we're mocking pagination as well, and this is the - // easiest way to "wrap" and represent a new request restarting it from page 1 - cveRh, _, err := c.security.GetCveExecute(c.security.GetCve(ctx, cve.ID)) - if err != nil { - logrus.Errorf("could not retrieve new state for %s from Red Hat: %v", cve.ID, err) - continue - } - - for _, product := range products { - if ignoredPackagesBuffer[product.ID] == nil { - ignoredUpstreamPackages, err := c.db.GetAllIgnoredPackagesByProductID(product.ID) - if err != nil { - logrus.Errorf("could not get ignored packages: %v", err) - continue - } - ignoredPackagesBuffer[product.ID] = ignoredUpstreamPackages - } - ignoredUpstreamPackages := ignoredPackagesBuffer[product.ID] - - pName := productName(product.RedHatMajorVersion.Int32) - - beginTx, err := c.db.Begin() - if err != nil { - c.log.Errorf("could not begin transaction: %v", err) - continue - } - tx := c.db.UseTransaction(beginTx) - - skipCve := false - defer func() { - if skipCve { - _ = beginTx.Rollback() - } - }() - - if cveRh.AffectedRelease != nil { - for _, state := range *cveRh.AffectedRelease { - if (product.Cpe.Valid && state.Cpe == product.Cpe.String) || state.ProductName == pName { - st := apollopb.AffectedProduct_STATE_FIXED_UPSTREAM - packageName := "TBD" - if state.Package != nil { - packageName = *state.Package - - match, err := c.checkForIgnoredPackage(ignoredUpstreamPackages, packageName) - if err != nil { - c.log.Errorf("Invalid glob: %v", err) - continue - } - if match { - st = apollopb.AffectedProduct_STATE_UNKNOWN - } - } else { - st = apollopb.AffectedProduct_STATE_UNKNOWN - } - skipCve = c.checkProduct(tx, cve, shortCode, product, st, packageName, &state.Advisory) - if skipCve { - break - } - } - } - } - if cveRh.PackageState != nil { - for _, state := range *cveRh.PackageState { - if (product.Cpe.Valid && state.Cpe == product.Cpe.String) || state.ProductName == pName { - pState := productState(state.FixState) - packageName := "TBD" - if state.PackageName != "" { - packageName = state.PackageName - - match, err := c.checkForIgnoredPackage(ignoredUpstreamPackages, packageName) - if err != nil { - c.log.Errorf("Invalid glob: %v", err) - continue - } - if match { - pState = apollopb.AffectedProduct_STATE_UNKNOWN - } - } - skipCve = c.checkProduct(tx, cve, shortCode, product, pState, packageName, nil) - if skipCve { - break - } - } - } - } - - err = beginTx.Commit() - if err != nil { - c.log.Errorf("could not commit transaction: %v", err) - continue - } - } - } - - return nil -} - -func (c *Controller) UpdateCVEStateWorkflow(ctx workflow.Context) error { - activityCtx := workflow.WithActivityOptions(ctx, workflow.ActivityOptions{ - ScheduleToStartTimeout: 5 * time.Minute, - StartToCloseTimeout: 12 * time.Hour, - HeartbeatTimeout: 30 * time.Second, - }) - return workflow.ExecuteActivity(activityCtx, c.UpdateCVEStateActivity).Get(ctx, nil) -} diff --git a/apollo/workflow/update_cve_state_test.go b/apollo/workflow/update_cve_state_test.go deleted file mode 100644 index 4d5c421..0000000 --- a/apollo/workflow/update_cve_state_test.go +++ /dev/null @@ -1,249 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package workflow - -import ( - "github.com/stretchr/testify/require" - "go.temporal.io/sdk/testsuite" - apollopb "peridot.resf.org/apollo/pb" - "peridot.resf.org/apollo/rhsecurity" - "testing" -) - -func getUpdateCVEStateEnv() *testsuite.TestWorkflowEnvironment { - env := getPollRedHatCVEsEnv() - env.RegisterActivity(controller.UpdateCVEStateActivity) - - return env -} - -func TestInstance_UpdateCVEState_AffectedUpstream(t *testing.T) { - resetDb() - - securityMock.Cves[1] = []*rhsecurity.CVE{ - { - CVE: "CVE-2021-3602", - Severity: "moderate", - PublicDate: "2021-07-15T14:00:00Z", - Advisories: []string{}, - Bugzilla: "1969264", - BugzillaDescription: "CVE-2021-3602 buildah: Host environment variables leaked in build container when using chroot isolation", - CvssScore: nil, - CvssScoringVector: nil, - CWE: "CWE-200", - AffectedPackages: nil, - ResourceUrl: "https://access.redhat.com/hydra/rest/securitydata/cve/CVE-2021-3602.json", - Cvss3ScoringVector: "CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:C/C:H/I:N/A:N", - Cvss3Score: "5.6", - }, - } - securityMock.ActiveCVE = &rhsecurity.CVEDetailed{ - Bugzilla: rhsecurity.CVEDetailedBugzilla{Id: "190", Url: "test-bugzilla-url"}, - Cvss3: rhsecurity.CVEDetailedCvss3{}, - Cwe: "CWE-200", - Details: []string{}, - Acknowledgement: "", - AffectedRelease: nil, - Name: "", - Csaw: false, - PackageState: &[]rhsecurity.CVEDetailedPackageState{ - { - ProductName: "Red Hat Enterprise Linux 8", - FixState: "Affected", - PackageName: "container-tools/2.0", - Cpe: "cpe:/o:redhat:enterprise_linux:8", - }, - }, - } - - env := getUpdateCVEStateEnv() - env.ExecuteWorkflow(controller.PollRedHatCVEsWorkflow) - require.Nil(t, env.GetWorkflowError()) - - env = getUpdateCVEStateEnv() - env.ExecuteWorkflow(controller.UpdateCVEStateWorkflow) - require.Nil(t, env.GetWorkflowError()) - - require.Len(t, mockDb.AffectedProducts, 1) - require.Equal(t, int(apollopb.AffectedProduct_STATE_AFFECTED_UPSTREAM), mockDb.AffectedProducts[0].State) -} - -func TestInstance_UpdateCVEState_WillNotFixUpstream(t *testing.T) { - resetDb() - - securityMock.Cves[1] = []*rhsecurity.CVE{ - { - CVE: "CVE-2021-3602", - Severity: "moderate", - PublicDate: "2021-07-15T14:00:00Z", - Advisories: []string{}, - Bugzilla: "1969264", - BugzillaDescription: "CVE-2021-3602 buildah: Host environment variables leaked in build container when using chroot isolation", - CvssScore: nil, - CvssScoringVector: nil, - CWE: "CWE-200", - AffectedPackages: nil, - ResourceUrl: "https://access.redhat.com/hydra/rest/securitydata/cve/CVE-2021-3602.json", - Cvss3ScoringVector: "CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:C/C:H/I:N/A:N", - Cvss3Score: "5.6", - }, - } - securityMock.ActiveCVE = &rhsecurity.CVEDetailed{ - Bugzilla: rhsecurity.CVEDetailedBugzilla{Id: "190", Url: "test-bugzilla-url"}, - Cvss3: rhsecurity.CVEDetailedCvss3{}, - Cwe: "CWE-200", - Details: []string{}, - Acknowledgement: "", - AffectedRelease: nil, - Name: "", - Csaw: false, - PackageState: &[]rhsecurity.CVEDetailedPackageState{ - { - ProductName: "Red Hat Enterprise Linux 8", - FixState: "Will not fix", - PackageName: "container-tools/2.0", - Cpe: "cpe:/o:redhat:enterprise_linux:8", - }, - }, - } - - env := getUpdateCVEStateEnv() - env.ExecuteWorkflow(controller.PollRedHatCVEsWorkflow) - require.Nil(t, env.GetWorkflowError()) - - env = getUpdateCVEStateEnv() - env.ExecuteWorkflow(controller.UpdateCVEStateWorkflow) - require.Nil(t, env.GetWorkflowError()) - - require.Len(t, mockDb.AffectedProducts, 1) - require.Equal(t, int(apollopb.AffectedProduct_STATE_WILL_NOT_FIX_UPSTREAM), mockDb.AffectedProducts[0].State) -} - -func TestInstance_UpdateCVEState_NotAffectedUpstream(t *testing.T) { - resetDb() - - securityMock.Cves[1] = []*rhsecurity.CVE{ - { - CVE: "CVE-2021-3602", - Severity: "moderate", - PublicDate: "2021-07-15T14:00:00Z", - Advisories: []string{}, - Bugzilla: "1969264", - BugzillaDescription: "CVE-2021-3602 buildah: Host environment variables leaked in build container when using chroot isolation", - CvssScore: nil, - CvssScoringVector: nil, - CWE: "CWE-200", - AffectedPackages: nil, - ResourceUrl: "https://access.redhat.com/hydra/rest/securitydata/cve/CVE-2021-3602.json", - Cvss3ScoringVector: "CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:C/C:H/I:N/A:N", - Cvss3Score: "5.6", - }, - } - securityMock.ActiveCVE = &rhsecurity.CVEDetailed{ - Bugzilla: rhsecurity.CVEDetailedBugzilla{Id: "190", Url: "test-bugzilla-url"}, - Cvss3: rhsecurity.CVEDetailedCvss3{}, - Cwe: "CWE-200", - Details: []string{}, - Acknowledgement: "", - AffectedRelease: nil, - Name: "", - Csaw: false, - PackageState: &[]rhsecurity.CVEDetailedPackageState{ - { - ProductName: "Red Hat Enterprise Linux 8", - FixState: "Not affected", - PackageName: "container-tools/2.0", - Cpe: "cpe:/o:redhat:enterprise_linux:8", - }, - }, - } - - env := getUpdateCVEStateEnv() - env.ExecuteWorkflow(controller.PollRedHatCVEsWorkflow) - require.Nil(t, env.GetWorkflowError()) - - env = getUpdateCVEStateEnv() - env.ExecuteWorkflow(controller.UpdateCVEStateWorkflow) - require.Nil(t, env.GetWorkflowError()) - - require.Len(t, mockDb.AffectedProducts, 0) -} - -func TestInstance_UpdateCVEState_OutOfSupportScope(t *testing.T) { - resetDb() - - securityMock.Cves[1] = []*rhsecurity.CVE{ - { - CVE: "CVE-2021-3602", - Severity: "moderate", - PublicDate: "2021-07-15T14:00:00Z", - Advisories: []string{}, - Bugzilla: "1969264", - BugzillaDescription: "CVE-2021-3602 buildah: Host environment variables leaked in build container when using chroot isolation", - CvssScore: nil, - CvssScoringVector: nil, - CWE: "CWE-200", - AffectedPackages: nil, - ResourceUrl: "https://access.redhat.com/hydra/rest/securitydata/cve/CVE-2021-3602.json", - Cvss3ScoringVector: "CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:C/C:H/I:N/A:N", - Cvss3Score: "5.6", - }, - } - securityMock.ActiveCVE = &rhsecurity.CVEDetailed{ - Bugzilla: rhsecurity.CVEDetailedBugzilla{Id: "190", Url: "test-bugzilla-url"}, - Cvss3: rhsecurity.CVEDetailedCvss3{}, - Cwe: "CWE-200", - Details: []string{}, - Acknowledgement: "", - AffectedRelease: nil, - Name: "", - Csaw: false, - PackageState: &[]rhsecurity.CVEDetailedPackageState{ - { - ProductName: "Red Hat Enterprise Linux 8", - FixState: "Out of support scope", - PackageName: "container-tools/2.0", - Cpe: "cpe:/o:redhat:enterprise_linux:8", - }, - }, - } - - env := getUpdateCVEStateEnv() - env.ExecuteWorkflow(controller.PollRedHatCVEsWorkflow) - require.Nil(t, env.GetWorkflowError()) - - env = getUpdateCVEStateEnv() - env.ExecuteWorkflow(controller.UpdateCVEStateWorkflow) - require.Nil(t, env.GetWorkflowError()) - - require.Len(t, mockDb.AffectedProducts, 1) - require.Equal(t, int(apollopb.AffectedProduct_STATE_OUT_OF_SUPPORT_SCOPE), mockDb.AffectedProducts[0].State) -} diff --git a/apollo/workflow/workflow.go b/apollo/workflow/workflow.go deleted file mode 100644 index 853e4c2..0000000 --- a/apollo/workflow/workflow.go +++ /dev/null @@ -1,452 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package workflow - -import ( - "database/sql" - "fmt" - "github.com/gobwas/glob" - "github.com/sirupsen/logrus" - "github.com/spf13/viper" - "go.temporal.io/sdk/client" - apollodb "peridot.resf.org/apollo/db" - apollopb "peridot.resf.org/apollo/pb" - "peridot.resf.org/apollo/rherrata" - "peridot.resf.org/apollo/rhsecurity" - "peridot.resf.org/apollo/rpmutils" - "peridot.resf.org/koji" - "peridot.resf.org/utils" - "strconv" - "strings" -) - -var forceKoji koji.API - -type Controller struct { - log *logrus.Logger - temporal client.Client - db apollodb.Access - mainQueue string - - errata rherrata.APIService - security rhsecurity.DefaultApi - - vendor string -} - -type Koji struct { - Endpoint string - Compose string - ModuleCompose string -} - -type NewControllerInput struct { - Temporal client.Client - Database apollodb.Access - MainQueue string -} - -type Option func(c *Controller) - -func WithSecurityAPI(api rhsecurity.DefaultApi) Option { - return func(c *Controller) { - c.security = api - } -} - -func WithErrataAPI(api rherrata.APIService) Option { - return func(c *Controller) { - c.errata = api - } -} - -// NewController returns a new workflow controller. It is the entry point for the Temporal worker. -// Usually each project share a common controller with different workflows and activities enabled -// in the `cmd` package. -func NewController(input *NewControllerInput, opts ...Option) (*Controller, error) { - c := &Controller{ - log: logrus.New(), - temporal: input.Temporal, - db: input.Database, - mainQueue: input.MainQueue, - vendor: viper.GetString("vendor"), - } - - for _, opt := range opts { - opt(c) - } - - return c, nil -} - -// productName simply appends major version to `Red Hat Enterprise Linux` -func productName(majorVersion int32) string { - return fmt.Sprintf("Red Hat Enterprise Linux %d", majorVersion) -} - -// affectedProductNameForArchAndVersion creates appropriate upstream product names for arch and version -// This is then used to parse affected packages -func affectedProductNameForArchAndVersion(arch string, majorVersion int32) string { - var archString string - switch arch { - case "x86_64": - archString = "x86_64" - break - case "aarch64": - archString = "ARM 64" - break - case "ppc64le": - archString = "Power, little endian" - break - case "s390x": - archString = "IBM z Systems" - break - default: - archString = "UnknownBreakOnPurpose" - break - } - return fmt.Sprintf("Red Hat Enterprise Linux for %s 8", archString) -} - -// productState returns appropriate proto type for string states -func productState(state string) apollopb.AffectedProduct_State { - switch state { - case "Under investigation": - return apollopb.AffectedProduct_STATE_UNDER_INVESTIGATION_UPSTREAM - case "Not affected": - return apollopb.AffectedProduct_STATE_UNKNOWN - case "Will not fix": - return apollopb.AffectedProduct_STATE_WILL_NOT_FIX_UPSTREAM - case "Out of support scope": - return apollopb.AffectedProduct_STATE_OUT_OF_SUPPORT_SCOPE - case "Affected": - return apollopb.AffectedProduct_STATE_AFFECTED_UPSTREAM - default: - return apollopb.AffectedProduct_STATE_UNDER_INVESTIGATION_UPSTREAM - } -} - -// checkProduct is used to check and validate CVE package states and releases -func (c *Controller) checkProduct(tx apollodb.Access, cve *apollodb.CVE, shortCode *apollodb.ShortCode, product *apollodb.Product, productState apollopb.AffectedProduct_State, packageName string, advisory *string) bool { - // Re-create a valid product name using the short code prefix and major version. - // Example: Red Hat Enterprise Linux 8 translates to Rocky Linux 8 for the short code `RL`. - // Check `//apollo:seed.sql` for more info - mirrorProductName := fmt.Sprintf("%s %d", product.RedHatProductPrefix.String, product.RedHatMajorVersion.Int32) - - // Get the affected product if exists - affectedProduct, err := tx.GetAffectedProductByCVEAndPackage(cve.ID, packageName) - if err != nil { - // The affected product does not exist, so we can mark this product as affected if this product exists - if err == sql.ErrNoRows { - // Check if the current package name matches an NVR and if we have a non-NVR variant - skipCreate := false - epochlessPackage := rpmutils.Epoch().ReplaceAllString(packageName, "") - if rpmutils.NVR().MatchString(epochlessPackage) { - nvr := rpmutils.NVR().FindStringSubmatch(epochlessPackage) - affectedProduct, err = tx.GetAffectedProductByCVEAndPackage(cve.ID, nvr[1]) - if err == nil { - skipCreate = true - } - } - - if !skipCreate { - // Get the mirrored product name product if exists (this should exist if supported) - // Example: Rocky Linux only supports 8 so we will only have `Rocky Linux 8` in our supported products - // In the future, when we support 8 and 9 at the same time, we only need to add `Rocky Linux 9` to start - // mirroring errata for el9 packages - product, err := tx.GetProductByNameAndShortCode(mirrorProductName, shortCode.Code) - if err != nil { - // Product isn't supported so skip - if err == sql.ErrNoRows { - logrus.Infof("Product %s not supported", mirrorProductName) - return true - } else { - logrus.Errorf("could not get product: %v", err) - return true - } - } - - // If product state isn't set to unknown (usually when product isn't affected) - // create a new affected product entry for the CVE - if productState != apollopb.AffectedProduct_STATE_UNKNOWN { - affectedProduct, err = tx.CreateAffectedProduct(product.ID, cve.ID, int(productState), product.CurrentFullVersion, packageName, advisory) - if err != nil { - logrus.Errorf("could not create affected product: %v", err) - return true - } - logrus.Infof("Added product %s (%s) to %s with state %s", mirrorProductName, packageName, cve.ID, productState.String()) - } - } - } else { - logrus.Errorf("could not get affected product: %v", err) - return true - } - } - - // We don't use else because this may change if a non-NVR variant is found - if err == nil { - // If the state isn't set to unknown (it is then usually queued for deletion) - if productState != apollopb.AffectedProduct_STATE_UNKNOWN { - // If it's already in that state, skip - if int(productState) == affectedProduct.State { - return true - } - - // If the affected product is set to FixedDownstream and we're trying to set it to FixedUpstream, skip - if affectedProduct.State == int(apollopb.AffectedProduct_STATE_FIXED_DOWNSTREAM) && productState == apollopb.AffectedProduct_STATE_FIXED_UPSTREAM { - return true - } - - err := tx.UpdateAffectedProductStateAndPackageAndAdvisory(affectedProduct.ID, int(productState), packageName, advisory) - if err != nil { - logrus.Errorf("could not update affected product state: %v", err) - return true - } - logrus.Infof("Updated product %s (%s) on %s with state %s", mirrorProductName, packageName, cve.ID, productState.String()) - } else { - // Delete affected product if state is set to Unknown - // That means that the product is set as NotAffected - err = tx.DeleteAffectedProduct(affectedProduct.ID) - if err != nil { - logrus.Errorf("could not delete unaffected product: %v", err) - return true - } - logrus.Infof("Product %s (%s) not affected by %s", mirrorProductName, packageName, cve.ID) - } - } - - return false -} - -func (c *Controller) isNvrIdentical(build *koji.Build, nvr []string) bool { - // Join all release bits and remove the dist tag (because sometimes downstream forks do not match the upstream dist tag) - // Example: Rocky Linux 8.3 initial build did not tag updated RHEL packages as el8_3, but as el8 - joinedRelease := rpmutils.Dist().ReplaceAllString(strings.TrimSuffix(strings.Join(nvr[2:], "."), "."), "") - // Remove all module release bits (to make it possible to actually match NVR) - joinedRelease = rpmutils.ModuleDist().ReplaceAllString(joinedRelease, "") - // Same operations for the build release - buildRelease := rpmutils.Dist().ReplaceAllString(build.Release, "") - buildRelease = rpmutils.ModuleDist().ReplaceAllString(buildRelease, "") - - // Check if package name, version matches and that the release prefix matches - // The reason we're only checking for prefix in release is that downstream - // builds may append `.1` or something else - // Example: Rocky Linux appends `.rocky` to modified packages - if build.PackageName == nvr[0] && build.Version == nvr[1] && strings.HasPrefix(buildRelease, joinedRelease) { - return true - } - - return false -} - -func (c *Controller) checkForIgnoredPackage(ignoredPackages []string, packageName string) (bool, error) { - for _, ignoredPackage := range ignoredPackages { - g, err := glob.Compile(ignoredPackage) - if err != nil { - return false, err - } - - if g.Match(packageName) { - return true, nil - } - } - - return false, nil -} - -func (c *Controller) checkForRebootSuggestedPackage(pkgs []string, packageName string) (bool, error) { - for _, p := range pkgs { - g, err := glob.Compile(p) - if err != nil { - return false, err - } - - if g.Match(packageName) { - return true, nil - } - } - - return false, nil -} - -func (c *Controller) checkKojiForBuild(tx apollodb.Access, ignoredPackages []string, nvrOnly string, affectedProduct *apollodb.AffectedProduct, cve *apollodb.CVE) apollopb.BuildStatus { - product, err := tx.GetProductByID(affectedProduct.ProductID) - if err != nil { - c.log.Errorf("could not get product: %v", err) - return apollopb.BuildStatus_BUILD_STATUS_SKIP - } - if product.BuildSystem != "koji" { - return apollopb.BuildStatus_BUILD_STATUS_SKIP - } - - var k koji.API - if forceKoji != nil { - k = forceKoji - } else { - k, err = koji.New(product.BuildSystemEndpoint) - if err != nil { - c.log.Errorf("could not create koji client: %v", err) - return apollopb.BuildStatus_BUILD_STATUS_SKIP - } - } - - // Check if the submitted NVR is valid - nvr := rpmutils.NVR().FindStringSubmatch(nvrOnly) - if len(nvr) < 3 { - logrus.Errorf("Invalid NVR %s", nvrOnly) - return apollopb.BuildStatus_BUILD_STATUS_SKIP - } - nvr = nvr[1:] - - match, err := c.checkForIgnoredPackage(ignoredPackages, nvr[0]) - if err != nil { - logrus.Errorf("Invalid glob: %v", err) - return apollopb.BuildStatus_BUILD_STATUS_SKIP - } - if match { - return apollopb.BuildStatus_BUILD_STATUS_WILL_NOT_FIX - } - - var tagged []*koji.Build - - // If the package is part of a module, we have to check for valid builds - // rather than check in the compose tag - if strings.Contains(nvrOnly, ".module") { - // We need to find the package id - packageRes, err := k.GetPackage(&koji.GetPackageRequest{ - PackageName: nvr[0], - }) - if err != nil { - logrus.Errorf("Could not get package information from Koji: %v", err) - return apollopb.BuildStatus_BUILD_STATUS_SKIP - } - - // Use package id to get builds - buildsRes, err := k.ListBuilds(&koji.ListBuildsRequest{ - PackageID: packageRes.ID, - }) - if err != nil { - logrus.Errorf("Could not get builds from Koji: %v", err) - return apollopb.BuildStatus_BUILD_STATUS_SKIP - } - - tagged = buildsRes.Builds - } else { - // Non-module packages can be queried using the list tagged operation. - // We only check the compose tag - taggedRes, err := k.ListTagged(&koji.ListTaggedRequest{ - Tag: product.KojiCompose.String, - Package: nvr[0], - }) - if err != nil { - logrus.Errorf("Could not get tagged builds for package %s: %v", nvr[0], err) - return apollopb.BuildStatus_BUILD_STATUS_SKIP - } - - tagged = taggedRes.Builds - } - - // No valid builds found usually means that we don't ship that package - if len(tagged) <= 0 { - logrus.Errorf("No valid builds found for package %s", nvr[0]) - return apollopb.BuildStatus_BUILD_STATUS_NOT_FIXED - } - - // Use a top-level fixed state to track if the NVR exists (at least once for modules) - fixed := false - for _, build := range tagged { - latestBuild := build - // Skip module contents (this is content inserted by module-build-service) - if latestBuild.Extra != nil && latestBuild.Extra.Typeinfo != nil { - continue - } - - // Re-construct a valid NVR - kojiNvr := fmt.Sprintf("%s-%s-%s", latestBuild.PackageName, latestBuild.Version, latestBuild.Release) - - // If the NVR is identical, that means that the fix has been built - if c.isNvrIdentical(latestBuild, nvr) { - logrus.Infof("%s has been fixed downstream with build %d (%s)", cve.ID, latestBuild.BuildId, kojiNvr) - err := tx.UpdateAffectedProductStateAndPackageAndAdvisory(affectedProduct.ID, int(apollopb.AffectedProduct_STATE_FIXED_DOWNSTREAM), affectedProduct.Package, &affectedProduct.Advisory.String) - if err != nil { - logrus.Errorf("Could not update affected product %d: %v", affectedProduct.ID, err) - return apollopb.BuildStatus_BUILD_STATUS_SKIP - } - - // Get all RPMs for build - rpms, err := k.ListRPMs(&koji.ListRPMsRequest{ - BuildID: latestBuild.BuildId, - }) - if err != nil { - logrus.Errorf("Could not get RPMs from Koji: %v", err) - return apollopb.BuildStatus_BUILD_STATUS_SKIP - } - - var srcRpm string - for _, rpm := range rpms.RPMs { - if rpm.Arch == "src" { - epochInt := 0 - if rpm.Epoch != nil { - epochInt = *rpm.Epoch - } - - srcRpm = fmt.Sprintf("%s-%d:%s-%s.%s.rpm", rpm.Name, epochInt, rpm.Version, rpm.Release, rpm.Arch) - break - } - } - - // Add all RPMs as a build reference to the CVE - // This is the "Affected packages" section of an advisory - for _, rpm := range rpms.RPMs { - // Construct a valid rpm name (this is what the repos will contain) - rpmStr := fmt.Sprintf("%s-%d:%s-%s.%s.rpm", rpm.Name, utils.Default[int](rpm.Epoch), rpm.Version, rpm.Release, rpm.Arch) - _, err = tx.CreateBuildReference(affectedProduct.ID, rpmStr, srcRpm, cve.ID, "", utils.Pointer[string](strconv.Itoa(latestBuild.BuildId)), nil) - if err != nil { - logrus.Errorf("Could not create build reference: %v", err) - return apollopb.BuildStatus_BUILD_STATUS_SKIP - } - } - - // We've seen at least one fix - fixed = true - // Since we've seen a fix, we don't have to keep looking - break - } - } - - // No fix has been detected, will mark as FixedUpstream - if !fixed { - logrus.Errorf("%s has not been fixed for NVR %s", cve.ID, nvrOnly) - return apollopb.BuildStatus_BUILD_STATUS_NOT_FIXED - } - - return apollopb.BuildStatus_BUILD_STATUS_FIXED -} diff --git a/apollo/workflow/workflow_test.go b/apollo/workflow/workflow_test.go deleted file mode 100644 index 76032ba..0000000 --- a/apollo/workflow/workflow_test.go +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package workflow - -import ( - "database/sql" - "encoding/json" - "go.temporal.io/sdk/testsuite" - "os" - apollodb "peridot.resf.org/apollo/db" - apollomock "peridot.resf.org/apollo/db/mock" - apollopb "peridot.resf.org/apollo/pb" - "peridot.resf.org/apollo/rherrata" - "peridot.resf.org/apollo/rhsecuritymock" - "peridot.resf.org/koji" - "testing" - "time" -) - -var ( - mockDb *apollomock.Access - securityMock *rhsecuritymock.Client - errataMock *rherrata.MockInstance - kojiMock *koji.Mock - testWfSuite *testsuite.WorkflowTestSuite - controller *Controller -) - -func resetDb() { - *mockDb = *apollomock.New() - now := time.Now() - - mirrorFromDate, _ := time.Parse("2006-01-02", "2021-06-01") - mockDb.ShortCodes = append(mockDb.ShortCodes, &apollodb.ShortCode{ - Code: "RL", - Mode: int8(apollopb.ShortCode_MODE_MIRROR), - CreatedAt: &now, - ArchivedAt: sql.NullTime{}, - }) - mockDb.Products = append(mockDb.Products, &apollodb.Product{ - ID: 1, - Name: "Rocky Linux 8", - CurrentFullVersion: "8.4", - RedHatMajorVersion: sql.NullInt32{Valid: true, Int32: 8}, - ShortCode: "RL", - Archs: []string{"x86_64", "aarch64"}, - MirrorFromDate: sql.NullTime{Valid: true, Time: mirrorFromDate}, - RedHatProductPrefix: sql.NullString{Valid: true, String: "Rocky Linux"}, - BuildSystem: "koji", // we're testing koji only for now - BuildSystemEndpoint: "local", - KojiCompose: sql.NullString{Valid: true, String: "Rocky-8.4"}, - KojiModuleCompose: sql.NullString{Valid: true, String: "Rocky-8.4-module"}, - }) -} - -func readTestDataJson(file string, target interface{}) error { - data, err := os.ReadFile(file) - if err != nil { - return err - } - - return json.Unmarshal(data, target) -} - -func TestMain(m *testing.M) { - mockDb = apollomock.New() - securityMock = rhsecuritymock.New() - errataMock = rherrata.NewMock() - kojiMock = koji.NewMock() - forceKoji = kojiMock - - testWfSuite = &testsuite.WorkflowTestSuite{} - - input := &NewControllerInput{ - Database: mockDb, - } - instance, err := NewController( - input, - WithSecurityAPI(securityMock), - WithErrataAPI(errataMock.API), - ) - if err != nil { - panic(err.(any)) - } - - controller = instance - - resetDb() - - os.Exit(m.Run()) -} From 53d53f03ac0732cd4035bcca94b3753d1a907ab6 Mon Sep 17 00:00:00 2001 From: Mustafa Gezen Date: Fri, 17 Feb 2023 19:38:04 +0100 Subject: [PATCH 2/3] Delete publisher too, we're using apollo_tree --- apollo/rherrata/BUILD.bazel | 30 - apollo/rherrata/api.go | 72 -- apollo/rherrata/compact_errata.go | 98 --- apollo/rherrata/errata.go | 236 ------ apollo/rherrata/errata_test.go | 141 ---- apollo/rherrata/mock.go | 88 --- apollo/rherrata/testdata/RHBA-2021-2759.html | 697 ----------------- apollo/rherrata/testdata/RHSA-2021-2743.html | 710 ------------------ apollo/rhsecurity/BUILD.bazel | 22 - apollo/rhsecurity/README.md | 119 --- .../rhsecurity/Red-Hat-Security-Data-API.yaml | 427 ----------- apollo/rhsecurity/api_default.go | 380 ---------- apollo/rhsecurity/client.go | 536 ------------- apollo/rhsecurity/configuration.go | 230 ------ apollo/rhsecurity/docs/CVE.md | 313 -------- apollo/rhsecurity/docs/CVEDetailed.md | 271 ------- .../docs/CVEDetailedAffectedRelease.md | 140 ---- apollo/rhsecurity/docs/CVEDetailedBugzilla.md | 93 --- apollo/rhsecurity/docs/CVEDetailedCvss3.md | 93 --- .../docs/CVEDetailedPackageState.md | 114 --- apollo/rhsecurity/docs/DefaultApi.md | 173 ----- apollo/rhsecurity/gen.go | 32 - apollo/rhsecurity/model_cve.go | 469 ------------ apollo/rhsecurity/model_cve_detailed.go | 411 ---------- .../model_cve_detailed_affected_release.go | 230 ------ .../rhsecurity/model_cve_detailed_bugzilla.go | 165 ---- apollo/rhsecurity/model_cve_detailed_cvss3.go | 165 ---- .../model_cve_detailed_package_state.go | 194 ----- apollo/rhsecurity/response.go | 48 -- apollo/rhsecurity/utils.go | 329 -------- apollo/rhsecuritymock/BUILD.bazel | 12 - apollo/rhsecuritymock/client.go | 102 --- publisher/BUILD | 0 publisher/README.md | 16 - publisher/cmd/BUILD | 0 .../cmd/publisher-legacy-errata/BUILD.bazel | 30 - publisher/cmd/publisher-legacy-errata/main.go | 95 --- publisher/updateinfo/BUILD.bazel | 11 - publisher/updateinfo/legacy/BUILD.bazel | 17 - publisher/updateinfo/legacy/legacy.go | 601 --------------- publisher/updateinfo/repomd.go | 72 -- publisher/updateinfo/updateinfo.go | 103 --- 42 files changed, 8085 deletions(-) delete mode 100644 apollo/rherrata/BUILD.bazel delete mode 100644 apollo/rherrata/api.go delete mode 100644 apollo/rherrata/compact_errata.go delete mode 100644 apollo/rherrata/errata.go delete mode 100644 apollo/rherrata/errata_test.go delete mode 100644 apollo/rherrata/mock.go delete mode 100644 apollo/rherrata/testdata/RHBA-2021-2759.html delete mode 100644 apollo/rherrata/testdata/RHSA-2021-2743.html delete mode 100644 apollo/rhsecurity/BUILD.bazel delete mode 100644 apollo/rhsecurity/README.md delete mode 100644 apollo/rhsecurity/Red-Hat-Security-Data-API.yaml delete mode 100644 apollo/rhsecurity/api_default.go delete mode 100644 apollo/rhsecurity/client.go delete mode 100644 apollo/rhsecurity/configuration.go delete mode 100644 apollo/rhsecurity/docs/CVE.md delete mode 100644 apollo/rhsecurity/docs/CVEDetailed.md delete mode 100644 apollo/rhsecurity/docs/CVEDetailedAffectedRelease.md delete mode 100644 apollo/rhsecurity/docs/CVEDetailedBugzilla.md delete mode 100644 apollo/rhsecurity/docs/CVEDetailedCvss3.md delete mode 100644 apollo/rhsecurity/docs/CVEDetailedPackageState.md delete mode 100644 apollo/rhsecurity/docs/DefaultApi.md delete mode 100644 apollo/rhsecurity/gen.go delete mode 100644 apollo/rhsecurity/model_cve.go delete mode 100644 apollo/rhsecurity/model_cve_detailed.go delete mode 100644 apollo/rhsecurity/model_cve_detailed_affected_release.go delete mode 100644 apollo/rhsecurity/model_cve_detailed_bugzilla.go delete mode 100644 apollo/rhsecurity/model_cve_detailed_cvss3.go delete mode 100644 apollo/rhsecurity/model_cve_detailed_package_state.go delete mode 100644 apollo/rhsecurity/response.go delete mode 100644 apollo/rhsecurity/utils.go delete mode 100644 apollo/rhsecuritymock/BUILD.bazel delete mode 100644 apollo/rhsecuritymock/client.go delete mode 100644 publisher/BUILD delete mode 100644 publisher/README.md delete mode 100644 publisher/cmd/BUILD delete mode 100644 publisher/cmd/publisher-legacy-errata/BUILD.bazel delete mode 100644 publisher/cmd/publisher-legacy-errata/main.go delete mode 100644 publisher/updateinfo/BUILD.bazel delete mode 100644 publisher/updateinfo/legacy/BUILD.bazel delete mode 100644 publisher/updateinfo/legacy/legacy.go delete mode 100644 publisher/updateinfo/repomd.go delete mode 100644 publisher/updateinfo/updateinfo.go diff --git a/apollo/rherrata/BUILD.bazel b/apollo/rherrata/BUILD.bazel deleted file mode 100644 index af10f13..0000000 --- a/apollo/rherrata/BUILD.bazel +++ /dev/null @@ -1,30 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -go_library( - name = "rherrata", - srcs = [ - "api.go", - "compact_errata.go", - "errata.go", - "mock.go", - ], - importpath = "peridot.resf.org/apollo/rherrata", - visibility = ["//visibility:public"], - deps = [ - "//apollo/proto/v1:pb", - "//vendor/github.com/PuerkitoBio/goquery", - "//vendor/github.com/go-chi/chi", - "//vendor/github.com/gocolly/colly/v2:colly", - ], -) - -go_test( - name = "rherrata_test", - srcs = ["errata_test.go"], - data = glob(["testdata/**"]), - embed = [":rherrata"], - deps = [ - "//apollo/proto/v1:pb", - "//vendor/github.com/stretchr/testify/require", - ], -) diff --git a/apollo/rherrata/api.go b/apollo/rherrata/api.go deleted file mode 100644 index 4f638a1..0000000 --- a/apollo/rherrata/api.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package rherrata - -import ( - "io" - "net/http" - "time" -) - -type APIService interface { - GetErrata(advisory string) (*Errata, error) - GetAdvisories(currentVersion string, after *time.Time) ([]*CompactErrata, error) -} - -// API is the APIService implementation. Should not be used directly -type API struct { - client *http.Client - userAgent string - baseURLErrata string - baseURLAPI string -} - -func NewClient() *API { - return &API{ - client: &http.Client{ - Timeout: 30 * time.Second, - }, - userAgent: "apollo/rherrata/0.2", - baseURLErrata: "https://access.redhat.com/errata", - baseURLAPI: "https://access.redhat.com/hydra/rest/search/kcs", - } -} - -func (a *API) newRequest(method string, url string, body io.Reader) (*http.Request, error) { - req, err := http.NewRequest(method, url, body) - if err != nil { - return nil, err - } - - req.Header.Set("User-Agent", a.userAgent) - - return req, nil -} diff --git a/apollo/rherrata/compact_errata.go b/apollo/rherrata/compact_errata.go deleted file mode 100644 index 4e7a959..0000000 --- a/apollo/rherrata/compact_errata.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package rherrata - -import ( - "encoding/json" - "fmt" - "net/url" - "strings" - "time" -) - -var internalAfterDates = map[string]string{ - "8.4": "2021-04-29T00:00:00Z", - "9.0": "2022-05-17T00:00:00Z", -} - -type CompactErrata struct { - Name string `json:"id"` - Description string `json:"portal_description"` - Synopsis string `json:"portal_synopsis"` - Severity string `json:"portal_severity"` - Type string `json:"portal_advisory_type"` - AffectedPackages []string `json:"portal_package"` - CVEs []string `json:"portal_CVE"` - Fixes []string `json:"portal_BZ"` - PublicationDate string `json:"portal_publication_date"` -} - -type internalAdvisoriesInnerResponse struct { - Docs []*CompactErrata `json:"docs"` -} - -type internalAdvisoriesResponse struct { - Response *internalAdvisoriesInnerResponse `json:"response"` -} - -func (a *API) GetAdvisories(currentVersion string, after *time.Time) ([]*CompactErrata, error) { - req, err := a.newRequest("GET", a.baseURLAPI, nil) - if err != nil { - return nil, err - } - - fq1 := "documentKind:(%22Errata%22)" - usableVersion := strings.Replace(currentVersion, ".", "%5C.", -1) - fq2 := fmt.Sprintf("portal_product_filter:Red%%5C+Hat%%5C+Enterprise%%5C+Linux%%7C*%%7C%s%%7C*", usableVersion) - var fq3 string - if after != nil { - fq3 = "&fq=" + url.QueryEscape(fmt.Sprintf("portal_publication_date:[%s TO NOW]", after.Format(time.RFC3339))) - } else if afterDate := internalAfterDates[currentVersion]; afterDate != "" { - fq3 = "&fq=" + url.QueryEscape(fmt.Sprintf("portal_publication_date:[%s TO NOW]", afterDate)) - } - req.URL.RawQuery = fmt.Sprintf("fq=%s&fq=%s%s&q=*:*&rows=10000&sort=portal_publication_date+desc&start=0", fq1, fq2, fq3) - - req.Header.Set("Accept", "application/json") - - res, err := a.client.Do(req) - if err != nil { - return nil, err - } - defer res.Body.Close() - - var marshalBody internalAdvisoriesResponse - err = json.NewDecoder(res.Body).Decode(&marshalBody) - if err != nil { - return nil, err - } - - return marshalBody.Response.Docs, nil -} diff --git a/apollo/rherrata/errata.go b/apollo/rherrata/errata.go deleted file mode 100644 index 7269d5d..0000000 --- a/apollo/rherrata/errata.go +++ /dev/null @@ -1,236 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package rherrata - -import ( - "errors" - "fmt" - "github.com/PuerkitoBio/goquery" - "github.com/gocolly/colly/v2" - apollopb "peridot.resf.org/apollo/pb" - "strings" - "time" -) - -type Architecture string - -const ( - ArchX8664 Architecture = "x86_64" - ArchAArch64 Architecture = "aarch64" - ArchPPC64 Architecture = "ppc64le" - ArchS390X Architecture = "s390x" - ArchNoArch Architecture = "noarch" -) - -type Fix struct { - BugzillaID string - Description string -} - -type UpdatedPackages struct { - SRPMs []string - Packages map[Architecture][]string -} - -type Errata struct { - Synopsis string - Type apollopb.Advisory_Type - Severity apollopb.Advisory_Severity - Topic []string - Description []string - Solution []string - AffectedProducts map[string]*UpdatedPackages - Fixes []*Fix - CVEs []string - References []string - IssuedAt time.Time -} - -func (a *API) GetErrata(advisory string) (*Errata, error) { - var err error - var errata Errata - c := colly.NewCollector(colly.UserAgent(a.userAgent)) - - // Do not fix this typo. It is like this on Red Hat's website - c.OnHTML("div#synpopsis", func(element *colly.HTMLElement) { - errata.Synopsis = element.DOM.Find("p").Text() - }) - c.OnHTML("div#topic > p", func(element *colly.HTMLElement) { - errata.Topic = append(errata.Topic, element.Text) - }) - c.OnHTML("div#solution > p", func(element *colly.HTMLElement) { - errata.Solution = append(errata.Solution, element.Text) - }) - c.OnHTML("div#fixes > ul > li", func(element *colly.HTMLElement) { - fixComponents := strings.SplitN(element.Text, "-", 3) - if len(fixComponents) != 3 { - return - } - - for i, comp := range fixComponents { - fixComponents[i] = strings.TrimSpace(comp) - } - - fix := &Fix{ - BugzillaID: fixComponents[1], - Description: fixComponents[2], - } - errata.Fixes = append(errata.Fixes, fix) - }) - c.OnHTML("div#cves > ul > li", func(element *colly.HTMLElement) { - errata.CVEs = append(errata.CVEs, strings.TrimSpace(element.Text)) - }) - c.OnHTML("div#references > ul > li", func(element *colly.HTMLElement) { - errata.References = append(errata.References, strings.TrimSpace(element.Text)) - }) - c.OnHTML("dl.details", func(element *colly.HTMLElement) { - issuedAt, err := time.Parse("2006-01-02", element.DOM.Find("dd").First().Text()) - if err == nil { - errata.IssuedAt = issuedAt - } - }) - c.OnHTML("div#packages", func(element *colly.HTMLElement) { - productIndex := map[int]string{} - products := map[string]*UpdatedPackages{} - element.DOM.Find("h2").Each(func(i int, selection *goquery.Selection) { - productIndex[i] = selection.Text() - products[selection.Text()] = &UpdatedPackages{} - }) - - element.DOM.Find("table.files").Each(func(i int, selection *goquery.Selection) { - productUpdate := products[productIndex[i]] - if productUpdate.Packages == nil { - productUpdate.Packages = map[Architecture][]string{} - } - - selection.Find("td.name").Each(func(_ int, selection *goquery.Selection) { - name := strings.TrimSpace(selection.Text()) - isRpm := strings.HasSuffix(name, ".rpm") - isSrcRpm := strings.HasSuffix(name, ".src.rpm") - if isRpm { - if isSrcRpm { - productUpdate.SRPMs = append(productUpdate.SRPMs, name) - } else { - var arch Architecture - if strings.Contains(name, ".x86_64") || strings.Contains(name, ".i686") { - arch = ArchX8664 - } else if strings.Contains(name, ".aarch64") { - arch = ArchAArch64 - } else if strings.Contains(name, ".ppc64le") { - arch = ArchPPC64 - } else if strings.Contains(name, ".s390x") { - arch = ArchS390X - } else if strings.Contains(name, ".noarch") { - arch = ArchNoArch - } - - if productUpdate.Packages[arch] == nil { - productUpdate.Packages[arch] = []string{} - } - productUpdate.Packages[arch] = append(productUpdate.Packages[arch], name) - } - } - }) - - errata.AffectedProducts = products - }) - }) - c.OnHTML("div#description > p", func(element *colly.HTMLElement) { - htmlText, err := element.DOM.Html() - if err != nil { - return - } - htmlText = strings.TrimSuffix(htmlText, "
") - - if element.Text == "Security Fix(es):" || element.Text == "Bug Fix(es) and Enhancement(s):" || element.Text == "Bug Fix(es):" || element.Text == "Enhancement(s):" { - return - } - errata.Description = append(errata.Description, strings.Split(htmlText, "
")...) - }) - c.OnHTML("div#type-severity", func(element *colly.HTMLElement) { - typeSeverity := strings.Split(element.DOM.Find("p").Text(), ":") - if typeSeverity[0] == "Product Enhancement Advisory" { - errata.Type = apollopb.Advisory_TYPE_ENHANCEMENT - } else if typeSeverity[0] == "Bug Fix Advisory" { - errata.Type = apollopb.Advisory_TYPE_BUGFIX - } else { - if len(typeSeverity) != 2 { - err = errors.New("invalid type/severity") - return - } - - typeSplit := strings.Split(typeSeverity[0], " ") - if len(typeSplit) != 2 { - err = errors.New("invalid type") - return - } - - switch strings.TrimSpace(typeSplit[0]) { - case "Security": - errata.Type = apollopb.Advisory_TYPE_SECURITY - break - case "BugFix": - errata.Type = apollopb.Advisory_TYPE_BUGFIX - break - case "Enhancement": - errata.Type = apollopb.Advisory_TYPE_ENHANCEMENT - break - } - - switch strings.TrimSpace(typeSeverity[1]) { - case "Low": - errata.Severity = apollopb.Advisory_SEVERITY_LOW - break - case "Moderate": - errata.Severity = apollopb.Advisory_SEVERITY_MODERATE - break - case "Important": - errata.Severity = apollopb.Advisory_SEVERITY_IMPORTANT - break - case "Critical": - errata.Severity = apollopb.Advisory_SEVERITY_CRITICAL - break - } - } - }) - - errC := c.Visit(fmt.Sprintf("%s/%s", a.baseURLErrata, advisory)) - if errC != nil { - return nil, errC - } - - c.Wait() - - if err != nil { - return nil, err - } - return &errata, nil -} diff --git a/apollo/rherrata/errata_test.go b/apollo/rherrata/errata_test.go deleted file mode 100644 index 0ad8c88..0000000 --- a/apollo/rherrata/errata_test.go +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package rherrata - -import ( - "github.com/stretchr/testify/require" - "io/ioutil" - apollopb "peridot.resf.org/apollo/pb" - "testing" -) - -func newInstance() *MockInstance { - return NewMock() -} - -func TestRHBA20212759(t *testing.T) { - mock := newInstance() - - htmlFile, err := ioutil.ReadFile("testdata/RHBA-2021-2759.html") - require.Nil(t, err) - - mock.HTMLResponses["RHBA-2021:2759"] = string(htmlFile[:]) - - errata, err := mock.API.GetErrata("RHBA-2021:2759") - require.Nil(t, err) - - require.Equal(t, "firefox bugfix update", errata.Synopsis) - require.Equal(t, apollopb.Advisory_TYPE_BUGFIX, errata.Type) - require.Len(t, errata.Topic, 1) - require.Equal(t, "An update for firefox is now available for Red Hat Enterprise Linux 8.", errata.Topic[0]) - require.Len(t, errata.Description, 3) - require.Equal(t, "Mozilla Firefox is an open-source web browser, designed for standards", errata.Description[0]) - require.Equal(t, "compliance, performance, and portability.", errata.Description[1]) - require.Equal(t, "This update upgrades Firefox to version 78.12.0 ESR.", errata.Description[2]) - require.Len(t, errata.AffectedProducts, 12) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux for x86_64 8"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux for x86_64 - Extended Update Support 8.4"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux Server - AUS 8.4"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux for IBM z Systems 8"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux for IBM z Systems - Extended Update Support 8.4"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux for Power, little endian 8"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux for Power, little endian - Extended Update Support 8.4"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux Server - TUS 8.4"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux for ARM 64 8"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux for ARM 64 - Extended Update Support 8.4"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux Server (for IBM Power LE) - Update Services for SAP Solutions 8.4"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux Server - Update Services for SAP Solutions 8.4"]) - - x86 := errata.AffectedProducts["Red Hat Enterprise Linux for x86_64 8"] - require.Len(t, x86.SRPMs, 1) - require.Equal(t, "firefox-78.12.0-2.el8_4.src.rpm", x86.SRPMs[0]) - require.Len(t, x86.Packages[ArchX8664], 3) - require.Equal(t, "firefox-78.12.0-2.el8_4.x86_64.rpm", x86.Packages[ArchX8664][0]) - require.Equal(t, "firefox-debuginfo-78.12.0-2.el8_4.x86_64.rpm", x86.Packages[ArchX8664][1]) - require.Equal(t, "firefox-debugsource-78.12.0-2.el8_4.x86_64.rpm", x86.Packages[ArchX8664][2]) -} - -func TestRHBA20212743(t *testing.T) { - mock := newInstance() - - htmlFile, err := ioutil.ReadFile("testdata/RHSA-2021-2743.html") - require.Nil(t, err) - - mock.HTMLResponses["RHSA-2021:2743"] = string(htmlFile[:]) - - errata, err := mock.API.GetErrata("RHSA-2021:2743") - require.Nil(t, err) - - require.Equal(t, "Important: firefox security update", errata.Synopsis) - require.Equal(t, apollopb.Advisory_TYPE_SECURITY, errata.Type) - require.Equal(t, apollopb.Advisory_SEVERITY_IMPORTANT, errata.Severity) - require.Len(t, errata.Topic, 2) - require.Equal(t, "An update for firefox is now available for Red Hat Enterprise Linux 8.", errata.Topic[0]) - require.Equal(t, "Red Hat Product Security has rated this update as having a security impact of Important. A Common Vulnerability Scoring System (CVSS) base score, which gives a detailed severity rating, is available for each vulnerability from the CVE link(s) in the References section.", errata.Topic[1]) - require.Len(t, errata.Description, 3) - require.Equal(t, "Mozilla Firefox is an open-source web browser, designed for standards compliance, performance, and portability.", errata.Description[0]) - require.Equal(t, "This update upgrades Firefox to version 78.12.0 ESR.", errata.Description[1]) - require.Equal(t, "For more details about the security issue(s), including the impact, a CVSS score, acknowledgments, and other related information, refer to the CVE page(s) listed in the References section.", errata.Description[2]) - require.Len(t, errata.AffectedProducts, 12) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux for x86_64 8"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux for x86_64 - Extended Update Support 8.4"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux Server - AUS 8.4"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux for IBM z Systems 8"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux for IBM z Systems - Extended Update Support 8.4"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux for Power, little endian 8"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux for Power, little endian - Extended Update Support 8.4"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux Server - TUS 8.4"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux for ARM 64 8"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux for ARM 64 - Extended Update Support 8.4"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux Server (for IBM Power LE) - Update Services for SAP Solutions 8.4"]) - require.NotNil(t, errata.AffectedProducts["Red Hat Enterprise Linux Server - Update Services for SAP Solutions 8.4"]) - require.Len(t, errata.Fixes, 3) - require.Equal(t, "1970109", errata.Fixes[0].BugzillaID) - require.Equal(t, "CVE-2021-30547 chromium-browser: Out of bounds write in ANGLE", errata.Fixes[0].Description) - require.Equal(t, "1982013", errata.Fixes[1].BugzillaID) - require.Equal(t, "CVE-2021-29970 Mozilla: Use-after-free in accessibility features of a document", errata.Fixes[1].Description) - require.Equal(t, "1982014", errata.Fixes[2].BugzillaID) - require.Equal(t, "CVE-2021-29976 Mozilla: Memory safety bugs fixed in Firefox 90 and Firefox ESR 78.12", errata.Fixes[2].Description) - require.Len(t, errata.CVEs, 3) - require.Equal(t, "CVE-2021-29970", errata.CVEs[0]) - require.Equal(t, "CVE-2021-29976", errata.CVEs[1]) - require.Equal(t, "CVE-2021-30547", errata.CVEs[2]) - require.Len(t, errata.References, 1) - require.Equal(t, "https://access.redhat.com/security/updates/classification/#important", errata.References[0]) - - x86 := errata.AffectedProducts["Red Hat Enterprise Linux for x86_64 8"] - require.Len(t, x86.SRPMs, 1) - require.Equal(t, "firefox-78.12.0-1.el8_4.src.rpm", x86.SRPMs[0]) - require.Len(t, x86.Packages[ArchX8664], 3) - require.Equal(t, "firefox-78.12.0-1.el8_4.x86_64.rpm", x86.Packages[ArchX8664][0]) - require.Equal(t, "firefox-debuginfo-78.12.0-1.el8_4.x86_64.rpm", x86.Packages[ArchX8664][1]) - require.Equal(t, "firefox-debugsource-78.12.0-1.el8_4.x86_64.rpm", x86.Packages[ArchX8664][2]) -} diff --git a/apollo/rherrata/mock.go b/apollo/rherrata/mock.go deleted file mode 100644 index 41dbd2d..0000000 --- a/apollo/rherrata/mock.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package rherrata - -import ( - "encoding/json" - "github.com/go-chi/chi" - "net/http" - "net/http/httptest" -) - -type MockInstance struct { - API *API - // Mapped to advisory id/name - HTMLResponses map[string]string - Advisories *internalAdvisoriesResponse - TestServerErrata *httptest.Server - TestServerMock *httptest.Server -} - -func NewMock() *MockInstance { - mockInstance := &MockInstance{ - HTMLResponses: map[string]string{}, - Advisories: &internalAdvisoriesResponse{ - Response: &internalAdvisoriesInnerResponse{ - Docs: []*CompactErrata{}, - }, - }, - } - - muxErrata := chi.NewMux() - muxErrata.Get("/{advisory}", func(w http.ResponseWriter, r *http.Request) { - advisory := chi.URLParam(r, "advisory") - - if response := mockInstance.HTMLResponses[advisory]; response != "" { - w.Header().Set("Content-Type", "text/html") - _, _ = w.Write([]byte(response)) - } else { - w.WriteHeader(http.StatusNotFound) - } - }) - - muxAPI := chi.NewMux() - muxAPI.Get("/*", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - - _ = json.NewEncoder(w).Encode(mockInstance.Advisories) - }) - - api := NewClient() - tsErrata := httptest.NewServer(muxErrata) - tsAPI := httptest.NewServer(muxAPI) - api.baseURLErrata = tsErrata.URL - api.baseURLAPI = tsAPI.URL - - mockInstance.API = api - mockInstance.TestServerErrata = tsErrata - - return mockInstance -} diff --git a/apollo/rherrata/testdata/RHBA-2021-2759.html b/apollo/rherrata/testdata/RHBA-2021-2759.html deleted file mode 100644 index 4b1f110..0000000 --- a/apollo/rherrata/testdata/RHBA-2021-2759.html +++ /dev/null @@ -1,697 +0,0 @@ - - - - -
-
- - - - - - -
- - - - - - - - - diff --git a/apollo/rherrata/testdata/RHSA-2021-2743.html b/apollo/rherrata/testdata/RHSA-2021-2743.html deleted file mode 100644 index 6e06611..0000000 --- a/apollo/rherrata/testdata/RHSA-2021-2743.html +++ /dev/null @@ -1,710 +0,0 @@ - - - - - - - - - - - - -
- - - - - - - - - diff --git a/apollo/rhsecurity/BUILD.bazel b/apollo/rhsecurity/BUILD.bazel deleted file mode 100644 index b2ed8b4..0000000 --- a/apollo/rhsecurity/BUILD.bazel +++ /dev/null @@ -1,22 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "rhsecurity", - srcs = [ - "api_default.go", - "client.go", - "configuration.go", - "gen.go", - "model_cve.go", - "model_cve_detailed.go", - "model_cve_detailed_affected_release.go", - "model_cve_detailed_bugzilla.go", - "model_cve_detailed_cvss3.go", - "model_cve_detailed_package_state.go", - "response.go", - "utils.go", - ], - importpath = "peridot.resf.org/apollo/rhsecurity", - visibility = ["//visibility:public"], - deps = ["//vendor/golang.org/x/oauth2"], -) diff --git a/apollo/rhsecurity/README.md b/apollo/rhsecurity/README.md deleted file mode 100644 index d03b734..0000000 --- a/apollo/rhsecurity/README.md +++ /dev/null @@ -1,119 +0,0 @@ -# Go API client for rhsecurity - -Unofficial OpenAPI definitions for Red Hat Security Data API - -## Overview -This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [OpenAPI-spec](https://www.openapis.org/) from a remote server, you can easily generate an API client. - -- API version: 1.0 -- Package version: 1.0.0 -- Build package: org.openapitools.codegen.languages.GoClientCodegen - -## Installation - -Install the following dependencies: - -```shell -go get github.com/stretchr/testify/assert -go get golang.org/x/oauth2 -go get golang.org/x/net/context -``` - -Put the package under your project folder and add the following in import: - -```golang -import sw "./rhsecurity" -``` - -To use a proxy, set the environment variable `HTTP_PROXY`: - -```golang -os.Setenv("HTTP_PROXY", "http://proxy_name:proxy_port") -``` - -## Configuration of Server URL - -Default configuration comes with `Servers` field that contains server objects as defined in the OpenAPI specification. - -### Select Server Configuration - -For using other server than the one defined on index 0 set context value `sw.ContextServerIndex` of type `int`. - -```golang -ctx := context.WithValue(context.Background(), sw.ContextServerIndex, 1) -``` - -### Templated Server URL - -Templated server URL is formatted using default variables from configuration or from context value `sw.ContextServerVariables` of type `map[string]string`. - -```golang -ctx := context.WithValue(context.Background(), sw.ContextServerVariables, map[string]string{ - "basePath": "v2", -}) -``` - -Note, enum values are always validated and all unused variables are silently ignored. - -### URLs Configuration per Operation - -Each operation can use different server URL defined using `OperationServers` map in the `Configuration`. -An operation is uniquely identifield by `"{classname}Service.{nickname}"` string. -Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps. - -``` -ctx := context.WithValue(context.Background(), sw.ContextOperationServerIndices, map[string]int{ - "{classname}Service.{nickname}": 2, -}) -ctx = context.WithValue(context.Background(), sw.ContextOperationServerVariables, map[string]map[string]string{ - "{classname}Service.{nickname}": { - "port": "8443", - }, -}) -``` - -## Documentation for API Endpoints - -All URIs are relative to *https://access.redhat.com/hydra/rest/securitydata* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -*DefaultApi* | [**GetCve**](docs/DefaultApi.md#getcve) | **Get** /cve/{CVE}.json | Get specific CVE -*DefaultApi* | [**GetCves**](docs/DefaultApi.md#getcves) | **Get** /cve.json | Get CVEs - - -## Documentation For Models - - - [CVE](docs/CVE.md) - - [CVEDetailed](docs/CVEDetailed.md) - - [CVEDetailedAffectedRelease](docs/CVEDetailedAffectedRelease.md) - - [CVEDetailedBugzilla](docs/CVEDetailedBugzilla.md) - - [CVEDetailedCvss3](docs/CVEDetailedCvss3.md) - - [CVEDetailedPackageState](docs/CVEDetailedPackageState.md) - - -## Documentation For Authorization - - Endpoints do not require authorization. - - -## Documentation for Utility Methods - -Due to the fact that model structure members are all pointers, this package contains -a number of utility functions to easily obtain pointers to values of basic types. -Each of these functions takes a value of the given basic type and returns a pointer to it: - -* `PtrBool` -* `PtrInt` -* `PtrInt32` -* `PtrInt64` -* `PtrFloat` -* `PtrFloat32` -* `PtrFloat64` -* `PtrString` -* `PtrTime` - -## Author - -mustafa@ctrliq.com - diff --git a/apollo/rhsecurity/Red-Hat-Security-Data-API.yaml b/apollo/rhsecurity/Red-Hat-Security-Data-API.yaml deleted file mode 100644 index b0231e3..0000000 --- a/apollo/rhsecurity/Red-Hat-Security-Data-API.yaml +++ /dev/null @@ -1,427 +0,0 @@ -openapi: 3.0.0 -x-stoplight: - id: yjn90w5p8y4ly -info: - title: Red Hat Security Data API - version: '1.0' - description: Unofficial OpenAPI definitions for Red Hat Security Data API - contact: - name: Mustafa Gezen - email: mustafa@ctrliq.com -servers: - - url: 'https://access.redhat.com/hydra/rest/securitydata' -paths: - /cve.json: - get: - summary: Get CVEs - tags: [] - operationId: get-cves - parameters: - - schema: - type: string - format: date - in: query - name: before - description: 'CVEs before the query date. [ISO 8601 is the expected format]' - - schema: - type: string - format: date - in: query - name: after - description: 'CVEs after the query date. [ISO 8601 is the expected format]' - - schema: - type: string - in: query - name: ids - description: CVEs for Ids separated by comma - - schema: - type: string - in: query - name: bug - description: CVEs for Bugzilla Ids - - schema: - type: string - in: query - name: advisory - description: CVEs for advisory - - schema: - type: string - in: query - name: severity - description: CVEs for severity - - schema: - type: string - in: query - name: package - description: CVEs which affect the package - - schema: - type: string - in: query - name: product - description: CVEs which affect the product. The parameter supports Perl compatible regular expressions. - - schema: - type: string - in: query - name: cwe - description: CVEs with CWE - - schema: - type: number - in: query - name: cvss_score - description: CVEs with CVSS score greater than or equal to this value - - schema: - type: string - in: query - name: cvss3_score - description: CVEs with CVSSv3 score greater than or equal to this value - - schema: - type: number - in: query - name: page - description: CVEs for page number - - schema: - type: number - in: query - name: per_page - description: Number of CVEs to return per page - - schema: - type: number - in: query - name: created_days_ago - description: Index of CVEs definitions created days ago - description: List all the recent CVEs when no parameter is passed. Returns a convenience object as response with very minimum attributes. - responses: - '200': - description: OK - content: - application/json: - schema: - type: array - items: - $ref: '#/components/schemas/CVE' - parameters: [] - '/cve/{CVE}.json': - parameters: - - schema: - type: string - name: CVE - in: path - required: true - get: - summary: Get specific CVE - tags: [] - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/CVEDetailed' - operationId: get-cve - description: Retrieve full CVE details -components: - schemas: - CVE: - description: CVE model used in listing - type: object - x-examples: - example-1: - CVE: CVE-2020-24489 - severity: important - public_date: '2021-06-08T17:00:00Z' - advisories: - - 'RHSA-2021:2307' - - 'RHSA-2021:2306' - - 'RHSA-2021:2305' - - 'RHSA-2021:2304' - - 'RHSA-2021:2519' - - 'RHSA-2021:2308' - - 'RHSA-2021:2299' - - 'RHSA-2021:2303' - - 'RHSA-2021:2302' - - 'RHSA-2021:2522' - - 'RHSA-2021:2301' - - 'RHSA-2021:2300' - bugzilla: '1962650' - bugzilla_description: 'CVE-2020-24489 hw: vt-d related privilege escalation' - cvss_score: null - cvss_scoring_vector: null - CWE: CWE-459 - affected_packages: - - 'microcode_ctl-4:20191115-4.20210525.1.el8_2' - - 'microcode_ctl-2:2.1-12.37.el7_2' - - 'redhat-virtualization-host-0:4.3.16-20210615.0.el7_9' - - 'microcode_ctl-2:2.1-53.16.el7_7' - - 'microcode_ctl-4:20210216-1.20210525.1.el8_4' - - 'microcode_ctl-2:2.1-16.40.el7_3' - - 'microcode_ctl-2:1.17-33.33.el6_10' - - 'microcode_ctl-4:20190618-1.20210525.1.el8_1' - - 'microcode_ctl-2:2.1-22.39.el7_4' - - 'microcode_ctl-2:2.1-73.9.el7_9' - - 'microcode_ctl-2:2.1-47.21.el7_6' - resource_url: 'https://access.redhat.com/hydra/rest/securitydata/cve/CVE-2020-24489.json' - cvss3_scoring_vector: 'CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H' - cvss3_score: '8.8' - properties: - CVE: - type: string - minLength: 1 - severity: - type: string - minLength: 1 - public_date: - type: string - minLength: 1 - advisories: - type: array - items: - type: string - bugzilla: - type: string - minLength: 1 - bugzilla_description: - type: string - minLength: 1 - cvss_score: - type: number - cvss_scoring_vector: - type: string - CWE: - type: string - minLength: 1 - affected_packages: - type: array - items: - type: string - resource_url: - type: string - minLength: 1 - cvss3_scoring_vector: - type: string - minLength: 1 - cvss3_score: - type: string - minLength: 1 - required: - - CVE - - severity - - public_date - - advisories - - bugzilla - - bugzilla_description - - CWE - - affected_packages - - resource_url - - cvss3_scoring_vector - - cvss3_score - CVEDetailed: - description: CVE model used when retrieving a specific CVE - type: object - x-examples: - example-1: - threat_severity: Important - public_date: '2021-06-08T17:00:00Z' - bugzilla: - description: 'CVE-2020-24489 hw: vt-d related privilege escalation' - id: '1962650' - url: 'https://bugzilla.redhat.com/show_bug.cgi?id=1962650' - cvss3: - cvss3_base_score: '8.8' - cvss3_scoring_vector: 'CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H' - status: verified - cwe: CWE-459 - details: - - Incomplete cleanup in some Intel(R) VT-d products may allow an authenticated user to potentially enable escalation of privilege via local access. - - A flaw was found in Intel® VT-d products. Entries from the context cache on some types of context cache invalidations may not be properly invalidated which may allow an authenticated user to potentially enable escalation of privilege via local access. The highest threat from this vulnerability is to data confidentiality and integrity as well as system availability. - acknowledgement: Red Hat would like to thank Intel for reporting this issue. - affected_release: - - product_name: Red Hat Enterprise Linux 6 Extended Lifecycle Support - release_date: '2021-06-09T00:00:00Z' - advisory: 'RHSA-2021:2299' - cpe: 'cpe:/o:redhat:rhel_els:6' - package: 'microcode_ctl-2:1.17-33.33.el6_10' - - product_name: Red Hat Enterprise Linux 7 - release_date: '2021-06-09T00:00:00Z' - advisory: 'RHSA-2021:2305' - cpe: 'cpe:/o:redhat:enterprise_linux:7' - package: 'microcode_ctl-2:2.1-73.9.el7_9' - - product_name: Red Hat Enterprise Linux 7.2 Advanced Update Support - release_date: '2021-06-09T00:00:00Z' - advisory: 'RHSA-2021:2300' - cpe: 'cpe:/o:redhat:rhel_aus:7.2' - package: 'microcode_ctl-2:2.1-12.37.el7_2' - - product_name: Red Hat Enterprise Linux 7.3 Advanced Update Support - release_date: '2021-06-09T00:00:00Z' - advisory: 'RHSA-2021:2302' - cpe: 'cpe:/o:redhat:rhel_aus:7.3' - package: 'microcode_ctl-2:2.1-16.40.el7_3' - - product_name: Red Hat Enterprise Linux 7.4 Advanced Update Support - release_date: '2021-06-09T00:00:00Z' - advisory: 'RHSA-2021:2301' - cpe: 'cpe:/o:redhat:rhel_aus:7.4' - package: 'microcode_ctl-2:2.1-22.39.el7_4' - - product_name: Red Hat Enterprise Linux 7.4 Telco Extended Update Support - release_date: '2021-06-09T00:00:00Z' - advisory: 'RHSA-2021:2301' - cpe: 'cpe:/o:redhat:rhel_tus:7.4' - package: 'microcode_ctl-2:2.1-22.39.el7_4' - - product_name: Red Hat Enterprise Linux 7.4 Update Services for SAP Solutions - release_date: '2021-06-09T00:00:00Z' - advisory: 'RHSA-2021:2301' - cpe: 'cpe:/o:redhat:rhel_e4s:7.4' - package: 'microcode_ctl-2:2.1-22.39.el7_4' - - product_name: Red Hat Enterprise Linux 7.6 Advanced Update Support - release_date: '2021-06-09T00:00:00Z' - advisory: 'RHSA-2021:2303' - cpe: 'cpe:/o:redhat:rhel_aus:7.6' - package: 'microcode_ctl-2:2.1-47.21.el7_6' - - product_name: Red Hat Enterprise Linux 7.6 Telco Extended Update Support - release_date: '2021-06-09T00:00:00Z' - advisory: 'RHSA-2021:2303' - cpe: 'cpe:/o:redhat:rhel_tus:7.6' - package: 'microcode_ctl-2:2.1-47.21.el7_6' - - product_name: Red Hat Enterprise Linux 7.6 Update Services for SAP Solutions - release_date: '2021-06-09T00:00:00Z' - advisory: 'RHSA-2021:2303' - cpe: 'cpe:/o:redhat:rhel_e4s:7.6' - package: 'microcode_ctl-2:2.1-47.21.el7_6' - - product_name: Red Hat Enterprise Linux 7.7 Extended Update Support - release_date: '2021-06-09T00:00:00Z' - advisory: 'RHSA-2021:2304' - cpe: 'cpe:/o:redhat:rhel_eus:7.7' - package: 'microcode_ctl-2:2.1-53.16.el7_7' - - product_name: Red Hat Enterprise Linux 8 - release_date: '2021-06-09T00:00:00Z' - advisory: 'RHSA-2021:2308' - cpe: 'cpe:/o:redhat:enterprise_linux:8' - package: 'microcode_ctl-4:20210216-1.20210525.1.el8_4' - - product_name: Red Hat Enterprise Linux 8.1 Extended Update Support - release_date: '2021-06-09T00:00:00Z' - advisory: 'RHSA-2021:2306' - cpe: 'cpe:/o:redhat:rhel_eus:8.1' - package: 'microcode_ctl-4:20190618-1.20210525.1.el8_1' - - product_name: Red Hat Enterprise Linux 8.2 Extended Update Support - release_date: '2021-06-09T00:00:00Z' - advisory: 'RHSA-2021:2307' - cpe: 'cpe:/o:redhat:rhel_eus:8.2' - package: 'microcode_ctl-4:20191115-4.20210525.1.el8_2' - - product_name: Red Hat Virtualization 4 for Red Hat Enterprise Linux 7 - release_date: '2021-06-22T00:00:00Z' - advisory: 'RHSA-2021:2519' - cpe: 'cpe:/o:redhat:enterprise_linux:7::hypervisor' - package: 'redhat-virtualization-host-0:4.3.16-20210615.0.el7_9' - - product_name: Red Hat Virtualization 4 for Red Hat Enterprise Linux 8 - release_date: '2021-06-22T00:00:00Z' - advisory: 'RHSA-2021:2522' - cpe: 'cpe:/o:redhat:enterprise_linux:8::hypervisor' - name: CVE-2020-24489 - csaw: false - properties: - threat_severity: - type: string - minLength: 1 - public_date: - type: string - minLength: 1 - bugzilla: - type: object - required: - - description - - id - - url - properties: - description: - type: string - minLength: 1 - id: - type: string - minLength: 1 - url: - type: string - minLength: 1 - cvss3: - type: object - required: - - cvss3_base_score - - cvss3_scoring_vector - - status - properties: - cvss3_base_score: - type: string - minLength: 1 - cvss3_scoring_vector: - type: string - minLength: 1 - status: - type: string - minLength: 1 - cwe: - type: string - minLength: 1 - details: - type: array - items: - type: string - acknowledgement: - type: string - minLength: 1 - affected_release: - type: array - uniqueItems: true - minItems: 1 - items: - type: object - properties: - product_name: - type: string - minLength: 1 - release_date: - type: string - minLength: 1 - advisory: - type: string - minLength: 1 - cpe: - type: string - minLength: 1 - package: - type: string - minLength: 1 - required: - - product_name - - release_date - - advisory - - cpe - name: - type: string - minLength: 1 - csaw: - type: boolean - package_state: - type: array - items: - type: object - properties: - product_name: - type: string - fix_state: - type: string - package_name: - type: string - cpe: - type: string - required: - - product_name - - fix_state - - package_name - - cpe - required: - - threat_severity - - public_date - - bugzilla - - cvss3 - - cwe - - details - - acknowledgement - - name - - csaw diff --git a/apollo/rhsecurity/api_default.go b/apollo/rhsecurity/api_default.go deleted file mode 100644 index 8f7e9d4..0000000 --- a/apollo/rhsecurity/api_default.go +++ /dev/null @@ -1,380 +0,0 @@ -/* - * Red Hat Security Data API - * - * Unofficial OpenAPI definitions for Red Hat Security Data API - * - * API version: 1.0 - * Contact: mustafa@ctrliq.com - */ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package rhsecurity - -import ( - "bytes" - _context "context" - _ioutil "io/ioutil" - _nethttp "net/http" - _neturl "net/url" - "strings" -) - -// Linger please -var ( - _ _context.Context -) - -type DefaultApi interface { - - /* - * GetCve Get specific CVE - * Retrieve full CVE details - * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param cVE - * @return ApiGetCveRequest - */ - GetCve(ctx _context.Context, cVE string) ApiGetCveRequest - - /* - * GetCveExecute executes the request - * @return CVEDetailed - */ - GetCveExecute(r ApiGetCveRequest) (CVEDetailed, *_nethttp.Response, error) - - /* - * GetCves Get CVEs - * List all the recent CVEs when no parameter is passed. Returns a convenience object as response with very minimum attributes. - * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @return ApiGetCvesRequest - */ - GetCves(ctx _context.Context) ApiGetCvesRequest - - /* - * GetCvesExecute executes the request - * @return []CVE - */ - GetCvesExecute(r ApiGetCvesRequest) ([]CVE, *_nethttp.Response, error) -} - -// DefaultApiService DefaultApi service -type DefaultApiService service - -type ApiGetCveRequest struct { - ctx _context.Context - ApiService DefaultApi - cVE string -} - -func (r ApiGetCveRequest) Execute() (CVEDetailed, *_nethttp.Response, error) { - return r.ApiService.GetCveExecute(r) -} - -/* - * GetCve Get specific CVE - * Retrieve full CVE details - * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param cVE - * @return ApiGetCveRequest - */ -func (a *DefaultApiService) GetCve(ctx _context.Context, cVE string) ApiGetCveRequest { - return ApiGetCveRequest{ - ApiService: a, - ctx: ctx, - cVE: cVE, - } -} - -/* - * Execute executes the request - * @return CVEDetailed - */ -func (a *DefaultApiService) GetCveExecute(r ApiGetCveRequest) (CVEDetailed, *_nethttp.Response, error) { - var ( - localVarHTTPMethod = _nethttp.MethodGet - localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte - localVarReturnValue CVEDetailed - ) - - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "DefaultApiService.GetCve") - if err != nil { - return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} - } - - localVarPath := localBasePath + "/cve/{CVE}.json" - localVarPath = strings.Replace(localVarPath, "{"+"CVE"+"}", _neturl.PathEscape(parameterToString(r.cVE, "")), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := _neturl.Values{} - localVarFormParams := _neturl.Values{} - - // to determine the Content-Type header - localVarHTTPContentTypes := []string{} - - // set Content-Type header - localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) - if localVarHTTPContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHTTPContentType - } - - // to determine the Accept header - localVarHTTPHeaderAccepts := []string{"application/json"} - - // set Accept header - localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) - if localVarHTTPHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept - } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) - if err != nil { - return localVarReturnValue, nil, err - } - - localVarHTTPResponse, err := a.client.callAPI(req) - if err != nil || localVarHTTPResponse == nil { - return localVarReturnValue, localVarHTTPResponse, err - } - - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) - localVarHTTPResponse.Body.Close() - localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) - if err != nil { - return localVarReturnValue, localVarHTTPResponse, err - } - - if localVarHTTPResponse.StatusCode >= 300 { - newErr := GenericOpenAPIError{ - body: localVarBody, - error: localVarHTTPResponse.Status, - } - return localVarReturnValue, localVarHTTPResponse, newErr - } - - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr := GenericOpenAPIError{ - body: localVarBody, - error: err.Error(), - } - return localVarReturnValue, localVarHTTPResponse, newErr - } - - return localVarReturnValue, localVarHTTPResponse, nil -} - -type ApiGetCvesRequest struct { - ctx _context.Context - ApiService DefaultApi - before *string - after *string - ids *string - bug *string - advisory *string - severity *string - package_ *string - product *string - cwe *string - cvssScore *float32 - cvss3Score *string - page *float32 - perPage *float32 - createdDaysAgo *float32 -} - -func (r ApiGetCvesRequest) Before(before string) ApiGetCvesRequest { - r.before = &before - return r -} -func (r ApiGetCvesRequest) After(after string) ApiGetCvesRequest { - r.after = &after - return r -} -func (r ApiGetCvesRequest) Ids(ids string) ApiGetCvesRequest { - r.ids = &ids - return r -} -func (r ApiGetCvesRequest) Bug(bug string) ApiGetCvesRequest { - r.bug = &bug - return r -} -func (r ApiGetCvesRequest) Advisory(advisory string) ApiGetCvesRequest { - r.advisory = &advisory - return r -} -func (r ApiGetCvesRequest) Severity(severity string) ApiGetCvesRequest { - r.severity = &severity - return r -} -func (r ApiGetCvesRequest) Package_(package_ string) ApiGetCvesRequest { - r.package_ = &package_ - return r -} -func (r ApiGetCvesRequest) Product(product string) ApiGetCvesRequest { - r.product = &product - return r -} -func (r ApiGetCvesRequest) Cwe(cwe string) ApiGetCvesRequest { - r.cwe = &cwe - return r -} -func (r ApiGetCvesRequest) CvssScore(cvssScore float32) ApiGetCvesRequest { - r.cvssScore = &cvssScore - return r -} -func (r ApiGetCvesRequest) Cvss3Score(cvss3Score string) ApiGetCvesRequest { - r.cvss3Score = &cvss3Score - return r -} -func (r ApiGetCvesRequest) Page(page float32) ApiGetCvesRequest { - r.page = &page - return r -} -func (r ApiGetCvesRequest) PerPage(perPage float32) ApiGetCvesRequest { - r.perPage = &perPage - return r -} -func (r ApiGetCvesRequest) CreatedDaysAgo(createdDaysAgo float32) ApiGetCvesRequest { - r.createdDaysAgo = &createdDaysAgo - return r -} - -func (r ApiGetCvesRequest) Execute() ([]CVE, *_nethttp.Response, error) { - return r.ApiService.GetCvesExecute(r) -} - -/* - * GetCves Get CVEs - * List all the recent CVEs when no parameter is passed. Returns a convenience object as response with very minimum attributes. - * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @return ApiGetCvesRequest - */ -func (a *DefaultApiService) GetCves(ctx _context.Context) ApiGetCvesRequest { - return ApiGetCvesRequest{ - ApiService: a, - ctx: ctx, - } -} - -/* - * Execute executes the request - * @return []CVE - */ -func (a *DefaultApiService) GetCvesExecute(r ApiGetCvesRequest) ([]CVE, *_nethttp.Response, error) { - var ( - localVarHTTPMethod = _nethttp.MethodGet - localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte - localVarReturnValue []CVE - ) - - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "DefaultApiService.GetCves") - if err != nil { - return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} - } - - localVarPath := localBasePath + "/cve.json" - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := _neturl.Values{} - localVarFormParams := _neturl.Values{} - - if r.before != nil { - localVarQueryParams.Add("before", parameterToString(*r.before, "")) - } - if r.after != nil { - localVarQueryParams.Add("after", parameterToString(*r.after, "")) - } - if r.ids != nil { - localVarQueryParams.Add("ids", parameterToString(*r.ids, "")) - } - if r.bug != nil { - localVarQueryParams.Add("bug", parameterToString(*r.bug, "")) - } - if r.advisory != nil { - localVarQueryParams.Add("advisory", parameterToString(*r.advisory, "")) - } - if r.severity != nil { - localVarQueryParams.Add("severity", parameterToString(*r.severity, "")) - } - if r.package_ != nil { - localVarQueryParams.Add("package", parameterToString(*r.package_, "")) - } - if r.product != nil { - localVarQueryParams.Add("product", parameterToString(*r.product, "")) - } - if r.cwe != nil { - localVarQueryParams.Add("cwe", parameterToString(*r.cwe, "")) - } - if r.cvssScore != nil { - localVarQueryParams.Add("cvss_score", parameterToString(*r.cvssScore, "")) - } - if r.cvss3Score != nil { - localVarQueryParams.Add("cvss3_score", parameterToString(*r.cvss3Score, "")) - } - if r.page != nil { - localVarQueryParams.Add("page", parameterToString(*r.page, "")) - } - if r.perPage != nil { - localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) - } - if r.createdDaysAgo != nil { - localVarQueryParams.Add("created_days_ago", parameterToString(*r.createdDaysAgo, "")) - } - // to determine the Content-Type header - localVarHTTPContentTypes := []string{} - - // set Content-Type header - localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) - if localVarHTTPContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHTTPContentType - } - - // to determine the Accept header - localVarHTTPHeaderAccepts := []string{"application/json"} - - // set Accept header - localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) - if localVarHTTPHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept - } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) - if err != nil { - return localVarReturnValue, nil, err - } - - localVarHTTPResponse, err := a.client.callAPI(req) - if err != nil || localVarHTTPResponse == nil { - return localVarReturnValue, localVarHTTPResponse, err - } - - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) - localVarHTTPResponse.Body.Close() - localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) - if err != nil { - return localVarReturnValue, localVarHTTPResponse, err - } - - if localVarHTTPResponse.StatusCode >= 300 { - newErr := GenericOpenAPIError{ - body: localVarBody, - error: localVarHTTPResponse.Status, - } - return localVarReturnValue, localVarHTTPResponse, newErr - } - - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr := GenericOpenAPIError{ - body: localVarBody, - error: err.Error(), - } - return localVarReturnValue, localVarHTTPResponse, newErr - } - - return localVarReturnValue, localVarHTTPResponse, nil -} diff --git a/apollo/rhsecurity/client.go b/apollo/rhsecurity/client.go deleted file mode 100644 index fd66afc..0000000 --- a/apollo/rhsecurity/client.go +++ /dev/null @@ -1,536 +0,0 @@ -/* - * Red Hat Security Data API - * - * Unofficial OpenAPI definitions for Red Hat Security Data API - * - * API version: 1.0 - * Contact: mustafa@ctrliq.com - */ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package rhsecurity - -import ( - "bytes" - "context" - "encoding/json" - "encoding/xml" - "errors" - "fmt" - "io" - "log" - "mime/multipart" - "net/http" - "net/http/httputil" - "net/url" - "os" - "path/filepath" - "reflect" - "regexp" - "strconv" - "strings" - "time" - "unicode/utf8" - - "golang.org/x/oauth2" -) - -var ( - jsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:vnd\.[^;]+\+)?json)`) - xmlCheck = regexp.MustCompile(`(?i:(?:application|text)/xml)`) -) - -// APIClient manages communication with the Red Hat Security Data API API v1.0 -// In most cases there should be only one, shared, APIClient. -type APIClient struct { - cfg *Configuration - common service // Reuse a single struct instead of allocating one for each service on the heap. - - // API Services - - DefaultApi DefaultApi -} - -type service struct { - client *APIClient -} - -// NewAPIClient creates a new API client. Requires a userAgent string describing your application. -// optionally a custom http.Client to allow for advanced features such as caching. -func NewAPIClient(cfg *Configuration) *APIClient { - if cfg.HTTPClient == nil { - cfg.HTTPClient = http.DefaultClient - } - - c := &APIClient{} - c.cfg = cfg - c.common.client = c - - // API Services - c.DefaultApi = (*DefaultApiService)(&c.common) - - return c -} - -func atoi(in string) (int, error) { - return strconv.Atoi(in) -} - -// selectHeaderContentType select a content type from the available list. -func selectHeaderContentType(contentTypes []string) string { - if len(contentTypes) == 0 { - return "" - } - if contains(contentTypes, "application/json") { - return "application/json" - } - return contentTypes[0] // use the first content type specified in 'consumes' -} - -// selectHeaderAccept join all accept types and return -func selectHeaderAccept(accepts []string) string { - if len(accepts) == 0 { - return "" - } - - if contains(accepts, "application/json") { - return "application/json" - } - - return strings.Join(accepts, ",") -} - -// contains is a case insenstive match, finding needle in a haystack -func contains(haystack []string, needle string) bool { - for _, a := range haystack { - if strings.ToLower(a) == strings.ToLower(needle) { - return true - } - } - return false -} - -// Verify optional parameters are of the correct type. -func typeCheckParameter(obj interface{}, expected string, name string) error { - // Make sure there is an object. - if obj == nil { - return nil - } - - // Check the type is as expected. - if reflect.TypeOf(obj).String() != expected { - return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) - } - return nil -} - -// parameterToString convert interface{} parameters to string, using a delimiter if format is provided. -func parameterToString(obj interface{}, collectionFormat string) string { - var delimiter string - - switch collectionFormat { - case "pipes": - delimiter = "|" - case "ssv": - delimiter = " " - case "tsv": - delimiter = "\t" - case "csv": - delimiter = "," - } - - if reflect.TypeOf(obj).Kind() == reflect.Slice { - return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") - } else if t, ok := obj.(time.Time); ok { - return t.Format(time.RFC3339) - } - - return fmt.Sprintf("%v", obj) -} - -// helper for converting interface{} parameters to json strings -func parameterToJson(obj interface{}) (string, error) { - jsonBuf, err := json.Marshal(obj) - if err != nil { - return "", err - } - return string(jsonBuf), err -} - -// callAPI do the request. -func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { - if c.cfg.Debug { - dump, err := httputil.DumpRequestOut(request, true) - if err != nil { - return nil, err - } - log.Printf("\n%s\n", string(dump)) - } - - resp, err := c.cfg.HTTPClient.Do(request) - if err != nil { - return resp, err - } - - if c.cfg.Debug { - dump, err := httputil.DumpResponse(resp, true) - if err != nil { - return resp, err - } - log.Printf("\n%s\n", string(dump)) - } - return resp, err -} - -// Allow modification of underlying config for alternate implementations and testing -// Caution: modifying the configuration while live can cause data races and potentially unwanted behavior -func (c *APIClient) GetConfig() *Configuration { - return c.cfg -} - -// prepareRequest build the request -func (c *APIClient) prepareRequest( - ctx context.Context, - path string, method string, - postBody interface{}, - headerParams map[string]string, - queryParams url.Values, - formParams url.Values, - formFileName string, - fileName string, - fileBytes []byte) (localVarRequest *http.Request, err error) { - - var body *bytes.Buffer - - // Detect postBody type and post. - if postBody != nil { - contentType := headerParams["Content-Type"] - if contentType == "" { - contentType = detectContentType(postBody) - headerParams["Content-Type"] = contentType - } - - body, err = setBody(postBody, contentType) - if err != nil { - return nil, err - } - } - - // add form parameters and file if available. - if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { - if body != nil { - return nil, errors.New("Cannot specify postBody and multipart form at the same time.") - } - body = &bytes.Buffer{} - w := multipart.NewWriter(body) - - for k, v := range formParams { - for _, iv := range v { - if strings.HasPrefix(k, "@") { // file - err = addFile(w, k[1:], iv) - if err != nil { - return nil, err - } - } else { // form value - w.WriteField(k, iv) - } - } - } - if len(fileBytes) > 0 && fileName != "" { - w.Boundary() - //_, fileNm := filepath.Split(fileName) - part, err := w.CreateFormFile(formFileName, filepath.Base(fileName)) - if err != nil { - return nil, err - } - _, err = part.Write(fileBytes) - if err != nil { - return nil, err - } - } - - // Set the Boundary in the Content-Type - headerParams["Content-Type"] = w.FormDataContentType() - - // Set Content-Length - headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) - w.Close() - } - - if strings.HasPrefix(headerParams["Content-Type"], "application/x-www-form-urlencoded") && len(formParams) > 0 { - if body != nil { - return nil, errors.New("Cannot specify postBody and x-www-form-urlencoded form at the same time.") - } - body = &bytes.Buffer{} - body.WriteString(formParams.Encode()) - // Set Content-Length - headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) - } - - // Setup path and query parameters - url, err := url.Parse(path) - if err != nil { - return nil, err - } - - // Override request host, if applicable - if c.cfg.Host != "" { - url.Host = c.cfg.Host - } - - // Override request scheme, if applicable - if c.cfg.Scheme != "" { - url.Scheme = c.cfg.Scheme - } - - // Adding Query Param - query := url.Query() - for k, v := range queryParams { - for _, iv := range v { - query.Add(k, iv) - } - } - - // Encode the parameters. - url.RawQuery = query.Encode() - - // Generate a new request - if body != nil { - localVarRequest, err = http.NewRequest(method, url.String(), body) - } else { - localVarRequest, err = http.NewRequest(method, url.String(), nil) - } - if err != nil { - return nil, err - } - - // add header parameters, if any - if len(headerParams) > 0 { - headers := http.Header{} - for h, v := range headerParams { - headers.Set(h, v) - } - localVarRequest.Header = headers - } - - // Add the user agent to the request. - localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) - - if ctx != nil { - // add context to the request - localVarRequest = localVarRequest.WithContext(ctx) - - // Walk through any authentication. - - // OAuth2 authentication - if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { - // We were able to grab an oauth2 token from the context - var latestToken *oauth2.Token - if latestToken, err = tok.Token(); err != nil { - return nil, err - } - - latestToken.SetAuthHeader(localVarRequest) - } - - // Basic HTTP Authentication - if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { - localVarRequest.SetBasicAuth(auth.UserName, auth.Password) - } - - // AccessToken Authentication - if auth, ok := ctx.Value(ContextAccessToken).(string); ok { - localVarRequest.Header.Add("Authorization", "Bearer "+auth) - } - - } - - for header, value := range c.cfg.DefaultHeader { - localVarRequest.Header.Add(header, value) - } - return localVarRequest, nil -} - -func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { - if len(b) == 0 { - return nil - } - if s, ok := v.(*string); ok { - *s = string(b) - return nil - } - if xmlCheck.MatchString(contentType) { - if err = xml.Unmarshal(b, v); err != nil { - return err - } - return nil - } - if jsonCheck.MatchString(contentType) { - if actualObj, ok := v.(interface{ GetActualInstance() interface{} }); ok { // oneOf, anyOf schemas - if unmarshalObj, ok := actualObj.(interface{ UnmarshalJSON([]byte) error }); ok { // make sure it has UnmarshalJSON defined - if err = unmarshalObj.UnmarshalJSON(b); err != nil { - return err - } - } else { - return errors.New("Unknown type with GetActualInstance but no unmarshalObj.UnmarshalJSON defined") - } - } else if err = json.Unmarshal(b, v); err != nil { // simple model - return err - } - return nil - } - return errors.New("undefined response type") -} - -// Add a file to the multipart request -func addFile(w *multipart.Writer, fieldName, path string) error { - file, err := os.Open(path) - if err != nil { - return err - } - defer file.Close() - - part, err := w.CreateFormFile(fieldName, filepath.Base(path)) - if err != nil { - return err - } - _, err = io.Copy(part, file) - - return err -} - -// Prevent trying to import "fmt" -func reportError(format string, a ...interface{}) error { - return fmt.Errorf(format, a...) -} - -// Set request body from an interface{} -func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { - if bodyBuf == nil { - bodyBuf = &bytes.Buffer{} - } - - if reader, ok := body.(io.Reader); ok { - _, err = bodyBuf.ReadFrom(reader) - } else if fp, ok := body.(**os.File); ok { - _, err = bodyBuf.ReadFrom(*fp) - } else if b, ok := body.([]byte); ok { - _, err = bodyBuf.Write(b) - } else if s, ok := body.(string); ok { - _, err = bodyBuf.WriteString(s) - } else if s, ok := body.(*string); ok { - _, err = bodyBuf.WriteString(*s) - } else if jsonCheck.MatchString(contentType) { - err = json.NewEncoder(bodyBuf).Encode(body) - } else if xmlCheck.MatchString(contentType) { - err = xml.NewEncoder(bodyBuf).Encode(body) - } - - if err != nil { - return nil, err - } - - if bodyBuf.Len() == 0 { - err = fmt.Errorf("Invalid body type %s\n", contentType) - return nil, err - } - return bodyBuf, nil -} - -// detectContentType method is used to figure out `Request.Body` content type for request header -func detectContentType(body interface{}) string { - contentType := "text/plain; charset=utf-8" - kind := reflect.TypeOf(body).Kind() - - switch kind { - case reflect.Struct, reflect.Map, reflect.Ptr: - contentType = "application/json; charset=utf-8" - case reflect.String: - contentType = "text/plain; charset=utf-8" - default: - if b, ok := body.([]byte); ok { - contentType = http.DetectContentType(b) - } else if kind == reflect.Slice { - contentType = "application/json; charset=utf-8" - } - } - - return contentType -} - -// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go -type cacheControl map[string]string - -func parseCacheControl(headers http.Header) cacheControl { - cc := cacheControl{} - ccHeader := headers.Get("Cache-Control") - for _, part := range strings.Split(ccHeader, ",") { - part = strings.Trim(part, " ") - if part == "" { - continue - } - if strings.ContainsRune(part, '=') { - keyval := strings.Split(part, "=") - cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") - } else { - cc[part] = "" - } - } - return cc -} - -// CacheExpires helper function to determine remaining time before repeating a request. -func CacheExpires(r *http.Response) time.Time { - // Figure out when the cache expires. - var expires time.Time - now, err := time.Parse(time.RFC1123, r.Header.Get("date")) - if err != nil { - return time.Now() - } - respCacheControl := parseCacheControl(r.Header) - - if maxAge, ok := respCacheControl["max-age"]; ok { - lifetime, err := time.ParseDuration(maxAge + "s") - if err != nil { - expires = now - } else { - expires = now.Add(lifetime) - } - } else { - expiresHeader := r.Header.Get("Expires") - if expiresHeader != "" { - expires, err = time.Parse(time.RFC1123, expiresHeader) - if err != nil { - expires = now - } - } - } - return expires -} - -func strlen(s string) int { - return utf8.RuneCountInString(s) -} - -// GenericOpenAPIError Provides access to the body, error and model on returned errors. -type GenericOpenAPIError struct { - body []byte - error string - model interface{} -} - -// Error returns non-empty string if there was an error. -func (e GenericOpenAPIError) Error() string { - return e.error -} - -// Body returns the raw bytes of the response -func (e GenericOpenAPIError) Body() []byte { - return e.body -} - -// Model returns the unpacked model of the error -func (e GenericOpenAPIError) Model() interface{} { - return e.model -} diff --git a/apollo/rhsecurity/configuration.go b/apollo/rhsecurity/configuration.go deleted file mode 100644 index d4da8ca..0000000 --- a/apollo/rhsecurity/configuration.go +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Red Hat Security Data API - * - * Unofficial OpenAPI definitions for Red Hat Security Data API - * - * API version: 1.0 - * Contact: mustafa@ctrliq.com - */ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package rhsecurity - -import ( - "context" - "fmt" - "net/http" - "strings" -) - -// contextKeys are used to identify the type of value in the context. -// Since these are string, it is possible to get a short description of the -// context key for logging and debugging using key.String(). - -type contextKey string - -func (c contextKey) String() string { - return "auth " + string(c) -} - -var ( - // ContextOAuth2 takes an oauth2.TokenSource as authentication for the request. - ContextOAuth2 = contextKey("token") - - // ContextBasicAuth takes BasicAuth as authentication for the request. - ContextBasicAuth = contextKey("basic") - - // ContextAccessToken takes a string oauth2 access token as authentication for the request. - ContextAccessToken = contextKey("accesstoken") - - // ContextAPIKeys takes a string apikey as authentication for the request - ContextAPIKeys = contextKey("apiKeys") - - // ContextHttpSignatureAuth takes HttpSignatureAuth as authentication for the request. - ContextHttpSignatureAuth = contextKey("httpsignature") - - // ContextServerIndex uses a server configuration from the index. - ContextServerIndex = contextKey("serverIndex") - - // ContextOperationServerIndices uses a server configuration from the index mapping. - ContextOperationServerIndices = contextKey("serverOperationIndices") - - // ContextServerVariables overrides a server configuration variables. - ContextServerVariables = contextKey("serverVariables") - - // ContextOperationServerVariables overrides a server configuration variables using operation specific values. - ContextOperationServerVariables = contextKey("serverOperationVariables") -) - -// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth -type BasicAuth struct { - UserName string `json:"userName,omitempty"` - Password string `json:"password,omitempty"` -} - -// APIKey provides API key based authentication to a request passed via context using ContextAPIKey -type APIKey struct { - Key string - Prefix string -} - -// ServerVariable stores the information about a server variable -type ServerVariable struct { - Description string - DefaultValue string - EnumValues []string -} - -// ServerConfiguration stores the information about a server -type ServerConfiguration struct { - URL string - Description string - Variables map[string]ServerVariable -} - -// ServerConfigurations stores multiple ServerConfiguration items -type ServerConfigurations []ServerConfiguration - -// Configuration stores the configuration of the API client -type Configuration struct { - Host string `json:"host,omitempty"` - Scheme string `json:"scheme,omitempty"` - DefaultHeader map[string]string `json:"defaultHeader,omitempty"` - UserAgent string `json:"userAgent,omitempty"` - Debug bool `json:"debug,omitempty"` - Servers ServerConfigurations - OperationServers map[string]ServerConfigurations - HTTPClient *http.Client -} - -// NewConfiguration returns a new Configuration object -func NewConfiguration() *Configuration { - cfg := &Configuration{ - DefaultHeader: make(map[string]string), - UserAgent: "OpenAPI-Generator/1.0.0/go", - Debug: false, - Servers: ServerConfigurations{ - { - URL: "https://access.redhat.com/hydra/rest/securitydata", - Description: "No description provided", - }, - }, - OperationServers: map[string]ServerConfigurations{}, - } - return cfg -} - -// AddDefaultHeader adds a new HTTP header to the default header in the request -func (c *Configuration) AddDefaultHeader(key string, value string) { - c.DefaultHeader[key] = value -} - -// URL formats template on a index using given variables -func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error) { - if index < 0 || len(sc) <= index { - return "", fmt.Errorf("Index %v out of range %v", index, len(sc)-1) - } - server := sc[index] - url := server.URL - - // go through variables and replace placeholders - for name, variable := range server.Variables { - if value, ok := variables[name]; ok { - found := bool(len(variable.EnumValues) == 0) - for _, enumValue := range variable.EnumValues { - if value == enumValue { - found = true - } - } - if !found { - return "", fmt.Errorf("The variable %s in the server URL has invalid value %v. Must be %v", name, value, variable.EnumValues) - } - url = strings.Replace(url, "{"+name+"}", value, -1) - } else { - url = strings.Replace(url, "{"+name+"}", variable.DefaultValue, -1) - } - } - return url, nil -} - -// ServerURL returns URL based on server settings -func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) { - return c.Servers.URL(index, variables) -} - -func getServerIndex(ctx context.Context) (int, error) { - si := ctx.Value(ContextServerIndex) - if si != nil { - if index, ok := si.(int); ok { - return index, nil - } - return 0, reportError("Invalid type %T should be int", si) - } - return 0, nil -} - -func getServerOperationIndex(ctx context.Context, endpoint string) (int, error) { - osi := ctx.Value(ContextOperationServerIndices) - if osi != nil { - if operationIndices, ok := osi.(map[string]int); !ok { - return 0, reportError("Invalid type %T should be map[string]int", osi) - } else { - index, ok := operationIndices[endpoint] - if ok { - return index, nil - } - } - } - return getServerIndex(ctx) -} - -func getServerVariables(ctx context.Context) (map[string]string, error) { - sv := ctx.Value(ContextServerVariables) - if sv != nil { - if variables, ok := sv.(map[string]string); ok { - return variables, nil - } - return nil, reportError("ctx value of ContextServerVariables has invalid type %T should be map[string]string", sv) - } - return nil, nil -} - -func getServerOperationVariables(ctx context.Context, endpoint string) (map[string]string, error) { - osv := ctx.Value(ContextOperationServerVariables) - if osv != nil { - if operationVariables, ok := osv.(map[string]map[string]string); !ok { - return nil, reportError("ctx value of ContextOperationServerVariables has invalid type %T should be map[string]map[string]string", osv) - } else { - variables, ok := operationVariables[endpoint] - if ok { - return variables, nil - } - } - } - return getServerVariables(ctx) -} - -// ServerURLWithContext returns a new server URL given an endpoint -func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) { - sc, ok := c.OperationServers[endpoint] - if !ok { - sc = c.Servers - } - - if ctx == nil { - return sc.URL(0, nil) - } - - index, err := getServerOperationIndex(ctx, endpoint) - if err != nil { - return "", err - } - - variables, err := getServerOperationVariables(ctx, endpoint) - if err != nil { - return "", err - } - - return sc.URL(index, variables) -} diff --git a/apollo/rhsecurity/docs/CVE.md b/apollo/rhsecurity/docs/CVE.md deleted file mode 100644 index 7353ae7..0000000 --- a/apollo/rhsecurity/docs/CVE.md +++ /dev/null @@ -1,313 +0,0 @@ -# CVE - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**CVE** | **string** | | -**Severity** | **string** | | -**PublicDate** | **string** | | -**Advisories** | **[]string** | | -**Bugzilla** | **string** | | -**BugzillaDescription** | **string** | | -**CvssScore** | Pointer to **float32** | | [optional] -**CvssScoringVector** | Pointer to **string** | | [optional] -**CWE** | **string** | | -**AffectedPackages** | **[]string** | | -**ResourceUrl** | **string** | | -**Cvss3ScoringVector** | **string** | | -**Cvss3Score** | **string** | | - -## Methods - -### NewCVE - -`func NewCVE(cVE string, severity string, publicDate string, advisories []string, bugzilla string, bugzillaDescription string, cWE string, affectedPackages []string, resourceUrl string, cvss3ScoringVector string, cvss3Score string, ) *CVE` - -NewCVE instantiates a new CVE object -This constructor will assign default values to properties that have it defined, -and makes sure properties required by API are set, but the set of arguments -will change when the set of required properties is changed - -### NewCVEWithDefaults - -`func NewCVEWithDefaults() *CVE` - -NewCVEWithDefaults instantiates a new CVE object -This constructor will only assign default values to properties that have it defined, -but it doesn't guarantee that properties required by API are set - -### GetCVE - -`func (o *CVE) GetCVE() string` - -GetCVE returns the CVE field if non-nil, zero value otherwise. - -### GetCVEOk - -`func (o *CVE) GetCVEOk() (*string, bool)` - -GetCVEOk returns a tuple with the CVE field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetCVE - -`func (o *CVE) SetCVE(v string)` - -SetCVE sets CVE field to given value. - - -### GetSeverity - -`func (o *CVE) GetSeverity() string` - -GetSeverity returns the Severity field if non-nil, zero value otherwise. - -### GetSeverityOk - -`func (o *CVE) GetSeverityOk() (*string, bool)` - -GetSeverityOk returns a tuple with the Severity field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetSeverity - -`func (o *CVE) SetSeverity(v string)` - -SetSeverity sets Severity field to given value. - - -### GetPublicDate - -`func (o *CVE) GetPublicDate() string` - -GetPublicDate returns the PublicDate field if non-nil, zero value otherwise. - -### GetPublicDateOk - -`func (o *CVE) GetPublicDateOk() (*string, bool)` - -GetPublicDateOk returns a tuple with the PublicDate field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetPublicDate - -`func (o *CVE) SetPublicDate(v string)` - -SetPublicDate sets PublicDate field to given value. - - -### GetAdvisories - -`func (o *CVE) GetAdvisories() []string` - -GetAdvisories returns the Advisories field if non-nil, zero value otherwise. - -### GetAdvisoriesOk - -`func (o *CVE) GetAdvisoriesOk() (*[]string, bool)` - -GetAdvisoriesOk returns a tuple with the Advisories field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetAdvisories - -`func (o *CVE) SetAdvisories(v []string)` - -SetAdvisories sets Advisories field to given value. - - -### GetBugzilla - -`func (o *CVE) GetBugzilla() string` - -GetBugzilla returns the Bugzilla field if non-nil, zero value otherwise. - -### GetBugzillaOk - -`func (o *CVE) GetBugzillaOk() (*string, bool)` - -GetBugzillaOk returns a tuple with the Bugzilla field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetBugzilla - -`func (o *CVE) SetBugzilla(v string)` - -SetBugzilla sets Bugzilla field to given value. - - -### GetBugzillaDescription - -`func (o *CVE) GetBugzillaDescription() string` - -GetBugzillaDescription returns the BugzillaDescription field if non-nil, zero value otherwise. - -### GetBugzillaDescriptionOk - -`func (o *CVE) GetBugzillaDescriptionOk() (*string, bool)` - -GetBugzillaDescriptionOk returns a tuple with the BugzillaDescription field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetBugzillaDescription - -`func (o *CVE) SetBugzillaDescription(v string)` - -SetBugzillaDescription sets BugzillaDescription field to given value. - - -### GetCvssScore - -`func (o *CVE) GetCvssScore() float32` - -GetCvssScore returns the CvssScore field if non-nil, zero value otherwise. - -### GetCvssScoreOk - -`func (o *CVE) GetCvssScoreOk() (*float32, bool)` - -GetCvssScoreOk returns a tuple with the CvssScore field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetCvssScore - -`func (o *CVE) SetCvssScore(v float32)` - -SetCvssScore sets CvssScore field to given value. - -### HasCvssScore - -`func (o *CVE) HasCvssScore() bool` - -HasCvssScore returns a boolean if a field has been set. - -### GetCvssScoringVector - -`func (o *CVE) GetCvssScoringVector() string` - -GetCvssScoringVector returns the CvssScoringVector field if non-nil, zero value otherwise. - -### GetCvssScoringVectorOk - -`func (o *CVE) GetCvssScoringVectorOk() (*string, bool)` - -GetCvssScoringVectorOk returns a tuple with the CvssScoringVector field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetCvssScoringVector - -`func (o *CVE) SetCvssScoringVector(v string)` - -SetCvssScoringVector sets CvssScoringVector field to given value. - -### HasCvssScoringVector - -`func (o *CVE) HasCvssScoringVector() bool` - -HasCvssScoringVector returns a boolean if a field has been set. - -### GetCWE - -`func (o *CVE) GetCWE() string` - -GetCWE returns the CWE field if non-nil, zero value otherwise. - -### GetCWEOk - -`func (o *CVE) GetCWEOk() (*string, bool)` - -GetCWEOk returns a tuple with the CWE field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetCWE - -`func (o *CVE) SetCWE(v string)` - -SetCWE sets CWE field to given value. - - -### GetAffectedPackages - -`func (o *CVE) GetAffectedPackages() []string` - -GetAffectedPackages returns the AffectedPackages field if non-nil, zero value otherwise. - -### GetAffectedPackagesOk - -`func (o *CVE) GetAffectedPackagesOk() (*[]string, bool)` - -GetAffectedPackagesOk returns a tuple with the AffectedPackages field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetAffectedPackages - -`func (o *CVE) SetAffectedPackages(v []string)` - -SetAffectedPackages sets AffectedPackages field to given value. - - -### GetResourceUrl - -`func (o *CVE) GetResourceUrl() string` - -GetResourceUrl returns the ResourceUrl field if non-nil, zero value otherwise. - -### GetResourceUrlOk - -`func (o *CVE) GetResourceUrlOk() (*string, bool)` - -GetResourceUrlOk returns a tuple with the ResourceUrl field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetResourceUrl - -`func (o *CVE) SetResourceUrl(v string)` - -SetResourceUrl sets ResourceUrl field to given value. - - -### GetCvss3ScoringVector - -`func (o *CVE) GetCvss3ScoringVector() string` - -GetCvss3ScoringVector returns the Cvss3ScoringVector field if non-nil, zero value otherwise. - -### GetCvss3ScoringVectorOk - -`func (o *CVE) GetCvss3ScoringVectorOk() (*string, bool)` - -GetCvss3ScoringVectorOk returns a tuple with the Cvss3ScoringVector field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetCvss3ScoringVector - -`func (o *CVE) SetCvss3ScoringVector(v string)` - -SetCvss3ScoringVector sets Cvss3ScoringVector field to given value. - - -### GetCvss3Score - -`func (o *CVE) GetCvss3Score() string` - -GetCvss3Score returns the Cvss3Score field if non-nil, zero value otherwise. - -### GetCvss3ScoreOk - -`func (o *CVE) GetCvss3ScoreOk() (*string, bool)` - -GetCvss3ScoreOk returns a tuple with the Cvss3Score field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetCvss3Score - -`func (o *CVE) SetCvss3Score(v string)` - -SetCvss3Score sets Cvss3Score field to given value. - - - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/apollo/rhsecurity/docs/CVEDetailed.md b/apollo/rhsecurity/docs/CVEDetailed.md deleted file mode 100644 index 916bbfa..0000000 --- a/apollo/rhsecurity/docs/CVEDetailed.md +++ /dev/null @@ -1,271 +0,0 @@ -# CVEDetailed - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**ThreatSeverity** | **string** | | -**PublicDate** | **string** | | -**Bugzilla** | [**CVEDetailedBugzilla**](CVEDetailedBugzilla.md) | | -**Cvss3** | [**CVEDetailedCvss3**](CVEDetailedCvss3.md) | | -**Cwe** | **string** | | -**Details** | **[]string** | | -**Acknowledgement** | **string** | | -**AffectedRelease** | Pointer to [**[]CVEDetailedAffectedRelease**](CVEDetailedAffectedRelease.md) | | [optional] -**Name** | **string** | | -**Csaw** | **bool** | | -**PackageState** | Pointer to [**[]CVEDetailedPackageState**](CVEDetailedPackageState.md) | | [optional] - -## Methods - -### NewCVEDetailed - -`func NewCVEDetailed(threatSeverity string, publicDate string, bugzilla CVEDetailedBugzilla, cvss3 CVEDetailedCvss3, cwe string, details []string, acknowledgement string, name string, csaw bool, ) *CVEDetailed` - -NewCVEDetailed instantiates a new CVEDetailed object -This constructor will assign default values to properties that have it defined, -and makes sure properties required by API are set, but the set of arguments -will change when the set of required properties is changed - -### NewCVEDetailedWithDefaults - -`func NewCVEDetailedWithDefaults() *CVEDetailed` - -NewCVEDetailedWithDefaults instantiates a new CVEDetailed object -This constructor will only assign default values to properties that have it defined, -but it doesn't guarantee that properties required by API are set - -### GetThreatSeverity - -`func (o *CVEDetailed) GetThreatSeverity() string` - -GetThreatSeverity returns the ThreatSeverity field if non-nil, zero value otherwise. - -### GetThreatSeverityOk - -`func (o *CVEDetailed) GetThreatSeverityOk() (*string, bool)` - -GetThreatSeverityOk returns a tuple with the ThreatSeverity field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetThreatSeverity - -`func (o *CVEDetailed) SetThreatSeverity(v string)` - -SetThreatSeverity sets ThreatSeverity field to given value. - - -### GetPublicDate - -`func (o *CVEDetailed) GetPublicDate() string` - -GetPublicDate returns the PublicDate field if non-nil, zero value otherwise. - -### GetPublicDateOk - -`func (o *CVEDetailed) GetPublicDateOk() (*string, bool)` - -GetPublicDateOk returns a tuple with the PublicDate field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetPublicDate - -`func (o *CVEDetailed) SetPublicDate(v string)` - -SetPublicDate sets PublicDate field to given value. - - -### GetBugzilla - -`func (o *CVEDetailed) GetBugzilla() CVEDetailedBugzilla` - -GetBugzilla returns the Bugzilla field if non-nil, zero value otherwise. - -### GetBugzillaOk - -`func (o *CVEDetailed) GetBugzillaOk() (*CVEDetailedBugzilla, bool)` - -GetBugzillaOk returns a tuple with the Bugzilla field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetBugzilla - -`func (o *CVEDetailed) SetBugzilla(v CVEDetailedBugzilla)` - -SetBugzilla sets Bugzilla field to given value. - - -### GetCvss3 - -`func (o *CVEDetailed) GetCvss3() CVEDetailedCvss3` - -GetCvss3 returns the Cvss3 field if non-nil, zero value otherwise. - -### GetCvss3Ok - -`func (o *CVEDetailed) GetCvss3Ok() (*CVEDetailedCvss3, bool)` - -GetCvss3Ok returns a tuple with the Cvss3 field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetCvss3 - -`func (o *CVEDetailed) SetCvss3(v CVEDetailedCvss3)` - -SetCvss3 sets Cvss3 field to given value. - - -### GetCwe - -`func (o *CVEDetailed) GetCwe() string` - -GetCwe returns the Cwe field if non-nil, zero value otherwise. - -### GetCweOk - -`func (o *CVEDetailed) GetCweOk() (*string, bool)` - -GetCweOk returns a tuple with the Cwe field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetCwe - -`func (o *CVEDetailed) SetCwe(v string)` - -SetCwe sets Cwe field to given value. - - -### GetDetails - -`func (o *CVEDetailed) GetDetails() []string` - -GetDetails returns the Details field if non-nil, zero value otherwise. - -### GetDetailsOk - -`func (o *CVEDetailed) GetDetailsOk() (*[]string, bool)` - -GetDetailsOk returns a tuple with the Details field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetDetails - -`func (o *CVEDetailed) SetDetails(v []string)` - -SetDetails sets Details field to given value. - - -### GetAcknowledgement - -`func (o *CVEDetailed) GetAcknowledgement() string` - -GetAcknowledgement returns the Acknowledgement field if non-nil, zero value otherwise. - -### GetAcknowledgementOk - -`func (o *CVEDetailed) GetAcknowledgementOk() (*string, bool)` - -GetAcknowledgementOk returns a tuple with the Acknowledgement field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetAcknowledgement - -`func (o *CVEDetailed) SetAcknowledgement(v string)` - -SetAcknowledgement sets Acknowledgement field to given value. - - -### GetAffectedRelease - -`func (o *CVEDetailed) GetAffectedRelease() []CVEDetailedAffectedRelease` - -GetAffectedRelease returns the AffectedRelease field if non-nil, zero value otherwise. - -### GetAffectedReleaseOk - -`func (o *CVEDetailed) GetAffectedReleaseOk() (*[]CVEDetailedAffectedRelease, bool)` - -GetAffectedReleaseOk returns a tuple with the AffectedRelease field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetAffectedRelease - -`func (o *CVEDetailed) SetAffectedRelease(v []CVEDetailedAffectedRelease)` - -SetAffectedRelease sets AffectedRelease field to given value. - -### HasAffectedRelease - -`func (o *CVEDetailed) HasAffectedRelease() bool` - -HasAffectedRelease returns a boolean if a field has been set. - -### GetName - -`func (o *CVEDetailed) GetName() string` - -GetName returns the Name field if non-nil, zero value otherwise. - -### GetNameOk - -`func (o *CVEDetailed) GetNameOk() (*string, bool)` - -GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetName - -`func (o *CVEDetailed) SetName(v string)` - -SetName sets Name field to given value. - - -### GetCsaw - -`func (o *CVEDetailed) GetCsaw() bool` - -GetCsaw returns the Csaw field if non-nil, zero value otherwise. - -### GetCsawOk - -`func (o *CVEDetailed) GetCsawOk() (*bool, bool)` - -GetCsawOk returns a tuple with the Csaw field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetCsaw - -`func (o *CVEDetailed) SetCsaw(v bool)` - -SetCsaw sets Csaw field to given value. - - -### GetPackageState - -`func (o *CVEDetailed) GetPackageState() []CVEDetailedPackageState` - -GetPackageState returns the PackageState field if non-nil, zero value otherwise. - -### GetPackageStateOk - -`func (o *CVEDetailed) GetPackageStateOk() (*[]CVEDetailedPackageState, bool)` - -GetPackageStateOk returns a tuple with the PackageState field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetPackageState - -`func (o *CVEDetailed) SetPackageState(v []CVEDetailedPackageState)` - -SetPackageState sets PackageState field to given value. - -### HasPackageState - -`func (o *CVEDetailed) HasPackageState() bool` - -HasPackageState returns a boolean if a field has been set. - - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/apollo/rhsecurity/docs/CVEDetailedAffectedRelease.md b/apollo/rhsecurity/docs/CVEDetailedAffectedRelease.md deleted file mode 100644 index 313d04d..0000000 --- a/apollo/rhsecurity/docs/CVEDetailedAffectedRelease.md +++ /dev/null @@ -1,140 +0,0 @@ -# CVEDetailedAffectedRelease - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**ProductName** | **string** | | -**ReleaseDate** | **string** | | -**Advisory** | **string** | | -**Cpe** | **string** | | -**Package** | Pointer to **string** | | [optional] - -## Methods - -### NewCVEDetailedAffectedRelease - -`func NewCVEDetailedAffectedRelease(productName string, releaseDate string, advisory string, cpe string, ) *CVEDetailedAffectedRelease` - -NewCVEDetailedAffectedRelease instantiates a new CVEDetailedAffectedRelease object -This constructor will assign default values to properties that have it defined, -and makes sure properties required by API are set, but the set of arguments -will change when the set of required properties is changed - -### NewCVEDetailedAffectedReleaseWithDefaults - -`func NewCVEDetailedAffectedReleaseWithDefaults() *CVEDetailedAffectedRelease` - -NewCVEDetailedAffectedReleaseWithDefaults instantiates a new CVEDetailedAffectedRelease object -This constructor will only assign default values to properties that have it defined, -but it doesn't guarantee that properties required by API are set - -### GetProductName - -`func (o *CVEDetailedAffectedRelease) GetProductName() string` - -GetProductName returns the ProductName field if non-nil, zero value otherwise. - -### GetProductNameOk - -`func (o *CVEDetailedAffectedRelease) GetProductNameOk() (*string, bool)` - -GetProductNameOk returns a tuple with the ProductName field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetProductName - -`func (o *CVEDetailedAffectedRelease) SetProductName(v string)` - -SetProductName sets ProductName field to given value. - - -### GetReleaseDate - -`func (o *CVEDetailedAffectedRelease) GetReleaseDate() string` - -GetReleaseDate returns the ReleaseDate field if non-nil, zero value otherwise. - -### GetReleaseDateOk - -`func (o *CVEDetailedAffectedRelease) GetReleaseDateOk() (*string, bool)` - -GetReleaseDateOk returns a tuple with the ReleaseDate field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetReleaseDate - -`func (o *CVEDetailedAffectedRelease) SetReleaseDate(v string)` - -SetReleaseDate sets ReleaseDate field to given value. - - -### GetAdvisory - -`func (o *CVEDetailedAffectedRelease) GetAdvisory() string` - -GetAdvisory returns the Advisory field if non-nil, zero value otherwise. - -### GetAdvisoryOk - -`func (o *CVEDetailedAffectedRelease) GetAdvisoryOk() (*string, bool)` - -GetAdvisoryOk returns a tuple with the Advisory field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetAdvisory - -`func (o *CVEDetailedAffectedRelease) SetAdvisory(v string)` - -SetAdvisory sets Advisory field to given value. - - -### GetCpe - -`func (o *CVEDetailedAffectedRelease) GetCpe() string` - -GetCpe returns the Cpe field if non-nil, zero value otherwise. - -### GetCpeOk - -`func (o *CVEDetailedAffectedRelease) GetCpeOk() (*string, bool)` - -GetCpeOk returns a tuple with the Cpe field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetCpe - -`func (o *CVEDetailedAffectedRelease) SetCpe(v string)` - -SetCpe sets Cpe field to given value. - - -### GetPackage - -`func (o *CVEDetailedAffectedRelease) GetPackage() string` - -GetPackage returns the Package field if non-nil, zero value otherwise. - -### GetPackageOk - -`func (o *CVEDetailedAffectedRelease) GetPackageOk() (*string, bool)` - -GetPackageOk returns a tuple with the Package field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetPackage - -`func (o *CVEDetailedAffectedRelease) SetPackage(v string)` - -SetPackage sets Package field to given value. - -### HasPackage - -`func (o *CVEDetailedAffectedRelease) HasPackage() bool` - -HasPackage returns a boolean if a field has been set. - - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/apollo/rhsecurity/docs/CVEDetailedBugzilla.md b/apollo/rhsecurity/docs/CVEDetailedBugzilla.md deleted file mode 100644 index 0982f5b..0000000 --- a/apollo/rhsecurity/docs/CVEDetailedBugzilla.md +++ /dev/null @@ -1,93 +0,0 @@ -# CVEDetailedBugzilla - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Description** | **string** | | -**Id** | **string** | | -**Url** | **string** | | - -## Methods - -### NewCVEDetailedBugzilla - -`func NewCVEDetailedBugzilla(description string, id string, url string, ) *CVEDetailedBugzilla` - -NewCVEDetailedBugzilla instantiates a new CVEDetailedBugzilla object -This constructor will assign default values to properties that have it defined, -and makes sure properties required by API are set, but the set of arguments -will change when the set of required properties is changed - -### NewCVEDetailedBugzillaWithDefaults - -`func NewCVEDetailedBugzillaWithDefaults() *CVEDetailedBugzilla` - -NewCVEDetailedBugzillaWithDefaults instantiates a new CVEDetailedBugzilla object -This constructor will only assign default values to properties that have it defined, -but it doesn't guarantee that properties required by API are set - -### GetDescription - -`func (o *CVEDetailedBugzilla) GetDescription() string` - -GetDescription returns the Description field if non-nil, zero value otherwise. - -### GetDescriptionOk - -`func (o *CVEDetailedBugzilla) GetDescriptionOk() (*string, bool)` - -GetDescriptionOk returns a tuple with the Description field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetDescription - -`func (o *CVEDetailedBugzilla) SetDescription(v string)` - -SetDescription sets Description field to given value. - - -### GetId - -`func (o *CVEDetailedBugzilla) GetId() string` - -GetId returns the Id field if non-nil, zero value otherwise. - -### GetIdOk - -`func (o *CVEDetailedBugzilla) GetIdOk() (*string, bool)` - -GetIdOk returns a tuple with the Id field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetId - -`func (o *CVEDetailedBugzilla) SetId(v string)` - -SetId sets Id field to given value. - - -### GetUrl - -`func (o *CVEDetailedBugzilla) GetUrl() string` - -GetUrl returns the Url field if non-nil, zero value otherwise. - -### GetUrlOk - -`func (o *CVEDetailedBugzilla) GetUrlOk() (*string, bool)` - -GetUrlOk returns a tuple with the Url field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetUrl - -`func (o *CVEDetailedBugzilla) SetUrl(v string)` - -SetUrl sets Url field to given value. - - - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/apollo/rhsecurity/docs/CVEDetailedCvss3.md b/apollo/rhsecurity/docs/CVEDetailedCvss3.md deleted file mode 100644 index 0c4f18b..0000000 --- a/apollo/rhsecurity/docs/CVEDetailedCvss3.md +++ /dev/null @@ -1,93 +0,0 @@ -# CVEDetailedCvss3 - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Cvss3BaseScore** | **string** | | -**Cvss3ScoringVector** | **string** | | -**Status** | **string** | | - -## Methods - -### NewCVEDetailedCvss3 - -`func NewCVEDetailedCvss3(cvss3BaseScore string, cvss3ScoringVector string, status string, ) *CVEDetailedCvss3` - -NewCVEDetailedCvss3 instantiates a new CVEDetailedCvss3 object -This constructor will assign default values to properties that have it defined, -and makes sure properties required by API are set, but the set of arguments -will change when the set of required properties is changed - -### NewCVEDetailedCvss3WithDefaults - -`func NewCVEDetailedCvss3WithDefaults() *CVEDetailedCvss3` - -NewCVEDetailedCvss3WithDefaults instantiates a new CVEDetailedCvss3 object -This constructor will only assign default values to properties that have it defined, -but it doesn't guarantee that properties required by API are set - -### GetCvss3BaseScore - -`func (o *CVEDetailedCvss3) GetCvss3BaseScore() string` - -GetCvss3BaseScore returns the Cvss3BaseScore field if non-nil, zero value otherwise. - -### GetCvss3BaseScoreOk - -`func (o *CVEDetailedCvss3) GetCvss3BaseScoreOk() (*string, bool)` - -GetCvss3BaseScoreOk returns a tuple with the Cvss3BaseScore field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetCvss3BaseScore - -`func (o *CVEDetailedCvss3) SetCvss3BaseScore(v string)` - -SetCvss3BaseScore sets Cvss3BaseScore field to given value. - - -### GetCvss3ScoringVector - -`func (o *CVEDetailedCvss3) GetCvss3ScoringVector() string` - -GetCvss3ScoringVector returns the Cvss3ScoringVector field if non-nil, zero value otherwise. - -### GetCvss3ScoringVectorOk - -`func (o *CVEDetailedCvss3) GetCvss3ScoringVectorOk() (*string, bool)` - -GetCvss3ScoringVectorOk returns a tuple with the Cvss3ScoringVector field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetCvss3ScoringVector - -`func (o *CVEDetailedCvss3) SetCvss3ScoringVector(v string)` - -SetCvss3ScoringVector sets Cvss3ScoringVector field to given value. - - -### GetStatus - -`func (o *CVEDetailedCvss3) GetStatus() string` - -GetStatus returns the Status field if non-nil, zero value otherwise. - -### GetStatusOk - -`func (o *CVEDetailedCvss3) GetStatusOk() (*string, bool)` - -GetStatusOk returns a tuple with the Status field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetStatus - -`func (o *CVEDetailedCvss3) SetStatus(v string)` - -SetStatus sets Status field to given value. - - - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/apollo/rhsecurity/docs/CVEDetailedPackageState.md b/apollo/rhsecurity/docs/CVEDetailedPackageState.md deleted file mode 100644 index 9e76dc8..0000000 --- a/apollo/rhsecurity/docs/CVEDetailedPackageState.md +++ /dev/null @@ -1,114 +0,0 @@ -# CVEDetailedPackageState - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**ProductName** | **string** | | -**FixState** | **string** | | -**PackageName** | **string** | | -**Cpe** | **string** | | - -## Methods - -### NewCVEDetailedPackageState - -`func NewCVEDetailedPackageState(productName string, fixState string, packageName string, cpe string, ) *CVEDetailedPackageState` - -NewCVEDetailedPackageState instantiates a new CVEDetailedPackageState object -This constructor will assign default values to properties that have it defined, -and makes sure properties required by API are set, but the set of arguments -will change when the set of required properties is changed - -### NewCVEDetailedPackageStateWithDefaults - -`func NewCVEDetailedPackageStateWithDefaults() *CVEDetailedPackageState` - -NewCVEDetailedPackageStateWithDefaults instantiates a new CVEDetailedPackageState object -This constructor will only assign default values to properties that have it defined, -but it doesn't guarantee that properties required by API are set - -### GetProductName - -`func (o *CVEDetailedPackageState) GetProductName() string` - -GetProductName returns the ProductName field if non-nil, zero value otherwise. - -### GetProductNameOk - -`func (o *CVEDetailedPackageState) GetProductNameOk() (*string, bool)` - -GetProductNameOk returns a tuple with the ProductName field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetProductName - -`func (o *CVEDetailedPackageState) SetProductName(v string)` - -SetProductName sets ProductName field to given value. - - -### GetFixState - -`func (o *CVEDetailedPackageState) GetFixState() string` - -GetFixState returns the FixState field if non-nil, zero value otherwise. - -### GetFixStateOk - -`func (o *CVEDetailedPackageState) GetFixStateOk() (*string, bool)` - -GetFixStateOk returns a tuple with the FixState field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetFixState - -`func (o *CVEDetailedPackageState) SetFixState(v string)` - -SetFixState sets FixState field to given value. - - -### GetPackageName - -`func (o *CVEDetailedPackageState) GetPackageName() string` - -GetPackageName returns the PackageName field if non-nil, zero value otherwise. - -### GetPackageNameOk - -`func (o *CVEDetailedPackageState) GetPackageNameOk() (*string, bool)` - -GetPackageNameOk returns a tuple with the PackageName field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetPackageName - -`func (o *CVEDetailedPackageState) SetPackageName(v string)` - -SetPackageName sets PackageName field to given value. - - -### GetCpe - -`func (o *CVEDetailedPackageState) GetCpe() string` - -GetCpe returns the Cpe field if non-nil, zero value otherwise. - -### GetCpeOk - -`func (o *CVEDetailedPackageState) GetCpeOk() (*string, bool)` - -GetCpeOk returns a tuple with the Cpe field if it's non-nil, zero value otherwise -and a boolean to check if the value has been set. - -### SetCpe - -`func (o *CVEDetailedPackageState) SetCpe(v string)` - -SetCpe sets Cpe field to given value. - - - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/apollo/rhsecurity/docs/DefaultApi.md b/apollo/rhsecurity/docs/DefaultApi.md deleted file mode 100644 index 8d8cfec..0000000 --- a/apollo/rhsecurity/docs/DefaultApi.md +++ /dev/null @@ -1,173 +0,0 @@ -# \DefaultApi - -All URIs are relative to *https://access.redhat.com/hydra/rest/securitydata* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**GetCve**](DefaultApi.md#GetCve) | **Get** /cve/{CVE}.json | Get specific CVE -[**GetCves**](DefaultApi.md#GetCves) | **Get** /cve.json | Get CVEs - - - -## GetCve - -> CVEDetailed GetCve(ctx, cVE).Execute() - -Get specific CVE - - - -### Example - -```go -package main - -import ( - "context" - "fmt" - "os" - openapiclient "./openapi" -) - -func main() { - cVE := "cVE_example" // string | - - configuration := openapiclient.NewConfiguration() - api_client := openapiclient.NewAPIClient(configuration) - resp, r, err := api_client.DefaultApi.GetCve(context.Background(), cVE).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `DefaultApi.GetCve``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `GetCve`: CVEDetailed - fmt.Fprintf(os.Stdout, "Response from `DefaultApi.GetCve`: %v\n", resp) -} -``` - -### Path Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. -**cVE** | **string** | | - -### Other Parameters - -Other parameters are passed through a pointer to a apiGetCveRequest struct via the builder pattern - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - - -### Return type - -[**CVEDetailed**](CVEDetailed.md) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) -[[Back to Model list]](../README.md#documentation-for-models) -[[Back to README]](../README.md) - - -## GetCves - -> []CVE GetCves(ctx).Before(before).After(after).Ids(ids).Bug(bug).Advisory(advisory).Severity(severity).Package_(package_).Product(product).Cwe(cwe).CvssScore(cvssScore).Cvss3Score(cvss3Score).Page(page).PerPage(perPage).CreatedDaysAgo(createdDaysAgo).Execute() - -Get CVEs - - - -### Example - -```go -package main - -import ( - "context" - "fmt" - "os" - "time" - openapiclient "./openapi" -) - -func main() { - before := time.Now() // string | CVEs before the query date. [ISO 8601 is the expected format] (optional) - after := time.Now() // string | CVEs after the query date. [ISO 8601 is the expected format] (optional) - ids := "ids_example" // string | CVEs for Ids separated by comma (optional) - bug := "bug_example" // string | CVEs for Bugzilla Ids (optional) - advisory := "advisory_example" // string | CVEs for advisory (optional) - severity := "severity_example" // string | CVEs for severity (optional) - package_ := "package__example" // string | CVEs which affect the package (optional) - product := "product_example" // string | CVEs which affect the product. The parameter supports Perl compatible regular expressions. (optional) - cwe := "cwe_example" // string | CVEs with CWE (optional) - cvssScore := float32(8.14) // float32 | CVEs with CVSS score greater than or equal to this value (optional) - cvss3Score := "cvss3Score_example" // string | CVEs with CVSSv3 score greater than or equal to this value (optional) - page := float32(8.14) // float32 | CVEs for page number (optional) - perPage := float32(8.14) // float32 | Number of CVEs to return per page (optional) - createdDaysAgo := float32(8.14) // float32 | Index of CVEs definitions created days ago (optional) - - configuration := openapiclient.NewConfiguration() - api_client := openapiclient.NewAPIClient(configuration) - resp, r, err := api_client.DefaultApi.GetCves(context.Background()).Before(before).After(after).Ids(ids).Bug(bug).Advisory(advisory).Severity(severity).Package_(package_).Product(product).Cwe(cwe).CvssScore(cvssScore).Cvss3Score(cvss3Score).Page(page).PerPage(perPage).CreatedDaysAgo(createdDaysAgo).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `DefaultApi.GetCves``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `GetCves`: []CVE - fmt.Fprintf(os.Stdout, "Response from `DefaultApi.GetCves`: %v\n", resp) -} -``` - -### Path Parameters - - - -### Other Parameters - -Other parameters are passed through a pointer to a apiGetCvesRequest struct via the builder pattern - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **before** | **string** | CVEs before the query date. [ISO 8601 is the expected format] | - **after** | **string** | CVEs after the query date. [ISO 8601 is the expected format] | - **ids** | **string** | CVEs for Ids separated by comma | - **bug** | **string** | CVEs for Bugzilla Ids | - **advisory** | **string** | CVEs for advisory | - **severity** | **string** | CVEs for severity | - **package_** | **string** | CVEs which affect the package | - **product** | **string** | CVEs which affect the product. The parameter supports Perl compatible regular expressions. | - **cwe** | **string** | CVEs with CWE | - **cvssScore** | **float32** | CVEs with CVSS score greater than or equal to this value | - **cvss3Score** | **string** | CVEs with CVSSv3 score greater than or equal to this value | - **page** | **float32** | CVEs for page number | - **perPage** | **float32** | Number of CVEs to return per page | - **createdDaysAgo** | **float32** | Index of CVEs definitions created days ago | - -### Return type - -[**[]CVE**](CVE.md) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) -[[Back to Model list]](../README.md#documentation-for-models) -[[Back to README]](../README.md) - diff --git a/apollo/rhsecurity/gen.go b/apollo/rhsecurity/gen.go deleted file mode 100644 index 98a664c..0000000 --- a/apollo/rhsecurity/gen.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -//go:generate openapi-gen . -g go -i ./Red-Hat-Security-Data-API.yaml --additional-properties=packageName=rhsecurity,generateInterfaces=true -package rhsecurity diff --git a/apollo/rhsecurity/model_cve.go b/apollo/rhsecurity/model_cve.go deleted file mode 100644 index 127615c..0000000 --- a/apollo/rhsecurity/model_cve.go +++ /dev/null @@ -1,469 +0,0 @@ -/* - * Red Hat Security Data API - * - * Unofficial OpenAPI definitions for Red Hat Security Data API - * - * API version: 1.0 - * Contact: mustafa@ctrliq.com - */ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package rhsecurity - -import ( - "encoding/json" -) - -// CVE CVE model used in listing -type CVE struct { - CVE string `json:"CVE"` - Severity string `json:"severity"` - PublicDate string `json:"public_date"` - Advisories []string `json:"advisories"` - Bugzilla string `json:"bugzilla"` - BugzillaDescription string `json:"bugzilla_description"` - CvssScore *float32 `json:"cvss_score,omitempty"` - CvssScoringVector *string `json:"cvss_scoring_vector,omitempty"` - CWE string `json:"CWE"` - AffectedPackages []string `json:"affected_packages"` - ResourceUrl string `json:"resource_url"` - Cvss3ScoringVector string `json:"cvss3_scoring_vector"` - Cvss3Score string `json:"cvss3_score"` -} - -// NewCVE instantiates a new CVE object -// This constructor will assign default values to properties that have it defined, -// and makes sure properties required by API are set, but the set of arguments -// will change when the set of required properties is changed -func NewCVE(cVE string, severity string, publicDate string, advisories []string, bugzilla string, bugzillaDescription string, cWE string, affectedPackages []string, resourceUrl string, cvss3ScoringVector string, cvss3Score string) *CVE { - this := CVE{} - this.CVE = cVE - this.Severity = severity - this.PublicDate = publicDate - this.Advisories = advisories - this.Bugzilla = bugzilla - this.BugzillaDescription = bugzillaDescription - this.CWE = cWE - this.AffectedPackages = affectedPackages - this.ResourceUrl = resourceUrl - this.Cvss3ScoringVector = cvss3ScoringVector - this.Cvss3Score = cvss3Score - return &this -} - -// NewCVEWithDefaults instantiates a new CVE object -// This constructor will only assign default values to properties that have it defined, -// but it doesn't guarantee that properties required by API are set -func NewCVEWithDefaults() *CVE { - this := CVE{} - return &this -} - -// GetCVE returns the CVE field value -func (o *CVE) GetCVE() string { - if o == nil { - var ret string - return ret - } - - return o.CVE -} - -// GetCVEOk returns a tuple with the CVE field value -// and a boolean to check if the value has been set. -func (o *CVE) GetCVEOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.CVE, true -} - -// SetCVE sets field value -func (o *CVE) SetCVE(v string) { - o.CVE = v -} - -// GetSeverity returns the Severity field value -func (o *CVE) GetSeverity() string { - if o == nil { - var ret string - return ret - } - - return o.Severity -} - -// GetSeverityOk returns a tuple with the Severity field value -// and a boolean to check if the value has been set. -func (o *CVE) GetSeverityOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.Severity, true -} - -// SetSeverity sets field value -func (o *CVE) SetSeverity(v string) { - o.Severity = v -} - -// GetPublicDate returns the PublicDate field value -func (o *CVE) GetPublicDate() string { - if o == nil { - var ret string - return ret - } - - return o.PublicDate -} - -// GetPublicDateOk returns a tuple with the PublicDate field value -// and a boolean to check if the value has been set. -func (o *CVE) GetPublicDateOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.PublicDate, true -} - -// SetPublicDate sets field value -func (o *CVE) SetPublicDate(v string) { - o.PublicDate = v -} - -// GetAdvisories returns the Advisories field value -func (o *CVE) GetAdvisories() []string { - if o == nil { - var ret []string - return ret - } - - return o.Advisories -} - -// GetAdvisoriesOk returns a tuple with the Advisories field value -// and a boolean to check if the value has been set. -func (o *CVE) GetAdvisoriesOk() (*[]string, bool) { - if o == nil { - return nil, false - } - return &o.Advisories, true -} - -// SetAdvisories sets field value -func (o *CVE) SetAdvisories(v []string) { - o.Advisories = v -} - -// GetBugzilla returns the Bugzilla field value -func (o *CVE) GetBugzilla() string { - if o == nil { - var ret string - return ret - } - - return o.Bugzilla -} - -// GetBugzillaOk returns a tuple with the Bugzilla field value -// and a boolean to check if the value has been set. -func (o *CVE) GetBugzillaOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.Bugzilla, true -} - -// SetBugzilla sets field value -func (o *CVE) SetBugzilla(v string) { - o.Bugzilla = v -} - -// GetBugzillaDescription returns the BugzillaDescription field value -func (o *CVE) GetBugzillaDescription() string { - if o == nil { - var ret string - return ret - } - - return o.BugzillaDescription -} - -// GetBugzillaDescriptionOk returns a tuple with the BugzillaDescription field value -// and a boolean to check if the value has been set. -func (o *CVE) GetBugzillaDescriptionOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.BugzillaDescription, true -} - -// SetBugzillaDescription sets field value -func (o *CVE) SetBugzillaDescription(v string) { - o.BugzillaDescription = v -} - -// GetCvssScore returns the CvssScore field value if set, zero value otherwise. -func (o *CVE) GetCvssScore() float32 { - if o == nil || o.CvssScore == nil { - var ret float32 - return ret - } - return *o.CvssScore -} - -// GetCvssScoreOk returns a tuple with the CvssScore field value if set, nil otherwise -// and a boolean to check if the value has been set. -func (o *CVE) GetCvssScoreOk() (*float32, bool) { - if o == nil || o.CvssScore == nil { - return nil, false - } - return o.CvssScore, true -} - -// HasCvssScore returns a boolean if a field has been set. -func (o *CVE) HasCvssScore() bool { - if o != nil && o.CvssScore != nil { - return true - } - - return false -} - -// SetCvssScore gets a reference to the given float32 and assigns it to the CvssScore field. -func (o *CVE) SetCvssScore(v float32) { - o.CvssScore = &v -} - -// GetCvssScoringVector returns the CvssScoringVector field value if set, zero value otherwise. -func (o *CVE) GetCvssScoringVector() string { - if o == nil || o.CvssScoringVector == nil { - var ret string - return ret - } - return *o.CvssScoringVector -} - -// GetCvssScoringVectorOk returns a tuple with the CvssScoringVector field value if set, nil otherwise -// and a boolean to check if the value has been set. -func (o *CVE) GetCvssScoringVectorOk() (*string, bool) { - if o == nil || o.CvssScoringVector == nil { - return nil, false - } - return o.CvssScoringVector, true -} - -// HasCvssScoringVector returns a boolean if a field has been set. -func (o *CVE) HasCvssScoringVector() bool { - if o != nil && o.CvssScoringVector != nil { - return true - } - - return false -} - -// SetCvssScoringVector gets a reference to the given string and assigns it to the CvssScoringVector field. -func (o *CVE) SetCvssScoringVector(v string) { - o.CvssScoringVector = &v -} - -// GetCWE returns the CWE field value -func (o *CVE) GetCWE() string { - if o == nil { - var ret string - return ret - } - - return o.CWE -} - -// GetCWEOk returns a tuple with the CWE field value -// and a boolean to check if the value has been set. -func (o *CVE) GetCWEOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.CWE, true -} - -// SetCWE sets field value -func (o *CVE) SetCWE(v string) { - o.CWE = v -} - -// GetAffectedPackages returns the AffectedPackages field value -func (o *CVE) GetAffectedPackages() []string { - if o == nil { - var ret []string - return ret - } - - return o.AffectedPackages -} - -// GetAffectedPackagesOk returns a tuple with the AffectedPackages field value -// and a boolean to check if the value has been set. -func (o *CVE) GetAffectedPackagesOk() (*[]string, bool) { - if o == nil { - return nil, false - } - return &o.AffectedPackages, true -} - -// SetAffectedPackages sets field value -func (o *CVE) SetAffectedPackages(v []string) { - o.AffectedPackages = v -} - -// GetResourceUrl returns the ResourceUrl field value -func (o *CVE) GetResourceUrl() string { - if o == nil { - var ret string - return ret - } - - return o.ResourceUrl -} - -// GetResourceUrlOk returns a tuple with the ResourceUrl field value -// and a boolean to check if the value has been set. -func (o *CVE) GetResourceUrlOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.ResourceUrl, true -} - -// SetResourceUrl sets field value -func (o *CVE) SetResourceUrl(v string) { - o.ResourceUrl = v -} - -// GetCvss3ScoringVector returns the Cvss3ScoringVector field value -func (o *CVE) GetCvss3ScoringVector() string { - if o == nil { - var ret string - return ret - } - - return o.Cvss3ScoringVector -} - -// GetCvss3ScoringVectorOk returns a tuple with the Cvss3ScoringVector field value -// and a boolean to check if the value has been set. -func (o *CVE) GetCvss3ScoringVectorOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.Cvss3ScoringVector, true -} - -// SetCvss3ScoringVector sets field value -func (o *CVE) SetCvss3ScoringVector(v string) { - o.Cvss3ScoringVector = v -} - -// GetCvss3Score returns the Cvss3Score field value -func (o *CVE) GetCvss3Score() string { - if o == nil { - var ret string - return ret - } - - return o.Cvss3Score -} - -// GetCvss3ScoreOk returns a tuple with the Cvss3Score field value -// and a boolean to check if the value has been set. -func (o *CVE) GetCvss3ScoreOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.Cvss3Score, true -} - -// SetCvss3Score sets field value -func (o *CVE) SetCvss3Score(v string) { - o.Cvss3Score = v -} - -func (o CVE) MarshalJSON() ([]byte, error) { - toSerialize := map[string]interface{}{} - if true { - toSerialize["CVE"] = o.CVE - } - if true { - toSerialize["severity"] = o.Severity - } - if true { - toSerialize["public_date"] = o.PublicDate - } - if true { - toSerialize["advisories"] = o.Advisories - } - if true { - toSerialize["bugzilla"] = o.Bugzilla - } - if true { - toSerialize["bugzilla_description"] = o.BugzillaDescription - } - if o.CvssScore != nil { - toSerialize["cvss_score"] = o.CvssScore - } - if o.CvssScoringVector != nil { - toSerialize["cvss_scoring_vector"] = o.CvssScoringVector - } - if true { - toSerialize["CWE"] = o.CWE - } - if true { - toSerialize["affected_packages"] = o.AffectedPackages - } - if true { - toSerialize["resource_url"] = o.ResourceUrl - } - if true { - toSerialize["cvss3_scoring_vector"] = o.Cvss3ScoringVector - } - if true { - toSerialize["cvss3_score"] = o.Cvss3Score - } - return json.Marshal(toSerialize) -} - -type NullableCVE struct { - value *CVE - isSet bool -} - -func (v NullableCVE) Get() *CVE { - return v.value -} - -func (v *NullableCVE) Set(val *CVE) { - v.value = val - v.isSet = true -} - -func (v NullableCVE) IsSet() bool { - return v.isSet -} - -func (v *NullableCVE) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableCVE(val *CVE) *NullableCVE { - return &NullableCVE{value: val, isSet: true} -} - -func (v NullableCVE) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableCVE) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} diff --git a/apollo/rhsecurity/model_cve_detailed.go b/apollo/rhsecurity/model_cve_detailed.go deleted file mode 100644 index 9b9dd1f..0000000 --- a/apollo/rhsecurity/model_cve_detailed.go +++ /dev/null @@ -1,411 +0,0 @@ -/* - * Red Hat Security Data API - * - * Unofficial OpenAPI definitions for Red Hat Security Data API - * - * API version: 1.0 - * Contact: mustafa@ctrliq.com - */ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package rhsecurity - -import ( - "encoding/json" -) - -// CVEDetailed CVE model used when retrieving a specific CVE -type CVEDetailed struct { - ThreatSeverity string `json:"threat_severity"` - PublicDate string `json:"public_date"` - Bugzilla CVEDetailedBugzilla `json:"bugzilla"` - Cvss3 CVEDetailedCvss3 `json:"cvss3"` - Cwe string `json:"cwe"` - Details []string `json:"details"` - Acknowledgement string `json:"acknowledgement"` - AffectedRelease *[]CVEDetailedAffectedRelease `json:"affected_release,omitempty"` - Name string `json:"name"` - Csaw bool `json:"csaw"` - PackageState *[]CVEDetailedPackageState `json:"package_state,omitempty"` -} - -// NewCVEDetailed instantiates a new CVEDetailed object -// This constructor will assign default values to properties that have it defined, -// and makes sure properties required by API are set, but the set of arguments -// will change when the set of required properties is changed -func NewCVEDetailed(threatSeverity string, publicDate string, bugzilla CVEDetailedBugzilla, cvss3 CVEDetailedCvss3, cwe string, details []string, acknowledgement string, name string, csaw bool) *CVEDetailed { - this := CVEDetailed{} - this.ThreatSeverity = threatSeverity - this.PublicDate = publicDate - this.Bugzilla = bugzilla - this.Cvss3 = cvss3 - this.Cwe = cwe - this.Details = details - this.Acknowledgement = acknowledgement - this.Name = name - this.Csaw = csaw - return &this -} - -// NewCVEDetailedWithDefaults instantiates a new CVEDetailed object -// This constructor will only assign default values to properties that have it defined, -// but it doesn't guarantee that properties required by API are set -func NewCVEDetailedWithDefaults() *CVEDetailed { - this := CVEDetailed{} - return &this -} - -// GetThreatSeverity returns the ThreatSeverity field value -func (o *CVEDetailed) GetThreatSeverity() string { - if o == nil { - var ret string - return ret - } - - return o.ThreatSeverity -} - -// GetThreatSeverityOk returns a tuple with the ThreatSeverity field value -// and a boolean to check if the value has been set. -func (o *CVEDetailed) GetThreatSeverityOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.ThreatSeverity, true -} - -// SetThreatSeverity sets field value -func (o *CVEDetailed) SetThreatSeverity(v string) { - o.ThreatSeverity = v -} - -// GetPublicDate returns the PublicDate field value -func (o *CVEDetailed) GetPublicDate() string { - if o == nil { - var ret string - return ret - } - - return o.PublicDate -} - -// GetPublicDateOk returns a tuple with the PublicDate field value -// and a boolean to check if the value has been set. -func (o *CVEDetailed) GetPublicDateOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.PublicDate, true -} - -// SetPublicDate sets field value -func (o *CVEDetailed) SetPublicDate(v string) { - o.PublicDate = v -} - -// GetBugzilla returns the Bugzilla field value -func (o *CVEDetailed) GetBugzilla() CVEDetailedBugzilla { - if o == nil { - var ret CVEDetailedBugzilla - return ret - } - - return o.Bugzilla -} - -// GetBugzillaOk returns a tuple with the Bugzilla field value -// and a boolean to check if the value has been set. -func (o *CVEDetailed) GetBugzillaOk() (*CVEDetailedBugzilla, bool) { - if o == nil { - return nil, false - } - return &o.Bugzilla, true -} - -// SetBugzilla sets field value -func (o *CVEDetailed) SetBugzilla(v CVEDetailedBugzilla) { - o.Bugzilla = v -} - -// GetCvss3 returns the Cvss3 field value -func (o *CVEDetailed) GetCvss3() CVEDetailedCvss3 { - if o == nil { - var ret CVEDetailedCvss3 - return ret - } - - return o.Cvss3 -} - -// GetCvss3Ok returns a tuple with the Cvss3 field value -// and a boolean to check if the value has been set. -func (o *CVEDetailed) GetCvss3Ok() (*CVEDetailedCvss3, bool) { - if o == nil { - return nil, false - } - return &o.Cvss3, true -} - -// SetCvss3 sets field value -func (o *CVEDetailed) SetCvss3(v CVEDetailedCvss3) { - o.Cvss3 = v -} - -// GetCwe returns the Cwe field value -func (o *CVEDetailed) GetCwe() string { - if o == nil { - var ret string - return ret - } - - return o.Cwe -} - -// GetCweOk returns a tuple with the Cwe field value -// and a boolean to check if the value has been set. -func (o *CVEDetailed) GetCweOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.Cwe, true -} - -// SetCwe sets field value -func (o *CVEDetailed) SetCwe(v string) { - o.Cwe = v -} - -// GetDetails returns the Details field value -func (o *CVEDetailed) GetDetails() []string { - if o == nil { - var ret []string - return ret - } - - return o.Details -} - -// GetDetailsOk returns a tuple with the Details field value -// and a boolean to check if the value has been set. -func (o *CVEDetailed) GetDetailsOk() (*[]string, bool) { - if o == nil { - return nil, false - } - return &o.Details, true -} - -// SetDetails sets field value -func (o *CVEDetailed) SetDetails(v []string) { - o.Details = v -} - -// GetAcknowledgement returns the Acknowledgement field value -func (o *CVEDetailed) GetAcknowledgement() string { - if o == nil { - var ret string - return ret - } - - return o.Acknowledgement -} - -// GetAcknowledgementOk returns a tuple with the Acknowledgement field value -// and a boolean to check if the value has been set. -func (o *CVEDetailed) GetAcknowledgementOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.Acknowledgement, true -} - -// SetAcknowledgement sets field value -func (o *CVEDetailed) SetAcknowledgement(v string) { - o.Acknowledgement = v -} - -// GetAffectedRelease returns the AffectedRelease field value if set, zero value otherwise. -func (o *CVEDetailed) GetAffectedRelease() []CVEDetailedAffectedRelease { - if o == nil || o.AffectedRelease == nil { - var ret []CVEDetailedAffectedRelease - return ret - } - return *o.AffectedRelease -} - -// GetAffectedReleaseOk returns a tuple with the AffectedRelease field value if set, nil otherwise -// and a boolean to check if the value has been set. -func (o *CVEDetailed) GetAffectedReleaseOk() (*[]CVEDetailedAffectedRelease, bool) { - if o == nil || o.AffectedRelease == nil { - return nil, false - } - return o.AffectedRelease, true -} - -// HasAffectedRelease returns a boolean if a field has been set. -func (o *CVEDetailed) HasAffectedRelease() bool { - if o != nil && o.AffectedRelease != nil { - return true - } - - return false -} - -// SetAffectedRelease gets a reference to the given []CVEDetailedAffectedRelease and assigns it to the AffectedRelease field. -func (o *CVEDetailed) SetAffectedRelease(v []CVEDetailedAffectedRelease) { - o.AffectedRelease = &v -} - -// GetName returns the Name field value -func (o *CVEDetailed) GetName() string { - if o == nil { - var ret string - return ret - } - - return o.Name -} - -// GetNameOk returns a tuple with the Name field value -// and a boolean to check if the value has been set. -func (o *CVEDetailed) GetNameOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.Name, true -} - -// SetName sets field value -func (o *CVEDetailed) SetName(v string) { - o.Name = v -} - -// GetCsaw returns the Csaw field value -func (o *CVEDetailed) GetCsaw() bool { - if o == nil { - var ret bool - return ret - } - - return o.Csaw -} - -// GetCsawOk returns a tuple with the Csaw field value -// and a boolean to check if the value has been set. -func (o *CVEDetailed) GetCsawOk() (*bool, bool) { - if o == nil { - return nil, false - } - return &o.Csaw, true -} - -// SetCsaw sets field value -func (o *CVEDetailed) SetCsaw(v bool) { - o.Csaw = v -} - -// GetPackageState returns the PackageState field value if set, zero value otherwise. -func (o *CVEDetailed) GetPackageState() []CVEDetailedPackageState { - if o == nil || o.PackageState == nil { - var ret []CVEDetailedPackageState - return ret - } - return *o.PackageState -} - -// GetPackageStateOk returns a tuple with the PackageState field value if set, nil otherwise -// and a boolean to check if the value has been set. -func (o *CVEDetailed) GetPackageStateOk() (*[]CVEDetailedPackageState, bool) { - if o == nil || o.PackageState == nil { - return nil, false - } - return o.PackageState, true -} - -// HasPackageState returns a boolean if a field has been set. -func (o *CVEDetailed) HasPackageState() bool { - if o != nil && o.PackageState != nil { - return true - } - - return false -} - -// SetPackageState gets a reference to the given []CVEDetailedPackageState and assigns it to the PackageState field. -func (o *CVEDetailed) SetPackageState(v []CVEDetailedPackageState) { - o.PackageState = &v -} - -func (o CVEDetailed) MarshalJSON() ([]byte, error) { - toSerialize := map[string]interface{}{} - if true { - toSerialize["threat_severity"] = o.ThreatSeverity - } - if true { - toSerialize["public_date"] = o.PublicDate - } - if true { - toSerialize["bugzilla"] = o.Bugzilla - } - if true { - toSerialize["cvss3"] = o.Cvss3 - } - if true { - toSerialize["cwe"] = o.Cwe - } - if true { - toSerialize["details"] = o.Details - } - if true { - toSerialize["acknowledgement"] = o.Acknowledgement - } - if o.AffectedRelease != nil { - toSerialize["affected_release"] = o.AffectedRelease - } - if true { - toSerialize["name"] = o.Name - } - if true { - toSerialize["csaw"] = o.Csaw - } - if o.PackageState != nil { - toSerialize["package_state"] = o.PackageState - } - return json.Marshal(toSerialize) -} - -type NullableCVEDetailed struct { - value *CVEDetailed - isSet bool -} - -func (v NullableCVEDetailed) Get() *CVEDetailed { - return v.value -} - -func (v *NullableCVEDetailed) Set(val *CVEDetailed) { - v.value = val - v.isSet = true -} - -func (v NullableCVEDetailed) IsSet() bool { - return v.isSet -} - -func (v *NullableCVEDetailed) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableCVEDetailed(val *CVEDetailed) *NullableCVEDetailed { - return &NullableCVEDetailed{value: val, isSet: true} -} - -func (v NullableCVEDetailed) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableCVEDetailed) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} diff --git a/apollo/rhsecurity/model_cve_detailed_affected_release.go b/apollo/rhsecurity/model_cve_detailed_affected_release.go deleted file mode 100644 index 247a46e..0000000 --- a/apollo/rhsecurity/model_cve_detailed_affected_release.go +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Red Hat Security Data API - * - * Unofficial OpenAPI definitions for Red Hat Security Data API - * - * API version: 1.0 - * Contact: mustafa@ctrliq.com - */ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package rhsecurity - -import ( - "encoding/json" -) - -// CVEDetailedAffectedRelease struct for CVEDetailedAffectedRelease -type CVEDetailedAffectedRelease struct { - ProductName string `json:"product_name"` - ReleaseDate string `json:"release_date"` - Advisory string `json:"advisory"` - Cpe string `json:"cpe"` - Package *string `json:"package,omitempty"` -} - -// NewCVEDetailedAffectedRelease instantiates a new CVEDetailedAffectedRelease object -// This constructor will assign default values to properties that have it defined, -// and makes sure properties required by API are set, but the set of arguments -// will change when the set of required properties is changed -func NewCVEDetailedAffectedRelease(productName string, releaseDate string, advisory string, cpe string) *CVEDetailedAffectedRelease { - this := CVEDetailedAffectedRelease{} - this.ProductName = productName - this.ReleaseDate = releaseDate - this.Advisory = advisory - this.Cpe = cpe - return &this -} - -// NewCVEDetailedAffectedReleaseWithDefaults instantiates a new CVEDetailedAffectedRelease object -// This constructor will only assign default values to properties that have it defined, -// but it doesn't guarantee that properties required by API are set -func NewCVEDetailedAffectedReleaseWithDefaults() *CVEDetailedAffectedRelease { - this := CVEDetailedAffectedRelease{} - return &this -} - -// GetProductName returns the ProductName field value -func (o *CVEDetailedAffectedRelease) GetProductName() string { - if o == nil { - var ret string - return ret - } - - return o.ProductName -} - -// GetProductNameOk returns a tuple with the ProductName field value -// and a boolean to check if the value has been set. -func (o *CVEDetailedAffectedRelease) GetProductNameOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.ProductName, true -} - -// SetProductName sets field value -func (o *CVEDetailedAffectedRelease) SetProductName(v string) { - o.ProductName = v -} - -// GetReleaseDate returns the ReleaseDate field value -func (o *CVEDetailedAffectedRelease) GetReleaseDate() string { - if o == nil { - var ret string - return ret - } - - return o.ReleaseDate -} - -// GetReleaseDateOk returns a tuple with the ReleaseDate field value -// and a boolean to check if the value has been set. -func (o *CVEDetailedAffectedRelease) GetReleaseDateOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.ReleaseDate, true -} - -// SetReleaseDate sets field value -func (o *CVEDetailedAffectedRelease) SetReleaseDate(v string) { - o.ReleaseDate = v -} - -// GetAdvisory returns the Advisory field value -func (o *CVEDetailedAffectedRelease) GetAdvisory() string { - if o == nil { - var ret string - return ret - } - - return o.Advisory -} - -// GetAdvisoryOk returns a tuple with the Advisory field value -// and a boolean to check if the value has been set. -func (o *CVEDetailedAffectedRelease) GetAdvisoryOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.Advisory, true -} - -// SetAdvisory sets field value -func (o *CVEDetailedAffectedRelease) SetAdvisory(v string) { - o.Advisory = v -} - -// GetCpe returns the Cpe field value -func (o *CVEDetailedAffectedRelease) GetCpe() string { - if o == nil { - var ret string - return ret - } - - return o.Cpe -} - -// GetCpeOk returns a tuple with the Cpe field value -// and a boolean to check if the value has been set. -func (o *CVEDetailedAffectedRelease) GetCpeOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.Cpe, true -} - -// SetCpe sets field value -func (o *CVEDetailedAffectedRelease) SetCpe(v string) { - o.Cpe = v -} - -// GetPackage returns the Package field value if set, zero value otherwise. -func (o *CVEDetailedAffectedRelease) GetPackage() string { - if o == nil || o.Package == nil { - var ret string - return ret - } - return *o.Package -} - -// GetPackageOk returns a tuple with the Package field value if set, nil otherwise -// and a boolean to check if the value has been set. -func (o *CVEDetailedAffectedRelease) GetPackageOk() (*string, bool) { - if o == nil || o.Package == nil { - return nil, false - } - return o.Package, true -} - -// HasPackage returns a boolean if a field has been set. -func (o *CVEDetailedAffectedRelease) HasPackage() bool { - if o != nil && o.Package != nil { - return true - } - - return false -} - -// SetPackage gets a reference to the given string and assigns it to the Package field. -func (o *CVEDetailedAffectedRelease) SetPackage(v string) { - o.Package = &v -} - -func (o CVEDetailedAffectedRelease) MarshalJSON() ([]byte, error) { - toSerialize := map[string]interface{}{} - if true { - toSerialize["product_name"] = o.ProductName - } - if true { - toSerialize["release_date"] = o.ReleaseDate - } - if true { - toSerialize["advisory"] = o.Advisory - } - if true { - toSerialize["cpe"] = o.Cpe - } - if o.Package != nil { - toSerialize["package"] = o.Package - } - return json.Marshal(toSerialize) -} - -type NullableCVEDetailedAffectedRelease struct { - value *CVEDetailedAffectedRelease - isSet bool -} - -func (v NullableCVEDetailedAffectedRelease) Get() *CVEDetailedAffectedRelease { - return v.value -} - -func (v *NullableCVEDetailedAffectedRelease) Set(val *CVEDetailedAffectedRelease) { - v.value = val - v.isSet = true -} - -func (v NullableCVEDetailedAffectedRelease) IsSet() bool { - return v.isSet -} - -func (v *NullableCVEDetailedAffectedRelease) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableCVEDetailedAffectedRelease(val *CVEDetailedAffectedRelease) *NullableCVEDetailedAffectedRelease { - return &NullableCVEDetailedAffectedRelease{value: val, isSet: true} -} - -func (v NullableCVEDetailedAffectedRelease) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableCVEDetailedAffectedRelease) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} diff --git a/apollo/rhsecurity/model_cve_detailed_bugzilla.go b/apollo/rhsecurity/model_cve_detailed_bugzilla.go deleted file mode 100644 index 01ca853..0000000 --- a/apollo/rhsecurity/model_cve_detailed_bugzilla.go +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Red Hat Security Data API - * - * Unofficial OpenAPI definitions for Red Hat Security Data API - * - * API version: 1.0 - * Contact: mustafa@ctrliq.com - */ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package rhsecurity - -import ( - "encoding/json" -) - -// CVEDetailedBugzilla struct for CVEDetailedBugzilla -type CVEDetailedBugzilla struct { - Description string `json:"description"` - Id string `json:"id"` - Url string `json:"url"` -} - -// NewCVEDetailedBugzilla instantiates a new CVEDetailedBugzilla object -// This constructor will assign default values to properties that have it defined, -// and makes sure properties required by API are set, but the set of arguments -// will change when the set of required properties is changed -func NewCVEDetailedBugzilla(description string, id string, url string) *CVEDetailedBugzilla { - this := CVEDetailedBugzilla{} - this.Description = description - this.Id = id - this.Url = url - return &this -} - -// NewCVEDetailedBugzillaWithDefaults instantiates a new CVEDetailedBugzilla object -// This constructor will only assign default values to properties that have it defined, -// but it doesn't guarantee that properties required by API are set -func NewCVEDetailedBugzillaWithDefaults() *CVEDetailedBugzilla { - this := CVEDetailedBugzilla{} - return &this -} - -// GetDescription returns the Description field value -func (o *CVEDetailedBugzilla) GetDescription() string { - if o == nil { - var ret string - return ret - } - - return o.Description -} - -// GetDescriptionOk returns a tuple with the Description field value -// and a boolean to check if the value has been set. -func (o *CVEDetailedBugzilla) GetDescriptionOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.Description, true -} - -// SetDescription sets field value -func (o *CVEDetailedBugzilla) SetDescription(v string) { - o.Description = v -} - -// GetId returns the Id field value -func (o *CVEDetailedBugzilla) GetId() string { - if o == nil { - var ret string - return ret - } - - return o.Id -} - -// GetIdOk returns a tuple with the Id field value -// and a boolean to check if the value has been set. -func (o *CVEDetailedBugzilla) GetIdOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.Id, true -} - -// SetId sets field value -func (o *CVEDetailedBugzilla) SetId(v string) { - o.Id = v -} - -// GetUrl returns the Url field value -func (o *CVEDetailedBugzilla) GetUrl() string { - if o == nil { - var ret string - return ret - } - - return o.Url -} - -// GetUrlOk returns a tuple with the Url field value -// and a boolean to check if the value has been set. -func (o *CVEDetailedBugzilla) GetUrlOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.Url, true -} - -// SetUrl sets field value -func (o *CVEDetailedBugzilla) SetUrl(v string) { - o.Url = v -} - -func (o CVEDetailedBugzilla) MarshalJSON() ([]byte, error) { - toSerialize := map[string]interface{}{} - if true { - toSerialize["description"] = o.Description - } - if true { - toSerialize["id"] = o.Id - } - if true { - toSerialize["url"] = o.Url - } - return json.Marshal(toSerialize) -} - -type NullableCVEDetailedBugzilla struct { - value *CVEDetailedBugzilla - isSet bool -} - -func (v NullableCVEDetailedBugzilla) Get() *CVEDetailedBugzilla { - return v.value -} - -func (v *NullableCVEDetailedBugzilla) Set(val *CVEDetailedBugzilla) { - v.value = val - v.isSet = true -} - -func (v NullableCVEDetailedBugzilla) IsSet() bool { - return v.isSet -} - -func (v *NullableCVEDetailedBugzilla) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableCVEDetailedBugzilla(val *CVEDetailedBugzilla) *NullableCVEDetailedBugzilla { - return &NullableCVEDetailedBugzilla{value: val, isSet: true} -} - -func (v NullableCVEDetailedBugzilla) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableCVEDetailedBugzilla) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} diff --git a/apollo/rhsecurity/model_cve_detailed_cvss3.go b/apollo/rhsecurity/model_cve_detailed_cvss3.go deleted file mode 100644 index 8402bc2..0000000 --- a/apollo/rhsecurity/model_cve_detailed_cvss3.go +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Red Hat Security Data API - * - * Unofficial OpenAPI definitions for Red Hat Security Data API - * - * API version: 1.0 - * Contact: mustafa@ctrliq.com - */ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package rhsecurity - -import ( - "encoding/json" -) - -// CVEDetailedCvss3 struct for CVEDetailedCvss3 -type CVEDetailedCvss3 struct { - Cvss3BaseScore string `json:"cvss3_base_score"` - Cvss3ScoringVector string `json:"cvss3_scoring_vector"` - Status string `json:"status"` -} - -// NewCVEDetailedCvss3 instantiates a new CVEDetailedCvss3 object -// This constructor will assign default values to properties that have it defined, -// and makes sure properties required by API are set, but the set of arguments -// will change when the set of required properties is changed -func NewCVEDetailedCvss3(cvss3BaseScore string, cvss3ScoringVector string, status string) *CVEDetailedCvss3 { - this := CVEDetailedCvss3{} - this.Cvss3BaseScore = cvss3BaseScore - this.Cvss3ScoringVector = cvss3ScoringVector - this.Status = status - return &this -} - -// NewCVEDetailedCvss3WithDefaults instantiates a new CVEDetailedCvss3 object -// This constructor will only assign default values to properties that have it defined, -// but it doesn't guarantee that properties required by API are set -func NewCVEDetailedCvss3WithDefaults() *CVEDetailedCvss3 { - this := CVEDetailedCvss3{} - return &this -} - -// GetCvss3BaseScore returns the Cvss3BaseScore field value -func (o *CVEDetailedCvss3) GetCvss3BaseScore() string { - if o == nil { - var ret string - return ret - } - - return o.Cvss3BaseScore -} - -// GetCvss3BaseScoreOk returns a tuple with the Cvss3BaseScore field value -// and a boolean to check if the value has been set. -func (o *CVEDetailedCvss3) GetCvss3BaseScoreOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.Cvss3BaseScore, true -} - -// SetCvss3BaseScore sets field value -func (o *CVEDetailedCvss3) SetCvss3BaseScore(v string) { - o.Cvss3BaseScore = v -} - -// GetCvss3ScoringVector returns the Cvss3ScoringVector field value -func (o *CVEDetailedCvss3) GetCvss3ScoringVector() string { - if o == nil { - var ret string - return ret - } - - return o.Cvss3ScoringVector -} - -// GetCvss3ScoringVectorOk returns a tuple with the Cvss3ScoringVector field value -// and a boolean to check if the value has been set. -func (o *CVEDetailedCvss3) GetCvss3ScoringVectorOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.Cvss3ScoringVector, true -} - -// SetCvss3ScoringVector sets field value -func (o *CVEDetailedCvss3) SetCvss3ScoringVector(v string) { - o.Cvss3ScoringVector = v -} - -// GetStatus returns the Status field value -func (o *CVEDetailedCvss3) GetStatus() string { - if o == nil { - var ret string - return ret - } - - return o.Status -} - -// GetStatusOk returns a tuple with the Status field value -// and a boolean to check if the value has been set. -func (o *CVEDetailedCvss3) GetStatusOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.Status, true -} - -// SetStatus sets field value -func (o *CVEDetailedCvss3) SetStatus(v string) { - o.Status = v -} - -func (o CVEDetailedCvss3) MarshalJSON() ([]byte, error) { - toSerialize := map[string]interface{}{} - if true { - toSerialize["cvss3_base_score"] = o.Cvss3BaseScore - } - if true { - toSerialize["cvss3_scoring_vector"] = o.Cvss3ScoringVector - } - if true { - toSerialize["status"] = o.Status - } - return json.Marshal(toSerialize) -} - -type NullableCVEDetailedCvss3 struct { - value *CVEDetailedCvss3 - isSet bool -} - -func (v NullableCVEDetailedCvss3) Get() *CVEDetailedCvss3 { - return v.value -} - -func (v *NullableCVEDetailedCvss3) Set(val *CVEDetailedCvss3) { - v.value = val - v.isSet = true -} - -func (v NullableCVEDetailedCvss3) IsSet() bool { - return v.isSet -} - -func (v *NullableCVEDetailedCvss3) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableCVEDetailedCvss3(val *CVEDetailedCvss3) *NullableCVEDetailedCvss3 { - return &NullableCVEDetailedCvss3{value: val, isSet: true} -} - -func (v NullableCVEDetailedCvss3) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableCVEDetailedCvss3) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} diff --git a/apollo/rhsecurity/model_cve_detailed_package_state.go b/apollo/rhsecurity/model_cve_detailed_package_state.go deleted file mode 100644 index e604c56..0000000 --- a/apollo/rhsecurity/model_cve_detailed_package_state.go +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Red Hat Security Data API - * - * Unofficial OpenAPI definitions for Red Hat Security Data API - * - * API version: 1.0 - * Contact: mustafa@ctrliq.com - */ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package rhsecurity - -import ( - "encoding/json" -) - -// CVEDetailedPackageState struct for CVEDetailedPackageState -type CVEDetailedPackageState struct { - ProductName string `json:"product_name"` - FixState string `json:"fix_state"` - PackageName string `json:"package_name"` - Cpe string `json:"cpe"` -} - -// NewCVEDetailedPackageState instantiates a new CVEDetailedPackageState object -// This constructor will assign default values to properties that have it defined, -// and makes sure properties required by API are set, but the set of arguments -// will change when the set of required properties is changed -func NewCVEDetailedPackageState(productName string, fixState string, packageName string, cpe string) *CVEDetailedPackageState { - this := CVEDetailedPackageState{} - this.ProductName = productName - this.FixState = fixState - this.PackageName = packageName - this.Cpe = cpe - return &this -} - -// NewCVEDetailedPackageStateWithDefaults instantiates a new CVEDetailedPackageState object -// This constructor will only assign default values to properties that have it defined, -// but it doesn't guarantee that properties required by API are set -func NewCVEDetailedPackageStateWithDefaults() *CVEDetailedPackageState { - this := CVEDetailedPackageState{} - return &this -} - -// GetProductName returns the ProductName field value -func (o *CVEDetailedPackageState) GetProductName() string { - if o == nil { - var ret string - return ret - } - - return o.ProductName -} - -// GetProductNameOk returns a tuple with the ProductName field value -// and a boolean to check if the value has been set. -func (o *CVEDetailedPackageState) GetProductNameOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.ProductName, true -} - -// SetProductName sets field value -func (o *CVEDetailedPackageState) SetProductName(v string) { - o.ProductName = v -} - -// GetFixState returns the FixState field value -func (o *CVEDetailedPackageState) GetFixState() string { - if o == nil { - var ret string - return ret - } - - return o.FixState -} - -// GetFixStateOk returns a tuple with the FixState field value -// and a boolean to check if the value has been set. -func (o *CVEDetailedPackageState) GetFixStateOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.FixState, true -} - -// SetFixState sets field value -func (o *CVEDetailedPackageState) SetFixState(v string) { - o.FixState = v -} - -// GetPackageName returns the PackageName field value -func (o *CVEDetailedPackageState) GetPackageName() string { - if o == nil { - var ret string - return ret - } - - return o.PackageName -} - -// GetPackageNameOk returns a tuple with the PackageName field value -// and a boolean to check if the value has been set. -func (o *CVEDetailedPackageState) GetPackageNameOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.PackageName, true -} - -// SetPackageName sets field value -func (o *CVEDetailedPackageState) SetPackageName(v string) { - o.PackageName = v -} - -// GetCpe returns the Cpe field value -func (o *CVEDetailedPackageState) GetCpe() string { - if o == nil { - var ret string - return ret - } - - return o.Cpe -} - -// GetCpeOk returns a tuple with the Cpe field value -// and a boolean to check if the value has been set. -func (o *CVEDetailedPackageState) GetCpeOk() (*string, bool) { - if o == nil { - return nil, false - } - return &o.Cpe, true -} - -// SetCpe sets field value -func (o *CVEDetailedPackageState) SetCpe(v string) { - o.Cpe = v -} - -func (o CVEDetailedPackageState) MarshalJSON() ([]byte, error) { - toSerialize := map[string]interface{}{} - if true { - toSerialize["product_name"] = o.ProductName - } - if true { - toSerialize["fix_state"] = o.FixState - } - if true { - toSerialize["package_name"] = o.PackageName - } - if true { - toSerialize["cpe"] = o.Cpe - } - return json.Marshal(toSerialize) -} - -type NullableCVEDetailedPackageState struct { - value *CVEDetailedPackageState - isSet bool -} - -func (v NullableCVEDetailedPackageState) Get() *CVEDetailedPackageState { - return v.value -} - -func (v *NullableCVEDetailedPackageState) Set(val *CVEDetailedPackageState) { - v.value = val - v.isSet = true -} - -func (v NullableCVEDetailedPackageState) IsSet() bool { - return v.isSet -} - -func (v *NullableCVEDetailedPackageState) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableCVEDetailedPackageState(val *CVEDetailedPackageState) *NullableCVEDetailedPackageState { - return &NullableCVEDetailedPackageState{value: val, isSet: true} -} - -func (v NullableCVEDetailedPackageState) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableCVEDetailedPackageState) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} diff --git a/apollo/rhsecurity/response.go b/apollo/rhsecurity/response.go deleted file mode 100644 index bedc39f..0000000 --- a/apollo/rhsecurity/response.go +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Red Hat Security Data API - * - * Unofficial OpenAPI definitions for Red Hat Security Data API - * - * API version: 1.0 - * Contact: mustafa@ctrliq.com - */ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package rhsecurity - -import ( - "net/http" -) - -// APIResponse stores the API response returned by the server. -type APIResponse struct { - *http.Response `json:"-"` - Message string `json:"message,omitempty"` - // Operation is the name of the OpenAPI operation. - Operation string `json:"operation,omitempty"` - // RequestURL is the request URL. This value is always available, even if the - // embedded *http.Response is nil. - RequestURL string `json:"url,omitempty"` - // Method is the HTTP method used for the request. This value is always - // available, even if the embedded *http.Response is nil. - Method string `json:"method,omitempty"` - // Payload holds the contents of the response body (which may be nil or empty). - // This is provided here as the raw response.Body() reader will have already - // been drained. - Payload []byte `json:"-"` -} - -// NewAPIResponse returns a new APIResonse object. -func NewAPIResponse(r *http.Response) *APIResponse { - - response := &APIResponse{Response: r} - return response -} - -// NewAPIResponseWithError returns a new APIResponse object with the provided error message. -func NewAPIResponseWithError(errorMessage string) *APIResponse { - - response := &APIResponse{Message: errorMessage} - return response -} diff --git a/apollo/rhsecurity/utils.go b/apollo/rhsecurity/utils.go deleted file mode 100644 index 4aa6f30..0000000 --- a/apollo/rhsecurity/utils.go +++ /dev/null @@ -1,329 +0,0 @@ -/* - * Red Hat Security Data API - * - * Unofficial OpenAPI definitions for Red Hat Security Data API - * - * API version: 1.0 - * Contact: mustafa@ctrliq.com - */ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package rhsecurity - -import ( - "encoding/json" - "time" -) - -// PtrBool is a helper routine that returns a pointer to given boolean value. -func PtrBool(v bool) *bool { return &v } - -// PtrInt is a helper routine that returns a pointer to given integer value. -func PtrInt(v int) *int { return &v } - -// PtrInt32 is a helper routine that returns a pointer to given integer value. -func PtrInt32(v int32) *int32 { return &v } - -// PtrInt64 is a helper routine that returns a pointer to given integer value. -func PtrInt64(v int64) *int64 { return &v } - -// PtrFloat32 is a helper routine that returns a pointer to given float value. -func PtrFloat32(v float32) *float32 { return &v } - -// PtrFloat64 is a helper routine that returns a pointer to given float value. -func PtrFloat64(v float64) *float64 { return &v } - -// PtrString is a helper routine that returns a pointer to given string value. -func PtrString(v string) *string { return &v } - -// PtrTime is helper routine that returns a pointer to given Time value. -func PtrTime(v time.Time) *time.Time { return &v } - -type NullableBool struct { - value *bool - isSet bool -} - -func (v NullableBool) Get() *bool { - return v.value -} - -func (v *NullableBool) Set(val *bool) { - v.value = val - v.isSet = true -} - -func (v NullableBool) IsSet() bool { - return v.isSet -} - -func (v *NullableBool) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableBool(val *bool) *NullableBool { - return &NullableBool{value: val, isSet: true} -} - -func (v NullableBool) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableBool) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} - -type NullableInt struct { - value *int - isSet bool -} - -func (v NullableInt) Get() *int { - return v.value -} - -func (v *NullableInt) Set(val *int) { - v.value = val - v.isSet = true -} - -func (v NullableInt) IsSet() bool { - return v.isSet -} - -func (v *NullableInt) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableInt(val *int) *NullableInt { - return &NullableInt{value: val, isSet: true} -} - -func (v NullableInt) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableInt) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} - -type NullableInt32 struct { - value *int32 - isSet bool -} - -func (v NullableInt32) Get() *int32 { - return v.value -} - -func (v *NullableInt32) Set(val *int32) { - v.value = val - v.isSet = true -} - -func (v NullableInt32) IsSet() bool { - return v.isSet -} - -func (v *NullableInt32) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableInt32(val *int32) *NullableInt32 { - return &NullableInt32{value: val, isSet: true} -} - -func (v NullableInt32) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableInt32) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} - -type NullableInt64 struct { - value *int64 - isSet bool -} - -func (v NullableInt64) Get() *int64 { - return v.value -} - -func (v *NullableInt64) Set(val *int64) { - v.value = val - v.isSet = true -} - -func (v NullableInt64) IsSet() bool { - return v.isSet -} - -func (v *NullableInt64) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableInt64(val *int64) *NullableInt64 { - return &NullableInt64{value: val, isSet: true} -} - -func (v NullableInt64) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableInt64) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} - -type NullableFloat32 struct { - value *float32 - isSet bool -} - -func (v NullableFloat32) Get() *float32 { - return v.value -} - -func (v *NullableFloat32) Set(val *float32) { - v.value = val - v.isSet = true -} - -func (v NullableFloat32) IsSet() bool { - return v.isSet -} - -func (v *NullableFloat32) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableFloat32(val *float32) *NullableFloat32 { - return &NullableFloat32{value: val, isSet: true} -} - -func (v NullableFloat32) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableFloat32) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} - -type NullableFloat64 struct { - value *float64 - isSet bool -} - -func (v NullableFloat64) Get() *float64 { - return v.value -} - -func (v *NullableFloat64) Set(val *float64) { - v.value = val - v.isSet = true -} - -func (v NullableFloat64) IsSet() bool { - return v.isSet -} - -func (v *NullableFloat64) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableFloat64(val *float64) *NullableFloat64 { - return &NullableFloat64{value: val, isSet: true} -} - -func (v NullableFloat64) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableFloat64) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} - -type NullableString struct { - value *string - isSet bool -} - -func (v NullableString) Get() *string { - return v.value -} - -func (v *NullableString) Set(val *string) { - v.value = val - v.isSet = true -} - -func (v NullableString) IsSet() bool { - return v.isSet -} - -func (v *NullableString) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableString(val *string) *NullableString { - return &NullableString{value: val, isSet: true} -} - -func (v NullableString) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableString) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} - -type NullableTime struct { - value *time.Time - isSet bool -} - -func (v NullableTime) Get() *time.Time { - return v.value -} - -func (v *NullableTime) Set(val *time.Time) { - v.value = val - v.isSet = true -} - -func (v NullableTime) IsSet() bool { - return v.isSet -} - -func (v *NullableTime) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableTime(val *time.Time) *NullableTime { - return &NullableTime{value: val, isSet: true} -} - -func (v NullableTime) MarshalJSON() ([]byte, error) { - return v.value.MarshalJSON() -} - -func (v *NullableTime) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} diff --git a/apollo/rhsecuritymock/BUILD.bazel b/apollo/rhsecuritymock/BUILD.bazel deleted file mode 100644 index 925e65b..0000000 --- a/apollo/rhsecuritymock/BUILD.bazel +++ /dev/null @@ -1,12 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "rhsecuritymock", - srcs = ["client.go"], - importpath = "peridot.resf.org/apollo/rhsecuritymock", - visibility = ["//visibility:public"], - deps = [ - "//apollo/rhsecurity", - "//utils", - ], -) diff --git a/apollo/rhsecuritymock/client.go b/apollo/rhsecuritymock/client.go deleted file mode 100644 index 24abcf1..0000000 --- a/apollo/rhsecuritymock/client.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package rhsecuritymock - -import ( - _context "context" - _nethttp "net/http" - "peridot.resf.org/apollo/rhsecurity" - "peridot.resf.org/utils" -) - -type Client struct { - orig rhsecurity.DefaultApi - - ActivePage float32 - ActiveCVE *rhsecurity.CVEDetailed - Cves map[float32][]*rhsecurity.CVE -} - -func New() *Client { - return &Client{ - orig: rhsecurity.NewAPIClient(rhsecurity.NewConfiguration()).DefaultApi, - ActivePage: 1, - Cves: map[float32][]*rhsecurity.CVE{}, - } -} - -/* - * GetCve Get specific CVE - * Retrieve full CVE details - * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param cVE - * @return ApiGetCveRequest - */ -func (c *Client) GetCve(ctx _context.Context, cVE string) rhsecurity.ApiGetCveRequest { - return c.orig.GetCve(ctx, cVE) -} - -/* - * GetCveExecute executes the request - * @return CVEDetailed - */ -func (c *Client) GetCveExecute(_ rhsecurity.ApiGetCveRequest) (rhsecurity.CVEDetailed, *_nethttp.Response, error) { - if c.ActiveCVE != nil { - return *c.ActiveCVE, &_nethttp.Response{}, nil - } - - return rhsecurity.CVEDetailed{}, nil, utils.CouldNotFindObject -} - -/* - * GetCves Get CVEs - * List all the recent CVEs when no parameter is passed. Returns a convenience object as response with very minimum attributes. - * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @return ApiGetCvesRequest - */ -func (c *Client) GetCves(ctx _context.Context) rhsecurity.ApiGetCvesRequest { - c.ActivePage = 1 - return c.orig.GetCves(ctx) -} - -/* - * GetCvesExecute executes the request - * @return []CVE - */ -func (c *Client) GetCvesExecute(_ rhsecurity.ApiGetCvesRequest) ([]rhsecurity.CVE, *_nethttp.Response, error) { - var cves []rhsecurity.CVE - for _, cve := range c.Cves[c.ActivePage] { - cves = append(cves, *cve) - } - c.ActivePage++ - - return cves, &_nethttp.Response{}, nil -} diff --git a/publisher/BUILD b/publisher/BUILD deleted file mode 100644 index e69de29..0000000 diff --git a/publisher/README.md b/publisher/README.md deleted file mode 100644 index 776a5ea..0000000 --- a/publisher/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# publisher -(Peridot uses yumrepofs, this is for legacy errata/koji errata) - -### Legacy errata mode -This mode only populates pungi generated repositories with errata metadata. -It can be deployed like this: -``` -STABLE_STAGE=-prod bazel run --platforms @io_bazel_rules_go//go/toolchain:linux_amd64 //publisher/cmd/publisher-legacy-errata:publisher-legacy-errata-tool -``` - -After an updates compose is finished and merged into the correct point release directory (for example: 8.4-RC2) run: -``` -ansible-playbook -i inventories/hosts.ini playbooks/secparse001-publish.yml -``` - -The ansible playbook is present in https://github.com/rocky-linux/peridot-ansible diff --git a/publisher/cmd/BUILD b/publisher/cmd/BUILD deleted file mode 100644 index e69de29..0000000 diff --git a/publisher/cmd/publisher-legacy-errata/BUILD.bazel b/publisher/cmd/publisher-legacy-errata/BUILD.bazel deleted file mode 100644 index b9ca84d..0000000 --- a/publisher/cmd/publisher-legacy-errata/BUILD.bazel +++ /dev/null @@ -1,30 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library") -load("//rules_resf:defs.bzl", "container") - -go_library( - name = "publisher-legacy-errata_lib", - srcs = ["main.go"], - importpath = "peridot.resf.org/publisher/cmd/publisher-legacy-errata", - visibility = ["//visibility:private"], - deps = [ - "//apollo/db/connector", - "//publisher/updateinfo/legacy", - "//utils", - "//vendor/github.com/sirupsen/logrus", - "//vendor/github.com/spf13/cobra", - ], -) - -go_binary( - name = "publisher-legacy-errata", - embed = [":publisher-legacy-errata_lib"], - visibility = ["//visibility:public"], -) - -container( - base = "//bases/bazel/go", - files = [ - ":publisher-legacy-errata", - ], - image_name = "publisher-legacy-errata-tool", -) diff --git a/publisher/cmd/publisher-legacy-errata/main.go b/publisher/cmd/publisher-legacy-errata/main.go deleted file mode 100644 index 551fd80..0000000 --- a/publisher/cmd/publisher-legacy-errata/main.go +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package main - -import ( - "github.com/sirupsen/logrus" - "github.com/spf13/cobra" - "path/filepath" - apolloconnector "peridot.resf.org/apollo/db/connector" - "peridot.resf.org/publisher/updateinfo/legacy" - "peridot.resf.org/utils" -) - -var root = &cobra.Command{ - Use: "publisher-legacy-errata", - Run: mn, -} - -var cnf = utils.NewFlagConfig() - -var ( - repoDir string - from string - composeName string - productName string - productShort string - productID int64 - scanAndStop bool -) - -func init() { - dname := "apollo" - cnf.DatabaseName = &dname - cnf.Name = "publisher" - - pflags := root.PersistentFlags() - pflags.StringVar(&repoDir, "repo-dir", "/mnt/repos-staging/pub/rocky", "Directory with composes") - pflags.StringVar(&from, "from", "releng@rockylinux.org", "Email address of publisher") - pflags.StringVar(&composeName, "compose-name", "", "Compose to use") - pflags.StringVar(&productName, "product-name", "", "Product name") - pflags.StringVar(&productShort, "product-short", "", "Product name (short)") - pflags.Int64Var(&productID, "product-id", 0, "Product ID") - pflags.BoolVar(&scanAndStop, "scan-and-stop", false, "Scan RPMs and stop, used for debugging purposes") - _ = root.MarkPersistentFlagRequired("compose-name") - _ = root.MarkPersistentFlagRequired("product-name") - _ = root.MarkPersistentFlagRequired("product-short") - _ = root.MarkPersistentFlagRequired("product-id") - - utils.AddDBFlagsOnly(pflags, cnf) - utils.BindOnly(pflags, cnf) -} - -func mn(_ *cobra.Command, _ []string) { - scanner := &legacy.Scanner{ - DB: apolloconnector.MustAuto(), - } - err := scanner.ScanAndPublish(from, filepath.Join(repoDir, composeName), productName, productShort, productID, scanAndStop) - if err != nil { - logrus.Fatalf("could not scan and publish: %v", err) - } -} - -func main() { - if err := root.Execute(); err != nil { - logrus.Fatal(err) - } -} diff --git a/publisher/updateinfo/BUILD.bazel b/publisher/updateinfo/BUILD.bazel deleted file mode 100644 index 640c648..0000000 --- a/publisher/updateinfo/BUILD.bazel +++ /dev/null @@ -1,11 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "updateinfo", - srcs = [ - "repomd.go", - "updateinfo.go", - ], - importpath = "peridot.resf.org/publisher/updateinfo", - visibility = ["//visibility:public"], -) diff --git a/publisher/updateinfo/legacy/BUILD.bazel b/publisher/updateinfo/legacy/BUILD.bazel deleted file mode 100644 index 74d1f10..0000000 --- a/publisher/updateinfo/legacy/BUILD.bazel +++ /dev/null @@ -1,17 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "legacy", - srcs = ["legacy.go"], - importpath = "peridot.resf.org/publisher/updateinfo/legacy", - visibility = ["//visibility:public"], - deps = [ - "//apollo/db", - "//apollo/proto/v1:pb", - "//apollo/rpmutils", - "//publisher/updateinfo", - "//utils", - "//vendor/github.com/sirupsen/logrus", - "@org_golang_google_protobuf//types/known/wrapperspb:go_default_library", - ], -) diff --git a/publisher/updateinfo/legacy/legacy.go b/publisher/updateinfo/legacy/legacy.go deleted file mode 100644 index fbbbad2..0000000 --- a/publisher/updateinfo/legacy/legacy.go +++ /dev/null @@ -1,601 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package legacy - -import ( - "bytes" - "compress/gzip" - "crypto/sha256" - "database/sql" - "encoding/hex" - "encoding/xml" - "errors" - "fmt" - "github.com/sirupsen/logrus" - "google.golang.org/protobuf/types/known/wrapperspb" - "io" - "io/fs" - "io/ioutil" - "os" - "path/filepath" - apollodb "peridot.resf.org/apollo/db" - apollopb "peridot.resf.org/apollo/pb" - "peridot.resf.org/apollo/rpmutils" - "peridot.resf.org/publisher/updateinfo" - "peridot.resf.org/utils" - "strconv" - "strings" - "sync" - "time" -) - -type Scanner struct { - DB apollodb.Access -} - -type internalAdvisory struct { - Pb *apollopb.Advisory - Db *apollodb.Advisory -} - -type rpm struct { - Name string - Src string - Sha256 string - Epoch string - Repo string - Err error - Advisory *internalAdvisory -} - -func (s *Scanner) recursiveRPMScan(rootDir string, cache map[string]string) (<-chan rpm, <-chan error) { - res := make(chan rpm) - errc := make(chan error, 1) - - go func() { - var wg sync.WaitGroup - err := filepath.WalkDir(rootDir, func(path string, d fs.DirEntry, err error) error { - if err != nil { - return err - } - if d.IsDir() { - return nil - } - if !strings.HasSuffix(d.Name(), ".rpm") { - return nil - } - if strings.Contains(path, "kickstart/Packages") { - return nil - } - - wg.Add(1) - go func() { - k, err := s.findRepoData(filepath.Join(path, "..")) - if err != nil { - logrus.Errorf("could not find repodata for %s: %s", path, err) - k = filepath.Join(path, "..") - } - k = filepath.Join(k, "..") - - var sum string - if s := cache[d.Name()]; s != "" { - sum = s - } else { - f, _ := os.Open(path) - defer f.Close() - hasher := sha256.New() - _, err = io.Copy(hasher, f) - sum = hex.EncodeToString(hasher.Sum(nil)) - } - - select { - case res <- rpm{ - Name: d.Name(), - Sha256: sum, - Repo: k, - Err: err, - }: - } - - wg.Done() - }() - - select { - default: - return nil - } - }) - go func() { - wg.Wait() - close(res) - }() - errc <- err - }() - - return res, errc -} - -func (s *Scanner) findRepoData(rootDir string) (string, error) { - if rootDir == "." { - return "", errors.New("could not find repodata") - } - - repoDataPath := filepath.Join(rootDir, "repodata") - stat, err := os.Stat(repoDataPath) - if err != nil { - if os.IsNotExist(err) { - return s.findRepoData(filepath.Join(rootDir, "..")) - } else { - return "", err - } - } - - if stat.IsDir() { - return repoDataPath, nil - } else { - return s.findRepoData(filepath.Join(rootDir, "..")) - } -} - -func (s *Scanner) ScanAndPublish(from string, composeName string, productName string, productShort string, productID int64, scanAndStop bool) error { - logrus.Infof("using %s as root directory", composeName) - - realPathCompose, err := filepath.EvalSymlinks(composeName) - if err != nil { - return err - } - - logrus.Infof("real path is %s", realPathCompose) - - _, err = os.Stat(realPathCompose) - if err != nil { - return fmt.Errorf("could not find compose %s: %w", realPathCompose, err) - } - - // Read cache file if exists, so we can skip hashing on known artifacts - cacheFile := filepath.Join(realPathCompose, fmt.Sprintf("apollocache_%d", productID)) - cache := map[string]string{} - if _, err := os.Stat(cacheFile); err == nil { - cacheBts, err := ioutil.ReadFile(cacheFile) - if err != nil { - return err - } - cacheLines := strings.Split(string(cacheBts), "\n") - for _, line := range cacheLines { - if line == "" { - continue - } - parts := strings.Split(line, " ") - cache[parts[0]] = parts[1] - } - } - - rpms := map[string][]*rpm{} - rpmsChan, errChan := s.recursiveRPMScan(realPathCompose, cache) - for r := range rpmsChan { - rpmCopy := r - if rpmCopy.Err != nil { - return rpmCopy.Err - } - - if rpms[rpmCopy.Repo] == nil { - rpms[rpmCopy.Repo] = []*rpm{} - } - - rpms[rpmCopy.Repo] = append(rpms[rpmCopy.Repo], &rpmCopy) - } - if err := <-errChan; err != nil { - return err - } - - if len(rpms) == 0 { - return errors.New("no rpms found") - } - - // Cache hashes in {REPO_DIR}/apollocache_{PRODUCT_ID} - var newCacheEntries []string - for _, v := range rpms { - for _, rpm := range v { - entry := fmt.Sprintf("%s %s", rpm.Name, rpm.Sha256) - if !utils.StrContains(entry, newCacheEntries) { - newCacheEntries = append(newCacheEntries, entry) - } - } - } - if err := ioutil.WriteFile(cacheFile, []byte(strings.Join(newCacheEntries, "\n")), 0644); err != nil { - return err - } - - if scanAndStop { - for k := range rpms { - logrus.Infof("repo %s", k) - } - return nil - } - - published := map[string][]*rpm{} - - beginTx, err := s.DB.Begin() - if err != nil { - logrus.Errorf("Could not initiate tx: %v", err) - } - tx := s.DB.UseTransaction(beginTx) - rollback := false - - advisories, err := tx.GetAllAdvisories(&apollopb.AdvisoryFilters{ - IncludeUnpublished: wrapperspb.Bool(true), - }, 0, -1) - if err != nil { - return err - } - for _, advisory := range advisories { - advisoryPb := apollodb.DTOAdvisoryToPB(advisory) - - touchedOnce := false - for _, artifactWithSrpm := range advisory.BuildArtifacts { - artifactSplit := strings.Split(artifactWithSrpm, ":::") - artifact := artifactSplit[0] - artifactSrc := rpmutils.Epoch().ReplaceAllString(artifactSplit[1], "") - - for repo, repoRpms := range rpms { - if strings.HasSuffix(repo, "/Packages") { - repo = strings.TrimSuffix(repo, "/Packages") - } - if published[repo] == nil { - published[repo] = []*rpm{} - } - - for _, repoRpm := range repoRpms { - if repoRpm.Name == rpmutils.Epoch().ReplaceAllString(artifact, "") { - logrus.Infof("Advisory %s affects %s", advisoryPb.Name, artifact) - err = tx.AddAdvisoryRPM(advisory.ID, artifact, productID) - if err != nil { - logrus.Errorf("Could not add advisory RPM: %v", err) - rollback = true - break - } - touchedOnce = true - repoRpm.Epoch = strings.TrimSuffix(rpmutils.Epoch().FindStringSubmatch(artifact)[0], ":") - repoRpm.Advisory = &internalAdvisory{ - Pb: advisoryPb, - Db: advisory, - } - repoRpm.Src = artifactSrc - published[repo] = append(published[repo], repoRpm) - } - } - } - } - if rollback { - break - } - if !touchedOnce { - continue - } - - if !advisory.PublishedAt.Valid { - advisory.PublishedAt = sql.NullTime{Valid: true, Time: time.Now()} - _, err = tx.UpdateAdvisory(advisory) - if err != nil { - logrus.Errorf("could not update advisory %s: %v", advisoryPb.Name, err) - rollback = true - break - } - } - } - - publishedMappedByAdvisory := map[string]map[string][]*rpm{} - advisoryByName := map[string]*internalAdvisory{} - - for repo, publishedRpms := range published { - if publishedMappedByAdvisory[repo] == nil { - publishedMappedByAdvisory[repo] = map[string][]*rpm{} - } - - for _, publishedRpm := range publishedRpms { - if publishedMappedByAdvisory[repo][publishedRpm.Advisory.Pb.Name] == nil { - publishedMappedByAdvisory[repo][publishedRpm.Advisory.Pb.Name] = []*rpm{} - } - if advisoryByName[publishedRpm.Advisory.Pb.Name] == nil { - advisoryByName[publishedRpm.Advisory.Pb.Name] = publishedRpm.Advisory - } - publishedMappedByAdvisory[repo][publishedRpm.Advisory.Pb.Name] = append(publishedMappedByAdvisory[repo][publishedRpm.Advisory.Pb.Name], publishedRpm) - } - } - - for repo, advisories := range publishedMappedByAdvisory { - repoDataDir, err := s.findRepoData(repo) - if err != nil { - logrus.Error(err) - rollback = true - break - } - repoMdPath := filepath.Join(repoDataDir, "repomd.xml") - - f, err := os.Open(repoMdPath) - if err != nil { - logrus.Errorf("Could not open repomd.xml: %v", err) - rollback = true - break - } - - var repomd updateinfo.RepoMdRoot - err = xml.NewDecoder(f).Decode(&repomd) - if err != nil { - logrus.Errorf("Could not decode repomd: %v", err) - rollback = true - break - } - - _ = f.Close() - - var olderUpdateInfo string - for _, e := range repomd.Data { - if e.Type == "updateinfo" { - olderUpdateInfo = e.Location.Href - } - } - - updateInfo := &updateinfo.UpdatesRoot{ - Updates: []*updateinfo.Update{}, - } - - for advisoryName, publishedRpms := range advisories { - advisory := advisoryByName[advisoryName] - - updateType := "enhancement" - switch advisory.Pb.Type { - case apollopb.Advisory_TYPE_BUGFIX: - updateType = "bugfix" - break - case apollopb.Advisory_TYPE_SECURITY: - updateType = "security" - break - } - - severity := advisory.Pb.Severity.String() - if advisory.Pb.Severity == apollopb.Advisory_SEVERITY_UNKNOWN { - severity = "None" - } - - update := &updateinfo.Update{ - From: from, - Status: "final", - Type: updateType, - Version: "2", - ID: advisory.Pb.Name, - Title: advisory.Pb.Synopsis, - Issued: &updateinfo.UpdateDate{ - Date: advisory.Db.PublishedAt.Time.Format(updateinfo.TimeFormat), - }, - Updated: &updateinfo.UpdateDate{ - Date: advisory.Db.RedHatIssuedAt.Time.Format(updateinfo.TimeFormat), - }, - Rights: "Copyright (C) 2022 Rocky Enterprise Software Foundation", - Release: productName, - PushCount: "1", - Severity: severity, - Summary: advisory.Pb.Topic, - Description: advisory.Pb.Description, - References: &updateinfo.UpdateReferenceRoot{ - References: []*updateinfo.UpdateReference{}, - }, - PkgList: &updateinfo.UpdateCollectionRoot{ - Collections: []*updateinfo.UpdateCollection{ - { - Short: productShort, - Name: productName, - Packages: []*updateinfo.UpdatePackage{}, - }, - }, - }, - } - - for _, cve := range advisory.Pb.Cves { - sourceBy := cve.SourceBy - sourceLink := cve.SourceLink - id := cve.Name - - referenceType := "erratum" - if strings.HasPrefix(id, "CVE") { - referenceType = "cve" - } - - reference := &updateinfo.UpdateReference{ - Href: sourceLink.Value, - ID: id, - Type: referenceType, - Title: fmt.Sprintf("Update information for %s is retrieved from %s", id, sourceBy.Value), - } - - update.References.References = append(update.References.References, reference) - } - - for _, publishedRpm := range publishedRpms { - nvr := rpmutils.NVR().FindStringSubmatch(publishedRpm.Name) - - updPkg := &updateinfo.UpdatePackage{ - Name: nvr[1], - Version: nvr[2], - Release: nvr[3], - Epoch: publishedRpm.Epoch, - Arch: nvr[4], - Src: publishedRpm.Src, - Filename: publishedRpm.Name, - Sum: []*updateinfo.UpdatePackageSum{ - { - Type: "sha256", - Value: publishedRpm.Sha256, - }, - }, - } - if advisory.Db.RebootSuggested { - updPkg.RebootSuggested = "True" - } - update.PkgList.Collections[0].Packages = append(update.PkgList.Collections[0].Packages, updPkg) - } - if rollback { - break - } - - updateInfo.Updates = append(updateInfo.Updates, update) - } - if rollback { - break - } - - xmlBytes, err := xml.MarshalIndent(updateInfo, "", " ") - if err != nil { - logrus.Errorf("Could not encode updateinfo xml: %v", err) - rollback = true - break - } - - hasher := sha256.New() - - openSize := len(xmlBytes) - _, err = hasher.Write(xmlBytes) - if err != nil { - logrus.Errorf("Could not hash updateinfo: %v", err) - rollback = true - break - } - openChecksum := hex.EncodeToString(hasher.Sum(nil)) - hasher.Reset() - - var gzippedBuf bytes.Buffer - w := gzip.NewWriter(&gzippedBuf) - _, err = w.Write(xmlBytes) - if err != nil { - logrus.Errorf("Could not gzip encode: %v", err) - rollback = true - break - } - _ = w.Close() - - closedSize := len(gzippedBuf.Bytes()) - _, err = hasher.Write(gzippedBuf.Bytes()) - if err != nil { - logrus.Errorf("Could not hash gzipped: %v", err) - rollback = true - break - } - closedChecksum := hex.EncodeToString(hasher.Sum(nil)) - hasher.Reset() - - timestamp := strconv.FormatInt(time.Now().Unix(), 10) - - updateInfoPath := filepath.Join(repoDataDir, fmt.Sprintf("%s-updateinfo.xml.gz", closedChecksum)) - updateInfoEntry := &updateinfo.RepoMdData{ - Type: "updateinfo", - Checksum: &updateinfo.RepoMdDataChecksum{ - Type: "sha256", - Value: closedChecksum, - }, - OpenChecksum: &updateinfo.RepoMdDataChecksum{ - Type: "sha256", - Value: openChecksum, - }, - Location: &updateinfo.RepoMdDataLocation{ - Href: strings.ReplaceAll(updateInfoPath, repo+"/", ""), - }, - Timestamp: timestamp, - Size: strconv.Itoa(closedSize), - OpenSize: strconv.Itoa(openSize), - } - - if olderUpdateInfo == "" { - repomd.Data = append(repomd.Data, updateInfoEntry) - } else { - for i, e := range repomd.Data { - if e.Type == "updateinfo" { - repomd.Data[i] = updateInfoEntry - } - } - } - - uif, err := os.OpenFile(updateInfoPath, os.O_TRUNC|os.O_RDWR|os.O_CREATE, 0644) - if err != nil { - logrus.Errorf("Could not open updateinfo file %s: %v", updateInfoPath, err) - rollback = true - break - } - _, err = uif.Write(gzippedBuf.Bytes()) - if err != nil { - logrus.Errorf("Could not write gzipped updateinfo file: %v", err) - rollback = true - break - } - _ = uif.Close() - - if repomd.Rpm != "" && repomd.XmlnsRpm == "" { - repomd.XmlnsRpm = repomd.Rpm - repomd.Rpm = "" - } - - updateF, err := os.OpenFile(repoMdPath, os.O_TRUNC|os.O_RDWR|os.O_CREATE, 0644) - if err != nil { - logrus.Errorf("Could not open repomd file for update: %v", err) - rollback = true - break - } - _, _ = updateF.Write([]byte(xml.Header)) - enc := xml.NewEncoder(updateF) - enc.Indent("", " ") - err = enc.Encode(&repomd) - if err != nil { - logrus.Errorf("Could not encode updated repomd file: %v", err) - rollback = true - break - } - _ = updateF.Close() - - if olderUpdateInfo != "" { - _ = os.Remove(filepath.Join(repo, olderUpdateInfo)) - } - } - - if rollback { - err := beginTx.Rollback() - if err != nil { - logrus.Errorf("Could not rollback: %v", err) - } - - return errors.New("rolled back") - } - - err = beginTx.Commit() - if err != nil { - logrus.Errorf("Could not commit transaction: %v", err) - } - - return nil -} diff --git a/publisher/updateinfo/repomd.go b/publisher/updateinfo/repomd.go deleted file mode 100644 index 1c1be4c..0000000 --- a/publisher/updateinfo/repomd.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package updateinfo - -import "encoding/xml" - -type RepoMdDistro struct { - CpeId string `xml:"cpeid,attr"` - Value string `xml:",chardata"` -} - -type RepoMdDistroRoot struct { - Distro []*RepoMdDistro `xml:"distro"` -} - -type RepoMdDataChecksum struct { - Type string `xml:"type,attr"` - Value string `xml:",chardata"` -} - -type RepoMdDataLocation struct { - Href string `xml:"href,attr"` -} - -type RepoMdData struct { - Type string `xml:"type,attr"` - Checksum *RepoMdDataChecksum `xml:"checksum"` - OpenChecksum *RepoMdDataChecksum `xml:"open-checksum"` - Location *RepoMdDataLocation `xml:"location"` - Timestamp string `xml:"timestamp"` - Size string `xml:"size"` - OpenSize string `xml:"open-size"` -} - -type RepoMdRoot struct { - XMLName xml.Name `xml:"repomd"` - Xmlns string `xml:"xmlns,attr"` - XmlnsRpm string `xml:"xmlns:rpm,attr"` - Rpm string `xml:"rpm,attr,omitempty"` - - Revision string `xml:"revision"` - Tags *RepoMdDistroRoot `xml:"tags"` - Data []*RepoMdData `xml:"data"` -} diff --git a/publisher/updateinfo/updateinfo.go b/publisher/updateinfo/updateinfo.go deleted file mode 100644 index c84fbfb..0000000 --- a/publisher/updateinfo/updateinfo.go +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) All respective contributors to the Peridot Project. All rights reserved. -// Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. -// Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package updateinfo - -import "encoding/xml" - -const ( - TimeFormat = "2006-01-02 15:04:05" -) - -type UpdatesRoot struct { - XMLName xml.Name `xml:"updates"` - Updates []*Update `xml:"update"` -} - -type UpdateDate struct { - Date string `xml:"date,attr"` -} - -type UpdateReference struct { - Href string `xml:"href,attr"` - ID string `xml:"id,attr"` - Type string `xml:"type,attr"` - Title string `xml:"title,attr"` -} - -type UpdateReferenceRoot struct { - References []*UpdateReference `xml:"reference"` -} - -type UpdatePackageSum struct { - Type string `xml:"type,attr"` - Value string `xml:",chardata"` -} - -type UpdatePackage struct { - Name string `xml:"name,attr"` - Version string `xml:"version,attr"` - Release string `xml:"release,attr"` - Epoch string `xml:"epoch,attr"` - Arch string `xml:"arch,attr"` - Src string `xml:"src,attr"` - Filename string `xml:"filename"` - RebootSuggested string `xml:"reboot_suggested"` - Sum []*UpdatePackageSum `xml:"sum"` -} - -type UpdateCollection struct { - Short string `xml:"short,attr"` - Name string `xml:"name"` - Packages []*UpdatePackage `xml:"package"` -} - -type UpdateCollectionRoot struct { - Collections []*UpdateCollection `xml:"collection"` -} - -type Update struct { - From string `xml:"from,attr"` - Status string `xml:"status,attr"` - Type string `xml:"type,attr"` - Version string `xml:"version,attr"` - ID string `xml:"id"` - Title string `xml:"title"` - Issued *UpdateDate `xml:"issued"` - Updated *UpdateDate `xml:"updated"` - Rights string `xml:"rights"` - Release string `xml:"release"` - PushCount string `xml:"pushcount"` - Severity string `xml:"severity"` - Summary string `xml:"summary"` - Description string `xml:"description"` - References *UpdateReferenceRoot `xml:"references"` - PkgList *UpdateCollectionRoot `xml:"pkglist"` -} From 1cac9ed958adaa8569e9b911dcd43d4da2ce222a Mon Sep 17 00:00:00 2001 From: Mustafa Gezen Date: Fri, 17 Feb 2023 19:43:07 +0100 Subject: [PATCH 3/3] Add a dummy placeholder for apollo tests --- apollo/BUILD.bazel | 4 ++++ apollo/test-dummy.sh | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100755 apollo/test-dummy.sh diff --git a/apollo/BUILD.bazel b/apollo/BUILD.bazel index e69de29..f2dbdb0 100644 --- a/apollo/BUILD.bazel +++ b/apollo/BUILD.bazel @@ -0,0 +1,4 @@ +sh_test( + name = "test-dummy", + srcs = ["test-dummy.sh"], +) diff --git a/apollo/test-dummy.sh b/apollo/test-dummy.sh new file mode 100755 index 0000000..7e30a2e --- /dev/null +++ b/apollo/test-dummy.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env sh +# +# Copyright (c) All respective contributors to the Peridot Project. All rights reserved. +# Copyright (c) 2021-2022 Rocky Enterprise Software Foundation, Inc. All rights reserved. +# Copyright (c) 2021-2022 Ctrl IQ, Inc. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# 3. Neither the name of the copyright holder nor the names of its contributors +# may be used to endorse or promote products derived from this software without +# specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# + +exit 0