1#
2# Licensed to the Apache Software Foundation (ASF) under one
3# or more contributor license agreements. See the NOTICE file
4# distributed with this work for additional information
5# regarding copyright ownership. The ASF licenses this file
6# to you under the Apache License, Version 2.0 (the
7# "License"); you may not use this file except in compliance
8# with the License. You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing,
13# software distributed under the License is distributed on an
14# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15# KIND, either express or implied. See the License for the
16# specific language governing permissions and limitations
17# under the License.
18from __future__ import annotations
19
20import logging
21from functools import cache
22from typing import Protocol
23
24from airflow.configuration import conf
25from airflow.exceptions import AirflowException
26
27log = logging.getLogger(__name__)
28
29
30class FernetProtocol(Protocol):
31 """This class is only used for TypeChecking (for IDEs, mypy, etc)."""
32
33 is_encrypted: bool
34
35 def decrypt(self, msg: bytes | str, ttl: int | None = None) -> bytes:
36 """Decrypt with Fernet."""
37 ...
38
39 def encrypt(self, msg: bytes) -> bytes:
40 """Encrypt with Fernet."""
41 ...
42
43
44class _NullFernet:
45 """
46 A "Null" encryptor class that doesn't encrypt or decrypt but that presents a similar interface to Fernet.
47
48 The purpose of this is to make the rest of the code not have to know the
49 difference, and to only display the message once, not 20 times when
50 `airflow db migrate` is run.
51 """
52
53 is_encrypted = False
54
55 def decrypt(self, msg: bytes | str, ttl: int | None = None) -> bytes:
56 """Decrypt with Fernet."""
57 if isinstance(msg, bytes):
58 return msg
59 if isinstance(msg, str):
60 return msg.encode("utf-8")
61 raise ValueError(f"Expected bytes or str, got {type(msg)}")
62
63 def encrypt(self, msg: bytes) -> bytes:
64 """Encrypt with Fernet."""
65 return msg
66
67
68class _RealFernet:
69 """
70 A wrapper around the real Fernet to set is_encrypted to True.
71
72 This class is only used internally to avoid changing the interface of
73 the get_fernet function.
74 """
75
76 from cryptography.fernet import Fernet, MultiFernet
77
78 is_encrypted = True
79
80 def __init__(self, fernet: MultiFernet):
81 self._fernet = fernet
82
83 def decrypt(self, msg: bytes | str, ttl: int | None = None) -> bytes:
84 """Decrypt with Fernet."""
85 return self._fernet.decrypt(msg, ttl)
86
87 def encrypt(self, msg: bytes) -> bytes:
88 """Encrypt with Fernet."""
89 return self._fernet.encrypt(msg)
90
91 def rotate(self, msg: bytes | str) -> bytes:
92 """Rotate the Fernet key for the given message."""
93 return self._fernet.rotate(msg)
94
95
96@cache
97def get_fernet() -> FernetProtocol:
98 """
99 Deferred load of Fernet key.
100
101 This function could fail either because Cryptography is not installed
102 or because the Fernet key is invalid.
103
104 :return: Fernet object
105 :raises: airflow.exceptions.AirflowException if there's a problem trying to load Fernet
106 """
107 from cryptography.fernet import Fernet, MultiFernet
108
109 try:
110 fernet_key = conf.get("core", "FERNET_KEY")
111 if not fernet_key:
112 log.warning("empty cryptography key - values will not be stored encrypted.")
113 return _NullFernet()
114
115 fernet = MultiFernet([Fernet(fernet_part.encode("utf-8")) for fernet_part in fernet_key.split(",")])
116 return _RealFernet(fernet)
117 except (ValueError, TypeError) as value_error:
118 raise AirflowException(f"Could not create Fernet object: {value_error}")