/*
    Copyright (C) 2022 Tenable, Inc.

	Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

		http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

package vulnerability_test

import (
	"io"
	"os"
	"path/filepath"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gbytes"
	vulnUtils "github.com/tenable/terrascan/test/e2e/vulnerability"
	"github.com/tenable/terrascan/test/helper"
)

var (
	terrascanBinaryPath  string
	iacRootRelPath       = filepath.Join("..", "test_data", "iac")
	policyRootRelPath    = filepath.Join("..", "test_data", "policies")
	outWriter, errWriter io.Writer
	tempFile             *os.File
	err                  error
)

const (
	googleApplicationKeyTestEnvName = "GOOGLE_APPLICATION_CREDENTIALS_TEST_SECRET"
	googleApplicationKeyEnvName     = "GOOGLE_APPLICATION_CREDENTIALS"
	azureAuthKeyTestEnvName         = "AZURE_AUTH_TEST_SECRET"
	azureAuthKeyEnvName             = "AZURE_AUTH_LOCATION"
)

var _ = Describe("Vulnerability", func() {

	BeforeSuite(func() {
		terrascanBinaryPath = helper.GetTerrascanBinaryPath()
	})

	BeforeEach(func() {
		outWriter = gbytes.NewBuffer()
		errWriter = gbytes.NewBuffer()
	})

	AfterEach(func() {
		outWriter = nil
		errWriter = nil
	})

	Describe("resource with container images to be scanned for vulnerabilities", func() {
		resourceVulnerabilityIacRelPath := filepath.Join(iacRootRelPath, "resource_for_vulnerability_scan")
		Context("resource with aws ecr registry image used which has vulnerabilities", func() {
			iacDir := filepath.Join(resourceVulnerabilityIacRelPath, "aws_ecr_registry_used_in_resource")
			PIt("should display vulnerabilities and vulnerability count should be present in scan summary", func() {
				scanArgs := []string{"-p", policyRootRelPath, "-i", "terraform", "-d", iacDir, "-o", "json"}
				// exit code is zero since no violations are present for resource
				vulnUtils.RunScanAndVerifyVulnerabilityCount(terrascanBinaryPath, helper.ExitCodeZero, 1, outWriter, errWriter, scanArgs...)
			})
		})
		Context("resource with azure registry image used which has vulnerabilities", func() {
			iacDir := filepath.Join(resourceVulnerabilityIacRelPath, "azure_registry_used_in_resource")
			JustBeforeEach(func() {
				data := os.Getenv(azureAuthKeyTestEnvName)
				if data != "" {
					tempFile, err = os.CreateTemp("", "azure.auth")
					Expect(err).NotTo(HaveOccurred())
					tempFile.Write([]byte(data))
					os.Setenv(azureAuthKeyEnvName, tempFile.Name())
				}
			})
			JustAfterEach(func() {
				if tempFile != nil && tempFile.Name() != "" {
					os.Remove(tempFile.Name())
				}
			})
			PIt("should display vulnerabilities and  vulnerability count should be present in scan summary", func() {
				scanArgs := []string{"-p", policyRootRelPath, "-i", "terraform", "-d", iacDir, "-o", "json"}
				// exit code is zero since no violations are present for resource
				vulnUtils.RunScanAndVerifyVulnerabilityCount(terrascanBinaryPath, helper.ExitCodeZero, 1, outWriter, errWriter, scanArgs...)
			})
		})
		Context("resource with google registry image used which has vulnerabilities", func() {
			iacDir := filepath.Join(resourceVulnerabilityIacRelPath, "google_gcr_registry_used_in_resource")
			JustBeforeEach(func() {
				data := os.Getenv(googleApplicationKeyTestEnvName)
				if data != "" {
					tempFile, err = os.CreateTemp("", "app-key.json")
					Expect(err).NotTo(HaveOccurred())
					tempFile.Write([]byte(data))
					os.Setenv(googleApplicationKeyEnvName, tempFile.Name())
				}
			})
			JustAfterEach(func() {
				if tempFile != nil && tempFile.Name() != "" {
					os.Remove(tempFile.Name())
				}
			})
			PIt("should display vulnerabilities and  vulnerability count should be present in scan summary", func() {
				scanArgs := []string{"-p", policyRootRelPath, "-i", "k8s", "-d", iacDir, "-o", "json"}
				// exit code is zero since no violations are present for resource
				vulnUtils.RunScanAndVerifyVulnerabilityCount(terrascanBinaryPath, helper.ExitCodeZero, 1, outWriter, errWriter, scanArgs...)
			})
		})
	})
})
