Repository navigation
Expand file tree
/
Copy pathReference.php
More file actions
422 lines (340 loc) · 14.4 KB
/
Copy pathReference.php
File metadata and controls
422 lines (340 loc) · 14.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
416
417
418
419
420
421
422
<?php
declare(strict_types=1);
namespace Jane\Component\JsonSchemaRuntime;
use Jane\Component\JsonSchemaRuntime\Exception\InvalidReferenceException;
use Jane\Component\JsonSchemaRuntime\Exception\ReferenceDecodeException;
use Jane\Component\JsonSchemaRuntime\Exception\ReferenceFetchException;
use Jane\Component\JsonSchemaRuntime\Exception\ReferencePointerException;
use League\Uri\Http;
use League\Uri\UriString;
use Psr\Http\Message\UriInterface;
use Rs\Json\Pointer;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml;
/**
* Deal with a JSON Reference.
*/
class Reference
{
/**
* league/uri v7 static factories, detected once per process: composer
* allows both ^6.7.2 and ^7.4, and method_exists() must not run on every
* single Reference construction.
*/
private static ?bool $uriHasNewFactory = null;
private static ?bool $uriHasFromComponentsFactory = null;
private string|int|float|bool|array|null $resolved = null;
private Http $referenceUri;
private Http $originUri;
private Http $mergedUri;
private ReferenceResolver $resolver;
public function __construct(string $reference, string $origin, ?ReferenceResolver $resolver = null)
{
$this->resolver = $resolver ?? ReferenceResolver::default();
$reference = $this->fixPath($reference);
$origin = $this->fixPath($origin);
$originParts = UriString::parse($origin);
$referenceParts = parse_url($reference);
$mergedParts = array_merge($originParts, $referenceParts);
if (\array_key_exists('path', $referenceParts)) {
$mergedParts['path'] = $this->joinPath(\dirname($originParts['path']), $referenceParts['path']);
}
self::$uriHasNewFactory ??= method_exists(Http::class, 'new');
self::$uriHasFromComponentsFactory ??= method_exists(Http::class, 'fromComponents');
try {
$this->referenceUri = self::$uriHasNewFactory ? Http::new($reference) : Http::createFromString($reference);
$this->originUri = self::$uriHasNewFactory ? Http::new($origin) : Http::createFromString($origin);
$this->mergedUri = self::$uriHasFromComponentsFactory ? Http::fromComponents($mergedParts) : Http::createFromComponents($mergedParts);
} catch (\Throwable $exception) {
throw new InvalidReferenceException(\sprintf('Unable to parse reference "%s" against origin "%s".', $reference, $origin), 0, $exception);
}
}
/**
* Resolve a JSON Reference.
*
* @return mixed Return the json value (deserialized) referenced
*/
public function resolve(?callable $deserializeCallback = null)
{
if (null === $this->resolved) {
$this->resolved = $this->doResolve();
}
if (null === $deserializeCallback) {
return $this->resolved;
}
return $deserializeCallback($this->resolved);
}
/**
* Resolve a JSON Reference for a Schema.
*
* @return string|int|float|bool|array|null Return the json value referenced
*/
protected function doResolve(): string|int|float|bool|array|null
{
$fragment = (string) $this->mergedUri->withFragment('');
$reference = \sprintf('%s_%s', $fragment, $this->mergedUri->getFragment());
$this->validateReference($fragment);
if (!$this->resolver->hasFile($fragment)) {
$this->resolver->setFile($fragment, $this->fetchAndNormalizeContents($fragment));
}
if (!$this->resolver->hasArray($reference)) {
if ('' === $this->mergedUri->getFragment()) {
$array = json_decode($this->resolver->getFile($fragment), true);
} else {
try {
if (!$this->resolver->hasPointer($fragment)) {
$this->resolver->setPointer($fragment, new Pointer($this->resolver->getFile($fragment)));
}
$pointer = $this->resolver->getPointer($fragment)->get($this->mergedUri->getFragment());
} catch (\Throwable $exception) {
throw new ReferencePointerException(\sprintf('Unable to resolve pointer "%s" in reference document "%s".', $this->mergedUri->getFragment(), $fragment), 0, $exception);
}
$array = json_decode(json_encode($pointer), true);
}
$this->resolver->setArray($reference, $array);
}
return $this->resolver->getArray($reference);
}
/**
* Fetch the referenced document and normalize its contents to JSON.
*
* JSON is tried first (valid JSON roots such as "[]" / "0" / "null" must
* not be misrouted through the YAML parser); YAML is the fallback for
* YAML documents.
*/
private function fetchAndNormalizeContents(string $fragment): string
{
// Redirects are not followed by default (see setFollowRedirects()): an
// allowlisted host must not be able to bounce the fetch to an
// arbitrary (possibly non allowlisted) host.
$context = stream_context_create([
'http' => ['follow_location' => $this->resolver->followsRedirects() ? 1 : 0],
]);
// $http_response_header is populated by the HTTP stream wrapper in
// this very scope (overwriting this default), and is left empty for
// every other wrapper: initialize it so the read below is always safe.
$http_response_header = [];
$contents = @file_get_contents($fragment, false, $context);
if (false === $contents) {
throw new ReferenceFetchException(\sprintf('Unable to fetch reference document "%s".', $fragment));
}
if (!$this->resolver->followsRedirects()) {
$statusCode = $this->lastHttpStatusCode($http_response_header);
if (null !== $statusCode && $statusCode >= 300 && $statusCode < 400) {
throw new ReferenceFetchException(\sprintf('Reference document "%s" answered with HTTP status %d: redirects are not followed when fetching external references (set "external-ref-follow-redirects" to true to enable them).', $fragment, $statusCode));
}
}
try {
json_decode($contents, true, 512, \JSON_THROW_ON_ERROR);
return $contents;
} catch (\JsonException) {
// Not JSON: fall back to YAML parsing below.
}
try {
$decoded = Yaml::parse($contents,
Yaml::PARSE_OBJECT | Yaml::PARSE_OBJECT_FOR_MAP | Yaml::PARSE_DATETIME | Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE);
} catch (ParseException $exception) {
throw new ReferenceDecodeException(\sprintf('Unable to parse reference document "%s": content is neither valid JSON nor valid YAML.', $fragment), 0, $exception);
}
$encoded = json_encode($decoded);
if (false === $encoded) {
throw new ReferenceDecodeException(\sprintf('Unable to convert reference document "%s" back to JSON.', $fragment));
}
return $encoded;
}
/**
* HTTP status of the last fetch, parsed from the headers populated by the
* HTTP stream wrapper ($http_response_header, local to the fetch call).
*
* @param array<string> $responseHeaders
*/
private function lastHttpStatusCode(array $responseHeaders): ?int
{
$statusLine = null;
foreach ($responseHeaders as $header) {
if (str_starts_with($header, 'HTTP/')) {
$statusLine = $header;
}
}
if (null === $statusLine || !preg_match('#^HTTP/\S+\s+(\d{3})#', $statusLine, $matches)) {
return null;
}
return (int) $matches[1];
}
/**
* Return true if reference and origin are in the same document.
*/
public function isInCurrentDocument(): bool
{
return
$this->mergedUri->getScheme() === $this->originUri->getScheme()
&& $this->mergedUri->getHost() === $this->originUri->getHost()
&& $this->mergedUri->getPort() === $this->originUri->getPort()
&& $this->mergedUri->getPath() === $this->originUri->getPath()
&& $this->mergedUri->getQuery() === $this->originUri->getQuery()
;
}
public function getMergedUri(): UriInterface
{
return $this->mergedUri;
}
public function getReferenceUri(): UriInterface
{
return $this->referenceUri;
}
public function getOriginUri(): UriInterface
{
return $this->originUri;
}
private function validateReference(string $fragment): void
{
$scheme = $this->mergedUri->getScheme();
$allowedSchemes = ['', 'http', 'https', 'file'];
if (!\in_array($scheme, $allowedSchemes, true)) {
throw new InvalidReferenceException(\sprintf('Reference scheme "%s" is not allowed. Allowed schemes: http, https, file (or local path without scheme).', $scheme));
}
if ('' === $scheme || 'file' === $scheme) {
$this->validateLocalPath($fragment);
}
if (\in_array($scheme, ['http', 'https'], true)) {
$this->validateRemoteRef();
}
}
private function validateLocalPath(string $fragment): void
{
$originPath = $this->originUri->getPath();
// An empty or root origin path degenerates to an empty base directory,
// which authorizes absolute paths only: containment logic still runs,
// there is just no meaningful directory to stay under.
$baseDir = \dirname($originPath);
$basePath = is_dir($baseDir) ? realpath($baseDir) : false;
if (false === $basePath) {
$basePath = $baseDir;
}
$basePath = rtrim(str_replace('\\', '/', $basePath), '/');
$path = $fragment;
if (str_starts_with($path, 'file://')) {
$path = substr($path, 7);
}
if (!str_starts_with($path, '/') && !preg_match('#^[a-zA-Z]:/#', $path)) {
$path = $basePath . '/' . $path;
}
$normalized = file_exists($path) ? realpath($path) : false;
if (false === $normalized) {
$normalized = $this->normalizePath($path);
}
$normalized = str_replace('\\', '/', $normalized);
$allowedBases = $this->getAllowedLocalBases($basePath);
foreach ($allowedBases as $base) {
if ($normalized === $base || str_starts_with($normalized, $base . '/')) {
return;
}
}
throw new InvalidReferenceException(\sprintf('Local reference "%s" resolves outside the allowed directories [%s]. Add its location to "allowed-local-ref-roots" in your Jane configuration.', $fragment, implode(', ', $allowedBases)));
}
/**
* Directories a local reference may resolve into: the directory of the referencing
* document, plus every root explicitly allowed through "allowed-local-ref-roots".
*
* @return string[]
*/
private function getAllowedLocalBases(string $basePath): array
{
$bases = [$basePath];
foreach ($this->resolver->getAllowedLocalRefRoots() as $root) {
if (!\is_string($root) || '' === $root) {
continue;
}
$root = str_replace('\\', '/', $root);
$realRoot = is_dir($root) ? realpath($root) : false;
$root = false !== $realRoot ? str_replace('\\', '/', $realRoot) : $this->normalizePath($root);
if ('' === $root) {
continue;
}
$bases[] = rtrim($root, '/');
}
return array_values(array_unique($bases));
}
private function validateRemoteRef(): void
{
if (!$this->resolver->allowsExternalRefs()) {
throw new InvalidReferenceException('External (HTTP/HTTPS) references are not allowed. Set "allow-external-refs" to true in your Jane configuration to enable them, or use "external-ref-allowed-hosts" to restrict to specific hosts.');
}
if ([] !== $this->resolver->getAllowedExternalHosts()) {
$host = $this->mergedUri->getHost();
$allowed = false;
foreach ($this->resolver->getAllowedExternalHosts() as $allowedHost) {
if ($host === $allowedHost || str_ends_with($host, '.' . $allowedHost)) {
$allowed = true;
break;
}
}
if (!$allowed) {
throw new InvalidReferenceException(\sprintf('Remote reference host "%s" is not allowed. Must be one of: %s.', $host, implode(', ', $this->resolver->getAllowedExternalHosts())));
}
}
}
private function normalizePath(string $path): string
{
$parts = explode('/', str_replace('\\', '/', $path));
$resolved = [];
foreach ($parts as $part) {
if ('.' === $part || '' === $part) {
continue;
}
if ('..' === $part) {
if ([] !== $resolved) {
array_pop($resolved);
}
continue;
}
$resolved[] = $part;
}
$prefix = '';
if (str_starts_with($path, '/')) {
$prefix = '/';
}
return $prefix . implode('/', $resolved);
}
/**
* Join path like unix path join :.
*
* a/b + c => a/b/c
* a/b + /c => /c
* a/b/c + .././d => a/b/d
*/
private function joinPath(...$paths): string
{
$resultPath = null;
foreach ($paths as $path) {
if (null === $resultPath || (!empty($path) && '/' === $path[0])) {
$resultPath = $path;
} else {
$resultPath = $resultPath . '/' . $path;
}
}
$resultPath = preg_replace('~/{2,}~', '/', $resultPath);
if ('/' === $resultPath) {
return '/';
}
$resultPathParts = [];
foreach (explode('/', rtrim($resultPath, '/')) as $part) {
if ('.' === $part) {
continue;
}
if ('..' === $part && \count($resultPathParts) > 0) {
array_pop($resultPathParts);
continue;
}
$resultPathParts[] = $part;
}
return implode('/', $resultPathParts);
}
private function fixPath(string $path): string
{
if ('\\' === \DIRECTORY_SEPARATOR) {
$path = lcfirst(str_replace(\DIRECTORY_SEPARATOR, '/', $path));
}
return $path;
}
}