diff --git a/.github/workflows/codehealth.yml b/.github/workflows/codehealth.yml index c200687..c558893 100644 --- a/.github/workflows/codehealth.yml +++ b/.github/workflows/codehealth.yml @@ -22,18 +22,20 @@ jobs: node-version: 22.4.1 check-latest: true - # Install eslint + - name: Use terraform + uses: hashicorp/setup-terraform@v3 + - name: Install packages working-directory: cloudrun-malware-scanner/ run: npm install - - name: ESlint + - name: Check ESlint working-directory: cloudrun-malware-scanner/ run: npm run eslint - name: Check Format working-directory: cloudrun-malware-scanner/ - run: npm run check-format -- --log-level warn + run: npm run check-format - name: Typescript checks working-directory: cloudrun-malware-scanner/ @@ -42,3 +44,15 @@ jobs: - name: NPM Audit working-directory: cloudrun-malware-scanner/ run: npm audit + + - name: terraform validate infra + working-directory: terraform/infra/ + run: | + terraform init -no-color + terraform validate -no-color + + - name: terraform validate service + working-directory: terraform/service/ + run: | + terraform init -no-color + terraform validate -no-color diff --git a/.gitignore b/.gitignore index 03cddf9..eabb11e 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,10 @@ cvds pyenv config.json .vscode + +# Terraform +*.tfstate +*.tfstate.backup +*.tfstate.lock.info +*.tfplan +.terraform diff --git a/cloudrun-malware-scanner/.gcloudignore b/cloudrun-malware-scanner/.gcloudignore index da72999..598b49f 100644 --- a/cloudrun-malware-scanner/.gcloudignore +++ b/cloudrun-malware-scanner/.gcloudignore @@ -3,3 +3,4 @@ pyenv node_modules .gcloudignore .eslintrc.js +config.json.tmpl diff --git a/cloudrun-malware-scanner/.husky/pre-commit b/cloudrun-malware-scanner/.husky/pre-commit index f24bc74..7f1c14a 100644 --- a/cloudrun-malware-scanner/.husky/pre-commit +++ b/cloudrun-malware-scanner/.husky/pre-commit @@ -4,4 +4,5 @@ cd cloudrun-malware-scanner npm run eslint npm run check-format npm run typecheck +npm run terraform-validate npm audit diff --git a/cloudrun-malware-scanner/.prettierignore b/cloudrun-malware-scanner/.prettierignore index 784342a..4172e82 100644 --- a/cloudrun-malware-scanner/.prettierignore +++ b/cloudrun-malware-scanner/.prettierignore @@ -9,3 +9,4 @@ package-lock.json public CHANGELOG.md ../.release-please-manifest.json +../terraform/*/.terraform diff --git a/cloudrun-malware-scanner/cloudbuild.yaml b/cloudrun-malware-scanner/cloudbuild.yaml new file mode 100644 index 0000000..f088889 --- /dev/null +++ b/cloudrun-malware-scanner/cloudbuild.yaml @@ -0,0 +1,28 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +steps: + - name: "gcr.io/cloud-builders/docker" + args: + [ + "build", + "--tag=$LOCATION-docker.pkg.dev/$PROJECT_ID/malware-scanner/malware-scanner:latest", + "-f", + "Dockerfile", + ".", + ] +images: + - "$LOCATION-docker.pkg.dev/$PROJECT_ID/malware-scanner/malware-scanner:latest" +options: + logging: "CLOUD_LOGGING_ONLY" diff --git a/cloudrun-malware-scanner/package.json b/cloudrun-malware-scanner/package.json index 622c697..229a190 100644 --- a/cloudrun-malware-scanner/package.json +++ b/cloudrun-malware-scanner/package.json @@ -4,9 +4,13 @@ "description": "Service to scan GCS documents for the malware and move the analyzed documents to appropriate buckets", "main": "index.js", "scripts": { - "check-format": "prettier --config .prettierrc.js --check ..", + "check-format": "npm run prettier-check && npm run terraform-fmt-check", "start": "node server.js", + "terraform-fmt": "terraform fmt ../terraform/*/*.tf ../terraform/*/*/*.tf", + "terraform-fmt-check": "terraform fmt -check ../terraform/*/*.tf ../terraform/*/*/*.tf", + "terraform-validate": "echo 'validating terraform/infra' && cd ../terraform/infra && terraform init && terraform validate && echo 'validating terraform/service' && cd ../service && terraform init && terraform validate", "prettier": "prettier --config .prettierrc.js --write ..", + "prettier-check": "prettier --config .prettierrc.js --check --log-level=warn ..", "start-proxy": "node gcs-proxy-server.js", "test": "echo \"Error: no test specified\" && exit 1", "eslint": "eslint *.js", diff --git a/release-please-config.json b/release-please-config.json index 977279a..42545eb 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -7,7 +7,11 @@ "bump-patch-for-minor-pre-major": false, "draft": false, "prerelease": false, - "include-component-in-tag": false + "include-component-in-tag": false, + "extra-files": [ + "terraform/infra/versions.tf", + "terraform/service/versions.tf" + ] } }, "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json" diff --git a/terraform/README.md b/terraform/README.md new file mode 100644 index 0000000..d93eeaa --- /dev/null +++ b/terraform/README.md @@ -0,0 +1,219 @@ +# Terraform deployment + +This directory contains the terraform files required to deploy the +malware-scanner service on cloud run. + +The deployment is split into 4 stages: + +1. Set up the google cloud project environment and service configuration. +1. Use Terraform to set up the required service accounts and deploy required + infrastructure. +1. Launch cloud build to build the Docker image for the malware-scanner + service. +1. Use Terraform to deploy the malware-scanner service to cloud run, and + connect the service to the infrastructure created in stage 2. + +Follow the instructions below to use Terraform to deploy the malware scanner +service in a demo project. + +## Create a project and assign billing + +Using the Cloud Console, create a new Cloud project, and assign the billing +account. Take note of the Project ID of your new project. + +## Clone repo + +In Cloud shell, run the following to pull the malware-scanner source code from +GitHub. + +```bash +git clone https://github.com/GoogleCloudPlatform/docker-clamav-malware-scanner.git +cd docker-clamav-malware-scanner +``` + +## Initialize environment with service configuration + +Run the following commands in Cloud Shell to setup your environment and specify +the parameters of your service for the Terraform deployment. + +Replace `MY_PROJECT_ID` with the ID of your newly created Project. + +```bash + +PROJECT_ID=MY_PROJECT_ID +gcloud config set project $PROJECT_ID + +TF_VAR_project_id=$PROJECT_ID +TF_VAR_config_json=$(cat < **Error:** Error creating Trigger: googleapi: Error 400: Invalid resource +> state for "": Permission denied while using the Eventarc Service Agent. If you +> recently started to use Eventarc, it may take a few minutes before all +> necessary permissions are propagated to the Service Agent. Otherwise, verify +> that it has Eventarc Service Agent role. + +## Test the service + +### Get version info from cloud run + +You can query the malware-scanner service for the version information: + +```bash +MALWARE_SCANNER_URL="$(terraform output -raw cloud_run_uri)" +curl -H "Authorization: Bearer $(gcloud auth print-identity-token)" \ + "${MALWARE_SCANNER_URL}" +``` + +This command will output lines showing the versions of the malware scanner, +ClamAV and the current malware definitions version/datem for example: + +```text +gcs-malware-scanner version 3.0.0 +Using Clam AV version: ClamAV 1.0.5/27396/Thu Sep 12 08:46:40 2024 + +Service to scan GCS documents for the malware and move the analyzed documents to appropriate buckets +``` + +### Create and scan a clean file and an simulated infected file + +Run the following command to create 2 files in the unscanned bucket, a simple +`clean.txt` file and an `eicar-infected.txt` file containing a +[test string which simulates a virus](https://en.wikipedia.org/wiki/EICAR_test_file) + +```bash +echo -e 'HELLO WORLD!' \ + | gcloud storage cp - "gs://unscanned-${PROJECT_ID}/clean.txt" +echo -e 'X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*' \ + | gcloud storage cp - "gs://unscanned-${PROJECT_ID}/eicar-infected.txt" +``` + +Check contents of the unscanned bucket + +```bash +gcloud storage ls gs://unscanned-${PROJECT_ID}/ +``` + +This should return no results as the files will have been moved by the +malware-scanner. If the files still exist, re-run the command after a couple of +seconds. + +Check contents of the clean files bucket + +```bash +gcloud storage ls gs://clean-${PROJECT_ID}/ +``` + +This should show that the clean.txt file has been moved to the clean bucket. + +Check contents of the quarantined bucket: + +```bash +gcloud storage ls gs://quarantined-${PROJECT_ID}/ +``` + +This should show that the eicar-infected.txt file has been moved to the +quarantined bucket. + +Show the log items with the scan status: + +```bash +gcloud logging read \ + 'resource.labels.service_name = "malware-scanner" AND "Scan status for"' \ + --limit=10 --format='value(jsonPayload.message)' +``` + +This will output log lines similar to: + +```text +Scan status for gs://unscanned-PROJECT_ID/clean.txt: CLEAN (13 bytes in 85 ms) +Scan status for gs://unscanned-PROJECT_ID/eicar-infected.txt: INFECTED stream: Eicar-Signature FOUND (69 bytes in 77 ms) +``` diff --git a/terraform/infra/.terraform.lock.hcl b/terraform/infra/.terraform.lock.hcl new file mode 100644 index 0000000..74fc3dc --- /dev/null +++ b/terraform/infra/.terraform.lock.hcl @@ -0,0 +1,41 @@ +# This file is maintained automatically by "terraform init". +# Manual edits may be lost in future updates. + +provider "registry.terraform.io/hashicorp/google" { + version = "6.2.0" + constraints = ">= 6.2.0" + hashes = [ + "h1:7JIgzQKRW0AT6UliiYSjYUKxDr03baZpQmt5XVkrujs=", + "zh:08a7dc0b53d2b63baab928e66086bf3e09107516af078ce011d2667456e64834", + "zh:1cf9a1373e516844b43fdcea36e73f5a68f19ad07afcf6093788eb235c710163", + "zh:2d4a7cb26c3f0d036d51db219a09013d3d779e44d584e0fc631df0f2cd5e5550", + "zh:47e1fc68e455f99f1875deaed9aa5434a852e2a70a3cb5a5e9b5a2d8c25d7b74", + "zh:78531a8624ddcd45277e1b465e773ac92001ea0e200e9dc1147ebeb24d56359e", + "zh:a76751723c034d44764df22925178f78d8b4852e3e6ac6c5d86f51666c9e666c", + "zh:a83a59a7e667cfffb0d501a501e9b3d2d4fcc83deb07a318c9690d537cbdc4b6", + "zh:b16473b7e59e01690d8234a0044c304505688f5518b205e9ed06fc63ddc82977", + "zh:b957648ad0383e17149bf3a02def81ebc6bd55ca0cffb6ec1c368a1b4f33c4fd", + "zh:e2f3f4a27b41a20bdbb7a80fbcde1a4c36bbd1c83edb9256bc1724754f8d370f", + "zh:ecfce738f85a81603aa51162d5237d6faaa2ffc0f0e52694f8b420ad761a8957", + "zh:f569b65999264a9416862bca5cd2a6177d94ccb0424f3a4ef424428912b9cb3c", + ] +} + +provider "registry.terraform.io/hashicorp/null" { + version = "3.2.3" + hashes = [ + "h1:+AnORRgFbRO6qqcfaQyeX80W0eX3VmjadjnUFUJTiXo=", + "zh:22d062e5278d872fe7aed834f5577ba0a5afe34a3bdac2b81f828d8d3e6706d2", + "zh:23dead00493ad863729495dc212fd6c29b8293e707b055ce5ba21ee453ce552d", + "zh:28299accf21763ca1ca144d8f660688d7c2ad0b105b7202554ca60b02a3856d3", + "zh:55c9e8a9ac25a7652df8c51a8a9a422bd67d784061b1de2dc9fe6c3cb4e77f2f", + "zh:756586535d11698a216291c06b9ed8a5cc6a4ec43eee1ee09ecd5c6a9e297ac1", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:9d5eea62fdb587eeb96a8c4d782459f4e6b73baeece4d04b4a40e44faaee9301", + "zh:a6355f596a3fb8fc85c2fb054ab14e722991533f87f928e7169a486462c74670", + "zh:b5a65a789cff4ada58a5baffc76cb9767dc26ec6b45c00d2ec8b1b027f6db4ed", + "zh:db5ab669cf11d0e9f81dc380a6fdfcac437aea3d69109c7aef1a5426639d2d65", + "zh:de655d251c470197bcbb5ac45d289595295acb8f829f6c781d4a75c8c8b7c7dd", + "zh:f5c68199f2e6076bce92a12230434782bf768103a427e9bb9abee99b116af7b5", + ] +} diff --git a/terraform/infra/apis/main.tf b/terraform/infra/apis/main.tf new file mode 100644 index 0000000..66c4030 --- /dev/null +++ b/terraform/infra/apis/main.tf @@ -0,0 +1,34 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +## Enable APIs +# +# Requires that the following APIs are already enabled: +# cloudresourcemanager.googleapis.com +# serviceusage.googleapis.com +# +resource "google_project_service" "apis" { + for_each = toset([ + "artifactregistry.googleapis.com", + "cloudbuild.googleapis.com", + "cloudscheduler.googleapis.com", + "eventarc.googleapis.com", + "logging.googleapis.com", + "monitoring.googleapis.com", + "pubsub.googleapis.com", + "run.googleapis.com", + ]) + service = each.key +} + diff --git a/terraform/infra/create_buckets/main.tf b/terraform/infra/create_buckets/main.tf new file mode 100644 index 0000000..e6e8acf --- /dev/null +++ b/terraform/infra/create_buckets/main.tf @@ -0,0 +1,35 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +variable "bucket_location" { + description = "Location to create Cloud Storage buckets" +} + +variable "uniform_bucket_level_access" { + description = "When creating cloud storage buckets, the parameter uniform_bucket_level_access is set to this value" + default = true + type = bool +} + +variable "bucket_names" { + description = "The set of bucket names to create" + type = set(string) +} + +resource "google_storage_bucket" "scanner_buckets" { + for_each = var.bucket_names + name = each.key + location = var.bucket_location + uniform_bucket_level_access = var.uniform_bucket_level_access +} diff --git a/terraform/infra/main.tf b/terraform/infra/main.tf new file mode 100644 index 0000000..8460cd5 --- /dev/null +++ b/terraform/infra/main.tf @@ -0,0 +1,147 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +provider "google" { + project = var.project_id + region = var.region +} + +locals { + repo_root = abspath("${path.module}/../..") + src_root = abspath("${local.repo_root}/cloudrun-malware-scanner") + + ## Read config and extract bucket names + config_json = jsondecode(var.config_json) + cvd_mirror_bucket = local.config_json.ClamCvdMirrorBucket + unscanned_bucket_names = local.config_json.buckets[*].unscanned + clean_bucket_names = local.config_json.buckets[*].clean + quarantined_bucket_names = local.config_json.buckets[*].quarantined + all_buckets = toset(concat(local.clean_bucket_names, local.unscanned_bucket_names, local.quarantined_bucket_names)) +} + +## Enable the APIs +module "apis" { + source = "./apis" + count = var.enable_apis ? 1 : 0 +} + +## Create the service accounts for scanner and builder, and add roles +# +resource "google_service_account" "malware_scanner_sa" { + account_id = var.service_name + display_name = "Service Account for malware scanner cloud run service" + depends_on = [module.apis] +} + +resource "google_project_iam_member" "malware_scanner_iam" { + for_each = toset(["roles/monitoring.metricWriter", "roles/run.invoker", "roles/eventarc.eventReceiver"]) + project = var.project_id + role = each.value + member = "serviceAccount:${google_service_account.malware_scanner_sa.email}" +} + +resource "google_service_account" "build_service_account" { + account_id = "${var.service_name}-build" + display_name = "Service Account for malware scanner cloud run service" + depends_on = [module.apis] +} + +resource "google_project_iam_binding" "build_iam" { + for_each = toset(["roles/storage.objectViewer", "roles/logging.logWriter", "roles/artifactregistry.writer"]) + project = var.project_id + role = each.value + members = ["serviceAccount:${google_service_account.build_service_account.email}"] +} + +resource "google_artifact_registry_repository" "repo" { + location = var.region + repository_id = var.service_name + description = "Image registry for Malware Scanner" + format = "DOCKER" + depends_on = [module.apis] +} + +## Allow GCS to publish to pubsub +# +data "google_storage_project_service_account" "gcs_account" { + depends_on = [module.apis] +} +resource "google_project_iam_binding" "gcs_sa_pubsub_publish" { + project = var.project_id + role = "roles/pubsub.publisher" + members = ["serviceAccount:${data.google_storage_project_service_account.gcs_account.email_address}"] +} + +## Create configured scanner buckets if requested. +# +module "create_buckets" { + source = "./create_buckets" + count = var.create_buckets ? 1 : 0 + bucket_location = var.bucket_location + uniform_bucket_level_access = var.uniform_bucket_level_access + bucket_names = local.all_buckets + depends_on = [module.apis] +} + +## Allow service account to admin the scanner buckets. +# +# They may not have been created by TF, so use a data resource +# to verify their existence. +# +data "google_storage_bucket" "scanner-buckets" { + for_each = local.all_buckets + name = each.value + depends_on = [module.create_buckets] +} +resource "google_storage_bucket_iam_binding" "buckets_sa_binding" { + for_each = local.all_buckets + bucket = data.google_storage_bucket.scanner-buckets[each.key].name + role = "roles/storage.admin" + members = [ + "serviceAccount:${google_service_account.malware_scanner_sa.email}", + ] +} + +## Create the CVD Mirror bucket and allow service account admin access. +# +resource "google_storage_bucket" "cvd_mirror_bucket" { + name = local.cvd_mirror_bucket + location = var.bucket_location + uniform_bucket_level_access = var.uniform_bucket_level_access + depends_on = [module.apis] +} +resource "google_storage_bucket_iam_binding" "cvd_mirror_bucket_sa_binding" { + bucket = google_storage_bucket.cvd_mirror_bucket.name + role = "roles/storage.admin" + members = [ + "serviceAccount:${google_service_account.malware_scanner_sa.email}", + ] +} + +## Perform an update/initial load of mirror bucket. +# +resource "null_resource" "populate_cvd_mirror" { + provisioner "local-exec" { + command = join(" ; ", [ + "echo '\n\nPopulating CVD Mirror bucket ${google_storage_bucket.cvd_mirror_bucket.name}\n\n'", + "python3 -m venv pyenv", + ". pyenv/bin/activate", + "pip3 install crcmod cvdupdate", + "./updateCvdMirror.sh '${google_storage_bucket.cvd_mirror_bucket.name}'", + "echo '\n\nPopulating CVD Mirror bucket successful\n\n'", + ]) + interpreter = ["bash", "-x", "-e", "-c"] + working_dir = local.src_root + } +} diff --git a/terraform/infra/variables.tf b/terraform/infra/variables.tf new file mode 100644 index 0000000..ec0eb35 --- /dev/null +++ b/terraform/infra/variables.tf @@ -0,0 +1,52 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +variable "project_id" { + description = "Google Cloud Project ID to use" +} + +variable "bucket_location" { + description = "Location to create Cloud Storage buckets" +} + +variable "region" { + description = "Region name for creation of resources" +} + +variable "service_name" { + default = "malware-scanner" +} + +variable "config_json" { + description = "String containing JSON encoded configuration to pass to the cloud run service as environment variable CONFIG_JSON" + type = string +} + +variable "enable_apis" { + description = "Automatically enable required APIs (requires that cloudresourcemanager.googleapis.com and serviceusage.googleapis.com are already enabled)" + default = true + type = bool +} + +variable "create_buckets" { + description = "Creates all the unscanned, clean, and quarantined buckets defined in the config. " + default = true + type = bool +} + +variable "uniform_bucket_level_access" { + description = "When creating cloud storage buckets, the parameter uniform_bucket_level_access is set to this value" + default = true + type = bool +} diff --git a/terraform/infra/versions.tf b/terraform/infra/versions.tf new file mode 100644 index 0000000..680fcc0 --- /dev/null +++ b/terraform/infra/versions.tf @@ -0,0 +1,27 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +terraform { + required_providers { + google = { + source = "hashicorp/google" + version = ">= 6.2.0" + } + } + required_version = ">= 1.5" + + provider_meta "google" { + module_name = "cloud-solutions/gcs-malware-scanner-deploy-v3.1.0" # x-release-please-version + } +} diff --git a/terraform/service/.terraform.lock.hcl b/terraform/service/.terraform.lock.hcl new file mode 100644 index 0000000..162cc1c --- /dev/null +++ b/terraform/service/.terraform.lock.hcl @@ -0,0 +1,61 @@ +# This file is maintained automatically by "terraform init". +# Manual edits may be lost in future updates. + +provider "registry.terraform.io/hashicorp/google" { + version = "6.2.0" + constraints = ">= 6.2.0" + hashes = [ + "h1:7JIgzQKRW0AT6UliiYSjYUKxDr03baZpQmt5XVkrujs=", + "zh:08a7dc0b53d2b63baab928e66086bf3e09107516af078ce011d2667456e64834", + "zh:1cf9a1373e516844b43fdcea36e73f5a68f19ad07afcf6093788eb235c710163", + "zh:2d4a7cb26c3f0d036d51db219a09013d3d779e44d584e0fc631df0f2cd5e5550", + "zh:47e1fc68e455f99f1875deaed9aa5434a852e2a70a3cb5a5e9b5a2d8c25d7b74", + "zh:78531a8624ddcd45277e1b465e773ac92001ea0e200e9dc1147ebeb24d56359e", + "zh:a76751723c034d44764df22925178f78d8b4852e3e6ac6c5d86f51666c9e666c", + "zh:a83a59a7e667cfffb0d501a501e9b3d2d4fcc83deb07a318c9690d537cbdc4b6", + "zh:b16473b7e59e01690d8234a0044c304505688f5518b205e9ed06fc63ddc82977", + "zh:b957648ad0383e17149bf3a02def81ebc6bd55ca0cffb6ec1c368a1b4f33c4fd", + "zh:e2f3f4a27b41a20bdbb7a80fbcde1a4c36bbd1c83edb9256bc1724754f8d370f", + "zh:ecfce738f85a81603aa51162d5237d6faaa2ffc0f0e52694f8b420ad761a8957", + "zh:f569b65999264a9416862bca5cd2a6177d94ccb0424f3a4ef424428912b9cb3c", + ] +} + +provider "registry.terraform.io/hashicorp/null" { + version = "3.2.3" + hashes = [ + "h1:+AnORRgFbRO6qqcfaQyeX80W0eX3VmjadjnUFUJTiXo=", + "zh:22d062e5278d872fe7aed834f5577ba0a5afe34a3bdac2b81f828d8d3e6706d2", + "zh:23dead00493ad863729495dc212fd6c29b8293e707b055ce5ba21ee453ce552d", + "zh:28299accf21763ca1ca144d8f660688d7c2ad0b105b7202554ca60b02a3856d3", + "zh:55c9e8a9ac25a7652df8c51a8a9a422bd67d784061b1de2dc9fe6c3cb4e77f2f", + "zh:756586535d11698a216291c06b9ed8a5cc6a4ec43eee1ee09ecd5c6a9e297ac1", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:9d5eea62fdb587eeb96a8c4d782459f4e6b73baeece4d04b4a40e44faaee9301", + "zh:a6355f596a3fb8fc85c2fb054ab14e722991533f87f928e7169a486462c74670", + "zh:b5a65a789cff4ada58a5baffc76cb9767dc26ec6b45c00d2ec8b1b027f6db4ed", + "zh:db5ab669cf11d0e9f81dc380a6fdfcac437aea3d69109c7aef1a5426639d2d65", + "zh:de655d251c470197bcbb5ac45d289595295acb8f829f6c781d4a75c8c8b7c7dd", + "zh:f5c68199f2e6076bce92a12230434782bf768103a427e9bb9abee99b116af7b5", + ] +} + +provider "registry.terraform.io/hashicorp/random" { + version = "3.6.3" + constraints = ">= 3.6.3" + hashes = [ + "h1:Fnaec9vA8sZ8BXVlN3Xn9Jz3zghSETIKg7ch8oXhxno=", + "zh:04ceb65210251339f07cd4611885d242cd4d0c7306e86dda9785396807c00451", + "zh:448f56199f3e99ff75d5c0afacae867ee795e4dfda6cb5f8e3b2a72ec3583dd8", + "zh:4b4c11ccfba7319e901df2dac836b1ae8f12185e37249e8d870ee10bb87a13fe", + "zh:4fa45c44c0de582c2edb8a2e054f55124520c16a39b2dfc0355929063b6395b1", + "zh:588508280501a06259e023b0695f6a18149a3816d259655c424d068982cbdd36", + "zh:737c4d99a87d2a4d1ac0a54a73d2cb62974ccb2edbd234f333abd079a32ebc9e", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:a357ab512e5ebc6d1fda1382503109766e21bbfdfaa9ccda43d313c122069b30", + "zh:c51bfb15e7d52cc1a2eaec2a903ac2aff15d162c172b1b4c17675190e8147615", + "zh:e0951ee6fa9df90433728b96381fb867e3db98f66f735e0c3e24f8f16903f0ad", + "zh:e3cdcb4e73740621dabd82ee6a37d6cfce7fee2a03d8074df65086760f5cf556", + "zh:eff58323099f1bd9a0bec7cb04f717e7f1b2774c7d612bf7581797e1622613a0", + ] +} diff --git a/terraform/service/main.tf b/terraform/service/main.tf new file mode 100644 index 0000000..58b0f2c --- /dev/null +++ b/terraform/service/main.tf @@ -0,0 +1,148 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +provider "google" { + project = var.project_id + region = var.region +} + +## Read config and extract bucket names +locals { + config_json = jsondecode(var.config_json) + unscanned_bucket_names = local.config_json.buckets[*].unscanned +} + +## Verify service account exists +# +data "google_service_account" "malware_scanner_sa" { + account_id = var.service_name +} + +## Lookup the hash of the latest image +## +data "google_artifact_registry_docker_image" "scanner-service-image" { + location = var.region + repository_id = var.service_name + image_name = "${var.service_name}:latest" +} + +## Deploy the Cloud Run Service +# +resource "google_cloud_run_v2_service" "malware_scanner" { + name = var.service_name + location = var.region + ingress = "INGRESS_TRAFFIC_ALL" + + template { + scaling { + max_instance_count = 5 + min_instance_count = 1 + } + service_account = data.google_service_account.malware_scanner_sa.email + containers { + image = data.google_artifact_registry_docker_image.scanner-service-image.self_link + resources { + limits = { + cpu = "1" + memory = "4Gi" + } + cpu_idle = false # CPU is still allocated outside of requests + startup_cpu_boost = true + } + env { + name = "CONFIG_JSON" + value = var.config_json + } + } + max_instance_request_concurrency = 20 + } + traffic { + type = "TRAFFIC_TARGET_ALLOCATION_TYPE_LATEST" + percent = 100 + } +} + +## Verify unscanned bucket(s) exist +# +data "google_storage_bucket" "unscanned-bucket" { + for_each = toset(local.unscanned_bucket_names) + name = each.value +} + +## Create EventArc Triggers on unscanned bucket(s) +# +resource "google_eventarc_trigger" "gcs-object-written" { + for_each = toset(local.unscanned_bucket_names) + name = "gcs-trigger-${each.value}" + location = var.bucket_location + matching_criteria { + attribute = "type" + value = "google.cloud.storage.object.v1.finalized" + } + matching_criteria { + attribute = "bucket" + value = data.google_storage_bucket.unscanned-bucket[each.value].name + } + destination { + cloud_run_service { + service = google_cloud_run_v2_service.malware_scanner.name + region = google_cloud_run_v2_service.malware_scanner.location + } + } + service_account = data.google_service_account.malware_scanner_sa.email +} + +## Update pubsub subscriptions to increase deadlines +# +resource "null_resource" "update-subscription-ack-deadline" { + for_each = toset(local.unscanned_bucket_names) + provisioner "local-exec" { + command = "gcloud pubsub subscriptions update \"${google_eventarc_trigger.gcs-object-written[each.key].transport[0].pubsub[0].subscription}\" --ack-deadline=120" + } +} + +## Deploy scheduled task to refresh the CVD Mirror + +# To avoid having too many clients use the same time slot, +# ClamAV requires that updates are scheduled at a random minute between 3 +# and 57 avoiding multiples of 10. +resource "random_shuffle" "minutes" { + input = [ + "3", "4", "5", "6", "7", "8", "9", + "11", "12", "13", "14", "15", "16", "17", "18", "19", + "21", "22", "23", "24", "25", "26", "27", "28", "29", + "31", "32", "33", "34", "35", "36", "37", "38", "39", + "41", "42", "43", "44", "45", "46", "47", "48", "49", + "51", "52", "53", "54", "55", "56", "57" + ] + result_count = 1 +} + +resource "google_cloud_scheduler_job" "cvd_mirror_update" { + name = "${var.service_name}-cvd-mirror-update" + schedule = "${random_shuffle.minutes.result[0]} */2 * * *" + attempt_deadline = "320s" + region = var.region + http_target { + http_method = "POST" + uri = google_cloud_run_v2_service.malware_scanner.uri + body = base64encode("{\"kind\":\"schedule#cvd_update\"}") + headers = { + "Content-Type" = "application/json" + } + oidc_token { + service_account_email = data.google_service_account.malware_scanner_sa.email + } + } +} diff --git a/terraform/service/outputs.tf b/terraform/service/outputs.tf new file mode 100644 index 0000000..42549c1 --- /dev/null +++ b/terraform/service/outputs.tf @@ -0,0 +1,18 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +output "cloud_run_uri" { + value = google_cloud_run_v2_service.malware_scanner.uri + description = "Cloud Run URI for malware-scanner service" +} diff --git a/terraform/service/variables.tf b/terraform/service/variables.tf new file mode 100644 index 0000000..1817801 --- /dev/null +++ b/terraform/service/variables.tf @@ -0,0 +1,34 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +variable "project_id" { + description = "Google Cloud Project ID to use" +} + +variable "bucket_location" { + description = "Location to create Cloud Storage buckets" +} + +variable "region" { + description = "Region name for creation of resources" +} + +variable "service_name" { + default = "malware-scanner" +} + +variable "config_json" { + description = "String containing JSON encoded configuration to pass to the cloud run service as environment variable CONFIG_JSON" + type = string +} diff --git a/terraform/service/versions.tf b/terraform/service/versions.tf new file mode 100644 index 0000000..36ba40b --- /dev/null +++ b/terraform/service/versions.tf @@ -0,0 +1,31 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +terraform { + required_providers { + google = { + source = "hashicorp/google" + version = ">= 6.2.0" + } + random = { + source = "hashicorp/random" + version = ">= 3.6.3" + } + } + required_version = ">= 1.5" + + provider_meta "google" { + module_name = "cloud-solutions/gcs-malware-scanner-deploy-v3.1.0" # x-release-please-version + } +}