added API tokens, deprecate API passwords (#4637)

This commit is contained in:
Kevin Papst
2024-04-05 23:51:16 +02:00
committed by GitHub
parent dd51c8dfba
commit afe0656502
60 changed files with 889 additions and 624 deletions

View File

@@ -22,42 +22,25 @@ use Symfony\Component\HttpKernel\HttpKernelBrowser;
*/
abstract class APIControllerBaseTest extends ControllerBaseTest
{
/**
* @return array<string, string>
*/
private function getAuthHeader(string $username, string $password): array
{
return [
'HTTP_AUTHORIZATION' => 'Bearer ' . $password,
];
}
protected function getClientForAuthenticatedUser(string $role = User::ROLE_USER): HttpKernelBrowser
{
switch ($role) {
case User::ROLE_SUPER_ADMIN:
$client = self::createClient([], [
'HTTP_X_AUTH_USER' => UserFixtures::USERNAME_SUPER_ADMIN,
'HTTP_X_AUTH_TOKEN' => UserFixtures::DEFAULT_API_TOKEN,
]);
break;
case User::ROLE_ADMIN:
$client = self::createClient([], [
'HTTP_X_AUTH_USER' => UserFixtures::USERNAME_ADMIN,
'HTTP_X_AUTH_TOKEN' => UserFixtures::DEFAULT_API_TOKEN,
]);
break;
case User::ROLE_TEAMLEAD:
$client = self::createClient([], [
'HTTP_X_AUTH_USER' => UserFixtures::USERNAME_TEAMLEAD,
'HTTP_X_AUTH_TOKEN' => UserFixtures::DEFAULT_API_TOKEN,
]);
break;
case User::ROLE_USER:
$client = self::createClient([], [
'HTTP_X_AUTH_USER' => UserFixtures::USERNAME_USER,
'HTTP_X_AUTH_TOKEN' => UserFixtures::DEFAULT_API_TOKEN,
]);
break;
default:
throw new \Exception(sprintf('Unknown role "%s"', $role));
}
return $client;
return match ($role) {
User::ROLE_SUPER_ADMIN => self::createClient([], $this->getAuthHeader(UserFixtures::USERNAME_SUPER_ADMIN, UserFixtures::DEFAULT_API_TOKEN . '_super')),
User::ROLE_ADMIN => self::createClient([], $this->getAuthHeader(UserFixtures::USERNAME_ADMIN, UserFixtures::DEFAULT_API_TOKEN . '_admin')),
User::ROLE_TEAMLEAD => self::createClient([], $this->getAuthHeader(UserFixtures::USERNAME_TEAMLEAD, UserFixtures::DEFAULT_API_TOKEN . '_teamlead')),
User::ROLE_USER => self::createClient([], $this->getAuthHeader(UserFixtures::USERNAME_USER, UserFixtures::DEFAULT_API_TOKEN . '_user')),
default => throw new \Exception(sprintf('Unknown role "%s"', $role)),
};
}
protected function createUrl(string $url): string
@@ -81,16 +64,12 @@ abstract class APIControllerBaseTest extends ControllerBaseTest
protected function assertRequestIsSecured(HttpKernelBrowser $client, string $url, string $method = 'GET'): void
{
$this->request($client, $url, $method);
$this->assertResponseIsSecured($client->getResponse(), $url);
}
$response = $client->getResponse();
/**
* @param Response $response
* @param string $url
*/
protected function assertResponseIsSecured(Response $response, string $url): void
{
$data = ['message' => 'Authentication required, missing user header: X-AUTH-USER'];
$data = [
'message' => 'Unauthorized',
'code' => 401
];
self::assertEquals(
$data,
@@ -99,17 +78,12 @@ abstract class APIControllerBaseTest extends ControllerBaseTest
);
self::assertEquals(
Response::HTTP_FORBIDDEN,
Response::HTTP_UNAUTHORIZED,
$response->getStatusCode(),
sprintf('The secure URL %s has the wrong status code %s.', $url, $response->getStatusCode())
);
}
/**
* @param string $role
* @param string $url
* @param string $method
*/
protected function assertUrlIsSecuredForRole(string $role, string $url, string $method = 'GET'): void
{
$client = $this->getClientForAuthenticatedUser($role);

View File

@@ -97,20 +97,20 @@ class ApiDocControllerTest extends ControllerBaseTest
'/api/users',
'/api/users/{id}',
'/api/users/me',
'/api/users/api-token/{id}',
];
$this->assertArrayHasKey('openapi', $json);
$this->assertEquals('3.0.0', $json['openapi']);
$this->assertArrayHasKey('info', $json);
$this->assertEquals('Kimai - API Docs', $json['info']['title']);
$this->assertEquals('0.7', $json['info']['version']);
$this->assertEquals('1.0', $json['info']['version']);
$this->assertArrayHasKey('paths', $json);
$this->assertEquals($paths, array_keys($json['paths']));
$this->assertArrayHasKey('security', $json);
$this->assertArrayHasKey('X-AUTH-USER', $json['security'][0]);
$this->assertArrayHasKey('X-AUTH-TOKEN', $json['security'][0]);
$this->assertEquals(['bearer' => []], $json['security'][0]);
$this->assertArrayHasKey('components', $json);
$this->assertArrayHasKey('schemas', $json['components']);

View File

@@ -0,0 +1,65 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace API\Authentication;
use App\API\Authentication\AccessTokenHandler;
use App\Entity\AccessToken;
use App\Entity\User;
use App\Repository\AccessTokenRepository;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
/**
* @covers \App\API\Authentication\AccessTokenHandler
*/
class AccessTokenHandlerTest extends TestCase
{
private function getSut(?AccessToken $accessToken = null): AccessTokenHandler
{
$userProvider = $this->createMock(AccessTokenRepository::class);
$userProvider->method('findByToken')->willReturn($accessToken);
return new AccessTokenHandler($userProvider);
}
public function testUnknownToken(): void
{
$this->expectException(BadCredentialsException::class);
$this->expectExceptionMessage('Invalid credentials.');
$sut = $this->getSut();
$sut->getUserBadgeFrom('foo');
}
public function testInvalidToken(): void
{
$user = new User();
$user->setUserIdentifier('foo');
$accessToken = new AccessToken($user, 'Test');
$accessToken->setExpiresAt(new \DateTimeImmutable('-1 day'));
$this->expectException(BadCredentialsException::class);
$this->expectExceptionMessage('Invalid token.');
$sut = $this->getSut($accessToken);
$sut->getUserBadgeFrom('foo');
}
public function testValidTokenSetsLastUsage(): void
{
$user = new User();
$user->setUserIdentifier('foo-bar');
$accessToken = new AccessToken($user, 'Test');
$this->assertNull($accessToken->getLastUsage());
$sut = $this->getSut($accessToken);
$badge = $sut->getUserBadgeFrom('foo');
$this->assertNotNull($accessToken->getLastUsage());
$this->assertSame('foo-bar', $badge->getUserIdentifier());
}
}

View File

@@ -1,178 +0,0 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Tests\API\Authentication;
use App\API\Authentication\SessionAuthenticator;
use App\API\Authentication\TokenAuthenticator;
use App\Entity\User;
use App\Repository\ApiUserRepository;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactoryInterface;
use Symfony\Component\PasswordHasher\PasswordHasherInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\CustomCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
/**
* @covers \App\API\Authentication\SessionAuthenticator
*/
class SessionAuthenticatorTest extends TestCase
{
private function getSut(bool $verify = true): SessionAuthenticator
{
$userProvider = $this->createMock(ApiUserRepository::class);
$passwordHasherFactory = $this->createMock(PasswordHasherFactoryInterface::class);
$passwordHasher = $this->createMock(PasswordHasherInterface::class);
$passwordHasher->method('verify')->willReturn($verify);
$passwordHasherFactory->method('getPasswordHasher')->willReturn($passwordHasher);
$token = new TokenAuthenticator($userProvider, $passwordHasherFactory);
return new SessionAuthenticator($token);
}
public function testSupports(): void
{
$sut = $this->getSut();
// not supporting because /api path is not the beginning of the URL
$request = new Request([], [], [], [], [], ['REQUEST_URI' => 'dfghj/api/doc/dfghj']);
self::assertFalse($sut->supports($request));
$request = new Request([], [], [], [], [], ['REQUEST_URI' => '/api/fooo']);
self::assertTrue($sut->supports($request));
$request = new Request([], [], [], [], [], ['REQUEST_URI' => '/api/doc']);
self::assertFalse($sut->supports($request));
$request = new Request([], [], [], [], [], ['REQUEST_URI' => '/api/fooo', 'HTTP_X-AUTH-SESSION' => true]);
self::assertFalse($sut->supports($request));
$request = new Request([], [], [], [], [], ['REQUEST_URI' => '/api/fooo', 'HTTP_X-AUTH-USER' => 'foo', 'HTTP_X-AUTH-TOKEN' => 'bar']);
self::assertTrue($sut->supports($request));
$request = new Request([], [], [], [], [], ['REQUEST_URI' => '/api/fooo', 'HTTP_X-AUTH-USER' => 'foo', 'HTTP_X-AUTH-TOKEN' => 'bar', 'HTTP_X-AUTH-SESSION' => true]);
self::assertFalse($sut->supports($request));
}
public function testAuthenticateWithMissingAuthHeader(): void
{
$this->expectException(CustomUserMessageAuthenticationException::class);
$this->expectExceptionMessage('Authentication required, missing user header: X-AUTH-USER');
$sut = $this->getSut();
$request = new Request([], [], [], [], [], ['REQUEST_URI' => '/api/fooo']);
$sut->authenticate($request);
}
public function testAuthenticateWithMissingToken(): void
{
$this->expectException(CustomUserMessageAuthenticationException::class);
$this->expectExceptionMessage('Authentication required, missing token header: X-AUTH-TOKEN');
$sut = $this->getSut();
$request = new Request([], [], [], [], [], ['REQUEST_URI' => '/api/fooo', 'HTTP_X-AUTH-USER' => 'foo']);
$sut->authenticate($request);
}
public function testAuthenticateWithEmptyToken(): void
{
$this->expectException(CustomUserMessageAuthenticationException::class);
$this->expectExceptionMessage('Authentication required, missing token header: X-AUTH-TOKEN');
$sut = $this->getSut();
$request = new Request([], [], [], [], [], ['REQUEST_URI' => '/api/fooo', 'HTTP_X-AUTH-USER' => 'foo', 'HTTP_X-AUTH-TOKEN' => '']);
$sut->authenticate($request);
}
public function testAuthenticateWithMissingUser(): void
{
$this->expectException(CustomUserMessageAuthenticationException::class);
$this->expectExceptionMessage('Authentication required, missing user header: X-AUTH-USER');
$sut = $this->getSut();
$request = new Request([], [], [], [], [], ['REQUEST_URI' => '/api/fooo', 'HTTP_X-AUTH-TOKEN' => 'bar']);
$sut->authenticate($request);
}
public function testAuthenticateWithEmptyUser(): void
{
$this->expectException(CustomUserMessageAuthenticationException::class);
$this->expectExceptionMessage('Authentication required, missing user header: X-AUTH-USER');
$sut = $this->getSut();
$request = new Request([], [], [], [], [], ['REQUEST_URI' => '/api/fooo', 'HTTP_X-AUTH-USER' => '', 'HTTP_X-AUTH-TOKEN' => 'bar']);
$sut->authenticate($request);
}
public function testAuthenticate(): void
{
$sut = $this->getSut();
$request = new Request([], [], [], [], [], ['REQUEST_URI' => '/api/fooo', 'HTTP_X-AUTH-USER' => 'foo2', 'HTTP_X-AUTH-TOKEN' => 'bar']);
$passport = $sut->authenticate($request);
self::assertInstanceOf(Passport::class, $passport);
$badge = $passport->getBadge(UserBadge::class);
self::assertInstanceOf(UserBadge::class, $badge);
self::assertEquals('foo2', $badge->getUserIdentifier());
$user = new User();
$user->setApiToken('bar2');
$badge = $passport->getBadge(CustomCredentials::class);
self::assertInstanceOf(CustomCredentials::class, $badge);
self::assertFalse($badge->isResolved());
$badge->executeCustomChecker($user);
self::assertTrue($badge->isResolved());
}
public function testAuthenticateFailsOnMissingApiTokenForUser(): void
{
$this->expectException(BadCredentialsException::class);
$this->expectExceptionMessage('The user has no activated API account.');
$sut = $this->getSut();
$request = new Request([], [], [], [], [], ['REQUEST_URI' => '/api/fooo', 'HTTP_X-AUTH-USER' => 'foo2', 'HTTP_X-AUTH-TOKEN' => 'bar']);
$passport = $sut->authenticate($request);
$user = new User();
/** @var CustomCredentials $badge */
$badge = $passport->getBadge(CustomCredentials::class);
$badge->executeCustomChecker($user);
}
public function testAuthenticateFailsOnWrongPassword(): void
{
$this->expectException(BadCredentialsException::class);
$this->expectExceptionMessage('The presented password is invalid.');
$sut = $this->getSut(false);
$request = new Request([], [], [], [], [], ['REQUEST_URI' => '/api/fooo', 'HTTP_X-AUTH-USER' => 'foo2', 'HTTP_X-AUTH-TOKEN' => 'bar']);
$passport = $sut->authenticate($request);
$user = new User();
$user->setApiToken('bar');
/** @var CustomCredentials $badge */
$badge = $passport->getBadge(CustomCredentials::class);
$badge->executeCustomChecker($user);
}
}

View File

@@ -24,6 +24,7 @@ use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
/**
* @covers \App\API\Authentication\TokenAuthenticator
* @group legacy
*/
class TokenAuthenticatorTest extends TestCase
{
@@ -47,19 +48,13 @@ class TokenAuthenticatorTest extends TestCase
self::assertFalse($sut->supports($request));
$request = new Request([], [], [], [], [], ['REQUEST_URI' => '/api/fooo']);
self::assertTrue($sut->supports($request));
self::assertFalse($sut->supports($request));
$request = new Request([], [], [], [], [], ['REQUEST_URI' => '/api/doc']);
self::assertFalse($sut->supports($request));
$request = new Request([], [], [], [], [], ['REQUEST_URI' => '/api/fooo', 'HTTP_X-AUTH-SESSION' => true]);
self::assertTrue($sut->supports($request));
$request = new Request([], [], [], [], [], ['REQUEST_URI' => '/api/fooo', 'HTTP_X-AUTH-USER' => 'foo', 'HTTP_X-AUTH-TOKEN' => 'bar']);
self::assertTrue($sut->supports($request));
$request = new Request([], [], [], [], [], ['REQUEST_URI' => '/api/fooo', 'HTTP_X-AUTH-USER' => 'foo', 'HTTP_X-AUTH-TOKEN' => 'bar', 'HTTP_X-AUTH-SESSION' => true]);
self::assertTrue($sut->supports($request));
}
public function testAuthenticateWithMissingAuthHeader(): void

View File

@@ -0,0 +1,93 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace API;
use App\DataFixtures\UserFixtures;
use App\Entity\User;
use App\Tests\API\APIControllerBaseTest;
use Symfony\Component\HttpFoundation\Response;
/**
* These tests make sure, that the deprecated API login with X-AUTH-USER and X-AUTH-TOKEN still works.
*
* @group legacy
* @group integration
*/
class AuthenticationTest extends APIControllerBaseTest
{
public function testPinIsSecure(): void
{
$this->assertUrlIsSecured('/api/ping');
}
public function testPingWithAccessToken(): void
{
$client = $this->getClientForAuthenticatedUser(User::ROLE_USER);
$this->assertAccessIsGranted($client, '/api/ping');
$response = $client->getResponse()->getContent();
$this->assertIsString($response);
$result = json_decode($response, true);
$this->assertIsArray($result);
$this->assertEquals(['message' => 'pong'], $result);
}
public function testPingWithAuthTokenAndUsername(): void
{
$client = self::createClient([], $this->getAuthHeader(UserFixtures::USERNAME_USER, UserFixtures::DEFAULT_API_TOKEN));
$this->assertAccessIsGranted($client, '/api/ping');
$response = $client->getResponse()->getContent();
$this->assertIsString($response);
$result = json_decode($response, true);
$this->assertIsArray($result);
$this->assertEquals(['message' => 'pong'], $result);
}
public function testPingWithInvalidAuthTokenAndUsername(): void
{
$client = self::createClient([], $this->getAuthHeader(UserFixtures::USERNAME_USER, 'xxxx'));
$url = '/api/ping';
$method = 'GET';
$this->request($client, $url, $method);
$response = $client->getResponse();
$data = [
'message' => 'Invalid credentials',
];
$this->assertIsString($response->getContent());
$this->assertEquals(
$data,
json_decode($response->getContent(), true),
sprintf('The secure URL %s is not protected.', $url)
);
$this->assertEquals(
Response::HTTP_FORBIDDEN,
$response->getStatusCode(),
sprintf('The secure URL %s has the wrong status code %s.', $url, $response->getStatusCode())
);
}
/**
* @return array<string, string>
*/
private function getAuthHeader(string $username, string $password): array
{
return [
'HTTP_X_AUTH_USER' => $username,
'HTTP_X_AUTH_TOKEN' => $password,
];
}
}