cache.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. """Implementation of caching solutions.
  2. - :py:obj:`searx.cache.ExpireCache` and its :py:obj:`searx.cache.ExpireCacheCfg`
  3. ----
  4. """
  5. from __future__ import annotations
  6. __all__ = ["ExpireCacheCfg", "ExpireCacheStats", "ExpireCache", "ExpireCacheSQLite"]
  7. import abc
  8. import dataclasses
  9. import datetime
  10. import hashlib
  11. import hmac
  12. import os
  13. import pickle
  14. import secrets
  15. import sqlite3
  16. import string
  17. import tempfile
  18. import time
  19. import typing
  20. from base64 import urlsafe_b64encode, urlsafe_b64decode
  21. import msgspec
  22. from cryptography.fernet import Fernet
  23. from cryptography.hazmat.primitives import hashes
  24. from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
  25. from searx import sqlitedb
  26. from searx import logger
  27. from searx import get_setting
  28. log = logger.getChild("cache")
  29. class ExpireCacheCfg(msgspec.Struct): # pylint: disable=too-few-public-methods
  30. """Configuration of a :py:obj:`ExpireCache` cache."""
  31. name: str
  32. """Name of the cache."""
  33. db_url: str = ""
  34. """URL of the SQLite DB, the path to the database file. If unset a default
  35. DB will be created in `/tmp/sxng_cache_{self.name}.db`"""
  36. MAX_VALUE_LEN: int = 1024 * 10
  37. """Max lenght of a *serialized* value."""
  38. MAXHOLD_TIME: int = 60 * 60 * 24 * 7 # 7 days
  39. """Hold time (default in sec.), after which a value is removed from the cache."""
  40. MAINTENANCE_PERIOD: int = 60 * 60 # 2h
  41. """Maintenance period in seconds / when :py:obj:`MAINTENANCE_MODE` is set to
  42. ``auto``."""
  43. MAINTENANCE_MODE: typing.Literal["auto", "off"] = "auto"
  44. """Type of maintenance mode
  45. ``auto``:
  46. Maintenance is carried out automatically as part of the maintenance
  47. intervals (:py:obj:`MAINTENANCE_PERIOD`); no external process is required.
  48. ``off``:
  49. Maintenance is switched off and must be carried out by an external process
  50. if required.
  51. """
  52. # encryption of the values stored in the DB
  53. password: bytes = get_setting("server.secret_key").encode() # type: ignore
  54. """Password used in case of :py:obj:`ExpireCacheCfg.ENCRYPT_VALUE` is
  55. ``True``.
  56. The default password is taken from :ref:`secret_key <server.secret_key>`.
  57. When the password is changed, the values in the cache can no longer be
  58. decrypted, which is why all values in the cache are deleted when the
  59. password is changed.
  60. """
  61. ENCRYPT_VALUE: bool = True
  62. """Encrypting the values before they are written to the DB (see:
  63. :py:obj:`ExpireCacheCfg.password`)."""
  64. def __post_init__(self):
  65. # if db_url is unset, use a default DB in /tmp/sxng_cache_{name}.db
  66. if not self.db_url:
  67. self.db_url = tempfile.gettempdir() + os.sep + f"sxng_cache_{ExpireCache.normalize_name(self.name)}.db"
  68. @dataclasses.dataclass
  69. class ExpireCacheStats:
  70. """Dataclass wich provides information on the status of the cache."""
  71. cached_items: dict[str, list[tuple[str, typing.Any, int]]]
  72. """Values in the cache mapped by table name.
  73. .. code: python
  74. {
  75. "table name": [
  76. ("foo key": "foo value", <expire>),
  77. ("bar key": "bar value", <expire>),
  78. # ...
  79. ],
  80. # ...
  81. }
  82. """
  83. def report(self):
  84. c_tables = 0
  85. c_kv = 0
  86. lines = []
  87. for table_name, kv_list in self.cached_items.items():
  88. c_tables += 1
  89. if not kv_list:
  90. lines.append(f"[{table_name:20s}] empty")
  91. continue
  92. for key, value, expire in kv_list:
  93. valid_until = datetime.datetime.fromtimestamp(expire).strftime("%Y-%m-%d %H:%M:%S")
  94. c_kv += 1
  95. lines.append(f"[{table_name:20s}] {valid_until} {key:12}" f" --> ({type(value).__name__}) {value} ")
  96. lines.append(f"number of tables: {c_tables}")
  97. lines.append(f"number of key/value pairs: {c_kv}")
  98. return "\n".join(lines)
  99. class ExpireCache(abc.ABC):
  100. """Abstract base class for the implementation of a key/value cache
  101. with expire date."""
  102. cfg: ExpireCacheCfg
  103. hmac_iterations: int = 10_000
  104. crypt_hash_property = "crypt_hash"
  105. @abc.abstractmethod
  106. def set(self, key: str, value: typing.Any, expire: int | None) -> bool:
  107. """Set *key* to *value*. To set a timeout on key use argument
  108. ``expire`` (in sec.). If expire is unset the default is taken from
  109. :py:obj:`ExpireCacheCfg.MAXHOLD_TIME`. After the timeout has expired,
  110. the key will automatically be deleted.
  111. """
  112. @abc.abstractmethod
  113. def get(self, key: str, default=None) -> typing.Any:
  114. """Return *value* of *key*. If key is unset, ``None`` is returned."""
  115. @abc.abstractmethod
  116. def maintenance(self, force: bool = False, drop_crypted: bool = False) -> bool:
  117. """Performs maintenance on the cache.
  118. ``force``:
  119. Maintenance should be carried out even if the maintenance interval has
  120. not yet been reached.
  121. ``drop_crypted``:
  122. The encrypted values can no longer be decrypted (if the password is
  123. changed), they must be removed from the cache.
  124. """
  125. @abc.abstractmethod
  126. def state(self) -> ExpireCacheStats:
  127. """Returns a :py:obj:`ExpireCacheStats`, which provides information
  128. about the status of the cache."""
  129. @staticmethod
  130. def build_cache(cfg: ExpireCacheCfg) -> ExpireCache:
  131. """Factory to build a caching instance.
  132. .. note::
  133. Currently, only the SQLite adapter is available, but other database
  134. types could be implemented in the future, e.g. a Valkey (Redis)
  135. adapter.
  136. """
  137. return ExpireCacheSQLite(cfg)
  138. @staticmethod
  139. def normalize_name(name: str) -> str:
  140. """Returns a normalized name that can be used as a file name or as a SQL
  141. table name."""
  142. _valid = "-_." + string.ascii_letters + string.digits
  143. return "".join([c for c in name if c in _valid])
  144. def derive_key(self, password: bytes, salt: bytes, iterations: int) -> bytes:
  145. """Derive a secret-key from a given password and salt."""
  146. kdf = PBKDF2HMAC(
  147. algorithm=hashes.SHA256(),
  148. length=32,
  149. salt=salt,
  150. iterations=iterations,
  151. )
  152. return urlsafe_b64encode(kdf.derive(password))
  153. def serialize(self, value: typing.Any) -> bytes:
  154. dump: bytes = pickle.dumps(value)
  155. if self.cfg.ENCRYPT_VALUE:
  156. dump = self.encrypt(dump)
  157. return dump
  158. def deserialize(self, value: bytes) -> typing.Any:
  159. if self.cfg.ENCRYPT_VALUE:
  160. value = self.decrypt(value)
  161. obj = pickle.loads(value)
  162. return obj
  163. def encrypt(self, message: bytes) -> bytes:
  164. """Encode and decode values by a method using `Fernet with password`_ where
  165. the key is derived from the password (PBKDF2HMAC_). The *password* for
  166. encryption is taken from the :ref:`server.secret_key`
  167. .. _Fernet with password: https://stackoverflow.com/a/55147077
  168. .. _PBKDF2HMAC: https://cryptography.io/en/latest/hazmat/primitives/key-derivation-functions/#pbkdf2
  169. """
  170. # Including the salt in the output makes it possible to use a random
  171. # salt value, which in turn ensures the encrypted output is guaranteed
  172. # to be fully random regardless of password reuse or message
  173. # repetition.
  174. salt = secrets.token_bytes(16) # randomly generated salt
  175. # Including the iteration count ensures that you can adjust
  176. # for CPU performance increases over time without losing the ability to
  177. # decrypt older messages.
  178. iterations = int(self.hmac_iterations)
  179. key = self.derive_key(self.cfg.password, salt, iterations)
  180. crypted_msg = Fernet(key).encrypt(message)
  181. # Put salt and iteration count on the beginning of the binary
  182. token = b"%b%b%b" % (salt, iterations.to_bytes(4, "big"), urlsafe_b64encode(crypted_msg))
  183. return urlsafe_b64encode(token)
  184. def decrypt(self, token: bytes) -> bytes:
  185. token = urlsafe_b64decode(token)
  186. # Strip salt and iteration count from the beginning of the binary
  187. salt = token[:16]
  188. iterations = int.from_bytes(token[16:20], "big")
  189. key = self.derive_key(self.cfg.password, salt, iterations)
  190. crypted_msg = urlsafe_b64decode(token[20:])
  191. message = Fernet(key).decrypt(crypted_msg)
  192. return message
  193. def secret_hash(self, name: str | bytes) -> str:
  194. """Creates a hash of the argument ``name``. The hash value is formed
  195. from the ``name`` combined with the :py:obj:`password
  196. <ExpireCacheCfg.password>`. Can be used, for example, to make the
  197. ``key`` stored in the DB unreadable for third parties."""
  198. if isinstance(name, str):
  199. name = bytes(name, encoding='utf-8')
  200. m = hmac.new(name + self.cfg.password, digestmod='sha256')
  201. return m.hexdigest()
  202. class ExpireCacheSQLite(sqlitedb.SQLiteAppl, ExpireCache):
  203. """Cache that manages key/value pairs in a SQLite DB. The DB model in the
  204. SQLite DB is implemented in abstract class :py:obj:`SQLiteAppl
  205. <searx.sqlitedb.SQLiteAppl>`.
  206. The following configurations are required / supported:
  207. - :py:obj:`ExpireCacheCfg.db_url`
  208. - :py:obj:`ExpireCacheCfg.MAXHOLD_TIME`
  209. - :py:obj:`ExpireCacheCfg.MAINTENANCE_PERIOD`
  210. - :py:obj:`ExpireCacheCfg.MAINTENANCE_MODE`
  211. - :py:obj:`ExpireCacheCfg.ENCRYPT_VALUE`
  212. """
  213. DB_SCHEMA = 1
  214. # The key/value tables will be created on demand by self.create_table
  215. DDL_CREATE_TABLES = {}
  216. CACHE_TABLE_PREFIX = "CACHE-TABLE-"
  217. def __init__(self, cfg: ExpireCacheCfg):
  218. """An instance of the SQLite expire cache is build up from a
  219. :py:obj:`config <ExpireCacheCfg>`."""
  220. self.cfg = cfg
  221. if cfg.db_url == ":memory:":
  222. log.critical("don't use SQLite DB in :memory: in production!!")
  223. super().__init__(cfg.db_url)
  224. def init(self, conn: sqlite3.Connection) -> bool:
  225. ret_val = super().init(conn)
  226. if not ret_val:
  227. return False
  228. if self.cfg.ENCRYPT_VALUE:
  229. new = hashlib.sha256(self.cfg.password).hexdigest()
  230. old = self.properties(self.crypt_hash_property)
  231. if old != new:
  232. if old is not None:
  233. log.warning("[%s] crypt token changed: drop all cache tables", self.cfg.name)
  234. self.maintenance(force=True, drop_crypted=True)
  235. self.properties.set(self.crypt_hash_property, new)
  236. return True
  237. def maintenance(self, force: bool = False, drop_crypted: bool = False) -> bool:
  238. if not force and int(time.time()) < self.next_maintenance_time:
  239. # log.debug("no maintenance required yet, next maintenance interval is in the future")
  240. return False
  241. # Prevent parallel DB maintenance cycles from other DB connections
  242. # (e.g. in multi thread or process environments).
  243. self.properties.set("LAST_MAINTENANCE", "") # hint: this (also) sets the m_time of the property!
  244. if drop_crypted:
  245. self.truncate_tables(self.table_names)
  246. return True
  247. # drop items by expire time stamp ..
  248. expire = int(time.time())
  249. with self.connect() as conn:
  250. for table in self.table_names:
  251. res = conn.execute(f"DELETE FROM {table} WHERE expire < ?", (expire,))
  252. log.debug("deleted %s keys from table %s (expire date reached)", res.rowcount, table)
  253. # Vacuuming the WALs
  254. # https://www.theunterminatedstring.com/sqlite-vacuuming/
  255. conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
  256. conn.close()
  257. return True
  258. def create_table(self, table: str) -> bool:
  259. """Create DB ``table`` if it has not yet been created, no recreates are
  260. initiated if the table already exists.
  261. """
  262. if table in self.table_names:
  263. # log.debug("key/value table %s exists in DB (no need to recreate)", table)
  264. return False
  265. log.info("key/value table '%s' NOT exists in DB -> create DB table ..", table)
  266. sql_table = "\n".join(
  267. [
  268. f"CREATE TABLE IF NOT EXISTS {table} (",
  269. " key TEXT,",
  270. " value BLOB,",
  271. f" expire INTEGER DEFAULT (strftime('%s', 'now') + {self.cfg.MAXHOLD_TIME}),",
  272. "PRIMARY KEY (key))",
  273. ]
  274. )
  275. sql_index = f"CREATE INDEX IF NOT EXISTS index_expire_{table} ON {table}(expire);"
  276. with self.connect() as conn:
  277. conn.execute(sql_table)
  278. conn.execute(sql_index)
  279. conn.close()
  280. self.properties.set(f"{self.CACHE_TABLE_PREFIX}-{table}", table)
  281. return True
  282. @property
  283. def table_names(self) -> list[str]:
  284. """List of key/value tables already created in the DB."""
  285. sql = f"SELECT value FROM properties WHERE name LIKE '{self.CACHE_TABLE_PREFIX}%%'"
  286. rows = self.DB.execute(sql).fetchall() or []
  287. return [r[0] for r in rows]
  288. def truncate_tables(self, table_names: list[str]):
  289. log.debug("truncate table: %s", ",".join(table_names))
  290. with self.connect() as conn:
  291. for table in table_names:
  292. conn.execute(f"DELETE FROM {table}")
  293. conn.close()
  294. return True
  295. @property
  296. def next_maintenance_time(self) -> int:
  297. """Returns (unix epoch) time of the next maintenance."""
  298. return self.cfg.MAINTENANCE_PERIOD + self.properties.m_time("LAST_MAINTENANCE", int(time.time()))
  299. # implement ABC methods of ExpireCache
  300. def set(self, key: str, value: typing.Any, expire: int | None, table: str | None = None) -> bool:
  301. """Set key/value in ``table``. If expire is unset the default is taken
  302. from :py:obj:`ExpireCacheCfg.MAXHOLD_TIME`. If ``table`` argument is
  303. ``None`` (the default), a table name is generated from the
  304. :py:obj:`ExpireCacheCfg.name`. If DB ``table`` does not exists, it will be
  305. created (on demand) by :py:obj:`self.create_table
  306. <ExpireCacheSQLite.create_table>`.
  307. """
  308. self.maintenance()
  309. value = self.serialize(value=value)
  310. if len(value) > self.cfg.MAX_VALUE_LEN:
  311. log.warning("ExpireCache.set(): %s.key='%s' - value too big to cache (len: %s) ", table, value, len(value))
  312. return False
  313. if not expire:
  314. expire = self.cfg.MAXHOLD_TIME
  315. expire = int(time.time()) + expire
  316. table_name = table
  317. if not table_name:
  318. table_name = self.normalize_name(self.cfg.name)
  319. self.create_table(table_name)
  320. sql = (
  321. f"INSERT INTO {table_name} (key, value, expire) VALUES (?, ?, ?)"
  322. f" ON CONFLICT DO "
  323. f"UPDATE SET value=?, expire=?"
  324. )
  325. if table:
  326. with self.DB:
  327. self.DB.execute(sql, (key, value, expire, value, expire))
  328. else:
  329. with self.connect() as conn:
  330. conn.execute(sql, (key, value, expire, value, expire))
  331. conn.close()
  332. return True
  333. def get(self, key: str, default=None, table: str | None = None) -> typing.Any:
  334. """Get value of ``key`` from ``table``. If ``table`` argument is
  335. ``None`` (the default), a table name is generated from the
  336. :py:obj:`ExpireCacheCfg.name`. If ``key`` not exists (in table), the
  337. ``default`` value is returned.
  338. """
  339. self.maintenance()
  340. if not table:
  341. table = self.normalize_name(self.cfg.name)
  342. if table not in self.table_names:
  343. return default
  344. sql = f"SELECT value FROM {table} WHERE key = ?"
  345. row = self.DB.execute(sql, (key,)).fetchone()
  346. if row is None:
  347. return default
  348. return self.deserialize(row[0])
  349. def state(self) -> ExpireCacheStats:
  350. cached_items = {}
  351. for table in self.table_names:
  352. cached_items[table] = []
  353. for row in self.DB.execute(f"SELECT key, value, expire FROM {table}"):
  354. cached_items[table].append((row[0], self.deserialize(row[1]), row[2]))
  355. return ExpireCacheStats(cached_items=cached_items)