You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "ucaeon (via GitHub)" <gi...@apache.org> on 2026/09/09 16:11:27 UTC
[PR] Add declarative configuration for FAB custom roles [airflow]
ucaeon opened a new pull request, #72820:
URL: https://github.com/apache/airflow/pull/72820
## Summary
The FAB provider currently has no configuration for provisioning custom roles during API server startup. Deployments must create them through the UI or CLI separately from their Airflow configuration.
This PR adds `[fab] custom_roles` to create missing roles with their declared permissions. Existing roles are skipped, preserving changes made through the UI or CLI. This follows the same-name skip behavior of `airflow roles import`.
Existing FAB creation helpers commit each operation individually. Reusing them could leave a role with incomplete permissions after a failure, and subsequent initialization would skip that role because it already exists.
## Change
- Add `[fab] custom_roles`, defaulting to `{}`, with support for `AIRFLOW__FAB__CUSTOM_ROLES`.
- Validate the entire configuration before creating any configured role, including entries for existing and built-in roles.
- Create missing custom roles after default-role synchronization in `sync_roles()`.
- Skip existing roles and warn when built-in role names are configured.
- Commit each new role and its permission assignments in one transaction.
- Document configuration, initialization behavior, and the distinction between declared permissions and existing FAB permission maintenance.
Example:
```ini
[fab]
custom_roles = {"PythonTester": [{"action": "can_read", "resource": "DAGs"}], "Analyst": []}
```
Permission entries contain exactly `action` and `resource`, using actual FAB names such as `can_read` and `DAGs`. Duplicate permission pairs are applied once.
The creation path reuses lookup helpers but avoids the existing helpers that commit individual writes. If creation fails, the current role's transaction is rolled back; roles successfully created earlier remain committed.
If another process creates the same role first, that role is skipped without adding permissions. Conflicts on concurrently created shared actions, resources, or permissions are checked after rollback and retried from the beginning of role creation, with at most three attempts. Other failures are propagated.
`bulk_sync_roles()` is not reused for configured roles because it can add permissions to existing roles.
## Behavior change
API server startup applies the configuration when `[fab] update_fab_perms` is enabled. Explicitly running `airflow sync-perm` also applies it, regardless of that flag.
Changing or removing a configured role does not update or delete an existing database role. Deleting a configured role from the database allows it to be recreated during the next initialization.
An empty permission list declares no permissions, but normal FAB initialization still grants custom roles `can_read` on `Website`. Existing default-role and permission maintenance remains unchanged.
This PR does not make roles read-only in the UI, create users, or assign roles to users. Resource names remain ordinary strings; the documentation recommends `DAG(access_control=...)` for access to individual Dags.
## Tests
- Missing roles are created with their declared permissions, including empty lists and duplicate permission entries.
- Existing roles retain manually modified permissions.
- Invalid configuration fails before any configured role is created, including invalid entries for existing or built-in roles.
- Failures during permission creation or before commit leave no incomplete role or newly created permission objects, while preserving previously committed data.
- Two independent database sessions creating the same role with different permissions retain only the winning role's permissions, repeated five times on both PostgreSQL and MySQL.
- Concurrent creation of shared actions, resources, and permissions retries successfully on PostgreSQL and MySQL.
- Startup respects `update_fab_perms`, while explicit role synchronization applies the configuration independently of the flag.
Tested locally with Breeze using Python 3.10:
- FAB and `common.compat` unit tests on SQLite: **855 passed, 9 skipped**.
- Custom-role tests on PostgreSQL: **46 passed**.
- Custom-role tests on MySQL: **46 passed**.
Regular and manual static checks passed, including formatting, linting, provider type checks, and provider metadata validation.
closes: #38347
---
##### Was generative AI tooling used to co-author this PR?
- [x] Yes — Codex (GPT-6)
Generated-by: Codex (GPT-6) following [[the guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#gen-ai-assisted-contributions)](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#gen-ai-assisted-contributions)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add declarative configuration for FAB custom roles [airflow]
Posted by "ucaeon (via GitHub)" <gi...@apache.org>.
ucaeon commented on code in PR #72820:
URL: https://github.com/apache/airflow/pull/72820#discussion_r3985420885
##########
providers/fab/src/airflow/providers/fab/auth_manager/security_manager/override.py:
##########
@@ -1241,11 +1241,112 @@ def sync_roles(self) -> None:
# Sync the default roles (Admin, Viewer, User, Op, public) with related permissions
self.bulk_sync_roles(self.ROLE_CONFIGS)
+ self.create_roles_from_config()
+
self.add_homepage_access_to_custom_roles()
# init existing roles, the rest role could be created through UI.
self.update_admin_permission()
self.clean_perms()
+ def _get_custom_roles_config(self) -> dict[str, list[tuple[str, str]]]:
+ config = conf.getjson("fab", "custom_roles", fallback={})
+ if not isinstance(config, dict):
+ raise AirflowConfigException("[fab] custom_roles must be a JSON object")
+
+ roles: dict[str, list[tuple[str, str]]] = {}
+ for name, items in config.items():
+ if not isinstance(name, str) or not name.strip() or len(name) > 64:
+ raise AirflowConfigException("[fab] custom_roles role names must contain 1 to 64 characters")
+ if not isinstance(items, list):
+ raise AirflowConfigException(f"[fab] custom_roles[{name!r}] must be a list")
+ perms: set[tuple[str, str]] = set()
+ for index, item in enumerate(items):
+ location = f"[fab] custom_roles[{name!r}][{index}]"
+ if not isinstance(item, dict) or item.keys() != {"action", "resource"}:
+ raise AirflowConfigException(f"{location} must contain only 'action' and 'resource'")
+ for key, limit in (("action", 100), ("resource", 250)):
+ value = item[key]
+ if not isinstance(value, str) or not value.strip() or len(value) > limit:
+ raise AirflowConfigException(
+ f"{location}.{key} must be a non-empty string of at most {limit} characters"
+ )
+ perms.add((item["action"], item["resource"]))
+ roles[name] = sorted(perms)
+ return roles
+
+ def create_roles_from_config(self) -> None:
+ """Create missing configured roles, preserving permissions on existing roles."""
+ roles = self._get_custom_roles_config()
+ for name, perms in roles.items():
+ if name in EXISTING_ROLES:
+ log.warning("Skipping built-in role '%s' in [fab] custom_roles", name)
+ continue
+ self._create_role_from_config(name, perms)
+
+ def _create_role_from_config(self, name: str, perms: list[tuple[str, str]]) -> None:
+ # FAB's public creation helpers commit individually; a configured role must
+ # become visible only after all its declared permissions have been attached.
+ for attempt in range(3):
+ conflict: tuple[str, ...] | None = None
+ try:
+ if self.find_role(name) is not None:
+ return
+ role = self.role_model()
+ role.name = name
+ role.permissions = []
+ self.session.add(role)
+ self.session.flush()
+
+ for action_name, resource_name in perms:
+ perm = self.get_permission(action_name, resource_name)
+ if perm is None:
+ action = self.get_action(action_name)
+ if action is None:
+ conflict = ("action", action_name)
+ action = self.action_model()
Review Comment:
Thanks for pointing this out!
I've updated the implementation in `1e3179cf1d` to validate `action` and `resource` names against existing FAB database entries before creating any configured roles.
Unknown names now raise a configuration error instead of creating new actions or resources. The names are validated independently, so a new permission combination is still allowed when both names already exist.
I've also updated the documentation and tests. The targeted tests passed on SQLite, PostgreSQL, and MySQL.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add declarative configuration for FAB custom roles [airflow]
Posted by "boring-cyborg[bot] (via GitHub)" <gi...@apache.org>.
boring-cyborg[bot] commented on PR #72820:
URL: https://github.com/apache/airflow/pull/72820#issuecomment-5636700112
Awesome work, congrats on your first merged pull request! You are invited to check our [Issue Tracker](https://github.com/apache/airflow/issues) for additional contributions.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add declarative configuration for FAB custom roles [airflow]
Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on code in PR #72820:
URL: https://github.com/apache/airflow/pull/72820#discussion_r3982749205
##########
providers/fab/src/airflow/providers/fab/auth_manager/security_manager/override.py:
##########
@@ -1241,11 +1241,112 @@ def sync_roles(self) -> None:
# Sync the default roles (Admin, Viewer, User, Op, public) with related permissions
self.bulk_sync_roles(self.ROLE_CONFIGS)
+ self.create_roles_from_config()
+
self.add_homepage_access_to_custom_roles()
# init existing roles, the rest role could be created through UI.
self.update_admin_permission()
self.clean_perms()
+ def _get_custom_roles_config(self) -> dict[str, list[tuple[str, str]]]:
+ config = conf.getjson("fab", "custom_roles", fallback={})
+ if not isinstance(config, dict):
+ raise AirflowConfigException("[fab] custom_roles must be a JSON object")
+
+ roles: dict[str, list[tuple[str, str]]] = {}
+ for name, items in config.items():
+ if not isinstance(name, str) or not name.strip() or len(name) > 64:
+ raise AirflowConfigException("[fab] custom_roles role names must contain 1 to 64 characters")
+ if not isinstance(items, list):
+ raise AirflowConfigException(f"[fab] custom_roles[{name!r}] must be a list")
+ perms: set[tuple[str, str]] = set()
+ for index, item in enumerate(items):
+ location = f"[fab] custom_roles[{name!r}][{index}]"
+ if not isinstance(item, dict) or item.keys() != {"action", "resource"}:
+ raise AirflowConfigException(f"{location} must contain only 'action' and 'resource'")
+ for key, limit in (("action", 100), ("resource", 250)):
+ value = item[key]
+ if not isinstance(value, str) or not value.strip() or len(value) > limit:
+ raise AirflowConfigException(
+ f"{location}.{key} must be a non-empty string of at most {limit} characters"
+ )
+ perms.add((item["action"], item["resource"]))
+ roles[name] = sorted(perms)
+ return roles
+
+ def create_roles_from_config(self) -> None:
+ """Create missing configured roles, preserving permissions on existing roles."""
+ roles = self._get_custom_roles_config()
+ for name, perms in roles.items():
+ if name in EXISTING_ROLES:
+ log.warning("Skipping built-in role '%s' in [fab] custom_roles", name)
+ continue
+ self._create_role_from_config(name, perms)
+
+ def _create_role_from_config(self, name: str, perms: list[tuple[str, str]]) -> None:
+ # FAB's public creation helpers commit individually; a configured role must
+ # become visible only after all its declared permissions have been attached.
+ for attempt in range(3):
+ conflict: tuple[str, ...] | None = None
+ try:
+ if self.find_role(name) is not None:
+ return
+ role = self.role_model()
+ role.name = name
+ role.permissions = []
+ self.session.add(role)
+ self.session.flush()
+
+ for action_name, resource_name in perms:
+ perm = self.get_permission(action_name, resource_name)
+ if perm is None:
+ action = self.get_action(action_name)
+ if action is None:
+ conflict = ("action", action_name)
+ action = self.action_model()
Review Comment:
We might want to validate the name of action and resource to avoid feeding garbage in the DB
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add declarative configuration for FAB custom roles [airflow]
Posted by "ucaeon (via GitHub)" <gi...@apache.org>.
ucaeon commented on code in PR #72820:
URL: https://github.com/apache/airflow/pull/72820#discussion_r3985420885
##########
providers/fab/src/airflow/providers/fab/auth_manager/security_manager/override.py:
##########
@@ -1241,11 +1241,112 @@ def sync_roles(self) -> None:
# Sync the default roles (Admin, Viewer, User, Op, public) with related permissions
self.bulk_sync_roles(self.ROLE_CONFIGS)
+ self.create_roles_from_config()
+
self.add_homepage_access_to_custom_roles()
# init existing roles, the rest role could be created through UI.
self.update_admin_permission()
self.clean_perms()
+ def _get_custom_roles_config(self) -> dict[str, list[tuple[str, str]]]:
+ config = conf.getjson("fab", "custom_roles", fallback={})
+ if not isinstance(config, dict):
+ raise AirflowConfigException("[fab] custom_roles must be a JSON object")
+
+ roles: dict[str, list[tuple[str, str]]] = {}
+ for name, items in config.items():
+ if not isinstance(name, str) or not name.strip() or len(name) > 64:
+ raise AirflowConfigException("[fab] custom_roles role names must contain 1 to 64 characters")
+ if not isinstance(items, list):
+ raise AirflowConfigException(f"[fab] custom_roles[{name!r}] must be a list")
+ perms: set[tuple[str, str]] = set()
+ for index, item in enumerate(items):
+ location = f"[fab] custom_roles[{name!r}][{index}]"
+ if not isinstance(item, dict) or item.keys() != {"action", "resource"}:
+ raise AirflowConfigException(f"{location} must contain only 'action' and 'resource'")
+ for key, limit in (("action", 100), ("resource", 250)):
+ value = item[key]
+ if not isinstance(value, str) or not value.strip() or len(value) > limit:
+ raise AirflowConfigException(
+ f"{location}.{key} must be a non-empty string of at most {limit} characters"
+ )
+ perms.add((item["action"], item["resource"]))
+ roles[name] = sorted(perms)
+ return roles
+
+ def create_roles_from_config(self) -> None:
+ """Create missing configured roles, preserving permissions on existing roles."""
+ roles = self._get_custom_roles_config()
+ for name, perms in roles.items():
+ if name in EXISTING_ROLES:
+ log.warning("Skipping built-in role '%s' in [fab] custom_roles", name)
+ continue
+ self._create_role_from_config(name, perms)
+
+ def _create_role_from_config(self, name: str, perms: list[tuple[str, str]]) -> None:
+ # FAB's public creation helpers commit individually; a configured role must
+ # become visible only after all its declared permissions have been attached.
+ for attempt in range(3):
+ conflict: tuple[str, ...] | None = None
+ try:
+ if self.find_role(name) is not None:
+ return
+ role = self.role_model()
+ role.name = name
+ role.permissions = []
+ self.session.add(role)
+ self.session.flush()
+
+ for action_name, resource_name in perms:
+ perm = self.get_permission(action_name, resource_name)
+ if perm is None:
+ action = self.get_action(action_name)
+ if action is None:
+ conflict = ("action", action_name)
+ action = self.action_model()
Review Comment:
Thanks for pointing this out!
I've updated the implementation in 1e3179cf1d to validate action and resource names against the existing FAB database entries before creating any configured roles.
Unknown names now raise a configuration error instead of creating new actions or resources. The names are validated independently so a new permission combination is still allowed when both names already exist.
I've also updated the documentation and tests. The targeted tests passed on SQLite, PostgreSQL, and MySQL.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add declarative configuration for FAB custom roles [airflow]
Posted by "ucaeon (via GitHub)" <gi...@apache.org>.
ucaeon commented on code in PR #72820:
URL: https://github.com/apache/airflow/pull/72820#discussion_r3985420885
##########
providers/fab/src/airflow/providers/fab/auth_manager/security_manager/override.py:
##########
@@ -1241,11 +1241,112 @@ def sync_roles(self) -> None:
# Sync the default roles (Admin, Viewer, User, Op, public) with related permissions
self.bulk_sync_roles(self.ROLE_CONFIGS)
+ self.create_roles_from_config()
+
self.add_homepage_access_to_custom_roles()
# init existing roles, the rest role could be created through UI.
self.update_admin_permission()
self.clean_perms()
+ def _get_custom_roles_config(self) -> dict[str, list[tuple[str, str]]]:
+ config = conf.getjson("fab", "custom_roles", fallback={})
+ if not isinstance(config, dict):
+ raise AirflowConfigException("[fab] custom_roles must be a JSON object")
+
+ roles: dict[str, list[tuple[str, str]]] = {}
+ for name, items in config.items():
+ if not isinstance(name, str) or not name.strip() or len(name) > 64:
+ raise AirflowConfigException("[fab] custom_roles role names must contain 1 to 64 characters")
+ if not isinstance(items, list):
+ raise AirflowConfigException(f"[fab] custom_roles[{name!r}] must be a list")
+ perms: set[tuple[str, str]] = set()
+ for index, item in enumerate(items):
+ location = f"[fab] custom_roles[{name!r}][{index}]"
+ if not isinstance(item, dict) or item.keys() != {"action", "resource"}:
+ raise AirflowConfigException(f"{location} must contain only 'action' and 'resource'")
+ for key, limit in (("action", 100), ("resource", 250)):
+ value = item[key]
+ if not isinstance(value, str) or not value.strip() or len(value) > limit:
+ raise AirflowConfigException(
+ f"{location}.{key} must be a non-empty string of at most {limit} characters"
+ )
+ perms.add((item["action"], item["resource"]))
+ roles[name] = sorted(perms)
+ return roles
+
+ def create_roles_from_config(self) -> None:
+ """Create missing configured roles, preserving permissions on existing roles."""
+ roles = self._get_custom_roles_config()
+ for name, perms in roles.items():
+ if name in EXISTING_ROLES:
+ log.warning("Skipping built-in role '%s' in [fab] custom_roles", name)
+ continue
+ self._create_role_from_config(name, perms)
+
+ def _create_role_from_config(self, name: str, perms: list[tuple[str, str]]) -> None:
+ # FAB's public creation helpers commit individually; a configured role must
+ # become visible only after all its declared permissions have been attached.
+ for attempt in range(3):
+ conflict: tuple[str, ...] | None = None
+ try:
+ if self.find_role(name) is not None:
+ return
+ role = self.role_model()
+ role.name = name
+ role.permissions = []
+ self.session.add(role)
+ self.session.flush()
+
+ for action_name, resource_name in perms:
+ perm = self.get_permission(action_name, resource_name)
+ if perm is None:
+ action = self.get_action(action_name)
+ if action is None:
+ conflict = ("action", action_name)
+ action = self.action_model()
Review Comment:
Thanks for pointing this out!
I've updated the implementation in `1e3179cf1d` to validate `action` and `resource` names against existing FAB database entries before creating any configured roles.
Unknown names now raise a configuration error instead of creating new actions or resources. The names are validated independently, so a new permission combination is still allowed when both names already exist.
I've also updated the documentation and tests. The targeted tests passed on SQLite, PostgreSQL, and MySQL.
Thanks again for the helpful feedback!☺️
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add declarative configuration for FAB custom roles [airflow]
Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck merged PR #72820:
URL: https://github.com/apache/airflow/pull/72820
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org