This is an automated email from the ASF dual-hosted git repository.

arm pushed a commit to branch taint_tracking_types
in repository https://gitbox.apache.org/repos/asf/tooling-trusted-releases.git

commit fef79800b8ebefa79628e57cbb5e9227a4d0d861
Author: Alastair McFarlane <[email protected]>
AuthorDate: Wed Feb 25 11:56:34 2026 +0000

    First cut of taint tracking types for project and version
---
 atr/blueprints/get.py  | 166 ++++++++++++++++++++++++++++++++++++++++++++-----
 atr/blueprints/post.py |  34 +++++-----
 atr/cache.py           |  62 ++++++++++++++++++
 atr/get/announce.py    |   6 +-
 atr/get/compose.py     |  18 ++++--
 atr/models/safe.py     |  62 ++++++++++++++++++
 atr/models/unsafe.py   |  28 +++++++++
 atr/server.py          |   4 ++
 atr/web.py             |   1 +
 9 files changed, 346 insertions(+), 35 deletions(-)

diff --git a/atr/blueprints/get.py b/atr/blueprints/get.py
index f715defd..7eef135a 100644
--- a/atr/blueprints/get.py
+++ b/atr/blueprints/get.py
@@ -15,18 +15,24 @@
 # specific language governing permissions and limitations
 # under the License.
 
+import inspect
 import time
 from collections.abc import Awaitable, Callable
 from types import ModuleType
-from typing import Any
+from typing import Any, Literal, get_args, get_origin, get_type_hints
 
 import asfquart.auth as auth
 import asfquart.base as base
 import asfquart.session
 import quart
 
+import atr.cache as cache
+import atr.db as db
 import atr.ldap as ldap
 import atr.log as log
+import atr.models.safe as safe
+import atr.models.sql as sql
+import atr.models.unsafe as unsafe
 import atr.web as web
 
 _BLUEPRINT_NAME = "get_blueprint"
@@ -34,17 +40,151 @@ _BLUEPRINT = quart.Blueprint(_BLUEPRINT_NAME, __name__)
 _routes: list[str] = []
 
 
