# `passlib.apache` - Apache Password Files

This module provides utilities for reading and writing Apache’s htpasswd and htdigest files; though the use of two helper classes.

Changed in version 1.6: The api for this module was updated to be more flexible, and to have less ambiguous method names. The old method and keyword names are deprecated, and will be removed in Passlib 1.8.

Changed in version 1.7: These classes will now preserve blank lines and “#” comments when updating htpasswd files; previous releases would throw a parse error.

Changed in version 1.8: A number of methods deprecated since 1.6, have been removed.

## Htpasswd Files

The `HTpasswdFile` class allows managing of htpasswd files. A quick summary of its usage:

    >>> from passlib.apache import HtpasswdFile

    >>> # when creating a new file, set to new=True, add entries, and save.
    >>> ht = HtpasswdFile("test.htpasswd", new=True)
    >>> ht.set_password("someuser", "really secret password")
    >>> ht.save()

    >>> # loading an existing file to update a password
    >>> ht = HtpasswdFile("test.htpasswd")
    >>> ht.set_password("someuser", "new secret password")
    >>> ht.save()

    >>> # examining file, verifying user's password
    >>> ht = HtpasswdFile("test.htpasswd")
    >>> ht.users()
    [ "someuser" ]
    >>> ht.check_password("someuser", "wrong password")
    False
    >>> ht.check_password("someuser", "new secret password")
    True

    >>> # making in-memory changes and exporting to string
    >>> ht = HtpasswdFile()
    >>> ht.set_password("someuser", "mypass")
    >>> ht.set_password("someuser", "anotherpass")
    >>> print ht.to_string()
    someuser:$apr1$T4f7D9ly$EobZDROnHblCNPCtrgh5i/
    anotheruser:$apr1$vBdPWvh1$GrhfbyGvN/7HalW5cS9XB1

Warning

`HtpasswdFile` currently defaults to using `apr_md5_crypt`, as this is the only htpasswd hash guaranteed to be portable across operating systems. However, for security reasons Passlib 1.7 will default to using the strongest algorithm available on the host platform (e.g. `bcrypt` or `sha256_crypt`). Applications that are relying on the old behavior should specify `HtpasswdFile(default_scheme="portable")` (new in Passlib 1.6.3).

