flask_rbac_icdc package
Submodules
flask_rbac_icdc.rbac module
This module provides role-based access control (RBAC) functionality for Flask applications.
The RBAC module validates the role of the subject based on the role name provided in the authentication headers. The role name is validated against the roles defined in the RBAC policy configuration.
Example:
rbac = RBAC(rbac_config_path, Account)
If it is necessary to implement more advanced conditional role assignment, you can override the RbacAccount.get_role method to achieve this.
- exception flask_rbac_icdc.rbac.PermissionException(message)[source]
Bases:
Exception
Raised when subject trying to perform an operation without the access rights
- class flask_rbac_icdc.rbac.RBAC(config_path, account_model, use_operator_group=True)[source]
Bases:
object
RBAC class to handle role-based access control.
- policy
The RBAC policy configuration loaded from the YAML file.
- Type:
dict
- roles
Enum of roles defined in the policy configuration.
- Type:
Enum
- account_model
The account model class to use for account operations.
- Type:
- use_operator_group
Flag to enable operator group functionality, is True by default.
- Type:
bool
- allow(action)[source]
A decorator to enforce role-based access control for an endpoint.
This decorator validates that the requesting subject has the required permissions to access the endpoint by checking: 1. Account name from x-auth-account header 2. Role from x-auth-role header 3. Owner from x-auth-user header 4. Policy configuration for the current role from the RBAC configuration
- Parameters:
action (str) -- The action to check permissions for, in format "object.permission"
- Returns:
Decorated function that includes RBAC permission check
- Return type:
function
- Raises:
Unauthorized 401 -- If account name or role headers are missing/invalid.
Forbidden 403 -- If the subject does not have permission for the requested action.
Example:
@app.route('/users', methods=['GET']) @rbac.allow("users.read") def get_user(subject): # Function implementation pass
- load_config(config_path)[source]
Load RBAC configuration from a YAML file.
This function reads the role-based access control configuration from a YAML file and returns the parsed configuration as a dictionary. The configuration defines roles, their permissions for different resources, and any filters that should be applied when accessing those resources.
- Parameters:
config_file (str) -- Path to the YAML configuration file.
- Returns:
Parsed RBAC configuration containing roles, permissions, and filters.
- Return type:
dict
- Raises:
FileNotFoundError -- If the specified configuration file does not exist.
yaml.YAMLError -- If the configuration file contains invalid YAML syntax.
- class flask_rbac_icdc.rbac.RbacAccount[source]
Bases:
object
Abstract base class that defines the interface for RBAC account objects.
This class serves as a contract for implementing role-based access control (RBAC) account functionality. Any concrete implementation must provide properties for account identification and name, as well as a method to determine the subject's role based on authentication information.
Note
All subclasses must implement the abstract methods and properties defined here.
Example:
class Account(db.Model, RbacAccount): __tablename__ = "accounts" object_name = "accounts" id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(64), unique=True, nullable=False) # ...Other account properties here @classmethod def get_by_name(cls, account_name: str) -> Optional["Account"]: return cls.query.filter_by(name=account_name).first() def get_role(self, requested_role: str) -> str: operator = is_operator(self.name, requested_role) if requested_role == "operator" and not operator: raise PermissionException("You are not operator") if operator: return "operator" return requested_role
- abstractmethod classmethod get_by_name(account_name)[source]
Retrieve an account by its name.
- Parameters:
account_name (str) -- The name of the account to retrieve.
- Returns:
Account instanse or None
- Return type:
Example:
@classmethod def get_by_name(cls, account_name: str) -> Optional["Account"]: return cls.query.filter_by(name=account_name).first()
- abstractmethod get_role(requested_role)[source]
Determines the effective role of the account based on provided authentication information.
Note
This is an abstract method that can be implemented by subclasses.
This method can be used for more complex checks on a requested role or for conditional granting of another role for the subject.
- Parameters:
requested_role (str) -- The role identifier provided in authentication headers.
- Returns:
The granted role value to be used for this subject.
- Return type:
str
- Raises:
PermissionException -- This method should raise this error, if the provided role is invalid or not allowed for this account.
- abstract property id: int
The ID of the account.
- abstract property name: str
The name of the account.
- class flask_rbac_icdc.rbac.Subject(account, role, owner, policy)[source]
Bases:
object
Class represents a subject in the system, combining their account, role, and access permissions. It facilitates role-based access control (RBAC) by validating whether a user can perform a specific action and defining scope-based access restrictions.
- account
The account associated with this subject.
- Type:
- account_id
The ID of the account.
- Type:
int
- account_name
The name of the account.
- Type:
str
- role
The role assigned to this subject.
- Type:
Enum
- owner
The owner identifier for this subject.
- Type:
str
- policy
The policy configuration applied to this subject.
- Type:
dict
- filters(object_name)[source]
Get the filters that should be applied for this subject when accessing a specific object.
Filters are used to restrict the scope of data access based on the subject's role and attributes.
- Parameters:
object_name (str) -- The name of the object to get filters for.
- Returns:
A dictionary of filter key-value pairs to be applied when accessing the object.
- Return type:
dict
Example:
# Example implementation in a SQLAlchemy base model class Base(db.Model): __abstract__ = True @property @abstractmethod def object_name(self): pass @classmethod def filtered(cls, subject: "Subject"): "Apply scope filters" return cls.query.filter_by(**subject.filters(cls.object_name))
Module contents
- exception flask_rbac_icdc.PermissionException(message)[source]
Bases:
Exception
Raised when subject trying to perform an operation without the access rights
- class flask_rbac_icdc.RBAC(config_path, account_model, use_operator_group=True)[source]
Bases:
object
RBAC class to handle role-based access control.
- policy
The RBAC policy configuration loaded from the YAML file.
- Type:
dict
- roles
Enum of roles defined in the policy configuration.
- Type:
Enum
- account_model
The account model class to use for account operations.
- Type:
- use_operator_group
Flag to enable operator group functionality, is True by default.
- Type:
bool
- allow(action)[source]
A decorator to enforce role-based access control for an endpoint.
This decorator validates that the requesting subject has the required permissions to access the endpoint by checking: 1. Account name from x-auth-account header 2. Role from x-auth-role header 3. Owner from x-auth-user header 4. Policy configuration for the current role from the RBAC configuration
- Parameters:
action (str) -- The action to check permissions for, in format "object.permission"
- Returns:
Decorated function that includes RBAC permission check
- Return type:
function
- Raises:
Unauthorized 401 -- If account name or role headers are missing/invalid.
Forbidden 403 -- If the subject does not have permission for the requested action.
Example:
@app.route('/users', methods=['GET']) @rbac.allow("users.read") def get_user(subject): # Function implementation pass
- load_config(config_path)[source]
Load RBAC configuration from a YAML file.
This function reads the role-based access control configuration from a YAML file and returns the parsed configuration as a dictionary. The configuration defines roles, their permissions for different resources, and any filters that should be applied when accessing those resources.
- Parameters:
config_file (str) -- Path to the YAML configuration file.
- Returns:
Parsed RBAC configuration containing roles, permissions, and filters.
- Return type:
dict
- Raises:
FileNotFoundError -- If the specified configuration file does not exist.
yaml.YAMLError -- If the configuration file contains invalid YAML syntax.
- class flask_rbac_icdc.RbacAccount[source]
Bases:
object
Abstract base class that defines the interface for RBAC account objects.
This class serves as a contract for implementing role-based access control (RBAC) account functionality. Any concrete implementation must provide properties for account identification and name, as well as a method to determine the subject's role based on authentication information.
Note
All subclasses must implement the abstract methods and properties defined here.
Example:
class Account(db.Model, RbacAccount): __tablename__ = "accounts" object_name = "accounts" id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(64), unique=True, nullable=False) # ...Other account properties here @classmethod def get_by_name(cls, account_name: str) -> Optional["Account"]: return cls.query.filter_by(name=account_name).first() def get_role(self, requested_role: str) -> str: operator = is_operator(self.name, requested_role) if requested_role == "operator" and not operator: raise PermissionException("You are not operator") if operator: return "operator" return requested_role
- abstractmethod classmethod get_by_name(account_name)[source]
Retrieve an account by its name.
- Parameters:
account_name (str) -- The name of the account to retrieve.
- Returns:
Account instanse or None
- Return type:
Example:
@classmethod def get_by_name(cls, account_name: str) -> Optional["Account"]: return cls.query.filter_by(name=account_name).first()
- abstractmethod get_role(requested_role)[source]
Determines the effective role of the account based on provided authentication information.
Note
This is an abstract method that can be implemented by subclasses.
This method can be used for more complex checks on a requested role or for conditional granting of another role for the subject.
- Parameters:
requested_role (str) -- The role identifier provided in authentication headers.
- Returns:
The granted role value to be used for this subject.
- Return type:
str
- Raises:
PermissionException -- This method should raise this error, if the provided role is invalid or not allowed for this account.
- abstract property id: int
The ID of the account.
- abstract property name: str
The name of the account.
- class flask_rbac_icdc.Subject(account, role, owner, policy)[source]
Bases:
object
Class represents a subject in the system, combining their account, role, and access permissions. It facilitates role-based access control (RBAC) by validating whether a user can perform a specific action and defining scope-based access restrictions.
- account
The account associated with this subject.
- Type:
- account_id
The ID of the account.
- Type:
int
- account_name
The name of the account.
- Type:
str
- role
The role assigned to this subject.
- Type:
Enum
- owner
The owner identifier for this subject.
- Type:
str
- policy
The policy configuration applied to this subject.
- Type:
dict
- filters(object_name)[source]
Get the filters that should be applied for this subject when accessing a specific object.
Filters are used to restrict the scope of data access based on the subject's role and attributes.
- Parameters:
object_name (str) -- The name of the object to get filters for.
- Returns:
A dictionary of filter key-value pairs to be applied when accessing the object.
- Return type:
dict
Example:
# Example implementation in a SQLAlchemy base model class Base(db.Model): __abstract__ = True @property @abstractmethod def object_name(self): pass @classmethod def filtered(cls, subject: "Subject"): "Apply scope filters" return cls.query.filter_by(**subject.filters(cls.object_name))