<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

namespace Crypt\GPG\Tests;

use Crypt\GPG;
use Crypt\GPG\Exceptions;
use Crypt\GPG\SignatureCreationInfo;

/**
 * Tests signing abilities of Crypt_GPG.
 *
 * @category  Encryption
 * @package   Crypt_GPG
 * @author    Michael Gauthier <mike@silverorange.com>
 * @copyright 2005-2008 silverorange
 * @license   https://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 * @link      https://github.com/pear/Crypt_GPG
 */
class SignTest extends TestCase
{
    public function testHasSignKeys()
    {
        $this->assertFalse($this->gpg->hasSignKeys());
        $this->gpg->addSignKey('no-passphrase@example.com');
        $this->assertTrue($this->gpg->hasSignKeys());
    }

    /**
     * @group string
     */
    public function testSignKeyNotFoundException_invalid()
    {
        $this->expectException(Exceptions\KeyNotFoundException::class);

        $data = 'Hello, Alice! Goodbye, Bob!';
        $this->gpg->addSignKey('non-existent-key@example.com');
        $this->gpg->sign($data);
    }

    /**
     * @group string
     */
    public function testSignKeyNotFoundException_none()
    {
        $this->expectException(Exceptions\KeyNotFoundException::class);

        $data = 'Hello, Alice! Goodbye, Bob!';
        $this->gpg->sign($data);
    }

    /**
     * @group string
     */
    public function testSignBadPassphraseException_missing()
    {
        $this->expectException(Exceptions\BadPassphraseException::class);

        $data = 'Hello, Alice! Goodbye, Bob!';
        $this->gpg->addSignKey('first-keypair@example.com');
        $this->gpg->sign($data);
    }

    /**
     * @group string
     */
    public function testSignBadPassphraseException_bad()
    {
        $this->expectException(Exceptions\BadPassphraseException::class);

        $data = 'Hello, Alice! Goodbye, Bob!';
        $this->gpg->addSignKey('first-keypair@example.com', 'incorrect');
        $this->gpg->sign($data);
    }

    /**
     * @group string
     */
    public function testSignNoPassphrase()
    {
        $this->gpg->setEngineOptions(['sign' => '--emit-version']);

        $data = 'Hello, Alice! Goodbye, Bob!';
        $this->gpg->addSignKey('no-passphrase@example.com');
        $signedData = $this->gpg->sign($data);

        // Check if --emit-version option works
        $this->assertStringContainsString('Version:', $signedData);
        $this->gpg->setEngineOptions([]);

        $signatures = $this->gpg->verify($signedData);

        $this->assertCount(1, $signatures);
        foreach ($signatures as $signature) {
            $this->assertTrue($signature->isValid());
        }
    }

    /**
     * @group string
     */
    public function testSignNormal()
    {
        $data = 'Hello, Alice! Goodbye, Bob!';
        $this->gpg->addSignKey('first-keypair@example.com', 'test1');
        $signedData = $this->gpg->sign($data);
        $signatures = $this->gpg->verify($signedData);

        $this->assertCount(1, $signatures);
        foreach ($signatures as $signature) {
            $this->assertTrue($signature->isValid());
        }
    }

    /**
     * @group string
     */
    public function testSignClear()
    {
        $data = 'Hello, Alice! Goodbye, Bob!';
        $this->gpg->addSignKey('first-keypair@example.com', 'test1');
        $signedData = $this->gpg->sign($data, GPG::SIGN_MODE_CLEAR);

        $signatures = $this->gpg->verify($signedData);
        $this->assertCount(1, $signatures);
        foreach ($signatures as $signature) {
            $this->assertTrue($signature->isValid());
        }
    }

    /**
     * @group string
     */
    public function testSignDetached()
    {
        $data = 'Hello, Alice! Goodbye, Bob!';
        $this->gpg->addSignKey('first-keypair@example.com', 'test1');
        $signatureData = $this->gpg->sign($data, GPG::SIGN_MODE_DETACHED);
        $signatures = $this->gpg->verify($data, $signatureData);

        $this->assertCount(1, $signatures);
        foreach ($signatures as $signature) {
            $this->assertTrue($signature->isValid());
        }
    }

