<?php

declare(strict_types=1);

/*
 * Copyright (c) 2017-2023 François Kooman <fkooman@tuxed.net>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

namespace fkooman\OAuth\Server\Tests;

use fkooman\OAuth\Server\Exception\SignerException;
use fkooman\OAuth\Server\Json;
use fkooman\OAuth\Server\Signer;
use PHPUnit\Framework\TestCase;

/**
 * @internal
 *
 * @coversNothing
 */
final class SignerTest extends TestCase
{
    public function testSignVerify(): void
    {
        $s = new Signer(Signer::generateSecretKey());
        static::assertSame('test', $s->verify($s->sign('test')));
    }

    public function testSign(): void
    {
        $s = new Signer('k7.sec.amrwnqr8ZVN0HZcx.nnoh-vryw4S6WVvnay6y4BCrsbupKICTrFbQpNDh9Jyu2RojUzeOcIMQmwlBdwKBMEdn8hxXCVIHQR1hkDG-BQ');
        static::assertSame(
            'v7.amrwnqr8ZVN0HZcx.eyJmb28iOiJiYXIifQ.Fym0SzMoLipqpGveyksg51LMcTkKJW2sNNECGKZBN1_684W_Hs_ujxw3ckmp9OucxDEGfUZ2iRd3MorQ6ROuAw',
            $s->sign(Json::encode(['foo' => 'bar']))
        );
    }

    public function testVerify(): void
    {
        $s = new Signer('k7.sec.amrwnqr8ZVN0HZcx.nnoh-vryw4S6WVvnay6y4BCrsbupKICTrFbQpNDh9Jyu2RojUzeOcIMQmwlBdwKBMEdn8hxXCVIHQR1hkDG-BQ');
        static::assertSame(
            Json::encode(['foo' => 'bar']),
            $s->verify('v7.amrwnqr8ZVN0HZcx.eyJmb28iOiJiYXIifQ.Fym0SzMoLipqpGveyksg51LMcTkKJW2sNNECGKZBN1_684W_Hs_ujxw3ckmp9OucxDEGfUZ2iRd3MorQ6ROuAw')
        );
    }

    public function testPublicKey(): void
    {
        static::assertSame(
            'k7.pub.amrwnqr8ZVN0HZcx.rtkaI1M3jnCDEJsJQXcCgTBHZ_IcVwlSB0EdYZAxvgU',
            Signer::publicKeyFromSecretKey('k7.sec.amrwnqr8ZVN0HZcx.nnoh-vryw4S6WVvnay6y4BCrsbupKICTrFbQpNDh9Jyu2RojUzeOcIMQmwlBdwKBMEdn8hxXCVIHQR1hkDG-BQ')
        );
    }

    public function testBrokenKeyFormat(): void
    {
        static::expectException(SignerException::class);
        static::expectExceptionMessage('invalid key (invalid format)');
        new Signer('foo');
    }

    public function testBrokenSignatureFormat(): void
    {
        static::expectException(SignerException::class);
        static::expectExceptionMessage('invalid token (invalid format)');
        $s = new Signer(Signer::generateSecretKey());
        $s->verify('foo');
    }

    public function testWrongKid(): void
    {
        static::expectException(SignerException::class);
        static::expectExceptionMessage('invalid token (unexpected key id "amrwnqr8ZVN0HZcx")');
        $s = new Signer('k7.sec.CxRDbelNFiR12C8U.8_02eR6zEOZ_LrNekW7czmX9JsRKebm1QNdoafF6XF-B1GmlTQJVy_8BUa4XLiPXLc9NtDSHLQqtnXxTbFltiA');
        $s->verify('v7.amrwnqr8ZVN0HZcx.eyJmb28iOiJiYXIifQ.Fym0SzMoLipqpGveyksg51LMcTkKJW2sNNECGKZBN1_684W_Hs_ujxw3ckmp9OucxDEGfUZ2iRd3MorQ6ROuAw');
    }

    public function testFakeKid(): void
    {
        // keyId in key is replaced by keyId in token
        static::expectException(SignerException::class);
        static::expectExceptionMessage('invalid token (invalid signature)');
        $s = new Signer('k7.sec.amrwnqr8ZVN0HZcx.8_02eR6zEOZ_LrNekW7czmX9JsRKebm1QNdoafF6XF-B1GmlTQJVy_8BUa4XLiPXLc9NtDSHLQqtnXxTbFltiA');
        $s->verify('v7.amrwnqr8ZVN0HZcx.eyJmb28iOiJiYXIifQ.Fym0SzMoLipqpGveyksg51LMcTkKJW2sNNECGKZBN1_684W_Hs_ujxw3ckmp9OucxDEGfUZ2iRd3MorQ6ROuAw');
    }

