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

kaxil 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 d71919898ab Fix rotate-fernet-key failing on trigger rows from 
deferred tasks (#77614)
d71919898ab is described below

commit d71919898ab5e23bb166c335c36f348c32dcc826
Author: Jed Cunningham <[email protected]>
AuthorDate: Thu Nov 26 08:51:56 2026 -0700

    Fix rotate-fernet-key failing on trigger rows from deferred tasks (#77614)
    
    
    The Execution API stored a deferring task's trigger kwargs in a different
    form from every other trigger writer, so `airflow rotate-fernet-key`
    failed with InvalidToken whenever such a row existed. Rotation also
    converts rows that earlier releases left in that form.
    
    No SDK sends trigger kwargs as a string, and the server cannot store one
    consistently, so the deferral payload no longer accepts one.
    
    * Key the string trigger kwargs converter by path
    
    A body-schema converter can't match one member of the TIStateUpdate union
    on cadwyn 8, which 3.4 still uses, so building the versioned routes fails
    there.
---
 airflow-core/docs/security/secrets/fernet.rst      |  6 +-
 airflow-core/docs/security/security_model.rst      |  2 +-
 .../execution_api/datamodels/taskinstance.py       | 20 ++----
 .../execution_api/routes/task_instances.py         | 11 +--
 .../api_fastapi/execution_api/versions/__init__.py |  2 +
 .../execution_api/versions/v2026_12_01.py          | 48 +++++++++++++
 airflow-core/src/airflow/cli/cli_config.py         |  6 +-
 .../src/airflow/config_templates/config.yml        |  2 +-
 airflow-core/src/airflow/models/trigger.py         | 25 +++++--
 .../versions/head/test_task_instances.py           | 29 ++++++++
 .../execution_api/versions/v2026_12_01/__init__.py | 16 +++++
 .../versions/v2026_12_01/test_task_instances.py    | 83 ++++++++++++++++++++++
 .../cli/commands/test_rotate_fernet_key_command.py | 35 ++++++++-
 docker-stack-docs/entrypoint.rst                   |  2 +-
 go-sdk/pkg/execution/genmodels/models.gen.go       |  8 +--
 go-sdk/schema/supervisor-schema.json               |  3 -
 java-sdk/sdk/schema/schema.json                    |  3 -
 scripts/ci/prek/check_security_doc_constants.py    |  2 +-
 .../src/airflow/sdk/api/datamodels/_generated.py   |  2 +-
 task-sdk/src/airflow/sdk/definitions/dag.py        |  4 +-
 .../airflow/sdk/execution_time/schema/schema.json  |  3 -
 .../sdk/execution_time/schema/versions/__init__.py |  2 +
 .../execution_time/schema/versions/v2026_12_01.py  | 42 +++++++++++
 .../execution_time/schema/test_migrator.py         | 35 +++++++++
 ts-sdk/schema/supervisor-schema.json               |  3 -
 ts-sdk/src/generated/supervisor.ts                 |  9 +--
 26 files changed, 333 insertions(+), 70 deletions(-)

diff --git a/airflow-core/docs/security/secrets/fernet.rst 
b/airflow-core/docs/security/secrets/fernet.rst
index 341e2186bd3..13a249f2afc 100644
--- a/airflow-core/docs/security/secrets/fernet.rst
+++ b/airflow-core/docs/security/secrets/fernet.rst
@@ -21,7 +21,7 @@ Fernet
 ------
 
 Airflow uses `Fernet <https://github.com/fernet/spec/>`__ to encrypt passwords 
in the connection
-configuration and the variable configuration. It guarantees that a password 
encrypted using it cannot be manipulated or read without the key.
+configuration, the variable configuration and the kwargs of triggers. It 
guarantees that a password encrypted using it cannot be manipulated or read 
without the key.
 Fernet is an implementation of symmetric (also known as "secret key") 
authenticated cryptography.
 
 The first time Airflow is started, the ``airflow.cfg`` file is generated with 
the default configuration and the unique Fernet
@@ -51,7 +51,7 @@ If you need to generate a new fernet key you can use the 
following code snippet.
 Rotating encryption keys
 ''''''''''''''''''''''''
 
-Once connection credentials and variables have been encrypted using a fernet
+Once connection credentials, variables and trigger kwargs have been encrypted 
using a fernet
 key, changing the key will cause decryption of existing credentials to fail. To
 rotate the fernet key without invalidating existing encrypted values, prepend
 the new key to the ``fernet_key`` setting, run
@@ -59,5 +59,5 @@ the new key to the ``fernet_key`` setting, run
 ``fernet_key``:
 
 #. Set ``fernet_key`` to ``new_fernet_key,old_fernet_key``
-#. Run ``airflow rotate-fernet-key`` to re-encrypt existing credentials with 
the new fernet key
+#. Run ``airflow rotate-fernet-key`` to re-encrypt existing credentials, 
variables and trigger kwargs with the new fernet key
 #. Set ``fernet_key`` to ``new_fernet_key``
diff --git a/airflow-core/docs/security/security_model.rst 
b/airflow-core/docs/security/security_model.rst
index ec5c340851d..ecdb3db4911 100644
--- a/airflow-core/docs/security/security_model.rst
+++ b/airflow-core/docs/security/security_model.rst
@@ -744,7 +744,7 @@ model — Airflow does not enforce these natively.
         - Asset manager credentials
         - Dag File Processor
       * - ``AIRFLOW__CORE__FERNET_KEY``
-        - Fernet encryption key for connections/variables at rest
+        - Fernet encryption key for connections, variables and trigger kwargs 
at rest
         - API Server, Scheduler, Workers, Dag File Processor, Triggerer
       * - ``AIRFLOW__DATABASE__SQL_ALCHEMY_CONN``
         - Metadata database connection string
diff --git 
a/airflow-core/src/airflow/api_fastapi/execution_api/datamodels/taskinstance.py 
b/airflow-core/src/airflow/api_fastapi/execution_api/datamodels/taskinstance.py
index 3a8ed411c23..45ab9e3ac77 100644
--- 
a/airflow-core/src/airflow/api_fastapi/execution_api/datamodels/taskinstance.py
+++ 
b/airflow-core/src/airflow/api_fastapi/execution_api/datamodels/taskinstance.py
@@ -180,23 +180,15 @@ class TIDeferredStatePayload(StrictBaseModel):
         ),
     ]
     classpath: str
