|
| 1 | +"""Redis-backed security state shared with the Go and Node servers.""" |
| 2 | + |
| 3 | +import hashlib |
| 4 | +import json |
| 5 | +import secrets |
| 6 | +import time |
| 7 | + |
| 8 | +import redis |
| 9 | + |
| 10 | +PREFIX = "fcaptcha:v1:" |
| 11 | +POW_TTL_MS = 300_000 |
| 12 | +SPENT_TTL_MS = 600_000 |
| 13 | +IDEMPOTENCY_TTL_MS = 300_000 |
| 14 | +DETECTION_TTL_MS = 900_000 |
| 15 | + |
| 16 | +CLAIM = """ |
| 17 | +if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end |
| 18 | +if redis.call('SET', KEYS[2], '1', 'NX', 'PX', ARGV[1]) == false then return -1 end |
| 19 | +redis.call('DEL', KEYS[1]) |
| 20 | +return 1 |
| 21 | +""" |
| 22 | +RATE = """ |
| 23 | +redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', ARGV[1]) |
| 24 | +local count = redis.call('ZCARD', KEYS[1]); local added = 0 |
| 25 | +if count < tonumber(ARGV[3]) then |
| 26 | + redis.call('ZADD', KEYS[1], ARGV[2], ARGV[4]); count=count+1; added=1 |
| 27 | +end |
| 28 | +redis.call('PEXPIRE', KEYS[1], ARGV[5]); return {count, added} |
| 29 | +""" |
| 30 | +SITEKEY = """ |
| 31 | +if redis.call('SISMEMBER', KEYS[1], ARGV[1]) == 1 then |
| 32 | + redis.call('PEXPIRE', KEYS[1], ARGV[3]); return 1 |
| 33 | +end |
| 34 | +if redis.call('SCARD', KEYS[1]) >= tonumber(ARGV[2]) then return 0 end |
| 35 | +redis.call('SADD', KEYS[1], ARGV[1]); redis.call('PEXPIRE', KEYS[1], ARGV[3]); return 1 |
| 36 | +""" |
| 37 | + |
| 38 | + |
| 39 | +class RedisState: |
| 40 | + def __init__(self, url: str, client=None): |
| 41 | + self.client = client or redis.Redis.from_url(url, decode_responses=True) |
| 42 | + self.client.ping() |
| 43 | + |
| 44 | + @staticmethod |
| 45 | + def opaque(kind: str, value: str) -> str: |
| 46 | + return f"{PREFIX}{kind}:{hashlib.sha256(value.encode()).hexdigest()}" |
| 47 | + |
| 48 | + @staticmethod |
| 49 | + def challenge_key(challenge_id: str) -> str: |
| 50 | + return f"{PREFIX}pow:challenge:{challenge_id}" |
| 51 | + |
| 52 | + def put_challenge(self, challenge: dict) -> None: |
| 53 | + ttl = challenge["expiresAt"] - int(time.time() * 1000) |
| 54 | + if ttl <= 0: |
| 55 | + raise RuntimeError("challenge already expired") |
| 56 | + stored = {**challenge, "challengeId": challenge["id"]} |
| 57 | + stored.pop("id", None) |
| 58 | + self.client.set(self.challenge_key(challenge["id"]), json.dumps(stored), px=ttl) |
| 59 | + |
| 60 | + def get_challenge(self, challenge_id: str): |
| 61 | + payload = self.client.get(self.challenge_key(challenge_id)) |
| 62 | + if not payload: |
| 63 | + return None |
| 64 | + challenge = json.loads(payload) |
| 65 | + challenge["id"] = challenge.get("challengeId", challenge_id) |
| 66 | + return challenge |
| 67 | + |
| 68 | + def claim_challenge(self, challenge_id: str, solution_key: str): |
| 69 | + result = int(self.client.eval( |
| 70 | + CLAIM, 2, self.challenge_key(challenge_id), |
| 71 | + f"{PREFIX}pow:spent:{solution_key}", SPENT_TTL_MS, |
| 72 | + )) |
| 73 | + return result == 1, "solution_already_used" if result == -1 else "challenge_not_found" |
| 74 | + |
| 75 | + def claim_token(self, signature: str) -> bool: |
| 76 | + return bool(self.client.set(f"{PREFIX}token:spent:{signature}", "1", nx=True, px=SPENT_TTL_MS)) |
| 77 | + |
| 78 | + def idempotency_key(self, key: str, token: str) -> str: |
| 79 | + token_hash = hashlib.sha256(token.encode()).hexdigest()[:32] |
| 80 | + return self.opaque("siteverify:idempotency", f"{key}:{token_hash}") |
| 81 | + |
| 82 | + def get_idempotency(self, key: str, token: str): |
| 83 | + if not key: |
| 84 | + return None |
| 85 | + payload = self.client.get(self.idempotency_key(key, token)) |
| 86 | + return json.loads(payload) if payload else None |
| 87 | + |
| 88 | + def set_idempotency(self, key: str, token: str, response: dict) -> None: |
| 89 | + if key: |
| 90 | + self.client.set(self.idempotency_key(key, token), json.dumps(response), px=IDEMPOTENCY_TTL_MS) |
| 91 | + |
| 92 | + def rate_check(self, key: str, window: int, maximum: int): |
| 93 | + now = int(time.time() * 1000) |
| 94 | + count, added = self.client.eval( |
| 95 | + RATE, 1, self.opaque("rate", key), now-window*1000, now, maximum, |
| 96 | + f"{now}:{secrets.token_hex(8)}", window*1000+1000, |
| 97 | + ) |
| 98 | + return int(added) == 0, int(count) |
| 99 | + |
| 100 | + def record_suspicion(self, site_key: str, ip: str) -> None: |
| 101 | + now = int(time.time() * 1000); key = self.opaque("suspicion", f"{site_key}|{ip}") |
| 102 | + with self.client.pipeline(transaction=True) as p: |
| 103 | + p.zremrangebyscore(key, "-inf", now-DETECTION_TTL_MS) |
| 104 | + p.zadd(key, {f"{now}:{secrets.token_hex(8)}": now}) |
| 105 | + p.zremrangebyrank(key, 0, -17).pexpire(key, DETECTION_TTL_MS).execute() |
| 106 | + |
| 107 | + def suspicion_count(self, site_key: str, ip: str) -> int: |
| 108 | + key = self.opaque("suspicion", f"{site_key}|{ip}") |
| 109 | + self.client.zremrangebyscore(key, "-inf", int(time.time()*1000)-DETECTION_TTL_MS) |
| 110 | + return int(self.client.zcard(key)) |
| 111 | + |
| 112 | + def record_fingerprint(self, fp: str, ip: str, site_key: str) -> None: |
| 113 | + fp_key = self.opaque("fingerprint:ips", f"{site_key}|{fp}") |
| 114 | + ip_key = self.opaque("fingerprint:fps", ip) |
| 115 | + with self.client.pipeline(transaction=True) as p: |
| 116 | + p.sadd(fp_key, self.opaque("value:ip", ip)).pexpire(fp_key, DETECTION_TTL_MS) |
| 117 | + p.sadd(ip_key, self.opaque("value:fp", fp)).pexpire(ip_key, DETECTION_TTL_MS).execute() |
| 118 | + |
| 119 | + def ip_fingerprint_count(self, ip: str) -> int: |
| 120 | + return int(self.client.scard(self.opaque("fingerprint:fps", ip))) |
| 121 | + |
| 122 | + def fingerprint_ip_count(self, fp: str, site_key: str) -> int: |
| 123 | + return int(self.client.scard(self.opaque("fingerprint:ips", f"{site_key}|{fp}"))) |
| 124 | + |
| 125 | + def claim_site_key(self, site_key: str, ip: str, maximum: int) -> bool: |
| 126 | + return int(self.client.eval( |
| 127 | + SITEKEY, 1, self.opaque("sitekeys", ip), self.opaque("value:sitekey", site_key), |
| 128 | + maximum, 3_600_000, |
| 129 | + )) == 1 |
0 commit comments