Compare commits

..
37 changed files with 1601 additions and 2543 deletions

No files matched your search

+2
View File
@@ -1,6 +1,8 @@
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
# Required for uv support for now
enable-beta-ecosystems: true
updates:
# Enable version updates for pnpm
- package-ecosystem: "npm"
-25
View File
@@ -139,8 +139,6 @@ jobs:
file: ./Dockerfile
platforms: ${{ matrix.platform }}
labels: ${{ steps.docker-meta.outputs.labels }}
sbom: true
provenance: mode=max
build-args: |
PNGX_TAG_VERSION=${{ steps.docker-meta.outputs.version }}
outputs: type=image,name=${{ env.REGISTRY }}/${{ steps.repo.outputs.name }},push-by-digest=true,name-canonical=true,push=${{ steps.check-push.outputs.should-push }}
@@ -173,7 +171,6 @@ jobs:
permissions:
contents: read
packages: write
id-token: write
steps:
- name: Download digests
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
@@ -261,25 +258,3 @@ jobs:
echo "Copying ${tag} to ${quay_tag}"
skopeo copy --all "docker://${tag}" "docker://${quay_tag}"
done
- name: Install cosign
uses: sigstore/cosign-installer@881c63bd87e38389154debd8331404ce7ca8a3ab # v4.1.4
- name: Sign images (keyless)
env:
FIRST_TAG: ${{ fromJSON(steps.docker-meta.outputs.json).tags[0] }}
GHCR_REPO: ${{ env.REGISTRY }}/${{ needs.build-arch.outputs.repository }}
PUSH_EXTERNAL: ${{ needs.build-arch.outputs.push-external }}
run: |
digest=$(docker buildx imagetools inspect "${FIRST_TAG}" --format '{{json .Manifest}}' | jq -r '.digest')
echo "Signing manifest list ${digest}"
repos=("${GHCR_REPO}")
if [ "${PUSH_EXTERNAL}" == "true" ]; then
repos+=("docker.io/paperlessngx/paperless-ngx" "quay.io/paperlessngx/paperless-ngx")
fi
for repo in "${repos[@]}"; do
echo "Verifying digest in ${repo}"
docker buildx imagetools inspect "${repo}@${digest}" > /dev/null
echo "Signing ${repo}@${digest}"
cosign sign --yes "${repo}@${digest}"
done
+1 -1
View File
@@ -193,7 +193,7 @@ jobs:
runs-on: ubuntu-26.04
permissions:
contents: read
container: mcr.microsoft.com/playwright:v1.65.1-resolute
container: mcr.microsoft.com/playwright:v1.64.1-resolute
env:
PLAYWRIGHT_BROWSERS_PATH: /ms-playwright
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
+4 -4
View File
@@ -129,10 +129,10 @@ ARG RUNTIME_PACKAGES="\
ghostscript \
gnupg \
icc-profiles-free \
# PostgreSQL
postgresql-client \
# MySQL / MariaDB
mariadb-client \
# PostgreSQL client library, used by psycopg
libpq5 \
# MariaDB client library, used by mysqlclient
libmariadb3 \
# OCRmyPDF dependencies
tesseract-ocr \
tesseract-ocr-eng \
+1 -1
View File
@@ -35,7 +35,7 @@ services:
- "3143:3143" # IMAP
restart: unless-stopped
nginx:
image: docker.io/nginx:1.31.9-alpine
image: docker.io/nginx:1.31.7-alpine
hostname: nginx
container_name: nginx
ports:
@@ -0,0 +1,66 @@
#!/usr/bin/env python3
"""
Single-shot database readiness probe used by the init-wait-for-db s6 service.
Exits 0 if the database server is accepting connections, 1 otherwise. The
retry and backoff loop lives in the calling shell script.
This replaces pg_isready / mariadb-admin ping, so the image does not need the
PostgreSQL or MariaDB command line clients. Like those tools, this only checks
that the server answers. A server which responds with an error, such as bad
credentials or an unknown database, counts as ready, so the real error is
reported by the migrations step instead of this one timing out.
"""
import os
import sys
CONNECT_TIMEOUT = 5
def postgres_ready() -> bool:
from psycopg import pq
from psycopg.conninfo import make_conninfo
# This is libpq's PQping, which is what pg_isready uses. It reports OK when
# the server answers, even if it would refuse these credentials, and REJECT
# when the server is up but still starting or shutting down.
conninfo = make_conninfo(
host=os.environ.get("PAPERLESS_DBHOST", "localhost"),
port=int(os.environ.get("PAPERLESS_DBPORT", "5432")),
user=os.environ.get("PAPERLESS_DBUSER", "paperless"),
connect_timeout=CONNECT_TIMEOUT,
)
return pq.PGconn.ping(conninfo.encode()) == pq.Ping.OK
def mariadb_ready() -> bool:
import MySQLdb
try:
MySQLdb.connect(
host=os.environ.get("PAPERLESS_DBHOST", "localhost"),
port=int(os.environ.get("PAPERLESS_DBPORT", "3306")),
user=os.environ.get("PAPERLESS_DBUSER", "paperless"),
passwd=os.environ.get("PAPERLESS_DBPASS", "paperless"),
connect_timeout=CONNECT_TIMEOUT,
).close()
return True
except MySQLdb.OperationalError as e:
# Codes below 2000 are errors sent by the server (access denied, too
# many connections, ...). 2000+ are client side (can't connect, lost
# connection), meaning the server was not reached.
code = e.args[0] if e.args and isinstance(e.args[0], int) else 0
return 0 < code < 2000
def main() -> int:
if os.environ.get("PAPERLESS_DBENGINE") == "mariadb":
ready = mariadb_ready()
else:
ready = postgres_ready()
return 0 if ready else 1
if __name__ == "__main__":
sys.exit(main())
@@ -7,6 +7,7 @@ set -euo pipefail
declare -r LOG_PREFIX="[init-db-wait]"
declare -ri TIMEOUT=60
declare -r PROBE="/etc/s6-overlay/s6-rc.d/init-wait-for-db/db_ready.py"
declare -i ATTEMPT=0
declare -i DELAY=0
declare -i STARTED_AT=${EPOCHSECONDS:?EPOCHSECONDS var unset}
@@ -35,11 +36,7 @@ delay_next_attempt() {
wait_for_postgres() {
echo "${LOG_PREFIX} Waiting for PostgreSQL to start..."
local -r host="${PAPERLESS_DBHOST:-localhost}"
local -r port="${PAPERLESS_DBPORT:-5432}"
local -r user="${PAPERLESS_DBUSER:-paperless}"
while ! pg_isready -h "${host}" -p "${port}" --username "${user}"; do
while ! python3 "${PROBE}"; do
delay_next_attempt
done
echo "${LOG_PREFIX} Connected to PostgreSQL"
@@ -48,10 +45,7 @@ wait_for_postgres() {
wait_for_mariadb() {
echo "${LOG_PREFIX} Waiting for MariaDB to start..."
local -r host="${PAPERLESS_DBHOST:-localhost}"
local -r port="${PAPERLESS_DBPORT:-3306}"
while ! mariadb-admin --host="${host}" --port="${port}" --skip-ssl ping --silent >/dev/null 2>&1; do
while ! python3 "${PROBE}"; do
delay_next_attempt
done
echo "${LOG_PREFIX} Connected to MariaDB"
+35 -35
View File
@@ -5,14 +5,14 @@
<trans-unit id="ngb.alert.close" datatype="html">
<source>Close</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/alert/alert.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/alert/alert.ts</context>
<context context-type="linenumber">38,39</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.carousel.slide-number" datatype="html">
<source> Slide <x id="INTERPOLATION" equiv-text="source?: NgbSli"/> of <x id="INTERPOLATION_1" equiv-text="s._cycleToSelec"/> </source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/carousel/carousel.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/carousel/carousel.ts</context>
<context context-type="linenumber">386,393</context>
</context-group>
<note priority="1" from="description">Currently selected slide number read by screen reader</note>
@@ -20,219 +20,219 @@
<trans-unit id="ngb.carousel.previous" datatype="html">
<source>Previous</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/carousel/carousel.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/carousel/carousel.ts</context>
<context context-type="linenumber">425,426</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.carousel.next" datatype="html">
<source>Next</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/carousel/carousel.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/carousel/carousel.ts</context>
<context context-type="linenumber">452,453</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.datepicker.select-month" datatype="html">
<source>Select month</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/datepicker/datepicker-navigation-select.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/datepicker/datepicker-navigation-select.ts</context>
<context context-type="linenumber">52</context>
</context-group>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/datepicker/datepicker-navigation-select.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/datepicker/datepicker-navigation-select.ts</context>
<context context-type="linenumber">52</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.datepicker.select-year" datatype="html">
<source>Select year</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/datepicker/datepicker-navigation-select.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/datepicker/datepicker-navigation-select.ts</context>
<context context-type="linenumber">52</context>
</context-group>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/datepicker/datepicker-navigation-select.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/datepicker/datepicker-navigation-select.ts</context>
<context context-type="linenumber">52</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.datepicker.previous-month" datatype="html">
<source>Previous month</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/datepicker/datepicker-navigation.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/datepicker/datepicker-navigation.ts</context>
<context context-type="linenumber">73,76</context>
</context-group>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/datepicker/datepicker-navigation.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/datepicker/datepicker-navigation.ts</context>
<context context-type="linenumber">73,76</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.datepicker.next-month" datatype="html">
<source>Next month</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/datepicker/datepicker-navigation.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/datepicker/datepicker-navigation.ts</context>
<context context-type="linenumber">73,74</context>
</context-group>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/datepicker/datepicker-navigation.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/datepicker/datepicker-navigation.ts</context>
<context context-type="linenumber">73,74</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.pagination.first" datatype="html">
<source>««</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/pagination/pagination.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/pagination/pagination.ts</context>
<context context-type="linenumber">277,278</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.pagination.previous" datatype="html">
<source>«</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/pagination/pagination.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/pagination/pagination.ts</context>
<context context-type="linenumber">277,278</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.pagination.next" datatype="html">
<source>»</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/pagination/pagination.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/pagination/pagination.ts</context>
<context context-type="linenumber">277</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.pagination.last" datatype="html">
<source>»»</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/pagination/pagination.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/pagination/pagination.ts</context>
<context context-type="linenumber">277</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.pagination.first-aria" datatype="html">
<source>First</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/pagination/pagination.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/pagination/pagination.ts</context>
<context context-type="linenumber">277,278</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.pagination.previous-aria" datatype="html">
<source>Previous</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/pagination/pagination.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/pagination/pagination.ts</context>
<context context-type="linenumber">277,278</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.pagination.next-aria" datatype="html">
<source>Next</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/pagination/pagination.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/pagination/pagination.ts</context>
<context context-type="linenumber">277,278</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.pagination.last-aria" datatype="html">
<source>Last</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/pagination/pagination.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/pagination/pagination.ts</context>
<context context-type="linenumber">277,278</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.progressbar.value" datatype="html">
<source><x id="INTERPOLATION"/></source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/progressbar/progressbar.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/progressbar/progressbar.ts</context>
<context context-type="linenumber">39,40</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.timepicker.HH" datatype="html">
<source>HH</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="linenumber">442</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.timepicker.hours" datatype="html">
<source>Hours</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="linenumber">442</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.timepicker.MM" datatype="html">
<source>MM</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="linenumber">442</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.timepicker.minutes" datatype="html">
<source>Minutes</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="linenumber">442</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.timepicker.increment-hours" datatype="html">
<source>Increment hours</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="linenumber">442</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.timepicker.decrement-hours" datatype="html">
<source>Decrement hours</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="linenumber">442</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.timepicker.increment-minutes" datatype="html">
<source>Increment minutes</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="linenumber">442</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.timepicker.decrement-minutes" datatype="html">
<source>Decrement minutes</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="linenumber">442</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.timepicker.SS" datatype="html">
<source>SS</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="linenumber">442</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.timepicker.seconds" datatype="html">
<source>Seconds</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="linenumber">442</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.timepicker.increment-seconds" datatype="html">
<source>Increment seconds</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="linenumber">442</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.timepicker.decrement-seconds" datatype="html">
<source>Decrement seconds</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="linenumber">442</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.timepicker.PM" datatype="html">
<source><x id="INTERPOLATION"/></source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
<context context-type="linenumber">442</context>
</context-group>
</trans-unit>
<trans-unit id="ngb.toast.close-aria" datatype="html">
<source>Close</source>
<context-group purpose="location">
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/toast/toast.ts</context>
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/toast/toast.ts</context>
<context context-type="linenumber">80</context>
</context-group>
</trans-unit>
+30 -30
View File
@@ -15,60 +15,60 @@
},
"private": true,
"dependencies": {
"@angular/cdk": "^22.3.0",
"@angular/common": "~22.3.0",
"@angular/compiler": "~22.3.0",
"@angular/core": "~22.3.0",
"@angular/forms": "~22.3.0",
"@angular/localize": "~22.3.0",
"@angular/platform-browser": "~22.3.0",
"@angular/router": "~22.3.0",
"@angular/cdk": "^22.2.4",
"@angular/common": "~22.2.3",
"@angular/compiler": "~22.2.3",
"@angular/core": "~22.2.3",
"@angular/forms": "~22.2.3",
"@angular/localize": "~22.2.3",
"@angular/platform-browser": "~22.2.3",
"@angular/router": "~22.2.3",
"@ng-bootstrap/ng-bootstrap": "^21.0.0",
"@ng-select/ng-select": "~24.2.1",
"@ngneat/dirty-check-forms": "^3.0.3",
"@popperjs/core": "^2.11.8",
"bootstrap": "^5.3.9",
"bootstrap": "^5.3.8",
"bootstrap-icons": "^1.13.2",
"file-saver": "^2.0.5",
"lodash-es": "^4.18.1",
"marked": "~18.2.1",
"marked": "~18.1.1",
"mime-names": "^1.0.0",
"ngx-color": "^10.1.0",
"ngx-cookie-service": "^22.2.0",
"ngx-cookie-service": "^22.0.0",
"ngx-device-detector": "^12.0.0",
"ngx-ui-tour-ng-bootstrap": "^19.0.0",
"normalize-diacritics": "^5.0.0",
"pdfjs-dist": "^6.5.438",
"pdfjs-dist": "^6.4.299",
"rxjs": "^7.8.2",
"tslib": "^2.9.1",
"tslib": "^2.8.1",
"utif": "^3.1.0",
"uuid": "^14.0.3"
},
"devDependencies": {
"@angular-builders/jest": "^22.0.1",
"@angular-devkit/core": "^22.3.0",
"@angular-devkit/schematics": "^22.3.0",
"@angular-eslint/builder": "22.8.0",
"@angular-eslint/eslint-plugin": "22.8.0",
"@angular-eslint/eslint-plugin-template": "22.8.0",
"@angular-eslint/schematics": "22.8.0",
"@angular-eslint/template-parser": "22.8.0",
"@angular/build": "22.3.0",
"@angular/cli": "22.3.0",
"@angular/compiler-cli": "~22.3.0",
"@playwright/test": "^1.65.1",
"@angular-devkit/core": "^22.2.4",
"@angular-devkit/schematics": "^22.2.4",
"@angular-eslint/builder": "22.6.0",
"@angular-eslint/eslint-plugin": "22.6.0",
"@angular-eslint/eslint-plugin-template": "22.6.0",
"@angular-eslint/schematics": "22.6.0",
"@angular-eslint/template-parser": "22.6.0",
"@angular/build": "22.2.4",
"@angular/cli": "22.2.4",
"@angular/compiler-cli": "~22.2.3",
"@playwright/test": "^1.64.1",
"@types/jest": "^30.0.0",
"@types/node": "^26.6.6",
"@typescript-eslint/eslint-plugin": "^8.74.0",
"@typescript-eslint/parser": "^8.74.0",
"@typescript-eslint/utils": "^8.74.0",
"eslint": "^10.15.0",
"@types/node": "^26.6.5",
"@typescript-eslint/eslint-plugin": "^8.72.0",
"@typescript-eslint/parser": "^8.72.0",
"@typescript-eslint/utils": "^8.72.0",
"eslint": "^10.13.0",
"jest": "30.5.2",
"jest-environment-jsdom": "^30.5.2",
"jest-junit": "^17.0.0",
"jest-preset-angular": "^17.0.3",
"jest-websocket-mock": "^2.5.0",
"prettier": "^3.10.1",
"prettier": "^3.9.10",
"prettier-plugin-organize-imports": "^4.3.0",
"ts-node": "~10.9.2",
"typescript": "^6.0.3"
+1235 -1670
View File
File diff suppressed because it is too large. Load diff
+9 -17
View File
@@ -19,7 +19,7 @@ from documents.models import StoragePath
from documents.models import Tag
from documents.models import Workflow
from documents.models import WorkflowTrigger
from documents.permissions import restrict_queryset_to_visible
from documents.permissions import permitted_object_ids
from documents.regex import safe_regex_search
if TYPE_CHECKING:
@@ -55,10 +55,8 @@ def match_correspondents(document: Document, classifier: DocumentClassifier, use
user = document.owner
if user is not None:
correspondents = restrict_queryset_to_visible(
Correspondent.objects.all(),
user,
"view_correspondent",
correspondents = Correspondent.objects.filter(
id__in=permitted_object_ids(user, Correspondent, "view_correspondent"),
)
else:
correspondents = Correspondent.objects.all()
@@ -86,10 +84,8 @@ def match_document_types(document: Document, classifier: DocumentClassifier, use
user = document.owner
if user is not None:
document_types = restrict_queryset_to_visible(
DocumentType.objects.all(),
user,
"view_documenttype",
document_types = DocumentType.objects.filter(
id__in=permitted_object_ids(user, DocumentType, "view_documenttype"),
)
else:
document_types = DocumentType.objects.all()
@@ -116,10 +112,8 @@ def match_tags(document: Document, classifier: DocumentClassifier, user=None):
user = document.owner
if user is not None:
tags = restrict_queryset_to_visible(
Tag.objects.all(),
user,
"view_tag",
tags = Tag.objects.filter(
id__in=permitted_object_ids(user, Tag, "view_tag"),
)
else:
tags = Tag.objects.all()
@@ -149,10 +143,8 @@ def match_storage_paths(document: Document, classifier: DocumentClassifier, user
user = document.owner
if user is not None:
storage_paths = restrict_queryset_to_visible(
StoragePath.objects.all(),
user,
"view_storagepath",
storage_paths = StoragePath.objects.filter(
id__in=permitted_object_ids(user, StoragePath, "view_storagepath"),
)
else:
storage_paths = StoragePath.objects.all()
+48 -26
View File
@@ -435,33 +435,31 @@ def annotate_authorizing_fields(
)
def user_is_active_superuser(user: User | None) -> bool:
def user_is_unrestricted(user: User | None) -> bool:
"""
True only for an active, authenticated superuser. ``None`` is not one.
True when ``user`` means "no restriction at all" (an absent user, or an
*active* superuser) without needing a database check to know it.
``permitted_object_ids(None, ...)`` itself means the much narrower "only
unowned rows", which is NOT the same thing as "no user filtering
requested", so callers must special-case this before ever calling it.
A deactivated superuser is deliberately NOT unrestricted here, matching
permitted_object_ids's own is_active-before-is_superuser ordering.
Callers that can avoid a database round trip entirely when this is true
(e.g. checking a single already-loaded object's visibility rather than
filtering a queryset) should do so via this function directly, rather
than through restrict_queryset_to_visible() below.
"""
if user is None:
return True
return (
user is not None
and getattr(user, "is_authenticated", False)
getattr(user, "is_authenticated", False)
and getattr(user, "is_active", False)
and getattr(user, "is_superuser", False)
)
def user_is_unrestricted(user: User | None) -> bool:
"""
True when ``user`` means "no restriction at all": an absent user, or an
active superuser.
This is for callers that treat "no user" as "do not filter", such as a
system-triggered code path. It is NOT how ``permitted_object_ids`` and
``restrict_queryset_to_visible`` read ``None``: they take it to mean "no
identity", which sees only unowned rows. A deactivated superuser is not
unrestricted, matching ``permitted_object_ids``'s is_active-before-
is_superuser ordering.
"""
return user is None or user_is_active_superuser(user)
def restrict_queryset_to_visible(
queryset: QuerySet[ModelT],
user: User | None,
@@ -470,14 +468,38 @@ def restrict_queryset_to_visible(
"""
Restrict ``queryset`` to the rows ``user`` may see with ``perm``.
``user=None`` means no identity and sees only unowned rows, exactly as in
``permitted_object_ids``. A caller that wants "no restriction" when there
is no user has to say so itself rather than rely on ``None``.
Delegates the visibility check to the database as a
``WHERE id IN (subquery)`` rather than materializing the full
permitted-id set into a Python collection first: a caller that only
needs to check a small handful of rows (a resolved-id list, a few
RAG-neighbour candidate ids) never pays for scanning or holding the
installation's entire taxonomy in memory to do it.
The check is a ``WHERE id IN (subquery)`` rather than a materialized id
set, so a caller that only checks a handful of rows never scans or holds
the installation's whole taxonomy. An active superuser skips the subquery
entirely and gets ``queryset`` back unchanged.
Returns ``queryset`` unchanged for user_is_unrestricted(user); every
other case is delegated to ``permitted_object_ids`` rather than
re-deciding the ordering here.
"""
if user_is_unrestricted(user):
return queryset
return queryset.filter(pk__in=permitted_object_ids(user, queryset.model, perm))
def user_is_active_superuser(user: User | None) -> bool:
"""
True only for an active, authenticated superuser.
"""
return user is not None and user_is_unrestricted(user)
def restrict_queryset_to_owner_visible(
queryset: QuerySet[ModelT],
user: User | None,
perm: str,
) -> QuerySet[ModelT]:
"""
Like ``restrict_queryset_to_visible``, but ``user=None`` sees only unowned
rows (``permitted_object_ids(None, ...)`` semantics) instead of every row.
See ``user_is_active_superuser``.
"""
if user_is_active_superuser(user):
return queryset
+2 -7
View File
@@ -74,10 +74,6 @@ _LOCK_BACKOFF_CAP: Final[float] = 10.0 # seconds
T = TypeVar("T")
# Upper bound on autocomplete suggestions. tantivy sizes its collector from the
# requested limit, so an unbounded value aborts the whole process on allocation.
MAX_AUTOCOMPLETE_LIMIT = 1000
class ViewerGrant(NamedTuple):
"""Direct user and group view grants for a single document.
@@ -1002,8 +998,7 @@ class TantivyBackend:
Args:
term: Prefix to match against autocomplete words
limit: Maximum number of suggestions to return, capped at
MAX_AUTOCOMPLETE_LIMIT
limit: Maximum number of suggestions to return
user: User for permission filtering (None for no filtering)
Returns:
@@ -1026,7 +1021,7 @@ class TantivyBackend:
"autocomplete_word",
normalized_term,
permission_query,
min(limit, MAX_AUTOCOMPLETE_LIMIT),
limit,
)
return [x[0] for x in matches]
+7 -15
View File
@@ -86,6 +86,7 @@ from documents.permissions import get_document_count_filter_for_user
from documents.permissions import get_permission_grantees
from documents.permissions import has_perms_owner_aware
from documents.permissions import permitted_document_ids
from documents.permissions import permitted_object_ids
from documents.permissions import restrict_queryset_to_visible
from documents.permissions import set_permissions_for_objects
from documents.regex import validate_regex_pattern
@@ -111,10 +112,6 @@ if TYPE_CHECKING:
logger = logging.getLogger("paperless.serializers")
# How much of an upload is read to detect its type. libmagic examines at most
# 7 MiB (its default bytes_max), so this is more than it will ever look at.
_MIME_SNIFF_BYTES = 8 * 1024 * 1024
# https://www.django-rest-framework.org/api-guide/serializers/#example
class DynamicFieldsModelSerializer(serializers.ModelSerializer[Any]):
@@ -596,9 +593,7 @@ class TagSerializer(MatchingModelSerializer, OwnedObjectSerializer):
.annotate(document_count=Count("documents", filter=filter_q))
)
user = getattr(request, "user", None) if request else self.user
# No user at all (no request, no serializer user) means no restriction
if user is not None:
children = restrict_queryset_to_visible(children, user, "view_tag")
children = restrict_queryset_to_visible(children, user, "view_tag")
view = self.context.get("view")
ordering = (
@@ -1797,10 +1792,8 @@ class RunZoneOcrSerializer(serializers.Serializer[Any]):
serializers.PrimaryKeyRelatedField,
): # pragma: no cover
return
template_field.queryset = restrict_queryset_to_visible(
OcrTemplate.objects.all(),
user,
"view_ocrtemplate",
template_field.queryset = OcrTemplate.objects.filter(
id__in=permitted_object_ids(user, OcrTemplate, "view_ocrtemplate"),
).prefetch_related("zones", "zones__custom_field")
@@ -2370,9 +2363,8 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
)
def validate_document(self, document):
# libmagic only examines a bounded prefix, so an upload of any size is
# never read into memory just to detect its type
mime_type = magic.from_buffer(document.read(_MIME_SNIFF_BYTES), mime=True)
document_data = document.file.read()
mime_type = magic.from_buffer(document_data, mime=True)
if not is_mime_type_supported(mime_type):
if (
@@ -2388,7 +2380,7 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
_("File type %(type)s not supported") % {"type": mime_type},
)
return document.name, document
return document.name, document_data
def validate_correspondent(self, correspondent):
if correspondent:
+9 -12
View File
@@ -85,14 +85,11 @@ DRF_DATETIME_FIELD = serializers.DateTimeField()
def add_inbox_tags(sender, document: Document, logging_group=None, **kwargs) -> None:
inbox_tags = Tag.objects.filter(is_inbox_tag=True)
# An unowned document gets every inbox tag, not just the unowned ones
if document.owner is not None:
inbox_tags = restrict_queryset_to_visible(
inbox_tags,
document.owner,
"view_tag",
)
inbox_tags = restrict_queryset_to_visible(
Tag.objects.filter(is_inbox_tag=True),
document.owner,
"view_tag",
)
document.add_nested_tags(inbox_tags)
@@ -789,15 +786,15 @@ def cleanup_user_deletion(sender, instance: User | Group, **kwargs) -> None:
if instance.pk in permissions.get("default_view_users", []):
permissions["default_view_users"].remove(instance.pk)
updated = True
if instance.pk in permissions.get("default_edit_users", []):
permissions["default_edit_users"].remove(instance.pk)
if instance.pk in permissions.get("default_change_users", []):
permissions["default_change_users"].remove(instance.pk)
updated = True
elif isinstance(instance, Group):
if instance.pk in permissions.get("default_view_groups", []):
permissions["default_view_groups"].remove(instance.pk)
updated = True
if instance.pk in permissions.get("default_edit_groups", []):
permissions["default_edit_groups"].remove(instance.pk)
if instance.pk in permissions.get("default_change_groups", []):
permissions["default_change_groups"].remove(instance.pk)
updated = True
if updated:
ui_settings.settings["permissions"] = permissions
@@ -1069,13 +1069,6 @@ class TestAutocomplete:
results = backend.autocomplete("micro", limit=10)
assert "microsoft" in results
def test_huge_limit_is_clamped(self, backend: TantivyBackend) -> None:
"""An oversized limit must be capped, not handed to tantivy as-is."""
doc = DocumentFactory.create(title="Microsoft invoice", content="payment")
backend.add_or_update(doc)
assert "microsoft" in backend.autocomplete("micro", limit=10**15)
def test_results_ordered_by_document_frequency(
self,
backend: TantivyBackend,
-32
View File
@@ -2089,38 +2089,6 @@ class TestDocumentApi(DirectoriesMixin, ConsumeTaskMixin, APITestCase):
self.assertIsNone(overrides.document_type_id)
self.assertIsNone(overrides.tag_ids)
def test_upload_type_is_detected_from_a_prefix(self) -> None:
"""
GIVEN:
- An upload larger than the prefix read to detect its type
WHEN:
- The document is posted
THEN:
- The type is detected from the prefix and the upload is accepted
- The file handed to the consumer holds the whole upload
"""
self.consume_file_mock.return_value = celery.result.AsyncResult(
id=str(uuid.uuid4()),
)
content = SIMPLE_DIGITAL_PDF.read_bytes()
with (
mock.patch("documents.serialisers._MIME_SNIFF_BYTES", 1024),
SimpleUploadedFile(
"simple.pdf",
content,
content_type="application/pdf",
) as f,
):
response = self.client.post(
"/api/documents/post_document/",
{"document": f},
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
input_doc, _ = self.assert_queue_consumption_task_call_args()
self.assertEqual(input_doc.original_file.read_bytes(), content)
def test_upload_with_path_traversal_filename_is_reduced_to_basename(self) -> None:
self.consume_file_mock.return_value = celery.result.AsyncResult(
id=str(uuid.uuid4()),
-40
View File
@@ -1,5 +1,3 @@
from typing import Any
import pytest
from django.core.management import call_command
from django.core.management.base import CommandError
@@ -339,41 +337,3 @@ class TestDocumentListObjectFilterSchema:
param = next(p for p in params if p["name"] == param_name)
assert param["schema"] == {"type": "array", "items": {"type": "integer"}}
assert param["explode"] is False
class TestOauthCallbackSchema:
@pytest.mark.parametrize("name", ["code", "state"])
def test_empty_code_and_state_are_not_schema_valid(
self,
api_schema: dict[str, Any],
name: str,
) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The code and state parameters of the OAuth callback are read
THEN:
- They are required and not empty, the view answers 400 to an empty one
"""
params = api_schema["paths"]["/api/oauth/callback/"]["get"]["parameters"]
param = next(p for p in params if p["name"] == name)
assert param["required"] is True
assert param["schema"]["minLength"] == 1
class TestOcrPageImageSchema:
def test_page_image_is_declared_as_png(self, api_schema: dict[str, Any]) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The 200 response of the OCR template page image is read
THEN:
- It is a PNG, which is what the view serves
"""
path = "/api/ocr_templates/document-page-image/{doc_id}/{page}/"
content = api_schema["paths"][path]["get"]["responses"]["200"]["content"]
assert list(content) == ["image/png"]
+4 -11
View File
@@ -671,8 +671,8 @@ class TestDocumentSearchApi(DirectoriesMixin, APITestCase):
content="things i paid for in august",
pk=2,
checksum="B",
# More than 1 month ago, in the search timezone
added=timezone.localtime() - relativedelta(months=1, days=7),
# 1 month, 1 day ago
added=timezone.now() - relativedelta(months=1, days=1),
)
d3 = Document.objects.create(
title="bank statement 3",
@@ -706,10 +706,6 @@ class TestDocumentSearchApi(DirectoriesMixin, APITestCase):
@override_settings(
TIME_ZONE="America/Denver",
)
@time_machine.travel(
datetime.datetime(2026, 12, 1, 0, 1, tzinfo=datetime.UTC),
tick=False,
)
def test_search_added_in_last_month_timezone_behind(self) -> None:
"""
GIVEN:
@@ -733,8 +729,8 @@ class TestDocumentSearchApi(DirectoriesMixin, APITestCase):
content="things i paid for in august",
pk=2,
checksum="B",
# More than 1 month ago, in the search timezone
added=timezone.localtime() - relativedelta(months=1, days=7),
# 1 month, 1 day ago
added=timezone.now() - relativedelta(months=1, days=1),
)
d3 = Document.objects.create(
title="bank statement 3",
@@ -1000,9 +996,6 @@ class TestDocumentSearchApi(DirectoriesMixin, APITestCase):
response = self.client.get("/api/search/autocomplete/?term=test&limit=-1")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
response = self.client.get("/api/search/autocomplete/?term=test&limit=null")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
response = self.client.get("/api/search/autocomplete/")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
@@ -24,9 +24,7 @@ from documents.permissions import has_perms_owner_aware
from documents.permissions import permitted_document_ids
from documents.permissions import permitted_object_ids
from documents.permissions import restrict_queryset_to_visible
from documents.serialisers import TagSerializer
from documents.serialisers import _get_viewable_duplicates
from documents.signals.handlers import add_inbox_tags
from paperless_testing.factories import CorrespondentFactory
from paperless_testing.factories import DocumentFactory
from paperless_testing.factories import DocumentTypeFactory
@@ -1287,34 +1285,25 @@ class TestBulkEditObjectsTagDescendantPartialPermission:
@pytest.mark.django_db
class TestRestrictQuerysetToVisible:
"""restrict_queryset_to_visible() returns its queryset argument
unchanged only for an active superuser, so the cases that may do that
have to be kept narrow."""
unchanged only for "no restriction at all", so the cases that may do
that have to be kept narrow."""
def test_no_user_sees_only_unowned_rows(self) -> None:
def test_no_user_means_no_restriction(self) -> None:
"""
GIVEN:
- No user at all (a system-triggered call)
- One owned and one unowned tag
WHEN:
- restrict_queryset_to_visible() is called
THEN:
- Only the unowned tag is visible, matching permitted_object_ids
for None, never the whole queryset
- The queryset is returned unfiltered, rather than
permitted_object_ids(None, ...)'s narrower "unowned rows only"
"""
owner = UserFactory(username="vis_none_owner")
owned = TagFactory(owner=owner)
unowned = TagFactory(owner=None)
tag = TagFactory(owner=owner)
visible_ids = set(
restrict_queryset_to_visible(
Tag.objects.all(),
None,
"view_tag",
).values_list("pk", flat=True),
)
visible = restrict_queryset_to_visible(Tag.objects.all(), None, "view_tag")
assert unowned.pk in visible_ids
assert owned.pk not in visible_ids
assert tag.pk in visible.values_list("pk", flat=True)
def test_active_superuser_means_no_restriction(self) -> None:
"""
@@ -1483,89 +1472,3 @@ class TestGetPermissionGrantees:
"change": {"users": [], "groups": []},
},
}
@pytest.mark.django_db
class TestAddInboxTagsVisibility:
def test_unowned_document_gets_every_inbox_tag(self) -> None:
"""
GIVEN:
- An unowned document
- An inbox tag owned by a user and an unowned inbox tag
WHEN:
- add_inbox_tags() runs for the document
THEN:
- Both inbox tags are added, since an unowned document is not
restricted to unowned tags
"""
owner = UserFactory(username="inbox_owner")
owned = TagFactory(owner=owner, is_inbox_tag=True)
unowned = TagFactory(owner=None, is_inbox_tag=True)
doc = DocumentFactory(owner=None)
add_inbox_tags(sender=None, document=doc)
assert set(doc.tags.values_list("pk", flat=True)) == {owned.pk, unowned.pk}
def test_owned_document_only_gets_inbox_tags_its_owner_can_view(self) -> None:
"""
GIVEN:
- A document owned by one user
- An inbox tag owned by the same user, one owned by someone else,
and one unowned
WHEN:
- add_inbox_tags() runs for the document
THEN:
- Only the owner's tag and the unowned tag are added
"""
owner = UserFactory(username="inbox_doc_owner")
other = UserFactory(username="inbox_other")
own = TagFactory(owner=owner, is_inbox_tag=True)
hidden = TagFactory(owner=other, is_inbox_tag=True)
unowned = TagFactory(owner=None, is_inbox_tag=True)
doc = DocumentFactory(owner=owner)
add_inbox_tags(sender=None, document=doc)
added = set(doc.tags.values_list("pk", flat=True))
assert added == {own.pk, unowned.pk}
assert hidden.pk not in added
@pytest.mark.django_db
class TestTagSerializerChildrenVisibility:
def test_no_user_and_no_request_shows_every_child(self) -> None:
"""
GIVEN:
- A tag with a child owned by another user
- A TagSerializer with neither a request nor a user
WHEN:
- The children are serialized
THEN:
- The child is listed, since no user at all means no restriction
here, unlike restrict_queryset_to_visible(None)
"""
parent = TagFactory(owner=None)
child = TagFactory(owner=UserFactory(), tn_parent=parent)
serializer = TagSerializer(parent, context={})
assert {entry["id"] for entry in serializer.data["children"]} == {child.pk}
def test_serializer_user_without_request_hides_unviewable_child(self) -> None:
"""
GIVEN:
- A tag with a child owned by another user
- A TagSerializer given a regular user but no request
WHEN:
- The children are serialized
THEN:
- The child is not listed, the user having no view permission on it
"""
parent = TagFactory(owner=None)
TagFactory(owner=UserFactory(), tn_parent=parent)
viewer = UserFactory()
serializer = TagSerializer(parent, user=viewer, context={})
assert serializer.data["children"] == []
+27 -127
View File
@@ -662,13 +662,11 @@ class TagViewSet(PermissionsAwareDocumentCountMixin, ModelViewSet[Tag]):
user = getattr(getattr(self, "request", None), "user", None)
children_source = list(
annotate_document_count_for_related_queryset(
restrict_queryset_to_visible(
Tag.objects.filter(
pk__in=descendant_pks | {t.pk for t in all_tags},
),
user,
"view_tag",
).select_related("owner"),
Tag.objects.filter(
pk__in=descendant_pks | {t.pk for t in all_tags},
)
.filter(pk__in=permitted_object_ids(user, Tag, "view_tag"))
.select_related("owner"),
through_model=self.document_count_through,
related_object_field=self._get_document_count_source_field(),
user=user,
@@ -944,7 +942,7 @@ class EmailDocumentDetailSchema(EmailSerializer):
parameters=[
OpenApiParameter(
name="id",
type=OpenApiTypes.INT,
type=OpenApiTypes.STR,
location=OpenApiParameter.PATH,
),
],
@@ -1038,14 +1036,6 @@ class DocumentViewSet(
# Bound the IN clauses used for search results and through-table lookups.
selection_data_batch_size = 10_000
def initial(self, request, *args, **kwargs):
super().initial(request, *args, **kwargs)
# Only ASCII digits can be a document id, reject anything else here, before
# any action calls int() on it
pk = kwargs.get("pk")
if pk is not None and not (pk.isascii() and pk.isdigit()):
raise Http404
def _get_selection_data_for_queryset(
self,
queryset: QuerySet[Document],
@@ -2215,7 +2205,7 @@ class DocumentViewSet(
raise Http404
try:
doc_name, doc_file = serializer.validated_data.get("document")
doc_name, doc_data = serializer.validated_data.get("document")
version_label = serializer.validated_data.get("version_label")
t = int(mktime(datetime.now().timetuple()))
@@ -2226,9 +2216,7 @@ class DocumentViewSet(
pathvalidate.sanitize_filename(doc_name),
)
with temp_file_path.open("wb") as scratch_file:
for chunk in doc_file.chunks():
scratch_file.write(chunk)
temp_file_path.write_bytes(doc_data)
os.utime(temp_file_path, times=(t, t))
@@ -2896,13 +2884,6 @@ class UnifiedSearchViewSet(DocumentViewSet):
return Response(max_asn + 1)
LOG_FILES = {
"paperless": "paperless.log",
"mail": "mail.log",
"celery": "celery.log",
}
@extend_schema_view(
list=extend_schema(
description="Logs view",
@@ -2920,7 +2901,6 @@ LOG_FILES = {
name="id",
type=OpenApiTypes.STR,
location=OpenApiParameter.PATH,
enum=list(LOG_FILES),
),
OpenApiParameter(
name="limit",
@@ -2941,12 +2921,18 @@ LOG_FILES = {
class LogViewSet(ViewSet):
permission_classes = (IsAuthenticated, PaperlessAdminPermissions)
ALLOWED_LOG_FILES = {
"paperless": "paperless.log",
"mail": "mail.log",
"celery": "celery.log",
}
def get_log_file(self, log_key: str) -> Path:
return Path(settings.LOGGING_DIR) / LOG_FILES[log_key]
return Path(settings.LOGGING_DIR) / self.ALLOWED_LOG_FILES[log_key]
def retrieve(self, request, *args, **kwargs):
log_key = kwargs.get("pk")
if log_key not in LOG_FILES:
if log_key not in self.ALLOWED_LOG_FILES:
raise Http404
log_file = self.get_log_file(log_key)
@@ -2975,7 +2961,9 @@ class LogViewSet(ViewSet):
def list(self, request, *args, **kwargs):
existing_logs = [
log_key for log_key in LOG_FILES if self.get_log_file(log_key).is_file()
log_key
for log_key in self.ALLOWED_LOG_FILES
if self.get_log_file(log_key).is_file()
]
return Response(existing_logs)
@@ -3510,7 +3498,7 @@ class PostDocumentView(GenericAPIView[Any]):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
doc_name, doc_file = serializer.validated_data.get("document")
doc_name, doc_data = serializer.validated_data.get("document")
doc_name = normalize("NFC", doc_name)
correspondent_id = serializer.validated_data.get("correspondent")
document_type_id = serializer.validated_data.get("document_type")
@@ -3530,9 +3518,7 @@ class PostDocumentView(GenericAPIView[Any]):
pathvalidate.sanitize_filename(doc_name),
)
with temp_file_path.open("wb") as scratch_file:
for chunk in doc_file.chunks():
scratch_file.write(chunk)
temp_file_path.write_bytes(doc_data)
os.utime(temp_file_path, times=(t, t))
@@ -3747,10 +3733,7 @@ class SearchAutoCompleteView(GenericAPIView[Any]):
return HttpResponseBadRequest("Term required")
if "limit" in request.query_params:
try:
limit = int(request.query_params["limit"])
except ValueError:
return HttpResponseBadRequest("Invalid limit")
limit = int(request.query_params["limit"])
if limit <= 0:
return HttpResponseBadRequest("Invalid limit")
else:
@@ -4026,36 +4009,7 @@ class GlobalSearchView(PassUserMixin):
get=extend_schema(
description="Get statistics for the current user",
responses={
(200, "application/json"): inline_serializer(
name="Statistics",
fields={
"documents_total": serializers.IntegerField(),
"documents_inbox": serializers.IntegerField(allow_null=True),
"inbox_tag": serializers.IntegerField(
allow_null=True,
help_text="The first inbox tag, kept for backwards compatibility",
),
"inbox_tags": serializers.ListField(
child=serializers.IntegerField(),
allow_null=True,
),
"document_file_type_counts": serializers.ListField(
child=inline_serializer(
name="MimeTypeCount",
fields={
"mime_type": serializers.CharField(),
"mime_type_count": serializers.IntegerField(),
},
),
),
"character_count": serializers.IntegerField(),
"tag_count": serializers.IntegerField(),
"correspondent_count": serializers.IntegerField(),
"document_type_count": serializers.IntegerField(),
"storage_path_count": serializers.IntegerField(),
"current_asn": serializers.IntegerField(),
},
),
(200, "application/json"): OpenApiTypes.OBJECT,
},
),
)
@@ -4540,13 +4494,7 @@ def get_github_stars() -> int | None:
get=extend_schema(
description="Get the current version of the Paperless-NGX server",
responses={
(200, "application/json"): inline_serializer(
name="RemoteVersion",
fields={
"version": serializers.CharField(),
"update_available": serializers.BooleanField(),
},
),
(200, "application/json"): OpenApiTypes.OBJECT,
},
),
)
@@ -4611,17 +4559,7 @@ class RemoteVersionView(GenericAPIView[Any]):
),
],
responses={
(200, "application/json"): inline_serializer(
name="ReleaseNotes",
fields={
"version": serializers.CharField(),
"releases": serializers.ListField(
child=serializers.DictField(),
help_text="GitHub release objects",
),
"stars": serializers.IntegerField(allow_null=True),
},
),
(200, "application/json"): OpenApiTypes.OBJECT,
},
),
)
@@ -5333,10 +5271,8 @@ class BulkEditObjectsView(PassUserMixin):
"document_types": DocumentTypeFilterSet,
"storage_paths": StoragePathFilterSet,
}[object_type]
user_permitted_objects = restrict_queryset_to_visible(
object_class.objects.all(),
user,
perm_codename,
user_permitted_objects = object_class.objects.filter(
id__in=permitted_object_ids(user, object_class, perm_codename),
)
objs = filterset_class(
data=filters,
@@ -5887,26 +5823,6 @@ class SystemStatusView(PassUserMixin):
)
@extend_schema_view(
get=extend_schema(
description="List the documents in the trash",
responses={(200, "application/json"): DocumentSerializer(many=True)},
),
post=extend_schema(
description="Restore documents from the trash, or delete them permanently",
responses={
(200, "application/json"): inline_serializer(
name="TrashActionResult",
fields={
"result": serializers.CharField(),
"doc_ids": serializers.ListField(
child=serializers.IntegerField(),
),
},
),
},
),
)
class TrashView(ListModelMixin, PassUserMixin):
permission_classes = (IsAuthenticated, TrashPermissions)
serializer_class = TrashSerializer
@@ -6055,22 +5971,6 @@ class OcrTemplateViewSet(BulkPermissionMixin, PassUserMixin, ModelViewSet[OcrTem
]
return super().get_permissions()
@extend_schema(
parameters=[
OpenApiParameter(
name="doc_id",
type=OpenApiTypes.INT,
location=OpenApiParameter.PATH,
),
OpenApiParameter(
name="page",
type={"type": "integer", "minimum": 1},
location=OpenApiParameter.PATH,
description="1-based page number",
),
],
responses={(200, "image/png"): OpenApiTypes.BINARY},
)
@action(
detail=False,
methods=["get"],
+6 -6
View File
@@ -44,7 +44,7 @@ from documents.models import OcrTemplate
from documents.models import OcrTemplateZone
from documents.parsers import ParseError
from documents.parsers import rasterize_pdf_page_to_png
from documents.permissions import restrict_queryset_to_visible
from documents.permissions import permitted_object_ids
from documents.regex import safe_regex_fullmatch
from documents.validators import monetary_validator
from documents.versioning import get_root_document
@@ -261,12 +261,12 @@ def _visible_templates(
"""The enabled templates both the owner and the requester can view, if given."""
templates = OcrTemplate.objects.filter(enabled=True)
if owner is not None:
templates = restrict_queryset_to_visible(templates, owner, "view_ocrtemplate")
templates = templates.filter(
id__in=permitted_object_ids(owner, OcrTemplate, "view_ocrtemplate"),
)
if requester is not None:
templates = restrict_queryset_to_visible(
templates,
requester,
"view_ocrtemplate",
templates = templates.filter(
id__in=permitted_object_ids(requester, OcrTemplate, "view_ocrtemplate"),
)
return templates.order_by("name", "pk").prefetch_related(
"zones",
+22 -22
View File
@@ -2,7 +2,7 @@ msgid ""
msgstr ""
"Project-Id-Version: paperless-ngx\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-11-30 18:39+0000\n"
"POT-Creation-Date: 2026-11-27 02:54+0000\n"
"PO-Revision-Date: 2022-02-17 04:17\n"
"Last-Translator: \n"
"Language-Team: English\n"
@@ -1879,49 +1879,49 @@ msgstr ""
msgid "OCR template zones"
msgstr ""
#: documents/serialisers.py:495 documents/serialisers.py:819
#: documents/serialisers.py:2918 documents/views.py:372 documents/views.py:638
#: documents/views.py:2878 paperless_mail/serialisers.py:145
#: documents/serialisers.py:491 documents/serialisers.py:815
#: documents/serialisers.py:2913 documents/views.py:372 documents/views.py:638
#: documents/views.py:2868 paperless_mail/serialisers.py:145
msgid "Insufficient permissions."
msgstr ""
#: documents/serialisers.py:651
#: documents/serialisers.py:647
msgid "Invalid color."
msgstr ""
#: documents/serialisers.py:2385
#: documents/serialisers.py:2380
#, python-format
msgid "File type %(type)s not supported"
msgstr ""
#: documents/serialisers.py:2429
#: documents/serialisers.py:2424
#, python-format
msgid "Custom field id must be an integer: %(id)s"
msgstr ""
#: documents/serialisers.py:2436
#: documents/serialisers.py:2431
#, python-format
msgid "Custom field with id %(id)s does not exist"
msgstr ""
#: documents/serialisers.py:2453 documents/serialisers.py:2463
#: documents/serialisers.py:2448 documents/serialisers.py:2458
msgid ""
"Custom fields must be a list of integers or an object mapping ids to values."
msgstr ""
#: documents/serialisers.py:2458
#: documents/serialisers.py:2453
msgid "Some custom fields don't exist or were specified twice."
msgstr ""
#: documents/serialisers.py:2605
#: documents/serialisers.py:2600
msgid "Invalid variable detected."
msgstr ""
#: documents/serialisers.py:2974
#: documents/serialisers.py:2969
msgid "Duplicate document identifiers are not allowed."
msgstr ""
#: documents/serialisers.py:3004 documents/views.py:5061
#: documents/serialisers.py:2999 documents/views.py:5001
#, python-format
msgid "Documents not found: %(ids)s"
msgstr ""
@@ -2192,36 +2192,36 @@ msgstr ""
msgid "Specify only one of text, title_search, query, or more_like_id."
msgstr ""
#: documents/views.py:365 documents/views.py:2875
#: documents/views.py:365 documents/views.py:2865
msgid "Invalid more_like_id"
msgstr ""
#: documents/views.py:1705
#: documents/views.py:1697
msgid "Invalid AI configuration."
msgstr ""
#: documents/views.py:1716
#: documents/views.py:1708
msgid "AI backend request timed out."
msgstr ""
#: documents/views.py:1728
#: documents/views.py:1720
msgid "AI backend rejected the request. Check logs for details."
msgstr ""
#: documents/views.py:5077
#: documents/views.py:5017
#, python-format
msgid "Insufficient permissions to share document %(id)s."
msgstr ""
#: documents/views.py:5124
#: documents/views.py:5064
msgid "Bundle is already being processed."
msgstr ""
#: documents/views.py:5190
#: documents/views.py:5130
msgid "The share link bundle is still being prepared. Please try again later."
msgstr ""
#: documents/views.py:5204
#: documents/views.py:5144
msgid "The share link bundle is unavailable."
msgstr ""
@@ -2661,7 +2661,7 @@ msgstr ""
msgid "Chinese Traditional"
msgstr ""
#: paperless/urls.py:455
#: paperless/urls.py:452
msgid "Paperless-ngx administration"
msgstr ""
+9 -13
View File
@@ -374,19 +374,15 @@ class TikaDocumentParser:
try:
parsed = self._tika_client.metadata.from_file(document_path, mime_type)
metadata: list[MetadataEntry] = []
for key, value in parsed.data.items():
if isinstance(value, list):
value = " ".join(str(item) for item in value)
metadata.append(
{
"namespace": "",
"prefix": "",
"key": key,
"value": str(value),
},
)
return metadata
return [
{
"namespace": "",
"prefix": "",
"key": key,
"value": parsed.data[key],
}
for key in parsed.data
]
except Exception as e:
logger.warning(
"Error while fetching document metadata for %s: %s",
-5
View File
@@ -365,8 +365,3 @@ class ApplicationConfigurationSerializer(
class Meta:
model = ApplicationConfiguration
fields = "__all__"
class TOTPActivationSerializer(serializers.Serializer[dict[str, str]]):
secret = serializers.CharField()
code = serializers.CharField()
@@ -131,10 +131,8 @@ class TestTikaParser:
httpx_mock.add_response(
json={
"Content-Type": "application/vnd.oasis.opendocument.text",
"X-TIKA:Parsed-By": ["ParserA", "ParserB"],
"X-TIKA:Parsed-By-Full-Set": [],
"X-TIKA:Parsed-By": [],
"Some-key": "value",
"meta:page-count": 2,
"dcterms:created": "2020-11-21T00:00:00",
},
)
@@ -146,11 +144,6 @@ class TestTikaParser:
assert "dcterms:created" in [m["key"] for m in metadata]
assert "Some-key" in [m["key"] for m in metadata]
values = {entry["key"]: entry["value"] for entry in metadata}
assert values["X-TIKA:Parsed-By"] == "ParserA ParserB"
assert values["X-TIKA:Parsed-By-Full-Set"] == ""
assert values["meta:page-count"] == "2"
assert all(isinstance(value, str) for value in values.values())
def test_convert_failure(
self,
-95
View File
@@ -1,95 +0,0 @@
import pytest
from django.test import Client
from rest_framework import status
from rest_framework.test import APIClient
class TestUnmatchedApiPaths:
@pytest.mark.parametrize("method", ["get", "post", "put", "patch", "delete"])
def test_unmatched_api_path_is_a_json_404(
self,
rest_api_client: APIClient,
method: str,
) -> None:
"""
GIVEN:
- An unauthenticated client
WHEN:
- Any method is sent to an /api/ URL that no route matches
THEN:
- The response is a JSON 404, not a redirect to the login page
"""
response = getattr(rest_api_client, method)("/api/this_does_not_exist/")
assert response.status_code == status.HTTP_404_NOT_FOUND
assert response["Content-Type"].startswith("application/json")
def test_unmatched_api_path_is_a_json_404_when_authenticated(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- An /api/ URL that no route matches is requested
THEN:
- The response is a JSON 404, not the frontend page
"""
response = admin_client.get("/api/this/is/nested/and/missing/")
assert response.status_code == status.HTTP_404_NOT_FOUND
assert response["Content-Type"].startswith("application/json")
def test_other_paths_still_reach_the_frontend_catch_all(
self,
client: Client,
) -> None:
"""
GIVEN:
- An anonymous browser request
WHEN:
- A non-API path is requested
THEN:
- The frontend catch-all still applies, which sends the user to log in
"""
response = client.get("/documents/")
assert response.status_code == status.HTTP_302_FOUND
assert "login" in response["Location"]
class TestDocumentRouteIds:
@pytest.mark.parametrize(
"action",
[
"download",
"history",
"metadata",
"notes",
"preview",
"root",
"share_links",
"suggestions",
"thumb",
],
)
@pytest.mark.parametrize("pk", ["null", "true", "abc", "0.5", "%20"])
def test_non_numeric_document_id_is_a_json_404(
self,
admin_client: APIClient,
action: str,
pk: str,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- A document sub-route is requested with an id that is not a number
THEN:
- The response is a JSON 404, not a server error
"""
response = admin_client.get(f"/api/documents/{pk}/{action}/")
assert response.status_code == status.HTTP_404_NOT_FOUND
assert response["Content-Type"].startswith("application/json")
@@ -1,39 +0,0 @@
import pytest
from rest_framework import status
from rest_framework.test import APIClient
class TestTotpView:
def test_options_does_not_fail(self, admin_client: APIClient) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- OPTIONS is sent to the TOTP endpoint
THEN:
- The request succeeds, DRF's metadata needs a serializer on the view
"""
response = admin_client.options("/api/profile/totp/")
assert response.status_code == status.HTTP_200_OK
@pytest.mark.parametrize(
"body",
[{}, {"secret": "abc"}, {"code": "123456"}, {"secret": None, "code": None}],
)
def test_activation_with_missing_fields_is_a_400(
self,
admin_client: APIClient,
body: dict[str, str | None],
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- TOTP is activated without both the secret and the code
THEN:
- The response is a 400, not a server error
"""
response = admin_client.post("/api/profile/totp/", body, format="json")
assert response.status_code == status.HTTP_400_BAD_REQUEST
+4 -4
View File
@@ -658,9 +658,9 @@ class TestUserGroupDeletionCleanup(TestCase):
"permissions": {
"default_owner": user2.id,
"default_view_users": [user2.id],
"default_edit_users": [user2.id],
"default_change_users": [user2.id],
"default_view_groups": [group.id],
"default_edit_groups": [group.id],
"default_change_groups": [group.id],
},
},
)
@@ -670,13 +670,13 @@ class TestUserGroupDeletionCleanup(TestCase):
permissions = ui_settings.settings.get("permissions", {})
self.assertIsNone(permissions.get("default_owner"))
self.assertEqual(permissions.get("default_view_users"), [])
self.assertEqual(permissions.get("default_edit_users"), [])
self.assertEqual(permissions.get("default_change_users"), [])
group.delete()
ui_settings.refresh_from_db()
permissions = ui_settings.settings.get("permissions", {})
self.assertEqual(permissions.get("default_view_groups"), [])
self.assertEqual(permissions.get("default_edit_groups"), [])
self.assertEqual(permissions.get("default_change_groups"), [])
def test_user_group_deletion_error_handling(self) -> None:
"""
-3
View File
@@ -57,7 +57,6 @@ from documents.views import WorkflowTriggerViewSet
from documents.views import WorkflowViewSet
from documents.views import serve_logo
from paperless.consumers import StatusConsumer
from paperless.views import ApiNotFoundView
from paperless.views import ApplicationConfigurationViewSet
from paperless.views import DisconnectSocialAccountView
from paperless.views import FaviconView
@@ -310,8 +309,6 @@ urlpatterns = [
RedirectView.as_view(url="schema/view/"),
),
*api_router.urls,
# Must stay last, anything unmatched under /api/ is a JSON 404
re_path(r"^.*$", ApiNotFoundView.as_view(), name="api_not_found"),
],
),
),
+6 -55
View File
@@ -24,12 +24,9 @@ from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema
from drf_spectacular.utils import extend_schema_view
from drf_spectacular.utils import inline_serializer
from rest_framework import serializers
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.decorators import action
from rest_framework.exceptions import NotFound
from rest_framework.exceptions import ValidationError
from rest_framework.fields import BooleanField
from rest_framework.filters import OrderingFilter
@@ -38,7 +35,6 @@ from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.throttling import ScopedRateThrottle
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from documents.models import PaperlessTask
@@ -53,7 +49,6 @@ from paperless.serialisers import ApplicationConfigurationSerializer
from paperless.serialisers import GroupSerializer
from paperless.serialisers import PaperlessAuthTokenSerializer
from paperless.serialisers import ProfileSerializer
from paperless.serialisers import TOTPActivationSerializer
from paperless.serialisers import UserSerializer
@@ -279,16 +274,8 @@ class ProfileView(GenericAPIView[Any]):
@extend_schema_view(
get=extend_schema(
description="Generate a new TOTP secret, its otpauth URL and a QR code",
responses={
(200, "application/json"): inline_serializer(
name="TotpSetup",
fields={
"url": serializers.CharField(),
"qr_svg": serializers.CharField(help_text="QR code as an SVG"),
"secret": serializers.CharField(),
},
),
(200, "application/json"): OpenApiTypes.OBJECT,
},
),
post=extend_schema(
@@ -303,17 +290,7 @@ class ProfileView(GenericAPIView[Any]):
},
},
responses={
(200, "application/json"): inline_serializer(
name="TotpActivation",
fields={
"success": serializers.BooleanField(),
"recovery_codes": serializers.ListField(
child=serializers.CharField(),
allow_null=True,
help_text="Only returned when the code was valid",
),
},
),
(200, "application/json"): OpenApiTypes.OBJECT,
},
),
delete=extend_schema(
@@ -329,7 +306,6 @@ class TOTPView(GenericAPIView[Any]):
"""
permission_classes = [IsAuthenticated]
serializer_class = TOTPActivationSerializer
def get(self, request, *args, **kwargs):
"""
@@ -352,18 +328,15 @@ class TOTPView(GenericAPIView[Any]):
"""
Validates a TOTP code and activates the TOTP authenticator
"""
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
secret = serializer.validated_data["secret"]
valid = totp_auth.validate_totp_code(
secret,
serializer.validated_data["code"],
request.data["secret"],
request.data["code"],
)
recovery_codes = None
if valid:
auth = totp_auth.TOTP.activate(
request.user,
secret,
request.data["secret"],
).instance
signals.authenticator_added.send(
sender=Authenticator,
@@ -550,14 +523,7 @@ class DisconnectSocialAccountView(GenericAPIView[Any]):
@extend_schema_view(
get=extend_schema(
responses={
(200, "application/json"): inline_serializer(
name="SocialAccountProvider",
fields={
"name": serializers.CharField(),
"login_url": serializers.CharField(),
},
many=True,
),
(200, "application/json"): OpenApiTypes.OBJECT,
},
),
)
@@ -591,18 +557,3 @@ class SocialAccountProvidersView(GenericAPIView[Any]):
]
return Response(sorted(resp, key=lambda p: p["name"]))
@extend_schema(exclude=True)
class ApiNotFoundView(APIView):
"""
A JSON 404 for any /api/ URL that no other route matches. Without this, those
URLs fall through to the frontend catch-all, which answers a redirect to the
login page or the single page app, never an error an API client can read.
"""
authentication_classes = ()
permission_classes = ()
def initial(self, request, *args, **kwargs):
raise NotFound
+8 -5
View File
@@ -11,7 +11,8 @@ from documents.models import Correspondent
from documents.models import DocumentType
from documents.models import StoragePath
from documents.models import Tag
from documents.permissions import restrict_queryset_to_visible
from documents.permissions import permitted_object_ids
from documents.permissions import restrict_queryset_to_owner_visible
MATCH_THRESHOLD = 0.8
@@ -33,7 +34,7 @@ def _resolve_visible_ids(
"""
if not ids:
return []
queryset = restrict_queryset_to_visible(
queryset = restrict_queryset_to_owner_visible(
model.objects.filter(pk__in=ids),
user,
perm,
@@ -66,9 +67,11 @@ def _match_by_name(
model: type[ModelT],
perm: str,
) -> list[ModelT]:
# A workflow may have no user. In that case only unowned objects are visible,
# which avoids another user's private taxonomy.
queryset = restrict_queryset_to_visible(model.objects.all(), user, perm)
# A workflow may have no user. In that case permitted_object_ids limits
# matching to unowned objects, avoiding another user's private taxonomy.
queryset = model.objects.filter(
pk__in=permitted_object_ids(user, model, perm),
)
return _match_names_to_queryset(names, queryset)
+2 -2
View File
@@ -13,7 +13,7 @@ from documents.models import Document
from documents.models import DocumentType
from documents.models import StoragePath
from documents.models import Tag
from documents.permissions import restrict_queryset_to_visible
from documents.permissions import restrict_queryset_to_owner_visible
from paperless_ai.prompts.context import TaxonomyBlockPromptContext
from paperless_ai.prompts.render import render_prompt
@@ -97,7 +97,7 @@ def _visible_ranked_candidates(
"""
if not weighted_ids:
return []
visible_queryset = restrict_queryset_to_visible(
visible_queryset = restrict_queryset_to_owner_visible(
model.objects.filter(pk__in=weighted_ids),
user,
perm,
+48 -40
View File
@@ -2,7 +2,6 @@ import datetime
import imaplib
import itertools
import logging
import os
import socket
import ssl
import tempfile
@@ -894,6 +893,8 @@ class MailAccountHandler(LoggingMixin):
def _handle_message(self, message, rule: MailRule) -> int:
message = self._preprocess_message(message)
processed_elements = 0
# Skip Message handling when only attachments are to be processed but
# message doesn't have any.
if (
@@ -901,7 +902,7 @@ class MailAccountHandler(LoggingMixin):
and rule.consumption_scope == MailRule.ConsumptionScope.ATTACHMENTS_ONLY
):
self._record_processed_without_consumption(message, rule)
return 0
return processed_elements
self.log.debug(
f"Rule {rule}: "
@@ -912,47 +913,29 @@ class MailAccountHandler(LoggingMixin):
tag_ids: list[int] = [tag.id for tag in rule.assign_tags.all()]
doc_type = rule.assign_document_type
consume_tasks: list[Signature] = []
if (
rule.consumption_scope == MailRule.ConsumptionScope.EML_ONLY
or rule.consumption_scope == MailRule.ConsumptionScope.EVERYTHING
):
consume_tasks.append(
self._build_eml_task(
message,
rule,
tag_ids,
doc_type,
),
processed_elements += self._process_eml(
message,
rule,
tag_ids,
doc_type,
)
if (
rule.consumption_scope == MailRule.ConsumptionScope.ATTACHMENTS_ONLY
or rule.consumption_scope == MailRule.ConsumptionScope.EVERYTHING
):
consume_tasks.extend(
self._build_attachment_tasks(
message,
rule,
tag_ids,
doc_type,
),
processed_elements += self._process_attachments(
message,
rule,
tag_ids,
doc_type,
)
# One chord per message, so the mail action and the ProcessedMail row
# are written once, after every part of the message has been consumed
if consume_tasks:
queue_consumption_tasks(
consume_tasks=consume_tasks,
rule=rule,
message=message,
uid_validity=self._current_uid_validity,
)
else:
self._record_processed_without_consumption(message, rule)
return len(consume_tasks)
return processed_elements
def _record_processed_without_consumption(
self,
@@ -1011,14 +994,16 @@ class MailAccountHandler(LoggingMixin):
return True
return False
def _build_attachment_tasks(
def _process_attachments(
self,
message: MailMessage,
rule: MailRule,
tag_ids,
doc_type,
) -> list[Signature]:
consume_tasks: list[Signature] = []
):
processed_attachments = 0
consume_tasks = []
for att in message.attachments:
if (
@@ -1119,6 +1104,8 @@ class MailAccountHandler(LoggingMixin):
)
consume_tasks.append(consume_task)
processed_attachments += 1
else:
self.log.debug(
f"Rule {rule}: "
@@ -1127,22 +1114,33 @@ class MailAccountHandler(LoggingMixin):
f"by paperless",
)
return consume_tasks
if len(consume_tasks) > 0:
queue_consumption_tasks(
consume_tasks=consume_tasks,
rule=rule,
message=message,
uid_validity=self._current_uid_validity,
)
else:
# No files to consume, just mark as processed if it wasn't by .eml processing
self._record_processed_without_consumption(message, rule)
def _build_eml_task(
return processed_attachments
def _process_eml(
self,
message: MailMessage,
rule: MailRule,
tag_ids,
doc_type,
) -> Signature:
):
settings.SCRATCH_DIR.mkdir(parents=True, exist_ok=True)
fd, temp_filename = tempfile.mkstemp(
_, temp_filename = tempfile.mkstemp(
prefix="paperless-mail-",
dir=settings.SCRATCH_DIR,
suffix=".eml",
)
with os.fdopen(fd, "wb") as f:
with Path(temp_filename).open("wb") as f:
# Move "From"-header to beginning of file
# TODO: This ugly workaround is needed because the parser is
# chosen only by the mime_type detected via magic
@@ -1193,7 +1191,17 @@ class MailAccountHandler(LoggingMixin):
owner_id=rule.owner.id if rule.owner else None,
)
return consume_file.s(
consume_task = consume_file.s(
input_doc=input_doc,
overrides=doc_overrides,
).set(headers={"trigger_source": PaperlessTask.TriggerSource.EMAIL_CONSUME})
queue_consumption_tasks(
consume_tasks=[consume_task],
rule=rule,
message=message,
uid_validity=self._current_uid_validity,
)
processed_elements = 1
return processed_elements
-38
View File
@@ -416,44 +416,6 @@ class TestMail(
1,
)
def test_handle_message_everything_scope_single_row(self) -> None:
"""
GIVEN:
- A rule consuming the eml and attachments, and a mail with or
without attachments
WHEN:
- The mail is handled and its queued mail action is applied
THEN:
- The eml and attachments are queued together in one call
- Exactly one ProcessedMail row exists and it is not
PROCESSED_WO_CONSUMPTION
"""
rule = MailRule.objects.create(
account=MailAccount.objects.create(
name="test",
imap_server="",
username="admin",
password="secret",
),
consumption_scope=MailRule.ConsumptionScope.EVERYTHING,
)
for attachments in (0, 2):
with self.subTest(attachments=attachments):
self.mailMocker._queue_consumption_tasks_mock.reset_mock()
message = self.mailMocker.messageBuilder.create_message(
subject=f"{attachments} attachments",
attachments=attachments,
)
result = self.mail_account_handler._handle_message(message, rule)
self.mailMocker.apply_mail_actions()
self.assertEqual(result, 1 + attachments)
self.mailMocker._queue_consumption_tasks_mock.assert_called_once()
processed = ProcessedMail.objects.get(rule=rule, uid=message.uid)
self.assertEqual(processed.status, "SUCCESS")
def test_handle_empty_message_long_subject(self) -> None:
"""
GIVEN:
@@ -272,6 +272,8 @@ class TestMailMessageGpgDecryptor(TestMail):
"override_title": message.subject,
"override_filename": f"{message.subject}.eml",
},
],
[
{"override_title": "file_0", "override_filename": "file_0.pdf"},
{"override_title": "file_1", "override_filename": "file_1.pdf"},
],
+2 -34
View File
@@ -10,7 +10,6 @@ from django.http import HttpResponseRedirect
from django.utils import timezone
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter
from drf_spectacular.utils import extend_schema
from drf_spectacular.utils import extend_schema_view
from drf_spectacular.utils import inline_serializer
@@ -255,39 +254,8 @@ class MailRuleViewSet(PassUserMixin, ModelViewSet[MailRule]):
@extend_schema_view(
get=extend_schema(
description=(
"Callback view for OAuth2 authentication. Redirects back to the "
"frontend, with the outcome in the query string"
),
parameters=[
OpenApiParameter(
name="code",
# An empty value is rejected
type={"type": "string", "minLength": 1},
location=OpenApiParameter.QUERY,
required=True,
description="Authorization code returned by the OAuth provider",
),
OpenApiParameter(
name="state",
# An empty value is rejected
type={"type": "string", "minLength": 1},
location=OpenApiParameter.QUERY,
required=True,
description="State value, must match the one stored in the session",
),
OpenApiParameter(
name="scope",
type=OpenApiTypes.STR,
location=OpenApiParameter.QUERY,
required=False,
description="Granted scopes, sent by Gmail but not by Outlook",
),
],
responses={
302: None,
(400, "text/html"): OpenApiTypes.STR,
},
description="Callback view for OAuth2 authentication",
responses={200: None},
),
)
class OauthCallbackView(GenericAPIView[Any]):