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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Strict public CMR collection retrieval and blind-boundary construction."""

from __future__ import annotations

import copy
import hashlib
import json
import logging
import time
from collections.abc import Callable
from contextlib import closing
from datetime import UTC, datetime
from typing import Any
from urllib.parse import parse_qsl, urljoin, urlsplit

import httpx
from pydantic import ValidationError

from gcmd_classifier.config import DatasetCMRSettings
from gcmd_classifier.datasets.errors import (
    CMRError,
    CMRResponseError,
    CMRRetrievalError,
    CMRURLValidationError,
)
from gcmd_classifier.datasets.models import (
    BlindCollectionView,
    CMRPreclassificationFailure,
    CMRRedirectProvenance,
    CMRRetrievedSource,
    DatasetErrorRecord,
    DatasetIdentity,
    ResolvedCMRCollection,
    SealedExpertKeywordPayload,
)
from gcmd_classifier.logging_config import get_logger, log_event

_REDIRECT_STATUSES = {301, 302, 303, 307, 308}
_APPROVED_RESPONSE_HEADERS = {
    "content-type",
    "content-length",
    "etag",
    "last-modified",
    "cmr-request-id",
}
_AUTH_QUERY_NAMES = {
    "access_token",
    "api_key",
    "apikey",
    "auth",
    "authorization",
    "bearer",
    "client_secret",
    "credential",
    "jwt",
    "password",
    "signature",
    "sig",
    "token",
}


class ValidatedCMRURL:
    """Validated URL and exact decoded Native ID."""

    __slots__ = ("native_id", "url")

    def __init__(self, *, url: str, native_id: str) -> None:
        self.url = url
        self.native_id = native_id


def validate_cmr_url(
    url: str,
    settings: DatasetCMRSettings | None = None,
) -> ValidatedCMRURL:
    """Validate a CMR collection-search URL without normalizing it."""
    policy = settings or DatasetCMRSettings()
    if not isinstance(url, str) or not url:
        raise CMRURLValidationError("CMR_URL_INVALID", "CMR URL must be a non-empty string.")

    try:
        parsed = urlsplit(url)
        port = parsed.port
    except ValueError as exc:
        raise CMRURLValidationError("CMR_URL_INVALID", "CMR URL is malformed.") from exc

    if parsed.scheme != "https":
        raise CMRURLValidationError("CMR_URL_SCHEME", "CMR URL must use HTTPS.")
    if parsed.hostname != policy.host:
        raise CMRURLValidationError("CMR_URL_HOST", "CMR URL host is not approved.")
    if port not in (None, 443):
        raise CMRURLValidationError("CMR_URL_PORT", "CMR URL must use the default HTTPS port.")
    if parsed.username is not None or parsed.password is not None:
        raise CMRURLValidationError(
            "CMR_URL_USERINFO", "CMR URL must not contain user information."
        )
    if parsed.path != policy.collection_path:
        raise CMRURLValidationError("CMR_URL_PATH", "CMR URL path is not approved.")
    if parsed.fragment:
        raise CMRURLValidationError("CMR_URL_FRAGMENT", "CMR URL must not contain a fragment.")

    try:
        query_items = parse_qsl(parsed.query, keep_blank_values=True, strict_parsing=False)
    except ValueError as exc:
        raise CMRURLValidationError("CMR_URL_QUERY", "CMR URL query is malformed.") from exc

    for name, _ in query_items:
        normalized_name = name.strip().lower().replace("-", "_")
        if normalized_name in _AUTH_QUERY_NAMES or any(
            marker in normalized_name
            for marker in ("token", "password", "credential", "authorization")
        ):
            raise CMRURLValidationError(
                "CMR_URL_AUTH_QUERY",
                "CMR URL contains a prohibited authentication-related query parameter.",
            )

    native_values = [value for name, value in query_items if name == "native_id"]
    if len(native_values) != 1:
        raise CMRURLValidationError(
            "CMR_URL_NATIVE_ID_COUNT",
            "CMR URL must contain exactly one native_id query parameter.",
        )
    if native_values[0] == "":
        raise CMRURLValidationError(
            "CMR_URL_NATIVE_ID_EMPTY",
            "CMR URL native_id query value must not be empty.",
        )
    return ValidatedCMRURL(url=url, native_id=native_values[0])


def _safe_response_metadata(headers: httpx.Headers) -> dict[str, str]:
    return {
        name.lower(): value
        for name, value in headers.items()
        if name.lower() in _APPROVED_RESPONSE_HEADERS
    }


def _is_json_media_type(value: str | None) -> bool:
    if not value:
        return False
    media_type = value.split(";", 1)[0].strip().lower()
    return media_type == "application/json" or (
        media_type.startswith("application/") and media_type.endswith("+json")
    )


def _looks_like_login_response(content_type: str | None, body: bytes) -> bool:
    sample = body[:8192].lower()
    media_type = (content_type or "").lower()
    if "text/html" not in media_type and not sample.lstrip().startswith(b"<"):
        return False
    return any(
        marker in sample
        for marker in (
            b"<form",
            b'type="password"',
            b"type='password'",
            b"sign in",
            b"log in",
            b"login",
        )
    )


def _raise_retrieval_error(exc: httpx.HTTPError) -> None:
    if isinstance(exc, httpx.TimeoutException):
        raise CMRRetrievalError("CMR_TIMEOUT", "CMR request timed out.") from exc
    if isinstance(exc, httpx.TransportError):
        raise CMRRetrievalError(
            "CMR_TRANSPORT_ERROR",
            "CMR connection, TLS, or transport failed.",
        ) from exc
    raise CMRRetrievalError("CMR_HTTP_ERROR", "CMR request failed.") from exc


def retrieve_cmr_source(
    url: str,
    *,
    client: httpx.Client,
    settings: DatasetCMRSettings | None = None,
    utc_now: Callable[[], datetime] | None = None,
    monotonic: Callable[[], float] | None = None,
) -> tuple[ValidatedCMRURL, CMRRetrievedSource]:
    """Retrieve exact CMR source bytes using injected transport and manual redirects."""
    policy = settings or DatasetCMRSettings()
    validated = validate_cmr_url(url, policy)
    now = utc_now or (lambda: datetime.now(UTC))
    elapsed_clock = monotonic or time.monotonic
    started = elapsed_clock()
    current_url = validated.url
    visited = {current_url}
    redirects: list[CMRRedirectProvenance] = []
    timeout = httpx.Timeout(
        connect=policy.connect_timeout_seconds,
        read=policy.read_timeout_seconds,
        write=policy.read_timeout_seconds,
        pool=policy.connect_timeout_seconds,
    )
    headers = {
        "Accept": "application/json",
        "Accept-Encoding": "identity",
        "Client-Id": policy.client_id,
    }

    while True:
        if elapsed_clock() - started > policy.operation_timeout_seconds:
            raise CMRRetrievalError(
                "CMR_OPERATION_TIMEOUT",
                "CMR retrieval exceeded the overall operation limit.",
            )
        try:
            request = client.build_request(
                "GET",
                current_url,
                headers=headers,
                timeout=timeout,
            )
            if "authorization" in request.headers or "cookie" in request.headers:
                raise CMRRetrievalError(
                    "CMR_CLIENT_STATE",
                    "CMR requests must not include authorization or cookie state.",
                )
            with closing(
                client.send(
                    request,
                    stream=True,
                    follow_redirects=False,
                    auth=None,
                )
            ) as response:
                status = response.status_code
                if status in _REDIRECT_STATUSES:
                    location = response.headers.get("location")
                    if not location:
                        raise CMRRetrievalError(
                            "CMR_REDIRECT_LOCATION",
                            "CMR redirect did not provide a Location header.",
                        )
                    target = urljoin(current_url, location)
                    target_validated = validate_cmr_url(target, policy)
                    if target_validated.native_id != validated.native_id:
                        raise CMRURLValidationError(
                            "CMR_REDIRECT_NATIVE_ID",
                            "CMR redirect changed the submitted Native ID.",
                        )
                    if target in visited:
                        raise CMRRetrievalError(
                            "CMR_REDIRECT_LOOP",
                            "CMR redirect loop was detected.",
                        )
                    if len(redirects) >= policy.max_redirects:
                        raise CMRRetrievalError(
                            "CMR_REDIRECT_LIMIT",
                            "CMR redirect limit was exceeded.",
                        )
                    redirects.append(
                        CMRRedirectProvenance(
                            status_code=status,
                            source_url=current_url,
                            target_url=target,
                        )
                    )
                    visited.add(target)
                    current_url = target
                    continue
                if 300 <= status < 400:
                    raise CMRRetrievalError(
                        "CMR_REDIRECT_UNSUPPORTED",
                        "CMR returned an unsupported redirect status.",
                    )
                if status in {401, 403}:
                    raise CMRRetrievalError(
                        "CMR_NOT_PUBLIC",
                        "CMR resource is not publicly accessible.",
                    )
                if status < 200 or status >= 300:
                    raise CMRRetrievalError(
                        "CMR_HTTP_STATUS",
                        f"CMR returned HTTP status {status}.",
                    )

                content_length = response.headers.get("content-length")
                if content_length is not None:
                    try:
                        declared_length = int(content_length)
                    except ValueError as exc:
                        raise CMRRetrievalError(
                            "CMR_CONTENT_LENGTH",
                            "CMR response Content-Length is invalid.",
                        ) from exc
                    if declared_length > policy.max_response_bytes:
                        raise CMRRetrievalError(
                            "CMR_RESPONSE_TOO_LARGE",
                            "CMR response exceeds the configured size limit.",
                        )

                content_encoding = response.headers.get("content-encoding")
                if content_encoding and content_encoding.lower() != "identity":
                    raise CMRRetrievalError(
                        "CMR_CONTENT_ENCODING",
                        "CMR response used an unsupported content encoding.",
                    )
                chunks: list[bytes] = []
                byte_count = 0
                response_chunks = (
                    (response.content,) if response.is_stream_consumed else response.iter_raw()
                )
                for chunk in response_chunks:
                    if elapsed_clock() - started > policy.operation_timeout_seconds:
                        raise CMRRetrievalError(
                            "CMR_OPERATION_TIMEOUT",
                            "CMR retrieval exceeded the overall operation limit.",
                        )
                    byte_count += len(chunk)
                    if byte_count > policy.max_response_bytes:
                        raise CMRRetrievalError(
                            "CMR_RESPONSE_TOO_LARGE",
                            "CMR response exceeds the configured size limit.",
                        )
                    chunks.append(chunk)
                body = b"".join(chunks)
                content_type = response.headers.get("content-type")
                if _looks_like_login_response(content_type, body):
                    raise CMRRetrievalError(
                        "CMR_LOGIN_RESPONSE",
                        "CMR returned an authentication or login response.",
                    )
                if not _is_json_media_type(content_type):
                    raise CMRRetrievalError(
                        "CMR_MEDIA_TYPE",
                        "CMR response does not use a supported JSON media type.",
                    )
                try:
                    source_text = body.decode("utf-8")
                except UnicodeDecodeError as exc:
                    raise CMRResponseError(
                        "CMR_TEXT_DECODE",
                        "CMR JSON response is not valid UTF-8.",
                    ) from exc
                try:
                    parsed = json.loads(source_text)
                except json.JSONDecodeError as exc:
                    raise CMRResponseError(
                        "CMR_JSON_INVALID",
                        "CMR response contains malformed JSON.",
                    ) from exc
                if not isinstance(parsed, dict):
                    raise CMRResponseError(
                        "CMR_JSON_ROOT",
                        "CMR response root must be a JSON object.",
                    )
                source = CMRRetrievedSource(
                    submitted_url=url,
                    final_url=current_url,
                    redirect_history=tuple(redirects),
                    retrieved_at=now().astimezone(UTC).isoformat().replace("+00:00", "Z"),
                    status_code=status,
                    response_metadata=_safe_response_metadata(response.headers),
                    response_bytes=body,
                    source_text=source_text,
                    sha256=hashlib.sha256(body).hexdigest(),
                    parsed_json=copy.deepcopy(parsed),
                )
                return validated, source
        except CMRError:
            raise
        except httpx.HTTPError as exc:
            _raise_retrieval_error(exc)


def _required_non_empty_string(container: dict[str, Any], key: str, label: str) -> str:
    value = container.get(key)
    if not isinstance(value, str) or not value:
        raise CMRResponseError(
            "CMR_REQUIRED_FIELD",
            f"CMR collection requires a non-empty {label}.",
        )
    return value


def _canonical_payload_hash(value: Any) -> str:
    serialized = json.dumps(
        value,
        ensure_ascii=False,
        sort_keys=True,
        separators=(",", ":"),
    ).encode("utf-8")
    return hashlib.sha256(serialized).hexdigest()


def resolve_cmr_collection(
    validated_url: ValidatedCMRURL,
    source: CMRRetrievedSource,
) -> ResolvedCMRCollection:
    """Resolve one collection and construct separate blind and sealed objects."""
    root = source.parsed_json
    hits = root.get("hits")
    items = root.get("items")
    if isinstance(hits, bool) or not isinstance(hits, int) or hits < 0:
        raise CMRResponseError("CMR_HITS_INVALID", "CMR hits must be a non-negative integer.")
    if not isinstance(items, list):
        raise CMRResponseError("CMR_ITEMS_INVALID", "CMR items must be an array.")
    if hits != len(items):
        raise CMRResponseError(
            "CMR_CARDINALITY_MISMATCH",
            "CMR hits and item cardinality do not agree.",
        )
    if len(items) != 1:
        raise CMRResponseError(
            "CMR_CARDINALITY",
            "CMR response must contain exactly one collection item.",
        )
    item = items[0]
    if not isinstance(item, dict):
        raise CMRResponseError("CMR_ITEM_INVALID", "CMR collection item must be an object.")
    meta = item.get("meta")
    umm = item.get("umm")
    if not isinstance(meta, dict):
        raise CMRResponseError("CMR_META_INVALID", "CMR collection meta must be an object.")
    if not isinstance(umm, dict):
        raise CMRResponseError("CMR_UMM_INVALID", "CMR collection umm must be an object.")

    concept_id = _required_non_empty_string(meta, "concept-id", "Concept ID")
    returned_native_id = _required_non_empty_string(meta, "native-id", "Native ID")
    short_name = _required_non_empty_string(umm, "ShortName", "ShortName")
    version = _required_non_empty_string(umm, "Version", "Version")
    revision_id = meta.get("revision-id")
    if isinstance(revision_id, bool) or not isinstance(revision_id, int) or revision_id < 1:
        raise CMRResponseError(
            "CMR_REVISION_ID_INVALID",
            "CMR revision ID must be a positive integer.",
        )

    derived_native_id = f"{short_name}_{version}"
    if validated_url.native_id != returned_native_id or returned_native_id != derived_native_id:
        raise CMRResponseError(
            "CMR_NATIVE_ID_MISMATCH",
            "Submitted, returned, and derived Native IDs do not match exactly.",
        )

    related_urls = umm.get("RelatedUrls", [])
    if not isinstance(related_urls, list) or any(
        not isinstance(entry, dict) for entry in related_urls
    ):
        raise CMRResponseError(
            "CMR_RELATED_URLS_INVALID",
            "CMR RelatedUrls must be an array of objects when present.",
        )
    expert_keywords = umm.get("ScienceKeywords", [])
    if not isinstance(expert_keywords, list) or any(
        not isinstance(entry, dict) for entry in expert_keywords
    ):
        raise CMRResponseError(
            "CMR_SCIENCE_KEYWORDS_INVALID",
            "CMR ScienceKeywords must be an array of objects when present.",
        )

    try:
        identity = DatasetIdentity(
            concept_id=concept_id,
            native_id=returned_native_id,
            short_name=short_name,
            version=version,
            cmr_revision_id=revision_id,
        )
    except ValidationError as exc:
        raise CMRResponseError(
            "CMR_IDENTITY_INVALID",
            "CMR collection identity is invalid.",
        ) from exc

    blind_material = {
        "identity": identity.model_dump(mode="json"),
        "derived_native_id": derived_native_id,
        "entry_title": umm.get("EntryTitle") if isinstance(umm.get("EntryTitle"), str) else None,
        "summary": umm.get("Abstract") if isinstance(umm.get("Abstract"), str) else None,
        "related_urls": copy.deepcopy(related_urls),
        "expert_keywords_excluded": True,
    }
    blind_view = BlindCollectionView(
        **blind_material,
        blind_view_sha256=_canonical_payload_hash(blind_material),
    )
    sealed_keywords = copy.deepcopy(expert_keywords)
    sealed_material = {
        "dataset_key": concept_id,
        "source_path": "umm.ScienceKeywords",
        "science_keywords": sealed_keywords,
    }
    sealed_payload = SealedExpertKeywordPayload(
        dataset_key=concept_id,
        science_keywords=tuple(sealed_keywords),
        payload_sha256=_canonical_payload_hash(sealed_material),
    )
    return ResolvedCMRCollection(
        dataset_key=concept_id,
        submitted_native_id=validated_url.native_id,
        returned_native_id=returned_native_id,
        derived_native_id=derived_native_id,
        identity=identity,
        source=source,
        source_item=copy.deepcopy(item),
        blind_view=blind_view,
        sealed_expert_keywords=sealed_payload,
    )


def retrieve_and_resolve_cmr_collection(
    url: str,
    *,
    client: httpx.Client,
    settings: DatasetCMRSettings | None = None,
    utc_now: Callable[[], datetime] | None = None,
    monotonic: Callable[[], float] | None = None,
    logger: logging.Logger | None = None,
) -> ResolvedCMRCollection:
    """Retrieve and resolve one collection while logging only safe metadata."""
    active_logger = logger or get_logger("gcmd_classifier.datasets.cmr")
    try:
        validated, source = retrieve_cmr_source(
            url,
            client=client,
            settings=settings,
            utc_now=utc_now,
            monotonic=monotonic,
        )
        result = resolve_cmr_collection(validated, source)
    except CMRError as exc:
        log_event(
            active_logger,
            "cmr_failed",
            stage="source",
            error_code=exc.code,
        )
        raise
    log_event(
        active_logger,
        "cmr_resolved",
        stage="source",
        concept_id=result.dataset_key,
        native_id=result.identity.native_id,
        revision_id=result.identity.cmr_revision_id,
        source_sha256=result.source.sha256,
        status_code=result.source.status_code,
    )
    return result


def preclassification_failure(error: CMRError) -> CMRPreclassificationFailure:
    """Represent a CMR failure with explicit zero-inference semantics."""
    return CMRPreclassificationFailure(
        error=DatasetErrorRecord(
            code=error.code,
            message=str(error),
            stage="source",
        )
    )