<?php
/**
 * @license GPL-2.0-or-later
 * @file
 */

use MediaWiki\Password\PasswordFactory;

/**
 * Testing framework for the password hashes
 *
 * @since 1.24
 */
abstract class PasswordTestCase extends MediaWikiUnitTestCase {
	/**
	 * @var PasswordFactory
	 */
	protected $passwordFactory;

	protected function setUp(): void {
		parent::setUp();

		$this->passwordFactory = new PasswordFactory();
		foreach ( static::getTypeConfigs() as $type => $config ) {
			$this->passwordFactory->register( $type, $config );
		}
	}

	/**
	 * Return an array of configs to be used for this class's password type.
	 *
	 * @return array[]
	 */
	abstract protected static function getTypeConfigs();

	/**
	 * An array of tests in the form of (bool, string, string), where the first
	 * element is whether the second parameter (a password hash) and the third
	 * parameter (a password) should match.
	 * @return array
	 */
	public static function providePasswordTests() {
		throw new LogicException( "Not implemented" );
	}

	/**
	 * @dataProvider providePasswordTests
	 */
	public function testHashing( $shouldMatch, $hash, $password ) {
		$passwordObj = $this->passwordFactory->newFromCiphertext( $hash );
		$this->assertSame( $shouldMatch, $passwordObj->verify( $password ) );
	}

	/**
	 * @dataProvider providePasswordTests
	 */
	public function testStringSerialization( $shouldMatch, $hash, $password ) {
		$hashObj = $this->passwordFactory->newFromCiphertext( $hash );
		$serialized = $hashObj->toString();
		$unserialized = $this->passwordFactory->newFromCiphertext( $serialized );
		$this->assertEquals( $hashObj->toString(), $unserialized->toString() );
	}

	/**
	 * @dataProvider providePasswordTests
	 * @covers \MediaWiki\Password\InvalidPassword
	 */
	public function testInvalidUnequalNormal( $shouldMatch, $hash, $password ) {
		$invalid = $this->passwordFactory->newFromCiphertext( null );
		$normal = $this->passwordFactory->newFromCiphertext( $hash );

		$this->assertFalse( $invalid->verify( $hash ) );
	}

	protected static function getValidTypes() {
		return array_keys( static::getTypeConfigs() );
	}

	public static function provideTypes() {
		foreach ( static::getValidTypes() as $type ) {
			yield [ $type ];
		}
	}

	/**
	 * @dataProvider provideTypes
	 */
	public function testCrypt( $type ) {
		$fromType = $this->passwordFactory->newFromType( $type );
		$fromType->crypt( 'password' );
		$fromPlaintext = $this->passwordFactory->newFromPlaintext( 'password', $fromType );
		$this->assertTrue( $fromType->verify( 'password' ) );
		$this->assertTrue( $fromPlaintext->verify( 'password' ) );
		$this->assertFalse( $fromType->verify( 'different password' ) );
		$this->assertFalse( $fromPlaintext->verify( 'different password' ) );
		$this->assertEquals( get_class( $fromType ),
			get_class( $fromPlaintext ),
			'newFromPlaintext() should produce instance of the same class as newFromType()'
		);
	}
}