    /**
     * @group string
     */
    public function testSignDualOnePassphrase()
    {
        $data = 'Hello, Alice! Goodbye, Bob!';
        $this->gpg->addSignKey('no-passphrase@example.com');
        $this->gpg->addSignKey('first-keypair@example.com', 'test1');
        $signedData = $this->gpg->sign($data);
        $signatures = $this->gpg->verify($signedData);

        $this->assertCount(2, $signatures);
        foreach ($signatures as $signature) {
            $this->assertTrue($signature->isValid());
        }
    }

    /**
     * @group string
     */
    public function testSignDualNormal()
    {
        $data = 'Hello, Alice! Goodbye, Bob!';
        $this->gpg->addSignKey('first-keypair@example.com', 'test1');
        $this->gpg->addSignKey('second-keypair@example.com', 'test2');
        $signedData = $this->gpg->sign($data);
        $signatures = $this->gpg->verify($signedData);

        $this->assertCount(2, $signatures);
        foreach ($signatures as $signature) {
            $this->assertTrue($signature->isValid());
        }
    }

    /**
     * @group string
     */
    public function testSignDualClear()
    {
        $data = 'Hello, Alice! Goodbye, Bob!';
        $this->gpg->addSignKey('first-keypair@example.com', 'test1');
        $this->gpg->addSignKey('second-keypair@example.com', 'test2');
        $signedData = $this->gpg->sign($data, GPG::SIGN_MODE_CLEAR);
        $signatures = $this->gpg->verify($signedData);

        $this->assertCount(2, $signatures);
        foreach ($signatures as $signature) {
            $this->assertTrue($signature->isValid());
        }
    }

    /**
     * @group string
     */
    public function testSignDualDetached()
    {
        $data = 'Hello, Alice! Goodbye, Bob!';
        $this->gpg->addSignKey('first-keypair@example.com', 'test1');
        $this->gpg->addSignKey('second-keypair@example.com', 'test2');
        $signatureData = $this->gpg->sign($data, GPG::SIGN_MODE_DETACHED);
        $signatures = $this->gpg->verify($data, $signatureData);

        $this->assertCount(2, $signatures);
        foreach ($signatures as $signature) {
            $this->assertTrue($signature->isValid());
        }
    }

    /**
     * @group string
     */
    public function testSignEmpty()
    {
        $data = '';

        $this->gpg->addSignKey('first-keypair@example.com', 'test1');

        $signedData = $this->gpg->sign($data);
        $signatures = $this->gpg->verify($signedData);

        $this->assertCount(1, $signatures);
        foreach ($signatures as $signature) {
            $this->assertTrue($signature->isValid());
        }
    }

    /**
     * @group string
     */
    public function testSignDetachedTextmode()
    {
        // data with Unix line endings
        $data = "It was the best of times,\n"
            . "it was the worst of times,\n"
            . "it was the age of wisdom,\n"
            . "it was the age of foolishness,\n"
            . "it was the epoch of belief,\n"
            . "it was the epoch of incredulity,\n"
            . "it was the season of Light,\n"
            . "it was the season of Darkness,\n"
            . "it was the spring of hope,\n"
            . "it was the winter of despair,";

        $this->gpg->addSignKey('first-keypair@example.com', 'test1');
        $signatureData = $this->gpg->sign($data, GPG::SIGN_MODE_DETACHED, true, true);

        // convert data to Windows line endings
        $data = str_replace("\n", "\r\n", $data);

        // verify data
        $signatures = $this->gpg->verify($data, $signatureData);
        $this->assertCount(1, $signatures);
        foreach ($signatures as $signature) {
            $this->assertTrue(
                $signature->isValid(),
                'Failed asserting textmode signature is valid.'
            );
        }
    }