class passlib.apache.HtpasswdFile(path=None, new=False, autosave=False, ...)

  class for reading & writing Htpasswd files.

  The class constructor accepts the following arguments:

  Parameters:

    - path (filepath) –

      Specifies path to htpasswd file, use to implicitly load from and save to.

      This class has two modes of operation:

      1. It can be “bound” to a local file by passing a `path` to the class constructor. In this case it will load the contents of the file when created, and the `load()` and `save()` methods will automatically load from and save to that file if they are called without arguments.

      2. Alternately, it can exist as an independant object, in which case `load()` and `save()` will require an explicit path to be provided whenever they are called. As well, `autosave` behavior will not be available.

         This feature is new in Passlib 1.6, and is the default if no `path` value is provided to the constructor.

      This is also exposed as a readonly instance attribute.

    - new (bool) –

      Normally, if path is specified, `HtpasswdFile` will immediately load the contents of the file. However, when creating a new htpasswd file, applications can set `new=True` so that the existing file (if any) will not be loaded.

      Added in version 1.6: This feature was previously enabled by setting `autoload=False`. That alias was removed in Passlib 1.8

    - autosave (bool) –

      Normally, any changes made to an `HtpasswdFile` instance will not be saved until `save()` is explicitly called. However, if `autosave=True` is specified, any changes made will be saved to disk immediately (assuming path has been set).

      This is also exposed as a writeable instance attribute.

    - encoding (str) –

      Optionally specify character encoding used to read/write file and hash passwords. Defaults to `utf-8`, though `latin-1` is the only other commonly encountered encoding.

      This is also exposed as a readonly instance attribute.

    - default_scheme (str) –

      Optionally specify default scheme to use when encoding new passwords.

      This can be any of the schemes with builtin Apache support, OR natively supported by the host OS’s `crypt.crypt()` function.

      - Builtin schemes include `"bcrypt"` (apache 2.4+), `"apr_md5_crypt"`, and ``"des_crypt"`.

      - Schemes commonly supported by Unix hosts include `"bcrypt"`, `"sha256_crypt"`, and `"des_crypt"`.

      In order to not have to sort out what you should use, passlib offers a number of aliases, that will resolve to the most appropriate scheme based on your needs:

      - `"portable"`, `"portable_apache_24"` – pick scheme that’s portable across hosts running apache >= 2.4. This will be the default as of Passlib 2.0.

      - `"portable_apache_22"` – pick scheme that’s portable across hosts running apache >= 2.4. This is the default up to Passlib 1.9.

      - `"host"`, `"host_apache_24"` – pick strongest scheme supported by

          apache >= 2.4 and/or host OS.

      - `"host_apache_22"` – pick strongest scheme supported by

          apache >= 2.2 and/or host OS.

      Added in version 1.6: This keyword was previously named `default`. That alias was removed in Passlib 1.8.

      Changed in version 1.6.3: Added support for `"bcrypt"`, `"sha256_crypt"`, and `"portable"` alias.

      Changed in version 1.7: Added apache 2.4 semantics, and additional aliases.

    - context (`CryptContext`) –

      `CryptContext` instance used to create and verify the hashes found in the htpasswd file. The default value is a pre-built context which supports all of the hashes officially allowed in an htpasswd file.

      This is also exposed as a readonly instance attribute.

      Warning

      This option may be used to add support for non-standard hash formats to an htpasswd file. However, the resulting file will probably not be usable by another application, and particularly not by Apache.

  ### Loading & Saving

  load(path: PathLike | None = None) → bool

    Load state from local file. If no path is specified, attempts to load from `self.path`.

    Parameters:

      path (str) – local file to load from

  load_if_changed() → bool

    Reload from `self.path` only if file has changed since last load

  load_string(data: str | bytes) → None

    Load state from unicode or bytes string, replacing current state

  save(path: PathLike | None = None) → None

    Save current state to file. If no path is specified, attempts to save to `self.path`.

  to_string() → bytes

    Export current state as a string of bytes

  ### Inspection

  users() → list[bytes | str]

    Return list of all users in database

  check_password(user, password)

    Verify password for specified user. If algorithm marked as deprecated by CryptContext, will automatically be re-hashed.

    Returns:

      - `None` if user not found.

      - `False` if user found, but password does not match.

      - `True` if user found and password matches.

    Changed in version 1.6: This method was previously called `verify`, it was renamed to prevent ambiguity with the `CryptContext` method. The old alias was removed in Passlib 1.8.

  get_hash(user)

    Return hash stored for user, or `None` if user not found.

    Changed in version 1.6: This method was previously named `find`, it was renamed for clarity. The old name was removed in Passlib 1.8.

  ### Modification

  set_password(user, password)

    Set password for user; adds user if needed.

    Returns:

      - `True` if existing user was updated.

      - `False` if user account was added.

    Changed in version 1.6: This method was previously called `update`, it was renamed to prevent ambiguity with the dictionary method. The old alias was removed in Passlib 1.8.

  delete(user)

    Delete user’s entry.

    Returns:

      - `True` if user deleted.

      - `False` if user not found.

  ### Alternate Constructors

  classmethod from_string(data: str | bytes, **kwargs: Any) → Self

    create new object from raw string.

    Parameters:

      - data (str or bytes) – database to load, as single string.

      - **kwds – all other keywords are the same as in the class constructor

  ### Attributes

  path

    Path to local file that will be used as the default for all `load()` and `save()` operations. May be written to, initialized by the path constructor keyword.

  autosave

    Writeable flag indicating whether changes will be automatically written to path.

  ### Errors

  raises ValueError:

    All of the methods in this class will raise a `ValueError` if any user name contains a forbidden character (one of `:\r\n\t\x00`), or is longer than 255 characters.

## Htdigest Files

The `HtdigestFile` class allows management of htdigest files in a similar fashion to `HtpasswdFile`.

class passlib.apache.HtdigestFile(path, default_realm=None, new=False, autosave=False, ...)

  class for reading & writing Htdigest files.

  The class constructor accepts the following arguments:

  Parameters:

    - path (filepath) –

      Specifies path to htdigest file, use to implicitly load from and save to.

      This class has two modes of operation:

      1. It can be “bound” to a local file by passing a `path` to the class constructor. In this case it will load the contents of the file when created, and the `load()` and `save()` methods will automatically load from and save to that file if they are called without arguments.

      2. Alternately, it can exist as an independant object, in which case `load()` and `save()` will require an explicit path to be provided whenever they are called. As well, `autosave` behavior will not be available.

         This feature is new in Passlib 1.6, and is the default if no `path` value is provided to the constructor.

      This is also exposed as a readonly instance attribute.

    - default_realm (str) –

      If `default_realm` is set, all the `HtdigestFile` methods that require a realm will use this value if one is not provided explicitly. If unset, they will raise an error stating that an explicit realm is required.

      This is also exposed as a writeable instance attribute.

      Added in version 1.6.

    - new (bool) –

      Normally, if path is specified, `HtdigestFile` will immediately load the contents of the file. However, when creating a new htpasswd file, applications can set `new=True` so that the existing file (if any) will not be loaded.

      Added in version 1.6: This feature was previously enabled by setting `autoload=False`. That alias was removed in Passlib 1.8

    - autosave (bool) –

      Normally, any changes made to an `HtdigestFile` instance will not be saved until `save()` is explicitly called. However, if `autosave=True` is specified, any changes made will be saved to disk immediately (assuming path has been set).

      This is also exposed as a writeable instance attribute.

    - encoding (str) –

      Optionally specify character encoding used to read/write file and hash passwords. Defaults to `utf-8`, though `latin-1` is the only other commonly encountered encoding.

      This is also exposed as a readonly instance attribute.

  ### Loading & Saving

  load(path: PathLike | None = None) → bool

    Load state from local file. If no path is specified, attempts to load from `self.path`.

    Parameters:

      path (str) – local file to load from

  load_if_changed() → bool

    Reload from `self.path` only if file has changed since last load

  load_string(data: str | bytes) → None

    Load state from unicode or bytes string, replacing current state

  save(path: PathLike | None = None) → None

    Save current state to file. If no path is specified, attempts to save to `self.path`.

  to_string() → bytes

    Export current state as a string of bytes

  ### Inspection

  realms()

    Return list of all realms in database

  users(realm=None)

    Return list of all users in specified realm.

    - uses `self.default_realm` if no realm explicitly provided.

    - returns empty list if realm not found.

  check_password(user, [realm, ]password)

    Verify password for specified user + realm.

    If `self.default_realm` has been set, this may be called with the syntax `check_password(user, password)`, otherwise it must be called with all three arguments: `check_password(user, realm, password)`.

    Returns:

      - `None` if user or realm not found.

      - `False` if user found, but password does not match.

      - `True` if user found and password matches.

    Changed in version 1.6: This method was previously called `verify`, it was renamed to prevent ambiguity with the `CryptContext` method. The old alias was removed in Passlib 1.8.

  get_hash(user, realm=None)

    Return `htdigest` hash stored for user.

    - uses `self.default_realm` if no realm explicitly provided.

    - returns `None` if user or realm not found.

    Changed in version 1.6: This method was previously named `find`, it was renamed for clarity. The old name is was removed Passlib 1.8.

  ### Modification

  set_password(user, [realm, ]password)

    Set password for user; adds user & realm if needed.

    If `self.default_realm` has been set, this may be called with the syntax `set_password(user, password)`, otherwise it must be called with all three arguments: `set_password(user, realm, password)`.

    Returns:

      - `True` if existing user was updated

      - `False` if user account added.

  delete(user, realm=None)

    Delete user’s entry for specified realm.

    if realm is not specified, uses `self.default_realm`.

    Returns:

      - `True` if user deleted,

      - `False` if user not found in realm.

  delete_realm(realm)

    Delete all users for specified realm.

    if realm is not specified, uses `self.default_realm`.

    Returns:

      number of users deleted (0 if realm not found)

  ### Alternate Constructors

  classmethod from_string(data: str | bytes, **kwargs: Any) → Self

    create new object from raw string.

    Parameters:

      - data (str or bytes) – database to load, as single string.

      - **kwds – all other keywords are the same as in the class constructor

  ### Attributes

  default_realm

    The default realm that will be used if one is not provided to methods that require it. By default this is `None`, in which case an explicit realm must be provided for every method call. Can be written to.

  path

    Path to local file that will be used as the default for all `load()` and `save()` operations. May be written to, initialized by the path constructor keyword.

  autosave

    Writeable flag indicating whether changes will be automatically written to path.

  ### Errors

  raises ValueError:

    All of the methods in this class will raise a `ValueError` if any user name or realm contains a forbidden character (one of `:\r\n\t\x00`), or is longer than 255 characters.

Footnotes

[1]

Htpasswd Manual - http://httpd.apache.org/docs/current/programs/htpasswd.html

[2]

Apache Auth Configuration - http://httpd.apache.org/docs/current/howto/auth.html