Skip to content

A community-supported supercharged document management system: scan, index and archive all your documents

Merge branch 'main' into dev

shamoon0f84af27d066
diff --cc docs/changelog.md
index 569e30e29,e2b1b597c..c361309d1
--- a/docs/changelog.md
+++ b/docs/changelog.md
@@@ -1,5 -1,32 +1,32 @@@
# Changelog
+ ## paperless-ngx 2.20.12
+
+ ### Security
+
-- Resolve [GHSA-96jx-fj7m-qh6x](https://github.com/paperless-ngx/paperless-ngx/security/advisories/GHSA-96jx-fj7m-qh6x)
++- Resolve [GHSA-96jx-fj7m-qh6x](https://github.com/paperless-ngx/paperless-ngx/security/advisories/GHSA-96jx-fj7m-qh6x)
+
+ ### Bug Fixes
+
-- Fix: Scope the workflow saves to prevent clobbering filename/archive_filename [@stumpylog](https://github.com/stumpylog) ([#12390](https://github.com/paperless-ngx/paperless-ngx/pull/12390))
-- Fix: don't try to usermod/groupmod when non-root + update docs (#<!---->12365) [@stumpylog](https://github.com/stumpylog) ([#12391](https://github.com/paperless-ngx/paperless-ngx/pull/12391))
-- Fix: avoid moving files if already moved [@shamoon](https://github.com/shamoon) ([#12389](https://github.com/paperless-ngx/paperless-ngx/pull/12389))
-- Fix: remove pagination from document notes api spec [@shamoon](https://github.com/shamoon) ([#12388](https://github.com/paperless-ngx/paperless-ngx/pull/12388))
-- Fix: fix file button hover color in dark mode [@shamoon](https://github.com/shamoon) ([#12367](https://github.com/paperless-ngx/paperless-ngx/pull/12367))
-- Fixhancement: only offer basic auth for appropriate requests [@shamoon](https://github.com/shamoon) ([#12362](https://github.com/paperless-ngx/paperless-ngx/pull/12362))
++- Fix: Scope the workflow saves to prevent clobbering filename/archive_filename [@stumpylog](https://github.com/stumpylog) ([#12390](https://github.com/paperless-ngx/paperless-ngx/pull/12390))
++- Fix: don't try to usermod/groupmod when non-root + update docs (#<!---->12365) [@stumpylog](https://github.com/stumpylog) ([#12391](https://github.com/paperless-ngx/paperless-ngx/pull/12391))
++- Fix: avoid moving files if already moved [@shamoon](https://github.com/shamoon) ([#12389](https://github.com/paperless-ngx/paperless-ngx/pull/12389))
++- Fix: remove pagination from document notes api spec [@shamoon](https://github.com/shamoon) ([#12388](https://github.com/paperless-ngx/paperless-ngx/pull/12388))
++- Fix: fix file button hover color in dark mode [@shamoon](https://github.com/shamoon) ([#12367](https://github.com/paperless-ngx/paperless-ngx/pull/12367))
++- Fixhancement: only offer basic auth for appropriate requests [@shamoon](https://github.com/shamoon) ([#12362](https://github.com/paperless-ngx/paperless-ngx/pull/12362))
+
+ ### All App Changes
+
+ <details>
+ <summary>5 changes</summary>
+
-- Fix: Scope the workflow saves to prevent clobbering filename/archive_filename [@stumpylog](https://github.com/stumpylog) ([#12390](https://github.com/paperless-ngx/paperless-ngx/pull/12390))
-- Fix: avoid moving files if already moved [@shamoon](https://github.com/shamoon) ([#12389](https://github.com/paperless-ngx/paperless-ngx/pull/12389))
-- Fix: remove pagination from document notes api spec [@shamoon](https://github.com/shamoon) ([#12388](https://github.com/paperless-ngx/paperless-ngx/pull/12388))
-- Fix: fix file button hover color in dark mode [@shamoon](https://github.com/shamoon) ([#12367](https://github.com/paperless-ngx/paperless-ngx/pull/12367))
-- Fixhancement: only offer basic auth for appropriate requests [@shamoon](https://github.com/shamoon) ([#12362](https://github.com/paperless-ngx/paperless-ngx/pull/12362))
++- Fix: Scope the workflow saves to prevent clobbering filename/archive_filename [@stumpylog](https://github.com/stumpylog) ([#12390](https://github.com/paperless-ngx/paperless-ngx/pull/12390))
++- Fix: avoid moving files if already moved [@shamoon](https://github.com/shamoon) ([#12389](https://github.com/paperless-ngx/paperless-ngx/pull/12389))
++- Fix: remove pagination from document notes api spec [@shamoon](https://github.com/shamoon) ([#12388](https://github.com/paperless-ngx/paperless-ngx/pull/12388))
++- Fix: fix file button hover color in dark mode [@shamoon](https://github.com/shamoon) ([#12367](https://github.com/paperless-ngx/paperless-ngx/pull/12367))
++- Fixhancement: only offer basic auth for appropriate requests [@shamoon](https://github.com/shamoon) ([#12362](https://github.com/paperless-ngx/paperless-ngx/pull/12362))
+ </details>
+
## paperless-ngx 2.20.11
### Security
diff --cc pyproject.toml
index 6bbdf0f48,cc9e1a3cc..f2a20ac47
--- a/pyproject.toml
+++ b/pyproject.toml
@@@ -1,11 -1,12 +1,11 @@@
[project]
name = "paperless-ngx"
- version = "2.20.11"
+ version = "2.20.13"
description = "A community-supported supercharged document management system: scan, index and archive all your physical documents"
readme = "README.md"
-requires-python = ">=3.10"
+requires-python = ">=3.11"
classifiers = [
"Programming Language :: Python :: 3 :: Only",
- "Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
diff --cc src-ui/src/app/interceptors/auth-expiry.interceptor.spec.ts
index 000000000,9bc22ca15..7e9f156b6
mode 000000,100644..100644
--- a/src-ui/src/app/interceptors/auth-expiry.interceptor.spec.ts
+++ b/src-ui/src/app/interceptors/auth-expiry.interceptor.spec.ts
@@@ -1,0 -1,154 +1,122 @@@
-import { HttpErrorResponse, HttpRequest } from '@angular/common/http'
-import { TestBed } from '@angular/core/testing'
++import {
++ HttpErrorResponse,
++ HttpHandlerFn,
++ HttpRequest,
++} from '@angular/common/http'
+ import { throwError } from 'rxjs'
+ import * as navUtils from '../utils/navigation'
-import { AuthExpiryInterceptor } from './auth-expiry.interceptor'
++import { createAuthExpiryInterceptor } from './auth-expiry.interceptor'
+
-describe('AuthExpiryInterceptor', () => {
- let interceptor: AuthExpiryInterceptor
++describe('withAuthExpiryInterceptor', () => {
++ let interceptor: ReturnType<typeof createAuthExpiryInterceptor>
+ let dateNowSpy: jest.SpiedFunction<typeof Date.now>
+
+ beforeEach(() => {
- TestBed.configureTestingModule({
- providers: [AuthExpiryInterceptor],
- })
-
- interceptor = TestBed.inject(AuthExpiryInterceptor)
++ interceptor = createAuthExpiryInterceptor()
+ dateNowSpy = jest.spyOn(Date, 'now').mockReturnValue(1000)
+ })
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ it('reloads when an API request returns 401', () => {
+ const reloadSpy = jest
+ .spyOn(navUtils, 'locationReload')
+ .mockImplementation(() => {})
+
- interceptor
- .intercept(new HttpRequest('GET', '/api/documents/'), {
- handle: (_request) =>
- throwError(
- () =>
- new HttpErrorResponse({
- status: 401,
- url: '/api/documents/',
- })
- ),
- })
- .subscribe({
- error: () => undefined,
- })
++ interceptor(
++ new HttpRequest('GET', '/api/documents/'),
++ failingHandler('/api/documents/', 401)
++ ).subscribe({
++ error: () => undefined,
++ })
+
+ expect(reloadSpy).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not reload for non-401 errors', () => {
+ const reloadSpy = jest
+ .spyOn(navUtils, 'locationReload')
+ .mockImplementation(() => {})
+
- interceptor
- .intercept(new HttpRequest('GET', '/api/documents/'), {
- handle: (_request) =>
- throwError(
- () =>
- new HttpErrorResponse({
- status: 500,
- url: '/api/documents/',
- })
- ),
- })
- .subscribe({
- error: () => undefined,
- })
++ interceptor(
++ new HttpRequest('GET', '/api/documents/'),
++ failingHandler('/api/documents/', 500)
++ ).subscribe({
++ error: () => undefined,
++ })
+
+ expect(reloadSpy).not.toHaveBeenCalled()
+ })
+
+ it('does not reload for non-api 401 responses', () => {
+ const reloadSpy = jest
+ .spyOn(navUtils, 'locationReload')
+ .mockImplementation(() => {})
+
- interceptor
- .intercept(new HttpRequest('GET', '/accounts/profile/'), {
- handle: (_request) =>
- throwError(
- () =>
- new HttpErrorResponse({
- status: 401,
- url: '/accounts/profile/',
- })
- ),
- })
- .subscribe({
- error: () => undefined,
- })
++ interceptor(
++ new HttpRequest('GET', '/accounts/profile/'),
++ failingHandler('/accounts/profile/', 401)
++ ).subscribe({
++ error: () => undefined,
++ })
+
+ expect(reloadSpy).not.toHaveBeenCalled()
+ })
+
+ it('reloads only once even with multiple API 401 responses', () => {
+ const reloadSpy = jest
+ .spyOn(navUtils, 'locationReload')
+ .mockImplementation(() => {})
+
+ const request = new HttpRequest('GET', '/api/documents/')
- const handler = {
- handle: (_request) =>
- throwError(
- () =>
- new HttpErrorResponse({
- status: 401,
- url: '/api/documents/',
- })
- ),
- }
-
- interceptor.intercept(request, handler).subscribe({
++ const handler = failingHandler('/api/documents/', 401)
++
++ interceptor(request, handler).subscribe({
+ error: () => undefined,
+ })
- interceptor.intercept(request, handler).subscribe({
++ interceptor(request, handler).subscribe({
+ error: () => undefined,
+ })
+
+ expect(reloadSpy).toHaveBeenCalledTimes(1)
+ })
+
+ it('retries reload after cooldown for repeated API 401 responses', () => {
+ const reloadSpy = jest
+ .spyOn(navUtils, 'locationReload')
+ .mockImplementation(() => {})
+
+ dateNowSpy
+ .mockReturnValueOnce(1000)
+ .mockReturnValueOnce(2500)
+ .mockReturnValueOnce(3501)
+
+ const request = new HttpRequest('GET', '/api/documents/')
- const handler = {
- handle: (_request) =>
- throwError(
- () =>
- new HttpErrorResponse({
- status: 401,
- url: '/api/documents/',
- })
- ),
- }
-
- interceptor.intercept(request, handler).subscribe({
++ const handler = failingHandler('/api/documents/', 401)
++
++ interceptor(request, handler).subscribe({
+ error: () => undefined,
+ })
- interceptor.intercept(request, handler).subscribe({
++ interceptor(request, handler).subscribe({
+ error: () => undefined,
+ })
- interceptor.intercept(request, handler).subscribe({
++ interceptor(request, handler).subscribe({
+ error: () => undefined,
+ })
+
+ expect(reloadSpy).toHaveBeenCalledTimes(2)
+ })
+ })
++
++function failingHandler(url: string, status: number): HttpHandlerFn {
++ return (_request) =>
++ throwError(
++ () =>
++ new HttpErrorResponse({
++ status,
++ url,
++ })
++ )
++}
diff --cc src-ui/src/app/interceptors/auth-expiry.interceptor.ts
index 000000000,3be9cc6e0..814cceed5
mode 000000,100644..100644
--- a/src-ui/src/app/interceptors/auth-expiry.interceptor.ts
+++ b/src-ui/src/app/interceptors/auth-expiry.interceptor.ts
@@@ -1,0 -1,38 +1,37 @@@
+ import {
+ HttpErrorResponse,
+ HttpEvent,
- HttpHandler,
- HttpInterceptor,
++ HttpHandlerFn,
++ HttpInterceptorFn,
+ HttpRequest,
+ } from '@angular/common/http'
-import { Injectable } from '@angular/core'
+ import { catchError, Observable, throwError } from 'rxjs'
+ import { locationReload } from '../utils/navigation'
+
-@Injectable()
-export class AuthExpiryInterceptor implements HttpInterceptor {
- private lastReloadAttempt = Number.NEGATIVE_INFINITY
++export const createAuthExpiryInterceptor = (): HttpInterceptorFn => {
++ let lastReloadAttempt = Number.NEGATIVE_INFINITY
+
- intercept(
++ return (
+ request: HttpRequest<unknown>,
- next: HttpHandler
- ): Observable<HttpEvent<unknown>> {
- return next.handle(request).pipe(
++ next: HttpHandlerFn
++ ): Observable<HttpEvent<unknown>> =>
++ next(request).pipe(
+ catchError((error: unknown) => {
+ if (
+ error instanceof HttpErrorResponse &&
+ error.status === 401 &&
+ request.url.includes('/api/')
+ ) {
+ const now = Date.now()
- if (now - this.lastReloadAttempt >= 2000) {
- this.lastReloadAttempt = now
++ if (now - lastReloadAttempt >= 2000) {
++ lastReloadAttempt = now
+ locationReload()
+ }
+ }
+
+ return throwError(() => error)
+ })
+ )
- }
+ }
++
++export const withAuthExpiryInterceptor = createAuthExpiryInterceptor()
diff --cc src-ui/src/environments/environment.prod.ts
index 1e8adbc22,ff10ca3f2..4b66010c6
--- a/src-ui/src/environments/environment.prod.ts
+++ b/src-ui/src/environments/environment.prod.ts
@@@ -3,10 -3,10 +3,10 @@@ const base_url = new URL(document.baseU
export const environment = {
production: true,
apiBaseUrl: document.baseURI + 'api/',
- apiVersion: '9', // match src/paperless/settings.py
+ apiVersion: '10', // match src/paperless/settings.py
appTitle: 'Paperless-ngx',
tag: 'prod',
- version: '2.20.11',
+ version: '2.20.13',
webSocketHost: window.location.host,
webSocketProtocol: window.location.protocol == 'https:' ? 'wss:' : 'ws:',
webSocketBaseUrl: base_url.pathname + 'ws/',
diff --cc src-ui/src/main.ts
index bd1e6ebbb,12fc46428..c5c94d3ff
--- a/src-ui/src/main.ts
+++ b/src-ui/src/main.ts
@@@ -153,8 -146,9 +153,9 @@@ import { AppComponent } from './app/app
import { DirtyDocGuard } from './app/guards/dirty-doc.guard'
import { DirtySavedViewGuard } from './app/guards/dirty-saved-view.guard'
import { PermissionsGuard } from './app/guards/permissions.guard'
-import { ApiVersionInterceptor } from './app/interceptors/api-version.interceptor'
-import { AuthExpiryInterceptor } from './app/interceptors/auth-expiry.interceptor'
-import { CsrfInterceptor } from './app/interceptors/csrf.interceptor'
+import { withApiVersionInterceptor } from './app/interceptors/api-version.interceptor'
++import { withAuthExpiryInterceptor } from './app/interceptors/auth-expiry.interceptor'
+import { withCsrfInterceptor } from './app/interceptors/csrf.interceptor'
import { DocumentTitlePipe } from './app/pipes/document-title.pipe'
import { FilterPipe } from './app/pipes/filter.pipe'
import { UsernamePipe } from './app/pipes/username.pipe'
@@@ -397,21 -407,6 +398,25 @@@ bootstrapApplication(AppComponent,
CorrespondentNamePipe,
DocumentTypeNamePipe,
StoragePathNamePipe,
- provideHttpClient(withInterceptorsFromDi()),
+ provideHttpClient(
+ withInterceptorsFromDi(),
- withInterceptors([withCsrfInterceptor, withApiVersionInterceptor]),
++ withInterceptors([
++ withCsrfInterceptor,
++ withApiVersionInterceptor,
++ withAuthExpiryInterceptor,
++ ]),
+ withFetch()
+ ),
+ provideUiTour({
+ enableBackdrop: true,
+ backdropConfig: {
+ offset: 10,
+ },
+ prevBtnTitle: $localize`Prev`,
+ nextBtnTitle: $localize`Next`,
+ endBtnTitle: $localize`End`,
+ isOptional: true,
+ useLegacyTitle: true,
+ }),
],
}).catch((err) => console.error(err))
diff --cc src/documents/tests/test_api_bulk_edit.py
index 04c3b5ff8,8400372a7..86ef8bb44
--- a/src/documents/tests/test_api_bulk_edit.py
+++ b/src/documents/tests/test_api_bulk_edit.py
@@@ -262,8 -262,52 +262,52 @@@ class TestBulkEditAPI(DirectoriesMixin
self.assertEqual(kwargs["add_custom_fields"], [self.cf1.id])
self.assertEqual(kwargs["remove_custom_fields"], [self.cf2.id])
+ @mock.patch("documents.serialisers.bulk_edit.modify_custom_fields")
+ def test_api_modify_custom_fields_documentlink_forbidden_for_unpermitted_target(
+ self,
+ m,
- ):
++ ) -> None:
+ self.setup_mock(m, "modify_custom_fields")
+ user = User.objects.create_user(username="doc-owner")
+ user.user_permissions.add(Permission.objects.get(codename="change_document"))
+ other_user = User.objects.create_user(username="other-user")
+ source_doc = Document.objects.create(
+ checksum="source",
+ title="Source",
+ owner=user,
+ )
+ target_doc = Document.objects.create(
+ checksum="target",
+ title="Target",
+ owner=other_user,
+ )
+ doclink_field = CustomField.objects.create(
+ name="doclink",
+ data_type=CustomField.FieldDataType.DOCUMENTLINK,
+ )
+
+ self.client.force_authenticate(user=user)
+
+ response = self.client.post(
+ "/api/documents/bulk_edit/",
+ json.dumps(
+ {
+ "documents": [source_doc.id],
+ "method": "modify_custom_fields",
+ "parameters": {
+ "add_custom_fields": {doclink_field.id: [target_doc.id]},
+ "remove_custom_fields": [],
+ },
+ },
+ ),
+ content_type="application/json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ m.assert_not_called()
+
@mock.patch("documents.serialisers.bulk_edit.modify_custom_fields")
- def test_api_modify_custom_fields_with_values(self, m):
+ def test_api_modify_custom_fields_with_values(self, m) -> None:
self.setup_mock(m, "modify_custom_fields")
response = self.client.post(
"/api/documents/bulk_edit/",
diff --cc src/documents/tests/test_api_custom_fields.py
index 945f9e4d7,998bc445a..c02a05e8f
--- a/src/documents/tests/test_api_custom_fields.py
+++ b/src/documents/tests/test_api_custom_fields.py
@@@ -1140,7 -1248,101 +1141,103 @@@ class TestCustomFieldsAPI(DirectoriesMi
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(doc5.custom_fields.first().value, [1])
- def test_documentlink_patch_requires_change_permission_on_target_documents(self):
++ def test_documentlink_patch_requires_change_permission_on_target_documents(
++ self,
++ ) -> None:
+ source_owner = User.objects.create_user(username="source-owner")
+ source_owner.user_permissions.add(
+ Permission.objects.get(codename="change_document"),
+ )
+ other_user = User.objects.create_user(username="other-user")
+
+ source_doc = Document.objects.create(
+ title="Source",
+ checksum="source",
+ mime_type="application/pdf",
+ owner=source_owner,
+ )
+ target_doc = Document.objects.create(
+ title="Target",
+ checksum="target",
+ mime_type="application/pdf",
+ owner=other_user,
+ )
+ custom_field_doclink = CustomField.objects.create(
+ name="Test Custom Field Doc Link",
+ data_type=CustomField.FieldDataType.DOCUMENTLINK,
+ )
+
+ self.client.force_authenticate(user=source_owner)
+
+ resp = self.client.patch(
+ f"/api/documents/{source_doc.id}/",
+ data={
+ "custom_fields": [
+ {
+ "field": custom_field_doclink.id,
+ "value": [target_doc.id],
+ },
+ ],
+ },
+ format="json",
+ )
+
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(
+ CustomFieldInstance.objects.filter(field=custom_field_doclink).count(),
+ 0,
+ )
+
+ def test_documentlink_patch_allowed_with_change_permission_on_target_documents(
+ self,
- ):
++ ) -> None:
+ source_owner = User.objects.create_user(username="source-owner")
+ source_owner.user_permissions.add(
+ Permission.objects.get(codename="change_document"),
+ )
+ other_user = User.objects.create_user(username="other-user")
+
+ source_doc = Document.objects.create(
+ title="Source",
+ checksum="source",
+ mime_type="application/pdf",
+ owner=source_owner,
+ )
+ target_doc = Document.objects.create(
+ title="Target",
+ checksum="target",
+ mime_type="application/pdf",
+ owner=other_user,
+ )
+ custom_field_doclink = CustomField.objects.create(
+ name="Test Custom Field Doc Link",
+ data_type=CustomField.FieldDataType.DOCUMENTLINK,
+ )
+
+ assign_perm("change_document", source_owner, target_doc)
+ self.client.force_authenticate(user=source_owner)
+
+ resp = self.client.patch(
+ f"/api/documents/{source_doc.id}/",
+ data={
+ "custom_fields": [
+ {
+ "field": custom_field_doclink.id,
+ "value": [target_doc.id],
+ },
+ ],
+ },
+ format="json",
+ )
+
+ self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ target_doc.refresh_from_db()
+ self.assertEqual(
+ target_doc.custom_fields.get(field=custom_field_doclink).value,
+ [source_doc.id],
+ )
+
- def test_custom_field_filters(self):
+ def test_custom_field_filters(self) -> None:
custom_field_string = CustomField.objects.create(
name="Test Custom Field String",
data_type=CustomField.FieldDataType.STRING,
diff --cc src/documents/tests/test_api_search.py
index 779576461,190e0c431..6c2ad1eb8
--- a/src/documents/tests/test_api_search.py
+++ b/src/documents/tests/test_api_search.py
@@@ -772,7 -806,59 +806,61 @@@ class TestDocumentSearchApi(Directories
self.assertEqual(results[0]["id"], d3.id)
self.assertEqual(results[1]["id"], d1.id)
- def test_search_more_like_requires_view_permission_on_seed_document(self):
++ def test_search_more_like_requires_view_permission_on_seed_document(
++ self,
++ ) -> None:
+ """
+ GIVEN:
+ - A user can search documents they own
+ - Another user's private document exists with similar content
+ WHEN:
+ - The user requests more-like-this for the private seed document
+ THEN:
+ - The request is rejected
+ """
+ owner = User.objects.create_user("owner")
+ attacker = User.objects.create_user("attacker")
+ attacker.user_permissions.add(
+ Permission.objects.get(codename="view_document"),
+ )
+
+ private_seed = Document.objects.create(
+ title="private bank statement",
+ content="quarterly treasury bank statement wire transfer",
+ checksum="seed",
+ owner=owner,
+ pk=10,
+ )
+ visible_doc = Document.objects.create(
+ title="attacker-visible match",
+ content="quarterly treasury bank statement wire transfer summary",
+ checksum="visible",
+ owner=attacker,
+ pk=11,
+ )
+ other_doc = Document.objects.create(
+ title="unrelated",
+ content="completely different topic",
+ checksum="other",
+ owner=attacker,
+ pk=12,
+ )
+
+ with AsyncWriter(index.open_index()) as writer:
+ index.update_document(writer, private_seed)
+ index.update_document(writer, visible_doc)
+ index.update_document(writer, other_doc)
+
+ self.client.force_authenticate(user=attacker)
+
+ response = self.client.get(
+ f"/api/documents/?more_like_id={private_seed.id}",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.content, b"Insufficient permissions.")
+
- def test_search_filtering(self):
+ def test_search_filtering(self) -> None:
t = Tag.objects.create(name="tag")
t2 = Tag.objects.create(name="tag2")
c = Correspondent.objects.create(name="correspondent")
@@@ -1356,7 -1443,84 +1444,84 @@@
self.assertEqual(results["custom_fields"][0]["id"], custom_field1.id)
self.assertEqual(results["workflows"][0]["id"], workflow1.id)
- def test_global_search_filters_owned_mail_objects(self):
++ def test_global_search_filters_owned_mail_objects(self) -> None:
+ user1 = User.objects.create_user("mail-search-user")
+ user2 = User.objects.create_user("other-mail-search-user")
+ user1.user_permissions.add(
+ Permission.objects.get(codename="view_mailaccount"),
+ Permission.objects.get(codename="view_mailrule"),
+ )
+
+ own_account = MailAccount.objects.create(
+ name="bank owned account",
+ username="[email protected]",
+ password="secret",
+ imap_server="imap.owner.example.com",
+ imap_port=993,
+ imap_security=MailAccount.ImapSecurity.SSL,
+ character_set="UTF-8",
+ owner=user1,
+ )
+ other_account = MailAccount.objects.create(
+ name="bank other account",
+ username="[email protected]",
+ password="secret",
+ imap_server="imap.other.example.com",
+ imap_port=993,
+ imap_security=MailAccount.ImapSecurity.SSL,
+ character_set="UTF-8",
+ owner=user2,
+ )
+ unowned_account = MailAccount.objects.create(
+ name="bank shared account",
+ username="[email protected]",
+ password="secret",
+ imap_server="imap.shared.example.com",
+ imap_port=993,
+ imap_security=MailAccount.ImapSecurity.SSL,
+ character_set="UTF-8",
+ )
+ own_rule = MailRule.objects.create(
+ name="bank owned rule",
+ account=own_account,
+ action=MailRule.MailAction.MOVE,
+ owner=user1,
+ )
+ other_rule = MailRule.objects.create(
+ name="bank other rule",
+ account=other_account,
+ action=MailRule.MailAction.MOVE,
+ owner=user2,
+ )
+ unowned_rule = MailRule.objects.create(
+ name="bank shared rule",
+ account=unowned_account,
+ action=MailRule.MailAction.MOVE,
+ )
+
+ self.client.force_authenticate(user1)
+
+ response = self.client.get("/api/search/?query=bank")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertCountEqual(
+ [account["id"] for account in response.data["mail_accounts"]],
+ [own_account.id, unowned_account.id],
+ )
+ self.assertCountEqual(
+ [rule["id"] for rule in response.data["mail_rules"]],
+ [own_rule.id, unowned_rule.id],
+ )
+ self.assertNotIn(
+ other_account.id,
+ [account["id"] for account in response.data["mail_accounts"]],
+ )
+ self.assertNotIn(
+ other_rule.id,
+ [rule["id"] for rule in response.data["mail_rules"]],
+ )
+
- def test_global_search_bad_request(self):
+ def test_global_search_bad_request(self) -> None:
"""
WHEN:
- Global search query is made without or with query < 3 characters
diff --cc src/documents/tests/test_api_status.py
index 705f28145,ec3f9e611..b8f7d408e
--- a/src/documents/tests/test_api_status.py
+++ b/src/documents/tests/test_api_status.py
@@@ -91,7 -63,13 +92,13 @@@ class TestSystemStatus(APITestCase)
response = self.client.get(self.ENDPOINT)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ def test_system_status_with_bad_basic_auth_challenges(self) -> None:
+ self.client.credentials(HTTP_AUTHORIZATION="Basic invalid")
+ response = self.client.get(self.ENDPOINT)
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(response["WWW-Authenticate"], 'Basic realm="api"')
+
- def test_system_status_container_detection(self):
+ def test_system_status_container_detection(self) -> None:
"""
GIVEN:
- The application is running in a containerized environment
diff --cc src/documents/tests/test_file_handling.py
index 0cd34e939,4e09643b5..ba23e04c3
--- a/src/documents/tests/test_file_handling.py
+++ b/src/documents/tests/test_file_handling.py
@@@ -204,11 -167,57 +205,57 @@@ class TestFileHandling(DirectoriesMixin
)
self.assertEqual(document.filename, "none/none.pdf")
+ @override_settings(FILENAME_FORMAT=None)
+ def test_stale_save_recovers_already_moved_files(self) -> None:
+ old_storage_path = StoragePath.objects.create(
+ name="old-path",
+ path="old/{{title}}",
+ )
+ new_storage_path = StoragePath.objects.create(
+ name="new-path",
+ path="new/{{title}}",
+ )
+ original_bytes = b"original"
+ archive_bytes = b"archive"
+
+ doc = Document.objects.create(
+ title="document",
+ mime_type="application/pdf",
+ checksum=hashlib.md5(original_bytes).hexdigest(),
+ archive_checksum=hashlib.md5(archive_bytes).hexdigest(),
+ filename="old/document.pdf",
+ archive_filename="old/document.pdf",
+ storage_path=old_storage_path,
+ )
+ create_source_path_directory(doc.source_path)
+ doc.source_path.write_bytes(original_bytes)
+ create_source_path_directory(doc.archive_path)
+ doc.archive_path.write_bytes(archive_bytes)
+
+ stale_doc = Document.objects.get(pk=doc.pk)
+ fresh_doc = Document.objects.get(pk=doc.pk)
+ fresh_doc.storage_path = new_storage_path
+ fresh_doc.save()
+ doc.refresh_from_db()
+ self.assertEqual(doc.filename, "new/document.pdf")
+ self.assertEqual(doc.archive_filename, "new/document.pdf")
+
+ stale_doc.storage_path = new_storage_path
+ stale_doc.save()
+
+ doc.refresh_from_db()
+ self.assertEqual(doc.filename, "new/document.pdf")
+ self.assertEqual(doc.archive_filename, "new/document.pdf")
+ self.assertIsFile(doc.source_path)
+ self.assertIsFile(doc.archive_path)
+ self.assertIsNotFile(settings.ORIGINALS_DIR / "old" / "document.pdf")
+ self.assertIsNotFile(settings.ARCHIVE_DIR / "old" / "document.pdf")
+
@override_settings(FILENAME_FORMAT="{correspondent}/{correspondent}")
- def test_document_delete(self):
+ def test_document_delete(self) -> None:
document = Document()
document.mime_type = "application/pdf"
- document.storage_type = Document.STORAGE_TYPE_UNENCRYPTED
+
document.save()
# Ensure that filename is properly generated
diff --cc src/documents/tests/test_workflows.py
index 453a53341,924533698..58d989882
--- a/src/documents/tests/test_workflows.py
+++ b/src/documents/tests/test_workflows.py
@@@ -963,7 -956,65 +963,65 @@@ class TestWorkflows
self.assertEqual(Path(doc.filename), expected_filename)
self.assertTrue(doc.source_path.is_file())
+ def test_workflow_document_updated_does_not_overwrite_filename(self) -> None:
+ """
+ GIVEN:
+ - A document whose filename has been updated in the DB by a concurrent
+ bulk_update_documents task (simulating update_filename_and_move_files
+ completing and writing the new filename to the DB)
+ - A stale in-memory document instance still holding the old filename
+ - An active DOCUMENT_UPDATED workflow
+ WHEN:
+ - run_workflows is called with the stale in-memory instance
+ (as would happen in the second concurrent bulk_update_documents task)
+ THEN:
+ - The DB filename is NOT overwritten with the stale in-memory value
+ (regression test for GH #12386 — the race window between
+ refresh_from_db and document.save in run_workflows)
+ """
+ trigger = WorkflowTrigger.objects.create(
+ type=WorkflowTrigger.WorkflowTriggerType.DOCUMENT_UPDATED,
+ )
+ action = WorkflowAction.objects.create(
+ type=WorkflowAction.WorkflowActionType.ASSIGNMENT,
+ assign_title="Updated by workflow",
+ )
+ workflow = Workflow.objects.create(name="Race condition test workflow", order=0)
+ workflow.triggers.add(trigger)
+ workflow.actions.add(action)
+ workflow.save()
+
+ doc = Document.objects.create(
+ title="race condition test",
+ mime_type="application/pdf",
+ checksum="racecondition123",
+ original_filename="old.pdf",
+ filename="old/path/old.pdf",
+ )
+
+ # Simulate BUD-1 completing update_filename_and_move_files:
+ # the DB now holds the new filename while BUD-2's in-memory instance is stale.
+ new_filename = "new/path/new.pdf"
+ Document.global_objects.filter(pk=doc.pk).update(filename=new_filename)
+
+ # The stale instance still has filename="old/path/old.pdf" in memory.
+ # Mock refresh_from_db so the stale value persists through run_workflows,
+ # replicating the race window between refresh and save.
+ # Mock update_filename_and_move_files to prevent file-not-found errors
+ # since we are only testing DB state here.
+ with (
+ mock.patch(
+ "documents.signals.handlers.update_filename_and_move_files",
+ ),
+ mock.patch.object(Document, "refresh_from_db"),
+ ):
+ run_workflows(WorkflowTrigger.WorkflowTriggerType.DOCUMENT_UPDATED, doc)
+
+ # The DB filename must not have been reverted to the stale old value.
+ doc.refresh_from_db()
+ self.assertEqual(doc.filename, new_filename)
+
- def test_document_added_workflow(self):
+ def test_document_added_workflow(self) -> None:
trigger = WorkflowTrigger.objects.create(
type=WorkflowTrigger.WorkflowTriggerType.DOCUMENT_ADDED,
filter_filename="*sample*",
diff --cc src/documents/views.py
index 91fb0c1ff,5985c17a8..ffdc309fd
--- a/src/documents/views.py
+++ b/src/documents/views.py
@@@ -80,9 -69,9 +80,10 @@@ from packaging import version as packag
from redis import Redis
from rest_framework import parsers
from rest_framework import serializers
+from rest_framework import status
from rest_framework.decorators import action
from rest_framework.exceptions import NotFound
+ from rest_framework.exceptions import PermissionDenied
from rest_framework.exceptions import ValidationError
from rest_framework.filters import OrderingFilter
from rest_framework.filters import SearchFilter
diff --cc src/paperless_mail/tests/test_api.py
index ce3668f7a,905509ec1..6cf1f6717
--- a/src/paperless_mail/tests/test_api.py
+++ b/src/paperless_mail/tests/test_api.py
@@@ -632,7 -632,115 +632,117 @@@ class TestAPIMailRules(DirectoriesMixin
self.assertEqual(returned_rule1.name, "Updated Name 1")
self.assertEqual(returned_rule1.action, MailRule.MailAction.DELETE)
- def test_create_mail_rule_forbidden_for_unpermitted_account(self):
++ def test_create_mail_rule_forbidden_for_unpermitted_account(self) -> None:
+ other_user = User.objects.create_user(username="mail-owner")
+ foreign_account = MailAccount.objects.create(
+ name="ForeignEmail",
+ username="username1",
+ password="password1",
+ imap_server="server.example.com",
+ imap_port=443,
+ imap_security=MailAccount.ImapSecurity.SSL,
+ character_set="UTF-8",
+ owner=other_user,
+ )
+
+ response = self.client.post(
+ self.ENDPOINT,
+ data={
+ "name": "Rule1",
+ "account": foreign_account.pk,
+ "folder": "INBOX",
+ "filter_from": "[email protected]",
+ "maximum_age": 30,
+ "action": MailRule.MailAction.MARK_READ,
+ "assign_title_from": MailRule.TitleSource.FROM_SUBJECT,
+ "assign_correspondent_from": MailRule.CorrespondentSource.FROM_NOTHING,
+ "order": 0,
+ "attachment_type": MailRule.AttachmentProcessing.ATTACHMENTS_ONLY,
+ },
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(MailRule.objects.count(), 0)
+
- def test_create_mail_rule_allowed_for_granted_account_change_permission(self):
++ def test_create_mail_rule_allowed_for_granted_account_change_permission(
++ self,
++ ) -> None:
+ other_user = User.objects.create_user(username="mail-owner")
+ foreign_account = MailAccount.objects.create(
+ name="ForeignEmail",
+ username="username1",
+ password="password1",
+ imap_server="server.example.com",
+ imap_port=443,
+ imap_security=MailAccount.ImapSecurity.SSL,
+ character_set="UTF-8",
+ owner=other_user,
+ )
+ assign_perm("change_mailaccount", self.user, foreign_account)
+
+ response = self.client.post(
+ self.ENDPOINT,
+ data={
+ "name": "Rule1",
+ "account": foreign_account.pk,
+ "folder": "INBOX",
+ "filter_from": "[email protected]",
+ "maximum_age": 30,
+ "action": MailRule.MailAction.MARK_READ,
+ "assign_title_from": MailRule.TitleSource.FROM_SUBJECT,
+ "assign_correspondent_from": MailRule.CorrespondentSource.FROM_NOTHING,
+ "order": 0,
+ "attachment_type": MailRule.AttachmentProcessing.ATTACHMENTS_ONLY,
+ },
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(MailRule.objects.get().account, foreign_account)
+
- def test_update_mail_rule_forbidden_for_unpermitted_account(self):
++ def test_update_mail_rule_forbidden_for_unpermitted_account(self) -> None:
+ own_account = MailAccount.objects.create(
+ name="Email1",
+ username="username1",
+ password="password1",
+ imap_server="server.example.com",
+ imap_port=443,
+ imap_security=MailAccount.ImapSecurity.SSL,
+ character_set="UTF-8",
+ )
+ other_user = User.objects.create_user(username="mail-owner")
+ foreign_account = MailAccount.objects.create(
+ name="ForeignEmail",
+ username="username2",
+ password="password2",
+ imap_server="server.example.com",
+ imap_port=443,
+ imap_security=MailAccount.ImapSecurity.SSL,
+ character_set="UTF-8",
+ owner=other_user,
+ )
+ rule1 = MailRule.objects.create(
+ name="Rule1",
+ account=own_account,
+ folder="INBOX",
+ filter_from="[email protected]",
+ maximum_age=30,
+ action=MailRule.MailAction.MARK_READ,
+ assign_title_from=MailRule.TitleSource.FROM_SUBJECT,
+ assign_correspondent_from=MailRule.CorrespondentSource.FROM_NOTHING,
+ order=0,
+ attachment_type=MailRule.AttachmentProcessing.ATTACHMENTS_ONLY,
+ )
+
+ response = self.client.patch(
+ f"{self.ENDPOINT}{rule1.pk}/",
+ data={"account": foreign_account.pk},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ rule1.refresh_from_db()
+ self.assertEqual(rule1.account, own_account)
+
- def test_get_mail_rules_owner_aware(self):
+ def test_get_mail_rules_owner_aware(self) -> None:
"""
GIVEN:
- Configured rules with different users
diff --cc uv.lock
index 66cfc41ac,9702c6dfc..aa763f617
--- a/uv.lock
+++ b/uv.lock
@@@ -2849,10 -1991,9 +2849,10 @@@ wheels =
[[package]]
name = "paperless-ngx"
- version = "2.20.11"
+ version = "2.20.13"
source = { virtual = "." }
dependencies = [
+ { name = "azure-ai-documentintelligence", marker = "sys_platform == 'darwin' or sys_platform == 'linux'" },
{ name = "babel", marker = "sys_platform == 'darwin' or sys_platform == 'linux'" },
{ name = "bleach", marker = "sys_platform == 'darwin' or sys_platform == 'linux'" },
{ name = "celery", extra = ["redis"], marker = "sys_platform == 'darwin' or sys_platform == 'linux'" },