|
| 1 | +################################################################################ |
| 2 | +# Copyright IBM Corporation 2026 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +################################################################################ |
| 16 | + |
| 17 | +"""Validated raw application identity and canonical URI ownership.""" |
| 18 | + |
| 19 | +import json |
| 20 | +import unicodedata |
| 21 | +from collections.abc import Iterable, Mapping |
| 22 | +from dataclasses import dataclass |
| 23 | +from pathlib import Path |
| 24 | +from urllib.parse import quote |
| 25 | + |
| 26 | +from cldk.utils.exceptions import CodeanalyzerExecutionException |
| 27 | + |
| 28 | + |
| 29 | +@dataclass(frozen=True) |
| 30 | +class ApplicationIdentity: |
| 31 | + namespace: str |
| 32 | + application_name: str |
| 33 | + application_id: str |
| 34 | + |
| 35 | + |
| 36 | +def _segment(value: str) -> str: |
| 37 | + if not isinstance(value, str) or not value.strip() or value in {".", ".."} or any(c in "/\\" or unicodedata.category(c) in {"Cc", "Cs"} for c in value): |
| 38 | + raise ValueError("identity names must be nonempty raw names without separators or control characters") |
| 39 | + return quote(value, safe="-._~", encoding="utf-8", errors="strict") |
| 40 | + |
| 41 | + |
| 42 | +def resolve_identity(application_name: str | None, namespace: str | None, *, project_root: Path | None = None) -> ApplicationIdentity: |
| 43 | + if application_name is None: |
| 44 | + if project_root is None: |
| 45 | + raise CodeanalyzerExecutionException("application_name is required to scope queries to an application.") |
| 46 | + application_name = Path(project_root).expanduser().resolve().name |
| 47 | + namespace = application_name if namespace is None else namespace |
| 48 | + return ApplicationIdentity(namespace, application_name, f"can://{_segment(namespace)}/{_segment(application_name)}") |
| 49 | + |
| 50 | + |
| 51 | +def validate_identity(payload, identity: ApplicationIdentity, *, envelope: bool = True): |
| 52 | + """Reject legacy or foreign persisted data without synthesizing metadata.""" |
| 53 | + if envelope and hasattr(payload, "application"): |
| 54 | + app_model = payload.application |
| 55 | + if hasattr(app_model, "identity_version") and "identity_version" not in app_model.model_fields_set: |
| 56 | + raise CodeanalyzerExecutionException("Analysis identity marker is missing from the application.") |
| 57 | + raw = ( |
| 58 | + payload.model_dump(include={"identity_version": True, "language": True, "application": {"identity_version", "id", "application_name", "identity_namespace"}}) |
| 59 | + if envelope and hasattr(payload, "model_dump") |
| 60 | + else payload |
| 61 | + ) |
| 62 | + if not isinstance(raw, dict): |
| 63 | + raise CodeanalyzerExecutionException("Analysis identity metadata must be an object.") |
| 64 | + app = raw.get("application", {}) if envelope else raw |
| 65 | + if not isinstance(app, dict): |
| 66 | + raise CodeanalyzerExecutionException("Application identity metadata must be an object.") |
| 67 | + if envelope and raw.get("language") != "java" and (type(app.get("identity_version")) is not int or app.get("identity_version") != 2): |
| 68 | + raise CodeanalyzerExecutionException("Analysis identity marker is missing from the application.") |
| 69 | + if ( |
| 70 | + type(raw.get("identity_version")) is not int |
| 71 | + or raw.get("identity_version") != 2 |
| 72 | + or app.get("application_name") != identity.application_name |
| 73 | + or app.get("identity_namespace") != identity.namespace |
| 74 | + or app.get("id") != identity.application_id |
| 75 | + ): |
| 76 | + raise CodeanalyzerExecutionException("Analysis identity metadata is missing, incompatible, or outside the requested application scope.") |
| 77 | + return payload |
| 78 | + |
| 79 | + |
| 80 | +def cache_matches(path: Path, identity: ApplicationIdentity) -> bool: |
| 81 | + try: |
| 82 | + validate_identity(json.loads(path.read_text(encoding="utf-8")), identity) |
| 83 | + return True |
| 84 | + except (OSError, ValueError, CodeanalyzerExecutionException): |
| 85 | + return False |
| 86 | + |
| 87 | + |
| 88 | +def index_module_rows(rows: Iterable[Mapping[str, str]]) -> dict[str, dict[str, str]]: |
| 89 | + """Collapse repeated module projections by canonical identity, never by filename.""" |
| 90 | + index: dict[str, dict[str, str]] = {} |
| 91 | + for row in rows: |
| 92 | + module_id, file_key = row["module_id"], row["file_key"] |
| 93 | + if module_id in index and index[module_id]["file_key"] != file_key: |
| 94 | + raise ValueError(f"Conflicting file keys for canonical module {module_id}: {index[module_id]['file_key']!r} and {file_key!r}") |
| 95 | + index[module_id] = {"module_id": module_id, "file_key": file_key} |
| 96 | + return index |
| 97 | + |
| 98 | + |
| 99 | +def scoped_module_keys(index: Mapping[str, Mapping[str, str]], application_id: str, languages: tuple[str, ...]) -> dict[str, str]: |
| 100 | + """Derive the relative-key API only after validating owner and language. |
| 101 | +
|
| 102 | + Candidate IDs remain in the primary index; an ambiguous relative key cannot silently |
| 103 | + select whichever module happened to be projected last. |
| 104 | + """ |
| 105 | + candidates: dict[str, set[str]] = {} |
| 106 | + prefixes = tuple(f"{application_id}/{language}/" for language in languages) |
| 107 | + for module_id, row in index.items(): |
| 108 | + if not module_id.startswith(prefixes): |
| 109 | + raise ValueError(f"Module URI is outside the bound application/language scope: {module_id}") |
| 110 | + candidates.setdefault(row["file_key"], set()).add(module_id) |
| 111 | + for key, ids in candidates.items(): |
| 112 | + if len(ids) != 1: |
| 113 | + raise ValueError(f"Ambiguous module file key {key!r}: {sorted(ids)}") |
| 114 | + return {key: next(iter(ids)) for key, ids in candidates.items()} |
0 commit comments