Repository navigation
Expand file tree
/
Copy pathApiTokenAuthenticator.php
More file actions
225 lines (181 loc) · 7.13 KB
/
Copy pathApiTokenAuthenticator.php
File metadata and controls
225 lines (181 loc) · 7.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
<?php
namespace SyncEngine\Security;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\IpUtils;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
use SyncEngine\Entity\ApiToken;
use SyncEngine\Repository\ApiTokenRepository;
use SyncEngine\Repository\UserRepository;
use SyncEngine\Security\Badge\ApiTokenBadge;
use SyncEngine\Security\Scope\ScopeRegistry;
class ApiTokenAuthenticator extends AbstractAuthenticator
{
public function __construct(
#[Autowire( '%env(SYNCENGINE_API_TOKEN_HEADER)%' )]
private readonly ?string $header,
private readonly UserRepository $userRepository,
private readonly ApiTokenRepository $apiTokenRepository,
protected readonly LoggerInterface $syncengineLogger,
) {}
public function supports( Request $request ): ?bool
{
$path = $request->getPathInfo();
return '/api' === $path || str_starts_with( $path, '/api/' );
}
public function authenticate( Request $request ): Passport
{
if ( empty( $this->header ) ) {
$authorization = $request->headers->get( 'Authorization' );
// Bearer token.
$apiToken = substr( $authorization, 7 );
} else {
$apiToken = $request->headers->get( $this->header );
}
if ( empty( $apiToken ) ) {
throw new CustomUserMessageAuthenticationException( 'No API Token provided' );
}
// Resolve the user and ApiToken entity.
$user = $this->userRepository->findByApiToken( $apiToken );
if ( ! $user ) {
throw new UserNotFoundException();
}
// Load and validate scopes.
$apiTokenEntity = $this->apiTokenRepository->findOneBy( [ 'token' => $apiToken ] );
if ( ! $apiTokenEntity instanceof ApiToken ) {
throw new CustomUserMessageAuthenticationException( 'Invalid API Token' );
}
$validate = function ( $apiToken ) use ( $user, $apiTokenEntity, $request ) {
if ( $apiToken !== $apiTokenEntity->getToken() ) {
throw new CustomUserMessageAuthenticationException( 'API Token mismatch' );
}
if ( ! $this->isTokenValid( $apiTokenEntity, $request ) ) {
throw new CustomUserMessageAuthenticationException( 'Invalid API Token' );
}
return $user;
};
// Inject scopes as custom token data.
$passport = new SelfValidatingPassport(
new UserBadge( $apiToken, $validate ),
[ new ApiTokenBadge( $apiTokenEntity, true ) ]
);
return $passport;
}
public function createToken( Passport $passport, string $firewallName ): TokenInterface
{
$apiTokenBadge = $passport->getBadge( ApiTokenBadge::class );
if ( ! $apiTokenBadge instanceof ApiTokenBadge ) {
throw new \LogicException( 'ApiTokenBadge not found in passport.' );
}
return new ApiTokenSecurityToken(
$passport->getUser(),
$apiTokenBadge->getApiToken(),
$firewallName
);
}
public function isTokenValid( ApiToken|string $apiToken, Request $request ): bool
{
if ( ! $apiToken instanceof ApiToken ) {
$apiToken = $this->apiTokenRepository->findOneBy( [ 'token' => $apiToken ] );
}
if ( ! $apiToken instanceof ApiToken ) {
return false;
}
if ( new \DateTime() > $apiToken->getExpiresAt() ) {
throw new CustomUserMessageAuthenticationException( 'Expired API Token' );
}
$config = $apiToken->getConfig();
$rawScopes = $config['scopes'] ?? [];
// No scopes = no access (no backward compatibility).
if ( empty( $rawScopes ) ) {
throw new CustomUserMessageAuthenticationException( 'Token has no scopes assigned' );
}
// Validate each scope.
$invalidScopes = array_filter( $rawScopes, fn( $scope ) => ! ScopeRegistry::isValid( $scope ) );
if ( ! empty( $invalidScopes ) ) {
throw new CustomUserMessageAuthenticationException( 'Token has invalid scopes: ' . implode( ', ', $invalidScopes ) );
}
if ( empty( $config['restrictions'] ) ) {
return true;
}
try {
$restrictions = $config['restrictions'];
$ips = $restrictions['ip'] ?? '';
if ( $ips && $ips = array_map( 'trim', explode( ',', $ips ) ) ) {
$ip = $request->getClientIp();
if ( ! IpUtils::checkIp( $ip, $ips ) ) {
return false;
}
}
/**
* Note: This is not actual security, it's a soft restriction.
* The 'origin' header can be spoofed, so this is more of a convenience check than a security measure.
*/
$hosts = $restrictions['host'] ?? '';
if ( $hosts && $hosts = array_map( 'trim', explode( ',', $hosts ) ) ) {
$host = $request->headers->get( 'origin' ) ?: $request->headers->get( 'HTTP_ORIGIN' );
if ( ! $host ) {
return in_array( 'localhost', $hosts ) && IpUtils::isPrivateIp( $request->getClientIp() );
}
if ( ! $this->validateHost( $host, $hosts ) ) {
return false;
}
}
} catch ( \Exception $e ) {
$this->syncengineLogger->error( $e );
// Do not provide further information to the client, further info can be found in the logs
throw new AuthenticationException();
}
return true;
}
public function validateHost( string $host, array $allowedHosts ): bool
{
// Normalize domain to ensure it doesn't have a leading protocol.
$parsedHost = parse_url( $host, PHP_URL_HOST ) ?: $host;
foreach ( $allowedHosts as $allowedHost ) {
if ( strcasecmp( $parsedHost, $allowedHost ) === 0 ) {
return true;
}
// Handle host wildcards (e.g., *.example.com).
if ( str_starts_with( $allowedHost, '*' ) ) {
$pattern = preg_quote( ltrim( $allowedHost, '*' ), '/' );
$pattern = '/^([a-z0-9-]+\.)?' . $pattern . '$/i';
if ( preg_match( $pattern, $parsedHost ) ) {
return true;
}
}
}
return false;
}
public function onAuthenticationSuccess( Request $request, TokenInterface $token, string $firewallName ): ?Response
{
return null;
}
public function onAuthenticationFailure( Request $request, AuthenticationException $exception ): ?Response
{
$data = [
'message' => strtr( $exception->getMessageKey(), $exception->getMessageData() ),
];
return new JsonResponse( $data, Response::HTTP_UNAUTHORIZED );
}
// public function start(Request $request, AuthenticationException $authException = null): Response
// {
// /*
// * If you would like this class to control what happens when an anonymous user accesses a
// * protected page (e.g. redirect to /login), uncomment this method and make this class
// * implement Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface.
// *
// * For more details, see https://symfony.com/doc/current/security/experimental_authenticators.html#configuring-the-authentication-entry-point
// */
// }
}