authentik.blueprints.v1.hash

Blueprint hashing

 1"""Blueprint hashing"""
 2
 3from collections.abc import Generator
 4from hashlib import sha512
 5from os import getenv
 6from pathlib import Path
 7from typing import Any
 8
 9from django.utils.crypto import salted_hmac
10from yaml import load
11from yaml.error import YAMLError
12
13from authentik.blueprints.v1.common import BlueprintLoader, Env, File, YAMLTag
14
15
16def iter_external_tags(
17    value: Any, ancestors: frozenset[int] = frozenset()
18) -> Generator[Env | File]:
19    """Find all `!Env` and `!File` tags in a loaded blueprint, including tags used as
20    arguments of other tags. A node is not descended into again below itself; a node
21    reached by several routes is visited once per route."""
22    if id(value) in ancestors:
23        return
24    ancestors = ancestors | {id(value)}
25    if isinstance(value, Env | File):
26        yield value
27    if isinstance(value, dict):
28        children = value.values()
29    elif isinstance(value, list | tuple):
30        children = value
31    elif isinstance(value, YAMLTag):
32        children = vars(value).values()
33    else:
34        return
35    for child in children:
36        yield from iter_external_tags(child, ancestors)
37
38
39# One byte where a readable value contributes a 64-byte digest
40MISSING_VALUE_MARKER = b"\0"
41
42
43def blueprint_hash(content: str) -> str:
44    """Hash a blueprint's content and the current values of its `!Env` and `!File` tags.
45    The values are keyed with the secret key, as the hash is visible in the API and a
46    plain hash of a short secret could be brute-forced."""
47    hasher = sha512(content.encode())
48    try:
49        raw_blueprint = load(content, BlueprintLoader)
50    except YAMLError:
51        return hasher.hexdigest()
52    values = salted_hmac("goauthentik.io/blueprints/v1/external-values", b"", algorithm="sha512")
53    has_values = False
54    for tag in iter_external_tags(raw_blueprint):
55        # Mapping-node tags have no key or path; nested tags cannot be resolved here
56        if isinstance(tag, Env):
57            key = getattr(tag, "key", None)
58            if not isinstance(key, str):
59                continue
60            try:
61                env = getenv(key)
62            except ValueError:
63                env = None
64            value = None if env is None else env.encode(errors="surrogateescape")
65        else:
66            path = getattr(tag, "path", None)
67            if not isinstance(path, str):
68                continue
69            try:
70                value = Path(path).read_bytes()
71            except OSError, ValueError:
72                value = None
73        has_values = True
74        # A missing value still takes its place in the sequence, so a value that goes
75        # missing while another appears cannot leave the hash unchanged
76        values.update(MISSING_VALUE_MARKER if value is None else sha512(value).digest())
77    if has_values:
78        hasher.update(values.digest())
79    return hasher.hexdigest()
def iter_external_tags( value: Any, ancestors: frozenset[int] = frozenset()) -> Generator[authentik.blueprints.v1.common.Env | authentik.blueprints.v1.common.File]:
17def iter_external_tags(
18    value: Any, ancestors: frozenset[int] = frozenset()
19) -> Generator[Env | File]:
20    """Find all `!Env` and `!File` tags in a loaded blueprint, including tags used as
21    arguments of other tags. A node is not descended into again below itself; a node
22    reached by several routes is visited once per route."""
23    if id(value) in ancestors:
24        return
25    ancestors = ancestors | {id(value)}
26    if isinstance(value, Env | File):
27        yield value
28    if isinstance(value, dict):
29        children = value.values()
30    elif isinstance(value, list | tuple):
31        children = value
32    elif isinstance(value, YAMLTag):
33        children = vars(value).values()
34    else:
35        return
36    for child in children:
37        yield from iter_external_tags(child, ancestors)

Find all !Env and !File tags in a loaded blueprint, including tags used as arguments of other tags. A node is not descended into again below itself; a node reached by several routes is visited once per route.

MISSING_VALUE_MARKER = b'\x00'
def blueprint_hash(content: str) -> str:
44def blueprint_hash(content: str) -> str:
45    """Hash a blueprint's content and the current values of its `!Env` and `!File` tags.
46    The values are keyed with the secret key, as the hash is visible in the API and a
47    plain hash of a short secret could be brute-forced."""
48    hasher = sha512(content.encode())
49    try:
50        raw_blueprint = load(content, BlueprintLoader)
51    except YAMLError:
52        return hasher.hexdigest()
53    values = salted_hmac("goauthentik.io/blueprints/v1/external-values", b"", algorithm="sha512")
54    has_values = False
55    for tag in iter_external_tags(raw_blueprint):
56        # Mapping-node tags have no key or path; nested tags cannot be resolved here
57        if isinstance(tag, Env):
58            key = getattr(tag, "key", None)
59            if not isinstance(key, str):
60                continue
61            try:
62                env = getenv(key)
63            except ValueError:
64                env = None
65            value = None if env is None else env.encode(errors="surrogateescape")
66        else:
67            path = getattr(tag, "path", None)
68            if not isinstance(path, str):
69                continue
70            try:
71                value = Path(path).read_bytes()
72            except OSError, ValueError:
73                value = None
74        has_values = True
75        # A missing value still takes its place in the sequence, so a value that goes
76        # missing while another appears cannot leave the hash unchanged
77        values.update(MISSING_VALUE_MARKER if value is None else sha512(value).digest())
78    if has_values:
79        hasher.update(values.digest())
80    return hasher.hexdigest()

Hash a blueprint's content and the current values of its !Env and !File tags. The values are keyed with the secret key, as the hash is visible in the API and a plain hash of a short secret could be brute-forced.