diff --git a/.env.example b/.env.example index 9d9cd01..1931fbd 100644 --- a/.env.example +++ b/.env.example @@ -27,9 +27,15 @@ ACME_HTTP_PORT=80 # WEB_TLS_CERT_FILE=/state/tls/web.crt # WEB_TLS_KEY_FILE=/state/tls/web.key # WEB_JWT_TTL_SECONDS=28800 +# WEB_AUTH_RECHECK_SECONDS=60 +# WEB_TRUSTED_ORIGINS=https://files.example.com +# WEB_TLS_HANDSHAKE_TIMEOUT_SECONDS=5 +# WEB_REQUEST_TIMEOUT_SECONDS=30 +# WEB_MAX_CONNECTIONS=64 # WEB_USAGE_SCAN_INTERVAL_SECONDS=900 # WEB_DIRECTORY_CACHE_SECONDS=300 # WEB_LOGIN_ATTEMPTS_PER_5_MIN=10 +# WEB_LOGIN_ACCOUNT_ATTEMPTS_PER_5_MIN=10 # DOCUMENT_SCAN_SECONDS=30 # DOCUMENT_OCR_LANGUAGE=deu+eng # DOCUMENT_OCR_TIMEOUT_SECONDS=600 diff --git a/Dockerfile b/Dockerfile index e91239d..18e4ea2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -45,8 +45,10 @@ COPY app/audit_store.py /app/audit_store.py COPY app/audit_collector.py /app/audit_collector.py COPY app/trash.py /app/trash.py COPY app/web_ui.py /app/web_ui.py +COPY app/web_security.py /app/web_security.py COPY app/document_types.py /app/document_types.py COPY app/documents.py /app/documents.py +COPY app/document_search.py /app/document_search.py COPY app/document_index.py /app/document_index.py COPY app/extract_document.py /app/extract_document.py COPY app/web /app/web diff --git a/README.md b/README.md index 5156fd5..b840cdd 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,10 @@ The catalog includes active Data folders and each user's own Private folder. Eve Linux filesystem events update the filename catalog as files change, with periodic scans recovering missed events. Text extraction and OCR run through a persistent background queue; files become searchable by filename before content extraction finishes. Search updates while typing, and open views refresh every two seconds to show completed extraction. Full-text queries match word prefixes and ignore accents; filename-only queries also match substrings. +Search stays in SQLite. FTS5 indexes text together with folder and file-type tokens; a compact character index also covers filename substrings and one- or two-character searches. Composite B-tree indexes cover folder/type filters and the UI's name, newest-first and oldest-first sorting. Pagination uses filter-bound cursors. Name and date sorting seek into their B-tree indexes; relevance uses FTS5's native ordered stream so ongoing OCR updates cannot invalidate a saved score threshold. Counts, file-type options and queue progress use incrementally maintained summaries. Broad text searches show a lower bound rather than delay results for an exact count. Large Private folders use bounded, current permission checks for facets and page candidates; their totals may also be lower bounds. Original files are checked before an item is returned, and current permissions are checked again for previews and downloads. + +The first start after this upgrade rebuilds the derived search indexes and summaries once. It preserves document IDs, previews, OCR jobs, pause state, permissions and original files. `python3 scripts/benchmark-document-search --rows 2000000` creates an isolated synthetic catalog and measures 64 combinations of search scope, sorting and folder/type filters plus deep cursor pages for metadata and relevance ordering. It uses a small original-file fixture rather than creating two million physical files. `--database /tmp/adfs-search-benchmark.db` retains that disposable catalog for repeat runs. + Content search indexes only PDFs, Word documents (`docx`, `odt`) and PowerPoint presentations (`pptx`, `odp`). All file types remain searchable by filename, including text, Markdown, spreadsheets and images. Existing extracted content from excluded types is removed from the derived search index on upgrade; original files and filename entries remain intact. PDFs and common images receive a first-page/image thumbnail. PDFs open in a fullscreen dialog with the locally bundled Mozilla PDF.js viewer, including page navigation, zoom, thumbnails and search within native PDF text. PDF loading and byte-range requests check current folder access. Legacy binary Office formats (`doc`, `ppt`) remain searchable by filename. Extracted text is limited to 2 MiB per file; encrypted, damaged, or oversized documents may have no searchable content. Only PDF pages that themselves contain raster images and little extracted text are queued for local OCR using Poppler and Tesseract, with German and English enabled by default. Search OCR renders those pages at 300 DPI, capped at 3500 pixels on the longest side, instead of inheriting high DPI from embedded logos or rebuilding an OCR PDF. Each render and recognition step has a 30-second timeout. Photos can still require a recognition attempt to establish whether they contain text; text-free pages finish without adding search content. Native text remains searchable while OCR is pending. OCR text is used for search. No file type displays a separate extracted document-text panel in its dialog. The PDF viewer displays the original PDF. Downloads always return the original file. No OCR replacement or separate OCR PDF is published. Failed jobs retry with backoff, and pending work survives restarts. @@ -372,7 +376,7 @@ Domain Admins can use **Papierkorb** in the web console to filter and list retai ## Web Administration Console -Open `https:///` after setup. Only members of the group identified by `DOMAIN_ADMINS_SID` can sign in. The form accepts `DOMAIN\username`, `username@realm`, or an unqualified username (which is qualified with `WORKGROUP`). +Open `https:///` after setup to search files. Domain Admins can open the administration console at `/admin/`; its APIs require membership in the group identified by `DOMAIN_ADMINS_SID`. The form accepts `DOMAIN\username`, `username@realm`, or an unqualified username (which is qualified with `WORKGROUP`). The console is intentionally operational and plain: @@ -389,15 +393,17 @@ The console is intentionally operational and plain: The PDF report deliberately excludes the activity log and backup log. Its dedicated snapshot endpoint removes those fields before returning data. Typst, its WebAssembly compiler, and the report fonts are shipped with the application; Typst source and PDF bytes are created only in the authenticated browser and are never uploaded to another service. The first export downloads roughly 22 MiB of compiler/font assets, which are then cached as immutable files. The CSP grants only `'wasm-unsafe-eval'` for WebAssembly compilation and does not enable JavaScript `'unsafe-eval'`. -The mutation endpoints manage Data access (`POST /api/access`), restore retained files, or start an immediate backup/share reconciliation; all require the same Domain Admin JWT as every protected page. Restore cannot overwrite a live file. Backup schedules, retention, and `BACKUP_AUTO_ENABLED` are configured through the environment. Automatic backups can be enabled or disabled only through the environment and therefore require a redeployment/restart. +The mutation endpoints under `/admin/api/` manage Data access, restore retained files, control indexing, or start an immediate backup/share reconciliation. They require an active Domain Admin session and CSRF protection. Restore cannot overwrite a live file. Backup schedules, retention, and `BACKUP_AUTO_ENABLED` are configured through the environment. Automatic backups can be enabled or disabled only through the environment and therefore require a redeployment/restart. ### Authentication and sessions - Credentials are submitted only over HTTPS. The password is passed to `kinit` through stdin, is never placed in a process argument, and the temporary Kerberos credential cache is immediately removed. -- After Kerberos succeeds, the service resolves the account SID and its complete group SID set through winbind. Login succeeds only when that set contains `DOMAIN_ADMINS_SID`. +- After Kerberos succeeds, the service resolves the account SID, Unix UID and complete group SID set through winbind. Human AD users can sign in; only members of `DOMAIN_ADMINS_SID` receive administration access. Sessions recheck that identity through winbind on their first request after `WEB_AUTH_RECHECK_SECONDS` (default 60 seconds). Directory failures deny data and administration requests; directory caching can delay visibility of an AD change. - Authentication is form-based; the browser never performs NTLM, SPNEGO, or Kerberos negotiation. -- JWTs use HMAC-SHA256, default to eight hours, and are accepted from the protected cookie or an `Authorization: Bearer` header. -- Login attempts are rate-limited per client address. +- JWTs use HMAC-SHA256, default to eight hours, and are accepted from the protected cookie or an `Authorization: Bearer` header. An active session entry in SQLite is also required. Logout removes that entry immediately, including for bearer-token reuse, and revocation survives restarts. Logout also works during directory outages. Existing sessions issued before this upgrade require a new login. +- Every POST requires `application/json`. Browser requests must originate from the exact configured HTTPS origin, derived from `WEB_HOSTNAME` and the external `WEB_HTTPS_PORT` (default 443), or explicitly listed in `WEB_TRUSTED_ORIGINS`. The service ignores Host and forwarded headers when determining trusted origins. Authenticated changes and logout require the session's `csrfToken` from login or `GET /api/session` in `X-CSRF-Token`. Login requires `X-CSRF-Token: login`; origin-less API clients must use an explicit bearer token and the session's CSRF token for authenticated changes. No cross-origin CORS access is granted. +- Login attempts are reserved atomically before authentication, with separate five-minute limits for client address and target account across client addresses. Successful logins consume a reservation and do not reset either limit. Case variations and the supported domain-qualified spellings of an account share a budget. +- TLS handshakes run in bounded connection workers, outside the accept loop, with a five-second timeout. Request I/O also has a timeout. - Responses set HSTS, a restrictive Content Security Policy, clickjacking protection, and MIME sniffing protection. APIs and ordinary UI assets use no-store caching; pinned Typst compiler/font assets use immutable long-term caching. ### TLS with an internal ACME CA @@ -467,7 +473,13 @@ Useful optional settings: | `WEB_TLS_AUTORENEW` | `true` | Renew managed certificates automatically | | `ACME_RENEW_CHECK_SECONDS` | `900` | Interval for ACME renewal checks; minimum 60 seconds | | `WEB_JWT_TTL_SECONDS` | `28800` | Session lifetime, 5 minutes to 7 days | -| `WEB_LOGIN_ATTEMPTS_PER_5_MIN` | `10` | Per-address login attempt limit | +| `WEB_AUTH_RECHECK_SECONDS` | `60` | Session identity/role recheck interval via winbind, 5 to 300 seconds | +| `WEB_TRUSTED_ORIGINS` | derived | Comma-separated exact HTTPS origins; default uses `WEB_HOSTNAME` and `WEB_HTTPS_PORT` | +| `WEB_LOGIN_ATTEMPTS_PER_5_MIN` | `10` | Per-address login attempt limit, including successful attempts | +| `WEB_LOGIN_ACCOUNT_ATTEMPTS_PER_5_MIN` | `10` | Per-target-account login attempt limit across client addresses | +| `WEB_TLS_HANDSHAKE_TIMEOUT_SECONDS` | `5` | TLS handshake deadline, 1 to 30 seconds | +| `WEB_REQUEST_TIMEOUT_SECONDS` | `30` | Request I/O timeout, 1 to 300 seconds | +| `WEB_MAX_CONNECTIONS` | `64` | Concurrent connection workers, 4 to 512; excess connections are closed | | `WEB_USAGE_SCAN_INTERVAL_SECONDS` | `900` | Recursive storage scan interval | | `WEB_DIRECTORY_CACHE_SECONDS` | `300` | AD membership tree cache time | | `TRASH_RETENTION_DAYS` | `7` | Recycled-file lifetime; cleanup accepts 1 to 365 days | diff --git a/app/document_search.py b/app/document_search.py new file mode 100644 index 0000000..4a0555c --- /dev/null +++ b/app/document_search.py @@ -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 diff --git a/app/documents.py b/app/documents.py index f3f3fb1..0bb123d 100644 --- a/app/documents.py +++ b/app/documents.py @@ -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 diff --git a/app/web/app.js b/app/web/app.js index 448f383..84f5266 100644 --- a/app/web/app.js +++ b/app/web/app.js @@ -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; diff --git a/app/web/portal.js b/app/web/portal.js index f6221a4..572df79 100644 --- a/app/web/portal.js +++ b/app/web/portal.js @@ -17,11 +17,12 @@ function icon(name) { }; return ``; } -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", () => { diff --git a/app/web_security.py b/app/web_security.py new file mode 100644 index 0000000..612110b --- /dev/null +++ b/app/web_security.py @@ -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 diff --git a/app/web_ui.py b/app/web_ui.py index c39f0dc..b53edb0 100644 --- a/app/web_ui.py +++ b/app/web_ui.py @@ -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: diff --git a/scripts/benchmark-document-search b/scripts/benchmark-document-search new file mode 100644 index 0000000..d7efd07 --- /dev/null +++ b/scripts/benchmark-document-search @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 +"""Isolated search benchmark; never opens production state or document roots. + +Usage: python3 scripts/benchmark-document-search --rows 2000000 +Original-file checks use one tiny fixture; catalog/FTS/index SQL is real. +""" +import argparse +import contextlib +import json +import os +from pathlib import Path +import sqlite3 +import statistics +import sys +import tempfile +import time +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from app import documents, document_search +from app.state_db import connect_state_db + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument('--rows', type=int, default=200000) +parser.add_argument('--database', help='Create/reuse a benchmark DB at this new, disposable path') +parser.add_argument('--repeat', type=int, default=3) +parser.add_argument('--query-only', action='store_true', help='Read an existing benchmark without migration or writes') +args = parser.parse_args() +if args.rows < 1000 or args.repeat < 1: + parser.error('Use at least 1000 rows and one repetition') +if args.query_only and not args.database: + parser.error('--query-only requires --database') + +with tempfile.TemporaryDirectory(prefix='adfs-search-benchmark-') as temporary: + root = Path(temporary) + filename = Path(args.database + '.fixture.pdf') if args.database else root / 'fixture.pdf' + if not filename.exists() and not args.query_only: + filename.write_bytes(b'%PDF-1.7\nbenchmark fixture\n') + stamp = documents.fingerprint(filename.stat()) + path = args.database or str(root / 'search.db') + if args.query_only: + if not Path(path).is_file(): + raise SystemExit('Query-only mode requires an existing database file') + if os.path.exists(path + '-wal') and os.path.getsize(path + '-wal'): + raise SystemExit('Checkpoint the offline benchmark before query-only mode') + conn = sqlite3.connect(Path(path).resolve().as_uri() + '?mode=ro&immutable=1', uri=True) + conn.row_factory = sqlite3.Row + else: + conn = connect_state_db(path) + tables = {row[0] for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")} + if tables: + if 'document_sources' not in tables or {row[0] for row in conn.execute('SELECT id FROM document_sources')} != {f'data:benchmark-{i:02}' for i in range(20)}: + raise SystemExit('Refusing to open a database not created by this benchmark') + document_search.register(conn) + if not args.query_only: + documents.ensure_schema(conn) + document_search.global_indexes(conn, documents.SEARCHABLE_NAME_SQL.format(name='name')) + conn.commit() + sources = {f'data:benchmark-{i:02}': {'id': f'data:benchmark-{i:02}', 'kind': 'data', + 'label': f'Folder {i}', 'root': str(root), 'owner_sid': ''} for i in range(20)} + count = conn.execute('SELECT count(*) FROM documents').fetchone()[0] + if count not in (0, args.rows): + raise SystemExit('Existing benchmark catalog has a different size') + if args.query_only: + if count != args.rows: + raise SystemExit('Query-only mode requires the completed benchmark catalog') + stamp = conn.execute('SELECT fingerprint FROM documents LIMIT 1').fetchone()[0] + elif count and conn.execute('SELECT fingerprint FROM documents LIMIT 1').fetchone()[0] != stamp: + # Refresh only the disposable fixture fingerprint on benchmarks made + # by older versions of this script, which used an ephemeral file. + conn.execute('UPDATE documents SET fingerprint=? WHERE fingerprint<>?', (stamp, stamp)) + conn.commit() + if not count: + conn.executemany('INSERT INTO document_sources VALUES(:id,:kind,:label,:root,:owner_sid)', sources.values()) + conn.commit() + started = time.perf_counter() + for start in range(0, args.rows, 10000): + rows = [] + for number in range(start, min(args.rows, start + 10000)): + extension = ('.pdf', '.docx', '.pptx', '.png', '.bin')[(number // 20) % 5] + name = f'Invoice_{number:09}_customer{number % 113:03}' + extension + body = 'Invoice contract customer project financial report native indexed document. ' * 3 + if number >= args.rows - 2000: + body += ' LATEONLY742' + if number % 1000 == 0: + body += ' SPARSE742' + rows.append((f'{number + 1:032x}', f'data:benchmark-{number % 20:02}', name, name, + extension, 10000, float(number), stamp, body, 'pending' if number % 17 == 0 else 'ready')) + conn.executemany('''INSERT INTO documents(id,source_id,path,name,extension,size,modified,fingerprint,body,state) + VALUES(?,?,?,?,?,?,?,?,?,?)''', rows) + conn.commit() + if (start + 10000) % 100000 == 0: + print(f'Catalog: {start + 10000:,} / {args.rows:,} ({time.perf_counter() - started:.1f}s)', flush=True) + conn.execute('ANALYZE') + conn.execute("INSERT INTO document_fts(document_fts) VALUES('optimize')") + conn.execute("INSERT INTO document_names_fts(document_names_fts) VALUES('optimize')") + conn.commit() + print(f'Build finished: {time.perf_counter() - started:.1f}s', flush=True) + results = [] + @contextlib.contextmanager + def open_fixture(*unused): + with filename.open('rb') as handle: + yield handle, os.fstat(handle.fileno()) + + cases = [] + for sort in ('recent', 'oldest', 'name', 'relevance'): + for label, query, scope in (('browse', '', 'all'), ('common', 'invoice', 'all'), + ('content', 'contract', 'content'), ('substring', '0001', 'name'), + ('one-letter', 'o', 'name'), ('absent', 'XYZZY742', 'name'), + ('late', 'LATEONLY742', 'content'), ('sparse', 'SPARSE742', 'content')): + for filtered in (False, True): + params = {'q': [query], 'scope': [scope], 'sort': [sort]} + if filtered: + params.update(source=['data:benchmark-00'], type=['pdf']) + cases.append((f'{label}/{sort}/' + ('folder+type' if filtered else 'all'), params)) + with mock.patch.object(documents, 'allowed_sources', return_value=sources), mock.patch.object(documents, 'open_file', open_fixture), \ + mock.patch.object(documents, 'fingerprint', return_value=stamp): + for label, params in cases: + times = [] + for iteration in range(args.repeat): + started = time.perf_counter() + result = documents.search(conn, {}, params) + times.append((time.perf_counter() - started) * 1000) + if label.startswith('absent/'): + assert not result['items'] and result['total'] == 0 + else: + assert result['items'], label + if params.get('source'): + assert all(item['sourceId'] == params['source'][0] and item['extension'] == 'pdf' for item in result['items']) + record = {'case': label, 'medianMs': round(statistics.median(times), 2), + 'maxMs': round(max(times), 2), 'returned': len(result['items']), 'totalExact': result['totalExact']} + results.append(record) + print(json.dumps(record), flush=True) + # Seek near the end directly. No OFFSET walk through preceding pages. + signature = document_search.cursor_scope('', 'all', '', '', 'oldest') + params = {'sort': ['oldest'], 'cursor': [document_search.encode_cursor(signature, + [float(args.rows - 1000), args.rows - 999, f'{args.rows - 999:032x}'], args.rows - 999)]} + started = time.perf_counter() + result = documents.search(conn, {}, params) + assert len(result['items']) == 40 + deep_ms = (time.perf_counter() - started) * 1000 + print(json.dumps({'case': 'deep-cursor', 'elapsedMs': round(deep_ms, 2), 'returned': len(result['items'])}), flush=True) + # Relevance uses FTS5's ranked stream rather than a score seek. Verify + # its cost near the end as well, including the skipped ranked rows. + signature = document_search.cursor_scope('invoice', 'all', '', '', 'relevance') + params = {'q': ['invoice'], 'sort': ['relevance'], 'cursor': [document_search.encode_cursor(signature, + [0, 1, f'{1:032x}', args.rows - 1000], args.rows - 1000)]} + started = time.perf_counter() + result = documents.search(conn, {}, params) + assert len(result['items']) == 40 + deep_rank_ms = (time.perf_counter() - started) * 1000 + print(json.dumps({'case': 'deep-relevance-cursor', 'elapsedMs': round(deep_rank_ms, 2), + 'returned': len(result['items'])}), flush=True) + print(json.dumps({'rows': args.rows, 'cases': len(cases), 'medianMs': round(statistics.median(r['medianMs'] for r in results), 2), + 'worstMs': max(deep_ms, deep_rank_ms, *(r['maxMs'] for r in results)), + 'databaseBytes': os.path.getsize(path)}), flush=True) + conn.close() diff --git a/scripts/dev b/scripts/dev index e852896..7586c13 100755 --- a/scripts/dev +++ b/scripts/dev @@ -317,6 +317,7 @@ printf 'starting actual file server and HTTPS web UI\n' -e "WEB_ENABLED=true" \ -e "WEB_HOSTNAME=${dev_web_hostname}" \ -e "WEB_BIND_PORT=8443" \ + -e "WEB_HTTPS_PORT=${dev_https_port}" \ -e "WEB_JWT_SECRET=preview-only-jwt-secret-with-at-least-32-bytes" \ -e "WEB_TLS_MODE=acme" \ -e "ACME_CA_SERVER=https://ca.${dev_dns_domain}:9000/acme/acme/directory" \ diff --git a/tests/document_ui_smoke.mjs b/tests/document_ui_smoke.mjs index 9cc908a..b5b2917 100644 --- a/tests/document_ui_smoke.mjs +++ b/tests/document_ui_smoke.mjs @@ -34,17 +34,24 @@ function viewerPdf() { return Buffer.from(pdf+`trailer\n<< /Size 10 /Root 1 0 R >>\nstartxref\n${offset}\n%%EOF\n`); } const pdf=viewerPdf(); -let role='user', loggedIn=true, deniedId='', pendingRequests=[], errors=[]; -const browser=await chromium.launch({headless:true}); +const csrfToken='fixture-session-bound-csrf'; +let role='user', loggedIn=true, deniedId='', pendingRequests=[], errors=[], cursorMode=false, cursorRequests=[]; +const browser=await chromium.launch({headless:true,...(process.env.CHROMIUM_EXECUTABLE_PATH?{executablePath:process.env.CHROMIUM_EXECUTABLE_PATH}:{})}); try { const page=await browser.newPage({viewport:{width:1500,height:1050}}); page.on('pageerror',error=>errors.push(error.message)); await page.route('http://adfs.test/**',async route=>{ const url=new URL(route.request().url()); let body,type='application/json',status=200; if(url.pathname==='/api/session'){ - if(!loggedIn){status=401;body={error:'Anmeldung erforderlich'};}else body={user:'EXAMPLE\\alice',role,expiresAt:9999999999}; - }else if(url.pathname==='/api/login'){loggedIn=true;body={user:'EXAMPLE\\alice',role,expiresAt:9999999999};} - else if(url.pathname==='/api/logout'){loggedIn=false;body={ok:true};} + if(!loggedIn){status=401;body={error:'Anmeldung erforderlich'};}else body={user:'EXAMPLE\\alice',role,expiresAt:9999999999,csrfToken}; + }else if(url.pathname==='/api/login'){ + assert.equal(route.request().headers()['x-csrf-token'],'login'); + loggedIn=true;body={user:'EXAMPLE\\alice',role,expiresAt:9999999999,csrfToken}; + } + else if(url.pathname==='/api/logout'){ + assert.equal(route.request().headers()['x-csrf-token'],csrfToken); + loggedIn=false;body={ok:true}; + } else if(url.pathname==='/api/documents'){ pendingRequests.push(url.searchParams.get('q')); const query=(url.searchParams.get('q')||'').toLowerCase(),scope=url.searchParams.get('scope'); @@ -53,6 +60,15 @@ try { if(url.searchParams.get('source'))rows=rows.filter(row=>row.sourceId===url.searchParams.get('source')); if(url.searchParams.get('type'))rows=rows.filter(row=>row.extension===url.searchParams.get('type')); body={items:rows,total:rows.length,hasMore:false,sources,types:['pdf','docx','txt','csv'],pending:rows.filter(row=>row.state==='ocr').length}; + if(cursorMode&&query==='cursor742'){ + const cursor=url.searchParams.get('cursor')||''; + cursorRequests.push({cursor,type:url.searchParams.get('type'),sort:url.searchParams.get('sort')}); + assert.ok(['','test-cursor-40','test-cursor-80'].includes(cursor),'Unexpected page cursor'); + const start=cursor?Number(cursor.split('-').at(-1)):0; + const hasMore=start+40row.id===parts[3]); if(!row||row.id===deniedId){status=404;body={error:'Datei nicht verfügbar'};} @@ -216,11 +232,40 @@ try { await page.locator('#login-form input[name=password]').fill('password'); await page.locator('#login-form button').click();await all(); assert.equal(await page.locator('#admin-link').isHidden(),true); + // Cursor pages work in both directions; changing any filter starts at page 1. + cursorMode=true; + for(let index=0;index<85;index++)fixtures.push({...fixtures[0],id:(1000+index).toString(16).padStart(32,'0'),name:`Cursor742 ${String(index).padStart(3,'0')}.pdf`,path:`Cursor742 ${index}.pdf`,hasPreview:false}); + await page.locator('#search-query').fill('Cursor742'); + await page.waitForFunction(()=>document.querySelectorAll('.document-card').length===40&&document.querySelector('.document-card h2')?.textContent==='Cursor742 000.pdf'); + assert.equal(await page.locator('#result-summary').innerText(),'Mindestens 41 Dateien'); + await page.locator('#next-page').click(); + await page.waitForFunction(()=>document.querySelector('.document-card h2')?.textContent==='Cursor742 040.pdf'); + assert.equal(cursorRequests.at(-1).cursor,'test-cursor-40'); + await page.locator('#next-page').click(); + await page.waitForFunction(()=>document.querySelector('.document-card h2')?.textContent==='Cursor742 080.pdf'); + assert.equal(await page.locator('#documents .document-card').count(),5); + assert.equal(await page.locator('#next-page').isDisabled(),true); + assert.equal(await page.locator('#result-summary').innerText(),'85 Dateien'); + await page.locator('#previous-page').click(); + await page.waitForFunction(()=>document.querySelector('.document-card h2')?.textContent==='Cursor742 040.pdf'); + assert.equal(cursorRequests.at(-1).cursor,'test-cursor-40'); + await page.locator('#type-filter').selectOption('pdf'); + await page.waitForFunction(()=>document.querySelector('.document-card h2')?.textContent==='Cursor742 000.pdf'); + assert.equal(cursorRequests.at(-1).cursor,''); + await page.locator('#next-page').click(); + await page.waitForFunction(()=>document.querySelector('.document-card h2')?.textContent==='Cursor742 040.pdf'); + await page.locator('#sort-filter').selectOption('oldest'); + await page.waitForFunction(()=>document.querySelector('.document-card h2')?.textContent==='Cursor742 000.pdf'); + assert.equal(cursorRequests.at(-1).cursor,''); + await page.evaluate(()=>window.scrollTo(0,0)); + await page.screenshot({path:path.join(out,'07-cursor-search.png'),fullPage:false}); + fixtures.splice(5);cursorMode=false; + await page.locator('#reset-filters').click();await all(); role='domain-admin';await page.goto('http://adfs.test/');await all(); assert.equal(await page.locator('#admin-link').getAttribute('href'),'/admin/overview'); assert.equal(await page.locator('#admin-link').isVisible(),true); assert.ok(pendingRequests.includes('FINANZ742')&&pendingRequests.includes('SCANLIVE742')); assert.deepEqual(errors,[]); - console.log('PASS: user login, admin separation, live content search, own-private filter, preview/download links, OCR refresh, revocation, grid/list, desktop/mobile, portrait/landscape image fitting.'); + console.log('PASS: user login, admin separation, live content search, own-private filter, cursor pagination and reset, exact/lower-bound counts, preview/download links, OCR refresh, revocation, grid/list, desktop/mobile, portrait/landscape image fitting.'); console.log('Screenshots: '+out); } finally {await browser.close();} diff --git a/tests/fixtures/web-test.crt b/tests/fixtures/web-test.crt new file mode 100644 index 0000000..78c1731 --- /dev/null +++ b/tests/fixtures/web-test.crt @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDVDCCAjygAwIBAgIRAJ9j/HiPhinNMutkqNMKqLUwDQYJKoZIhvcNAQELBQAw +HTEbMBkGA1UEAxMSZmlsZXMuZXhhbXBsZS50ZXN0MB4XDTI2MTAwNDE4Mzc1N1oX +DTM2MTAwMTE4Mzc1N1owHTEbMBkGA1UEAxMSZmlsZXMuZXhhbXBsZS50ZXN0MIIB +IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwD4RhCcwNCHbcOJCXpGWCFcI +HA0gVz707rCMFKaNS8zNUIJCFy9VS376rNHKAGonvmosuZE7DC+K0Rfs7EgzKwuh +nulqkXpIcfxY4F1tx+gGhH8Rn1V0faCzMElrzWCeWfjGBP6FpxFVKTOUaALgVMSM +bBQGTdbrgbK3K5826OWhbG3YeXsCrnzIPhSpqALI+t4czPk9L2Gk31jQRwTsQBpp +SvCaTVau2/uIYGQS/fHT4Op9TQ1/Nk0+vAMZPgZ511O5AUZHR1QC5S4jJJarrw/2 +5ofSufmBeackYQUIRpGZ5YcrGzDu1er1ObsryCXA/uewWrDMbxkFyJYE+TTW0wID +AQABo4GOMIGLMA4GA1UdDwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYI +KwYBBQUHAwIwHQYDVR0OBBYEFMHQWSMDT8mcJPBt0dtz7WC7xdBIMDsGA1UdEQQ0 +MDKCCWxvY2FsaG9zdIISZmlsZXMuZXhhbXBsZS50ZXN0ghFldmlsLmV4YW1wbGUu +dGVzdDANBgkqhkiG9w0BAQsFAAOCAQEAkcosHPK7t1Gg8KhobfxgGY9FBtutRteH +IV0SgvrUauT3PaB7Ie4V8PtMjWgvpeZe5poalBfQfNK+Wvh9vrwoBNOCHb6riuaj +W5Whs4O4TYn+hAy+7kJv26UOmdAz2IyGNlz/NgRb6/1Pa5L5Ffr8iA+rA0ifMebP +HKMlkz/VWJv4U9NJ4vgdHQPR6tUxi57PeDpKLdtMRD5M0dl2oIHCRiFc6mCwjsmc +JxVoC/x3GnizucERkNmxmc4P53/4TU2DspqlCSAz0/SznI5xxh5+URs0MQZ6LQnt +qPk05mTHbLjSTVWLEPqYuX3iGxTEcCki2JquMmhdNUrr98jh8waITQ== +-----END CERTIFICATE----- diff --git a/tests/fixtures/web-test.key b/tests/fixtures/web-test.key new file mode 100644 index 0000000..408ecba --- /dev/null +++ b/tests/fixtures/web-test.key @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpQIBAAKCAQEAwD4RhCcwNCHbcOJCXpGWCFcIHA0gVz707rCMFKaNS8zNUIJC +Fy9VS376rNHKAGonvmosuZE7DC+K0Rfs7EgzKwuhnulqkXpIcfxY4F1tx+gGhH8R +n1V0faCzMElrzWCeWfjGBP6FpxFVKTOUaALgVMSMbBQGTdbrgbK3K5826OWhbG3Y +eXsCrnzIPhSpqALI+t4czPk9L2Gk31jQRwTsQBppSvCaTVau2/uIYGQS/fHT4Op9 +TQ1/Nk0+vAMZPgZ511O5AUZHR1QC5S4jJJarrw/25ofSufmBeackYQUIRpGZ5Ycr +GzDu1er1ObsryCXA/uewWrDMbxkFyJYE+TTW0wIDAQABAoIBAFtehLu/VnFIsEAI +QcwpvNnM561RbdAZu5cgsQt1l41x0xmTN29Gj28Y9HKkKTKmQaqGUyiFhr+FbyBv +EyvAKxWn6xKY1Q48xObsLZ/BuBY9yK87p7gHiRzWfqQSGVsdM1YG37Lq98IOgl/Z +RI1k5JNVcXpC0DY50mgr9VQV0abB/eHJ3aptM6rm8BBhloXz5RlSEzNNnLllCyaE +XCp1tbcNMKh/pr/KvRLbGEmHnpshtuDNhAKJj2Qi9C+ClIDJx6TeDI96aHDC2s+5 ++JUIu8OzqxiFestXeKXcOCTICcjRi1MMZlewsiJCMloWSKDbSZ5Q6hErXqm082GB +PE5v7nkCgYEAzuwMFCCtEkV2SdF3gt1Nj8hu7lztQui5rRsG25w403D8PCavQNUe +fxZKgb1Yaxy0tVVY0YM5nn3SSWGa7Ckar42FUOMrQwkrMrR1Het/YiZEnlouY1JF +MpIJ8r/noGmfYnxbf7aUYJ747fMNPJ/bPtM1dudfNecNz+JPFg1wGosCgYEA7daz +aGKxUAeg/Tg8IXDtdI8R5A0gzKqSnHcD2AB5W53ePcuV2RPfmTFRaqtyIBaoWkdN +IwuZ7arlZWURieNnu5aEmno4jiOHRz/xAfoBewgvRC5GAOsl2HAQ5YhPMauQx06c +KvqyaRU71eM7a97tdOWKiH9HBSiVLVLcjEZQ5dkCgYEAnjubsPib4NEFd8WaopQg +78bSLa0aMoRNGLcGM4HvYqGQAV+DvQw8Wert5vCoYKB+//vYA79ZnH2TBVKCaf20 +znJmdEiDmKu2QPwGY27m5mNlLcLAnmsXR2it+tgNhHnAzEtUnQE9zfVDXpLymF2W +ByD0TYz5HfsmcMYavD5ib6kCgYEA4rvUKsYzPRUYv221vTeX149wwdRWGWbe/7Ri +ALBrAREdxhFoGBrfBX7DnAo3cSnIctAYVDmCE9XgfGn+b1JQGL/kSBQOCEsMcrsd +OgIpGS3zSW9HoyaI3K3xHbB1tudUzPw+2qZGIPFyKnRGuI48Fz2gdIHJpbxLgnrE +8CE0i/kCgYEAn1Ilvn9uzcGix9nh5UnQTcCtCh8cgt0Q6HUrmSBrG6iufli6SjKr +yyo5MOG6Yipi0gB5J/WqmbDXjfzgN3yFdwuckRhUH+8rO1OH3qGM+uBlcT3fm+Ka +fdSvt98noLGX6cOoQW7PvWSX708tg7QuT8dqSXduFL4pY0HGtJ0LZCs= +-----END RSA PRIVATE KEY----- diff --git a/tests/test_document_search.py b/tests/test_document_search.py new file mode 100644 index 0000000..54836dd --- /dev/null +++ b/tests/test_document_search.py @@ -0,0 +1,216 @@ +import os +from pathlib import Path +import sqlite3 +import unittest +from unittest import mock + +from app import document_search, documents +from tests.test_documents import DocumentFixture, IDENTITY + + +class SearchPlanTests(DocumentFixture): + def legacy_catalog(self): + for row in self.conn.execute("SELECT name FROM sqlite_master WHERE type='trigger' AND tbl_name='documents'").fetchall(): + self.conn.execute('DROP TRIGGER ' + row['name']) + for row in self.conn.execute("SELECT name FROM sqlite_master WHERE type='index' AND (name LIKE 'document_search_%' OR name LIKE 'document_global_%')").fetchall(): + self.conn.execute('DROP INDEX ' + row['name']) + self.conn.execute('DROP TABLE document_fts') + self.conn.execute('DROP TABLE document_names_fts') + self.conn.execute('DROP TABLE document_counts') + self.conn.execute('DROP VIEW document_search_content') + self.conn.execute("CREATE VIRTUAL TABLE document_fts USING fts5(name,path,body,content='documents',content_rowid='rowid',tokenize='unicode61 remove_diacritics 2',prefix='2 3 4')") + self.conn.execute("INSERT INTO document_fts(document_fts) VALUES('rebuild')") + self.conn.execute('PRAGMA user_version=2') + self.conn.commit() + + def test_genuine_version_two_catalog_migrates_without_changing_documents_or_worker(self): + documents.control_worker(self.conn, 'pause', 'admin') + before = [tuple(row) for row in self.conn.execute('SELECT * FROM documents ORDER BY id')] + originals = [(path, path.read_bytes(), path.stat().st_ino) for path in self.data.rglob('*') if path.is_file()] + self.legacy_catalog() + documents.ensure_schema(self.conn) + self.assertEqual(before, [tuple(row) for row in self.conn.execute('SELECT * FROM documents ORDER BY id')]) + self.assertTrue(documents.worker_paused(self.conn)) + self.assertEqual(self.find({'type': ['docx']})['total'], 1) + self.assertEqual(self.find({'q': ['ast'], 'scope': ['name']})['total'], 1) + self.assertEqual(self.find({'q': ['Umsatz'], 'scope': ['content']})['total'], 1) + for path, content, inode in originals: + self.assertEqual((path.read_bytes(), path.stat().st_ino), (content, inode)) + + def test_failed_derived_index_rebuild_rolls_back_and_can_be_retried(self): + self.legacy_catalog() + before = [tuple(row) for row in self.conn.execute('SELECT * FROM documents ORDER BY id')] + with mock.patch.object(document_search, 'name_terms', side_effect=RuntimeError('simulated interrupted build')): + with self.assertRaises(sqlite3.OperationalError): + documents.ensure_schema(self.conn) + self.assertEqual(self.conn.execute('PRAGMA user_version').fetchone()[0], 2) + self.assertEqual([row['name'] for row in self.conn.execute('PRAGMA table_info(document_fts)')], ['name', 'path', 'body']) + self.assertEqual(before, [tuple(row) for row in self.conn.execute('SELECT * FROM documents ORDER BY id')]) + documents.ensure_schema(self.conn) + self.assertEqual(self.find({'q': ['Umsatz'], 'scope': ['content']})['total'], 1) + + def test_folder_type_and_sort_plans_seek_without_a_temporary_sort(self): + visible = documents.SEARCHABLE_NAME_SQL.format(name='d.name') + for sort, order, primary in (('recent', 'modified DESC,id DESC', 'modified'), + ('oldest', 'modified,id', 'modified'), + ('name', 'name COLLATE NOCASE,id', 'name COLLATE NOCASE')): + for typed in (False, True): + with self.subTest(sort=sort, typed=typed): + index = 'document_search_' + sort + ('_type' if typed else '') + where = 'source_id=? AND ' + visible + values = ['data:' + self.folder_ids['Finance']] + if typed: + where += ' AND extension=?' + values.append('.docx') + op = '<' if sort == 'recent' else '>' + where += f' AND ({primary},id) {op} (?,?)' + values += ['a' if sort == 'name' else 0, '0' * 32] + if sort == 'name': + where += ' AND name COLLATE NOCASE>=?' + values += ['a'] + plan = ' '.join(row['detail'] for row in self.conn.execute( + f'EXPLAIN QUERY PLAN SELECT id FROM documents d INDEXED BY {index} WHERE {where} ORDER BY {order} LIMIT 40', values)) + self.assertIn('SEARCH', plan) + self.assertIn(index, plan) + self.assertNotIn('TEMP B-TREE', plan) + bounds = ('name>?',) if sort == 'name' else ('(modified,id)<(?,?)', 'modified(?,?)', 'modified>?') + self.assertTrue(any(bound in plan for bound in bounds), plan) + + def test_counts_and_name_postings_follow_rename_type_state_and_delete(self): + row = self.document('forecast.docx') + source = row['source_id'] + self.conn.execute("UPDATE documents SET name='renamed.pdf',extension='.pdf',state='ocr' WHERE id=?", (row['id'],)) + self.conn.commit() + self.assertEqual(self.find({'q': ['renamed'], 'scope': ['name']})['total'], 1) + self.assertEqual(self.find({'q': ['forecast'], 'scope': ['name']})['total'], 0) + self.assertEqual([tuple(value) for value in self.conn.execute('SELECT extension,state,amount FROM document_counts WHERE source_id=?', (source,))], [('.pdf', 'ocr', 1)]) + self.conn.execute('DELETE FROM documents WHERE id=?', (row['id'],)) + self.conn.commit() + self.assertEqual(self.conn.execute('SELECT count(*) FROM document_counts WHERE source_id=?', (source,)).fetchone()[0], 0) + self.assertEqual(self.conn.execute("SELECT count(*) FROM document_names_fts WHERE document_names_fts MATCH ?", (document_search.key('ren', 'g'),)).fetchone()[0], 0) + + def test_ocr_updates_do_not_rewrite_filename_postings(self): + terms = mock.Mock(wraps=document_search.name_terms) + self.conn.create_function('document_name_terms', 1, terms, deterministic=True) + self.conn.execute("UPDATE documents SET body='new OCR text',state='ready' WHERE name='forecast.docx'") + self.conn.commit() + terms.assert_not_called() + + def test_browsing_has_no_full_count_distinct_scan_or_private_catalog_walk(self): + statements = [] + self.conn.set_trace_callback(statements.append) + self.find() + self.conn.set_trace_callback(None) + queries = '\n'.join(statements).lower() + self.assertNotIn('count(*) from documents', queries) + self.assertNotIn('select distinct extension from documents', queries) + self.assertNotIn('readable_private', queries) + self.assertIn('from document_counts', queries) + + def test_cursor_is_bound_to_filters_and_rejects_malformed_input(self): + signature = document_search.cursor_scope('', 'all', '', '', 'recent') + cursor = document_search.encode_cursor(signature, [1, 1, '0' * 32], 40) + for params in ({'cursor': [cursor], 'type': ['pdf']}, {'cursor': ['***']}, + {'cursor': [document_search.encode_cursor(signature, [{}, 1, 'x'], 1)]}, {'offset': ['2000000']}): + with self.subTest(params=params), self.assertRaises(ValueError): + self.find(params) + + +class SearchPaginationTests(DocumentFixture): + def setUp(self): + super().setUp() + for index in range(620): + self.write(self.data / 'Finance' / f'report_{index:04}.pdf', 'COMMON742 LATE742' if index >= 600 else 'COMMON742') + self.scan() + rows = self.conn.execute("SELECT id,path FROM documents WHERE name LIKE 'report_%'").fetchall() + for index, row in enumerate(rows): + self.conn.execute("UPDATE documents SET body=?,state='ready',modified=? WHERE id=?", + ('COMMON742 LATE742' if index >= 600 else 'COMMON742', index // 3, row['id'])) + self.conn.commit() + + def test_all_sorts_and_scopes_paginate_without_duplicates_or_missing_matches(self): + for scope, query in (('all', 'COMMON742'), ('content', 'COMMON742'), ('name', 'report_'), ('name', 'r')): + for sort in ('recent', 'oldest', 'name', 'relevance'): + with self.subTest(scope=scope, sort=sort): + params = {'scope': [scope], 'q': [query], 'sort': [sort], 'type': ['pdf'], 'limit': ['100']} + items = [] + for page in range(10): + result = self.find(params) + items.extend(result['items']) + if not result['hasMore']: + break + self.assertTrue(result['nextCursor']) + params['cursor'] = [result['nextCursor']] + self.assertEqual(len(items), 620) + self.assertEqual(len({row['id'] for row in items}), 620) + effective = 'recent' if sort == 'relevance' and scope == 'name' else sort + if effective == 'name': + self.assertEqual([row['name'] for row in items], sorted(row['name'] for row in items)) + elif effective in ('recent', 'oldest'): + self.assertEqual([row['modified'] for row in items], sorted((row['modified'] for row in items), reverse=effective == 'recent')) + + def test_broad_search_uses_a_lower_bound_and_selective_search_is_exact(self): + broad = self.find({'q': ['COMMON742'], 'scope': ['content'], 'type': ['pdf']}) + self.assertFalse(broad['totalExact']) + self.assertEqual((len(broad['items']), broad['total'], broad['hasMore']), (40, 41, True)) + narrow = self.find({'q': ['LATE742'], 'scope': ['content'], 'type': ['pdf']}) + self.assertTrue(narrow['totalExact']) + self.assertEqual(narrow['total'], 20) + self.assertFalse(narrow['hasMore']) + browse = self.find({'type': ['pdf']}) + self.assertEqual((browse['totalExact'], browse['total']), (True, 620)) + + def test_relevance_pagination_survives_ocr_changes_to_corpus_statistics(self): + params = {'q': ['report'], 'sort': ['relevance'], 'type': ['pdf']} + first = self.find(params) + self.assertEqual(len(first['items']), 40) + self.conn.execute("UPDATE documents SET body=? WHERE name='own.odt'", ('unrelated OCR text ' * 1000,)) + self.conn.commit() + params['cursor'] = [first['nextCursor']] + second = self.find(params) + self.assertEqual(len(second['items']), 40) + + def test_valid_cursor_can_seek_beyond_the_legacy_offset_limit(self): + params = {'type': ['pdf'], 'limit': ['40']} + first = self.find(params) + params.update(cursor=[first['nextCursor']], offset=['2000000']) + second = self.find(params) + self.assertEqual(len(second['items']), 40) + self.assertFalse({row['id'] for row in first['items']} & {row['id'] for row in second['items']}) + + def test_relevance_pagination_advances_past_denied_private_candidates(self): + for index in range(75): + self.write(self.private / 'alice' / f'private_rank_{index:04}.pdf', 'original') + self.scan() + self.conn.execute("UPDATE documents SET body='PRIVATEPAGING742',state='ready' WHERE name LIKE 'private_rank_%'") + self.conn.commit() + params = {'q': ['PRIVATEPAGING742'], 'scope': ['content'], 'sort': ['relevance'], 'limit': ['100']} + initial = self.find(params) + self.assertEqual(len(initial['items']), 75) + for item in initial['items'][:5]: + (self.private / 'alice' / item['path']).chmod(0) + params['limit'] = ['40'] + first = self.find(params) + params['cursor'] = [first['nextCursor']] + second = self.find(params) + self.assertEqual((len(first['items']), len(second['items'])), (40, 30)) + self.assertFalse({row['id'] for row in first['items']} & {row['id'] for row in second['items']}) + + def test_private_checks_are_bounded_even_for_a_large_catalog_and_hide_denied_files(self): + source = self.conn.execute("SELECT * FROM document_sources WHERE id='private:alice'").fetchone() + for index in range(620): + self.write(self.private / 'alice' / f'private_{index:04}.pdf', 'original') + documents.walk_source(self.conn, source) + (self.private / 'alice' / 'private_0619.pdf').chmod(0) + with mock.patch.object(documents, 'private_readable', wraps=documents.private_readable) as check: + result = self.find({'source': ['private:alice']}) + self.assertLess(check.call_count, 200) + self.assertFalse(result['totalExact']) + self.assertEqual(len(result['items']), 40) + self.assertNotIn('private_0619.pdf', {row['name'] for row in result['items']}) + (self.private / 'alice' / 'own.odt').chmod(0) + self.assertNotIn('odt', self.find({'source': ['private:alice']})['types']) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_documents.py b/tests/test_documents.py index 0b9b535..b9d6e74 100644 --- a/tests/test_documents.py +++ b/tests/test_documents.py @@ -100,7 +100,7 @@ class DocumentTests(DocumentFixture): self.assertEqual(self.find({'q':['fore'],'scope':['name']})['total'],1) result = self.find({'q':['Umsatz Munchen'],'scope':['content']}) self.assertEqual(result['total'],1) - self.assertIn('\x01',result['items'][0]['snippet']) + self.assertEqual(result['items'][0]['snippet'],'') self.assertEqual(self.find({'q':['forecast'],'scope':['content']})['total'],1) for query in ('"', '*', ':', '" OR NOT ()', 'x\x00y'): self.find({'q':[query]}) @@ -199,7 +199,7 @@ class DocumentTests(DocumentFixture): self.assertEqual(path.read_bytes(),original) self.assertEqual(path.stat().st_ino,inode) documents.ensure_schema(self.conn) - self.assertEqual(self.conn.execute('PRAGMA user_version').fetchone()[0],2) + self.assertEqual(self.conn.execute('PRAGMA user_version').fetchone()[0],3) def test_only_document_types_are_queued_for_content_and_all_types_keep_filename_search(self): for extension in ('.pdf','.docx','.pptx','.odt','.odp','.txt','.md','.csv','.xlsx','.ods','.html','.json','.bin'): @@ -481,6 +481,9 @@ class DocumentHttpTests(DocumentFixture): if identity: token,_ = self.tokens.issue(identity['sub'],identity['sid'],identity['role'],identity.get('uid')) headers['Authorization'] = 'Bearer '+token + headers['X-CSRF-Token'] = self.tokens.csrf(self.tokens.verify(token)) + if path == '/api/login': + headers['X-CSRF-Token'] = 'login' if body is not None: body=json.dumps(body);headers['Content-Type']='application/json' conn=http.client.HTTPConnection(*self.server.server_address) diff --git a/tests/test_web_security.py b/tests/test_web_security.py new file mode 100644 index 0000000..db1199c --- /dev/null +++ b/tests/test_web_security.py @@ -0,0 +1,332 @@ +import concurrent.futures +import http.client +import json +import os +from pathlib import Path +import socket +import ssl +import tempfile +import threading +import time +import unittest +from unittest import mock + +from app import state_db, web_security, web_ui + + +ADMIN = {'sub': 'EXAMPLE\\admin', 'sid': 'S-1-5-21-1-2-3-1100', 'uid': 1000, 'role': 'domain-admin'} +USER = {**ADMIN, 'role': 'user'} + + +class SessionTests(unittest.TestCase): + def test_logout_revocation_survives_registry_reopening_and_does_not_revoke_other_sessions(self): + with tempfile.TemporaryDirectory() as root: + path = str(Path(root) / 'state.db') + manager = web_ui.TokenManager('s' * 48, 600, web_security.Sessions(path)) + token, _ = manager.issue(ADMIN['sub'], ADMIN['sid'], ADMIN['role'], ADMIN['uid']) + other, _ = manager.issue(ADMIN['sub'], ADMIN['sid'], ADMIN['role'], ADMIN['uid']) + reopened = web_ui.TokenManager('s' * 48, 600, web_security.Sessions(path)) + reopened.revoke(reopened.verify(token)) + for instance in (manager, reopened, web_ui.TokenManager('s' * 48, 600, web_security.Sessions(path))): + with self.assertRaises(ValueError): + instance.verify(token) + self.assertEqual(instance.verify(other)['role'], 'domain-admin') + + def test_refresh_cannot_resurrect_a_logged_out_session(self): + manager = web_ui.TokenManager('s' * 48, 600) + token, _ = manager.issue(ADMIN['sub'], ADMIN['sid'], ADMIN['role']) + payload = manager.verify(token) + manager.revoke(payload) + manager.sessions.refresh(payload['jti'], ADMIN, time.time()) + with self.assertRaises(ValueError): + manager.verify(token) + + def test_unregistered_legacy_signed_jwt_is_no_longer_accepted(self): + before = web_ui.TokenManager('s' * 48, 600) + token, _ = before.issue(ADMIN['sub'], ADMIN['sid'], ADMIN['role']) + after = web_ui.TokenManager('s' * 48, 600) + with self.assertRaises(ValueError): + after.verify(token) + + def test_origin_is_exact_and_rejects_null_credentials_paths_and_non_https(self): + self.assertEqual(web_security.origin('https://FILES.example.test:443'), ('files.example.test', 443)) + self.assertNotEqual(web_security.origin('https://evil.example.test'), web_security.origin('https://files.example.test')) + for value in ('null', 'http://files.example.test', 'https://files.example.test.evil.test', + 'https://files.example.test/path', 'https://user@files.example.test', 'https://files.example.test#x', + 'https://files.example.test:0', 'https://files.example.test:'): + if value.endswith('.evil.test'): + self.assertNotEqual(web_security.origin(value), ('files.example.test', 443)) + else: + with self.assertRaises(ValueError): + web_security.origin(value) + + +class LoginLimitTests(unittest.TestCase): + def setUp(self): + web_ui.LOGIN_LIMIT.clear() + self.addCleanup(web_ui.LOGIN_LIMIT.clear) + patch = mock.patch.dict(os.environ, WEB_LOGIN_ATTEMPTS_PER_5_MIN='3', WEB_LOGIN_ACCOUNT_ATTEMPTS_PER_5_MIN='3') + patch.start() + self.addCleanup(patch.stop) + + def test_parallel_reservations_are_counted_before_authentication(self): + gate = threading.Barrier(8) + def attempt(number): + gate.wait(timeout=5) + return web_ui.reserve_login('127.0.0.1', f'user{number}') + with concurrent.futures.ThreadPoolExecutor(max_workers=8) as workers: + self.assertEqual(sum(workers.map(attempt, range(8))), 3) + + def test_account_limit_spans_ips_case_and_domain_login_formats(self): + for ip, username in (('1', 'alice'), ('2', 'EXAMPLE\\ALICE'), ('3', 'Alice@example.test')): + self.assertTrue(web_ui.reserve_login(ip, username)) + self.assertFalse(web_ui.reserve_login('4', 'alice')) + self.assertTrue(web_ui.reserve_login('4', 'bob')) + + def test_window_expires_without_an_unbounded_stale_key_collection(self): + with mock.patch.object(web_ui.time, 'monotonic', return_value=100): + for number in range(3): + self.assertTrue(web_ui.reserve_login('ip', 'alice')) + self.assertFalse(web_ui.reserve_login('ip', 'alice')) + with mock.patch.object(web_ui.time, 'monotonic', return_value=400): + self.assertTrue(web_ui.reserve_login('other', 'bob')) + self.assertNotIn(('ip', 'ip'), web_ui.LOGIN_LIMIT) + + +class SecurityHttpTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.db = str(Path(self.temp.name) / 'state.db') + self.tokens = web_ui.TokenManager('s' * 48, 600, web_security.Sessions(self.db)) + self.app = mock.Mock(tokens=self.tokens) + self.app.overview.return_value = {'admin': True} + self.action = mock.Mock(return_value={'paused': True}) + for patch in (mock.patch.object(web_ui, 'APP', self.app), + mock.patch.object(web_ui.directory, 'open_db', side_effect=lambda: state_db.connect_state_db(self.db)), + mock.patch.object(web_ui.documents, 'connect', side_effect=lambda: state_db.connect_state_db(self.db)), + mock.patch.object(web_ui.documents, 'ensure_schema'), + mock.patch.object(web_ui.documents, 'control_worker', self.action), + mock.patch.dict(os.environ, WEB_HOSTNAME='files.example.test', WEB_HTTPS_PORT='443', WEB_TRUSTED_ORIGINS='')): + patch.start() + self.addCleanup(patch.stop) + web_ui.LOGIN_LIMIT.clear() + self.addCleanup(web_ui.LOGIN_LIMIT.clear) + self.server = web_ui.ReusableHTTPServer(('127.0.0.1', 0), web_ui.Handler) + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + self.thread.start() + self.addCleanup(self.close_server) + self.token, _ = self.tokens.issue(ADMIN['sub'], ADMIN['sid'], ADMIN['role'], ADMIN['uid']) + self.csrf = self.tokens.csrf(self.tokens.verify(self.token)) + + def close_server(self): + self.server.shutdown() + self.server.server_close() + self.thread.join(timeout=5) + + def request(self, path='/admin/api/documents/control', method='POST', headers=None, body=None): + request_headers = {'Content-Type': 'application/json', 'Origin': 'https://files.example.test', + 'Cookie': f'{web_ui.JWT_COOKIE}={self.token}', 'X-CSRF-Token': self.csrf} + request_headers.update(headers or {}) + request_headers = {key: value for key, value in request_headers.items() if value is not None} + conn = http.client.HTTPConnection(*self.server.server_address, timeout=5) + try: + conn.request(method, path, headers=request_headers, body=body if body is not None else '{"action":"pause"}') + response = conn.getresponse() + return response.status, dict(response.headers), json.loads(response.read()) + finally: + conn.close() + + def test_cookie_mutations_require_exact_origin_json_and_session_bound_csrf(self): + for headers, status in (({'Origin': 'https://evil.example.test'}, 403), + ({'Origin': 'null'}, 403), ({'Origin': None}, 403), + ({'Origin': 'https://files.example.test:8443'}, 403), + ({'Content-Type': 'text/plain'}, 415), + ({'Content-Type': 'application/x-www-form-urlencoded'}, 415), + ({'X-CSRF-Token': None}, 403), ({'X-CSRF-Token': 'wrong'}, 403), + ({'Sec-Fetch-Site': 'same-site'}, 403)): + self.assertEqual(self.request(headers=headers)[0], status, headers) + other, _ = self.tokens.issue(ADMIN['sub'], ADMIN['sid'], ADMIN['role']) + self.assertEqual(self.request(headers={'X-CSRF-Token': self.tokens.csrf(self.tokens.verify(other))})[0], 403) + self.action.assert_not_called() + self.assertEqual(self.request(headers={'Content-Type': 'application/json; charset=utf-8'})[0], 200) + self.action.assert_called_once() + + def test_host_and_forwarded_headers_cannot_override_configured_origin(self): + self.assertEqual(self.request(headers={'Host': 'evil.example.test', 'Origin': 'https://evil.example.test', + 'X-Forwarded-Host': 'evil.example.test'})[0], 403) + self.action.assert_not_called() + + def test_bearer_api_client_still_needs_csrf_and_foreign_origins_are_rejected(self): + headers = {'Origin': None, 'Cookie': None, 'Authorization': 'Bearer ' + self.token} + self.assertEqual(self.request(headers={**headers, 'X-CSRF-Token': None})[0], 403) + self.assertEqual(self.request(headers={**headers, 'Origin': 'https://evil.example.test'})[0], 403) + self.assertEqual(self.request(headers=headers)[0], 200) + + def test_logout_revokes_cookie_and_bearer_replays(self): + self.assertEqual(self.request('/admin/api/overview', method='GET')[0], 200) + self.assertEqual(self.request('/api/logout', headers={'Origin': 'https://evil.example.test'})[0], 403) + self.assertEqual(self.request('/admin/api/overview', method='GET')[0], 200) + status, headers, _ = self.request('/api/logout') + self.assertEqual(status, 200) + self.assertIn('Max-Age=0', headers['Set-Cookie']) + self.assertEqual(self.request('/admin/api/overview', method='GET')[0], 401) + self.assertEqual(self.request('/admin/api/overview', method='GET', headers={ + 'Cookie': None, 'Authorization': 'Bearer ' + self.token})[0], 401) + self.assertEqual(self.request()[0], 401) + self.action.assert_not_called() + + def test_current_ad_role_controls_all_admin_routes_and_session_response(self): + resolver = mock.Mock(return_value=USER) + self.tokens.identity_resolver = resolver + self.assertEqual(self.request('/admin/api/overview', method='GET')[0], 200) + resolver.assert_not_called() + with self.tokens.sessions.connection() as conn, conn: + conn.execute('UPDATE web_sessions SET checked=0') + self.assertEqual(self.request('/admin/api/overview', method='GET')[0], 403) + self.assertEqual(self.request()[0], 403) + self.assertEqual(self.request('/api/session', method='GET')[2]['role'], 'user') + resolver.assert_called_once_with(ADMIN['sid']) + self.action.assert_not_called() + + def test_directory_failure_is_fail_closed(self): + self.tokens.identity_resolver = mock.Mock(return_value=None) + with self.tokens.sessions.connection() as conn, conn: + conn.execute('UPDATE web_sessions SET checked=0') + self.assertEqual(self.request('/admin/api/overview', method='GET')[0], 401) + self.assertEqual(self.request()[0], 401) + self.action.assert_not_called() + + def test_logout_still_revokes_when_directory_is_unavailable(self): + resolver = mock.Mock(return_value=None) + self.tokens.identity_resolver = resolver + with self.tokens.sessions.connection() as conn, conn: + conn.execute('UPDATE web_sessions SET checked=0') + self.assertEqual(self.request('/api/logout')[0], 200) + resolver.assert_not_called() + self.assertEqual(self.request('/admin/api/overview', method='GET')[0], 401) + self.action.assert_not_called() + + def test_login_requires_custom_header_and_origin_check(self): + with mock.patch.object(web_ui, 'authenticate_user', return_value=USER) as auth: + for headers in ({'X-CSRF-Token': None}, {'X-CSRF-Token': 'login', 'Origin': 'https://evil.example.test'}, + {'X-CSRF-Token': 'login', 'Content-Type': 'text/plain'}): + self.assertIn(self.request('/api/login', headers=headers)[0], (403, 415)) + auth.assert_not_called() + status, _, value = self.request('/api/login', headers={'X-CSRF-Token': 'login'}, body='{"username":"admin","password":"password"}') + self.assertEqual(status, 200) + self.assertEqual(value['csrfToken'], self.tokens.csrf(self.tokens.verify(value['token']))) + + def test_parallel_http_login_budget_is_reserved_before_ad_authentication(self): + release = threading.Event() + def authenticate(*args): + release.wait(timeout=3) + return None + with mock.patch.dict(os.environ, WEB_LOGIN_ATTEMPTS_PER_5_MIN='3'), \ + mock.patch.object(web_ui, 'authenticate_user', side_effect=authenticate) as auth, \ + concurrent.futures.ThreadPoolExecutor(max_workers=8) as workers: + jobs = [workers.submit(self.request, '/api/login', headers={'X-CSRF-Token': 'login'}, + body=json.dumps({'username': f'user{number}', 'password': 'bad'})) for number in range(8)] + deadline = time.monotonic() + 2 + while sum(job.done() for job in jobs) < 5 and time.monotonic() < deadline: + time.sleep(0.01) + release.set() + statuses = [job.result()[0] for job in jobs] + self.assertEqual(statuses.count(401), 3) + self.assertEqual(statuses.count(429), 5) + self.assertEqual(auth.call_count, 3) + + def test_successful_login_does_not_clear_ip_or_other_account_attempts(self): + with mock.patch.dict(os.environ, WEB_LOGIN_ATTEMPTS_PER_5_MIN='5', WEB_LOGIN_ACCOUNT_ATTEMPTS_PER_5_MIN='3'), \ + mock.patch.object(web_ui, 'authenticate_user', side_effect=lambda name, password: USER if name == 'own' else None): + def login(name): + return self.request('/api/login', headers={'X-CSRF-Token': 'login'}, + body=json.dumps({'username': name, 'password': 'password'}))[0] + self.assertEqual([login(name) for name in ('victim', 'victim', 'own', 'victim', 'own')], [401, 401, 200, 401, 200]) + self.assertEqual(login('victim'), 429) + self.assertEqual(login('another'), 429) + + +class TlsHandshakeTests(unittest.TestCase): + def context(self): + # Public test-only key; no runtime dependency on a certificate CLI. + root = Path(__file__).parent / 'fixtures' + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain(root / 'web-test.crt', root / 'web-test.key') + return context + + def test_silent_client_does_not_block_https_and_times_out(self): + with mock.patch.dict(os.environ, WEB_TLS_HANDSHAKE_TIMEOUT_SECONDS='1'): + server = web_ui.ReusableHTTPServer(('127.0.0.1', 0), web_ui.Handler, self.context()) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + def healthy(): + conn = http.client.HTTPSConnection(*server.server_address, context=ssl._create_unverified_context(), timeout=1) + try: + conn.request('GET', '/healthz') + response = conn.getresponse() + self.assertEqual(response.status, 200) + response.read() + finally: + conn.close() + healthy() + with socket.create_connection(server.server_address, timeout=2) as silent: + healthy() + silent.settimeout(2) + self.assertEqual(silent.recv(1), b'') + healthy() + # Invalid handshakes release their worker slot as well. + for number in range(70): + with socket.create_connection(server.server_address, timeout=2) as invalid: + invalid.sendall(b'not a TLS handshake\n') + invalid.recv(1) + healthy() + finally: + server.shutdown() + server.server_close() + thread.join(timeout=5) + + def test_connection_budget_rejects_excess_and_recovers_after_handshake_timeouts(self): + context = self.context() + ready = threading.Event() + entered = [] + lock = threading.Lock() + def wrap(*args, **kwargs): + connection = context.wrap_socket(*args, **kwargs) + with lock: + entered.append(connection) + if len(entered) == 4: + ready.set() + return connection + with mock.patch.dict(os.environ, WEB_TLS_HANDSHAKE_TIMEOUT_SECONDS='1', WEB_MAX_CONNECTIONS='4'): + server = web_ui.ReusableHTTPServer(('127.0.0.1', 0), web_ui.Handler, mock.Mock(wrap_socket=wrap)) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + clients = [] + try: + clients = [socket.create_connection(server.server_address, timeout=2) for _ in range(4)] + self.assertTrue(ready.wait(timeout=2)) + with socket.create_connection(server.server_address, timeout=2) as excess: + self.assertEqual(excess.recv(1), b'') + self.assertEqual(len(entered), 4) + for client in clients: + self.assertEqual(client.recv(1), b'') + conn = http.client.HTTPSConnection(*server.server_address, context=ssl._create_unverified_context(), timeout=2) + try: + conn.request('GET', '/healthz') + response = conn.getresponse() + self.assertEqual(response.status, 200) + response.read() + finally: + conn.close() + finally: + for client in clients: + client.close() + server.shutdown() + server.server_close() + thread.join(timeout=5) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/web_security_browser_fixture.py b/tests/web_security_browser_fixture.py new file mode 100644 index 0000000..cecf66d --- /dev/null +++ b/tests/web_security_browser_fixture.py @@ -0,0 +1,64 @@ +"""Disposable HTTPS server for the sibling-subdomain browser regression.""" +import json +import os +from pathlib import Path +import signal +import ssl +import tempfile +from types import SimpleNamespace + +from app import documents, state_db, web_security, web_ui + + +def main(): + with tempfile.TemporaryDirectory(prefix='adfs-security-browser-') as root: + path = str(Path(root) / 'state.db') + tokens = web_ui.TokenManager('browser-fixture-secret-' * 3, 600, web_security.Sessions(path)) + web_ui.APP = SimpleNamespace(tokens=tokens) + identity = {'sub': 'EXAMPLE\\admin', 'sid': 'S-1-5-21-1-2-3-1100', 'uid': 1000, 'role': 'domain-admin'} + web_ui.authenticate_user = lambda name, password: identity if (name, password) == ('admin', 'fixture-password') else None + web_ui.directory.open_db = lambda: state_db.connect_state_db(path) + documents.SEARCH_ROOT = str(Path(root) / 'search') + documents.SEARCH_DB = str(Path(root) / 'search' / 'search.db') + observations = [] + + class Handler(web_ui.Handler): + def do_POST(self): + if self.headers.get('Origin', '').startswith('https://evil.example.test:'): + observations.append({'cookie': bool(self.token()), 'type': self.headers.get_content_type()}) + super().do_POST() + + def do_GET(self): + if self.path == '/test-observations': + self.send_json(observations) + elif self.path == '/test-attacker': + body = b'Sibling attacker' + self.send_response(200) + self.send_header('Content-Type', 'text/html') + self.send_header('Content-Length', str(len(body))) + self.end_headers() + self.wfile.write(body) + else: + super().do_GET() + + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + fixture = Path(__file__).parent / 'fixtures' + context.load_cert_chain(fixture / 'web-test.crt', fixture / 'web-test.key') + server = web_ui.ReusableHTTPServer(('127.0.0.1', 0), Handler, context) + port = server.server_address[1] + os.environ['WEB_HOSTNAME'] = 'files.example.test' + os.environ['WEB_HTTPS_PORT'] = str(port) + os.environ['WEB_TRUSTED_ORIGINS'] = '' + + def stop(*args): + raise SystemExit() + signal.signal(signal.SIGTERM, stop) + print(json.dumps({'port': port}), flush=True) + try: + server.serve_forever() + finally: + server.server_close() + + +if __name__ == '__main__': + main() diff --git a/tests/web_security_browser_smoke.mjs b/tests/web_security_browser_smoke.mjs new file mode 100644 index 0000000..128acee --- /dev/null +++ b/tests/web_security_browser_smoke.mjs @@ -0,0 +1,70 @@ +// Real Chromium cookies and real HTTPS handlers, including a same-site attacker. +import assert from 'node:assert/strict'; +import {spawn} from 'node:child_process'; +import {createRequire} from 'node:module'; +import {createInterface} from 'node:readline'; +import {fileURLToPath} from 'node:url'; + +const require=createRequire(import.meta.url); +const {chromium}=require(process.env.PLAYWRIGHT_MODULE || 'playwright'); +const root=fileURLToPath(new URL('../',import.meta.url)); +const fixture=spawn(process.env.PYTHON || 'python3',['-m','tests.web_security_browser_fixture'],{cwd:root,stdio:['ignore','pipe','pipe']}); +let browser; +let logs=''; +fixture.stderr.on('data',chunk=>{logs+=chunk;}); +try { + const port=await new Promise((resolve,reject)=>{ + const lines=createInterface({input:fixture.stdout}); + const timeout=setTimeout(()=>reject(new Error('HTTPS fixture did not start: '+logs)),10000); + lines.on('line',line=>{if(line.startsWith('{')){clearTimeout(timeout);resolve(JSON.parse(line).port);}}); + fixture.once('exit',code=>{clearTimeout(timeout);reject(new Error('Fixture exited: '+code+' '+logs));}); + }); + const target=`https://files.example.test:${port}`; + const evil=`https://evil.example.test:${port}`; + browser=await chromium.launch({headless:true, + ...(process.env.CHROMIUM_EXECUTABLE_PATH?{executablePath:process.env.CHROMIUM_EXECUTABLE_PATH}:{}), + args:['--no-proxy-server','--host-resolver-rules=MAP files.example.test 127.0.0.1, MAP evil.example.test 127.0.0.1']}); + const context=await browser.newContext({ignoreHTTPSErrors:true}); + const page=await context.newPage(); + await page.goto(target+'/healthz'); + const login=await page.evaluate(async()=>{ + const response=await fetch('/api/login',{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':'login'}, + body:JSON.stringify({username:'admin',password:'fixture-password'})}); + return {status:response.status,...await response.json()}; + }); + assert.equal(login.status,200); + assert.ok(login.csrfToken); + const cookie=(await context.cookies(target)).find(item=>item.name==='adfs_session'); + assert.equal(cookie.httpOnly,true);assert.equal(cookie.secure,true);assert.equal(cookie.sameSite,'Strict'); + const control=async action=>page.evaluate(async({action,csrf})=>{ + const response=await fetch('/admin/api/documents/control',{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':csrf},body:JSON.stringify({action})}); + return {status:response.status,...await response.json()}; + },{action,csrf:login.csrfToken}); + assert.equal((await control('pause')).paused,true); + assert.equal((await control('resume')).paused,false); + const attacker=await context.newPage(); + await attacker.goto(evil+'/test-attacker'); + await attacker.evaluate(async target=>{ + await fetch(target+'/admin/api/documents/control',{method:'POST',mode:'no-cors',credentials:'include', + headers:{'Content-Type':'text/plain'},body:JSON.stringify({action:'pause'})}).catch(()=>undefined); + await fetch(target+'/api/logout',{method:'POST',mode:'no-cors',credentials:'include', + headers:{'Content-Type':'text/plain'},body:'{}'}).catch(()=>undefined); + },target); + // Prove that SameSite=Strict actually sent the admin cookie in this attack. + const observations=await page.evaluate(async()=>await (await fetch('/test-observations')).json()); + assert.equal(observations.length,2); + assert.ok(observations.every(item=>item.cookie && item.type==='text/plain')); + assert.equal(await page.evaluate(async()=> (await (await fetch('/admin/api/documents/status')).json()).paused),false); + assert.equal(await page.evaluate(async()=> (await fetch('/api/session')).status),200); + assert.equal(await page.evaluate(async()=> (await fetch('/admin/api/documents/control',{method:'POST', + headers:{'Content-Type':'application/json'},body:'{"action":"pause"}'})).status),403); + assert.equal(await page.evaluate(async csrf=> (await fetch('/api/logout',{method:'POST', + headers:{'Content-Type':'application/json','X-CSRF-Token':csrf},body:'{}'})).status,login.csrfToken),200); + assert.equal(await page.evaluate(async()=> (await fetch('/api/session')).status),401); + assert.equal(await page.evaluate(async token=> (await fetch('/admin/api/documents/status',{ + headers:{Authorization:'Bearer '+token}})).status,login.token),401); + console.log('PASS: real HTTPS login, session-bound CSRF, same-site sibling attack with admin cookie, pause/resume, logout and bearer replay.'); +} finally { + if(browser) await browser.close(); + fixture.kill('SIGTERM'); +}