    /**
     * @group file
     */
    public function testSignFileNoPassphrase()
    {
        $inputFilename  = $this->getDataFilename('testFileMedium.plain');
        $outputFilename
            = $this->getTempFilename('testSignFileNoPassphrase.asc');

        $this->gpg->addSignKey('no-passphrase@example.com');
        $this->gpg->signFile($inputFilename, $outputFilename);

        $signatures = $this->gpg->verifyFile($outputFilename);
        $this->assertCount(1, $signatures);
        foreach ($signatures as $signature) {
            $this->assertTrue($signature->isValid());
        }
    }

    /**
     * @group file
     */
    public function testSignFileNormal()
    {
        $inputFilename  = $this->getDataFilename('testFileMedium.plain');
        $outputFilename = $this->getTempFilename('testSignFileNormal.asc');

        $this->gpg->addSignKey('first-keypair@example.com', 'test1');
        $this->gpg->signFile($inputFilename, $outputFilename);

        $signatures = $this->gpg->verifyFile($outputFilename);
        $this->assertCount(1, $signatures);
        foreach ($signatures as $signature) {
            $this->assertTrue($signature->isValid());
        }
    }

    /**
     * @group file
     */
    public function testSignFileClear()
    {
        $inputFilename  = $this->getDataFilename('testFileMedium.plain');
        $outputFilename = $this->getTempFilename('testSignFileClear.asc');

        $this->gpg->addSignKey('first-keypair@example.com', 'test1');
        $this->gpg->signFile($inputFilename, $outputFilename, GPG::SIGN_MODE_CLEAR);
        $signatures = $this->gpg->verifyFile($outputFilename);

        $this->assertEquals(1, count($signatures));
        foreach ($signatures as $signature) {
            $this->assertTrue($signature->isValid());
        }
    }

    /**
     * @group file
     */
    public function testSignFileDetached()
    {
        $inputFilename  = $this->getDataFilename('testFileMedium.plain');
        $outputFilename = $this->getTempFilename('testSignFileDetached.asc');

        $this->gpg->addSignKey('first-keypair@example.com', 'test1');
        $this->gpg->signFile($inputFilename, $outputFilename, GPG::SIGN_MODE_DETACHED);
        $signatureData = file_get_contents($outputFilename);
        $signatures = $this->gpg->verifyFile($inputFilename, $signatureData);

        $this->assertEquals(1, count($signatures));
        foreach ($signatures as $signature) {
            $this->assertTrue($signature->isValid());
        }
    }

    /**
     * @group file
     */
    public function testSignFileDetachedToString()
    {
        $filename = $this->getDataFilename('testFileMedium.plain');

        $this->gpg->addSignKey('first-keypair@example.com', 'test1');
        $signatureData = $this->gpg->signFile($filename, null, GPG::SIGN_MODE_DETACHED);
        $signatures = $this->gpg->verifyFile($filename, $signatureData);

        $this->assertEquals(1, count($signatures));
        foreach ($signatures as $signature) {
            $this->assertTrue($signature->isValid());
        }
    }

    /**
     * @group file
     */
    public function testSignFileDualOnePassphrase()
    {
        $inputFilename  = $this->getDataFilename('testFileMedium.plain');
        $outputFilename
            = $this->getTempFilename('testSignFileDualOnePassphrase.asc');

        $this->gpg->addSignKey('no-passphrase@example.com');
        $this->gpg->addSignKey('first-keypair@example.com', 'test1');
        $this->gpg->signFile($inputFilename, $outputFilename);

        $signatures = $this->gpg->verifyFile($outputFilename);
        $this->assertEquals(2, count($signatures));
        foreach ($signatures as $signature) {
            $this->assertTrue($signature->isValid());
        }
    }

    /**
     * @group file
     */
    public function testSignFileDualNormal()
    {
        $inputFilename  = $this->getDataFilename('testFileMedium.plain');
        $outputFilename = $this->getTempFilename('testSignFileDualNormal.asc');

        $this->gpg->addSignKey('first-keypair@example.com', 'test1');
        $this->gpg->addSignKey('second-keypair@example.com', 'test2');
        $this->gpg->signFile($inputFilename, $outputFilename);

        $signatures = $this->gpg->verifyFile($outputFilename);
        $this->assertCount(2, $signatures);
        foreach ($signatures as $signature) {
            $this->assertTrue($signature->isValid());
        }
    }