-    trigger_kwargs: Annotated[dict[str, JsonValue] | str, 
Field(default_factory=dict)]
-    """
-    Kwargs to pass to the trigger constructor, either a plain dict or an 
encrypted string.
-
-    Both forms will be passed along to the trigger, the server will not handle 
either.
-    """
+    trigger_kwargs: Annotated[dict[str, JsonValue], 
Field(default_factory=dict)]
+    """Serde-encoded kwargs to pass to the trigger constructor. The server 
encrypts them before storing."""
 
     trigger_timeout: timedelta | None = None
     queue: str | None = None
     next_method: str
     """The name of the method on the operator to call in the worker after the 
trigger has fired."""
     next_kwargs: Annotated[dict[str, JsonValue], Field(default_factory=dict)]
-    """
-    Kwargs to pass to the above method, either a plain dict or an encrypted 
string.
-
-    Both forms will be passed along to the TaskSDK upon resume, the server 
will not handle either.
-    """
+    """Serde-encoded kwargs to pass to the above method; returned on resume 
with the event added under `event`."""
     rendered_map_index: str | None = None
 
 
@@ -237,11 +229,7 @@ class TIAwaitingInputStatePayload(StrictBaseModel):
     next_method: str
     """The name of the method on the operator to call in the worker after 
input is received."""
     next_kwargs: Annotated[dict[str, JsonValue], Field(default_factory=dict)]
-    """
-    Kwargs to pass to the above method, either a plain dict or an encrypted 
string.
-
-    Both forms will be passed along to the TaskSDK upon resume, the server 
will not handle either.
-    """
+    """Serde-encoded kwargs to pass to the above method; returned on resume 
with the event added under `event`."""
     rendered_map_index: str | None = None
 
 
