project-pegaprox icon indicating copy to clipboard operation
project-pegaprox copied to clipboard

[Bug] Two except clauses catch sqlite3 exception classes on connections dbcrypto opens with sqlcipher3, so on the encrypted install they never match: re-registering a security key answers 500 instead of 409, and the syslog FTS fallback cannot fall back

Open Frisch12 opened this issue 2 months ago • 2 comments

Describe the bug

On the install requirements.txt produces on Linux x86_64 — the only platform it pulls sqlcipher3-binary for (line 23) — pegaprox/core/dbcrypto.py opens every database through sqlcipher3. Two call sites still catch the exception classes of the standard library's sqlite3. Those are different classes: sqlcipher3 is a fork of pysqlite and builds its own hierarchy from Exception down, so sqlite3.IntegrityError never matches what a SQLCipher connection raises. Both handlers are dead code on exactly the installs the project ships, and both work on a developer machine, which is why the tests pass.

Measured with the wheel requirements.txt installs, in a python:3.13 container on x86_64:

sqlcipher3.IntegrityError is sqlite3.IntegrityError False
issubclass(sqlcipher3.IntegrityError, sqlite3.IntegrityError) False
issubclass(sqlcipher3.OperationalError, sqlite3.OperationalError) False
MRO of sqlcipher3.dbapi2.IntegrityError → sqlcipher3.dbapi2.DatabaseError → sqlcipher3.dbapi2.Error → Exception
except sqlite3.IntegrityError: around a duplicate INSERT on a sqlcipher3 connection not matched — falls through to the next except
grep -rn 'except sqlite3' pegaprox/ exactly the two sites below

dbcrypto anticipates this. It re-exports the classes of whichever driver it picked (dbcrypto.py:55-59):

# Re-export Row, IntegrityError etc. so callers can `from .dbcrypto import Row`
Row = _sqlite_module.Row
IntegrityError = _sqlite_module.IntegrityError
OperationalError = _sqlite_module.OperationalError
DatabaseError = _sqlite_module.DatabaseError

and db.py:2075 already uses them (except dbcrypto.OperationalError as e:). The two sites below predate or missed that.

1. webauthn.py:263 — registering an already-registered security key answers 500 instead of 409

# pegaprox/api/webauthn.py:244-267
    try:
        db = get_db()
        ...
        db.execute(
            '''INSERT INTO webauthn_credentials
               (username, credential_id, public_key, sign_count, transports, aaguid, name, user_handle, created_at)
               VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)''', (...))
    except sqlite3.IntegrityError:
        return jsonify({'error': 'Key is already registered'}), 409
    except Exception as e:
        logging.error(f"[WebAuthn] DB insert failed: {e}")
        return jsonify({'error': 'Could not persist credential'}), 500

get_db() (pegaprox/core/db.py:4751) returns a PegaProxDB, whose connection is dbcrypto.connect() (db.py:174-183). With SQLCipher active the unique-constraint violation is a sqlcipher3.dbapi2.IntegrityError, the first clause does not match, and the generic one answers: a user who re-registers a key they already have gets a server error and an ERROR-level log line about a failed insert, rather than the 409 and the accurate message the code was written to give.

2. syslog_server.py:220 — the FTS fallback cannot fall back

# pegaprox/background/syslog_server.py:178, 220-222
def _init_fts(cur):
    ...
    except sqlite3.OperationalError as exc:
        logging.info(f"[Syslog] FTS disabled for syslog DB: {exc}")
        return False

_open_db() uses dbcrypto.connect() — its own comment says so (syslog_server.py:142-144). The handler exists so a SQLite build without FTS5 degrades to "FTS disabled" instead of failing; with SQLCipher active the OperationalError is sqlcipher3's, the clause does not match, and the exception leaves _init_fts and then _init_db (:243, a try/finally with no except). The wheel from requirements.txt ships FTS5 (PRAGMA compile_options lists ENABLE_FTS5), so this branch is not hit on a standard install today — but the fallback it implements is unreachable on the one platform where the database is encrypted, and a future SQLCipher build without FTS5 would take the syslog server down instead of its full-text index.

Why it is invisible until it ships

