# Copyright 2024 The Debusine Developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.

"""Utilities used by debusine.signing."""

from pathlib import Path

from django.core.exceptions import ImproperlyConfigured

from nacl.exceptions import CryptoError
from nacl.public import PrivateKey


def read_private_key(private_key_path: Path) -> PrivateKey:
    """Read a NaCl private key."""
    try:
        if private_key_path.stat().st_mode & 0o077:
            raise ImproperlyConfigured(
                f"Permission too open for {private_key_path}. "
                f"Make sure that the file is not accessible by group or others."
            )
        private_key_bytes = private_key_path.read_bytes()
    except OSError as e:
        raise ImproperlyConfigured(f"Cannot read {private_key_path}: {e}")
    try:
        return PrivateKey(private_key_bytes)
    except CryptoError as e:
        raise ImproperlyConfigured(
            f"Cannot load key from {private_key_path}: {e}"
        )
