fix: the web service waits for the PostgreSQL driver instead of failing at start.
Release / release (push) Successful in 25s
Release / release (push) Successful in 25s
This commit is contained in:
1 parent
c0cd323a0c
commit
732cc8cb54
5 files changed
+72
-30
No files matched your search
@@ -5,12 +5,17 @@ router and that never leaves it. /auth issues an access token naming the user in
|
||||
a refresh token valid REFRESH_SECONDS; vpn-router-token issues tokens with the admin claim and
|
||||
any lifetime. A token without the admin claim must expire within MAX_LIFETIME seconds.
|
||||
|
||||
psycopg is imported by driver() when the database is used, not when the module is loaded, so the
|
||||
module loads while libpq cannot be found yet. A driver that cannot be imported and every
|
||||
failure of the database raise DatabaseError, the only database exception callers see.
|
||||
|
||||
Refresh tokens are random strings kept in PostgreSQL as their SHA-256, in the database of
|
||||
web.database, by default the vpn-router database on this host that provision() creates on the
|
||||
web service's first run, with the password in DATABASE_SECRET. A refresh token is used once: refreshing replaces it.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import contextlib
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
@@ -19,9 +24,6 @@ import secrets
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
import psycopg
|
||||
from psycopg.conninfo import make_conninfo
|
||||
|
||||
WEB_KEY = pathlib.Path('/etc/vpn-router/web.key')
|
||||
DATABASE_SECRET = pathlib.Path('/etc/vpn-router/database.secret')
|
||||
|
||||
@@ -41,6 +43,10 @@ LEEWAY = 60
|
||||
SCHEMA = 'CREATE TABLE IF NOT EXISTS refresh_tokens (hash text PRIMARY KEY, name text NOT NULL, expires timestamptz NOT NULL)'
|
||||
|
||||
|
||||
class DatabaseError(Exception):
|
||||
"""The PostgreSQL driver cannot be loaded, or the database of the refresh tokens failed."""
|
||||
|
||||
|
||||
def key():
|
||||
"""The signing key, or '' while the web service has not made it."""
|
||||
try:
|
||||
@@ -111,20 +117,34 @@ def admin_token(seconds):
|
||||
return {'token': sign({'admin': True, 'iat': now, 'exp': now + seconds}, secret), 'expires': now + seconds}
|
||||
|
||||
|
||||
def driver():
|
||||
"""The psycopg module; DatabaseError while libpq cannot be found."""
|
||||
try:
|
||||
import psycopg
|
||||
except ImportError as exc:
|
||||
raise DatabaseError(f'the PostgreSQL driver cannot be loaded: {exc}') from exc
|
||||
return psycopg
|
||||
|
||||
|
||||
def connection_string(cfg):
|
||||
"""web.database, or the database provision() creates."""
|
||||
"""web.database, or the database provision() creates; its password, of URL-safe characters, is written unquoted."""
|
||||
configured = cfg['web']['database'].strip()
|
||||
if configured:
|
||||
return configured
|
||||
password = DATABASE_SECRET.read_text(encoding='utf-8').strip()
|
||||
return make_conninfo(host='localhost', dbname=DATABASE, user=DATABASE, password=password)
|
||||
return f'host=localhost dbname={DATABASE} user={DATABASE} password={password}'
|
||||
|
||||
|
||||
def connect(cfg):
|
||||
"""A connection to the database of the refresh tokens, with their table."""
|
||||
connection = psycopg.connect(connection_string(cfg), autocommit=True)
|
||||
connection.execute(SCHEMA)
|
||||
return connection
|
||||
@contextlib.contextmanager
|
||||
def database(cfg):
|
||||
"""A connection to the database of the refresh tokens, with their table, closed at the end; DatabaseError on any failure."""
|
||||
psycopg = driver()
|
||||
try:
|
||||
with psycopg.connect(connection_string(cfg), autocommit=True) as connection:
|
||||
connection.execute(SCHEMA)
|
||||
yield connection
|
||||
except psycopg.Error as exc:
|
||||
raise DatabaseError(f'the token database failed: {exc}') from exc
|
||||
|
||||
|
||||
def digest(token):
|
||||
@@ -136,7 +156,7 @@ def issue(cfg, name):
|
||||
secret = key()
|
||||
now = int(time.time())
|
||||
refresh = secrets.token_urlsafe(32)
|
||||
with connect(cfg) as connection:
|
||||
with database(cfg) as connection:
|
||||
connection.execute('DELETE FROM refresh_tokens WHERE expires < now()')
|
||||
connection.execute("INSERT INTO refresh_tokens VALUES (%s, %s, now() + make_interval(secs => %s))",
|
||||
(digest(refresh), name, REFRESH_SECONDS))
|
||||
@@ -153,7 +173,7 @@ def take(cfg, token):
|
||||
"""Remove an unexpired refresh token and return the user it was issued to, or None."""
|
||||
if not isinstance(token, str) or not token:
|
||||
return None
|
||||
with connect(cfg) as connection:
|
||||
with database(cfg) as connection:
|
||||
row = connection.execute('DELETE FROM refresh_tokens WHERE hash = %s RETURNING name, expires > now()',
|
||||
(digest(token),)).fetchone()
|
||||
return row[0] if row and row[1] else None
|
||||
@@ -161,7 +181,7 @@ def take(cfg, token):
|
||||
|
||||
def revoke(cfg, name):
|
||||
"""Remove all refresh tokens of the user."""
|
||||
with connect(cfg) as connection:
|
||||
with database(cfg) as connection:
|
||||
connection.execute('DELETE FROM refresh_tokens WHERE name = %s', (name,))
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user