-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHttpBasicAuthentication.php
More file actions
402 lines (354 loc) · 12.1 KB
/
HttpBasicAuthentication.php
File metadata and controls
402 lines (354 loc) · 12.1 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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
<?php
/*
Copyright (c) 2013-2024 Mika Tuupola
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.
*/
/**
* @see https://github.com/tuupola/slim-basic-auth
* @license https://www.opensource.org/licenses/mit-license.php
*/
declare(strict_types=1);
namespace Tuupola\Middleware;
use Closure;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use SplStack;
use Tuupola\Http\Factory\ResponseFactory;
use Tuupola\Middleware\DoublePassTrait;
use Tuupola\Middleware\HttpBasicAuthentication\ArrayAuthenticator;
use Tuupola\Middleware\HttpBasicAuthentication\AuthenticatorInterface;
use Tuupola\Middleware\HttpBasicAuthentication\RequestMethodRule;
use Tuupola\Middleware\HttpBasicAuthentication\RequestPathRule;
use Tuupola\Middleware\HttpBasicAuthentication\RuleInterface;
final class HttpBasicAuthentication implements MiddlewareInterface
{
use DoublePassTrait;
/**
* @var SplStack<RuleInterface>
*/
private $rules;
/**
* @var mixed[]
*/
private $options = [
"secure" => true,
"relaxed" => ["localhost", "127.0.0.1"],
"users" => null,
"path" => null,
"ignore" => null,
"realm" => "Protected",
"authenticator" => null,
"before" => null,
"after" => null,
"error" => null,
];
/**
* @param mixed[] $options
*/
public function __construct(array $options = [])
{
/* Setup stack for rules */
$this->rules = new SplStack();
/* Store passed in options overwriting any defaults */
$this->hydrate($options);
/* If array of users was passed in options create an authenticator */
if (is_array($this->options["users"])) {
$this->options["authenticator"] = new ArrayAuthenticator([
"users" => $this->options["users"],
]);
}
/* If nothing was passed in options add default rules. */
if (!isset($options["rules"])) {
$this->rules->push(new RequestMethodRule([
"ignore" => ["OPTIONS"],
]));
}
/* If path was given in easy mode add rule for it. */
if (null !== $this->options["path"]) {
$this->rules->push(new RequestPathRule([
"path" => $this->options["path"],
"ignore" => $this->options["ignore"],
]));
}
/* There must be an authenticator either passed via options */
/* or added because $this->options["users"] was an array. */
if (null === $this->options["authenticator"]) {
throw new \RuntimeException("Authenticator or users array must be given");
}
}
/**
* Process a request in PSR-15 style and return a response.
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$host = $request->getUri()->getHost();
$scheme = $request->getUri()->getScheme();
$server_params = $request->getServerParams();
/* If rules say we should not authenticate call next and return. */
if (false === $this->shouldAuthenticate($request)) {
return $handler->handle($request);
}
/* HTTP allowed only if secure is false or server is in relaxed array. */
if ("https" !== $scheme && true === $this->options["secure"]) {
$allowedHost = in_array($host, $this->options["relaxed"]);
/* if 'headers' is in the 'relaxed' key, then we check for forwarding */
$allowedForward = false;
if (in_array("headers", $this->options["relaxed"])) {
if (
$request->getHeaderLine("X-Forwarded-Proto") === "https"
&& $request->getHeaderLine('X-Forwarded-Port') === "443"
) {
$allowedForward = true;
}
}
if (!($allowedHost || $allowedForward)) {
$message = sprintf(
"Insecure use of middleware over %s denied by configuration.",
strtoupper($scheme)
);
throw new \RuntimeException($message);
}
}
/* Just in case. */
$params = [
"user" => null,
"password" => null,
];
if (preg_match("/Basic\s+(.*)$/i", $request->getHeaderLine("Authorization"), $matches)) {
$explodedCredential = explode(":", base64_decode($matches[1]), 2);
if (count($explodedCredential) == 2) {
[$params["user"], $params["password"]] = $explodedCredential;
}
}
/* Check if user authenticates. */
if (false === $this->options["authenticator"]($params)) {
/* Set response headers before giving it to error callback */
$response = (new ResponseFactory())
->createResponse(401)
->withHeader(
"WWW-Authenticate",
sprintf('Basic realm="%s"', $this->options["realm"])
);
return $this->processError($response, [
"message" => "Authentication failed",
"params" => $params,
]);
}
/* Modify $request before calling next middleware. */
if (is_callable($this->options["before"])) {
$response = (new ResponseFactory())->createResponse(200);
$before_request = $this->options["before"]($request, $params);
if ($before_request instanceof ServerRequestInterface) {
$request = $before_request;
}
}
/* Everything ok, call next middleware. */
$response = $handler->handle($request);
/* Modify $response before returning. */
if (is_callable($this->options["after"])) {
$after_response = $this->options["after"]($response, $params);
if ($after_response instanceof ResponseInterface) {
return $after_response;
}
}
return $response;
}
/**
* Hydrate all options from given array.
*
* @param mixed[] $data
*/
private function hydrate(array $data = []): void
{
foreach ($data as $key => $value) {
/* https://github.com/facebook/hhvm/issues/6368 */
$key = str_replace(".", " ", $key);
$method = lcfirst(ucwords($key));
$method = str_replace(" ", "", $method);
if (method_exists($this, $method)) {
/* Try to use setter */
/** @phpstan-ignore-next-line */
call_user_func([$this, $method], $value);
} else {
/* Or fallback to setting option directly */
$this->options[$key] = $value;
}
}
}
/**
* Test if current request should be authenticated.
*/
private function shouldAuthenticate(ServerRequestInterface $request): bool
{
/* If any of the rules in stack return false will not authenticate */
foreach ($this->rules as $callable) {
if (false === $callable($request)) {
return false;
}
}
return true;
}
/**
* Execute the error handler.
*
* @param mixed[] $arguments
*/
private function processError(ResponseInterface $response, array $arguments): ResponseInterface
{
if (is_callable($this->options["error"])) {
$handler_response = $this->options["error"]($response, $arguments);
if ($handler_response instanceof ResponseInterface) {
return $handler_response;
}
}
return $response;
}
/**
* Set path where middleware should bind to.
*
* @param string|string[] $path
* @phpstan-ignore method.unused
*/
private function path($path): void
{
$this->options["path"] = (array) $path;
}
/**
* Set path which middleware ignores.
*
* @param string[] $ignore
* @phpstan-ignore method.unused
*/
private function ignore($ignore): void
{
$this->options["ignore"] = (array) $ignore;
}
/**
* Set the authenticator.
*
* @phpstan-ignore method.unused
*/
private function authenticator(callable $authenticator): void
{
$this->options["authenticator"] = $authenticator;
}
/**
* Set the users array.
*
* @param string[] $users
* @phpstan-ignore method.unused
*/
private function users(array $users): void
{
$this->options["users"] = $users;
}
/**
* Set the secure flag.
*
* @phpstan-ignore method.unused
*/
private function secure(bool $secure): void
{
$this->options["secure"] = $secure;
}
/**
* Set hosts where secure rule is relaxed.
*
* @param string[] $relaxed
* @phpstan-ignore method.unused
*/
private function relaxed(array $relaxed): void
{
$this->options["relaxed"] = $relaxed;
}
/**
* Set the handler which is called before other middlewares.
*
* @phpstan-ignore method.unused
*/
private function before(Closure $before): void
{
$this->options["before"] = $before->bindTo($this);
}
/**
* Set the handler which is called after other middlewares.
*
* @phpstan-ignore method.unused
*/
private function after(Closure $after): void
{
$this->options["after"] = $after->bindTo($this);
}
/**
* Set the handler which is if authentication fails.
*
* @phpstan-ignore method.unused
*/
private function error(callable $error): void
{
$this->options["error"] = $error;
}
/**
* Set the rules
*
* @param RuleInterface[] $rules
* @phpstan-ignore method.unused
*/
private function rules(array $rules): void
{
$this->rules = new SplStack();
foreach ($rules as $callable) {
$this->rules->push($callable);
}
}
/**
* Set the rules which determine if current request should be authenticated.
*
* Rules must be callables which return a boolean. If any of the rules return
* boolean false current request will not be authenticated.
*
* @param RuleInterface[] $rules
*/
public function withRules(array $rules): self
{
$new = clone $this;
/* Clear the stack */
unset($new->rules);
$new->rules = new SplStack();
/* Add the rules */
foreach ($rules as $callable) {
$new = $new->addRule($callable);
}
return $new;
}
/**
* Add a rule to the rules stack.
*
* Rules must be callables which return a boolean. If any of the rules return
* boolean false current request will not be authenticated.
*/
public function addRule(callable $callable): self
{
$new = clone $this;
$new->rules = clone $this->rules;
/* @phpstan-ignore-next-line */
$new->rules->push($callable);
return $new;
}
}