various security fixes
This commit is contained in:
1 parent
2682658507
commit
5cb3b5bedf
19 files changed
+1734
-137
No files matched your search
@@ -0,0 +1,321 @@
|
||||
"""Indexes and bounded query plans for the permission-filtered document catalog."""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import sqlite3
|
||||
import time
|
||||
|
||||
VERSION = 3
|
||||
PROBE_LIMIT = 512
|
||||
PRIVATE_FACET_LIMIT = 128
|
||||
ORDER_SCAN_SECONDS = 0.15
|
||||
NOCASE = str.maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')
|
||||
SORTS = {'recent': 'modified DESC,id DESC', 'oldest': 'modified,id', 'name': 'name COLLATE NOCASE,id'}
|
||||
|
||||
|
||||
def key(value, prefix):
|
||||
return prefix + str(value).encode().hex()
|
||||
|
||||
|
||||
def name_terms(name):
|
||||
# Include short searches too: a trigram-only index scans for one/two letters.
|
||||
name = name.casefold()
|
||||
return ' '.join(sorted({key(name[i:i + n], 'g')
|
||||
for n in (1, 2, 3) for i in range(len(name) - n + 1)}))
|
||||
|
||||
|
||||
def register(conn):
|
||||
conn.create_function('document_name_terms', 1, name_terms, deterministic=True)
|
||||
|
||||
|
||||
def ensure_schema(conn, visible, content_types):
|
||||
register(conn)
|
||||
if conn.execute('PRAGMA user_version').fetchone()[0] >= VERSION:
|
||||
return
|
||||
# DDL, FTS rebuild, rollups and the version marker commit together. A second
|
||||
# process waits here and then sees the finished migration. Originals and
|
||||
# document IDs, previews and the OCR queue are untouched.
|
||||
with conn:
|
||||
conn.execute('BEGIN IMMEDIATE')
|
||||
if conn.execute('PRAGMA user_version').fetchone()[0] >= VERSION:
|
||||
return
|
||||
for name in ('document_insert', 'document_delete', 'document_update'):
|
||||
conn.execute(f'DROP TRIGGER IF EXISTS {name}')
|
||||
conn.execute('DROP TABLE document_fts')
|
||||
conn.execute('DROP VIEW IF EXISTS document_search_content')
|
||||
conn.execute(f'''CREATE VIEW document_search_content AS
|
||||
SELECT rowid,name,path,CASE WHEN extension IN ({content_types}) THEN body ELSE '' END body,
|
||||
's'||lower(hex(source_id)) source_key, 't'||lower(hex(extension)) type_key
|
||||
FROM documents WHERE {visible}''')
|
||||
conn.execute('''CREATE VIRTUAL TABLE document_fts USING fts5(
|
||||
name,path,body,source_key,type_key,content='document_search_content',content_rowid='rowid',
|
||||
tokenize='unicode61 remove_diacritics 2',prefix='2 3 4')''')
|
||||
conn.execute('''CREATE VIRTUAL TABLE IF NOT EXISTS document_names_fts USING fts5(
|
||||
terms,source_key,type_key,content='',tokenize='ascii',detail='none',columnsize=0)''')
|
||||
conn.execute("INSERT INTO document_names_fts(document_names_fts) VALUES('delete-all')")
|
||||
conn.execute('''CREATE TABLE IF NOT EXISTS document_counts (
|
||||
source_id TEXT NOT NULL, extension TEXT NOT NULL, state TEXT NOT NULL,
|
||||
amount INTEGER NOT NULL, PRIMARY KEY(source_id,extension,state)) WITHOUT ROWID''')
|
||||
conn.execute('DELETE FROM document_counts')
|
||||
for sort, order in SORTS.items():
|
||||
for typed, prefix in ((False, 'source_id,'), (True, 'source_id,extension,')):
|
||||
suffix = '_type' if typed else ''
|
||||
conn.execute(f'''CREATE INDEX IF NOT EXISTS document_search_{sort}{suffix}
|
||||
ON documents({prefix}{order}) WHERE {visible}''')
|
||||
global_indexes(conn, visible)
|
||||
|
||||
def change(alias, deleting, names=False):
|
||||
condition = visible.replace('name', alias + '.name')
|
||||
body = f"CASE WHEN {alias}.extension IN ({content_types}) THEN {alias}.body ELSE '' END"
|
||||
fields = f"{alias}.rowid,{alias}.name,{alias}.path,{body},'s'||lower(hex({alias}.source_id)),'t'||lower(hex({alias}.extension))"
|
||||
terms = f"{alias}.rowid,document_name_terms({alias}.name),'s'||lower(hex({alias}.source_id)),'t'||lower(hex({alias}.extension))"
|
||||
if deleting:
|
||||
return f'''
|
||||
INSERT INTO document_names_fts(document_names_fts,rowid,terms,source_key,type_key)
|
||||
SELECT 'delete',{terms} WHERE {condition};
|
||||
''' if names else f'''
|
||||
INSERT INTO document_fts(document_fts,rowid,name,path,body,source_key,type_key)
|
||||
SELECT 'delete',{fields} WHERE {condition};
|
||||
'''
|
||||
return f'''
|
||||
INSERT INTO document_names_fts(rowid,terms,source_key,type_key) SELECT {terms} WHERE {condition};
|
||||
''' if names else f'''
|
||||
INSERT INTO document_fts(rowid,name,path,body,source_key,type_key) SELECT {fields} WHERE {condition};
|
||||
'''
|
||||
|
||||
for name, event, sql in (
|
||||
('document_insert', 'INSERT', change('new', False)),
|
||||
('document_delete', 'DELETE', change('old', True)),
|
||||
('document_update', 'UPDATE OF name,path,body,source_id,extension', change('old', True) + change('new', False)),
|
||||
):
|
||||
conn.execute(f'CREATE TRIGGER {name} AFTER {event} ON documents BEGIN {sql} END')
|
||||
for name, event, sql in (
|
||||
('document_name_insert', 'INSERT', change('new', False, True)),
|
||||
('document_name_delete', 'DELETE', change('old', True, True)),
|
||||
('document_name_update', 'UPDATE OF name,source_id,extension', change('old', True, True) + change('new', False, True)),
|
||||
):
|
||||
conn.execute(f'DROP TRIGGER IF EXISTS {name}')
|
||||
conn.execute(f'CREATE TRIGGER {name} AFTER {event} ON documents BEGIN {sql} END')
|
||||
for name, event, aliases in (
|
||||
('document_count_insert', 'INSERT', (('new', 1),)),
|
||||
('document_count_delete', 'DELETE', (('old', -1),)),
|
||||
('document_count_update', 'UPDATE OF name,source_id,extension,state', (('old', -1), ('new', 1))),
|
||||
):
|
||||
conn.execute(f'DROP TRIGGER IF EXISTS {name}')
|
||||
sql = ''
|
||||
for alias, delta in aliases:
|
||||
condition = visible.replace('name', alias + '.name')
|
||||
sql += f'''INSERT INTO document_counts(source_id,extension,state,amount)
|
||||
SELECT {alias}.source_id,{alias}.extension,{alias}.state,{delta} WHERE {condition}
|
||||
ON CONFLICT(source_id,extension,state) DO UPDATE SET amount=amount+excluded.amount;
|
||||
DELETE FROM document_counts WHERE source_id={alias}.source_id
|
||||
AND extension={alias}.extension AND state={alias}.state AND amount=0;'''
|
||||
conn.execute(f'CREATE TRIGGER {name} AFTER {event} ON documents BEGIN {sql} END')
|
||||
conn.execute("INSERT INTO document_fts(document_fts) VALUES('rebuild')")
|
||||
conn.execute("INSERT INTO document_fts(document_fts,rank) VALUES('rank','bm25(6,2,1,0,0)')")
|
||||
conn.execute(f'''INSERT INTO document_names_fts(rowid,terms,source_key,type_key)
|
||||
SELECT rowid,document_name_terms(name),'s'||lower(hex(source_id)),'t'||lower(hex(extension))
|
||||
FROM documents WHERE {visible}''')
|
||||
conn.execute(f'''INSERT INTO document_counts SELECT source_id,extension,state,count(*)
|
||||
FROM documents WHERE {visible} GROUP BY source_id,extension,state''')
|
||||
conn.execute(f'PRAGMA user_version={VERSION}')
|
||||
|
||||
|
||||
def cursor_scope(query, scope, source, extension, sort):
|
||||
return hashlib.sha256(json.dumps([query, scope, source, extension, sort]).encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
def global_indexes(conn, visible):
|
||||
for sort, order in SORTS.items():
|
||||
for typed in (False, True):
|
||||
suffix = '_type' if typed else ''
|
||||
conn.execute(f'''CREATE INDEX IF NOT EXISTS document_global_{sort}{suffix}
|
||||
ON documents({'extension,' if typed else ''}{order}) WHERE {visible}''')
|
||||
|
||||
|
||||
def encode_cursor(signature, values, consumed):
|
||||
return base64.urlsafe_b64encode(json.dumps([signature, values, consumed], separators=(',', ':')).encode()).decode().rstrip('=')
|
||||
|
||||
|
||||
def decode_cursor(value, signature):
|
||||
if not value:
|
||||
return None, 0
|
||||
try:
|
||||
if len(value) > 2048:
|
||||
raise ValueError()
|
||||
actual, position, consumed = json.loads(base64.urlsafe_b64decode(value + '=' * (-len(value) % 4)))
|
||||
if actual != signature or not isinstance(position, list) or len(position) not in (3, 4) or not isinstance(consumed, int) or consumed < 0:
|
||||
raise ValueError()
|
||||
if not isinstance(position[0], (str, int, float)) or not isinstance(position[1], int) or not isinstance(position[2], str):
|
||||
raise ValueError()
|
||||
if len(position) == 4 and (not isinstance(position[3], int) or position[3] < 0):
|
||||
raise ValueError()
|
||||
return position, consumed
|
||||
except (ValueError, TypeError, UnicodeError, json.JSONDecodeError) as exc:
|
||||
raise ValueError('Ungültiger Seitenzeiger') from exc
|
||||
|
||||
|
||||
def row_key(row, sort):
|
||||
if sort == 'relevance':
|
||||
return row['_rank'], row['rowid']
|
||||
if sort == 'name':
|
||||
return row['name'].translate(NOCASE), row['id']
|
||||
if sort == 'recent':
|
||||
return -row['modified'], -int(row['id'], 16)
|
||||
return row['modified'], row['id']
|
||||
|
||||
|
||||
def row_position(row, sort):
|
||||
primary = row['_rank'] if sort == 'relevance' else row['name'] if sort == 'name' else row['modified']
|
||||
result = [primary, row['rowid'], row['id']]
|
||||
if sort == 'relevance':
|
||||
result.append(row['_stream_offset'])
|
||||
return result
|
||||
|
||||
|
||||
def source_rows(conn, source_id, extension, sort, table, match, name_query, visible, position, amount):
|
||||
"""Selective matches sort a bounded set; broad ones walk a sorted index.
|
||||
|
||||
The latter has a work deadline: sparse matches near the end of a metadata
|
||||
index fall back to the FTS-driven plan rather than scanning the catalog.
|
||||
"""
|
||||
conditions = ['d.source_id=?', visible]
|
||||
values = [source_id]
|
||||
if extension:
|
||||
conditions.append('d.extension=?')
|
||||
values.append(extension)
|
||||
if name_query:
|
||||
conditions.append("d.name LIKE ? ESCAPE '\\'")
|
||||
values.append('%' + name_query.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_') + '%')
|
||||
order = {'name': 'd.name COLLATE NOCASE,d.id', 'oldest': 'd.modified,d.id',
|
||||
'recent': 'd.modified DESC,d.id DESC'}[sort]
|
||||
columns = 'd.rowid,d.id,d.source_id,d.path,d.name,d.extension,d.size,d.modified,d.fingerprint,d.state,d.preview,d.pages,d.attempts'
|
||||
if position:
|
||||
primary = 'd.name COLLATE NOCASE' if sort == 'name' else 'd.modified'
|
||||
op = '<' if sort == 'recent' else '>'
|
||||
# id is the stable tie-breaker in the metadata indexes.
|
||||
conditions.append(f'({primary},d.id) {op} (?,?)')
|
||||
values.extend((position[0], position[2]))
|
||||
if sort == 'name':
|
||||
# SQLite does not always turn a collated row-value comparison into
|
||||
# an index range. The redundant scalar bound guarantees the seek.
|
||||
conditions.append('d.name COLLATE NOCASE>=?')
|
||||
values.append(position[0])
|
||||
where = ' AND '.join(conditions)
|
||||
index = f'document_search_{sort}' + ('_type' if extension else '')
|
||||
if not table:
|
||||
return conn.execute(f'SELECT {columns},0 _rank FROM documents d INDEXED BY {index} WHERE {where} ORDER BY {order} LIMIT ?', [*values, amount]).fetchall(), False
|
||||
source_term = key(source_id, 's')
|
||||
type_term = key(extension, 't')
|
||||
scoped = f'({match}) AND ' + (source_term if table == 'document_names_fts' else 'source_key:' + source_term)
|
||||
if extension:
|
||||
scoped += ' AND ' + (type_term if table == 'document_names_fts' else 'type_key:' + type_term)
|
||||
# The FTS cursor must drive the join. A metadata-first plan reinitializes
|
||||
# MATCH for each catalog row, even when SQL asks for only 40 results.
|
||||
joined = f'{table} CROSS JOIN documents d ON d.rowid={table}.rowid'
|
||||
fts_where = f'{table} MATCH ? AND {where}'
|
||||
fts_values = [scoped, *values]
|
||||
probe = conn.execute(f'SELECT d.rowid FROM {joined} WHERE {fts_where} LIMIT ?', [*fts_values, PROBE_LIMIT + 1]).fetchall()
|
||||
if not probe:
|
||||
return [], True
|
||||
if len(probe) <= PROBE_LIMIT:
|
||||
amount = max(amount, PROBE_LIMIT + 1)
|
||||
if len(probe) > PROBE_LIMIT:
|
||||
deadline = time.monotonic() + ORDER_SCAN_SECONDS
|
||||
conn.set_progress_handler(lambda: time.monotonic() > deadline, 1000)
|
||||
try:
|
||||
rows = conn.execute(f'''SELECT {columns},0 _rank FROM documents d INDEXED BY {index}
|
||||
WHERE {where} AND d.rowid IN (SELECT rowid FROM {table} WHERE {table} MATCH ?)
|
||||
ORDER BY {order} LIMIT ?''', [*values, scoped, amount]).fetchall()
|
||||
return rows, False
|
||||
except sqlite3.OperationalError as exc:
|
||||
if 'interrupted' not in str(exc):
|
||||
raise
|
||||
finally:
|
||||
conn.set_progress_handler(None, 0)
|
||||
rows = conn.execute(f'SELECT {columns},0 _rank FROM {joined} WHERE {fts_where} ORDER BY {order} LIMIT ?', [*fts_values, amount]).fetchall()
|
||||
return rows, len(probe) <= PROBE_LIMIT
|
||||
|
||||
|
||||
def ranked_rows(conn, source_ids, extension, match, visible, consumed, amount, push_sources=True):
|
||||
# Rank all allowed sources together. Ranking each source independently
|
||||
# repeats BM25 work and posting-list intersections once per folder.
|
||||
scoped = '(' + match + ')'
|
||||
if push_sources:
|
||||
scoped += ' AND source_key:(' + ' OR '.join(key(source, 's') for source in source_ids) + ')'
|
||||
if extension:
|
||||
scoped += ' AND type_key:' + key(extension, 't')
|
||||
where = f'document_fts MATCH ? AND d.source_id IN ({",".join("?" for _ in source_ids)}) AND {visible}'
|
||||
values = [scoped, *source_ids]
|
||||
if extension:
|
||||
where += ' AND d.extension=?'
|
||||
values.append(extension)
|
||||
joined = 'document_fts CROSS JOIN documents d ON d.rowid=document_fts.rowid'
|
||||
probe = conn.execute(f'SELECT d.rowid FROM {joined} WHERE {where} LIMIT ?', [*values, PROBE_LIMIT + 1]).fetchall()
|
||||
if len(probe) <= PROBE_LIMIT:
|
||||
amount = max(amount, PROBE_LIMIT + 1)
|
||||
# BM25 values move for unchanged files when OCR changes corpus statistics.
|
||||
# A saved score threshold can therefore skip an entire page. Page through
|
||||
# FTS5's native ranked stream instead, before fetching catalog rows. Source
|
||||
# and type terms filter this stream, not just its final catalog join.
|
||||
rows = conn.execute(f'''SELECT d.rowid,d.id,d.source_id,d.path,d.name,d.extension,d.size,d.modified,
|
||||
d.fingerprint,d.state,d.preview,d.pages,d.attempts,page.score _rank
|
||||
FROM (SELECT rowid,rank score FROM document_fts WHERE document_fts MATCH ?
|
||||
ORDER BY rank LIMIT ? OFFSET ?) page
|
||||
JOIN documents d ON d.rowid=page.rowid
|
||||
WHERE d.source_id IN ({','.join('?' for _ in source_ids)}) AND {visible}
|
||||
ORDER BY page.score,page.rowid''', [scoped, amount, consumed, *source_ids]).fetchall()
|
||||
return [dict(row, _stream_offset=consumed + index + 1) for index, row in enumerate(rows)], len(probe) <= PROBE_LIMIT
|
||||
|
||||
|
||||
def global_rows(conn, source_ids, extension, sort, table, match, name_query, visible, position, amount, push_sources):
|
||||
"""One posting-list intersection for searches spanning multiple folders."""
|
||||
sources = ' OR '.join(key(source, 's') for source in source_ids)
|
||||
scoped = '(' + match + ')'
|
||||
if push_sources:
|
||||
scoped += ' AND ' + ('source_key:(' + sources + ')' if table == 'document_fts' else '(' + sources + ')')
|
||||
if extension:
|
||||
scoped += ' AND ' + ('type_key:' if table == 'document_fts' else '') + key(extension, 't')
|
||||
where = f'd.source_id IN ({",".join("?" for _ in source_ids)}) AND {visible}'
|
||||
values = list(source_ids)
|
||||
if extension:
|
||||
where += ' AND d.extension=?'
|
||||
values.append(extension)
|
||||
if name_query:
|
||||
where += " AND d.name LIKE ? ESCAPE '\\'"
|
||||
values.append('%' + name_query.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_') + '%')
|
||||
if position:
|
||||
primary = 'd.name COLLATE NOCASE' if sort == 'name' else 'd.modified'
|
||||
where += f' AND ({primary},d.id) {"<" if sort == "recent" else ">"} (?,?)'
|
||||
values += [position[0], position[2]]
|
||||
if sort == 'name':
|
||||
where += ' AND d.name COLLATE NOCASE>=?'
|
||||
values.append(position[0])
|
||||
joined = f'{table} CROSS JOIN documents d ON d.rowid={table}.rowid'
|
||||
probe = conn.execute(f'SELECT d.rowid FROM {joined} WHERE {table} MATCH ? AND {where} LIMIT ?',
|
||||
[scoped, *values, PROBE_LIMIT + 1]).fetchall()
|
||||
if not probe:
|
||||
return [], True
|
||||
complete = len(probe) <= PROBE_LIMIT
|
||||
if complete:
|
||||
amount = max(amount, PROBE_LIMIT + 1)
|
||||
columns = 'd.rowid,d.id,d.source_id,d.path,d.name,d.extension,d.size,d.modified,d.fingerprint,d.state,d.preview,d.pages,d.attempts'
|
||||
order = ','.join('d.' + part for part in SORTS[sort].split(','))
|
||||
if not complete:
|
||||
index = 'document_global_' + sort + ('_type' if extension else '')
|
||||
deadline = time.monotonic() + 1
|
||||
conn.set_progress_handler(lambda: time.monotonic() > deadline, 1000)
|
||||
try:
|
||||
rows = conn.execute(f'''SELECT {columns},0 _rank FROM documents d INDEXED BY {index}
|
||||
WHERE {where} AND d.rowid IN (SELECT rowid FROM {table} WHERE {table} MATCH ?)
|
||||
ORDER BY {order} LIMIT ?''', [*values, scoped, amount]).fetchall()
|
||||
return rows, False
|
||||
except sqlite3.OperationalError as exc:
|
||||
if 'interrupted' not in str(exc):
|
||||
raise
|
||||
finally:
|
||||
conn.set_progress_handler(None, 0)
|
||||
rows = conn.execute(f'''SELECT {columns},0 _rank FROM {joined} WHERE {table} MATCH ? AND {where}
|
||||
ORDER BY {order} LIMIT ?''', [scoped, *values, amount]).fetchall()
|
||||
return rows, complete
|
||||
+173
-54
@@ -11,12 +11,13 @@ import time
|
||||
import uuid
|
||||
|
||||
try:
|
||||
from . import access_control, reconcile_shares as directory
|
||||
from . import access_control, document_search, reconcile_shares as directory
|
||||
from .account_policy import account_name, is_excluded_user
|
||||
from .state_db import connect_state_db
|
||||
from .document_types import CONTENT_SUFFIXES, OFFICE_SUFFIXES, IMAGE_SUFFIXES
|
||||
except ImportError:
|
||||
import access_control
|
||||
import document_search
|
||||
import reconcile_shares as directory
|
||||
from account_policy import account_name, is_excluded_user
|
||||
from state_db import connect_state_db
|
||||
@@ -36,10 +37,15 @@ def is_excluded_filename(name):
|
||||
def connect():
|
||||
os.makedirs(SEARCH_ROOT, mode=0o700, exist_ok=True)
|
||||
os.chmod(SEARCH_ROOT, 0o700)
|
||||
return connect_state_db(SEARCH_DB)
|
||||
conn = connect_state_db(SEARCH_DB)
|
||||
document_search.register(conn)
|
||||
return conn
|
||||
|
||||
|
||||
def ensure_schema(conn):
|
||||
document_search.register(conn)
|
||||
if conn.execute('PRAGMA user_version').fetchone()[0] >= document_search.VERSION:
|
||||
return
|
||||
conn.executescript('''
|
||||
CREATE TABLE IF NOT EXISTS document_sources (
|
||||
id TEXT PRIMARY KEY, kind TEXT NOT NULL, label TEXT NOT NULL,
|
||||
@@ -103,6 +109,9 @@ def ensure_schema(conn):
|
||||
conn.execute(f"DELETE FROM documents WHERE NOT ({SEARCHABLE_NAME_SQL.format(name='name')})")
|
||||
conn.execute('PRAGMA user_version=2')
|
||||
|
||||
content_types = ','.join("'" + suffix + "'" for suffix in sorted(CONTENT_SUFFIXES))
|
||||
document_search.ensure_schema(conn, SEARCHABLE_NAME_SQL.format(name='name'), content_types)
|
||||
|
||||
|
||||
def worker_paused(conn):
|
||||
return bool(conn.execute('SELECT paused FROM document_worker WHERE id=1').fetchone()[0])
|
||||
@@ -382,82 +391,192 @@ def public_document(row, source, snippet=''):
|
||||
|
||||
|
||||
def search(conn, identity, params):
|
||||
# Keep rollups, posting lists and page selection in one WAL snapshot.
|
||||
# The caller's transaction, if any, remains under its own control.
|
||||
own_transaction = not conn.in_transaction
|
||||
if own_transaction:
|
||||
conn.execute('BEGIN')
|
||||
try:
|
||||
return search_snapshot(conn, identity, params)
|
||||
finally:
|
||||
if own_transaction:
|
||||
conn.rollback()
|
||||
|
||||
|
||||
def search_snapshot(conn, identity, params):
|
||||
sources = allowed_sources(conn, identity)
|
||||
query = str(params.get('q', [''])[0]).strip()[:256]
|
||||
scope = params.get('scope', ['all'])[0]
|
||||
source_filter = params.get('source', [''])[0]
|
||||
extension = params.get('type', [''])[0].lower().lstrip('.')
|
||||
sort = params.get('sort', ['recent'])[0]
|
||||
if sort not in {'name', 'oldest', 'recent', 'relevance'}:
|
||||
sort = 'recent'
|
||||
if sort == 'relevance' and (not query or scope == 'name'):
|
||||
sort = 'recent'
|
||||
try:
|
||||
limit = min(100, max(1, int(params.get('limit', ['40'])[0])))
|
||||
offset = max(0, int(params.get('offset', ['0'])[0]))
|
||||
if offset > 1000 and not params.get('cursor', [''])[0]:
|
||||
raise ValueError()
|
||||
except ValueError as exc:
|
||||
raise ValueError('Ungültige Seitennummer') from exc
|
||||
raise ValueError('Für weitere Seiten bitte den Seitenzeiger verwenden') from exc
|
||||
signature = document_search.cursor_scope(query, scope, source_filter, extension, sort)
|
||||
position, consumed = document_search.decode_cursor(params.get('cursor', [''])[0], signature)
|
||||
if position:
|
||||
offset = 0
|
||||
selected = {key: value for key, value in sources.items() if not source_filter or key == source_filter}
|
||||
base = {'items': [], 'total': 0, 'hasMore': False, 'sources': [{'id': key, 'label': value['label'], 'kind': value['kind']} for key, value in sources.items()], 'types': [], 'pending': 0}
|
||||
if not sources:
|
||||
base = {'items': [], 'total': 0, 'totalExact': True, 'hasMore': False, 'nextCursor': None,
|
||||
'sources': [{'id': key, 'label': value['label'], 'kind': value['kind']} for key, value in sources.items()],
|
||||
'types': [], 'pending': 0, 'pendingExact': True, 'searchIncomplete': False}
|
||||
if not selected:
|
||||
return base
|
||||
# Filter before snippets, pagination, counts and facets. Hidden files
|
||||
# must never influence any user-visible result.
|
||||
ids = list(selected)
|
||||
if not ids:
|
||||
return base
|
||||
placeholders = ','.join('?' for _ in ids)
|
||||
conn.execute('CREATE TEMP TABLE IF NOT EXISTS readable_private(id TEXT PRIMARY KEY)')
|
||||
conn.execute('DELETE FROM readable_private')
|
||||
for row in conn.execute(f"SELECT id,source_id,path FROM documents WHERE source_id IN ({placeholders}) AND source_id LIKE 'private:%'", ids).fetchall():
|
||||
if private_readable(selected[row['source_id']], row['path'], identity.get('uid')):
|
||||
conn.execute('INSERT INTO readable_private VALUES(?)', (row['id'],))
|
||||
private_condition = SEARCHABLE_NAME_SQL.format(name='d.name') + " AND (d.source_id NOT LIKE 'private:%' OR EXISTS (SELECT 1 FROM readable_private r WHERE r.id=d.id))"
|
||||
conditions = [f'd.source_id IN ({placeholders})', private_condition]
|
||||
values = ids[:]
|
||||
from_sql = 'documents d'
|
||||
content_types = ','.join("'" + extension + "'" for extension in sorted(CONTENT_SUFFIXES))
|
||||
snippet_sql = f"CASE WHEN d.extension IN ({content_types}) THEN substr(d.body,1,220) ELSE '' END"
|
||||
visible_sql = SEARCHABLE_NAME_SQL.format(name='d.name')
|
||||
readable = {}
|
||||
|
||||
def permitted(row):
|
||||
if selected[row['source_id']]['kind'] != 'private':
|
||||
return True
|
||||
if row['id'] not in readable:
|
||||
readable[row['id']] = private_readable(selected[row['source_id']], row['path'], identity.get('uid'))
|
||||
return readable[row['id']]
|
||||
|
||||
# Small, incrementally maintained rollups replace full scans for counts,
|
||||
# progress and dropdowns. Private facets are only published after a current
|
||||
# filesystem permission check. Large private folders get bounded samples;
|
||||
# their exact total is deliberately not inferred from unverified records.
|
||||
total = 0
|
||||
selected_count = 0
|
||||
metadata_exact = True
|
||||
types = set()
|
||||
for source_id, source in selected.items():
|
||||
groups = conn.execute('SELECT extension,state,amount FROM document_counts WHERE source_id=?', (source_id,)).fetchall()
|
||||
selected_count += sum(group['amount'] for group in groups)
|
||||
if source['kind'] == 'data':
|
||||
for group in groups:
|
||||
if group['extension']:
|
||||
types.add(group['extension'].lstrip('.'))
|
||||
if not extension or group['extension'] == '.' + extension:
|
||||
total += group['amount']
|
||||
if group['state'] in {'pending', 'ocr'}:
|
||||
base['pending'] += group['amount']
|
||||
continue
|
||||
count = sum(group['amount'] for group in groups)
|
||||
small = count <= document_search.PRIVATE_FACET_LIMIT
|
||||
metadata_exact = metadata_exact and small
|
||||
base['pendingExact'] = base['pendingExact'] and small
|
||||
suffixes = sorted({group['extension'] for group in groups})
|
||||
budget = document_search.PRIVATE_FACET_LIMIT
|
||||
for number, suffix in enumerate(suffixes):
|
||||
if not small and budget <= 0:
|
||||
break
|
||||
sample = count if small else max(1, budget // (len(suffixes) - number))
|
||||
rows = conn.execute(f'''SELECT d.id,d.source_id,d.path,d.extension,d.state FROM documents d
|
||||
INDEXED BY document_search_recent_type WHERE d.source_id=? AND d.extension=? AND {visible_sql}
|
||||
ORDER BY d.modified DESC,d.id DESC LIMIT ?''', (source_id, suffix, sample)).fetchall()
|
||||
budget -= len(rows)
|
||||
for row in rows:
|
||||
if permitted(row):
|
||||
if suffix:
|
||||
types.add(suffix.lstrip('.'))
|
||||
if not extension or suffix == '.' + extension:
|
||||
total += 1
|
||||
base['pending'] += int(row['state'] in {'pending', 'ocr'})
|
||||
|
||||
table, match = None, None
|
||||
if query:
|
||||
if scope == 'name':
|
||||
conditions.append("d.name LIKE ? ESCAPE '\\'")
|
||||
values.append('%' + query.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_') + '%')
|
||||
table = 'document_names_fts'
|
||||
normalized = query.casefold()
|
||||
size = min(3, len(normalized))
|
||||
match = ' AND '.join(document_search.key(normalized[i:i + size], 'g')
|
||||
for i in range(len(normalized) - size + 1))
|
||||
else:
|
||||
words = re.findall(r'\w+', query, flags=re.UNICODE)[:24]
|
||||
if not words:
|
||||
base['types'] = sorted(types)
|
||||
return base
|
||||
table = 'document_fts'
|
||||
match = ' AND '.join('"' + word + '"*' for word in words)
|
||||
if scope == 'content':
|
||||
match = 'body : (' + match + ')'
|
||||
from_sql += ' JOIN document_fts ON document_fts.rowid=d.rowid'
|
||||
conditions.append('document_fts MATCH ?')
|
||||
values.append(match)
|
||||
if scope == 'content':
|
||||
conditions.append(f'd.extension IN ({content_types})')
|
||||
else:
|
||||
# A stale body from an older worker must never make other file
|
||||
# types appear in content search, even before index cleanup.
|
||||
conditions.append(f"(d.extension IN ({content_types}) OR d.rowid IN (SELECT rowid FROM document_fts WHERE document_fts MATCH ?))")
|
||||
values.append('{name path} : (' + ' AND '.join('"' + word + '"*' for word in words) + ')')
|
||||
snippet_sql = f"CASE WHEN d.extension IN ({content_types}) THEN snippet(document_fts,2,char(1),char(2),' … ',32) ELSE '' END"
|
||||
if extension:
|
||||
conditions.append('d.extension=?')
|
||||
values.append('.' + extension)
|
||||
where = ' AND '.join(conditions)
|
||||
order = {'name': 'd.name COLLATE NOCASE', 'oldest': 'd.modified', 'recent': 'd.modified DESC'}.get(sort, 'd.modified DESC')
|
||||
if query and scope != 'name' and sort == 'relevance':
|
||||
order = 'bm25(document_fts,6,2,1)'
|
||||
base['total'] = conn.execute(f'SELECT count(*) FROM {from_sql} WHERE {where}', values).fetchone()[0]
|
||||
base['hasMore'] = offset + limit < base['total']
|
||||
columns = 'd.id,d.source_id,d.path,d.name,d.extension,d.size,d.modified,d.fingerprint,d.state,d.preview,d.pages,d.attempts'
|
||||
rows = conn.execute(f'SELECT {columns}, {snippet_sql} AS excerpt FROM {from_sql} WHERE {where} ORDER BY {order},d.id LIMIT ? OFFSET ?', [*values,limit,offset])
|
||||
match = ('body' if scope == 'content' else '{name path body}') + ' : (' + match + ')'
|
||||
candidates = []
|
||||
complete = True
|
||||
boundaries = []
|
||||
combined = sort == 'relevance' or table and len(selected) > 1
|
||||
selections = [list(selected)] if combined else list(selected)
|
||||
catalog_count = conn.execute('SELECT coalesce(sum(amount),0) FROM document_counts').fetchone()[0] if combined else 0
|
||||
push_sources = selected_count < catalog_count * 0.5
|
||||
rank_offset = position[3] if position and len(position) == 4 else consumed
|
||||
if sort == 'relevance' and max(consumed, rank_offset) > selected_count:
|
||||
raise ValueError('Ungültiger Seitenzeiger')
|
||||
for source_id in selections:
|
||||
private = any(source['kind'] == 'private' for source in selected.values()) if combined else selected[source_id]['kind'] == 'private'
|
||||
amount = limit + offset + (document_search.PRIVATE_FACET_LIMIT if private else 0) + 1
|
||||
if sort == 'relevance':
|
||||
rows, exhaustive = document_search.ranked_rows(conn, source_id, '.' + extension if extension else '',
|
||||
match, visible_sql, rank_offset, amount, selected_count != catalog_count)
|
||||
elif combined:
|
||||
rows, exhaustive = document_search.global_rows(conn, source_id, '.' + extension if extension else '', sort,
|
||||
table, match, query if scope == 'name' else '', visible_sql, position, amount, push_sources)
|
||||
else:
|
||||
rows, exhaustive = document_search.source_rows(conn, source_id, '.' + extension if extension else '', sort,
|
||||
table, match, query if scope == 'name' else '', visible_sql, position, amount)
|
||||
candidates.extend(rows)
|
||||
complete = complete and exhaustive
|
||||
if not exhaustive and len(rows) >= amount:
|
||||
boundaries.append(document_search.row_key(rows[-1], sort))
|
||||
candidates.sort(key=lambda row: document_search.row_key(row, sort))
|
||||
boundary = min(boundaries) if boundaries else None
|
||||
visible = []
|
||||
for row in rows:
|
||||
frontier = None
|
||||
exhausted = True
|
||||
for row in candidates:
|
||||
if boundary is not None and document_search.row_key(row, sort) > boundary:
|
||||
exhausted = False
|
||||
break
|
||||
frontier = row
|
||||
if not permitted(row):
|
||||
continue
|
||||
try:
|
||||
with open_file(selected[row['source_id']]['root'], row['path']) as (_, info):
|
||||
if fingerprint(info) == row['fingerprint'] and private_readable(selected[row['source_id']], row['path'], identity.get('uid')):
|
||||
visible.append(row)
|
||||
if fingerprint(info) != row['fingerprint']:
|
||||
continue
|
||||
except OSError:
|
||||
continue
|
||||
base['items'] = [public_document(row, selected[row['source_id']], row['excerpt']) for row in visible]
|
||||
base['types'] = sorted({row['extension'].lstrip('.') for row in conn.execute(f'SELECT DISTINCT extension FROM documents d WHERE source_id IN ({placeholders}) AND {private_condition}', ids) if row['extension']})
|
||||
base['pending'] = conn.execute(f"SELECT count(*) FROM documents d WHERE source_id IN ({placeholders}) AND {private_condition} AND state IN ('pending','ocr')", ids).fetchone()[0]
|
||||
visible.append(row)
|
||||
if len(visible) > offset + limit:
|
||||
exhausted = False
|
||||
break
|
||||
more = len(visible) > offset + limit
|
||||
page = visible[offset:offset + limit]
|
||||
incomplete = not more and boundary is not None and (not exhausted or frontier is not None and document_search.row_key(frontier, sort) >= boundary)
|
||||
base['hasMore'] = more or incomplete
|
||||
base['searchIncomplete'] = incomplete
|
||||
if query:
|
||||
if complete and not position:
|
||||
total = sum(1 for row in candidates if permitted(row))
|
||||
exact = True
|
||||
elif not base['hasMore']:
|
||||
total, exact = consumed + offset + len(page), True
|
||||
else:
|
||||
total, exact = consumed + offset + len(page) + int(more), False
|
||||
else:
|
||||
exact = metadata_exact
|
||||
if not exact:
|
||||
total = max(total, consumed + offset + len(page) + int(more))
|
||||
base['total'], base['totalExact'] = total, exact
|
||||
if base['hasMore'] and (page or frontier is not None):
|
||||
last = page[-1] if more else frontier
|
||||
base['nextCursor'] = document_search.encode_cursor(signature, document_search.row_position(last, sort),
|
||||
consumed + offset + len(page))
|
||||
items = []
|
||||
for row in page:
|
||||
# The portal shows file metadata, never extracted text. Computing FTS
|
||||
# snippets here repeats a potentially broad MATCH once per result.
|
||||
items.append(public_document(row, selected[row['source_id']]))
|
||||
if row['extension']:
|
||||
types.add(row['extension'].lstrip('.'))
|
||||
base['items'], base['types'] = items, sorted(types)
|
||||
return base
|
||||
|
||||
|
||||
|
||||
+2
-2
@@ -63,7 +63,7 @@ async function api(path, options = {}) {
|
||||
if (path.startsWith("/api/") && !["/api/login", "/api/logout", "/api/session"].includes(path)) path = "/admin" + path;
|
||||
const response = await fetch(path, {
|
||||
...options,
|
||||
headers: {"Content-Type": "application/json", ...(options.headers || {})},
|
||||
headers: {"Content-Type": "application/json", "X-CSRF-Token": path === "/api/login" ? "login" : state.session?.csrfToken || "", ...(options.headers || {})},
|
||||
credentials: "same-origin",
|
||||
});
|
||||
let body = {};
|
||||
@@ -93,7 +93,7 @@ function showLogin() {
|
||||
|
||||
function showApp(session) {
|
||||
if (session.role !== "domain-admin") { location.replace("/"); return; }
|
||||
state.session = {user: session.user, expiresAt: session.expiresAt};
|
||||
state.session = {user: session.user, expiresAt: session.expiresAt, csrfToken: session.csrfToken};
|
||||
document.querySelector("#session-user").textContent = session.user;
|
||||
loginView.hidden = true;
|
||||
appView.hidden = false;
|
||||
|
||||
+16
-16
@@ -17,11 +17,12 @@ function icon(name) {
|
||||
};
|
||||
return `<svg class="action-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">${paths[name]}</svg>`;
|
||||
}
|
||||
let session = null, offset = 0, listMode = false, timer, debounce, request, serial = 0, lastResult = "", activeDocument = null, initialFilters = null;
|
||||
let session = null, offset = 0, pageCursors = [""], listMode = false, timer, debounce, request, serial = 0, lastResult = "", activeDocument = null, initialFilters = null;
|
||||
const pageSize = 40;
|
||||
function resetPages() { offset = 0; pageCursors = [""]; serial++; request?.abort(); request = null; }
|
||||
|
||||
async function api(path, options = {}) {
|
||||
const response = await fetch(path, {...options,credentials:"same-origin",headers:{"Content-Type":"application/json",...(options.headers || {})}});
|
||||
const response = await fetch(path, {...options,credentials:"same-origin",headers:{"Content-Type":"application/json","X-CSRF-Token":path === "/api/login" ? "login" : session?.csrfToken || "",...(options.headers || {})}});
|
||||
let body = {};
|
||||
try { body = await response.json(); } catch (_) { /* Empty response. */ }
|
||||
if (response.status === 401) { showLogin(); throw new Error("Bitte erneut anmelden."); }
|
||||
@@ -47,7 +48,7 @@ function showFiles(value) {
|
||||
$("#login-view").hidden = true; $("#portal-view").hidden = false;
|
||||
const params = new URLSearchParams(location.search);
|
||||
initialFilters = {source:params.get("source") || "",type:params.get("type") || ""};
|
||||
offset = 0;
|
||||
resetPages();
|
||||
for (const [id,key] of [["search-query","q"],["search-scope","scope"],["sort-filter","sort"]]) {
|
||||
if (params.has(key)) $("#" + id).value = params.get(key);
|
||||
}
|
||||
@@ -55,7 +56,7 @@ function showFiles(value) {
|
||||
timer = setInterval(() => { if (!document.hidden && session) { refresh(false); if (activeDocument) loadDetail(activeDocument, false); } }, 2000);
|
||||
}
|
||||
function filters() {
|
||||
return new URLSearchParams({q:$("#search-query").value,scope:$("#search-scope").value || "all",source:$("#source-filter").value,type:$("#type-filter").value,sort:$("#sort-filter").value || "recent",limit:pageSize,offset});
|
||||
return new URLSearchParams({q:$("#search-query").value,scope:$("#search-scope").value || "all",source:$("#source-filter").value,type:$("#type-filter").value,sort:$("#sort-filter").value || "recent",limit:pageSize,offset,cursor:pageCursors[Math.floor(offset / pageSize)] || ""});
|
||||
}
|
||||
function updateOptions(select, items, firstLabel) {
|
||||
const current = select.value || (initialFilters && initialFilters[select.id === "source-filter" ? "source" : "type"]) || "";
|
||||
@@ -80,17 +81,16 @@ async function refresh(userAction = true) {
|
||||
history.replaceState({}, "", "/" + (params.get("q") || params.get("source") || params.get("type") ? "?" + params : ""));
|
||||
updateOptions($("#source-filter"), result.sources.map(source => ({id:source.id,label:source.kind === "private" ? "Mein Private-Ordner" : source.label})), "Alle Ordner");
|
||||
updateOptions($("#type-filter"), result.types.map(type => ({id:type,label:type.toUpperCase()})), "Alle Dateitypen");
|
||||
if (initialFilters) {
|
||||
const changed = $("#source-filter").value !== params.get("source") || $("#type-filter").value !== params.get("type");
|
||||
initialFilters = null;
|
||||
if (changed) { request = null; refresh(); return; }
|
||||
}
|
||||
$("#result-summary").textContent = `${result.total.toLocaleString("de-DE")} ${result.total === 1 ? "Datei" : "Dateien"}`;
|
||||
const changed = $("#source-filter").value !== params.get("source") || $("#type-filter").value !== params.get("type");
|
||||
initialFilters = null;
|
||||
if (changed) { resetPages(); refresh(); return; }
|
||||
pageCursors[Math.floor(offset / pageSize) + 1] = result.nextCursor || "";
|
||||
$("#result-summary").textContent = `${result.totalExact === false ? "Mindestens " : ""}${result.total.toLocaleString("de-DE")} ${result.total === 1 ? "Datei" : "Dateien"}`;
|
||||
$("#index-progress").hidden = !result.pending;
|
||||
$("#index-progress").textContent = result.pending ? `Text wird für ${result.pending} ${result.pending === 1 ? "Datei" : "Dateien"} erfasst.` : "";
|
||||
$("#index-progress").textContent = result.pending ? `Text wird für ${result.pendingExact === false ? "mindestens " : ""}${result.pending} ${result.pending === 1 ? "Datei" : "Dateien"} erfasst.` : "";
|
||||
$("#previous-page").disabled = offset === 0;
|
||||
$("#next-page").disabled = !result.hasMore;
|
||||
$("#page-label").textContent = result.total ? `Seite ${Math.floor(offset / pageSize) + 1}` : "";
|
||||
$("#page-label").textContent = result.total || result.hasMore ? `Seite ${Math.floor(offset / pageSize) + 1}` : "";
|
||||
const signature = JSON.stringify(result.items);
|
||||
if (signature !== lastResult) {
|
||||
lastResult = signature;
|
||||
@@ -134,10 +134,10 @@ $("#document-dialog").addEventListener("close", () => { activeDocument = null; $
|
||||
$("#document-close").addEventListener("click", () => $("#document-dialog").close());
|
||||
$("#documents").addEventListener("click", event => { const button = event.target.closest("[data-document]"); if (button) loadDetail(button.dataset.document); });
|
||||
$("#documents").addEventListener("error", event => { if (event.target.tagName === "IMG") event.target.hidden = true; }, true);
|
||||
$("#document-search").addEventListener("submit", event => { event.preventDefault(); clearTimeout(debounce); offset = 0; refresh(); });
|
||||
$("#search-query").addEventListener("input", () => { clearTimeout(debounce); offset = 0; debounce = setTimeout(() => refresh(), 200); });
|
||||
for (const id of ["search-scope", "source-filter", "type-filter", "sort-filter"]) $("#" + id).addEventListener("change", () => { offset = 0; refresh(); });
|
||||
$("#reset-filters").addEventListener("click", () => { $("#search-query").value = ""; $("#search-scope").value = "all"; $("#source-filter").value = ""; $("#type-filter").value = ""; offset = 0; refresh(); });
|
||||
$("#document-search").addEventListener("submit", event => { event.preventDefault(); clearTimeout(debounce); resetPages(); refresh(); });
|
||||
$("#search-query").addEventListener("input", () => { clearTimeout(debounce); resetPages(); debounce = setTimeout(() => refresh(), 200); });
|
||||
for (const id of ["search-scope", "source-filter", "type-filter", "sort-filter"]) $("#" + id).addEventListener("change", () => { resetPages(); refresh(); });
|
||||
$("#reset-filters").addEventListener("click", () => { $("#search-query").value = ""; $("#search-scope").value = "all"; $("#source-filter").value = ""; $("#type-filter").value = ""; resetPages(); refresh(); });
|
||||
$("#previous-page").addEventListener("click", () => { offset = Math.max(0, offset - pageSize); refresh(); });
|
||||
$("#next-page").addEventListener("click", () => { offset += pageSize; refresh(); });
|
||||
for (const [id,mode] of [["view-grid",false],["view-list",true]]) $("#" + id).addEventListener("click", () => {
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Persistent, revocable web sessions and strict browser-origin validation."""
|
||||
|
||||
import contextlib
|
||||
import hashlib
|
||||
import sqlite3
|
||||
import threading
|
||||
import urllib.parse
|
||||
|
||||
try:
|
||||
from .state_db import connect_state_db
|
||||
except ImportError:
|
||||
from state_db import connect_state_db
|
||||
|
||||
|
||||
class Sessions:
|
||||
def __init__(self, path=None):
|
||||
# Tests can use an isolated in-memory registry. Production passes the
|
||||
# persistent state database so logout survives a process restart.
|
||||
self.memory = sqlite3.connect(':memory:', check_same_thread=False) if path is None else None
|
||||
if self.memory:
|
||||
self.memory.row_factory = sqlite3.Row
|
||||
self.path = path
|
||||
self.lock = threading.RLock()
|
||||
with self.connection() as conn:
|
||||
conn.execute('''CREATE TABLE IF NOT EXISTS web_sessions (
|
||||
id TEXT PRIMARY KEY, sid TEXT NOT NULL, expires INTEGER NOT NULL,
|
||||
username TEXT NOT NULL, uid INTEGER, role TEXT NOT NULL, checked REAL NOT NULL)''')
|
||||
conn.execute('CREATE INDEX IF NOT EXISTS web_sessions_expiry ON web_sessions(expires)')
|
||||
conn.commit()
|
||||
|
||||
@contextlib.contextmanager
|
||||
def connection(self):
|
||||
with self.lock:
|
||||
if self.memory is None and self.path is None:
|
||||
raise RuntimeError('Session registry is closed')
|
||||
conn = self.memory if self.memory is not None else connect_state_db(self.path)
|
||||
try:
|
||||
yield conn
|
||||
finally:
|
||||
if self.memory is None:
|
||||
conn.close()
|
||||
|
||||
@staticmethod
|
||||
def key(jti):
|
||||
return hashlib.sha256(jti.encode()).hexdigest()
|
||||
|
||||
def issue(self, payload):
|
||||
with self.connection() as conn, conn:
|
||||
conn.execute('DELETE FROM web_sessions WHERE expires<=?', (payload['iat'],))
|
||||
conn.execute('INSERT INTO web_sessions VALUES(?,?,?,?,?,?,?)',
|
||||
(self.key(payload['jti']), payload['sid'], payload['exp'], payload['sub'],
|
||||
payload['uid'], payload['role'], payload['iat']))
|
||||
|
||||
def get(self, jti, now):
|
||||
with self.connection() as conn:
|
||||
row = conn.execute('SELECT * FROM web_sessions WHERE id=? AND expires>?',
|
||||
(self.key(jti), now)).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
def refresh(self, jti, identity, now):
|
||||
# UPDATE cannot resurrect a session logged out during the AD lookup.
|
||||
with self.connection() as conn, conn:
|
||||
conn.execute('UPDATE web_sessions SET username=?,uid=?,role=?,checked=? WHERE id=?',
|
||||
(identity['sub'], identity['uid'], identity['role'], now, self.key(jti)))
|
||||
|
||||
def revoke(self, jti):
|
||||
with self.connection() as conn, conn:
|
||||
conn.execute('DELETE FROM web_sessions WHERE id=?', (self.key(jti),))
|
||||
|
||||
def close(self):
|
||||
with self.lock:
|
||||
if self.memory is not None:
|
||||
self.memory.close()
|
||||
self.memory = None
|
||||
|
||||
def __del__(self):
|
||||
if getattr(self, 'memory', None) is not None:
|
||||
self.memory.close()
|
||||
|
||||
|
||||
def origin(value):
|
||||
try:
|
||||
parsed = urllib.parse.urlsplit(value)
|
||||
if parsed.scheme != 'https' or not parsed.hostname or parsed.username is not None or parsed.password is not None:
|
||||
raise ValueError()
|
||||
if parsed.path or parsed.query or parsed.fragment or any(char.isspace() for char in value):
|
||||
raise ValueError()
|
||||
port = 443 if parsed.port is None else parsed.port
|
||||
if port == 0 or parsed.netloc.endswith(':'):
|
||||
raise ValueError()
|
||||
host = parsed.hostname.casefold()
|
||||
return host, port
|
||||
except ValueError as exc:
|
||||
raise ValueError('Invalid HTTPS origin') from exc
|
||||
+159
-51
@@ -27,11 +27,11 @@ from typing import Dict, List, Optional, Tuple
|
||||
|
||||
try:
|
||||
from app import reconcile_shares as directory
|
||||
from app import trash, access_control, documents
|
||||
from app import trash, access_control, documents, web_security
|
||||
from app.account_policy import is_excluded_user
|
||||
except ImportError: # Container execution uses /app as the import root.
|
||||
import reconcile_shares as directory
|
||||
import trash, access_control, documents
|
||||
import trash, access_control, documents, web_security
|
||||
from account_policy import is_excluded_user
|
||||
|
||||
try:
|
||||
@@ -77,7 +77,7 @@ JWT_ISSUER = "ad-file-server-web"
|
||||
JWT_AUDIENCE = "ad-users"
|
||||
DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
||||
SID_RE = re.compile(r"S-\d+(?:-\d+)+", re.IGNORECASE)
|
||||
LOGIN_LIMIT: Dict[str, deque] = {}
|
||||
LOGIN_LIMIT: Dict[tuple, deque] = {}
|
||||
LOGIN_LIMIT_LOCK = threading.Lock()
|
||||
ACTION_LAUNCH_LOCK = threading.Lock()
|
||||
ACTIVE_PROCESS_STATES = frozenset({"starting", "running"})
|
||||
@@ -256,11 +256,13 @@ def base64url_decode(value: str) -> bytes:
|
||||
|
||||
|
||||
class TokenManager:
|
||||
def __init__(self, secret: str, ttl_seconds: int):
|
||||
def __init__(self, secret: str, ttl_seconds: int, sessions=None, identity_resolver=None):
|
||||
if len(secret.encode("utf-8")) < 32:
|
||||
raise RuntimeError("WEB_JWT_SECRET must contain at least 32 bytes")
|
||||
self.secret = secret.encode("utf-8")
|
||||
self.ttl_seconds = ttl_seconds
|
||||
self.sessions = sessions if sessions is not None else web_security.Sessions()
|
||||
self.identity_resolver = identity_resolver
|
||||
|
||||
def issue(self, username: str, sid: str, role: str = "user", uid: Optional[int] = None) -> Tuple[str, int]:
|
||||
issued = int(time.time())
|
||||
@@ -284,9 +286,10 @@ class TokenManager:
|
||||
]
|
||||
)
|
||||
signature = hmac.new(self.secret, signing_input.encode(), hashlib.sha256).digest()
|
||||
self.sessions.issue(payload)
|
||||
return f"{signing_input}.{base64url(signature)}", expires
|
||||
|
||||
def verify(self, token: str) -> Dict[str, object]:
|
||||
def verify(self, token: str, refresh_identity: bool = True) -> Dict[str, object]:
|
||||
try:
|
||||
encoded_header, encoded_payload, encoded_signature = token.split(".")
|
||||
signing_input = f"{encoded_header}.{encoded_payload}"
|
||||
@@ -308,10 +311,34 @@ class TokenManager:
|
||||
raise ValueError("expired")
|
||||
if int(payload.get("iat", 0)) > int(time.time()) + 60:
|
||||
raise ValueError("issued")
|
||||
jti = payload.get('jti')
|
||||
if not isinstance(jti, str) or not jti or len(jti) > 128:
|
||||
raise ValueError('session id')
|
||||
current = self.sessions.get(jti, time.time())
|
||||
if current is None or current['sid'] != payload['sid'] or current['expires'] != payload['exp']:
|
||||
raise ValueError('revoked')
|
||||
interval = env_int('WEB_AUTH_RECHECK_SECONDS', 60, 5, 300)
|
||||
if refresh_identity and self.identity_resolver and time.time() - current['checked'] >= interval:
|
||||
identity = self.identity_resolver(payload['sid'])
|
||||
if identity is None or identity.get('sid') != payload['sid']:
|
||||
# Fail closed on an unavailable directory; do not keep
|
||||
# trusting old admin claims while winbind is unreachable.
|
||||
raise ValueError('directory unavailable')
|
||||
self.sessions.refresh(jti, identity, time.time())
|
||||
current = self.sessions.get(jti, time.time())
|
||||
if current is None:
|
||||
raise ValueError('revoked')
|
||||
payload.update(sub=current['username'], uid=current['uid'], role=current['role'])
|
||||
return payload
|
||||
except (TypeError, ValueError, KeyError, json.JSONDecodeError) as exc:
|
||||
raise ValueError("Invalid or expired session") from exc
|
||||
|
||||
def csrf(self, payload):
|
||||
return base64url(hmac.new(self.secret, ('csrf:' + payload['jti']).encode(), hashlib.sha256).digest())
|
||||
|
||||
def revoke(self, payload):
|
||||
self.sessions.revoke(payload['jti'])
|
||||
|
||||
|
||||
def normalize_username(username: str) -> str:
|
||||
username = username.strip()
|
||||
@@ -406,20 +433,21 @@ def authenticate_user(username: str, password: str) -> Optional[Dict[str, str]]:
|
||||
user_sid_match = SID_RE.search(sid_result.stdout)
|
||||
if sid_result.returncode != 0 or user_sid_match is None:
|
||||
return None
|
||||
group_result = subprocess.run(
|
||||
["wbinfo", "--user-sids", user_sid_match.group(0)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=15,
|
||||
check=False,
|
||||
)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return None
|
||||
return current_identity(user_sid_match.group(0))
|
||||
|
||||
|
||||
def current_identity(sid: str):
|
||||
try:
|
||||
group_result = subprocess.run(["wbinfo", "--user-sids", sid], capture_output=True,
|
||||
text=True, timeout=15, check=False)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return None
|
||||
if group_result.returncode != 0:
|
||||
return None
|
||||
admin_sid = os.environ["DOMAIN_ADMINS_SID"].casefold()
|
||||
group_sids = {value.casefold() for value in SID_RE.findall(group_result.stdout)}
|
||||
sid = user_sid_match.group(0)
|
||||
try:
|
||||
resolved = subprocess.run(["wbinfo", "--sid-to-name", sid], capture_output=True, text=True, timeout=15, check=False)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
@@ -444,25 +472,27 @@ def authenticate_domain_admin(username: str, password: str) -> Optional[str]:
|
||||
return identity["sub"] if identity and identity["role"] == "domain-admin" else None
|
||||
|
||||
|
||||
def login_allowed(remote: str) -> bool:
|
||||
def reserve_login(remote: str, username: str) -> bool:
|
||||
now = time.monotonic()
|
||||
window = 300
|
||||
limit = env_int("WEB_LOGIN_ATTEMPTS_PER_5_MIN", 10, 3, 100)
|
||||
ip_limit = env_int("WEB_LOGIN_ATTEMPTS_PER_5_MIN", 10, 3, 100)
|
||||
account_limit = env_int('WEB_LOGIN_ACCOUNT_ATTEMPTS_PER_5_MIN', 10, 3, 100)
|
||||
# The supported domain-qualified spellings share the same target budget.
|
||||
account = username.strip().rsplit('\\', 1)[-1].split('@', 1)[0].casefold()[:256]
|
||||
keys = (('ip', remote), ('account', account))
|
||||
with LOGIN_LIMIT_LOCK:
|
||||
attempts = LOGIN_LIMIT.setdefault(remote, deque())
|
||||
while attempts and now - attempts[0] > window:
|
||||
attempts.popleft()
|
||||
return len(attempts) < limit
|
||||
|
||||
|
||||
def record_login_failure(remote: str) -> None:
|
||||
with LOGIN_LIMIT_LOCK:
|
||||
LOGIN_LIMIT.setdefault(remote, deque()).append(time.monotonic())
|
||||
|
||||
|
||||
def clear_login_failures(remote: str) -> None:
|
||||
with LOGIN_LIMIT_LOCK:
|
||||
LOGIN_LIMIT.pop(remote, None)
|
||||
for key in list(LOGIN_LIMIT):
|
||||
attempts = LOGIN_LIMIT[key]
|
||||
while attempts and now - attempts[0] >= window:
|
||||
attempts.popleft()
|
||||
if not attempts:
|
||||
del LOGIN_LIMIT[key]
|
||||
attempts = [LOGIN_LIMIT.get(key, ()) for key in keys]
|
||||
if len(attempts[0]) >= ip_limit or len(attempts[1]) >= account_limit:
|
||||
return False
|
||||
for key in keys:
|
||||
LOGIN_LIMIT.setdefault(key, deque()).append(now)
|
||||
return True
|
||||
|
||||
|
||||
def path_size(path: str) -> int:
|
||||
@@ -760,7 +790,8 @@ def tls_summary() -> Dict[str, object]:
|
||||
class App:
|
||||
def __init__(self):
|
||||
secret = os.environ.get("WEB_JWT_SECRET", "")
|
||||
self.tokens = TokenManager(secret, env_int("WEB_JWT_TTL_SECONDS", 28800, 300, 604800))
|
||||
self.tokens = TokenManager(secret, env_int("WEB_JWT_TTL_SECONDS", 28800, 300, 604800),
|
||||
web_security.Sessions(STATE_DB), current_identity)
|
||||
removed = drop_legacy_web_cache()
|
||||
if removed:
|
||||
log(f"Dropped {removed} legacy web cache file(s)")
|
||||
@@ -877,23 +908,24 @@ class Handler(BaseHTTPRequestHandler):
|
||||
morsel = cookie.get(JWT_COOKIE)
|
||||
return morsel.value if morsel else None
|
||||
|
||||
def user(self) -> Optional[Dict[str, object]]:
|
||||
def user(self, refresh_identity: bool = True) -> Optional[Dict[str, object]]:
|
||||
token = self.token()
|
||||
if not token:
|
||||
return None
|
||||
try:
|
||||
return APP.tokens.verify(token) if APP else None
|
||||
return APP.tokens.verify(token, refresh_identity=refresh_identity) if APP else None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
def require_user(self) -> Optional[Dict[str, object]]:
|
||||
value = self.user()
|
||||
def require_user(self, refresh_identity: bool = True) -> Optional[Dict[str, object]]:
|
||||
value = self.user(refresh_identity=refresh_identity)
|
||||
if value is None:
|
||||
self.send_error_json(HTTPStatus.UNAUTHORIZED, "Anmeldung erforderlich")
|
||||
return value
|
||||
|
||||
def require_admin(self) -> Optional[Dict[str, object]]:
|
||||
value = self.require_user()
|
||||
def require_admin(self, value=None) -> Optional[Dict[str, object]]:
|
||||
if value is None:
|
||||
value = self.require_user()
|
||||
if value is not None and value.get("role") != "domain-admin":
|
||||
self.send_error_json(HTTPStatus.FORBIDDEN, "Domänenadministrator erforderlich")
|
||||
return None
|
||||
@@ -914,6 +946,40 @@ class Handler(BaseHTTPRequestHandler):
|
||||
raise ValueError("Ein JSON-Objekt ist erforderlich")
|
||||
return value
|
||||
|
||||
def check_write_origin(self) -> bool:
|
||||
if self.headers.get_content_type() != 'application/json':
|
||||
self.send_error_json(HTTPStatus.UNSUPPORTED_MEDIA_TYPE, 'application/json erforderlich')
|
||||
return False
|
||||
value = self.headers.get('Origin')
|
||||
if value is not None:
|
||||
configured = os.getenv('WEB_TRUSTED_ORIGINS', '').strip()
|
||||
if not configured:
|
||||
hostname = os.getenv('WEB_HOSTNAME', os.getenv('AD_DNS_NAME', 'localhost'))
|
||||
port = env_int('WEB_HTTPS_PORT', 443, 1, 65535)
|
||||
configured = f'https://{hostname}' + (f':{port}' if port != 443 else '')
|
||||
try:
|
||||
allowed = {web_security.origin(item.strip()) for item in configured.split(',')}
|
||||
if web_security.origin(value) not in allowed:
|
||||
raise ValueError()
|
||||
except ValueError:
|
||||
self.send_error_json(HTTPStatus.FORBIDDEN, 'Nicht vertrauenswürdiger Origin')
|
||||
return False
|
||||
if self.headers.get('Sec-Fetch-Site') in {'cross-site', 'same-site'}:
|
||||
self.send_error_json(HTTPStatus.FORBIDDEN, 'Anfrage muss vom selben Origin stammen')
|
||||
return False
|
||||
return True
|
||||
|
||||
def check_csrf(self, user) -> bool:
|
||||
supplied = self.headers.get('X-CSRF-Token', '')
|
||||
# Origin-less API clients must explicitly carry their bearer token;
|
||||
# browser cookie requests always need an exact trusted Origin as well.
|
||||
bearer = self.headers.get('Authorization', '').startswith('Bearer ')
|
||||
if (not self.headers.get('Origin') and not bearer or
|
||||
not hmac.compare_digest(supplied.encode('utf-8'), APP.tokens.csrf(user).encode('ascii'))):
|
||||
self.send_error_json(HTTPStatus.FORBIDDEN, 'Ungültiger CSRF-Schutz')
|
||||
return False
|
||||
return True
|
||||
|
||||
def send_trash_download(self, params: Dict[str, List[str]]) -> None:
|
||||
item_id = params.get("id", [""])[0]
|
||||
try:
|
||||
@@ -953,23 +1019,29 @@ class Handler(BaseHTTPRequestHandler):
|
||||
|
||||
def do_POST(self) -> None: # pylint: disable=invalid-name
|
||||
parsed = urllib.parse.urlparse(self.path)
|
||||
if not self.check_write_origin():
|
||||
return
|
||||
if parsed.path == "/api/login":
|
||||
remote = self.client_address[0]
|
||||
if not login_allowed(remote):
|
||||
self.send_error_json(HTTPStatus.TOO_MANY_REQUESTS, "Zu viele Anmeldeversuche; bitte später erneut versuchen")
|
||||
# Login has no authenticated session yet. A custom header and JSON
|
||||
# prevent simple cross-origin requests; Origin is checked above.
|
||||
if self.headers.get('X-CSRF-Token') != 'login':
|
||||
self.send_error_json(HTTPStatus.FORBIDDEN, 'Ungültiger CSRF-Schutz')
|
||||
return
|
||||
remote = self.client_address[0]
|
||||
try:
|
||||
body = self.read_json_body()
|
||||
except ValueError as exc:
|
||||
self.send_error_json(HTTPStatus.BAD_REQUEST, str(exc))
|
||||
return
|
||||
identity = authenticate_user(str(body.get("username", "")), str(body.get("password", "")))
|
||||
username = str(body.get('username', ''))
|
||||
if not reserve_login(remote, username):
|
||||
self.send_error_json(HTTPStatus.TOO_MANY_REQUESTS, "Zu viele Anmeldeversuche; bitte später erneut versuchen")
|
||||
return
|
||||
identity = authenticate_user(username, str(body.get("password", "")))
|
||||
if identity is None:
|
||||
record_login_failure(remote)
|
||||
time.sleep(0.4)
|
||||
self.send_error_json(HTTPStatus.UNAUTHORIZED, "Ungültige Zugangsdaten")
|
||||
return
|
||||
clear_login_failures(remote)
|
||||
token, expires = APP.tokens.issue(identity["sub"], identity["sid"], identity["role"], identity["uid"])
|
||||
conn = directory.open_db()
|
||||
try:
|
||||
@@ -982,16 +1054,25 @@ class Handler(BaseHTTPRequestHandler):
|
||||
conn.close()
|
||||
max_age = max(0, expires - int(time.time()))
|
||||
cookie = f"{JWT_COOKIE}={token}; Path=/; Max-Age={max_age}; HttpOnly; Secure; SameSite=Strict"
|
||||
self.send_json({"user": identity["sub"], "sid": identity["sid"], "role": identity["role"], "expiresAt": expires, "token": token, "tokenType": "Bearer"}, cookie=cookie)
|
||||
payload = APP.tokens.verify(token)
|
||||
self.send_json({"user": identity["sub"], "sid": identity["sid"], "role": identity["role"], "expiresAt": expires, "token": token, "tokenType": "Bearer", 'csrfToken': APP.tokens.csrf(payload)}, cookie=cookie)
|
||||
return
|
||||
if parsed.path == "/api/logout":
|
||||
# Revoking a valid session must also work during an AD outage.
|
||||
user = self.require_user(refresh_identity=False)
|
||||
if user is None or not self.check_csrf(user):
|
||||
return
|
||||
APP.tokens.revoke(user)
|
||||
cookie = f"{JWT_COOKIE}=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Strict"
|
||||
self.send_json({"ok": True}, cookie=cookie)
|
||||
return
|
||||
if not parsed.path.startswith("/admin/api/"):
|
||||
self.send_error_json(HTTPStatus.NOT_FOUND, "Nicht gefunden")
|
||||
return
|
||||
administrator = self.require_admin()
|
||||
user = self.require_user()
|
||||
if user is None or not self.check_csrf(user):
|
||||
return
|
||||
administrator = self.require_admin(user)
|
||||
if administrator is None:
|
||||
return
|
||||
parsed = parsed._replace(path=parsed.path[len("/admin"):])
|
||||
@@ -1115,19 +1196,17 @@ class Handler(BaseHTTPRequestHandler):
|
||||
return
|
||||
params = urllib.parse.parse_qs(parsed.query)
|
||||
if path == "/api/session":
|
||||
self.send_json({"user": user["sub"], "sid": user["sid"], "role": user["role"], "expiresAt": user["exp"]})
|
||||
self.send_json({"user": user["sub"], "sid": user["sid"], "role": user["role"], "expiresAt": user["exp"], 'csrfToken': APP.tokens.csrf(user)})
|
||||
elif path == "/api/documents" or path.startswith("/api/documents/"):
|
||||
self.document_request(path, params, user)
|
||||
else:
|
||||
self.send_error_json(HTTPStatus.NOT_FOUND, "Nicht gefunden")
|
||||
return
|
||||
if path.startswith("/admin/api/"):
|
||||
if self.require_admin() is None:
|
||||
return
|
||||
path = path[len("/admin"):]
|
||||
user = self.require_user()
|
||||
user = self.require_admin()
|
||||
if user is None:
|
||||
return
|
||||
path = path[len("/admin"):]
|
||||
params = urllib.parse.parse_qs(parsed.query)
|
||||
try:
|
||||
if path == "/api/session":
|
||||
@@ -1342,6 +1421,36 @@ class ReusableHTTPServer(ThreadingHTTPServer):
|
||||
allow_reuse_address = True
|
||||
daemon_threads = True
|
||||
|
||||
def __init__(self, address, handler, tls_context=None):
|
||||
self.tls_context = tls_context
|
||||
self.connections = threading.BoundedSemaphore(env_int('WEB_MAX_CONNECTIONS', 64, 4, 512))
|
||||
super().__init__(address, handler)
|
||||
|
||||
def process_request(self, request, client_address):
|
||||
# Never wait for TLS or a free worker in the accept loop.
|
||||
if not self.connections.acquire(blocking=False):
|
||||
self.shutdown_request(request)
|
||||
return
|
||||
try:
|
||||
super().process_request(request, client_address)
|
||||
except Exception:
|
||||
self.connections.release()
|
||||
raise
|
||||
|
||||
def process_request_thread(self, request, client_address):
|
||||
connection = request
|
||||
try:
|
||||
if self.tls_context is not None:
|
||||
request.settimeout(env_int('WEB_TLS_HANDSHAKE_TIMEOUT_SECONDS', 5, 1, 30))
|
||||
connection = self.tls_context.wrap_socket(request, server_side=True, do_handshake_on_connect=False)
|
||||
connection.do_handshake()
|
||||
connection.settimeout(env_int('WEB_REQUEST_TIMEOUT_SECONDS', 30, 1, 300))
|
||||
super().process_request_thread(connection, client_address)
|
||||
except OSError:
|
||||
self.shutdown_request(connection)
|
||||
finally:
|
||||
self.connections.release()
|
||||
|
||||
|
||||
def serve_https() -> None:
|
||||
address = os.getenv("WEB_BIND_ADDRESS", "0.0.0.0")
|
||||
@@ -1352,9 +1461,8 @@ def serve_https() -> None:
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
context.load_cert_chain(TLS_CERT_FILE, TLS_KEY_FILE)
|
||||
server = ReusableHTTPServer((address, port), Handler)
|
||||
server = ReusableHTTPServer((address, port), Handler, tls_context=context)
|
||||
server.timeout = 1
|
||||
server.socket = context.wrap_socket(server.socket, server_side=True)
|
||||
cert_mtime = os.path.getmtime(TLS_CERT_FILE)
|
||||
try:
|
||||
while os.path.getmtime(TLS_CERT_FILE) == cert_mtime:
|
||||
|
||||
Reference in new issue
Block a user