    public function testWrongVersion(): void
    {
        static::expectException(SignerException::class);
        static::expectExceptionMessage('invalid token (invalid version)');
        $s = new Signer('k7.sec.amrwnqr8ZVN0HZcx.nnoh-vryw4S6WVvnay6y4BCrsbupKICTrFbQpNDh9Jyu2RojUzeOcIMQmwlBdwKBMEdn8hxXCVIHQR1hkDG-BQ');
        $s->verify('v6.amrwnqr8ZVN0HZcx.eyJmb28iOiJiYXIifQ.Fym0SzMoLipqpGveyksg51LMcTkKJW2sNNECGKZBN1_684W_Hs_ujxw3ckmp9OucxDEGfUZ2iRd3MorQ6ROuAw');
    }

    public function testInvalidKeyIdFormat(): void
    {
        $s = new Signer('k7.sec.amrwnqr8ZVN0HZcx.nnoh-vryw4S6WVvnay6y4BCrsbupKICTrFbQpNDh9Jyu2RojUzeOcIMQmwlBdwKBMEdn8hxXCVIHQR1hkDG-BQ');
        static::expectException(SignerException::class);
        static::expectExceptionMessage('invalid token (invalid key id)');
        $s->verify('v7.ABAC.CDEF.EFCD');
    }

    public function testInvalidEncodingKeyId(): void
    {
        static::expectException(SignerException::class);
        static::expectExceptionMessage('invalid key (invalid key id)');
        new Signer('k7.sec.%%%.nnoh-vryw4S6WVvnay6y4BCrsbupKICTrFbQpNDh9Jyu2RojUzeOcIMQmwlBdwKBMEdn8hxXCVIHQR1hkDG-BQ');
    }

    public function testInvalidSignatureEncoding(): void
    {
        static::expectException(SignerException::class);
        static::expectExceptionMessage('invalid token/key encoding');
        $s = new Signer('k7.sec.amrwnqr8ZVN0HZcx.nnoh-vryw4S6WVvnay6y4BCrsbupKICTrFbQpNDh9Jyu2RojUzeOcIMQmwlBdwKBMEdn8hxXCVIHQR1hkDG-BQ');
        $s->verify('v7.amrwnqr8ZVN0HZcx.eyJmb28iOiJiYXIifQ.%');
    }

    public function testPublicKeySource(): void
    {
        // sign something with key X
        $s = new Signer('k7.sec.pOzUzYV1_lW1pkTN.IJwY9O6fxs80Fz236EZjU00XR7O-KOt9YehHh-Klin-aGe1RyITjbK8mmfWQ7HUU5DiSUV7CdZu-_1BLTE4G_Q');
        $t = $s->sign('Hello World!');

        // verify it with public key of key X which is available from
        // TestPublicKeySource
        $s = new Signer(
            'k7.sec.ndZ4LwiAHoorFJqo.SPoe3jYhDV0mKtpl21KYL1_ZIv7aauVRqzQVUNBDKKFiC2ve84ijPQK_iUw2A1L8bh4tHQhC8fYNPNMLLzYL3A',
            new TestPublicKeySource()
        );
        static::assertSame(
            'Hello World!',
            $s->verify($t)
        );
    }

    public function testPublicKeySourceNoSuchKey(): void
    {
        // sign something with key Y
        $s = new Signer('k7.sec.2oxBe11qKMRxYrrX.gcKh8dFVhUmxtOjhHS-6rOIyAYgOlW22HPkABETt-CXw7TuBiVX_CcKNjrGFwu7uekUBLrxhTFQee0IODDgHQA');
        $t = $s->sign('Hello World!');

        // Key Y is neither the key loaded in the signer, nor part of the
        // TestPublicKeySource
        $s = new Signer(
            'k7.sec.ndZ4LwiAHoorFJqo.SPoe3jYhDV0mKtpl21KYL1_ZIv7aauVRqzQVUNBDKKFiC2ve84ijPQK_iUw2A1L8bh4tHQhC8fYNPNMLLzYL3A',
            new TestPublicKeySource()
        );
        static::expectException(SignerException::class);
        static::expectExceptionMessage('invalid token (public key for key id "2oxBe11qKMRxYrrX" not available)');
        $s->verify($t);
    }
}
