460 Commits
Author SHA1 Message Date
nils 6ec18900fe update workspace view data hook.
ci / docker (backend, backend/Dockerfile, backend) (push) Failing after 14s
ci / docker (frontend, frontend/Dockerfile, frontend) (push) Failing after 13s
2025-12-14 03:23:12 +01:00
nils b6857bd0b3 feat: optimize frontend document panel rendering and folder creation. 2025-12-12 03:47:50 +01:00
nils 6ba8084caa feat: Refactor DocumentsPanel to use a shared application shell context for state management 2025-12-12 02:57:10 +01:00
nils 34e6c3037f feat: Add document update functionality to frontend 2025-12-12 02:11:24 +01:00
nils b10404f0f3 feat: add frontend folder creation functionality. 2025-12-12 01:51:33 +01:00
nils d281364aef feat: refactor document filtering logic to useWorkspaceViewData. 2025-12-12 00:51:26 +01:00
nils b2a355312f feat: update frontend data management and types. 2025-12-11 21:27:09 +01:00
nils e8636ce7da feat: Replaced document preview with a new fullscreen viewer 2025-12-11 00:44:11 +01:00
nils f6bd6e2feb fix 2025-12-10 14:38:34 +01:00
nils 8cc5ed854a fix 2025-12-10 03:57:43 +01:00
nils c8cc4b4b7c feat: adjust frontend document navigation and opening contexts. 2025-12-10 03:56:22 +01:00
nils ae002b99f0 feat: refactor frontend sidepanel to detailPanel naming. 2025-12-10 03:56:17 +01:00
nils 9d13365348 feat: update frontend components for integration. 2025-12-10 03:55:44 +01:00
nils e367006a6c fix desktop opendetail panel on enter 2025-12-10 03:54:00 +01:00
nils d15d5388fa cleanup bulk actions 2025-12-10 03:06:14 +01:00
nils b9f0278329 feat: Centralize document preview logic into useDocumentPreview and add correspondentLookupByName to useCorrespondents 2025-12-10 02:33:22 +01:00
nils ed8450c0e2 refactor: streamline hook integration and context object creation in useDocumentsWorkspace by directly using hook return values and consolidating related state. 2025-12-10 02:07:44 +01:00
nils f0b58317b9 refactor: restructure useAppShell context into nested objects 2025-12-10 01:48:46 +01:00
nils 82dcd6d33c feat: enhance frontend tag operations with UI notifications. 2025-12-10 00:01:33 +01:00
nils 1d8d55144f feat: Implement asynchronous tag operations with user feedback 2025-12-09 23:13:18 +01:00
nils 3ccc1f6698 feat: Refactor tag and correspondent management to use canonical types and dedicated managers. 2025-12-09 18:56:11 +01:00
nils ce821c1817 feat: update frontend document management components. 2025-12-09 13:49:07 +01:00
nils 8a16293f0e feat: refine frontend folder management and display by merging folder tree data. 2025-12-09 12:37:27 +01:00
nils 463046c970 layout fixes 2025-12-09 12:04:44 +01:00
nils 116e839f67 less useMemo 2025-12-09 02:04:39 +01:00
nils 24950e1a12 simplify frontend document and folder memoization. 2025-12-09 02:03:46 +01:00
nils 1d127e2122 feat: Add TagRemovalZone component and refactor drag-drop for tag management 2025-12-09 01:30:31 +01:00
nils aaa4a9b577 feat: Prevent tag transfers on folders 2025-12-09 01:10:20 +01:00
nils ebc7ce67a1 feat: Refactor tag interaction handling to use unified handlers 2025-12-09 01:00:54 +01:00
nils 4f28230243 reverse toast order 2025-12-09 00:24:59 +01:00
nils a8c133bbf9 feat: refactor frontend document tag display by removing EntryTags. 2025-12-09 00:21:15 +01:00
nils f3292211a8 feat: remove unused canvas focus request from tag interactions. 2025-12-09 00:17:16 +01:00
nils 99fa12a1be feat: refactor frontend tag interaction handlers 2025-12-09 00:03:55 +01:00
nils c38d88c209 feat: Implement tag drag-and-drop functionality 2025-12-08 23:49:50 +01:00
nils 757913cf00 feat: Implement new drag-and-drop system for documents and tags, including workspace-level handling and improved visual feedback. 2025-12-08 23:30:18 +01:00
nils a850f70e24 feat: refactor folder refresh with toast notifications and console logging for toasts. 2025-12-08 19:20:36 +01:00
nils dbff980792 fix 2025-12-08 16:31:59 +01:00
nils 04a9316c8e npm 2025-12-08 16:27:20 +01:00
nils 3a0ef7867e feat: Add document move and tag mutations, refine document upload logic 2025-12-08 16:27:13 +01:00
nils 5632d2252a feat: refactor DesktopWorkspace to use new contexts for asset and tag interactions 2025-12-08 12:40:25 +01:00
nils 73468bbb02 refactor(documents): encapsulate panel logic and state into dedicated React contexts 2025-12-08 12:31:30 +01:00
nils 44cf4603fe fix tag dragging 2025-12-08 12:30:44 +01:00
nils 608239e412 feat: Refactor frontend authentication and tenant switching to use global state 2025-12-08 01:19:52 +01:00
nils 5840c9d1d0 feat: Refactor frontend hooks to use useNavigate and useAppDispatch directly 2025-12-08 00:05:06 +01:00
nils d46db2c701 refactor: centralize API error notifications with a new useNotifyApiError hook 2025-12-07 23:55:47 +01:00
nils 595c170c00 refactor: centralize frontend status message handling with useStatusToast 2025-12-07 23:46:10 +01:00
nils b29e856225 feat: refactor frontend document sorting preferences and sidebar utilities. 2025-12-07 22:55:26 +01:00
nils 53664f2421 refactor: Replace useWorkspaceBreadcrumbs hook with resolveBreadcrumbs utility 2025-12-07 22:10:34 +01:00
nils d62f462129 fix 2025-12-07 20:45:01 +01:00
nils 2d5cc1fd7c fix 2025-12-07 01:35:21 +01:00
nils 632665b0ed simplify shit 2025-12-07 01:31:34 +01:00
nils 47599aba4a feat: Refactor folder tree management to use FoldersManager and remove onToggle functionality 2025-12-07 01:12:28 +01:00
nils bd1cdc0817 feat: Refactor sidebar props to simplify data flow 2025-12-06 23:04:49 +01:00
nils 54d72138d2 feat: Add an Ollama-based PDF OCR script and refactor frontend folder tree management with a new FoldersManager and useSyncExternalStore. 2025-12-06 22:40:11 +01:00
nils c88c3c13d6 feat: Introduce FoldersManager and useFolderData to manage and display folder contents, including documents and subfolders. 2025-12-06 22:06:53 +01:00
nils 9b79115170 drop useMemo 2025-12-05 01:58:19 +01:00
nils 66a0be42bd cleanup 2025-12-05 00:41:00 +01:00
nils b8a23c7ec4 cleanup 2025-12-05 00:32:45 +01:00
nils 65ad797378 refine viewer detail panel logic and styling. 2025-12-05 00:14:25 +01:00
nils 36c8e4cbaa cleanup 2025-12-04 23:55:04 +01:00
nils 86b9ac2ab6 feat: Add document download link component, refactor download URL resolution with expiration checks 2025-12-04 23:38:17 +01:00
nils 22e39420bb feat: update frontend for document handling and styling. 2025-12-04 23:26:22 +01:00
nils 2389c6f4bc feat: update document workspace and taxonomy data hooks. 2025-12-04 23:10:12 +01:00
nils 8aa1872ea5 refactor: Reorganize frontend by moving UI components, hooks, and utilities to new components, logic, features, and lib directories 2025-12-04 23:05:35 +01:00
nils 128714a1e0 improve Content-Disposition header generation for non-ASCII characters. 2025-12-04 22:21:49 +01:00
nils 56e45561d6 fix 2025-12-04 22:19:49 +01:00
nils 4308ff220b refactor: Decouple frontend API calls from a shared client instance 2025-12-04 21:59:39 +01:00
nils d06fc133e7 refactor 2025-12-04 17:20:45 +01:00
nils 834d4f641b move date formatting to a utility. 2025-12-04 16:21:00 +01:00
nils 2353f114f6 fix 2025-12-04 14:48:20 +01:00
nils dd521f9f1d simplify 2025-12-04 14:37:09 +01:00
nils 34230cda21 fix 2025-12-04 13:22:04 +01:00
nils 0a67d88ff2 fix 2025-12-04 13:17:31 +01:00
nils e8f578eb48 feat: standardize correspondent and tag types with usage count 2025-12-04 13:11:52 +01:00
nils 225f810513 fix api in backend 2025-12-04 13:10:32 +01:00
nils b5d0a8cb66 refactor 2025-12-04 12:43:10 +01:00
nils 2ea74816fb feat: Refactor utility and component exports, update dependencies, and add Knip for unused code detection. 2025-12-04 11:58:04 +01:00
nils c3375b714d remove geometry.ts 2025-12-04 11:10:48 +01:00
nils f57bb9f6eb introduce a unified document viewer component. 2025-12-04 02:21:11 +01:00
nils cbd463e1d9 cleanup 2025-12-04 01:34:26 +01:00
nils 3f7c294948 feat: Remove documentLink prop and onNavigatorSnapshot logic, and add openDetailPanel and closeDetailPanel to document shell. 2025-12-04 01:32:28 +01:00
nils 8bb9f9950a feat: refactor document opening/preview logic to support preview/sidepanel actions. 2025-12-04 01:02:54 +01:00
nils 447b012e48 feat: Introduce DocumentOpenContext for document activation in the frontend 2025-12-04 00:57:54 +01:00
nils 65555c18e8 cleanup 2025-12-04 00:29:32 +01:00
nils 9f88823315 Remove document link and download URL management from frontend components 2025-12-04 00:23:27 +01:00
nils 4b02d1c7d5 cleanup 2025-12-04 00:09:32 +01:00
nils c6a627af8a feat: Add Download type and document download field, unify preview zoom styling 2025-12-03 23:56:35 +01:00
nils dad6f1e0b8 refactor document viewer UI buttons and props. 2025-12-03 22:48:18 +01:00
nils e46318aee5 feat: Add OCR script for PDFs using Ollama and refine document preview navigation and zoom behavior. 2025-12-03 17:07:51 +01:00
nils 186743ee37 feat: frontend status toast overlay, while refactoring document store usage. 2025-12-03 15:16:26 +01:00
nils 4337575b17 improve desktop layout rendering readiness. 2025-12-03 14:30:56 +01:00
nils e66451afbd feat: Introduce a generic inline rename input component for document editing 2025-12-03 12:00:57 +01:00
nils e1dd1990d7 refactor: Remove redundant max-width and max-height properties from preview zoom elements. 2025-12-02 15:16:39 +01:00
nils c0093edc09 refactor: remove openDocumentPreview and onDocumentOpen props from document panel components and hooks. 2025-12-02 14:59:23 +01:00
nils cf41148942 refactor: consolidate message display options into a shared MessageOptions interface. 2025-12-02 13:10:25 +01:00
nils ebe8b163b9 refactor: Consolidate mutation options, simplify tag attachment and removal logic, and remove unused tag drop handler. 2025-12-02 13:01:14 +01:00
nils 5ffe9e4d27 refactor: improve document preview type checking by replacing ts-ignore with explicit type checks. 2025-12-01 23:51:37 +01:00
nils 601ced5981 feat: Add an icon size slider component and implement dynamic icon sizing for document views, while refactoring the documents panel layout. 2025-12-01 23:42:43 +01:00
nils 033026f57c feat: Introduce configurable icon and card sizes for document views and desktop workspace. 2025-12-01 11:45:58 +01:00
nils fea1bf68c5 refactor: extract common resize handle styles into a reusable component. 2025-12-01 00:07:15 +01:00
nils 406ce1eb70 feat: add import for usePanelManager hook 2025-11-30 23:59:27 +01:00
nils 6e9decfbec fix: Stop enqueuing document analysis job when only title changes 2025-11-30 23:55:41 +01:00
nils 9aa16b0729 feat: implement hybrid document search combining Quickwit results with PostgreSQL pg_trgm title search, supported by a new index. 2025-11-30 23:50:38 +01:00
nils f4b564b9e1 refactor: use ref to access latest focused document ID in applySelectedFolder callback to stabilize dependencies 2025-11-30 23:32:00 +01:00
nils 6519345414 feat: Rename ocr-text asset type to text-content across the application 2025-11-30 03:24:24 +01:00
nils 45bdc7ed8e configure Nginx to serve mjs files. 2025-11-30 01:29:53 +01:00
nils 9cf63ece72 refactor: enhance content loading and cancellation with AbortController and improved state reset logic. 2025-11-29 14:27:35 +01:00
nils 79aa359c1f refactor: lazy load document content only when its tab is active and separate content state reset logic 2025-11-28 21:55:47 +01:00
nils b9019d48fc refactor: Separate content loading logic into distinct effects for state reset and lazy loading, and update overlay text color variable. 2025-11-28 21:55:20 +01:00
nils 70f2a576e1 fix: improve BreadcrumbTrail truncation and layout within flexible panel headers by adjusting CSS and width calculation constants. 2025-11-28 21:48:45 +01:00
nils c53bea7093 feat: Implement keyboard navigation for desktop layout items with occlusion and Z-order awareness. 2025-11-28 21:06:48 +01:00
nils d7811b7c7a refactor: Adjust floating panel positioning and styling by removing absolute positioning, adding backdrop blur, and refining width and margin properties. 2025-11-28 20:53:44 +01:00
nils 41555bb57d feat: Add shift-click additive selection for documents in grid view 2025-11-28 20:50:24 +01:00
nils 0b45eeb2d4 feat: enhance keyboard navigation with grid support, refined selection, and arrow key navigation. 2025-11-28 20:32:16 +01:00
nils 852ab511ab style 2025-11-28 20:19:04 +01:00
nils e0d63d94b4 feat: Enable moving and dragging selected folders, including mixed document and folder selections, with updated drag preview visuals and minor UI styling. 2025-11-28 20:12:56 +01:00
nils 4fd1b712fa feat: Sort document tags alphabetically and prevent hover/focus on empty folder menu items. 2025-11-28 19:46:25 +01:00
nils 34604c5842 refactor: Extract folder assignment logic into a new SelectionFolderMenu component, adding new icons and updating related styles. 2025-11-28 19:28:12 +01:00
nils 970490d9c8 refactor: remove unused code and parameters from drag logic and document viewer 2025-11-28 09:11:11 +01:00
nils 65ad1f6cfa feat: Introduce MediaViewer component to centralize media rendering and refactor document preview and zoom overlay to use it, along with new CSS padding variables. 2025-11-28 09:08:28 +01:00
nils 0b4a9441d0 feat: Add UI and logic to handle password-protected PDF documents. 2025-11-28 08:37:04 +01:00
nils 268488d93d fix: Clamp leader rotation limits to prevent extreme angles and add a safety check for inverted limits. 2025-11-28 01:27:57 +01:00
nils 7c03eecd30 fix: ensure card detaches from leader and clears followers when starting a drag, and centralize stack property recalculations. 2025-11-28 01:19:28 +01:00
nils 635747a1ee feat: Sort selected workspace items by Z-index to ensure consistent order. 2025-11-28 01:13:53 +01:00
nils e512c8215e feat: Implement enhanced card physics with rotational dynamics, mass scaling, stacking behavior, and drag torque. 2025-11-28 01:10:57 +01:00
nils e164a88a97 feat: introduce CardPhysics class to encapsulate card drag and physics state from LayoutCard. 2025-11-27 20:37:20 +01:00
nils 9bf9550b03 feat: Refactor tag drag and drop interactions 2025-11-27 17:59:28 +01:00
nils 68ed888172 refactor: begin spatial workspace architecture refactor with design document and updated pointer event handling for document activation. 2025-11-27 01:57:38 +01:00
nils 82243b4170 feat: Introduce PreviewContext and document a new spatial workspace architecture. 2025-11-27 01:14:18 +01:00
nils 9ba581f64e feat: add keyboard navigation for document views, externalize document preview handling, and include physics model documentation. 2025-11-27 01:06:31 +01:00
nils 3588fde3a2 larger 2025-11-27 00:19:39 +01:00
nils 844e0ed355 feat: Implement multi-touch drag and long-press stack selection with pointer tracking and physics model documentation. 2025-11-26 22:42:28 +01:00
nils 07e28b3f8d feat: Add initial random rotation for cards, introduce a PointerTrackingContext for pointer management, and include a design document for spatial workspace architecture. 2025-11-26 22:42:16 +01:00
nils 0c6504ef1c feat: Introduce spatial workspace architecture design document, enhance layout store item synchronization, and prevent metadata fetch retries. 2025-11-26 22:03:09 +01:00
nils e36732cc2d feat: introduce a new layered spatial workspace architecture design, implement initial card positioning logic, and add container size observation for the layout system. 2025-11-26 21:54:11 +01:00
nils ee1c5dc606 feat: add spatial workspace refactor design document and implement dirty tracking for layout persistence. 2025-11-26 20:39:49 +01:00
nils 39e3ac2a87 feat: Implement layout persistence for card positions and rotation, loading from and saving to the database. 2025-11-26 20:24:00 +01:00
nils 6157a4f571 docs: Add design document for spatial workspace architecture refactor and fix card center calculation in layout system. 2025-11-26 18:09:36 +01:00
nils 9a3ed74230 refactor: centralize multi-card bring-to-front logic and document new spatial workspace architecture. 2025-11-26 17:52:14 +01:00
nils 835dcc4faa feat: Add physics model design document, implement multi-card snapping and layout system improvements, and refine pointer event handling. 2025-11-26 17:30:46 +01:00
nils 155d8c5c4a feat: Add spatial workspace architecture design document and refactor card drag logic to use new LayoutCard drag state management. 2025-11-26 17:00:56 +01:00
nils 81194032e0 refactor: Introduce a layered architecture for card interactions, separating drag logic, and selection handling. 2025-11-26 15:46:04 +01:00
nils d44c33dd69 feat: Introduce useCardPointer for card-specific pointer events, add spatial capabilities to LayoutSystem 2025-11-26 14:02:56 +01:00
nils bbf7d23c96 feat: Introduce new LayoutSystem and spatial workspace architecture design document, refactor document card and workspace to use it, and simplify pointer event handling. 2025-11-26 13:39:19 +01:00
nils 27eea08605 refactor: replace workspace engine and drag/pointer logic with a new layout system and physics model.refactor: replace the workspace engine and drag/pointer logic with a new layout system. 2025-11-26 12:28:02 +01:00
nils e5e71cc5f8 cleanup 2025-11-26 11:00:21 +01:00
nils 0a4a3ae35c refactor: Decompose document and folder views into modular components and hooks, replacing monolithic list/grid implementations. 2025-11-26 01:50:53 +01:00
nils 342714528a refactor: Introduce dedicated Document and Asset types and migrate codebase from DocumentLike. 2025-11-26 00:38:01 +01:00
nils 93dcde471f feat: Refactor document drag initiation and state management with new session handling and geometry utilities. (slightly broken) 2025-11-26 00:03:59 +01:00
nils 757abe9a0f video thumbnails 2025-11-25 22:34:05 +01:00
nils c4603a0b3a feat: Implement Z-index-aware click behavior for selected documents and add group gravitation to document drag. 2025-11-25 21:55:52 +01:00
nils 45ff3fb9ac feat: introduce physics-based dynamic rotation for dragged documents by adding angular velocity and mass properties, and refine group drag selection logic. 2025-11-25 21:26:10 +01:00
nils 5accfb4339 refactor: make draggedDocIds a required property in PointerDownOptions and simplify handlePointerDown logic accordingly 2025-11-25 21:04:54 +01:00
nils e0fce40bc3 refactor: Unify document selection and drag interactions by replacing stack-specific callbacks and simplifying drag state. 2025-11-25 20:54:53 +01:00
nils 13c87f4b07 refactor: Simplify folder ancestor expansion logic and refine onCreateFolder parentId type. 2025-11-25 15:21:45 +01:00
nils d6206786f7 feat: Rework sidebar with dedicated components for menu, folders, tags, correspondents, and search, including tenant switching and theme controls. 2025-11-25 15:09:20 +01:00
nils 2c42e63bab refactor: Remove neutral contrast theme adjustment and improve floating menu event handling by delaying listeners and checking for unmounted elements. 2025-11-25 14:12:53 +01:00
nils 30602e6b66 feat: Propagate tenantId to document workspace and panel props. 2025-11-25 13:11:01 +01:00
nils 226d99b6bf refactor: Consolidate tag drag/drop handlers into a single tagInteractions prop and streamline prop inheritance in DesktopWorkspace. 2025-11-25 12:50:03 +01:00
nils 5191d50d42 refactor: Consolidate document view props into a shared interface and refine tag drop payload handling. 2025-11-25 12:11:42 +01:00
nils 9c116cfe8c refactor: Move DocumentsListProps to DocumentsPanel and implement desk view selection and ID generation. 2025-11-25 11:55:55 +01:00
nils f4c0af4730 feat: add Papercrate logo source and branding assets documentation 2025-11-25 10:17:56 +01:00
nils fe80ccc046 refactor: unify document panel empty state rendering and view mode logic, adjust related styles 2025-11-25 10:13:46 +01:00
nils ccc22beda2 refactor: extract various constants 2025-11-25 10:10:42 +01:00
nils 4d30e47ee8 fix 2025-11-25 00:42:32 +01:00
nils 81dd7b80d4 fix 2025-11-25 00:21:27 +01:00
nils 049c3f4a9a remove old logo 2025-11-25 00:12:53 +01:00
nils cc168b3460 clean 2025-11-25 00:08:18 +01:00
nils 9ef63a87cb refactor: centralize documents route configuration into new useDocumentsShell hook and export related types. 2025-11-24 23:55:37 +01:00
nils 70e7bda87e refactor: introduce dedicated identifier types for improved clarity and type safety 2025-11-24 23:47:36 +01:00
nils 22f0c040a2 refactor: Standardize document and folder identification with a new entryKey module. 2025-11-24 23:13:11 +01:00
nils 096c377897 refactor: Consolidate workspace utilities into new workspaceUtils.ts with typed entry keys, replacing appLayoutUtils.ts, and update related components. 2025-11-24 22:38:01 +01:00
nils deec2fe69d refactor: enforce setAuthToken to strictly require a token, add /notes to gitignore, and include logo asset. 2025-11-24 21:25:45 +01:00
nils 8c16730d31 docs: Add code quality instructions to README, ignore notes directory, and include project logo. 2025-11-24 21:23:55 +01:00
nils f5ca74b63c refactor: Delete isPlainObject type guard and replace its usages with direct typeof checks. 2025-11-24 21:22:38 +01:00
nils 63be4663ab remove isStringValue 2025-11-24 21:03:06 +01:00
nils d470bc8bf1 Merge remote-tracking branch 'ui/ui' into dev 2025-11-24 20:53:41 +01:00
nils 8aab635b13 simplify 2025-11-24 20:49:22 +01:00
nils 46fa63af8a cleanup 2025-11-24 20:42:43 +01:00
nils 4c8ff39305 cleanup 2025-11-24 20:19:44 +01:00
nils 66848e8526 css 2025-11-23 13:43:01 +01:00
nils 71f9330c67 cleanup 2025-11-23 13:22:00 +01:00
nils 85afff2c19 cleanup 2025-11-23 00:11:18 +01:00
nils 014f489857 ai-shit 2025-11-22 18:19:55 +01:00
nils d3c76bc303 apiClient 2025-11-22 15:30:08 +01:00
nils 530218a4b8 mimetype 2025-11-22 14:43:05 +01:00
nils 5498cf4342 apiclient 2025-11-22 04:22:18 +01:00
nils 138e46a286 content_type -> mime_type 2025-11-22 04:00:21 +01:00
nils 41005390e8 fix 2025-11-22 03:14:12 +01:00
nils 79578e5daa fix 2025-11-22 02:57:44 +01:00
nils 132d9e3d02 fix 2025-11-22 02:41:14 +01:00
nils 7bee56b960 fix 2025-11-22 01:17:25 +01:00
nils ab3faad6af fix 2025-11-22 00:32:42 +01:00
nils c50372af06 download url 2025-11-22 00:28:11 +01:00
nils dd7dae5f9d folder in summary 2025-11-21 15:41:55 +01:00
nils 5871c7ae6e DownloadLink 2025-11-21 13:53:13 +01:00
nils bd55b784d7 Merge remote-tracking branch 'ui/ui' into dev 2025-11-20 16:57:49 +01:00
nils 3ce6b0ce93 reduce to 1 object per asset 2025-11-20 16:54:12 +01:00
nils a08e975da1 cleanup 2025-11-20 02:36:32 +01:00
nils 78e6d3e431 assets without objects 2025-11-20 02:32:11 +01:00
nils 0eb4c0a294 Remove asset/document hydration pipeline and introduce client-side cache updates for correspondents, tags, and search results 2025-11-20 02:18:33 +01:00
nils b76f1df27f documentsmanager 2025-11-19 23:36:04 +01:00
nils e1b47ed153 search cleanup 2025-11-19 01:25:56 +01:00
nils 6923a68837 selection cleanup 2025-11-19 00:57:06 +01:00
nils 1764f24243 cleanup 2025-11-19 00:44:47 +01:00
nils 3e21e72953 cleanup 2025-11-18 14:17:53 +01:00
nils ea6e42175a buttons 2025-11-18 13:47:43 +01:00
nils 0c37ef5578 cleanup 2025-11-18 13:16:35 +01:00
nils 0b0a1a88fd cleanup 2025-11-18 00:41:49 +01:00
nils bc9be96123 theme 2025-11-17 23:32:26 +01:00
nils 5fe11f18ac tag colors 2025-11-17 16:49:32 +01:00
nils 61573431e3 physics 2025-11-17 01:46:01 +01:00
nils 42733a9a92 velocity based queue 2025-11-17 01:01:59 +01:00
nils c56058b939 queue 2025-11-17 00:43:43 +01:00
nils 5ffbcc47e3 lazy pdf rendering 2025-11-17 00:22:20 +01:00
nils 16c28bcba1 clean 2025-11-16 21:28:47 +01:00
nils fa6b4b94f6 no prev/next anymore 2025-11-16 21:25:39 +01:00
nils 1f2c62241c cleanup 2025-11-16 21:08:07 +01:00
nils 4b9f74d5a8 more pdfjs 2025-11-16 20:13:47 +01:00
nils dae66703f2 pdfjs 2025-11-16 11:36:11 +01:00
nils 42f3917881 no preview assets anymore 2025-11-16 01:46:58 +01:00
nils 7e0768a09a summary 2025-11-16 00:39:37 +01:00
nils d0379c57ce fuck 2025-11-15 04:11:22 +01:00
nils bd3eab8b40 cleanup 2025-11-14 19:46:18 +01:00
nils a3c5494bf7 refactor 2025-11-14 02:35:17 +01:00
nils 6f4ff68062 style 2025-11-14 02:23:07 +01:00
nils 2966e25646 logo 2025-11-14 01:58:57 +01:00
nils f5b807edc5 fix 2025-11-14 01:54:38 +01:00
nils 2effdff990 logo theme 2025-11-14 01:48:41 +01:00
nils a6d2c115fe fix 2025-11-14 01:48:31 +01:00
nils 59a0514541 tsc 2025-11-13 15:15:19 +01:00
nils eb20d0bc5e fix 2025-11-13 15:03:35 +01:00
nils 62e44b5375 clean 2025-11-13 14:07:31 +01:00
nils 18558ab087 fix 2025-11-13 13:32:26 +01:00
nils dfbd47f219 fix 2025-11-13 13:22:10 +01:00
nils 98165f71b0 links 2025-11-13 12:40:38 +01:00
nils f7251b8ce3 fix and new logo 2025-11-13 12:12:25 +01:00
nils 6fe7bbbbb5 lint 2025-11-13 02:49:37 +01:00
nils 1e740ea024 fix 2025-11-13 02:43:42 +01:00
nils 6d55e61cee typescript 2025-11-13 02:37:16 +01:00
nils ada089c05b typescript 2025-11-13 01:07:55 +01:00
nils 39787f9552 issued at cases license 2025-11-12 18:29:10 +01:00
nils b812d748ea cleanup 2025-11-12 17:02:27 +01:00
nils 190bd7d85c Merge remote-tracking branch 'ui/ui' into dev 2025-11-12 15:06:16 +01:00
nils d2e27c12a2 panel 2025-11-12 15:06:04 +01:00
nils e66b530f24 fix 2025-11-12 12:02:21 +01:00
nils 85ed89cf19 Merge remote-tracking branch 'ui/ui' into dev 2025-11-12 11:32:01 +01:00
nils 9cea0161d7 fix icon on firefox 2025-11-12 11:31:54 +01:00
nils 3042dacc00 left aligned grid 2025-11-12 11:26:06 +01:00
nils 3424691e4c theme 2025-11-12 02:50:20 +01:00
nils 363ed2e836 Merge remote-tracking branch 'ui/ui' into dev 2025-11-12 02:42:42 +01:00
nils 900ec18a7f fix 2025-11-12 02:42:37 +01:00
nils 13e103f382 Merge remote-tracking branch 'ui/ui' into dev 2025-11-12 02:34:17 +01:00
nils 32ef3ced59 panels 2025-11-12 02:24:46 +01:00
nils 44c982f015 document viewer 2025-11-12 02:24:46 +01:00
nils 762e4ee315 fix 2025-11-12 02:24:46 +01:00
nils d42192b2f1 fix 2025-11-12 02:24:46 +01:00
nils 06683e2a07 cleanup 2025-11-12 02:24:46 +01:00
nils 5653828ff3 api change 2025-11-12 02:24:31 +01:00
nils 84734cca2f tenants 2025-11-12 02:16:20 +01:00
nils b987bdacfe theme 2025-11-11 22:38:40 +01:00
nils 1111784caa selection fix 2025-11-11 21:50:08 +01:00
nils 8e7a2f3d6c desaturate theme a bit 2025-11-11 21:41:49 +01:00
nils cf070d35f0 Merge remote-tracking branch 'ui/ui' into dev 2025-11-11 18:03:50 +01:00
nils e019cc2cee update dockerfile and k8s 2025-11-11 18:03:43 +01:00
nils 2a87dad0ab fix 2025-11-11 16:55:08 +01:00
nils d46951d12e fix 2025-11-11 16:22:50 +01:00
nils 8feec04601 helm migration 2025-11-11 16:06:44 +01:00
nils 1193c71579 tag picker 2025-11-11 15:59:17 +01:00
nils 31db4ede38 admin migrate-database 2025-11-11 15:54:57 +01:00
nils 6f34a0a4fa fmt 2025-11-11 15:50:51 +01:00
nils cd9a8a0204 fix 2025-11-11 15:31:42 +01:00
nils edcf996d12 Merge remote-tracking branch 'ui/ui' into dev 2025-11-11 15:29:07 +01:00
nils 5333de0e89 cleanup 2025-11-11 15:23:07 +01:00
nils 1ee3d1cc5e fix 2025-11-11 15:18:06 +01:00
nils a8589a864a unify detailpanel and documentviewer 2025-11-11 14:45:19 +01:00
nils 7f371b2ab6 fix 2025-11-11 13:27:07 +01:00
nils 8751637b92 tenant deletion/reset 2025-11-11 12:17:24 +01:00
nils 10f9f3be2f guts 2025-11-11 12:01:22 +01:00
nils 2dd786ce14 hydration 2025-11-11 10:50:57 +01:00
nils 6ae497323e viewer 2025-11-11 10:09:15 +01:00
nils 4f29ff73c6 tenant gate active 2025-11-11 02:45:05 +01:00
nils ac9e688e7a /api/download 2025-11-11 02:19:39 +01:00
nils 3fe325c4ce fix 2025-11-11 01:57:00 +01:00
nils 425e03650f cleanup 2025-11-11 01:51:42 +01:00
nils 4ce4bd1a4b better date parsing 2025-11-11 01:36:17 +01:00
nils 26798ac430 fix 2025-11-11 00:48:13 +01:00
nils 70b9443e66 outline 2025-11-11 00:48:07 +01:00
nils 8788cd3e25 taskflow 2025-11-10 23:06:53 +01:00
nils 8dddb0b940 fix api spec 2025-11-10 22:45:39 +01:00
nils 992d7038e5 restore drag preview 2025-11-10 22:39:29 +01:00
nils 0a1416ef92 pixelpeeping 2025-11-10 22:08:46 +01:00
nils 8820ff1c15 fixes 2025-11-10 21:27:04 +01:00
nils ab81e76206 tweak 2025-11-10 15:01:20 +01:00
nils ef9bec3334 update deps 2025-11-10 14:46:34 +01:00
nils 8094ac3190 Merge remote-tracking branch 'ui/ui' into dev 2025-11-10 13:46:30 +01:00
nils 7376a5dd4d remove desktop help modal 2025-11-10 13:46:21 +01:00
nils d43885aa48 fix 2025-11-10 13:35:36 +01:00
nils 6eb50c0555 modal 2025-11-10 13:34:12 +01:00
nils 9252883a2b fix 2025-11-10 12:58:56 +01:00
nils fe2cb99651 fix 2025-11-10 12:54:12 +01:00
nils bf1e5cd107 style 2025-11-10 12:50:28 +01:00
nils 9757fd0c10 slightly warmer theme 2025-11-10 12:14:52 +01:00
nils 288c53364e fix 2025-11-10 12:14:40 +01:00
nils 218f2f2475 upload button tweaks 2025-11-10 11:34:45 +01:00
nils 585caaee58 refactor styles 2025-11-10 11:30:16 +01:00
nils 578dfd8998 update rust deps 2025-11-10 10:51:57 +01:00
nils b4a1821a55 upload queue 2025-11-10 02:05:17 +01:00
nils ac24297a7b upload button 2025-11-10 00:32:41 +01:00
nils 20cf597c5c refactor 2025-11-09 20:21:46 +01:00
nils 737c44da12 caching 2025-11-09 19:50:55 +01:00
nils bfab2f2cdc refactor 2025-11-09 19:50:16 +01:00
nils fed3a1a32f fix schema 2025-11-09 19:49:34 +01:00
nils cbdb180423 fix 2025-11-09 19:26:24 +01:00
nils 6d0d453aa1 Merge remote-tracking branch 'ui/ui' into dev 2025-11-09 19:10:02 +01:00
nils 3c1c910dc9 cleanup 2025-11-09 19:08:24 +01:00
nils 45ad2d4730 build on github 2025-11-09 19:03:03 +01:00
nils 12733e1879 crosscompile 2025-11-09 18:35:31 +01:00
nils da0f2ae8ab tests 2025-11-09 18:20:29 +01:00
nils 14b4dd434c multi-arch build 2025-11-09 18:11:16 +01:00
nils bc33f68209 cleanup 2025-11-09 13:03:44 +01:00
nils 81571e4c64 proxy downloads 2025-11-09 12:01:19 +01:00
nils d24d2c9249 rust-s3 2025-11-08 02:03:52 +01:00
nils 4bc7357e41 ux 2025-11-07 23:48:25 +01:00
nils 8dd6be2a5d cleanup 2025-11-07 22:44:55 +01:00
nils 08cf8bd50f tweak 2025-11-07 22:26:27 +01:00
nils 0bd54ef941 simplify previewzoomoverlay clicks 2025-11-07 22:22:41 +01:00
nils 7617d99ab2 trash 2025-11-07 12:46:46 +01:00
nils 06ac9fc87e fix 2025-11-07 12:44:44 +01:00
nils ae1884045d tag drop works 2025-11-07 12:00:28 +01:00
nils 9bf1fc1983 fix
ci / docker (frontend, frontend/Dockerfile, frontend) (push) Failing after 49s
ci / docker (backend, backend/Dockerfile, backend) (push) Failing after 17m1s
2025-11-07 11:29:48 +01:00
nils 30b90a5bf5 detailspanel, selection handling, single document details panel 2025-11-07 10:46:04 +01:00
nils 5b88ecf2dd debounce 2025-11-06 23:11:22 +01:00
nils 7f53bc900a refactor 2025-11-06 22:52:25 +01:00
nils ef2ed2dc58 refactor 2025-11-06 22:21:27 +01:00
nils 07169e853b fix 2025-11-06 21:40:36 +01:00
nils 5562c271e1 fix 2025-11-06 21:29:31 +01:00
nils 66173f87be fix 2025-11-06 20:56:21 +01:00
nils 3f49e26d19 work 2025-11-06 14:43:43 +01:00
nils a6f79dbc75 refactor 2025-11-06 12:26:29 +01:00
nils 28b9112781 settings 2025-11-06 11:41:28 +01:00
nils ebed18afef fix 2025-11-06 09:55:32 +01:00
nils cedbe99513 fix 2025-11-06 01:54:47 +01:00
nils 82ae18b4b9 sorting 2025-11-06 01:46:33 +01:00
nils a16f1501d3 folders-move 2025-11-06 00:58:17 +01:00
nils 4027ac66cb folder tree 2025-11-06 00:51:38 +01:00
nils 911051e75d order 2025-11-05 23:01:42 +01:00
nils c193b30c8e capsets 2025-11-05 22:15:27 +01:00
nils e9c5f27b17 capsapi 2025-11-05 15:21:02 +01:00
nils a75281aa13 readonly role 2025-11-05 14:10:57 +01:00
nils 7b6afa1128 fix 2025-11-05 12:47:31 +01:00
nils 45759e6ca4 zindex 2025-11-05 12:38:56 +01:00
nils 75a03de4e3 docs 2025-11-05 12:34:56 +01:00
nils 480bc20ae7 caps and delete 2025-11-05 12:32:10 +01:00
nils 934fb6b689 desktop redo 2025-11-05 12:29:30 +01:00
nils 928753add8 foo 2025-11-05 02:31:21 +01:00
nils ad54cecbac fix 2025-11-04 14:18:49 +01:00
nils 82b33a4d50 style 2025-11-04 14:18:41 +01:00
nils dd378b3ad8 desktop 2025-11-04 11:37:01 +01:00
nils f523e5651b fix 2025-11-04 00:48:37 +01:00
nils 01fd774b18 ui 2025-11-04 00:36:44 +01:00
nils 9ad704f50a floating selection box 2025-11-03 23:10:03 +01:00
nils 8d4adbea42 style 2025-11-03 10:45:16 +01:00
nils bfd49cd7b7 fix 2025-11-03 02:47:06 +01:00
nils 209ac191c9 cleanup 2025-11-03 02:34:12 +01:00
nils 152f824e2e selection 2025-11-03 02:31:46 +01:00
nils 1c261bf0a2 fix 2025-11-03 01:47:15 +01:00
nils 1cbbbeb6b0 fix 2025-11-03 00:32:59 +01:00
nils a819790899 fix 2025-11-03 00:17:28 +01:00
nils 2ee69406b6 stuff 2025-11-03 00:17:11 +01:00
nils c85cff720b on delete 2025-11-02 23:17:59 +01:00
nils 5c0f350296 idbdatabase 2025-11-02 22:33:27 +01:00
nils 626b6c16e0 fix 2025-11-02 22:25:00 +01:00
nils 74aacbc1eb fix 2025-11-02 22:08:15 +01:00
nils 3c24b890a4 fix 2025-11-02 21:38:11 +01:00
nils 4ec19dbd70 fix
ci / docker (frontend, frontend/Dockerfile, frontend) (push) Failing after 15m41s
ci / docker (backend, backend/Dockerfile, backend) (push) Failing after 15m46s
2025-11-02 15:56:12 +01:00
nils f8ab674b84 spacebar 2025-11-02 15:44:09 +01:00
nils 866a31b89d persistence 2025-11-02 15:34:26 +01:00
nils 4f296ac1e3 fix 2025-11-02 15:20:41 +01:00
nils d6a6d1233c various 2025-11-02 15:03:23 +01:00
nils 8f86a71c39 fix 2025-11-02 14:27:13 +01:00
nils 1cddc3c373 fix 2025-11-02 14:20:11 +01:00
nils bd2669af4d viewer 2025-11-02 14:12:40 +01:00
nils 65495a07b2 fix 2025-11-02 14:08:08 +01:00
nils a30b6eaa02 backend 409 on document conflict 2025-11-02 13:22:16 +01:00
nils 9ddaa59155 desktop selection 2025-11-02 13:12:36 +01:00
nils 5bf64fc5f3 icons 2025-11-02 12:22:02 +01:00
nils 824db2087c dbltap 2025-11-02 12:17:32 +01:00
nils 1135873968 ui 2025-11-02 12:12:11 +01:00
nils e7e7881772 playful 2025-11-02 04:40:07 +01:00
nils f7b274c1ec cors 2025-11-02 02:57:02 +01:00
nils b561f46d2c content disposition 2025-11-02 02:26:40 +01:00
nils b9c95437d2 details 2025-11-02 02:05:05 +01:00
nils 7d8595b63f rename 2025-11-02 01:18:24 +01:00
nils 32d627fd6d fix 2025-11-02 00:42:47 +01:00
nils 09430c6f40 refactor 2025-11-02 00:35:32 +01:00
nils 49998fa23d DocumentsPanel 2025-11-02 00:23:25 +01:00
nils 14077d26d7 style 2025-11-01 23:50:30 +01:00
nils 40832ff1c3 styling 2025-11-01 23:49:04 +01:00
nils 0b8f856876 folder-selection 2025-11-01 23:37:12 +01:00
nils 16ac16cd30 ui 2025-11-01 22:49:50 +01:00
nils 326a6042ec api-tokens 2025-11-01 22:46:04 +01:00
nils 8efe2d19ba user_sessions 2025-11-01 22:45:46 +01:00
nils 1c5b920e13 gitea-workflow 2025-11-01 21:43:32 +01:00
nils 00f5d3adea api-tokens 2025-11-01 21:42:52 +01:00
nils f6ceff5444 selection 2025-11-01 20:28:00 +01:00
nils 9559a1b5e2 fix 2025-11-01 19:59:39 +01:00
nils e752361f39 sidebar 2025-11-01 19:50:29 +01:00
nils 41c9ae30e9 fix 2025-11-01 19:45:16 +01:00
nils 03bc311403 detailpanel 2025-11-01 19:39:51 +01:00
nils 366f716b1c more screenshots 2025-11-01 15:13:47 +01:00
nils 3731fe8e40 clean 2025-11-01 15:01:35 +01:00
nils 3c416600a6 screenshot 2025-11-01 14:57:37 +01:00
nils 6f6ee59461 fix 2025-11-01 13:59:46 +01:00
nils 9aed7ec524 fix 2025-11-01 13:51:43 +01:00
nils 816c880e8e cleanup 2025-11-01 13:40:10 +01:00
nils 816910ca40 fix 2025-11-01 04:29:08 +01:00
nils 6eb3f8a3d9 detailpanel 2025-11-01 04:22:51 +01:00
nils 303ece0529 detailpanel 2025-11-01 04:16:31 +01:00
nils fd13edae6d build
ci / docker (frontend, frontend/Dockerfile, frontend) (push) Successful in 16m11s
ci / docker (backend, backend/Dockerfile, backend) (push) Successful in 16m16s
2025-11-01 02:52:04 +01:00
nils 09492f452f Revert "build"
This reverts commit b6bc5391cf.
2025-11-01 02:07:58 +01:00
nils b6bc5391cf build 2025-11-01 02:00:16 +01:00
nils ac91efc421 foo 2025-11-01 01:46:14 +01:00
nils 2fba3236ad Add GHCR build/publish workflow 2025-11-01 00:34:51 +01:00
nils 18352caabe webdav token regeneration 2025-10-31 20:37:07 +01:00
nils e9731ec691 webdav fix 2025-10-31 20:10:42 +01:00
nils 175387f0d3 rls 2025-10-31 19:13:11 +01:00
nils 2d8a4432cc style 2025-10-31 18:19:52 +01:00
nils c146084f75 fix 2025-10-31 17:44:33 +01:00
nils 1fcd265eb9 breadcrumbs 2025-10-31 17:43:00 +01:00
nils 1a1e9a80c3 breadcrumbs 2025-10-31 17:24:39 +01:00
nils d14d263e8f health 2025-10-31 15:55:55 +01:00
nils 48bed9a9fe magic token login 2025-10-31 15:16:30 +01:00
nils 91dd3289a9 deskview 2025-10-31 14:27:30 +01:00
nils b969cae524 screenshot 2025-10-31 13:52:48 +01:00
nils aaf9fd1bce fix 2025-10-31 13:44:26 +01:00
nils b254c651a7 fixes 2025-10-31 13:39:06 +01:00
nils 3af656b09f modalheader 2025-10-31 13:19:39 +01:00
nils 321b0d84ae panelheader 2025-10-31 13:12:09 +01:00
nils 6b4a4af5f1 fix 2025-10-31 12:56:17 +01:00
nils faf8fec9c7 revert document types 2025-10-31 12:56:09 +01:00
nils 0a87f33d89 style 2025-10-31 02:34:11 +01:00
nils eacab2ced6 cleanup 2025-10-31 02:19:38 +01:00
nils f796932cd8 cleanup 2025-10-31 02:06:38 +01:00
nils 17db827e3a cleanup 2025-10-31 01:52:51 +01:00
nils 722c2f9a5c tests 2025-10-31 01:26:24 +01:00
nils fa43bc749e cleanup 2025-10-31 01:19:01 +01:00
nils 5b5916ff92 openapi cleanup 2025-10-31 00:39:22 +01:00
nils 5ca7dc9678 cleanup 2025-10-31 00:38:52 +01:00
nils 39d1d80383 cleanup 2025-10-31 00:28:48 +01:00
nils 813ce24aeb document types 2025-10-31 00:13:16 +01:00
nils 3941ec61d3 rename 2025-10-30 23:12:30 +01:00
nils 4a3cb63263 created_at swagger 2025-10-30 23:03:57 +01:00
nils 5386724e0d docs 2025-10-30 22:18:30 +01:00
nils 85f3d90329 frontend cleanup 2025-10-30 18:17:01 +01:00
nils bb34a47fa8 squash database migrations 2025-10-30 17:53:00 +01:00
nils 7fae0e44ac fix 2025-10-30 16:56:23 +01:00
nils 80d21ed0a1 deployment 2025-10-30 16:21:52 +01:00
nils 67fd787a14 cleanup 2025-10-30 14:41:15 +01:00
nils 86be6256a4 fix 2025-10-30 02:45:54 +01:00
427 changed files with 54806 additions and 27417 deletions
-53
View File
@@ -1,53 +0,0 @@
name: ci
on:
push:
branches:
- main
- staging
tags:
- '*'
jobs:
docker:
runs-on: ubuntu-latest
strategy:
matrix:
include:
- service: frontend
context: frontend
dockerfile: frontend/Dockerfile
- service: backend
context: backend
dockerfile: backend/Dockerfile
steps:
- name: Checkout with submodules
uses: actions/checkout@v4
with:
submodules: recursive
- name: Login to Docker Registry
uses: docker/login-action@v2
with:
registry: ${{ vars.REGISTRY_URL }}
username: ${{ vars.REGISTRY_USER }}
password: ${{ secrets.REGISTRY_PASSWORD }}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
driver: remote
endpoint: ${{ env.BUILDKIT_ARM64_ENDPOINT }}
- name: Build and Push ${{ matrix.service }} Image
uses: docker/build-push-action@v6
with:
context: ${{ matrix.context }}
file: ${{ matrix.dockerfile }}
platforms: linux/arm64
push: true
provenance: false
tags: |
${{ vars.REGISTRY_URL }}/${{ gitea.repository }}-${{ matrix.service }}:${{ gitea.ref_type == 'tag' && gitea.ref_name || (gitea.ref_name == 'main' && 'latest' || gitea.ref_name) }}
${{ vars.REGISTRY_URL }}/${{ gitea.repository }}-${{ matrix.service }}:${{ gitea.sha }}
+146
View File
@@ -0,0 +1,146 @@
name: ci
on:
push:
branches:
- main
- staging
- dev
tags:
- '*'
jobs:
docker:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
strategy:
matrix:
include:
- service: frontend
context: frontend
dockerfile: frontend/Dockerfile
- service: backend
context: backend
dockerfile: backend/Dockerfile
steps:
- name: Checkout with submodules
uses: actions/checkout@v4
with:
submodules: recursive
- name: Derive repository metadata
id: repo_meta
run: |
repo="${GITHUB_REPOSITORY}"
owner="${repo%%/*}"
name="${repo##*/}"
echo "repo_owner=$owner" >> "$GITHUB_OUTPUT"
echo "repo_name=$name" >> "$GITHUB_OUTPUT"
- name: Compute base tag
id: compute_tag
env:
GITHUB_SHA: ${{ github.sha }}
GITHUB_REF_TYPE: ${{ github.ref_type }}
GITHUB_REF_NAME: ${{ github.ref_name }}
run: |
sha="${GITHUB_SHA}"
ref_type="${GITHUB_REF_TYPE}"
ref_name="${GITHUB_REF_NAME}"
short="${sha:0:7}"
tag="$short"
if [ "$ref_type" = "tag" ]; then
tag="$ref_name"
elif [ "$ref_name" = "dev" ]; then
tag="${tag}-dev"
elif [ "$ref_name" = "staging" ]; then
tag="${tag}-staging"
fi
echo "base_tag=$tag" >> "$GITHUB_OUTPUT"
- name: Login to local registry
if: ${{ vars.REGISTRY_URL != '' }}
uses: docker/login-action@v2
with:
registry: ${{ vars.REGISTRY_URL }}
username: ${{ vars.REGISTRY_USER }}
password: ${{ secrets.REGISTRY_PASSWORD }}
- name: Login to GHCR
uses: docker/login-action@v2
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ github.token }}
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Determine branch alias tag
id: branch_alias
env:
REF_NAME: ${{ github.ref_name }}
run: |
alias=""
case "${REF_NAME}" in
dev) alias="latest-dev" ;;
staging) alias="latest-staging" ;;
main) alias="latest" ;;
esac
echo "alias=$alias" >> "$GITHUB_OUTPUT"
- name: Assemble image tags
id: tag_list
env:
REGISTRY_URL: ${{ vars.REGISTRY_URL }}
REPO_NAME: ${{ steps.repo_meta.outputs.repo_name }}
SERVICE: ${{ matrix.service }}
BASE_TAG: ${{ steps.compute_tag.outputs.base_tag }}
GIT_SHA: ${{ github.sha }}
BRANCH_ALIAS: ${{ steps.branch_alias.outputs.alias }}
shell: bash
run: |
tags=""
if [ -n "${REGISTRY_URL}" ]; then
repo_tag="${REGISTRY_URL}/${REPO_NAME}-${SERVICE}"
tags="${tags}${repo_tag}:${BASE_TAG}\n${repo_tag}:${GIT_SHA}"
fi
ghcr_tag="ghcr.io/papercrate-dms/${REPO_NAME}-${SERVICE}"
if [ -n "${tags}" ]; then
tags="${tags}\n"
fi
tags="${tags}${ghcr_tag}:${BASE_TAG}\n${ghcr_tag}:${GIT_SHA}"
if [ -n "${BRANCH_ALIAS}" ]; then
if [ -n "${REGISTRY_URL}" ]; then
tags="${tags}\n${repo_tag}:${BRANCH_ALIAS}"
fi
tags="${tags}\n${ghcr_tag}:${BRANCH_ALIAS}"
fi
export TAGS="${tags}"
python -c 'import os; tags=[t.strip() for t in os.environ["TAGS"].split("\\n") if t.strip()]; print("tags=" + ",".join(tags))' | tee -a "$GITHUB_OUTPUT"
- name: Build and Push ${{ matrix.service }} Image
uses: docker/build-push-action@v6
with:
context: ${{ matrix.context }}
file: ${{ matrix.dockerfile }}
platforms: linux/amd64,linux/arm64
push: true
provenance: false
tags: ${{ steps.tag_list.outputs.tags }}
cache-from: type=gha
cache-to: type=gha,mode=max
+107
View File
@@ -0,0 +1,107 @@
# Development
This document collects runtime assumptions and workflows for local development,
integration testing, and infrastructure automation.
## Local Development
Use the provided `papercrate.tmux` to spin up the full stack in one tmux session:
```bash
tmux -f papercrate.tmux attach
```
This creates windows for the compose stack, frontend dev server, backend API, and
background worker using the repository-relative paths defined in the tmux file.
Detach with `Ctrl+b d` and reattach later with the same command.
The development Postgres container now seeds two database roles:
- `papercrate_app_login` (password `papercrate_app`) is used by the backend and
is subject to row-level security policies.
- `papercrate` remains the owner role for running Diesel migrations or other
maintenance tasks.
When connecting manually to inspect RLS behaviour, switch to the application
role with `SET ROLE papercrate_app_login;` before querying tenant tables.
## Backend Integration Tests
Integration tests require a running Postgres instance (and, optionally, Quickwit
for OCR indexing). The repository includes a lightweight compose file for local
runs:
```bash
docker compose -f docker-compose.test.yml up -d
export TEST_DATABASE_URL=postgres://papercrate:papercrate_test@localhost:5433/papercrate_test
# optional, enables Quickwit indexing jobs
export QUICKWIT_ENDPOINT=http://localhost:7280
export QUICKWIT_INDEX=documents
cargo test
```
Stop the database when you are done:
```bash
docker compose -f docker-compose.test.yml down
```
The compose service uses tmpfs storage, giving each test run a clean database.
## Runtime Dependencies
- `ocrmypdf` (optional but recommended): Used by the OCR worker to extract text
from PDFs when no embedded text layer is available. Ensure it is installed and
available on the worker hosts if OCR is desired.
- Quickwit (optional): The Quickwit indexer is used to ingest extracted text for
search. Set `QUICKWIT_ENDPOINT` and `QUICKWIT_INDEX` in the environment when
running workers if you want indexing jobs to run. The local compose file starts
a Quickwit instance on `http://localhost:7280` and seeds the `documents` index
automatically.
## Configuration
The backend reads its settings from environment variables. In particular:
- `DATABASE_URL` connection string for the primary Postgres database (required).
- `DATABASE_MAX_POOL_SIZE` optional override for the r2d2 connection pool size.
Defaults to `2`; increase it in staging/production to match expected concurrency.
- `PROXY_DOWNLOADS` set to `true` when the object store is only reachable from
the backend network. When enabled, `/api/download/{token}` and asset-object fetches
stream bytes through the API instead of redirecting clients to S3/Hetzner.
On startup each binary logs the effective configuration with secrets redacted
(for example, the database password is masked). This makes it easier to confirm
runtime settings in staging without exposing credentials.
## Running Migrations in Kubernetes
The backend container image ships the `diesel` CLI, so schema migrations can be
executed as a short-lived Job (or Helm hook) before rolling out new pods. Example
manifest:
```yaml
apiVersion: batch/v1
kind: Job
metadata:
name: papercrate-migrate
spec:
template:
spec:
restartPolicy: OnFailure
containers:
- name: migrate
image: ghcr.io/example/papercrate-backend:<TAG>
command: ["/usr/local/bin/diesel", "migration", "run"]
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: papercrate-db
key: DATABASE_URL
```
Run the Job manually (`kubectl apply -f migrate-job.yaml`) or configure it as a
Helm pre-install/pre-upgrade hook so migrations run automatically on each
deployment. Once the Job succeeds, deploy/update the backend `Deployment` as
usual.
+36 -61
View File
@@ -1,73 +1,48 @@
# Papercrate # Papercrate
## Local Development ![Papercrate document workspace](docs/screenshot.png)
Use the provided `papercrate.tmux` to spin up the full stack in one tmux session: ## Single-Host Deployment (Docker Compose)
For self-hosting (for example on a Raspberry Pi), use the production-oriented
`docker-compose.yml`. Define the required secrets in a `.env` file alongside the
compose file before starting the stack:
```bash ```bash
tmux -f papercrate.tmux attach cat <<'EOF' > .env
POSTGRES_PASSWORD=change-me
MINIO_ROOT_PASSWORD=change-me-too
JWT_SECRET=generate-a-long-random-string
WEBAUTHN_RP_ID=papercrate.local
WEBAUTHN_ORIGIN=http://papercrate.local:8080
# Optional overrides
# CORS_ALLOWED_ORIGIN=http://papercrate.local:8080
# REFRESH_COOKIE_SECURE=true
EOF
docker compose build
docker compose up -d
``` ```
This creates windows for the compose stack, frontend dev server, backend API, and background worker using the repository-relative paths defined in the tmux file. Detach with `Ctrl+b d` and reattach later with the same command. **Important:** the WebAuthn settings must match the public URL clients will use.
The relying party (RP) identifier is the bare host name, while the origin must
include scheme and port. Adjust the values above if you serve Papercrate from a
different host, domain, or HTTPS endpoint—otherwise passkey registration and
login will fail.
## Backend Integration Tests The compose file builds the backend and frontend images locally, then launches
Postgres, MinIO, Quickwit, the API, background worker, WebDAV endpoint, and the
SPA frontend. Once the containers report healthy, visit `http://<host>:8080`
and use the passkey signup flow to provision the first tenant/user. Upgrades are
as simple as `git pull` followed by `docker compose up -d`.
Integration tests require a running Postgres instance (and, optionally, Quickwit for OCR indexing). The repository includes a lightweight compose file for local runs: ## Screenshots
```bash ![Document detail view](docs/detailview.png)
docker compose -f docker-compose.test.yml up -d ![Desk overview](docs/deskview.png)
export TEST_DATABASE_URL=postgres://papercrate:papercrate_test@localhost:5433/papercrate_test ![Document view](docs/documentview.png)
# optional, enables Quickwit indexing jobs
export QUICKWIT_ENDPOINT=http://localhost:7280
export QUICKWIT_INDEX=documents
cargo test
```
Stop the database when you are done: ---
```bash For development workflows (local stack, integration tests, migrations, and
docker compose -f docker-compose.test.yml down configuration details) see [DEVELOPMENT.md](./DEVELOPMENT.md).
```
The compose service uses tmpfs storage, giving each test run a clean database.
## Runtime Dependencies
- `ocrmypdf` (optional but recommended): Used by the OCR worker to extract text from PDFs when no embedded text layer is available. Ensure it is installed and available on the worker hosts if OCR is desired.
- Quickwit (optional): The Quickwit indexer is used to ingest extracted text for search. Set `QUICKWIT_ENDPOINT` and `QUICKWIT_INDEX` in the environment when running workers if you want indexing jobs to run. The local compose file starts a Quickwit instance on `http://localhost:7280` and seeds the `documents` index automatically.
## Configuration
The backend reads its settings from environment variables (see `backend/.env` for local defaults). In particular:
- `DATABASE_URL` connection string for the primary Postgres database (required).
- `DATABASE_MAX_POOL_SIZE` optional override for the r2d2 connection pool size. Defaults to `2`; increase it in staging/production to match expected concurrency.
On startup each binary logs the effective configuration with secrets redacted (for example, the database password is masked). This makes it easier to confirm the runtime settings in staging without exposing credentials.
## Running Migrations in Kubernetes
The backend container image ships the `diesel` CLI, so schema migrations can be executed as a short-lived Job (or Helm hook) before rolling out new pods. Example manifest:
```yaml
apiVersion: batch/v1
kind: Job
metadata:
name: papercrate-migrate
spec:
template:
spec:
restartPolicy: OnFailure
containers:
- name: migrate
image: ghcr.io/example/papercrate-backend:<TAG>
command: ["/usr/local/bin/diesel", "migration", "run"]
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: papercrate-db
key: DATABASE_URL
```
Run the Job manually (`kubectl apply -f migrate-job.yaml`) or configure it as a Helm pre-install/pre-upgrade hook so migrations run automatically on each deployment. Once the Job succeeds, deploy/update the backend `Deployment` as usual.
+1165 -1158
View File
File diff suppressed because it is too large Load Diff
+48 -19
View File
@@ -1,26 +1,24 @@
[package] [package]
name = "backend" name = "papercrate"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
[dependencies] [dependencies]
# Web framework # Web framework
axum = { version = "0.7", features = ["multipart"] } axum = { version = "0.8", features = ["multipart"] }
tokio = { version = "1", features = ["full"] } tokio = { version = "1.48", features = ["full"] }
tower = { version = "0.4", features = ["make", "util"] } tower = { version = "0.5", features = ["make", "util"] }
tower-http = { version = "0.6", features = ["cors", "trace"] } tower-http = { version = "0.6", features = ["cors", "trace"] }
axum-extra = { version = "0.9", features = ["typed-header"] } axum-extra = { version = "0.12", features = ["typed-header"] }
# Database # Database
diesel = { version = "2.1", features = ["postgres", "uuid", "chrono", "serde_json", "r2d2"] } diesel = { version = "2.3.3", features = ["postgres", "uuid", "chrono", "serde_json", "r2d2"] }
diesel_migrations = "2.1" diesel_migrations = "2.1"
uuid = { version = "1.6", features = ["v4", "serde"] } uuid = { version = "1.6", features = ["v4", "serde"] }
chrono = { version = "0.4", features = ["serde"] } chrono = { version = "0.4", features = ["serde"] }
# S3 # S3
aws-config = "1.1" rust-s3 = { version = "0.37", features = ["with-tokio", "tokio-rustls-tls"] }
aws-sdk-s3 = "1.14"
aws-credential-types = "1.2"
# Serialization # Serialization
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
@@ -34,37 +32,68 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] }
dotenv = "0.15" dotenv = "0.15"
sha2 = "0.10" sha2 = "0.10"
hex = "0.4" hex = "0.4"
hmac = "0.12"
bytes = "1.5" bytes = "1.5"
async-trait = "0.1" async-trait = "0.1"
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] }
pdfium-render = "0.8" pdfium-render = "0.8.36"
mime_guess = "2.0" mime_guess = "2.0"
tempfile = "3.10" tempfile = "3.10"
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] } reqwest = { version = "0.12.24", default-features = false, features = ["json", "rustls-tls", "stream"] }
percent-encoding = "2.3" percent-encoding = "2.3"
base64 = "0.21" base64 = "0.22"
quick-xml = "0.32" quick-xml = "0.38"
futures-util = "0.3" futures-util = "0.3"
url = "2.5" url = "2.5"
once_cell = "1.19" once_cell = "1.19"
regex = "1.11"
infer = "0.19"
utoipa = { version = "4.2", default-features = false, features = ["chrono", "uuid", "preserve_order"] } utoipa = { version = "4.2", default-features = false, features = ["chrono", "uuid", "preserve_order"] }
clap = { version = "4.5", features = ["derive"] }
# Error handling # Error handling
thiserror = "1.0" thiserror = "2.0"
anyhow = "1.0" anyhow = "1.0"
# Authentication & security # Authentication & security
argon2 = "0.5" argon2 = "0.5"
jsonwebtoken = "9" jsonwebtoken = { version = "10", features = ["rust_crypto"] }
webauthn-rs = { version = "0.5", features = ["danger-allow-state-serialisation", "danger-credential-internals"] } webauthn-rs = { version = "0.5", features = ["danger-allow-state-serialisation", "danger-credential-internals"] }
serde_bytes = "0.11" serde_bytes = "0.11"
serde_cbor_2 = "0.13" serde_cbor_2 = "0.13"
# Misc # Misc
rand = "0.8" rand = "0.9"
hyper = "1.2"
http-body-util = "0.1"
chrono-tz = "0.8"
[dev-dependencies] [dev-dependencies]
once_cell = "1.19" once_cell = "1.19"
hyper = "1.2"
http-body-util = "0.1"
webauthn-rs-core = "0.5" webauthn-rs-core = "0.5"
serde_yaml = "0.9"
[build-dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_yaml = "0.9"
serde_json = "1.0"
regex = "1.11"
[[bin]]
name = "backend"
path = "src/main.rs"
[[bin]]
name = "worker"
path = "src/bin/worker.rs"
[[bin]]
name = "webdav"
path = "src/bin/webdav.rs"
[[bin]]
name = "admin"
path = "src/bin/admin.rs"
[[bin]]
name = "openapi-dump"
path = "src/bin/openapi_dump.rs"
+102 -24
View File
@@ -1,29 +1,114 @@
# syntax=docker/dockerfile:1 # syntax=docker/dockerfile:1.7
FROM rust:1-slim AS builder ARG RUST_VERSION=1
FROM --platform=$BUILDPLATFORM rust:${RUST_VERSION}-slim AS builder
ARG TARGETARCH
ENV TARGETARCH=${TARGETARCH}
WORKDIR /app WORKDIR /app
RUN apt-get update \ RUN cat <<'SCRIPT' >/usr/local/bin/resolve-target.sh
&& apt-get install -y --no-install-recommends \ #!/bin/sh
set -e
case "$1" in
amd64)
echo x86_64-unknown-linux-gnu
;;
arm64)
echo aarch64-unknown-linux-gnu
;;
*)
echo "Unsupported TARGETARCH: $1" >&2
exit 1
;;
esac
SCRIPT
RUN chmod +x /usr/local/bin/resolve-target.sh
ENV PKG_CONFIG_ALLOW_CROSS=1 \
CC_aarch64_unknown_linux_gnu=aarch64-linux-gnu-gcc \
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc \
PKG_CONFIG_LIBDIR_aarch64_unknown_linux_gnu=/usr/lib/aarch64-linux-gnu/pkgconfig \
PKG_CONFIG_PATH_aarch64_unknown_linux_gnu=/usr/lib/aarch64-linux-gnu/pkgconfig \
PKG_CONFIG_SYSROOT_DIR_aarch64_unknown_linux_gnu=/usr/aarch64-linux-gnu \
OPENSSL_DIR_aarch64_unknown_linux_gnu=/usr/lib/aarch64-linux-gnu \
OPENSSL_LIB_DIR_aarch64_unknown_linux_gnu=/usr/lib/aarch64-linux-gnu \
OPENSSL_INCLUDE_DIR_aarch64_unknown_linux_gnu=/usr/include/aarch64-linux-gnu \
CC_x86_64_unknown_linux_gnu=x86_64-linux-gnu-gcc \
CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER=x86_64-linux-gnu-gcc \
PKG_CONFIG_LIBDIR_x86_64_unknown_linux_gnu=/usr/lib/x86_64-linux-gnu/pkgconfig \
PKG_CONFIG_PATH_x86_64_unknown_linux_gnu=/usr/lib/x86_64-linux-gnu/pkgconfig \
OPENSSL_DIR_x86_64_unknown_linux_gnu=/usr/lib/x86_64-linux-gnu \
OPENSSL_LIB_DIR_x86_64_unknown_linux_gnu=/usr/lib/x86_64-linux-gnu \
OPENSSL_INCLUDE_DIR_x86_64_unknown_linux_gnu=/usr/include/x86_64-linux-gnu
RUN set -eux; \
case "${TARGETARCH}" in \
amd64) TARGET_DEB_ARCH=amd64 ;; \
arm64) TARGET_DEB_ARCH=arm64 ;; \
*) echo "Unsupported TARGETARCH: ${TARGETARCH}" >&2; exit 1 ;; \
esac; \
BUILD_DEB_ARCH="$(dpkg --print-architecture)"; \
if [ "${TARGET_DEB_ARCH}" != "${BUILD_DEB_ARCH}" ]; then \
dpkg --add-architecture "${TARGET_DEB_ARCH}"; \
fi; \
apt-get update; \
apt-get install -y --no-install-recommends \
build-essential \ build-essential \
pkg-config \ pkg-config \
curl \
libssl-dev \ libssl-dev \
libpq-dev \ libpq-dev \
libjpeg-dev \ libjpeg-dev \
libpng-dev \ libpng-dev \
curl \ zlib1g-dev; \
&& rm -rf /var/lib/apt/lists/* if [ "${TARGET_DEB_ARCH}" != "${BUILD_DEB_ARCH}" ]; then \
case "${TARGETARCH}" in \
arm64) CROSS_GCC=gcc-aarch64-linux-gnu ;; \
amd64) CROSS_GCC=gcc-x86-64-linux-gnu ;; \
esac; \
apt-get install -y --no-install-recommends \
"${CROSS_GCC}" \
"libc6-dev:${TARGET_DEB_ARCH}" \
"libssl-dev:${TARGET_DEB_ARCH}" \
"libpq-dev:${TARGET_DEB_ARCH}" \
"libjpeg-dev:${TARGET_DEB_ARCH}" \
"libpng-dev:${TARGET_DEB_ARCH}" \
"zlib1g-dev:${TARGET_DEB_ARCH}"; \
fi; \
rm -rf /var/lib/apt/lists/*
COPY Cargo.toml Cargo.lock ./ COPY Cargo.toml Cargo.lock build.rs ./
COPY src ./src COPY src ./src
COPY migrations ./migrations COPY migrations ./migrations
COPY tests ./tests COPY tests ./tests
COPY resources ./resources
COPY diesel.toml ./ COPY diesel.toml ./
RUN cargo build --release --bin backend --bin worker --bin webdav --bin admin RUN set -eux; \
RUN cargo install diesel_cli --no-default-features --features postgres TARGET="$(/usr/local/bin/resolve-target.sh "${TARGETARCH}")"; \
rustup target add "${TARGET}"; \
cargo build --release --target "${TARGET}" --bin backend --bin worker --bin webdav --bin admin; \
mkdir -p /artifacts; \
for bin in backend worker webdav admin; do \
cp "target/${TARGET}/release/${bin}" "/artifacts/${bin}"; \
done
FROM debian:trixie-slim AS runtime RUN set -eux; \
case "${TARGETARCH}" in \
amd64) pdfium_package=pdfium-linux-x64.tgz ;; \
arm64) pdfium_package=pdfium-linux-arm64.tgz ;; \
*) echo "Unsupported TARGETARCH: ${TARGETARCH}" >&2; exit 1 ;; \
esac; \
curl -fsSL "https://github.com/bblanchon/pdfium-binaries/releases/latest/download/${pdfium_package}" -o /tmp/pdfium.tgz; \
mkdir -p /tmp/pdfium; \
tar -xzf /tmp/pdfium.tgz -C /tmp/pdfium --strip-components=1; \
pdfium_so="$(find /tmp/pdfium -name libpdfium.so -type f | head -n1)"; \
[ -n "${pdfium_so}" ]; \
cp "${pdfium_so}" /artifacts/libpdfium.so; \
rm -rf /tmp/pdfium.tgz /tmp/pdfium
FROM --platform=$TARGETPLATFORM debian:trixie-slim AS runtime
ARG TARGETARCH
WORKDIR /app WORKDIR /app
RUN apt-get update \ RUN apt-get update \
@@ -38,25 +123,18 @@ RUN apt-get update \
tesseract-ocr \ tesseract-ocr \
ghostscript \ ghostscript \
qpdf \ qpdf \
ffmpeg \
&& rm -rf /var/lib/apt/lists/* \ && rm -rf /var/lib/apt/lists/* \
&& mkdir -p /usr/local/lib \ && mkdir -p /usr/local/lib \
&& curl -fsSL https://github.com/bblanchon/pdfium-binaries/releases/latest/download/pdfium-linux-arm64.tgz -o /tmp/pdfium.tgz \
&& mkdir -p /tmp/pdfium \
&& tar -xzf /tmp/pdfium.tgz -C /tmp/pdfium --strip-components=1 \
&& pdfium_so="$(find /tmp/pdfium -name libpdfium.so -type f | head -n1)" \
&& [ -n "${pdfium_so}" ] \
&& mv "${pdfium_so}" /usr/local/lib/libpdfium.so \
&& ldconfig \
&& rm -rf /tmp/pdfium.tgz /tmp/pdfium \
&& useradd --system --create-home --uid 10001 appuser && useradd --system --create-home --uid 10001 appuser
COPY --from=builder /app/target/release/backend /usr/local/bin/papercrate-backend COPY --from=builder /artifacts/backend /usr/local/bin/papercrate-backend
COPY --from=builder /app/target/release/worker /usr/local/bin/papercrate-worker COPY --from=builder /artifacts/worker /usr/local/bin/papercrate-worker
COPY --from=builder /app/target/release/webdav /usr/local/bin/papercrate-webdav COPY --from=builder /artifacts/webdav /usr/local/bin/papercrate-webdav
COPY --from=builder /app/target/release/admin /usr/local/bin/papercrate-admin COPY --from=builder /artifacts/admin /usr/local/bin/papercrate-admin
COPY --from=builder /usr/local/cargo/bin/diesel /usr/local/bin/diesel COPY --from=builder /artifacts/libpdfium.so /usr/local/lib/libpdfium.so
RUN ldconfig
COPY migrations ./migrations COPY migrations ./migrations
COPY diesel.toml ./
ENV RUST_LOG=info ENV RUST_LOG=info
USER appuser USER appuser
+123
View File
@@ -0,0 +1,123 @@
use std::env;
use std::fs;
use std::path::PathBuf;
use regex::escape;
use serde::Deserialize;
#[derive(Deserialize)]
struct CaseSuite {
cases: Vec<CaseName>,
}
#[derive(Deserialize)]
struct CaseName {
name: String,
}
#[derive(Deserialize)]
struct MonthSuite {
months: Vec<MonthDefinition>,
}
#[derive(Deserialize)]
struct MonthDefinition {
name: String,
month: u32,
#[serde(default)]
locales: Vec<String>,
}
fn sanitize(name: &str) -> String {
let mut out = String::with_capacity(name.len());
for ch in name.chars() {
if ch.is_ascii_alphanumeric() {
out.push(ch);
} else {
out.push('_');
}
}
if out.is_empty() {
"case".to_string()
} else if out.chars().next().unwrap().is_ascii_digit() {
format!("_{}", out)
} else {
out
}
}
fn quote(value: &str) -> String {
serde_json::to_string(value).expect("string literal")
}
fn generate_tests() -> Result<String, Box<dyn std::error::Error>> {
let yaml_path = PathBuf::from("tests/data/issued_at_cases.yaml");
let contents = fs::read_to_string(&yaml_path)?;
let suite: CaseSuite = serde_yaml::from_str(&contents)?;
let mut output =
String::from("#[cfg(test)]\npub mod issued_at_generated_tests {\n use super::*;\n");
for case in suite.cases {
let ident = sanitize(&case.name);
output.push_str(&format!(
" #[test]\n fn {}() {{\n run_named_case(\"{}\");\n }}\n",
ident, case.name
));
}
output.push_str("}\n");
Ok(output)
}
fn generate_months() -> Result<String, Box<dyn std::error::Error>> {
let yaml_path = PathBuf::from("resources/issued_at_months.yaml");
let contents = fs::read_to_string(&yaml_path)?;
let suite: MonthSuite = serde_yaml::from_str(&contents)?;
let mut pattern_parts = Vec::with_capacity(suite.months.len());
let mut entries = String::new();
for entry in &suite.months {
pattern_parts.push(escape(&entry.name));
let locales_literal = if entry.locales.is_empty() {
"&[]".to_string()
} else {
let joined = entry
.locales
.iter()
.map(|loc| quote(loc))
.collect::<Vec<_>>()
.join(", ");
format!("&[{}]", joined)
};
entries.push_str(&format!(
" MonthVariant {{ name: {}, month: {}, locales: {} }},\n",
quote(&entry.name),
entry.month,
locales_literal
));
}
let pattern_literal = quote(&pattern_parts.join("|"));
let output = format!(
"pub(super) static MONTH_VARIANTS: &[MonthVariant] = &[\n{entries}];\n\n",
entries = entries
) + &format!(
"pub(super) const MONTH_PATTERN: &str = {};\n",
pattern_literal
);
Ok(output)
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("cargo:rerun-if-changed=tests/data/issued_at_cases.yaml");
println!("cargo:rerun-if-changed=resources/issued_at_months.yaml");
let out_dir = PathBuf::from(env::var("OUT_DIR")?);
fs::write(
out_dir.join("issued_at_generated_tests.rs"),
generate_tests()?,
)?;
fs::write(out_dir.join("issued_at_months.rs"), generate_months()?)?;
Ok(())
}
@@ -1,8 +1,10 @@
DROP TRIGGER IF EXISTS trg_jobs_updated_at ON jobs; DROP TRIGGER IF EXISTS trg_jobs_updated_at ON jobs;
DROP FUNCTION IF EXISTS touch_jobs_updated_at(); DROP FUNCTION IF EXISTS touch_jobs_updated_at();
DROP TABLE IF EXISTS webauthn_challenges;
DROP TABLE IF EXISTS user_passkeys;
DROP TABLE IF EXISTS webdav_tokens;
ALTER TABLE documents DROP CONSTRAINT IF EXISTS documents_current_version_fk; ALTER TABLE documents DROP CONSTRAINT IF EXISTS documents_current_version_fk;
DROP TABLE IF EXISTS document_asset_objects; DROP TABLE IF EXISTS document_asset_objects;
DROP TABLE IF EXISTS document_assets; DROP TABLE IF EXISTS document_assets;
DROP TABLE IF EXISTS document_versions; DROP TABLE IF EXISTS document_versions;
@@ -18,4 +20,6 @@ DROP TABLE IF EXISTS user_memberships;
DROP TABLE IF EXISTS users; DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS tenants; DROP TABLE IF EXISTS tenants;
DROP TYPE IF EXISTS tenant_status;
DROP EXTENSION IF EXISTS "pgcrypto"; DROP EXTENSION IF EXISTS "pgcrypto";
@@ -1,14 +1,17 @@
CREATE EXTENSION IF NOT EXISTS "pgcrypto"; CREATE EXTENSION IF NOT EXISTS "pgcrypto";
CREATE TYPE tenant_status AS ENUM ('creating', 'active', 'suspended', 'deleting', 'error');
CREATE TABLE tenants ( CREATE TABLE tenants (
id UUID PRIMARY KEY, id UUID PRIMARY KEY,
slug TEXT NOT NULL UNIQUE, name TEXT NOT NULL,
storage_root TEXT, storage_root TEXT,
quickwit_index TEXT, quickwit_index TEXT,
status TEXT NOT NULL DEFAULT 'active',
config JSONB NOT NULL DEFAULT '{}'::jsonb, config JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
status tenant_status NOT NULL,
created_by UUID
); );
CREATE UNIQUE INDEX tenants_storage_root_unique CREATE UNIQUE INDEX tenants_storage_root_unique
@@ -22,7 +25,6 @@ CREATE UNIQUE INDEX tenants_quickwit_index_unique
CREATE TABLE users ( CREATE TABLE users (
id UUID PRIMARY KEY, id UUID PRIMARY KEY,
username VARCHAR(100) NOT NULL UNIQUE, username VARCHAR(100) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
); );
@@ -31,14 +33,13 @@ CREATE TABLE user_memberships (
id UUID PRIMARY KEY, id UUID PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE, tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
role TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (user_id, tenant_id) UNIQUE (user_id, tenant_id)
); );
CREATE INDEX user_memberships_tenant_id_idx ON user_memberships (tenant_id); CREATE INDEX user_memberships_tenant_id_idx ON user_memberships(tenant_id);
CREATE INDEX user_memberships_user_id_idx ON user_memberships (user_id); CREATE INDEX user_memberships_user_id_idx ON user_memberships(user_id);
CREATE TABLE folders ( CREATE TABLE folders (
id UUID PRIMARY KEY, id UUID PRIMARY KEY,
@@ -51,8 +52,12 @@ CREATE TABLE folders (
CREATE INDEX idx_folders_parent ON folders(parent_id); CREATE INDEX idx_folders_parent ON folders(parent_id);
CREATE INDEX folders_tenant_id_idx ON folders(tenant_id); CREATE INDEX folders_tenant_id_idx ON folders(tenant_id);
CREATE UNIQUE INDEX folders_parent_name_unique_idx CREATE UNIQUE INDEX folders_tenant_parent_name_unique_idx
ON folders (COALESCE(parent_id, '00000000-0000-0000-0000-000000000000'::uuid), name); ON folders (
tenant_id,
COALESCE(parent_id, '00000000-0000-0000-0000-000000000000'::uuid),
name
);
CREATE TABLE documents ( CREATE TABLE documents (
id UUID PRIMARY KEY, id UUID PRIMARY KEY,
@@ -70,11 +75,10 @@ CREATE TABLE documents (
tenant_id UUID NOT NULL REFERENCES tenants(id) tenant_id UUID NOT NULL REFERENCES tenants(id)
); );
CREATE INDEX idx_documents_folder ON documents (folder_id); CREATE INDEX idx_documents_folder ON documents(folder_id);
CREATE INDEX idx_documents_deleted_at ON documents (deleted_at); CREATE INDEX idx_documents_deleted_at ON documents(deleted_at);
CREATE INDEX documents_tenant_id_idx ON documents (tenant_id); CREATE INDEX documents_tenant_id_idx ON documents(tenant_id);
CREATE INDEX idx_documents_current_version_id ON documents (current_version_id); CREATE INDEX idx_documents_current_version_id ON documents(current_version_id);
CREATE INDEX idx_documents_folder_title CREATE INDEX idx_documents_folder_title
ON documents ( ON documents (
COALESCE(folder_id, '00000000-0000-0000-0000-000000000000'::uuid), COALESCE(folder_id, '00000000-0000-0000-0000-000000000000'::uuid),
@@ -82,8 +86,9 @@ CREATE INDEX idx_documents_folder_title
) )
WHERE deleted_at IS NULL; WHERE deleted_at IS NULL;
CREATE UNIQUE INDEX documents_unique_folder_filename CREATE UNIQUE INDEX documents_tenant_folder_filename_unique
ON documents ( ON documents (
tenant_id,
COALESCE(folder_id, '00000000-0000-0000-0000-000000000000'::uuid), COALESCE(folder_id, '00000000-0000-0000-0000-000000000000'::uuid),
filename filename
) )
@@ -97,14 +102,13 @@ CREATE TABLE document_versions (
size_bytes BIGINT NOT NULL, size_bytes BIGINT NOT NULL,
checksum VARCHAR(64) NOT NULL, checksum VARCHAR(64) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
operations_summary JSONB NOT NULL DEFAULT '{}'::jsonb,
metadata JSONB NOT NULL DEFAULT '{}'::jsonb, metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
tenant_id UUID NOT NULL REFERENCES tenants(id), tenant_id UUID NOT NULL REFERENCES tenants(id),
CONSTRAINT document_versions_unique_version UNIQUE (document_id, version_number) CONSTRAINT document_versions_unique_version UNIQUE (document_id, version_number)
); );
CREATE INDEX idx_document_versions_document ON document_versions (document_id); CREATE INDEX idx_document_versions_document ON document_versions(document_id);
CREATE INDEX document_versions_tenant_id_idx ON document_versions (tenant_id); CREATE INDEX document_versions_tenant_id_idx ON document_versions(tenant_id);
ALTER TABLE documents ALTER TABLE documents
ADD CONSTRAINT documents_current_version_fk ADD CONSTRAINT documents_current_version_fk
@@ -114,13 +118,14 @@ ALTER TABLE documents
CREATE TABLE tags ( CREATE TABLE tags (
id UUID PRIMARY KEY, id UUID PRIMARY KEY,
label VARCHAR(100) NOT NULL UNIQUE, label VARCHAR(100) NOT NULL,
color VARCHAR(7), color VARCHAR(7),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
tenant_id UUID NOT NULL REFERENCES tenants(id) tenant_id UUID NOT NULL REFERENCES tenants(id)
); );
CREATE INDEX tags_tenant_id_idx ON tags (tenant_id); CREATE UNIQUE INDEX tags_tenant_label_unique ON tags(tenant_id, label);
CREATE INDEX tags_tenant_id_idx ON tags(tenant_id);
CREATE TABLE document_tags ( CREATE TABLE document_tags (
document_id UUID NOT NULL REFERENCES documents(id) ON DELETE CASCADE, document_id UUID NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
@@ -131,8 +136,8 @@ CREATE TABLE document_tags (
PRIMARY KEY (document_id, tag_id) PRIMARY KEY (document_id, tag_id)
); );
CREATE INDEX idx_document_tags_tag ON document_tags (tag_id); CREATE INDEX idx_document_tags_tag ON document_tags(tag_id);
CREATE INDEX document_tags_tenant_id_idx ON document_tags (tenant_id); CREATE INDEX document_tags_tenant_id_idx ON document_tags(tenant_id);
CREATE TABLE correspondents ( CREATE TABLE correspondents (
id UUID PRIMARY KEY, id UUID PRIMARY KEY,
@@ -140,27 +145,25 @@ CREATE TABLE correspondents (
metadata JSONB NOT NULL DEFAULT '{}'::jsonb, metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
tenant_id UUID NOT NULL REFERENCES tenants(id), tenant_id UUID NOT NULL REFERENCES tenants(id)
CONSTRAINT correspondents_name_unique UNIQUE (name)
); );
CREATE INDEX correspondents_tenant_id_idx ON correspondents (tenant_id); CREATE UNIQUE INDEX correspondents_tenant_name_unique
ON correspondents (tenant_id, name);
CREATE INDEX correspondents_tenant_id_idx ON correspondents(tenant_id);
CREATE TABLE document_correspondents ( CREATE TABLE document_correspondents (
document_id UUID NOT NULL REFERENCES documents(id) ON DELETE CASCADE, document_id UUID NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
correspondent_id UUID NOT NULL REFERENCES correspondents(id) ON DELETE CASCADE, correspondent_id UUID NOT NULL REFERENCES correspondents(id) ON DELETE CASCADE,
role VARCHAR(32) NOT NULL,
assigned_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), assigned_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
assigned_by UUID REFERENCES users(id), assigned_by UUID REFERENCES users(id),
tenant_id UUID NOT NULL REFERENCES tenants(id), tenant_id UUID NOT NULL REFERENCES tenants(id),
PRIMARY KEY (document_id, correspondent_id, role), PRIMARY KEY (document_id, correspondent_id)
CONSTRAINT document_correspondents_role_check CHECK (role IN ('sender', 'receiver', 'other'))
); );
CREATE INDEX idx_document_correspondents_document ON document_correspondents (document_id); CREATE INDEX idx_document_correspondents_document ON document_correspondents(document_id);
CREATE INDEX idx_document_correspondents_correspondent ON document_correspondents (correspondent_id); CREATE INDEX idx_document_correspondents_correspondent ON document_correspondents(correspondent_id);
CREATE INDEX idx_document_correspondents_role ON document_correspondents (role); CREATE INDEX document_correspondents_tenant_id_idx ON document_correspondents(tenant_id);
CREATE INDEX document_correspondents_tenant_id_idx ON document_correspondents (tenant_id);
CREATE TABLE document_assets ( CREATE TABLE document_assets (
id UUID PRIMARY KEY, id UUID PRIMARY KEY,
@@ -175,9 +178,9 @@ CREATE TABLE document_assets (
CONSTRAINT document_assets_cardinality_positive CHECK (cardinality IS NULL OR cardinality >= 1) CONSTRAINT document_assets_cardinality_positive CHECK (cardinality IS NULL OR cardinality >= 1)
); );
CREATE INDEX idx_document_assets_version ON document_assets (document_version_id); CREATE INDEX idx_document_assets_version ON document_assets(document_version_id);
CREATE INDEX idx_document_assets_type ON document_assets (asset_type); CREATE INDEX idx_document_assets_type ON document_assets(asset_type);
CREATE INDEX document_assets_tenant_id_idx ON document_assets (tenant_id); CREATE INDEX document_assets_tenant_id_idx ON document_assets(tenant_id);
CREATE TABLE document_asset_objects ( CREATE TABLE document_asset_objects (
id UUID PRIMARY KEY, id UUID PRIMARY KEY,
@@ -191,10 +194,8 @@ CREATE TABLE document_asset_objects (
); );
CREATE INDEX idx_document_asset_objects_asset_ordinal CREATE INDEX idx_document_asset_objects_asset_ordinal
ON document_asset_objects (asset_id, ordinal); ON document_asset_objects(asset_id, ordinal);
CREATE INDEX document_asset_objects_tenant_id_idx ON document_asset_objects(tenant_id);
CREATE INDEX document_asset_objects_tenant_id_idx
ON document_asset_objects (tenant_id);
CREATE TABLE jobs ( CREATE TABLE jobs (
id UUID PRIMARY KEY, id UUID PRIMARY KEY,
@@ -210,9 +211,9 @@ CREATE TABLE jobs (
CONSTRAINT jobs_status_check CHECK (status IN ('queued', 'processing', 'succeeded', 'failed')) CONSTRAINT jobs_status_check CHECK (status IN ('queued', 'processing', 'succeeded', 'failed'))
); );
CREATE INDEX idx_jobs_status_run_after ON jobs (status, run_after); CREATE INDEX idx_jobs_status_run_after ON jobs(status, run_after);
CREATE INDEX idx_jobs_job_type ON jobs (job_type); CREATE INDEX idx_jobs_job_type ON jobs(job_type);
CREATE INDEX jobs_tenant_id_idx ON jobs (tenant_id); CREATE INDEX jobs_tenant_id_idx ON jobs(tenant_id);
CREATE OR REPLACE FUNCTION touch_jobs_updated_at() CREATE OR REPLACE FUNCTION touch_jobs_updated_at()
RETURNS TRIGGER AS $$ RETURNS TRIGGER AS $$
@@ -239,6 +240,56 @@ CREATE TABLE refresh_tokens (
tenant_id UUID NOT NULL REFERENCES tenants(id) tenant_id UUID NOT NULL REFERENCES tenants(id)
); );
CREATE INDEX idx_refresh_tokens_user_id ON refresh_tokens (user_id); CREATE INDEX idx_refresh_tokens_user_id ON refresh_tokens(user_id);
CREATE INDEX idx_refresh_tokens_token_hash ON refresh_tokens (token_hash); CREATE INDEX idx_refresh_tokens_token_hash ON refresh_tokens(token_hash);
CREATE INDEX refresh_tokens_tenant_id_idx ON refresh_tokens (tenant_id); CREATE INDEX refresh_tokens_tenant_id_idx ON refresh_tokens(tenant_id);
CREATE TABLE webdav_tokens (
id UUID PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
token_prefix TEXT NOT NULL,
token_hash TEXT NOT NULL,
label TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
last_used_at TIMESTAMPTZ,
expires_at TIMESTAMPTZ,
revoked_at TIMESTAMPTZ
);
CREATE UNIQUE INDEX webdav_tokens_token_prefix_key ON webdav_tokens(token_prefix);
CREATE INDEX webdav_tokens_user_tenant_idx ON webdav_tokens(user_id, tenant_id);
CREATE TABLE user_passkeys (
id UUID PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
credential_id BYTEA NOT NULL UNIQUE,
public_key BYTEA NOT NULL,
credential JSONB NOT NULL,
sign_count BIGINT NOT NULL,
transports TEXT[] NOT NULL DEFAULT '{}'::text[],
aaguid UUID,
nickname TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
last_used_at TIMESTAMPTZ,
revoked_at TIMESTAMPTZ,
revoked_by UUID,
revoked_reason TEXT
);
CREATE INDEX user_passkeys_user_id_idx ON user_passkeys(user_id);
CREATE TABLE webauthn_challenges (
id UUID PRIMARY KEY,
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
purpose TEXT NOT NULL,
challenge BYTEA NOT NULL,
state BYTEA NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
expires_at TIMESTAMPTZ NOT NULL,
CONSTRAINT webauthn_challenges_purpose_check CHECK (purpose IN ('registration', 'authentication'))
);
CREATE INDEX webauthn_challenges_user_id_idx ON webauthn_challenges(user_id);
CREATE INDEX webauthn_challenges_expires_at_idx ON webauthn_challenges(expires_at);
@@ -0,0 +1,2 @@
ALTER TABLE documents
RENAME COLUMN created_at TO uploaded_at;
@@ -0,0 +1,2 @@
ALTER TABLE documents
RENAME COLUMN uploaded_at TO created_at;
@@ -0,0 +1,2 @@
DROP TABLE magic_tokens;
DROP TYPE magic_token_kind;
@@ -0,0 +1,18 @@
CREATE TYPE magic_token_kind AS ENUM ('email_login', 'demo_login');
CREATE TABLE magic_tokens (
id UUID PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
kind magic_token_kind NOT NULL,
token_hash VARCHAR NOT NULL UNIQUE,
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
expires_at TIMESTAMPTZ NOT NULL,
max_uses INTEGER,
used_count INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
created_by UUID REFERENCES users(id) ON DELETE SET NULL,
last_used_at TIMESTAMPTZ
);
CREATE INDEX magic_tokens_token_hash_idx ON magic_tokens (token_hash);
CREATE INDEX magic_tokens_expires_at_idx ON magic_tokens (expires_at);
@@ -0,0 +1,28 @@
-- Move tables and types back to the public schema
ALTER TABLE tenant.webdav_tokens SET SCHEMA public;
ALTER TABLE tenant.user_memberships SET SCHEMA public;
ALTER TABLE tenant.refresh_tokens SET SCHEMA public;
ALTER TABLE tenant.tags SET SCHEMA public;
ALTER TABLE tenant.document_correspondents SET SCHEMA public;
ALTER TABLE tenant.document_tags SET SCHEMA public;
ALTER TABLE tenant.document_asset_objects SET SCHEMA public;
ALTER TABLE tenant.document_assets SET SCHEMA public;
ALTER TABLE tenant.document_versions SET SCHEMA public;
ALTER TABLE tenant.documents SET SCHEMA public;
ALTER TABLE tenant.folders SET SCHEMA public;
ALTER TABLE tenant.correspondents SET SCHEMA public;
ALTER FUNCTION shared.touch_jobs_updated_at() SET SCHEMA public;
ALTER TABLE shared.magic_tokens SET SCHEMA public;
ALTER TABLE shared.jobs SET SCHEMA public;
ALTER TABLE shared.webauthn_challenges SET SCHEMA public;
ALTER TABLE shared.user_passkeys SET SCHEMA public;
ALTER TABLE shared.users SET SCHEMA public;
ALTER TABLE shared.tenants SET SCHEMA public;
ALTER TYPE shared.magic_token_kind SET SCHEMA public;
ALTER TYPE shared.tenant_status SET SCHEMA public;
DROP SCHEMA IF EXISTS tenant CASCADE;
DROP SCHEMA IF EXISTS shared CASCADE;
@@ -0,0 +1,45 @@
CREATE SCHEMA IF NOT EXISTS shared;
CREATE SCHEMA IF NOT EXISTS tenant;
-- Move global types and tables into the shared schema
ALTER TYPE tenant_status SET SCHEMA shared;
ALTER TYPE magic_token_kind SET SCHEMA shared;
ALTER TABLE tenants SET SCHEMA shared;
ALTER TABLE users SET SCHEMA shared;
ALTER TABLE user_passkeys SET SCHEMA shared;
ALTER TABLE webauthn_challenges SET SCHEMA shared;
ALTER TABLE jobs SET SCHEMA shared;
ALTER TABLE magic_tokens SET SCHEMA shared;
ALTER FUNCTION touch_jobs_updated_at() SET SCHEMA shared;
-- Move tenant-scoped tables into the tenant schema
ALTER TABLE correspondents SET SCHEMA tenant;
ALTER TABLE folders SET SCHEMA tenant;
ALTER TABLE documents SET SCHEMA tenant;
ALTER TABLE document_versions SET SCHEMA tenant;
ALTER TABLE document_assets SET SCHEMA tenant;
ALTER TABLE document_asset_objects SET SCHEMA tenant;
ALTER TABLE document_tags SET SCHEMA tenant;
ALTER TABLE document_correspondents SET SCHEMA tenant;
ALTER TABLE tags SET SCHEMA tenant;
ALTER TABLE refresh_tokens SET SCHEMA tenant;
ALTER TABLE user_memberships SET SCHEMA tenant;
ALTER TABLE webdav_tokens SET SCHEMA tenant;
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'papercrate_app') THEN
RETURN;
END IF;
GRANT USAGE ON SCHEMA shared TO papercrate_app;
GRANT USAGE ON SCHEMA tenant TO papercrate_app;
GRANT SELECT ON ALL TABLES IN SCHEMA shared TO papercrate_app;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA tenant TO papercrate_app;
ALTER DEFAULT PRIVILEGES IN SCHEMA shared GRANT SELECT ON TABLES TO papercrate_app;
ALTER DEFAULT PRIVILEGES IN SCHEMA tenant GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO papercrate_app;
END
$$;
@@ -0,0 +1,51 @@
DROP POLICY IF EXISTS tenant_membership_select_policy ON tenant.user_memberships;
ALTER TABLE tenant.user_memberships NO FORCE ROW LEVEL SECURITY;
ALTER TABLE tenant.user_memberships DISABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS tenant_isolation_policy ON tenant.webdav_tokens;
ALTER TABLE tenant.webdav_tokens NO FORCE ROW LEVEL SECURITY;
ALTER TABLE tenant.webdav_tokens DISABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS tenant_isolation_policy ON tenant.tags;
ALTER TABLE tenant.tags NO FORCE ROW LEVEL SECURITY;
ALTER TABLE tenant.tags DISABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS tenant_refresh_token_policy ON tenant.refresh_tokens;
ALTER TABLE tenant.refresh_tokens NO FORCE ROW LEVEL SECURITY;
ALTER TABLE tenant.refresh_tokens DISABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS tenant_isolation_policy ON tenant.folders;
ALTER TABLE tenant.folders NO FORCE ROW LEVEL SECURITY;
ALTER TABLE tenant.folders DISABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS tenant_isolation_policy ON tenant.documents;
ALTER TABLE tenant.documents NO FORCE ROW LEVEL SECURITY;
ALTER TABLE tenant.documents DISABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS tenant_isolation_policy ON tenant.document_versions;
ALTER TABLE tenant.document_versions NO FORCE ROW LEVEL SECURITY;
ALTER TABLE tenant.document_versions DISABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS tenant_isolation_policy ON tenant.document_tags;
ALTER TABLE tenant.document_tags NO FORCE ROW LEVEL SECURITY;
ALTER TABLE tenant.document_tags DISABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS tenant_isolation_policy ON tenant.document_correspondents;
ALTER TABLE tenant.document_correspondents NO FORCE ROW LEVEL SECURITY;
ALTER TABLE tenant.document_correspondents DISABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS tenant_isolation_policy ON tenant.document_assets;
ALTER TABLE tenant.document_assets NO FORCE ROW LEVEL SECURITY;
ALTER TABLE tenant.document_assets DISABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS tenant_isolation_policy ON tenant.document_asset_objects;
ALTER TABLE tenant.document_asset_objects NO FORCE ROW LEVEL SECURITY;
ALTER TABLE tenant.document_asset_objects DISABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS tenant_isolation_policy ON tenant.correspondents;
ALTER TABLE tenant.correspondents NO FORCE ROW LEVEL SECURITY;
ALTER TABLE tenant.correspondents DISABLE ROW LEVEL SECURITY;
DROP FUNCTION IF EXISTS shared.current_refresh_token_hash();
DROP FUNCTION IF EXISTS shared.current_user_id();
DROP FUNCTION IF EXISTS shared.current_tenant_id();
@@ -0,0 +1,69 @@
CREATE OR REPLACE FUNCTION shared.current_tenant_id() RETURNS uuid AS $$
SELECT CASE
WHEN setting IS NULL OR setting = '' THEN NULL
ELSE setting::uuid
END
FROM (SELECT current_setting('papercrate.tenant_id', true) AS setting) s;
$$ LANGUAGE SQL STABLE;
CREATE OR REPLACE FUNCTION shared.current_user_id() RETURNS uuid AS $$
SELECT CASE
WHEN setting IS NULL OR setting = '' THEN NULL
ELSE setting::uuid
END
FROM (SELECT current_setting('papercrate.user_id', true) AS setting) s;
$$ LANGUAGE SQL STABLE;
CREATE OR REPLACE FUNCTION shared.current_refresh_token_hash() RETURNS text AS $$
SELECT NULLIF(current_setting('papercrate.refresh_token_hash', true), '')
$$ LANGUAGE SQL STABLE;
-- Helper to create tenant isolation policy
CREATE OR REPLACE FUNCTION shared.ensure_tenant_policy(table_reg regclass) RETURNS void AS $$
BEGIN
EXECUTE format('ALTER TABLE %s ENABLE ROW LEVEL SECURITY', table_reg);
EXECUTE format('ALTER TABLE %s FORCE ROW LEVEL SECURITY', table_reg);
EXECUTE format(
'CREATE POLICY tenant_isolation_policy ON %s USING (tenant_id = shared.current_tenant_id()) WITH CHECK (tenant_id = shared.current_tenant_id())',
table_reg
);
END;
$$ LANGUAGE plpgsql;
SELECT shared.ensure_tenant_policy('tenant.correspondents');
SELECT shared.ensure_tenant_policy('tenant.document_asset_objects');
SELECT shared.ensure_tenant_policy('tenant.document_assets');
SELECT shared.ensure_tenant_policy('tenant.document_correspondents');
SELECT shared.ensure_tenant_policy('tenant.document_tags');
SELECT shared.ensure_tenant_policy('tenant.document_versions');
SELECT shared.ensure_tenant_policy('tenant.documents');
SELECT shared.ensure_tenant_policy('tenant.folders');
SELECT shared.ensure_tenant_policy('tenant.tags');
SELECT shared.ensure_tenant_policy('tenant.webdav_tokens');
-- user_memberships has a special read policy to allow tenant discovery during login
ALTER TABLE tenant.user_memberships ENABLE ROW LEVEL SECURITY;
ALTER TABLE tenant.user_memberships FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_membership_select_policy ON tenant.user_memberships
USING (
tenant_id = shared.current_tenant_id()
OR (
shared.current_user_id() IS NOT NULL
AND user_id = shared.current_user_id()
)
)
WITH CHECK (tenant_id = shared.current_tenant_id());
ALTER TABLE tenant.refresh_tokens ENABLE ROW LEVEL SECURITY;
ALTER TABLE tenant.refresh_tokens FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_refresh_token_policy ON tenant.refresh_tokens
USING (
tenant_id = shared.current_tenant_id()
OR (
shared.current_refresh_token_hash() IS NOT NULL
AND token_hash = shared.current_refresh_token_hash()
)
)
WITH CHECK (tenant_id = shared.current_tenant_id());
DROP FUNCTION shared.ensure_tenant_policy(regclass);
@@ -0,0 +1,5 @@
DROP POLICY IF EXISTS tenant_webdav_token_policy ON tenant.webdav_tokens;
ALTER TABLE tenant.webdav_tokens NO FORCE ROW LEVEL SECURITY;
ALTER TABLE tenant.webdav_tokens DISABLE ROW LEVEL SECURITY;
DROP FUNCTION IF EXISTS shared.current_webdav_token_prefix();
@@ -0,0 +1,15 @@
CREATE OR REPLACE FUNCTION shared.current_webdav_token_prefix() RETURNS text AS $$
SELECT NULLIF(current_setting('papercrate.webdav_token_prefix', true), '')
$$ LANGUAGE SQL STABLE;
ALTER TABLE tenant.webdav_tokens ENABLE ROW LEVEL SECURITY;
ALTER TABLE tenant.webdav_tokens FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_webdav_token_policy ON tenant.webdav_tokens
USING (
tenant_id = shared.current_tenant_id()
OR (
shared.current_webdav_token_prefix() IS NOT NULL
AND token_prefix = shared.current_webdav_token_prefix()
)
)
WITH CHECK (tenant_id = shared.current_tenant_id());
@@ -0,0 +1,31 @@
DROP POLICY IF EXISTS tenant_api_token_policy ON tenant.api_tokens;
DROP FUNCTION IF EXISTS shared.current_api_token_prefix();
ALTER TABLE tenant.api_tokens DISABLE ROW LEVEL SECURITY;
ALTER TABLE tenant.api_tokens NO FORCE ROW LEVEL SECURITY;
ALTER TABLE tenant.api_tokens
DROP COLUMN IF EXISTS capabilities;
DROP TYPE IF EXISTS shared.api_token_capability;
ALTER TABLE tenant.api_tokens RENAME TO webdav_tokens;
ALTER INDEX tenant.api_tokens_token_prefix_key RENAME TO webdav_tokens_token_prefix_key;
ALTER INDEX tenant.api_tokens_user_tenant_idx RENAME TO webdav_tokens_user_tenant_idx;
CREATE OR REPLACE FUNCTION shared.current_webdav_token_prefix() RETURNS text AS $$
SELECT NULLIF(current_setting('papercrate.webdav_token_prefix', true), '')
$$ LANGUAGE SQL STABLE;
ALTER TABLE tenant.webdav_tokens ENABLE ROW LEVEL SECURITY;
ALTER TABLE tenant.webdav_tokens FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_webdav_token_policy ON tenant.webdav_tokens
USING (
tenant_id = shared.current_tenant_id()
OR (
shared.current_webdav_token_prefix() IS NOT NULL
AND token_prefix = shared.current_webdav_token_prefix()
)
)
WITH CHECK (tenant_id = shared.current_tenant_id());
@@ -0,0 +1,28 @@
ALTER TABLE tenant.webdav_tokens RENAME TO api_tokens;
ALTER INDEX tenant.webdav_tokens_token_prefix_key RENAME TO api_tokens_token_prefix_key;
ALTER INDEX tenant.webdav_tokens_user_tenant_idx RENAME TO api_tokens_user_tenant_idx;
DROP POLICY IF EXISTS tenant_webdav_token_policy ON tenant.api_tokens;
DROP FUNCTION IF EXISTS shared.current_webdav_token_prefix();
CREATE TYPE shared.api_token_capability AS ENUM ('api', 'webdav');
ALTER TABLE tenant.api_tokens
ADD COLUMN capabilities shared.api_token_capability[] NOT NULL DEFAULT ARRAY['webdav']::shared.api_token_capability[];
ALTER TABLE tenant.api_tokens ENABLE ROW LEVEL SECURITY;
ALTER TABLE tenant.api_tokens FORCE ROW LEVEL SECURITY;
CREATE OR REPLACE FUNCTION shared.current_api_token_prefix() RETURNS text AS $$
SELECT NULLIF(current_setting('papercrate.api_token_prefix', true), '')
$$ LANGUAGE SQL STABLE;
CREATE POLICY tenant_api_token_policy ON tenant.api_tokens
USING (
tenant_id = shared.current_tenant_id()
OR (
shared.current_api_token_prefix() IS NOT NULL
AND token_prefix = shared.current_api_token_prefix()
)
)
WITH CHECK (tenant_id = shared.current_tenant_id());
@@ -0,0 +1,26 @@
CREATE OR REPLACE FUNCTION shared.current_refresh_token_hash() RETURNS text AS $$
SELECT NULLIF(current_setting('papercrate.refresh_token_hash', true), '')
$$ LANGUAGE SQL STABLE;
ALTER POLICY tenant_user_session_policy ON tenant.user_sessions
USING (
tenant_id = shared.current_tenant_id()
OR (
shared.current_refresh_token_hash() IS NOT NULL
AND token_hash = shared.current_refresh_token_hash()
)
);
ALTER POLICY tenant_user_session_policy ON tenant.user_sessions
WITH CHECK (tenant_id = shared.current_tenant_id());
ALTER POLICY tenant_user_session_policy ON tenant.user_sessions
RENAME TO tenant_refresh_token_policy;
ALTER INDEX tenant.idx_user_sessions_user_id RENAME TO idx_refresh_tokens_user_id;
ALTER INDEX tenant.idx_user_sessions_token_hash RENAME TO idx_refresh_tokens_token_hash;
ALTER INDEX tenant.user_sessions_tenant_id_idx RENAME TO refresh_tokens_tenant_id_idx;
ALTER TABLE tenant.user_sessions RENAME TO refresh_tokens;
DROP FUNCTION IF EXISTS shared.current_user_session_hash();
@@ -0,0 +1,26 @@
ALTER TABLE tenant.refresh_tokens RENAME TO user_sessions;
ALTER INDEX tenant.idx_refresh_tokens_user_id RENAME TO idx_user_sessions_user_id;
ALTER INDEX tenant.idx_refresh_tokens_token_hash RENAME TO idx_user_sessions_token_hash;
ALTER INDEX tenant.refresh_tokens_tenant_id_idx RENAME TO user_sessions_tenant_id_idx;
ALTER POLICY tenant_refresh_token_policy ON tenant.user_sessions
RENAME TO tenant_user_session_policy;
CREATE OR REPLACE FUNCTION shared.current_user_session_hash() RETURNS text AS $$
SELECT NULLIF(current_setting('papercrate.user_session_hash', true), '')
$$ LANGUAGE SQL STABLE;
ALTER POLICY tenant_user_session_policy ON tenant.user_sessions
USING (
tenant_id = shared.current_tenant_id()
OR (
shared.current_user_session_hash() IS NOT NULL
AND token_hash = shared.current_user_session_hash()
)
);
ALTER POLICY tenant_user_session_policy ON tenant.user_sessions
WITH CHECK (tenant_id = shared.current_tenant_id());
DROP FUNCTION IF EXISTS shared.current_refresh_token_hash();
@@ -0,0 +1,13 @@
ALTER TABLE tenant.document_tags
DROP CONSTRAINT IF EXISTS document_tags_assigned_by_fkey,
ADD CONSTRAINT document_tags_assigned_by_fkey
FOREIGN KEY (assigned_by)
REFERENCES shared.users (id)
ON DELETE NO ACTION;
ALTER TABLE tenant.document_correspondents
DROP CONSTRAINT IF EXISTS document_correspondents_assigned_by_fkey,
ADD CONSTRAINT document_correspondents_assigned_by_fkey
FOREIGN KEY (assigned_by)
REFERENCES shared.users (id)
ON DELETE NO ACTION;
@@ -0,0 +1,13 @@
ALTER TABLE tenant.document_tags
DROP CONSTRAINT IF EXISTS document_tags_assigned_by_fkey,
ADD CONSTRAINT document_tags_assigned_by_fkey
FOREIGN KEY (assigned_by)
REFERENCES shared.users (id)
ON DELETE SET NULL;
ALTER TABLE tenant.document_correspondents
DROP CONSTRAINT IF EXISTS document_correspondents_assigned_by_fkey,
ADD CONSTRAINT document_correspondents_assigned_by_fkey
FOREIGN KEY (assigned_by)
REFERENCES shared.users (id)
ON DELETE SET NULL;
@@ -0,0 +1,28 @@
CREATE TYPE api_token_capability AS ENUM ('api', 'webdav');
ALTER TABLE tenant.api_tokens
ADD COLUMN capabilities api_token_capability[] NOT NULL DEFAULT ARRAY[]::api_token_capability[];
UPDATE tenant.api_tokens t
SET capabilities = ARRAY['api']::api_token_capability[]
FROM tenant.capability_sets cs
WHERE t.capability_set_id = cs.id
AND cs.slug = 'owner';
UPDATE tenant.api_tokens t
SET capabilities = ARRAY['webdav']::api_token_capability[]
FROM tenant.capability_sets cs
WHERE t.capability_set_id = cs.id
AND cs.slug = 'webdav'
AND (t.capabilities IS NULL OR array_length(t.capabilities, 1) = 0);
ALTER TABLE tenant.api_tokens
DROP COLUMN capability_set_id;
ALTER TABLE tenant.user_memberships
DROP COLUMN capability_set_id;
DROP TABLE IF EXISTS tenant.capability_set_capabilities;
DROP TABLE IF EXISTS tenant.capability_sets;
DROP TYPE IF EXISTS api_capability;
@@ -0,0 +1,158 @@
CREATE TYPE api_capability AS ENUM (
'documents:read',
'documents:edit',
'documents:write',
'documents:upload',
'folders:read',
'folders:edit',
'folders:write',
'tags:read',
'tags:edit',
'tags:write',
'correspondents:read',
'correspondents:edit',
'correspondents:write',
'profile:read',
'profile:write',
'webdav:read',
'webdav:write',
'capability_sets:read',
'capability_sets:write'
);
CREATE TABLE tenant.capability_sets (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id UUID NOT NULL REFERENCES shared.tenants(id) ON DELETE CASCADE,
slug TEXT NOT NULL,
cap_version INT NOT NULL DEFAULT 1,
is_system BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (tenant_id, slug)
);
CREATE TABLE tenant.capability_set_capabilities (
capability_set_id UUID NOT NULL REFERENCES tenant.capability_sets(id) ON DELETE CASCADE,
capability api_capability NOT NULL,
PRIMARY KEY (capability_set_id, capability)
);
ALTER TABLE tenant.api_tokens
ADD COLUMN capability_set_id UUID REFERENCES tenant.capability_sets(id);
ALTER TABLE tenant.user_memberships
ADD COLUMN capability_set_id UUID REFERENCES tenant.capability_sets(id);
WITH owner_sets AS (
INSERT INTO tenant.capability_sets (tenant_id, slug, is_system)
SELECT id, 'owner', TRUE
FROM shared.tenants
RETURNING id, tenant_id
),
user_sets AS (
INSERT INTO tenant.capability_sets (tenant_id, slug, is_system)
SELECT id, 'user', TRUE
FROM shared.tenants
RETURNING id, tenant_id
),
readonly_sets AS (
INSERT INTO tenant.capability_sets (tenant_id, slug, is_system)
SELECT id, 'readonly', TRUE
FROM shared.tenants
RETURNING id, tenant_id
),
webdav_sets AS (
INSERT INTO tenant.capability_sets (tenant_id, slug, is_system)
SELECT id, 'webdav', TRUE
FROM shared.tenants
RETURNING id, tenant_id
)
INSERT INTO tenant.capability_set_capabilities (capability_set_id, capability)
SELECT set_id,
capability
FROM (
SELECT os.id AS set_id,
UNNEST(ARRAY[
'documents:read'::api_capability,
'documents:edit'::api_capability,
'documents:write'::api_capability,
'documents:upload'::api_capability,
'folders:read'::api_capability,
'folders:edit'::api_capability,
'folders:write'::api_capability,
'tags:read'::api_capability,
'tags:edit'::api_capability,
'tags:write'::api_capability,
'correspondents:read'::api_capability,
'correspondents:edit'::api_capability,
'correspondents:write'::api_capability,
'profile:read'::api_capability,
'profile:write'::api_capability,
'webdav:read'::api_capability,
'webdav:write'::api_capability,
'capability_sets:read'::api_capability,
'capability_sets:write'::api_capability
]) AS capability
FROM owner_sets os
UNION ALL
SELECT us.id,
UNNEST(ARRAY[
'documents:read'::api_capability,
'documents:edit'::api_capability,
'documents:write'::api_capability,
'documents:upload'::api_capability,
'folders:read'::api_capability,
'folders:edit'::api_capability,
'folders:write'::api_capability,
'tags:read'::api_capability,
'tags:edit'::api_capability,
'tags:write'::api_capability,
'correspondents:read'::api_capability,
'correspondents:edit'::api_capability,
'correspondents:write'::api_capability,
'profile:read'::api_capability,
'profile:write'::api_capability
]) AS capability
FROM user_sets us
UNION ALL
SELECT rs.id,
UNNEST(ARRAY[
'documents:read'::api_capability,
'folders:read'::api_capability,
'tags:read'::api_capability,
'correspondents:read'::api_capability,
'webdav:read'::api_capability
]) AS capability
FROM readonly_sets rs
UNION ALL
SELECT ws.id,
UNNEST(ARRAY['webdav:read'::api_capability]) AS capability
FROM webdav_sets ws
) seeded;
UPDATE tenant.user_memberships um
SET capability_set_id = cs.id
FROM tenant.capability_sets cs
WHERE cs.tenant_id = um.tenant_id
AND cs.slug = 'owner';
UPDATE tenant.api_tokens t
SET capability_set_id = cs.id
FROM tenant.capability_sets cs
WHERE cs.tenant_id = t.tenant_id
AND cs.slug = 'owner';
UPDATE tenant.api_tokens t
SET capability_set_id = cs.id
FROM tenant.capability_sets cs
WHERE cs.tenant_id = t.tenant_id
AND cs.slug = 'webdav'
AND t.capability_set_id IS NULL;
ALTER TABLE tenant.api_tokens
ALTER COLUMN capability_set_id SET NOT NULL;
ALTER TABLE tenant.api_tokens
DROP COLUMN capabilities;
DROP TYPE IF EXISTS api_token_capability;
@@ -0,0 +1 @@
DROP INDEX IF EXISTS shared.jobs_purge_document_pending_unique;
@@ -0,0 +1,8 @@
CREATE UNIQUE INDEX jobs_purge_document_pending_unique
ON shared.jobs (
tenant_id,
((payload ->> 'document_id')::uuid)
)
WHERE job_type = 'purge-document'
AND payload ? 'document_id'
AND status IN ('queued', 'processing');
@@ -0,0 +1,5 @@
DROP INDEX IF EXISTS tenant.idx_documents_tenant_folder_updated_at;
DROP INDEX IF EXISTS tenant.idx_documents_tenant_folder_created_at;
DROP INDEX IF EXISTS tenant.idx_documents_tenant_folder_issued_at;
DROP INDEX IF EXISTS tenant.idx_documents_tenant_folder_title_order;
DROP COLLATION IF EXISTS unicode_ci;
@@ -0,0 +1,37 @@
CREATE COLLATION IF NOT EXISTS unicode_ci
(provider = icu, locale = 'und-u-ks-level2');
CREATE INDEX idx_documents_tenant_folder_title_order
ON tenant.documents (
tenant_id,
COALESCE(folder_id, '00000000-0000-0000-0000-000000000000'::uuid),
title COLLATE "unicode_ci"
)
WHERE deleted_at IS NULL;
CREATE INDEX idx_documents_tenant_folder_issued_at
ON tenant.documents (
tenant_id,
COALESCE(folder_id, '00000000-0000-0000-0000-000000000000'::uuid),
issued_at,
title COLLATE "unicode_ci"
)
WHERE deleted_at IS NULL;
CREATE INDEX idx_documents_tenant_folder_created_at
ON tenant.documents (
tenant_id,
COALESCE(folder_id, '00000000-0000-0000-0000-000000000000'::uuid),
created_at,
title COLLATE "unicode_ci"
)
WHERE deleted_at IS NULL;
CREATE INDEX idx_documents_tenant_folder_updated_at
ON tenant.documents (
tenant_id,
COALESCE(folder_id, '00000000-0000-0000-0000-000000000000'::uuid),
updated_at,
title COLLATE "unicode_ci"
)
WHERE deleted_at IS NULL;
@@ -0,0 +1,13 @@
ALTER TABLE shared.jobs
DROP CONSTRAINT jobs_tenant_id_fkey;
ALTER TABLE shared.jobs
ALTER COLUMN tenant_id SET NOT NULL;
ALTER TABLE shared.jobs
ADD CONSTRAINT jobs_tenant_id_fkey
FOREIGN KEY (tenant_id)
REFERENCES shared.tenants(id);
ALTER TABLE shared.jobs
DROP COLUMN result;
@@ -0,0 +1,14 @@
ALTER TABLE shared.jobs
ALTER COLUMN tenant_id DROP NOT NULL;
ALTER TABLE shared.jobs
DROP CONSTRAINT jobs_tenant_id_fkey;
ALTER TABLE shared.jobs
ADD CONSTRAINT jobs_tenant_id_fkey
FOREIGN KEY (tenant_id)
REFERENCES shared.tenants(id)
ON DELETE SET NULL;
ALTER TABLE shared.jobs
ADD COLUMN result JSONB;
@@ -0,0 +1,4 @@
-- diesel:run_in_transaction = false
-- Enum values cannot be removed safely; this down migration intentionally left empty.
SELECT 1;
@@ -0,0 +1,46 @@
-- diesel:run_in_transaction = false
DO $$
BEGIN
BEGIN
EXECUTE 'ALTER TYPE tenant.api_capability ADD VALUE ''tenants:write''';
EXCEPTION
WHEN undefined_object THEN
BEGIN
EXECUTE 'ALTER TYPE api_capability ADD VALUE ''tenants:write''';
EXCEPTION
WHEN duplicate_object THEN NULL;
END;
WHEN duplicate_object THEN NULL;
END;
END $$;
DO $$
BEGIN
BEGIN
EXECUTE 'ALTER TYPE tenant.api_capability ADD VALUE ''tenants:reset''';
EXCEPTION
WHEN undefined_object THEN
BEGIN
EXECUTE 'ALTER TYPE api_capability ADD VALUE ''tenants:reset''';
EXCEPTION
WHEN duplicate_object THEN NULL;
END;
WHEN duplicate_object THEN NULL;
END;
END $$;
DO $$
BEGIN
BEGIN
EXECUTE 'ALTER TYPE tenant.api_capability ADD VALUE ''tenants:delete''';
EXCEPTION
WHEN undefined_object THEN
BEGIN
EXECUTE 'ALTER TYPE api_capability ADD VALUE ''tenants:delete''';
EXCEPTION
WHEN duplicate_object THEN NULL;
END;
WHEN duplicate_object THEN NULL;
END;
END $$;
@@ -0,0 +1,9 @@
-- diesel:run_in_transaction = false
DELETE FROM tenant.capability_set_capabilities
WHERE capability IN (
'tenants:write'::api_capability,
'tenants:reset'::api_capability,
'tenants:delete'::api_capability
)
AND capability_set_id IN (SELECT id FROM tenant.capability_sets WHERE slug = 'owner');
@@ -0,0 +1,22 @@
-- diesel:run_in_transaction = false
WITH owner_sets AS (
SELECT id FROM tenant.capability_sets WHERE slug = 'owner'
)
INSERT INTO tenant.capability_set_capabilities (capability_set_id, capability)
SELECT id, 'tenants:write'::api_capability FROM owner_sets
ON CONFLICT DO NOTHING;
WITH owner_sets AS (
SELECT id FROM tenant.capability_sets WHERE slug = 'owner'
)
INSERT INTO tenant.capability_set_capabilities (capability_set_id, capability)
SELECT id, 'tenants:reset'::api_capability FROM owner_sets
ON CONFLICT DO NOTHING;
WITH owner_sets AS (
SELECT id FROM tenant.capability_sets WHERE slug = 'owner'
)
INSERT INTO tenant.capability_set_capabilities (capability_set_id, capability)
SELECT id, 'tenants:delete'::api_capability FROM owner_sets
ON CONFLICT DO NOTHING;
@@ -0,0 +1,24 @@
CREATE TABLE tenant.document_asset_objects (
id UUID PRIMARY KEY,
asset_id UUID NOT NULL REFERENCES tenant.document_assets(id) ON DELETE CASCADE,
ordinal INT NOT NULL,
s3_key TEXT NOT NULL,
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
tenant_id UUID NOT NULL REFERENCES shared.tenants(id),
CONSTRAINT document_asset_objects_ordinal_positive CHECK (ordinal >= 1),
CONSTRAINT document_asset_objects_asset_ordinal_unique UNIQUE (asset_id, ordinal)
);
CREATE INDEX idx_document_asset_objects_asset_ordinal
ON tenant.document_asset_objects(asset_id, ordinal);
CREATE INDEX document_asset_objects_tenant_id_idx ON tenant.document_asset_objects(tenant_id);
ALTER TABLE tenant.document_assets ADD COLUMN cardinality INT;
UPDATE tenant.document_assets SET cardinality = 1;
INSERT INTO tenant.document_asset_objects (id, asset_id, ordinal, s3_key, metadata, tenant_id)
SELECT gen_random_uuid(), id, 1, s3_key, metadata, tenant_id
FROM tenant.document_assets;
ALTER TABLE tenant.document_assets DROP COLUMN s3_key;
@@ -0,0 +1,27 @@
-- Prevent concurrent inserts/updates during backfill.
LOCK TABLE tenant.document_asset_objects IN ACCESS EXCLUSIVE MODE;
LOCK TABLE tenant.document_assets IN ACCESS EXCLUSIVE MODE;
ALTER TABLE tenant.document_assets ADD COLUMN s3_key TEXT;
UPDATE tenant.document_assets AS da
SET s3_key = o.s3_key,
metadata = COALESCE(da.metadata, '{}'::jsonb) || COALESCE(o.metadata, '{}'::jsonb)
FROM tenant.document_asset_objects AS o
WHERE o.asset_id = da.id
AND o.ordinal = 1;
DELETE FROM tenant.document_asset_objects WHERE ordinal <> 1;
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM tenant.document_assets WHERE s3_key IS NULL) THEN
RAISE EXCEPTION 'cannot drop document_asset_objects: some assets are missing a populated ordinal 1 object (s3_key null)';
END IF;
END
$$;
ALTER TABLE tenant.document_assets ALTER COLUMN s3_key SET NOT NULL;
ALTER TABLE tenant.document_assets DROP COLUMN cardinality;
DROP TABLE tenant.document_asset_objects;
@@ -0,0 +1,3 @@
-- Revert column rename.
ALTER TABLE tenant.documents
RENAME COLUMN mime_type TO content_type;
@@ -0,0 +1,3 @@
-- Rename document content_type column to mime_type for consistency with API.
ALTER TABLE tenant.documents
RENAME COLUMN content_type TO mime_type;
@@ -0,0 +1,3 @@
UPDATE tenant.document_assets
SET asset_type = 'ocr-text'
WHERE asset_type = 'text-content';
@@ -0,0 +1,3 @@
UPDATE tenant.document_assets
SET asset_type = 'text-content'
WHERE asset_type = 'ocr-text';
@@ -0,0 +1 @@
DROP INDEX IF EXISTS tenant.idx_documents_title_trgm;
@@ -0,0 +1,6 @@
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX idx_documents_title_trgm
ON tenant.documents
USING gin (title gin_trgm_ops)
WHERE deleted_at IS NULL;
@@ -1,6 +0,0 @@
DROP INDEX IF EXISTS folders_tenant_parent_name_unique_idx;
CREATE UNIQUE INDEX folders_parent_name_unique_idx
ON folders (
COALESCE(parent_id, '00000000-0000-0000-0000-000000000000'::uuid),
name
);
@@ -1,7 +0,0 @@
DROP INDEX IF EXISTS folders_parent_name_unique_idx;
CREATE UNIQUE INDEX folders_tenant_parent_name_unique_idx
ON folders (
tenant_id,
COALESCE(parent_id, '00000000-0000-0000-0000-000000000000'::uuid),
name
);
@@ -1,16 +0,0 @@
-- Revert correspondent uniqueness to global name
DROP INDEX IF EXISTS correspondents_tenant_name_unique;
ALTER TABLE correspondents ADD CONSTRAINT correspondents_name_unique UNIQUE (name);
-- Revert tag uniqueness to global label
DROP INDEX IF EXISTS tags_tenant_label_unique;
ALTER TABLE tags ADD CONSTRAINT tags_label_key UNIQUE (label);
-- Revert document filename uniqueness to global folder scope
DROP INDEX IF EXISTS documents_tenant_folder_filename_unique;
CREATE UNIQUE INDEX documents_unique_folder_filename
ON documents (
COALESCE(folder_id, '00000000-0000-0000-0000-000000000000'::uuid),
filename
)
WHERE deleted_at IS NULL;
@@ -1,20 +0,0 @@
-- Ensure document filenames are unique per tenant + folder
DROP INDEX IF EXISTS documents_tenant_folder_filename_unique;
DROP INDEX IF EXISTS documents_unique_folder_filename;
CREATE UNIQUE INDEX documents_tenant_folder_filename_unique
ON documents (
tenant_id,
COALESCE(folder_id, '00000000-0000-0000-0000-000000000000'::uuid),
filename
)
WHERE deleted_at IS NULL;
-- Ensure tag labels are unique per tenant
ALTER TABLE tags DROP CONSTRAINT IF EXISTS tags_label_key;
DROP INDEX IF EXISTS tags_tenant_label_unique;
CREATE UNIQUE INDEX tags_tenant_label_unique ON tags (tenant_id, label);
-- Ensure correspondent names are unique per tenant
ALTER TABLE correspondents DROP CONSTRAINT IF EXISTS correspondents_name_unique;
DROP INDEX IF EXISTS correspondents_tenant_name_unique;
CREATE UNIQUE INDEX correspondents_tenant_name_unique ON correspondents (tenant_id, name);
@@ -1,2 +0,0 @@
ALTER TABLE document_versions
ADD COLUMN operations_summary JSONB NOT NULL DEFAULT '{}'::jsonb;
@@ -1,2 +0,0 @@
ALTER TABLE document_versions
DROP COLUMN IF EXISTS operations_summary;
@@ -1,7 +0,0 @@
ALTER TABLE document_correspondents DROP CONSTRAINT document_correspondents_pkey;
ALTER TABLE document_correspondents ADD COLUMN role VARCHAR(32) NOT NULL DEFAULT 'other';
UPDATE document_correspondents SET role = 'other';
ALTER TABLE document_correspondents ALTER COLUMN role DROP DEFAULT;
ALTER TABLE document_correspondents
ADD CONSTRAINT document_correspondents_pkey
PRIMARY KEY (document_id, correspondent_id, role);
@@ -1,24 +0,0 @@
WITH ranked AS (
SELECT
document_id,
correspondent_id,
role,
assigned_at,
assigned_by,
tenant_id,
ROW_NUMBER() OVER (PARTITION BY document_id, correspondent_id ORDER BY assigned_at DESC) AS rn
FROM document_correspondents
)
DELETE FROM document_correspondents dc
USING ranked r
WHERE dc.document_id = r.document_id
AND dc.correspondent_id = r.correspondent_id
AND dc.role = r.role
AND dc.tenant_id = r.tenant_id
AND r.rn > 1;
ALTER TABLE document_correspondents DROP CONSTRAINT document_correspondents_pkey;
ALTER TABLE document_correspondents DROP COLUMN role;
ALTER TABLE document_correspondents
ADD CONSTRAINT document_correspondents_pkey
PRIMARY KEY (document_id, correspondent_id);
@@ -1,3 +0,0 @@
DROP INDEX IF EXISTS webdav_tokens_user_tenant_idx;
DROP INDEX IF EXISTS webdav_tokens_token_prefix_key;
DROP TABLE IF EXISTS webdav_tokens;
@@ -1,16 +0,0 @@
CREATE TABLE webdav_tokens (
id UUID PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
token_prefix TEXT NOT NULL,
token_hash TEXT NOT NULL,
label TEXT,
scopes JSONB NOT NULL DEFAULT '["webdav"]'::jsonb,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
last_used_at TIMESTAMPTZ,
expires_at TIMESTAMPTZ,
revoked_at TIMESTAMPTZ
);
CREATE UNIQUE INDEX webdav_tokens_token_prefix_key ON webdav_tokens(token_prefix);
CREATE INDEX webdav_tokens_user_tenant_idx ON webdav_tokens(user_id, tenant_id);
@@ -1,2 +0,0 @@
ALTER TABLE webdav_tokens
ADD COLUMN scopes JSONB NOT NULL DEFAULT '["webdav"]'::jsonb;
@@ -1,2 +0,0 @@
ALTER TABLE webdav_tokens
DROP COLUMN IF EXISTS scopes;
@@ -1,5 +0,0 @@
ALTER TABLE tenants
DROP COLUMN IF EXISTS status,
DROP COLUMN IF EXISTS created_by;
DROP TYPE IF EXISTS tenant_status;
@@ -1,19 +0,0 @@
ALTER TABLE tenants
DROP COLUMN IF EXISTS status;
ALTER TABLE tenants
DROP COLUMN IF EXISTS created_by;
DROP TYPE IF EXISTS tenant_status;
CREATE TYPE tenant_status AS ENUM ('creating', 'active', 'suspended', 'deleting', 'error');
ALTER TABLE tenants
ADD COLUMN status tenant_status,
ADD COLUMN created_by UUID;
UPDATE tenants
SET status = 'active';
ALTER TABLE tenants
ALTER COLUMN status SET NOT NULL;
@@ -1 +0,0 @@
DROP TABLE IF EXISTS user_passkeys;
@@ -1,19 +0,0 @@
CREATE TABLE user_passkeys (
id UUID PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
credential_id BYTEA NOT NULL UNIQUE,
public_key BYTEA NOT NULL,
credential JSONB NOT NULL,
sign_count BIGINT NOT NULL,
transports TEXT[] NOT NULL DEFAULT '{}',
aaguid UUID,
nickname TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
last_used_at TIMESTAMPTZ,
revoked_at TIMESTAMPTZ,
revoked_by UUID,
revoked_reason TEXT
);
CREATE INDEX user_passkeys_user_id_idx ON user_passkeys (user_id);
@@ -1 +0,0 @@
DROP TABLE IF EXISTS webauthn_challenges;
@@ -1,13 +0,0 @@
CREATE TABLE webauthn_challenges (
id UUID PRIMARY KEY,
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
purpose TEXT NOT NULL,
challenge BYTEA NOT NULL,
state BYTEA NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
expires_at TIMESTAMPTZ NOT NULL,
CONSTRAINT webauthn_challenges_purpose_check CHECK (purpose IN ('registration', 'authentication'))
);
CREATE INDEX webauthn_challenges_user_id_idx ON webauthn_challenges (user_id);
CREATE INDEX webauthn_challenges_expires_at_idx ON webauthn_challenges (expires_at);
@@ -1,2 +0,0 @@
ALTER TABLE user_memberships
ADD COLUMN role TEXT NOT NULL DEFAULT 'user';
@@ -1,2 +0,0 @@
ALTER TABLE user_memberships
DROP COLUMN role;
@@ -1,5 +0,0 @@
ALTER TABLE tenants
RENAME COLUMN name TO slug;
ALTER TABLE tenants
RENAME CONSTRAINT tenants_name_key TO tenants_slug_key;
@@ -1,5 +0,0 @@
ALTER TABLE tenants
RENAME COLUMN slug TO name;
ALTER TABLE tenants
RENAME CONSTRAINT tenants_slug_key TO tenants_name_key;
@@ -1,2 +0,0 @@
ALTER TABLE tenants
ADD CONSTRAINT tenants_name_key UNIQUE (name);
@@ -1,2 +0,0 @@
ALTER TABLE tenants
DROP CONSTRAINT IF EXISTS tenants_name_key;
@@ -1,6 +0,0 @@
ALTER TABLE users
ADD COLUMN password_hash VARCHAR(255) NOT NULL DEFAULT '';
-- Optional: remove the default if you need to reintroduce passwords later
ALTER TABLE users
ALTER COLUMN password_hash DROP DEFAULT;
@@ -1,2 +0,0 @@
ALTER TABLE users
DROP COLUMN password_hash;
@@ -0,0 +1,21 @@
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'papercrate_app') THEN
CREATE ROLE papercrate_app NOLOGIN;
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'papercrate_app_login') THEN
CREATE ROLE papercrate_app_login LOGIN PASSWORD 'papercrate_app';
GRANT papercrate_app TO papercrate_app_login;
END IF;
END
$$;
-- Ensure the login role inherits and uses a sensible search path by default
ALTER ROLE papercrate_app_login INHERIT;
ALTER ROLE papercrate_app_login SET search_path = 'tenant, shared, public';
GRANT CONNECT ON DATABASE papercrate TO papercrate_app;
GRANT CONNECT ON DATABASE papercrate TO papercrate_app_login;
GRANT USAGE ON SCHEMA public TO papercrate_app;
GRANT USAGE ON SCHEMA public TO papercrate_app_login;
+648
View File
@@ -0,0 +1,648 @@
months:
- name: "january"
month: 1
locales:
- "en"
- name: "jan"
month: 1
locales:
- "en"
- name: "janvier"
month: 1
locales:
- "fr"
- name: "janv"
month: 1
locales:
- "fr"
- name: "januar"
month: 1
locales:
- "de"
- name: "janu\u00e1r"
month: 1
locales:
- "hu"
- name: "leden"
month: 1
locales:
- "cs"
- name: "sije\u010danj"
month: 1
locales:
- "hr"
- name: "sijecanj"
month: 1
locales:
- "hr"
- name: "stycze\u0144"
month: 1
locales:
- "pl"
- name: "styczen"
month: 1
locales:
- "pl"
- name: "ocak"
month: 1
locales:
- "tr"
- name: "february"
month: 2
locales:
- "en"
- name: "feb"
month: 2
locales:
- "en"
- name: "f\u00e9vrier"
month: 2
locales:
- "fr"
- name: "fevrier"
month: 2
locales:
- "fr"
- name: "f\u00e9vr"
month: 2
locales:
- "fr"
- name: "fevr"
month: 2
locales:
- "fr"
- name: "februar"
month: 2
locales:
- "de"
- name: "\u00fanor"
month: 2
locales:
- "cs"
- name: "unor"
month: 2
locales:
- "cs"
- name: "\u00fanora"
month: 2
locales:
- "cs"
- name: "unora"
month: 2
locales:
- "cs"
- name: "velja\u010da"
month: 2
locales:
- "hr"
- name: "veljaca"
month: 2
locales:
- "hr"
- name: "velja\u010de"
month: 2
locales:
- "hr"
- name: "veljace"
month: 2
locales:
- "hr"
- name: "luty"
month: 2
locales:
- "pl"
- name: "\u015fubat"
month: 2
locales:
- "tr"
- name: "subat"
month: 2
locales:
- "tr"
- name: "march"
month: 3
locales:
- "en"
- name: "mar"
month: 3
locales:
- "en"
- name: "m\u00e4rz"
month: 3
locales:
- "de"
- name: "maerz"
month: 3
locales:
- "de"
- name: "mars"
month: 3
locales:
- "fr"
- name: "m\u00e4r"
month: 3
locales:
- "de"
- name: "marz"
month: 3
locales:
- "de"
- name: "b\u0159ezen"
month: 3
locales:
- "cs"
- name: "brezen"
month: 3
locales:
- "cs"
- name: "b\u0159ezna"
month: 3
locales:
- "cs"
- name: "brezna"
month: 3
locales:
- "cs"
- name: "o\u017eujak"
month: 3
locales:
- "hr"
- name: "ozujak"
month: 3
locales:
- "hr"
- name: "o\u017eujka"
month: 3
locales:
- "hr"
- name: "ozujka"
month: 3
locales:
- "hr"
- name: "marzec"
month: 3
locales:
- "pl"
- name: "mart"
month: 3
locales:
- "sr"
- "bs"
- name: "m\u00e1rcius"
month: 3
locales:
- "hu"
- name: "martie"
month: 3
locales:
- "ro"
- name: "april"
month: 4
locales:
- "en"
- name: "apr"
month: 4
locales:
- "en"
- name: "avril"
month: 4
locales:
- "fr"
- name: "abril"
month: 4
locales:
- "es"
- "pt"
- name: "duben"
month: 4
locales:
- "cs"
- name: "travanj"
month: 4
locales:
- "hr"
- name: "nisan"
month: 4
locales:
- "tr"
- name: "kwiecie\u0144"
month: 4
locales:
- "pl"
- name: "kwiecien"
month: 4
locales:
- "pl"
- name: "aprile"
month: 4
locales:
- "it"
- name: "may"
month: 5
locales:
- "en"
- name: "mai"
month: 5
locales:
- "fr"
- "de"
- name: "mayo"
month: 5
locales:
- "es"
- name: "kv\u011bten"
month: 5
locales:
- "cs"
- name: "kveten"
month: 5
locales:
- "cs"
- name: "kv\u011btna"
month: 5
locales:
- "cs"
- name: "kvetna"
month: 5
locales:
- "cs"
- name: "svibanj"
month: 5
locales:
- "hr"
- name: "maj"
month: 5
locales:
- "pl"
- "bs"
- "sr"
- "hr"
- name: "may\u0131s"
month: 5
locales:
- "tr"
- name: "mayis"
month: 5
locales:
- "tr"
- name: "maggio"
month: 5
locales:
- "it"
- name: "m\u00e1j"
month: 5
locales:
- "hu"
- "sk"
- name: "june"
month: 6
locales:
- "en"
- name: "jun"
month: 6
locales:
- "en"
- "de"
- name: "juin"
month: 6
locales:
- "fr"
- name: "junio"
month: 6
locales:
- "es"
- name: "juni"
month: 6
locales:
- "de"
- name: "\u010derven"
month: 6
locales:
- "cs"
- name: "cerven"
month: 6
locales:
- "cs"
- name: "lipanj"
month: 6
locales:
- "hr"
- name: "haziran"
month: 6
locales:
- "tr"
- name: "czerwiec"
month: 6
locales:
- "pl"
- name: "j\u00fanius"
month: 6
locales:
- "hu"
- name: "giugno"
month: 6
locales:
- "it"
- name: "july"
month: 7
locales:
- "en"
- name: "jul"
month: 7
locales:
- "en"
- "de"
- name: "juillet"
month: 7
locales:
- "fr"
- name: "julio"
month: 7
locales:
- "es"
- name: "temmuz"
month: 7
locales:
- "tr"
- name: "\u010dervenec"
month: 7
locales:
- "cs"
- name: "cervenec"
month: 7
locales:
- "cs"
- name: "srpanj"
month: 7
locales:
- "hr"
- name: "lipiec"
month: 7
locales:
- "pl"
- name: "luglio"
month: 7
locales:
- "it"
- name: "j\u00falius"
month: 7
locales:
- "hu"
- name: "august"
month: 8
locales:
- "en"
- name: "aug"
month: 8
locales:
- "en"
- "de"
- name: "ao\u00fbt"
month: 8
locales:
- "fr"
- name: "aout"
month: 8
locales:
- "fr"
- name: "agosto"
month: 8
locales:
- "es"
- "pt"
- "it"
- name: "a\u011fustos"
month: 8
locales:
- "tr"
- name: "agustos"
month: 8
locales:
- "tr"
- name: "kolovoz"
month: 8
locales:
- "hr"
- name: "srpen"
month: 8
locales:
- "cs"
- name: "sierpie\u0144"
month: 8
locales:
- "pl"
- name: "sierpien"
month: 8
locales:
- "pl"
- name: "augustus"
month: 8
locales:
- "nl"
- name: "agost"
month: 8
locales:
- "it"
- "ca"
- name: "september"
month: 9
locales:
- "en"
- name: "sept"
month: 9
locales:
- "en"
- "fr"
- name: "sep"
month: 9
locales:
- "en"
- name: "septembre"
month: 9
locales:
- "fr"
- name: "septiembre"
month: 9
locales:
- "es"
- name: "eyl\u00fcl"
month: 9
locales:
- "tr"
- name: "eylul"
month: 9
locales:
- "tr"
- name: "z\u00e1\u0159\u00ed"
month: 9
locales:
- "cs"
- name: "zari"
month: 9
locales:
- "cs"
- name: "rujan"
month: 9
locales:
- "hr"
- name: "wrzesie\u0144"
month: 9
locales:
- "pl"
- name: "wrzesien"
month: 9
locales:
- "pl"
- name: "septembrie"
month: 9
locales:
- "ro"
- name: "settembre"
month: 9
locales:
- "it"
- name: "october"
month: 10
locales:
- "en"
- name: "oct"
month: 10
locales:
- "en"
- name: "oktober"
month: 10
locales:
- "de"
- name: "okt\u00f3ber"
month: 10
locales:
- "hu"
- name: "octobre"
month: 10
locales:
- "fr"
- name: "octubre"
month: 10
locales:
- "es"
- name: "\u0159\u00edjen"
month: 10
locales:
- "cs"
- name: "rijen"
month: 10
locales:
- "hr"
- name: "pa\u017adziernik"
month: 10
locales:
- "pl"
- name: "pazdziernik"
month: 10
locales:
- "pl"
- name: "ekim"
month: 10
locales:
- "tr"
- name: "octombrie"
month: 10
locales:
- "ro"
- name: "november"
month: 11
locales:
- "en"
- name: "nov"
month: 11
locales:
- "en"
- name: "novembre"
month: 11
locales:
- "fr"
- name: "noviembre"
month: 11
locales:
- "es"
- name: "studeni"
month: 11
locales:
- "hr"
- name: "kas\u0131m"
month: 11
locales:
- "tr"
- name: "kasim"
month: 11
locales:
- "tr"
- name: "listopad"
month: 11
locales:
- "pl"
- "cs"
- name: "novembro"
month: 11
locales:
- "pt"
- name: "listopadu"
month: 11
locales:
- "cs"
- name: "noiembrie"
month: 11
locales:
- "ro"
- name: "december"
month: 12
locales:
- "en"
- name: "dec"
month: 12
locales:
- "en"
- name: "dezember"
month: 12
locales:
- "de"
- name: "d\u00e9cembre"
month: 12
locales:
- "fr"
- name: "decembre"
month: 12
locales:
- "fr"
- name: "prosinec"
month: 12
locales:
- "cs"
- name: "prosinac"
month: 12
locales:
- "hr"
- name: "grudzie\u0144"
month: 12
locales:
- "pl"
- name: "grudzien"
month: 12
locales:
- "pl"
- name: "grudnia"
month: 12
locales:
- "pl"
- name: "aral\u0131k"
month: 12
locales:
- "tr"
- name: "aralik"
month: 12
locales:
- "tr"
- name: "decembrie"
month: 12
locales:
- "ro"
+324
View File
@@ -0,0 +1,324 @@
use argon2::{
password_hash::{rand_core::OsRng as PasswordHashOsRng, PasswordHasher, SaltString},
Argon2,
};
use chrono::{NaiveDateTime, Utc};
use diesel::prelude::*;
use rand::{rngs::OsRng, TryRngCore};
use uuid::Uuid;
use crate::{
auth::capability_sets::{load_capabilities_for_set, load_capability_set},
error::AppError,
models::{ApiCapability, ApiToken, CapabilitySet, NewApiToken},
schema::api_tokens,
state::PgPooledConnection,
tenants::{apply_api_token_prefix, clear_api_token_prefix},
};
use crate::schema::api_tokens::dsl as api_tokens_dsl;
const TOKEN_PREFIX_LENGTH: usize = 12;
const TOKEN_SECRET_LENGTH: usize = 32;
/// Represents a newly issued API token and the raw secret that was generated for it.
pub struct IssuedApiToken {
pub token: String,
pub record: ApiToken,
}
/// Creates a new API token for the supplied user/tenant combination.
pub fn create_api_token(
conn: &mut PgPooledConnection,
user_id: Uuid,
tenant_id: Uuid,
label: Option<String>,
expires_at: Option<NaiveDateTime>,
capability_set_id: Uuid,
) -> Result<IssuedApiToken, AppError> {
let capability_set =
validate_capability_set_belongs_to_tenant(conn, capability_set_id, tenant_id)?;
let raw_secret = generate_secret()?;
let token_prefix = raw_secret[..TOKEN_PREFIX_LENGTH].to_string();
let token_hash = hash_secret(&raw_secret)?;
let new_token = NewApiToken {
id: Uuid::new_v4(),
user_id,
tenant_id,
token_prefix,
token_hash,
label,
expires_at,
capability_set_id: capability_set.id,
};
let record = diesel::insert_into(api_tokens::table)
.values(&new_token)
.get_result::<ApiToken>(conn)?;
Ok(IssuedApiToken {
token: raw_secret,
record,
})
}
/// Lists API tokens belonging to a user within an optional tenant scope.
pub fn list_api_tokens(
conn: &mut PgPooledConnection,
user_id: Uuid,
tenant_id: Option<Uuid>,
) -> Result<Vec<ApiToken>, AppError> {
let mut query = api_tokens::table
.filter(api_tokens::user_id.eq(user_id))
.into_boxed();
if let Some(tenant_id) = tenant_id {
query = query.filter(api_tokens::tenant_id.eq(tenant_id));
}
let tokens = query
.order(api_tokens::created_at.asc())
.load::<ApiToken>(conn)?;
Ok(tokens)
}
/// Regenerates the secret value for an API token.
pub fn regenerate_api_token(
conn: &mut PgPooledConnection,
token_id: Uuid,
user_id: Uuid,
tenant_id: Option<Uuid>,
) -> Result<IssuedApiToken, AppError> {
let record = find_user_token(conn, token_id, user_id, tenant_id)?;
if record.revoked_at.is_some() {
return Err(AppError::bad_request(
"cannot regenerate a revoked API token",
));
}
let raw_secret = generate_secret()?;
let token_prefix = raw_secret[..TOKEN_PREFIX_LENGTH].to_string();
let token_hash = hash_secret(&raw_secret)?;
let updated = diesel::update(api_tokens::table.find(record.id))
.set((
api_tokens::token_prefix.eq(&token_prefix),
api_tokens::token_hash.eq(&token_hash),
api_tokens::last_used_at.eq::<Option<NaiveDateTime>>(None),
))
.get_result::<ApiToken>(conn)?;
Ok(IssuedApiToken {
token: raw_secret,
record: updated,
})
}
/// Attempts to resolve an API token by its secret value while ensuring it provides the
/// requested capability.
pub fn find_active_token_by_secret(
conn: &mut PgPooledConnection,
tenant_id: Option<Uuid>,
secret: &str,
required_capability: Option<ApiCapability>,
) -> Result<Option<ApiToken>, AppError> {
if secret.len() < TOKEN_PREFIX_LENGTH {
return Ok(None);
}
let prefix = &secret[..TOKEN_PREFIX_LENGTH];
let candidates = with_api_token_prefix(conn, prefix, |conn| {
let mut query = api_tokens::table
.filter(api_tokens::token_prefix.eq(prefix))
.filter(api_tokens::revoked_at.is_null())
.into_boxed();
let now = Utc::now().naive_utc();
query = query.filter(
api_tokens::expires_at
.is_null()
.or(api_tokens::expires_at.gt(now)),
);
if let Some(tenant_id) = tenant_id {
query = query.filter(api_tokens::tenant_id.eq(tenant_id));
}
query.load::<ApiToken>(conn).map_err(AppError::from)
})?;
for token in candidates {
if let Some(required) = required_capability {
let capabilities = load_capabilities_for_set(conn, token.capability_set_id)?;
if !capabilities.contains(&required) {
continue;
}
}
if verify_token_secret(secret, &token.token_hash)? {
return Ok(Some(token));
}
}
Ok(None)
}
/// Revokes an API token belonging to the specified user.
pub fn revoke_api_token(
conn: &mut PgPooledConnection,
token_id: Uuid,
user_id: Uuid,
) -> Result<(), AppError> {
let token = find_user_token(conn, token_id, user_id, None)?;
diesel::update(api_tokens::table.find(token.id))
.set(api_tokens::revoked_at.eq(Utc::now().naive_utc()))
.execute(conn)?;
Ok(())
}
/// Updates the last-used timestamp for a token.
pub fn touch_api_token(conn: &mut PgPooledConnection, token_id: Uuid) -> Result<(), AppError> {
diesel::update(api_tokens::table.filter(api_tokens::id.eq(token_id)))
.set(api_tokens::last_used_at.eq(Utc::now().naive_utc()))
.execute(conn)?;
Ok(())
}
/// Verifies a secret against its stored hash representation.
pub fn verify_token_secret(secret: &str, token_hash: &str) -> Result<bool, AppError> {
crate::auth::password::verify_password(secret, token_hash).map_err(|err| {
tracing::error!(error = ?err, "failed to verify token");
AppError::internal("failed to verify token")
})
}
fn find_user_token(
conn: &mut PgPooledConnection,
token_id: Uuid,
user_id: Uuid,
tenant_id: Option<Uuid>,
) -> Result<ApiToken, AppError> {
let mut query = api_tokens_dsl::api_tokens
.filter(api_tokens_dsl::id.eq(token_id))
.filter(api_tokens_dsl::user_id.eq(user_id))
.into_boxed();
if let Some(tid) = tenant_id {
query = query.filter(api_tokens_dsl::tenant_id.eq(tid));
}
query
.first::<ApiToken>(conn)
.optional()
.map_err(AppError::from)?
.ok_or_else(AppError::not_found)
}
fn validate_capability_set_belongs_to_tenant(
conn: &mut PgPooledConnection,
capability_set_id: Uuid,
tenant_id: Uuid,
) -> Result<CapabilitySet, AppError> {
let capability_set = load_capability_set(conn, capability_set_id)?;
if capability_set.tenant_id != tenant_id {
return Err(AppError::bad_request(
"capability set does not belong to the tenant",
));
}
Ok(capability_set)
}
fn with_api_token_prefix<T, F>(
conn: &mut PgPooledConnection,
prefix: &str,
operation: F,
) -> Result<T, AppError>
where
F: FnOnce(&mut PgPooledConnection) -> Result<T, AppError>,
{
apply_api_token_prefix(conn, prefix)?;
let operation_result = operation(conn);
let clear_result = clear_api_token_prefix(conn);
if let Err(err) = clear_result {
return Err(err);
}
operation_result
}
fn generate_secret() -> Result<String, AppError> {
let mut buffer = [0u8; TOKEN_SECRET_LENGTH];
OsRng.try_fill_bytes(&mut buffer).map_err(|err| {
tracing::error!(error = ?err, "failed to generate token");
AppError::internal("failed to generate token")
})?;
Ok(hex::encode(buffer))
}
fn hash_secret(secret: &str) -> Result<String, AppError> {
let mut salt_rng = PasswordHashOsRng;
let salt = SaltString::generate(&mut salt_rng);
let hash = Argon2::default()
.hash_password(secret.as_bytes(), &salt)
.map_err(|err| {
tracing::error!(error = ?err, "failed to hash token");
AppError::internal("failed to hash token")
})?;
Ok(hash.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::auth::capability_sets::{
compute_slug, normalize_capabilities, owner_capabilities, webdav_capabilities,
};
#[test]
fn generated_secret_has_expected_length() {
let secret = generate_secret().unwrap();
assert_eq!(secret.len(), TOKEN_SECRET_LENGTH * 2);
}
#[test]
fn hash_and_verify_secret_round_trip() {
let secret = generate_secret().unwrap();
let hash = hash_secret(&secret).unwrap();
assert!(verify_token_secret(&secret, &hash).unwrap());
assert!(!verify_token_secret("wrong", &hash).unwrap());
}
#[test]
fn normalize_capabilities_deduplicates() {
let mut caps = owner_capabilities().to_vec();
caps.push(ApiCapability::DocumentsRead);
let normalized = normalize_capabilities(caps).unwrap();
assert_eq!(normalized.len(), owner_capabilities().len());
}
#[test]
fn normalize_capabilities_rejects_empty() {
assert!(normalize_capabilities(Vec::new()).is_err());
}
#[test]
fn compute_slug_matches_system_sets() {
let owner_slug = compute_slug(owner_capabilities());
assert_eq!(owner_slug, "owner");
let webdav_slug = compute_slug(webdav_capabilities());
assert_eq!(webdav_slug, "webdav");
}
#[test]
fn prefix_length_is_less_than_secret_length() {
assert!(TOKEN_PREFIX_LENGTH < TOKEN_SECRET_LENGTH * 2);
}
}
+120
View File
@@ -0,0 +1,120 @@
use std::sync::Arc;
use axum::{
http::{Request, StatusCode},
response::IntoResponse,
};
use tower::{Layer, Service};
use crate::{auth::AuthenticatedUser, error::AppError, models::ApiCapability};
#[derive(Clone, Copy)]
pub enum CapabilityStrategy {
All,
Any,
}
#[derive(Clone)]
pub struct RequireCapabilitiesLayer {
required: Arc<Vec<ApiCapability>>,
strategy: CapabilityStrategy,
}
impl RequireCapabilitiesLayer {
pub fn all<I>(caps: I) -> Self
where
I: IntoIterator<Item = ApiCapability>,
{
Self {
required: Arc::new(caps.into_iter().collect()),
strategy: CapabilityStrategy::All,
}
}
pub fn any<I>(caps: I) -> Self
where
I: IntoIterator<Item = ApiCapability>,
{
Self {
required: Arc::new(caps.into_iter().collect()),
strategy: CapabilityStrategy::Any,
}
}
}
impl<S> Layer<S> for RequireCapabilitiesLayer {
type Service = RequireCapabilities<S>;
fn layer(&self, inner: S) -> Self::Service {
RequireCapabilities {
inner,
required: Arc::clone(&self.required),
strategy: self.strategy,
}
}
}
#[derive(Clone)]
pub struct RequireCapabilities<S> {
inner: S,
required: Arc<Vec<ApiCapability>>,
strategy: CapabilityStrategy,
}
impl<S, B> Service<Request<B>> for RequireCapabilities<S>
where
S: Service<Request<B>, Response = axum::response::Response> + Send,
S::Future: Send + 'static,
B: Send + 'static,
{
type Response = S::Response;
type Error = S::Error;
type Future = std::pin::Pin<
Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>> + Send>,
>;
fn poll_ready(
&mut self,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: Request<B>) -> Self::Future {
if self.required.is_empty() {
let fut = self.inner.call(req);
return Box::pin(async move { fut.await });
}
let (parts, body) = req.into_parts();
let user = match parts.extensions.get::<AuthenticatedUser>() {
Some(user) => user,
None => {
let response = AppError::unauthorized().into_response();
return Box::pin(async move { Ok(response) });
}
};
let allowed = match self.strategy {
CapabilityStrategy::All => self
.required
.iter()
.all(|cap| user.capabilities.contains(cap)),
CapabilityStrategy::Any => self
.required
.iter()
.any(|cap| user.capabilities.contains(cap)),
};
if !allowed {
let response = AppError::new(StatusCode::FORBIDDEN, "missing required capability")
.with_code("missing_capability")
.into_response();
return Box::pin(async move { Ok(response) });
}
let req = Request::from_parts(parts, body);
let fut = self.inner.call(req);
Box::pin(async move { fut.await })
}
}
+323
View File
@@ -0,0 +1,323 @@
use chrono::Utc;
use diesel::{pg::Pg, prelude::*, Connection};
use sha2::{Digest, Sha256};
use uuid::Uuid;
use crate::{
error::AppError,
models::{ApiCapability, CapabilitySet, NewCapabilitySet, NewCapabilitySetCapability},
schema::{
capability_set_capabilities, capability_set_capabilities::dsl as csc_dsl, capability_sets,
capability_sets::dsl as cs_dsl,
},
};
const OWNER_CAPABILITIES: [ApiCapability; 22] = [
ApiCapability::CorrespondentsEdit,
ApiCapability::CorrespondentsRead,
ApiCapability::CorrespondentsWrite,
ApiCapability::DocumentsEdit,
ApiCapability::DocumentsRead,
ApiCapability::DocumentsUpload,
ApiCapability::DocumentsWrite,
ApiCapability::FoldersEdit,
ApiCapability::FoldersRead,
ApiCapability::FoldersWrite,
ApiCapability::ProfileRead,
ApiCapability::ProfileWrite,
ApiCapability::TagsEdit,
ApiCapability::TagsRead,
ApiCapability::TagsWrite,
ApiCapability::WebdavRead,
ApiCapability::WebdavWrite,
ApiCapability::CapabilitySetsRead,
ApiCapability::CapabilitySetsWrite,
ApiCapability::TenantsWrite,
ApiCapability::TenantsReset,
ApiCapability::TenantsDelete,
];
const USER_CAPABILITIES: [ApiCapability; 16] = [
ApiCapability::CorrespondentsEdit,
ApiCapability::CorrespondentsRead,
ApiCapability::CorrespondentsWrite,
ApiCapability::DocumentsEdit,
ApiCapability::DocumentsRead,
ApiCapability::DocumentsUpload,
ApiCapability::DocumentsWrite,
ApiCapability::FoldersEdit,
ApiCapability::FoldersRead,
ApiCapability::FoldersWrite,
ApiCapability::ProfileRead,
ApiCapability::ProfileWrite,
ApiCapability::TagsEdit,
ApiCapability::TagsRead,
ApiCapability::TagsWrite,
ApiCapability::WebdavRead,
];
const READONLY_CAPABILITIES: [ApiCapability; 5] = [
ApiCapability::CorrespondentsRead,
ApiCapability::DocumentsRead,
ApiCapability::FoldersRead,
ApiCapability::TagsRead,
ApiCapability::WebdavRead,
];
const WEBDAV_CAPABILITIES: [ApiCapability; 1] = [ApiCapability::WebdavRead];
pub fn owner_capabilities() -> &'static [ApiCapability] {
&OWNER_CAPABILITIES
}
pub fn user_capabilities() -> &'static [ApiCapability] {
&USER_CAPABILITIES
}
pub fn readonly_capabilities() -> &'static [ApiCapability] {
&READONLY_CAPABILITIES
}
pub fn webdav_capabilities() -> &'static [ApiCapability] {
&WEBDAV_CAPABILITIES
}
pub fn is_system_slug(slug: &str) -> bool {
matches!(slug, "owner" | "user" | "readonly" | "webdav")
}
pub fn create_capability_set<C>(
conn: &mut C,
tenant_id: Uuid,
slug: &str,
capabilities: Vec<ApiCapability>,
) -> Result<CapabilitySet, AppError>
where
C: Connection<Backend = Pg> + diesel::connection::LoadConnection,
{
let normalized = normalize_capabilities(capabilities)?;
conn.transaction::<CapabilitySet, AppError, _>(|conn| {
if cs_dsl::capability_sets
.filter(cs_dsl::tenant_id.eq(tenant_id))
.filter(cs_dsl::slug.eq(slug))
.first::<CapabilitySet>(conn)
.optional()
.map_err(AppError::from)?
.is_some()
{
return Err(AppError::conflict("capability set slug already exists"));
}
let set = NewCapabilitySet {
id: Uuid::new_v4(),
tenant_id,
slug: slug.to_owned(),
cap_version: 1,
is_system: false,
};
diesel::insert_into(capability_sets::table)
.values(&set)
.execute(conn)
.map_err(AppError::from)?;
persist_capabilities(conn, set.id, &normalized)?;
capability_sets::table
.find(set.id)
.first::<CapabilitySet>(conn)
.map_err(AppError::from)
})
}
pub fn normalize_capabilities(
mut capabilities: Vec<ApiCapability>,
) -> Result<Vec<ApiCapability>, AppError> {
if capabilities.is_empty() {
return Err(AppError::bad_request("at least one capability is required"));
}
capabilities.sort_by(|a, b| a.as_str().cmp(b.as_str()));
capabilities.dedup();
Ok(capabilities)
}
pub fn load_capabilities_for_set<C>(
conn: &mut C,
capability_set_id: Uuid,
) -> Result<Vec<ApiCapability>, AppError>
where
C: Connection<Backend = Pg> + diesel::connection::LoadConnection,
{
let mut capabilities: Vec<ApiCapability> = csc_dsl::capability_set_capabilities
.filter(csc_dsl::capability_set_id.eq(capability_set_id))
.select(csc_dsl::capability)
.load(conn)
.map_err(AppError::from)?;
capabilities.sort_by(|a, b| a.as_str().cmp(b.as_str()));
Ok(capabilities)
}
pub fn ensure_capability_set<C>(
conn: &mut C,
tenant_id: Uuid,
capabilities: &[ApiCapability],
) -> Result<CapabilitySet, AppError>
where
C: Connection<Backend = Pg> + diesel::connection::LoadConnection,
{
if capabilities.is_empty() {
return Err(AppError::bad_request("at least one capability is required"));
}
let slug = compute_slug(capabilities);
conn.transaction::<CapabilitySet, AppError, _>(|conn| {
if let Some(existing) = cs_dsl::capability_sets
.filter(cs_dsl::tenant_id.eq(tenant_id))
.filter(cs_dsl::slug.eq(&slug))
.first::<CapabilitySet>(conn)
.optional()
.map_err(AppError::from)?
{
ensure_capability_membership(conn, &existing, capabilities)?;
return Ok(existing);
}
let set = NewCapabilitySet {
id: Uuid::new_v4(),
tenant_id,
slug: slug.clone(),
cap_version: 1,
is_system: matches!(slug.as_str(), "owner" | "user" | "readonly" | "webdav"),
};
diesel::insert_into(capability_sets::table)
.values(&set)
.execute(conn)
.map_err(AppError::from)?;
persist_capabilities(conn, set.id, capabilities)?;
Ok(capability_sets::table
.find(set.id)
.first::<CapabilitySet>(conn)
.map_err(AppError::from)?)
})
}
pub fn refresh_capability_set<C>(
conn: &mut C,
set: &CapabilitySet,
capabilities: &[ApiCapability],
) -> Result<CapabilitySet, AppError>
where
C: Connection<Backend = Pg> + diesel::connection::LoadConnection,
{
conn.transaction::<CapabilitySet, AppError, _>(|conn| {
diesel::delete(
csc_dsl::capability_set_capabilities.filter(csc_dsl::capability_set_id.eq(set.id)),
)
.execute(conn)
.map_err(AppError::from)?;
persist_capabilities(conn, set.id, capabilities)?;
diesel::update(capability_sets::table.find(set.id))
.set((
cs_dsl::cap_version.eq(set.cap_version + 1),
cs_dsl::updated_at.eq(Utc::now().naive_utc()),
))
.execute(conn)
.map_err(AppError::from)?;
capability_sets::table
.find(set.id)
.first::<CapabilitySet>(conn)
.map_err(AppError::from)
})
}
pub fn load_capability_set<C>(conn: &mut C, id: Uuid) -> Result<CapabilitySet, AppError>
where
C: Connection<Backend = Pg> + diesel::connection::LoadConnection,
{
capability_sets::table
.find(id)
.first::<CapabilitySet>(conn)
.map_err(AppError::from)
}
pub fn compute_slug(capabilities: &[ApiCapability]) -> String {
if capabilities == owner_capabilities() {
return "owner".to_string();
}
if capabilities == user_capabilities() {
return "user".to_string();
}
if capabilities == readonly_capabilities() {
return "readonly".to_string();
}
if capabilities == webdav_capabilities() {
return "webdav".to_string();
}
let joined = capabilities
.iter()
.map(|cap| cap.as_str())
.collect::<Vec<_>>()
.join(",");
let digest = Sha256::digest(joined.as_bytes());
let hex = hex::encode(digest);
format!("caps-{}", &hex[..12])
}
fn ensure_capability_membership<C>(
conn: &mut C,
set: &CapabilitySet,
desired: &[ApiCapability],
) -> Result<(), AppError>
where
C: Connection<Backend = Pg> + diesel::connection::LoadConnection,
{
let current = load_capabilities_for_set(conn, set.id)?;
if current == desired {
return Ok(());
}
let _ = refresh_capability_set(conn, set, desired)?;
Ok(())
}
fn persist_capabilities<C>(
conn: &mut C,
set_id: Uuid,
capabilities: &[ApiCapability],
) -> Result<(), AppError>
where
C: Connection<Backend = Pg> + diesel::connection::LoadConnection,
{
if capabilities.is_empty() {
return Err(AppError::bad_request("at least one capability is required"));
}
let records: Vec<NewCapabilitySetCapability> = capabilities
.iter()
.map(|cap| NewCapabilitySetCapability {
capability_set_id: set_id,
capability: *cap,
})
.collect();
diesel::insert_into(capability_set_capabilities::table)
.values(&records)
.execute(conn)
.map_err(AppError::from)?;
Ok(())
}
+70 -8
View File
@@ -2,10 +2,29 @@ use anyhow::Result;
use chrono::{Duration, Utc}; use chrono::{Duration, Utc};
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation}; use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use uuid::Uuid; use uuid::Uuid;
use crate::config::AppConfig; use crate::config::AppConfig;
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum PrincipalKind {
UserSession,
ApiToken,
}
#[derive(Debug, Clone)]
pub struct AccessTokenContext {
pub user_id: Uuid,
pub tenant_id: Uuid,
pub username: String,
pub principal_kind: PrincipalKind,
pub principal_id: Uuid,
pub capability_set_id: Uuid,
pub cap_version: i32,
}
#[derive(Clone)] #[derive(Clone)]
pub struct JwtService { pub struct JwtService {
encoding: EncodingKey, encoding: EncodingKey,
@@ -23,28 +42,34 @@ pub struct JwtService {
impl JwtService { impl JwtService {
pub fn from_config(config: &AppConfig) -> Result<Self> { pub fn from_config(config: &AppConfig) -> Result<Self> {
let access_expiry = Duration::minutes(config.jwt_expiry_minutes);
Ok(Self { Ok(Self {
encoding: EncodingKey::from_secret(config.jwt_secret.as_bytes()), encoding: EncodingKey::from_secret(config.jwt_secret.as_bytes()),
decoding: DecodingKey::from_secret(config.jwt_secret.as_bytes()), decoding: DecodingKey::from_secret(config.jwt_secret.as_bytes()),
issuer: config.jwt_issuer.clone(), issuer: config.jwt_issuer.clone(),
audience: config.jwt_audience.clone(), audience: config.jwt_audience.clone(),
expiry: Duration::minutes(config.jwt_expiry_minutes), expiry: access_expiry,
download_audience: config.download_token_audience.clone(), download_audience: config.download_token_audience.clone(),
download_expiry: Duration::minutes(config.download_token_expiry_minutes), download_expiry: Duration::minutes(config.download_token_expiry_minutes),
selector_audience: format!("{}:tenant-selector", config.jwt_audience), selector_audience: format!("{}:tenant-selector", config.jwt_audience),
selector_expiry: Duration::minutes(15), selector_expiry: access_expiry,
signup_audience: format!("{}:signup", config.jwt_audience), signup_audience: format!("{}:signup", config.jwt_audience),
signup_expiry: Duration::minutes(15), signup_expiry: Duration::minutes(15),
}) })
} }
pub fn generate_token(&self, user_id: Uuid, tenant_id: Uuid, username: &str) -> Result<String> { pub fn generate_token(&self, context: AccessTokenContext) -> Result<String> {
let now = Utc::now(); let now = Utc::now();
let exp = now + self.expiry; let exp = now + self.expiry;
let claims = Claims { let claims = Claims {
sub: user_id, sub: context.user_id,
tenant_id, tenant_id: context.tenant_id,
username: username.to_owned(), username: context.username,
principal_kind: context.principal_kind,
principal_id: context.principal_id,
capability_set_id: context.capability_set_id,
cap_version: context.cap_version,
iss: self.issuer.clone(), iss: self.issuer.clone(),
aud: self.audience.clone(), aud: self.audience.clone(),
iat: now.timestamp() as usize, iat: now.timestamp() as usize,
@@ -65,13 +90,38 @@ impl JwtService {
pub fn generate_download_token( pub fn generate_download_token(
&self, &self,
document_id: Uuid, document_id: Uuid,
version_id: Uuid,
user_id: Uuid, user_id: Uuid,
tenant_id: Uuid, tenant_id: Uuid,
) -> Result<String> { ) -> Result<String> {
let now = Utc::now(); let now = Utc::now();
let exp = now + self.download_expiry; let exp = now + self.download_expiry;
let claims = DownloadClaims { let claims = DownloadClaims {
doc_id: document_id, subject: DownloadSubject::Document {
doc_id: document_id,
version_id,
},
user_id,
tenant_id,
iss: self.issuer.clone(),
aud: self.download_audience.clone(),
iat: now.timestamp() as usize,
exp: exp.timestamp() as usize,
};
Ok(encode(&Header::default(), &claims, &self.encoding)?)
}
pub fn generate_asset_download_token(
&self,
asset_id: Uuid,
user_id: Uuid,
tenant_id: Uuid,
) -> Result<String> {
let now = Utc::now();
let exp = now + self.download_expiry;
let claims = DownloadClaims {
subject: DownloadSubject::Asset { asset_id },
user_id, user_id,
tenant_id, tenant_id,
iss: self.issuer.clone(), iss: self.issuer.clone(),
@@ -148,15 +198,27 @@ pub struct Claims {
pub sub: Uuid, pub sub: Uuid,
pub tenant_id: Uuid, pub tenant_id: Uuid,
pub username: String, pub username: String,
pub principal_kind: PrincipalKind,
pub principal_id: Uuid,
pub capability_set_id: Uuid,
pub cap_version: i32,
pub iss: String, pub iss: String,
pub aud: String, pub aud: String,
pub iat: usize, pub iat: usize,
pub exp: usize, pub exp: usize,
} }
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "scope", rename_all = "snake_case")]
pub enum DownloadSubject {
Document { doc_id: Uuid, version_id: Uuid },
Asset { asset_id: Uuid },
}
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DownloadClaims { pub struct DownloadClaims {
pub doc_id: Uuid, #[serde(flatten)]
pub subject: DownloadSubject,
pub user_id: Uuid, pub user_id: Uuid,
pub tenant_id: Uuid, pub tenant_id: Uuid,
pub iss: String, pub iss: String,
+169 -38
View File
@@ -1,57 +1,153 @@
pub mod api_tokens;
pub mod capability_guard;
pub mod capability_sets;
pub mod jwt; pub mod jwt;
pub mod passkeys; pub mod passkeys;
pub mod password; pub mod password;
pub mod webdav_tokens;
use axum::{async_trait, extract::FromRequestParts, http::request::Parts}; use std::sync::{Arc, Mutex};
use axum::{
extract::FromRequestParts,
http::{request::Parts, StatusCode},
};
use axum_extra::headers::{authorization::Bearer, Authorization}; use axum_extra::headers::{authorization::Bearer, Authorization};
use axum_extra::TypedHeader; use axum_extra::TypedHeader;
use diesel::{pg::PgConnection, prelude::*};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::{ use crate::{
error::AppError, auth::capability_sets::{load_capabilities_for_set, load_capability_set},
error::{AppError, AppResult},
models::{ApiCapability, TenantStatus},
schema::tenants::dsl as tenant_dsl,
state::{AppState, PgPooledConnection}, state::{AppState, PgPooledConnection},
}; };
use uuid::Uuid; use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize)] use crate::auth::jwt::PrincipalKind;
#[derive(Debug, Clone)]
pub struct TenantMembershipUser {
pub user_id: Uuid,
}
impl FromRequestParts<AppState> for TenantMembershipUser {
type Rejection = AppError;
#[allow(refining_impl_trait)]
fn from_request_parts<'a>(
parts: &'a mut Parts,
state: &AppState,
) -> impl std::future::Future<Output = Result<Self, Self::Rejection>> + Send + 'a {
let state = state.clone();
async move {
let TypedHeader(Authorization(bearer)) =
TypedHeader::<Authorization<Bearer>>::from_request_parts(parts, &state)
.await
.map_err(|_| AppError::unauthorized())?;
if let Ok(claims) = state.jwt.verify_token(bearer.token()) {
return Ok(Self {
user_id: claims.sub,
});
}
let selector = state
.jwt
.verify_tenant_selector_token(bearer.token())
.map_err(|_| AppError::unauthorized())?;
Ok(Self {
user_id: selector.sub,
})
}
}
}
#[derive(Clone)]
pub struct TenantConnectionHolder {
inner: Arc<Mutex<Option<PgPooledConnection>>>,
}
impl TenantConnectionHolder {
pub fn new(conn: PgPooledConnection) -> Self {
Self {
inner: Arc::new(Mutex::new(Some(conn))),
}
}
pub fn into_conn(self) -> Option<PgPooledConnection> {
self.inner.lock().ok()?.take()
}
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct AuthenticatedUser { pub struct AuthenticatedUser {
pub user_id: uuid::Uuid, pub user_id: uuid::Uuid,
pub username: String, pub username: String,
pub tenant_id: uuid::Uuid, pub tenant_id: uuid::Uuid,
pub principal_kind: PrincipalKind,
pub principal_id: Uuid,
pub capability_set_id: Uuid,
pub cap_version: i32,
pub capabilities: Vec<ApiCapability>,
} }
#[async_trait]
impl FromRequestParts<AppState> for AuthenticatedUser { impl FromRequestParts<AppState> for AuthenticatedUser {
type Rejection = AppError; type Rejection = AppError;
async fn from_request_parts( #[allow(refining_impl_trait)]
parts: &mut Parts, fn from_request_parts<'a>(
parts: &'a mut Parts,
state: &AppState, state: &AppState,
) -> Result<Self, Self::Rejection> { ) -> impl std::future::Future<Output = Result<Self, Self::Rejection>> + Send + 'a {
if let Some(user) = parts.extensions.get::<AuthenticatedUser>() { let state = state.clone();
return Ok(user.clone()); async move {
} if let Some(user) = parts.extensions.get::<AuthenticatedUser>() {
return Ok(user.clone());
}
let TypedHeader(Authorization(bearer)) = let TypedHeader(Authorization(bearer)) =
TypedHeader::<Authorization<Bearer>>::from_request_parts(parts, state) TypedHeader::<Authorization<Bearer>>::from_request_parts(parts, &state)
.await .await
.map_err(|_| AppError::unauthorized())?;
let claims = state
.jwt
.verify_token(bearer.token())
.map_err(|_| AppError::unauthorized())?; .map_err(|_| AppError::unauthorized())?;
let claims = state let mut tenant_conn = state.db_for_tenant(claims.tenant_id)?;
.jwt let capability_set = load_capability_set(&mut tenant_conn, claims.capability_set_id)
.verify_token(bearer.token()) .map_err(|_| AppError::unauthorized())?;
.map_err(|_| AppError::unauthorized())?;
let user = AuthenticatedUser { if capability_set.cap_version != claims.cap_version {
user_id: claims.sub, return Err(AppError::unauthorized());
username: claims.username, }
tenant_id: claims.tenant_id,
};
parts.extensions.insert(user.clone()); let capabilities = load_capabilities_for_set(&mut tenant_conn, capability_set.id)
.map_err(|_| AppError::unauthorized())?;
Ok(user) let user = AuthenticatedUser {
user_id: claims.sub,
username: claims.username,
tenant_id: claims.tenant_id,
principal_kind: claims.principal_kind,
principal_id: claims.principal_id,
capability_set_id: claims.capability_set_id,
cap_version: claims.cap_version,
capabilities,
};
parts.extensions.insert(user.clone());
parts
.extensions
.insert(TenantConnectionHolder::new(tenant_conn));
Ok(user)
}
} }
} }
@@ -68,23 +164,58 @@ impl TenantScopedConn {
} }
} }
#[async_trait]
impl FromRequestParts<AppState> for TenantScopedConn { impl FromRequestParts<AppState> for TenantScopedConn {
type Rejection = AppError; type Rejection = AppError;
async fn from_request_parts( #[allow(refining_impl_trait)]
parts: &mut Parts, fn from_request_parts<'a>(
parts: &'a mut Parts,
state: &AppState, state: &AppState,
) -> Result<Self, Self::Rejection> { ) -> impl std::future::Future<Output = Result<Self, Self::Rejection>> + Send + 'a {
let user = AuthenticatedUser::from_request_parts(parts, state).await?; let state = state.clone();
let tenant_id = user.tenant_id; async move {
let conn = state.db_for_tenant(tenant_id)?; let user = AuthenticatedUser::from_request_parts(parts, &state).await?;
let tenant_id = user.tenant_id;
let mut conn = if let Some(holder) = parts.extensions.remove::<TenantConnectionHolder>()
{
holder
.into_conn()
.ok_or_else(|| AppError::internal("tenant connection unavailable"))?
} else {
state.db_for_tenant(tenant_id)?
};
Ok(Self { ensure_active_tenant_with_conn(&mut conn, tenant_id)?;
conn,
tenant_id, Ok(Self {
user_id: user.user_id, conn,
user, tenant_id,
}) user_id: user.user_id,
user,
})
}
} }
} }
pub(crate) fn ensure_active_tenant(state: &AppState, tenant_id: Uuid) -> AppResult<()> {
let mut conn = state.db_unscoped()?;
ensure_active_tenant_with_conn(&mut conn, tenant_id)
}
pub(crate) fn ensure_active_tenant_with_conn(
conn: &mut PgConnection,
tenant_id: Uuid,
) -> AppResult<()> {
use tenant_dsl::tenants;
let status: TenantStatus = tenants
.find(tenant_id)
.select(tenant_dsl::status)
.first(conn)?;
if status != TenantStatus::Active {
return Err(AppError::new(StatusCode::FORBIDDEN, "tenant is not active"));
}
Ok(())
}
+82 -160
View File
@@ -56,6 +56,7 @@ impl PreparedPasskey {
pub struct RegistrationChallengeResponse { pub struct RegistrationChallengeResponse {
pub challenge_id: Uuid, pub challenge_id: Uuid,
#[serde(flatten)] #[serde(flatten)]
#[schema(value_type = Object)]
pub challenge: CreationChallengeResponse, pub challenge: CreationChallengeResponse,
} }
@@ -64,6 +65,7 @@ pub struct RegistrationChallengeResponse {
pub struct AuthenticationChallengeResponse { pub struct AuthenticationChallengeResponse {
pub challenge_id: Uuid, pub challenge_id: Uuid,
#[serde(flatten)] #[serde(flatten)]
#[schema(value_type = Object)]
pub challenge: RequestChallengeResponse, pub challenge: RequestChallengeResponse,
} }
@@ -116,13 +118,55 @@ impl PasskeyService {
.execute(conn); .execute(conn);
} }
fn begin_registration(
&self,
conn: &mut PgConnection,
user_id: Uuid,
username: &str,
challenge_user_id: Option<Uuid>,
exclude: Option<Vec<CredentialID>>,
) -> AppResult<RegistrationChallengeResponse> {
self.prune_expired(conn);
let (challenge, state) = self
.webauthn
.start_passkey_registration(user_id, username, username, exclude)
.map_err(|err| {
tracing::error!(error = %err, "failed to start passkey registration");
AppError::internal("failed to start passkey registration")
})?;
let challenge_id = Uuid::new_v4();
let expires_at = (Utc::now() + self.challenge_ttl).naive_utc();
let challenge_bytes: Vec<u8> = challenge.public_key.challenge.clone().into();
let state_bytes = serde_json::to_vec(&state)
.context("failed to encode passkey registration state")
.map_err(AppError::internal)?;
let record = NewWebauthnChallenge {
id: challenge_id,
user_id: challenge_user_id,
purpose: PURPOSE_REGISTRATION.to_string(),
challenge: challenge_bytes,
state: state_bytes,
expires_at,
};
diesel::insert_into(challenge_dsl::webauthn_challenges)
.values(&record)
.execute(conn)?;
Ok(RegistrationChallengeResponse {
challenge_id,
challenge,
})
}
pub fn start_registration( pub fn start_registration(
&self, &self,
conn: &mut PgConnection, conn: &mut PgConnection,
user: &User, user: &User,
) -> AppResult<RegistrationChallengeResponse> { ) -> AppResult<RegistrationChallengeResponse> {
self.prune_expired(conn);
let existing: Vec<UserPasskey> = passkey_dsl::user_passkeys let existing: Vec<UserPasskey> = passkey_dsl::user_passkeys
.filter(passkey_dsl::user_id.eq(user.id)) .filter(passkey_dsl::user_id.eq(user.id))
.filter(passkey_dsl::revoked_at.is_null()) .filter(passkey_dsl::revoked_at.is_null())
@@ -139,38 +183,7 @@ impl PasskeyService {
) )
}; };
let (challenge, state) = self self.begin_registration(conn, user.id, &user.username, Some(user.id), exclude)
.webauthn
.start_passkey_registration(user.id, &user.username, &user.username, exclude)
.map_err(|err| {
tracing::error!(error = %err, "failed to start passkey registration");
AppError::internal("failed to start passkey registration")
})?;
let challenge_id = Uuid::new_v4();
let expires_at = (Utc::now() + self.challenge_ttl).naive_utc();
let challenge_bytes: Vec<u8> = challenge.public_key.challenge.clone().into();
let state_bytes = serde_json::to_vec(&state)
.context("failed to encode passkey registration state")
.map_err(AppError::internal)?;
let record = NewWebauthnChallenge {
id: challenge_id,
user_id: Some(user.id),
purpose: PURPOSE_REGISTRATION.to_string(),
challenge: challenge_bytes,
state: state_bytes,
expires_at,
};
diesel::insert_into(challenge_dsl::webauthn_challenges)
.values(&record)
.execute(conn)?;
Ok(RegistrationChallengeResponse {
challenge_id,
challenge,
})
} }
pub fn start_signup_registration( pub fn start_signup_registration(
@@ -179,50 +192,16 @@ impl PasskeyService {
user_id: Uuid, user_id: Uuid,
username: &str, username: &str,
) -> AppResult<RegistrationChallengeResponse> { ) -> AppResult<RegistrationChallengeResponse> {
self.prune_expired(conn); self.begin_registration(conn, user_id, username, None, None)
let (challenge, state) = self
.webauthn
.start_passkey_registration(user_id, username, username, None)
.map_err(|err| {
tracing::error!(error = %err, "failed to start passkey registration");
AppError::internal("failed to start passkey registration")
})?;
let challenge_id = Uuid::new_v4();
let expires_at = (Utc::now() + self.challenge_ttl).naive_utc();
let challenge_bytes: Vec<u8> = challenge.public_key.challenge.clone().into();
let state_bytes = serde_json::to_vec(&state)
.context("failed to encode passkey registration state")
.map_err(AppError::internal)?;
let record = NewWebauthnChallenge {
id: challenge_id,
user_id: None,
purpose: PURPOSE_REGISTRATION.to_string(),
challenge: challenge_bytes,
state: state_bytes,
expires_at,
};
diesel::insert_into(challenge_dsl::webauthn_challenges)
.values(&record)
.execute(conn)?;
Ok(RegistrationChallengeResponse {
challenge_id,
challenge,
})
} }
pub fn finish_registration( fn complete_registration(
&self, &self,
conn: &mut PgConnection, conn: &mut PgConnection,
user: &User,
challenge_id: Uuid, challenge_id: Uuid,
credential: RegisterPublicKeyCredential, credential: &RegisterPublicKeyCredential,
nickname: Option<String>, expected_user: Option<Uuid>,
) -> AppResult<UserPasskey> { ) -> AppResult<PreparedPasskey> {
let record: WebauthnChallenge = challenge_dsl::webauthn_challenges let record: WebauthnChallenge = challenge_dsl::webauthn_challenges
.find(challenge_id) .find(challenge_id)
.first(conn) .first(conn)
@@ -238,8 +217,14 @@ impl PasskeyService {
return Err(AppError::bad_request("challenge is not for registration")); return Err(AppError::bad_request("challenge is not for registration"));
} }
if record.user_id != Some(user.id) { if let Some(expected) = expected_user {
return Err(AppError::unauthorized()); if record.user_id != Some(expected) {
return Err(AppError::unauthorized());
}
} else if record.user_id.is_some() {
return Err(AppError::bad_request(
"unexpected user context for signup registration",
));
} }
if record.expires_at < Utc::now().naive_utc() { if record.expires_at < Utc::now().naive_utc() {
@@ -253,7 +238,7 @@ impl PasskeyService {
let passkey = self let passkey = self
.webauthn .webauthn
.finish_passkey_registration(&credential, &state) .finish_passkey_registration(credential, &state)
.map_err(|err| { .map_err(|err| {
tracing::warn!(error = %err, "passkey registration validation failed"); tracing::warn!(error = %err, "passkey registration validation failed");
AppError::bad_request("invalid passkey attestation") AppError::bad_request("invalid passkey attestation")
@@ -294,24 +279,36 @@ impl PasskeyService {
.context("failed to serialise passkey") .context("failed to serialise passkey")
.map_err(AppError::internal)?; .map_err(AppError::internal)?;
let new_passkey = NewUserPasskey { diesel::delete(challenge_dsl::webauthn_challenges.find(challenge_id)).execute(conn)?;
Ok(PreparedPasskey {
id: Uuid::new_v4(), id: Uuid::new_v4(),
user_id: user.id,
credential_id: credential_id_vec, credential_id: credential_id_vec,
public_key: public_key_bytes, public_key: public_key_bytes,
credential: credential_json, credential: credential_json,
sign_count: credential_struct.counter as i64, sign_count: credential_struct.counter as i64,
transports, transports,
aaguid, aaguid,
nickname, })
}; }
pub fn finish_registration(
&self,
conn: &mut PgConnection,
user: &User,
challenge_id: Uuid,
credential: RegisterPublicKeyCredential,
nickname: Option<String>,
) -> AppResult<UserPasskey> {
let prepared =
self.complete_registration(conn, challenge_id, &credential, Some(user.id))?;
let new_passkey = prepared.into_new_user_passkey(user.id, nickname);
diesel::insert_into(passkey_dsl::user_passkeys) diesel::insert_into(passkey_dsl::user_passkeys)
.values(&new_passkey) .values(&new_passkey)
.execute(conn)?; .execute(conn)?;
diesel::delete(challenge_dsl::webauthn_challenges.find(challenge_id)).execute(conn)?;
let created: UserPasskey = passkey_dsl::user_passkeys let created: UserPasskey = passkey_dsl::user_passkeys
.find(new_passkey.id) .find(new_passkey.id)
.select(UserPasskey::as_select()) .select(UserPasskey::as_select())
@@ -408,84 +405,7 @@ impl PasskeyService {
challenge_id: Uuid, challenge_id: Uuid,
credential: &RegisterPublicKeyCredential, credential: &RegisterPublicKeyCredential,
) -> AppResult<PreparedPasskey> { ) -> AppResult<PreparedPasskey> {
let record: WebauthnChallenge = challenge_dsl::webauthn_challenges self.complete_registration(conn, challenge_id, credential, None)
.find(challenge_id)
.first(conn)
.map_err(|err| {
if matches!(err, diesel::result::Error::NotFound) {
AppError::bad_request("challenge not found")
} else {
AppError::from(err)
}
})?;
if record.purpose != PURPOSE_REGISTRATION {
return Err(AppError::bad_request("challenge is not for registration"));
}
if record.expires_at < Utc::now().naive_utc() {
diesel::delete(challenge_dsl::webauthn_challenges.find(challenge_id)).execute(conn)?;
return Err(AppError::bad_request("challenge expired"));
}
let state: PasskeyRegistration = serde_json::from_slice(&record.state)
.context("failed to decode registration state")
.map_err(AppError::internal)?;
let passkey = self
.webauthn
.finish_passkey_registration(credential, &state)
.map_err(|err| {
tracing::warn!(error = %err, "passkey registration validation failed");
AppError::bad_request("invalid passkey attestation")
})?;
let credential_struct: Credential = passkey.clone().into();
let credential_id_vec: Vec<u8> = credential_struct.cred_id.clone().into();
let duplicate = passkey_dsl::user_passkeys
.filter(passkey_dsl::credential_id.eq(&credential_id_vec))
.first::<UserPasskey>(conn)
.optional()?;
if duplicate.is_some() {
diesel::delete(challenge_dsl::webauthn_challenges.find(challenge_id)).execute(conn)?;
return Err(AppError::conflict("credential already registered"));
}
let public_key_bytes = serde_cbor_2::to_vec(&credential_struct.cred)
.context("failed to encode credential public key")
.map_err(AppError::internal)?;
let transports: Vec<Option<String>> = credential_struct
.transports
.clone()
.unwrap_or_default()
.into_iter()
.map(|transport| Some(transport.as_ref().to_string()))
.collect();
let aaguid = match credential_struct.attestation.metadata {
AttestationMetadata::Packed { aaguid } | AttestationMetadata::Tpm { aaguid, .. } => {
Some(aaguid)
}
_ => None,
};
let credential_json = serde_json::to_value(&passkey)
.context("failed to serialise passkey")
.map_err(AppError::internal)?;
diesel::delete(challenge_dsl::webauthn_challenges.find(challenge_id)).execute(conn)?;
Ok(PreparedPasskey {
id: Uuid::new_v4(),
credential_id: credential_id_vec,
public_key: public_key_bytes,
credential: credential_json,
sign_count: credential_struct.counter as i64,
transports,
aaguid,
})
} }
pub fn revoke_passkey( pub fn revoke_passkey(
@@ -651,6 +571,7 @@ impl From<UserPasskey> for PasskeySummary {
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct PasskeyRegistrationFinishPayload { pub struct PasskeyRegistrationFinishPayload {
pub challenge_id: Uuid, pub challenge_id: Uuid,
#[schema(value_type = Object)]
pub credential: RegisterPublicKeyCredential, pub credential: RegisterPublicKeyCredential,
#[serde(default)] #[serde(default)]
pub nickname: Option<String>, pub nickname: Option<String>,
@@ -666,5 +587,6 @@ pub struct PasskeyLoginStartPayload {
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct PasskeyLoginFinishPayload { pub struct PasskeyLoginFinishPayload {
pub challenge_id: Uuid, pub challenge_id: Uuid,
#[schema(value_type = Object)]
pub credential: PublicKeyCredential, pub credential: PublicKeyCredential,
} }
+6 -3
View File
@@ -1,9 +1,11 @@
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
use argon2::{ use argon2::{
password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString}, password_hash::{
rand_core::OsRng as PasswordHashOsRng, PasswordHash, PasswordHasher, PasswordVerifier,
SaltString,
},
Argon2, Argon2,
}; };
use rand::rngs::OsRng;
pub fn verify_password(password: &str, password_hash: &str) -> Result<bool> { pub fn verify_password(password: &str, password_hash: &str) -> Result<bool> {
let parsed_hash = PasswordHash::new(password_hash).map_err(|err| anyhow!(err))?; let parsed_hash = PasswordHash::new(password_hash).map_err(|err| anyhow!(err))?;
@@ -13,7 +15,8 @@ pub fn verify_password(password: &str, password_hash: &str) -> Result<bool> {
} }
pub fn hash_password(password: &str) -> Result<String> { pub fn hash_password(password: &str) -> Result<String> {
let salt = SaltString::generate(&mut OsRng); let mut rng = PasswordHashOsRng;
let salt = SaltString::generate(&mut rng);
let hash = Argon2::default() let hash = Argon2::default()
.hash_password(password.as_bytes(), &salt) .hash_password(password.as_bytes(), &salt)
.map_err(|err| anyhow!(err))?; .map_err(|err| anyhow!(err))?;
-190
View File
@@ -1,190 +0,0 @@
use argon2::{
password_hash::{PasswordHasher, SaltString},
Argon2,
};
use chrono::{NaiveDateTime, Utc};
use diesel::prelude::*;
use rand::rngs::OsRng;
use rand::RngCore;
use uuid::Uuid;
use crate::{
error::AppError,
models::{NewWebdavToken, WebdavToken},
schema::webdav_tokens,
state::PgPooledConnection,
};
const TOKEN_PREFIX_LENGTH: usize = 12;
const TOKEN_SECRET_LENGTH: usize = 32;
pub struct IssuedWebdavToken {
pub token: String,
pub record: WebdavToken,
}
pub fn create_webdav_token(
conn: &mut PgPooledConnection,
user_id: Uuid,
tenant_id: Uuid,
label: Option<String>,
expires_at: Option<NaiveDateTime>,
) -> Result<IssuedWebdavToken, AppError> {
let raw_secret = generate_secret()?;
let token_prefix = raw_secret[..TOKEN_PREFIX_LENGTH].to_string();
let token_hash = hash_secret(&raw_secret)?;
let new_token = NewWebdavToken {
id: Uuid::new_v4(),
user_id,
tenant_id,
token_prefix,
token_hash,
label,
expires_at,
};
let record = diesel::insert_into(webdav_tokens::table)
.values(&new_token)
.get_result::<WebdavToken>(conn)?;
Ok(IssuedWebdavToken {
token: raw_secret,
record,
})
}
pub fn list_webdav_tokens(
conn: &mut PgPooledConnection,
user_id: Uuid,
tenant_id: Option<Uuid>,
) -> Result<Vec<WebdavToken>, AppError> {
let mut query = webdav_tokens::table
.filter(webdav_tokens::user_id.eq(user_id))
.into_boxed();
if let Some(tenant_id) = tenant_id {
query = query.filter(webdav_tokens::tenant_id.eq(tenant_id));
}
let tokens = query
.order(webdav_tokens::created_at.asc())
.load::<WebdavToken>(conn)?;
Ok(tokens)
}
pub fn find_active_token_by_secret(
conn: &mut PgPooledConnection,
user_id: Uuid,
tenant_id: Option<Uuid>,
secret: &str,
) -> Result<Option<WebdavToken>, AppError> {
if secret.len() < TOKEN_PREFIX_LENGTH {
return Ok(None);
}
let prefix = &secret[..TOKEN_PREFIX_LENGTH];
let mut query = webdav_tokens::table
.filter(webdav_tokens::user_id.eq(user_id))
.filter(webdav_tokens::token_prefix.eq(prefix))
.filter(webdav_tokens::revoked_at.is_null())
.into_boxed();
let now = Utc::now().naive_utc();
query = query.filter(
webdav_tokens::expires_at
.is_null()
.or(webdav_tokens::expires_at.gt(now)),
);
if let Some(tenant_id) = tenant_id {
query = query.filter(webdav_tokens::tenant_id.eq(tenant_id));
}
let candidates = query.load::<WebdavToken>(conn)?;
for token in candidates {
if verify_token_secret(secret, &token.token_hash)? {
return Ok(Some(token));
}
}
Ok(None)
}
pub fn revoke_webdav_token(
conn: &mut PgPooledConnection,
token_id: Uuid,
user_id: Uuid,
) -> Result<(), AppError> {
let affected = diesel::update(
webdav_tokens::table
.filter(webdav_tokens::id.eq(token_id))
.filter(webdav_tokens::user_id.eq(user_id)),
)
.set(webdav_tokens::revoked_at.eq(Utc::now().naive_utc()))
.execute(conn)?;
if affected == 0 {
return Err(AppError::not_found());
}
Ok(())
}
pub fn touch_webdav_token(conn: &mut PgPooledConnection, token_id: Uuid) -> Result<(), AppError> {
diesel::update(webdav_tokens::table.filter(webdav_tokens::id.eq(token_id)))
.set(webdav_tokens::last_used_at.eq(Utc::now().naive_utc()))
.execute(conn)?;
Ok(())
}
pub fn verify_token_secret(secret: &str, token_hash: &str) -> Result<bool, AppError> {
crate::auth::password::verify_password(secret, token_hash).map_err(|err| {
tracing::error!(error = ?err, "failed to verify token");
AppError::internal("failed to verify token")
})
}
fn generate_secret() -> Result<String, AppError> {
let mut buffer = [0u8; TOKEN_SECRET_LENGTH];
OsRng.try_fill_bytes(&mut buffer).map_err(|err| {
tracing::error!(error = ?err, "failed to generate token");
AppError::internal("failed to generate token")
})?;
Ok(hex::encode(buffer))
}
fn hash_secret(secret: &str) -> Result<String, AppError> {
let salt = SaltString::generate(&mut OsRng);
let hash = Argon2::default()
.hash_password(secret.as_bytes(), &salt)
.map_err(|err| {
tracing::error!(error = ?err, "failed to hash token");
AppError::internal("failed to hash token")
})?;
Ok(hash.to_string())
}
fn _ensure_constants() {
assert!(TOKEN_PREFIX_LENGTH < TOKEN_SECRET_LENGTH * 2);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn generated_secret_has_expected_length() {
let secret = generate_secret().unwrap();
assert_eq!(secret.len(), TOKEN_SECRET_LENGTH * 2);
}
#[test]
fn hash_and_verify_secret_round_trip() {
let secret = generate_secret().unwrap();
let hash = hash_secret(&secret).unwrap();
assert!(verify_token_secret(&secret, &hash).unwrap());
assert!(!verify_token_secret("wrong", &hash).unwrap());
}
}
+471 -140
View File
@@ -1,29 +1,47 @@
use std::env;
use std::sync::Arc; use std::sync::Arc;
use anyhow::{anyhow, bail, Context, Result}; use anyhow::{anyhow, bail, Context, Result};
use diesel::{dsl::exists, prelude::*, select}; use chrono::{Duration as ChronoDuration, Utc};
use clap::{Parser, Subcommand, ValueEnum};
use diesel::{dsl::exists, pg::PgConnection, prelude::*, select};
use diesel_migrations::MigrationHarness;
use rand::{rngs::OsRng, TryRngCore};
use reqwest::{Client, Method, StatusCode}; use reqwest::{Client, Method, StatusCode};
use sha2::{Digest, Sha256};
use tokio::task;
use uuid::Uuid; use uuid::Uuid;
use backend::{ use papercrate::{
config::AppConfig, auth::capability_sets::{ensure_capability_set, owner_capabilities},
config::{redact_database_url, AppConfig},
db::{self, PgPool}, db::{self, PgPool},
documents::search::ensure_quickwit_index, documents::search::ensure_quickwit_index,
jobs::{enqueue_job, JOB_ANALYZE_DOCUMENT}, jobs::{enqueue_job, JOB_ANALYZE_DOCUMENT, JOB_DELETE_TENANT},
migrations::MIGRATIONS,
models::{ models::{
DocumentAsset, DocumentAssetObject, NewUser, NewUserMembership, Tenant, TenantStatus, User, DocumentAsset, MagicToken, MagicTokenKind, NewUser, NewUserMembership, Tenant,
TenantStatus, User,
}, },
s3, s3,
schema::{ schema::{document_assets, documents, magic_tokens, tenants, user_memberships, users},
document_asset_objects, document_assets, documents, tenants, user_memberships, users,
},
storage::{ObjectStorage, S3Storage, TenantStorage}, storage::{ObjectStorage, S3Storage, TenantStorage},
tenants::TenantService, tenants::{apply_tenant_guc, clear_tenant_context, TenantService},
utils::tracing::init_tracing, utils::{text::normalize_identifier, tracing::init_tracing},
workers::tenants::{build_delete_proof_message, sign_delete_proof, DeleteAction},
}; };
#[derive(Debug)] #[derive(Parser)]
#[command(
name = "papercrate-admin",
version,
about = "Papercrate administration utility"
)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command { enum Command {
CreateUser { CreateUser {
username: String, username: String,
@@ -34,11 +52,22 @@ enum Command {
}, },
CreateTenant { CreateTenant {
name: String, name: String,
#[arg(long = "storage-root")]
storage_root: Option<String>, storage_root: Option<String>,
#[arg(long = "quickwit-index")]
quickwit_index: Option<String>, quickwit_index: Option<String>,
}, },
DeleteTenant { DeleteTenant {
tenant_id: Uuid, tenant_id: Uuid,
#[arg(long = "tenant-name")]
tenant_name: String,
},
ResetTenant {
tenant_id: Uuid,
#[arg(long = "tenant-name")]
tenant_name: String,
#[arg(long = "final-status", value_enum, default_value_t = TenantFinalStatusArg::Active)]
final_status: TenantFinalStatusArg,
}, },
AddUserToTenant { AddUserToTenant {
username: String, username: String,
@@ -52,71 +81,79 @@ enum Command {
tenant_id: Uuid, tenant_id: Uuid,
}, },
ListTenants, ListTenants,
DeleteAssets(Uuid), DeleteAssets {
QuickwitCreate(Uuid), tenant_id: Uuid,
QuickwitDelete(Uuid), #[arg(long = "asset-type")]
asset_type: Option<String>,
#[arg(long = "all", help = "Confirm deleting every asset for the tenant")]
delete_all: bool,
},
QuickwitCreate {
tenant_id: Uuid,
},
QuickwitDelete {
tenant_id: Uuid,
},
EnqueueDeleteTenant {
tenant_id: Uuid,
#[arg(long = "tenant-name")]
tenant_name: String,
#[arg(long = "remove-tenant")]
remove_tenant: bool,
#[arg(long = "final-status", value_enum)]
final_status: Option<TenantFinalStatusArg>,
},
MagicToken {
username: String,
#[arg(long = "ttl-minutes", default_value_t = 10)]
ttl_minutes: i64,
#[arg(
long = "max-uses",
value_name = "MAX_USES",
help = "Maximum number of uses before the token is rejected (default: unlimited)"
)]
max_uses: Option<i32>,
#[arg(long = "kind", value_enum, default_value_t = MagicTokenKindArg::EmailLogin)]
kind: MagicTokenKindArg,
},
MigrateDatabase {
#[arg(
long = "database-url",
value_name = "URL",
help = "Override the migrations database URL (defaults to MIGRATIONS_DATABASE_URL or DATABASE_URL)"
)]
database_url: Option<String>,
},
} }
impl Command { #[derive(Copy, Clone, Debug, ValueEnum)]
fn usage() -> &'static str { enum MagicTokenKindArg {
"Usage: admin\n\ #[value(name = "email_login")]
create-user <username>\n\ EmailLogin,
list-users\n\ #[value(name = "demo_login")]
delete-user <username>\n\ DemoLogin,
create-tenant <name> [storage_root] [quickwit_index]\n\ }
delete-tenant <tenant-id>\n\
add-user-to-tenant <username> <tenant-id>\n\
remove-user-from-tenant <username> <tenant-id>\n\
reanalyze-documents <tenant-id>\n\
list-tenants\n\
delete-assets <tenant-id>\n\
quickwit-create-index <tenant-id>\n\
quickwit-delete-index <tenant-id>"
}
fn parse_tenant_id(arg: Option<String>) -> Result<Uuid> { impl From<MagicTokenKindArg> for MagicTokenKind {
let raw = arg.ok_or_else(|| anyhow!("tenant id required"))?; fn from(value: MagicTokenKindArg) -> Self {
Uuid::parse_str(&raw).map_err(|_| anyhow!("invalid tenant id: {}", raw)) match value {
MagicTokenKindArg::EmailLogin => MagicTokenKind::EmailLogin,
MagicTokenKindArg::DemoLogin => MagicTokenKind::DemoLogin,
}
} }
}
fn parse() -> Result<Self> { #[derive(Copy, Clone, Debug, ValueEnum)]
let mut args = env::args().skip(1); enum TenantFinalStatusArg {
match args.next().as_deref() { Active,
Some("create-user") => Ok(Self::CreateUser { Suspended,
username: args.next().ok_or_else(|| anyhow!("username required"))?, }
}),
Some("list-users") => Ok(Self::ListUsers), impl TenantFinalStatusArg {
Some("delete-user") => Ok(Self::DeleteUser { fn as_str(&self) -> &'static str {
username: args.next().ok_or_else(|| anyhow!("username required"))?, match self {
}), TenantFinalStatusArg::Active => "active",
Some("create-tenant") => Ok(Self::CreateTenant { TenantFinalStatusArg::Suspended => "suspended",
name: args.next().ok_or_else(|| anyhow!("tenant name required"))?,
storage_root: args.next(),
quickwit_index: args.next(),
}),
Some("delete-tenant") => Ok(Self::DeleteTenant {
tenant_id: Self::parse_tenant_id(args.next())?,
}),
Some("add-user-to-tenant") => Ok(Self::AddUserToTenant {
username: args.next().ok_or_else(|| anyhow!("username required"))?,
tenant_id: Self::parse_tenant_id(args.next())?,
}),
Some("remove-user-from-tenant") => Ok(Self::RemoveUserFromTenant {
username: args.next().ok_or_else(|| anyhow!("username required"))?,
tenant_id: Self::parse_tenant_id(args.next())?,
}),
Some("reanalyze-documents") => Ok(Self::ReanalyzeDocuments {
tenant_id: Self::parse_tenant_id(args.next())?,
}),
Some("list-tenants") => Ok(Self::ListTenants),
Some("delete-assets") => Ok(Self::DeleteAssets(Self::parse_tenant_id(args.next())?)),
Some("quickwit-create-index") => {
Ok(Self::QuickwitCreate(Self::parse_tenant_id(args.next())?))
}
Some("quickwit-delete-index") => {
Ok(Self::QuickwitDelete(Self::parse_tenant_id(args.next())?))
}
_ => Err(anyhow!(Self::usage())),
} }
} }
} }
@@ -124,11 +161,11 @@ impl Command {
#[tokio::main] #[tokio::main]
async fn main() -> Result<()> { async fn main() -> Result<()> {
init_tracing("info"); init_tracing("info");
let command = Command::parse()?; let cli = Cli::parse();
let config = AppConfig::load_and_log("admin")?; let config = AppConfig::load_and_log("admin")?;
let pool = db::init_pool_with_size(&config.database_url, config.database_max_pool_size)?; let pool = db::init_pool_with_size(&config.database_url, config.database_max_pool_size)?;
match command { match cli.command {
Command::CreateUser { username } => create_user(&pool, &username)?, Command::CreateUser { username } => create_user(&pool, &username)?,
Command::ListUsers => list_users(&pool)?, Command::ListUsers => list_users(&pool)?,
Command::DeleteUser { username } => delete_user(&pool, &username)?, Command::DeleteUser { username } => delete_user(&pool, &username)?,
@@ -137,7 +174,15 @@ async fn main() -> Result<()> {
storage_root, storage_root,
quickwit_index, quickwit_index,
} => create_tenant(&pool, &name, storage_root, quickwit_index)?, } => create_tenant(&pool, &name, storage_root, quickwit_index)?,
Command::DeleteTenant { tenant_id } => delete_tenant(&pool, tenant_id)?, Command::DeleteTenant {
tenant_id,
tenant_name,
} => delete_tenant(&config, &pool, tenant_id, &tenant_name)?,
Command::ResetTenant {
tenant_id,
tenant_name,
final_status,
} => reset_tenant(&config, &pool, tenant_id, &tenant_name, final_status)?,
Command::AddUserToTenant { Command::AddUserToTenant {
username, username,
tenant_id, tenant_id,
@@ -148,35 +193,94 @@ async fn main() -> Result<()> {
} => remove_user_from_tenant(&pool, &username, tenant_id)?, } => remove_user_from_tenant(&pool, &username, tenant_id)?,
Command::ReanalyzeDocuments { tenant_id } => reanalyze_documents(&pool, tenant_id)?, Command::ReanalyzeDocuments { tenant_id } => reanalyze_documents(&pool, tenant_id)?,
Command::ListTenants => list_tenants(&pool)?, Command::ListTenants => list_tenants(&pool)?,
Command::DeleteAssets(tenant_id) => { Command::DeleteAssets {
delete_assets_for_tenant(&config, &pool, tenant_id).await? tenant_id,
asset_type,
delete_all,
} => {
let asset_type = asset_type.as_deref();
if asset_type.is_none() && !delete_all {
bail!("refusing to delete all assets without --all confirmation");
}
delete_assets_for_tenant(&config, &pool, tenant_id, asset_type).await?
} }
Command::QuickwitCreate(tenant_id) => { Command::QuickwitCreate { tenant_id } => {
quickwit_index(&config, &pool, tenant_id, Method::POST).await? quickwit_index(&config, &pool, tenant_id, Method::POST).await?
} }
Command::QuickwitDelete(tenant_id) => { Command::QuickwitDelete { tenant_id } => {
quickwit_index(&config, &pool, tenant_id, Method::DELETE).await? quickwit_index(&config, &pool, tenant_id, Method::DELETE).await?
} }
Command::EnqueueDeleteTenant {
tenant_id,
tenant_name,
remove_tenant,
final_status,
} => enqueue_delete_tenant_job(
&config,
&pool,
tenant_id,
&tenant_name,
remove_tenant,
final_status,
)?,
Command::MagicToken {
username,
ttl_minutes,
max_uses,
kind,
} => {
create_magic_token(&pool, &username, ttl_minutes, max_uses, kind.into())?;
}
Command::MigrateDatabase { database_url } => {
let url = database_url.unwrap_or_else(|| config.migrations_database_url().to_string());
migrate_database(url).await?;
}
} }
Ok(()) Ok(())
} }
async fn migrate_database(database_url: String) -> Result<()> {
let redacted = redact_database_url(&database_url);
tracing::info!(database_url = %redacted, "running pending migrations");
let result = task::spawn_blocking(move || -> Result<()> {
let mut conn =
PgConnection::establish(&database_url).context("failed to connect to database")?;
conn.run_pending_migrations(MIGRATIONS)
.map_err(|err| anyhow!("failed to run migrations: {err}"))?;
Ok(())
})
.await
.context("migration task panicked")?;
result?;
tracing::info!(database_url = %redacted, "migrations completed");
Ok(())
}
fn create_user(pool: &PgPool, username: &str) -> Result<()> { fn create_user(pool: &PgPool, username: &str) -> Result<()> {
if username.trim().is_empty() { let username = normalize_identifier(
bail!("username must not be empty"); username,
} 100,
"username must not be empty",
"username must not exceed 100 characters",
Some("username may only contain printable characters"),
|ch| !ch.is_control(),
)
.map_err(|err| anyhow!("{:?}", err))?;
let mut conn = pool.get().context("failed to get database connection")?; let mut conn = pool.get().context("failed to get database connection")?;
let exists: bool = let exists: bool =
select(exists(users::table.filter(users::username.eq(username)))).get_result(&mut conn)?; select(exists(users::table.filter(users::username.eq(&username)))).get_result(&mut conn)?;
if exists { if exists {
bail!("user '{}' already exists", username); bail!("user '{}' already exists", username);
} }
let new_user = NewUser { let new_user = NewUser {
id: Uuid::new_v4(), id: Uuid::new_v4(),
username: username.to_string(), username: username.clone(),
}; };
diesel::insert_into(users::table) diesel::insert_into(users::table)
@@ -228,8 +332,17 @@ fn delete_user(pool: &PgPool, username: &str) -> Result<()> {
.optional()? .optional()?
.ok_or_else(|| anyhow!("user '{}' not found", username))?; .ok_or_else(|| anyhow!("user '{}' not found", username))?;
diesel::delete(user_memberships::table.filter(user_memberships::user_id.eq(user.id))) let has_memberships: bool = select(exists(
.execute(&mut conn)?; user_memberships::table.filter(user_memberships::user_id.eq(user.id)),
))
.get_result(&mut conn)?;
if has_memberships {
bail!(
"user '{}' is still a member of one or more tenants; remove memberships first",
username
);
}
diesel::delete(users::table.filter(users::id.eq(user.id))).execute(&mut conn)?; diesel::delete(users::table.filter(users::id.eq(user.id))).execute(&mut conn)?;
println!("deleted user '{}'", username); println!("deleted user '{}'", username);
@@ -268,7 +381,113 @@ fn create_tenant(
Ok(()) Ok(())
} }
fn delete_tenant(pool: &PgPool, tenant_id: Uuid) -> Result<()> { fn create_magic_token(
pool: &PgPool,
username: &str,
ttl_minutes: i64,
max_uses: Option<i32>,
kind: MagicTokenKind,
) -> Result<()> {
let mut conn = pool.get().context("failed to get database connection")?;
let user: User = users::table
.filter(users::username.eq(username))
.first(&mut conn)
.with_context(|| format!("user '{}' not found", username))?;
let raw_token = generate_random_token();
let token_hash = hash_token(&raw_token);
let expires_at = Utc::now() + ChronoDuration::minutes(ttl_minutes);
let new_token = MagicToken {
id: Uuid::new_v4(),
user_id: user.id,
kind,
token_hash,
metadata: serde_json::json!({}),
expires_at: expires_at.naive_utc(),
max_uses,
used_count: 0,
created_at: Utc::now().naive_utc(),
created_by: None,
last_used_at: None,
};
diesel::insert_into(magic_tokens::table)
.values(&new_token)
.execute(&mut conn)?;
println!(
"Magic token created for '{}' (kind: {}, expires_at: {}, max_uses: {})",
username,
kind.as_str(),
expires_at,
max_uses.map_or("".to_string(), |v| v.to_string())
);
println!("Token: {}", raw_token);
Ok(())
}
fn generate_random_token() -> String {
let mut bytes = [0u8; 32];
OsRng
.try_fill_bytes(&mut bytes)
.expect("failed to read random bytes");
hex::encode(bytes)
}
fn hash_token(token: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(token.as_bytes());
hex::encode(hasher.finalize())
}
fn delete_tenant(
config: &AppConfig,
pool: &PgPool,
tenant_id: Uuid,
tenant_name: &str,
) -> Result<()> {
enqueue_delete_tenant_job_internal(config, pool, tenant_id, tenant_name, true, None)?;
println!(
"delete job enqueued; tenant '{}' will be permanently removed",
tenant_name
);
Ok(())
}
fn reset_tenant(
config: &AppConfig,
pool: &PgPool,
tenant_id: Uuid,
tenant_name: &str,
final_status: TenantFinalStatusArg,
) -> Result<()> {
enqueue_delete_tenant_job_internal(
config,
pool,
tenant_id,
tenant_name,
false,
Some(final_status),
)?;
println!(
"reset job enqueued; tenant '{}' will be wiped and set to {}",
tenant_name,
final_status.as_str()
);
Ok(())
}
fn enqueue_delete_tenant_job_internal(
config: &AppConfig,
pool: &PgPool,
tenant_id: Uuid,
expected_name: &str,
remove_tenant: bool,
final_status: Option<TenantFinalStatusArg>,
) -> Result<()> {
let mut conn = pool.get().context("failed to get database connection")?; let mut conn = pool.get().context("failed to get database connection")?;
let tenant: Tenant = tenants::table let tenant: Tenant = tenants::table
@@ -277,19 +496,100 @@ fn delete_tenant(pool: &PgPool, tenant_id: Uuid) -> Result<()> {
.optional()? .optional()?
.ok_or_else(|| anyhow!("tenant '{}' not found", tenant_id))?; .ok_or_else(|| anyhow!("tenant '{}' not found", tenant_id))?;
let member_exists: bool = select(exists( apply_tenant_guc(&mut conn, tenant.id)
user_memberships::table.filter(user_memberships::tenant_id.eq(tenant.id)), .map_err(|err| anyhow!("failed to set tenant context for {}: {err:?}", tenant.name))?;
))
.get_result(&mut conn)?; if tenant.name != expected_name {
if member_exists { bail!(
bail!("tenant '{}' still has user memberships", tenant.name); "tenant name mismatch: expected '{}', database has '{}'",
expected_name,
tenant.name
);
} }
diesel::delete(tenants::table.filter(tenants::id.eq(tenant.id))).execute(&mut conn)?; diesel::update(tenants::table.find(tenant.id))
println!("deleted tenant '{}'", tenant.name); .set(tenants::status.eq(TenantStatus::Deleting))
.execute(&mut conn)?;
let nonce = generate_random_token();
let issued_at = Utc::now();
let issued_at_str = issued_at.to_rfc3339();
let action = if remove_tenant {
DeleteAction::Delete
} else {
DeleteAction::Reset
};
let resolved_final_status = if remove_tenant {
None
} else {
Some(
final_status
.unwrap_or(TenantFinalStatusArg::Suspended)
.as_str(),
)
};
let message = build_delete_proof_message(
tenant.id,
expected_name,
action,
&nonce,
&issued_at_str,
resolved_final_status,
);
let signature = sign_delete_proof(&config.jwt_secret, &message).map_err(|err| anyhow!(err))?;
let mut payload = serde_json::json!({
"remove_tenant": remove_tenant,
"tenant_name": tenant.name.clone(),
"action": action.as_str(),
"nonce": nonce,
"issued_at": issued_at_str,
"signature": signature,
});
if let Some(status) = resolved_final_status {
payload["final_status"] = serde_json::json!(status);
}
enqueue_job(&mut conn, tenant.id, JOB_DELETE_TENANT, payload, None)?;
let status_label = if remove_tenant {
"deleted"
} else {
final_status.map(|s| s.as_str()).unwrap_or("suspended")
};
println!(
"delete-tenant job enqueued for '{}' (remove_tenant={}, final_status={})",
tenant.name, remove_tenant, status_label
);
clear_tenant_context(&mut conn).map_err(|err| {
anyhow!(
"failed to clear tenant context for {}: {err:?}",
tenant.name
)
})?;
Ok(()) Ok(())
} }
fn enqueue_delete_tenant_job(
config: &AppConfig,
pool: &PgPool,
tenant_id: Uuid,
tenant_name: &str,
remove_tenant: bool,
final_status: Option<TenantFinalStatusArg>,
) -> Result<()> {
enqueue_delete_tenant_job_internal(
config,
pool,
tenant_id,
tenant_name,
remove_tenant,
final_status,
)
}
fn add_user_to_tenant(pool: &PgPool, username: &str, tenant_id: Uuid) -> Result<()> { fn add_user_to_tenant(pool: &PgPool, username: &str, tenant_id: Uuid) -> Result<()> {
let mut conn = pool.get().context("failed to get database connection")?; let mut conn = pool.get().context("failed to get database connection")?;
@@ -305,10 +605,15 @@ fn add_user_to_tenant(pool: &PgPool, username: &str, tenant_id: Uuid) -> Result<
.optional()? .optional()?
.ok_or_else(|| anyhow!("tenant '{}' not found", tenant_id))?; .ok_or_else(|| anyhow!("tenant '{}' not found", tenant_id))?;
let owner_capability_set_id = ensure_capability_set(&mut conn, tenant.id, owner_capabilities())
.map_err(|err| anyhow!("failed to ensure owner capability set: {:?}", err))?
.id;
let membership = NewUserMembership { let membership = NewUserMembership {
id: Uuid::new_v4(), id: Uuid::new_v4(),
user_id: user.id, user_id: user.id,
tenant_id: tenant.id, tenant_id: tenant.id,
capability_set_id: Some(owner_capability_set_id),
}; };
diesel::insert_into(user_memberships::table) diesel::insert_into(user_memberships::table)
@@ -421,10 +726,10 @@ async fn delete_assets_for_tenant(
config: &AppConfig, config: &AppConfig,
pool: &PgPool, pool: &PgPool,
tenant_id: Uuid, tenant_id: Uuid,
asset_type: Option<&str>,
) -> Result<()> { ) -> Result<()> {
let s3_client = s3::build_client(config).await?; let bucket = s3::build_bucket(config)?;
let storage: Arc<dyn ObjectStorage> = let storage: Arc<dyn ObjectStorage> = Arc::new(S3Storage::new(bucket));
Arc::new(S3Storage::new(s3_client, config.s3_bucket.clone()));
let mut conn = pool.get().context("failed to get database connection")?; let mut conn = pool.get().context("failed to get database connection")?;
let tenant: Tenant = tenants::table let tenant: Tenant = tenants::table
@@ -433,57 +738,83 @@ async fn delete_assets_for_tenant(
.optional()? .optional()?
.ok_or_else(|| anyhow!("tenant '{}' not found", tenant_id))?; .ok_or_else(|| anyhow!("tenant '{}' not found", tenant_id))?;
let tenant_storage = TenantStorage::new(Arc::clone(&storage), &tenant) apply_tenant_guc(&mut conn, tenant.id)
.with_context(|| format!("missing storage root for tenant {}", tenant.name))?; .map_err(|err| anyhow!("failed to set tenant context for {}: {err:?}", tenant.name))?;
let assets: Vec<DocumentAsset> = document_assets::table let result = async {
.filter(document_assets::tenant_id.eq(tenant.id)) let tenant_storage = TenantStorage::new(Arc::clone(&storage), &tenant)
.load(&mut conn) .with_context(|| format!("missing storage root for tenant {}", tenant.name))?;
.with_context(|| format!("failed to load assets for tenant {}", tenant.name))?;
if assets.is_empty() { let mut asset_query = document_assets::table
println!("Tenant {}: no assets", tenant.name); .filter(document_assets::tenant_id.eq(tenant.id))
return Ok(()); .into_boxed();
}
println!( if let Some(asset_type) = asset_type {
"Tenant {} ({}): deleting {} assets…", asset_query = asset_query.filter(document_assets::asset_type.eq(asset_type));
tenant.name,
tenant.id,
assets.len()
);
let asset_ids: Vec<Uuid> = assets.iter().map(|asset| asset.id).collect();
let objects: Vec<DocumentAssetObject> = document_asset_objects::table
.filter(document_asset_objects::tenant_id.eq(tenant.id))
.filter(document_asset_objects::asset_id.eq_any(&asset_ids))
.load(&mut conn)
.with_context(|| format!("failed to load asset objects for tenant {}", tenant.name))?;
for object in &objects {
if let Err(err) = tenant_storage.delete_object(&object.s3_key).await {
eprintln!(
"Failed to delete object {} (tenant {}): {err}",
object.s3_key, tenant.name
);
} }
}
diesel::delete( let assets: Vec<DocumentAsset> = asset_query
document_asset_objects::table .load(&mut conn)
.filter(document_asset_objects::tenant_id.eq(tenant.id)) .with_context(|| format!("failed to load assets for tenant {}", tenant.name))?;
.filter(document_asset_objects::asset_id.eq_any(&asset_ids)),
)
.execute(&mut conn)
.with_context(|| format!("failed to remove asset objects for tenant {}", tenant.name))?;
diesel::delete(document_assets::table.filter(document_assets::tenant_id.eq(tenant.id))) if assets.is_empty() {
match asset_type {
Some(asset_type) => {
println!("Tenant {}: no assets of type '{}'", tenant.name, asset_type)
}
None => println!("Tenant {}: no assets", tenant.name),
}
return Ok(());
}
match asset_type {
Some(asset_type) => println!(
"Tenant {} ({}): deleting {} '{}' assets…",
tenant.name,
tenant.id,
assets.len(),
asset_type
),
None => println!(
"Tenant {} ({}): deleting {} assets…",
tenant.name,
tenant.id,
assets.len()
),
}
let asset_ids: Vec<Uuid> = assets.iter().map(|asset| asset.id).collect();
for asset in &assets {
if let Err(err) = tenant_storage.delete_object(&asset.s3_key).await {
eprintln!(
"Failed to delete object {} (tenant {}): {err}",
asset.s3_key, tenant.name
);
}
}
diesel::delete(
document_assets::table
.filter(document_assets::tenant_id.eq(tenant.id))
.filter(document_assets::id.eq_any(&asset_ids)),
)
.execute(&mut conn) .execute(&mut conn)
.with_context(|| format!("failed to remove asset records for tenant {}", tenant.name))?; .with_context(|| format!("failed to remove asset records for tenant {}", tenant.name))?;
println!("Tenant {}: asset records deleted.", tenant.name); println!("Tenant {}: asset records deleted.", tenant.name);
Ok(()) Ok(())
}
.await;
clear_tenant_context(&mut conn).map_err(|err| {
anyhow!(
"failed to clear tenant context for {}: {err:?}",
tenant.name
)
})?;
result
} }
async fn quickwit_index( async fn quickwit_index(
+1 -1
View File
@@ -1,4 +1,4 @@
use backend::openapi::ApiDoc; use papercrate::openapi::ApiDoc;
use utoipa::OpenApi; use utoipa::OpenApi;
fn main() { fn main() {
+1 -1
View File
@@ -3,7 +3,7 @@ use std::net::SocketAddr;
use tokio::net::TcpListener; use tokio::net::TcpListener;
use tower::make::Shared; use tower::make::Shared;
use backend::{routes::webdav, utils::bootstrap::init_component}; use papercrate::{routes::webdav, utils::bootstrap::init_component};
#[tokio::main] #[tokio::main]
async fn main() -> anyhow::Result<()> { async fn main() -> anyhow::Result<()> {
+1 -1
View File
@@ -2,7 +2,7 @@ use std::time::Duration;
use tokio::signal; use tokio::signal;
use backend::{default_handlers, utils::bootstrap::init_component, Worker}; use papercrate::{default_handlers, utils::bootstrap::init_component, Worker};
#[tokio::main] #[tokio::main]
async fn main() -> anyhow::Result<()> { async fn main() -> anyhow::Result<()> {
+76 -1
View File
@@ -1,6 +1,7 @@
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use url::Url; use url::Url;
use serde::de::Deserializer;
use serde::Deserialize; use serde::Deserialize;
use serde_aux::field_attributes::deserialize_bool_from_anything; use serde_aux::field_attributes::deserialize_bool_from_anything;
@@ -9,6 +10,8 @@ use crate::db::DEFAULT_MAX_POOL_SIZE;
#[derive(Clone, Debug, Deserialize)] #[derive(Clone, Debug, Deserialize)]
pub struct AppConfig { pub struct AppConfig {
pub database_url: String, pub database_url: String,
#[serde(default)]
pub migrations_database_url: Option<String>,
#[serde(default = "default_database_max_pool_size")] #[serde(default = "default_database_max_pool_size")]
pub database_max_pool_size: u32, pub database_max_pool_size: u32,
#[serde(default = "default_server_host")] #[serde(default = "default_server_host")]
@@ -41,6 +44,8 @@ pub struct AppConfig {
pub refresh_cookie_domain: Option<String>, pub refresh_cookie_domain: Option<String>,
#[serde(default)] #[serde(default)]
pub cors_allowed_origin: Option<String>, pub cors_allowed_origin: Option<String>,
#[serde(default, deserialize_with = "deserialize_bool_from_anything")]
pub proxy_downloads: bool,
#[serde(default)] #[serde(default)]
pub aws_endpoint_url: Option<String>, pub aws_endpoint_url: Option<String>,
#[serde(default)] #[serde(default)]
@@ -58,6 +63,16 @@ pub struct AppConfig {
pub worker_max_document_bytes: u64, pub worker_max_document_bytes: u64,
#[serde(default = "default_upload_body_limit_bytes")] #[serde(default = "default_upload_body_limit_bytes")]
pub upload_body_limit_bytes: u64, pub upload_body_limit_bytes: u64,
#[serde(default = "default_service_timezone")]
pub service_timezone: String,
#[serde(default = "default_issued_at_date_order")]
pub issued_at_date_order: String,
#[serde(default)]
pub issued_at_filename_date_order: Option<String>,
#[serde(default, deserialize_with = "deserialize_string_list")]
pub issued_at_date_parser_locales: Vec<String>,
#[serde(default, deserialize_with = "deserialize_string_list")]
pub issued_at_ignore_dates: Vec<String>,
#[serde(default)] #[serde(default)]
pub webauthn_rp_id: Option<String>, pub webauthn_rp_id: Option<String>,
#[serde(default)] #[serde(default)]
@@ -73,12 +88,14 @@ impl AppConfig {
tracing::info!( tracing::info!(
component, component,
database_url = %config.redacted_database_url(), database_url = %config.redacted_database_url(),
migrations_database_url = %config.redacted_migrations_database_url(),
pool_size = config.database_max_pool_size, pool_size = config.database_max_pool_size,
quickwit_enabled = config.quickwit_endpoint.is_some(), quickwit_enabled = config.quickwit_endpoint.is_some(),
passkeys_enabled = config.webauthn_origin.is_some(), passkeys_enabled = config.webauthn_origin.is_some(),
s3_bucket = %config.s3_bucket, s3_bucket = %config.s3_bucket,
worker_max_document_bytes = config.worker_max_document_bytes, worker_max_document_bytes = config.worker_max_document_bytes,
upload_body_limit_bytes = config.upload_body_limit_bytes, upload_body_limit_bytes = config.upload_body_limit_bytes,
proxy_downloads = config.proxy_downloads,
"loaded backend configuration" "loaded backend configuration"
); );
Ok(config) Ok(config)
@@ -93,6 +110,18 @@ impl AppConfig {
pub fn redacted_database_url(&self) -> String { pub fn redacted_database_url(&self) -> String {
redact_database_url(&self.database_url) redact_database_url(&self.database_url)
} }
pub fn redacted_migrations_database_url(&self) -> String {
redact_database_url(self.migrations_database_url())
}
pub fn migrations_database_url(&self) -> &str {
if let Some(ref url) = self.migrations_database_url {
url
} else {
&self.database_url
}
}
} }
impl AppConfig { impl AppConfig {
@@ -180,11 +209,57 @@ fn default_upload_body_limit_bytes() -> u64 {
128 * 1024 * 1024 128 * 1024 * 1024
} }
fn default_service_timezone() -> String {
"UTC".to_string()
}
fn default_issued_at_date_order() -> String {
"DMY".to_string()
}
fn deserialize_string_list<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum Helper {
List(Vec<String>),
Single(String),
}
let helper = Option::<Helper>::deserialize(deserializer)?;
let mut values = Vec::new();
if let Some(helper) = helper {
match helper {
Helper::List(list) => {
for entry in list {
let trimmed = entry.trim();
if !trimmed.is_empty() {
values.push(trimmed.to_string());
}
}
}
Helper::Single(value) => {
for part in value.split(',') {
let trimmed = part.trim();
if !trimmed.is_empty() {
values.push(trimmed.to_string());
}
}
}
}
}
Ok(values)
}
fn default_webauthn_rp_name() -> String { fn default_webauthn_rp_name() -> String {
"Papercrate".to_string() "Papercrate".to_string()
} }
fn redact_database_url(raw: &str) -> String { pub fn redact_database_url(raw: &str) -> String {
match Url::parse(raw) { match Url::parse(raw) {
Ok(mut parsed) => { Ok(mut parsed) => {
if parsed.password().is_some() { if parsed.password().is_some() {
+30 -1
View File
@@ -1,12 +1,40 @@
use std::time::Duration; use std::time::Duration;
use diesel::pg::PgConnection; use diesel::pg::PgConnection;
use diesel::r2d2::{ConnectionManager, Pool}; use diesel::r2d2::{ConnectionManager, CustomizeConnection, Pool};
use diesel::RunQueryDsl;
pub type PgPool = Pool<ConnectionManager<PgConnection>>; pub type PgPool = Pool<ConnectionManager<PgConnection>>;
pub const DEFAULT_MAX_POOL_SIZE: u32 = 2; pub const DEFAULT_MAX_POOL_SIZE: u32 = 2;
#[derive(Debug)]
struct SchemaCustomizer;
impl CustomizeConnection<PgConnection, diesel::r2d2::Error> for SchemaCustomizer {
fn on_acquire(&self, conn: &mut PgConnection) -> Result<(), diesel::r2d2::Error> {
diesel::sql_query(
"SELECT set_config('search_path', (
SELECT string_agg(schema_name, ', ')
FROM (
SELECT 'tenant' AS schema_name WHERE EXISTS (
SELECT 1 FROM pg_namespace WHERE nspname = 'tenant'
)
UNION ALL
SELECT 'shared' AS schema_name WHERE EXISTS (
SELECT 1 FROM pg_namespace WHERE nspname = 'shared'
)
UNION ALL
SELECT 'public' AS schema_name
) AS schemas
), false)",
)
.execute(conn)
.map(|_| ())
.map_err(diesel::r2d2::Error::QueryError)
}
}
pub fn init_pool(database_url: &str) -> anyhow::Result<PgPool> { pub fn init_pool(database_url: &str) -> anyhow::Result<PgPool> {
init_pool_with_size(database_url, DEFAULT_MAX_POOL_SIZE) init_pool_with_size(database_url, DEFAULT_MAX_POOL_SIZE)
} }
@@ -17,6 +45,7 @@ pub fn init_pool_with_size(database_url: &str, max_size: u32) -> anyhow::Result<
let pool = Pool::builder() let pool = Pool::builder()
.max_size(pool_size) .max_size(pool_size)
.connection_timeout(Duration::from_secs(10)) .connection_timeout(Duration::from_secs(10))
.connection_customizer(Box::new(SchemaCustomizer))
.build(manager)?; .build(manager)?;
Ok(pool) Ok(pool)
} }
+58 -81
View File
@@ -1,6 +1,7 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::path::Path as FsPath; use std::path::Path as FsPath;
use chrono::{Duration as ChronoDuration, Utc};
use diesel::prelude::*; use diesel::prelude::*;
use serde::Serialize; use serde::Serialize;
use serde_json::Value; use serde_json::Value;
@@ -8,30 +9,27 @@ use utoipa::ToSchema;
use uuid::Uuid; use uuid::Uuid;
use crate::error::{AppError, AppResult}; use crate::error::{AppError, AppResult};
use crate::models::{Document, DocumentAsset, DocumentAssetObject, DocumentVersion}; use crate::models::{Document, DocumentAsset, DocumentVersion};
use crate::schema::{document_asset_objects, document_assets, document_versions}; use crate::schema::{document_assets, document_versions};
use crate::state::AppState; use crate::state::{AppState, PgPooledConnection};
use crate::utils::time::to_iso; use crate::utils::{http::inline_content_disposition, time::to_iso};
#[derive(Serialize, Clone, ToSchema)]
pub struct DownloadLink {
pub url: String,
pub expires_at: i64,
}
#[derive(Serialize, Clone, ToSchema)] #[derive(Serialize, Clone, ToSchema)]
pub struct DocumentAssetResponse { pub struct DocumentAssetResponse {
pub id: Uuid, pub id: Uuid,
pub asset_type: String, pub asset_type: String,
pub mime_type: String, pub mime_type: String,
#[schema(value_type = Object)]
pub metadata: Value, pub metadata: Value,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub cardinality: Option<i32>, #[schema(nullable)]
} pub download: Option<DownloadLink>,
#[derive(Serialize, Clone, ToSchema)]
pub struct DocumentAssetObjectResponse {
pub id: Uuid,
pub ordinal: i32,
pub metadata: Value,
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub expires_at: Option<i64>,
} }
#[derive(Serialize, ToSchema)] #[derive(Serialize, ToSchema)]
@@ -39,12 +37,12 @@ pub struct DocumentAssetDetailResponse {
pub id: Uuid, pub id: Uuid,
pub asset_type: String, pub asset_type: String,
pub mime_type: String, pub mime_type: String,
#[schema(value_type = Object)]
pub metadata: Value, pub metadata: Value,
pub created_at: String, pub created_at: String,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub cardinality: Option<i32>, #[schema(nullable)]
#[serde(default, skip_serializing_if = "Vec::is_empty")] pub download: Option<DownloadLink>,
pub objects: Vec<DocumentAssetObjectResponse>,
} }
#[derive(Serialize, Clone, ToSchema)] #[derive(Serialize, Clone, ToSchema)]
@@ -54,6 +52,7 @@ pub struct DocumentVersionResponse {
pub size_bytes: i64, pub size_bytes: i64,
pub checksum: String, pub checksum: String,
pub created_at: String, pub created_at: String,
#[schema(value_type = Object)]
pub metadata: Value, pub metadata: Value,
} }
@@ -63,22 +62,35 @@ pub struct DocumentVersionDetailResponse {
pub version: DocumentVersionResponse, pub version: DocumentVersionResponse,
#[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde(default, skip_serializing_if = "Vec::is_empty")]
pub assets: Vec<DocumentAssetResponse>, pub assets: Vec<DocumentAssetResponse>,
pub download_path: String, pub download: DownloadLink,
} }
pub fn build_download_path( pub fn build_download_link(
state: &AppState, state: &AppState,
document: &Document, document: &Document,
version_id: Uuid,
user_id: Uuid, user_id: Uuid,
) -> AppResult<String> { ) -> AppResult<DownloadLink> {
state state
.jwt .jwt
.generate_download_token(document.id, user_id, document.tenant_id) .generate_download_token(document.id, version_id, user_id, document.tenant_id)
.map(|token| format!("/download/{token}"))
.map_err(|err| { .map_err(|err| {
tracing::error!(error = ?err, "failed to generate download token"); tracing::error!(error = ?err, "failed to generate download token");
AppError::internal("failed to generate download token") AppError::internal("failed to generate download token")
}) })
.and_then(|token| {
let expires_at = Utc::now()
.checked_add_signed(ChronoDuration::minutes(
state.config.download_token_expiry_minutes,
))
.ok_or_else(|| AppError::internal("failed to compute download expiry"))?
.timestamp_millis();
Ok(DownloadLink {
url: format!("/api/download/{token}"),
expires_at,
})
})
} }
pub fn to_version_response(version: DocumentVersion) -> DocumentVersionResponse { pub fn to_version_response(version: DocumentVersion) -> DocumentVersionResponse {
@@ -98,13 +110,13 @@ pub fn to_asset_summary(asset: DocumentAsset) -> DocumentAssetResponse {
asset_type: asset.asset_type, asset_type: asset.asset_type,
mime_type: asset.mime_type, mime_type: asset.mime_type,
metadata: asset.metadata, metadata: asset.metadata,
cardinality: asset.cardinality, download: None,
} }
} }
pub fn to_asset_detail_response( pub fn to_asset_detail_response(
asset: DocumentAsset, asset: DocumentAsset,
objects: Vec<DocumentAssetObjectResponse>, download: Option<DownloadLink>,
) -> DocumentAssetDetailResponse { ) -> DocumentAssetDetailResponse {
DocumentAssetDetailResponse { DocumentAssetDetailResponse {
id: asset.id, id: asset.id,
@@ -112,69 +124,46 @@ pub fn to_asset_detail_response(
mime_type: asset.mime_type, mime_type: asset.mime_type,
metadata: asset.metadata, metadata: asset.metadata,
created_at: to_iso(asset.created_at), created_at: to_iso(asset.created_at),
cardinality: asset.cardinality, download,
objects,
} }
} }
pub fn to_asset_object_response( pub fn asset_disposition(asset: &DocumentAsset) -> Option<String> {
object: DocumentAssetObject, let filename = asset.asset_type.clone();
url: Option<String>, inline_content_disposition(&filename)
expires_at: Option<i64>,
) -> DocumentAssetObjectResponse {
DocumentAssetObjectResponse {
id: object.id,
ordinal: object.ordinal,
metadata: object.metadata,
url,
expires_at,
}
} }
pub fn delete_asset(state: &AppState, tenant_id: Uuid, asset_id: Uuid) -> AppResult<()> { pub fn delete_asset(
let mut conn = state.db_for_tenant(tenant_id)?; conn: &mut PgPooledConnection,
tenant_id: Uuid,
asset_id: Uuid,
) -> AppResult<()> {
diesel::delete( diesel::delete(
document_assets::table document_assets::table
.filter(document_assets::id.eq(asset_id)) .filter(document_assets::id.eq(asset_id))
.filter(document_assets::tenant_id.eq(tenant_id)), .filter(document_assets::tenant_id.eq(tenant_id)),
) )
.execute(&mut conn)?; .execute(conn)?;
Ok(()) Ok(())
} }
pub async fn load_asset_responses( pub fn load_asset_responses_with_conn(
state: &AppState, conn: &mut PgPooledConnection,
tenant_id: Uuid, tenant_id: Uuid,
version_id: Uuid, version_id: Uuid,
) -> AppResult<Vec<DocumentAssetResponse>> { ) -> AppResult<Vec<DocumentAssetResponse>> {
let mut conn = state.db_for_tenant(tenant_id)?; let assets: Vec<DocumentAsset> = document_assets::table
let assets: Vec<(DocumentAsset, Option<DocumentAssetObject>)> = document_assets::table
.left_outer_join(
document_asset_objects::table.on(document_asset_objects::asset_id
.eq(document_assets::id)
.and(document_asset_objects::ordinal.eq(1))),
)
.filter(document_assets::document_version_id.eq(version_id)) .filter(document_assets::document_version_id.eq(version_id))
.filter(document_assets::tenant_id.eq(tenant_id)) .filter(document_assets::tenant_id.eq(tenant_id))
.order(document_assets::created_at.asc()) .order(document_assets::created_at.asc())
.select(( .load(conn)?;
document_assets::all_columns,
document_asset_objects::all_columns.nullable(),
))
.load(&mut conn)?;
drop(conn);
Ok(assets Ok(assets.into_iter().map(to_asset_summary).collect())
.into_iter()
.map(|(asset, _)| to_asset_summary(asset))
.collect())
} }
pub fn load_primary_assets( pub fn load_primary_assets(
state: &AppState, conn: &mut PgPooledConnection,
tenant_id: Uuid,
documents: &[Document], documents: &[Document],
) -> AppResult<HashMap<Uuid, (DocumentVersionResponse, Vec<DocumentAssetResponse>)>> { ) -> AppResult<HashMap<Uuid, (DocumentVersionResponse, Vec<DocumentAssetResponse>)>> {
if documents.is_empty() { if documents.is_empty() {
@@ -191,37 +180,25 @@ pub fn load_primary_assets(
version_ids.sort(); version_ids.sort();
version_ids.dedup(); version_ids.dedup();
let mut conn = state.db_for_tenant(tenant_id)?;
let versions: Vec<DocumentVersion> = document_versions::table let versions: Vec<DocumentVersion> = document_versions::table
.filter(document_versions::id.eq_any(&version_ids)) .filter(document_versions::id.eq_any(&version_ids))
.load(&mut conn)?; .load(conn)?;
let mut version_map: HashMap<Uuid, DocumentVersion> = HashMap::new(); let mut version_map: HashMap<Uuid, DocumentVersion> = HashMap::new();
for version in versions { for version in versions {
version_map.insert(version.id, version); version_map.insert(version.id, version);
} }
let assets: Vec<(DocumentAsset, Option<DocumentAssetObject>)> = document_assets::table let assets: Vec<DocumentAsset> = document_assets::table
.left_outer_join(
document_asset_objects::table.on(document_asset_objects::asset_id
.eq(document_assets::id)
.and(document_asset_objects::ordinal.eq(1))),
)
.filter(document_assets::document_version_id.eq_any(&version_ids)) .filter(document_assets::document_version_id.eq_any(&version_ids))
.order(( .order((
document_assets::document_version_id.asc(), document_assets::document_version_id.asc(),
document_assets::created_at.asc(), document_assets::created_at.asc(),
)) ))
.select(( .load(conn)?;
document_assets::all_columns,
document_asset_objects::all_columns.nullable(),
))
.load(&mut conn)?;
drop(conn);
let mut assets_by_version: HashMap<Uuid, Vec<DocumentAssetResponse>> = HashMap::new(); let mut assets_by_version: HashMap<Uuid, Vec<DocumentAssetResponse>> = HashMap::new();
for (asset, _object) in assets { for asset in assets {
let version_id = asset.document_version_id; let version_id = asset.document_version_id;
let response = to_asset_summary(asset); let response = to_asset_summary(asset);
assets_by_version assets_by_version
+1
View File
@@ -16,6 +16,7 @@ use crate::utils::time::to_iso;
pub struct DocumentCorrespondentResponse { pub struct DocumentCorrespondentResponse {
pub id: Uuid, pub id: Uuid,
pub name: String, pub name: String,
#[schema(value_type = Object)]
pub metadata: Value, pub metadata: Value,
pub assigned_at: String, pub assigned_at: String,
} }
+4
View File
@@ -2,5 +2,9 @@ pub mod asset;
pub mod correspondents; pub mod correspondents;
pub mod folders; pub mod folders;
pub mod metadata; pub mod metadata;
pub mod ordering;
pub mod relations;
pub mod search; pub mod search;
pub mod tags; pub mod tags;
pub use ordering::{DocumentSortField, SortDirection};
+58
View File
@@ -0,0 +1,58 @@
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
pub const UNICODE_COLLATION_NAME: &str = "unicode_ci";
pub const UNICODE_COLLATION_LOCALE: &str = "und-u-ks-level2";
const TITLE_ASC: &str = "title COLLATE \"unicode_ci\" ASC";
const TITLE_DESC: &str = "title COLLATE \"unicode_ci\" DESC";
const ISSUED_AT_ASC: &str = "issued_at ASC NULLS LAST";
const ISSUED_AT_DESC: &str = "issued_at DESC NULLS LAST";
const CREATED_AT_ASC: &str = "created_at ASC";
const CREATED_AT_DESC: &str = "created_at DESC";
const UPDATED_AT_ASC: &str = "updated_at ASC";
const UPDATED_AT_DESC: &str = "updated_at DESC";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum DocumentSortField {
Title,
IssuedAt,
CreatedAt,
UpdatedAt,
}
impl Default for DocumentSortField {
fn default() -> Self {
DocumentSortField::Title
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum SortDirection {
Asc,
Desc,
}
impl Default for SortDirection {
fn default() -> Self {
SortDirection::Asc
}
}
pub fn ordering_clauses(
field: DocumentSortField,
direction: SortDirection,
) -> (&'static str, Option<&'static str>) {
match (field, direction) {
(DocumentSortField::Title, SortDirection::Asc) => (TITLE_ASC, None),
(DocumentSortField::Title, SortDirection::Desc) => (TITLE_DESC, None),
(DocumentSortField::IssuedAt, SortDirection::Asc) => (ISSUED_AT_ASC, Some(TITLE_ASC)),
(DocumentSortField::IssuedAt, SortDirection::Desc) => (ISSUED_AT_DESC, Some(TITLE_ASC)),
(DocumentSortField::CreatedAt, SortDirection::Asc) => (CREATED_AT_ASC, Some(TITLE_ASC)),
(DocumentSortField::CreatedAt, SortDirection::Desc) => (CREATED_AT_DESC, Some(TITLE_ASC)),
(DocumentSortField::UpdatedAt, SortDirection::Asc) => (UPDATED_AT_ASC, Some(TITLE_ASC)),
(DocumentSortField::UpdatedAt, SortDirection::Desc) => (UPDATED_AT_DESC, Some(TITLE_ASC)),
}
}
+33
View File
@@ -0,0 +1,33 @@
use std::collections::HashMap;
use uuid::Uuid;
use crate::documents::correspondents::{
load_correspondents_for_documents, DocumentCorrespondentResponse,
};
use crate::documents::tags::load_tags_for_documents;
use crate::error::AppResult;
use crate::models::Tag;
use crate::state::PgPooledConnection;
/// Loads tags and correspondents for the provided documents in a single pass.
pub fn load_tags_and_correspondents(
conn: &mut PgPooledConnection,
document_ids: &[Uuid],
) -> AppResult<HashMap<Uuid, (Vec<Tag>, Vec<DocumentCorrespondentResponse>)>> {
if document_ids.is_empty() {
return Ok(HashMap::new());
}
let tags_map = load_tags_for_documents(conn, document_ids)?;
let mut correspondents_map = load_correspondents_for_documents(conn, document_ids)?;
let mut result = HashMap::with_capacity(document_ids.len());
for id in document_ids {
let tags = tags_map.get(id).cloned().unwrap_or_default();
let correspondents = correspondents_map.remove(id).unwrap_or_default();
result.insert(*id, (tags, correspondents));
}
Ok(result)
}
+14
View File
@@ -163,6 +163,20 @@ pub async fn ensure_quickwit_index(client: &Client, endpoint: &str, index_id: &s
} }
} }
pub async fn delete_quickwit_index(client: &Client, endpoint: &str, index_id: &str) -> Result<()> {
let base = endpoint.trim_end_matches('/');
let url = format!("{}/api/v1/indexes/{}", base, index_id);
let response = client.delete(&url).send().await?;
match response.status() {
status if status.is_success() => Ok(()),
StatusCode::NOT_FOUND => Ok(()),
status => {
let body = response.text().await.unwrap_or_default();
bail!("quickwit delete index failed with status {status}: {body}");
}
}
}
pub fn extract_document_id(hit: &Value) -> Option<Uuid> { pub fn extract_document_id(hit: &Value) -> Option<Uuid> {
for key in ["_source", "source", "fields", "stored_fields"] { for key in ["_source", "source", "fields", "stored_fields"] {
if let Some(value) = hit.get(key) { if let Some(value) = hit.get(key) {
+29 -6
View File
@@ -4,7 +4,9 @@ use axum::{
Json, Json,
}; };
use serde::Serialize; use serde::Serialize;
use std::fmt::Display; use serde_json::Value;
use std::fmt::{self, Display};
use utoipa::ToSchema;
pub type AppResult<T> = Result<T, AppError>; pub type AppResult<T> = Result<T, AppError>;
@@ -13,6 +15,7 @@ pub struct AppError {
status: StatusCode, status: StatusCode,
message: String, message: String,
code: Option<String>, code: Option<String>,
details: Option<Value>,
} }
impl AppError { impl AppError {
@@ -21,6 +24,7 @@ impl AppError {
status, status,
message: message.into(), message: message.into(),
code: None, code: None,
details: None,
} }
} }
@@ -36,6 +40,10 @@ impl AppError {
Self::new(StatusCode::UNAUTHORIZED, "unauthorized") Self::new(StatusCode::UNAUTHORIZED, "unauthorized")
} }
pub fn forbidden(message: impl Into<String>) -> Self {
Self::new(StatusCode::FORBIDDEN, message)
}
pub fn not_found() -> Self { pub fn not_found() -> Self {
Self::new(StatusCode::NOT_FOUND, "resource not found") Self::new(StatusCode::NOT_FOUND, "resource not found")
} }
@@ -48,24 +56,38 @@ impl AppError {
self.code = Some(code.into()); self.code = Some(code.into());
self self
} }
pub fn with_details(mut self, details: Value) -> Self {
self.details = Some(details);
self
}
}
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.status, self.message)
}
} }
impl IntoResponse for AppError { impl IntoResponse for AppError {
fn into_response(self) -> Response { fn into_response(self) -> Response {
let status = self.status; let status = self.status;
let body = Json(ErrorResponse { let body = Json(ApiErrorResponse {
error: self.message, error: self.message,
code: self.code, code: self.code,
details: self.details,
}); });
(status, body).into_response() (status, body).into_response()
} }
} }
#[derive(Serialize)] #[derive(Serialize, ToSchema)]
struct ErrorResponse { pub struct ApiErrorResponse {
error: String, error: String,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
code: Option<String>, code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
details: Option<Value>,
} }
impl From<diesel::result::Error> for AppError { impl From<diesel::result::Error> for AppError {
@@ -73,8 +95,9 @@ impl From<diesel::result::Error> for AppError {
match value { match value {
diesel::result::Error::NotFound => AppError::not_found(), diesel::result::Error::NotFound => AppError::not_found(),
other => { other => {
tracing::error!(error = ?other, "database operation failed"); let message = format!("database operation failed: {other}");
AppError::internal("database operation failed") tracing::error!(error = ?other, message);
AppError::internal(message)
} }
} }
} }
+1
View File
@@ -0,0 +1 @@
pub mod responders;
+157
View File
@@ -0,0 +1,157 @@
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
Json,
};
use serde::Serialize;
use crate::error::{AppError, AppResult};
/// Helper trait to convert error-centric results into the application's error type.
pub trait IntoAppResult<T> {
fn into_app_result(self) -> AppResult<T>;
}
impl<T, E> IntoAppResult<T> for Result<T, E>
where
AppError: From<E>,
{
fn into_app_result(self) -> AppResult<T> {
self.map_err(AppError::from)
}
}
/// Extension helpers for optional values to map them into `AppResult`.
pub trait OptionAppResultExt<T> {
fn or_not_found(self) -> AppResult<T>;
fn or_bad_request(self, message: impl Into<String>) -> AppResult<T>;
}
impl<T> OptionAppResultExt<T> for Option<T> {
fn or_not_found(self) -> AppResult<T> {
self.ok_or_else(AppError::not_found)
}
fn or_bad_request(self, message: impl Into<String>) -> AppResult<T> {
self.ok_or_else(|| AppError::bad_request(message))
}
}
/// Provides helpers for statements returning number of affected rows.
pub trait RowsAffectedExt: Sized {
fn or_error(self, error: AppError) -> AppResult<usize>;
fn or_not_found(self) -> AppResult<usize> {
self.or_error(AppError::not_found())
}
}
impl RowsAffectedExt for usize {
fn or_error(self, error: AppError) -> AppResult<usize> {
if self == 0 {
Err(error)
} else {
Ok(self)
}
}
}
/// Wrapper providing a consistent JSON response with a status code.
pub struct JsonResponse<T> {
status: StatusCode,
payload: T,
}
impl<T> JsonResponse<T> {
pub fn new(status: StatusCode, payload: T) -> Self {
Self { status, payload }
}
pub fn ok(payload: T) -> Self {
Self::new(StatusCode::OK, payload)
}
pub fn created(payload: T) -> Self {
Self::new(StatusCode::CREATED, payload)
}
pub fn accepted(payload: T) -> Self {
Self::new(StatusCode::ACCEPTED, payload)
}
pub fn into_inner(self) -> T {
self.payload
}
pub fn as_inner(&self) -> &T {
&self.payload
}
}
impl<T> From<T> for JsonResponse<T> {
fn from(value: T) -> Self {
Self::ok(value)
}
}
impl<T> IntoResponse for JsonResponse<T>
where
T: Serialize,
{
fn into_response(self) -> Response {
(self.status, Json(self.payload)).into_response()
}
}
/// Helper for returning empty responses with a status code.
pub fn empty(status: StatusCode) -> AppResult<StatusCode> {
Ok(status)
}
/// Helper for returning `204 No Content`.
pub fn no_content() -> AppResult<StatusCode> {
empty(StatusCode::NO_CONTENT)
}
/// Helper for returning JSON payloads with `200 OK`.
pub fn ok_json<T>(value: T) -> AppResult<JsonResponse<T>>
where
T: Serialize,
{
Ok(JsonResponse::ok(value))
}
/// Helper for returning JSON payloads with `201 Created`.
pub fn created_json<T>(value: T) -> AppResult<JsonResponse<T>>
where
T: Serialize,
{
Ok(JsonResponse::created(value))
}
/// Helper for returning JSON payloads with `202 Accepted`.
pub fn accepted_json<T>(value: T) -> AppResult<JsonResponse<T>>
where
T: Serialize,
{
Ok(JsonResponse::accepted(value))
}
/// Standard wrapper for paginated responses.
#[derive(Serialize)]
pub struct PaginatedResponse<T, M>
where
T: Serialize,
M: Serialize,
{
pub data: T,
pub meta: M,
}
pub fn paginated_json<T, M>(data: T, meta: M) -> AppResult<JsonResponse<PaginatedResponse<T, M>>>
where
T: Serialize,
M: Serialize,
{
let payload = PaginatedResponse { data, meta };
Ok(JsonResponse::ok(payload))
}
+167
View File
@@ -0,0 +1,167 @@
use std::collections::HashSet;
use chrono::{DateTime, Datelike, NaiveDate, TimeZone, Utc};
use chrono_tz::Tz;
use once_cell::sync::Lazy;
use tracing::warn;
use crate::config::AppConfig;
#[derive(Clone, Copy, Debug)]
pub enum DateOrder {
Dmy,
Mdy,
Ymd,
}
impl DateOrder {
pub fn parse(value: &str) -> Self {
Self::try_parse(value).unwrap_or(DateOrder::Dmy)
}
pub fn try_parse(value: &str) -> Option<Self> {
match value.trim().to_ascii_uppercase().as_str() {
"YMD" => Some(DateOrder::Ymd),
"MDY" => Some(DateOrder::Mdy),
"DMY" => Some(DateOrder::Dmy),
_ => None,
}
}
}
static MIN_ISSUED_AT_DATE: Lazy<NaiveDate> =
Lazy::new(|| NaiveDate::from_ymd_opt(1901, 1, 1).expect("valid minimum issued_at date"));
#[derive(Clone, Debug)]
pub struct IssuedAtSettings {
pub timezone: Tz,
pub date_order: DateOrder,
pub filename_date_order: Option<DateOrder>,
pub locales: HashSet<String>,
pub ignore_dates: HashSet<NaiveDate>,
pub min_date: NaiveDate,
}
impl IssuedAtSettings {
pub fn from_config(config: &AppConfig) -> Self {
let timezone = config.service_timezone.parse::<Tz>().unwrap_or_else(|_| {
warn!(
timezone = %config.service_timezone,
"invalid service timezone configured; falling back to UTC"
);
chrono_tz::UTC
});
let date_order = DateOrder::parse(&config.issued_at_date_order);
let filename_date_order =
config
.issued_at_filename_date_order
.as_deref()
.and_then(|value| {
DateOrder::try_parse(value).or_else(|| {
warn!(value, "invalid issued_at filename date order; ignoring");
None
})
});
let locales = config
.issued_at_date_parser_locales
.iter()
.filter_map(|value| {
let trimmed = value.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_ascii_lowercase())
}
})
.collect::<HashSet<_>>();
// Ignore dates are evaluated after normalizing candidate timestamps to
// the configured service timezone, so administrators should provide
// local calendar dates rather than UTC midnights.
let ignore_dates = config
.issued_at_ignore_dates
.iter()
.filter_map(|value| {
let trimmed = value.trim();
if trimmed.is_empty() {
return None;
}
match NaiveDate::parse_from_str(trimmed, "%Y-%m-%d") {
Ok(date) => Some(date),
Err(err) => {
warn!(value = trimmed, error = %err, "invalid issued_at ignore date");
None
}
}
})
.collect();
Self {
timezone,
date_order,
filename_date_order,
locales,
ignore_dates,
min_date: *MIN_ISSUED_AT_DATE,
}
}
/// Returns the immutable (lowercase) locale allowlist supplied via config.
pub fn locales(&self) -> &HashSet<String> {
&self.locales
}
/// Returns the immutable set of local-calendar dates that should be ignored.
pub fn ignore_dates(&self) -> &HashSet<NaiveDate> {
&self.ignore_dates
}
/// Returns the configured service timezone (copy type).
pub fn timezone(&self) -> Tz {
self.timezone
}
pub fn date_order(&self) -> DateOrder {
self.date_order
}
pub fn filename_date_order(&self) -> Option<DateOrder> {
self.filename_date_order
}
pub fn normalize_naive(
&self,
date: NaiveDate,
now_utc: chrono::DateTime<Utc>,
) -> Option<DateTime<Utc>> {
if !self.is_valid_with_now(date, now_utc) {
return None;
}
self.timezone
.with_ymd_and_hms(date.year(), date.month(), date.day(), 0, 0, 0)
.earliest()
.map(|dt| dt.with_timezone(&Utc))
}
pub fn normalize_datetime(
&self,
dt: chrono::DateTime<Utc>,
now_utc: chrono::DateTime<Utc>,
) -> Option<DateTime<Utc>> {
let local_date = dt.with_timezone(&self.timezone).date_naive();
self.normalize_naive(local_date, now_utc)
}
fn is_valid_with_now(&self, date: NaiveDate, now_utc: chrono::DateTime<Utc>) -> bool {
if date < self.min_date {
return false;
}
let now_local = now_utc.with_timezone(&self.timezone).date_naive();
if date > now_local {
return false;
}
!self.ignore_dates.contains(&date)
}
}
+2 -1
View File
@@ -18,8 +18,9 @@ pub const STATUS_FAILED: &str = "failed";
pub const JOB_ANALYZE_DOCUMENT: &str = "analyze-document"; pub const JOB_ANALYZE_DOCUMENT: &str = "analyze-document";
pub const JOB_GENERATE_THUMBNAILS: &str = "generate-thumbnails"; pub const JOB_GENERATE_THUMBNAILS: &str = "generate-thumbnails";
pub const JOB_GENERATE_OCR_TEXT: &str = "generate-ocr-text"; pub const JOB_GENERATE_OCR_TEXT: &str = "generate-ocr-text";
pub const JOB_INDEX_DOCUMENT_TEXT: &str = "index-document-text";
pub const JOB_PROVISION_TENANT: &str = "provision-tenant"; pub const JOB_PROVISION_TENANT: &str = "provision-tenant";
pub const JOB_PURGE_DOCUMENT: &str = "purge-document";
pub const JOB_DELETE_TENANT: &str = "delete-tenant";
#[derive(Debug, Error)] #[derive(Debug, Error)]
pub enum JobQueueError { pub enum JobQueueError {
+5
View File
@@ -3,15 +3,20 @@ pub mod config;
pub mod db; pub mod db;
pub mod documents; pub mod documents;
pub mod error; pub mod error;
pub mod http;
pub mod issued_at;
pub mod jobs; pub mod jobs;
pub mod models; pub mod models;
pub mod openapi; pub mod openapi;
pub mod routes; pub mod routes;
pub mod s3; pub mod s3;
pub mod schema; pub mod schema;
pub mod services;
pub mod state; pub mod state;
pub mod storage; pub mod storage;
pub mod tenants; pub mod tenants;
pub mod utils; pub mod utils;
pub mod workers; pub mod workers;
pub use workers::{default_handlers, Worker}; pub use workers::{default_handlers, Worker};
pub mod migrations;
pub mod test_support;

Some files were not shown because too many files have changed in this diff Show More