forked from stac-utils/stac-api-validator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidations.py
More file actions
3822 lines (3336 loc) · 131 KB
/
validations.py
File metadata and controls
3822 lines (3336 loc) · 131 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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Validations module."""
import copy
import itertools
import json
import logging
import re
import time
from dataclasses import dataclass
from enum import Enum
from typing import (
Any,
Dict,
Iterator,
List,
Mapping,
Optional,
Pattern,
Set,
Tuple,
Union,
)
import pystac
import yaml
from deepdiff import DeepDiff
from more_itertools import take
from pystac import (
Catalog,
Collection,
Item,
ItemCollection,
StacIO,
STACValidationError,
)
from pystac_client import Client
from requests import Request, Session
from shapely.geometry import shape
from stac_check.lint import Linter
from stac_validator.stac_validator import StacValidate
from stac_api_validator.geometries import (
geometry_collection,
linestring,
multilinestring,
multipoint,
multipolygon,
point,
polygon,
polygon_with_hole,
)
from .filters import (
cql2_json_and,
cql2_json_between,
cql2_json_common_1,
cql2_json_ex_2,
cql2_json_ex_3,
cql2_json_ex_4,
cql2_json_ex_6,
cql2_json_ex_8,
cql2_json_ex_9,
cql2_json_like,
cql2_json_not,
cql2_json_not_between,
cql2_json_not_like,
cql2_json_numeric_comparisons,
cql2_json_or,
cql2_json_s_intersects,
cql2_json_string_comparisons,
cql2_json_timestamp_comparisons,
cql2_text_and,
cql2_text_between,
cql2_text_ex_2,
cql2_text_ex_3,
cql2_text_ex_4,
cql2_text_ex_6,
cql2_text_ex_8,
cql2_text_ex_9,
cql2_text_like,
cql2_text_not,
cql2_text_not_between,
cql2_text_not_like,
cql2_text_numeric_comparisons,
cql2_text_or,
cql2_text_s_intersects,
cql2_text_string_comparisons,
cql2_text_timestamp_comparisons,
)
logger = logging.getLogger(__name__)
LATEST_STAC_API_FOUNDATION_VERSION = "https://api.stacspec.org/v1.0.0/"
class Method(Enum):
GET = "GET"
POST = "POST"
PUT = "PUT"
PATCH = "PATCH"
DELETE = "DELETE"
def __str__(self) -> str:
return self.value
class Context(Enum):
CORE = "Core"
ITEM_SEARCH = "Item Search"
FEATURES = "Features"
COLLECTIONS = "Collections"
CHILDREN = "Children Ext"
BROWSEABLE = "Browseable Ext"
ITEM_SEARCH_FILTER = "Item Search - Filter Ext"
ITEM_SEARCH_SORT = "Item Search - Sort Ext"
ITEM_SEARCH_FIELDS = "Item Search - Fields Ext"
ITEM_SEARCH_QUERY = "Item Search - Query Ext"
FEATURES_FILTER = "Features - Filter Ext"
FEATURES_SORT = "Features - Sort Ext"
FEATURES_FIELDS = "Features - Fields Ext"
FEATURES_QUERY = "Features - Query Ext"
FEATURES_TXN = "Features - Transaction Ext"
def __str__(self) -> str:
return self.value
class BaseErrors:
def __init__(self) -> None:
self.errors: List[Tuple[str, str]] = []
def __contains__(self, item: str) -> bool:
return item in (e[0] for e in self.errors)
def __bool__(self) -> bool:
return bool(self.errors)
def __str__(self) -> str:
return str(self.errors)
def __repr__(self) -> str:
return str(self.errors)
def __iter__(self) -> Iterator[str]:
return iter(self.as_list())
def as_list(self) -> List[str]:
return [e[1] for e in self.errors]
class Errors(BaseErrors):
def __iadd__(self, x: Union[Tuple[str, str], str]) -> "Errors":
if isinstance(x, str):
self.errors.append(("none", x))
elif isinstance(x, tuple):
self.errors.append(x)
return self
class Warnings(BaseErrors):
def __iadd__(self, x: Union[Tuple[str, str], str]) -> "Warnings":
if isinstance(x, str):
self.errors.append(("none", x))
elif isinstance(x, tuple):
self.errors.append(x)
return self
@dataclass
class QueryConfig:
query_comparison_field: Optional[str]
query_eq_value: Optional[str]
query_neq_value: Optional[str]
query_lt_value: Optional[str]
query_lte_value: Optional[str]
query_gt_value: Optional[str]
query_gte_value: Optional[str]
query_substring_field: Optional[str]
query_starts_with_value: Optional[str]
query_ends_with_value: Optional[str]
query_contains_value: Optional[str]
query_in_field: Optional[str]
query_in_values: Optional[str]
cc_core_regex = re.compile(r"https://api\.stacspec\.org/(.+)/core")
cc_browseable_regex = re.compile(r"https://api\.stacspec\.org/(.+)/browseable")
cc_children_regex = re.compile(r"https://api\.stacspec\.org/(.+)/children")
cc_collections_regex = re.compile(r"https://api\.stacspec\.org/(.+)/collections")
cc_features_regex = re.compile(r"https://api\.stacspec\.org/(.+)/ogcapi-features")
cc_features_transaction_regex = re.compile(
r"https://api\.stacspec\.org/(.+)/ogcapi-features/extensions/transaction"
)
cc_features_fields_regex = re.compile(
r"https://api\.stacspec\.org/(.+)/ogcapi-features#fields"
)
cc_features_sort_regex = re.compile(
r"https://api\.stacspec\.org/(.+)/ogcapi-features#sort"
)
cc_features_query_regex = re.compile(
r"https://api\.stacspec\.org/(.+)/ogcapi-features#query"
)
cc_features_filter_regex = re.compile(
r"https://api\.stacspec\.org/(.+)/ogcapi-features#filter"
)
cc_item_search_regex = re.compile(r"https://api\.stacspec\.org/(.+)/item-search")
cc_item_search_fields_regex = re.compile(
r"https://api\.stacspec\.org/(.+)/item-search#fields"
)
cc_item_search_sort_regex = re.compile(
r"https://api\.stacspec\.org/(.+)/item-search#sort"
)
cc_item_search_query_regex = re.compile(
r"https://api\.stacspec\.org/(.+)/item-search#query"
)
cc_item_search_filter_regex = re.compile(
r"https://api\.stacspec\.org/(.+)/item-search#filter"
)
geojson_mt = "application/geo+json"
geojson_charset_mt = "application/geo+json; charset=utf-8"
valid_datetimes = [
"1985-04-12T23:20:50.52Z",
"1996-12-19T16:39:57-00:00",
"1996-12-19T16:39:57+00:00",
"1996-12-19T16:39:57-08:00",
"1996-12-19T16:39:57+08:00",
"../1985-04-12T23:20:50.52Z",
"1985-04-12T23:20:50.52Z/..",
"/1985-04-12T23:20:50.52Z",
"1985-04-12T23:20:50.52Z/",
"1985-04-12T23:20:50.52Z/1986-04-12T23:20:50.52Z",
"1985-04-12T23:20:50.52+01:00/1986-04-12T23:20:50.52+01:00",
"1985-04-12T23:20:50.52-01:00/1986-04-12T23:20:50.52-01:00",
"1937-01-01T12:00:27.87+01:00",
"1985-04-12T23:20:50.52Z",
"1937-01-01T12:00:27.8710+01:00",
"1937-01-01T12:00:27.8+01:00",
"1937-01-01T12:00:27.8Z",
"2020-07-23T00:00:00.000+03:00",
"2020-07-23T00:00:00+03:00",
"1985-04-12t23:20:50.000z",
"2020-07-23T00:00:00Z",
"2020-07-23T00:00:00.0Z",
"2020-07-23T00:00:00.01Z",
"2020-07-23T00:00:00.012Z",
"2020-07-23T00:00:00.0123Z",
"2020-07-23T00:00:00.01234Z",
"2020-07-23T00:00:00.012345Z",
"2020-07-23T00:00:00.0123456Z",
"2020-07-23T00:00:00.01234567Z",
"2020-07-23T00:00:00.012345678Z",
]
invalid_datetimes = [
"/",
"../..",
"/..",
"../",
"/1984-04-12T23:20:50.52Z/1985-04-12T23:20:50.52Z",
"1984-04-12T23:20:50.52Z/1985-04-12T23:20:50.52Z/",
"/1984-04-12T23:20:50.52Z/1985-04-12T23:20:50.52Z/",
"1985-04-12", # date only
"1937-01-01T12:00:27.87+0100", # invalid TZ format, no sep :
"37-01-01T12:00:27.87Z", # invalid year, must be 4 digits
"1985-12-12T23:20:50.52", # no TZ
"21985-12-12T23:20:50.52Z", # year must be 4 digits
"1985-13-12T23:20:50.52Z", # month > 12
"1985-12-32T23:20:50.52Z", # day > 31
"1985-12-01T25:20:50.52Z", # hour > 24
"1985-12-01T00:60:50.52Z", # minute > 59
"1985-12-01T00:06:61.52Z", # second > 60
"1985-04-12T23:20:50.Z", # fractional sec . but no frac secs
"1985-04-12T23:20:50,Z", # fractional sec , but no frac secs
"1990-12-31T23:59:61Z", # second > 60 w/o fractional seconds
"1986-04-12T23:20:50.52Z/1985-04-12T23:20:50.52Z",
"1985-04-12T23:20:50,52Z", # comma as frac sec sep allowed in ISO8601 but not RFC3339
]
def supports_collections(conforms_to: List[str]) -> bool:
return supports(conforms_to, cc_collections_regex)
def supports_features(conforms_to: List[str]) -> bool:
return supports(conforms_to, cc_features_regex)
def supports(conforms_to: List[str], pattern: Pattern[str]) -> bool:
return any(pattern.fullmatch(x) for x in conforms_to)
def is_json_type(maybe_type: Optional[str]) -> bool:
return maybe_type is not None and (
maybe_type == "application/json" or maybe_type.startswith("application/json;")
)
def is_geojson_type(maybe_type: Optional[str]) -> bool:
return maybe_type is not None and (
maybe_type == "application/geo+json"
or maybe_type.startswith("application/geo+json;")
)
def get_catalog(data_dict: Dict[str, Any], r_session: Session) -> Catalog:
stac_io = StacIO.default()
if r_session.headers:
stac_io.headers = r_session.headers # type: ignore
stac_io.headers["Accept-Encoding"] = "*"
catalog = Catalog.from_dict(data_dict)
catalog._stac_io = stac_io
return catalog
# def is_json_or_geojson_type(maybe_type: Optional[str]) -> bool:
# return maybe_type and (is_json_type(maybe_type) or is_geojson_type(maybe_type))
def has_content_type(headers: Mapping[str, str], content_type: str) -> bool:
return headers.get("content-type", "").split(";")[0] == content_type
def has_json_content_type(headers: Mapping[str, str]) -> bool:
return is_json_type(headers.get("content-type"))
def has_geojson_content_type(headers: Mapping[str, str]) -> bool:
return is_geojson_type(headers.get("content-type"))
def stac_validate(
url: str,
body: Optional[Dict[str, Any]],
errors: Errors,
context: Context,
method: Method = Method.GET,
open_assets_urls: bool = True,
headers: Optional[dict] = None,
) -> None:
if not body:
errors += f"[{context}] : {method} {url} body was empty when running stac-validate and stac-check"
else:
if _type := body.get("type"):
try:
match _type:
case "Collection":
Collection.from_dict(body)
case "FeatureCollection":
ItemCollection.from_dict(body)
case "Feature":
Item.from_dict(body)
case _:
errors += f"[{context}] : {method} {url} object with type '{_type}' could not be hydrated with pystac"
except Exception as e:
errors += f"[{context}] : {method} {url} '{body.get('id')}' failed pystac hydration: {e}"
if _type in ["Collection", "Feature"]:
logger.debug(f"stac-validator validation: {url}")
if not (
stac_validator := StacValidate(
links=True,
assets=True,
assets_open_urls=open_assets_urls,
headers=headers or {},
)
).validate_dict(body):
errors += f"[{context}] : {method} {url} failed stac-validator validation: {stac_validator.message}"
else:
errors += f"[{context}] : {method} {url} missing 'type' attribute"
def stac_check(
url: str,
errors: Errors,
warnings: Warnings,
context: Context,
method: Method = Method.GET,
open_assets_urls: bool = True,
headers: Optional[dict] = None,
config_file: Optional[str] = None,
) -> None:
try:
logger.debug(f"stac-check validation: {url}")
linter = Linter(
url,
config_file=config_file,
assets_open_urls=open_assets_urls,
headers=headers or {},
)
if not linter.valid_stac:
errors += f"[{context}] : {method} {url} is not a valid STAC object: {linter.error_msg}"
if msgs := linter.best_practices_msg[1:]: # first msg is a header, so skip
warnings += f"[{context}] : {method} {url} has these stac-check recommendations: {','.join([x.strip() for x in msgs])}"
except KeyError as e:
# see https://github.com/stac-utils/stac-check/issues/104
errors += f"[{Context.CORE}] Error running stac-check, probably because an item doesn't have a bbox defined, which is okay!: {e} "
except Exception as e:
errors += f"[{Context.CORE}] Error while running stac-check: {e} "
def retrieve(
method: Method,
url: str,
errors: Errors,
context: Context,
r_session: Session,
params: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
status_code: int = 200,
body: Optional[Dict[str, Any]] = None,
additional: Optional[str] = "",
content_type: Optional[str] = None,
) -> Tuple[int, Optional[Dict[str, Any]], Optional[Mapping[str, str]]]:
request = Request(method.value, url, headers=headers, params=params, json=body)
resp = r_session.send(r_session.prepare_request(request))
# todo: handle connection exception, etc.
# todo: handle timeout
if resp.status_code != status_code:
errors += (
f"[{context}] : {method} {url} params={params} body={json.dumps(body) if body else ''}"
f" had unexpected status code {resp.status_code} instead of {status_code}: {additional}"
)
elif status_code < 400:
if not content_type:
if url.endswith("/search") or url.endswith("/items"):
if not has_content_type(resp.headers, geojson_mt):
errors += f"[{context}] : {method} {url} params={params} body={body} content-type header is {resp.headers.get('content-type')} instead of '{geojson_mt}'"
elif not has_content_type(resp.headers, "application/json"):
errors += f"[{context}] : {method} {url} params={params} body={body} content-type header is {resp.headers.get('content-type')} instead of 'application/json'"
elif content_type == "undefined":
if resp.headers.get("content-type"):
errors += f"[{context}] : {method} {url} params={params} body={body} content-type header is {resp.headers.get('content-type')} instead of undefined"
elif not has_content_type(resp.headers, content_type):
errors += f"[{context}] : {method} {url} params={params} body={body} content-type header is {resp.headers.get('content-type')} instead of '{content_type}'"
if has_json_content_type(resp.headers) or has_geojson_content_type(
resp.headers
):
try:
return resp.status_code, resp.json(), resp.headers
except json.decoder.JSONDecodeError:
errors += f"[{context}] : {method} {url} returned non-JSON value"
return resp.status_code, None, resp.headers
def validate_core_landing_page_body(
body: Dict[str, Any],
headers: Mapping[str, str],
errors: Errors,
warnings: Warnings,
conformance_classes: List[str],
collection: Optional[str],
geometry: Optional[str],
) -> bool:
if not has_json_content_type(headers):
errors += (
"CORE-1",
"[Core] : Landing Page (/) response Content-Type header is not application/json",
)
if not body.get("links"):
errors += ("CORE-3", "/ : 'links' field must be defined and non-empty.")
conforms_to = body.get("conformsTo", [])
if not conforms_to:
errors += (
"CORE-2",
"[Core] : Landing Page (/) 'conformsTo' field must be defined and non-empty."
"This field is required as of STAC 1.0.0",
)
else:
if any(
x
for x in conforms_to
if re.match(
r"^https://api\.stacspec\.org/v1\.0\.0.*/(core|item-search|ogcapi-features|collections)$",
x,
)
and not x.startswith(LATEST_STAC_API_FOUNDATION_VERSION)
):
warnings += f"STAC API Specification {LATEST_STAC_API_FOUNDATION_VERSION} is the latest version, but API advertises an older version or older versions."
if not supports(conforms_to, cc_core_regex):
errors += ("CORE-4", "/: STAC API - Core not contained in 'conformsTo'")
if "browseable" in conformance_classes and not any(
cc_browseable_regex.fullmatch(x) for x in conforms_to
):
errors += (
"CORE-5",
"/: Browseable configured for validation, but not contained in 'conformsTo'",
)
if "children" in conformance_classes and not any(
cc_children_regex.fullmatch(x) for x in conforms_to
):
errors += (
"CORE-6",
"/: Children configured for validation, but not contained in 'conformsTo'",
)
if "collections" in conformance_classes:
if not supports_collections(conforms_to):
errors += (
"CORE-7",
"/: Collections configured for validation, but not contained in 'conformsTo'",
)
if collection is None:
logger.fatal(
"Collections configured for validation, but `--collection` parameter not specified"
)
return False
if "features" in conformance_classes:
if not supports_features(conforms_to):
errors += (
"CORE-8",
"/: Features configured for validation, but not contained in 'conformsTo'",
)
if collection is None:
logger.fatal(
"Features configured for validation, but `--collection` parameter not specified"
)
return False
if "item-search" in conformance_classes:
if not supports(conforms_to, cc_item_search_regex):
errors += (
"CORE-9",
"/: Item Search configured for validation, but not contained in 'conformsTo'",
)
if collection is None:
logger.fatal(
"Item Search configured for validation, but `--collection` parameter not specified"
)
return False
if geometry is None:
logger.warning(
" Item Search configured for validation, but `--geometry` parameter not specified. Intersection tests will not be run"
)
if "children" in conformance_classes and not any(
cc_children_regex.fullmatch(x) for x in conforms_to
):
errors += (
"CORE-6",
"/: Children configured for validation, but not contained in 'conformsTo'",
)
return True
def validate_api(
root_url: str,
ccs_to_validate: List[str],
collection: Optional[str],
geometry: Optional[str],
auth_bearer_token: Optional[str],
auth_query_parameter: Optional[str],
fields_nested_property: Optional[str],
validate_pagination: bool,
query_config: QueryConfig,
transaction_collection: Optional[str],
headers: Optional[Dict[str, str]],
open_assets_urls: bool = True,
stac_check_config: Optional[str] = None,
) -> Tuple[Warnings, Errors]:
warnings = Warnings()
errors = Errors()
r_session = Session()
if auth_bearer_token:
r_session.headers.update({"Authorization": f"Bearer {auth_bearer_token}"})
if auth_query_parameter and (xs := auth_query_parameter.split("=", 1)):
r_session.params = {xs[0]: xs[1]}
if headers:
r_session.headers.update(headers)
_, landing_page_body, landing_page_headers = retrieve(
Method.GET, root_url, errors, Context.CORE, r_session
)
if not landing_page_body:
return warnings, errors
assert landing_page_body is not None
assert landing_page_headers is not None
if "core" in ccs_to_validate:
# fail fast if there are errors with conformance or links so far
if not validate_core_landing_page_body(
landing_page_body,
landing_page_headers,
errors,
warnings,
ccs_to_validate,
collection,
geometry,
):
return warnings, errors
logger.info("Validating STAC API - Core conformance class.")
validate_core(landing_page_body, errors, warnings, r_session)
if "browseable" in ccs_to_validate:
logger.info("Validating STAC API - Browseable conformance class.")
validate_browseable(landing_page_body, errors, warnings, r_session)
if "children" in ccs_to_validate:
logger.info("Validating STAC API - Children conformance class.")
validate_children(landing_page_body, errors, warnings, r_session)
if "collections" in ccs_to_validate:
logger.info("Validating STAC API - Collections conformance class.")
validate_collections(
landing_page_body,
collection,
errors,
warnings,
r_session,
open_assets_urls,
stac_check_config,
)
conforms_to = landing_page_body.get("conformsTo", [])
if "features" in ccs_to_validate:
logger.info("Validating STAC API - Features conformance class.")
validate_collections(
landing_page_body,
collection,
errors,
warnings,
r_session,
open_assets_urls,
stac_check_config,
)
validate_features(
landing_page_body,
conforms_to,
collection,
geometry,
warnings,
errors,
r_session,
validate_pagination,
open_assets_urls,
stac_check_config,
)
if "transaction" in ccs_to_validate:
logger.info(
"STAC API - Features - Transaction extension conformance class found."
)
validate_transaction(
context=Context.FEATURES_TXN,
landing_page_body=landing_page_body,
collection=collection,
errors=errors,
warnings=warnings,
r_session=r_session,
transaction_collection=transaction_collection,
)
if "features#fields" in ccs_to_validate:
logger.info("STAC API - Features - Fields extension conformance class found.")
logger.info("STAC API - Features - Fields extension is not yet supported.")
if "features#sort" in ccs_to_validate:
logger.info("STAC API - Features - Sort extension conformance class found.")
logger.info("STAC API - Features - Sort extension is not yet supported.")
if "features#query" in ccs_to_validate:
logger.info("STAC API - Features - Query extension conformance class found.")
logger.info("STAC API - Features - Query extension is not yet supported.")
if "features#filter" in ccs_to_validate:
logger.info("STAC API - Features - Filter Extension conformance class found.")
validate_features_filter(
root_body=landing_page_body,
collection=collection,
errors=errors,
r_session=r_session,
)
if "item-search" in ccs_to_validate:
logger.info("Validating STAC API - Item Search conformance class.")
validate_item_search(
root_url=root_url,
root_body=landing_page_body,
collection=collection, # type:ignore
conforms_to=conforms_to,
warnings=warnings,
errors=errors,
geometry=geometry,
conformance_classes=ccs_to_validate,
r_session=r_session,
validate_pagination=validate_pagination,
open_assets_urls=open_assets_urls,
)
if "item-search#fields" in ccs_to_validate:
logger.info(
"STAC API - Item Search - Fields extension conformance class found."
)
validate_fields(
context=Context.ITEM_SEARCH_FIELDS,
landing_page_body=landing_page_body,
collection=collection,
errors=errors,
warnings=warnings,
r_session=r_session,
fields_nested_property=fields_nested_property,
)
if "item-search#sort" in ccs_to_validate:
logger.info("STAC API - Item Search - Sort extension conformance class found.")
validate_sort(
context=Context.ITEM_SEARCH_SORT,
landing_page_body=landing_page_body,
collection=collection,
errors=errors,
warnings=warnings,
r_session=r_session,
query_config=query_config,
)
if "item-search#query" in ccs_to_validate:
logger.info("STAC API - Item Search - Query extension conformance class found.")
validate_query(
context=Context.ITEM_SEARCH_QUERY,
landing_page_body=landing_page_body,
collection=collection,
errors=errors,
warnings=warnings,
r_session=r_session,
query_config=query_config,
)
if "item-search#filter" in ccs_to_validate:
logger.info(
"STAC API - Item Search - Filter Extension conformance class found."
)
validate_item_search_filter(
root_url=root_url,
root_body=landing_page_body,
collection=collection,
errors=errors,
r_session=r_session,
)
if not errors:
try:
catalog = Client.open(root_url, headers=headers)
catalog.validate()
for child in catalog.get_children():
child.validate()
except STACValidationError as e:
errors += f"pystac validation error: {e}"
except Exception as e:
errors += f"Error with pystac: {e}"
return warnings, errors
def link_by_rel(
links: Optional[List[Dict[str, Any]]], rel: str
) -> Optional[Dict[str, Any]]:
if not links:
return None
else:
return next(iter(links_by_rel(links, rel)), None)
def links_by_rel(
links: Optional[List[Dict[str, Any]]], rel: str
) -> List[Dict[str, Any]]:
if not links:
return []
else:
return [link for link in links if link.get("rel") == rel]
def validate_core(
root_body: Dict[str, Any], errors: Errors, warnings: Warnings, r_session: Session
) -> None:
links = root_body.get("links")
if links is None:
errors += "/ : 'links' attribute missing"
if not (root := link_by_rel(links, "root")):
errors += "/ : Link[rel=root] must exist"
else:
if not is_json_type(root.get("type")):
errors += f"/ : Link[rel=root] type is not application/json, instead {root.get('type')}"
if not (_self := link_by_rel(links, "self")):
warnings += "/ : Link[rel=self] must exist"
else:
if not is_json_type(_self.get("type")):
errors += f"/ : Link[rel=self] type is not application/json, instead {_self.get('type')}"
if not (service_desc := link_by_rel(links, "service-desc")):
errors += "/ : Link[rel=service-desc] must exist"
else:
if not (service_desc_type := service_desc.get("type")):
errors += "/ : Link[rel=service-desc] must have a type defined"
else:
r_service_desc = r_session.send(
Request(
"GET", service_desc["href"], headers={"Accept": service_desc_type}
).prepare()
)
if not r_service_desc.status_code == 200:
errors += "/ : Link[service-desc] must return 200"
else:
content_type = r_service_desc.headers.get("content-type", "")
if content_type in ["application/yaml", "application/vnd.oai.openapi"]:
pass
# openapi_spec = r_service_desc.json()
# todo: verify limits exist and test them
elif content_type in [
"application/json",
"application/vnd.oai.openapi+json",
"application/vnd.oai.openapi+json;version=3.0",
"application/vnd.oai.openapi+json;version=3.1",
]:
yaml.safe_load(r_service_desc.text)
if (
(ct := r_service_desc.headers.get("content-type", ""))
== service_desc_type
) or (
(";" in ct or ";" in service_desc_type)
and (ct.split(";", 1)[0] == service_desc_type.split(";", 1)[0])
):
pass
else:
errors += f"service-desc ({service_desc}): media type used in Accept header must get response with same Content-Type header: used '{service_desc_type}', got '{ct}'"
if not (service_doc := link_by_rel(links, "service-doc")):
warnings += "/ : Link[rel=service-doc] should exist"
else:
if service_doc.get("type") != "text/html":
errors += "service-doc type is not text/html"
retrieve(
Method.GET,
service_doc["href"],
errors,
Context.CORE,
content_type="text/html",
r_session=r_session,
)
# this validates, among other things, that the child and item link relations reference
# valid STAC Catalogs, Collections, and/or Items
try:
catalog = get_catalog(root_body, r_session)
list(take(1000, catalog.get_all_items()))
except pystac.errors.STACTypeError as e:
errors += (
f"[{Context.CORE}] Error while traversing Catalog child/item links to find Items: {e} "
"This can be reproduced with 'list(pystac.Catalog.from_file(root_url).get_all_items())'"
)
except UnicodeEncodeError as e:
# see https://github.com/jjrom/resto/issues/356#issuecomment-1443818163
errors += f"[{Context.CORE}] Error while traversing Catalog, a non-ascii character is encoded incorrectly somewhere: {e} "
except Exception as e:
errors += f"[{Context.CORE}] Error while traversing Catalog with pystac: {e} "
def validate_browseable(
root_body: Dict[str, Any],
errors: Errors,
warnings: Warnings,
r_session: Session,
) -> None:
# child or item links exist in the root
child_links = links_by_rel(root_body.get("links"), "child")
item_links = links_by_rel(root_body.get("links"), "item")
if not (child_links or item_links):
errors += f"[{Context.BROWSEABLE}] /: Root catalog does not contain any child or item link relations"
# check that at least a few of the items that can be reached from child/item link relations
# can be found through search
try:
catalog = get_catalog(root_body, r_session)
for item in take(10, catalog.get_all_items()):
if link := link_by_rel(root_body.get("links"), "search"):
_, body, _ = retrieve(
Method.GET,
link["href"],
errors,
Context.BROWSEABLE,
params={"ids": item.id, "collections": item.collection_id},
r_session=r_session,
)
if body and len(body.get("features", [])) != 1:
errors += f"[{Context.BROWSEABLE}] /: Link[rel=children] must href /children"
else:
errors += (
f"[{Context.BROWSEABLE}] /: Link[rel=search] could not be found"
)
except pystac.errors.STACTypeError as e:
errors += (
f"[{Context.BROWSEABLE}] Error while traversing Catalog child/item links to find Items: {e}. "
"This can be reproduced with 'pystac.Catalog.from_file(root_url).get_all_items()'"
)
def validate_children(
root_body: Dict[str, Any],
errors: Errors,
warnings: Warnings,
r_session: Session,
) -> None:
children_link = link_by_rel(root_body.get("links"), "children")
if (
not children_link
or not children_link.get("href", "").endswith("/children")
or not is_json_type(children_link.get("type"))
):
errors += f"[{Context.CHILDREN}] /: Link[rel=children] must href /children"
return
if not (children_href := children_link.get("href")):
errors += f"[{Context.CHILDREN}] /: Link[rel=children] missing href"
else:
_, children_body, resp_headers = retrieve(
Method.GET,
children_href,
errors,
Context.CHILDREN,
r_session=r_session,
)
if not children_body:
errors += f"[{Context.CHILDREN}] /children body was empty"
return
if not resp_headers or not has_json_content_type(resp_headers):
errors += f"[{Context.CHILDREN}] /children content-type header was not application/json"
if not (self_link := link_by_rel(children_body.get("links", []), "self")):
errors += f"[{Context.CHILDREN}] /children does not have self link"
elif children_link.get("href") != self_link.get("href"):
errors += (
f"[{Context.CHILDREN}] /children self link does not match requested url"
)
if not link_by_rel(children_body.get("links", []), "root"):
errors += f"[{Context.CHILDREN}] /children does not have root link"
# each child link in Landing Page must have an entry in children
child_links = links_by_rel(root_body.get("links"), "child")
child_link_bodies = []
for child_link in child_links:
if child_href := child_link.get("href"):
_, child_body, child_resp_headers = retrieve(
Method.GET,
child_href,
errors,
Context.CHILDREN,
r_session=r_session,
)
child_link_bodies.append(child_body)
else:
errors += f"[{Context.CHILDREN}] child link {json.dumps(child_link)} missing href field"
child_links_vs_children_diff = DeepDiff(
child_link_bodies, children_body.get("children"), ignore_order=True
)
if iterable_item_removed := child_links_vs_children_diff.get(
"iterable_item_removed"
):
errors += (
f"[{Context.CHILDREN}] /: child links contained these objects that /children does not: "
f"{json.dumps(iterable_item_removed)}"
)
if iterable_item_added := child_links_vs_children_diff.get(
"iterable_item_added"
):
errors += (
f"[{Context.CHILDREN}] /: child links missing these objects that /children contains: "
f"{json.dumps(iterable_item_added)}"
)