Extract expiry calculation from KeyConfirmationQueue

This commit is contained in:
Piotr F. Mieszkowski 2024-04-12 11:47:05 +02:00
parent e6619a660f
commit abd3f923fb
Signed by: pfm
GPG key ID: BDE5BC1FA5DC53D5
4 changed files with 34 additions and 9 deletions

16
lacre/keymgmt.py Normal file
View file

@ -0,0 +1,16 @@
"""Key management utilities."""
from datetime import datetime, timedelta
from lacre.config import get_item
def calculate_expiry_date(now: datetime) -> datetime:
"""Calculate date-time of key queue item expiry.
Given current timestamp and configuration item
[database]max_queue_hours, return a date-time object that should be
older than any key in our confirmation queue. If a key is older
than this threshold, we should remove it."""
max_hours = get_item('database', 'max_queue_hours', 1)
return now - timedelta(hours=max_hours)

View file

@ -1,6 +1,6 @@
"""Lacre identity and key repositories."""
from datetime import timedelta
from datetime import datetime, timedelta
from sqlalchemy import create_engine, select, delete, and_, func
from sqlalchemy.exc import OperationalError
@ -173,12 +173,10 @@ class KeyConfirmationQueue:
with self._engine.connect() as conn:
return [e for e in conn.execute(seldel)]
def delete_expired_queue_items(self, when):
max_hours = get_item('database', 'max_queue_hours', 1)
oldest = when - timedelta(hours=max_hours)
delq = delete(self._keys).where(self._keys.c.time < oldest)
LOG.debug('Deleting queue items older than %s: %s', repr(oldest), delq)
def delete_expired_queue_items(self, older_than: datetime):
"""Remove keys that have been in queue before `older_than`."""
delq = delete(self._keys).where(self._keys.c.time < older_than)
LOG.debug('Deleting queue items older than %s: %s', repr(older_than), delq)
with self._engine.connect() as conn:
conn.execute(delq)

View file

@ -0,0 +1,10 @@
import unittest
import datetime
import lacre.keymgmt as km
class KeyManagementUtilitiesTest(unittest.TestCase):
def test_expiry_date_calculation(self):
ts = datetime.datetime(2024, 1, 1, 12, 0)
exp = km.calculate_expiry_date(ts)
self.assertEqual(exp, datetime.datetime(2024, 1, 1, 11, 0))

View file

@ -25,6 +25,7 @@ import logging
import lacre
import lacre.config as conf
from lacre.notify import notify
from lacre.keymgmt import calculate_expiry_date
# Read configuration from /etc/lacre.conf
conf.load_config()
@ -84,8 +85,8 @@ def cleanup(key_dir, key_queue):
LOG.info('Deleted key for: %s', email)
now = datetime.now()
key_queue.delete_expired_queue_items(now)
expiry_date = calculate_expiry_date(datetime.now())
key_queue.delete_expired_queue_items(expiry_date)
_validate_config()