-
-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathInjectionMiddleware.php
More file actions
415 lines (369 loc) · 13.4 KB
/
InjectionMiddleware.php
File metadata and controls
415 lines (369 loc) · 13.4 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
403
404
405
406
407
408
409
410
411
412
413
414
415
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2020-2024 LibreCode coop and contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Libresign\Middleware;
use OC\AppFramework\Http as AppFrameworkHttp;
use OCA\Libresign\AppInfo\Application;
use OCA\Libresign\Controller\AEnvironmentAwareController;
use OCA\Libresign\Controller\AEnvironmentPageAwareController;
use OCA\Libresign\Controller\ISignatureUuid;
use OCA\Libresign\Db\FileMapper;
use OCA\Libresign\Db\SignRequestMapper;
use OCA\Libresign\Enum\SignRequestStatus;
use OCA\Libresign\Exception\LibresignException;
use OCA\Libresign\Handler\CertificateEngine\CertificateEngineFactory;
use OCA\Libresign\Helper\JSActions;
use OCA\Libresign\Helper\ValidateHelper;
use OCA\Libresign\Middleware\Attribute\CanSignRequestUuid;
use OCA\Libresign\Middleware\Attribute\PrivateValidation;
use OCA\Libresign\Middleware\Attribute\RequireFileAccess;
use OCA\Libresign\Middleware\Attribute\RequireManager;
use OCA\Libresign\Middleware\Attribute\RequireSetupOk;
use OCA\Libresign\Middleware\Attribute\RequireSigner;
use OCA\Libresign\Middleware\Attribute\RequireSignerUuid;
use OCA\Libresign\Middleware\Attribute\RequireSignRequestUuid;
use OCA\Libresign\Service\FileAccessService;
use OCA\Libresign\Service\SignFileService;
use OCA\Libresign\Service\UuidResolverService;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\ContentSecurityPolicy;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Http\JSONResponse;
use OCP\AppFramework\Http\RedirectResponse;
use OCP\AppFramework\Http\Response;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\AppFramework\Middleware;
use OCP\AppFramework\Services\IInitialState;
use OCP\IAppConfig;
use OCP\IL10N;
use OCP\IRequest;
use OCP\ISession;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserSession;
use OCP\Util;
class InjectionMiddleware extends Middleware {
public function __construct(
private IRequest $request,
private ISession $session,
private IUserSession $userSession,
private ValidateHelper $validateHelper,
private SignRequestMapper $signRequestMapper,
private CertificateEngineFactory $certificateEngineFactory,
private FileMapper $fileMapper,
private IInitialState $initialState,
private FileAccessService $fileAccessService,
private SignFileService $signFileService,
private UuidResolverService $uuidResolverService,
private IL10N $l10n,
private IAppConfig $appConfig,
private IURLGenerator $urlGenerator,
protected ?string $userId,
) {
$this->request = $request;
}
/**
* @param Controller $controller
* @param string $methodName
* @throws \Exception
*/
#[\Override]
public function beforeController(Controller $controller, string $methodName) {
if ($controller instanceof AEnvironmentAwareController) {
$apiVersion = $this->request->getParam('apiVersion');
/** @var AEnvironmentAwareController $controller */
$controller->setAPIVersion((int)substr((string)$apiVersion, 1));
}
$reflectionMethod = new \ReflectionMethod($controller, $methodName);
if (!empty($reflectionMethod->getAttributes(RequireManager::class))) {
$this->getLoggedIn();
}
if (!empty($reflectionMethod->getAttributes(RequireSigner::class))) {
$this->requireSigner();
}
if (!empty($reflectionMethod->getAttributes(RequireSignerUuid::class))) {
$this->requireSignerUuid();
}
if (!empty($reflectionMethod->getAttributes(RequireFileAccess::class))) {
$this->requireFileAccess($reflectionMethod);
}
$this->requireSetupOk($reflectionMethod);
$this->privateValidation($reflectionMethod);
$this->handleUuid($controller, $reflectionMethod);
}
private function privateValidation(\ReflectionMethod $reflectionMethod): void {
if (empty($reflectionMethod->getAttributes(PrivateValidation::class))) {
return;
}
if ($this->userSession->isLoggedIn()) {
return;
}
$isValidationUrlPrivate = (bool)$this->appConfig->getValueBool(Application::APP_ID, 'make_validation_url_private', false);
if (!$isValidationUrlPrivate) {
return;
}
$redirectUrl = $this->request->getRawPathInfo();
throw new LibresignException(json_encode([
'action' => JSActions::ACTION_REDIRECT,
'errors' => [$this->l10n->t('You are not logged in. Please log in.')],
'redirect' => $this->urlGenerator->linkToRoute('core.login.showLoginForm', [
'redirect_url' => $redirectUrl,
]),
]), Http::STATUS_UNAUTHORIZED);
}
private function handleUuid(Controller $controller, \ReflectionMethod $reflectionMethod): void {
if (!$controller instanceof ISignatureUuid) {
return;
}
$uuid = $this->getUuidFromRequest();
$this->maintainSessionConsistencyWithUuid($uuid);
if (!empty($reflectionMethod->getAttributes(CanSignRequestUuid::class))) {
/** @var AEnvironmentPageAwareController $controller */
$controller->validateRenewSigner(
uuid: $uuid,
);
/** @var AEnvironmentPageAwareController $controller */
$controller->loadNextcloudFileFromSignRequestUuid(
uuid: $uuid,
);
}
if (!empty($attribute = $reflectionMethod->getAttributes(RequireSignRequestUuid::class))) {
$attribute = $reflectionMethod->getAttributes(RequireSignRequestUuid::class);
$attribute = current($attribute);
/** @var RequireSignRequestUuid $intance */
$intance = $attribute->newInstance();
$user = $this->userSession->getUser();
$this->redirectSignedToValidationIfNeeded($intance);
$isIdDocApproval = $intance->allowIdDocs() && $this->request->getParam('idDocApproval') === 'true';
if (!($intance->skipIfAuthenticated() && $user instanceof IUser)) {
if ($isIdDocApproval) {
try {
$resolution = $this->uuidResolverService->resolveUuidForUser($uuid, $user);
/** @var AEnvironmentPageAwareController $controller */
$controller->loadIdDocApprovalFromResolution($resolution);
} catch (LibresignException $e) {
throw $e;
}
} else {
/** @var AEnvironmentPageAwareController $controller */
$controller->validateSignRequestUuid(
uuid: $uuid,
);
/** @var AEnvironmentPageAwareController $controller */
$controller->loadNextcloudFileFromSignRequestUuid(
uuid: $uuid,
);
}
}
}
}
private function getUuidFromRequest(): ?string {
return $this->request->getParam('uuid', $this->request->getHeader('libresign-sign-request-uuid'));
}
/**
* Maintain session consistency when sign request UUID is provided
*
* For unauthenticated requests with a sign request UUID header,
* store the UUID in the session to ensure consistent session ID
* across multiple HTTP requests. Each request without authentication
* would otherwise create a new session ID, causing data lookup failures.
*
* @param string|null $uuid The sign request UUID from request header
*/
private function maintainSessionConsistencyWithUuid(?string $uuid): void {
if ($uuid && !($this->userSession->getUser() instanceof IUser)) {
if (!$this->session->get('libresign-uuid')) {
$this->session->set('libresign-uuid', $uuid);
}
}
}
private function getLoggedIn(): void {
$user = $this->userSession->getUser();
if (!$user instanceof IUser) {
throw new \Exception($this->l10n->t('You are not allowed to request signing'), Http::STATUS_UNPROCESSABLE_ENTITY);
}
$this->validateHelper->canRequestSign($user);
}
private function requireSigner(): void {
$uuid = $this->getUuidFromRequest();
try {
$user = $this->userSession->getUser();
$isIdDocApproval = $this->request->getParam('idDocApproval') === 'true';
if ($isIdDocApproval) {
$this->uuidResolverService->resolveUuidForUser($uuid, $user);
} else {
$this->validateHelper->validateSigner($uuid, $user);
}
} catch (LibresignException $e) {
throw new LibresignException($e->getMessage());
}
}
private function requireSignerUuid(): void {
$uuid = $this->getUuidFromRequest();
try {
$this->validateHelper->validateSignerUuid($uuid);
} catch (LibresignException $e) {
throw new LibresignException($e->getMessage());
}
}
private function requireFileAccess(\ReflectionMethod $reflectionMethod): void {
$attributes = $reflectionMethod->getAttributes(RequireFileAccess::class);
$attribute = current($attributes);
/** @var RequireFileAccess $requirement */
$requirement = $attribute->newInstance();
$identifier = $requirement->getIdentifier();
$hasAccess = match ($identifier) {
'nodeId' => $this->fileAccessService->userCanAccessFileByNodeId((int)$this->request->getParam('nodeId', -1)),
'fileId' => $this->fileAccessService->userCanAccessFileById((int)$this->request->getParam('fileId', -1)),
default => throw new \InvalidArgumentException('Unsupported file access identifier: ' . $identifier),
};
if ($hasAccess) {
return;
}
throw new LibresignException(json_encode([]), Http::STATUS_FORBIDDEN);
}
private function redirectSignedToValidationIfNeeded(RequireSignRequestUuid $requirement): void {
if (!$requirement->redirectIfSignedToValidation()) {
return;
}
$uuid = $this->getUuidFromRequest();
if (!$uuid) {
return;
}
try {
$signRequest = $this->signRequestMapper->getByUuid($uuid);
if ($signRequest->getStatusEnum() !== SignRequestStatus::SIGNED) {
return;
}
$file = $this->fileMapper->getById($signRequest->getFileId());
$fileUuid = $file->getUuid();
} catch (\Throwable) {
return;
}
$path = $this->request->getRawPathInfo() ?? '';
$redirectUrl = str_contains($path, '/p/')
? $this->urlGenerator->linkToRouteAbsolute('libresign.page.validationFilePublic', [
'uuid' => $fileUuid,
])
: $this->urlGenerator->linkToRouteAbsolute('libresign.page.indexFPath', [
'path' => 'validation/' . $fileUuid,
]);
throw new LibresignException(json_encode([
'action' => JSActions::ACTION_REDIRECT,
'redirect' => $redirectUrl,
]), Http::STATUS_SEE_OTHER);
}
private function requireSetupOk(\ReflectionMethod $reflectionMethod): void {
$attribute = $reflectionMethod->getAttributes(RequireSetupOk::class);
if (empty($attribute)) {
return;
}
$attribute = current($attribute);
if (!$this->certificateEngineFactory->getEngine()->isSetupOk()) {
/** @var RequireSetupOk $requirement */
$requireSetupOk = $attribute->newInstance();
throw new LibresignException(json_encode([
'action' => JSActions::ACTION_INCOMPLETE_SETUP,
'template' => $requireSetupOk->getTemplate(),
]));
}
}
/**
* @param Controller $controller
* @param string $methodName
* @param \Exception $exception
* @throws \Exception
* @return Response
*/
#[\Override]
public function afterException($controller, $methodName, \Exception $exception): Response {
if (str_contains($this->request->getHeader('Accept'), 'html')) {
$template = 'external';
if ($this->isJson($exception->getMessage())) {
$settings = json_decode($exception->getMessage(), true);
if (isset($settings['action']) && $settings['action'] === JSActions::ACTION_REDIRECT && isset($settings['redirect'])) {
if (isset($settings['errors'])) {
$this->session->set('loginMessages', [
[], $settings['errors'],
]);
}
return new RedirectResponse($settings['redirect']);
}
foreach ($settings as $key => $value) {
if ($key === 'template') {
$template = $value;
continue;
}
$this->initialState->provideInitialState($key, $value);
}
} else {
$this->initialState->provideInitialState('error', ['message' => $exception->getMessage()]);
}
Util::addScript(Application::APP_ID, 'libresign-' . $template);
Util::addStyle(Application::APP_ID, 'libresign-' . $template);
$response = new TemplateResponse(
appName: Application::APP_ID,
templateName: $template,
renderAs: $this->getRenderAsFromTemplate($template),
status: $this->getStatusCodeFromException($exception)
);
$policy = new ContentSecurityPolicy();
$policy->addAllowedFrameDomain('\'self\'');
$response->setContentSecurityPolicy($policy);
return $response;
}
if ($exception instanceof LibresignException) {
if ($this->isJson($exception->getMessage())) {
$body = json_decode($exception->getMessage());
} else {
$body = [
'message' => $exception->getMessage(),
];
}
if ($controller instanceof \OCP\AppFramework\OCSController) {
$format = $this->request->getParam('format');
// if none is given try the first Accept header
if ($format === null) {
$headers = $this->request->getHeader('Accept');
$format = $controller->getResponderByHTTPHeader($headers, 'json');
}
$response = new DataResponse(
data: $body,
statusCode: $this->getStatusCodeFromException($exception)
);
if ($format !== null) {
$response = $controller->buildResponse($response, $format);
} else {
$response = $controller->buildResponse($response);
}
} else {
$response = new JSONResponse(
data: $body,
statusCode: $this->getStatusCodeFromException($exception)
);
}
return $response;
}
throw $exception;
}
private function getRenderAsFromTemplate(string $template): string {
if ($template === 'external') {
return TemplateResponse::RENDER_AS_BASE;
}
return TemplateResponse::RENDER_AS_USER;
}
private function getStatusCodeFromException(\Exception $exception): int {
if ($exception->getCode() === 0) {
return AppFrameworkHttp::STATUS_UNPROCESSABLE_ENTITY;
}
return (int)$exception->getCode();
}
protected function isJson(string $string): bool {
json_decode($string);
return json_last_error() === JSON_ERROR_NONE;
}
}