This is an automated email from the ASF dual-hosted git repository.
Lee-W pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git
The following commit(s) were added to refs/heads/main by this push:
new 1a23e5c825a Validate HITL params answers against their schemas on
submit (#74569)
1a23e5c825a is described below
commit 1a23e5c825a45daefba659fc008f419e78a7d287
Author: Shivam Rastogi <[email protected]>
AuthorDate: Sun Nov 29 20:44:27 2026 -0800
Validate HITL params answers against their schemas on submit (#74569)
* Validate HITL params answers against their schemas on submit
The PATCH hitlDetails route stored params_input as given, so an answer
outside a param's JSON Schema, or one naming other params, was accepted and
reported as successful. The task then failed on resume, in
HITLOperator.validate_params_input, after the person had moved on; tasks
from other language SDKs only checked the names. The route now runs the
same check on submit and returns 400, as it already does for options.
* Add newsfragment for HITL params answer validation
* Remove newsfragment for HITL params answer validation
* Raise on invalid HITL params answers and catch at the call site
A function named validate should raise when validation fails, so the route
can turn the error into a 400 where it is handled, as the Dag-run trigger route
does.
---
.../api_fastapi/core_api/routes/public/hitl.py | 45 ++++++++++-
.../core_api/routes/public/test_hitl.py | 89 ++++++++++++++++++++++
2 files changed, 133 insertions(+), 1 deletion(-)
diff --git
a/airflow-core/src/airflow/api_fastapi/core_api/routes/public/hitl.py
b/airflow-core/src/airflow/api_fastapi/core_api/routes/public/hitl.py
index a4a96550d08..ed627e4afc0 100644
--- a/airflow-core/src/airflow/api_fastapi/core_api/routes/public/hitl.py
+++ b/airflow-core/src/airflow/api_fastapi/core_api/routes/public/hitl.py
@@ -17,7 +17,7 @@
from __future__ import annotations
from dataclasses import dataclass
-from typing import Annotated, Any
+from typing import TYPE_CHECKING, Annotated, Any
from uuid import UUID
import structlog
@@ -70,6 +70,7 @@ from
airflow.api_fastapi.core_api.services.public.task_coordinates import (
resolve_task_scope,
)
from airflow.api_fastapi.logging.decorators import action_logging
+from airflow.exceptions import ParamValidationError
from airflow.models.dag_version import DagVersion
from airflow.models.dagrun import DagRun
from airflow.models.hitl import HITLDetail as HITLDetailModel, HITLUser
@@ -77,9 +78,13 @@ from airflow.models.renderedtifields import
load_legacy_rendered_fields
from airflow.models.task_coordinates import TaskCoordinateResolver
from airflow.models.taskinstance import TaskInstance as TI
from airflow.models.trigger import handle_event_submit
+from airflow.serialization.definitions.param import SerializedParam,
SerializedParamsDict
from airflow.triggers.base import TriggerEvent
from airflow.utils.state import TaskInstanceState
+if TYPE_CHECKING:
+ from collections.abc import Mapping
+
task_instances_hitl_router = AirflowRouter(
tags=["Task Instance"],
prefix="/dags/{dag_id}/dagRuns/{dag_run_id}",
@@ -100,6 +105,40 @@ class HITLDetailView:
return getattr(self.value, name)
+def _validate_params_input(params: Mapping[str, Any], params_input:
Mapping[str, Any]) -> None:
+ """
+ Raise ``ParamValidationError`` if ``params_input`` is not a valid answer
to the request's ``params``.
+
+ Mirrors ``HITLOperator.validate_params_input``: when both are given, the
answer must name exactly
+ the declared params, and each value must pass its param's JSON Schema. A
param stored without a
+ schema, as older providers store it, accepts any value.
+ """
+ if not params or not params_input:
+ return
+ if set(params) != set(params_input):
+ raise ParamValidationError(
+ f"params_input {sorted(params_input)} does not match params
{sorted(params)}."
+ )
+ SerializedParamsDict(
+ {key: _build_answer_param(value, params[key]) for key, value in
params_input.items()}
+ ).validate()
+
+
+def _build_answer_param(value: Any, spec: Any) -> SerializedParam:
+ """
+ Build a param holding the submitted ``value``, with the JSON Schema from
the field's ``spec``.
+
+ A ``spec`` without a schema, such as a plain value older providers store,
attaches none, so any
+ value passes.
+ """
+ param = SerializedParam(value)
+ if isinstance(spec, dict) and isinstance(spec.get("schema"), dict):
+ # Set rather than passed as keywords: a schema's own "default" or
"description" would
+ # collide with SerializedParam's arguments.
+ param.schema = spec["schema"]
+ return param
+
+
def _get_task_instance_with_hitl_detail(
dag_id: str,
dag_run_id: str,
@@ -266,6 +305,10 @@ def update_hitl_detail(
status.HTTP_400_BAD_REQUEST,
"Multiple options chosen but this Human-in-the-loop task accepts
only a single option.",
)
+ try:
+ _validate_params_input(hitl_detail_model.params or {},
update_hitl_detail_payload.params_input)
+ except ParamValidationError as e:
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, str(e)) from e
if not hitl_detail_model.is_awaited_by(locked_ti):
raise HTTPException(
diff --git
a/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_hitl.py
b/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_hitl.py
index e8eb36ce51c..ceecb508705 100644
--- a/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_hitl.py
+++ b/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_hitl.py
@@ -251,6 +251,33 @@ def sample_hitl_detail(sample_ti: TaskInstance, session:
Session) -> HITLDetail:
return hitl_detail_model
[email protected]
+def sample_hitl_detail_with_schema(sample_ti: TaskInstance, session: Session)
-> HITLDetail:
+ hitl_detail_model = HITLDetail(
+ ti_id=sample_ti.id,
+ options=["Approve", "Reject"],
+ subject="This is subject",
+ body="this is body",
+ defaults=["Approve"],
+ multiple=False,
+ # As Param.serialize() stores it. The schema carries its own "default"
and "description".
+ params={
+ "replicas": {
+ "value": 3,
+ "description": "How many replicas to start",
+ "schema": {"type": "integer", "minimum": 1, "maximum": 10,
"default": 3, "description": "n"},
+ "source": "task",
+ },
+ "note": {"value": "", "description": None, "schema": {"type":
"string"}, "source": "task"},
+ },
+ assignees=None,
+ )
+ session.add(hitl_detail_model)
+ session.commit()
+
+ return hitl_detail_model
+
+
@pytest.fixture
def sample_hitl_detail_non_respondent(sample_ti: TaskInstance, session:
Session) -> HITLDetail:
hitl_detail_model = HITLDetail(
@@ -667,6 +694,68 @@ class TestUpdateHITLDetailEndpoint:
assert response.status_code == 400
assert "Invalid options" in response.json()["detail"]
+ @pytest.mark.usefixtures("sample_hitl_detail_with_schema",
"park_sample_ti")
+ @pytest.mark.parametrize(
+ ("params_input", "expected_detail"),
+ [
+ pytest.param(
+ {"replicas": 50, "note": "load test"},
+ "Invalid input for param replicas: 50 is greater than the
maximum of 10",
+ id="value-outside-schema",
+ ),
+ pytest.param(
+ {"replicas": "five", "note": "load test"},
+ "Invalid input for param replicas: 'five' is not of type
'integer'",
+ id="value-of-wrong-type",
+ ),
+ pytest.param(
+ {"replicas": 5},
+ "params_input ['replicas'] does not match params ['note',
'replicas'].",
+ id="missing-param",
+ ),
+ pytest.param(
+ {"replicas": 5, "note": "load test", "color": "red"},
+ "params_input ['color', 'note', 'replicas'] does not match
params ['note', 'replicas'].",
+ id="unknown-param",
+ ),
+ ],
+ )
+ def test_should_respond_400_for_invalid_params_input(
+ self,
+ test_client: TestClient,
+ sample_ti_url_identifier: str,
+ params_input: dict[str, Any],
+ expected_detail: str,
+ ) -> None:
+ """Write-side validation rejects a params_input that
HITLOperator.validate_params_input would fail."""
+ response = test_client.patch(
+ f"{sample_ti_url_identifier}/hitlDetails",
+ json={"chosen_options": ["Approve"], "params_input": params_input},
+ )
+ assert response.status_code == 400
+ assert response.json()["detail"].startswith(expected_detail)
+
+ @pytest.mark.usefixtures("sample_hitl_detail_with_schema",
"park_sample_ti")
+ @pytest.mark.parametrize(
+ "params_input",
+ [
+ pytest.param({"replicas": 5, "note": "load test"},
id="valid-values"),
+ pytest.param({}, id="no-params-input"),
+ ],
+ )
+ def test_should_accept_params_input_that_passes_its_schema(
+ self,
+ test_client: TestClient,
+ sample_ti_url_identifier: str,
+ params_input: dict[str, Any],
+ ) -> None:
+ response = test_client.patch(
+ f"{sample_ti_url_identifier}/hitlDetails",
+ json={"chosen_options": ["Approve"], "params_input": params_input},
+ )
+ assert response.status_code == 200
+ assert response.json()["params_input"] == params_input
+
@pytest.mark.usefixtures("sample_hitl_detail", "park_sample_ti")
def test_should_validate_against_row_refreshed_under_lock(
self,