-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathEntitySource.php
More file actions
272 lines (228 loc) · 7.78 KB
/
EntitySource.php
File metadata and controls
272 lines (228 loc) · 7.78 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
<?php
declare(strict_types=1);
namespace SimpleSAML\Module\aggregator2;
use DateInterval;
use DateTimeImmutable;
use DateTimeZone;
use Exception;
use SimpleSAML\Configuration;
use SimpleSAML\Error;
use SimpleSAML\Logger;
use SimpleSAML\SAML2\Utils\XPath;
use SimpleSAML\SAML2\XML\md\EntitiesDescriptor;
use SimpleSAML\SAML2\XML\md\EntityDescriptor;
use SimpleSAML\Utils;
use SimpleSAML\XML\DOMDocumentFactory;
use SimpleSAML\XMLSecurity\Alg\Signature\SignatureAlgorithmFactory;
use SimpleSAML\XMLSecurity\Key\PublicKey;
use function file_exists;
use function file_get_contents;
use function is_null;
use function parse_url;
use function serialize;
use function sha1;
use function strval;
use function time;
use function var_export;
/**
* Class for loading metadata from files and URLs.
*
* @package SimpleSAMLphp
*/
class EntitySource
{
/**
* Our log "location".
*
* @var string
*/
protected string $logLoc;
/**
* The aggregator we belong to.
*
* @var \SimpleSAML\Module\aggregator2\Aggregator
*/
protected Aggregator $aggregator;
/**
* The URL we should fetch it from.
*
* @var string
*/
protected string $url;
/**
* The certificate we should use to validate downloaded metadata.
*
* @var string|null
*/
protected ?string $certificate;
/**
* The parsed metadata.
*
* @var \SimpleSAML\SAML2\XML\md\EntitiesDescriptor|\SimpleSAML\SAML2\XML\md\EntityDescriptor|null
*/
protected EntityDescriptor|EntitiesDescriptor|null $metadata = null;
/**
* The cache ID.
*
* @var string
*/
protected string $cacheId;
/**
* The cache tag.
*
* @var string
*/
protected string $cacheTag;
/**
* Whether we have attempted to update the cache already.
*
* @var bool
*/
protected bool $updateAttempted = false;
/**
* Initialize this EntitySource.
*
* @param \SimpleSAML\Configuration $config The configuration.
*/
public function __construct(Aggregator $aggregator, Configuration $config)
{
$this->logLoc = 'aggregator2:' . $aggregator->getId() . ': ';
$this->aggregator = $aggregator;
$this->url = $config->getString('url');
$this->certificate = $config->getOptionalString('cert', null);
$this->cacheId = sha1($this->url);
$this->cacheTag = sha1(serialize($config));
}
/**
* Retrieve and parse the metadata.
*
* @return \SimpleSAML\SAML2\XML\md\EntitiesDescriptor|\SimpleSAML\SAML2\XML\md\EntityDescriptor|null
* The downloaded metadata or NULL if we were unable to download or parse it.
*/
private function downloadMetadata(): EntitiesDescriptor|EntityDescriptor|null
{
Logger::debug($this->logLoc . 'Downloading metadata from ' . var_export($this->url, true));
$configUtils = new Utils\Config();
$httpUtils = new Utils\HTTP();
$client = $httpUtils->createHttpClient();
$response = $client->request('GET', $this->url);
try {
// Trigger any issues that may occur during transport
$statusCode = $response->getStatusCode();
} catch (TransportException $e) {
Logger::error('Unable to load metadata from ' . var_export($this->url, true));
return null;
} finally {
$data = $response->getContent();
}
$doc = DOMDocumentFactory::create();
/** @var string $data */
$res = $doc->loadXML($data);
if (!$res) {
Logger::error($this->logLoc . 'Error parsing XML from ' . var_export($this->url, true));
return null;
}
/** @psalm-var \DOMElement[] $root */
$root = XPath::xpQuery(
$doc->documentElement,
'/saml_metadata:EntityDescriptor|/saml_metadata:EntitiesDescriptor',
XPath::getXPath($doc->documentElement),
);
if (count($root) === 0) {
Logger::error(
$this->logLoc . 'No <EntityDescriptor> or <EntitiesDescriptor> in metadata from ' .
var_export($this->url, true),
);
return null;
}
if (count($root) > 1) {
Logger::error(
$this->logLoc . 'More than one <EntityDescriptor> or <EntitiesDescriptor> in metadata from ' .
var_export($this->url, true),
);
return null;
}
$root = $root[0];
try {
if ($root->localName === 'EntityDescriptor') {
$md = EntityDescriptor::fromXML($root);
} else {
$md = EntitiesDescriptor::fromXML($root);
}
} catch (Exception $e) {
Logger::error(
$this->logLoc . 'Unable to parse metadata from ' .
var_export($this->url, true) . ': ' . $e->getMessage(),
);
return null;
}
if ($this->certificate !== null) {
$file = $configUtils->getCertPath($this->certificate);
$verifier = (new SignatureAlgorithmFactory())->getAlgorithm(
$md->getSignature()->getSignedInfo()->getSignatureMethod()->getAlgorithm(),
PublicKey::fromFile($file),
);
/** @var \SimpleSAML\SAML2\XML\md\EntitiesDescriptor|\SimpleSAML\SAML2\XML\md\EntityDescriptor $md */
$md = $md->verify($verifier);
Logger::debug($this->logLoc . 'Validated signature on metadata from ' . var_export($this->url, true));
}
return $md;
}
/**
* Attempt to update our cache file.
*/
public function updateCache(): void
{
if ($this->updateAttempted) {
return;
}
$this->updateAttempted = true;
$this->metadata = $this->downloadMetadata();
if ($this->metadata === null) {
return;
}
$now = new DateTimeImmutable('@' . strval(time()));
$now = $now->setTimeZone(new DateTimeZone('Z'));
$expires = $now->add(new DateInterval('PT24H'));
if ($this->metadata->getValidUntil() !== null && $this->metadata->getValidUntil() < $expires) {
$expires = $this->metadata->getValidUntil();
}
$metadataSerialized = serialize($this->metadata);
$this->aggregator->addCacheItem($this->cacheId, $metadataSerialized, $expires, $this->cacheTag);
}
/**
* Retrieve the metadata file.
*
* This function will check its cached copy, to see whether it can be used.
*
* @return \SimpleSAML\SAML2\XML\md\EntityDescriptor|\SimpleSAML\SAML2\XML\md\EntitiesDescriptor|null
* The downloaded metadata.
*/
public function getMetadata(): EntityDescriptor|EntitiesDescriptor|null
{
if ($this->metadata !== null) {
/* We have already downloaded the metdata. */
return $this->metadata;
}
if (!$this->aggregator->isCacheValid($this->cacheId, $this->cacheTag)) {
$this->updateCache();
/** @psalm-suppress TypeDoesNotContainType */
if ($this->metadata !== null) {
return $this->metadata;
}
/* We were unable to update the cache - use cached metadata. */
}
$cacheFile = $this->aggregator->getCacheFile($this->cacheId);
if (is_null($cacheFile) || !file_exists($cacheFile)) {
Logger::error($this->logLoc . 'No cached metadata available.');
return null;
}
Logger::debug($this->logLoc . 'Using cached metadata from ' . var_export($cacheFile, true));
$metadata = file_get_contents($cacheFile);
if ($metadata !== false) {
$this->metadata = unserialize($metadata);
return $this->metadata;
}
return null;
}
}