+async def _authenticate() -> web.Committer:
+    web_session = await asfquart.session.read()
+    if web_session is None:
+        raise base.ASFQuartException("Not authenticated", errorcode=401)
+    if (web_session.uid is None) or (not await 
ldap.is_active(web_session.uid)):
+        asfquart.session.clear()
+        raise base.ASFQuartException("Account is disabled", errorcode=401)
+    return web.Committer(web_session)
+
+
+def _register(func: Callable[..., Any]) -> None:
+    module_name = func.__module__.split(".")[-1]
+    _routes.append(f"get.{module_name}.{func.__name__}")
+
+
+async def _validate_project(raw: str) -> safe.ProjectName:
+    if cache.project_version_has_project(raw):
+        return safe.ProjectName(raw)
+    async with db.session() as data:
+        project = await data.project(name=raw, 
status=sql.ProjectStatus.ACTIVE, _committee=False).get()
+    if project is None:
+        raise base.ASFQuartException(f"Project {raw!r} not found", 
errorcode=404)
+    return safe.ProjectName(project.name)
+
+
+async def _validate_version(project_name: safe.ProjectName, raw: str) -> 
safe.VersionName:
+    if cache.project_version_has_version(project_name, raw):
+        return safe.VersionName(raw)
+    async with db.session() as data:
+        release = await data.release(
+            project_name=str(project_name),
+            version=raw,
+            _project=False,
+            _committee=False,
+        ).get()
+    if release is None:
+        raise base.ASFQuartException(f"Version {raw!r} not found for project 
{project_name!s}", errorcode=404)
+    return safe.VersionName(release.version)
+
+
+_QUART_CONVERTERS: dict[type, str] = {
+    int: "int",
+    float: "float",
+}
+
+_VALIDATED_TYPES: set[Any] = {safe.ProjectName, safe.VersionName}
+
+
+def _build_path(func: Callable[..., Any]) -> tuple[str, list[tuple[str, 
type]], dict[str, str]]:
+    """Inspect a function's type hints to build a URL path and a validation 
plan.
+
+    Returns (path, validated_params, literal_params) where validated_params is 
a
+    list of (param_name, param_type) for each parameter that needs async
+    validation, and literal_params maps parameter names to their values.
+    """
+    hints = get_type_hints(func, include_extras=True)
+    params = list(inspect.signature(func).parameters.keys())
+    segments: list[str] = []
+    validated_params: list[tuple[str, type]] = []
+    literal_params: dict[str, str] = {}
+
+    for param_name in params:
+        # This is the session object
+        if param_name == "session":
+            continue
+
+        hint = hints.get(param_name)
+        if hint is None:
+            raise TypeError(f"Parameter {param_name!r} in {func.__name__} has 
no type annotation")
+
+        origin = get_origin(hint)
+
+        if origin is Literal:
+            literal_value = get_args(hint)[0]
+            segments.append(str(literal_value))
+            literal_params[param_name] = str(literal_value)
+        elif hint in _VALIDATED_TYPES:
+            segments.append(f"<{param_name}>")
+            validated_params.append((param_name, hint))
+        elif hint in _QUART_CONVERTERS:
+            converter = _QUART_CONVERTERS[hint]
+            segments.append(f"<{converter}:{param_name}>")
+        elif hint is str:
+            segments.append(f"<{param_name}>")
+        else:
+            raise TypeError(f"Parameter {param_name!r} in {func.__name__} has 
unsupported type {hint!r}")
+
+    path = "/" + "/".join(segments)
+    return path, validated_params, literal_params
+
+
+async def _run_validators(kwargs: dict[str, Any], validated_params: 
list[tuple[str, type]]) -> None:
+    """Validate URL parameters in order, using the cache/DB validators."""
+    for param_name, param_type in validated_params:
+        raw = kwargs[param_name]
+        if param_type is safe.ProjectName:
+            kwargs[param_name] = await _validate_project(raw)
+        elif param_type is safe.VersionName:
+            project_name = kwargs.get("project_name", "")
+            kwargs[param_name] = await _validate_version(project_name, raw)
+
+
+def typed(func: Callable[..., Any]) -> web.RouteFunction[Any]:
+    """Decorator that derives the URL path from the function's type 
annotations.
+
+    - Literal["..."] parameters become literal path segments
+    - safe.ProjectName / safe.VersionName parameters are validated via cache/DB
+    - int, float use Quart's built-in type converters
+    - str parameters pass through as-is
+    """
+    path, validated_params, literal_params = _build_path(func)
+
+    async def wrapper(*_args: Any, **kwargs: Any) -> Any:
+        enhanced_session = await _authenticate()
+        await _run_validators(kwargs, validated_params)
+        kwargs.update(literal_params)
+
+        start_time_ns = time.perf_counter_ns()
+        response = await func(enhanced_session, **kwargs)
+        end_time_ns = time.perf_counter_ns()
+        total_ns = end_time_ns - start_time_ns
+        total_ms = total_ns // 1_000_000
+
+        log.performance(
+            f"GET {path} {func.__name__} = 0 0 {total_ms}",
+        )
+
+        return response
+
+    endpoint = func.__module__.replace(".", "_") + "_" + func.__name__
+    wrapper.__name__ = func.__name__
+    wrapper.__doc__ = func.__doc__
+    wrapper.__annotations__["endpoint"] = _BLUEPRINT_NAME + "." + endpoint
+
+    decorated = auth.require(auth.Requirements.committer)(wrapper)
+    _BLUEPRINT.add_url_rule(path, endpoint=endpoint, view_func=decorated, 
methods=["GET"])
+    _register(func)
+
+    return decorated
+
+
 def committer(path: str) -> Callable[[web.CommitterRouteFunction[Any]], 
web.RouteFunction[Any]]:
     def decorator(func: web.CommitterRouteFunction[Any]) -> 
web.RouteFunction[Any]:
         async def wrapper(*args: Any, **kwargs: Any) -> Any:
-            web_session = await asfquart.session.read()
-            if web_session is None:
-                raise base.ASFQuartException("Not authenticated", 
errorcode=401)
-            if (web_session.uid is None) or (not await 
ldap.is_active(web_session.uid)):
-                asfquart.session.clear()
-                raise base.ASFQuartException("Account is disabled", 
errorcode=401)
-
-            enhanced_session = web.Committer(web_session)
+            enhanced_session = await _authenticate()
             start_time_ns = time.perf_counter_ns()
             response = await func(enhanced_session, *args, **kwargs)
             end_time_ns = time.perf_counter_ns()
@@ -65,9 +205,7 @@ def committer(path: str) -> 
Callable[[web.CommitterRouteFunction[Any]], web.Rout
 
         decorated = auth.require(auth.Requirements.committer)(wrapper)
         _BLUEPRINT.add_url_rule(path, endpoint=endpoint, view_func=decorated, 
methods=["GET"])
-
-        module_name = func.__module__.split(".")[-1]
-        _routes.append(f"get.{module_name}.{func.__name__}")
+        _register(func)
 
         return decorated
 
@@ -87,9 +225,7 @@ def public(path: str) -> Callable[[Callable[..., 
Awaitable[Any]]], web.RouteFunc
         wrapper.__annotations__["endpoint"] = _BLUEPRINT_NAME + "." + endpoint
 
         _BLUEPRINT.add_url_rule(path, endpoint=endpoint, view_func=wrapper, 
methods=["GET"])
-
-        module_name = func.__module__.split(".")[-1]
-        _routes.append(f"get.{module_name}.{func.__name__}")
+        _register(func)
 
         return wrapper
 
diff --git a/atr/blueprints/post.py b/atr/blueprints/post.py
index 8c9133a0..18a7f81d 100644
--- a/atr/blueprints/post.py
+++ b/atr/blueprints/post.py
@@ -27,9 +27,11 @@ import asfquart.session
 import pydantic
 import quart
 
+import atr.db as db
 import atr.form
 import atr.ldap as ldap
 import atr.log as log
+import atr.models.sql as sql
 import atr.web as web
 
 _BLUEPRINT_NAME = "post_blueprint"
@@ -37,17 +39,25 @@ _BLUEPRINT = quart.Blueprint(_BLUEPRINT_NAME, __name__)
 _routes: list[str] = []
 
 
+async def _authenticate() -> web.Committer:
+    web_session = await asfquart.session.read()
+    if web_session is None:
+        raise base.ASFQuartException("Not authenticated", errorcode=401)
+    if (web_session.uid is None) or (not await 
ldap.is_active(web_session.uid)):
+        asfquart.session.clear()
+        raise base.ASFQuartException("Account is disabled", errorcode=401)
+    return web.Committer(web_session)
+
+
+def _register(func: Callable[..., Any]) -> None:
+    module_name = func.__module__.split(".")[-1]
+    _routes.append(f"post.{module_name}.{func.__name__}")
+
+
 def committer(path: str) -> Callable[[web.CommitterRouteFunction[Any]], 
web.RouteFunction[Any]]:
     def decorator(func: web.CommitterRouteFunction[Any]) -> 
web.RouteFunction[Any]:
         async def wrapper(*args: Any, **kwargs: Any) -> Any:
-            web_session = await asfquart.session.read()
-            if web_session is None:
-                raise base.ASFQuartException("Not authenticated", 
errorcode=401)
-            if (web_session.uid is None) or (not await 
ldap.is_active(web_session.uid)):
-                asfquart.session.clear()
-                raise base.ASFQuartException("Account is disabled", 
errorcode=401)
-
-            enhanced_session = web.Committer(web_session)
+            enhanced_session = await _authenticate()
             start_time_ns = time.perf_counter_ns()
             response = await func(enhanced_session, *args, **kwargs)
             end_time_ns = time.perf_counter_ns()
@@ -68,9 +78,7 @@ def committer(path: str) -> 
Callable[[web.CommitterRouteFunction[Any]], web.Rout
 
         decorated = auth.require(auth.Requirements.committer)(wrapper)
         _BLUEPRINT.add_url_rule(path, endpoint=endpoint, view_func=decorated, 
methods=["POST"])
-
-        module_name = func.__module__.split(".")[-1]
-        _routes.append(f"post.{module_name}.{func.__name__}")
+        _register(func)
 
         return decorated
 
@@ -187,9 +195,7 @@ def public(path: str) -> Callable[[Callable[..., 
Awaitable[Any]]], web.RouteFunc
         wrapper.__name__ = func.__name__
 
         _BLUEPRINT.add_url_rule(path, endpoint=endpoint, view_func=wrapper, 
methods=["POST"])
-
-        module_name = func.__module__.split(".")[-1]
-        _routes.append(f"post.{module_name}.{func.__name__}")
+        _register(func)
 
         return wrapper
 
diff --git a/atr/cache.py b/atr/cache.py
index f652a02d..e578f0aa 100644
--- a/atr/cache.py
+++ b/atr/cache.py
@@ -27,11 +27,14 @@ import pydantic
 import atr.config as config
 import atr.ldap as ldap
 import atr.log as log
+import atr.models.safe as safe
 import atr.models.schema as schema
 
 # Fifth prime after 3600
 ADMINS_POLL_INTERVAL_SECONDS: Final[int] = 3631
 
+PROJECT_VERSION_POLL_INTERVAL_SECONDS: Final[int] = 307
+
 
 class AdminsCache(schema.Strict):
     refreshed: datetime.datetime = schema.description("When the cache was last 
refreshed")
@@ -92,6 +95,39 @@ async def admins_startup_load() -> None:
         log.warning(f"Failed to fetch admin users from LDAP at startup: {e}")
 
 
+def project_version_get() -> dict[str, set[str]]:
+    if asfquart.APP is not None:
+        return asfquart.APP.extensions.get("project_versions", {})
+    return {}
+
+
+def project_version_has_project(project_name: str) -> bool:
+    return project_name in project_version_get()
+
+
+def project_version_has_version(project_name: safe.ProjectName, version_name: 
str) -> bool:
+    projects = project_version_get()
+    if str(project_name) not in projects:
+        return False
+    return version_name in projects[str(project_name)]
+
+
+async def project_version_refresh_loop() -> None:
+    while True:
+        await asyncio.sleep(PROJECT_VERSION_POLL_INTERVAL_SECONDS)
+        try:
+            await _project_version_refresh()
+        except Exception as e:
+            log.warning(f"Project/version cache refresh failed: {e}")
+
+
+async def project_version_startup_load() -> None:
+    try:
+        await _project_version_refresh()
+    except Exception as e:
+        log.warning(f"Failed to populate project/version cache at startup: 
{e}")
+
+
 def _admins_path() -> pathlib.Path:
     return pathlib.Path(config.get().STATE_DIR) / "cache" / "admins.json"
 
@@ -134,3 +170,29 @@ def _admins_update_app_extensions(admins: frozenset[str]) 
-> None:
     app = asfquart.APP
     app.extensions["admins"] = admins
     app.extensions["admins_refreshed"] = datetime.datetime.now(datetime.UTC)
+
+
+async def _project_version_fetch_from_db() -> dict[str, set[str]]:
+    import atr.db as db
+    import atr.models.sql as sql
+
+    projects: dict[str, set[str]] = {}
+    async with db.session() as data:
+        all_projects = await data.project(status=sql.ProjectStatus.ACTIVE, 
_committee=False).all()
+        for project in all_projects:
+            all_releases = await data.release(project_name=project.name, 
_project=False, _committee=False).all()
+            projects[project.name] = {release.version for release in 
all_releases}
+    return projects
+
+
+async def _project_version_refresh() -> None:
+    projects = await _project_version_fetch_from_db()
+    _project_version_update_app_extensions(projects)
+    total_versions = sum(len(v) for v in projects.values())
+    log.info(f"Project/version cache refreshed: {len(projects)} projects, 
{total_versions} versions")
+
+
+def _project_version_update_app_extensions(projects: dict[str, set[str]]) -> 
None:
+    app = asfquart.APP
+    app.extensions["project_versions"] = projects
+    app.extensions["project_versions_refreshed"] = 
datetime.datetime.now(datetime.UTC)
diff --git a/atr/get/announce.py b/atr/get/announce.py
index 235c8463..bb437543 100644
--- a/atr/get/announce.py
+++ b/atr/get/announce.py
@@ -36,7 +36,11 @@ import atr.web as web
 
 
 @get.committer("/announce/<project_name>/<version_name>")
-async def selected(session: web.Committer, project_name: str, version_name: 
str) -> str | web.WerkzeugResponse:
+async def selected(
+    session: web.Committer,
+    project_name: str,
+    version_name: str,
+) -> str | web.WerkzeugResponse:
     """Allow the user to announce a release preview."""
     await session.check_access(project_name)
 
diff --git a/atr/get/compose.py b/atr/get/compose.py
index 6e400872..7040cbe5 100644
--- a/atr/get/compose.py
+++ b/atr/get/compose.py
@@ -15,25 +15,33 @@
 # specific language governing permissions and limitations
 # under the License.
 
+from typing import Literal
+
 import asfquart.base as base
 
 import atr.blueprints.get as get
 import atr.db as db
 import atr.mapping as mapping
+import atr.models.safe as safe
 import atr.models.sql as sql
 import atr.shared as shared
 import atr.web as web
 
 
[email protected]("/compose/<project_name>/<version_name>")
-async def selected(session: web.Committer, project_name: str, version_name: 
str) -> web.WerkzeugResponse | str:
[email protected]
+async def selected(
+    session: web.Committer,
+    _compose: Literal["compose"],
+    project_name: safe.ProjectName,
+    version_name: safe.VersionName,
+) -> web.WerkzeugResponse | str:
     """Show the contents of the release candidate draft."""
-    await session.check_access(project_name)
+    await session.check_access(str(project_name))
 
     async with db.session() as data:
         release = await data.release(
-            project_name=project_name,
-            version=version_name,
+            project_name=str(project_name),
+            version=str(version_name),
             _committee=True,
             _project_release_policy=True,
         ).demand(base.ASFQuartException("Release does not exist", 
errorcode=404))
diff --git a/atr/models/safe.py b/atr/models/safe.py
new file mode 100644
index 00000000..c6f9893b
--- /dev/null
+++ b/atr/models/safe.py
@@ -0,0 +1,62 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+
+class ProjectName:
+    """A project name that has been validated against the cache or database."""
+
+    __slots__ = ("_value",)
+
+    def __init__(self, value: str) -> None:
+        self._value = value
+
+    def __eq__(self, other: object) -> bool:
+        if isinstance(other, ProjectName):
+            return self._value == other._value
+        return NotImplemented
+
+    def __hash__(self) -> int:
+        return hash(self._value)
+
+    def __repr__(self) -> str:
+        return f"ProjectName({self._value!r})"
+
+    def __str__(self) -> str:
+        return self._value
+
+
+class VersionName:
+    """A version name that has been validated against the cache or database."""
+
+    __slots__ = ("_value",)
+
+    def __init__(self, value: str) -> None:
+        self._value = value
+
+    def __eq__(self, other: object) -> bool:
+        if isinstance(other, VersionName):
+            return self._value == other._value
+        return NotImplemented
+
+    def __hash__(self) -> int:
+        return hash(self._value)
+
+    def __repr__(self) -> str:
+        return f"VersionName({self._value!r})"
+
+    def __str__(self) -> str:
+        return self._value
diff --git a/atr/models/unsafe.py b/atr/models/unsafe.py
new file mode 100644
index 00000000..55174c0d
--- /dev/null
+++ b/atr/models/unsafe.py
@@ -0,0 +1,28 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+
+class UnsafeStr:
+    """A raw string from URL routing that has not been validated."""
+
+    __slots__ = ("_value",)
+
+    def __init__(self, value: str) -> None:
+        self._value = value
+
+    def __repr__(self) -> str:
+        return f"UnsafeStr({self._value!r})"
diff --git a/atr/server.py b/atr/server.py
index 6dcee179..fe73716a 100644
--- a/atr/server.py
+++ b/atr/server.py
@@ -277,6 +277,10 @@ def _app_setup_lifecycle(app: base.QuartApp, app_config: 
type[config.AppConfig])
         admins_task = asyncio.create_task(cache.admins_refresh_loop())
         app.extensions["admins_task"] = admins_task
 
+        await cache.project_version_startup_load()
+        project_version_task = 
asyncio.create_task(cache.project_version_refresh_loop())
+        app.extensions["project_version_task"] = project_version_task
+
         worker_manager = manager.get_worker_manager()
         await worker_manager.start()
 
diff --git a/atr/web.py b/atr/web.py
index 4d7d8c9c..c49857ba 100644
--- a/atr/web.py
+++ b/atr/web.py
@@ -42,6 +42,7 @@ if TYPE_CHECKING:
     import pydantic
     import werkzeug.wrappers.response as response
 
+
 R = TypeVar("R", covariant=True)
 
 type WerkzeugResponse = response.Response


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to