-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathProvideConsent.php
More file actions
343 lines (293 loc) · 13.5 KB
/
Copy pathProvideConsent.php
File metadata and controls
343 lines (293 loc) · 13.5 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
<?php
/**
* Copyright 2010 SURFnet B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use OpenConext\EngineBlock\Authentication\Value\ConsentType;
use OpenConext\EngineBlock\Metadata\Entity\IdentityProvider;
use OpenConext\EngineBlock\Metadata\Entity\ServiceProvider;
use OpenConext\EngineBlock\Service\AuthenticationStateHelperInterface;
use OpenConext\EngineBlock\Service\Consent\ConsentServiceInterface;
use OpenConext\EngineBlock\Service\ProcessingStateHelperInterface;
use OpenConext\EngineBlockBundle\Service\DiscoverySelectionService;
use Psr\Log\LogLevel;
use SAML2\Constants;
use Symfony\Component\HttpFoundation\Request;
use Twig\Environment;
/**
* Ask the user for consent over all of the attributes being sent to the SP.
*
* Note this is part 1/2 of the Corto Consent Internal Response Processing service.
*/
class EngineBlock_Corto_Module_Service_ProvideConsent
implements EngineBlock_Corto_Module_Service_ServiceInterface
{
/** @var EngineBlock_Corto_ProxyServer */
private $_server;
/**
* @var EngineBlock_Corto_XmlToArray
*/
private $_xmlConverter;
/** @var EngineBlock_Corto_Model_Consent_Factory */
private $_consentFactory;
/** @var ConsentServiceInterface */
private $_consentService;
/** @var AuthenticationStateHelperInterface */
private $_authenticationStateHelper;
/**
* @var Environment
*/
private $twig;
/**
* @var ProcessingStateHelperInterface
*/
private $_processingStateHelper;
/** @var \Psr\Log\LoggerInterface */
private $logger;
private DiscoverySelectionService $discoverySelectionService;
public function __construct(
EngineBlock_Corto_ProxyServer $server,
EngineBlock_Corto_XmlToArray $xmlConverter,
EngineBlock_Corto_Model_Consent_Factory $consentFactory,
ConsentServiceInterface $consentService,
AuthenticationStateHelperInterface $authStateHelper,
Environment $twig,
ProcessingStateHelperInterface $processingStateHelper,
DiscoverySelectionService $discoverySelectionService
)
{
$this->_server = $server;
$this->_xmlConverter = $xmlConverter;
$this->_consentFactory = $consentFactory;
$this->_consentService = $consentService;
$this->_authenticationStateHelper = $authStateHelper;
$this->twig = $twig;
$this->_processingStateHelper = $processingStateHelper;
$this->logger = EngineBlock_ApplicationSingleton::getLog();
$this->discoverySelectionService = $discoverySelectionService;
}
/**
* @param $serviceName
* @param Request $httpRequest
*/
public function serve($serviceName, Request $httpRequest)
{
$serviceEntityId = $this->_server->getUrl('assertionConsumerService');
$response = $this->_server->getBindingsModule()->receiveResponse($serviceEntityId, $serviceEntityId);
$receivedRequest = $this->_server->getReceivedRequestFromResponse($response);
$correlationIdRepository = EngineBlock_ApplicationSingleton::getInstance()
->getDiContainer()
->getCorrelationIdRepository();
$correlationIdRepository->resolve($receivedRequest->getId());
// update previous response with current response
$this->_processingStateHelper->updateStepResponseByRequestId(
$receivedRequest->getId(),
ProcessingStateHelperInterface::STEP_CONSENT,
$response
);
$request = $this->_server->getReceivedRequestFromResponse($response);
$serviceProvider = $this->_server->getRepository()->fetchServiceProviderByEntityId($request->getIssuer()->getValue());
$spMetadataChain = EngineBlock_SamlHelper::getSpRequesterChain(
$serviceProvider,
$request,
$this->_server->getRepository()
);
$identityProviderEntityId = $response->getOriginalIssuer();
$identityProvider = $this->_server->getRepository()->fetchIdentityProviderByEntityId($identityProviderEntityId);
// Flush log if SP or IdP has additional logging enabled
$requireAdditionalLogging = EngineBlock_SamlHelper::doRemoteEntitiesRequireAdditionalLogging(
array_merge($spMetadataChain, array($identityProvider))
);
if ($requireAdditionalLogging) {
$application = EngineBlock_ApplicationSingleton::getInstance();
$application->flushLog(
'Activated additional logging for one or more SPs in the SP requester chain, or the IdP'
);
$this->logger->info('Raw HTTP request', array('http_request' => (string) $application->getHttpRequest()));
}
// $serviceProviderMetadata will contain the metadata of the SP we'll be presenting to
// the user, either the directly connected SP, or in case of trusted proxy, the SP behind
// that proxy.
$serviceProviderMetadata = $spMetadataChain[0];
$attributes = $response->getAssertion()->getAttributes();
$consentRepository = $this->_consentFactory->create($this->_server, $response, $attributes);
$authenticationState = $this->_authenticationStateHelper->getAuthenticationState();
$session = $httpRequest->getSession();
$idpDiscovery = $this->discoverySelectionService->getDiscoveryFromRequest($session, $identityProvider);
if ($this->isConsentDisabled($spMetadataChain, $identityProvider)) {
$implicitConsent = $consentRepository->implicitConsentWasGivenFor($serviceProviderMetadata);
if (!$implicitConsent->given()) {
$consentRepository->giveImplicitConsentFor($serviceProviderMetadata);
} else {
$consentRepository->upgradeAttributeHashFor($serviceProviderMetadata, ConsentType::Implicit, $implicitConsent);
}
$response->setConsent(Constants::CONSENT_INAPPLICABLE);
$response->setDestination($response->getReturn());
$response->setDeliverByBinding('INTERNAL');
// Consent is disabled, we now mark authentication_state as completed
$authenticationState->completeCurrentProcedure($response->getInResponseTo());
$this->_server->getBindingsModule()->send(
$response,
$serviceProvider
);
return;
}
$priorConsent = $consentRepository->explicitConsentWasGivenFor($serviceProviderMetadata);
if ($priorConsent->given()) {
$consentRepository->upgradeAttributeHashFor($serviceProviderMetadata, ConsentType::Explicit, $priorConsent);
$response->setConsent(Constants::CONSENT_PRIOR);
$response->setDestination($response->getReturn());
$response->setDeliverByBinding('INTERNAL');
// Prior consent is found, we now mark authentication_state as completed
$authenticationState->completeCurrentProcedure($response->getInResponseTo());
$this->_server->getBindingsModule()->send(
$response,
$serviceProvider
);
return;
}
$settings = EngineBlock_ApplicationSingleton::getInstance()->getDiContainer();
// Profile url is configurable in parameters.yaml (profile_base_url)
$profileUrl = '#';
$configuredUrl = $settings->getProfileBaseUrl();
if (!empty($configuredUrl)) {
$profileUrl = $configuredUrl;
}
// If attribute manipulation was executed before consent, the SetNameId filter has already been applied, and
// applying the NameIdResolver is not required.
$featureConfiguration = $settings->getFeatureConfiguration();
$amPriorToConsent = $featureConfiguration->isEnabled('eb.run_all_manipulations_prior_to_consent');
// Show the correctly formatted nameId on the consent screen
$isPersistent = $serviceProviderMetadata->nameIdFormat === Constants::NAMEID_PERSISTENT;
// Create a local copy of the NameID that is set on the response. We do not yet want to update the actual NameID
// in the $response yet as this will cause side effects when saving the consent entry. The 'hashed user id'
// will not be consistent.
$nameId = clone $response->getNameId();
if ($isPersistent && !$amPriorToConsent) {
$collabPersonIdValue = $nameId->getValue();
// Load the persistent name id for this combination of SP/Identifier and update the local copy of the nameId
// to ensure the correct identifier is shown on the consent screen.
$resolver = new EngineBlock_Saml2_NameIdResolver($this->logger);
$nameId = $resolver->resolve(
$request,
$response,
$serviceProviderMetadata,
$collabPersonIdValue
);
}
// The nameId format is not yet updated on the response (will be performed in the SetNameId filter after
// consent), but in order to display the correct nameId format, we set the SP requested name Id format on the
// name id copy that is used to render the correct identifier on the consent page. If AM was already performed,
// use the nameIdFormat from the nameId, and do not overwrite it with the SP's preferred format.
if (!$amPriorToConsent) {
$nameId->setFormat($serviceProviderMetadata->nameIdFormat);
}
$html = $this->twig->render(
'@theme/Authentication/View/Proxy/consent.html.twig',
[
'action' => $this->_server->getUrl('processConsentService'),
'responseId' => $receivedRequest->getId(),
'sp' => $serviceProviderMetadata,
'idp' => $identityProvider,
'idpDiscovery' => $idpDiscovery,
'idpSupport' => $this->getSupportContact($identityProvider),
'attributes' => $attributes,
'attributeSources' => $this->getAttributeSources($request->getId()),
'attributeMotivations' => $this->getAttributeMotivations($serviceProviderMetadata, $attributes),
'informationalConsent' => $identityProvider->getConsentSettings()->isInformational($serviceProviderMetadata->entityId),
'consentCount' => $this->_consentService->countAllFor($response->getNameIdValue()),
'nameId' => $nameId,
'nameIdIsPersistent' => $isPersistent,
'profileUrl' => $profileUrl,
'showConsentExplanation' => $identityProvider->getConsentSettings()->hasConsentExplanation($serviceProviderMetadata->entityId),
'consentSettings' => $identityProvider->getConsentSettings(),
'spEntityId' => $serviceProviderMetadata->entityId,
'hideHeader' => true,
'hideFooter' => true,
]
);
$this->_server->sendOutput($html);
}
/**
* @param ServiceProvider[] $serviceProviders
* @param IdentityProvider $identityProvider
* @return bool
*/
private function isConsentDisabled(array $serviceProviders, IdentityProvider $identityProvider)
{
foreach ($serviceProviders as $serviceProvider) {
if (!$serviceProvider->getCoins()->isConsentRequired()) {
return true;
}
if (!$identityProvider->getConsentSettings()->isEnabled($serviceProvider->entityId)) {
return true;
}
}
return false;
}
/**
* Find attribute sources in the session.
*
* The attribute aggregator corto filter stores the aggregated attribute
* sources in the session.
*/
private function getAttributeSources($requestId)
{
if (isset($_SESSION[$requestId]['attribute_sources'])) {
return $_SESSION[$requestId]['attribute_sources'];
}
return [];
}
/**
* Find motivations in SP ARP for all given attributes.
*
* @param ServiceProvider $sp
* @param array $attributes
* @return array
*/
private function getAttributeMotivations(ServiceProvider $sp, array $attributes)
{
$motivations = [];
foreach (array_keys($attributes) as $attributeName) {
$motivations[$attributeName] = $this->getAttributeMotivation($sp, $attributeName);
}
return array_filter($motivations);
}
/**
* Find motivation text in SP ARP for given attribute.
*
* @param ServiceProvider $sp
* @param string $attributeName
* @return string
*/
private function getAttributeMotivation(ServiceProvider $sp, $attributeName)
{
$arp = $sp->getAttributeReleasePolicy();
if ($arp === null) {
return null;
}
return $arp->getMotivation($attributeName);
}
/**
* @return ContactPerson|null
*/
public function getSupportContact(IdentityProvider $idp)
{
foreach ($idp->contactPersons as $contact) {
if ($contact->contactType === 'support') {
return $contact;
}
}
}
}