repository

BlowfishCMS

A small content management system for OpenBSD

version 0.45.6 · ISC · 2026-12-03 · releases

81 lines · 3.5 KB · download this file

"""Signing a test request in, as the admin's login page would.

Since 0.25 the admin only trusts its own session cookie (httpd's password
prompt and REMOTE_USER are gone). A suite builds a request's environment as
before, with 'REMOTE_USER' naming who it's for (or '' for nobody), and passes
it through sign(): the user's name is turned into a signed bf_session cookie,
made exactly as new_session_cookie (Auth.pm) makes one, with the test site's
own session key. The site's own admin account (admin_user in its settings
file, 'admin' by default) is added to the catalogue as an owner if it isn't
there yet, as blowfishctl install would make it; any other name must already
be a user, or its cookie is refused, as httpd's name was before. Suites that test signing in itself use the login
page instead and pass REMOTE_USER ''.

Used by the core suites, tests/upgrade.py (on a copy of a site's catalogue,
as one of its own owners) and the add-ons' tests.
"""
import contextlib, hashlib, hmac, pathlib, re, secrets, sqlite3, time


@contextlib.contextmanager
def connect(path):
    """A connection for a with block that commits and then closes. sqlite3's
    own with only commits: the connection (and its open files) stays until
    the garbage collector finds it, which Python 3.14's collector does late
    enough for a suite to run out of open files on OpenBSD."""
    c = sqlite3.connect(path)
    try:
        with c:
            yield c
    finally:
        c.close()


def _conf(root, key, default):
    conf = root / 'etc/blowfishcms.conf'
    if conf.exists():
        m = re.search(r'^\s*' + key + r'\s*=\s*(\S+)', conf.read_text(), re.M)
        if m:
            return m.group(1)
    return default


def _catalogue(root):
    return root / _conf(root, 'data', '/var/db/blowfishcms').lstrip('/') / 'catalog.sqlite'


def session_key(root):
    """The test site's session key, made the first time it's asked for."""
    path = pathlib.Path(root) / 'etc/blowfishcms-session/session.key'
    if not path.exists() or len(path.read_text().strip()) < 32:
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(secrets.token_hex(32) + '\n')
    return re.sub(r'\s+', '', path.read_text())


def session_cookie(root, user, role='owner'):
    """A bf_session cookie for user on the test site at root ('' if there's no catalogue yet)."""
    root = pathlib.Path(root)
    key = session_key(root)
    gen = 1
    db = _catalogue(root)
    if db.exists():
        with connect(db) as c:
            if c.execute("select count(*) from sqlite_master where name='admin_users'").fetchone()[0]:
                row = c.execute('select session_gen from admin_users where name=?', (user,)).fetchone()
                if row is None and user == _conf(root, 'admin_user', 'admin'):
                    c.execute("insert into admin_users (name,email,role,hash,created_at) values (?,'',?,'','2026-01-01T00:00:00Z')", (user, role))
                elif row is not None:
                    gen = row[0] or 1
    value = f'{user}.{gen}.{int(time.time()) + 3600}.{secrets.token_hex(16)}'
    mac = hmac.new(key.encode(), value.encode(), hashlib.sha256).hexdigest()
    return f'bf_session={value}.{mac}'


def sign(env):
    """Turn env['REMOTE_USER'] into a session cookie; returns env for subprocess.run(env=...)."""
    user = env.pop('REMOTE_USER', '') or ''
    if user:
        cookie = session_cookie(env['BLOWFISH_ROOT'], user)
        env['HTTP_COOKIE'] = '; '.join(c for c in [env.get('HTTP_COOKIE', ''), cookie] if c)
    return env