package agent_test

import (
	"encoding/json"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/module/starboard_vulnerability/agent"
	report "gitlab.com/gitlab-org/security-products/analyzers/report/v3"
)

func TestConvert(t *testing.T) {
	rawFindings := []byte(`
		[
			{
				"Namespace": "default",
				"Kind": "Deployment",
				"Name": "nginx",
				"Results": [
					{
						"Target": "nginx:alpine (alpine 3.17.3)",
						"Class": "os-pkgs",
						"Type": "alpine"
					}
				]
			},
			{
				"Namespace": "default",
				"Kind": "Deployment",
				"Name": "nginx116",
				"Results": [
					{
						"Target": "nginx:1.16 (debian 10.3)",
						"Class": "os-pkgs",
						"Type": "debian",
						"Vulnerabilities": [
							{
								"VulnerabilityID": "CVE-2020-27350",
								"PkgName": "apt",
								"InstalledVersion": "1.8.2",
								"FixedVersion": "1.8.2.2",
								"PrimaryURL": "https://avd.aquasec.com/nvd/cve-2020-27350",
								"Title": "apt: integer overflows and underflows while parsing .deb packages",
								"Description": "APT had several integer overflows and underflows while parsing .deb packages, aka GHSL-2020-168 GHSL-2020-169, in files apt-pkg/contrib/extracttar.cc, apt-pkg/deb/debfile.cc, and apt-pkg/contrib/arfile.cc. This issue affects: apt 1.2.32ubuntu0 versions prior to 1.2.32ubuntu0.2; 1.6.12ubuntu0 versions prior to 1.6.12ubuntu0.2; 2.0.2ubuntu0 versions prior to 2.0.2ubuntu0.2; 2.1.10ubuntu0 versions prior to 2.1.10ubuntu0.1;",
								"Severity": "MEDIUM",
								"References": [
									"https://access.redhat.com/security/cve/CVE-2020-27350",
									"https://bugs.launchpad.net/bugs/1899193"
								],
								"PublishedDate": "2020-12-10T04:15:00Z",
								"LastModifiedDate": "2022-10-29T02:41:00Z"
							}
						]
					}
				]
			},
			{
				"Namespace": "default",
				"Kind": "Pod",
				"Name": "trivy-scanner",
				"Results": [
					{
						"Target": "aquasec/trivy:0.38.3 (alpine 3.17.2)",
						"Class": "os-pkgs",
						"Type": "alpine",
						"Vulnerabilities": [
							{
								"VulnerabilityID": "CVE-2023-0464",
								"PkgName": "libcrypto3",
								"InstalledVersion": "3.0.8-r0",
								"FixedVersion": "3.0.8-r1",
								"PrimaryURL": "https://avd.aquasec.com/nvd/cve-2023-0464",
								"Title": "openssl: Denial of service by excessive resource usage in verifying X509 policy constraints",
								"Description": "A security vulnerability has been identified in all supported versions of OpenSSL related to the verification of X.509 certificate chains that include policy constraints. Attackers may be able to exploit this vulnerability by creating a malicious certificate chain that triggers exponential use of computational resources, leading to a denial-of-service (DoS) attack on affected systems. Policy processing is disabled by default but can be enabled by passing the '-policy' argument to the command line utilities or by calling the 'X509_VERIFY_PARAM_set1_policies()' function.",
								"Severity": "HIGH",
								"References": [
									"https://access.redhat.com/security/cve/CVE-2023-0464",
									"https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-0464"
								],
								"PublishedDate": "2023-03-22T17:15:00Z",
								"LastModifiedDate": "2023-03-29T19:37:00Z"
							}
						]
					},
					{
						"Target": "usr/local/bin/trivy",
						"Class": "lang-pkgs",
						"Type": "gobinary",
						"Vulnerabilities": [
							{
								"VulnerabilityID": "CVE-2020-8911",
								"PkgName": "github.com/aws/aws-sdk-go",
								"InstalledVersion": "v1.44.212",
								"PrimaryURL": "https://avd.aquasec.com/nvd/cve-2020-8911",
								"Title": "aws/aws-sdk-go: CBC padding oracle issue in AWS S3 Crypto SDK for golang",
								"Description": "A padding oracle vulnerability exists in the AWS S3 Crypto SDK for GoLang versions prior to V2. The SDK allows users to encrypt files with AES-CBC without computing a Message Authentication Code (MAC), which then allows an attacker who has write access to the target's S3 bucket and can observe whether or not an endpoint with access to the key can decrypt a file, they can reconstruct the plaintext with (on average) 128*length (plaintext) queries to the endpoint, by exploiting CBC's ability to manipulate the bytes of the next block and PKCS5 padding errors. It is recommended to update your SDK to V2 or later, and re-encrypt your files.",
								"Severity": "MEDIUM",
								"References": [
									"https://access.redhat.com/security/cve/CVE-2020-8911",
									"https://aws.amazon.com/blogs/developer/updates-to-the-amazon-s3-encryption-client/?s=09"
								],
								"PublishedDate": "2020-08-11T20:15:00Z",
								"LastModifiedDate": "2020-08-18T13:37:00Z"
							}
						]
					}
				]
			}
		]
	`)

	var findings []agent.Resource
	err := json.Unmarshal(rawFindings, &findings)
	require.NoError(t, err)

	actual, err := agent.Convert(findings, 5000000000)
	require.NoError(t, err)

	expectedScanner := agent.TrivyScanner
	expectedScanner.Version = "0.38.3"

	expected := []*agent.Payload{
		{
			Vulnerability: &report.Vulnerability{
				Name:        "CVE-2020-27350",
				Message:     "CVE-2020-27350 in apt",
				Description: "APT had several integer overflows and underflows while parsing .deb packages, aka GHSL-2020-168 GHSL-2020-169, in files apt-pkg/contrib/extracttar.cc, apt-pkg/deb/debfile.cc, and apt-pkg/contrib/arfile.cc. This issue affects: apt 1.2.32ubuntu0 versions prior to 1.2.32ubuntu0.2; 1.6.12ubuntu0 versions prior to 1.6.12ubuntu0.2; 2.0.2ubuntu0 versions prior to 2.0.2ubuntu0.2; 2.1.10ubuntu0 versions prior to 2.1.10ubuntu0.1;",
				Severity:    report.SeverityLevelMedium,
				Confidence:  report.ConfidenceLevelUnknown,
				Solution:    "Upgrade apt from 1.8.2 to 1.8.2.2",
				Location: report.Location{
					Dependency: &report.Dependency{
						Package: report.Package{Name: "apt"},
						Version: "1.8.2",
					},
					Image:           "nginx:1.16",
					OperatingSystem: "debian 10.3",
					KubernetesResource: &report.KubernetesResource{
						Namespace:     "default",
						Name:          "nginx116",
						ContainerName: "",
						Kind:          "Deployment",
						AgentID:       "5000000000",
					},
				},
				Identifiers: []report.Identifier{
					{
						Type:  report.IdentifierTypeCVE,
						Name:  "CVE-2020-27350",
						Value: "CVE-2020-27350",
						URL:   "https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-27350",
					},
				},
				Links: []report.Link{
					{URL: "https://avd.aquasec.com/nvd/cve-2020-27350"},
					{URL: "https://access.redhat.com/security/cve/CVE-2020-27350"},
					{URL: "https://bugs.launchpad.net/bugs/1899193"},
				},
			},
			Scanner: expectedScanner,
		},
		{
			Vulnerability: &report.Vulnerability{
				Name:        "CVE-2023-0464",
				Message:     "CVE-2023-0464 in libcrypto3",
				Description: "A security vulnerability has been identified in all supported versions of OpenSSL related to the verification of X.509 certificate chains that include policy constraints. Attackers may be able to exploit this vulnerability by creating a malicious certificate chain that triggers exponential use of computational resources, leading to a denial-of-service (DoS) attack on affected systems. Policy processing is disabled by default but can be enabled by passing the '-policy' argument to the command line utilities or by calling the 'X509_VERIFY_PARAM_set1_policies()' function.",
				Severity:    report.SeverityLevelHigh,
				Confidence:  report.ConfidenceLevelUnknown,
				Solution:    "Upgrade libcrypto3 from 3.0.8-r0 to 3.0.8-r1",
				Location: report.Location{
					Dependency: &report.Dependency{
						Package: report.Package{Name: "libcrypto3"},
						Version: "3.0.8-r0",
					},
					Image:           "aquasec/trivy:0.38.3",
					OperatingSystem: "alpine 3.17.2",
					KubernetesResource: &report.KubernetesResource{
						Namespace:     "default",
						Name:          "trivy-scanner",
						ContainerName: "",
						Kind:          "Pod",
						AgentID:       "5000000000",
					},
				},
				Identifiers: []report.Identifier{
					{
						Type:  report.IdentifierTypeCVE,
						Name:  "CVE-2023-0464",
						Value: "CVE-2023-0464",
						URL:   "https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-0464",
					},
				},
				Links: []report.Link{
					{URL: "https://avd.aquasec.com/nvd/cve-2023-0464"},
					{URL: "https://access.redhat.com/security/cve/CVE-2023-0464"},
					{URL: "https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-0464"},
				},
			},
			Scanner: expectedScanner,
		},
		{
			Vulnerability: &report.Vulnerability{
				Name:        "CVE-2020-8911",
				Message:     "CVE-2020-8911 in github.com/aws/aws-sdk-go",
				Description: "A padding oracle vulnerability exists in the AWS S3 Crypto SDK for GoLang versions prior to V2. The SDK allows users to encrypt files with AES-CBC without computing a Message Authentication Code (MAC), which then allows an attacker who has write access to the target's S3 bucket and can observe whether or not an endpoint with access to the key can decrypt a file, they can reconstruct the plaintext with (on average) 128*length (plaintext) queries to the endpoint, by exploiting CBC's ability to manipulate the bytes of the next block and PKCS5 padding errors. It is recommended to update your SDK to V2 or later, and re-encrypt your files.",
				Severity:    report.SeverityLevelMedium,
				Confidence:  report.ConfidenceLevelUnknown,
				Solution:    "Upgrade github.com/aws/aws-sdk-go from v1.44.212 to ",
				Location: report.Location{
					Dependency: &report.Dependency{
						Package: report.Package{Name: "github.com/aws/aws-sdk-go"},
						Version: "v1.44.212",
					},
					Image:           "aquasec/trivy:0.38.3",
					OperatingSystem: "alpine 3.17.2",
					KubernetesResource: &report.KubernetesResource{
						Namespace:     "default",
						Name:          "trivy-scanner",
						ContainerName: "",
						Kind:          "Pod",
						AgentID:       "5000000000",
					},
				},
				Identifiers: []report.Identifier{
					{
						Type:  report.IdentifierTypeCVE,
						Name:  "CVE-2020-8911",
						Value: "CVE-2020-8911",
						URL:   "https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-8911",
					},
				},
				Links: []report.Link{
					{URL: "https://avd.aquasec.com/nvd/cve-2020-8911"},
					{URL: "https://access.redhat.com/security/cve/CVE-2020-8911"},
					{URL: "https://aws.amazon.com/blogs/developer/updates-to-the-amazon-s3-encryption-client/?s=09"},
				},
			},
			Scanner: expectedScanner,
		},
	}

	assert.Equal(t, expected, actual, "parses report into correct structure")
}

func TestConvertWithError(t *testing.T) {
	rawFindings := []byte(`
		[
			{
				"Namespace": "default",
				"Kind": "Deployment",
				"Name": "nginx",
				"Error": "scan error: unable to initialize a scanner: unable to initialize a docker scanner: 4 errors occurred:\\n\\t* unable to inspect the image (localhost:1234/nginx:latest): Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?\\n\\t* unable to initialize Podman client: no podman socket found: stat podman/podman.sock: no such file or directory\\n\\t* containerd socket not found: /run/containerd/containerd.sock\\n\\t* Get \"https://localhost:1234/v2/\": dial tcp [::1]:1234: connect: connection refused; Get \"http://localhost:1234/v2/\": dial tcp [::1]:1234: connect: connection refused\\n\\n"
			}
		]
	`)

	var findings []agent.Resource
	err := json.Unmarshal(rawFindings, &findings)
	require.NoError(t, err)

	actual, err := agent.Convert(findings, 5000000000)
	require.NoError(t, err)

	// Empty payload is returned if Finding contains error
	expected := []*agent.Payload{}

	assert.Equal(t, expected, actual, "parses report into correct structure")
}
