File size: 7,975 Bytes
a490f0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Validate a DATA LAB source manifest without external dependencies."""

from __future__ import annotations

import argparse
import json
import re
from datetime import datetime
from pathlib import Path, PurePosixPath
from typing import Any
from urllib.parse import urlparse

SHA256_RE = re.compile(r"^[a-f0-9]{64}$")
SOURCE_ID_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*$")
DECISIONS = {"proposed", "approved", "rejected", "withdrawn"}
PERMISSIONS = {"pending", "approved", "rejected"}
REDISTRIBUTION = {"allowed", "restricted", "prohibited", "unknown"}
PRIVACY_STATES = {"pending", "passed", "failed"}


def _is_https(value: Any) -> bool:
    if not isinstance(value, str):
        return False
    parsed = urlparse(value)
    return parsed.scheme == "https" and bool(parsed.netloc)


def _is_utc_timestamp(value: Any) -> bool:
    if not isinstance(value, str) or not value.endswith("Z"):
        return False
    try:
        datetime.fromisoformat(value.removesuffix("Z") + "+00:00")
    except ValueError:
        return False
    return True


def _is_safe_relative_path(value: Any) -> bool:
    if not isinstance(value, str) or not value.strip() or "\\" in value:
        return False
    path = PurePosixPath(value)
    return not path.is_absolute() and ".." not in path.parts and "." not in path.parts


def validate_manifest(data: Any) -> list[str]:
    """Return human-readable validation errors; an empty list means valid."""
    errors: list[str] = []
    if not isinstance(data, dict):
        return ["manifest root must be a JSON object"]

    if data.get("schema_version") != "1.0":
        errors.append("schema_version must be '1.0'")
    if not isinstance(data.get("dataset_id"), str) or not data["dataset_id"].strip():
        errors.append("dataset_id must be a non-empty string")

    decision = data.get("decision")
    if not isinstance(decision, dict):
        errors.append("decision must be an object")
        decision = {}
    status = decision.get("status")
    if status not in DECISIONS:
        errors.append(f"decision.status must be one of {sorted(DECISIONS)}")
    if not isinstance(decision.get("notes"), list) or not all(
        isinstance(note, str) for note in decision.get("notes", [])
    ):
        errors.append("decision.notes must be an array of strings")
    if status == "approved":
        if not isinstance(decision.get("reviewed_by"), str) or not decision["reviewed_by"].strip():
            errors.append("approved manifest requires decision.reviewed_by")
        if not _is_utc_timestamp(decision.get("reviewed_at")):
            errors.append("approved manifest requires a UTC decision.reviewed_at ending in Z")

    sources = data.get("sources")
    if not isinstance(sources, list):
        errors.append("sources must be an array")
        return errors

    seen_ids: set[str] = set()
    for index, source in enumerate(sources):
        prefix = f"sources[{index}]"
        if not isinstance(source, dict):
            errors.append(f"{prefix} must be an object")
            continue

        source_id = source.get("source_id")
        if not isinstance(source_id, str) or not SOURCE_ID_RE.fullmatch(source_id):
            errors.append(f"{prefix}.source_id must use lowercase letters, digits, dot, underscore, or hyphen")
        elif source_id in seen_ids:
            errors.append(f"{prefix}.source_id is duplicated: {source_id}")
        else:
            seen_ids.add(source_id)

        for field in ("title", "publisher", "version"):
            if not isinstance(source.get(field), str) or not source[field].strip():
                errors.append(f"{prefix}.{field} must be a non-empty string")
        if not _is_https(source.get("canonical_url")):
            errors.append(f"{prefix}.canonical_url must be an HTTPS URL")
        if not _is_utc_timestamp(source.get("retrieved_at")):
            errors.append(f"{prefix}.retrieved_at must be a UTC timestamp ending in Z")
        if not _is_safe_relative_path(source.get("content_path")):
            errors.append(f"{prefix}.content_path must be a safe POSIX-style relative path")
        if not isinstance(source.get("sha256"), str) or not SHA256_RE.fullmatch(source["sha256"]):
            errors.append(f"{prefix}.sha256 must be a lowercase 64-character SHA-256 digest")

        licence = source.get("license")
        if not isinstance(licence, dict):
            errors.append(f"{prefix}.license must be an object")
            licence = {}
        if not isinstance(licence.get("identifier"), str) or not licence["identifier"].strip():
            errors.append(f"{prefix}.license.identifier must be non-empty")
        if not _is_https(licence.get("url")):
            errors.append(f"{prefix}.license.url must be an HTTPS URL")
        if licence.get("permission_status") not in PERMISSIONS:
            errors.append(f"{prefix}.license.permission_status is invalid")
        if licence.get("redistribution") not in REDISTRIBUTION:
            errors.append(f"{prefix}.license.redistribution is invalid")

        privacy = source.get("privacy")
        if not isinstance(privacy, dict):
            errors.append(f"{prefix}.privacy must be an object")
            privacy = {}
        if privacy.get("review_status") not in PRIVACY_STATES:
            errors.append(f"{prefix}.privacy.review_status is invalid")
        if privacy.get("contains_personal_data") not in (True, False, None):
            errors.append(f"{prefix}.privacy.contains_personal_data must be true, false, or null")
        if not isinstance(privacy.get("notes"), list) or not all(
            isinstance(note, str) for note in privacy.get("notes", [])
        ):
            errors.append(f"{prefix}.privacy.notes must be an array of strings")

        use = source.get("use")
        if not isinstance(use, dict):
            errors.append(f"{prefix}.use must be an object")
            use = {}
        if not isinstance(use.get("purpose"), str) or not use["purpose"].strip():
            errors.append(f"{prefix}.use.purpose must be non-empty")
        if not isinstance(use.get("allowed"), bool):
            errors.append(f"{prefix}.use.allowed must be a boolean")
        if not isinstance(use.get("restrictions"), list) or not all(
            isinstance(item, str) for item in use.get("restrictions", [])
        ):
            errors.append(f"{prefix}.use.restrictions must be an array of strings")

        if status == "approved":
            if licence.get("permission_status") != "approved":
                errors.append(f"{prefix} is not approved by the licensing review")
            if privacy.get("review_status") != "passed":
                errors.append(f"{prefix} has not passed privacy review")
            if not isinstance(privacy.get("consent_or_lawful_basis"), str) or not privacy[
                "consent_or_lawful_basis"
            ].strip():
                errors.append(f"{prefix} lacks consent or another documented lawful basis")
            if use.get("allowed") is not True:
                errors.append(f"{prefix}.use.allowed must be true for an approved manifest")

    return errors


def load_manifest(path: Path) -> dict[str, Any]:
    data = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(data, dict):
        raise ValueError("manifest root must be an object")
    return data


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("manifest", type=Path)
    args = parser.parse_args()

    try:
        data = load_manifest(args.manifest)
    except (OSError, json.JSONDecodeError, ValueError) as exc:
        print(f"INVALID: {exc}")
        return 2

    errors = validate_manifest(data)
    if errors:
        print("INVALID")
        for error in errors:
            print(f"- {error}")
        return 1

    print(f"VALID: {data['dataset_id']} ({data['decision']['status']})")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())