Page MenuHomePhabricator

Implement K8s JWT authentication for Airflow 3 REST API
Closed, ResolvedPublic

Description

Airflow 3 has dropped support for pluggable token authentication. Also Airflow 3 deprecated direct database access, so we need to use REST API for database access. Finally, we are planning to sunset Kerberos in DPE. With this, we need a new authentication approach for the REST API access in Airflow.

Airflow 3 is using its own JWT token system to autheniticate its API. It is used for both REST API (public facing, and also used for Web UI), and for Execution API (used internally). In order to access any API, client need to present JWT token as Authorization: Bearer $token HTTP header. Public REST API users are able to obtain the token via /auth/token API endpoint, by presenting some form of credentials. Deployer has to choose an Auth manager that will handle user/role management, as well as this login flow. Airflow 3 also has internal mechanism to issue JWT token for Execution API usage. Note that Airflow 3 is using a JWT, it is JWT shaped, but not interoperable. It is impossible to use another JWT provider as a mean for Airflow 3 to authenticate API access. The configuration parameters available in the documentation are for tuning its behaviour for scalability and different security models, and not for plugging another JWT system.

We use FabAuthManager as it provides integration with OIDC (that is used for CAS-SSO), as well as it provides a simple username/password authentication that is useful for airflow-devenv. Both methods are able to issue a token that is then used for the REST API authentication. Airflow 2 had support for pluggable backends that we used to accept Kerberos tokens. While the documentation is still there, the callsites seems to be removed, so we can't use this anymore.

However, FabAuthManager provides the documented way to extend the login flow, /auth/token. It is implemented as a FabAuthManager.create_token, which can override and extend the original behaviour. I propose that we use K8s Service Account JWT token to login and exchange it to Airflow JWT token. It extends the standard Token aquisition flow, by replacing login and password with K8s Service Account JWT token.

What is K8s Service Account JWT token? It is a JWT token that issued by kubelet that allow bearer of this token to authenticate to either K8s API (if the audience of the token is K8s API server, it is default behaviour, Airflow in fact uses this to create pods from within Airflow), or to anuthenticate third-party service in OIDC-like fashion (if audience is set to any other appropriate value) across pods where the Kubernetes is only issuing the tokens and providing a way to validate online and offline that the token is bound to a Service Account, Namespace, and sometimes, a pod. Hashicorp Vault and RadosGW are using this. Again, K8s JWT token can't be used to completely replace Airflow JWT token system. OIDC support in K8s is also very limited, so we can't integrate K8s as an OIDC/OAuth provider.

To authenticate a K8s JWT token, server need to obtain JWKS URL from well-known K8s API url, https://kubernetes.default.svc/.well-known/openid-configuration, then obtain set of public keys from jwks, and decode the presented token with those keys. In pseudocode, it looks like this

# initialise the jwks client
token_file = "/var/run/secrets/kubernetes.io/serviceaccount/token"
with open(token_file, "r") as f:
    server_token = f.read().strip()
headers = {"Authorization": f"Bearer {server_token}"}

host = "https://kubernetes.default.svc"

jwks_uri = requests.get(
    f"{host}/.well-known/openid-configuration",
    headers=headers,  # k8s permissions can be relaxed here to make this endpoint public
).json()["jwks_uri"]
jwks_client = jwt.PyJWKClient(jwks_uri, headers=headers)
# verify presented token
signing_key = jwks_client.get_signing_key_from_jwt(oauth_token)
decoded = jwt.decode(oauth_token, signing_key, options={"verify_aud": False})  # TODO: verify audience, e.g. audience "airflow-test-k8s.discovery.wmnet"

Token contains information such as audience, namespace, node/pod, service account, expiration, and combined subject.

{
    "aud": [
        "https://dse-k8s-ctrl.svc.eqiad.wmnet:6443"
    ],
    "exp": 1820410823,
    ...
    "kubernetes.io": {
        "namespace": "airflow-test-k8s",
        "node": {
            "name": "dse-k8s-worker1009.eqiad.wmnet",
        },
        "pod": {
            "name": "airflow-scheduler-5dfc65b7dd-f4n5v",
        },
        "serviceaccount": {
            "name": "airflow",
        },
    },
    "sub": "system:serviceaccount:airflow-test-k8s:airflow"
}

