WhakerPy 1.0

https://sourceforge.net/projects/whakerpy/

Module whakerpy.httpd

Class FileAccessChecker

Description

Specialized class for checking file permissions on a specified file.

This class provides methods to check if a user, group, or owner has specific access rights to a given file, such as read permissions.

Available only for UNIX-based platforms. Instantiating the class on another platform raises an EnvironmentError.

Example
 >>> checker = FileAccessChecker('/path/to/file')
 >>> checker.read_allowed(who='owner')
 > True
 >>> checker.read_allowed(who='group')
 > False

Constructor

Initialize the FileAccessChecker with a specific file.

The initialization ensures that the system supports group-related functionalities by checking for the availability of the 'grp' module.

Parameters
  • filename: (str) Path to the file to check.
Raises
  • EnvironmentError: If 'grp' module is not available (invalid platform)
  • FileNotFoundError: If the file does not exist.
View Source
def __init__(self, filename: str):
    """Initialize the FileAccessChecker with a specific file.

    The initialization ensures that the system supports group-related
    functionalities by checking for the availability of the 'grp' module.

    :param filename: (str) Path to the file to check.
    :raises: EnvironmentError: If 'grp' module is not available (invalid platform)
    :raises: FileNotFoundError: If the file does not exist.

    """
    if grp is None:
        raise EnvironmentError("The 'grp' module is not available on this platform.")
    self.__filename = filename
    if os.path.exists(self.__filename) is False:
        raise FileNotFoundError(f'File not found: {self.__filename}')
    self.__file_stat = os.stat(self.__filename)

Public functions

get_filename

Return the examined filename.

View Source
def get_filename(self):
    """Return the examined filename."""
    return self.__filename

read_allowed

Check if the given persons have read permission on the file.

"who" is one of the UnixPermission() or a comibation with '&' or '|' (but not both). For example 'group&others' checks if both group and others have read access; 'owner|group' checks if either owner or group has read access; 'owner&group&others' checks if all have read access. Forbidden combination is for example: 'owner&group|others'

Parameters
  • who: (str) Can be 'others', 'group', or 'owner', or a combination.
Returns
  • (bool) True if read permission is granted, False otherwise.
Raises
  • ValueError: If 'who' contains invalid roles or syntax.
View Source
def read_allowed(self, who: str='others') -> bool:
    """Check if the given persons have read permission on the file.

        "who" is one of the UnixPermission() or a comibation with '&' or '|'
        (but not both). For example 'group&others' checks if both group
        and others have read access; 'owner|group' checks if either owner
        or group has read access; 'owner&group&others' checks if all have
        read access. Forbidden combination is for example:
        'owner&group|others'

        :param who: (str) Can be 'others', 'group', or 'owner', or a combination.
        :return: (bool) True if read permission is granted, False otherwise.
        :raises: ValueError: If 'who' contains invalid roles or syntax.

        """
    with UnixPermissions() as permissions:
        valid_roles = list(permissions)
        role_pattern = '|'.join((re.escape(role) for role in valid_roles))
        expression_pattern = f'^\\s*({role_pattern})(\\s*[\\&\\|]\\s*({role_pattern}))*\\s*$'
        if not re.match(expression_pattern, who):
            raise ValueError(f"Invalid 'who' value or syntax: {who}. Must contain only {valid_roles} with '&' or '|'.")
    if '&' in who and '|' in who:
        raise ValueError("Combination of '&' and '|' is forbidden in the 'who' parameter.")
    or_conditions = who.split('|')
    for or_condition in or_conditions:
        and_roles = or_condition.split('&')
        if all((self.__check_permission_for_role(role.strip()) for role in and_roles)):
            return True
    return False

Protected functions

__check_permission_for_role

Helper function to check permissions for a single role.

Parameters
  • role: (str) Who to check permissions for: 'others', 'group', or 'owner'.
View Source
def __check_permission_for_role(self, role: str) -> bool:
    """Helper function to check permissions for a single role.

        :param role: (str) Who to check permissions for: 'others', 'group', or 'owner'.

        """
    current_uid = os.geteuid()
    current_gid = os.getegid()
    mode = self.__file_stat.st_mode
    owner_uid = self.__file_stat.st_uid
    group_gid = self.__file_stat.st_gid
    if role == 'owner' and current_uid == owner_uid:
        return bool(mode & stat.S_IRUSR)
    elif role == 'group' and current_gid == group_gid:
        return bool(mode & stat.S_IRGRP)
    elif role == 'others':
        return bool(mode & stat.S_IROTH)
    return False