Skip to content

certified.layout — Config Directory Layout

Manages the on-disk layout of the certified configuration directory. See Configuration / Keyfile Layout for the directory structure.

config

Lookup and return the location of the certified-apis configuration directory.

Priority order is
  1. certified_config (if not None)
  2. $CERTIFIED_CONFIG (if CERTIFIED_CONFIG defined)
  3. $VIRTUAL_ENV/etc/certified (if VIRTUAL_ENV defined)
  4. /etc/certified
The return value of this function is cached,

so changes to environment variables have no effect after the first return from this function.

Parameters:

Name Type Description Default
certified_config Optional[Pstr]

if defined, this value is returned.

None
should_exist bool

require that the directory exist?

True

Raises:

Type Description
NotADirectoryError

Raised if the config does not point to a directory. If exists == False, this is only raised when the config exists, but is not a non-directory.

Source code in certified/layout.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def config(certified_config: Optional[Pstr] = None,
        should_exist: bool = True) -> Path:
    """Lookup and return the location of the certified-apis
    configuration directory.

    Priority order is:
      1. certified_config (if not None)
      2. $CERTIFIED_CONFIG (if CERTIFIED_CONFIG defined)
      3. $VIRTUAL_ENV/etc/certified (if VIRTUAL_ENV defined)
      4. /etc/certified

    Note: The return value of this function is cached,
          so changes to environment variables have
          no effect after the first return from this function.

    Args:
      certified_config: if defined, this value is returned.
      should_exist: require that the directory exist?

    Raises:
      NotADirectoryError: Raised if the config does not point to a directory.
                          If exists == False, this is only raised
                          when the config exists,
                          but is not a non-directory.

    """
    if certified_config is None:
        try:
            certified_config = os.environ["CERTIFIED_CONFIG"]
        except KeyError:
            pre = os.environ.get("VIRTUAL_ENV", "/")
            certified_config = Path(pre)/"etc"/"certified"

    p = Path(certified_config)
    if should_exist:
        if not p.is_dir():
            raise NotADirectoryError(str(p))
    else:
        if p.exists() and not p.is_dir():
            raise NotADirectoryError(str(p))
    return p

check_config

Scans the base configuration directory and returns a list of warnings and error messages.

    >>> cfg = certified.config()
    >>> warn, err = certified.check(cfg)
    >>> if len(err) > 0:
    >>>    print(f"{len(err)} errors:")
    >>>    print("

".join(err))

Source code in certified/layout.py
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def check_config(base : Path) -> Tuple[List[str], List[str]]:
    """ Scans the base configuration directory and
        returns a list of warnings and error messages.

        >>> cfg = certified.config()
        >>> warn, err = certified.check(cfg)
        >>> if len(err) > 0:
        >>>    print(f"{len(err)} errors:")
        >>>    print("\n".join(err))
    """
    warnings : List[str] = []
    errors : List[str] = []
    def error(err):
        nonlocal errors
        errors.append(err)
        return warnings, errors
    def warn(s):
        nonlocal warnings
        warnings.append(s)
    def gone(p):
        if not p.exists():
            error(f"{p} does not exist")
        elif p.is_dir():
            error(f"{p} exists, but is a directory")
        elif p.is_file():
            error(f"{p} exists, but is a file")
        error(f"{p} exists, but is neither a file nor a directory")
        return warnings, errors

    def notexist(f):
        error(f"{p} does not exist.")
    if not base.is_dir():
        return gone(base)

    for keyname in ["CA", "id"]:
        key = base/f"{keyname}.key"
        if not key.is_file():
            gone(key)
        if not is_user_only(key):
            error(f"Invalid key file permissions on {key}!")
        crt = base/f"{keyname}.crt"
        if not crt.is_file():
            gone(crt)
    if not (base/"known_clients").is_dir():
        gone(base/"known_clients")
    if not (base/"known_servers").is_dir():
        gone(base/"known_servers")

    fca = base / "CA.crt"
    ca = Blob.read(fca)
    for fself in [ base/"known_servers"/"self.crt"
                 , base/"known_clients"/"self.crt" ]:
        if fself.is_file():
            stest = Blob.read(fself)
            if ca.bytes() != stest.bytes():
                warn(f"{fself} does not match {fca}")
        else:
            warn(f"{fself} does not exist.")

    return warnings, errors