import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SecurityHubComponent } from './security-hub.component';
import { of } from 'rxjs';
import { delay, finalize } from 'rxjs/operators';
import { SharedTestingModule } from '../../../../shared/shared.module';
import { SecurityhubService } from '../../../../../../ng-swagger-gen/services/securityhub.service';
import { HttpHeaders, HttpResponse } from '@angular/common/http';
import { VulnerabilityItem } from '../../../../../../ng-swagger-gen/models/vulnerability-item';
import { NO_ERRORS_SCHEMA } from '@angular/core';

describe('SecurityHubComponent', () => {
    let component: SecurityHubComponent;
    let fixture: ComponentFixture<SecurityHubComponent>;
    const mockedVuls: VulnerabilityItem[] = [
        {
            cve_id: 'CVE-2021-44228',
            cvss_v3_score: 10,
            desc: 'Apache Log4j2 2.0-beta9 through 2.15.0 (excluding security releases 2.12.2, 2.12.3, and 2.3.1) JNDI features used in configuration, log messages, and parameters do not protect against attacker controlled LDAP and other JNDI related endpoints. An attacker who can control log messages or log message parameters can execute arbitrary code loaded from LDAP servers when message lookup substitution is enabled. From log4j 2.15.0, this behavior has been disabled by default. From version 2.16.0 (along with 2.12.2, 2.12.3, and 2.3.1), this functionality has been completely removed. Note that this vulnerability is specific to log4j-core and does not affect log4net, log4cxx, or other Apache Logging Services projects.',
            digest: 'sha256:7027e69a2172e38cef8ac2cb1f046025895c9fcf3160e8f70ffb26446f680e4d',
            fixed_version: '2.3.2, 2.12.2, 2.15.0',
            links: ['https://avd.aquasec.com/nvd/cve-2021-44228'],
            package: 'org.apache.logging.log4j:log4j-core',
            project_id: 11,
            repository_name: 'sample/nuxeo',
            severity: 'Critical',
            tags: [],
            version: '2.11.1',
        },
        {
            cve_id: 'CVE-2021-44228',
            cvss_v3_score: 10,
            desc: 'Apache Log4j2 2.0-beta9 through 2.15.0 (excluding security releases 2.12.2, 2.12.3, and 2.3.1) JNDI features used in configuration, log messages, and parameters do not protect against attacker controlled LDAP and other JNDI related endpoints. An attacker who can control log messages or log message parameters can execute arbitrary code loaded from LDAP servers when message lookup substitution is enabled. From log4j 2.15.0, this behavior has been disabled by default. From version 2.16.0 (along with 2.12.2, 2.12.3, and 2.3.1), this functionality has been completely removed. Note that this vulnerability is specific to log4j-core and does not affect log4net, log4cxx, or other Apache Logging Services projects.',
            digest: 'sha256:7027e69a2172e38cef8ac2cb1f046025895c9fcf3160e8f70ffb26446f680e4d',
            fixed_version: '2.3.2, 2.12.2, 2.15.0',
            links: ['https://avd.aquasec.com/nvd/cve-2021-44228'],
            package: 'org.apache.logging.log4j:log4j-core',
            project_id: 1,
            repository_name: 'library/nuxeo',
            severity: 'Critical',
            tags: ['v2.3.0'],
            version: '2.11.1',
        },
        {
            cve_id: 'CVE-2021-21345',
            cvss_v3_score: 9.9,
            desc: "XStream is a Java library to serialize objects to XML and back again. In XStream before version 1.4.16, there is a vulnerability which may allow a remote attacker who has sufficient rights to execute commands of the host only by manipulating the processed input stream. No user is affected, who followed the recommendation to setup XStream's security framework with a whitelist limited to the minimal required types. If you rely on XStream's default blacklist of the Security Framework, you will have to use at least version 1.4.16.",
            digest: 'sha256:7027e69a2172e38cef8ac2cb1f046025895c9fcf3160e8f70ffb26446f680e4d',
            fixed_version: '1.4.16',
            links: ['https://avd.aquasec.com/nvd/cve-2021-21345'],
            package: 'com.thoughtworks.xstream:xstream',
            project_id: 1,
            repository_name: 'library/nuxeo',
            severity: 'Critical',
            tags: ['v2.3.0'],
            version: '1.4.10',
        },
        {
            cve_id: 'CVE-2021-21345',
            cvss_v3_score: 9.9,
            desc: "XStream is a Java library to serialize objects to XML and back again. In XStream before version 1.4.16, there is a vulnerability which may allow a remote attacker who has sufficient rights to execute commands of the host only by manipulating the processed input stream. No user is affected, who followed the recommendation to setup XStream's security framework with a whitelist limited to the minimal required types. If you rely on XStream's default blacklist of the Security Framework, you will have to use at least version 1.4.16.",
            digest: 'sha256:7027e69a2172e38cef8ac2cb1f046025895c9fcf3160e8f70ffb26446f680e4d',
            fixed_version: '1.4.16',
            links: ['https://avd.aquasec.com/nvd/cve-2021-21345'],
            package: 'com.thoughtworks.xstream:xstream',
            project_id: 11,
            repository_name: 'sample/nuxeo',
            severity: 'Critical',
            tags: [],
            version: '1.4.10',
        },
        {
            cve_id: 'CVE-2020-27619',
            cvss_v3_score: 9.8,
            desc: 'In Python 3 through 3.9.0, the Lib/test/multibytecodec_support.py CJK codec tests call eval() on content retrieved via HTTP.',
            digest: 'sha256:c7c1c56aab2d5b0f1470ec90d7113665ed577d6952b48b88f556e3448a9a4175',
            links: ['https://avd.aquasec.com/nvd/cve-2020-27619'],
            package: 'libpython3.9-stdlib',
            project_id: 1,
            repository_name: 'library/spectral',
            severity: 'Low',
            tags: ['v6.1.0'],
            version: '3.9.2-1',
        },
        {
            cve_id: 'CVE-2020-27619',
            cvss_v3_score: 9.8,
            desc: 'In Python 3 through 3.9.0, the Lib/test/multibytecodec_support.py CJK codec tests call eval() on content retrieved via HTTP.',
            digest: 'sha256:c7c1c56aab2d5b0f1470ec90d7113665ed577d6952b48b88f556e3448a9a4175',
            links: ['https://avd.aquasec.com/nvd/cve-2020-27619'],
            package: 'libpython3.9-minimal',
            project_id: 1,
            repository_name: 'library/spectral',
            severity: 'Low',
            tags: ['v6.1.0'],
            version: '3.9.2-1',
        },
        {
            cve_id: 'CVE-2022-37454',
            cvss_v3_score: 9.8,
            desc: 'The Keccak XKCP SHA-3 reference implementation before fdc6fef has an integer overflow and resultant buffer overflow that allows attackers to execute arbitrary code or eliminate expected cryptographic properties. This occurs in the sponge function interface.',
            digest: 'sha256:c7c1c56aab2d5b0f1470ec90d7113665ed577d6952b48b88f556e3448a9a4175',
            links: ['https://avd.aquasec.com/nvd/cve-2022-37454'],
            package: 'libpython3.9-stdlib',
            project_id: 1,
            repository_name: 'library/spectral',
            severity: 'Low',
            tags: ['v6.1.0'],
            version: '3.9.2-1',
        },
        {
            cve_id: 'CVE-2019-1010022',
            cvss_v3_score: 9.8,
            desc: '** DISPUTED ** GNU Libc current is affected by: Mitigation bypass. The impact is: Attacker may bypass stack guard protection. The component is: nptl. The attack vector is: Exploit stack buffer overflow vulnerability and use this bypass vulnerability to bypass stack guard. NOTE: Upstream comments indicate "this is being treated as a non-security bug and no real threat."',
            digest: 'sha256:d2b2f2980e9ccc570e5726b56b54580f23a018b7b7314c9eaff7e5e479c78657',
            links: ['https://avd.aquasec.com/nvd/cve-2019-1010022'],
            package: 'libc6',
            project_id: 6,
            repository_name: 'dockerhub-proxy-cache/library/nginx',
            severity: 'Low',
            tags: [],
            version: '2.36-9',
        },
        {
            cve_id: 'CVE-2019-1010022',
            cvss_v3_score: 9.8,
            desc: '** DISPUTED ** GNU Libc current is affected by: Mitigation bypass. The impact is: Attacker may bypass stack guard protection. The component is: nptl. The attack vector is: Exploit stack buffer overflow vulnerability and use this bypass vulnerability to bypass stack guard. NOTE: Upstream comments indicate "this is being treated as a non-security bug and no real threat."',
            digest: 'sha256:c7c1c56aab2d5b0f1470ec90d7113665ed577d6952b48b88f556e3448a9a4175',
            links: ['https://avd.aquasec.com/nvd/cve-2019-1010022'],
            package: 'libc6',
            project_id: 1,
            repository_name: 'library/spectral',
            severity: 'Low',
            tags: ['v6.1.0'],
            version: '2.31-13+deb11u6',
        },
        {
            cve_id: 'CVE-2017-9117',
            cvss_v3_score: 9.8,
            desc: 'In LibTIFF 4.0.7, the program processes BMP images without verifying that biWidth and biHeight in the bitmap-information header match the actual input, leading to a heap-based buffer over-read in bmp2tiff.',
            digest: 'sha256:d2b2f2980e9ccc570e5726b56b54580f23a018b7b7314c9eaff7e5e479c78657',
            links: ['https://avd.aquasec.com/nvd/cve-2017-9117'],
            package: 'libtiff6',
            project_id: 6,
            repository_name: 'dockerhub-proxy-cache/library/nginx',
            severity: 'Low',
            tags: [],
            version: '4.5.0-6',
        },
    ];

    const fakedSecurityhubService = {
        ListVulnerabilitiesResponse() {
            const res: HttpResponse<Array<VulnerabilityItem>> =
                new HttpResponse<Array<VulnerabilityItem>>({
                    headers: new HttpHeaders({ 'x-total-count': '-1' }),
                    body: mockedVuls,
                });
            return of(res)
                .pipe(delay(0))
                .pipe(
                    finalize(() => {
                        component.loading = false;
                    })
                );
        },
    };

    beforeEach(async () => {
        await TestBed.configureTestingModule({
            schemas: [NO_ERRORS_SCHEMA],
            imports: [SharedTestingModule],
            declarations: [SecurityHubComponent],
            providers: [
                {
                    provide: SecurityhubService,
                    useValue: fakedSecurityhubService,
                },
            ],
        }).compileComponents();

        fixture = TestBed.createComponent(SecurityHubComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });

    it('should render vulnerabilities', async () => {
        fixture.detectChanges();
        await fixture.whenStable();
        fixture.autoDetectChanges(true);
        await fixture.whenStable();
        const rows = fixture.nativeElement.querySelectorAll('clr-dg-row');
        expect(rows.length).toEqual(10);
    });
});
