101 lines
3.2 KiB
Python
101 lines
3.2 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Sender blocklist checking with wildcard support
|
|
"""
|
|
|
|
import fnmatch
|
|
from typing import List, Dict
|
|
from email.utils import parseaddr
|
|
|
|
from logger import log
|
|
from aws.dynamodb_handler import DynamoDBHandler
|
|
|
|
|
|
class BlocklistChecker:
|
|
"""Checks if senders are blocked"""
|
|
|
|
def __init__(self, dynamodb: DynamoDBHandler):
|
|
self.dynamodb = dynamodb
|
|
|
|
def is_sender_blocked(
|
|
self,
|
|
recipient: str,
|
|
sender: str,
|
|
worker_name: str
|
|
) -> bool:
|
|
"""
|
|
Check if sender is blocked for this recipient
|
|
|
|
Args:
|
|
recipient: Recipient email address
|
|
sender: Sender email address (may include name)
|
|
worker_name: Worker name for logging
|
|
|
|
Returns:
|
|
True if sender is blocked
|
|
"""
|
|
patterns = self.dynamodb.get_blocked_patterns(recipient)
|
|
|
|
if not patterns:
|
|
return False
|
|
|
|
sender_clean = parseaddr(sender)[1].lower()
|
|
|
|
for pattern in patterns:
|
|
if fnmatch.fnmatch(sender_clean, pattern.lower()):
|
|
log(
|
|
f"⛔ BLOCKED: Sender {sender_clean} matches pattern '{pattern}' "
|
|
f"for inbox {recipient}",
|
|
'WARNING',
|
|
worker_name
|
|
)
|
|
return True
|
|
|
|
return False
|
|
|
|
def batch_check_blocked_senders(
|
|
self,
|
|
recipients: List[str],
|
|
senders: List[str], # <-- Geändert: Erwartet nun eine Liste
|
|
worker_name: str
|
|
) -> Dict[str, bool]:
|
|
"""
|
|
Batch check if ANY of the senders are blocked for multiple recipients (more efficient)
|
|
|
|
Args:
|
|
recipients: List of recipient email addresses
|
|
senders: List of sender email addresses (Envelope & Header)
|
|
worker_name: Worker name for logging
|
|
|
|
Returns:
|
|
Dictionary mapping recipient -> is_blocked (bool)
|
|
"""
|
|
# Get all blocked patterns in one batch call
|
|
patterns_by_recipient = self.dynamodb.batch_get_blocked_patterns(recipients)
|
|
|
|
# Alle übergebenen Adressen bereinigen
|
|
senders_clean = [parseaddr(s)[1].lower() for s in senders if s]
|
|
result = {}
|
|
|
|
for recipient in recipients:
|
|
patterns = patterns_by_recipient.get(recipient, [])
|
|
|
|
is_blocked = False
|
|
for pattern in patterns:
|
|
for sender_clean in senders_clean:
|
|
if fnmatch.fnmatch(sender_clean, pattern.lower()):
|
|
log(
|
|
f"⛔ BLOCKED: Sender {sender_clean} matches pattern '{pattern}' "
|
|
f"for inbox {recipient}",
|
|
'WARNING',
|
|
worker_name
|
|
)
|
|
is_blocked = True
|
|
break # Bricht die Senders-Schleife ab
|
|
if is_blocked:
|
|
break # Bricht die Pattern-Schleife ab
|
|
|
|
result[recipient] = is_blocked
|
|
|
|
return result
|