|
| 1 | +# Keycloak Direct OIDC Authentication for Airflow |
| 2 | +# Airflow authenticates directly with Keycloak (no proxy layer) |
| 3 | + |
| 4 | +import os |
| 5 | +import logging |
| 6 | +from airflow.www.security import AirflowSecurityManager |
| 7 | +from flask_appbuilder.security.manager import AUTH_OAUTH |
| 8 | + |
| 9 | +log = logging.getLogger(__name__) |
| 10 | + |
| 11 | +# Enable OAuth authentication |
| 12 | +AUTH_TYPE = AUTH_OAUTH |
| 13 | + |
| 14 | +# Keycloak OIDC Configuration |
| 15 | +OIDC_ISSUER = "${keycloak_provider_url}" |
| 16 | +OIDC_CLIENT_ID = "${keycloak_client_id}" |
| 17 | + |
| 18 | +# Client secret must be provided via environment variable |
| 19 | +OIDC_CLIENT_SECRET = os.getenv("OIDC_CLIENT_SECRET", "CHANGE_ME") |
| 20 | + |
| 21 | +# OAuth provider configuration |
| 22 | +OAUTH_PROVIDERS = [ |
| 23 | + { |
| 24 | + "name": "keycloak", |
| 25 | + "icon": "fa-key", |
| 26 | + "token_key": "access_token", |
| 27 | + "remote_app": { |
| 28 | + "client_id": OIDC_CLIENT_ID, |
| 29 | + "client_secret": OIDC_CLIENT_SECRET, |
| 30 | + "api_base_url": OIDC_ISSUER, |
| 31 | + "client_kwargs": { |
| 32 | + "scope": "openid email profile groups" |
| 33 | + }, |
| 34 | + "access_token_url": f"{OIDC_ISSUER}/protocol/openid-connect/token", |
| 35 | + "authorize_url": f"{OIDC_ISSUER}/protocol/openid-connect/auth", |
| 36 | + "request_token_url": None, |
| 37 | + "server_metadata_url": f"{OIDC_ISSUER}/.well-known/openid-configuration", |
| 38 | + }, |
| 39 | + } |
| 40 | +] |
| 41 | + |
| 42 | +# Auto-register users on first login (only if they have approved Keycloak groups) |
| 43 | +# Users without approved groups will be rejected during authentication |
| 44 | +AUTH_USER_REGISTRATION = True |
| 45 | +AUTH_USER_REGISTRATION_ROLE = "Viewer" # Not used - role determined by Keycloak group mapping |
| 46 | + |
| 47 | +# Role mapping configuration |
| 48 | +class CustomSecurityManager(AirflowSecurityManager): |
| 49 | + """ |
| 50 | + Custom security manager to map Keycloak groups to Airflow roles. |
| 51 | + |
| 52 | + IMPORTANT: Users must have at least one approved Keycloak group to access Airflow. |
| 53 | + Users without approved groups will be denied access during authentication. |
| 54 | + """ |
| 55 | + |
| 56 | + def oauth_user_info(self, provider, response): |
| 57 | + """ |
| 58 | + Get user info from OAuth provider and map groups to roles. |
| 59 | + |
| 60 | + Args: |
| 61 | + provider: OAuth provider name |
| 62 | + response: OAuth response containing tokens |
| 63 | + |
| 64 | + Returns: |
| 65 | + Dictionary with user information |
| 66 | + """ |
| 67 | + if provider == "keycloak": |
| 68 | + import json |
| 69 | + import base64 |
| 70 | + |
| 71 | + # Log the OAuth response structure (without sensitive token values) |
| 72 | + log.info(f"OAuth callback from provider: {provider}") |
| 73 | + log.info(f"OAuth response keys: {list(response.keys())}") |
| 74 | + |
| 75 | + # Get access token |
| 76 | + access_token = response.get("access_token") |
| 77 | + if not access_token: |
| 78 | + log.error(f"No access token in OAuth response. Response keys: {list(response.keys())}") |
| 79 | + log.error(f"Full response (for debugging): {response}") |
| 80 | + return {} |
| 81 | + |
| 82 | + try: |
| 83 | + # Decode JWT to get user info and groups |
| 84 | + # JWT structure: header.payload.signature |
| 85 | + parts = access_token.split('.') |
| 86 | + if len(parts) != 3: |
| 87 | + log.error(f"Invalid JWT format. Expected 3 parts, got {len(parts)}") |
| 88 | + return {} |
| 89 | + |
| 90 | + payload = parts[1] |
| 91 | + # Add padding if needed |
| 92 | + payload += '=' * (4 - len(payload) % 4) |
| 93 | + decoded = json.loads(base64.urlsafe_b64decode(payload)) |
| 94 | + |
| 95 | + # Log what we received from Keycloak (useful for debugging) |
| 96 | + log.info(f"JWT payload keys: {list(decoded.keys())}") |
| 97 | + log.info(f"Available claims: username={decoded.get('preferred_username')}, email={decoded.get('email')}") |
| 98 | + log.info(f"Groups in token: {decoded.get('groups', [])}") |
| 99 | + |
| 100 | + # Extract user information (with fallbacks for different claim names) |
| 101 | + username = decoded.get("preferred_username") or decoded.get("username") or decoded.get("sub") |
| 102 | + email = decoded.get("email", f"{username}@example.com") |
| 103 | + first_name = decoded.get("given_name") or decoded.get("first_name") or username |
| 104 | + last_name = decoded.get("family_name") or decoded.get("last_name") or "" |
| 105 | + |
| 106 | + # Groups might be in different formats depending on Keycloak mapper config |
| 107 | + groups = decoded.get("groups", []) |
| 108 | + if isinstance(groups, str): |
| 109 | + groups = [groups] |
| 110 | + |
| 111 | + # Some Keycloak configs put groups in realm_access or resource_access |
| 112 | + if not groups and "realm_access" in decoded: |
| 113 | + groups = decoded["realm_access"].get("roles", []) |
| 114 | + if not groups and "resource_access" in decoded: |
| 115 | + client_access = decoded["resource_access"].get(OIDC_CLIENT_ID, {}) |
| 116 | + groups = client_access.get("roles", []) |
| 117 | + |
| 118 | + user_info = { |
| 119 | + "username": username, |
| 120 | + "email": email, |
| 121 | + "first_name": first_name, |
| 122 | + "last_name": last_name, |
| 123 | + "groups": groups, |
| 124 | + } |
| 125 | + |
| 126 | + log.info(f"Keycloak user login: username={user_info['username']}, email={user_info['email']}, groups={user_info['groups']}") |
| 127 | + |
| 128 | + # Map groups to roles |
| 129 | + user_info["role_keys"] = self._map_groups_to_roles(user_info["groups"]) |
| 130 | + log.info(f"Mapped to Airflow roles: {user_info['role_keys']}") |
| 131 | + |
| 132 | + return user_info |
| 133 | + |
| 134 | + except Exception as e: |
| 135 | + log.error(f"Error decoding access token: {e}", exc_info=True) |
| 136 | + log.error(f"Token (first 50 chars): {access_token[:50]}...") |
| 137 | + return {} |
| 138 | + |
| 139 | + return {} |
| 140 | + |
| 141 | + def _map_groups_to_roles(self, keycloak_groups): |
| 142 | + """ |
| 143 | + Map Keycloak groups to Airflow roles. |
| 144 | + |
| 145 | + Role mapping (configured via Terraform): |
| 146 | +%{ for group, roles in keycloak_role_mapping ~} |
| 147 | + - ${group} → ${join(", ", roles)} |
| 148 | +%{ endfor ~} |
| 149 | + |
| 150 | + Users with multiple groups get the highest priority role. |
| 151 | + Priority: Admin > Op > User > Viewer > Public |
| 152 | + |
| 153 | + IMPORTANT: Users without any approved Keycloak groups will be rejected. |
| 154 | + |
| 155 | + Args: |
| 156 | + keycloak_groups: List of Keycloak group names from OIDC token |
| 157 | + |
| 158 | + Returns: |
| 159 | + List of Airflow role names |
| 160 | + |
| 161 | + Raises: |
| 162 | + Exception: If user has no approved Keycloak groups (access denied) |
| 163 | + """ |
| 164 | + # Keycloak group to Airflow role mapping (from Terraform configuration) |
| 165 | + group_role_mapping = { |
| 166 | +%{ for group, roles in keycloak_role_mapping ~} |
| 167 | + '${group}': '${roles[0]}', |
| 168 | +%{ endfor ~} |
| 169 | + } |
| 170 | + |
| 171 | + log.debug(f"Group role mapping: {group_role_mapping}") |
| 172 | + log.debug(f"User's Keycloak groups: {keycloak_groups}") |
| 173 | + |
| 174 | + # Role priority (higher index = higher priority) |
| 175 | + role_priority = ['Public', 'Viewer', 'User', 'Op', 'Admin'] |
| 176 | + |
| 177 | + # Find highest priority role from user's groups |
| 178 | + highest_role_name = None |
| 179 | + highest_priority = -1 |
| 180 | + |
| 181 | + for group in keycloak_groups: |
| 182 | + # Handle group paths (e.g., "/airflow/admin" or "airflow_admin") |
| 183 | + group_name = group.split('/')[-1] # Get last part of path |
| 184 | + |
| 185 | + if group_name in group_role_mapping: |
| 186 | + role_name = group_role_mapping[group_name] |
| 187 | + if role_name in role_priority: |
| 188 | + priority = role_priority.index(role_name) |
| 189 | + if priority > highest_priority: |
| 190 | + highest_priority = priority |
| 191 | + highest_role_name = role_name |
| 192 | + log.info(f"Group '{group}' maps to role '{role_name}' (priority {priority})") |
| 193 | + |
| 194 | + # Return the highest priority role |
| 195 | + if highest_role_name: |
| 196 | + return [highest_role_name] |
| 197 | + else: |
| 198 | + # Reject users who don't have any approved Keycloak groups |
| 199 | + log.error(f"Access denied: User has no approved Keycloak groups. User groups: {keycloak_groups}") |
| 200 | + log.error("User must be assigned to one of these Keycloak groups to access Airflow:") |
| 201 | + log.error(f" Approved groups: {list(group_role_mapping.keys())}") |
| 202 | + raise Exception( |
| 203 | + "Access denied: You are not assigned to any approved Keycloak groups. " |
| 204 | + "Please contact your administrator to request access." |
| 205 | + ) |
| 206 | + |
| 207 | +# Set the custom security manager |
| 208 | +SECURITY_MANAGER_CLASS = CustomSecurityManager |
| 209 | + |
| 210 | +# Security settings |
| 211 | +WTF_CSRF_ENABLED = True |
| 212 | +WTF_CSRF_TIME_LIMIT = None |
| 213 | + |
| 214 | +# Session configuration |
| 215 | +PERMANENT_SESSION_LIFETIME = 28800 # 8 hours |
| 216 | + |
| 217 | +log.info("Airflow webserver configured for direct Keycloak OIDC authentication") |
| 218 | +log.info(f"Keycloak provider: {OIDC_ISSUER}") |
| 219 | +log.info(f"Keycloak client: {OIDC_CLIENT_ID}") |
0 commit comments