Now we can use token subject (e.g. "system:serviceaccount:airflow-test-k8s:airflow") as an Airflow user username, and set of bounds, e.g. namespace and service account as a clues to define a role, using a standard user auto-creation and role-mapping mechanism we use for SSO. E.g. I propose generate role-keys using namespaces, so we can permit access between namespaces as well as within namespaces.

subject = decoded["sub"]
role_keys = [f"kubernetes.io:namespace:{decoded["kubernetes.io"]["namespace"]}"]
userinfo = {
    "username": subject,
    "email": f"{subject}@email.notfound",
    "role_keys": role_keys,
}
user = self.security_manager.auth_user_oauth(userinfo, rotate_session_id=False)  # this will auto-create a user
AUTH_ROLES_MAPPING = {
    "kubernetes.io:namespace:airflow-test-k8s": ["Admin"],
    "kubernetes.io:namespace:airflow-analytics-test" ["Op"],
    ...
}

On a client-side, we will need to add another projected volume serviceAccountToken that is scoped to airflow

spec:
  containers:
    - name: ...

      volumeMounts:
      - name: airflow-token
        mountPath: /var/run/secrets/kubernetes.io-airflow
  volumes:
  - name: airflow-token
    projected:
      defaultMode: 420
      sources:
      - serviceAccountToken:
          path: token
          expirationSeconds: 600 # 10 minutes is the minimum TTL
          audience: airflow-test-k8s.discovery.wmnet        # Must match your JWT role's `bound_audiences`

We can then read it the same way as before and exchange it to the Airflow token, see the client documentation for the details.

token_file = "/var/run/secrets/kubernetes.io-airflow/token"
with open(token_file, "r") as f:
    k8s_token = f.read().strip()

body = {"k8s_token": k8s_token}
airflow_auth = requests.post(f"{host}/auth/token", json=body).json()  # {'access_token': '...'}

configuration = airflow_client.client.Configuration(host=host)
configuration.access_token = airflow_auth['access_token']
with airflow_client.client.ApiClient(configuration) as api_client:
    api_instance = airflow_client.client.AssetApi(api_client)
    ...

Event Timeline

There is an option to use Kubernetes OIDC T435591, or even the raw API, P96394.

atsuko changed the task status from Open to In Progress.Sep 8 2026, 2:40 PM

Change #1338217 had a related patch set uploaded (by Atsuko; author: Atsuko):

[operations/deployment-charts@master] wip: pluggable authmanager

https://gerrit.wikimedia.org/r/1338217

I propose a new way to authenticate to Airflow 3 with both legacy Kerberos and new K8s ways.

I added FabAuthManager that overrides airflow.providers.fab.auth_manager.fab_auth_manager.FabAuthManager (source) and extends create_token(), which is the interface to extend /auth/token behviour. It looks into request body for gss_token and k8s_token, and uses corresponding code to validate the token and obtain the user information. There are few questions:

  1. Before deprecation, kerberos authenticator used to only pre-existing users. We can continue with this behaviour, or we can automatically create users.
  2. For K8s, there are options to validate token offline by only checking the signature, or validate token online against K8s API. The considerations are the same as with future migration from Hadoop to K8s/Radosgw. cc @BTullis
  3. This code is hardly ready for upstream, as Airflow FabAuthManager is quite rigid and hardly support pluggable authentication. I'm considering to keep this code locally, and cleaning up our authentication stack.
atsuko renamed this task from Devise and implement API authentication for Airflow 3 to Implement K8s JWT authentication for Airflow 3 REST API.Sep 10 2026, 12:56 PM
atsuko updated the task description. (Show Details)

Updated the task description with the design.

atsuko updated the task description. (Show Details)

T435591 tackles OIDC/JWKS configuration, we can enable open access to those endpoints here. However, the proposed code can also work with authenticated access.

Change #1338217 merged by jenkins-bot:

[operations/deployment-charts@master] airflow: pluggable authmanager for K8s tokens

https://gerrit.wikimedia.org/r/1338217

atsuko closed https://gitlab.wikimedia.org/repos/data-engineering/airflow-dags/-/merge_requests/2647

Draft: Using Kubernetes service account token authentication for ExternalTaskSensor instead of Kerberos