dbcrypto.py:17 and :44-52: on macOS, ARM and Windows sqlcipher3 is not importable, the module falls back to sqlite3, and both except clauses match. The test suite passes everywhere it is usually run. On a Linux x86_64 host with the wheel installed, the handlers are silently dead. We hit the same pattern in code of our own on such a host — that is how this was found, and a grep for except sqlite3 then turned up these two.

Steps to Reproduce

  1. Install on Linux x86_64 from requirements.txt, so that dbcrypto.BACKEND is 'sqlcipher' (from the install directory, python3 -c 'from pegaprox.core import dbcrypto; print(dbcrypto.BACKEND)' prints sqlcipher, and the startup output no longer carries the sqlcipher3 not installed warning).
  2. Register a WebAuthn security key, then register the same authenticator again (or replay the registration POST for a credential id that already exists).
  3. Observed, per the code path above: HTTP 500 Could not persist credential, and [WebAuthn] DB insert failed: UNIQUE constraint failed: webauthn_credentials.credential_id in the log. Expected: HTTP 409 Key is already registered, nothing at ERROR level.

What was measured directly is the row in the table above — the exact except shape, on a sqlcipher3 connection, falling through; the route was read, not driven.

Expected behavior

Both handlers match the exception the active driver raises. The module that chose the driver already exports them for this purpose:

from pegaprox.core.dbcrypto import IntegrityError, OperationalError

— one line in each file, and the import sqlite3 in webauthn.py:16 becomes unused (syslog_server.py:11 keeps its own "for type re-exports").

Worth doing alongside: a guard against the pattern coming back, because it looks correct and passes the tests on every machine without SQLCipher. Either a test that asserts no except sqlite3. remains outside dbcrypto.py, or a CI job that runs the suite with sqlcipher3-binary installed, which is the configuration customers actually get.

Environment

  • PegaProx Version: 1.1.1 (both files unchanged on Testing)
  • Installation Method: Manual (git clone)
  • OS: Debian 13, Python 3.13, sqlcipher3-binary from requirements.txt; the class check repeated in a python:3.13 container on x86_64
  • Browser: n/a
  • Behind Reverse Proxy? No
  • UI? n/a

Logs

The check, as run:

platform: x86_64 3.13.15
sqlcipher3.IntegrityError is sqlite3.IntegrityError: False
issubclass(sqlcipher3.IntegrityError, sqlite3.IntegrityError): False
issubclass(sqlcipher3.OperationalError, sqlite3.OperationalError): False
sqlcipher3.IntegrityError.__mro__: ['sqlcipher3.dbapi2.IntegrityError', 'sqlcipher3.dbapi2.DatabaseError', 'sqlcipher3.dbapi2.Error', 'builtins.Exception', 'builtins.BaseException', 'builtins.object']
except sqlite3.IntegrityError: NOT matched; fell through to generic handler -> 500 (sqlcipher3.dbapi2.IntegrityError: UNIQUE constraint failed: t.id)

Screenshots

Not applicable.

Checklist

  • [x] I have searched existing issues to make sure this is not a duplicate
  • [x] I am using the latest version of PegaProx
  • [x] I've put enough in here that someone can start on it without asking me three questions first
  • [x] I understand PegaProx is maintained by volunteers in their free time. Nobody is on call, and writing URGENT doesn't get anyone out of bed 🪄

– Dennis

Frisch12 avatar Sep 15 '26 08:09 Frisch12

Checked it here and you're right on both counts — dbcrypto.BACKEND is sqlcipher on our own box too, and the two trees really are disjoint, so both handlers were dead on exactly the install we ship.

Fixed on Testing (27e9083): both import from dbcrypto now, and sqlite3 is gone from the two imports. The part I liked about your report is the last bit, so there's a test that walks the AST under pegaprox/ and fails if except sqlite3. reappears anywhere outside dbcrypto.py — this is the kind of thing that looks correct and stays green on every machine without SQLCipher, so a grep-once fix wouldn't have held.

Ships with the next release, not 1.1.1.

Marcus

mkellermann97 avatar Sep 15 '26 10:09 mkellermann97

Both handlers catch the right exception classes on SQLCipher connections now — 1.2.0.

Marcus

mkellermann97 avatar Sep 21 '26 07:09 mkellermann97