-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEnsureAccess.php
264 lines (222 loc) · 7.49 KB
/
EnsureAccess.php
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
<?php
namespace zennit\ABAC\Http\Middleware;
use Closure;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Psr\SimpleCache\InvalidArgumentException;
use RuntimeException;
use Symfony\Component\HttpFoundation\Response;
use Throwable;
use zennit\ABAC\DTO\AccessContext;
use zennit\ABAC\Enums\PolicyMethod;
use zennit\ABAC\Services\AbacAttributeLoader;
use zennit\ABAC\Services\AbacCacheManager;
use zennit\ABAC\Services\AbacService;
use zennit\ABAC\Traits\AccessesAbacConfiguration;
/**
* Class EnsurePermissions
*
* Middleware implementation for ABAC permission checking.
* Validates user access to resources based on configured policies and subjects.
*/
readonly class EnsureAccess
{
use AccessesAbacConfiguration;
public function __construct(
protected AbacService $abac,
protected AbacCacheManager $cacheManager,
protected AbacAttributeLoader $attributeLoader
) {
}
/**
* Handle an incoming request.
*
* @param Request $request The incoming HTTP request
* @param Closure $next The next middleware in the pipeline
*
* @return Response The HTTP response
*/
public function handle(Request $request, Closure $next): Response
{
try {
if (!$request->user()) {
return $this->unauthorizedResponse();
}
if (!$this->checkAccess($request)) {
return $this->unauthorizedResponse();
}
return $next($request);
} catch (Throwable $e) {
report($e);
return $this->unauthorizedResponse();
}
}
/**
* Return a standardized unauthorized response.
* Creates a JSON response with error message for unauthorized access.
*
* @return Response The HTTP response with 401 status
*/
private function unauthorizedResponse(): Response
{
return response()->json(
['error' => 'Unauthorized to access this route.'],
Response::HTTP_UNAUTHORIZED
);
}
/**
* AbacCheck if the request has access
*
* @param Request $request
*
* @throws InvalidArgumentException
* @throws Exception
* @return bool
*/
private function checkAccess(Request $request): bool
{
// First check excluded routes
if ($this->isExcludedRoute($request)) {
return true;
}
// If not excluded, check ABAC permissions
$method = $this->matchRequestOperation($request);
if (!$method) {
return true;
}
$subject = $this->defineSubject($request);
$object = $this->defineObject($request);
$context = new AccessContext(
method: $method,
subject: $subject,
object: $this->attributeLoader->loadAllObjectAttributes($object),
environment: $request->toArray()
);
$context = $this->abac->evaluate($context);
$request->attributes->set('abac', $context);
return $context->can;
}
/**
* AbacCheck if the current route is in the excluded routes list
*/
private function isExcludedRoute(Request $request): bool
{
$currentPath = $request->path();
$currentMethod = strtoupper($request->method());
$excludedRoutes = $this->getExcludedRoutes();
foreach ($excludedRoutes as $route) {
// If route is string, exclude all methods
if (is_string($route) && $this->matchPath($currentPath, $route)) {
return true;
}
// If route is array with method and path
if (!is_array($route) && !isset($route['path'])) {
return false;
}
if (!$this->matchPath($currentPath, $route['path'])) {
continue;
}
// If method is not specified or is '*', exclude all methods
if (!isset($route['method']) || $route['method'] === '*') {
return true;
}
// Handle both string and array method definitions
$methods = (array) $route['method'];
if (in_array($currentMethod, array_map('strtoupper', $methods))) {
return true;
}
}
return false;
}
/**
* Match path against pattern, supporting wildcards
*/
private function matchPath(string $path, string $pattern): bool
{
$path = trim($path, '/');
$pattern = trim($pattern, '/');
// Direct match check
if ($path === $pattern) {
return true;
}
// Wildcard check
if (str_ends_with($pattern, '*')) {
$basePattern = rtrim($pattern, '*');
return str_starts_with($path, $basePattern);
}
return false;
}
/**
* Match the request methods against PermissionOperations
*/
private function matchRequestOperation(Request $request): ?PolicyMethod
{
return match (strtoupper($request->method())) {
'GET', 'HEAD' => PolicyMethod::READ,
'POST' => PolicyMethod::CREATE,
'PUT', 'PATCH' => PolicyMethod::UPDATE,
'DELETE' => PolicyMethod::DELETE,
default => null,
};
}
/**
* Define the subject for permission checking.
* Retrieves the subject from the request using the method configured in abac.middleware.path_resources
*
* @param Request $request The incoming HTTP request
*
* @return Builder The subject for permission checking
*/
private function defineSubject(Request $request): Builder
{
$path = trim($request->path(), '/');
$patterns = $this->getPathPatterns();
return $this->findMatchingSubject($path, $patterns);
}
/**
* Find the matching model class for a given path and handle different ID types
*/
private function findMatchingSubject(string $path, array $patterns): Builder
{
foreach ($patterns as $pattern => $model_class_string) {
if (preg_match("#^$pattern$#", $path)) {
$parts = explode('/', $path);
$id = end($parts);
if ($this->isValidId($id)) {
return $model_class_string::where('id', $id);
}
return $model_class_string::query();
}
}
throw new RuntimeException("Unable to find matching subject for path: $path");
}
/**
* Check if a string is a valid UUID
*/
private function isValidId(string $id): bool
{
return preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i', $id) === 1 || is_numeric($id);
}
/**
* Define the object for permission checking.
* Retrieves the object from the request using the method configured in abac.middleware.object_method.
*
* @param Request $request The incoming HTTP request
*
* @throws RuntimeException When the configured object method doesn't exist
*/
private function defineObject(Request $request): Model
{
$method = $this->getObjectMethod();
if (!is_callable([$request, $method])) {
throw new RuntimeException("Object method '$method' is not callable on request");
}
$object = $request->$method();
if (is_null($object)) {
throw new RuntimeException("Object method '$method' returned null");
}
return $object;
}
}