diff --git 
a/airflow-core/src/airflow/api_fastapi/execution_api/routes/task_instances.py 
b/airflow-core/src/airflow/api_fastapi/execution_api/routes/task_instances.py
index 31d652563dd..356f94cc0ec 100644
--- 
a/airflow-core/src/airflow/api_fastapi/execution_api/routes/task_instances.py
+++ 
b/airflow-core/src/airflow/api_fastapi/execution_api/routes/task_instances.py
@@ -973,21 +973,14 @@ def _create_ti_state_update_query_and_update_state(
         if ti_patch_payload.trigger_timeout is not None:
             timeout = timezone.utcnow() + ti_patch_payload.trigger_timeout
 
-        trigger_kwargs = ti_patch_payload.trigger_kwargs
-        if not isinstance(trigger_kwargs, str):
-            # If it's passed as a string, assume the client encrypted it, 
otherwise assume it doesn't need to
-            # be. Just JSON serialize it
-            trigger_kwargs = json.dumps(trigger_kwargs)
-
-        trigger_row = Trigger(
+        trigger_row = Trigger.from_serialized_kwargs(
             classpath=ti_patch_payload.classpath,
-            kwargs={},
+            serialized_kwargs=ti_patch_payload.trigger_kwargs,
             queue=ti_patch_payload.queue,
             team_name=get_team_name_for_ti(task_instance_id, session),
             dag_id=dag_id,
             used_by_ref={"ti_id": str(task_instance_id)},
         )
-        trigger_row.encrypted_kwargs = trigger_kwargs
         session.add(trigger_row)
         session.flush()
 
diff --git 
a/airflow-core/src/airflow/api_fastapi/execution_api/versions/__init__.py 
b/airflow-core/src/airflow/api_fastapi/execution_api/versions/__init__.py
index 7d828483598..34dced3fd65 100644
--- a/airflow-core/src/airflow/api_fastapi/execution_api/versions/__init__.py
+++ b/airflow-core/src/airflow/api_fastapi/execution_api/versions/__init__.py
@@ -68,6 +68,7 @@ from airflow.api_fastapi.execution_api.versions.v2026_10_30 
import (
     IdentifyArchivedTaskStateUpdates,
     ReturnNotFoundForMissingDagRun,
 )
+from airflow.api_fastapi.execution_api.versions.v2026_12_01 import 
RemoveStringTriggerKwargs
 from airflow.api_fastapi.execution_api.versions.v2027_02_28 import (
     AddCallbackStateEndpoint,
     AddDagProcessorJobEndpoints,
@@ -88,6 +89,7 @@ bundle = VersionBundle(
         AddCallbackStateEndpoint,
         ResolveOmittedXComMapIndexByTaskDefinition,
     ),
+    Version("2026-12-01", RemoveStringTriggerKwargs),
     Version(
         "2026-10-30",
         AddArgBindingsToTIRunContext,
diff --git 
a/airflow-core/src/airflow/api_fastapi/execution_api/versions/v2026_12_01.py 
b/airflow-core/src/airflow/api_fastapi/execution_api/versions/v2026_12_01.py
new file mode 100644
index 00000000000..5367e27bf4d
--- /dev/null
+++ b/airflow-core/src/airflow/api_fastapi/execution_api/versions/v2026_12_01.py
@@ -0,0 +1,48 @@
+# 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.
+
+from __future__ import annotations
+
+from cadwyn import RequestInfo, VersionChange, 
convert_request_to_next_version_for, schema
+from fastapi import HTTPException
+from pydantic import JsonValue
+
+from airflow.api_fastapi.compat import HTTP_422_UNPROCESSABLE_CONTENT
+from airflow.api_fastapi.execution_api.datamodels.taskinstance import 
TIDeferredStatePayload
+
+
+class RemoveStringTriggerKwargs(VersionChange):
+    """Stop accepting `trigger_kwargs` as a string in 
TIDeferredStatePayload."""
+
+    description = __doc__
+
+    instructions_to_migrate_to_previous_version = (
+        
schema(TIDeferredStatePayload).field("trigger_kwargs").had(type=dict[str, 
JsonValue] | str),
+    )
+
+    # Keyed by path: cadwyn 8 can't match a body-schema converter to one 
member of the TIStateUpdate union.
+    
@convert_request_to_next_version_for("/task-instances/{task_instance_id}/state",
 ["PATCH"])  # type: ignore[arg-type]
+    def reject_string_trigger_kwargs(request: RequestInfo) -> None:
+        """Reject a string from older clients; the server can't tell whether 
it is encrypted."""
+        if isinstance(request.body, dict) and 
isinstance(request.body.get("trigger_kwargs"), str):
+            raise HTTPException(
+                status_code=HTTP_422_UNPROCESSABLE_CONTENT,
+                detail={
+                    "reason": "invalid_trigger_kwargs",
+                    "message": "trigger_kwargs must be a serialized dict, not 
a string",
+                },
+            )
diff --git a/airflow-core/src/airflow/cli/cli_config.py 
b/airflow-core/src/airflow/cli/cli_config.py
index b072a612af2..ab3ba276ab3 100644
--- a/airflow-core/src/airflow/cli/cli_config.py
+++ b/airflow-core/src/airflow/cli/cli_config.py
@@ -2391,10 +2391,10 @@ core_commands: list[CLICommand] = [
     ActionCommand(
         name="rotate-fernet-key",
         
func=lazy_load_command("airflow.cli.commands.rotate_fernet_key_command.rotate_fernet_key"),
-        help="Rotate encrypted connection credentials and variables",
+        help="Rotate encrypted connection credentials, variables and trigger 
kwargs",
         description=(
-            "Rotate all encrypted connection credentials and variables; see "
-            
"https://airflow.apache.org/docs/apache-airflow/stable/howto/secure-connections.html";
+            "Rotate all encrypted connection credentials, variables and 
trigger kwargs; see "
+            
"https://airflow.apache.org/docs/apache-airflow/stable/security/secrets/fernet.html";
             "#rotating-encryption-keys"
         ),
         args=(),
diff --git a/airflow-core/src/airflow/config_templates/config.yml 
b/airflow-core/src/airflow/config_templates/config.yml
index 1fe1c50215c..93b09366d11 100644
--- a/airflow-core/src/airflow/config_templates/config.yml
+++ b/airflow-core/src/airflow/config_templates/config.yml
@@ -238,7 +238,7 @@ core:
       type: boolean
     fernet_key:
       description: |
-        Secret key to save connection passwords in the db
+        Secret key to encrypt connection passwords, variables and trigger 
kwargs in the db
       version_added: ~
       type: string
       sensitive: true
diff --git a/airflow-core/src/airflow/models/trigger.py 
b/airflow-core/src/airflow/models/trigger.py
index 0053c9cfe6c..24c8ed8cb93 100644
--- a/airflow-core/src/airflow/models/trigger.py
+++ b/airflow-core/src/airflow/models/trigger.py
@@ -249,9 +249,8 @@ class Trigger(Base):
         from airflow.crypto import get_fernet
         from airflow.sdk.serde import deserialize
 
-        # We weren't able to encrypt the kwargs in all migration paths,
-        # so we need to handle the case where they are not encrypted.
-        # Triggers aren't long lasting, so we can skip encrypting them now.
+        # Plaintext JSON comes from running without a fernet key, the offline 
2.9 migration,
+        # or task deferrals in older Airflow 3 releases.
         if encrypted_kwargs.startswith("{"):
             decrypted_kwargs = json.loads(encrypted_kwargs)
         else:
@@ -274,7 +273,11 @@ class Trigger(Base):
         """Encrypts data with a new key. See: :ref:`security/fernet`."""
         from airflow.crypto import get_fernet
 
-        self.encrypted_kwargs = 
get_fernet().rotate(self.encrypted_kwargs.encode("utf-8")).decode("utf-8")
+        fernet = get_fernet()
+        if self.encrypted_kwargs.startswith("{"):
+            self.encrypted_kwargs = 
fernet.encrypt(self.encrypted_kwargs.encode("utf-8")).decode("utf-8")
+        else:
+            self.encrypted_kwargs = 
fernet.rotate(self.encrypted_kwargs.encode("utf-8")).decode("utf-8")
 
     @classmethod
     def from_object(cls, trigger: BaseTrigger) -> Trigger:
@@ -288,6 +291,7 @@ class Trigger(Base):
         classpath: str,
         serialized_kwargs: dict[str, Any],
         queue: str | None = None,
+        team_name: str | None = None,
         *,
         dag_id: str | None = None,
         used_by_ref: dict[str, Any] | None = None,
@@ -295,10 +299,17 @@ class Trigger(Base):
         """
         Create a trigger row from kwargs that are already in their 
serde-encoded form.
 
-        The kwargs are stored exactly as given and decoded by the triggerer 
when it creates
-        the trigger, the same as kwargs stored by :meth:`from_object`.
+        The kwargs are encrypted without being re-serialized and decoded by 
the triggerer when it
+        creates the trigger, the same as kwargs stored by :meth:`from_object`.
         """
-        trigger = cls(classpath=classpath, kwargs={}, queue=queue, 
dag_id=dag_id, used_by_ref=used_by_ref)
+        trigger = cls(
+            classpath=classpath,
+            kwargs={},
+            queue=queue,
+            team_name=team_name,
+            dag_id=dag_id,
+            used_by_ref=used_by_ref,
+        )
         trigger.encrypted_kwargs = 
cls._encrypt_serialized_kwargs(serialized_kwargs)
         return trigger
 
diff --git 
a/airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py
 
b/airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py
index 7bae05fd4ef..291cf7967c0 100644
--- 
a/airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py
+++ 
b/airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py
@@ -17,6 +17,7 @@
 
 from __future__ import annotations
 
+import json
 import re
 from concurrent.futures import ThreadPoolExecutor
 from contextlib import nullcontext
@@ -58,6 +59,7 @@ from airflow.api_fastapi.execution_api.datamodels.token 
import ExecutionToken, T
 from airflow.api_fastapi.execution_api.routes import task_instances as 
task_instances_route
 from airflow.api_fastapi.execution_api.routes.task_instances import 
_emit_task_span, ti_update_state
 from airflow.api_fastapi.execution_api.security import require_auth
+from airflow.crypto import get_fernet
 from airflow.exceptions import AirflowSkipException, TaskNotFound
 from airflow.jobs.scheduler_job_runner import SchedulerJobRunner
 from airflow.models import DagRun, RenderedTaskInstanceFields, TaskReschedule, 
Trigger
@@ -4013,6 +4015,8 @@ class TestTIUpdateState:
             assert len(t) == 1
             assert t[0].created_date == instant
             assert t[0].classpath == "my-classpath"
+            stored = 
get_fernet().decrypt(t[0].encrypted_kwargs.encode("utf-8"))
+            assert json.loads(stored) == payload["trigger_kwargs"]
             assert t[0].kwargs == {
                 "key": "value",
                 "moment": datetime(2024, 12, 18, 00, 00, 1, 
tzinfo=timezone.utc),
@@ -4023,6 +4027,31 @@ class TestTIUpdateState:
                 assert t[0].queue is None
             assert (t[0].dag_id, t[0].used_by_ref) == (ti.dag_id, {"ti_id": 
str(ti.id)})
 
+    def test_ti_update_state_to_deferred_rejects_string_trigger_kwargs(
+        self, client, session, create_task_instance
+    ):
+        ti = create_task_instance(
+            
task_id="test_ti_update_state_to_deferred_rejects_string_trigger_kwargs",
+            state=State.RUNNING,
+            session=session,
+        )
+        session.commit()
+
+        response = client.patch(
+            f"/execution/task-instances/{ti.id}/state",
+            json={
+                "state": "deferred",
+                "trigger_kwargs": '{"key": "value"}',
+                "classpath": "my-classpath",
+                "next_method": "execute_callback",
+            },
+        )
+
+        assert response.status_code == 422
+        session.expire_all()
+        assert session.scalar(select(TaskInstance.state).where(TaskInstance.id 
== ti.id)) == State.RUNNING
+        assert session.scalars(select(Trigger)).all() == []
+
     @staticmethod
     def _defer_ti_in_team_bundle(client, session, create_task_instance):
         """Map the TI's Dag to a bundle/team, then defer it via the Execution 
API."""
diff --git 
a/airflow-core/tests/unit/api_fastapi/execution_api/versions/v2026_12_01/__init__.py
 
b/airflow-core/tests/unit/api_fastapi/execution_api/versions/v2026_12_01/__init__.py
new file mode 100644
index 00000000000..13a83393a91
--- /dev/null
+++ 
b/airflow-core/tests/unit/api_fastapi/execution_api/versions/v2026_12_01/__init__.py
@@ -0,0 +1,16 @@
+# 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.
diff --git 
a/airflow-core/tests/unit/api_fastapi/execution_api/versions/v2026_12_01/test_task_instances.py
 
b/airflow-core/tests/unit/api_fastapi/execution_api/versions/v2026_12_01/test_task_instances.py
new file mode 100644
index 00000000000..f8014549f76
--- /dev/null
+++ 
b/airflow-core/tests/unit/api_fastapi/execution_api/versions/v2026_12_01/test_task_instances.py
@@ -0,0 +1,83 @@
+# 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.
+from __future__ import annotations
+
+import pytest
+from sqlalchemy import select
+
+from airflow.models import TaskInstance, Trigger
+from airflow.utils.state import State
+
+from tests_common.test_utils.db import clear_db_runs, clear_db_triggers
+
+pytestmark = pytest.mark.db_test
+
+PREVIOUS_VERSION = "2026-10-30"
+
+
[email protected](autouse=True)
+def _clean_db():
+    clear_db_runs()
+    clear_db_triggers()
+    yield
+    clear_db_runs()
+    clear_db_triggers()
+
+
[email protected](
+    ("trigger_kwargs", "expected_status", "expected_state"),
+    [
+        pytest.param({"key": "value"}, 204, State.DEFERRED, id="dict"),
+        pytest.param('{"key": "value"}', 422, State.RUNNING, id="string"),
+    ],
+)
+def test_old_version_deferral_trigger_kwargs(
+    client, session, create_task_instance, trigger_kwargs, expected_status, 
expected_state
+):
+    ti = create_task_instance(
+        task_id="test_old_version_deferral_trigger_kwargs", 
state=State.RUNNING, session=session
+    )
+    session.commit()
+    client.headers["Airflow-API-Version"] = PREVIOUS_VERSION
+
+    response = client.patch(
+        f"/execution/task-instances/{ti.id}/state",
+        json={
+            "state": "deferred",
+            "trigger_kwargs": trigger_kwargs,
+            "classpath": "my-classpath",
+            "next_method": "execute_callback",
+        },
+    )
+
+    assert response.status_code == expected_status, response.text
+    if expected_status == 422:
+        assert response.json()["detail"]["reason"] == "invalid_trigger_kwargs"
+    session.expire_all()
+    assert session.scalar(select(TaskInstance.state).where(TaskInstance.id == 
ti.id)) == expected_state
+    triggers = session.scalars(select(Trigger)).all()
+    assert [t.kwargs for t in triggers] == ([trigger_kwargs] if 
expected_status == 204 else [])
+
+
[email protected]("version", [PREVIOUS_VERSION, "2026-12-01"])
+def test_trigger_kwargs_schema_by_version(client, version):
+    response = client.get(f"/execution/openapi.json?version={version}")
+
+    assert response.status_code == 200
+    field = 
response.json()["components"]["schemas"]["TIDeferredStatePayload"]["properties"]["trigger_kwargs"]
+    types = {option.get("type") for option in field.get("oneOf", [field])}
+    assert ("string" in types) == (version == PREVIOUS_VERSION)
diff --git 
a/airflow-core/tests/unit/cli/commands/test_rotate_fernet_key_command.py 
b/airflow-core/tests/unit/cli/commands/test_rotate_fernet_key_command.py
index 0592cc535f2..845498294d6 100644
--- a/airflow-core/tests/unit/cli/commands/test_rotate_fernet_key_command.py
+++ b/airflow-core/tests/unit/cli/commands/test_rotate_fernet_key_command.py
@@ -16,6 +16,7 @@
 # under the License.
 from __future__ import annotations
 
+import json
 from argparse import ArgumentParser
 from typing import TYPE_CHECKING
 
@@ -26,12 +27,12 @@ from sqlalchemy import select
 from airflow.cli import cli_parser
 from airflow.cli.commands import rotate_fernet_key_command
 from airflow.crypto import get_fernet
-from airflow.models import Connection, Variable
+from airflow.models import Connection, Trigger, Variable
 from airflow.sdk import BaseHook
 from airflow.utils.session import provide_session
 
 from tests_common.test_utils.config import conf_vars
-from tests_common.test_utils.db import clear_db_connections, clear_db_variables
+from tests_common.test_utils.db import clear_db_connections, 
clear_db_triggers, clear_db_variables
 
 if TYPE_CHECKING:
     from sqlalchemy.orm import Session
@@ -49,10 +50,12 @@ class TestRotateFernetKeyCommand:
     def setup_method(self) -> None:
         clear_db_connections(add_default_connections_back=False)
         clear_db_variables()
+        clear_db_triggers()
 
     def teardown_method(self) -> None:
         clear_db_connections(add_default_connections_back=False)
         clear_db_variables()
+        clear_db_triggers()
 
     @provide_session
     def test_should_rotate_variable(self, *, session: Session):
@@ -143,3 +146,31 @@ class TestRotateFernetKeyCommand:
             # Mock for the second connection
             mock_supervisor_comms.send.return_value = 
mock_get_connection(var2_key)
             assert BaseHook.get_connection(var2_key).password == "pass"
+
+    @provide_session
+    def test_should_rotate_trigger_and_encrypt_plaintext_trigger(self, *, 
session: Session):
+        fernet_key1 = Fernet.generate_key()
+        fernet_key2 = Fernet.generate_key()
+        classpath = "airflow.triggers.testing.SuccessTrigger"
+
+        with conf_vars({("core", "fernet_key"): fernet_key1.decode()}):
+            get_fernet.cache_clear()
+            encrypted = Trigger(classpath=classpath, kwargs={"secret": 
"encrypted"})
+            # Plaintext JSON, as written by task deferrals on earlier Airflow 
3 releases.
+            plaintext = Trigger(classpath=classpath, kwargs={})
+            plaintext.encrypted_kwargs = json.dumps({"secret": "plaintext"})
+            session.add_all([encrypted, plaintext])
+            session.commit()
+
+        with conf_vars({("core", "fernet_key"): 
f"{fernet_key2.decode()},{fernet_key1.decode()}"}):
+            get_fernet.cache_clear()
+            args = self.parser.parse_args(["rotate-fernet-key"])
+            rotate_fernet_key_command.rotate_fernet_key(args)
+
+        session.expire_all()
+        with conf_vars({("core", "fernet_key"): fernet_key2.decode()}):
+            get_fernet.cache_clear()
+            rotated_encrypted, rotated_plaintext = 
session.scalars(select(Trigger).order_by(Trigger.id))
+            assert rotated_encrypted.kwargs == {"secret": "encrypted"}
+            assert "plaintext" not in rotated_plaintext.encrypted_kwargs
+            assert rotated_plaintext.kwargs == {"secret": "plaintext"}
diff --git a/docker-stack-docs/entrypoint.rst b/docker-stack-docs/entrypoint.rst
index 8785493aa61..70354a776aa 100644
--- a/docker-stack-docs/entrypoint.rst
+++ b/docker-stack-docs/entrypoint.rst
@@ -211,7 +211,7 @@ If there are any other arguments - they are simply passed 
to the "airflow" comma
           kerberos          Start a kerberos ticket renewer
           plugins           Dump information about loaded plugins
           rotate-fernet-key
-                            Rotate encrypted connection credentials and 
variables
+                            Rotate encrypted connection credentials, variables 
and trigger kwargs
           scheduler         Start a scheduler instance
           standalone        Run an all-in-one copy of Airflow
           triggerer         Start a triggerer instance
diff --git a/go-sdk/pkg/execution/genmodels/models.gen.go 
b/go-sdk/pkg/execution/genmodels/models.gen.go
index 05e2fa7bb46..c54f0f629f1 100644
--- a/go-sdk/pkg/execution/genmodels/models.gen.go
+++ b/go-sdk/pkg/execution/genmodels/models.gen.go
@@ -1890,26 +1890,26 @@ type TriggerKwargs map[string]interface{}
 
 type VersionData map[string]interface{}
 
+type TaskInstanceState string
+
 const TaskInstanceStateAwaitingInput TaskInstanceState = "awaiting_input"
 const TaskInstanceStateDeferred TaskInstanceState = "deferred"
 const TaskInstanceStateSkipped TaskInstanceState = "skipped"
 const TaskInstanceStateUpstreamFailed TaskInstanceState = "upstream_failed"
 const TaskInstanceStateUpForReschedule TaskInstanceState = "up_for_reschedule"
 const TaskInstanceStateUpForRetry TaskInstanceState = "up_for_retry"
-const TaskInstanceStateFailed TaskInstanceState = "failed"
 
+const TaskInstanceStateFailed TaskInstanceState = "failed"
 const TaskInstanceStateRestarting TaskInstanceState = "restarting"
 const TaskInstanceStateSuccess TaskInstanceState = "success"
 const TaskInstanceStateRunning TaskInstanceState = "running"
-const TaskInstanceStateQueued TaskInstanceState = "queued"
 
 type TaskOutlets []AssetProfile
 
+const TaskInstanceStateQueued TaskInstanceState = "queued"
 const TaskInstanceStateScheduled TaskInstanceState = "scheduled"
 const TaskInstanceStateRemoved TaskInstanceState = "removed"
 
-type TaskInstanceState string
-
 // Variable schema for responses with fields that are needed for Runtime.
 type VariableResponse struct {
        // Key corresponds to the JSON schema field "key".
diff --git a/go-sdk/schema/supervisor-schema.json 
b/go-sdk/schema/supervisor-schema.json
index 08c7b3a734d..5158c33fd2e 100644
--- a/go-sdk/schema/supervisor-schema.json
+++ b/go-sdk/schema/supervisor-schema.json
@@ -1555,9 +1555,6 @@
               },
               "type": "object"
             },
-            {
-              "type": "string"
-            },
             {
               "type": "null"
             }
diff --git a/java-sdk/sdk/schema/schema.json b/java-sdk/sdk/schema/schema.json
index 08c7b3a734d..5158c33fd2e 100644
--- a/java-sdk/sdk/schema/schema.json
+++ b/java-sdk/sdk/schema/schema.json
@@ -1555,9 +1555,6 @@
               },
               "type": "object"
             },
-            {
-              "type": "string"
-            },
             {
               "type": "null"
             }
diff --git a/scripts/ci/prek/check_security_doc_constants.py 
b/scripts/ci/prek/check_security_doc_constants.py
index 05e59ba89bf..cf49e41f202 100755
--- a/scripts/ci/prek/check_security_doc_constants.py
+++ b/scripts/ci/prek/check_security_doc_constants.py
@@ -94,7 +94,7 @@ CORE_DESCRIPTIONS: dict[tuple[str, str], str] = {
     ("api", "secret_key"): "API secret key for log token signing",
     ("api_auth", "jwt_secret"): "JWT signing key (symmetric mode)",
     ("core", "asset_manager_kwargs"): "Asset manager credentials",
-    ("core", "fernet_key"): "Fernet encryption key for connections/variables 
at rest",
+    ("core", "fernet_key"): "Fernet encryption key for connections, variables 
and trigger kwargs at rest",
     ("database", "sql_alchemy_conn"): "Metadata database connection string",
     ("database", "sql_alchemy_conn_async"): "Async metadata database 
connection string",
     ("database", "sql_alchemy_engine_args"): "SQLAlchemy engine parameters 
(may contain credentials)",
diff --git a/task-sdk/src/airflow/sdk/api/datamodels/_generated.py 
b/task-sdk/src/airflow/sdk/api/datamodels/_generated.py
index 9caf2853ab7..8ec9ba2f4b2 100644
--- a/task-sdk/src/airflow/sdk/api/datamodels/_generated.py
+++ b/task-sdk/src/airflow/sdk/api/datamodels/_generated.py
@@ -598,7 +598,7 @@ class TIDeferredStatePayload(BaseModel):
     )
     state: Annotated[Literal["deferred"], Field(title="State")] = "deferred"
     classpath: Annotated[str, Field(title="Classpath")]
-    trigger_kwargs: Annotated[dict[str, JsonValue | None] | str | None, 
Field(title="Trigger Kwargs")] = None
+    trigger_kwargs: Annotated[dict[str, JsonValue | None] | None, 
Field(title="Trigger Kwargs")] = None
     trigger_timeout: Annotated[timedelta | None, Field(title="Trigger 
Timeout")] = None
     queue: Annotated[str | None, Field(title="Queue")] = None
     next_method: Annotated[str, Field(title="Next Method")]
diff --git a/task-sdk/src/airflow/sdk/definitions/dag.py 
b/task-sdk/src/airflow/sdk/definitions/dag.py
index b0e227c5c85..4a7083965b1 100644
--- a/task-sdk/src/airflow/sdk/definitions/dag.py
+++ b/task-sdk/src/airflow/sdk/definitions/dag.py
@@ -1575,9 +1575,7 @@ def _run_task(
                 log.info("[DAG TEST] running trigger in line")
                 # trigger_kwargs need to be deserialized before passing to the
                 # trigger class since they are in serde encoded format.
-                # Ignore needed to convince mypy that trigger_kwargs is a dict
-                # or a str because its unable to infer JsonValue.
-                kwargs = deserialize(msg.trigger_kwargs)  # type: 
ignore[type-var]
+                kwargs = deserialize(msg.trigger_kwargs)
                 if TYPE_CHECKING:
                     assert isinstance(kwargs, dict)
                 trigger = import_string(msg.classpath)(**kwargs)
diff --git a/task-sdk/src/airflow/sdk/execution_time/schema/schema.json 
b/task-sdk/src/airflow/sdk/execution_time/schema/schema.json
index 08c7b3a734d..5158c33fd2e 100644
--- a/task-sdk/src/airflow/sdk/execution_time/schema/schema.json
+++ b/task-sdk/src/airflow/sdk/execution_time/schema/schema.json
@@ -1555,9 +1555,6 @@
               },
               "type": "object"
             },
-            {
-              "type": "string"
-            },
             {
               "type": "null"
             }
diff --git 
a/task-sdk/src/airflow/sdk/execution_time/schema/versions/__init__.py 
b/task-sdk/src/airflow/sdk/execution_time/schema/versions/__init__.py
index a6cbc03f253..2b43603b6ac 100644
--- a/task-sdk/src/airflow/sdk/execution_time/schema/versions/__init__.py
+++ b/task-sdk/src/airflow/sdk/execution_time/schema/versions/__init__.py
@@ -46,6 +46,7 @@ def get_bundle() -> VersionBundle:
         AddRegionCoordinatesToSupervisorTaskInstance,
         AddRetryReasonToTaskState,
     )
+    from airflow.sdk.execution_time.schema.versions.v2026_12_01 import 
RemoveStringTriggerKwargsFromDeferTask
     from airflow.sdk.execution_time.schema.versions.v2027_02_28 import (
         AddExecutionTimeoutToSupervisorTIRunContext,
         AddExternalClearTargetToSucceedTask,
@@ -62,6 +63,7 @@ def get_bundle() -> VersionBundle:
             MakeSupervisorVariableValueNonNullable,
             AddXComBackendErrorType,
         ),
+        Version("2026-12-01", RemoveStringTriggerKwargsFromDeferTask),
         Version(
             "2026-10-30",
             AddArgBindingsToSupervisorTIRunContext,
diff --git 
a/task-sdk/src/airflow/sdk/execution_time/schema/versions/v2026_12_01.py 
b/task-sdk/src/airflow/sdk/execution_time/schema/versions/v2026_12_01.py
new file mode 100644
index 00000000000..ab2f667f3ae
--- /dev/null
+++ b/task-sdk/src/airflow/sdk/execution_time/schema/versions/v2026_12_01.py
@@ -0,0 +1,42 @@
+# 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.
+"""Supervisor schema version 2026-12-01."""
+
+from __future__ import annotations
+
+from cadwyn import VersionChange, schema
+from pydantic import JsonValue
+
+from airflow.sdk.api.datamodels._generated import TIDeferredStatePayload
+
+
+class RemoveStringTriggerKwargsFromDeferTask(VersionChange):
+    """
+    Stop accepting ``trigger_kwargs`` as a string in ``DeferTask``.
+
+    The supervisor-schema mirror of the execution API's 
``RemoveStringTriggerKwargs``.
+    """
+
+    description = __doc__
+
+    instructions_to_migrate_to_previous_version = (
+        # DeferTask inherits the field from the generated 
TIDeferredStatePayload, and Cadwyn only
+        # changes a field on the class that declares it.
+        schema(TIDeferredStatePayload)
+        .field("trigger_kwargs")
+        .had(type=dict[str, JsonValue | None] | str | None),
+    )
diff --git a/task-sdk/tests/task_sdk/execution_time/schema/test_migrator.py 
b/task-sdk/tests/task_sdk/execution_time/schema/test_migrator.py
index 5b7569262cb..ea8266796c3 100644
--- a/task-sdk/tests/task_sdk/execution_time/schema/test_migrator.py
+++ b/task-sdk/tests/task_sdk/execution_time/schema/test_migrator.py
@@ -65,6 +65,7 @@ from airflow.sdk.api.datamodels._generated import (
 )
 from airflow.sdk.exceptions import ErrorType
 from airflow.sdk.execution_time.comms import (
+    DeferTask,
     ErrorResponse,
     GetXCom,
     GetXComCount,
@@ -162,6 +163,40 @@ def test_put_variable_value_from_older_runtime_is_kept():
     assert upgraded["value"] == "x"
 
 
[email protected](
+    ("trigger_kwargs", "accepted"),
+    [
+        pytest.param({"key": "value"}, True, id="dict"),
+        pytest.param('{"key": "value"}', False, id="string"),
+    ],
+)
+def test_defer_task_trigger_kwargs_from_older_runtime(trigger_kwargs, 
accepted):
+    body = {
+        "type": "DeferTask",
+        "classpath": "my-classpath",
+        "trigger_kwargs": trigger_kwargs,
+        "next_method": "execute_callback",
+    }
+
+    if accepted:
+        upgraded = get_schema_version_migrator().upgrade(body, DeferTask, 
"2026-10-30")
+        assert upgraded["trigger_kwargs"] == trigger_kwargs
+    else:
+        with pytest.raises(ValidationError):
+            get_schema_version_migrator().upgrade(body, DeferTask, 
"2026-10-30")
+
+
+def test_defer_task_trigger_kwargs_is_string_only_before_2026_12_01():
+    from airflow.sdk.execution_time.schema.versions import bundle
+
+    versioned = generate_versioned_models(bundle)
+    fields = {"classpath": "my-classpath", "trigger_kwargs": "{}", 
"next_method": "execute_callback"}
+
+    assert versioned["2026-10-30"][DeferTask](**fields).trigger_kwargs == "{}"
+    with pytest.raises(ValidationError):
+        versioned["2026-12-01"][DeferTask](**fields)
+
+
 @pytest.mark.parametrize(
     ("model", "extra"),
     [
diff --git a/ts-sdk/schema/supervisor-schema.json 
b/ts-sdk/schema/supervisor-schema.json
index 08c7b3a734d..5158c33fd2e 100644
--- a/ts-sdk/schema/supervisor-schema.json
+++ b/ts-sdk/schema/supervisor-schema.json
@@ -1555,9 +1555,6 @@
               },
               "type": "object"
             },
-            {
-              "type": "string"
-            },
             {
               "type": "null"
             }
diff --git a/ts-sdk/src/generated/supervisor.ts 
b/ts-sdk/src/generated/supervisor.ts
index db7e0ce1b73..615b35ac5b2 100644
--- a/ts-sdk/src/generated/supervisor.ts
+++ b/ts-sdk/src/generated/supervisor.ts
@@ -329,12 +329,9 @@ export type Type18 = "DagRunResult";
 export type Type19 = "DagRunStateResult";
 export type State2 = "deferred";
 export type Classpath = string;
-export type TriggerKwargs =
-  | {
-      [k: string]: JsonValue | null;
-    }
-  | string
-  | null;
+export type TriggerKwargs = {
+  [k: string]: JsonValue | null;
+} | null;
 export type TriggerTimeout = string | null;
 export type Queue1 = string | null;
 export type NextMethod2 = string;

Reply via email to