    /**
     * @group file
     */
    public function testSignFileDualClear()
    {
        $inputFilename  = $this->getDataFilename('testFileMedium.plain');
        $outputFilename = $this->getTempFilename('testSignFileDualClear.asc');

        $this->gpg->addSignKey('first-keypair@example.com', 'test1');
        $this->gpg->addSignKey('second-keypair@example.com', 'test2');
        $this->gpg->signFile($inputFilename, $outputFilename, GPG::SIGN_MODE_CLEAR);
        $signatures = $this->gpg->verifyFile($outputFilename);

        $this->assertCount(2, $signatures);
        foreach ($signatures as $signature) {
            $this->assertTrue($signature->isValid());
        }
    }

    /**
     * @group file
     */
    public function testSignFileDualDetached()
    {
        $inputFilename  = $this->getDataFilename('testFileMedium.plain');
        $outputFilename
            = $this->getTempFilename('testSignFileDualDetached.asc');

        $this->gpg->addSignKey('first-keypair@example.com', 'test1');
        $this->gpg->addSignKey('second-keypair@example.com', 'test2');
        $this->gpg->signFile($inputFilename, $outputFilename, GPG::SIGN_MODE_DETACHED);

        $signatureData = file_get_contents($outputFilename);
        $signatures = $this->gpg->verifyFile($inputFilename, $signatureData);

        $this->assertCount(2, $signatures);
        foreach ($signatures as $signature) {
            $this->assertTrue($signature->isValid());
        }
    }

    /**
     * @group file
     */
    public function testSignFileFileException_input()
    {
        $this->expectException(Exceptions\FileException::class);

        // input file does not exist
        $inputFilename
            = $this->getDataFilename('testSignFileFileFileException_input.plain');

        $this->gpg->addSignKey('first-keypair@example.com', 'test1');
        $this->gpg->signFile($inputFilename);
    }

    /**
     * @group file
     */
    public function testSignFileFileException_output()
    {
        $this->expectException(Exceptions\FileException::class);

        // input file is encrypted with first-keypair@example.com
        // output file does not exist
        $inputFilename  = $this->getDataFilename('testFileMedium.plain');
        $outputFilename = './non-existent'
            . '/testSignFileFileException_output.plain';

        $this->gpg->addSignKey('first-keypair@example.com', 'test1');
        $this->gpg->signFile($inputFilename, $outputFilename);
    }

    /**
     * @group file
     */
    public function testSignFileEmpty()
    {
        $filename = $this->getDataFilename('testFileEmpty.plain');

        $this->gpg->addSignKey('first-keypair@example.com', 'test1');

        $signedData = $this->gpg->signFile($filename);
        $signatures = $this->gpg->verify($signedData);

        $this->assertCount(1, $signatures);
        foreach ($signatures as $signature) {
            $this->assertTrue($signature->isValid());
        }
    }

    public function testGetLastSignatureInfo()
    {
        $this->gpg->addSignKey('first-keypair@example.com', 'test1');
        $signedData = $this->gpg->sign('test', GPG::SIGN_MODE_DETACHED);
        $sigInfo = $this->gpg->getLastSignatureInfo();

        $this->assertInstanceOf(SignatureCreationInfo::class, $sigInfo);
        $this->assertTrue($sigInfo->isValid());
        $this->assertEquals(date('Y-m-d'), date('Y-m-d', $sigInfo->getTimestamp()));
        $this->assertEquals(GPG::SIGN_MODE_DETACHED, $sigInfo->getMode());
        $this->assertEquals(
            '8D2299D9C5C211128B32BBB0C097D9EC94C06363',
            $sigInfo->getKeyFingerprint()
        );
        $this->assertNotNull($sigInfo->getHashAlgorithmName());
    }
}
