From 3a2edfc4d274bdcd9aed5f6a1a16cd74a92c1e31 Mon Sep 17 00:00:00 2001 From: albert Date: Mon, 2 Nov 2026 14:07:15 -0700 Subject: [PATCH 01/82] Implement account and administration portals with secure collection portability --- README.md | 8 + deployment/nginx-root.conf.example | 1 + deployment/nginx-subpath.conf.example | 1 + docs/administration.md | 62 ++ docs/development/portal-assessment.md | 51 ++ docs/groups.md | 6 +- docs/operations.md | 21 +- docs/portability.md | 82 +++ docs/portal.md | 91 +++ docs/releases/0.2.0.md | 17 + pom.xml | 4 +- qualification/clients/thunderbird.py | 17 +- qualification/passkeys/dav-credentials.mjs | 10 +- qualification/passkeys/groups.mjs | 147 ++-- qualification/passkeys/oidc.mjs | 12 +- qualification/passkeys/passkeys.mjs | 18 +- qualification/passkeys/portal-helpers.mjs | 45 ++ qualification/passkeys/portal.mjs | 124 ++++ qualification/passkeys/recovery.mjs | 43 +- qualification/passkeys/run.py | 3 + qualification/passkeys/sharing_capacity.py | 2 +- qualification/proxy/nginx.conf.template | 11 + .../caldav/account/AccountService.java | 26 + .../caldav/calendar/CalendarInterchange.java | 300 +++++++++ .../caldav/config/OperationalProblems.java | 25 + .../caldav/config/PortabilityWorkFilter.java | 34 + .../config/RequestDiagnosticsFilter.java | 7 + .../ServletDeploymentConfiguration.java | 14 +- .../management/AdministrationController.java | 97 +++ .../management/AdministrationService.java | 149 +++++ .../management/DavConnectionAdvice.java | 2 +- .../management/GroupManagementController.java | 175 +++-- .../caldav/management/GroupSharingAdvice.java | 37 -- .../caldav/management/ImportStaging.java | 101 +++ .../management/IndividualSharingAdvice.java | 52 -- .../management/ManagementController.java | 66 +- .../caldav/management/ManagementService.java | 19 +- .../management/OperationalDiagnostics.java | 39 +- .../management/PortabilityController.java | 90 +++ .../caldav/management/PortabilityService.java | 215 ++++++ .../caldav/management/PortalController.java | 113 ++++ .../caldav/management/PortalErrors.java | 126 ++++ .../caldav/management/PortalPage.java | 18 + .../caldav/management/PortalPageAdvice.java | 38 ++ .../caldav/management/PortalService.java | 375 +++++++++++ .../management/SharingManagementService.java | 75 +++ .../caldav/security/RecentAuthentication.java | 18 + .../caldav/security/audit/SecurityAudit.java | 10 +- .../caldav/sharing/GroupService.java | 125 ++++ .../busystack/caldav/storage/DavStore.java | 12 + src/main/resources/application.yaml | 5 + src/main/resources/static/assets/account.css | 4 +- src/main/resources/static/assets/portal.js | 14 + .../resources/templates/account-detail.html | 9 + .../resources/templates/account-error.html | 2 +- src/main/resources/templates/account-new.html | 7 + src/main/resources/templates/accounts.html | 9 + .../resources/templates/administration.html | 9 +- src/main/resources/templates/audit.html | 9 + .../templates/collection-delete.html | 7 + .../resources/templates/collection-new.html | 8 + .../templates/collection-sharing.html | 15 + src/main/resources/templates/collection.html | 11 + src/main/resources/templates/collections.html | 11 + src/main/resources/templates/connections.html | 12 + src/main/resources/templates/credentials.html | 9 + src/main/resources/templates/dashboard.html | 23 +- src/main/resources/templates/diagnostics.html | 16 +- src/main/resources/templates/error/400.html | 1 + src/main/resources/templates/error/403.html | 2 +- src/main/resources/templates/error/404.html | 1 + src/main/resources/templates/error/500.html | 1 + src/main/resources/templates/error/503.html | 1 + .../resources/templates/fragments/layout.html | 42 ++ .../resources/templates/group-detail.html | 11 + src/main/resources/templates/group-error.html | 2 +- src/main/resources/templates/groups.html | 13 +- .../resources/templates/import-report.html | 9 + .../templates/issued-credential.html | 2 +- src/main/resources/templates/login.html | 14 +- .../resources/templates/oauth-clients.html | 6 +- .../resources/templates/oauth-consent.html | 2 +- src/main/resources/templates/oauth-error.html | 2 +- .../resources/templates/oauth-grants.html | 6 +- src/main/resources/templates/passkeys.html | 10 +- src/main/resources/templates/password.html | 2 +- src/main/resources/templates/portability.html | 7 + .../resources/templates/portal-error.html | 7 + .../resources/templates/recovery-codes.html | 2 +- src/main/resources/templates/recovery.html | 2 +- src/main/resources/templates/security.html | 9 + src/main/resources/templates/sessions.html | 2 +- .../calendar/CalendarInterchangeTest.java | 149 +++++ .../caldav/management/PortalManagementIT.java | 625 ++++++++++++++++++ 94 files changed, 3817 insertions(+), 427 deletions(-) create mode 100644 docs/administration.md create mode 100644 docs/development/portal-assessment.md create mode 100644 docs/portability.md create mode 100644 docs/portal.md create mode 100644 docs/releases/0.2.0.md create mode 100644 qualification/passkeys/portal-helpers.mjs create mode 100644 qualification/passkeys/portal.mjs create mode 100644 src/main/java/org/busystack/caldav/calendar/CalendarInterchange.java create mode 100644 src/main/java/org/busystack/caldav/config/OperationalProblems.java create mode 100644 src/main/java/org/busystack/caldav/config/PortabilityWorkFilter.java create mode 100644 src/main/java/org/busystack/caldav/management/AdministrationController.java create mode 100644 src/main/java/org/busystack/caldav/management/AdministrationService.java delete mode 100644 src/main/java/org/busystack/caldav/management/GroupSharingAdvice.java create mode 100644 src/main/java/org/busystack/caldav/management/ImportStaging.java delete mode 100644 src/main/java/org/busystack/caldav/management/IndividualSharingAdvice.java create mode 100644 src/main/java/org/busystack/caldav/management/PortabilityController.java create mode 100644 src/main/java/org/busystack/caldav/management/PortabilityService.java create mode 100644 src/main/java/org/busystack/caldav/management/PortalController.java create mode 100644 src/main/java/org/busystack/caldav/management/PortalErrors.java create mode 100644 src/main/java/org/busystack/caldav/management/PortalPage.java create mode 100644 src/main/java/org/busystack/caldav/management/PortalPageAdvice.java create mode 100644 src/main/java/org/busystack/caldav/management/PortalService.java create mode 100644 src/main/java/org/busystack/caldav/management/SharingManagementService.java create mode 100644 src/main/resources/static/assets/portal.js create mode 100644 src/main/resources/templates/account-detail.html create mode 100644 src/main/resources/templates/account-new.html create mode 100644 src/main/resources/templates/accounts.html create mode 100644 src/main/resources/templates/audit.html create mode 100644 src/main/resources/templates/collection-delete.html create mode 100644 src/main/resources/templates/collection-new.html create mode 100644 src/main/resources/templates/collection-sharing.html create mode 100644 src/main/resources/templates/collection.html create mode 100644 src/main/resources/templates/collections.html create mode 100644 src/main/resources/templates/connections.html create mode 100644 src/main/resources/templates/credentials.html create mode 100644 src/main/resources/templates/error/400.html create mode 100644 src/main/resources/templates/error/404.html create mode 100644 src/main/resources/templates/error/500.html create mode 100644 src/main/resources/templates/error/503.html create mode 100644 src/main/resources/templates/fragments/layout.html create mode 100644 src/main/resources/templates/group-detail.html create mode 100644 src/main/resources/templates/import-report.html create mode 100644 src/main/resources/templates/portability.html create mode 100644 src/main/resources/templates/portal-error.html create mode 100644 src/main/resources/templates/security.html create mode 100644 src/test/java/org/busystack/caldav/calendar/CalendarInterchangeTest.java create mode 100644 src/test/java/org/busystack/caldav/management/PortalManagementIT.java diff --git a/README.md b/README.md index 96f13b1..513a9aa 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,14 @@ Qualified graphical clients are Thunderbird 159.0 and GNOME Calendar 50.0 / Evolution Data Server 3.56.2 in the configurations listed in the [compatibility documentation](docs/observance-until-compatibility.md). +## Account and administration portals + +Use the [user guide](docs/portal.md) for first sign-in, collection lifecycle, sharing, +client connection and security settings; [portability](docs/portability.md) for +validated iCalendar import/export; and [administration](docs/administration.md) for +bounded account/group management, audit and diagnostics. The interface uses local +server-rendered assets and does not require a frontend service or CDN. + ## Documentation and limitations Start with [account security](docs/account-security.md), diff --git a/deployment/nginx-root.conf.example b/deployment/nginx-root.conf.example index 5b50ecd..030f3c0 100644 --- a/deployment/nginx-root.conf.example +++ b/deployment/nginx-root.conf.example @@ -13,6 +13,7 @@ server { proxy_set_header Forwarded ""; proxy_set_header X-Forwarded-Host ""; proxy_set_header X-Forwarded-Proto ""; + location = /portability/preview { client_max_body_size 9m; proxy_pass http://127.0.0.1:8080; } location = /actuator { return 404; } location ^~ /actuator/ { return 404; } location / { proxy_pass http://127.0.0.1:8080; } diff --git a/deployment/nginx-subpath.conf.example b/deployment/nginx-subpath.conf.example index 62d4de8..102ba77 100644 --- a/deployment/nginx-subpath.conf.example +++ b/deployment/nginx-subpath.conf.example @@ -19,6 +19,7 @@ server { proxy_pass http://127.0.0.1:8080/calendar/.well-known/oauth-authorization-server; } location = /calendar { return 308 https://calendar.example.org/calendar/; } + location = /calendar/portability/preview { client_max_body_size 9m; proxy_pass http://127.0.0.1:8080; } location = /actuator { return 404; } location ^~ /actuator/ { return 404; } location = /calendar/actuator { return 404; } diff --git a/docs/administration.md b/docs/administration.md new file mode 100644 index 0000000..fc67028 --- /dev/null +++ b/docs/administration.md @@ -0,0 +1,62 @@ +# Server administration + +Complete recent primary and passkey verification, then select **Server +administration**. This area is distinct from your personal account. Administrator +status does not bypass private calendar permissions. + +The overview shows the packaged application version, enabled/disabled account +counts, calendar/task-list and current resource counts, queried PostgreSQL/migration +versions, and observed HTTP errors. Database availability means its queries +succeeded for that request. Backup status is **Unknown** because backups are an +external operator responsibility. No automatic update check or telemetry runs. + +## Accounts + +Search and filter **Accounts** in 50-row pages. Select one for identity type, +status, role and display-name maintenance. Username, UUID, privileges and external +issuer/subject mappings cannot be edited here. Profile edits detect stale values. + +**Create account** provisions an ordinary local account. Transfer the initial +password securely; the user must enroll/verify their own passkey before sensitive +changes. Organization accounts use the configured closed allowlist or protected +user identity linking. Provider roles do not grant application administration. + +Disabling requires explicit confirmation, invalidates sessions and independently +issued client access, and retains stored data/membership. There is no browser +reactivation, password reset or administrator creation. Use controlled offline +[bootstrap/recovery](operations.md) after independent identity verification. + +## Groups + +Search groups and page through members without loading the account directory. +Create an empty group, rename it, add an exact active username, remove an individual +member, or confirm group deletion. Single-member operations do not replace the +remaining membership set. Disabled memberships can be removed. + +Before adding/removing a member, review the access-consequence explanation and +confirm it. Existing/future grants apply on addition; other direct/group grants +remain on removal. Group administration shows grant counts, not private collection +names or contents. Existing directory limits, mutation locks and V13 transactional +binding/synchronization reconciliation remain authoritative. See [groups](groups.md). + +## Security audit and diagnostics + +**Security & Audit** filters retained fixed action/outcome metadata and exact +account usernames in 50-row pages. It exposes no peer hashes, secrets, request +bodies or calendar contents. The existing approximately 10,000-row / thirty-day +retention remains. New account/profile, collection lifecycle/import and direct-share +mutations use that same structured audit. Export reads do not add activity tracking. +OAuth client registration remains administrator-controlled. + +**System & Diagnostics** shows configured deployment addresses, runtime/database +versions, applied migration and HTTP observations. A process-local buffer retains +up to fifty actual server failures with time, coarse surface, method, status and +server-generated request ID. It contains no resource paths, usernames or contents +and resets on restart. It is not durable monitoring or a backup-health assertion. + +Use X-Request-ID to correlate safe operator logs. Database failure may prevent +session validation and access to administration itself; use local readiness probes +and deployment logs. Invalid configuration fails startup. Provider outage, expired +credentials, denied access and established CalDAV compatibility conditions have +contextual guidance. Infrastructure, SQL, files, configuration, certificates, +updates and backup/recovery remain under the deployment operator's control. diff --git a/docs/development/portal-assessment.md b/docs/development/portal-assessment.md new file mode 100644 index 0000000..56a452a --- /dev/null +++ b/docs/development/portal-assessment.md @@ -0,0 +1,51 @@ +# Portal implementation assessment + +Starting checkout: `release/v0.2.0`, `db302ec69f786ba89945e1a761734a844572145b`. +The existing uncommitted application-version change to 0.2.0 is preserved. +Development uses `feature/v0.2.0-portals`; no changes are made to main or published +migrations. No AGENTS.md instructions were present in the checkout or ancestors. +The release procedure remains authoritative for integration and publication. + +## Existing contracts + +Spring MVC/Thymeleaf renders twenty small templates. ManagementController and +ManagementService expose collection creation, individual sharing, DAV credential +issuance/revocation and ordinary account provisioning/disabling. GroupService +already enforces administrator membership management separately from owner grants. +OperationalDiagnostics exposes aggregate metadata; SecurityAudit already stores +bounded structured events. Login and passkeys lacked the common stylesheet. + +CalendarStore is authoritative for collection identity, resource admission, UID +uniqueness, revisions and synchronization. DavStore owns bindings and atomic DAV +property changes/deletion. `collection_effective_members` combines direct/group +READ/WRITE permissions for DAV authorization. V13 reconciles group bindings under +the existing mutation locks. Metadata changes must retain paths, types and bodies. + +V1–V13 are forward-only Flyway migrations. Account UUIDs, enabled state, security +epochs and SessionSecurity checks remain authoritative. Sensitive mutations require +the existing ten-minute primary and WebAuthn factors. External identities retain +issuer/subject mappings, closed allowlisting, local factors and bounded freshness. +Offline bootstrap/recovery, OAuth, session and credential revocation are retained. + +## Gaps and implementation boundaries + +Add coherent personal/admin navigation; bounded metadata screens; collection +editing/deletion confirmation; per-collection grants and effective permissions; +connection instructions and security organization; structured paginated account, +group and audit administration; contextual setup; and validated iCalendar +preview/confirmation/export. Reuse services rather than dispatching browser HTTP +to DAV or maintaining another collection/permission model. No event/task editor, +public sharing, registration, email or privileged browser recovery is introduced. + +Use standard CalDAV calendar-description and the existing dead-property mechanism +for the Apple calendar-color convention. Client acceptance must be measured; a +stored property alone is not proof of a client's UI behavior. + +The required PostgreSQL/HTTPS integration tests, real Keycloak fixture, independent +Python/Thunderbird clients, packaged Chromium WebAuthn/proxy/restore harness and +distribution checks already exist. Extend these. Historical evidence qualifies +only its recorded artifacts. Current qualification results are recorded separately. + +Reference review: Baïkal 0.13.0 administration and Radicale 3.9.0 collection, +metadata, share, upload and deletion workflows inform the workflow structure only. +No competitor source or modified third-party implementation is incorporated. diff --git a/docs/groups.md b/docs/groups.md index a1be5ee..1313098 100644 --- a/docs/groups.md +++ b/docs/groups.md @@ -1,8 +1,8 @@ # Groups and calendar sharing -An administrator with recent primary authentication and passkey verification manages local groups under **Administration → Sharing groups**. Groups have stable internal identifiers, a display name and up to 1,000 account members. The interface creates, renames, replaces membership and deletes groups. Deleting a group removes its collection grants. Account disabling still denies access even when its membership remains recorded. +An administrator with recent primary authentication and passkey verification manages local groups under **Administration → Sharing groups**. Groups have stable internal identifiers, a display name and up to 1,000 account members. The interface creates and renames groups, pages through members, adds/removes one member at a time, and confirms group deletion. The existing atomic replacement service remains available internally for established protocol and capacity tests. Deleting a group removes its collection grants. Account disabling still denies access even when its membership remains recorded. -A collection owner uses **Group sharing** on the account page to grant read-only or read/write access, or remove a grant. Sharing references the same authoritative collection. Administrators manage membership: granting a group therefore delegates control of its current and future membership. An administrator explicitly adding their own account receives that group's granted access; administrative status by itself does not bypass calendar permissions. Individual account grants and group grants combine to provide the effective access. +A collection owner opens **Manage sharing** on the collection detail page to grant read-only or read/write access, or remove a grant. Sharing references the same authoritative collection. Administrators manage membership: granting a group therefore delegates control of its current and future membership. An administrator explicitly adding their own account receives that group's granted access; administrative status by itself does not bypass calendar permissions. Individual account grants and group grants combine to provide the effective access. The sharing dropdown exposes group names and identifiers. DAV membership metadata is limited to members, owners of collections granted to the group, and administrators. Group administration, owned grants and effective calendar permissions are checked in the services as well as the HTTP layer. Mutations require current account state and recent MFA; browser forms retain CSRF protection. @@ -10,7 +10,7 @@ Membership/grant changes reconcile shared collection bindings and change affecte The directory supports at most 1,000 groups, at most 1,000 accounts per group and 10,000 recorded group memberships in total. Group creation/replacement checks these existing admission bounds before accepting changes. No separate grant-count ceiling makes accepted sharing states impossible to maintain: a group may be granted many collections and an owner may have more than 10,000 group grants. -The account dashboard lists owned group grants in pages of 50, with Previous/Next controls and removal actions on every page. Membership maintenance streams affected collection locks in stable UUID order; V13 reconciles bindings and generations with set-based SQL under the exclusive mutation lock and one transaction. Readers therefore observe the complete permission change after commit, rather than partially revoked batches. Group deletion removes its memberships and grants atomically. Individual READ/WRITE grants continue to contribute independently to effective access. Group/principal retirement identifiers remain durable and are never reused. +Each owned collection lists direct and group grants, plus combined effective permissions, in independent pages of 50. Removal feedback distinguishes removing a grant from losing all access. Membership maintenance streams affected collection locks in stable UUID order; V13 reconciles bindings and generations with set-based SQL under the exclusive mutation lock and one transaction. Readers therefore observe the complete permission change after commit, rather than partially revoked batches. Group deletion removes its memberships and grants atomically. Individual READ/WRITE grants continue to contribute independently to effective access. Group/principal retirement identifiers remain durable and are never reused. `GroupServiceIT` exercises many grants across a modest number of calendars/groups and a single group spanning more than 10,000 calendars, including listing, removal, membership replacement and deletion. The required packaged workload additionally seeds 12,500 disposable grants across 25 calendars and 500 groups, then uses actual CSRF-protected browser forms to inspect the first/last pages, revoke a grant, replace membership and delete a group while recording Docker/DB observations. SQL fixture population is not a measurement of HTTP grant-creation throughput. diff --git a/docs/operations.md b/docs/operations.md index dcf272e..13a4a91 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -187,14 +187,19 @@ The image must already be pulled (or source-built for development) and the datab ## First browser sign-in and user creation -1. Open the configured public HTTPS address in a browser that trusts its certificate. Use the final hostname: passkeys are bound to its relying-party ID and origin. At **Sign in to BusyStack**, enter the bootstrap username/password and choose **Verify password**. -2. Follow **enroll your first passkey** or open **Passkeys and authentication**. Give it a name, choose **Register passkey**, and complete the authenticator's user-verification prompt. Choose **Verify passkey to complete MFA** for the same account. Registration alone is not the completed two-factor sign-in. -3. Return to **Account management**, then open **Administration**. Under **Provision an account**, enter the new user's username, display name and initial password and choose **Create account**. Usernames start with an ASCII letter or digit and contain only ASCII letters, digits, `.`, `_` or `-`, up to 64 characters. Passwords use the limits above. The new account is an ordinary user; administrator status does not grant access to that user's private calendars. -4. Give the initial credential to the intended user through a secure channel. Sign out of the administrator session. The new user signs in and enrolls/verifies their own passkey using the same steps. Account changes require both factors verified within ten minutes. When they become stale, return to `/login` and use **Verify password** and **Verify passkey** for the same account. For an already enrolled account, the passkey settings page requires that recent MFA and redirects to login until it is complete. -5. On the user's account page, use **Create a collection** to create an **Events** collection and a separate **Tasks** collection. Their displayed component types are `VEVENT` and `VTODO`. The account interface manages collections and access; create and edit the actual events/tasks in a CalDAV client. -6. Under **DAV credentials**, enter a device/application label and a lifetime from 1 to 365 days, then choose **Issue credential**. The **New DAV credential** page shows the complete secret once. Copy it directly into that client's password store; do not use the account password. Losing the secret requires issuing a replacement, not retrieving the old one. Return to the account page to revoke a device's credential when needed. - -Keep a second enrolled authenticator or securely stored recovery codes where possible. A virtual-authenticator test does not establish that a particular physical device or synchronized passkey provider works; check that device before relying on it. The documented offline recovery procedure remains available to the server operator. +Follow [the user portal guide](portal.md) for primary sign-in, passkey enrollment +and verification, collection creation, credential issuance and client configuration. +Administrators use **Server administration → Accounts → Create account**, transfer +the initial password securely, and let the user enroll their own factors. See +[administration](administration.md) for account/group/audit workflows and boundaries. +No email service is required. The existing password, recent-factor, session, +recovery and identity-provider policies remain unchanged. + +For portal imports, add a proxy location allowing a 9 MiB multipart request only +at `/portability/preview`, preserving any application prefix. The supplied +`deployment/nginx-*.conf.example` files include it. DAV continues to use its existing +1 MiB body limit. See [portability](portability.md) for bounded temporary storage, +preview expiry, transactional writes and export format. ## Client access and sync compatibility diff --git a/docs/portability.md b/docs/portability.md new file mode 100644 index 0000000..5cd8cee --- /dev/null +++ b/docs/portability.md @@ -0,0 +1,82 @@ +# iCalendar import and export + +The account portal exposes data portability through the same CalendarStore, +DavStore and CalendarAdmission used by DAV. It does not add an event/task editor, +a weaker calendar profile or scheduling actions. + +## Export + +An owner or current read-authorized recipient can export a collection. Application +administration provides no additional content access. A repeatable-read snapshot +retrieves bodies in the existing batches of at most 16 resources / 4 MiB. A private +temporary file is completed and validated before download success headers are +sent. Errors never return a silently incomplete successful export. The download +uses `text/calendar; charset=utf-8`, a fixed safe attachment filename and +`Cache-Control: no-store`; the file is removed after delivery. + +The output is a lossless [RFC 5545 §3.4 iCalendar stream](https://www.rfc-editor.org/rfc/rfc5545.html#section-3.4): +complete VCALENDAR objects in resource order. This keeps resource UIDs, recurrence +masters/exceptions, supported extensions and each resource's timezone definitions +together without merging conflicting definitions with the same TZID. Stored valid +objects are not rebuilt through a serializer. A missing final line ending receives +a separator before the next object. Ordinary resource retrieval remains unchanged. + +Some other importers consume only one VCALENDAR. Test the destination's complete +stream behavior before migration; protocol interoperability does not establish its +file-import behavior. BusyStack accepts both multi-component VCALENDAR files and +streams. Export limits are 10,000 resources and 64 MiB. Files larger than the +import limit must be divided at complete VCALENDAR boundaries before importing. +These are explicit operating limits, not a claim of arbitrary-size migration. + +## Preview, confirm and results + +Select an authorized collection and upload actual iCalendar content. File names +are ignored and never select server paths. The server's existing parser, text and +complexity limits locate UID series; every resulting resource goes through full +CalendarAdmission and the existing VEVENT/VTODO validation. All exceptions for a +UID remain with the master. Unsupported components and wrong-destination types +are reported explicitly. Malformed framing rejects the file before mutation. + +Preview lists each item and its disposition. An identical existing UID/resource is +**Skipped**. Different content with an existing UID is **Conflicting** and is not +overwritten. Multiple masters or repeated UIDs in separate input objects are +rejected rather than guessed or discarded. Validation rejections are counted. +No replacement or implicit merge is offered. + +A preview is an opaque account/security-generation-bound token backed by a private +server temporary file. One preview per account is retained for at most ten minutes; +a new preview replaces the earlier one. Total staged files are capped at 32 MiB / +32 previews per instance. Confirmation or cancellation deletes the staged file. +Graceful shutdown cleans pending files; after a crash, operators must ensure +ordinary temporary-file cleanup. Previews cannot survive a JVM restart or transfer +to another instance; the default deployment runs one application instance. + +Confirmation requires the checkbox, current account state and recent MFA again. +The service takes existing DAV namespace/collection locks, rechecks write permission +and reclassifies conflicts. Valid new series are written with create-only +preconditions in one transaction. A database failure rolls them all back. Otherwise +the results explicitly report imported, skipped, conflicting and rejected items; +only the valid new subset is imported. Replaying a consumed or expired token fails. +No invitation, outbound attachment fetch or alarm execution occurs. + +## Processing and deployment limits + +Upload files are limited to 8 MiB, each resulting UID resource to 1 MiB, and items +to 1,000. The existing depth/component/property/parameter bounds apply cumulatively +across the input; retained resulting resource bytes are separately bounded to +16 MiB to prevent timezone duplication exhausting memory. Two simultaneous +portability requests are admitted; further requests receive 503 and Retry-After. +Temporary disk use also remains subject to the deployment's private temp limit. + +The proxy must allow 9 MiB multipart requests **only** at `/portability/preview` +(with its configured application prefix). Other DAV/form limits remain unchanged. +The deployment examples and qualification proxy include this location. Do not +raise DAV resource or authentication-body limits to enable multi-item imports. +Temporary files, database snapshots and backups can contain private calendar data; +protect host and database access as described in [operations](operations.md). + +Focused service/HTTPS tests and native fixtures exercise byte-preserving +export → import → retrieve comparisons, UID/resource counts, recurrence, tasks, +timezones, duplicate/conflict classification, rollback, unauthorized operations, +CSRF and safe download names. Packaged browser evidence is independent of those +service tests; consult the current qualification receipt for executed results. diff --git a/docs/portal.md b/docs/portal.md new file mode 100644 index 0000000..66edced --- /dev/null +++ b/docs/portal.md @@ -0,0 +1,91 @@ +# Your BusyStack account + +BusyStack manages your account, collections and client access. Edit actual events +and tasks in your CalDAV application. Local authentication requires no identity +provider, email service or vendor account. + +## First sign-in + +Open your operator's configured HTTPS address. Verify your local password, or use +the configured organization sign-in. Enroll your first passkey under **Security → +Passkeys**, then verify that passkey to complete MFA. Registration alone does not +complete authentication. Sensitive changes require primary sign-in and passkey +verification within ten minutes. The overview and security pages explain which +step is needed. Renew both factors for the same account when they expire. + +The overview adapts to actual passkeys, owned/shared collections, unexpired DAV +credentials and unused recovery codes. It never claims that a device is connected. +Save recovery codes offline; see [account security](account-security.md). There is +no public registration, email recovery or browser-based operator recovery. + +## Calendars and task lists + +Open **Calendars & Tasks**. **My calendars and task lists** contains your owned +collections; **Shared with me** contains direct/group shared collections. Search +and page through names. Select a collection for its details and address. + +Choose **Create a collection**, supply a name, choose Calendar or Task list and +optionally enter a description and colour. Types stay fixed. Metadata changes +preserve the collection's identity, address and stored resources. Descriptions use +CalDAV `calendar-description`; colour uses the Apple `calendar-color` convention, +with #RRGGBB or #RRGGBBAA values. This is not a universal client-colour guarantee. +A client may maintain its own local colour preference. + +Read/write recipients can change shared metadata and import contents according to +the existing DAV permissions. Only owners can manage sharing or delete a +collection. Deletion has a separate review page and requires server-checked +confirmation of the current state. It removes resources, history, bindings and +sharing grants. Export before deletion when a migration copy is needed; operator +backups are separate. If another request changes the target, reload and review the +new state instead of retrying a stale form. + +## Sharing and effective access + +Open **Manage sharing** on an owned collection. Add a direct grant using the +recipient's exact username; no public account directory or autocomplete is +provided. Grant read-only or read and write, change a recorded grant, or remove it. +Group grants apply to every current and future member. Administrators maintain +membership, so granting a group delegates that membership decision. + +The effective-permission table uses the same `collection_effective_members` view +as DAV authorization. Any read/write grant supplies read/write access. Removing a +direct grant does not remove access provided by a group; removing one group grant +does not remove another grant. Disabled accounts cannot authenticate, even if +membership remains recorded. Sharing changes can invalidate synchronization tokens; +clients must perform initial synchronization when a token is rejected. + +## Connect an application + +Open **Connections**, then issue a named credential under **Security → DAV +credentials**. Copy its once-shown secret directly into the application's password +settings. The account password is not the DAV password. Secrets cannot be retrieved +later. Credential labels, creation/expiration and active/expired/revoked status are +available without displaying verifiers. To replace one, issue a replacement, +configure the client, then revoke the old credential. + +Copy the displayed server address, username and, when needed, collection address. +Addresses include the operator's configured subpath and never depend on request +Host or forwarding headers. Use normal TLS verification. + +Thunderbird instructions on Connections follow the documented network-calendar +wizard. Historical qualification covers Thunderbird 159.0 and GNOME Calendar 50.0 / +EDS 3.56.2 on the exact 0.1.0 executable and configurations in the +[client record](observance-until-compatibility.md#qualified-client-configurations). +The GNOME record uses a source provisioned through EDS's supported API; it does not +qualify a graphical account-creation wizard. Do not equate that with a verified +GNOME setup procedure. Current artifact results are recorded separately; BusyMax +and other untested clients are not advertised as supported. + +Registered OAuth applications may use browser consent instead of a DAV credential. +Review them under **Security → OAuth applications**; see [OAuth](oauth.md). + +## Security and data portability + +Security links to passkeys, credentials, browser sessions, recovery and OAuth +grants. Local accounts can change their password. Organization-managed accounts +change primary credentials at their identity provider; there is no local-password +fallback. Local passkeys, credentials and permissions still belong to BusyStack. +Provider outages/freshness retain the [existing identity policy](keycloak.md). + +Use **Import & Export** for validated, confirmed iCalendar migration. See +[portability](portability.md) for conflict handling, limits and representation. diff --git a/docs/releases/0.2.0.md b/docs/releases/0.2.0.md new file mode 100644 index 0000000..0a7454c --- /dev/null +++ b/docs/releases/0.2.0.md @@ -0,0 +1,17 @@ +# 0.2.0 development + +This branch adds a server-rendered account and administration portal: collection +metadata/lifecycle, per-collection direct/group/effective access, connections, +security organization, contextual setup, bounded account/group/audit screens, +operational diagnostics and confirmed iCalendar portability. It retains the +existing Java/Spring/Thymeleaf/PostgreSQL stack and V1–V13 schema. + +Start with the [user guide](../portal.md), [administration guide](../administration.md) +and [portability limits and representation](../portability.md). The optional +Keycloak identity, recent-factor, recovery, OAuth, credential and CalDAV policies +remain unchanged. Proxy import limits need the documented dedicated location. + +This document describes development functionality, not release qualification or +readiness. Exact source/artifact, executed browser/client/security/recovery results +and unverified environments must be recorded independently before publication. +Historical 0.1.0 client results do not qualify a different executable. diff --git a/pom.xml b/pom.xml index 706f3b2..b227d2c 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 org.springframework.bootspring-boot-starter-parent4.1.2 - org.busystackcaldav-server0.1.0 + org.busystackcaldav-server0.2.0 BusyStack CalDAV Server Independent calendar and task server https://github.com/busystack/caldav-server @@ -45,7 +45,7 @@ org.apache.maven.pluginsmaven-surefire-plugin3.5.6 org.apache.maven.pluginsmaven-failsafe-plugin3.5.6-Xmx256mintegration-testverify org.apache.maven.pluginsmaven-jar-plugin3.4.2 - org.springframework.bootspring-boot-maven-plugin4.1.2 + org.springframework.bootspring-boot-maven-plugin4.1.2build-info org.apache.maven.pluginsmaven-enforcer-plugin3.6.2toolchainenforce[25,26)[3.9.12,4) com.diffplug.spotlessspotless-maven-plugin3.10.41.32.0checkvalidate org.cyclonedxcyclonedx-maven-plugin2.9.3prepare-packagemakeAggregateBomfalsejson diff --git a/qualification/clients/thunderbird.py b/qualification/clients/thunderbird.py index c57f4ed..fad2181 100644 --- a/qualification/clients/thunderbird.py +++ b/qualification/clients/thunderbird.py @@ -33,6 +33,9 @@ Services.prefs.setBoolPref('signon.rememberSignons',true); Services.logins.setLoginSavingEnabled(new URL(eventUrl).origin,true); await cal.auth.passwordManagerSave(username,password,new URL(eventUrl).origin,'BusyStack DAV'); + const discovered=await cal.provider.caldav.detectCalendars(username,password,eventUrl,true); + const detected=discovered.find(calendar=>calendar.uri.spec===eventUrl); + if(!detected || detected.name!=='Thunderbird events' || detected.getProperty('color')!=='#126A5E') throw new Error('Native discovery lost display name or Apple calendar-color'); globalThis.busystackCalendars=[]; globalThis.busystackMetadata=[]; Services.obs.addObserver({observe(subject){ @@ -62,7 +65,7 @@ globalThis.busystackCalendars.push(calendar); await globalThis.busystackRefresh(calendar,true); } - return {app:Services.appinfo.name,version:Services.appinfo.version}; + return {app:Services.appinfo.name,version:Services.appinfo.version,appleCalendarColor:detected.getProperty('color')}; })().then(done,error=>done({error:String(error.message)})); """ @@ -282,6 +285,8 @@ def main(): principal = client.principal() events = principal.make_calendar(name="Thunderbird events", cal_id="thunderbird-events", supported_calendar_component_set=["VEVENT"]) tasks = principal.make_calendar(name="Thunderbird tasks", cal_id="thunderbird-tasks", supported_calendar_component_set=["VTODO"]) + metadata = client.request(str(events.url), "PROPPATCH", body='#126A5EFFNative metadata qualification') + assert metadata.status == 207 sync_profile = verify_sync_profile(client, events) with tempfile.TemporaryDirectory(prefix="busystack-thunderbird-") as temporary: profile = Path(temporary) @@ -324,6 +329,14 @@ def main(): (artifacts / ("thunderbird-" + kind + ".ics")).write_bytes(result[kind].encode("utf-8")) assert len(events.events()) == 3 and len(tasks.todos(include_completed=True)) == 1 urls, completed = python_edits_native_items(events, tasks) + stream = "".join(item.data for item in events.objects()) + "".join(item.data for item in tasks.objects()) + imported = driver.execute_script(""" + const parser=Cc['@mozilla.org/calendar/ics-parser;1'].createInstance(Ci.calIIcsParser); + parser.parseString(arguments[0]); + return parser.getItems().map(item=>({id:item.id,type:item.isEvent()?'VEVENT':'VTODO'})); + """, script_args=[stream], new_sandbox=False) + assert {item["id"] for item in imported} == {"thunderbird-event", "thunderbird-task", "thunderbird-all-day", "thunderbird-floating"} + assert sum(item["type"] == "VEVENT" for item in imported) == 3 cross = driver.execute_async_script(CROSS_CLIENT, new_sandbox=False) assert cross == {"crossClient": True, "nativeOccurrenceCount": 3, "nativeDetachedExceptions": 1}, cross final = independent_items(events, tasks) @@ -334,7 +347,7 @@ def main(): deleted = driver.execute_async_script(DELETE, new_sandbox=False) assert deleted == {"deleted": True}, deleted assert len(events.events()) == 0 and len(tasks.todos(include_completed=True)) == 0 - print(json.dumps({"client": info["app"], "version": info["version"], "driver": importlib.metadata.version("marionette_driver"), "crossClient": {"python-caldav": importlib.metadata.version("caldav"), "icalendar": importlib.metadata.version("icalendar"), "sameResources": 4, "nativeRecurrenceInstances": cross["nativeOccurrenceCount"], "nativeDetachedExceptions": cross["nativeDetachedExceptions"], "excludedOccurrences": 1}, "mode": "isolated headless native desktop CalDAV provider", "syncConfiguration": sync_profile, "status": "passed", "operations": ["server discovery by native provider", "recurring event CRUD", "Unicode and unknown-property round trip", "alarm preservation without execution", "undated VTODO CRUD and completion", "same-object Thunderbird to Python to Thunderbird to Python edits", "cross-client recurrence, alarm, extension and completion timestamp preservation", "same-resource detached exception identity/time/title edits in both clients", "EXDATE exclusion verified by native occurrence expansion", "all-day DATE and exclusive end preservation across both clients", "floating DATE-TIME preservation across both clients", "native refresh and deletion synchronization"]}, sort_keys=True)) + print(json.dumps({"client": info["app"], "version": info["version"], "driver": importlib.metadata.version("marionette_driver"), "crossClient": {"python-caldav": importlib.metadata.version("caldav"), "icalendar": importlib.metadata.version("icalendar"), "sameResources": 4, "nativeRecurrenceInstances": cross["nativeOccurrenceCount"], "nativeDetachedExceptions": cross["nativeDetachedExceptions"], "excludedOccurrences": 1}, "nativeAppleCalendarColor": info["appleCalendarColor"], "nativeIcalendarStreamItems": len(imported), "mode": "isolated headless native desktop CalDAV provider", "syncConfiguration": sync_profile, "status": "passed", "operations": ["server discovery by native provider", "recurring event CRUD", "Unicode and unknown-property round trip", "alarm preservation without execution", "undated VTODO CRUD and completion", "same-object Thunderbird to Python to Thunderbird to Python edits", "cross-client recurrence, alarm, extension and completion timestamp preservation", "same-resource detached exception identity/time/title edits in both clients", "EXDATE exclusion verified by native occurrence expansion", "all-day DATE and exclusive end preservation across both clients", "floating DATE-TIME preservation across both clients", "native refresh and deletion synchronization"]}, sort_keys=True)) finally: try: if driver is not None: diff --git a/qualification/passkeys/dav-credentials.mjs b/qualification/passkeys/dav-credentials.mjs index 98e0a8e..8437cbd 100644 --- a/qualification/passkeys/dav-credentials.mjs +++ b/qualification/passkeys/dav-credentials.mjs @@ -3,7 +3,7 @@ import {randomUUID} from 'node:crypto'; import {call} from './transport.mjs'; export async function issueDavCredential(page, base, privateValues, label, username = process.env.BUSYSTACK_BROWSER_USERNAME) { - await page.goto(base + '/'); + await page.goto(base + '/security/credentials'); const form = page.locator('form').filter({has: page.locator('input[name=label]')}); await form.locator('input[name=label]').fill(label); await form.locator('input[name=days]').fill('1'); @@ -15,7 +15,7 @@ export async function issueDavCredential(page, base, privateValues, label, usern assert.equal(credential.length, 80); const encoded = Buffer.from(username + ':' + credential).toString('base64'); privateValues.push(credential, encoded); - await page.goto(base + '/'); + await page.goto(base + '/security/credentials'); assert.ok(!(await page.content()).includes(credential), 'A device secret must not appear again in management'); return {credential, encoded}; } @@ -25,10 +25,10 @@ export async function qualifyDavCredentials(page, base, privateValues, username const {credential, encoded} = await issueDavCredential(page, base, privateValues, label, username); assert.equal((await call(base, '/dav/missing', {headers: {Authorization: 'Basic ' + encoded}})).status, 404); await verifySyncDepth(page, base, encoded); - await page.goto(base + '/'); + await page.goto(base + '/security/credentials'); assert.ok(!(await page.content()).includes(credential), 'A device secret must not appear again in the management page'); - const entry = page.locator('li').filter({hasText: label}); - await Promise.all([page.waitForURL(base + '/'), entry.getByRole('button', {name: 'Revoke', exact: true}).click()]); + const entry = page.locator('tbody tr').filter({hasText: label}); + await Promise.all([page.waitForURL(base + '/security/credentials'), entry.getByRole('button', {name: 'Revoke', exact: true}).click()]); assert.equal((await call(base, '/dav/missing', {headers: {Authorization: 'Basic ' + encoded}})).status, 401); console.log('BROWSER_DAV_CREDENTIAL_ISSUANCE_DISPLAY_ONCE_AND_REVOCATION_PASSED'); } diff --git a/qualification/passkeys/groups.mjs b/qualification/passkeys/groups.mjs index aaad1ee..dc5bdd5 100644 --- a/qualification/passkeys/groups.mjs +++ b/qualification/passkeys/groups.mjs @@ -1,83 +1,88 @@ import assert from 'node:assert/strict'; import {randomBytes} from 'node:crypto'; +import {openCollection,provisionAccount,prefixOf} from './portal-helpers.mjs'; -export async function qualifyGroups(page, base, privateValues) { - const prefix = new URL(base).pathname.replace(/\/$/, ''); - const member = 'browsergroupmember'; - const password = randomBytes(32).toString('base64url'); +export async function qualifyGroups(page,base,privateValues) { + const prefix=prefixOf(base),member='browsergroupmember',password=randomBytes(32).toString('base64url'); privateValues.push(password); - await page.goto(base + '/admin'); - const provision = page.locator(`form[action="${prefix}/admin/accounts"]`); - await provision.locator('input[name=username]').fill(member); - await provision.locator('input[name=displayName]').fill('Browser Group Member'); - await provision.locator('input[name=password]').fill(password); - await Promise.all([page.waitForURL(base + '/admin'), provision.getByRole('button', {name: 'Create account', exact: true}).click()]); - await page.getByText(member, {exact: true}).waitFor(); - await page.getByRole('link', {name: 'Sharing groups', exact: true}).click(); - await page.getByRole('heading', {name: 'Sharing groups', exact: true}).waitFor(); - const create = page.locator(`form[action="${prefix}/admin/groups"]`); + const account=await provisionAccount(page,base,member,'Browser Group Member',password); + await page.goto(base+'/admin/groups'); + const create=page.locator(`form[action="${prefix}/admin/groups"]`); await create.locator('input[name=name]').fill('Browser sharing group'); - await create.locator('textarea[name=usernames]').fill(member); - await Promise.all([page.waitForURL(base + '/admin/groups'), create.getByRole('button', {name: 'Create group', exact: true}).click()]); - let card = page.locator('article').filter({has: page.getByRole('heading', {name: 'Browser sharing group', exact: true})}); - assert.equal(await card.locator('textarea[name=usernames]').inputValue(), member); - const group = await card.locator('code').innerText(); - assert.match(group, /^[a-f0-9-]{36}$/i); - const edit = card.locator(`form[action="${prefix}/admin/groups/${group}"]`); - await edit.locator('input[name=name]').fill('Browser group renamed'); - await edit.locator('textarea[name=usernames]').fill(''); - await Promise.all([page.waitForURL(base + '/admin/groups'), edit.getByRole('button', {name: 'Save group', exact: true}).click()]); - card = page.locator('article').filter({has: page.getByRole('heading', {name: 'Browser group renamed', exact: true})}); - assert.equal(await card.locator('textarea[name=usernames]').inputValue(), ''); - await card.locator('textarea[name=usernames]').fill(member); - await Promise.all([page.waitForURL(base + '/admin/groups'), card.getByRole('button', {name: 'Save group', exact: true}).click()]); - await page.goto(base + '/'); - const sharing = page.locator(`form[action="${prefix}/group-shares"]`).filter({has: page.locator('select[name=group]')}); - await sharing.locator('select[name=collection]').selectOption({label: 'Browser-qualified tasks'}); + await Promise.all([page.waitForURL(/\/admin\/groups\/[a-f0-9-]{36}$/i),create.getByRole('button',{name:'Create group',exact:true}).click()]); + const group=new URL(page.url()).pathname.split('/').at(-1); + const add=page.locator(`form[action="${prefix}/admin/groups/${group}/members"]`); + await add.locator('input[name=username]').fill(member);await add.locator('input[name=confirmed]').check(); + await Promise.all([page.waitForURL(base+'/admin/groups/'+group),add.getByRole('button',{name:'Add member',exact:true}).click()]); + const row=page.locator('tbody tr').filter({has:page.getByText(member,{exact:true})}); + await row.locator('input[name=confirmed]').check(); + await Promise.all([page.waitForURL(base+'/admin/groups/'+group),row.getByRole('button',{name:'Remove member',exact:true}).click()]); + assert.equal(await row.count(),0); + await add.locator('input[name=username]').fill(member);await add.locator('input[name=confirmed]').check(); + await Promise.all([page.waitForURL(base+'/admin/groups/'+group),add.getByRole('button',{name:'Add member',exact:true}).click()]); + const rename=page.locator(`form[action="${prefix}/admin/groups/${group}"]`); + await rename.locator('input[name=name]').fill('Browser group renamed'); + await Promise.all([page.waitForURL(base+'/admin/groups/'+group),rename.getByRole('button',{name:'Save group name',exact:true}).click()]); + await page.getByRole('heading',{name:'Browser group renamed',exact:true}).waitFor(); + const collection=await openCollection(page,base,'Browser-qualified tasks'); + await page.goto(base+'/collections/'+collection+'/sharing'); + const sharing=page.locator(`form[action="${prefix}/group-shares"]`).filter({has:page.locator('select[name=group]')}); + await sharing.locator('..').locator('summary').click(); await sharing.locator('select[name=group]').selectOption(group); - for (const permission of ['READ', 'WRITE']) { - await sharing.locator('select[name=permission]').selectOption(permission); - await Promise.all([page.waitForURL(base + '/'), sharing.getByRole('button', {name: 'Save group access', exact: true}).click()]); - const grant = page.locator('tbody tr').filter({hasText: 'Browser group renamed'}); - assert.ok((await grant.innerText()).includes(permission)); + await sharing.locator('select[name=permission]').selectOption('READ'); + await Promise.all([page.waitForURL(base+'/collections/'+collection+'/sharing'),sharing.getByRole('button',{name:'Grant group access',exact:true}).click()]); + const grant=page.locator('table').filter({has:page.locator('caption').filter({hasText:'Groups with grants for this collection'})}).locator('tbody tr').filter({hasText:'Browser group renamed'}); + for(const permission of ['WRITE','REVOKE']) { + await grant.locator('select[name=permission]').selectOption(permission); + await Promise.all([page.waitForURL(base+'/collections/'+collection+'/sharing'),grant.getByRole('button',{name:'Save group grant',exact:true}).click()]); } - let grant = page.locator('tbody tr').filter({hasText: 'Browser group renamed'}); - await Promise.all([page.waitForURL(base + '/'), grant.getByRole('button', {name: 'Remove group access', exact: true}).click()]); - assert.equal(await page.locator('tbody tr').filter({hasText: 'Browser group renamed'}).count(), 0); - await page.goto(base + '/admin/groups'); - card = page.locator('article').filter({has: page.getByRole('heading', {name: 'Browser group renamed', exact: true})}); - await Promise.all([page.waitForURL(base + '/admin/groups'), card.getByRole('button', {name: 'Delete group', exact: true}).click()]); - assert.equal(await page.getByRole('heading', {name: 'Browser group renamed', exact: true}).count(), 0); - await page.goto(base + '/'); - assert.equal(await page.locator(`option[value="${group}"]`).count(), 0); + assert.equal(await grant.count(),0); + await page.goto(base+'/admin/groups/'+group); + const remove=page.locator(`form[action="${prefix}/admin/groups/${group}/delete"]`); + await remove.locator('input[name=confirmed]').check(); + await Promise.all([page.waitForURL(base+'/admin/groups'),remove.getByRole('button',{name:'Delete group',exact:true}).click()]); + assert.equal(await page.getByRole('link',{name:'Browser group renamed',exact:true}).count(),0); + await page.goto(base+'/collections/'+collection+'/sharing'); + assert.equal(await page.locator(`option[value="${group}"]`).count(),0); console.log('BROWSER_GROUP_MEMBERSHIP_UPDATE_DELETE_AND_OWNER_GRANTS_PASSED'); } - -export async function qualifySharingCapacity(page, administratorPage, base, fixture) { - const prefix = new URL(base).pathname.replace(/\/$/, ''); - await page.goto(base + '/'); - const rows = page.locator('table').filter({has: page.locator('caption').filter({hasText: 'Groups with access to your owned collections'})}).locator('tbody tr'); - assert.equal(await rows.count(), 50); - await page.getByRole('link', {name: 'Next group sharing page', exact: true}).waitFor(); - await page.goto(base + '/?group-shares-page=249'); - assert.equal(await rows.count(), 50); - assert.equal(await page.getByRole('link', {name: 'Next group sharing page', exact: true}).count(), 0); - const remove = rows.first().locator('form'); - const removedGroup = await remove.locator('input[name=group]').inputValue(); - await Promise.all([page.waitForURL(base + '/'), remove.getByRole('button', {name: 'Remove group access', exact: true}).click()]); - assert.equal(await rows.count(), 50); - await administratorPage.goto(base + '/admin/groups'); - let card = administratorPage.locator('article').filter({has: administratorPage.getByRole('heading', {name: fixture.groupName, exact: true})}); - await card.locator('input[name=name]').fill('Capacity group updated'); - await card.locator('textarea[name=usernames]').fill('restorewriter'); - await Promise.all([administratorPage.waitForURL(base + '/admin/groups'), card.getByRole('button', {name: 'Save group', exact: true}).click()]); - card = administratorPage.locator('article').filter({has: administratorPage.getByRole('heading', {name: 'Capacity group updated', exact: true})}); - assert.equal(await card.locator('textarea[name=usernames]').inputValue(), 'restorewriter'); - await Promise.all([administratorPage.waitForURL(base + '/admin/groups'), card.getByRole('button', {name: 'Delete group', exact: true}).click()]); - assert.equal(await administratorPage.getByRole('heading', {name: 'Capacity group updated', exact: true}).count(), 0); - await page.goto(base + '/'); - await page.getByRole('heading', {name: 'BusyStack account', exact: true}).waitFor(); +export async function qualifySharingCapacity(page,administratorPage,base,fixture) { + const prefix=prefixOf(base); + assert.equal(fixture.collections.length,25); + let firstPageRows=0,lastPageRows=0; + for(const id of fixture.collections) { + await page.goto(base+'/collections/'+id+'/sharing'); + const rows=page.locator('table').filter({has:page.locator('caption').filter({hasText:'Groups with grants for this collection'})}).locator('tbody tr'); + assert.equal(await rows.count(),50);firstPageRows+=50; + await page.goto(base+'/collections/'+id+'/sharing?groupPage=9'); + assert.equal(await rows.count(),50);lastPageRows+=50; + const nav=page.getByRole('navigation',{name:'Group grant pages'}); + assert.equal(await nav.getByRole('link',{name:'Next',exact:true}).count(),0); + } + const id=fixture.collections[0]; + await page.goto(base+'/collections/'+id+'/sharing'); + const rows=page.locator('table').filter({has:page.locator('caption').filter({hasText:'Groups with grants for this collection'})}).locator('tbody tr'); + const remove=rows.first().locator('form'); + const removedGroup=await remove.locator('input[name=group]').inputValue(); + await remove.locator('select[name=permission]').selectOption('REVOKE'); + await Promise.all([page.waitForURL(base+'/collections/'+id+'/sharing'),remove.getByRole('button',{name:'Save group grant',exact:true}).click()]); + assert.equal(await rows.count(),50); + await administratorPage.goto(base+'/admin/groups/'+fixture.firstGroup); + const rename=administratorPage.locator(`form[action="${prefix}/admin/groups/${fixture.firstGroup}"]`); + await rename.locator('input[name=name]').fill('Capacity group updated'); + await Promise.all([administratorPage.waitForURL(base+'/admin/groups/'+fixture.firstGroup),rename.getByRole('button',{name:'Save group name',exact:true}).click()]); + const member=administratorPage.locator('tbody tr').filter({has:administratorPage.getByText('restorereader',{exact:true})}); + await member.locator('input[name=confirmed]').check(); + await Promise.all([administratorPage.waitForURL(base+'/admin/groups/'+fixture.firstGroup),member.getByRole('button',{name:'Remove member',exact:true}).click()]); + const add=administratorPage.locator(`form[action="${prefix}/admin/groups/${fixture.firstGroup}/members"]`); + await add.locator('input[name=username]').fill('restorewriter');await add.locator('input[name=confirmed]').check(); + await Promise.all([administratorPage.waitForURL(base+'/admin/groups/'+fixture.firstGroup),add.getByRole('button',{name:'Add member',exact:true}).click()]); + const members=administratorPage.locator('tbody tr'); + assert.equal(await members.count(),1);assert.ok((await members.innerText()).includes('restorewriter')); + const deletion=administratorPage.locator(`form[action="${prefix}/admin/groups/${fixture.firstGroup}/delete"]`); + await deletion.locator('input[name=confirmed]').check(); + await Promise.all([administratorPage.waitForURL(base+'/admin/groups'),deletion.getByRole('button',{name:'Delete group',exact:true}).click()]); console.log('BROWSER_12500_GRANTS_PAGINATION_REVOCATION_MEMBERSHIP_AND_GROUP_DELETE_PASSED'); - return {...fixture, browserPassed: true, firstPageRows: 50, lastPage: 249, lastPageRows: 50, removedGroup}; + return {...fixture,browserPassed:true,firstPageRows,lastPage:9,lastPageRows,removedGroup}; } diff --git a/qualification/passkeys/oidc.mjs b/qualification/passkeys/oidc.mjs index 5bdd4e0..a87297c 100644 --- a/qualification/passkeys/oidc.mjs +++ b/qualification/passkeys/oidc.mjs @@ -1,3 +1,4 @@ +import {createCollection} from './portal-helpers.mjs'; import assert from 'node:assert/strict'; import {readFileSync} from 'node:fs'; @@ -13,7 +14,7 @@ export async function organizationPrimary(page, base, privateValues, requirePass privateValues.push(password); await page.goto(base + '/login'); await page.getByRole('link', {name: "Sign in with your organization's identity provider", exact: true}).click(); - const dashboard = page.getByRole('heading', {name: 'BusyStack account', exact: true}); + const dashboard = page.getByRole('heading', {name: /^Welcome,/}); let destination; try { destination = await Promise.race([ @@ -44,7 +45,7 @@ export async function organizationPrimary(page, base, privateValues, requirePass } await page.waitForURL(url => accountLocation(url, base)); await dashboard.waitFor(); - await page.locator('main > p').first().getByText(process.env.BUSYSTACK_FEDERATED_USERNAME, {exact: true}).waitFor(); + await page.getByText(process.env.BUSYSTACK_FEDERATED_USERNAME, {exact: true}).first().waitFor(); const cookie = (await page.context().cookies()).find(value => value.name === 'JSESSIONID'); assert.ok(cookie && cookie.secure && cookie.httpOnly && cookie.sameSite === 'Lax', 'Cross-site OIDC callback must retain a protected Lax session'); } @@ -80,12 +81,7 @@ export async function newFederatedUser(browser, base, privateValues) { await page.locator('#security-status').filter({hasText: 'Passkey registered.'}).waitFor(); await Promise.all([page.waitForURL(base + '/'), page.getByRole('button', {name: 'Verify passkey to complete MFA', exact: true}).click()]); const prefix = new URL(base).pathname.replace(/\/$/, ''); - const form = page.locator(`form[action="${prefix}/collections"]`); - await form.locator('input[name=name]').fill('Federated browser-qualified tasks'); - await form.locator('select[name=component]').selectOption('VTODO'); - await Promise.all([page.waitForURL(base + '/'), form.getByRole('button', {name: 'Create', exact: true}).click()]); - const collection = page.locator('li').filter({has: page.getByText('Federated browser-qualified tasks', {exact: true})}); - assert.ok((await collection.innerText()).includes('VTODO')); + await createCollection(page,base,'Federated browser-qualified tasks','VTODO'); assert.equal(await page.getByText('Browser-qualified tasks', {exact: true}).count(), 0, 'An organization user must not discover the local administrator collection'); const forbidden = await page.goto(base + '/admin'); assert.equal(forbidden.status(), 403, 'Upstream realm roles must not grant application administration'); diff --git a/qualification/passkeys/passkeys.mjs b/qualification/passkeys/passkeys.mjs index 68b4aa2..b7e5c7a 100644 --- a/qualification/passkeys/passkeys.mjs +++ b/qualification/passkeys/passkeys.mjs @@ -1,3 +1,5 @@ +import {qualifyPersonalPortal,qualifyPortalPresentation} from './portal.mjs'; +import {createCollection, openCollection} from './portal-helpers.mjs'; import { chromium } from 'playwright'; import assert from 'node:assert/strict'; import { createInterface } from 'node:readline'; @@ -53,14 +55,10 @@ try { const mfaSession = (await context.cookies()).find(cookie => cookie.name === 'JSESSIONID')?.value; if (mfaSession) privateValues.push(mfaSession); assert.ok(mfaSession && mfaSession !== passwordSession, 'Passkey authentication must rotate session ID'); - const collectionForm = page.locator(`form[action="${prefix}/collections"]`); - await collectionForm.locator('input[name=name]').fill('Browser-qualified tasks'); - await collectionForm.locator('select[name=component]').selectOption('VTODO'); - await Promise.all([page.waitForURL(base + '/'), collectionForm.locator('button').click()]); - const createdCollection = page.locator('li').filter({has: page.getByText('Browser-qualified tasks', {exact: true})}); - await createdCollection.waitFor(); - assert.ok((await createdCollection.innerText()).includes('VTODO'), 'The created collection must actually advertise VTODO'); + await createCollection(page,base,'Browser-qualified tasks','VTODO'); console.log('PASSWORD_PLUS_WEBAUTHN_AND_MUTATION_PASSED'); + const localPortal=await qualifyPersonalPortal(page,base,privateValues,process.env.BUSYSTACK_BROWSER_USERNAME); + await qualifyPortalPresentation(page,base,localPortal,true); if (process.env.BUSYSTACK_BROWSER_GROUPS === 'true') await qualifyGroups(page, base, privateValues); const administratorPage = page; let activeCdp = cdp; @@ -76,6 +74,8 @@ try { activeAuthenticatorId = federated.authenticatorId; currentUsername = process.env.BUSYSTACK_FEDERATED_USERNAME; collectionName = 'Federated browser-qualified tasks'; + const externalPortal=await qualifyPersonalPortal(page,base,privateValues,currentUsername,'external'); + await qualifyPortalPresentation(page,base,externalPortal,false,'external'); } await qualifyAccountRecovery({page, base, privateValues, administratorPage, username: currentUsername, cdp: activeCdp, authenticatorId: activeAuthenticatorId}); @@ -90,7 +90,7 @@ try { console.log('READY_RESTART'); await waitFor('RESTARTED'); await page.goto(base + '/'); - await page.getByRole('heading', {name: 'BusyStack account', exact: true}).waitFor(); + await page.getByRole('heading', {name: /^Welcome,/}).waitFor(); assert.equal((await context.cookies()).find(value => value.name === 'JSESSIONID')?.value, persistentCookie, 'A persisted browser session must survive the application restart'); console.log('PERSISTED_BROWSER_SESSION_AFTER_RESTART_PASSED'); @@ -108,7 +108,7 @@ try { } await page.goto(base + '/login'); await Promise.all([page.waitForURL(base + '/'), page.getByRole('button', {name: 'Verify passkey', exact: true}).click()]); - await page.locator('li').getByText(collectionName, {exact: true}).waitFor(); + await openCollection(page,base,collectionName); console.log('PERSISTED_PASSKEY_AFTER_RESTART_PASSED'); console.log('READY_DISABLE'); await waitFor('DISABLED'); diff --git a/qualification/passkeys/portal-helpers.mjs b/qualification/passkeys/portal-helpers.mjs new file mode 100644 index 0000000..3594ec2 --- /dev/null +++ b/qualification/passkeys/portal-helpers.mjs @@ -0,0 +1,45 @@ +import assert from 'node:assert/strict'; +export function prefixOf(base) {return new URL(base).pathname.replace(/\/$/, '');} +export async function openCollection(page, base, name) { + await page.goto(base + '/collections?scope=all'); + const link=page.getByRole('link', {name,exact:true}); + const href=await link.getAttribute('href'); + assert.match(href,/\/collections\/[a-f0-9-]{36}$/i); + await link.click(); + return href.split('/').at(-1); +} +export async function createCollection(page,base,name,component) { + await page.goto(base+'/collections/new'); + const form=page.locator(`form[action="${prefixOf(base)}/collections"]`); + await form.locator('input[name=name]').fill(name); + await form.locator('select[name=component]').selectOption(component); + await Promise.all([page.waitForURL(/\/collections\/[a-f0-9-]{36}$/i),form.getByRole('button',{name:'Create collection',exact:true}).click()]); + assert.equal(await page.getByRole('heading',{name,exact:true}).count(),1); + assert.ok((await page.locator('main').innerText()).includes(component==='VTODO'?'Task list':'Calendar')); + return new URL(page.url()).pathname.split('/').at(-1); +} +export async function provisionAccount(page,base,username,displayName,password) { + await page.goto(base+'/admin/accounts/new'); + const form=page.locator(`form[action="${prefixOf(base)}/admin/accounts"]`); + await form.locator('input[name=username]').fill(username); + await form.locator('input[name=displayName]').fill(displayName); + await form.locator('input[name=password]').fill(password); + await Promise.all([page.waitForURL(/\/admin\/accounts\/[a-f0-9-]{36}$/i),form.getByRole('button',{name:'Create account',exact:true}).click()]); + await page.getByText(username,{exact:true}).waitFor(); + return new URL(page.url()).pathname.split('/').at(-1); +} +export async function grantDirect(page,base,collection,username,permission) { + await page.goto(base+'/collections/'+collection+'/sharing'); + const form=page.locator(`form[action="${prefixOf(base)}/shares"]`).filter({has:page.locator('input[name=username]:not([type=hidden])')}); + await form.locator('..').locator('summary').click(); + await form.locator('input[name=username]').fill(username); + await form.locator('select[name=permission]').selectOption(permission); + await Promise.all([page.waitForURL(base+'/collections/'+collection+'/sharing'),form.getByRole('button',{name:'Grant account access',exact:true}).click()]); + return page.locator('table').filter({has:page.locator('caption').filter({hasText:'Accounts with direct grants'})}).locator('tbody tr').filter({has:page.getByText(username,{exact:true})}); +} +export async function revokeDirect(page,base,collection,username) { + await page.goto(base+'/collections/'+collection+'/sharing'); + const row=page.locator('table').filter({has:page.locator('caption').filter({hasText:'Accounts with direct grants'})}).locator('tbody tr').filter({has:page.getByText(username,{exact:true})}); + await row.locator('select[name=permission]').selectOption('REVOKE'); + await Promise.all([page.waitForURL(base+'/collections/'+collection+'/sharing'),row.getByRole('button',{name:'Save direct grant',exact:true}).click()]); +} diff --git a/qualification/passkeys/portal.mjs b/qualification/passkeys/portal.mjs new file mode 100644 index 0000000..cc0d1af --- /dev/null +++ b/qualification/passkeys/portal.mjs @@ -0,0 +1,124 @@ +import assert from 'node:assert/strict'; +import {readFileSync, mkdirSync} from 'node:fs'; +import {createCollection,openCollection,provisionAccount,grantDirect,revokeDirect,prefixOf} from './portal-helpers.mjs'; +import {issueDavCredential} from './dav-credentials.mjs'; +import {call} from './transport.mjs'; + +const series='BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//BusyStack portal qualification//EN\r\nBEGIN:VTIMEZONE\r\nTZID:Fixture/Fixed\r\nBEGIN:STANDARD\r\nDTSTART:19700101T000000\r\nTZOFFSETFROM:+0200\r\nTZOFFSETTO:+0200\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\nBEGIN:VEVENT\r\nUID:portal-series\r\nDTSTAMP:20261101T000000Z\r\nDTSTART;TZID=Fixture/Fixed:20261102T090000\r\nDURATION:P1D\r\nRRULE:FREQ=DAILY;COUNT=3\r\nSUMMARY:Family time\r\nX-PRIVATE:preserve\r\nEND:VEVENT\r\nBEGIN:VEVENT\r\nUID:portal-series\r\nDTSTAMP:20261101T000000Z\r\nRECURRENCE-ID;TZID=Fixture/Fixed:20261103T090000\r\nDTSTART;TZID=Fixture/Fixed:20261103T110000\r\nSUMMARY:Moved occurrence\r\nEND:VEVENT\r\nBEGIN:VEVENT\r\nUID:portal-second\r\nDTSTAMP:20261101T000000Z\r\nDTSTART:20261105T090000Z\r\nSUMMARY:Second event\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n'; +async function importFile(page,base,id,content) { + await page.goto(base+'/portability?destination='+id); + const form=page.locator('form').filter({has:page.locator(`input[name=destination][value="${id}"]`)}); + await form.locator('input[type=file]').setInputFiles({name:'../../untrusted.ics',mimeType:'text/calendar',buffer:Buffer.from(content)}); + await Promise.all([page.waitForURL(base+'/portability/preview'),form.getByRole('button',{name:'Validate and preview import',exact:true}).click()]); + await page.getByRole('heading',{name:'Review your import',exact:true}).waitFor(); +} +async function confirmImport(page,base) { + const form=page.locator('form').filter({has:page.getByRole('button',{name:'Confirm import',exact:true})}); + await form.locator('input[name=confirmed]').check(); + await Promise.all([page.waitForURL(/\/portability\/import\/[a-f0-9-]{36}$/i),form.getByRole('button',{name:'Confirm import',exact:true}).click()]); + await page.getByRole('heading',{name:'Import results',exact:true}).waitFor(); +} +async function resourceUrls(page,base,address,encoded) { + const response=await call(base,new URL(address).pathname.slice(prefixOf(base).length),{method:'PROPFIND',headers:{Authorization:'Basic '+encoded,Depth:'1'},body:''}); + assert.equal(response.status,207); + return page.evaluate(xml=>[...new DOMParser().parseFromString(xml,'application/xml').getElementsByTagNameNS('DAV:','response')].map(r=>r.getElementsByTagNameNS('DAV:','href')[0].textContent).filter(h=>!h.endsWith('/')),response.body); +} +export async function qualifyPersonalPortal(page,base,privateValues,username,suffix='local') { + const name='Portal events '+suffix; + const id=await createCollection(page,base,name,'VEVENT'); + const originalAddress=await page.locator('#collection-address').inputValue(); + const edit=page.locator('form').filter({has:page.getByRole('button',{name:'Save details',exact:true})}); + await edit.locator('input[name=name]').fill(name+' renamed'); + await edit.locator('textarea[name=description]').fill(' family description'); + await edit.locator('input[name=color]').fill('#126A5EFF'); + await Promise.all([page.waitForURL(base+'/collections/'+id),edit.getByRole('button',{name:'Save details',exact:true}).click()]); + assert.equal(await page.locator('#collection-address').inputValue(),originalAddress); + assert.equal(await page.locator('img[src=x]').count(),0); + await importFile(page,base,id,series); + assert.equal(await page.getByRole('cell',{name:'Ready',exact:true}).count(),2); + await confirmImport(page,base); + assert.equal(await page.getByRole('cell',{name:'Imported',exact:true}).count(),2); + const device=await issueDavCredential(page,base,privateValues,'Portal round trip '+suffix,username); + const urls=await resourceUrls(page,base,originalAddress,device.encoded);assert.equal(urls.length,2); + const originalBodies=[]; + for(const url of urls) { + const response=await call(base,new URL(url,base).pathname.slice(prefixOf(base).length),{headers:{Authorization:'Basic '+device.encoded}}); + assert.equal(response.status,200);originalBodies.push(response.body); + } + const recurring=originalBodies.find(s=>s.includes('UID:portal-series')); + assert.ok(recurring.includes('RECURRENCE-ID;TZID=Fixture/Fixed:20261103T090000')); + assert.ok(recurring.includes('DURATION:P1D'));assert.ok(recurring.includes('X-PRIVATE:preserve')); + await page.goto(base+'/collections/'+id); + const downloadPromise=page.waitForEvent('download'); + await page.getByRole('link',{name:'Export iCalendar',exact:true}).click(); + const download=await downloadPromise; + const exported=readFileSync(await download.path()); + assert.equal(exported.toString(),originalBodies.join('')); + const destination=await createCollection(page,base,'Portal migrated '+suffix,'VEVENT'); + const destinationAddress=await page.locator('#collection-address').inputValue(); + await importFile(page,base,destination,exported);await confirmImport(page,base); + const newUrls=await resourceUrls(page,base,destinationAddress,device.encoded);assert.equal(newUrls.length,2); + const migrated=[]; + for(const url of newUrls) migrated.push((await call(base,new URL(url,base).pathname.slice(prefixOf(base).length),{headers:{Authorization:'Basic '+device.encoded}})).body); + assert.deepEqual(migrated.sort(),originalBodies.sort()); + await importFile(page,base,destination,exported); + assert.equal(await page.getByRole('cell',{name:'Skipped',exact:true}).count(),2); + await page.getByRole('button',{name:'Discard preview',exact:true}).click(); + await importFile(page,base,destination,Buffer.from(exported.toString().replace('SUMMARY:Family time','SUMMARY:Conflicting edit'))); + assert.equal(await page.getByRole('cell',{name:'Conflicting',exact:true}).count(),1); + await page.getByRole('button',{name:'Discard preview',exact:true}).click(); + const deniedUpload=await page.evaluate(async target=>{ + const response=await fetch(target,{method:'POST',body:new FormData()});return response.status; + },prefixOf(base)+'/portability/preview'); + assert.equal(deniedUpload,403); + await page.goto(base+'/collections/'+destination+'/delete'); + const withoutConfirmation=await page.evaluate(async ()=>{ + const form=document.querySelector('main form');const data=new URLSearchParams(new FormData(form));data.delete('confirmed'); + return (await fetch(form.action,{method:'POST',body:data})).status; + }); + assert.equal(withoutConfirmation,400); + await page.getByRole('checkbox').check(); + await Promise.all([page.waitForURL(base+'/collections'),page.getByRole('button',{name:'Delete collection permanently',exact:true}).click()]); + assert.ok([403,404].includes((await call(base,new URL(destinationAddress).pathname.slice(prefixOf(base).length),{method:'PROPFIND',headers:{Authorization:'Basic '+device.encoded,Depth:'0'},body:''})).status)); + console.log('PORTAL_COLLECTION_METADATA_IMPORT_EXPORT_ROUNDTRIP_CONFLICTS_AND_CONFIRMED_DELETE_PASSED '+suffix); + return {id,address:originalAddress,device,name:name+' renamed'}; +} + +export async function qualifyPortalPresentation(page,base,collection,administrator=true,suffix='local') { + const output=process.env.BUSYSTACK_PORTAL_EVIDENCE; + if(output) mkdirSync(output,{recursive:true}); + const pages=['/','/collections','/collections/new','/collections/'+collection.id,'/collections/'+collection.id+'/sharing','/connections','/security','/security/credentials','/security/passkeys','/security/sessions','/security/recovery','/security/password','/oauth-grants','/portability','/login']; + if(administrator) pages.push('/admin','/admin/accounts','/admin/accounts/new','/admin/groups','/admin/audit','/admin/diagnostics','/admin/oauth-clients'); + const unexpected=[]; + const observe=request=>{if(!request.url().startsWith(base+'/') && !request.url().startsWith('data:')) unexpected.push(new URL(request.url()).origin);}; + page.on('request',observe); + try { + for(const viewport of [{width:1280,height:900},{width:390,height:844}]) { + await page.setViewportSize(viewport); + for(const path of pages) { + const response=await page.goto(base+path);assert.equal(response.status(),200,path); + assert.equal(await page.locator('main h1').count(),1,path+' must have one primary heading'); + assert.equal(await page.locator('link[rel=stylesheet]').count(),1); + assert.ok(await page.evaluate(()=>getComputedStyle(document.body).backgroundColor!=='rgba(0, 0, 0, 0)'),path+' must be styled'); + assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1),path+' must fit the viewport'); + const unlabeled=await page.locator('input:not([type=hidden]),select,textarea').evaluateAll(elements=>elements.filter(e=>!e.labels?.length && !e.getAttribute('aria-label') && !e.getAttribute('aria-labelledby')).map(e=>e.name||e.id)); + assert.deepEqual(unlabeled,[],path+' control labels'); + await page.keyboard.press('Tab'); + assert.ok(await page.evaluate(()=>document.activeElement.tagName==='A'),'The skip link must be the first keyboard stop'); + await page.keyboard.press('Enter'); + assert.equal(new URL(page.url()).hash,'#main'); + if(output) await page.screenshot({path:output+'/'+suffix+'-'+viewport.width+'-'+path.replaceAll('/','_').replaceAll('?','_')+'.png',fullPage:true}); + } + } + await page.setViewportSize({width:1280,height:900}); + await page.goto(base+'/connections'); + await page.getByRole('button',{name:'Copy server',exact:true}).focus(); + assert.ok(await page.evaluate(()=>getComputedStyle(document.activeElement).outlineStyle!=='none')); + await page.emulateMedia({colorScheme:'dark',reducedMotion:'reduce'}); + await page.goto(base+'/'); + if(output) await page.screenshot({path:output+'/'+suffix+'-dark-overview.png',fullPage:true}); + await page.emulateMedia({colorScheme:'light',reducedMotion:'reduce'}); + assert.deepEqual(unexpected,[],'Frontend assets must remain local'); + } finally {page.off('request',observe);} + console.log('PORTAL_DESKTOP_MOBILE_KEYBOARD_LABEL_FOCUS_AND_LOCAL_ASSETS_PASSED '+suffix); +} diff --git a/qualification/passkeys/recovery.mjs b/qualification/passkeys/recovery.mjs index 1249a93..07baeef 100644 --- a/qualification/passkeys/recovery.mjs +++ b/qualification/passkeys/recovery.mjs @@ -1,3 +1,4 @@ +import {openCollection,provisionAccount,grantDirect,revokeDirect} from './portal-helpers.mjs'; import assert from 'node:assert/strict'; import {readFileSync, writeFileSync} from 'node:fs'; import {randomBytes} from 'node:crypto'; @@ -13,30 +14,17 @@ export async function qualifyRestoration({page, base, privateValues, administrat const prefix = new URL(base).pathname.replace(/\/$/, ''); const federated = process.env.BUSYSTACK_BROWSER_OIDC === 'true'; await page.goto(base + '/'); - const collection = await page.locator('li').filter({has: page.getByText(collectionName, {exact: true})}).locator('code').innerText(); + const collection = await openCollection(page,base,collectionName); const readerUsername = 'restorereader'; const writerUsername = 'restorewriter'; for (const member of [readerUsername, writerUsername]) { - await administratorPage.goto(base + '/admin'); - const provision = administratorPage.locator(`form[action="${prefix}/admin/accounts"]`); const initialPassword = randomBytes(32).toString('base64url'); privateValues.push(initialPassword); - await provision.locator('input[name=username]').fill(member); - await provision.locator('input[name=displayName]').fill('Restore ' + member); - await provision.locator('input[name=password]').fill(initialPassword); - await Promise.all([administratorPage.waitForURL(base + '/admin'), - provision.getByRole('button', {name: 'Create account', exact: true}).click()]); - await administratorPage.getByText(member, {exact: true}).waitFor(); + await provisionAccount(administratorPage,base,member,'Restore '+member,initialPassword); } - await page.goto(base + '/'); for (const [member, permission] of [[readerUsername, 'READ'], [writerUsername, 'WRITE']]) { - const share = page.locator(`form[action="${prefix}/shares"]`).filter({has: page.locator('select[name=collection]')}); - await share.locator('select[name=collection]').selectOption(collection); - await share.locator('input[name=username]').fill(member); - await share.locator('select[name=permission]').selectOption(permission); - await Promise.all([page.waitForURL(base + '/'), share.getByRole('button', {name: 'Save access', exact: true}).click()]); - const row = page.locator('tbody tr').filter({has: page.getByText(member, {exact: true})}); - await row.getByRole('button', {name: 'Remove individual access', exact: true}).waitFor(); + const row=await grantDirect(page,base,collection,member,permission); + await row.getByRole('button',{name:'Save direct grant',exact:true}).waitFor(); } const credential = await issueDavCredential(page, base, privateValues, 'Recovery snapshot device', username); const grant = await qualifyOAuth(page, base, privateValues, administratorPage, @@ -79,9 +67,9 @@ export async function qualifyRestoration({page, base, privateValues, administrat await Promise.all([page.waitForURL(base + '/'), page.getByRole('button', {name: 'Verify passkey', exact: true}).click()]); assert.notEqual((await page.context().cookies()).find(value => value.name === 'JSESSIONID')?.value, oldCookie); console.log('HTTPS_RECOVERY_RECENT_PRIMARY_AND_WEBAUTHN_REAUTHENTICATION_PASSED'); - await page.goto(base + '/'); - const device = page.locator('li').filter({hasText: 'Recovery snapshot device'}); - await Promise.all([page.waitForURL(base + '/'), device.getByRole('button', {name: 'Revoke', exact: true}).click()]); + await page.goto(base + '/security/credentials'); + const device = page.locator('tbody tr').filter({hasText: 'Recovery snapshot device'}); + await Promise.all([page.waitForURL(base + '/security/credentials'), device.getByRole('button', {name: 'Revoke', exact: true}).click()]); await page.goto(base + '/oauth-grants'); const authorization = page.locator('tbody tr').filter({hasText: grant.clientId}); await Promise.all([page.waitForURL(base + '/oauth-grants'), authorization.getByRole('button', {name: 'Revoke access', exact: true}).click()]); @@ -118,7 +106,7 @@ export async function qualifyRestoration({page, base, privateValues, administrat await page.locator('input[name=password]').fill(password); await Promise.all([page.waitForURL(url => accountLocation(url, base)), page.getByRole('button', {name: 'Verify password', exact: true}).click()]); - await page.getByRole('heading', {name: 'BusyStack account', exact: true}).waitFor(); + await page.getByRole('heading', {name: /^Welcome,/}).waitFor(); } await primaryCannotMutate(page, base); await page.goto(base + '/security/passkeys'); @@ -150,7 +138,7 @@ export async function qualifyRestoration({page, base, privateValues, administrat await readerPage.getByRole('button', {name: 'Register passkey', exact: true}).click(); await readerPage.locator('#security-status').filter({hasText: 'Passkey registered.'}).waitFor(); await Promise.all([readerPage.waitForURL(base + '/'), readerPage.getByRole('button', {name: 'Verify passkey to complete MFA', exact: true}).click()]); - await readerPage.locator('li').getByText(collectionName, {exact: true}).waitFor(); + await openCollection(readerPage,base,collectionName); readerCredential = await issueDavCredential(readerPage, base, privateValues, 'Recovered shared read device', readerUsername); } finally { await readerCdp.send('WebAuthn.setAutomaticPresenceSimulation', {authenticatorId: readerAuthenticator.authenticatorId, enabled: false}); @@ -161,14 +149,9 @@ export async function qualifyRestoration({page, base, privateValues, administrat readerEncoded: readerCredential.encoded}), {mode: 0o600}); console.log('READY_RESTORE_VERIFY'); await waitFor('RESTORE_VERIFIED'); - await page.goto(base + '/'); - const readerShares = page.locator('tbody tr').filter({has: page.getByText(readerUsername, {exact: true})}); - const readerShareCount = await readerShares.count(); - const restoredShare = readerShares.filter({has: page.locator(`input[name="collection"][value="${collection}"]`)}); - assert.equal(await restoredShare.count(), 1); - await Promise.all([page.waitForURL(base + '/'), restoredShare.getByRole('button', {name: 'Remove individual access', exact: true}).click()]); - assert.equal(await restoredShare.count(), 0); - assert.equal(await readerShares.count(), readerShareCount - 1); + await revokeDirect(page,base,collection,readerUsername); + const readerShares=page.locator('table').filter({has:page.locator('caption').filter({hasText:'Accounts with direct grants'})}).locator('tbody tr').filter({has:page.getByText(readerUsername,{exact:true})}); + assert.equal(await readerShares.count(),0); console.log('READY_RESTORE_REVOKED_READER_VERIFY'); await waitFor('RESTORE_REVOKED_READER_VERIFIED'); console.log('HTTPS_RESTORE_SHARED_RECIPIENT_FRESH_MFA_READ_WRITE_DENIAL_AND_REVOCATION_PASSED'); diff --git a/qualification/passkeys/run.py b/qualification/passkeys/run.py index cea6b12..86d486c 100644 --- a/qualification/passkeys/run.py +++ b/qualification/passkeys/run.py @@ -214,6 +214,9 @@ def main(): "--env", "BUSYSTACK_BROWSER_READER_PASSWORD_FILE=/fixture/reader-restore-password", "--volume", f"{directory / 'reader-restore-password'}:/fixture/reader-restore-password:ro", "--volume", f"{checkpoint.exchange}:/fixture/recovery.json:rw", "--volume", f"{directory / 'restore-password'}:/fixture/restore-password:ro"] + evidence = ROOT / "target/qualification/portal-browser" / project + evidence.mkdir(parents=True, mode=0o700) + browser_command += ["--volume", f"{evidence}:/evidence:rw", "--env", "BUSYSTACK_PORTAL_EVIDENCE=/evidence"] browser_command.append(args.browser_image) browser = subprocess.Popen( browser_command, diff --git a/qualification/passkeys/sharing_capacity.py b/qualification/passkeys/sharing_capacity.py index 742a3a4..0af1429 100644 --- a/qualification/passkeys/sharing_capacity.py +++ b/qualification/passkeys/sharing_capacity.py @@ -33,7 +33,7 @@ def seed(self): SELECT dav_reconcile_memberships(id) FROM collections WHERE id IN ({collection_ids}); COMMIT;""") self.started=time.monotonic() - current['sharingCapacity']={'firstGroup':self.groups[0],'groupName':'Capacity group 0','initialGrants':12500} + current['sharingCapacity']={'firstGroup':self.groups[0],'groupName':'Capacity group 0','initialGrants':12500,'collections':self.collections} self.checkpoint.exchange.write_text(json.dumps(current)) self.application=self.operations.compose(self.environment,'ps','--quiet','application') inspected=json.loads(self.operations.execute(['docker','inspect',self.application],self.environment))[0] diff --git a/qualification/proxy/nginx.conf.template b/qualification/proxy/nginx.conf.template index 85d566f..df43710 100644 --- a/qualification/proxy/nginx.conf.template +++ b/qualification/proxy/nginx.conf.template @@ -34,6 +34,17 @@ http { proxy_set_header X-Forwarded-Proto ""; proxy_set_header X-Request-ID $request_id; } + location = @@PREFIX@@/portability/preview { + client_max_body_size 9m; + proxy_http_version 1.1; + proxy_connect_timeout 5s; + proxy_read_timeout 120s; + proxy_pass http://application:8080; + proxy_set_header Host @@AUTHORITY@@; + proxy_set_header Forwarded ""; + proxy_set_header X-Forwarded-Host ""; + proxy_set_header X-Forwarded-Proto ""; + } location = @@PREFIX@@/actuator { return 404; } location ^~ @@PREFIX@@/actuator/ { return 404; } location = /actuator { return 404; } diff --git a/src/main/java/org/busystack/caldav/account/AccountService.java b/src/main/java/org/busystack/caldav/account/AccountService.java index 9e421d5..fcd31dc 100644 --- a/src/main/java/org/busystack/caldav/account/AccountService.java +++ b/src/main/java/org/busystack/caldav/account/AccountService.java @@ -175,9 +175,35 @@ public Account find(UUID id) { .orElse(null); } + /** Profile maintenance never changes login identity, roles or external mappings. */ + @Transactional + public void updateDisplayName(UUID id, String expected, String displayName) { + if (displayName == null + || displayName.isBlank() + || displayName.codePointCount(0, displayName.length()) > 200 + || !XmlCharacters.valid(displayName) + || displayName.codePoints().anyMatch(Character::isISOControl)) + throw new IllegalArgumentException( + "Use a display name of 1–200 characters without control characters"); + if (jdbc.update( + "UPDATE accounts SET display_name=? WHERE id=? AND display_name=?", + displayName, + id, + expected) + != 1) + throw new org.busystack.caldav.storage.StoreException( + org.busystack.caldav.storage.StoreException.Kind.PRECONDITION); + } + /** Internal operation; browser issuance must supply recent MFA before calling this service. */ @Transactional public IssuedCredential issueDavCredential(UUID accountId, String label, Instant expiresAt) { + if (label == null + || label.isBlank() + || label.length() > 100 + || !XmlCharacters.valid(label) + || label.codePoints().anyMatch(Character::isISOControl)) + throw new IllegalArgumentException("Use a credential label of 1–100 characters"); Account account = find(accountId); if (account == null || !account.enabled() || !isClientAccessCurrent(accountId)) throw new IllegalArgumentException("Account unavailable"); diff --git a/src/main/java/org/busystack/caldav/calendar/CalendarInterchange.java b/src/main/java/org/busystack/caldav/calendar/CalendarInterchange.java new file mode 100644 index 0000000..34926ec --- /dev/null +++ b/src/main/java/org/busystack/caldav/calendar/CalendarInterchange.java @@ -0,0 +1,300 @@ +package org.busystack.caldav.calendar; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.busystack.caldav.calendar.parser.ParameterInput; +import org.busystack.caldav.calendar.parser.ParsingLimitsHandler; +import org.springframework.stereotype.Component; + +/** + * Lossless framing only; the existing parser and admission service decide all calendar semantics. + */ +@Component +public final class CalendarInterchange { + public static final int MAX_FILE_BYTES = 8 * 1024 * 1024; + public static final int MAX_ITEMS = 1000; + + public record Item( + int number, String uid, String component, String label, byte[] content, String rejection) { + public Item { + content = content.clone(); + } + + @Override + public byte[] content() { + return content.clone(); + } + + @Override + public String toString() { + return "ImportItem[number=" + number + ", content=]"; + } + } + + private record Line(byte[] raw, String value) {} + + private record Frame(byte[] original, byte[] header, byte[] closing, List components) {} + + private final CalendarAdmission admission; + + public CalendarInterchange(CalendarAdmission admission) { + this.admission = admission; + } + + public List read(byte[] file, String destinationComponent) { + if (file == null || file.length == 0 || file.length > MAX_FILE_BYTES) throw invalid(); + List result = new ArrayList<>(); + var budget = new Budget(); + long retainedBytes = 0; + for (Frame frame : frames(file)) { + var model = index(frame.original(), budget); + if (model.size() != frame.components().size()) throw invalid(); + ByteArrayOutputStream zones = new ByteArrayOutputStream(); + Map> groups = new LinkedHashMap<>(); + for (int n = 0; n < model.size(); n++) { + var c = model.get(n); + if (c.type().equals(net.fortuna.ical4j.model.Component.VTIMEZONE)) + zones.writeBytes(frame.components().get(n)); + else { + String uid = c.uid(); + groups.computeIfAbsent(c.type() + "\u0000" + uid, k -> new ArrayList<>()).add(n); + } + } + if (groups.isEmpty()) throw invalid(); + for (var group : groups.values()) { + var first = model.get(group.getFirst()); + String uid = first.uid(); + String label = first.label(); + long size = frame.header().length + (long) zones.size() + frame.closing().length; + for (int index : group) size += frame.components().get(index).length; + if (size <= CalendarContent.MAX_BYTES && retainedBytes + size > 16L * 1024 * 1024) + throw invalid(); + byte[] content = new byte[0]; + if (size <= CalendarContent.MAX_BYTES) { + var bytes = new ByteArrayOutputStream(); + bytes.writeBytes(frame.header()); + bytes.writeBytes(zones.toByteArray()); + for (int index : group) bytes.writeBytes(frame.components().get(index)); + bytes.writeBytes(frame.closing()); + content = groups.size() == 1 ? frame.original() : bytes.toByteArray(); + retainedBytes += content.length; + } + String rejection = ""; + if (!java.util.Set.of("VEVENT", "VTODO").contains(first.type())) + rejection = "Unsupported component type"; + else if (!first.type().equals(destinationComponent)) + rejection = "Does not match the destination collection type"; + else if (size > CalendarContent.MAX_BYTES) + rejection = "UID series exceeds the 1 MiB resource limit"; + else { + try { + var accepted = admission.admit(content, destinationComponent); + content = accepted.content(); + uid = accepted.parsed().uid(); + } catch (IllegalArgumentException + | org.busystack.caldav.calendar.query.QueryException invalid) { + rejection = "Invalid or unsupported calendar data in this UID series"; + } + } + result.add( + new Item( + result.size() + 1, + uid, + first.type(), + label, + rejection.isEmpty() ? content : new byte[0], + rejection)); + if (result.size() > MAX_ITEMS) throw invalid(); + } + } + // Separate VCALENDAR objects must not turn repeated UIDs into an accidental overwrite. + Map counts = + result.stream() + .filter(i -> i.rejection().isEmpty()) + .collect( + java.util.stream.Collectors.groupingBy( + Item::uid, java.util.stream.Collectors.counting())); + return result.stream() + .map( + i -> + counts.getOrDefault(i.uid(), 0L) > 1 + ? new Item( + i.number(), + i.uid(), + i.component(), + i.label(), + i.content(), + "UID occurs in multiple calendar objects; combine its recurrence series before importing") + : i) + .toList(); + } + + private record Indexed(String type, String uid, String label) {} + + private static final class Budget { + int components, properties, parameters; + } + + private static List index(byte[] bytes, Budget budget) { + var handler = new IndexHandler(budget); + try { + String text = CalendarParsingInput.decode(bytes); + CalendarTextProfile.validate(text); + ParameterInput.parse(CalendarParsingInput.reader(text), new ParsingLimitsHandler(handler)); + return List.copyOf(handler.items); + } catch (java.io.IOException + | net.fortuna.ical4j.data.ParserException + | IllegalArgumentException failure) { + throw invalid(); + } + } + + /** Parser callbacks locate series; every emitted resource still passes complete admission. */ + private static final class IndexHandler + implements org.busystack.caldav.calendar.parser.ParameterListHandler { + final Budget budget; + final List items = new ArrayList<>(); + int depth; + String type, uid, label, property; + + IndexHandler(Budget budget) { + this.budget = budget; + } + + @Override + public void startCalendar() {} + + @Override + public void endCalendar() {} + + @Override + public void startComponent(String name) { + if (++budget.components > 2000) throw invalid(); + if (++depth == 1) { + type = name.toUpperCase(java.util.Locale.ROOT); + uid = ""; + label = "Untitled item"; + } + } + + @Override + public void endComponent(String name) { + if (depth-- == 1) items.add(new Indexed(type, uid, label)); + } + + @Override + public void startProperty(String name) { + if (++budget.properties > 20000) throw invalid(); + property = name.toUpperCase(java.util.Locale.ROOT); + } + + @Override + public void endProperty(String name) {} + + @Override + public void propertyValue(String value) { + if (depth != 1) return; + if (property.equals("UID") || property.equals("SUMMARY")) { + try { + CalendarTextValues.scalar(value); + String decoded = CalendarTextValues.list(value).getFirst(); + if (property.equals("UID")) uid = decoded; + else label = decoded; + } catch (IllegalArgumentException ignored) { + if (property.equals("UID")) uid = value; + } + } + } + + @Override + public void parameter(String name, String value) { + parameterValues(name, List.of(value)); + } + + @Override + public void parameterValues(String name, List values) { + budget.parameters += values.size(); + if (budget.parameters > 40000) throw invalid(); + } + } + + private static List frames(byte[] file) { + var lines = lines(file); + List result = new ArrayList<>(); + int cursor = 0; + while (cursor < lines.size()) { + int start = cursor; + if (!lines.get(cursor).value().replace("\uFEFF", "").equalsIgnoreCase("BEGIN:VCALENDAR")) + throw invalid(); + cursor++; + var header = new ByteArrayOutputStream(); + header.writeBytes(lines.get(start).raw()); + List components = new ArrayList<>(); + while (cursor < lines.size() + && !lines.get(cursor).value().equalsIgnoreCase("END:VCALENDAR")) { + Line line = lines.get(cursor); + if (line.value().regionMatches(true, 0, "BEGIN:", 0, 6)) { + int depth = 1, from = cursor++; + while (cursor < lines.size() && depth > 0) { + String value = lines.get(cursor++).value(); + if (value.regionMatches(true, 0, "BEGIN:", 0, 6)) depth++; + else if (value.regionMatches(true, 0, "END:", 0, 4)) depth--; + if (depth > 8) throw invalid(); + } + if (depth != 0) throw invalid(); + components.add(join(lines, from, cursor)); + if (components.size() > 2000) throw invalid(); + } else { + header.writeBytes(line.raw()); + cursor++; + } + } + if (cursor >= lines.size()) throw invalid(); + byte[] closing = lines.get(cursor++).raw(); + result.add( + new Frame( + join(lines, start, cursor), header.toByteArray(), closing, List.copyOf(components))); + if (result.size() > MAX_ITEMS) throw invalid(); + } + if (result.isEmpty()) throw invalid(); + return result; + } + + private static byte[] join(List lines, int from, int until) { + var result = new ByteArrayOutputStream(); + for (int i = from; i < until; i++) result.writeBytes(lines.get(i).raw()); + return result.toByteArray(); + } + + private static List lines(byte[] file) { + List lines = new ArrayList<>(); + int from = 0; + while (from < file.length) { + int end = from; + do { + while (end < file.length && file[end] != '\n') end++; + if (end < file.length) end++; + } while (end < file.length && (file[end] == ' ' || file[end] == '\t')); + byte[] raw = Arrays.copyOfRange(file, from, end); + try { + String logical = CalendarParsingInput.decode(raw); + if (logical.endsWith("\n")) logical = logical.substring(0, logical.length() - 1); + if (logical.endsWith("\r")) logical = logical.substring(0, logical.length() - 1); + lines.add(new Line(raw, logical)); + } catch (java.nio.charset.CharacterCodingException failure) { + throw invalid(); + } + if (lines.size() > 50000) throw invalid(); + from = end; + } + return lines; + } + + private static CalendarValidationException invalid() { + return new CalendarValidationException(CalendarValidationException.Reason.INVALID_DATA); + } +} diff --git a/src/main/java/org/busystack/caldav/config/OperationalProblems.java b/src/main/java/org/busystack/caldav/config/OperationalProblems.java new file mode 100644 index 0000000..0402f75 --- /dev/null +++ b/src/main/java/org/busystack/caldav/config/OperationalProblems.java @@ -0,0 +1,25 @@ +package org.busystack.caldav.config; + +import java.time.Instant; +import java.util.ArrayDeque; +import java.util.List; +import org.springframework.stereotype.Component; + +/** Process-local, bounded operational failures; no request paths, principals or contents. */ +@Component +public final class OperationalProblems { + public record Problem( + Instant time, String requestId, String surface, String method, int status) {} + + private final ArrayDeque recent = new ArrayDeque<>(); + + public synchronized void record(String requestId, String surface, String method, int status) { + if (status < 500) return; + if (recent.size() == 50) recent.removeLast(); + recent.addFirst(new Problem(Instant.now(), requestId, surface, method, status)); + } + + public synchronized List recent() { + return List.copyOf(recent); + } +} diff --git a/src/main/java/org/busystack/caldav/config/PortabilityWorkFilter.java b/src/main/java/org/busystack/caldav/config/PortabilityWorkFilter.java new file mode 100644 index 0000000..033baa1 --- /dev/null +++ b/src/main/java/org/busystack/caldav/config/PortabilityWorkFilter.java @@ -0,0 +1,34 @@ +package org.busystack.caldav.config; + +import jakarta.servlet.*; +import jakarta.servlet.http.*; +import java.io.IOException; +import java.util.concurrent.Semaphore; +import org.springframework.web.filter.OncePerRequestFilter; + +/** Bound concurrent multipart parsing, interchange work and private download files together. */ +final class PortabilityWorkFilter extends OncePerRequestFilter { + private final Semaphore work = new Semaphore(2); + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + String path = request.getRequestURI().substring(request.getContextPath().length()); + return !path.startsWith("/portability/"); + } + + @Override + protected void doFilterInternal( + HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + if (!work.tryAcquire()) { + response.setHeader("Retry-After", "1"); + response.sendError(503); + return; + } + try { + chain.doFilter(request, response); + } finally { + work.release(); + } + } +} diff --git a/src/main/java/org/busystack/caldav/config/RequestDiagnosticsFilter.java b/src/main/java/org/busystack/caldav/config/RequestDiagnosticsFilter.java index f53e7d5..a187ee7 100644 --- a/src/main/java/org/busystack/caldav/config/RequestDiagnosticsFilter.java +++ b/src/main/java/org/busystack/caldav/config/RequestDiagnosticsFilter.java @@ -13,6 +13,12 @@ /** Useful correlation/latency without logging resource paths, identities, headers or bodies. */ final class RequestDiagnosticsFilter extends OncePerRequestFilter { + private final OperationalProblems problems; + + RequestDiagnosticsFilter(OperationalProblems problems) { + this.problems = problems; + } + private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(RequestDiagnosticsFilter.class); @@ -64,6 +70,7 @@ protected void doFilterInternal( method, failed ? 500 : response.getStatus(), TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)); + problems.record(id, surface, method, failed ? 500 : response.getStatus()); if (previous == null) MDC.remove("request_id"); else MDC.put("request_id", previous); } diff --git a/src/main/java/org/busystack/caldav/config/ServletDeploymentConfiguration.java b/src/main/java/org/busystack/caldav/config/ServletDeploymentConfiguration.java index c7bd122..4715ff0 100644 --- a/src/main/java/org/busystack/caldav/config/ServletDeploymentConfiguration.java +++ b/src/main/java/org/busystack/caldav/config/ServletDeploymentConfiguration.java @@ -13,10 +13,10 @@ public class ServletDeploymentConfiguration { @Bean org.springframework.boot.web.servlet.FilterRegistrationBean - requestDiagnostics() { + requestDiagnostics(OperationalProblems problems) { var registration = new org.springframework.boot.web.servlet.FilterRegistrationBean<>( - new RequestDiagnosticsFilter()); + new RequestDiagnosticsFilter(problems)); registration.setOrder(org.springframework.core.Ordered.HIGHEST_PRECEDENCE + 1); return registration; } @@ -31,6 +31,16 @@ public class ServletDeploymentConfiguration { return registration; } + @Bean + org.springframework.boot.web.servlet.FilterRegistrationBean + portabilityWork() { + var registration = + new org.springframework.boot.web.servlet.FilterRegistrationBean<>( + new PortabilityWorkFilter()); + registration.setOrder(org.springframework.core.Ordered.HIGHEST_PRECEDENCE + 2); + return registration; + } + @Bean WebServerFactoryCustomizer deploymentContext( DeploymentProperties deployment, Environment environment) { diff --git a/src/main/java/org/busystack/caldav/management/AdministrationController.java b/src/main/java/org/busystack/caldav/management/AdministrationController.java new file mode 100644 index 0000000..e2fbcb5 --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/AdministrationController.java @@ -0,0 +1,97 @@ +package org.busystack.caldav.management; + +import java.util.UUID; +import org.busystack.caldav.security.audit.SecurityAudit; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +@Controller +public class AdministrationController { + private final AdministrationService administration; + + public AdministrationController(AdministrationService administration) { + this.administration = administration; + } + + @GetMapping("/admin/accounts") + String accounts( + Authentication auth, + @RequestParam(defaultValue = "") String q, + @RequestParam(defaultValue = "all") String status, + @RequestParam(defaultValue = "0") int page, + Model model) { + model.addAttribute("accountPage", administration.accounts(auth, q, status, page)); + model.addAttribute("query", q); + model.addAttribute("filter", status); + return "accounts"; + } + + @GetMapping("/admin/accounts/new") + String create() { + return "account-new"; + } + + @GetMapping("/admin/accounts/{id}") + String account(Authentication auth, @PathVariable UUID id, Model model) { + model.addAttribute("account", administration.account(auth, id)); + return "account-detail"; + } + + @PostMapping("/admin/accounts") + String provision( + Authentication auth, + @RequestParam String username, + @RequestParam String displayName, + @RequestParam String password, + RedirectAttributes flash) { + UUID id = administration.create(auth, username, displayName, password); + flash.addFlashAttribute( + "notice", + "Ordinary account created. Transfer the initial password securely; the user must enroll and verify their own passkey."); + return "redirect:/admin/accounts/" + id; + } + + @PostMapping("/admin/accounts/{id}/edit") + String edit( + Authentication auth, + @PathVariable UUID id, + @RequestParam String expected, + @RequestParam String displayName, + RedirectAttributes flash) { + administration.edit(auth, id, expected, displayName); + flash.addFlashAttribute("notice", "Display name saved."); + return "redirect:/admin/accounts/" + id; + } + + @PostMapping("/admin/accounts/{id}/disable") + String disable( + Authentication auth, + @PathVariable UUID id, + @RequestParam(defaultValue = "false") boolean confirmed, + RedirectAttributes flash) { + administration.disable(auth, id, confirmed); + flash.addFlashAttribute( + "notice", "Account disabled. Browser sessions and client access were revoked."); + return "redirect:/admin/accounts/" + id; + } + + @GetMapping("/admin/audit") + String audit( + Authentication auth, + @RequestParam(defaultValue = "") String action, + @RequestParam(defaultValue = "") String outcome, + @RequestParam(defaultValue = "") String username, + @RequestParam(defaultValue = "0") int page, + Model model) { + model.addAttribute("auditPage", administration.audit(auth, action, outcome, username, page)); + model.addAttribute("actions", SecurityAudit.Action.values()); + model.addAttribute("outcomes", SecurityAudit.Outcome.values()); + model.addAttribute("action", action); + model.addAttribute("outcome", outcome); + model.addAttribute("username", username); + return "audit"; + } +} diff --git a/src/main/java/org/busystack/caldav/management/AdministrationService.java b/src/main/java/org/busystack/caldav/management/AdministrationService.java new file mode 100644 index 0000000..5b6c934 --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/AdministrationService.java @@ -0,0 +1,149 @@ +package org.busystack.caldav.management; + +import java.time.Instant; +import java.util.Set; +import java.util.UUID; +import org.busystack.caldav.account.AccountService; +import org.busystack.caldav.security.audit.SecurityAudit; +import org.busystack.caldav.storage.StoreException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class AdministrationService { + public record AccountView( + UUID id, + String username, + String displayName, + boolean administrator, + boolean enabled, + boolean external) {} + + public record AuditEntry(Instant time, String action, String outcome, String username) {} + + private final ManagementService management; + private final AccountService accounts; + private final JdbcTemplate jdbc; + private final SecurityAudit audit; + private static final String ACCOUNT_SELECT = + "SELECT a.id,a.username,a.display_name,a.administrator,a.enabled,EXISTS(SELECT 1 FROM external_identities e WHERE e.account_id=a.id) AS external FROM accounts a"; + + public AdministrationService( + ManagementService management, + AccountService accounts, + JdbcTemplate jdbc, + SecurityAudit audit) { + this.management = management; + this.accounts = accounts; + this.jdbc = jdbc; + this.audit = audit; + } + + public PortalPage accounts( + Authentication auth, String query, String status, int page) { + management.requireAdministrator(auth); + PortalService.checkQuery(query); + if (!Set.of("all", "enabled", "disabled", "local", "external").contains(status)) + throw new IllegalArgumentException("Invalid account filter"); + String clause = + switch (status) { + case "enabled" -> " AND a.enabled"; + case "disabled" -> " AND NOT a.enabled"; + case "local" -> + " AND NOT EXISTS(SELECT 1 FROM external_identities e WHERE e.account_id=a.id)"; + case "external" -> + " AND EXISTS(SELECT 1 FROM external_identities e WHERE e.account_id=a.id)"; + default -> ""; + }; + return PortalPage.of( + jdbc.query( + ACCOUNT_SELECT + + " WHERE (strpos(lower(a.username),lower(?))>0 OR strpos(lower(a.display_name),lower(?))>0)" + + clause + + " ORDER BY a.username,a.id LIMIT 51 OFFSET ?", + AdministrationService::account, + query, + query, + PortalPage.offset(page)), + page); + } + + public AccountView account(Authentication auth, UUID id) { + management.requireAdministrator(auth); + var rows = jdbc.query(ACCOUNT_SELECT + " WHERE a.id=?", AdministrationService::account, id); + if (rows.isEmpty()) throw new StoreException(StoreException.Kind.NOT_FOUND); + return rows.getFirst(); + } + + @Transactional + public UUID create(Authentication auth, String username, String displayName, String password) { + management.requireAdministrator(auth); + UUID id = accounts.provision(username, displayName, password, false); + audit.record( + management.current(auth).id(), + SecurityAudit.Action.ACCOUNT_CREATED, + SecurityAudit.Outcome.SUCCESS, + null); + return id; + } + + @Transactional + public void edit(Authentication auth, UUID id, String expected, String displayName) { + management.requireAdministrator(auth); + account(auth, id); + accounts.updateDisplayName(id, expected, displayName); + audit.record( + management.current(auth).id(), + SecurityAudit.Action.ACCOUNT_PROFILE_UPDATED, + SecurityAudit.Outcome.SUCCESS, + null); + } + + @Transactional + public void disable(Authentication auth, UUID id, boolean confirmed) { + management.requireAdministrator(auth); + account(auth, id); + if (!confirmed) + throw new IllegalArgumentException("Confirm disabling this account and revoking its access"); + UUID actor = management.current(auth).id(); + accounts.disable(id); + audit.record(actor, SecurityAudit.Action.ACCOUNT_DISABLED, SecurityAudit.Outcome.SUCCESS, null); + } + + public PortalPage audit( + Authentication auth, String action, String outcome, String username, int page) { + management.requireAdministrator(auth); + PortalService.checkQuery(username); + if (!action.isEmpty()) SecurityAudit.Action.valueOf(action); + if (!outcome.isEmpty()) SecurityAudit.Outcome.valueOf(outcome); + return PortalPage.of( + jdbc.query( + "SELECT s.occurred_at,s.action,s.outcome,a.username FROM security_audit s LEFT JOIN accounts a ON a.id=s.account_id WHERE (?='' OR s.action=?) AND (?='' OR s.outcome=?) AND (?='' OR a.username=?) ORDER BY s.id DESC LIMIT 51 OFFSET ?", + (rs, row) -> + new AuditEntry( + rs.getTimestamp(1).toInstant(), + rs.getString(2), + rs.getString(3), + rs.getString(4)), + action, + action, + outcome, + outcome, + username, + username, + PortalPage.offset(page)), + page); + } + + private static AccountView account(java.sql.ResultSet rs, int row) throws java.sql.SQLException { + return new AccountView( + rs.getObject(1, UUID.class), + rs.getString(2), + rs.getString(3), + rs.getBoolean(4), + rs.getBoolean(5), + rs.getBoolean(6)); + } +} diff --git a/src/main/java/org/busystack/caldav/management/DavConnectionAdvice.java b/src/main/java/org/busystack/caldav/management/DavConnectionAdvice.java index 759017c..5a32c82 100644 --- a/src/main/java/org/busystack/caldav/management/DavConnectionAdvice.java +++ b/src/main/java/org/busystack/caldav/management/DavConnectionAdvice.java @@ -6,7 +6,7 @@ import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ModelAttribute; -@ControllerAdvice(assignableTypes = ManagementController.class) +@ControllerAdvice(assignableTypes = {ManagementController.class, PortalController.class}) public final class DavConnectionAdvice { public record Connection(String url, String username, String home, boolean compatibility) {} diff --git a/src/main/java/org/busystack/caldav/management/GroupManagementController.java b/src/main/java/org/busystack/caldav/management/GroupManagementController.java index 4d1fc28..d09f06a 100644 --- a/src/main/java/org/busystack/caldav/management/GroupManagementController.java +++ b/src/main/java/org/busystack/caldav/management/GroupManagementController.java @@ -1,132 +1,119 @@ package org.busystack.caldav.management; -import jakarta.servlet.http.HttpServletResponse; -import java.util.LinkedHashSet; import java.util.Set; import java.util.UUID; -import java.util.stream.Collectors; import org.busystack.caldav.sharing.GroupService; -import org.busystack.caldav.storage.StoreException; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; -/** Group administration and owner-controlled sharing use separate service authorization rules. */ @Controller public class GroupManagementController { - public record GroupForm(UUID id, String name, String usernames, int memberCount) {} - private final GroupService groups; + private final SharingManagementService sharing; - public GroupManagementController(GroupService groups) { + public GroupManagementController(GroupService groups, SharingManagementService sharing) { this.groups = groups; + this.sharing = sharing; } @GetMapping("/admin/groups") - String list(Authentication authentication, Model model) { - model.addAttribute( - "groups", - groups.list(authentication).stream() - .map( - group -> - new GroupForm( - group.id(), - group.name(), - group.members().stream() - .map(GroupService.Member::username) - .collect(Collectors.joining("\n")), - group.members().size())) - .toList()); + String list( + Authentication auth, + @RequestParam(defaultValue = "") String q, + @RequestParam(defaultValue = "0") int page, + Model model) { + model.addAttribute("groupPage", groups.search(auth, q, page)); + model.addAttribute("query", q); return "groups"; } + @GetMapping("/admin/groups/{id}") + String detail( + Authentication auth, + @PathVariable UUID id, + @RequestParam(defaultValue = "") String q, + @RequestParam(defaultValue = "0") int page, + Model model) { + model.addAttribute("group", groups.detail(auth, id)); + model.addAttribute("memberPage", groups.members(auth, id, q, page)); + model.addAttribute("query", q); + return "group-detail"; + } + @PostMapping("/admin/groups") - String create( - Authentication authentication, - @RequestParam String name, - @RequestParam(defaultValue = "") String usernames) { - groups.create(authentication, name, members(usernames)); - return "redirect:/admin/groups"; + String create(Authentication auth, @RequestParam String name, RedirectAttributes flash) { + UUID id = groups.create(auth, name, Set.of()); + flash.addFlashAttribute("notice", "Group created. Add members individually below."); + return "redirect:/admin/groups/" + id; } @PostMapping("/admin/groups/{id}") - String update( - Authentication authentication, + String rename( + Authentication auth, @PathVariable UUID id, + @RequestParam String expected, @RequestParam String name, - @RequestParam(defaultValue = "") String usernames) { - groups.update(authentication, id, name, members(usernames)); - return "redirect:/admin/groups"; + RedirectAttributes flash) { + groups.rename(auth, id, expected, name); + flash.addFlashAttribute("notice", "Group renamed."); + return "redirect:/admin/groups/" + id; + } + + @PostMapping("/admin/groups/{id}/members") + String add( + Authentication auth, + @PathVariable UUID id, + @RequestParam String username, + @RequestParam(defaultValue = "false") boolean confirmed, + RedirectAttributes flash) { + groups.changeMember(auth, id, username, null, true, confirmed); + flash.addFlashAttribute( + "notice", "Member added. Existing group grants now apply to this account."); + return "redirect:/admin/groups/" + id; + } + + @PostMapping("/admin/groups/{id}/members/{account}/remove") + String remove( + Authentication auth, + @PathVariable UUID id, + @PathVariable UUID account, + @RequestParam(defaultValue = "false") boolean confirmed, + RedirectAttributes flash) { + groups.changeMember(auth, id, null, account, false, confirmed); + flash.addFlashAttribute( + "notice", + "Group membership removed. Other direct or group grants may still provide access."); + return "redirect:/admin/groups/" + id; } @PostMapping("/admin/groups/{id}/delete") - String delete(Authentication authentication, @PathVariable UUID id) { - groups.delete(authentication, id); + String delete( + Authentication auth, + @PathVariable UUID id, + @RequestParam(defaultValue = "false") boolean confirmed, + RedirectAttributes flash) { + if (!confirmed) + throw new IllegalArgumentException("Confirm deletion of the group and all its grants"); + groups.delete(auth, id); + flash.addFlashAttribute( + "notice", "Group and its collection grants deleted. Other grants remain effective."); return "redirect:/admin/groups"; } @PostMapping("/group-shares") String share( - Authentication authentication, + Authentication auth, @RequestParam UUID collection, @RequestParam UUID group, - @RequestParam String permission) { - groups.grant(authentication, collection, group, permission); - return "redirect:/"; - } - - @ExceptionHandler(IllegalArgumentException.class) - String invalid(HttpServletResponse response, Model model) { - response.setStatus(400); - model.addAttribute( - "message", - "Check the group name and account usernames. Use a name of 1–200 characters and at most" - + " 1,000 active account usernames, one per line. Sharing requires a valid owned" - + " collection, group and access choice."); - return "group-error"; - } - - @ExceptionHandler(StoreException.class) - String storeFailure(StoreException error, HttpServletResponse response, Model model) { - int status = - switch (error.kind()) { - case NOT_FOUND -> 404; - case FORBIDDEN -> 403; - case LIMIT -> 507; - default -> 409; - }; - response.setStatus(status); - model.addAttribute( - "message", - switch (error.kind()) { - case NOT_FOUND -> "The requested collection no longer exists."; - case FORBIDDEN -> "Only the collection owner can change its group access."; - case LIMIT -> "This request exceeds the supported group or sharing limits."; - default -> - "The request conflicts with the current collection or group state. Refresh the page" - + " before trying again."; - }); - return "group-error"; - } - - private static Set members(String usernames) { - if (usernames.length() > 65536) throw new IllegalArgumentException("Member list too large"); - var result = new LinkedHashSet(); - usernames - .lines() - .map(String::strip) - .filter(value -> !value.isEmpty()) - .forEach( - value -> { - if (result.size() >= 1000 && !result.contains(value)) - throw new IllegalArgumentException("Too many group members"); - result.add(value); - }); - return Set.copyOf(result); + @RequestParam String permission, + @RequestParam String expected, + RedirectAttributes flash) { + sharing.group(auth, collection, group, permission, expected); + flash.addFlashAttribute( + "notice", "Group grant saved. Review effective permissions for remaining access."); + return "redirect:/collections/" + collection + "/sharing"; } } diff --git a/src/main/java/org/busystack/caldav/management/GroupSharingAdvice.java b/src/main/java/org/busystack/caldav/management/GroupSharingAdvice.java deleted file mode 100644 index 287baee..0000000 --- a/src/main/java/org/busystack/caldav/management/GroupSharingAdvice.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.busystack.caldav.management; - -import jakarta.servlet.http.HttpServletRequest; -import org.busystack.caldav.sharing.GroupService; -import org.springframework.security.core.Authentication; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.annotation.ModelAttribute; - -/** The primary-authenticated dashboard needs only group names and the user's owned grants. */ -@ControllerAdvice(assignableTypes = ManagementController.class) -public class GroupSharingAdvice { - private final GroupService groups; - - public GroupSharingAdvice(GroupService groups) { - this.groups = groups; - } - - @ModelAttribute - void sharing(Authentication authentication, HttpServletRequest request, Model model) { - if ("GET".equals(request.getMethod()) && "/".equals(request.getServletPath())) { - model.addAttribute("groupChoices", groups.choices(authentication)); - int page = 0; - String supplied = request.getParameter("group-shares-page"); - if (supplied != null) { - try { - page = Integer.parseInt(supplied); - } catch (NumberFormatException invalid) { - throw new IllegalArgumentException("Invalid group sharing page"); - } - } - var grants = groups.ownedGrants(authentication, page); - model.addAttribute("groupGrants", grants.rows()); - model.addAttribute("groupGrantPage", grants); - } - } -} diff --git a/src/main/java/org/busystack/caldav/management/ImportStaging.java b/src/main/java/org/busystack/caldav/management/ImportStaging.java new file mode 100644 index 0000000..567403e --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/ImportStaging.java @@ -0,0 +1,101 @@ +package org.busystack.caldav.management; + +import jakarta.annotation.PreDestroy; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import org.busystack.caldav.calendar.CalendarInterchange; +import org.busystack.caldav.storage.StoreException; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +/** Private, expiring confirmation files. No calendar bytes or paths are placed in browser state. */ +@Component +public class ImportStaging { + public record Staged( + UUID token, + UUID actor, + UUID epoch, + UUID destination, + Instant expires, + Path path, + long size) {} + + private final Map staged = new HashMap<>(); + private long bytes; + + public synchronized Staged save(UUID actor, UUID epoch, UUID destination, byte[] content) + throws IOException { + prune(); + for (var old : staged.values().stream().filter(s -> s.actor().equals(actor)).toList()) + remove(old); + if (content.length > CalendarInterchange.MAX_FILE_BYTES + || bytes + content.length > 32L * 1024 * 1024 + || staged.size() >= 32) throw new StoreException(StoreException.Kind.LIMIT); + Path path = Files.createTempFile("busystack-import-", ".private"); + try { + Files.write(path, content); + } catch (IOException failure) { + Files.deleteIfExists(path); + throw failure; + } + var stage = + new Staged( + UUID.randomUUID(), + actor, + epoch, + destination, + Instant.now().plusSeconds(600), + path, + content.length); + staged.put(stage.token(), stage); + bytes += content.length; + return stage; + } + + public synchronized Staged owned(UUID token, UUID actor, UUID epoch) { + prune(); + var result = staged.get(token); + if (result == null || !result.actor().equals(actor) || !result.epoch().equals(epoch)) + throw new StoreException(StoreException.Kind.PRECONDITION); + return result; + } + + public synchronized byte[] take(UUID token, UUID actor, UUID epoch) throws IOException { + var stage = owned(token, actor, epoch); + try { + return Files.readAllBytes(stage.path()); + } finally { + remove(stage); + } + } + + public synchronized void cancel(UUID token, UUID actor, UUID epoch) { + remove(owned(token, actor, epoch)); + } + + private void remove(Staged stage) { + try { + Files.deleteIfExists(stage.path()); + } catch (IOException failure) { + throw new IllegalStateException("Temporary import cleanup failed"); + } + if (staged.remove(stage.token()) != null) bytes -= stage.size(); + } + + @Scheduled(fixedDelay = 30000) + public synchronized void prune() { + for (var stage : + staged.values().stream().filter(s -> !s.expires().isAfter(Instant.now())).toList()) + remove(stage); + } + + @PreDestroy + public synchronized void close() { + for (var stage : staged.values().stream().toList()) remove(stage); + } +} diff --git a/src/main/java/org/busystack/caldav/management/IndividualSharingAdvice.java b/src/main/java/org/busystack/caldav/management/IndividualSharingAdvice.java deleted file mode 100644 index 3e9fa95..0000000 --- a/src/main/java/org/busystack/caldav/management/IndividualSharingAdvice.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.busystack.caldav.management; - -import org.springframework.http.HttpStatus; -import org.springframework.security.core.Authentication; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseStatus; - -@ControllerAdvice(assignableTypes = ManagementController.class) -public final class IndividualSharingAdvice { - private final ManagementService management; - - public IndividualSharingAdvice(ManagementService management) { - this.management = management; - } - - @ModelAttribute("individualShares") - ManagementService.SharePage shares( - Authentication authentication, - @RequestParam(name = "shares-page", defaultValue = "0") int page) { - return management.individualShares(authentication, page); - } - - @ExceptionHandler(org.springframework.dao.DataIntegrityViolationException.class) - @ResponseStatus(HttpStatus.CONFLICT) - String conflict() { - return "account-error"; - } - - @ExceptionHandler(org.busystack.caldav.storage.StoreException.class) - String storeFailure( - org.busystack.caldav.storage.StoreException failure, - jakarta.servlet.http.HttpServletResponse response) { - response.setStatus( - switch (failure.kind()) { - case NOT_FOUND -> 404; - case FORBIDDEN -> 403; - case LIMIT -> 507; - case PRECONDITION -> 412; - default -> 409; - }); - return "account-error"; - } - - @ExceptionHandler(IllegalArgumentException.class) - @ResponseStatus(HttpStatus.BAD_REQUEST) - String invalidInput() { - return "account-error"; - } -} diff --git a/src/main/java/org/busystack/caldav/management/ManagementController.java b/src/main/java/org/busystack/caldav/management/ManagementController.java index baea06c..885eccc 100644 --- a/src/main/java/org/busystack/caldav/management/ManagementController.java +++ b/src/main/java/org/busystack/caldav/management/ManagementController.java @@ -5,29 +5,41 @@ import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; @Controller public class ManagementController { private final ManagementService management; + private final PortalService portal; + private final SharingManagementService sharing; - public ManagementController(ManagementService management) { + public ManagementController( + ManagementService management, PortalService portal, SharingManagementService sharing) { this.management = management; + this.portal = portal; + this.sharing = sharing; } @GetMapping("/") String dashboard(Authentication auth, Model model) { model.addAttribute("account", management.current(auth)); - model.addAttribute("externallyManaged", management.externallyManaged(auth)); - model.addAttribute("collections", management.collections(auth)); - model.addAttribute("credentials", management.credentials(auth)); + model.addAttribute("setup", portal.setup(auth)); + model.addAttribute("recentCollections", portal.collections(auth, "all", "", 0)); return "dashboard"; } @PostMapping("/collections") String createCollection( - Authentication auth, @RequestParam String name, @RequestParam String component) { - management.createCollection(auth, name, component); - return "redirect:/"; + Authentication auth, + @RequestParam String name, + @RequestParam String component, + @RequestParam(defaultValue = "") String description, + @RequestParam(defaultValue = "") String color, + RedirectAttributes flash) { + UUID id = portal.create(auth, name, component, description, color); + flash.addFlashAttribute( + "notice", "Collection created. Use Connections to configure your application."); + return "redirect:/collections/" + id; } @PostMapping("/shares") @@ -35,9 +47,14 @@ String share( Authentication auth, @RequestParam UUID collection, @RequestParam String username, - @RequestParam String permission) { - management.share(auth, collection, username, permission); - return "redirect:/"; + @RequestParam String permission, + @RequestParam String expected, + RedirectAttributes flash) { + sharing.direct(auth, collection, username, permission, expected); + flash.addFlashAttribute( + "notice", + "Direct grant saved. Other grants may continue to provide access; review effective permissions below."); + return "redirect:/collections/" + collection + "/sharing"; } @PostMapping("/credentials") @@ -53,30 +70,11 @@ String issue( } @PostMapping("/credentials/{id}/revoke") - String revoke(Authentication auth, @PathVariable UUID id) { + String revoke(Authentication auth, @PathVariable UUID id, RedirectAttributes flash) { management.revoke(auth, id); - return "redirect:/"; - } - - @GetMapping("/admin") - String admin(Authentication auth, Model model) { - model.addAttribute("accounts", management.users(auth)); - return "administration"; - } - - @PostMapping("/admin/accounts") - String provision( - Authentication auth, - @RequestParam String username, - @RequestParam String displayName, - @RequestParam String password) { - management.provision(auth, username, displayName, password); - return "redirect:/admin"; - } - - @PostMapping("/admin/accounts/{id}/disable") - String disable(Authentication auth, @PathVariable UUID id) { - management.disable(auth, id); - return "redirect:/admin"; + flash.addFlashAttribute( + "notice", + "DAV credential revoked. Configure a replacement credential in the affected application."); + return "redirect:/security/credentials"; } } diff --git a/src/main/java/org/busystack/caldav/management/ManagementService.java b/src/main/java/org/busystack/caldav/management/ManagementService.java index 40de729..9bbb8b1 100644 --- a/src/main/java/org/busystack/caldav/management/ManagementService.java +++ b/src/main/java/org/busystack/caldav/management/ManagementService.java @@ -18,7 +18,11 @@ @Service public class ManagementService { public record Credential( - UUID id, String label, Instant created, Instant expires, boolean revoked) {} + UUID id, String label, Instant created, Instant expires, boolean revoked) { + public String status() { + return revoked ? "Revoked" : expires.isAfter(Instant.now()) ? "Active" : "Expired"; + } + } public record UserView( UUID id, String username, String displayName, boolean administrator, boolean enabled) {} @@ -134,7 +138,16 @@ public AccountService.IssuedCredential issue(Authentication auth, String label, @Transactional public void revoke(Authentication auth, UUID credential) { RecentAuthentication.requireMfa(auth); - accounts.revokeDav(requireAccount(auth).id(), credential); + UUID actor = requireAccount(auth).id(); + if (!Boolean.TRUE.equals( + jdbc.queryForObject( + "SELECT EXISTS(SELECT 1 FROM dav_credentials WHERE id=? AND account_id=?)", + Boolean.class, + credential, + actor))) + throw new org.busystack.caldav.storage.StoreException( + org.busystack.caldav.storage.StoreException.Kind.NOT_FOUND); + accounts.revokeDav(actor, credential); } @Transactional @@ -170,7 +183,7 @@ private AccountService.Account requireAccount(Authentication auth) { return account; } - private void requireAdministrator(Authentication auth) { + public void requireAdministrator(Authentication auth) { RecentAuthentication.requireMfa(auth); if (!requireAccount(auth).administrator()) throw new AccessDeniedException("Administrator required"); diff --git a/src/main/java/org/busystack/caldav/management/OperationalDiagnostics.java b/src/main/java/org/busystack/caldav/management/OperationalDiagnostics.java index 11db950..5a1c398 100644 --- a/src/main/java/org/busystack/caldav/management/OperationalDiagnostics.java +++ b/src/main/java/org/busystack/caldav/management/OperationalDiagnostics.java @@ -4,7 +4,6 @@ import java.util.concurrent.TimeUnit; import org.busystack.caldav.config.DeploymentProperties; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; @@ -17,29 +16,43 @@ public final class OperationalDiagnostics { private final JdbcTemplate jdbc; private final MeterRegistry meters; private final DeploymentProperties deployment; + private final org.busystack.caldav.config.OperationalProblems problems; + private final org.springframework.beans.factory.ObjectProvider< + org.springframework.boot.info.BuildProperties> + builds; public OperationalDiagnostics( ManagementService management, JdbcTemplate jdbc, MeterRegistry meters, - DeploymentProperties deployment) { + DeploymentProperties deployment, + org.busystack.caldav.config.OperationalProblems problems, + org.springframework.beans.factory.ObjectProvider< + org.springframework.boot.info.BuildProperties> + builds) { this.management = management; this.jdbc = jdbc; this.meters = meters; this.deployment = deployment; + this.problems = problems; + this.builds = builds; } - @GetMapping("/admin/diagnostics") + @GetMapping({"/admin", "/admin/diagnostics"}) String diagnostics( Authentication authentication, Model model, - jakarta.servlet.http.HttpServletResponse response) { - if (!management.current(authentication).administrator()) - throw new AccessDeniedException("Administrator privilege required"); + jakarta.servlet.http.HttpServletResponse response, + jakarta.servlet.http.HttpServletRequest request) { + management.requireAdministrator(authentication); response.setHeader("Cache-Control", "no-store"); model.addAttribute("baseUrl", deployment.publicBaseUrl().toString()); model.addAttribute("issuer", deployment.issuer().toString()); model.addAttribute("javaVersion", Runtime.version().toString()); + var build = builds.getIfAvailable(); + model.addAttribute( + "applicationVersion", build == null ? "Unknown (development build)" : build.getVersion()); + model.addAttribute("problems", problems.recent()); model.addAttribute( "databaseVersion", jdbc.queryForObject("SELECT current_setting('server_version')", String.class)); @@ -51,6 +64,18 @@ String diagnostics( model.addAttribute( "enabledAccounts", jdbc.queryForObject("SELECT count(*) FROM accounts WHERE enabled", Long.class)); + model.addAttribute( + "disabledAccounts", + jdbc.queryForObject("SELECT count(*) FROM accounts WHERE NOT enabled", Long.class)); + model.addAttribute( + "eventCollections", + jdbc.queryForObject( + "SELECT count(*) FROM collections WHERE component='VEVENT'", Long.class)); + model.addAttribute( + "taskCollections", + jdbc.queryForObject( + "SELECT count(*) FROM collections WHERE component='VTODO'", Long.class)); + model.addAttribute("databaseStatus", "Available — database queries succeeded for this request"); model.addAttribute( "collections", jdbc.queryForObject("SELECT count(*) FROM collections", Long.class)); model.addAttribute( @@ -68,6 +93,6 @@ String diagnostics( model.addAttribute("serverErrors", serverErrors); model.addAttribute("meanMillis", requests == 0 ? 0 : Math.round(total / requests)); model.addAttribute("maxMillis", Math.round(max)); - return "diagnostics"; + return request.getServletPath().equals("/admin") ? "administration" : "diagnostics"; } } diff --git a/src/main/java/org/busystack/caldav/management/PortabilityController.java b/src/main/java/org/busystack/caldav/management/PortabilityController.java new file mode 100644 index 0000000..38b3305 --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/PortabilityController.java @@ -0,0 +1,90 @@ +package org.busystack.caldav.management; + +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.nio.file.Files; +import java.util.UUID; +import org.busystack.caldav.calendar.CalendarInterchange; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +@Controller +public class PortabilityController { + private final PortalService portal; + private final PortabilityService portability; + + public PortabilityController(PortalService portal, PortabilityService portability) { + this.portal = portal; + this.portability = portability; + } + + @GetMapping("/portability") + String page( + Authentication auth, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "") String destination, + Model model) { + model.addAttribute("collectionPage", portal.collections(auth, "all", "", page)); + model.addAttribute("selectedDestination", destination); + return "portability"; + } + + @PostMapping("/portability/preview") + String preview( + Authentication auth, + @RequestParam UUID destination, + @RequestParam MultipartFile file, + Model model) + throws IOException { + if (file.isEmpty() || file.getSize() > CalendarInterchange.MAX_FILE_BYTES) + throw new org.busystack.caldav.storage.StoreException( + org.busystack.caldav.storage.StoreException.Kind.LIMIT); + byte[] content; + try (var input = file.getInputStream()) { + content = input.readNBytes(CalendarInterchange.MAX_FILE_BYTES + 1); + } + if (content.length > CalendarInterchange.MAX_FILE_BYTES) + throw new org.busystack.caldav.storage.StoreException( + org.busystack.caldav.storage.StoreException.Kind.LIMIT); + model.addAttribute("report", portability.preview(auth, destination, content)); + return "import-report"; + } + + @PostMapping("/portability/import/{token}") + String confirm( + Authentication auth, + @PathVariable UUID token, + @RequestParam(defaultValue = "false") boolean confirmed, + Model model) + throws IOException { + model.addAttribute("report", portability.confirm(auth, token, confirmed)); + return "import-report"; + } + + @PostMapping("/portability/import/{token}/cancel") + String cancel(Authentication auth, @PathVariable UUID token, RedirectAttributes flash) { + portability.cancel(auth, token); + flash.addFlashAttribute("notice", "Import preview discarded. No data was imported."); + return "redirect:/portability"; + } + + @GetMapping("/portability/collections/{id}/export") + void export(Authentication auth, @PathVariable UUID id, HttpServletResponse response) + throws IOException { + var export = portability.export(auth, id); + try { + response.setContentType("text/calendar; charset=utf-8"); + response.setHeader("Cache-Control", "no-store"); + response.setHeader( + "Content-Disposition", "attachment; filename=\"busystack-collection.ics\""); + response.setContentLengthLong(export.length()); + Files.copy(export.path(), response.getOutputStream()); + } finally { + Files.deleteIfExists(export.path()); + } + } +} diff --git a/src/main/java/org/busystack/caldav/management/PortabilityService.java b/src/main/java/org/busystack/caldav/management/PortabilityService.java new file mode 100644 index 0000000..a13a91c --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/PortabilityService.java @@ -0,0 +1,215 @@ +package org.busystack.caldav.management; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import org.busystack.caldav.calendar.CalendarInterchange; +import org.busystack.caldav.security.RecentAuthentication; +import org.busystack.caldav.security.audit.SecurityAudit; +import org.busystack.caldav.security.session.SessionSecurity; +import org.busystack.caldav.storage.CalendarStore; +import org.busystack.caldav.storage.DavStore; +import org.busystack.caldav.storage.StoreException; +import org.busystack.caldav.storage.WriteCondition; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class PortabilityService { + public record ItemResult( + int number, String label, String uid, String status, String explanation) {} + + public record Report( + UUID token, + String collectionName, + Instant expires, + List items, + long imported, + long ready, + long skipped, + long conflicts, + long rejected) { + public Report { + items = List.copyOf(items); + } + } + + public record Export(Path path, long length) {} + + private final PortalService portal; + private final SessionSecurity sessions; + private final CalendarStore calendars; + private final DavStore dav; + private final CalendarInterchange interchange; + private final ImportStaging staging; + private final JdbcTemplate jdbc; + private final SecurityAudit audit; + private final java.util.concurrent.Semaphore exports = new java.util.concurrent.Semaphore(2); + + public PortabilityService( + PortalService portal, + SessionSecurity sessions, + CalendarStore calendars, + DavStore dav, + CalendarInterchange interchange, + ImportStaging staging, + JdbcTemplate jdbc, + SecurityAudit audit) { + this.portal = portal; + this.sessions = sessions; + this.calendars = calendars; + this.dav = dav; + this.interchange = interchange; + this.staging = staging; + this.jdbc = jdbc; + this.audit = audit; + } + + @Transactional(isolation = Isolation.REPEATABLE_READ, timeout = 30) + public Report preview(Authentication auth, UUID destination, byte[] file) throws IOException { + RecentAuthentication.requireMfa(auth); + var actor = sessions.assertCurrent(auth); + var collection = portal.collection(auth, destination); + if (!collection.writable()) throw new StoreException(StoreException.Kind.FORBIDDEN); + var items = interchange.read(file, collection.component()); + var results = classify(actor.id(), destination, items, false); + var stage = staging.save(actor.id(), actor.epoch(), destination, file); + return report(stage.token(), collection.name(), stage.expires(), results); + } + + @Transactional(timeout = 30, rollbackFor = IOException.class) + public Report confirm(Authentication auth, UUID token, boolean confirmed) throws IOException { + RecentAuthentication.requireMfa(auth); + var actor = sessions.assertCurrent(auth); + var stage = staging.owned(token, actor.id(), actor.epoch()); + if (!confirmed) throw new IllegalArgumentException("Confirm importing the ready items"); + dav.lockCollection(actor.id(), stage.destination()); + var collection = portal.collection(auth, stage.destination()); + if (!collection.writable()) throw new StoreException(StoreException.Kind.FORBIDDEN); + var items = + interchange.read(staging.take(token, actor.id(), actor.epoch()), collection.component()); + var results = classify(actor.id(), stage.destination(), items, true); + audit.record( + actor.id(), SecurityAudit.Action.COLLECTION_IMPORTED, SecurityAudit.Outcome.SUCCESS, null); + return report(null, collection.name(), null, results); + } + + public void cancel(Authentication auth, UUID token) { + var actor = sessions.assertCurrent(auth); + staging.cancel(token, actor.id(), actor.epoch()); + } + + private List classify( + UUID actor, UUID destination, List items, boolean write) { + List result = new ArrayList<>(); + for (var item : items) { + String status, explanation; + if (!item.rejection().isEmpty()) { + status = "Rejected"; + explanation = item.rejection(); + } else { + var existing = + jdbc.queryForList( + "SELECT name FROM calendar_resources WHERE collection_id=? AND uid=?", + String.class, + destination, + item.uid()); + if (!existing.isEmpty()) { + var stored = calendars.get(actor, destination, existing.getFirst()); + boolean same = Arrays.equals(stored.content(), item.content()); + status = same ? "Skipped" : "Conflicting"; + explanation = + same + ? "Identical stored resource already exists" + : "This UID already exists with different contents; existing data is preserved"; + } else { + status = write ? "Imported" : "Ready"; + explanation = "New UID series; recurrence components remain together"; + if (write) + dav.putResource( + actor, + destination, + "import-" + UUID.randomUUID() + ".ics", + item.content(), + WriteCondition.create()); + } + } + result.add(new ItemResult(item.number(), item.label(), item.uid(), status, explanation)); + } + return List.copyOf(result); + } + + private static Report report(UUID token, String name, Instant expires, List results) { + return new Report( + token, + name, + expires, + results, + count(results, "Imported"), + count(results, "Ready"), + count(results, "Skipped"), + count(results, "Conflicting"), + count(results, "Rejected")); + } + + private static long count(List results, String status) { + return results.stream().filter(i -> i.status().equals(status)).count(); + } + + /** Build the complete download under one committed snapshot before sending success headers. */ + @Transactional(isolation = Isolation.REPEATABLE_READ, timeout = 60) + public Export export(Authentication auth, UUID id) throws IOException { + UUID actor = sessions.assertCurrent(auth).id(); + var collection = calendars.collection(actor, id); + if (!exports.tryAcquire()) throw new StoreException(StoreException.Kind.LIMIT); + Path file = null; + try { + file = Files.createTempFile("busystack-export-", ".private"); + long length = 0; + int count = 0; + String after = ""; + try (var output = Files.newOutputStream(file)) { + while (true) { + var batch = calendars.resourceBatch(actor, id, after); + if (batch.isEmpty()) break; + for (var resource : batch) { + byte[] body = resource.content(); + // Reuse strict validation for legacy invalid resources; never omit them silently. + org.busystack.caldav.calendar.CalendarContent.parse(body, collection.component()); + if (++count > 10000 || length + body.length + 2 > 64L * 1024 * 1024) + throw new StoreException(StoreException.Kind.LIMIT); + output.write(body); + length += body.length; + if (body[body.length - 1] != '\n') { + output.write('\r'); + output.write('\n'); + length += 2; + } + after = resource.name(); + } + } + if (count == 0) { + byte[] empty = + "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//BusyStack//Collection export//EN\r\nEND:VCALENDAR\r\n" + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + output.write(empty); + length = empty.length; + } + } + return new Export(file, length); + } catch (IOException | RuntimeException failure) { + if (file != null) Files.deleteIfExists(file); + throw failure; + } finally { + exports.release(); + } + } +} diff --git a/src/main/java/org/busystack/caldav/management/PortalController.java b/src/main/java/org/busystack/caldav/management/PortalController.java new file mode 100644 index 0000000..8c04143 --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/PortalController.java @@ -0,0 +1,113 @@ +package org.busystack.caldav.management; + +import java.util.UUID; +import org.busystack.caldav.sharing.GroupService; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +@Controller +public class PortalController { + private final PortalService portal; + private final GroupService groups; + + public PortalController(PortalService portal, GroupService groups) { + this.portal = portal; + this.groups = groups; + } + + @GetMapping("/collections") + String collections( + Authentication auth, + @RequestParam(defaultValue = "owned") String scope, + @RequestParam(defaultValue = "") String q, + @RequestParam(defaultValue = "0") int page, + Model model) { + model.addAttribute("collectionPage", portal.collections(auth, scope, q, page)); + model.addAttribute("scope", scope); + model.addAttribute("query", q); + return "collections"; + } + + @GetMapping("/collections/new") + String create() { + return "collection-new"; + } + + @GetMapping("/collections/{id}") + String collection(Authentication auth, @PathVariable UUID id, Model model) { + model.addAttribute("collection", portal.collection(auth, id)); + return "collection"; + } + + @PostMapping("/collections/{id}/edit") + String edit( + Authentication auth, + @PathVariable UUID id, + @RequestParam String state, + @RequestParam String name, + @RequestParam(defaultValue = "") String description, + @RequestParam(defaultValue = "") String color, + RedirectAttributes flash) { + portal.edit(auth, id, state, name, description, color); + flash.addFlashAttribute( + "notice", + "Collection details saved. Existing client addresses and contents are preserved."); + return "redirect:/collections/" + id; + } + + @GetMapping("/collections/{id}/delete") + String confirmDelete(Authentication auth, @PathVariable UUID id, Model model) { + model.addAttribute("collection", portal.owner(auth, id)); + return "collection-delete"; + } + + @PostMapping("/collections/{id}/delete") + String delete( + Authentication auth, + @PathVariable UUID id, + @RequestParam String state, + @RequestParam(defaultValue = "false") boolean confirmed, + RedirectAttributes flash) { + portal.delete(auth, id, state, confirmed); + flash.addFlashAttribute( + "notice", "Collection, its contents and its sharing access were deleted."); + return "redirect:/collections"; + } + + @GetMapping("/collections/{id}/sharing") + String sharing( + Authentication auth, + @PathVariable UUID id, + @RequestParam(defaultValue = "0") int directPage, + @RequestParam(defaultValue = "0") int groupPage, + @RequestParam(defaultValue = "0") int effectivePage, + Model model) { + model.addAttribute("collection", portal.owner(auth, id)); + model.addAttribute("directGrants", portal.direct(auth, id, directPage)); + model.addAttribute("groupGrants", portal.groupGrants(auth, id, groupPage)); + model.addAttribute("effectiveMembers", portal.effective(auth, id, effectivePage)); + model.addAttribute("groupChoices", groups.choices(auth)); + return "collection-sharing"; + } + + @GetMapping("/connections") + String connections(Authentication auth, @RequestParam(defaultValue = "0") int page, Model model) { + model.addAttribute("collectionPage", portal.collections(auth, "all", "", page)); + return "connections"; + } + + @GetMapping("/security") + String security(Authentication auth, Model model) { + model.addAttribute("setup", portal.setup(auth)); + return "security"; + } + + @GetMapping("/security/credentials") + String credentials(Authentication auth, @RequestParam(defaultValue = "0") int page, Model model) { + model.addAttribute("credentialPage", portal.credentials(auth, page)); + return "credentials"; + } +} diff --git a/src/main/java/org/busystack/caldav/management/PortalErrors.java b/src/main/java/org/busystack/caldav/management/PortalErrors.java new file mode 100644 index 0000000..42b549b --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/PortalErrors.java @@ -0,0 +1,126 @@ +package org.busystack.caldav.management; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.util.LinkedHashMap; +import java.util.Map; +import org.busystack.caldav.storage.StoreException; +import org.springframework.dao.DataAccessException; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +/** Safe browser errors; submitted secrets and parser/SQL exception messages never enter pages. */ +@ControllerAdvice( + assignableTypes = { + ManagementController.class, + PortalController.class, + AdministrationController.class, + GroupManagementController.class, + PortabilityController.class + }) +public class PortalErrors { + @ExceptionHandler({ + IllegalArgumentException.class, + StoreException.class, + DataAccessException.class, + org.busystack.caldav.calendar.CalendarValidationException.class, + org.springframework.web.multipart.MaxUploadSizeExceededException.class, + org.springframework.web.bind.MissingServletRequestParameterException.class, + org.springframework.web.method.annotation.MethodArgumentTypeMismatchException.class, + AccessDeniedException.class, + java.io.IOException.class + }) + String failure( + Exception failure, HttpServletRequest request, HttpServletResponse response, Model model) { + int status = 400; + String title = "Check the submitted details"; + String message = + "Review the field limits, destination and access choices shown by the workflow, then try again."; + if (failure instanceof AccessDeniedException) { + status = 403; + title = "Action not allowed"; + message = + "This action requires current permission and primary sign-in plus passkey verification within ten minutes. Verify your factors, then return to the page."; + } else if (failure instanceof StoreException error) { + status = + switch (error.kind()) { + case NOT_FOUND -> 404; + case FORBIDDEN -> 403; + case PRECONDITION -> 412; + case LIMIT -> 413; + default -> 409; + }; + title = + switch (status) { + case 404 -> "Resource unavailable"; + case 403 -> "Permission required"; + case 412 -> "This form is out of date"; + case 413 -> "Supported limit exceeded"; + default -> "The action conflicts with current data"; + }; + message = + switch (status) { + case 404, 403 -> + "The resource is unavailable to this account. An administrator role does not grant access to private collections."; + case 412 -> + "The resource or access changed since this form was opened. Reload its management page and review the current state before trying again."; + case 413 -> + "The request exceeds a supported size, count or processing limit. Use a smaller file or selection."; + default -> + "Existing data has been preserved. Review current names, permissions and UID conflicts before trying again."; + }; + } else if (failure instanceof org.springframework.dao.DataIntegrityViolationException) { + status = 409; + title = "Conflicting details"; + message = + "A name or identifier is already in use, or another request changed the resource. Review the current state and try again."; + } else if (failure instanceof DataAccessException || failure instanceof java.io.IOException) { + status = 503; + title = "Temporarily unavailable"; + message = + "The database operation could not complete. Try again after the operator checks database connectivity and service logs using the request identifier."; + } else if (failure + instanceof org.springframework.web.multipart.MaxUploadSizeExceededException) { + status = 413; + title = "File too large"; + message = "Import files are limited to 8 MiB, with a 1 MiB maximum for each UID series."; + } + response.setStatus(status); + response.setHeader("Cache-Control", "no-store"); + model.addAttribute("errorTitle", title); + model.addAttribute("message", message); + Map submitted = new LinkedHashMap<>(); + for (String name : + new String[] {"name", "displayName", "description", "color", "username", "label"}) { + String value = request.getParameter(name); + if (value != null && value.length() <= 8000) submitted.put(name, value); + } + model.addAttribute("submitted", submitted); + String path = request.getServletPath(); + String retry = "/"; + if (path.equals("/collections")) retry = "/collections/new"; + else if (path.startsWith("/collections/")) retry = path.replaceFirst("/(edit|delete)$", ""); + else if (path.equals("/admin/accounts")) retry = "/admin/accounts/new"; + else if (path.startsWith("/admin/accounts/")) retry = path.replaceFirst("/(edit|disable)$", ""); + else if (path.startsWith("/admin/groups/")) + retry = path.replaceFirst("/members.*$", "").replaceFirst("/delete$", ""); + else if (path.equals("/admin/groups")) retry = path; + else if (path.startsWith("/credentials")) retry = "/security/credentials"; + else if (path.startsWith("/portability")) retry = "/portability"; + else if (path.equals("/shares") || path.equals("/group-shares")) { + try { + retry = + "/collections/" + + java.util.UUID.fromString( + java.util.Objects.requireNonNullElse(request.getParameter("collection"), "")) + + "/sharing"; + } catch (IllegalArgumentException ignored) { + retry = "/collections"; + } + } + model.addAttribute("retryPath", retry); + return "portal-error"; + } +} diff --git a/src/main/java/org/busystack/caldav/management/PortalPage.java b/src/main/java/org/busystack/caldav/management/PortalPage.java new file mode 100644 index 0000000..16071c7 --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/PortalPage.java @@ -0,0 +1,18 @@ +package org.busystack.caldav.management; + +import java.util.List; + +public record PortalPage(List rows, int page, boolean hasNext) { + public PortalPage { + rows = List.copyOf(rows); + } + + public static int offset(int page) { + if (page < 0 || page > 100000) throw new IllegalArgumentException("Invalid page"); + return page * 50; + } + + public static PortalPage of(List rows, int page) { + return new PortalPage<>(rows.subList(0, Math.min(50, rows.size())), page, rows.size() > 50); + } +} diff --git a/src/main/java/org/busystack/caldav/management/PortalPageAdvice.java b/src/main/java/org/busystack/caldav/management/PortalPageAdvice.java new file mode 100644 index 0000000..a140e71 --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/PortalPageAdvice.java @@ -0,0 +1,38 @@ +package org.busystack.caldav.management; + +import jakarta.servlet.http.HttpServletRequest; +import org.busystack.caldav.security.RecentAuthentication; +import org.springframework.security.authentication.AnonymousAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ModelAttribute; + +/** Shared presentation only: authorization remains in the domain services. */ +@ControllerAdvice(annotations = Controller.class) +public class PortalPageAdvice { + private final ManagementService management; + + public PortalPageAdvice(ManagementService management) { + this.management = management; + } + + @ModelAttribute + void layout(Authentication auth, HttpServletRequest request, Model model) { + String path = request.getServletPath(); + model.addAttribute("portalPath", path); + model.addAttribute("administrationArea", path.startsWith("/admin")); + model.addAttribute("viewer", null); + model.addAttribute("primaryCurrent", RecentAuthentication.primaryCurrent(auth)); + model.addAttribute("mfaCurrent", RecentAuthentication.mfaCurrent(auth)); + if (auth != null && auth.isAuthenticated() && !(auth instanceof AnonymousAuthenticationToken)) { + try { + model.addAttribute("viewer", management.current(auth)); + model.addAttribute("externallyManaged", management.externallyManaged(auth)); + } catch (org.springframework.security.access.AccessDeniedException unavailable) { + // Error pages must remain renderable after a disabled or ended session. + } + } + } +} diff --git a/src/main/java/org/busystack/caldav/management/PortalService.java b/src/main/java/org/busystack/caldav/management/PortalService.java new file mode 100644 index 0000000..59e28f4 --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/PortalService.java @@ -0,0 +1,375 @@ +package org.busystack.caldav.management; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import javax.xml.namespace.QName; +import org.busystack.caldav.config.DeploymentProperties; +import org.busystack.caldav.protocol.DavPaths; +import org.busystack.caldav.protocol.DavXml; +import org.busystack.caldav.security.RecentAuthentication; +import org.busystack.caldav.security.audit.SecurityAudit; +import org.busystack.caldav.security.audit.SecurityHashes; +import org.busystack.caldav.storage.CalendarStore; +import org.busystack.caldav.storage.DavStore; +import org.busystack.caldav.storage.StoreException; +import org.busystack.caldav.storage.WriteCondition; +import org.busystack.caldav.xml.XmlCharacters; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** Bounded browser projections and compound operations over the authoritative DAV stores. */ +@Service +public class PortalService { + public static final QName DESCRIPTION = new QName(DavXml.CAL, "calendar-description"); + public static final QName COLOR = new QName("http://apple.com/ns/ical/", "calendar-color"); + private static final QName NAME = new QName(DavXml.DAV, "displayname"); + + public record CollectionView( + UUID id, + String name, + String component, + String ownerName, + String permission, + String description, + String color, + String address, + String state, + String deletionState) { + public String type() { + return "VTODO".equals(component) ? "Task list" : "Calendar"; + } + + public String access() { + return accessLabel(permission); + } + + public boolean owned() { + return "OWNER".equals(permission); + } + + public boolean writable() { + return !"READ".equals(permission); + } + } + + public record Setup( + long passkeys, long owned, long shared, long credentials, long recoveryCodes) {} + + public record DirectGrant( + String username, String permission, boolean enabled, String effective) {} + + public record GroupGrant(UUID id, String name, String permission) {} + + public record EffectiveMember( + String username, boolean enabled, String permission, boolean direct, long groups) { + public String access() { + return enabled ? accessLabel(permission) : "Disabled — access denied"; + } + } + + private final ManagementService management; + private final CalendarStore calendars; + private final DavStore dav; + private final JdbcTemplate jdbc; + private final DavPaths paths; + private final SecurityAudit audit; + + public PortalService( + ManagementService management, + CalendarStore calendars, + DavStore dav, + JdbcTemplate jdbc, + DeploymentProperties deployment, + SecurityAudit audit) { + this.management = management; + this.calendars = calendars; + this.dav = dav; + this.jdbc = jdbc; + this.paths = new DavPaths(deployment); + this.audit = audit; + } + + public Setup setup(Authentication auth) { + UUID actor = management.current(auth).id(); + return jdbc.queryForObject( + "SELECT " + + "(SELECT count(*) FROM user_credentials k JOIN user_entities u ON u.id=k.user_entity_user_id WHERE u.account_id=?)," + + "(SELECT count(*) FROM collections WHERE owner_id=?)," + + "(SELECT count(*) FROM collections c JOIN collection_effective_members m ON m.collection_id=c.id WHERE m.account_id=? AND c.owner_id<>?)," + + "(SELECT count(*) FROM dav_credentials WHERE account_id=? AND revoked_at IS NULL AND expires_at>now())," + + "(SELECT count(*) FROM account_recovery_codes WHERE account_id=? AND used_at IS NULL AND revoked_at IS NULL AND recovery_epoch=(SELECT recovery_epoch FROM system_state WHERE id=1) AND expires_at>now())", + (rs, row) -> + new Setup(rs.getLong(1), rs.getLong(2), rs.getLong(3), rs.getLong(4), rs.getLong(5)), + actor, + actor, + actor, + actor, + actor, + actor); + } + + @Transactional(isolation = org.springframework.transaction.annotation.Isolation.REPEATABLE_READ) + public PortalPage collections( + Authentication auth, String scope, String query, int page) { + UUID actor = management.current(auth).id(); + checkQuery(query); + if (!Set.of("owned", "shared", "all", "writable").contains(scope)) + throw new IllegalArgumentException("Invalid collection filter"); + String restriction = + switch (scope) { + case "owned" -> " AND c.owner_id=?"; + case "shared" -> " AND c.owner_id<>?"; + case "writable" -> " AND (c.owner_id=? OR e.permission='WRITE')"; + default -> ""; + }; + List args = new ArrayList<>(List.of(actor, actor, actor)); + if (!scope.equals("all")) args.add(actor); + args.add(query); + args.add(PortalPage.offset(page)); + var rows = + jdbc.query( + "SELECT c.id,c.name,c.component,a.display_name," + + "CASE WHEN c.owner_id=? THEN 'OWNER' ELSE e.permission END AS permission,b.path," + + "d.xml AS description,k.xml AS color FROM collections c " + + "JOIN accounts a ON a.id=c.owner_id JOIN dav_bindings b ON b.collection_id=c.id AND b.home_id=? " + + "LEFT JOIN collection_effective_members e ON e.collection_id=c.id AND e.account_id=? " + + "LEFT JOIN dav_collection_properties d ON d.collection_id=c.id AND d.namespace='urn:ietf:params:xml:ns:caldav' AND d.name='calendar-description' " + + "LEFT JOIN dav_collection_properties k ON k.collection_id=c.id AND k.namespace='http://apple.com/ns/ical/' AND k.name='calendar-color' " + + "WHERE (c.owner_id=b.home_id OR e.account_id IS NOT NULL)" + + restriction + + " AND strpos(lower(c.name),lower(?))>0 ORDER BY lower(c.name),c.id LIMIT 51 OFFSET ?", + (rs, row) -> + new CollectionView( + rs.getObject(1, UUID.class), + rs.getString(2), + rs.getString(3), + rs.getString(4), + rs.getString(5), + text(rs.getString(7)), + text(rs.getString(8)), + address(actor, rs.getString(6)), + "", + ""), + args.toArray()); + return PortalPage.of(rows, page); + } + + public CollectionView collection(Authentication auth, UUID id) { + UUID actor = management.current(auth).id(); + var collection = calendars.collection(actor, id); + var binding = dav.bindingFor(actor, id); + if (binding == null) throw new StoreException(StoreException.Kind.NOT_FOUND); + var props = dav.deadProperties(actor, id, null, Set.of(DESCRIPTION, COLOR)); + String description = text(props.get(DESCRIPTION)), color = text(props.get(COLOR)); + String state = + SecurityHashes.sha256( + id + + "\n" + + collection.name() + + "\n" + + binding.path() + + "\n" + + props.get(DESCRIPTION) + + "\n" + + props.get(COLOR)); + String deletion = state + ":" + collection.generation() + ":" + collection.revision(); + return new CollectionView( + id, + collection.name(), + collection.component(), + jdbc.queryForObject( + "SELECT display_name FROM accounts WHERE id=?", String.class, collection.owner()), + dav.permission(actor, id), + description, + color, + address(actor, binding.path()), + state, + deletion); + } + + @Transactional + public UUID create( + Authentication auth, String name, String component, String description, String color) { + RecentAuthentication.requireMfa(auth); + UUID actor = management.current(auth).id(); + validateMetadata(name, description, color); + if (!Set.of("VEVENT", "VTODO").contains(component)) + throw new IllegalArgumentException("Choose a calendar or task list"); + UUID id = calendars.createCollection(actor, name, component); + var binding = dav.bindingFor(actor, id); + dav.patch(actor, actor, binding.path(), null, properties(name, description, color), Set.of()); + audit.record( + actor, SecurityAudit.Action.COLLECTION_CREATED, SecurityAudit.Outcome.SUCCESS, null); + return id; + } + + @Transactional + public void edit( + Authentication auth, UUID id, String state, String name, String description, String color) { + RecentAuthentication.requireMfa(auth); + UUID actor = management.current(auth).id(); + var entry = dav.lockCollection(actor, id); + var current = collection(auth, id); + checkState(state, current.state()); + validateMetadata(name, description, color); + dav.patch( + actor, actor, entry.binding().path(), null, properties(name, description, color), Set.of()); + audit.record( + actor, SecurityAudit.Action.COLLECTION_UPDATED, SecurityAudit.Outcome.SUCCESS, null); + } + + @Transactional + public void delete(Authentication auth, UUID id, String state, boolean confirmed) { + RecentAuthentication.requireMfa(auth); + UUID actor = management.current(auth).id(); + var entry = dav.lockCollection(actor, id); + var current = owner(auth, id); + if (!confirmed) + throw new IllegalArgumentException("Confirm deletion of the collection and its contents"); + checkState(state, current.deletionState()); + dav.deleteBinding( + actor, actor, entry.binding().path(), WriteCondition.match(DavStore.bindingEtag(entry))); + audit.record( + actor, SecurityAudit.Action.COLLECTION_DELETED, SecurityAudit.Outcome.SUCCESS, null); + } + + public CollectionView owner(Authentication auth, UUID id) { + var result = collection(auth, id); + if (!result.owned()) throw new StoreException(StoreException.Kind.FORBIDDEN); + return result; + } + + public PortalPage direct(Authentication auth, UUID id, int page) { + owner(auth, id); + return PortalPage.of( + jdbc.query( + "SELECT a.username,m.permission,a.enabled,e.permission FROM collection_members m JOIN accounts a ON a.id=m.account_id LEFT JOIN collection_effective_members e ON e.collection_id=m.collection_id AND e.account_id=m.account_id WHERE m.collection_id=? ORDER BY a.username LIMIT 51 OFFSET ?", + (rs, row) -> + new DirectGrant( + rs.getString(1), rs.getString(2), rs.getBoolean(3), rs.getString(4)), + id, + PortalPage.offset(page)), + page); + } + + public PortalPage groupGrants(Authentication auth, UUID id, int page) { + owner(auth, id); + return PortalPage.of( + jdbc.query( + "SELECT g.id,g.name,m.permission FROM collection_group_members m JOIN sharing_groups g ON g.id=m.group_id WHERE m.collection_id=? ORDER BY g.name,g.id LIMIT 51 OFFSET ?", + (rs, row) -> + new GroupGrant(rs.getObject(1, UUID.class), rs.getString(2), rs.getString(3)), + id, + PortalPage.offset(page)), + page); + } + + public PortalPage effective(Authentication auth, UUID id, int page) { + owner(auth, id); + return PortalPage.of( + jdbc.query( + "SELECT a.username,a.enabled,e.permission,EXISTS(SELECT 1 FROM collection_members d WHERE d.collection_id=e.collection_id AND d.account_id=e.account_id)," + + "(SELECT count(*) FROM collection_group_members g JOIN sharing_group_members m ON m.group_id=g.group_id WHERE g.collection_id=e.collection_id AND m.account_id=e.account_id) " + + "FROM collection_effective_members e JOIN accounts a ON a.id=e.account_id JOIN collections c ON c.id=e.collection_id WHERE e.collection_id=? AND e.account_id<>c.owner_id ORDER BY a.username LIMIT 51 OFFSET ?", + (rs, row) -> + new EffectiveMember( + rs.getString(1), + rs.getBoolean(2), + rs.getString(3), + rs.getBoolean(4), + rs.getLong(5)), + id, + PortalPage.offset(page)), + page); + } + + public PortalPage credentials(Authentication auth, int page) { + UUID actor = management.current(auth).id(); + return PortalPage.of( + jdbc.query( + "SELECT id,label,created_at,expires_at,revoked_at FROM dav_credentials WHERE account_id=? ORDER BY created_at DESC,id LIMIT 51 OFFSET ?", + (rs, row) -> + new ManagementService.Credential( + rs.getObject(1, UUID.class), + rs.getString(2), + rs.getTimestamp(3).toInstant(), + rs.getTimestamp(4).toInstant(), + rs.getTimestamp(5) != null), + actor, + PortalPage.offset(page)), + page); + } + + private String address(UUID actor, String path) { + List parts = new ArrayList<>(List.of("calendars", actor.toString())); + parts.addAll(List.of(path.split("/"))); + return paths.href(parts, true); + } + + private static Map properties(String name, String description, String color) { + Map result = new LinkedHashMap<>(); + result.put(NAME, xml(NAME, name)); + result.put(DESCRIPTION, xml(DESCRIPTION, description)); + result.put(COLOR, xml(COLOR, color)); + return result; + } + + private static String xml(QName name, String value) { + return "" + + value + .replace("&", "&") + .replace("<", "<") + .replace(">", ">") + .replace("\r", " ") + + ""; + } + + private static String text(String xml) { + return xml == null ? "" : DavXml.parse(xml.getBytes(StandardCharsets.UTF_8)).getTextContent(); + } + + private static void validateMetadata(String name, String description, String color) { + if (name == null + || name.isBlank() + || name.length() > 200 + || !XmlCharacters.valid(name) + || description == null + || description.length() > 8000 + || !XmlCharacters.valid(description) + || color == null + || (!color.isEmpty() && !color.matches("#[a-fA-F0-9]{6}([a-fA-F0-9]{2})?"))) + throw new IllegalArgumentException( + "Use a name of 1–200 characters, a description up to 8,000 characters and an optional hexadecimal colour"); + } + + static void checkQuery(String query) { + if (query == null || query.length() > 200) + throw new IllegalArgumentException("Search is limited to 200 characters"); + } + + public static void checkState(String supplied, String current) { + if (supplied == null || !supplied.equals(current)) + throw new StoreException(StoreException.Kind.PRECONDITION); + } + + public static String accessLabel(String permission) { + return switch (permission) { + case "OWNER" -> "Owner"; + case "WRITE" -> "Read and write"; + default -> "Read-only"; + }; + } +} diff --git a/src/main/java/org/busystack/caldav/management/SharingManagementService.java b/src/main/java/org/busystack/caldav/management/SharingManagementService.java new file mode 100644 index 0000000..44c7ddf --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/SharingManagementService.java @@ -0,0 +1,75 @@ +package org.busystack.caldav.management; + +import java.util.UUID; +import org.busystack.caldav.security.RecentAuthentication; +import org.busystack.caldav.security.audit.SecurityAudit; +import org.busystack.caldav.sharing.GroupService; +import org.busystack.caldav.storage.DavStore; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class SharingManagementService { + private final PortalService portal; + private final ManagementService management; + private final DavStore dav; + private final GroupService groups; + private final JdbcTemplate jdbc; + private final SecurityAudit audit; + + public SharingManagementService( + PortalService portal, + ManagementService management, + DavStore dav, + GroupService groups, + JdbcTemplate jdbc, + SecurityAudit audit) { + this.portal = portal; + this.management = management; + this.dav = dav; + this.groups = groups; + this.jdbc = jdbc; + this.audit = audit; + } + + @Transactional + public void direct( + Authentication auth, UUID collection, String username, String permission, String expected) { + RecentAuthentication.requireMfa(auth); + UUID actor = management.current(auth).id(); + dav.lockCollection(actor, collection); + portal.owner(auth, collection); + var current = + jdbc.queryForList( + "SELECT m.permission FROM collection_members m JOIN accounts a ON a.id=m.account_id WHERE m.collection_id=? AND a.username=?", + String.class, + collection, + username); + PortalService.checkState(expected, current.isEmpty() ? "NONE" : current.getFirst()); + management.share(auth, collection, username, permission); + audit.record( + actor, + SecurityAudit.Action.INDIVIDUAL_SHARING_CHANGED, + SecurityAudit.Outcome.SUCCESS, + null); + } + + @Transactional + public void group( + Authentication auth, UUID collection, UUID group, String permission, String expected) { + RecentAuthentication.requireMfa(auth); + UUID actor = management.current(auth).id(); + dav.lockCollection(actor, collection); + portal.owner(auth, collection); + var current = + jdbc.queryForList( + "SELECT permission FROM collection_group_members WHERE collection_id=? AND group_id=?", + String.class, + collection, + group); + PortalService.checkState(expected, current.isEmpty() ? "NONE" : current.getFirst()); + groups.grant(auth, collection, group, permission); + } +} diff --git a/src/main/java/org/busystack/caldav/security/RecentAuthentication.java b/src/main/java/org/busystack/caldav/security/RecentAuthentication.java index f323d99..4cba64e 100644 --- a/src/main/java/org/busystack/caldav/security/RecentAuthentication.java +++ b/src/main/java/org/busystack/caldav/security/RecentAuthentication.java @@ -12,6 +12,24 @@ public final class RecentAuthentication { private RecentAuthentication() {} + public static boolean primaryCurrent(Authentication authentication) { + try { + requirePrimary(authentication); + return true; + } catch (AccessDeniedException unavailable) { + return false; + } + } + + public static boolean mfaCurrent(Authentication authentication) { + try { + requireMfa(authentication); + return true; + } catch (AccessDeniedException unavailable) { + return false; + } + } + public static void requirePassword(Authentication authentication) { if (!has(authentication, FactorGrantedAuthority.PASSWORD_AUTHORITY)) throw new AccessDeniedException("Recent password authentication is required"); diff --git a/src/main/java/org/busystack/caldav/security/audit/SecurityAudit.java b/src/main/java/org/busystack/caldav/security/audit/SecurityAudit.java index 94a1c8d..289035b 100644 --- a/src/main/java/org/busystack/caldav/security/audit/SecurityAudit.java +++ b/src/main/java/org/busystack/caldav/security/audit/SecurityAudit.java @@ -10,6 +10,7 @@ @Service public class SecurityAudit { public enum Action { + DATABASE_RESTORE, PASSWORD_LOGIN, PASSWORD_CHANGED, ACCOUNT_DISABLED, @@ -21,7 +22,14 @@ public enum Action { GROUP_CREATED, GROUP_UPDATED, GROUP_DELETED, - GROUP_SHARING_CHANGED + GROUP_SHARING_CHANGED, + COLLECTION_CREATED, + COLLECTION_UPDATED, + COLLECTION_DELETED, + COLLECTION_IMPORTED, + INDIVIDUAL_SHARING_CHANGED, + ACCOUNT_CREATED, + ACCOUNT_PROFILE_UPDATED } public enum Outcome { diff --git a/src/main/java/org/busystack/caldav/sharing/GroupService.java b/src/main/java/org/busystack/caldav/sharing/GroupService.java index 4e34b97..47bc151 100644 --- a/src/main/java/org/busystack/caldav/sharing/GroupService.java +++ b/src/main/java/org/busystack/caldav/sharing/GroupService.java @@ -29,6 +29,131 @@ public record Group(UUID id, String name, List members) { public record Choice(UUID id, String name) {} + public record Summary(UUID id, String name, long members, long grants) {} + + public record MemberView(UUID account, String username, String displayName, boolean enabled) {} + + public org.busystack.caldav.management.PortalPage search( + Authentication auth, String query, int page) { + administrator(auth); + if (query == null || query.length() > 200) + throw new IllegalArgumentException("Search is limited to 200 characters"); + return org.busystack.caldav.management.PortalPage.of( + jdbc.query( + "SELECT g.id,g.name,(SELECT count(*) FROM sharing_group_members m WHERE m.group_id=g.id),(SELECT count(*) FROM collection_group_members c WHERE c.group_id=g.id) FROM sharing_groups g WHERE strpos(lower(g.name),lower(?))>0 ORDER BY g.name,g.id LIMIT 51 OFFSET ?", + (rs, row) -> + new Summary( + rs.getObject(1, UUID.class), rs.getString(2), rs.getLong(3), rs.getLong(4)), + query, + org.busystack.caldav.management.PortalPage.offset(page)), + page); + } + + public Summary detail(Authentication auth, UUID group) { + administrator(auth); + var rows = + jdbc.query( + "SELECT g.id,g.name,(SELECT count(*) FROM sharing_group_members m WHERE m.group_id=g.id),(SELECT count(*) FROM collection_group_members c WHERE c.group_id=g.id) FROM sharing_groups g WHERE g.id=?", + (rs, row) -> + new Summary( + rs.getObject(1, UUID.class), rs.getString(2), rs.getLong(3), rs.getLong(4)), + group); + if (rows.isEmpty()) throw new StoreException(StoreException.Kind.NOT_FOUND); + return rows.getFirst(); + } + + public org.busystack.caldav.management.PortalPage members( + Authentication auth, UUID group, String query, int page) { + administrator(auth); + requireGroup(group); + if (query == null || query.length() > 200) + throw new IllegalArgumentException("Search is limited to 200 characters"); + return org.busystack.caldav.management.PortalPage.of( + jdbc.query( + "SELECT a.id,a.username,a.display_name,a.enabled FROM sharing_group_members m JOIN accounts a ON a.id=m.account_id WHERE m.group_id=? AND (strpos(lower(a.username),lower(?))>0 OR strpos(lower(a.display_name),lower(?))>0) ORDER BY a.username,a.id LIMIT 51 OFFSET ?", + (rs, row) -> + new MemberView( + rs.getObject(1, UUID.class), + rs.getString(2), + rs.getString(3), + rs.getBoolean(4)), + group, + query, + query, + org.busystack.caldav.management.PortalPage.offset(page)), + page); + } + + @Transactional(timeout = 30) + public void rename(Authentication auth, UUID group, String expected, String name) { + RecentAuthentication.requireMfa(auth); + DavMutationLock.exclusive(jdbc); + UUID actor = administrator(auth); + requireGroup(group); + validateName(name); + uniqueName(name, group); + lockAffected(group); + if (jdbc.update("UPDATE sharing_groups SET name=? WHERE id=? AND name=?", name, group, expected) + != 1) throw new StoreException(StoreException.Kind.PRECONDITION); + reconcileAffected(group); + audit.record( + actor, + org.busystack.caldav.security.audit.SecurityAudit.Action.GROUP_UPDATED, + org.busystack.caldav.security.audit.SecurityAudit.Outcome.SUCCESS, + null); + } + + @Transactional(timeout = 30) + public void changeMember( + Authentication auth, + UUID group, + String username, + UUID member, + boolean add, + boolean confirmed) { + RecentAuthentication.requireMfa(auth); + DavMutationLock.exclusive(jdbc); + UUID actor = administrator(auth); + requireGroup(group); + if (!confirmed) + throw new IllegalArgumentException("Confirm the effect on existing group sharing"); + if (add) member = accounts(Set.of(username)).iterator().next(); + if (member == null) throw new IllegalArgumentException("An account is required"); + lockAffected(group); + if (add + && !Boolean.TRUE.equals( + jdbc.queryForObject( + "SELECT EXISTS(SELECT 1 FROM sharing_group_members WHERE group_id=? AND account_id=?)", + Boolean.class, + group, + member))) { + if (jdbc.queryForObject( + "SELECT count(*) FROM sharing_group_members WHERE group_id=?", Long.class, group) + >= 1000 + || jdbc.queryForObject("SELECT count(*) FROM sharing_group_members", Long.class) >= 10000) + limit(); + } + jdbc.query("SELECT set_config('busystack.defer_dav_bindings','on',true)", rs -> {}); + int changed = + add + ? jdbc.update( + "INSERT INTO sharing_group_members(group_id,account_id) VALUES (?,?) ON CONFLICT DO NOTHING", + group, + member) + : jdbc.update( + "DELETE FROM sharing_group_members WHERE group_id=? AND account_id=?", + group, + member); + if (changed != 1) throw new StoreException(StoreException.Kind.PRECONDITION); + reconcileAffected(group); + jdbc.query("SELECT set_config('busystack.defer_dav_bindings','off',true)", rs -> {}); + audit.record( + actor, + org.busystack.caldav.security.audit.SecurityAudit.Action.GROUP_UPDATED, + org.busystack.caldav.security.audit.SecurityAudit.Outcome.SUCCESS, + null); + } + public record Grant( UUID collection, String collectionName, UUID group, String groupName, String permission) {} diff --git a/src/main/java/org/busystack/caldav/storage/DavStore.java b/src/main/java/org/busystack/caldav/storage/DavStore.java index 07831a8..d1c3d11 100644 --- a/src/main/java/org/busystack/caldav/storage/DavStore.java +++ b/src/main/java/org/busystack/caldav/storage/DavStore.java @@ -61,6 +61,18 @@ public DavStore(JdbcTemplate jdbc, CalendarStore calendars) { this.calendars = calendars; } + /** Acquire the existing namespace/collection locks for a compound browser operation. */ + @Transactional + public Entry lockCollection(UUID actor, UUID collection) { + org.busystack.caldav.storage.DavMutationLock.shared(jdbc); + writableHome(actor, actor); + lockHomes(actor); + Binding binding = bindingFor(actor, collection); + if (binding == null) missing(); + lockCollections(collection); + return resolve(actor, actor, binding.path()); + } + public Entry resolve(UUID actor, UUID home, String path) { requireEnabled(actor); checkPath(path, true); diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index daccb1e..a60c039 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -17,6 +17,11 @@ spring: flyway: validate-on-migrate: true clean-disabled: true + servlet: + multipart: + max-file-size: 8MB + max-request-size: 9MB + file-size-threshold: 0 mvc: log-request-details: false dispatch-options-request: true diff --git a/src/main/resources/static/assets/account.css b/src/main/resources/static/assets/account.css index 2f869bf..a782966 100644 --- a/src/main/resources/static/assets/account.css +++ b/src/main/resources/static/assets/account.css @@ -1,3 +1 @@ -:root{color-scheme:light dark;font-family:system-ui,sans-serif;line-height:1.6}body{margin:0}main{max-width:58rem;margin:auto;padding:2rem 1rem}nav{display:flex;gap:1rem;flex-wrap:wrap}label{display:block;margin:.7rem 0}input,select,textarea,button{font:inherit;padding:.4rem .6rem;margin-left:.3rem;max-width:100%;box-sizing:border-box}button{cursor:pointer}form{margin:1.2rem 0;padding:1rem;border:1px solid #888;border-radius:.3rem}li form{display:inline-block;margin:.4rem;padding:0;border:0}code{overflow-wrap:anywhere}a{color:light-dark(#0759b0,#93c5fd)}:focus-visible{outline:3px solid #c87800;outline-offset:3px} - -textarea{display:block;min-height:6rem;resize:vertical}table{border-collapse:collapse;max-width:100%}th,td{padding:.4rem;text-align:left;vertical-align:top;overflow-wrap:anywhere} +:root{color-scheme:light dark;--bg:#f4f6f8;--surface:#fff;--text:#172b38;--muted:#526571;--border:#cbd5dc;--accent:#08645e;--tint:#e5f4f0;--danger:#a42e35;--warning:#fff3d7;--shadow:0 2px 8px #182c3810;font:100%/1.6 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text)}a{color:var(--accent);text-underline-offset:.22em}a:hover{text-decoration-thickness:2px}button,input,select,textarea{font:inherit}button,.button{cursor:pointer;background:var(--accent);color:#fff;border:1px solid transparent;border-radius:.4rem;padding:.6rem 1rem;min-height:44px;font-weight:650;text-decoration:none;display:inline-flex;align-items:center;justify-content:center;gap:.4rem}button:hover,.button:hover{filter:brightness(.92)}button.quiet,.button.secondary{background:var(--surface);color:var(--accent);border-color:var(--border)}button.danger,.button.danger{background:var(--danger)}button:disabled{cursor:wait;opacity:.65}a,button,input,select,textarea,summary{scroll-margin-top:1rem}:focus-visible{outline:3px solid #bd6c00;outline-offset:3px}input:not([type=checkbox]):not([type=radio]),select,textarea{display:block;width:100%;max-width:40rem;background:var(--surface);color:var(--text);border:1px solid var(--border);border-radius:.35rem;min-height:44px;padding:.6rem .7rem}input[type=checkbox]{width:1.15rem;height:1.15rem;vertical-align:middle;margin-right:.6rem}input[readonly]{background:var(--bg)}textarea{resize:vertical;min-height:7rem}label{display:block;font-weight:600;margin:1rem 0 .4rem}label small{display:block;font-weight:400}form{margin:0}form>button{margin-top:1rem}h1,h2,h3{line-height:1.25;letter-spacing:-.025em}h1{font-size:clamp(1.8rem,4vw,2.5rem);margin:.3rem 0 1rem}h2{font-size:1.35rem;margin:0 0 1rem}h3{font-size:1.1rem}p{max-width:78ch}small,.muted,.eyebrow{color:var(--muted)}.eyebrow{text-transform:uppercase;letter-spacing:.1em;font-size:.75rem;font-weight:750}.app-header{background:var(--surface);border-bottom:1px solid var(--border)}.brand-row,.portal-switch,.section-nav{max-width:1200px;margin:auto;padding:.75rem 2rem;display:flex;gap:1.5rem;align-items:center;flex-wrap:wrap}.brand-row{justify-content:space-between}.brand{color:var(--text);font-size:1.2rem;font-weight:750;text-decoration:none;display:flex;gap:.65rem;align-items:center}.brand-mark{display:grid;place-items:center;background:var(--accent);color:#fff;width:2.1rem;height:2.1rem;border-radius:.5rem}.brand-caption{font-weight:400;color:var(--muted);font-size:.8rem;border-left:1px solid var(--border);padding-left:.8rem}.identity{display:flex;gap:1rem;align-items:center;font-size:.9rem}.portal-switch{padding-top:0;padding-bottom:0;gap:1.25rem}.portal-switch a{font-size:.85rem;font-weight:600;text-decoration:none;padding:.35rem 0}.portal-switch [aria-current=true]{border-bottom:2px solid var(--accent)}.section-nav{gap:.25rem;padding-top:.5rem;padding-bottom:.7rem}.section-nav a{padding:.5rem .8rem;text-decoration:none;color:var(--muted);font-size:.9rem;font-weight:650;border-radius:.35rem}.section-nav [aria-current=page]{background:var(--tint);color:var(--accent)}main{max-width:1200px;margin:auto;padding:2rem;min-height:65vh}main>nav:not(.pagination){display:flex;gap:1rem;flex-wrap:wrap;margin-bottom:1.5rem}section,article,.card{background:var(--surface);border:1px solid var(--border);border-radius:.65rem;padding:1.5rem;margin:1.25rem 0;box-shadow:var(--shadow)}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,280px),1fr));gap:1.25rem}.grid>section,.grid>.card{margin:0}.page-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:1rem;flex-wrap:wrap;margin-bottom:1.5rem}.actions{display:flex;align-items:center;gap:.75rem;flex-wrap:wrap}.actions a:not(.button){font-weight:600}.notice{border:1px solid var(--border);border-left:4px solid #bd6c00;background:var(--warning);padding:1rem 1.2rem;border-radius:.35rem;margin:1rem 0}.notice.success{border-left-color:var(--accent);background:var(--tint)}.notice.error{border-left-color:var(--danger)}.badge{font-size:.8rem;font-weight:650;padding:.2rem .65rem;border-radius:2rem;background:var(--bg);border:1px solid var(--border);display:inline-block}.danger-zone{border-color:var(--danger)}.empty{padding:2rem;text-align:center;border:1px dashed var(--border);border-radius:.5rem}.metric{font-size:2rem;font-weight:750;margin:0}.table-scroll{max-width:100%;overflow-x:auto}table{width:100%;border-collapse:collapse;font-size:.9rem}caption{text-align:left;font-weight:650;margin-bottom:.75rem}th{text-align:left;color:var(--muted);font-size:.8rem}td,th{padding:.85rem .65rem;border-bottom:1px solid var(--border);vertical-align:top}td:first-child,th:first-child{padding-left:0}td form{margin:0}td button{margin:0}table a{font-weight:650}dl{display:grid;grid-template-columns:minmax(8rem,1fr) 3fr;gap:.75rem 1.5rem}dt{color:var(--muted)}dd{margin:0;overflow-wrap:anywhere}code{font-size:.9em;overflow-wrap:anywhere}time{font-variant-numeric:tabular-nums}.copy-field{display:flex;gap:.5rem;align-items:center}.copy-field input{min-width:0;max-width:none}.pagination{display:flex;justify-content:center;gap:1.5rem;margin-top:1.5rem}.filters{display:flex;gap:1rem;align-items:flex-end;flex-wrap:wrap}.filters label{margin:0}.filters button{margin:0}.filters input{min-width:16rem}details{margin:1rem 0}summary{cursor:pointer;font-weight:650;min-height:44px;padding:.5rem 0}footer{max-width:1200px;margin:auto;padding:2rem;color:var(--muted);font-size:.85rem;display:flex;gap:1rem;flex-wrap:wrap;justify-content:space-between}footer p{width:100%;margin:0}.skip-link{position:absolute;top:-100px;left:1rem;background:var(--surface);padding:1rem;z-index:5}.skip-link:focus{top:0}.security-nav{display:flex;gap:1rem;flex-wrap:wrap;margin-bottom:1.5rem}.steps{padding-left:1.5rem}.steps li{padding:.5rem 0}.auth-page{max-width:620px}.auth-page>form{background:var(--surface);padding:1.5rem;border:1px solid var(--border);border-radius:.65rem}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}@media(max-width:650px){main{padding:1.25rem}.brand-row,.portal-switch,.section-nav{padding-left:1.25rem;padding-right:1.25rem;gap:.5rem}.brand-caption{display:none}.identity>span{max-width:9rem;overflow-wrap:anywhere}.section-nav a{padding:.5rem;font-size:.82rem}section,article,.card{padding:1.1rem}dl{grid-template-columns:1fr;gap:.25rem}dd{margin-bottom:.7rem}.copy-field{align-items:stretch}.filters{display:block}.filters>*{margin:.75rem 0}.filters input{min-width:0}footer{padding:1.25rem}.page-heading .button{width:100%}}@media(prefers-color-scheme:dark){:root{--bg:#101b22;--surface:#192831;--text:#e3edf2;--muted:#abbcc7;--border:#41545f;--accent:#71d9c0;--tint:#1d3b36;--warning:#3c321d;--danger:#e45f6b;--shadow:none}button,.button,.brand-mark{color:#102b26}button.danger,.button.danger{color:#1c0809}:focus-visible{outline-color:#f1b761}}@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;animation:none!important;transition:none!important}} diff --git a/src/main/resources/static/assets/portal.js b/src/main/resources/static/assets/portal.js new file mode 100644 index 0000000..207d968 --- /dev/null +++ b/src/main/resources/static/assets/portal.js @@ -0,0 +1,14 @@ +'use strict'; +document.querySelectorAll('[data-copy]').forEach(button => { + button.addEventListener('click', async () => { + const target = document.getElementById(button.dataset.copy); + const status = document.getElementById('copy-status'); + try { + await navigator.clipboard.writeText(target.value ?? target.textContent); + status.textContent = 'Copied. Paste it into your application settings.'; + } catch { + if (target.select) { target.focus(); target.select(); } + status.textContent = 'Select the field and use your browser’s Copy command.'; + } + }); +}); diff --git a/src/main/resources/templates/account-detail.html b/src/main/resources/templates/account-detail.html new file mode 100644 index 0000000..fb890a6 --- /dev/null +++ b/src/main/resources/templates/account-detail.html @@ -0,0 +1,9 @@ + + +
+ +Back to accounts

Account identity

Username
Status
Role
Primary sign-in

Passkeys, credentials and recovery are managed by the user or the documented offline operator procedure. No password-reset, reactivation or privilege-change action is available here.

+

Edit profile

+

Disable account

This ends the account's browser sessions and revokes client credentials and OAuth access. Its calendar contents and recorded memberships remain stored. Reactivation requires the controlled offline recovery procedure.

+ +
diff --git a/src/main/resources/templates/account-error.html b/src/main/resources/templates/account-error.html index 36cb948..eab742c 100644 --- a/src/main/resources/templates/account-error.html +++ b/src/main/resources/templates/account-error.html @@ -1 +1 @@ -Check account details · BusyStack

Check the submitted details

The action could not accept one or more values. Review the account, collection, permission and field limits, then try again.

Return to your account

+Check account details · BusyStack

Check the submitted details

The action could not accept one or more values. Review the account, collection, permission and field limits, then try again.

Return to your account

diff --git a/src/main/resources/templates/account-new.html b/src/main/resources/templates/account-new.html new file mode 100644 index 0000000..3f79ca9 --- /dev/null +++ b/src/main/resources/templates/account-new.html @@ -0,0 +1,7 @@ + + +
+ +Back to accounts

Create an ordinary account

Provision a local account, then transfer the initial password securely to the intended user. Their first sign-in requires passkey enrollment and verification before they can change collections or issue client access.

Use 1–64 ASCII letters, digits, dots, underscores or hyphens, starting with a letter or digit. The login identity cannot be edited here.

At least fourteen characters and at most seventy-two UTF-8 bytes. This form cannot create an administrator or configure an external identity mapping.

Organization accounts are provisioned through the operator's configured subject allowlist, or a user's protected identity-linking workflow.

+ +
diff --git a/src/main/resources/templates/accounts.html b/src/main/resources/templates/accounts.html new file mode 100644 index 0000000..f66c8ac --- /dev/null +++ b/src/main/resources/templates/accounts.html @@ -0,0 +1,9 @@ + + +
+ +
Server administration

Accounts

Provision ordinary users and maintain profiles. Administration does not grant access to private calendar contents.

Create account
+
+

No accounts match these filters.

Account directory — 50 per page
AccountDisplay nameIdentityStatusRole
+ +
diff --git a/src/main/resources/templates/administration.html b/src/main/resources/templates/administration.html index 54fca7d..5c93183 100644 --- a/src/main/resources/templates/administration.html +++ b/src/main/resources/templates/administration.html @@ -1,2 +1,9 @@ -BusyStack administration

Administration

Your account

OAuth client registration

Server diagnostics

Sharing groups

Accounts

  • · · administrator · disabled

Provision an account

+ +
+ +
Server administration

Server overview

Application version . Aggregate operational metadata does not grant access to private contents.

Create account
+

Accounts

Enabled · disabled

Manage accounts

Collections

calendars · task lists

Stored resources

Calendar and task resources, excluding retained history.

+

Operational status

Database
PostgreSQL
Applied migration
Server errors
observed by HTTP metrics since startup
Backup status
Unknown — backups are operated and verified outside the application.
Open system diagnostics

Administration tools

Administrator bootstrap and account recovery remain offline operator procedures.

+ +
diff --git a/src/main/resources/templates/audit.html b/src/main/resources/templates/audit.html new file mode 100644 index 0000000..a333f0a --- /dev/null +++ b/src/main/resources/templates/audit.html @@ -0,0 +1,9 @@ + + +
+ +Server administration

Security & Audit

Recorded security metadata is retained for up to thirty days and approximately ten thousand rows. This is a bounded security record, not a calendar-activity history.

Manage OAuth application registrations

+
+

No retained events match these filters.

Recorded security events
Time (UTC)EventOutcomeAssociated account
+ +
diff --git a/src/main/resources/templates/collection-delete.html b/src/main/resources/templates/collection-delete.html new file mode 100644 index 0000000..d4ef049 --- /dev/null +++ b/src/main/resources/templates/collection-delete.html @@ -0,0 +1,7 @@ + + +
+ +Cancel and return to collection

Delete ?

This permanently removes this , every stored item and its synchronization history. Individual and group sharing access will be removed. Connected applications will lose this collection.

Export the collection first if you need a migration copy. Operator backups are managed separately.

Export before deleting
+ +
diff --git a/src/main/resources/templates/collection-new.html b/src/main/resources/templates/collection-new.html new file mode 100644 index 0000000..595b2d0 --- /dev/null +++ b/src/main/resources/templates/collection-new.html @@ -0,0 +1,8 @@ + + +
+ +Back to collections

Create a collection

Keep calendars and task lists separate. The type stays fixed after creation.

+

Use #RRGGBB or #RRGGBBAA. This uses the Apple calendar-color convention; display depends on your client.

+ +
diff --git a/src/main/resources/templates/collection-sharing.html b/src/main/resources/templates/collection-sharing.html new file mode 100644 index 0000000..89f9c49 --- /dev/null +++ b/src/main/resources/templates/collection-sharing.html @@ -0,0 +1,15 @@ + + +
+ +Back to collection

Sharing:

Only the owner can change grants. Read-only permits retrieval; read and write also permits content and metadata changes. Group administrators control the group's current and future membership.

+

Direct account access

No direct grants. Group grants may still provide access.

Accounts with direct grants
UsernameDirect grantEffective accessChange grant
· disabled
+ +
Grant access to an account

Enter the exact username supplied by the recipient. This interface does not expose an account directory.

+

Group access

No groups have a grant for this collection.

Groups with grants for this collection
GroupGrantChange grant
+ +
Grant access to a group

All current and future group members receive this grant. Administrators control membership.

No sharing groups are available. Ask an administrator to create one.

+

Effective permissions

The owner's access is always Owner. For other accounts, any read/write grant gives read/write access. Removing one grant leaves all other grants effective. Disabled accounts cannot authenticate.

No recipients currently have effective grants.

Combined direct and group access
AccountEffective accessContributing grants
Direct grant;
+
+ +
diff --git a/src/main/resources/templates/collection.html b/src/main/resources/templates/collection.html new file mode 100644 index 0000000..aa6d1f6 --- /dev/null +++ b/src/main/resources/templates/collection.html @@ -0,0 +1,11 @@ + + +
+ +Back to collections +

CalDAV address

Connection guide · Import iCalendar

+

Edit collection details

Your read/write grant permits editing shared collection metadata. Only the owner can manage sharing or delete the collection.

Use #RRGGBB or #RRGGBBAA. Clients may maintain their own colour preferences.

Type: . Editing details keeps the same address, type and stored contents.

+

Collection details

You have read-only access. Ask the owner to change collection details or access.

+

Delete this collection

Deletion removes its contents and associated sharing access for everyone.

Review deletion
+ +
diff --git a/src/main/resources/templates/collections.html b/src/main/resources/templates/collections.html new file mode 100644 index 0000000..c76eecb --- /dev/null +++ b/src/main/resources/templates/collections.html @@ -0,0 +1,11 @@ + + +
+ +
My account

Calendars & Tasks

Manage collections and access. Use your connected application to edit their contents.

Create a collection
+ +
+

No collections match this view. Create a calendar or task listAsk a collection owner to share with your username.

Collection details
CollectionTypeOwnerAccessActions

Details Sharing
+ + +
diff --git a/src/main/resources/templates/connections.html b/src/main/resources/templates/connections.html new file mode 100644 index 0000000..e6f19c4 --- /dev/null +++ b/src/main/resources/templates/connections.html @@ -0,0 +1,12 @@ + + +
+ +
My account

Connect your applications

Use a dedicated DAV credential as the application password. Your browser sign-in password does not authenticate CalDAV.

Issue an application credential
+

Your connection settings

Authentication: named DAV credential using Basic over HTTPS. A registered application that supports BusyStack OAuth may use browser authorization instead.

+

Thunderbird

Previously verified: 159.0 Native calendar and task workflows were qualified on the 0.1.0 executable in Vancouver and Berlin. Verification of a later executable is recorded separately.

  1. Open the Calendar tab, choose New Calendar → On the Network.
  2. Enter the username above and the server address as Location. Leave This location doesn't require credentials unchecked, then choose Find Calendars.
  3. Enter your dedicated DAV credential in the password prompt. Use Password Manager if you want Thunderbird to retain it.
  4. Choose CalDAV, select discovered calendars and task lists, then choose Subscribe. Use Thunderbird's task view for tasks.
+

GNOME Calendar / Evolution Data Server

Previously verified: Calendar 50.0 / EDS 3.56.2 Event editing and synchronization were qualified on 0.1.0 in Vancouver. GNOME Calendar does not provide a task editor.

The qualified profile provisions the remote CalDAV source through Evolution Data Server. Graphical account-creation instructions have not been qualified; do not assume Thunderbird's discovery steps apply. Ask your operator to use the documented EDS source setup in the project's client qualification record. The collection-specific URL below is the CalDAV endpoint for that source.

+

Collection addresses

Create a collection or ask an owner to share one before connecting.

+

Connection troubleshooting

Authentication fails

Check the username and dedicated credential. Issue a replacement if it expired or was lost. Revocation and account disabling deny future authentication. Organization-managed accounts also need periodic provider sign-in within the operator's configured freshness limit; provider disabling does not immediately revoke every BusyStack credential.

Collections are missing or access changed

Check Calendars & Tasks. A collection owner must grant access directly or through a group. Refresh discovery after a change. If a synchronization token becomes invalid after sharing changes, let the client perform a fresh initial synchronization.

TLS, address or synchronization problems

Use exactly the configured HTTPS address, including any application prefix. Do not disable certificate validation. Ask the operator to check certificates and proxy configuration.

Strict synchronization-depth mode is enabled. The project's tested Thunderbird and python-caldav versions use Depth: 1 and need the documented default accommodation; ask the operator to review this deployment choice.

BusyMax has not been qualified against this implementation. No connection or OAuth compatibility claim is made.

+ +
diff --git a/src/main/resources/templates/credentials.html b/src/main/resources/templates/credentials.html new file mode 100644 index 0000000..35e83bc --- /dev/null +++ b/src/main/resources/templates/credentials.html @@ -0,0 +1,9 @@ + + +
+ +Back to security

DAV credentials

Issue a separate credential for each application or device. These are credentials, not a list of verified device connections. Secrets appear once and cannot be retrieved later.

+

Issue a credential

Choose 1–365 days. Expiration stops future authentication. For replacement, issue a new credential, configure the application, then revoke the old one.

+

Issued credentials

No DAV credentials have been issued. Create one above, then follow Connections.

Credential metadata
LabelCreatedExpiresStatusAction
+ +
diff --git a/src/main/resources/templates/dashboard.html b/src/main/resources/templates/dashboard.html index 8660681..a9010c7 100644 --- a/src/main/resources/templates/dashboard.html +++ b/src/main/resources/templates/dashboard.html @@ -1,15 +1,10 @@ -BusyStack account -

BusyStack account

Signed in as ().

- -

Manage event and task content in your CalDAV client. Changes to account access and collections require primary sign-in and passkey verification within the last ten minutes.

-

Organization sign-in

Linking an organization identity replaces local password sign-in for this account. Future sensitive operations require organization sign-in and your passkey.

-

Connect a CalDAV client

Server address:
Username:

Use a named DAV credential from this page as your client password. Browser and account passwords do not authenticate DAV. Capable registered applications can instead use browser OAuth authorization.

Strict synchronization depth mode is enabled. The tested Thunderbird and python-caldav versions use Depth: 1 and require the default synchronization accommodation to connect.

Collections

  • · ·
-

Create a collection

-
-

Share an owned collection

-
-

DAV credentials

The account password does not authenticate DAV requests. Each application uses a separate expiring credential.

-
  • · expires · revoked
-

Issue a credential

-
+ +
+ +
My account

Welcome,

·

Connect an application
+

My collections

Calendars and task lists you own.

Manage my collections

Shared with me

Collections available through direct or group access.

View shared collections

Account security

Review security
+

Finish setting up your account

  1. Enroll and verify your first passkey. Your primary sign-in and passkey protect account changes.
  2. Create a calendar or task list, or ask an owner to share one with your username.
  3. Issue an application credential for a CalDAV client, unless your application uses registered OAuth authorization.
  4. Save recovery codes offline so a lost passkey does not lock you out.

Follow the client connection guide. The server does not track whether you have configured an application.

+

Your calendars and task lists

You have no collections yet. Create your first calendar or task list.

Up to 50 available collections
NameTypeAccess

Open collection management to edit details, manage sharing or export your data.

+ +
diff --git a/src/main/resources/templates/diagnostics.html b/src/main/resources/templates/diagnostics.html index df5f75f..904b93b 100644 --- a/src/main/resources/templates/diagnostics.html +++ b/src/main/resources/templates/diagnostics.html @@ -1,8 +1,10 @@ -Server diagnostics · BusyStack
-

Server diagnostics

Administration · Account

-

Deployment

Public base URL
OAuth issuer
Java
PostgreSQL
Applied database migration
-

Durable state

Enabled accounts
Collections
Calendar resources
-

HTTP since this application started

Completed requests
Server errors
Mean duration, milliseconds
Recent maximum duration, milliseconds
-

Request logs contain server-generated correlation identifiers, endpoint categories, methods, status codes and duration. Use the response’s X-Request-ID when investigating a failed request. These aggregate counters reset on restart.

-
+ +
+ +Server administration

System & Diagnostics

Deployment

Application
Public base URL
OAuth issuer
Java runtime
Database
PostgreSQL
Applied migration
+

HTTP observations since startup

Completed requests
Server errors
Mean duration (ms)
Recent maximum (ms)

Metrics reset on restart. The recent maximum follows the metrics registry's observation window.

+

Recent operational problems

No server failures have been recorded in this process's bounded recent-problem buffer. This does not establish the absence of older or external failures.

Up to 50 observed server failures since startup
Time (UTC)SurfaceMethodStatusRequest identifier
+

Troubleshooting

Database or startup failure

Check local readiness probes, database availability, configured credentials and migration validation in operator logs. A database outage can prevent authenticated administration itself; use deployment monitoring. Configuration is validated at startup. Keep database access private and use the documented backup and recovery procedure.

Organization identity provider unavailable

Check the explicitly configured issuer, provider availability, trusted TLS certificate and redirect URI. Discovery is deferred to organization sign-in. Local accounts work independently. Externally managed accounts fail closed when provider authentication is required, without a password fallback. Previously issued client access keeps only its existing freshness bound.

Authentication or permission failure

Ask the user to check credential expiration, revocation and recent primary/passkey verification. Review recorded security outcomes in the audit viewer. Local disabling denies access even if group memberships remain. Administration does not bypass collection ownership.

CalDAV compatibility and synchronization

Use the project's qualified client/version profile. The documented default supports narrowly bounded sync Depth: 1 and local timezone-observance UNTIL repair. Strict-mode settings are controlled by the operator. Permission or group changes can invalidate synchronization tokens; a client must start fresh synchronization.

Use the response's X-Request-ID to correlate safe request metadata with operator logs. Request contents and credentials must not be collected for troubleshooting. Backups and public TLS renewal are external operator responsibilities; their status is unknown here.

+ +
diff --git a/src/main/resources/templates/error/400.html b/src/main/resources/templates/error/400.html new file mode 100644 index 0000000..63d1771 --- /dev/null +++ b/src/main/resources/templates/error/400.html @@ -0,0 +1 @@ +

Check the request

The request could not be understood. Review the form fields and try again.

diff --git a/src/main/resources/templates/error/403.html b/src/main/resources/templates/error/403.html index 49d3d6f..e117b2d 100644 --- a/src/main/resources/templates/error/403.html +++ b/src/main/resources/templates/error/403.html @@ -1 +1 @@ -Action not allowed · BusyStack

Action not allowed

Sensitive actions require recent sign-in and passkey verification. Sharing and administration also require permission for the affected account or collection.

Sign in again · Verify a passkey · Return to your account

\ No newline at end of file +Action not allowed · BusyStack

Action not allowed

Sensitive actions require recent sign-in and passkey verification. Sharing and administration also require permission for the affected account or collection.

Sign in again · Verify a passkey · Return to your account

\ No newline at end of file diff --git a/src/main/resources/templates/error/404.html b/src/main/resources/templates/error/404.html new file mode 100644 index 0000000..6a148db --- /dev/null +++ b/src/main/resources/templates/error/404.html @@ -0,0 +1 @@ +

Page unavailable

This page or resource is unavailable to this account.

diff --git a/src/main/resources/templates/error/500.html b/src/main/resources/templates/error/500.html new file mode 100644 index 0000000..4f1a28c --- /dev/null +++ b/src/main/resources/templates/error/500.html @@ -0,0 +1 @@ +

Service error

The operation could not complete. Use the request identifier when contacting your operator.

diff --git a/src/main/resources/templates/error/503.html b/src/main/resources/templates/error/503.html new file mode 100644 index 0000000..252db46 --- /dev/null +++ b/src/main/resources/templates/error/503.html @@ -0,0 +1 @@ +

Temporarily unavailable

The service cannot handle this request right now. Try again after a short wait, or ask the operator to check readiness and database connectivity.

diff --git a/src/main/resources/templates/fragments/layout.html b/src/main/resources/templates/fragments/layout.html new file mode 100644 index 0000000..35bd35a --- /dev/null +++ b/src/main/resources/templates/fragments/layout.html @@ -0,0 +1,42 @@ + + + + + BusyStack + + + + + + +
+ + + + + +
+ +

+
Security verification needed. Sensitive changes require primary sign-in and a passkey verified within ten minutes. Verify sign-in or set up a passkey.
+
+ +
BusyStack · Your server. Your data.Calendar and task contents are managed in your CalDAV applications.

+ + diff --git a/src/main/resources/templates/group-detail.html b/src/main/resources/templates/group-detail.html new file mode 100644 index 0000000..43edaca --- /dev/null +++ b/src/main/resources/templates/group-detail.html @@ -0,0 +1,11 @@ + + +
+ +Back to groups

members · collection grants. Collection names and contents remain private unless independently shared with you.

+

Rename group

+

Add one member

Adding an account gives it access to all collections already shared with this group, according to each owner's grant. Future grants also apply.

+

Current members

Removing a membership may remove calendar access. Any other direct or group grant continues to apply.

No members match this view.

Group members — 50 per page
AccountDisplay nameStatusMembership
+

Delete group

All recorded memberships and collection grants for this group will be removed. Access through other grants remains effective.

+ +
diff --git a/src/main/resources/templates/group-error.html b/src/main/resources/templates/group-error.html index 02b8fc3..94ccb10 100644 --- a/src/main/resources/templates/group-error.html +++ b/src/main/resources/templates/group-error.html @@ -1,2 +1,2 @@ -Check the group request · BusyStack

Check the group request

+Check the group request · BusyStack

Check the group request

diff --git a/src/main/resources/templates/groups.html b/src/main/resources/templates/groups.html index f0b40a7..f2a05fd 100644 --- a/src/main/resources/templates/groups.html +++ b/src/main/resources/templates/groups.html @@ -1,5 +1,10 @@ -Sharing groups · BusyStack

Sharing groups

Group administration requires recent primary sign-in and passkey verification. A group grants calendar access only when a collection owner shares with it. Administration alone does not grant access to calendar contents.

-

Create a group

Use up to 1,000 active accounts. An empty group has no members.

-

No sharing groups exist.

members ·

Deleting this group removes its collection grants.

-
+ +
+ +Server administration

Sharing groups

Manage local group membership. Owners choose which collections to share with each group. Membership administration does not bypass private collection permissions.

+

Create a group

+
+

No groups match this search. Create a group above to manage shared access.

Groups — 50 per page
GroupMembersCollection grants
+ +
diff --git a/src/main/resources/templates/import-report.html b/src/main/resources/templates/import-report.html new file mode 100644 index 0000000..62639c3 --- /dev/null +++ b/src/main/resources/templates/import-report.html @@ -0,0 +1,9 @@ + + +
+ +Back to Import & Export

Destination: .

Summary

Imported
Ready to import
Skipped (identical)
Conflicting
Rejected

Nothing has been imported yet. Confirmation imports only valid new items, preserving existing data. Authorization and conflicts are checked again at confirmation. Expires .

All reported new items were committed together. Existing resources were preserved. No rejected or conflicting item was written.

+

Item validation

Each UID series is one item, including its recurrence exceptions
ItemUIDResultDetails
.
+

Confirm or discard

+ +
diff --git a/src/main/resources/templates/issued-credential.html b/src/main/resources/templates/issued-credential.html index 8a2a78c..91a9b6b 100644 --- a/src/main/resources/templates/issued-credential.html +++ b/src/main/resources/templates/issued-credential.html @@ -1,2 +1,2 @@ -New DAV credential

New DAV credential

Store this secret in your application's credential settings. It is shown only in this response.

Username
Secret
Expires

Return to your account

+New DAV credential

New DAV credential

Store this secret in your application's credential settings. It is shown only in this response.

Username
Secret
Expires

Continue to connection instructions · Manage credentials

Return to your account

diff --git a/src/main/resources/templates/login.html b/src/main/resources/templates/login.html index 6df2fe7..71a7ef9 100644 --- a/src/main/resources/templates/login.html +++ b/src/main/resources/templates/login.html @@ -2,14 +2,14 @@ Sign in · BusyStack - -

Sign in to BusyStack

-

Account changes and client authorization require a password and a passkey verified within ten minutes. Complete both steps using the same account.

+ +

Sign in to BusyStack

+

Complete primary sign-in, then verify your passkey for the same account. Sensitive changes require both factors within ten minutes.

Signed in as .

Password changed and prior access revoked. Sign in with your new password, then verify your existing passkey.

Sign in failed. Check your account details.

Sign in with your organization's identity provider

-

- +

1. Primary sign-in

Use your organization identity provider. Local-password sign-in is unavailable for this account.

+

2. Verify your passkey

-

After verifying your password, enroll your first passkey. For a lost passkey, contact your server administrator for the documented local recovery operation.

+

After verifying your password, enroll your first passkey. For a lost passkey, use an offline recovery code after primary sign-in at account recovery. If you also lost primary sign-in, contact your operator for the documented recovery procedure.

Account management

-
+
diff --git a/src/main/resources/templates/oauth-clients.html b/src/main/resources/templates/oauth-clients.html index dc50f6a..aaae52d 100644 --- a/src/main/resources/templates/oauth-clients.html +++ b/src/main/resources/templates/oauth-clients.html @@ -1,9 +1,9 @@ -OAuth clients · BusyStack -

OAuth clients

+OAuth clients · BusyStack +

OAuth clients

Register a calendar or task application that supports authorization code with S256 PKCE. Native applications use public client identification and have no embedded secret. Generic CalDAV discovery does not register an OAuth client.

Registering and removing clients requires password and passkey verification within ten minutes. Removing a client revokes every grant issued to it.

Registered applications
Client IDNameRedirectsAction

Register a native application

Use application-owned HTTPS URLs, IP loopback HTTP URLs with a port, or reverse-domain application schemes such as org.example.calendar:/callback. Register at most five redirects. Non-loopback redirects use exact matching.

-
+
diff --git a/src/main/resources/templates/oauth-consent.html b/src/main/resources/templates/oauth-consent.html index 8f73fc0..81d88a4 100644 --- a/src/main/resources/templates/oauth-consent.html +++ b/src/main/resources/templates/oauth-consent.html @@ -1,2 +1,2 @@ -Authorize application · BusyStack

Authorize application

requests access to your calendars and tasks. Your collection permissions apply to every request.

+Authorize application · BusyStack

Authorize application

requests access to your calendars and tasks. Your collection permissions apply to every request.

diff --git a/src/main/resources/templates/oauth-error.html b/src/main/resources/templates/oauth-error.html index 4ac8f54..ce23a56 100644 --- a/src/main/resources/templates/oauth-error.html +++ b/src/main/resources/templates/oauth-error.html @@ -1,2 +1,2 @@ -OAuth request · BusyStack

Check the request

+OAuth request · BusyStack

Check the request

diff --git a/src/main/resources/templates/oauth-grants.html b/src/main/resources/templates/oauth-grants.html index 91f6d8d..4b418e7 100644 --- a/src/main/resources/templates/oauth-grants.html +++ b/src/main/resources/templates/oauth-grants.html @@ -1,7 +1,7 @@ -Client access · BusyStack -

OAuth client access

+Client access · BusyStack +

OAuth client access

Approved applications can access your calendar and task collections within your existing sharing permissions. Revoking access invalidates that application's current access and refresh credentials immediately.

Revocation requires password and passkey verification within ten minutes. Applications must sign in again after thirty days.

Authorization grants
ApplicationAuthorizedExpiresRevokedAction
()

No OAuth applications have been authorized.

-
+
diff --git a/src/main/resources/templates/passkeys.html b/src/main/resources/templates/passkeys.html index 3e3816f..0bae7c8 100644 --- a/src/main/resources/templates/passkeys.html +++ b/src/main/resources/templates/passkeys.html @@ -1,13 +1,13 @@ Passkeys · BusyStack - -

Passkeys

First enrollment requires a recent password. Adding or removing an existing passkey requires a recent password and passkey. Your authenticator must verify your presence and unlock the passkey.

+ +

Passkeys

First enrollment requires primary sign-in within ten minutes: a local password or your configured organization provider. Adding or removing a passkey requires recent primary sign-in and passkey verification. Your authenticator must verify your presence and unlock the passkey.

- -
Registered passkeys
NameCreatedLast usedAction
+

No passkeys are enrolled. Register one above, then verify it to complete MFA.

+
Registered passkeys
NameCreatedLast usedAction

Verify another factor · Account management

-
+
diff --git a/src/main/resources/templates/password.html b/src/main/resources/templates/password.html index a799dca..51970b9 100644 --- a/src/main/resources/templates/password.html +++ b/src/main/resources/templates/password.html @@ -1,2 +1,2 @@ -Password · BusyStack

Change your local password

Password changes require recent primary and passkey verification. They end every session and revoke DAV credentials, OAuth access and recovery codes. Your passkeys remain registered.

If your account uses an external identity provider, change the primary credential there.

Use at least fourteen characters, within seventy-two UTF-8 bytes.

+Password · BusyStack

Change your local password

Password changes require recent primary and passkey verification. They end every session and revoke DAV credentials, OAuth access and recovery codes. Your passkeys remain registered.

If your account uses an external identity provider, change the primary credential there.

Use at least fourteen characters, within seventy-two UTF-8 bytes.

diff --git a/src/main/resources/templates/portability.html b/src/main/resources/templates/portability.html new file mode 100644 index 0000000..54fe8fa --- /dev/null +++ b/src/main/resources/templates/portability.html @@ -0,0 +1,7 @@ + + +
+ +My account

Import & Export

Move your calendar and task data using iCalendar files. No invitations, alarms or outbound messages are executed by import.

Choose a collection

Readable collections can be exported. Owners and read/write recipients can import into a collection of the matching type.

No collections are available. Create a destination collection first.

Export this collection

Up to 8 MiB per file and 1 MiB per UID series, with at most 1,000 imported items. The actual content is validated. Select a file to review conflicts before confirming.

Data preservation and limits

Exports contain complete stored calendar objects as an RFC 5545 iCalendar stream. Recurrence exceptions and embedded timezone definitions stay with their UID series, including distinct timezone definitions from different resources. The exported stream preserves stored resource bytes. Some other applications accept only a single VCALENDAR per import; verify their import behavior before migration.

Exports are bounded to 10,000 resources and 64 MiB. Larger exports fail before a download starts. Imports preserve existing resources: identical resources are skipped and different resources with an existing UID are reported as conflicts. Valid new series are committed together; rejected, conflicting and skipped items are explicitly listed. A failure while writing rolls back every new resource.

Import previews expire after ten minutes and are replaced by your next preview. Restarting this instance invalidates pending previews. Files are stored temporarily on this server, not in browser storage.

+ +
diff --git a/src/main/resources/templates/portal-error.html b/src/main/resources/templates/portal-error.html new file mode 100644 index 0000000..aae831d --- /dev/null +++ b/src/main/resources/templates/portal-error.html @@ -0,0 +1,7 @@ + + +
+ +

The request could not complete

Your submitted non-secret fields
+ +
diff --git a/src/main/resources/templates/recovery-codes.html b/src/main/resources/templates/recovery-codes.html index d3ee169..793a496 100644 --- a/src/main/resources/templates/recovery-codes.html +++ b/src/main/resources/templates/recovery-codes.html @@ -1,2 +1,2 @@ -Save recovery codes · BusyStack

Save your recovery codes

These codes appear once. Store them securely offline. Each code is single use, expires at , and still requires your recent primary sign-in.

Generating another set revokes these codes. The server retains only their verifiers.

Return to recovery settings

+Save recovery codes · BusyStack

Save your recovery codes

These codes appear once. Store them securely offline. Each code is single use, expires at , and still requires your recent primary sign-in.

Generating another set revokes these codes. The server retains only their verifiers.

Return to recovery settings

diff --git a/src/main/resources/templates/recovery.html b/src/main/resources/templates/recovery.html index 5178790..68d47d3 100644 --- a/src/main/resources/templates/recovery.html +++ b/src/main/resources/templates/recovery.html @@ -1,2 +1,2 @@ -Recovery · BusyStack

Account recovery

Keep recovery codes offline. A code can replace a lost passkey after you recently verify your primary sign-in. It cannot replace your password or upstream sign-in.

Unused codes: · expires .

Generate new recovery codes

Requires recent primary and passkey verification. Generating a new set revokes every unused code from the previous set. Codes appear once.

Recover from a lost passkey

First verify your primary sign-in. Recovery consumes this code, removes all passkeys, revokes DAV and OAuth access, and ends every browser session. Then sign in again and enroll a new passkey.

+Recovery · BusyStack

Account recovery

Keep recovery codes offline. A code can replace a lost passkey after you recently verify your primary sign-in. It cannot replace your password or upstream sign-in.

Unused codes: · expires .

Generate new recovery codes

Requires recent primary and passkey verification. Generating a new set revokes every unused code from the previous set. Codes appear once.

Recover from a lost passkey

First verify your primary sign-in. Recovery consumes this code, removes all passkeys, revokes DAV and OAuth access, and ends every browser session. Then sign in again and enroll a new passkey.

diff --git a/src/main/resources/templates/security.html b/src/main/resources/templates/security.html new file mode 100644 index 0000000..b1b3cf0 --- /dev/null +++ b/src/main/resources/templates/security.html @@ -0,0 +1,9 @@ + + +
+ +My account

Security

+

Passkeys & authentication

Manage passkeys · Verify sign-in

Application credentials

Manage DAV credentials

Browser sessions

Review and end sessions. Password changes and recovery end all sessions.

Review sessions

Recovery

Manage recovery codes

OAuth applications

Review and revoke browser-authorized application access.

Manage OAuth grants

Primary credentials

Change your primary credentials through your organization's identity provider. A local-password fallback is unavailable.

Your password is managed on this server.

Change local password
+

Link an organization identity

Linking replaces local-password sign-in for this account and revokes existing sessions and client credentials. Your collection identity and enrolled passkeys are preserved. Future sign-in requires the configured provider.

+ +
diff --git a/src/main/resources/templates/sessions.html b/src/main/resources/templates/sessions.html index 44a115c..a9b230c 100644 --- a/src/main/resources/templates/sessions.html +++ b/src/main/resources/templates/sessions.html @@ -1,2 +1,2 @@ -Sessions · BusyStack

Active browser sessions

Sessions expire after thirty minutes of inactivity. Ending a session requires recent primary and passkey verification. DAV and OAuth access are managed separately.

Your browser sessions
CreatedLast usedExpiresBrowserAction
+Sessions · BusyStack

Active browser sessions

Sessions expire after thirty minutes of inactivity. Ending a session requires recent primary and passkey verification. DAV and OAuth access are managed separately.

Your browser sessions
CreatedLast usedExpiresBrowserAction
diff --git a/src/test/java/org/busystack/caldav/calendar/CalendarInterchangeTest.java b/src/test/java/org/busystack/caldav/calendar/CalendarInterchangeTest.java new file mode 100644 index 0000000..7d21c9b --- /dev/null +++ b/src/test/java/org/busystack/caldav/calendar/CalendarInterchangeTest.java @@ -0,0 +1,149 @@ +package org.busystack.caldav.calendar; + +import static org.assertj.core.api.Assertions.*; + +import java.nio.charset.StandardCharsets; +import org.busystack.caldav.config.DavCompatibilityProperties; +import org.junit.jupiter.api.Test; + +class CalendarInterchangeTest { + final CalendarInterchange interchange = + new CalendarInterchange(new CalendarAdmission(new DavCompatibilityProperties(true, true))); + + private static byte[] bytes(String text) { + return text.replace("\n", "\r\n").getBytes(StandardCharsets.UTF_8); + } + + private static String object(String components) { + return "BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//Interchange//EN\n" + + components + + "END:VCALENDAR\n"; + } + + private static String event(String uid) { + return "BEGIN:VEVENT\nUID:" + + uid + + "\nDTSTAMP:20261101T000000Z\nDTSTART:20261102T090000Z\nSUMMARY:Résumé\\, family\nX-DATA:preserve\nEND:VEVENT\n"; + } + + @Test + void splitsMultipleUidsAndRetainsRecurrenceExceptionsTogether() { + String master = event("series").replace("X-DATA:", "RRULE:FREQ=DAILY;COUNT=3\nX-DATA:"); + String exception = + event("series") + .replace( + "DTSTART:20261102T090000Z", + "RECURRENCE-ID:20261103T090000Z\nDTSTART:20261103T110000Z"); + var items = interchange.read(bytes(object(master + exception + event("second"))), "VEVENT"); + assertThat(items).hasSize(2).allSatisfy(i -> assertThat(i.rejection()).isEmpty()); + var parsed = CalendarContent.parse(items.getFirst().content(), "VEVENT"); + assertThat(parsed.uid()).isEqualTo("series"); + assertThat(parsed.calendar().getComponents("VEVENT")).hasSize(2); + assertThat(new String(items.getFirst().content(), StandardCharsets.UTF_8)) + .contains("RRULE:FREQ=DAILY;COUNT=3", "RECURRENCE-ID:20261103T090000Z", "X-DATA:preserve"); + } + + @Test + void losslessCalendarStreamsRetainEachOriginalRepresentation() { + byte[] a = bytes(object(event("a"))), b = bytes(object(event("b"))); + var all = new java.io.ByteArrayOutputStream(); + all.writeBytes(a); + all.writeBytes(b); + var items = interchange.read(all.toByteArray(), "VEVENT"); + assertThat(items.get(0).content()).isEqualTo(a); + assertThat(items.get(1).content()).isEqualTo(b); + } + + @Test + void taskProfilesAndWrongTypeAreExplicit() { + var task = + bytes( + object( + "BEGIN:VTODO\nUID:task\nDTSTAMP:20261101T000000Z\nSUMMARY:Undated task\nSTATUS:NEEDS-ACTION\nEND:VTODO\n")); + assertThat(interchange.read(task, "VTODO").getFirst().rejection()).isEmpty(); + assertThat(interchange.read(task, "VEVENT").getFirst().rejection()).contains("destination"); + assertThat( + interchange + .read( + bytes( + object( + "BEGIN:VJOURNAL\nUID:journal\nDTSTAMP:20261101T000000Z\nEND:VJOURNAL\n")), + "VEVENT") + .getFirst() + .rejection()) + .contains("Unsupported"); + } + + @Test + void invalidItemsAreReportedAndDuplicateMastersNeverDiscarded() { + var mixed = + interchange.read( + bytes( + object( + event("good") + + event("bad").replace("DTSTART:20261102T090000Z", "DTSTART:invalid"))), + "VEVENT"); + assertThat(mixed).hasSize(2); + assertThat(mixed.get(0).rejection()).isEmpty(); + assertThat(mixed.get(1).rejection()).isNotEmpty(); + assertThat( + interchange + .read(bytes(object(event("same") + event("same"))), "VEVENT") + .getFirst() + .rejection()) + .isNotEmpty(); + assertThat(interchange.read(bytes(object(event("same")) + object(event("same"))), "VEVENT")) + .allSatisfy(i -> assertThat(i.rejection()).contains("multiple")); + } + + @Test + void malformedOversizedAndDeepFilesFailBeforeAnyImport() { + assertThatThrownBy(() -> interchange.read(bytes(""), "VEVENT")) + .isInstanceOf(CalendarValidationException.class); + assertThatThrownBy( + () -> interchange.read(new byte[CalendarInterchange.MAX_FILE_BYTES + 1], "VEVENT")) + .isInstanceOf(CalendarValidationException.class); + assertThatThrownBy(() -> interchange.read(bytes(object("BEGIN:VEVENT\n".repeat(9))), "VEVENT")) + .isInstanceOf(CalendarValidationException.class); + assertThatThrownBy(() -> interchange.read(bytes(object(event("a")) + "garbage"), "VEVENT")) + .isInstanceOf(CalendarValidationException.class); + } + + @Test + void timezonesAndNominalDurationBytesRemainUntouched() { + String zone = + "BEGIN:VTIMEZONE\nTZID:Custom\nBEGIN:STANDARD\nDTSTART:19700101T000000\nTZOFFSETFROM:+0200\nTZOFFSETTO:+0200\nEND:STANDARD\nEND:VTIMEZONE\n"; + String event = + event("zone") + .replace( + "DTSTART:20261102T090000Z", "DTSTART;TZID=Custom:20261102T090000\nDURATION:P1D"); + byte[] source = bytes(object(zone + event)); + var item = interchange.read(source, "VEVENT").getFirst(); + assertThat(item.rejection()).isEmpty(); + assertThat(item.content()).isEqualTo(source); + assertThat( + CalendarContent.parse(item.content(), "VEVENT").calendar().getComponents("VTIMEZONE")) + .hasSize(1); + } + + @Test + void knownThunderbirdObservanceRepairUsesExistingAdmission() throws Exception { + String zone = + "BEGIN:VTIMEZONE\nTZID:Custom\nBEGIN:STANDARD\nDTSTART:19700101T000000\nTZOFFSETFROM:+0200\nTZOFFSETTO:+0200\nRRULE:FREQ=YEARLY;BYMONTH=1;UNTIL=20300101T000000\nEND:STANDARD\nEND:VTIMEZONE\n"; + var item = + interchange + .read( + bytes( + object( + zone + + event("repair") + .replace( + "DTSTART:20261102T090000Z", + "DTSTART;TZID=Custom:20261102T090000"))), + "VEVENT") + .getFirst(); + assertThat(item.rejection()).isEmpty(); + assertThat(new String(item.content(), StandardCharsets.UTF_8)) + .contains("UNTIL=20291231T220000Z"); + } +} diff --git a/src/test/java/org/busystack/caldav/management/PortalManagementIT.java b/src/test/java/org/busystack/caldav/management/PortalManagementIT.java new file mode 100644 index 0000000..8ffd0be --- /dev/null +++ b/src/test/java/org/busystack/caldav/management/PortalManagementIT.java @@ -0,0 +1,625 @@ +package org.busystack.caldav.management; + +import static org.assertj.core.api.Assertions.*; + +import java.net.*; +import java.net.http.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.time.Duration; +import java.util.*; +import org.busystack.caldav.account.AccountService; +import org.busystack.caldav.security.session.SessionSecurity; +import org.busystack.caldav.sharing.GroupService; +import org.busystack.caldav.storage.*; +import org.busystack.caldav.testing.*; +import org.junit.jupiter.api.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.*; +import org.springframework.security.core.context.SecurityContextImpl; +import org.springframework.security.web.context.HttpSessionSecurityContextRepository; +import org.springframework.session.*; +import org.springframework.test.context.*; +import org.testcontainers.junit.jupiter.*; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** Real PostgreSQL and HTTPS; factor fixtures test policy, not WebAuthn cryptography. */ +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = { + "busystack.public-base-url=https://localhost/team", + "busystack.issuer=https://localhost/team" + }) +@Testcontainers +@org.springframework.test.annotation.DirtiesContext( + classMode = org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_CLASS) +class PortalManagementIT { + @Container static final PostgreSQLContainer POSTGRES = LoopbackContainers.postgres(); + + @DynamicPropertySource + static void configuration(DynamicPropertyRegistry registry) { + registry.add("spring.datasource.url", POSTGRES::getJdbcUrl); + registry.add("spring.datasource.username", POSTGRES::getUsername); + registry.add("spring.datasource.password", POSTGRES::getPassword); + registry.add("server.ssl.enabled", () -> true); + registry.add("server.ssl.key-store", () -> TestTls.instance().keyStore()); + registry.add("server.ssl.key-store-password", () -> TestTls.instance().password()); + } + + @Autowired PortalService portal; + @Autowired ManagementService management; + @Autowired AdministrationService administration; + @Autowired SharingManagementService sharing; + @Autowired PortabilityService portability; + @Autowired AccountService accounts; + @Autowired CalendarStore calendars; + @Autowired DavStore dav; + @Autowired GroupService groups; + @Autowired JdbcTemplate jdbc; + @Autowired SessionRepository repository; + @Autowired org.springframework.transaction.PlatformTransactionManager transactions; + @LocalServerPort int port; + UUID admin, owner, reader, other, collection; + final String hostile = ""; + + @BeforeEach + void prepare() { + FixtureDatabase.reset( + jdbc, + "TRUNCATE spring_session,security_audit RESTART IDENTITY CASCADE", + "TRUNCATE accounts CASCADE"); + admin = + accounts.provision("portal-admin", "Administrator", "correct horse battery staple", true); + owner = + accounts.provision( + "portal-owner", "Owner " + hostile, "correct horse battery staple", false); + reader = accounts.provision("portal-reader", "Reader", "correct horse battery staple", false); + other = accounts.provision("portal-other", "Unrelated", "correct horse battery staple", false); + collection = + portal.create( + auth(owner, true), + "Private " + hostile, + "VEVENT", + "Description " + hostile, + "#126A5EFF"); + } + + @Test + void metadataUsesDavPropertiesAndRetainsPathsBytesAndTokens() { + var original = portal.collection(auth(owner, true), collection); + byte[] bytes = event("one"); + calendars.put(owner, collection, "one.ics", "one", bytes, WriteCondition.create()); + String token = calendars.currentSyncToken(owner, collection); + portal.edit( + auth(owner, true), collection, original.state(), "Renamed", "New description", "#123456"); + var changed = portal.collection(auth(owner, true), collection); + assertThat(changed.address()) + .isEqualTo(original.address()) + .startsWith("https://localhost/team/dav/"); + assertThat(changed.component()).isEqualTo("VEVENT"); + assertThat(changed.description()).isEqualTo("New description"); + assertThat(dav.deadProperty(owner, collection, null, PortalService.COLOR)).contains("#123456"); + assertThat(calendars.get(owner, collection, "one.ics").content()).isEqualTo(bytes); + assertThat(calendars.currentSyncToken(owner, collection)).isEqualTo(token); + denied(() -> portal.edit(auth(owner, true), collection, original.state(), "Stale", "", "")); + } + + @Test + void readWriteRecipientsHaveMetadataButNeverOwnerControls() { + management.share(auth(owner, true), collection, "portal-reader", "READ"); + var original = portal.collection(auth(reader, true), collection); + denied(() -> portal.edit(auth(reader, true), collection, original.state(), "Denied", "", "")); + management.share(auth(owner, true), collection, "portal-reader", "WRITE"); + portal.edit(auth(reader, true), collection, original.state(), "Shared edit", "", "#123456"); + denied(() -> portal.owner(auth(reader, true), collection)); + denied( + () -> + portal.delete( + auth(reader, true), + collection, + portal.collection(auth(reader, true), collection).deletionState(), + true)); + denied(() -> portal.collection(auth(admin, true), collection)); + denied(() -> portal.collection(auth(other, true), collection)); + } + + @Test + void deletionIsConfirmedRecheckedAndCascadesAllBindingsAndTokens() { + var g = groups.create(auth(admin, true), "Shared", Set.of("portal-reader")); + groups.grant(auth(owner, true), collection, g, "READ"); + management.share(auth(owner, true), collection, "portal-other", "WRITE"); + calendars.put(owner, collection, "one.ics", "one", event("one"), WriteCondition.create()); + var old = portal.collection(auth(owner, true), collection); + denied(() -> portal.delete(auth(owner, true), collection, old.deletionState(), false)); + calendars.put(owner, collection, "two.ics", "two", event("two"), WriteCondition.create()); + denied(() -> portal.delete(auth(owner, true), collection, old.deletionState(), true)); + String token = calendars.sync(reader, collection, "", 1).token(); + portal.delete( + auth(owner, true), + collection, + portal.collection(auth(owner, true), collection).deletionState(), + true); + for (String table : + List.of( + "dav_bindings", + "calendar_resources", + "collection_members", + "collection_group_members", + "sync_continuations", + "calendar_resource_versions")) { + assertThat( + jdbc.queryForObject( + "SELECT count(*) FROM " + table + " WHERE collection_id=?", + Long.class, + collection)) + .isZero(); + } + denied(() -> calendars.sync(reader, collection, token, 10)); + } + + @Test + void effectivePermissionsStayAuthoritativeAfterEachRevocation() { + UUID g = groups.create(auth(admin, true), "Contributors", Set.of("portal-reader")); + sharing.direct(auth(owner, true), collection, "portal-reader", "READ", "NONE"); + sharing.group(auth(owner, true), collection, g, "WRITE", "NONE"); + assertThat(portal.effective(auth(owner, false), collection, 0).rows()) + .singleElement() + .satisfies( + m -> { + assertThat(m.permission()) + .isEqualTo(dav.permission(reader, collection)) + .isEqualTo("WRITE"); + assertThat(m.direct()).isTrue(); + assertThat(m.groups()).isEqualTo(1); + }); + sharing.direct(auth(owner, true), collection, "portal-reader", "REVOKE", "READ"); + assertThat(dav.permission(reader, collection)).isEqualTo("WRITE"); + denied(() -> sharing.direct(auth(owner, true), collection, "portal-reader", "WRITE", "READ")); + denied(() -> portal.effective(auth(reader, true), collection, 0)); + denied(() -> portal.effective(auth(admin, true), collection, 0)); + groups.changeMember(auth(admin, true), g, null, reader, false, true); + denied(() -> portal.collection(auth(reader, true), collection)); + } + + @Test + void structuredMembershipDoesNotReplaceOtherMembersAndDisabledMembershipCanBeRemoved() { + UUID g = groups.create(auth(admin, true), "Team", Set.of("portal-reader")); + denied(() -> groups.changeMember(auth(owner, true), g, "portal-other", null, true, true)); + denied(() -> groups.changeMember(auth(admin, true), g, "portal-other", null, true, false)); + groups.changeMember(auth(admin, true), g, "portal-other", null, true, true); + assertThat(groups.detail(auth(admin, true), g).members()).isEqualTo(2); + accounts.disable(reader); + groups.changeMember(auth(admin, true), g, null, reader, false, true); + assertThat(groups.members(auth(admin, true), g, "", 0).rows()) + .singleElement() + .extracting(GroupService.MemberView::account) + .isEqualTo(other); + groups.rename(auth(admin, true), g, "Team", "New team"); + denied(() -> groups.rename(auth(admin, true), g, "Team", "Stale")); + } + + @Test + void accountProfileCannotChangeIdentityRolesOrMappings() { + var original = accounts.find(owner); + administration.edit(auth(admin, true), owner, original.displayName(), "Updated owner"); + var changed = accounts.find(owner); + assertThat(changed.id()).isEqualTo(original.id()); + assertThat(changed.username()).isEqualTo(original.username()); + assertThat(changed.administrator()).isFalse(); + assertThat(changed.passwordHash()).isEqualTo(original.passwordHash()); + denied(() -> administration.edit(auth(owner, true), other, "Unrelated", "Denied")); + denied(() -> administration.edit(auth(admin, true), owner, original.displayName(), "Stale")); + denied(() -> administration.disable(auth(admin, true), owner, false)); + administration.disable(auth(admin, true), owner, true); + assertThat(accounts.find(owner).enabled()).isFalse(); + denied(() -> portal.setup(authFor(original, true))); + assertThat(administration.accounts(auth(admin, true), "portal-owner", "disabled", 0).rows()) + .hasSize(1); + } + + @Test + void collectionAndAccountPagesAreBoundedSearchableAndIsolated() { + var tx = new org.springframework.transaction.support.TransactionTemplate(transactions); + tx.executeWithoutResult( + s -> { + for (int i = 0; i < 55; i++) calendars.createCollection(owner, "Page " + i, "VTODO"); + }); + assertThat(portal.collections(auth(owner, false), "owned", "", 0).rows()).hasSize(50); + assertThat(portal.collections(auth(owner, false), "owned", "", 0).hasNext()).isTrue(); + assertThat(portal.collections(auth(owner, false), "owned", "", 1).rows()).hasSize(6); + assertThat(portal.collections(auth(other, false), "all", "", 0).rows()).isEmpty(); + assertThat(portal.collections(auth(admin, false), "all", "", 0).rows()).isEmpty(); + denied(() -> portal.collections(auth(owner, true), "owned", "", -1)); + denied(() -> administration.accounts(auth(owner, true), "", "all", 0)); + assertThat(administration.accounts(auth(admin, true), "portal-owner", "local", 0).rows()) + .hasSize(1); + } + + @Test + void sensitiveOperationsRequireBothRecentFactorsAndCurrentAccount() { + denied(() -> portal.create(auth(owner, false), "Denied", "VEVENT", "", "")); + denied(() -> portal.create(null, "Denied", "VEVENT", "", "")); + denied(() -> management.issue(auth(owner, false), "Denied", 1)); + denied(() -> management.issue(auth(owner, true), "", 1)); + denied(() -> management.issue(auth(owner, true), "Valid", 366)); + var credential = management.issue(auth(owner, true), "Device", 1); + denied(() -> management.revoke(auth(other, true), credential.id())); + management.revoke(auth(owner, true), credential.id()); + assertThat(accounts.verifyDav("portal-owner", credential.secret())).isFalse(); + assertThat(portal.credentials(auth(owner, false), 0).rows()) + .singleElement() + .extracting(ManagementService.Credential::status) + .isEqualTo("Revoked"); + } + + @Test + void importPreviewConfirmationDuplicateConflictAndRoundTripAreAccurate() throws Exception { + byte[] file = (calendarBody("a") + calendarBody("b")).getBytes(StandardCharsets.UTF_8); + var preview = portability.preview(auth(owner, true), collection, file); + assertThat(preview.ready()).isEqualTo(2); + assertThat(calendars.metadataBatch(owner, collection, "", 10)).isEmpty(); + denied(() -> portability.confirm(auth(owner, true), preview.token(), false)); + denied(() -> portability.confirm(auth(other, true), preview.token(), true)); + var result = portability.confirm(auth(owner, true), preview.token(), true); + assertThat(result.imported()).isEqualTo(2); + assertThat(result.conflicts()).isZero(); + denied(() -> portability.confirm(auth(owner, true), preview.token(), true)); + var duplicate = portability.preview(auth(owner, true), collection, file); + assertThat(duplicate.skipped()).isEqualTo(2); + var conflict = + portability.preview( + auth(owner, true), + collection, + calendarBody("a") + .replace("DTSTART:20261028T000000Z", "DTSTART:20261029T000000Z") + .getBytes(StandardCharsets.UTF_8)); + assertThat(conflict.conflicts()).isEqualTo(1); + var exported = portability.export(auth(owner, true), collection); + byte[] bytes; + try { + bytes = Files.readAllBytes(exported.path()); + } finally { + Files.deleteIfExists(exported.path()); + } + UUID destination = portal.create(auth(owner, true), "Imported", "VEVENT", "", ""); + var roundtrip = + portability.confirm( + auth(owner, true), + portability.preview(auth(owner, true), destination, bytes).token(), + true); + assertThat(roundtrip.imported()).isEqualTo(2); + for (var m : calendars.metadataBatch(owner, destination, "", 10)) + assertThat(calendars.get(owner, destination, m.name()).content()).isEqualTo(event(m.uid())); + } + + @Test + void importRechecksWritePermissionAndReportsRejectedItemsWithoutMutation() throws Exception { + management.share(auth(owner, true), collection, "portal-reader", "WRITE"); + var preview = portability.preview(auth(reader, true), collection, event("safe")); + management.share(auth(owner, true), collection, "portal-reader", "READ"); + denied(() -> portability.confirm(auth(reader, true), preview.token(), true)); + denied(() -> portability.preview(auth(reader, true), collection, event("safe"))); + denied(() -> portability.export(auth(admin, true), collection)); + byte[] malformed = + calendarBody("invalid") + .replace("DTSTART:20261028T000000Z", "DTSTART:bad") + .getBytes(StandardCharsets.UTF_8); + var invalid = portability.preview(auth(owner, true), collection, malformed); + assertThat(invalid.rejected()).isEqualTo(1); + assertThat(calendars.metadataBatch(owner, collection, "", 10)).isEmpty(); + denied( + () -> + portability.preview( + auth(owner, true), collection, "not a calendar".getBytes(StandardCharsets.UTF_8))); + } + + @Test + void importRollbackNeverLeavesPartialResources() throws Exception { + var preview = + portability.preview( + auth(owner, true), + collection, + (calendarBody("a") + calendarBody("b")).getBytes(StandardCharsets.UTF_8)); + jdbc.execute( + "CREATE FUNCTION portal_fail_second() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.uid='b' THEN RAISE EXCEPTION 'injected failure'; END IF; RETURN NEW; END $$"); + jdbc.execute( + "CREATE TRIGGER portal_fail_second BEFORE INSERT ON calendar_resources FOR EACH ROW EXECUTE FUNCTION portal_fail_second()"); + try { + assertThatThrownBy(() -> portability.confirm(auth(owner, true), preview.token(), true)) + .isInstanceOf(org.springframework.dao.DataAccessException.class); + } finally { + jdbc.execute("DROP TRIGGER portal_fail_second ON calendar_resources"); + jdbc.execute("DROP FUNCTION portal_fail_second()"); + } + assertThat(calendars.metadataBatch(owner, collection, "", 10)).isEmpty(); + } + + @Test + void allPortalTemplatesRenderOverHttpsAndEscapeUntrustedText() throws Exception { + var browser = browser(owner, true); + for (String path : + List.of( + "/", + "/collections", + "/collections/new", + "/collections/" + collection, + "/collections/" + collection + "/delete", + "/collections/" + collection + "/sharing", + "/connections", + "/security", + "/security/credentials", + "/portability", + "/security/recovery", + "/security/password", + "/security/sessions", + "/oauth-grants", + "/security/passkeys", + "/login")) { + var response = get(browser, path); + assertThat(response.statusCode()).as(path).isEqualTo(200); + assertThat(response.body()) + .as(path) + .contains("/team/assets/account.css") + .doesNotContain(hostile); + assertThat(response.headers().firstValue("Cache-Control").orElse("")).contains("no-store"); + } + var adminBrowser = browser(admin, true); + UUID g = groups.create(auth(admin, true), "Group " + hostile, Set.of()); + for (String path : + List.of( + "/admin", + "/admin/accounts", + "/admin/accounts/new", + "/admin/accounts/" + owner, + "/admin/groups", + "/admin/groups/" + g, + "/admin/audit", + "/admin/diagnostics", + "/admin/oauth-clients")) { + var response = get(adminBrowser, path); + assertThat(response.statusCode()).as(path).isEqualTo(200); + assertThat(response.body()).as(path).doesNotContain(hostile); + } + assertThat(get(browser, "/admin/accounts").statusCode()).isEqualTo(403); + assertThat(get(adminBrowser, "/collections/" + collection).statusCode()).isEqualTo(403); + } + + @Test + void browserMutationsRequireCsrfAndServerConfirmation() throws Exception { + var browser = browser(owner, true); + assertThat( + post(browser, "/collections", Map.of("name", "CSRF denied", "component", "VEVENT")) + .statusCode()) + .isEqualTo(403); + String csrf = csrf(get(browser, "/collections/" + collection + "/delete").body()); + var deleted = + post( + browser, + "/collections/" + collection + "/delete", + Map.of( + "_csrf", + csrf, + "state", + portal.collection(auth(owner, true), collection).deletionState())); + assertThat(deleted.statusCode()).isEqualTo(400); + assertThat(calendars.collection(owner, collection)).isNotNull(); + var created = + post( + browser, + "/collections", + Map.of("_csrf", csrf, "name", "Browser collection", "component", "VTODO")); + assertThat(created.statusCode()).isEqualTo(302); + assertThat(created.headers().firstValue("Location").orElse("")).contains("/team/collections/"); + } + + @Test + void exportHttpHeadersAndAuditViewerNeverRevealSecrets() throws Exception { + calendars.put(owner, collection, "one.ics", "one", event("one"), WriteCondition.create()); + var credential = management.issue(auth(owner, true), "Private label", 1); + var response = get(browser(owner, true), "/portability/collections/" + collection + "/export"); + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.body()).isEqualTo(calendarBody("one")); + assertThat(response.headers().firstValue("Content-Type").orElse("")) + .startsWith("text/calendar"); + assertThat(response.headers().firstValue("Content-Disposition").orElse("")) + .contains("attachment") + .doesNotContain(hostile); + assertThat(get(browser(admin, true), "/admin/audit").body()) + .doesNotContain(credential.secret()) + .doesNotContain("DTSTART"); + denied(() -> administration.audit(auth(owner, true), "", "", "", 0)); + assertThat( + administration + .audit(auth(admin, true), "COLLECTION_CREATED", "SUCCESS", "portal-owner", 0) + .rows()) + .hasSize(1); + } + + @Test + void nativeCalendarAndTaskFixturesRoundTripWithoutByteChanges() throws Exception { + for (String type : List.of("VEVENT", "VTODO")) { + String name = type.equals("VEVENT") ? "thunderbird-event.ics" : "thunderbird-task.ics"; + byte[] original; + try (var input = getClass().getResourceAsStream("/calendar/clients/" + name)) { + assertThat(input).isNotNull(); + original = input.readAllBytes(); + } + UUID source = portal.create(auth(owner, true), "Native " + type, type, "", ""); + var first = portability.preview(auth(owner, true), source, original); + assertThat(first.ready()).isEqualTo(1); + assertThat(portability.confirm(auth(owner, true), first.token(), true).imported()) + .isEqualTo(1); + var export = portability.export(auth(owner, true), source); + byte[] exported; + try { + exported = Files.readAllBytes(export.path()); + } finally { + Files.deleteIfExists(export.path()); + } + assertThat(exported).isEqualTo(original); + UUID target = portal.create(auth(owner, true), "Migrated " + type, type, "", ""); + var second = portability.preview(auth(owner, true), target, exported); + assertThat(portability.confirm(auth(owner, true), second.token(), true).imported()) + .isEqualTo(1); + var metadata = calendars.metadataBatch(owner, target, "", 10); + assertThat(metadata).hasSize(1); + var parsed = org.busystack.caldav.calendar.CalendarContent.parse(original, type); + assertThat(metadata.getFirst().uid()).isEqualTo(parsed.uid()); + assertThat(calendars.get(owner, target, metadata.getFirst().name()).content()) + .isEqualTo(original); + } + } + + @Test + void supportedDirectoryCapacityUsesBoundedPagesAndSingleMemberAdmission() { + var tx = new org.springframework.transaction.support.TransactionTemplate(transactions); + tx.executeWithoutResult( + state -> { + jdbc.update( + "INSERT INTO accounts(id,username,display_name,password_hash) SELECT gen_random_uuid(),'capacity-user-'||lpad(n::text,4,'0'),'Capacity user '||n,? FROM generate_series(1,1000) n", + accounts.find(owner).passwordHash()); + jdbc.update( + "INSERT INTO sharing_groups(id,name,created_by) SELECT gen_random_uuid(),'Capacity group '||lpad(n::text,4,'0'),? FROM generate_series(1,1000) n", + admin); + }); + UUID group = groups.search(auth(admin, true), "Capacity group 0001", 0).rows().getFirst().id(); + jdbc.update( + "INSERT INTO sharing_group_members(group_id,account_id) SELECT ?,id FROM accounts WHERE username LIKE 'capacity-user-%'", + group); + long start = System.nanoTime(); + var accountPage = administration.accounts(auth(admin, true), "capacity-user-", "local", 0); + long accountsMillis = (System.nanoTime() - start) / 1000000; + assertThat(accountPage.rows()).hasSize(50); + assertThat(accountPage.hasNext()).isTrue(); + var last = administration.accounts(auth(admin, true), "capacity-user-", "local", 19); + assertThat(last.rows()).hasSize(50); + assertThat(last.hasNext()).isFalse(); + start = System.nanoTime(); + var groupPage = groups.search(auth(admin, true), "Capacity group ", 0); + long groupsMillis = (System.nanoTime() - start) / 1000000; + assertThat(groupPage.rows()).hasSize(50); + assertThat(groupPage.hasNext()).isTrue(); + start = System.nanoTime(); + var members = groups.members(auth(admin, true), group, "", 19); + long membersMillis = (System.nanoTime() - start) / 1000000; + assertThat(members.rows()).hasSize(50); + assertThat(members.hasNext()).isFalse(); + denied(() -> groups.changeMember(auth(admin, true), group, "portal-reader", null, true, true)); + groups.changeMember( + auth(admin, true), group, null, members.rows().getFirst().account(), false, true); + groups.changeMember(auth(admin, true), group, "portal-reader", null, true, true); + assertThat(groups.detail(auth(admin, true), group).members()).isEqualTo(1000); + System.out.printf( + "PORTAL_CAPACITY accounts=1000 groups=1000 members=1000 account_page_ms=%d group_page_ms=%d member_page_ms=%d%n", + accountsMillis, groupsMillis, membersMillis); + } + + private Authentication auth(UUID id, boolean mfa) { + return authFor(accounts.find(id), mfa); + } + + private Authentication authFor(AccountService.Account a, boolean mfa) { + List authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority(a.administrator() ? "ROLE_ADMIN" : "ROLE_USER")); + authorities.add(SessionSecurity.authority(a.securityEpoch())); + authorities.add( + FactorGrantedAuthority.fromAuthority(FactorGrantedAuthority.PASSWORD_AUTHORITY)); + if (mfa) + authorities.add( + FactorGrantedAuthority.fromAuthority(FactorGrantedAuthority.WEBAUTHN_AUTHORITY)); + return UsernamePasswordAuthenticationToken.authenticated(a.username(), null, authorities); + } + + private String persist(SessionRepository repo, Authentication auth) { + S session = repo.createSession(); + session.setAttribute( + HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, + new SecurityContextImpl(auth)); + repo.save(session); + return session.getId(); + } + + private HttpClient browser(UUID id, boolean mfa) throws Exception { + var cookies = new CookieManager(null, CookiePolicy.ACCEPT_ALL); + String encoded = + Base64.getEncoder() + .encodeToString(persist(repository, auth(id, mfa)).getBytes(StandardCharsets.UTF_8)); + cookies.put( + URI.create(base()), + Map.of( + "Set-Cookie", + List.of("JSESSIONID=" + encoded + "; Path=/team; Secure; HttpOnly; SameSite=Lax"))); + return HttpClient.newBuilder() + .sslContext(TestTls.instance().context()) + .cookieHandler(cookies) + .connectTimeout(Duration.ofSeconds(10)) + .followRedirects(HttpClient.Redirect.NEVER) + .build(); + } + + private HttpResponse get(HttpClient browser, String path) throws Exception { + return browser.send( + HttpRequest.newBuilder(URI.create(base() + path)) + .timeout(Duration.ofSeconds(30)) + .GET() + .build(), + HttpResponse.BodyHandlers.ofString()); + } + + private HttpResponse post(HttpClient browser, String path, Map fields) + throws Exception { + String form = + fields.entrySet().stream() + .map( + e -> + URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8) + + "=" + + URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8)) + .collect(java.util.stream.Collectors.joining("&")); + return browser.send( + HttpRequest.newBuilder(URI.create(base() + path)) + .timeout(Duration.ofSeconds(30)) + .header("Content-Type", "application/x-www-form-urlencoded") + .POST(HttpRequest.BodyPublishers.ofString(form)) + .build(), + HttpResponse.BodyHandlers.ofString()); + } + + private String base() { + return "https://localhost:" + port + "/team"; + } + + private static String csrf(String html) { + var matcher = + java.util.regex.Pattern.compile("name=\"_csrf\"[^>]*value=\"([^\"]+)\"").matcher(html); + assertThat(matcher.find()).isTrue(); + return matcher.group(1); + } + + private static String calendarBody(String uid) { + return "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Portal fixture//EN\r\nBEGIN:VEVENT\r\nUID:" + + uid + + "\r\nDTSTAMP:20261027T000000Z\r\nDTSTART:20261028T000000Z\r\nX-CLIENT:preserve\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"; + } + + private static byte[] event(String uid) { + return calendarBody(uid).getBytes(StandardCharsets.UTF_8); + } + + private interface Checked { + void run() throws Exception; + } + + private static void denied(Checked operation) { + assertThatThrownBy(operation::run) + .isInstanceOfAny( + IllegalArgumentException.class, StoreException.class, AccessDeniedException.class); + } +} From 5a23d5a817892d6374a2d1089b8b1968742d696a Mon Sep 17 00:00:00 2001 From: albert Date: Mon, 2 Nov 2026 14:28:57 -0700 Subject: [PATCH 02/82] Fix responsive security workflows and native portability qualification --- qualification/clients/thunderbird.py | 7 ++++++- qualification/passkeys/portal.mjs | 4 +++- .../security/oauth/OAuthManagementController.java | 12 +++++++++--- .../caldav/security/session/SessionController.java | 9 ++++++++- src/main/resources/static/assets/security.js | 2 +- src/main/resources/templates/account-detail.html | 2 +- src/main/resources/templates/account-error.html | 2 +- src/main/resources/templates/account-new.html | 2 +- src/main/resources/templates/accounts.html | 4 ++-- src/main/resources/templates/administration.html | 2 +- src/main/resources/templates/audit.html | 4 ++-- src/main/resources/templates/collection-delete.html | 2 +- src/main/resources/templates/collection-new.html | 2 +- src/main/resources/templates/collection-sharing.html | 8 ++++---- src/main/resources/templates/collection.html | 2 +- src/main/resources/templates/collections.html | 4 ++-- src/main/resources/templates/connections.html | 2 +- src/main/resources/templates/credentials.html | 6 +++--- src/main/resources/templates/dashboard.html | 4 ++-- src/main/resources/templates/diagnostics.html | 4 ++-- src/main/resources/templates/error/400.html | 2 +- src/main/resources/templates/error/403.html | 2 +- src/main/resources/templates/error/404.html | 2 +- src/main/resources/templates/error/500.html | 2 +- src/main/resources/templates/error/503.html | 2 +- src/main/resources/templates/fragments/layout.html | 4 ++-- src/main/resources/templates/group-detail.html | 4 ++-- src/main/resources/templates/group-error.html | 2 +- src/main/resources/templates/groups.html | 4 ++-- src/main/resources/templates/import-report.html | 4 ++-- src/main/resources/templates/issued-credential.html | 2 +- src/main/resources/templates/login.html | 4 ++-- src/main/resources/templates/oauth-clients.html | 4 ++-- src/main/resources/templates/oauth-consent.html | 2 +- src/main/resources/templates/oauth-error.html | 2 +- src/main/resources/templates/oauth-grants.html | 4 ++-- src/main/resources/templates/passkeys.html | 6 +++--- src/main/resources/templates/password.html | 2 +- src/main/resources/templates/portability.html | 2 +- src/main/resources/templates/portal-error.html | 2 +- src/main/resources/templates/recovery-codes.html | 2 +- src/main/resources/templates/recovery.html | 2 +- src/main/resources/templates/security.html | 2 +- src/main/resources/templates/sessions.html | 2 +- 44 files changed, 85 insertions(+), 65 deletions(-) diff --git a/qualification/clients/thunderbird.py b/qualification/clients/thunderbird.py index fad2181..44abaee 100644 --- a/qualification/clients/thunderbird.py +++ b/qualification/clients/thunderbird.py @@ -329,7 +329,12 @@ def main(): (artifacts / ("thunderbird-" + kind + ".ics")).write_bytes(result[kind].encode("utf-8")) assert len(events.events()) == 3 and len(tasks.todos(include_completed=True)) == 1 urls, completed = python_edits_native_items(events, tasks) - stream = "".join(item.data for item in events.objects()) + "".join(item.data for item in tasks.objects()) + stream_parts = [] + for resource in events.objects() + tasks.objects(): + resource.load() + assert resource.data is not None + stream_parts.append(resource.data.decode("utf-8") if isinstance(resource.data, bytes) else resource.data) + stream = "".join(stream_parts) imported = driver.execute_script(""" const parser=Cc['@mozilla.org/calendar/ics-parser;1'].createInstance(Ci.calIIcsParser); parser.parseString(arguments[0]); diff --git a/qualification/passkeys/portal.mjs b/qualification/passkeys/portal.mjs index cc0d1af..7786ce3 100644 --- a/qualification/passkeys/portal.mjs +++ b/qualification/passkeys/portal.mjs @@ -100,6 +100,7 @@ export async function qualifyPortalPresentation(page,base,collection,administrat assert.equal(await page.locator('main h1').count(),1,path+' must have one primary heading'); assert.equal(await page.locator('link[rel=stylesheet]').count(),1); assert.ok(await page.evaluate(()=>getComputedStyle(document.body).backgroundColor!=='rgba(0, 0, 0, 0)'),path+' must be styled'); + if(output) await page.screenshot({path:output+'/'+suffix+'-'+viewport.width+'-'+path.replaceAll('/','_').replaceAll('?','_')+'.png',fullPage:true}); assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1),path+' must fit the viewport'); const unlabeled=await page.locator('input:not([type=hidden]),select,textarea').evaluateAll(elements=>elements.filter(e=>!e.labels?.length && !e.getAttribute('aria-label') && !e.getAttribute('aria-labelledby')).map(e=>e.name||e.id)); assert.deepEqual(unlabeled,[],path+' control labels'); @@ -107,7 +108,8 @@ export async function qualifyPortalPresentation(page,base,collection,administrat assert.ok(await page.evaluate(()=>document.activeElement.tagName==='A'),'The skip link must be the first keyboard stop'); await page.keyboard.press('Enter'); assert.equal(new URL(page.url()).hash,'#main'); - if(output) await page.screenshot({path:output+'/'+suffix+'-'+viewport.width+'-'+path.replaceAll('/','_').replaceAll('?','_')+'.png',fullPage:true}); + assert.equal(await page.evaluate(()=>document.activeElement.id),'main','Skip navigation must move keyboard focus to the content'); + } } await page.setViewportSize({width:1280,height:900}); diff --git a/src/main/java/org/busystack/caldav/security/oauth/OAuthManagementController.java b/src/main/java/org/busystack/caldav/security/oauth/OAuthManagementController.java index b045dff..1d973d6 100644 --- a/src/main/java/org/busystack/caldav/security/oauth/OAuthManagementController.java +++ b/src/main/java/org/busystack/caldav/security/oauth/OAuthManagementController.java @@ -10,6 +10,7 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; @Controller public class OAuthManagementController { @@ -32,7 +33,8 @@ String register( Authentication authentication, @RequestParam String clientId, @RequestParam String name, - @RequestParam String redirects) { + @RequestParam String redirects, + RedirectAttributes flash) { clients.registerNative( authentication, clientId, @@ -42,12 +44,15 @@ String register( .map(String::strip) .filter(value -> !value.isEmpty()) .collect(Collectors.toSet())); + flash.addFlashAttribute("notice", "Application registration saved."); return "redirect:/admin/oauth-clients"; } @PostMapping("/admin/oauth-clients/{id}/remove") - String remove(Authentication authentication, @PathVariable String id) { + String remove(Authentication authentication, @PathVariable String id, RedirectAttributes flash) { clients.remove(authentication, id); + flash.addFlashAttribute( + "notice", "Application registration removed. Associated grants were revoked."); return "redirect:/admin/oauth-clients"; } @@ -59,8 +64,9 @@ String grants(Authentication authentication, Model model, HttpServletResponse re } @PostMapping("/oauth-grants/{id}/revoke") - String revoke(Authentication authentication, @PathVariable String id) { + String revoke(Authentication authentication, @PathVariable String id, RedirectAttributes flash) { grants.revoke(authentication, id); + flash.addFlashAttribute("notice", "Matching owned application grants are revoked."); return "redirect:/oauth-grants"; } diff --git a/src/main/java/org/busystack/caldav/security/session/SessionController.java b/src/main/java/org/busystack/caldav/security/session/SessionController.java index e4b9186..b5de86f 100644 --- a/src/main/java/org/busystack/caldav/security/session/SessionController.java +++ b/src/main/java/org/busystack/caldav/security/session/SessionController.java @@ -10,6 +10,7 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; @Controller public class SessionController { @@ -33,7 +34,11 @@ String list( } @PostMapping("/security/sessions/{id}/revoke") - String revoke(Authentication authentication, @PathVariable UUID id, HttpServletRequest request) { + String revoke( + Authentication authentication, + @PathVariable UUID id, + HttpServletRequest request, + RedirectAttributes flash) { var session = request.getSession(false); if (sessions.revoke( authentication, id, session == null ? null : session.getId(), request.getRemoteAddr())) { @@ -41,6 +46,8 @@ String revoke(Authentication authentication, @PathVariable UUID id, HttpServletR if (session != null) session.invalidate(); return "redirect:/login?session=ended"; } + flash.addFlashAttribute( + "notice", "The requested owned session has ended or is already unavailable."); return "redirect:/security/sessions"; } } diff --git a/src/main/resources/static/assets/security.js b/src/main/resources/static/assets/security.js index 4db4965..b1c6963 100644 --- a/src/main/resources/static/assets/security.js +++ b/src/main/resources/static/assets/security.js @@ -14,7 +14,7 @@ const response = await fetch(base + path, {method, credentials: 'same-origin', headers: {[csrfHeader]: csrfToken, 'Content-Type': 'application/json'}, body: body === undefined ? undefined : JSON.stringify(body)}); - if (!response.ok) throw new Error('Request failed (' + response.status + '). Verify your password and existing passkey, then try again.'); + if (!response.ok) throw new Error('Request failed (' + response.status + '). Verify your primary sign-in and existing passkey, then try again.'); return response.status === 204 ? null : response.json(); } function run(button, action) { diff --git a/src/main/resources/templates/account-detail.html b/src/main/resources/templates/account-detail.html index fb890a6..43ec64c 100644 --- a/src/main/resources/templates/account-detail.html +++ b/src/main/resources/templates/account-detail.html @@ -1,6 +1,6 @@ -
+
Back to accounts

Account identity

Username
Status
Role
Primary sign-in

Passkeys, credentials and recovery are managed by the user or the documented offline operator procedure. No password-reset, reactivation or privilege-change action is available here.

Edit profile

diff --git a/src/main/resources/templates/account-error.html b/src/main/resources/templates/account-error.html index eab742c..6e75274 100644 --- a/src/main/resources/templates/account-error.html +++ b/src/main/resources/templates/account-error.html @@ -1 +1 @@ -Check account details · BusyStack

Check the submitted details

The action could not accept one or more values. Review the account, collection, permission and field limits, then try again.

Return to your account

+Check account details · BusyStack

Check the submitted details

The action could not accept one or more values. Review the account, collection, permission and field limits, then try again.

Return to your account

diff --git a/src/main/resources/templates/account-new.html b/src/main/resources/templates/account-new.html index 3f79ca9..1e8d084 100644 --- a/src/main/resources/templates/account-new.html +++ b/src/main/resources/templates/account-new.html @@ -1,6 +1,6 @@ -
+
Back to accounts

Create an ordinary account

Provision a local account, then transfer the initial password securely to the intended user. Their first sign-in requires passkey enrollment and verification before they can change collections or issue client access.

Use 1–64 ASCII letters, digits, dots, underscores or hyphens, starting with a letter or digit. The login identity cannot be edited here.

At least fourteen characters and at most seventy-two UTF-8 bytes. This form cannot create an administrator or configure an external identity mapping.

Organization accounts are provisioned through the operator's configured subject allowlist, or a user's protected identity-linking workflow.

diff --git a/src/main/resources/templates/accounts.html b/src/main/resources/templates/accounts.html index f66c8ac..21627fa 100644 --- a/src/main/resources/templates/accounts.html +++ b/src/main/resources/templates/accounts.html @@ -1,9 +1,9 @@ -
+
Server administration

Accounts

Provision ordinary users and maintain profiles. Administration does not grant access to private calendar contents.

Create account
-

No accounts match these filters.

Account directory — 50 per page
AccountDisplay nameIdentityStatusRole
+

No accounts match these filters.

Account directory — 50 per page
AccountDisplay nameIdentityStatusRole
diff --git a/src/main/resources/templates/administration.html b/src/main/resources/templates/administration.html index 5c93183..cc2e8e2 100644 --- a/src/main/resources/templates/administration.html +++ b/src/main/resources/templates/administration.html @@ -1,6 +1,6 @@ -
+
Server administration

Server overview

Application version . Aggregate operational metadata does not grant access to private contents.

Create account

Accounts

Enabled · disabled

Manage accounts

Collections

calendars · task lists

Stored resources

Calendar and task resources, excluding retained history.

diff --git a/src/main/resources/templates/audit.html b/src/main/resources/templates/audit.html index a333f0a..06ca333 100644 --- a/src/main/resources/templates/audit.html +++ b/src/main/resources/templates/audit.html @@ -1,9 +1,9 @@ -
+
Server administration

Security & Audit

Recorded security metadata is retained for up to thirty days and approximately ten thousand rows. This is a bounded security record, not a calendar-activity history.

Manage OAuth application registrations

-

No retained events match these filters.

Recorded security events
Time (UTC)EventOutcomeAssociated account
+

No retained events match these filters.

Recorded security events
Time (UTC)EventOutcomeAssociated account
diff --git a/src/main/resources/templates/collection-delete.html b/src/main/resources/templates/collection-delete.html index d4ef049..7b9d4e1 100644 --- a/src/main/resources/templates/collection-delete.html +++ b/src/main/resources/templates/collection-delete.html @@ -1,6 +1,6 @@ -
+
Cancel and return to collection

Delete ?

This permanently removes this , every stored item and its synchronization history. Individual and group sharing access will be removed. Connected applications will lose this collection.

Export the collection first if you need a migration copy. Operator backups are managed separately.

Export before deleting
diff --git a/src/main/resources/templates/collection-new.html b/src/main/resources/templates/collection-new.html index 595b2d0..3a989ab 100644 --- a/src/main/resources/templates/collection-new.html +++ b/src/main/resources/templates/collection-new.html @@ -1,6 +1,6 @@ -
+
Back to collections

Create a collection

Keep calendars and task lists separate. The type stays fixed after creation.

Use #RRGGBB or #RRGGBBAA. This uses the Apple calendar-color convention; display depends on your client.

diff --git a/src/main/resources/templates/collection-sharing.html b/src/main/resources/templates/collection-sharing.html index 89f9c49..8fddb3b 100644 --- a/src/main/resources/templates/collection-sharing.html +++ b/src/main/resources/templates/collection-sharing.html @@ -1,15 +1,15 @@ -
+
Back to collection

Sharing:

Only the owner can change grants. Read-only permits retrieval; read and write also permits content and metadata changes. Group administrators control the group's current and future membership.

-

Direct account access

No direct grants. Group grants may still provide access.

Accounts with direct grants
UsernameDirect grantEffective accessChange grant
· disabled
+

Direct account access

No direct grants. Group grants may still provide access.

Accounts with direct grants
UsernameDirect grantEffective accessChange grant
· disabled
Grant access to an account

Enter the exact username supplied by the recipient. This interface does not expose an account directory.

-

Group access

No groups have a grant for this collection.

Groups with grants for this collection
GroupGrantChange grant
+

Group access

No groups have a grant for this collection.

Groups with grants for this collection
GroupGrantChange grant
Grant access to a group

All current and future group members receive this grant. Administrators control membership.

No sharing groups are available. Ask an administrator to create one.

-

Effective permissions

The owner's access is always Owner. For other accounts, any read/write grant gives read/write access. Removing one grant leaves all other grants effective. Disabled accounts cannot authenticate.

No recipients currently have effective grants.

Combined direct and group access
AccountEffective accessContributing grants
Direct grant;
+

Effective permissions

The owner's access is always Owner. For other accounts, any read/write grant gives read/write access. Removing one grant leaves all other grants effective. Disabled accounts cannot authenticate.

No recipients currently have effective grants.

Combined direct and group access
AccountEffective accessContributing grants
Direct grant;
diff --git a/src/main/resources/templates/collection.html b/src/main/resources/templates/collection.html index aa6d1f6..f5fe451 100644 --- a/src/main/resources/templates/collection.html +++ b/src/main/resources/templates/collection.html @@ -1,6 +1,6 @@ -
+
Back to collections

CalDAV address

Connection guide · Import iCalendar

diff --git a/src/main/resources/templates/collections.html b/src/main/resources/templates/collections.html index c76eecb..70687a9 100644 --- a/src/main/resources/templates/collections.html +++ b/src/main/resources/templates/collections.html @@ -1,11 +1,11 @@ -
+
My account

Calendars & Tasks

Manage collections and access. Use your connected application to edit their contents.

Create a collection
-

No collections match this view. Create a calendar or task listAsk a collection owner to share with your username.

Collection details
CollectionTypeOwnerAccessActions

Details Sharing
+

No collections match this view. Create a calendar or task listAsk a collection owner to share with your username.

Collection details
CollectionTypeOwnerAccessActions

Details Sharing
diff --git a/src/main/resources/templates/connections.html b/src/main/resources/templates/connections.html index e6f19c4..518846e 100644 --- a/src/main/resources/templates/connections.html +++ b/src/main/resources/templates/connections.html @@ -1,6 +1,6 @@ -
+
My account

Connect your applications

Use a dedicated DAV credential as the application password. Your browser sign-in password does not authenticate CalDAV.

Issue an application credential

Your connection settings

Authentication: named DAV credential using Basic over HTTPS. A registered application that supports BusyStack OAuth may use browser authorization instead.

diff --git a/src/main/resources/templates/credentials.html b/src/main/resources/templates/credentials.html index 35e83bc..260978b 100644 --- a/src/main/resources/templates/credentials.html +++ b/src/main/resources/templates/credentials.html @@ -1,9 +1,9 @@ -
+
-Back to security

DAV credentials

Issue a separate credential for each application or device. These are credentials, not a list of verified device connections. Secrets appear once and cannot be retrieved later.

+Back to security

DAV credentials

Issue a separate credential for each application or device. These are credentials, not a list of verified device connections. Secrets appear once and cannot be retrieved later.

Issue a credential

Choose 1–365 days. Expiration stops future authentication. For replacement, issue a new credential, configure the application, then revoke the old one.

-

Issued credentials

No DAV credentials have been issued. Create one above, then follow Connections.

Credential metadata
LabelCreatedExpiresStatusAction
+

Issued credentials

No DAV credentials have been issued. Create one above, then follow Connections.

Credential metadata
LabelCreatedExpiresStatusAction
diff --git a/src/main/resources/templates/dashboard.html b/src/main/resources/templates/dashboard.html index a9010c7..fcbfc0e 100644 --- a/src/main/resources/templates/dashboard.html +++ b/src/main/resources/templates/dashboard.html @@ -1,10 +1,10 @@ -
+
My account

Welcome,

·

Connect an application

My collections

Calendars and task lists you own.

Manage my collections

Shared with me

Collections available through direct or group access.

View shared collections

Account security

Review security

Finish setting up your account

  1. Enroll and verify your first passkey. Your primary sign-in and passkey protect account changes.
  2. Create a calendar or task list, or ask an owner to share one with your username.
  3. Issue an application credential for a CalDAV client, unless your application uses registered OAuth authorization.
  4. Save recovery codes offline so a lost passkey does not lock you out.

Follow the client connection guide. The server does not track whether you have configured an application.

-

Your calendars and task lists

You have no collections yet. Create your first calendar or task list.

Up to 50 available collections
NameTypeAccess

Open collection management to edit details, manage sharing or export your data.

+

Your calendars and task lists

You have no collections yet. Create your first calendar or task list.

Up to 50 available collections
NameTypeAccess

Open collection management to edit details, manage sharing or export your data.

diff --git a/src/main/resources/templates/diagnostics.html b/src/main/resources/templates/diagnostics.html index 904b93b..f461fd1 100644 --- a/src/main/resources/templates/diagnostics.html +++ b/src/main/resources/templates/diagnostics.html @@ -1,10 +1,10 @@ -
+
Server administration

System & Diagnostics

Deployment

Application
Public base URL
OAuth issuer
Java runtime
Database
PostgreSQL
Applied migration

HTTP observations since startup

Completed requests
Server errors
Mean duration (ms)
Recent maximum (ms)

Metrics reset on restart. The recent maximum follows the metrics registry's observation window.

-

Recent operational problems

No server failures have been recorded in this process's bounded recent-problem buffer. This does not establish the absence of older or external failures.

Up to 50 observed server failures since startup
Time (UTC)SurfaceMethodStatusRequest identifier
+

Recent operational problems

No server failures have been recorded in this process's bounded recent-problem buffer. This does not establish the absence of older or external failures.

Up to 50 observed server failures since startup
Time (UTC)SurfaceMethodStatusRequest identifier

Troubleshooting

Database or startup failure

Check local readiness probes, database availability, configured credentials and migration validation in operator logs. A database outage can prevent authenticated administration itself; use deployment monitoring. Configuration is validated at startup. Keep database access private and use the documented backup and recovery procedure.

Organization identity provider unavailable

Check the explicitly configured issuer, provider availability, trusted TLS certificate and redirect URI. Discovery is deferred to organization sign-in. Local accounts work independently. Externally managed accounts fail closed when provider authentication is required, without a password fallback. Previously issued client access keeps only its existing freshness bound.

Authentication or permission failure

Ask the user to check credential expiration, revocation and recent primary/passkey verification. Review recorded security outcomes in the audit viewer. Local disabling denies access even if group memberships remain. Administration does not bypass collection ownership.

CalDAV compatibility and synchronization

Use the project's qualified client/version profile. The documented default supports narrowly bounded sync Depth: 1 and local timezone-observance UNTIL repair. Strict-mode settings are controlled by the operator. Permission or group changes can invalidate synchronization tokens; a client must start fresh synchronization.

Use the response's X-Request-ID to correlate safe request metadata with operator logs. Request contents and credentials must not be collected for troubleshooting. Backups and public TLS renewal are external operator responsibilities; their status is unknown here.

diff --git a/src/main/resources/templates/error/400.html b/src/main/resources/templates/error/400.html index 63d1771..551feda 100644 --- a/src/main/resources/templates/error/400.html +++ b/src/main/resources/templates/error/400.html @@ -1 +1 @@ -

Check the request

The request could not be understood. Review the form fields and try again.

+

Check the request

The request could not be understood. Review the form fields and try again.

diff --git a/src/main/resources/templates/error/403.html b/src/main/resources/templates/error/403.html index e117b2d..54c3fac 100644 --- a/src/main/resources/templates/error/403.html +++ b/src/main/resources/templates/error/403.html @@ -1 +1 @@ -Action not allowed · BusyStack

Action not allowed

Sensitive actions require recent sign-in and passkey verification. Sharing and administration also require permission for the affected account or collection.

Sign in again · Verify a passkey · Return to your account

\ No newline at end of file +Action not allowed · BusyStack

Action not allowed

Sensitive actions require recent sign-in and passkey verification. Sharing and administration also require permission for the affected account or collection.

Sign in again · Verify a passkey · Return to your account

\ No newline at end of file diff --git a/src/main/resources/templates/error/404.html b/src/main/resources/templates/error/404.html index 6a148db..f116ca6 100644 --- a/src/main/resources/templates/error/404.html +++ b/src/main/resources/templates/error/404.html @@ -1 +1 @@ -

Page unavailable

This page or resource is unavailable to this account.

+

Page unavailable

This page or resource is unavailable to this account.

diff --git a/src/main/resources/templates/error/500.html b/src/main/resources/templates/error/500.html index 4f1a28c..da9c89f 100644 --- a/src/main/resources/templates/error/500.html +++ b/src/main/resources/templates/error/500.html @@ -1 +1 @@ -

Service error

The operation could not complete. Use the request identifier when contacting your operator.

+

Service error

The operation could not complete. Use the request identifier when contacting your operator.

diff --git a/src/main/resources/templates/error/503.html b/src/main/resources/templates/error/503.html index 252db46..20e9785 100644 --- a/src/main/resources/templates/error/503.html +++ b/src/main/resources/templates/error/503.html @@ -1 +1 @@ -

Temporarily unavailable

The service cannot handle this request right now. Try again after a short wait, or ask the operator to check readiness and database connectivity.

+

Temporarily unavailable

The service cannot handle this request right now. Try again after a short wait, or ask the operator to check readiness and database connectivity.

diff --git a/src/main/resources/templates/fragments/layout.html b/src/main/resources/templates/fragments/layout.html index 35bd35a..a2734f4 100644 --- a/src/main/resources/templates/fragments/layout.html +++ b/src/main/resources/templates/fragments/layout.html @@ -19,14 +19,14 @@ Overview Calendars & Tasks Connections - Security + Security Import & Export diff --git a/src/main/resources/templates/group-detail.html b/src/main/resources/templates/group-detail.html index 43edaca..e02a21a 100644 --- a/src/main/resources/templates/group-detail.html +++ b/src/main/resources/templates/group-detail.html @@ -1,11 +1,11 @@ -
+
Back to groups

members · collection grants. Collection names and contents remain private unless independently shared with you.

Rename group

Add one member

Adding an account gives it access to all collections already shared with this group, according to each owner's grant. Future grants also apply.

-

Current members

Removing a membership may remove calendar access. Any other direct or group grant continues to apply.

No members match this view.

Group members — 50 per page
AccountDisplay nameStatusMembership
+

Current members

Removing a membership may remove calendar access. Any other direct or group grant continues to apply.

No members match this view.

Group members — 50 per page
AccountDisplay nameStatusMembership

Delete group

All recorded memberships and collection grants for this group will be removed. Access through other grants remains effective.

diff --git a/src/main/resources/templates/group-error.html b/src/main/resources/templates/group-error.html index 94ccb10..ff2036f 100644 --- a/src/main/resources/templates/group-error.html +++ b/src/main/resources/templates/group-error.html @@ -1,2 +1,2 @@ -Check the group request · BusyStack

Check the group request

+Check the group request · BusyStack

Check the group request

diff --git a/src/main/resources/templates/groups.html b/src/main/resources/templates/groups.html index f2a05fd..6d69a58 100644 --- a/src/main/resources/templates/groups.html +++ b/src/main/resources/templates/groups.html @@ -1,10 +1,10 @@ -
+
Server administration

Sharing groups

Manage local group membership. Owners choose which collections to share with each group. Membership administration does not bypass private collection permissions.

Create a group

-

No groups match this search. Create a group above to manage shared access.

Groups — 50 per page
GroupMembersCollection grants
+

No groups match this search. Create a group above to manage shared access.

Groups — 50 per page
GroupMembersCollection grants
diff --git a/src/main/resources/templates/import-report.html b/src/main/resources/templates/import-report.html index 62639c3..d38ccca 100644 --- a/src/main/resources/templates/import-report.html +++ b/src/main/resources/templates/import-report.html @@ -1,9 +1,9 @@ -
+
Back to Import & Export

Destination: .

Summary

Imported
Ready to import
Skipped (identical)
Conflicting
Rejected

Nothing has been imported yet. Confirmation imports only valid new items, preserving existing data. Authorization and conflicts are checked again at confirmation. Expires .

All reported new items were committed together. Existing resources were preserved. No rejected or conflicting item was written.

-

Item validation

Each UID series is one item, including its recurrence exceptions
ItemUIDResultDetails
.
+

Item validation

Each UID series is one item, including its recurrence exceptions
ItemUIDResultDetails
.

Confirm or discard

diff --git a/src/main/resources/templates/issued-credential.html b/src/main/resources/templates/issued-credential.html index 91a9b6b..8a4e9aa 100644 --- a/src/main/resources/templates/issued-credential.html +++ b/src/main/resources/templates/issued-credential.html @@ -1,2 +1,2 @@ -New DAV credential

New DAV credential

Store this secret in your application's credential settings. It is shown only in this response.

Username
Secret
Expires

Continue to connection instructions · Manage credentials

Return to your account

+New DAV credential

New DAV credential

Store this secret in your application's credential settings. It is shown only in this response.

Username
Secret
Expires

Continue to connection instructions · Manage credentials

Return to your account

diff --git a/src/main/resources/templates/login.html b/src/main/resources/templates/login.html index 71a7ef9..3761a1b 100644 --- a/src/main/resources/templates/login.html +++ b/src/main/resources/templates/login.html @@ -3,9 +3,9 @@ Sign in · BusyStack -

Sign in to BusyStack

+

Sign in to BusyStack

Complete primary sign-in, then verify your passkey for the same account. Sensitive changes require both factors within ten minutes.

Signed in as .

Password changed and prior access revoked. Sign in with your new password, then verify your existing passkey.

-

Sign in failed. Check your account details.

+

Recovery completed. Prior passkeys and client access were revoked. Sign in again and enroll a new passkey.

Browser session ended. Sign in again to continue.

Sign in failed. Check your account details.

Sign in with your organization's identity provider

1. Primary sign-in

Use your organization identity provider. Local-password sign-in is unavailable for this account.

2. Verify your passkey

diff --git a/src/main/resources/templates/oauth-clients.html b/src/main/resources/templates/oauth-clients.html index aaae52d..c02fdba 100644 --- a/src/main/resources/templates/oauth-clients.html +++ b/src/main/resources/templates/oauth-clients.html @@ -1,9 +1,9 @@ OAuth clients · BusyStack -

OAuth clients

+

OAuth clients

Register a calendar or task application that supports authorization code with S256 PKCE. Native applications use public client identification and have no embedded secret. Generic CalDAV discovery does not register an OAuth client.

Registering and removing clients requires password and passkey verification within ten minutes. Removing a client revokes every grant issued to it.

-
Registered applications
Client IDNameRedirectsAction
+
Registered applications
Client IDNameRedirectsAction

Register a native application

Use application-owned HTTPS URLs, IP loopback HTTP URLs with a port, or reverse-domain application schemes such as org.example.calendar:/callback. Register at most five redirects. Non-loopback redirects use exact matching.

diff --git a/src/main/resources/templates/oauth-consent.html b/src/main/resources/templates/oauth-consent.html index 81d88a4..a45a410 100644 --- a/src/main/resources/templates/oauth-consent.html +++ b/src/main/resources/templates/oauth-consent.html @@ -1,2 +1,2 @@ -Authorize application · BusyStack

Authorize application

requests access to your calendars and tasks. Your collection permissions apply to every request.

+Authorize application · BusyStack

Authorize application

requests access to your calendars and tasks. Your collection permissions apply to every request.

diff --git a/src/main/resources/templates/oauth-error.html b/src/main/resources/templates/oauth-error.html index ce23a56..cadf6ef 100644 --- a/src/main/resources/templates/oauth-error.html +++ b/src/main/resources/templates/oauth-error.html @@ -1,2 +1,2 @@ -OAuth request · BusyStack

Check the request

+OAuth request · BusyStack

Check the request

diff --git a/src/main/resources/templates/oauth-grants.html b/src/main/resources/templates/oauth-grants.html index 4b418e7..53eb9fc 100644 --- a/src/main/resources/templates/oauth-grants.html +++ b/src/main/resources/templates/oauth-grants.html @@ -1,7 +1,7 @@ Client access · BusyStack -

OAuth client access

+

OAuth client access

Approved applications can access your calendar and task collections within your existing sharing permissions. Revoking access invalidates that application's current access and refresh credentials immediately.

Revocation requires password and passkey verification within ten minutes. Applications must sign in again after thirty days.

-
Authorization grants
ApplicationAuthorizedExpiresRevokedAction
()

No OAuth applications have been authorized.

+
Authorization grants
ApplicationAuthorizedExpiresRevokedAction
()

No OAuth applications have been authorized.

diff --git a/src/main/resources/templates/passkeys.html b/src/main/resources/templates/passkeys.html index 0bae7c8..1ef5bae 100644 --- a/src/main/resources/templates/passkeys.html +++ b/src/main/resources/templates/passkeys.html @@ -2,12 +2,12 @@ Passkeys · BusyStack -

Passkeys

First enrollment requires primary sign-in within ten minutes: a local password or your configured organization provider. Adding or removing a passkey requires recent primary sign-in and passkey verification. Your authenticator must verify your presence and unlock the passkey.

+

Passkeys

First enrollment requires primary sign-in within ten minutes: a local password or your configured organization provider. Adding or removing a passkey requires recent primary sign-in and passkey verification. Your authenticator must verify your presence and unlock the passkey.

-

No passkeys are enrolled. Register one above, then verify it to complete MFA.

-
Registered passkeys
NameCreatedLast usedAction
+

No passkeys are enrolled. Register one above, then verify it to complete MFA.

+
Registered passkeys
NameCreatedLast usedAction

Verify another factor · Account management

diff --git a/src/main/resources/templates/password.html b/src/main/resources/templates/password.html index 51970b9..cf43eff 100644 --- a/src/main/resources/templates/password.html +++ b/src/main/resources/templates/password.html @@ -1,2 +1,2 @@ -Password · BusyStack

Change your local password

Password changes require recent primary and passkey verification. They end every session and revoke DAV credentials, OAuth access and recovery codes. Your passkeys remain registered.

If your account uses an external identity provider, change the primary credential there.

Use at least fourteen characters, within seventy-two UTF-8 bytes.

+Password · BusyStack

Change your local password

Password changes require recent primary and passkey verification. They end every session and revoke DAV credentials, OAuth access and recovery codes. Your passkeys remain registered.

If your account uses an external identity provider, change the primary credential there.

Use at least fourteen characters, within seventy-two UTF-8 bytes.

diff --git a/src/main/resources/templates/portability.html b/src/main/resources/templates/portability.html index 54fe8fa..9a08790 100644 --- a/src/main/resources/templates/portability.html +++ b/src/main/resources/templates/portability.html @@ -1,6 +1,6 @@ -
+
My account

Import & Export

Move your calendar and task data using iCalendar files. No invitations, alarms or outbound messages are executed by import.

Choose a collection

Readable collections can be exported. Owners and read/write recipients can import into a collection of the matching type.

No collections are available. Create a destination collection first.

Export this collection

Up to 8 MiB per file and 1 MiB per UID series, with at most 1,000 imported items. The actual content is validated. Select a file to review conflicts before confirming.

Data preservation and limits

Exports contain complete stored calendar objects as an RFC 5545 iCalendar stream. Recurrence exceptions and embedded timezone definitions stay with their UID series, including distinct timezone definitions from different resources. The exported stream preserves stored resource bytes. Some other applications accept only a single VCALENDAR per import; verify their import behavior before migration.

Exports are bounded to 10,000 resources and 64 MiB. Larger exports fail before a download starts. Imports preserve existing resources: identical resources are skipped and different resources with an existing UID are reported as conflicts. Valid new series are committed together; rejected, conflicting and skipped items are explicitly listed. A failure while writing rolls back every new resource.

Import previews expire after ten minutes and are replaced by your next preview. Restarting this instance invalidates pending previews. Files are stored temporarily on this server, not in browser storage.

diff --git a/src/main/resources/templates/portal-error.html b/src/main/resources/templates/portal-error.html index aae831d..68f3ec4 100644 --- a/src/main/resources/templates/portal-error.html +++ b/src/main/resources/templates/portal-error.html @@ -1,6 +1,6 @@ -
+

The request could not complete

Your submitted non-secret fields
diff --git a/src/main/resources/templates/recovery-codes.html b/src/main/resources/templates/recovery-codes.html index 793a496..22ce775 100644 --- a/src/main/resources/templates/recovery-codes.html +++ b/src/main/resources/templates/recovery-codes.html @@ -1,2 +1,2 @@ -Save recovery codes · BusyStack

Save your recovery codes

These codes appear once. Store them securely offline. Each code is single use, expires at , and still requires your recent primary sign-in.

Generating another set revokes these codes. The server retains only their verifiers.

Return to recovery settings

+Save recovery codes · BusyStack

Save your recovery codes

These codes appear once. Store them securely offline. Each code is single use, expires at , and still requires your recent primary sign-in.

Generating another set revokes these codes. The server retains only their verifiers.

Return to recovery settings

diff --git a/src/main/resources/templates/recovery.html b/src/main/resources/templates/recovery.html index 68d47d3..0d152ef 100644 --- a/src/main/resources/templates/recovery.html +++ b/src/main/resources/templates/recovery.html @@ -1,2 +1,2 @@ -Recovery · BusyStack

Account recovery

Keep recovery codes offline. A code can replace a lost passkey after you recently verify your primary sign-in. It cannot replace your password or upstream sign-in.

Unused codes: · expires .

Generate new recovery codes

Requires recent primary and passkey verification. Generating a new set revokes every unused code from the previous set. Codes appear once.

Recover from a lost passkey

First verify your primary sign-in. Recovery consumes this code, removes all passkeys, revokes DAV and OAuth access, and ends every browser session. Then sign in again and enroll a new passkey.

+Recovery · BusyStack

Account recovery

Keep recovery codes offline. A code can replace a lost passkey after you recently verify your primary sign-in. It cannot replace your password or upstream sign-in.

Unused codes: · expires .

Generate new recovery codes

Requires recent primary and passkey verification. Generating a new set revokes every unused code from the previous set. Codes appear once.

Recover from a lost passkey

First verify your primary sign-in. Recovery consumes this code, removes all passkeys, revokes DAV and OAuth access, and ends every browser session. Then sign in again and enroll a new passkey.

diff --git a/src/main/resources/templates/security.html b/src/main/resources/templates/security.html index b1b3cf0..138c0e1 100644 --- a/src/main/resources/templates/security.html +++ b/src/main/resources/templates/security.html @@ -1,6 +1,6 @@ -
+
My account

Security

Passkeys & authentication

Manage passkeys · Verify sign-in

Application credentials

Manage DAV credentials

Browser sessions

Review and end sessions. Password changes and recovery end all sessions.

Review sessions

Recovery

Manage recovery codes

OAuth applications

Review and revoke browser-authorized application access.

Manage OAuth grants

Primary credentials

Change your primary credentials through your organization's identity provider. A local-password fallback is unavailable.

Your password is managed on this server.

Change local password
diff --git a/src/main/resources/templates/sessions.html b/src/main/resources/templates/sessions.html index a9b230c..ad1d896 100644 --- a/src/main/resources/templates/sessions.html +++ b/src/main/resources/templates/sessions.html @@ -1,2 +1,2 @@ -Sessions · BusyStack

Active browser sessions

Sessions expire after thirty minutes of inactivity. Ending a session requires recent primary and passkey verification. DAV and OAuth access are managed separately.

Your browser sessions
CreatedLast usedExpiresBrowserAction
+Sessions · BusyStack

Active browser sessions

Sessions expire after thirty minutes of inactivity. Ending a session requires recent primary and passkey verification. DAV and OAuth access are managed separately.

Your browser sessions
CreatedLast usedExpiresBrowserAction
From e77566143bbb17fa16eea1acca360980ecc585ca Mon Sep 17 00:00:00 2001 From: albert Date: Mon, 2 Nov 2026 16:26:03 -0700 Subject: [PATCH 03/82] Harden portal presentation and extend browser and native qualification --- .gitignore | 1 + docs/portal.md | 9 +- qualification/clients/README.md | 20 ++ qualification/clients/gnome.py | 302 ++++++++++++++++++ qualification/passkeys/groups.mjs | 34 +- qualification/passkeys/passkeys.mjs | 8 +- qualification/passkeys/portal-helpers.mjs | 2 +- qualification/passkeys/portal.mjs | 4 +- qualification/passkeys/run.py | 21 +- .../caldav/management/PortalPageAdvice.java | 6 +- src/main/resources/static/assets/account.css | 2 +- src/main/resources/templates/audit.html | 2 +- src/main/resources/templates/connections.html | 2 +- src/main/resources/templates/credentials.html | 2 +- src/main/resources/templates/diagnostics.html | 2 +- src/main/resources/templates/error.html | 1 + src/main/resources/templates/error/413.html | 1 + .../resources/templates/fragments/layout.html | 1 + .../resources/templates/import-report.html | 2 +- .../templates/issued-credential.html | 2 +- .../resources/templates/oauth-clients.html | 4 +- .../resources/templates/oauth-grants.html | 4 +- src/main/resources/templates/passkeys.html | 6 +- src/main/resources/templates/password.html | 2 +- .../resources/templates/recovery-codes.html | 2 +- src/main/resources/templates/recovery.html | 2 +- src/main/resources/templates/sessions.html | 2 +- .../caldav/management/PortalManagementIT.java | 67 ++++ .../management/PortalPageAdviceTest.java | 46 +++ 29 files changed, 530 insertions(+), 29 deletions(-) create mode 100644 qualification/clients/gnome.py create mode 100644 src/main/resources/templates/error.html create mode 100644 src/main/resources/templates/error/413.html create mode 100644 src/test/java/org/busystack/caldav/management/PortalPageAdviceTest.java diff --git a/.gitignore b/.gitignore index 6eb69d0..d087e47 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ target/ +.qualification-runs/ **/target/ .idea/ *.iml diff --git a/docs/portal.md b/docs/portal.md index 66edced..d5b4f9a 100644 --- a/docs/portal.md +++ b/docs/portal.md @@ -71,9 +71,12 @@ Thunderbird instructions on Connections follow the documented network-calendar wizard. Historical qualification covers Thunderbird 159.0 and GNOME Calendar 50.0 / EDS 3.56.2 on the exact 0.1.0 executable and configurations in the [client record](observance-until-compatibility.md#qualified-client-configurations). -The GNOME record uses a source provisioned through EDS's supported API; it does not -qualify a graphical account-creation wizard. Do not equate that with a verified -GNOME setup procedure. Current artifact results are recorded separately; BusyMax +The historical GNOME record uses a source provisioned through EDS's supported API. +Connections also documents the GNOME 50.0 wizard: **Manage Calendars → Add Calendar**, +enter the collection HTTPS address under **Connect to an Online Calendar**, supply +the username and dedicated DAV credential in **Credentials**, choose **Connect**, +select the discovered calendar and choose **Add Calendar**. Those graphical setup +steps are documented but await qualification. Current artifact results are recorded separately; BusyMax and other untested clients are not advertised as supported. Registered OAuth applications may use browser consent instead of a DAV credential. diff --git a/qualification/clients/README.md b/qualification/clients/README.md index 9dc78c5..0ba47a7 100644 --- a/qualification/clients/README.md +++ b/qualification/clients/README.md @@ -39,3 +39,23 @@ The packaged restore corpus admits the captured uploads, verifies corrected hash and transformed-PUT validator omission, and checks bytes/history/UTC expansion after restoration. Missing prerequisites, startup failures and assertion failures remain failures; earlier attempts are not relabeled as successful runs. + +## Optional installed GNOME connection wizard + +On a Linux graphical workstation with GNOME Calendar `50.0-1`, Evolution Data +Server `3.56.2-8`, Python GI/AT-SPI, GNOME Keyring, bubblewrap and an existing X11 +or Xwayland display, `qualification/passkeys/run.py --gnome` adds a real native +connection wizard to the existing packaged HTTPS browser profile. Use +`--application-image` and `--browser-image` as documented in the +[passkey qualification](../passkeys/README.md). Missing prerequisites fail; +this optional profile is never silently substituted for the normal browser run. + +The browser creates the collection, edits metadata, imports contents and issues a +DAV credential. The host fixture drives only its own GNOME accessibility tree +through Manage Calendars, Add Calendar, HTTPS address, credentials and discovery. +It verifies the durable native CalDAV source. It uses a disposable home, private +session/accessibility buses, keyring and namespace-only fixture CA trust. It does +not modify installed software, the host trust store or the user's existing +calendar/profile. Secrets remain in temporary private exchange files; retained +results contain redacted diagnostics and accessible control names. This profile +qualifies account setup, not every event-editing or assistive-technology workflow. diff --git a/qualification/clients/gnome.py b/qualification/clients/gnome.py new file mode 100644 index 0000000..4adb783 --- /dev/null +++ b/qualification/clients/gnome.py @@ -0,0 +1,302 @@ +#!/usr/bin/env python3 +"""Optional installed GNOME Calendar qualification, reusing private DBus/X11/AT-SPI fixtures. + +Only a disposable home and this process's own application accessibility tree are used. +No installed application, host trust store, existing calendar or user configuration changes. +""" +import argparse +import configparser +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import time +from urllib.parse import urlsplit + + +def execute_child(root): + import gi + gi.require_version('Atspi', '2.0') + gi.require_version('Gdk', '3.0') + gi.require_version('GdkX11', '3.0') + from gi.repository import Atspi, Gdk, GdkX11, Gio, GLib + Gdk.init([]) + fixture = json.loads((root / 'client.json').read_text()) + bus = Gio.bus_get_sync(Gio.BusType.SESSION, None) + address = bus.call_sync('org.a11y.Bus', '/org/a11y/bus', 'org.a11y.Bus', 'GetAddress', None, + GLib.VariantType.new('(s)'), Gio.DBusCallFlags.NONE, 10000, None).unpack()[0] + os.environ['AT_SPI_BUS_ADDRESS'] = address + # Unlock only this fixture's private login keyring through the supported daemon interface. + subprocess.run(['gnome-keyring-daemon', '--unlock'], input=b'private-qualification-keyring\n', + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True, timeout=15) + process = subprocess.Popen(['gnome-calendar'], stdout=(root / 'application.log').open('w'), stderr=subprocess.STDOUT) + def capture(label): + import ctypes + x = ctypes.CDLL('libX11.so.6') + pointer, window = ctypes.c_void_p, ctypes.c_ulong + x.XOpenDisplay.restype = pointer + x.XDefaultRootWindow.argtypes = [pointer] + x.XDefaultRootWindow.restype = window + x.XInternAtom.argtypes = [pointer, ctypes.c_char_p, ctypes.c_int] + x.XInternAtom.restype = window + x.XQueryTree.argtypes = [pointer, window, ctypes.POINTER(window), ctypes.POINTER(window), ctypes.POINTER(ctypes.POINTER(window)), ctypes.POINTER(ctypes.c_uint)] + x.XGetWindowProperty.argtypes = [pointer, window, window, ctypes.c_long, ctypes.c_long, ctypes.c_int, window, ctypes.POINTER(window), ctypes.POINTER(ctypes.c_int), ctypes.POINTER(window), ctypes.POINTER(window), ctypes.POINTER(ctypes.POINTER(ctypes.c_ubyte))] + x.XFree.argtypes = [pointer] + x.XCloseDisplay.argtypes = [pointer] + display = x.XOpenDisplay(None) + assert display + pid_atom = x.XInternAtom(display, b'_NET_WM_PID', 0) + matches = [] + def visit(parent, depth=0): + if depth > 4: return + rr, pp, count = window(), window(), ctypes.c_uint() + children = ctypes.POINTER(window)() + x.XQueryTree(display, parent, ctypes.byref(rr), ctypes.byref(pp), ctypes.byref(children), ctypes.byref(count)) + try: + for index in range(count.value): + wid = children[index] + actual, size, remaining, fmt = window(), window(), window(), ctypes.c_int() + data = ctypes.POINTER(ctypes.c_ubyte)() + x.XGetWindowProperty(display, wid, pid_atom, 0, 1, 0, 0, ctypes.byref(actual), ctypes.byref(fmt), ctypes.byref(size), ctypes.byref(remaining), ctypes.byref(data)) + if data: + if size.value and fmt.value == 32 and ctypes.cast(data, ctypes.POINTER(window))[0] == process.pid: + matches.append(wid) + x.XFree(data) + visit(wid, depth + 1) + finally: + if children: x.XFree(children) + try: + visit(x.XDefaultRootWindow(display)) + for index, wid in enumerate(matches): + native = GdkX11.X11Window.foreign_new_for_display(Gdk.Display.get_default(), wid) + width, height = native.get_width(), native.get_height() + if width >= 200 and height >= 100: + pixbuf = Gdk.pixbuf_get_from_window(native, 0, 0, width, height) + if pixbuf: pixbuf.savev(str(root / (label + '-' + str(index) + '.png')), 'png', [], []) + finally: + x.XCloseDisplay(display) + def pump(): + context = GLib.MainContext.default() + while context.pending(): + context.iteration(False) + def nodes(): + pump() + desktop = Atspi.get_desktop(0) + apps = [desktop.get_child_at_index(i) for i in range(desktop.get_child_count())] + candidates = [a for a in apps if a.get_name().lower() in ('gnome-calendar', 'org.gnome.calendar')] + if not candidates: + return [] + result = [] + def visit(item, depth=0): + if item is None or depth > 40 or len(result) >= 2000: + return + try: + item.clear_cache() + if item.get_state_set().contains(Atspi.StateType.SHOWING): + result.append(item) + for n in range(min(item.get_child_count(), 160)): + visit(item.get_child_at_index(n), depth + 1) + except GLib.Error: + pass + visit(candidates[0]) + return result + def snapshot(label): + rows = [{'role': n.get_role_name(), 'name': '[password field]' if 'password' in n.get_role_name() else n.get_name(), + 'states': [s.value_nick for s in n.get_state_set().get_states()], + 'actions': [n.get_action_iface().get_action_name(i) for i in range(n.get_action_iface().get_n_actions())] + if n.get_role_name() == 'button' and n.get_action_iface() else []} + for n in nodes()] + (root / (label + '.json')).write_text(json.dumps(rows, indent=2)) + if label in ('initial', 'discovered', 'connected', 'failed-network-address'): + capture(label) + def wait(condition, label, seconds=35): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + found = condition() + if found: + return found + time.sleep(.2) + snapshot('failed-' + label) + raise RuntimeError('GNOME timed out at ' + label) + def named(name): + return [n for n in nodes() if n.get_name() == name] + def action(item): + current = item + for _ in range(5): + iface = current.get_action_iface() + if iface and iface.get_n_actions(): + names = [iface.get_action_name(i) for i in range(iface.get_n_actions())] + selected = next((i for i, name in enumerate(names) if name in ('click', 'activate', 'widget.activate')), + 0 if current.get_role_name() == 'button' else None) + if selected is not None: + history_path = root / 'actions.json' + history = json.loads(history_path.read_text()) if history_path.exists() else [] + history.append({'role':current.get_role_name(), 'name':current.get_name(), 'actions':names, 'selected':names[selected]}) + history_path.write_text(json.dumps(history, indent=2)) + assert iface.do_action(selected) + return + current = current.get_parent() + if current is None: + break + focused = False + try: + focused = item.get_role_name() == 'button' and item.get_component_iface().grab_focus() + except GLib.Error: + pass + if focused: + def owns_focus(): + item.clear_cache() + return item.get_state_set().contains(Atspi.StateType.FOCUSED) and any( + n.get_role_name() == 'frame' and n.get_state_set().contains(Atspi.StateType.ACTIVE) for n in nodes()) + wait(owns_focus, 'owned-button-focus', 3) + assert Atspi.generate_keyboard_event(Gdk.KEY_Return, None, Atspi.KeySynthType.SYM) + history_path = root / 'actions.json' + history = json.loads(history_path.read_text()) if history_path.exists() else [] + history.append({'role':'button', 'name':item.get_name(), 'selected':'Return with owned button/application focus verified'}) + history_path.write_text(json.dumps(history, indent=2)) + return + if item.get_role_name() == 'button': + rect = item.get_component_iface().get_extents(Atspi.CoordType.SCREEN) + x, y = rect.x + rect.width // 2, rect.y + rect.height // 2 + frames = [n for n in nodes() if n.get_role_name() == 'frame' + and n.get_state_set().contains(Atspi.StateType.ACTIVE)] + bounds = [n.get_component_iface().get_extents(Atspi.CoordType.SCREEN) for n in frames] + assert rect.width > 0 and rect.height > 0 and any(b.x <= x < b.x+b.width and b.y <= y < b.y+b.height for b in bounds) + assert Atspi.generate_mouse_event(x, y, 'b1c') + history_path = root / 'actions.json' + history = json.loads(history_path.read_text()) if history_path.exists() else [] + history.append({'role':'button', 'name':item.get_name(), 'selected':'native click within active owned application bounds'}) + history_path.write_text(json.dumps(history, indent=2)) + return + raise RuntimeError('The owned GNOME control has no accessible activation action') + def click(name): + def buttons(): + return [n for n in named(name) if n.get_role_name() == 'button' + and n.get_state_set().contains(Atspi.StateType.SENSITIVE)] + matches = wait(buttons, 'control-' + name.replace(' ', '-')) + action(matches[0]) + def editable(): + return [n for n in nodes() if n.get_state_set().contains(Atspi.StateType.EDITABLE) + and n.get_editable_text_iface() is not None] + try: + wait(nodes, 'application') + snapshot('initial') + click('Manage Calendars') + click('Add Calendar') + wait(lambda: len(editable()) >= 2, 'network-address') + editable()[-1].get_editable_text_iface().set_text_contents(fixture['address']) + wait(lambda: named('Credentials'), 'credential-dialog') + fields = editable() + password_fields = [n for n in fields if 'password' in n.get_role_name()] + user_fields = [n for n in fields if 'password' not in n.get_role_name()] + assert password_fields and user_fields + user_fields[-1].get_editable_text_iface().set_text_contents(fixture['username']) + password_fields[-1].get_editable_text_iface().set_text_contents(fixture['credential']) + click('Connect') + wait(lambda: named(fixture['name']), 'discovered-collection', 60) + snapshot('discovered') + click('Add Calendar') + wait(lambda: any(fixture['name'] in n.get_name() for n in nodes()), 'saved-source') + # The official source file is durable native-client state, independently of the server. + def saved_sources(): + matched = [] + for path in (root / 'config/evolution/sources').glob('*.source'): + config = configparser.ConfigParser(interpolation=None) + config.read(path) + if config.get('Data Source', 'DisplayName', fallback='') == fixture['name']: + matched.append((path, config)) + return matched + matched = wait(saved_sources, 'saved-source-file') + assert len(matched) == 1, 'Exactly the selected collection must be provisioned' + source, config = matched[0] + assert config.get('Calendar', 'BackendName') == 'caldav' + assert config.get('Security', 'Method') == 'tls' + assert config.get('Authentication', 'User') == fixture['username'] + assert config.get('Authentication', 'Host') == urlsplit(fixture['address']).hostname + assert config.get('WebDAV Backend', 'ResourcePath') == urlsplit(fixture['address']).path + colour = config.get('Calendar', 'Color', fallback='') + report = {'status': 'passed', 'client': 'GNOME Calendar', 'version': fixture['gnomeVersion'], + 'dataServerVersion': fixture['edsVersion'], 'mode': 'real native connection wizard in private home/DBus/X11 namespace', + 'tls': 'normal verification with fixture CA only in private namespace', + 'steps': ['Manage Calendars', 'Add Calendar', 'collection HTTPS URL', 'Credentials User/Password', 'Connect', 'native discovery', 'Add Calendar'], + 'nativeBackend': 'caldav', 'nativeColour': colour} + (root / 'result.json').write_text(json.dumps(report, indent=2) + '\n') + snapshot('connected') + finally: + process.terminate() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--fixture', type=Path) + parser.add_argument('--output', type=Path) + parser.add_argument('--child', type=Path) + args = parser.parse_args() + if args.child: + execute_child(args.child) + return + if not os.environ.get('DISPLAY') or not shutil.which('bwrap'): + raise SystemExit('GNOME qualification requires the existing Linux X11 display, bubblewrap and native GNOME/AT-SPI prerequisites') + assert args.fixture and args.output + fixture = json.loads(args.fixture.read_text()) + versions = {package: subprocess.check_output(['dpkg-query', '-W', '-f=${Version}', package], text=True).strip() + for package in ('gnome-calendar', 'evolution-data-server')} + assert versions == {'gnome-calendar': '50.0-1', 'evolution-data-server': '3.56.2-8'}, 'The installed native qualification versions differ' + fixture.update(gnomeVersion=versions['gnome-calendar'], edsVersion=versions['evolution-data-server']) + with tempfile.TemporaryDirectory(prefix='busystack-portal-gnome-') as directory: + root = Path(directory) + for name in ('home', 'run', 'config', 'data', 'cache', 'state'): + (root / name).mkdir(mode=0o700) + shutil.copyfile(__file__, root / 'gnome.py') + (root / 'client.json').write_text(json.dumps(fixture)) + (root / 'client.json').chmod(0o600) + shutil.copyfile(fixture['ca'], root / 'ca.pem') + (root / 'trust.pem').write_bytes(Path('/etc/ssl/certs/ca-certificates.crt').read_bytes() + (root / 'ca.pem').read_bytes()) + (root / 'bus.conf').write_text('sessionunix:tmpdir=' + str(root / 'run') + '') + # Supported private-bus configuration: read-only /sys cannot service AppArmor policy queries. + accessibility_config = Path('/usr/share/defaults/at-spi2/accessibility.conf') + (root / 'a11y-bus.conf').write_text(accessibility_config.read_text().replace('', '', 1)) + env = os.environ.copy() + for key in ('DBUS_SESSION_BUS_ADDRESS', 'DBUS_STARTER_ADDRESS', 'DBUS_STARTER_BUS_TYPE', 'AT_SPI_BUS_ADDRESS', 'WAYLAND_DISPLAY', 'SSH_AUTH_SOCK'): + env.pop(key, None) + env.update(XDG_RUNTIME_DIR=str(root / 'run'), XDG_CONFIG_HOME=str(root / 'config'), XDG_DATA_HOME=str(root / 'data'), + XDG_CACHE_HOME=str(root / 'cache'), XDG_STATE_HOME=str(root / 'state'), GDK_BACKEND='x11', + GTK_A11Y='atspi', GTK_USE_PORTAL='0', NO_AT_BRIDGE='0', TZ='America/Vancouver', LANG='C.UTF-8', LC_ALL='C.UTF-8', + GNOME_KEYRING_CONTROL=str(root / 'run/keyring')) + if env.get('XAUTHORITY'): + shutil.copyfile(env['XAUTHORITY'], root / 'xauth') + (root / 'xauth').chmod(0o600) + env['XAUTHORITY'] = str(root / 'xauth') + command = ['bwrap', '--ro-bind', '/', '/', '--tmpfs', '/tmp', '--bind', str(root), str(root), + '--ro-bind', '/tmp/.X11-unix', '/tmp/.X11-unix', '--bind', str(root / 'home'), str(Path.home()), + '--chdir', str(root), + '--ro-bind', str(root / 'trust.pem'), '/etc/ssl/certs/ca-certificates.crt', '--proc', '/proc', '--dev', '/dev', + '--ro-bind', str(root / 'a11y-bus.conf'), str(accessibility_config), + '--unshare-pid', '--die-with-parent', 'dbus-run-session', '--config-file', str(root / 'bus.conf'), '--', + '/usr/bin/python3', str(root / 'gnome.py'), '--child', str(root)] + result = subprocess.run(command, env=env, capture_output=True, text=True, timeout=240) + args.output.mkdir(parents=True, exist_ok=True) + # Retain only redacted fixture diagnostics and accessibility names, never credentials/source files/keyrings. + diagnostic = result.stdout + result.stderr + for secret in (fixture['credential'],): + diagnostic = diagnostic.replace(secret, '[redacted]') + (args.output / 'gnome-process.log').write_text(diagnostic) + for path in root.glob('*.json'): + if path.name != 'client.json': + shutil.copyfile(path, args.output / ('gnome-' + path.name)) + for path in root.glob('*.png'): + shutil.copyfile(path, args.output / ('gnome-' + path.name)) + if result.returncode != 0: + raise RuntimeError('Native GNOME connection wizard qualification failed; see redacted fixture diagnostics') + print('GNOME_NATIVE_CONNECTION_WIZARD_PASSED', flush=True) + + +if __name__ == '__main__': + main() diff --git a/qualification/passkeys/groups.mjs b/qualification/passkeys/groups.mjs index dc5bdd5..2f9f0e4 100644 --- a/qualification/passkeys/groups.mjs +++ b/qualification/passkeys/groups.mjs @@ -1,11 +1,20 @@ import assert from 'node:assert/strict'; import {randomBytes} from 'node:crypto'; -import {openCollection,provisionAccount,prefixOf} from './portal-helpers.mjs'; +import {openCollection,provisionAccount,prefixOf,grantDirect,revokeDirect} from './portal-helpers.mjs'; export async function qualifyGroups(page,base,privateValues) { const prefix=prefixOf(base),member='browsergroupmember',password=randomBytes(32).toString('base64url'); privateValues.push(password); const account=await provisionAccount(page,base,member,'Browser Group Member',password); + const display='Group member '; + const profile=page.locator(`form[action="${prefix}/admin/accounts/${account}/edit"]`); + await profile.locator('input[name=displayName]').fill(display); + await Promise.all([page.waitForURL(base+'/admin/accounts/'+account),profile.getByRole('button',{name:'Save display name',exact:true}).click()]); + assert.equal(await page.getByRole('heading',{name:display,exact:true}).count(),1); + assert.equal(await page.locator('img[src=x]').count(),0); + await page.goto(base+'/admin/accounts?q='+encodeURIComponent(member)+'&status=enabled'); + assert.equal(await page.locator('tbody tr').count(),1); + assert.equal(await page.getByRole('link',{name:member,exact:true}).count(),1); await page.goto(base+'/admin/groups'); const create=page.locator(`form[action="${prefix}/admin/groups"]`); await create.locator('input[name=name]').fill('Browser sharing group'); @@ -35,6 +44,13 @@ export async function qualifyGroups(page,base,privateValues) { for(const permission of ['WRITE','REVOKE']) { await grant.locator('select[name=permission]').selectOption(permission); await Promise.all([page.waitForURL(base+'/collections/'+collection+'/sharing'),grant.getByRole('button',{name:'Save group grant',exact:true}).click()]); + if(permission==='WRITE') { + await grantDirect(page,base,collection,member,'READ'); + const effective=page.locator('table').filter({has:page.locator('caption').filter({hasText:'Combined direct and group access'})}).locator('tbody tr').filter({has:page.getByText(member,{exact:true})}); + assert.ok((await effective.innerText()).includes('Read and write')); + await revokeDirect(page,base,collection,member); + assert.ok((await effective.innerText()).includes('Read and write'),'Removing direct access must preserve the effective group write grant'); + } } assert.equal(await grant.count(),0); await page.goto(base+'/admin/groups/'+group); @@ -44,6 +60,22 @@ export async function qualifyGroups(page,base,privateValues) { assert.equal(await page.getByRole('link',{name:'Browser group renamed',exact:true}).count(),0); await page.goto(base+'/collections/'+collection+'/sharing'); assert.equal(await page.locator(`option[value="${group}"]`).count(),0); + await page.goto(base+'/admin/accounts/'+account); + const disable=page.locator(`form[action="${prefix}/admin/accounts/${account}/disable"]`); + await disable.locator('input[name=confirmed]').check(); + await Promise.all([page.waitForURL(base+'/admin/accounts/'+account),disable.getByRole('button',{name:'Disable account',exact:true}).click()]); + assert.equal(await page.getByText('Disabled',{exact:true}).count(),1); + await page.goto(base+'/admin/accounts?q='+encodeURIComponent(member)+'&status=disabled'); + assert.equal(await page.locator('tbody tr').count(),1); + const disabledContext=await page.context().browser().newContext(); + try { + const disabledPage=await disabledContext.newPage(); + await disabledPage.goto(base+'/login'); + await disabledPage.locator('input[name=username]').fill(member); + await disabledPage.locator('input[name=password]').fill(password); + await Promise.all([disabledPage.waitForURL(base+'/login?error'),disabledPage.getByRole('button',{name:'Verify password',exact:true}).click()]); + } finally {await disabledContext.close();} + console.log('BROWSER_ACCOUNT_PROFILE_SEARCH_DISABLE_AND_EFFECTIVE_DIRECT_GROUP_ACCESS_PASSED'); console.log('BROWSER_GROUP_MEMBERSHIP_UPDATE_DELETE_AND_OWNER_GRANTS_PASSED'); } diff --git a/qualification/passkeys/passkeys.mjs b/qualification/passkeys/passkeys.mjs index b7e5c7a..2af0633 100644 --- a/qualification/passkeys/passkeys.mjs +++ b/qualification/passkeys/passkeys.mjs @@ -3,7 +3,7 @@ import {createCollection, openCollection} from './portal-helpers.mjs'; import { chromium } from 'playwright'; import assert from 'node:assert/strict'; import { createInterface } from 'node:readline'; -import { readFileSync } from 'node:fs'; +import { readFileSync, writeFileSync } from 'node:fs'; import { qualifyOAuth } from './oauth.mjs'; import { qualifyDavCredentials } from './dav-credentials.mjs'; import {qualifyAccountRecovery} from './account-recovery.mjs'; @@ -59,6 +59,12 @@ try { console.log('PASSWORD_PLUS_WEBAUTHN_AND_MUTATION_PASSED'); const localPortal=await qualifyPersonalPortal(page,base,privateValues,process.env.BUSYSTACK_BROWSER_USERNAME); await qualifyPortalPresentation(page,base,localPortal,true); + if (process.env.BUSYSTACK_GNOME_EXCHANGE) { + writeFileSync(process.env.BUSYSTACK_GNOME_EXCHANGE, JSON.stringify({address:localPortal.address, + name:localPortal.name, username:process.env.BUSYSTACK_BROWSER_USERNAME, credential:localPortal.device.credential})); + console.log('READY_GNOME'); + await waitFor('GNOME_VERIFIED'); + } if (process.env.BUSYSTACK_BROWSER_GROUPS === 'true') await qualifyGroups(page, base, privateValues); const administratorPage = page; let activeCdp = cdp; diff --git a/qualification/passkeys/portal-helpers.mjs b/qualification/passkeys/portal-helpers.mjs index 3594ec2..a9566f0 100644 --- a/qualification/passkeys/portal-helpers.mjs +++ b/qualification/passkeys/portal-helpers.mjs @@ -25,7 +25,7 @@ export async function provisionAccount(page,base,username,displayName,password) await form.locator('input[name=displayName]').fill(displayName); await form.locator('input[name=password]').fill(password); await Promise.all([page.waitForURL(/\/admin\/accounts\/[a-f0-9-]{36}$/i),form.getByRole('button',{name:'Create account',exact:true}).click()]); - await page.getByText(username,{exact:true}).waitFor(); + await page.getByText(username,{exact:true}).and(page.locator('dd')).waitFor(); return new URL(page.url()).pathname.split('/').at(-1); } export async function grantDirect(page,base,collection,username,permission) { diff --git a/qualification/passkeys/portal.mjs b/qualification/passkeys/portal.mjs index 7786ce3..0eaad1f 100644 --- a/qualification/passkeys/portal.mjs +++ b/qualification/passkeys/portal.mjs @@ -93,7 +93,7 @@ export async function qualifyPortalPresentation(page,base,collection,administrat const observe=request=>{if(!request.url().startsWith(base+'/') && !request.url().startsWith('data:')) unexpected.push(new URL(request.url()).origin);}; page.on('request',observe); try { - for(const viewport of [{width:1280,height:900},{width:390,height:844}]) { + for(const viewport of [{width:1280,height:900},{width:390,height:844},{width:320,height:844}]) { await page.setViewportSize(viewport); for(const path of pages) { const response=await page.goto(base+path);assert.equal(response.status(),200,path); @@ -116,6 +116,8 @@ export async function qualifyPortalPresentation(page,base,collection,administrat await page.goto(base+'/connections'); await page.getByRole('button',{name:'Copy server',exact:true}).focus(); assert.ok(await page.evaluate(()=>getComputedStyle(document.activeElement).outlineStyle!=='none')); + await page.evaluate(()=>document.documentElement.style.fontSize='200%'); + assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1),'Two hundred percent text resizing must reflow'); await page.emulateMedia({colorScheme:'dark',reducedMotion:'reduce'}); await page.goto(base+'/'); if(output) await page.screenshot({path:output+'/'+suffix+'-dark-overview.png',fullPage:true}); diff --git a/qualification/passkeys/run.py b/qualification/passkeys/run.py index 86d486c..f4044b9 100644 --- a/qualification/passkeys/run.py +++ b/qualification/passkeys/run.py @@ -73,6 +73,7 @@ def main(): parser.add_argument("--oidc", action="store_true", help="Also qualify a real Keycloak login across distinct reserved test sites") parser.add_argument("--restore", action="store_true", help="Qualify actual HTTPS authentication, content and sync after restoring an older database") parser.add_argument("--groups", action="store_true", help="Require the V9 group-management and owner-sharing browser workflow") + parser.add_argument("--gnome", action="store_true", help="Also drive the installed GNOME connection wizard in an isolated home/DBus/X11 session") parser.add_argument("--workload", action="store_true", help="Measure the bounded independent-client workload during local HTTPS restoration") parser.add_argument("--clients", action="store_true", help="Run existing Python/native Thunderbird correctness profiles on the packaged server, without performance workload") parser.add_argument("--client-python", default=os.environ.get("BUSYSTACK_CLIENT_PYTHON", str(ROOT / ".client-venv/bin/python"))) @@ -80,6 +81,8 @@ def main(): parser.add_argument("--strict-sync-depth", action="store_true", help="Explicit false override; default qualification leaves the setting absent") parser.add_argument("--thunderbird-binary", default=os.environ.get("BUSYSTACK_THUNDERBIRD_BINARY", str(ROOT / ".client-tools/thunderbird/thunderbird"))) args = parser.parse_args() + if args.gnome and args.oidc: + parser.error("The installed GNOME fixture uses localhost TLS, not the browser container's reserved OIDC hostnames") if args.clients and (not args.restore or args.oidc or args.strict_sync_depth): parser.error("--clients requires local --restore and the default synchronization compatibility profile") if args.clients and (not Path(args.client_python).is_file() or not os.access(args.thunderbird_binary, os.X_OK)): @@ -208,6 +211,11 @@ def main(): browser_command += ["--env", "BUSYSTACK_BROWSER_CAPACITY=true"] if args.groups: browser_command += ["--env", "BUSYSTACK_BROWSER_GROUPS=true"] + if args.gnome: + gnome_exchange = directory / "gnome-client.json" + gnome_exchange.touch(mode=0o600) + browser_command += ["--volume", f"{gnome_exchange}:/fixture/gnome-client.json:rw", + "--env", "BUSYSTACK_GNOME_EXCHANGE=/fixture/gnome-client.json"] if checkpoint is not None: browser_command += ["--env", "BUSYSTACK_BROWSER_RESTORE=true", "--env", "BUSYSTACK_BROWSER_RECOVERY_FILE=/fixture/recovery.json", "--env", "BUSYSTACK_BROWSER_RECOVERY_PASSWORD_FILE=/fixture/restore-password", @@ -229,7 +237,7 @@ def main(): selector.register(browser.stdout, selectors.EVENT_READ) pending = b"" signals = set() - deadline = time.monotonic() + (1200 if args.restore else 600) + deadline = time.monotonic() + (1200 if args.restore else 600) + (240 if args.gnome else 0) password = (directory / "bootstrap-password").read_text().strip() while time.monotonic() < deadline: events = selector.select(timeout=1) @@ -246,7 +254,16 @@ def main(): line = raw.decode(errors="replace") print(line.replace(password, "[redacted]"), flush=True) signals.add(line) - if line == "READY_CAPACITY_SHARING" and checkpoint is not None and args.workload: + if line == "READY_GNOME" and args.gnome: + gnome_fixture = json.loads(gnome_exchange.read_text()) + gnome_fixture["ca"] = str(directory / "ca.pem") + gnome_exchange.write_text(json.dumps(gnome_fixture)) + subprocess.run(["/usr/bin/python3", str(ROOT / "qualification/clients/gnome.py"), + "--fixture", str(gnome_exchange), "--output", str(evidence)], check=True, timeout=250) + gnome_exchange.write_text("{}") + browser.stdin.write(b"GNOME_VERIFIED\n") + browser.stdin.flush() + elif line == "READY_CAPACITY_SHARING" and checkpoint is not None and args.workload: sharing_load = sharing_capacity.SharingCapacity(checkpoint, environment) sharing_load.seed() browser.stdin.write(b"CAPACITY_SHARING_SEEDED\n") diff --git a/src/main/java/org/busystack/caldav/management/PortalPageAdvice.java b/src/main/java/org/busystack/caldav/management/PortalPageAdvice.java index a140e71..5cfde53 100644 --- a/src/main/java/org/busystack/caldav/management/PortalPageAdvice.java +++ b/src/main/java/org/busystack/caldav/management/PortalPageAdvice.java @@ -21,6 +21,7 @@ public PortalPageAdvice(ManagementService management) { @ModelAttribute void layout(Authentication auth, HttpServletRequest request, Model model) { String path = request.getServletPath(); + if (path.equals("/dav") || path.startsWith("/dav/") || path.startsWith("/.well-known/")) return; model.addAttribute("portalPath", path); model.addAttribute("administrationArea", path.startsWith("/admin")); model.addAttribute("viewer", null); @@ -30,8 +31,9 @@ void layout(Authentication auth, HttpServletRequest request, Model model) { try { model.addAttribute("viewer", management.current(auth)); model.addAttribute("externallyManaged", management.externallyManaged(auth)); - } catch (org.springframework.security.access.AccessDeniedException unavailable) { - // Error pages must remain renderable after a disabled or ended session. + } catch (org.springframework.security.access.AccessDeniedException + | org.springframework.dao.DataAccessException unavailable) { + // Safe error layouts remain renderable after account revocation or a database outage. } } } diff --git a/src/main/resources/static/assets/account.css b/src/main/resources/static/assets/account.css index a782966..e060ebd 100644 --- a/src/main/resources/static/assets/account.css +++ b/src/main/resources/static/assets/account.css @@ -1 +1 @@ -:root{color-scheme:light dark;--bg:#f4f6f8;--surface:#fff;--text:#172b38;--muted:#526571;--border:#cbd5dc;--accent:#08645e;--tint:#e5f4f0;--danger:#a42e35;--warning:#fff3d7;--shadow:0 2px 8px #182c3810;font:100%/1.6 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text)}a{color:var(--accent);text-underline-offset:.22em}a:hover{text-decoration-thickness:2px}button,input,select,textarea{font:inherit}button,.button{cursor:pointer;background:var(--accent);color:#fff;border:1px solid transparent;border-radius:.4rem;padding:.6rem 1rem;min-height:44px;font-weight:650;text-decoration:none;display:inline-flex;align-items:center;justify-content:center;gap:.4rem}button:hover,.button:hover{filter:brightness(.92)}button.quiet,.button.secondary{background:var(--surface);color:var(--accent);border-color:var(--border)}button.danger,.button.danger{background:var(--danger)}button:disabled{cursor:wait;opacity:.65}a,button,input,select,textarea,summary{scroll-margin-top:1rem}:focus-visible{outline:3px solid #bd6c00;outline-offset:3px}input:not([type=checkbox]):not([type=radio]),select,textarea{display:block;width:100%;max-width:40rem;background:var(--surface);color:var(--text);border:1px solid var(--border);border-radius:.35rem;min-height:44px;padding:.6rem .7rem}input[type=checkbox]{width:1.15rem;height:1.15rem;vertical-align:middle;margin-right:.6rem}input[readonly]{background:var(--bg)}textarea{resize:vertical;min-height:7rem}label{display:block;font-weight:600;margin:1rem 0 .4rem}label small{display:block;font-weight:400}form{margin:0}form>button{margin-top:1rem}h1,h2,h3{line-height:1.25;letter-spacing:-.025em}h1{font-size:clamp(1.8rem,4vw,2.5rem);margin:.3rem 0 1rem}h2{font-size:1.35rem;margin:0 0 1rem}h3{font-size:1.1rem}p{max-width:78ch}small,.muted,.eyebrow{color:var(--muted)}.eyebrow{text-transform:uppercase;letter-spacing:.1em;font-size:.75rem;font-weight:750}.app-header{background:var(--surface);border-bottom:1px solid var(--border)}.brand-row,.portal-switch,.section-nav{max-width:1200px;margin:auto;padding:.75rem 2rem;display:flex;gap:1.5rem;align-items:center;flex-wrap:wrap}.brand-row{justify-content:space-between}.brand{color:var(--text);font-size:1.2rem;font-weight:750;text-decoration:none;display:flex;gap:.65rem;align-items:center}.brand-mark{display:grid;place-items:center;background:var(--accent);color:#fff;width:2.1rem;height:2.1rem;border-radius:.5rem}.brand-caption{font-weight:400;color:var(--muted);font-size:.8rem;border-left:1px solid var(--border);padding-left:.8rem}.identity{display:flex;gap:1rem;align-items:center;font-size:.9rem}.portal-switch{padding-top:0;padding-bottom:0;gap:1.25rem}.portal-switch a{font-size:.85rem;font-weight:600;text-decoration:none;padding:.35rem 0}.portal-switch [aria-current=true]{border-bottom:2px solid var(--accent)}.section-nav{gap:.25rem;padding-top:.5rem;padding-bottom:.7rem}.section-nav a{padding:.5rem .8rem;text-decoration:none;color:var(--muted);font-size:.9rem;font-weight:650;border-radius:.35rem}.section-nav [aria-current=page]{background:var(--tint);color:var(--accent)}main{max-width:1200px;margin:auto;padding:2rem;min-height:65vh}main>nav:not(.pagination){display:flex;gap:1rem;flex-wrap:wrap;margin-bottom:1.5rem}section,article,.card{background:var(--surface);border:1px solid var(--border);border-radius:.65rem;padding:1.5rem;margin:1.25rem 0;box-shadow:var(--shadow)}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,280px),1fr));gap:1.25rem}.grid>section,.grid>.card{margin:0}.page-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:1rem;flex-wrap:wrap;margin-bottom:1.5rem}.actions{display:flex;align-items:center;gap:.75rem;flex-wrap:wrap}.actions a:not(.button){font-weight:600}.notice{border:1px solid var(--border);border-left:4px solid #bd6c00;background:var(--warning);padding:1rem 1.2rem;border-radius:.35rem;margin:1rem 0}.notice.success{border-left-color:var(--accent);background:var(--tint)}.notice.error{border-left-color:var(--danger)}.badge{font-size:.8rem;font-weight:650;padding:.2rem .65rem;border-radius:2rem;background:var(--bg);border:1px solid var(--border);display:inline-block}.danger-zone{border-color:var(--danger)}.empty{padding:2rem;text-align:center;border:1px dashed var(--border);border-radius:.5rem}.metric{font-size:2rem;font-weight:750;margin:0}.table-scroll{max-width:100%;overflow-x:auto}table{width:100%;border-collapse:collapse;font-size:.9rem}caption{text-align:left;font-weight:650;margin-bottom:.75rem}th{text-align:left;color:var(--muted);font-size:.8rem}td,th{padding:.85rem .65rem;border-bottom:1px solid var(--border);vertical-align:top}td:first-child,th:first-child{padding-left:0}td form{margin:0}td button{margin:0}table a{font-weight:650}dl{display:grid;grid-template-columns:minmax(8rem,1fr) 3fr;gap:.75rem 1.5rem}dt{color:var(--muted)}dd{margin:0;overflow-wrap:anywhere}code{font-size:.9em;overflow-wrap:anywhere}time{font-variant-numeric:tabular-nums}.copy-field{display:flex;gap:.5rem;align-items:center}.copy-field input{min-width:0;max-width:none}.pagination{display:flex;justify-content:center;gap:1.5rem;margin-top:1.5rem}.filters{display:flex;gap:1rem;align-items:flex-end;flex-wrap:wrap}.filters label{margin:0}.filters button{margin:0}.filters input{min-width:16rem}details{margin:1rem 0}summary{cursor:pointer;font-weight:650;min-height:44px;padding:.5rem 0}footer{max-width:1200px;margin:auto;padding:2rem;color:var(--muted);font-size:.85rem;display:flex;gap:1rem;flex-wrap:wrap;justify-content:space-between}footer p{width:100%;margin:0}.skip-link{position:absolute;top:-100px;left:1rem;background:var(--surface);padding:1rem;z-index:5}.skip-link:focus{top:0}.security-nav{display:flex;gap:1rem;flex-wrap:wrap;margin-bottom:1.5rem}.steps{padding-left:1.5rem}.steps li{padding:.5rem 0}.auth-page{max-width:620px}.auth-page>form{background:var(--surface);padding:1.5rem;border:1px solid var(--border);border-radius:.65rem}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}@media(max-width:650px){main{padding:1.25rem}.brand-row,.portal-switch,.section-nav{padding-left:1.25rem;padding-right:1.25rem;gap:.5rem}.brand-caption{display:none}.identity>span{max-width:9rem;overflow-wrap:anywhere}.section-nav a{padding:.5rem;font-size:.82rem}section,article,.card{padding:1.1rem}dl{grid-template-columns:1fr;gap:.25rem}dd{margin-bottom:.7rem}.copy-field{align-items:stretch}.filters{display:block}.filters>*{margin:.75rem 0}.filters input{min-width:0}footer{padding:1.25rem}.page-heading .button{width:100%}}@media(prefers-color-scheme:dark){:root{--bg:#101b22;--surface:#192831;--text:#e3edf2;--muted:#abbcc7;--border:#41545f;--accent:#71d9c0;--tint:#1d3b36;--warning:#3c321d;--danger:#e45f6b;--shadow:none}button,.button,.brand-mark{color:#102b26}button.danger,.button.danger{color:#1c0809}:focus-visible{outline-color:#f1b761}}@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;animation:none!important;transition:none!important}} +:root{color-scheme:light dark;--bg:#f4f6f8;--surface:#fff;--text:#172b38;--muted:#526571;--border:#cbd5dc;--input-border:#74838b;--accent:#08645e;--tint:#e5f4f0;--danger:#a42e35;--warning:#fff3d7;--shadow:0 2px 8px #182c3810;font:100%/1.6 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text)}a{color:var(--accent);text-underline-offset:.22em}a:hover{text-decoration-thickness:2px}button,input,select,textarea{font:inherit}button,.button{cursor:pointer;background:var(--accent);color:#fff;border:1px solid transparent;border-radius:.4rem;padding:.6rem 1rem;min-height:44px;font-weight:650;text-decoration:none;display:inline-flex;align-items:center;justify-content:center;gap:.4rem}button:hover,.button:hover{filter:brightness(.92)}button.quiet,.button.secondary{background:var(--surface);color:var(--accent);border-color:var(--border)}button.danger,.button.danger{background:var(--danger)}button:disabled{cursor:wait;opacity:.65}a,button,input,select,textarea,summary{scroll-margin-top:1rem}:focus-visible{outline:3px solid #bd6c00;outline-offset:3px}input:not([type=checkbox]):not([type=radio]),select,textarea{display:block;width:100%;max-width:40rem;background:var(--surface);color:var(--text);border:1px solid var(--input-border);border-radius:.35rem;min-height:44px;padding:.6rem .7rem}input[type=checkbox]{width:1.15rem;height:1.15rem;vertical-align:middle;margin-right:.6rem}input[readonly]{background:var(--bg)}textarea{resize:vertical;min-height:7rem}label{display:block;font-weight:600;margin:1rem 0 .4rem}label small{display:block;font-weight:400}form{margin:0}form>button{margin-top:1rem}h1,h2,h3{line-height:1.25;letter-spacing:-.025em}h1{font-size:clamp(1.8rem,4vw,2.5rem);margin:.3rem 0 1rem}h2{font-size:1.35rem;margin:0 0 1rem}h3{font-size:1.1rem}p{max-width:78ch}small,.muted,.eyebrow{color:var(--muted)}.eyebrow{text-transform:uppercase;letter-spacing:.1em;font-size:.75rem;font-weight:750}.app-header{background:var(--surface);border-bottom:1px solid var(--border)}.brand-row,.portal-switch,.section-nav{max-width:1200px;margin:auto;padding:.75rem 2rem;display:flex;gap:1.5rem;align-items:center;flex-wrap:wrap}.brand-row{justify-content:space-between}.brand{color:var(--text);font-size:1.2rem;font-weight:750;text-decoration:none;display:flex;gap:.65rem;align-items:center}.brand-mark{display:grid;place-items:center;background:var(--accent);color:#fff;width:2.1rem;height:2.1rem;border-radius:.5rem}.brand-caption{font-weight:400;color:var(--muted);font-size:.8rem;border-left:1px solid var(--border);padding-left:.8rem}.identity{display:flex;gap:1rem;align-items:center;font-size:.9rem}.portal-switch{padding-top:0;padding-bottom:0;gap:1.25rem}.portal-switch a{font-size:.85rem;font-weight:600;text-decoration:none;padding:.35rem 0}.portal-switch [aria-current=true]{border-bottom:2px solid var(--accent)}.section-nav{gap:.25rem;padding-top:.5rem;padding-bottom:.7rem}.section-nav a{padding:.5rem .8rem;text-decoration:none;color:var(--muted);font-size:.9rem;font-weight:650;border-radius:.35rem}.section-nav [aria-current=page]{background:var(--tint);color:var(--accent)}main{max-width:1200px;margin:auto;padding:2rem;min-height:65vh}main>nav:not(.pagination){display:flex;gap:1rem;flex-wrap:wrap;margin-bottom:1.5rem}section,article,.card{background:var(--surface);border:1px solid var(--border);border-radius:.65rem;padding:1.5rem;margin:1.25rem 0;box-shadow:var(--shadow)}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,280px),1fr));gap:1.25rem}.grid>section,.grid>.card{margin:0}.page-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:1rem;flex-wrap:wrap;margin-bottom:1.5rem}.actions{display:flex;align-items:center;gap:.75rem;flex-wrap:wrap}.actions a:not(.button){font-weight:600}.notice{border:1px solid var(--border);border-left:4px solid #bd6c00;background:var(--warning);padding:1rem 1.2rem;border-radius:.35rem;margin:1rem 0}.notice.success{border-left-color:var(--accent);background:var(--tint)}.notice.error{border-left-color:var(--danger)}.badge{font-size:.8rem;font-weight:650;padding:.2rem .65rem;border-radius:2rem;background:var(--bg);border:1px solid var(--border);display:inline-block}.danger-zone{border-color:var(--danger)}.empty{padding:2rem;text-align:center;border:1px dashed var(--border);border-radius:.5rem}.metric{font-size:2rem;font-weight:750;margin:0}.table-scroll{max-width:100%;overflow-x:auto}table{width:100%;border-collapse:collapse;font-size:.9rem}caption{text-align:left;font-weight:650;margin-bottom:.75rem}th{text-align:left;color:var(--muted);font-size:.8rem}td,th{padding:.85rem .65rem;border-bottom:1px solid var(--border);vertical-align:top}td:first-child,th:first-child{padding-left:0}td form{margin:0}td button{margin:0}table a{font-weight:650}dl{display:grid;grid-template-columns:minmax(8rem,1fr) 3fr;gap:.75rem 1.5rem}dt{color:var(--muted)}dd{margin:0;overflow-wrap:anywhere}code{font-size:.9em;overflow-wrap:anywhere}time{font-variant-numeric:tabular-nums}.timestamp{white-space:nowrap}.separate-form,form+h2{margin-top:2rem}.copy-field{display:flex;gap:.5rem;align-items:center}.copy-field input{min-width:0;max-width:none}.pagination{display:flex;justify-content:center;gap:1.5rem;margin-top:1.5rem}.filters{display:flex;gap:1rem;align-items:flex-end;flex-wrap:wrap}.filters label{margin:0}.filters button{margin:0}.filters input{min-width:16rem}details{margin:1rem 0}summary{cursor:pointer;font-weight:650;min-height:44px;padding:.5rem 0}footer{max-width:1200px;margin:auto;padding:2rem;color:var(--muted);font-size:.85rem;display:flex;gap:1rem;flex-wrap:wrap;justify-content:space-between}footer p{width:100%;margin:0}.skip-link{position:absolute;top:-100px;left:1rem;background:var(--surface);padding:1rem;z-index:5}.skip-link:focus{top:0}.security-nav{display:flex;gap:1rem;flex-wrap:wrap;margin-bottom:1.5rem}.steps{padding-left:1.5rem}.steps li{padding:.5rem 0}.auth-page{max-width:620px}.auth-page>form{background:var(--surface);padding:1.5rem;border:1px solid var(--border);border-radius:.65rem}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}@media(max-width:650px){main{padding:1.25rem}.brand-row,.portal-switch,.section-nav{padding-left:1.25rem;padding-right:1.25rem;gap:.5rem}.brand-caption{display:none}.identity>span{max-width:9rem;overflow-wrap:anywhere}.section-nav a{padding:.5rem;font-size:.82rem}section,article,.card{padding:1.1rem}dl{grid-template-columns:1fr;gap:.25rem}dd{margin-bottom:.7rem}.copy-field{align-items:stretch}.filters{display:block}.filters>*{margin:.75rem 0}.filters input{min-width:0}footer{padding:1.25rem}.page-heading .button{width:100%}}@media(prefers-color-scheme:dark){:root{--bg:#101b22;--surface:#192831;--text:#e3edf2;--muted:#abbcc7;--border:#41545f;--input-border:#6f8795;--accent:#71d9c0;--tint:#1d3b36;--warning:#3c321d;--danger:#e45f6b;--shadow:none}button,.button,.brand-mark{color:#102b26}button.danger,.button.danger{color:#1c0809}:focus-visible{outline-color:#f1b761}}@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;animation:none!important;transition:none!important}} diff --git a/src/main/resources/templates/audit.html b/src/main/resources/templates/audit.html index 06ca333..a056906 100644 --- a/src/main/resources/templates/audit.html +++ b/src/main/resources/templates/audit.html @@ -4,6 +4,6 @@ Server administration

Security & Audit

Recorded security metadata is retained for up to thirty days and approximately ten thousand rows. This is a bounded security record, not a calendar-activity history.

Manage OAuth application registrations

-

No retained events match these filters.

Recorded security events
Time (UTC)EventOutcomeAssociated account
+

No retained events match these filters.

Recorded security events
Time (UTC)EventOutcomeAssociated account
diff --git a/src/main/resources/templates/connections.html b/src/main/resources/templates/connections.html index 518846e..81caf59 100644 --- a/src/main/resources/templates/connections.html +++ b/src/main/resources/templates/connections.html @@ -5,7 +5,7 @@
My account

Connect your applications

Use a dedicated DAV credential as the application password. Your browser sign-in password does not authenticate CalDAV.

Issue an application credential

Your connection settings

Authentication: named DAV credential using Basic over HTTPS. A registered application that supports BusyStack OAuth may use browser authorization instead.

Thunderbird

Previously verified: 159.0 Native calendar and task workflows were qualified on the 0.1.0 executable in Vancouver and Berlin. Verification of a later executable is recorded separately.

  1. Open the Calendar tab, choose New Calendar → On the Network.
  2. Enter the username above and the server address as Location. Leave This location doesn't require credentials unchecked, then choose Find Calendars.
  3. Enter your dedicated DAV credential in the password prompt. Use Password Manager if you want Thunderbird to retain it.
  4. Choose CalDAV, select discovered calendars and task lists, then choose Subscribe. Use Thunderbird's task view for tasks.
-

GNOME Calendar / Evolution Data Server

Previously verified: Calendar 50.0 / EDS 3.56.2 Event editing and synchronization were qualified on 0.1.0 in Vancouver. GNOME Calendar does not provide a task editor.

The qualified profile provisions the remote CalDAV source through Evolution Data Server. Graphical account-creation instructions have not been qualified; do not assume Thunderbird's discovery steps apply. Ask your operator to use the documented EDS source setup in the project's client qualification record. The collection-specific URL below is the CalDAV endpoint for that source.

+

GNOME Calendar / Evolution Data Server

Previously verified: Calendar 50.0 / EDS 3.56.2 Event editing and synchronization were qualified on 0.1.0 in Vancouver. GNOME Calendar does not provide a task editor.

Graphical setup: documented, awaiting qualification These steps follow GNOME Calendar 50.0's connection wizard. Use the specific calendar address below; task lists belong in a VTODO-capable application.

  1. Open Manage Calendars → Add Calendar.
  2. Under Connect to an Online Calendar, enter the collection's HTTPS address.
  3. When Credentials opens, enter your BusyStack username in User and a dedicated DAV credential in Password, then choose Connect.
  4. Select the discovered calendar, then choose Add Calendar. Refresh and verify the calendar in the application.

Collection addresses

Create a collection or ask an owner to share one before connecting.

Connection troubleshooting

Authentication fails

Check the username and dedicated credential. Issue a replacement if it expired or was lost. Revocation and account disabling deny future authentication. Organization-managed accounts also need periodic provider sign-in within the operator's configured freshness limit; provider disabling does not immediately revoke every BusyStack credential.

Collections are missing or access changed

Check Calendars & Tasks. A collection owner must grant access directly or through a group. Refresh discovery after a change. If a synchronization token becomes invalid after sharing changes, let the client perform a fresh initial synchronization.

TLS, address or synchronization problems

Use exactly the configured HTTPS address, including any application prefix. Do not disable certificate validation. Ask the operator to check certificates and proxy configuration.

Strict synchronization-depth mode is enabled. The project's tested Thunderbird and python-caldav versions use Depth: 1 and need the documented default accommodation; ask the operator to review this deployment choice.

BusyMax has not been qualified against this implementation. No connection or OAuth compatibility claim is made.

diff --git a/src/main/resources/templates/credentials.html b/src/main/resources/templates/credentials.html index 260978b..dc1ce3f 100644 --- a/src/main/resources/templates/credentials.html +++ b/src/main/resources/templates/credentials.html @@ -4,6 +4,6 @@ Back to security

DAV credentials

Issue a separate credential for each application or device. These are credentials, not a list of verified device connections. Secrets appear once and cannot be retrieved later.

Issue a credential

Choose 1–365 days. Expiration stops future authentication. For replacement, issue a new credential, configure the application, then revoke the old one.

-

Issued credentials

No DAV credentials have been issued. Create one above, then follow Connections.

Credential metadata
LabelCreatedExpiresStatusAction
+

Issued credentials

No DAV credentials have been issued. Create one above, then follow Connections.

Credential metadata
LabelCreatedExpiresStatusAction
diff --git a/src/main/resources/templates/diagnostics.html b/src/main/resources/templates/diagnostics.html index f461fd1..df12512 100644 --- a/src/main/resources/templates/diagnostics.html +++ b/src/main/resources/templates/diagnostics.html @@ -4,7 +4,7 @@ Server administration

System & Diagnostics

Deployment

Application
Public base URL
OAuth issuer
Java runtime
Database
PostgreSQL
Applied migration

HTTP observations since startup

Completed requests
Server errors
Mean duration (ms)
Recent maximum (ms)

Metrics reset on restart. The recent maximum follows the metrics registry's observation window.

-

Recent operational problems

No server failures have been recorded in this process's bounded recent-problem buffer. This does not establish the absence of older or external failures.

Up to 50 observed server failures since startup
Time (UTC)SurfaceMethodStatusRequest identifier
+

Recent operational problems

No server failures have been recorded in this process's bounded recent-problem buffer. This does not establish the absence of older or external failures.

Up to 50 observed server failures since startup
Time (UTC)SurfaceMethodStatusRequest identifier

Troubleshooting

Database or startup failure

Check local readiness probes, database availability, configured credentials and migration validation in operator logs. A database outage can prevent authenticated administration itself; use deployment monitoring. Configuration is validated at startup. Keep database access private and use the documented backup and recovery procedure.

Organization identity provider unavailable

Check the explicitly configured issuer, provider availability, trusted TLS certificate and redirect URI. Discovery is deferred to organization sign-in. Local accounts work independently. Externally managed accounts fail closed when provider authentication is required, without a password fallback. Previously issued client access keeps only its existing freshness bound.

Authentication or permission failure

Ask the user to check credential expiration, revocation and recent primary/passkey verification. Review recorded security outcomes in the audit viewer. Local disabling denies access even if group memberships remain. Administration does not bypass collection ownership.

CalDAV compatibility and synchronization

Use the project's qualified client/version profile. The documented default supports narrowly bounded sync Depth: 1 and local timezone-observance UNTIL repair. Strict-mode settings are controlled by the operator. Permission or group changes can invalidate synchronization tokens; a client must start fresh synchronization.

Use the response's X-Request-ID to correlate safe request metadata with operator logs. Request contents and credentials must not be collected for troubleshooting. Backups and public TLS renewal are external operator responsibilities; their status is unknown here.

diff --git a/src/main/resources/templates/error.html b/src/main/resources/templates/error.html new file mode 100644 index 0000000..b1cdabe --- /dev/null +++ b/src/main/resources/templates/error.html @@ -0,0 +1 @@ +

Request could not complete

Check the address and form details, then return to the workflow. If the problem continues, ask the operator to check service availability and recorded diagnostics.

diff --git a/src/main/resources/templates/error/413.html b/src/main/resources/templates/error/413.html new file mode 100644 index 0000000..d0cc9e8 --- /dev/null +++ b/src/main/resources/templates/error/413.html @@ -0,0 +1 @@ +

Upload too large

Import files are limited to 8 MiB. Each UID series must fit within the existing 1 MiB resource limit. Split a larger file before trying again.

diff --git a/src/main/resources/templates/fragments/layout.html b/src/main/resources/templates/fragments/layout.html index a2734f4..3917c99 100644 --- a/src/main/resources/templates/fragments/layout.html +++ b/src/main/resources/templates/fragments/layout.html @@ -35,6 +35,7 @@
Security verification needed. Sensitive changes require primary sign-in and a passkey verified within ten minutes. Verify sign-in or set up a passkey.
+
BusyStack · Your server. Your data.Calendar and task contents are managed in your CalDAV applications.

+

Security verification needed. Portal downloads and sensitive changes require primary sign-in and a passkey verified within ten minutes. Verify sign-in or set up a passkey.
diff --git a/src/main/resources/templates/group-detail.html b/src/main/resources/templates/group-detail.html index e02a21a..0ab04f9 100644 --- a/src/main/resources/templates/group-detail.html +++ b/src/main/resources/templates/group-detail.html @@ -3,9 +3,9 @@
Back to groups

members · collection grants. Collection names and contents remain private unless independently shared with you.

-

Rename group

-

Add one member

Adding an account gives it access to all collections already shared with this group, according to each owner's grant. Future grants also apply.

-

Current members

Removing a membership may remove calendar access. Any other direct or group grant continues to apply.

No members match this view.

Group members — 50 per page
AccountDisplay nameStatusMembership
+

Rename group

+

Add one member

Adding an account gives it access to all collections already shared with this group, according to each owner's grant. Future grants also apply.

+

Current members

Removing a membership may remove calendar access. Any other direct or group grant continues to apply.

No members match this view.

Group members — 50 per page
AccountDisplay nameStatusMembership

Delete group

All recorded memberships and collection grants for this group will be removed. Access through other grants remains effective.

diff --git a/src/main/resources/templates/groups.html b/src/main/resources/templates/groups.html index 6d69a58..c114b6f 100644 --- a/src/main/resources/templates/groups.html +++ b/src/main/resources/templates/groups.html @@ -3,7 +3,7 @@
Server administration

Sharing groups

Manage local group membership. Owners choose which collections to share with each group. Membership administration does not bypass private collection permissions.

-

Create a group

+

Create a group

No groups match this search. Create a group above to manage shared access.

Groups — 50 per page
GroupMembersCollection grants
diff --git a/src/main/resources/templates/import-report.html b/src/main/resources/templates/import-report.html index 4b29473..721a5f8 100644 --- a/src/main/resources/templates/import-report.html +++ b/src/main/resources/templates/import-report.html @@ -3,7 +3,7 @@
Back to Import & Export

Destination: .

Summary

Imported
Ready to import
Skipped (identical)
Conflicting
Rejected

Nothing has been imported yet. Confirmation imports only valid new items, preserving existing data. Authorization and conflicts are checked again at confirmation. Expires .

All reported new items were committed together. Existing resources were preserved. No rejected or conflicting item was written.

-

Item validation

On smaller screens, scroll the table sideways to see all columns. Keyboard: focus the table, then use the arrow keys.

Each UID series is one item, including its recurrence exceptions
ItemUIDResultDetails
.
-

Confirm or discard

+

Item validation

On smaller screens, scroll the table sideways to see all columns. Keyboard: focus the table, then use the arrow keys.

Each UID series is one item, including its recurrence exceptions
ItemUIDResultDetails
.
+

Confirm or discard

diff --git a/src/main/resources/templates/portability.html b/src/main/resources/templates/portability.html index c45f956..e143364 100644 --- a/src/main/resources/templates/portability.html +++ b/src/main/resources/templates/portability.html @@ -2,6 +2,6 @@
-My account

Import & Export

Move your calendar and task data using iCalendar files. No invitations, alarms or outbound messages are executed by import.

Choose a collection

Readable collections can be exported. Owners and read/write recipients can import into a collection of the matching type.

No collections are available. Create a destination collection first.

Export this collection

Up to 8 MiB per file and 1 MiB per UID series, with at most 1,000 imported items. The actual content is validated. Select a file to review conflicts before confirming.

Data preservation and limits

Exports combine resources into one VCALENDAR when their calendar headers and timezone definitions are identical, preserving component bytes. Otherwise, a lossless RFC 5545 stream keeps distinct calendar contexts intact and uses a -stream.ics filename. BusyStack imports both formats. Thunderbird 159.0 requires a single VCALENDAR for file import; verify other applications before migration. Recurrence exceptions stay with their UID series.

Exports are bounded to 10,000 resources and 64 MiB. Larger exports fail before a download starts. Imports preserve existing resources: identical resources are skipped and different resources with an existing UID are reported as conflicts. Valid new series are committed together; rejected, conflicting and skipped items are explicitly listed. A failure while writing rolls back every new resource.

Import previews expire after ten minutes and are replaced by your next preview. Restarting this instance invalidates pending previews. Files are stored temporarily on this server, not in browser storage.

+My account

Import & Export

Review your latest import preview or results

Move your calendar and task data using iCalendar files. No invitations, alarms or outbound messages are executed by import.

Choose a collection

Readable collections can be exported. Owners and read/write recipients can import into a collection of the matching type.

No collections are available. Create a destination collection first.

Export this collection

Up to 64 MiB per file and 1 MiB per UID series, with at most 10,000 imported items. The actual content is validated. Select a file to review conflicts before confirming.

Data preservation and limits

Exports combine resources into one VCALENDAR when their calendar headers and timezone definitions are identical, preserving component bytes. Otherwise, a lossless RFC 5545 stream keeps distinct calendar contexts intact and uses a -stream.ics filename. BusyStack imports both formats. Thunderbird 159.0 requires a single VCALENDAR for file import; verify other applications before migration. Recurrence exceptions stay with their UID series.

Exports are bounded to 10,000 resources and 64 MiB. Larger exports fail before a download starts. Imports preserve existing resources: identical resources are skipped and different resources with an existing UID are reported as conflicts. Valid new series are committed together; rejected, conflicting and skipped items are explicitly listed. A failure while writing rolls back every new resource.

Import previews expire after ten minutes and are replaced after your next upload validates successfully. Restarting this instance invalidates pending previews. Files are stored temporarily on this server, not in browser storage.

diff --git a/src/test/java/org/busystack/caldav/calendar/CalendarInterchangeTest.java b/src/test/java/org/busystack/caldav/calendar/CalendarInterchangeTest.java index 7d21c9b..0ae3fd0 100644 --- a/src/test/java/org/busystack/caldav/calendar/CalendarInterchangeTest.java +++ b/src/test/java/org/busystack/caldav/calendar/CalendarInterchangeTest.java @@ -26,6 +26,141 @@ private static String event(String uid) { + "\nDTSTAMP:20261101T000000Z\nDTSTART:20261102T090000Z\nSUMMARY:Résumé\\, family\nX-DATA:preserve\nEND:VEVENT\n"; } + @org.junit.jupiter.api.io.TempDir java.nio.file.Path temporary; + + private java.util.List read(byte[] bytes, String component) { + var source = temporary.resolve(java.util.UUID.randomUUID() + ".ics"); + var index = temporary.resolve(java.util.UUID.randomUUID() + ".index"); + try { + java.nio.file.Files.write(source, bytes); + try (var file = interchange.open(source, index)) { + var items = new java.util.ArrayList(); + for (int n = 0; n < file.size(); n++) items.add(interchange.item(file, n, component)); + return items; + } + } catch (java.io.IOException failure) { + throw new java.io.UncheckedIOException(failure); + } + } + + @Test + void invalidDuplicateNeighborsDoNotRejectValidSeriesAndEscapedUidsKeepTheirIdentity() { + var items = + read( + bytes( + object(event("same")) + + object(event("same").replace("DTSTART:20261102T090000Z", "DTSTART:invalid"))), + "VEVENT"); + assertThat(items).hasSize(2); + assertThat(items.getFirst().rejection()).isEmpty(); + assertThat(items.getLast().rejection()).isNotEmpty(); + for (String uid : + java.util.List.of("escaped\\,uid", "escaped\\;uid", "escaped\\\\uid", "MixedCaseUID")) { + byte[] body = bytes(object(event(uid))); + var item = read(body, "VEVENT").getFirst(); + assertThat(item.rejection()).isEmpty(); + assertThat(item.uid()).isEqualTo(CalendarContent.parse(body, "VEVENT").uid()); + assertThat(item.content()).isEqualTo(body); + } + } + + @Test + void indexedSingleAndStreamInputsExceedOldByteAndItemLimitsWithoutRetainingBodies() + throws Exception { + for (boolean stream : new boolean[] {false, true}) { + var input = temporary.resolve("large-" + stream + ".ics"); + var index = temporary.resolve("index-" + stream); + String padding = "x".repeat(8500); + try (var out = java.nio.file.Files.newOutputStream(input)) { + if (!stream) out.write(bytes("BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//Interchange//EN\n")); + for (int n = 0; n < 1100; n++) { + String value = event("large-" + n).replace("X-DATA:preserve", "X-DATA:" + padding); + if (stream) { + String zone = + "BEGIN:VTIMEZONE\nTZID:SameLocalName\nBEGIN:STANDARD\nDTSTART:19700101T000000\nTZOFFSETFROM:" + + (n % 2 == 0 ? "+0200" : "-0300") + + "\nTZOFFSETTO:" + + (n % 2 == 0 ? "+0200" : "-0300") + + "\nEND:STANDARD\nEND:VTIMEZONE\n"; + value = + value.replace( + "DTSTART:20261102T090000Z", "DTSTART;TZID=SameLocalName:20261102T090000"); + if (n % 100 == 0) { + value = + value.replace("X-DATA:", "RRULE:FREQ=DAILY;COUNT=2\nX-DATA:") + + event("large-" + n) + .replace( + "DTSTART:20261102T090000Z", + "RECURRENCE-ID;TZID=SameLocalName:20261103T090000\nDTSTART;TZID=SameLocalName:20261103T110000"); + } + out.write( + bytes( + object(zone + value) + .replace( + "PRODID:-//Interchange//EN", + "PRODID:-//Interchange//EN\nX-CALENDAR-CONTEXT:" + n))); + } else out.write(bytes(value)); + } + if (!stream) out.write(bytes("END:VCALENDAR\n")); + } + assertThat(java.nio.file.Files.size(input)).isGreaterThan(8L * 1024 * 1024); + try (var file = interchange.open(input, index)) { + assertThat(file.size()).isEqualTo(1100); + for (int n = 0; n < file.size(); n++) { + var item = interchange.item(file, n, "VEVENT"); + assertThat(item.uid()).isEqualTo("large-" + n); + assertThat(item.rejection()).isEmpty(); + assertThat(new String(item.content(), StandardCharsets.UTF_8)) + .contains("X-DATA:" + padding); + if (stream) { + String text = new String(item.content(), StandardCharsets.UTF_8); + assertThat(text) + .contains( + "X-CALENDAR-CONTEXT:" + n + "\r\n", + "TZOFFSETTO:" + (n % 2 == 0 ? "+0200" : "-0300")); + assertThat( + CalendarContent.parse(item.content(), "VEVENT") + .calendar() + .getComponents("VEVENT")) + .hasSize(n % 100 == 0 ? 2 : 1); + } + } + } + } + } + + @Test + void indexedFramingPreservesContextsExceptionsAndInvalidNeighbors() throws Exception { + String master = event("series").replace("X-DATA:", "RRULE:FREQ=DAILY;COUNT=3\nX-DATA:"); + String exception = + event("series") + .replace( + "DTSTART:20261102T090000Z", + "RECURRENCE-ID:20261103T090000Z\nDTSTART:20261103T110000Z"); + var input = temporary.resolve("mixed.ics"); + var index = temporary.resolve("index"); + java.nio.file.Files.write( + input, + bytes( + object(master + event("other") + exception) + + object(event("duplicate")) + + object(event("duplicate")))); + try (var file = interchange.open(input, index)) { + assertThat(file.size()).isEqualTo(4); + var series = interchange.item(file, 0, "VEVENT"); + assertThat(series.rejection()).isEmpty(); + assertThat( + CalendarContent.parse(series.content(), "VEVENT").calendar().getComponents("VEVENT")) + .hasSize(2); + assertThat(interchange.item(file, 1, "VEVENT").uid()).isEqualTo("other"); + assertThat(interchange.item(file, 2, "VEVENT").rejection()).contains("multiple"); + assertThat(interchange.item(file, 3, "VEVENT").rejection()).contains("multiple"); + } + java.nio.file.Files.write(input, bytes(object("BEGIN:VEVENT\nEND:VTODO\n"))); + assertThatThrownBy(() -> interchange.open(input, index)) + .isInstanceOf(CalendarValidationException.class); + } + @Test void splitsMultipleUidsAndRetainsRecurrenceExceptionsTogether() { String master = event("series").replace("X-DATA:", "RRULE:FREQ=DAILY;COUNT=3\nX-DATA:"); @@ -34,7 +169,7 @@ void splitsMultipleUidsAndRetainsRecurrenceExceptionsTogether() { .replace( "DTSTART:20261102T090000Z", "RECURRENCE-ID:20261103T090000Z\nDTSTART:20261103T110000Z"); - var items = interchange.read(bytes(object(master + exception + event("second"))), "VEVENT"); + var items = read(bytes(object(master + exception + event("second"))), "VEVENT"); assertThat(items).hasSize(2).allSatisfy(i -> assertThat(i.rejection()).isEmpty()); var parsed = CalendarContent.parse(items.getFirst().content(), "VEVENT"); assertThat(parsed.uid()).isEqualTo("series"); @@ -49,7 +184,7 @@ void losslessCalendarStreamsRetainEachOriginalRepresentation() { var all = new java.io.ByteArrayOutputStream(); all.writeBytes(a); all.writeBytes(b); - var items = interchange.read(all.toByteArray(), "VEVENT"); + var items = read(all.toByteArray(), "VEVENT"); assertThat(items.get(0).content()).isEqualTo(a); assertThat(items.get(1).content()).isEqualTo(b); } @@ -60,11 +195,10 @@ void taskProfilesAndWrongTypeAreExplicit() { bytes( object( "BEGIN:VTODO\nUID:task\nDTSTAMP:20261101T000000Z\nSUMMARY:Undated task\nSTATUS:NEEDS-ACTION\nEND:VTODO\n")); - assertThat(interchange.read(task, "VTODO").getFirst().rejection()).isEmpty(); - assertThat(interchange.read(task, "VEVENT").getFirst().rejection()).contains("destination"); + assertThat(read(task, "VTODO").getFirst().rejection()).isEmpty(); + assertThat(read(task, "VEVENT").getFirst().rejection()).contains("destination"); assertThat( - interchange - .read( + read( bytes( object( "BEGIN:VJOURNAL\nUID:journal\nDTSTAMP:20261101T000000Z\nEND:VJOURNAL\n")), @@ -77,7 +211,7 @@ void taskProfilesAndWrongTypeAreExplicit() { @Test void invalidItemsAreReportedAndDuplicateMastersNeverDiscarded() { var mixed = - interchange.read( + read( bytes( object( event("good") @@ -86,26 +220,21 @@ void invalidItemsAreReportedAndDuplicateMastersNeverDiscarded() { assertThat(mixed).hasSize(2); assertThat(mixed.get(0).rejection()).isEmpty(); assertThat(mixed.get(1).rejection()).isNotEmpty(); - assertThat( - interchange - .read(bytes(object(event("same") + event("same"))), "VEVENT") - .getFirst() - .rejection()) + assertThat(read(bytes(object(event("same") + event("same"))), "VEVENT").getFirst().rejection()) .isNotEmpty(); - assertThat(interchange.read(bytes(object(event("same")) + object(event("same"))), "VEVENT")) + assertThat(read(bytes(object(event("same")) + object(event("same"))), "VEVENT")) .allSatisfy(i -> assertThat(i.rejection()).contains("multiple")); } @Test void malformedOversizedAndDeepFilesFailBeforeAnyImport() { - assertThatThrownBy(() -> interchange.read(bytes(""), "VEVENT")) + assertThatThrownBy(() -> read(bytes(""), "VEVENT")) .isInstanceOf(CalendarValidationException.class); - assertThatThrownBy( - () -> interchange.read(new byte[CalendarInterchange.MAX_FILE_BYTES + 1], "VEVENT")) + assertThatThrownBy(() -> read(new byte[CalendarInterchange.MAX_FILE_BYTES + 1], "VEVENT")) .isInstanceOf(CalendarValidationException.class); - assertThatThrownBy(() -> interchange.read(bytes(object("BEGIN:VEVENT\n".repeat(9))), "VEVENT")) + assertThatThrownBy(() -> read(bytes(object("BEGIN:VEVENT\n".repeat(9))), "VEVENT")) .isInstanceOf(CalendarValidationException.class); - assertThatThrownBy(() -> interchange.read(bytes(object(event("a")) + "garbage"), "VEVENT")) + assertThatThrownBy(() -> read(bytes(object(event("a")) + "garbage"), "VEVENT")) .isInstanceOf(CalendarValidationException.class); } @@ -118,7 +247,7 @@ void timezonesAndNominalDurationBytesRemainUntouched() { .replace( "DTSTART:20261102T090000Z", "DTSTART;TZID=Custom:20261102T090000\nDURATION:P1D"); byte[] source = bytes(object(zone + event)); - var item = interchange.read(source, "VEVENT").getFirst(); + var item = read(source, "VEVENT").getFirst(); assertThat(item.rejection()).isEmpty(); assertThat(item.content()).isEqualTo(source); assertThat( @@ -131,8 +260,7 @@ void knownThunderbirdObservanceRepairUsesExistingAdmission() throws Exception { String zone = "BEGIN:VTIMEZONE\nTZID:Custom\nBEGIN:STANDARD\nDTSTART:19700101T000000\nTZOFFSETFROM:+0200\nTZOFFSETTO:+0200\nRRULE:FREQ=YEARLY;BYMONTH=1;UNTIL=20300101T000000\nEND:STANDARD\nEND:VTIMEZONE\n"; var item = - interchange - .read( + read( bytes( object( zone diff --git a/src/test/java/org/busystack/caldav/config/PortabilityWorkFilterTest.java b/src/test/java/org/busystack/caldav/config/PortabilityWorkFilterTest.java new file mode 100644 index 0000000..6ee04b6 --- /dev/null +++ b/src/test/java/org/busystack/caldav/config/PortabilityWorkFilterTest.java @@ -0,0 +1,84 @@ +package org.busystack.caldav.config; + +import static org.assertj.core.api.Assertions.*; + +import java.nio.file.Path; +import java.util.concurrent.atomic.AtomicBoolean; +import org.busystack.caldav.management.PortabilityStorage; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +class PortabilityWorkFilterTest { + @TempDir Path temporary; + + @Test + void unsupportedMultipartSurfacesNeverReachParsingOrAuthentication() throws Exception { + try (var storage = new PortabilityStorage(temporary.resolve("private").toString())) { + var filter = new PortabilityWorkFilter(storage); + for (String prefix : new String[] {"", "/team"}) { + for (String route : + new String[] { + "/login", + "/login/webauthn", + "/oauth2/token", + "/collections", + "/admin/groups", + "/dav/calendars/example/object.ics" + }) { + var request = request(prefix, route, "MuLtIpArT/form-data; boundary=fixture"); + var response = new MockHttpServletResponse(); + var parsed = new AtomicBoolean(); + filter.doFilter(request, response, (req, res) -> parsed.set(true)); + assertThat(response.getStatus()).isEqualTo(415); + assertThat(parsed.get()).isFalse(); + assertThat(storage.reservedBytes()).isZero(); + } + } + } + } + + @Test + void previewReservesMultipartAndBothPrivateProcessingFilesBeforeParsing() throws Exception { + try (var storage = new PortabilityStorage(temporary.resolve("private").toString())) { + var filter = new PortabilityWorkFilter(storage); + var response = new MockHttpServletResponse(); + var parsed = new AtomicBoolean(); + filter.doFilter( + request("/team", "/portability/preview", "multipart/form-data; boundary=fixture"), + response, + (req, res) -> { + assertThat(storage.reservedBytes()).isEqualTo(161 * PortabilityStorage.MIB); + parsed.set(true); + }); + assertThat(parsed.get()).isTrue(); + assertThat(storage.reservedBytes()).isZero(); + } + } + + @Test + void ordinaryDavAndAuthenticationBodiesKeepTheirExistingHandlers() throws Exception { + try (var storage = new PortabilityStorage(temporary.resolve("private").toString())) { + var filter = new PortabilityWorkFilter(storage); + for (String route : + new String[] {"/dav/calendars/example/object.ics", "/login", "/login/webauthn"}) { + var parsed = new AtomicBoolean(); + filter.doFilter( + request("", route, "application/json"), + new MockHttpServletResponse(), + (req, res) -> parsed.set(true)); + assertThat(parsed.get()).isTrue(); + assertThat(storage.reservedBytes()).isZero(); + } + } + } + + private MockHttpServletRequest request(String prefix, String route, String type) { + var request = new MockHttpServletRequest("POST", prefix + route); + request.setContextPath(prefix); + request.setServletPath(route); + request.setContentType(type); + return request; + } +} diff --git a/src/test/java/org/busystack/caldav/management/ImportStagingTest.java b/src/test/java/org/busystack/caldav/management/ImportStagingTest.java new file mode 100644 index 0000000..905273e --- /dev/null +++ b/src/test/java/org/busystack/caldav/management/ImportStagingTest.java @@ -0,0 +1,189 @@ +package org.busystack.caldav.management; + +import static org.assertj.core.api.Assertions.*; +import static org.springframework.transaction.support.TransactionSynchronization.*; + +import java.nio.file.*; +import java.time.*; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class ImportStagingTest { + @TempDir Path temporary; + UUID actor = UUID.randomUUID(), epoch = UUID.randomUUID(), destination = UUID.randomUUID(); + + private ImportStaging.Staged save( + ImportStaging staging, + UUID actor, + UUID epoch, + UUID destination, + PortabilityStorage.PrivateFile file, + long bytes) { + return staging.save( + actor, + epoch, + destination, + file, + bytes, + stage -> + new PortabilityService.Report( + stage.token(), "Fixture", stage.expires(), java.util.List.of(), 0, 0, 0, 0, 0)); + } + + @Test + void failedReportPreparationCannotReplaceThePreviousValidPreview() throws Exception { + var staging = new ImportStaging(new Time()); + try (var storage = new PortabilityStorage(temporary.resolve("private").toString())) { + var original = storage.create(1024); + var previous = save(staging, actor, epoch, destination, original, 1024); + try (var replacement = storage.create(1024)) { + assertThatThrownBy( + () -> + staging.save( + actor, + epoch, + destination, + replacement, + 1024, + stage -> { + throw new OutOfMemoryError("injected report preparation failure"); + })) + .isInstanceOf(OutOfMemoryError.class); + } + assertThat(staging.current(actor, epoch)).isSameAs(previous); + assertThat(staging.owned(previous.token(), actor, epoch).report()).isNotNull(); + assertThat(original.path()).exists(); + staging.close(); + assertThat(storage.reservedBytes()).isZero(); + } + } + + static final class Time extends Clock { + Instant now = Instant.parse("2026-11-03T00:00:00Z"); + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return now; + } + } + + @Test + void retainedMetadataHasAnAggregateBudgetAndFailedReplacementPreservesPreview() throws Exception { + var staging = new ImportStaging(new Time()); + try (var storage = new PortabilityStorage(temporary.resolve("private").toString())) { + var original = storage.create(1024); + var first = save(staging, actor, epoch, destination, original, 24L * 1024 * 1024); + try (var rejected = storage.create(1024)) { + assertThatThrownBy( + () -> + save( + staging, + UUID.randomUUID(), + epoch, + destination, + rejected, + 16L * 1024 * 1024)) + .isInstanceOf(PortabilityStorage.CapacityException.class); + assertThatThrownBy( + () -> save(staging, actor, epoch, destination, rejected, 33L * 1024 * 1024)) + .isInstanceOf(PortabilityStorage.CapacityException.class); + } + assertThat(staging.owned(first.token(), actor, epoch).state()) + .isEqualTo(ImportStaging.State.AVAILABLE); + assertThat(original.path()).exists(); + staging.close(); + assertThat(storage.reservedBytes()).isZero(); + } + } + + @Test + void rollbackCanRetryCommitIsSingleUseAndSecurityEpochAndOwnerRemainRequired() throws Exception { + var clock = new Time(); + var staging = new ImportStaging(clock); + try (var storage = new PortabilityStorage(temporary.resolve("private").toString())) { + var file = storage.create(1024); + var stage = save(staging, actor, epoch, destination, file, 1024); + assertThatThrownBy(() -> staging.begin(stage.token(), UUID.randomUUID(), epoch)) + .isInstanceOf(org.busystack.caldav.storage.StoreException.class); + assertThatThrownBy(() -> staging.begin(stage.token(), actor, UUID.randomUUID())) + .isInstanceOf(org.busystack.caldav.storage.StoreException.class); + assertThat(staging.begin(stage.token(), actor, epoch).state()) + .isEqualTo(ImportStaging.State.CONFIRMING); + assertThatThrownBy(() -> staging.begin(stage.token(), actor, epoch)) + .isInstanceOf(org.busystack.caldav.storage.StoreException.class); + assertThatThrownBy(() -> staging.cancel(stage.token(), actor, epoch)) + .isInstanceOf(org.busystack.caldav.storage.StoreException.class); + staging.complete(stage, STATUS_ROLLED_BACK, null); + assertThat(stage.state()).isEqualTo(ImportStaging.State.AVAILABLE); + assertThat(file.path()).exists(); + staging.begin(stage.token(), actor, epoch); + staging.complete(stage, STATUS_COMMITTED, null); + assertThat(stage.state()).isEqualTo(ImportStaging.State.CONSUMED); + assertThat(file.path()).doesNotExist(); + assertThatThrownBy(() -> staging.begin(stage.token(), actor, epoch)) + .isInstanceOf(org.busystack.caldav.storage.StoreException.class); + assertThat(storage.reservedBytes()).isZero(); + } + } + + @Test + void committedResultsRemainReviewableWhenLongConfirmationOutlivesPreviewExpiry() + throws Exception { + var time = new Time(); + var staging = new ImportStaging(time); + try (var storage = new PortabilityStorage(temporary.resolve("private").toString())) { + var file = storage.create(1024); + var stage = save(staging, actor, epoch, destination, file, 1024); + time.now = time.now.plusSeconds(590); + staging.begin(stage.token(), actor, epoch); + time.now = time.now.plusSeconds(100); + staging.prune(); + assertThat(stage.state()).isEqualTo(ImportStaging.State.CONFIRMING); + staging.complete(stage, STATUS_COMMITTED, null); + assertThat(staging.owned(stage.token(), actor, epoch).state()) + .isEqualTo(ImportStaging.State.CONSUMED); + assertThat(file.path()).doesNotExist(); + time.now = time.now.plusSeconds(601); + staging.prune(); + assertThatThrownBy(() -> staging.owned(stage.token(), actor, epoch)) + .isInstanceOf(org.busystack.caldav.storage.StoreException.class); + } + } + + @Test + void cancellationExpiryUnknownOutcomesAndExpiredRollbacksDiscardData() throws Exception { + for (String action : new String[] {"cancel", "expire", "unknown", "expired-rollback"}) { + var time = new Time(); + var staging = new ImportStaging(time); + try (var storage = new PortabilityStorage(temporary.resolve(action).toString())) { + var file = storage.create(1024); + var stage = save(staging, actor, epoch, destination, file, 1024); + if (action.equals("cancel")) staging.cancel(stage.token(), actor, epoch); + else if (action.equals("expire")) { + time.now = time.now.plusSeconds(601); + staging.prune(); + } else { + staging.begin(stage.token(), actor, epoch); + if (action.equals("expired-rollback")) time.now = time.now.plusSeconds(601); + staging.complete( + stage, action.equals("unknown") ? STATUS_UNKNOWN : STATUS_ROLLED_BACK, null); + } + assertThat(file.path()).doesNotExist(); + assertThat(storage.reservedBytes()).isZero(); + assertThatThrownBy(() -> staging.begin(stage.token(), actor, epoch)) + .isInstanceOf(org.busystack.caldav.storage.StoreException.class); + } + } + } +} diff --git a/src/test/java/org/busystack/caldav/management/PortabilityServiceTest.java b/src/test/java/org/busystack/caldav/management/PortabilityServiceTest.java new file mode 100644 index 0000000..1e85d4c --- /dev/null +++ b/src/test/java/org/busystack/caldav/management/PortabilityServiceTest.java @@ -0,0 +1,75 @@ +package org.busystack.caldav.management; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.Mockito.*; + +import java.nio.file.Path; +import java.util.List; +import java.util.UUID; +import org.busystack.caldav.security.audit.SecurityAudit; +import org.busystack.caldav.security.session.SessionSecurity; +import org.busystack.caldav.storage.CalendarStore; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.authority.FactorGrantedAuthority; + +class PortabilityServiceTest { + @TempDir Path temporary; + + @Test + void interruptedExportReleasesPrivateFileAndReservationEvenForMemoryFailure() throws Exception { + UUID actor = UUID.randomUUID(), collection = UUID.randomUUID(); + var auth = + UsernamePasswordAuthenticationToken.authenticated( + "fixture", + null, + List.of( + FactorGrantedAuthority.fromAuthority(FactorGrantedAuthority.PASSWORD_AUTHORITY), + FactorGrantedAuthority.fromAuthority(FactorGrantedAuthority.WEBAUTHN_AUTHORITY))); + var sessions = mock(SessionSecurity.class); + when(sessions.assertCurrent(auth)) + .thenReturn(new SessionSecurity.Account(actor, "fixture", UUID.randomUUID())); + for (boolean afterWrite : new boolean[] {false, true}) { + var calendars = mock(CalendarStore.class); + when(calendars.collection(actor, collection)) + .thenReturn( + new CalendarStore.Collection( + collection, actor, "Private", "VEVENT", UUID.randomUUID(), 1, 0)); + if (afterWrite) { + byte[] body = + "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Fixture//EN\r\nBEGIN:VEVENT\r\nUID:memory\r\nDTSTAMP:20261101T000000Z\r\nDTSTART:20261102T000000Z\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n" + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + when(calendars.resourceBatch(actor, collection, "")) + .thenReturn( + List.of( + new CalendarStore.Resource("fixture.ics", "memory", body, "\"fixture\"", 1))); + when(calendars.resourceBatch(actor, collection, "fixture.ics")) + .thenThrow(new OutOfMemoryError("injected qualification failure")); + } else + when(calendars.resourceBatch(actor, collection, "")) + .thenThrow(new OutOfMemoryError("injected qualification failure")); + Path directory = temporary.resolve("private-" + afterWrite); + try (var storage = new PortabilityStorage(directory.toString())) { + var service = + new PortabilityService( + null, + sessions, + calendars, + null, + null, + null, + null, + mock(SecurityAudit.class), + storage); + assertThatThrownBy(() -> service.export(auth, collection)) + .isInstanceOf(OutOfMemoryError.class); + assertThat(storage.reservedBytes()).isZero(); + assertThat(storage.usedBytes()).isZero(); + try (var entries = java.nio.file.Files.list(directory)) { + assertThat(entries.map(p -> p.getFileName().toString())).containsExactly("instance.lock"); + } + } + } + } +} diff --git a/src/test/java/org/busystack/caldav/management/PortabilityStorageTest.java b/src/test/java/org/busystack/caldav/management/PortabilityStorageTest.java new file mode 100644 index 0000000..b2b770b --- /dev/null +++ b/src/test/java/org/busystack/caldav/management/PortabilityStorageTest.java @@ -0,0 +1,129 @@ +package org.busystack.caldav.management; + +import static org.assertj.core.api.Assertions.*; + +import java.nio.file.*; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.UUID; +import java.util.concurrent.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class PortabilityStorageTest { + @TempDir Path temporary; + + @Test + void fileCountIsBoundedEvenWhenFilesAreTiny() throws Exception { + try (var storage = new PortabilityStorage(temporary.resolve("private").toString())) { + var files = new java.util.ArrayList(); + for (int n = 0; n < 72; n++) files.add(storage.create(1)); + assertThatThrownBy(() -> storage.create(1)) + .isInstanceOf(PortabilityStorage.CapacityException.class); + for (var file : files) file.close(); + assertThat(storage.reservedBytes()).isZero(); + } + } + + @Test + void reservationsCoverRetainedFilesDownloadsAndMultipartBeforeAdmission() throws Exception { + try (var storage = new PortabilityStorage(temporary.resolve("private").toString())) { + var preview = storage.create(PortabilityStorage.FILE_BYTES); + var download = storage.create(PortabilityStorage.FILE_BYTES); + assertThat(storage.reservedBytes()).isEqualTo(128 * PortabilityStorage.MIB); + assertThatThrownBy(() -> storage.begin(true)) + .isInstanceOf(PortabilityStorage.CapacityException.class); + assertThat(storage.reservedBytes()).isEqualTo(128 * PortabilityStorage.MIB); + download.close(); + try (var upload = storage.begin(true)) { + assertThat(storage.reservedBytes()).isEqualTo(225 * PortabilityStorage.MIB); + try (var file = storage.create(PortabilityStorage.FILE_BYTES); + var index = storage.create(PortabilityStorage.INDEX_BYTES)) { + assertThat(storage.reservedBytes()).isEqualTo(225 * PortabilityStorage.MIB); + Files.writeString(file.path(), "private"); + file.compact(); + assertThat(storage.reservedBytes()).isEqualTo(161 * PortabilityStorage.MIB + 7); + } + } + preview.close(); + assertThat(storage.reservedBytes()).isZero(); + } + } + + @Test + void operationGateAndByteLedgerAreSharedAcrossThreads() throws Exception { + try (var storage = new PortabilityStorage(temporary.resolve("private").toString()); + var pool = Executors.newFixedThreadPool(2)) { + var acquired = new CountDownLatch(2); + var release = new CountDownLatch(1); + var task = + (Callable) + () -> { + try (var work = storage.begin(false)) { + acquired.countDown(); + release.await(10, TimeUnit.SECONDS); + } + return null; + }; + var one = pool.submit(task); + var two = pool.submit(task); + assertThat(acquired.await(10, TimeUnit.SECONDS)).isTrue(); + try { + assertThatThrownBy(() -> storage.begin(false)) + .isInstanceOf(PortabilityStorage.CapacityException.class); + } finally { + release.countDown(); + } + one.get(); + two.get(); + assertThat(storage.reservedBytes()).isZero(); + } + } + + @Test + void privateFilesAndOrphanCleanupNeverFollowLinksOrDeleteUnrelatedFiles() throws Exception { + Path root = temporary.resolve("private"); + try (var storage = new PortabilityStorage(root.toString())) { + var file = storage.create(1024); + assertThat(Files.getPosixFilePermissions(root)) + .isEqualTo(PosixFilePermissions.fromString("rwx------")); + assertThat(Files.getPosixFilePermissions(file.path())) + .isEqualTo(PosixFilePermissions.fromString("rw-------")); + file.close(); + assertThat(Files.exists(file.path())).isFalse(); + storage.multipartDirectory(); + } + Path orphan = root.resolve("data-" + UUID.randomUUID() + ".private"); + Files.writeString(orphan, "calendar remnants"); + Path multipart = root.resolve("multipart/upload_fixture_00000001.tmp"); + Files.writeString(multipart, "upload remnants"); + Path unrelated = root.resolve("operator-notes"); + Files.writeString(unrelated, "preserve"); + try (var restarted = new PortabilityStorage(root.toString())) { + restarted.multipartDirectory(); + assertThat(orphan).doesNotExist(); + assertThat(multipart).doesNotExist(); + assertThat(unrelated).hasContent("preserve"); + } + Path outside = temporary.resolve("outside"); + Files.writeString(outside, "preserve"); + Files.createSymbolicLink(orphan, outside); + assertThatThrownBy(() -> new PortabilityStorage(root.toString())) + .isInstanceOf(java.io.IOException.class); + assertThat(outside).hasContent("preserve"); + } + + @Test + void failedCleanupKeepsReservationUntilItCanBeRetried() throws Exception { + try (var storage = new PortabilityStorage(temporary.resolve("private").toString())) { + var file = storage.create(1024); + Files.delete(file.path()); + Files.createDirectory(file.path()); + Files.writeString(file.path().resolve("block"), "x"); + file.close(); + assertThat(storage.reservedBytes()).isEqualTo(1024); + Files.delete(file.path().resolve("block")); + storage.cleanup(); + assertThat(storage.reservedBytes()).isZero(); + } + } +} diff --git a/src/test/java/org/busystack/caldav/management/PortalErrorsTest.java b/src/test/java/org/busystack/caldav/management/PortalErrorsTest.java new file mode 100644 index 0000000..1dd8488 --- /dev/null +++ b/src/test/java/org/busystack/caldav/management/PortalErrorsTest.java @@ -0,0 +1,33 @@ +package org.busystack.caldav.management; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.Mockito.*; + +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.transaction.TransactionTimedOutException; +import org.springframework.ui.ExtendedModelMap; + +class PortalErrorsTest { + @Test + void transactionDeadlineFailureReturnsSafeRecoveryToTheExistingPreview() { + var request = new MockHttpServletRequest(); + String path = "/portability/import/11111111-1111-4111-8111-111111111111"; + request.setServletPath(path); + var response = new MockHttpServletResponse(); + var model = new ExtendedModelMap(); + var errors = new PortalErrors(mock(FormRecovery.class)); + String view = + errors.failure( + new TransactionTimedOutException("private internal deadline"), + request, + response, + model, + null); + assertThat(view).isEqualTo("portal-error"); + assertThat(response.getStatus()).isEqualTo(503); + assertThat(model.get("retryPath")).isEqualTo(path); + assertThat(model.get("message").toString()).doesNotContain("private internal deadline"); + } +} diff --git a/src/test/java/org/busystack/caldav/management/PortalManagementIT.java b/src/test/java/org/busystack/caldav/management/PortalManagementIT.java index 4cb0af5..7618c41 100644 --- a/src/test/java/org/busystack/caldav/management/PortalManagementIT.java +++ b/src/test/java/org/busystack/caldav/management/PortalManagementIT.java @@ -58,6 +58,8 @@ static void configuration(DynamicPropertyRegistry registry) { @Autowired AdministrationService administration; @Autowired SharingManagementService sharing; @Autowired PortabilityService portability; + @Autowired PortabilityStorage portabilityStorage; + @Autowired org.busystack.caldav.calendar.CalendarInterchange interchange; @Autowired AccountService accounts; @Autowired CalendarStore calendars; @Autowired DavStore dav; @@ -92,6 +94,102 @@ void prepare() { "#126A5EFF"); } + @Test + void invalidRowFormsRetainTheirPageAndMemberFilter() throws Exception { + var names = new HashSet(); + for (int n = 0; n < 51; n++) { + String username = "paged-%02d".formatted(n); + accounts.provision(username, "Paged member " + n, "correct horse battery staple", false); + management.share(auth(owner, true), collection, username, "READ"); + names.add(username); + } + UUID group = groups.create(auth(admin, true), "Paged group", names); + var user = browser(owner, true); + var sharingPage = get(user, "/collections/" + collection + "/sharing?directPage=1"); + assertThat(sharingPage.body()).contains("name=\"directPage\" value=\"1\""); + fieldError( + post( + user, + "/shares", + Map.of( + "_csrf", + csrf(sharingPage.body()), + "collection", + collection.toString(), + "username", + "paged-50", + "permission", + "INVALID", + "expected", + "READ", + "directPage", + "1")), + 400, + "direct-grant-paged-50", + "permission"); + var administrator = browser(admin, true); + var members = get(administrator, "/admin/groups/" + group + "?page=1"); + UUID last = accounts.find("paged-50").id(); + fieldError( + post( + administrator, + "/admin/groups/" + group + "/members/" + last + "/remove", + Map.of("_csrf", csrf(members.body()), "memberPage", "1")), + 400, + "member-remove-" + last, + "confirmed"); + var filtered = + post( + administrator, + "/admin/groups/" + group + "/members/" + last + "/remove", + Map.of("_csrf", csrf(members.body()), "memberQuery", "paged-50")); + fieldError(filtered, 400, "member-remove-" + last, "confirmed"); + assertThat(filtered.body()).contains("name=\"q\" value=\"paged-50\""); + } + + @Test + void selectedImportDestinationRemainsEditableBeyondFirstListingPage() throws Exception { + for (int n = 0; n < 51; n++) portal.create(auth(owner, true), "A first " + n, "VEVENT", "", ""); + assertThat(portal.collections(auth(owner, true), "all", "", 0).rows()) + .noneMatch(c -> c.id().equals(collection)); + var response = get(browser(owner, true), "/portability?destination=" + collection); + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.body()) + .contains("value=\"" + collection + "\"", "Validate and preview import", "open=\"open\""); + assertThat(get(browser(other, true), "/portability?destination=" + collection).statusCode()) + .isIn(403, 404); + } + + @Test + void targetedAuditRetainsExistingCountAndAgePruning() { + var audit = new org.busystack.caldav.security.audit.SecurityAudit(jdbc); + jdbc.update( + "INSERT INTO security_audit(account_id,action,outcome,target_type,target_id,occurred_at) SELECT ?, 'ACCOUNT_PROFILE_UPDATED','SUCCESS','ACCOUNT',?,now()-interval '31 days' FROM generate_series(1,10005)", + admin, + owner); + audit.targeted( + admin, + org.busystack.caldav.security.audit.SecurityAudit.Action.ACCOUNT_PROFILE_UPDATED, + org.busystack.caldav.security.audit.SecurityAudit.Outcome.SUCCESS, + org.busystack.caldav.security.audit.SecurityAudit.TargetType.ACCOUNT, + owner, + null); + assertThat(jdbc.queryForObject("SELECT count(*) FROM security_audit", Long.class)) + .isLessThanOrEqualTo(10000); + audit.prune(); + assertThat( + jdbc.queryForObject( + "SELECT count(*) FROM security_audit WHERE occurred_at < now()-interval '30 days'", + Long.class)) + .isZero(); + assertThat( + jdbc.queryForObject( + "SELECT count(*) FROM security_audit WHERE target_id=? AND occurred_at > now()-interval '1 minute'", + Long.class, + owner)) + .isEqualTo(1); + } + @Test void metadataUsesDavPropertiesAndRetainsPathsBytesAndTokens() { var original = portal.collection(auth(owner, true), collection); @@ -289,7 +387,7 @@ void importPreviewConfirmationDuplicateConflictAndRoundTripAreAccurate() throws bytes = Files.readAllBytes(exported.path()); assertThat(new String(bytes, StandardCharsets.UTF_8).split("BEGIN:VCALENDAR", -1)).hasSize(2); } finally { - Files.deleteIfExists(exported.path()); + exported.close(); } UUID destination = portal.create(auth(owner, true), "Imported", "VEVENT", "", ""); var roundtrip = @@ -324,18 +422,18 @@ void incompatibleCalendarContextsExportLosslesslyWithoutCombiningTimezoneDefinit var export = portability.export(auth(owner, true), collection); try { assertThat(export.stream()).isTrue(); - var items = - new org.busystack.caldav.calendar.CalendarInterchange( - new org.busystack.caldav.calendar.CalendarAdmission( - new org.busystack.caldav.config.DavCompatibilityProperties(true, true))) - .read(Files.readAllBytes(export.path()), "VEVENT"); + var items = new java.util.ArrayList(); + try (var index = portabilityStorage.create(PortabilityStorage.INDEX_BYTES); + var file = interchange.open(export.path(), index.path())) { + for (int n = 0; n < file.size(); n++) items.add(interchange.item(file, n, "VEVENT")); + } assertThat(items).hasSize(2).allSatisfy(i -> assertThat(i.rejection()).isEmpty()); assertThat(items) .extracting(i -> new String(i.content(), StandardCharsets.UTF_8)) .containsExactlyInAnyOrder( new String(a, StandardCharsets.UTF_8), new String(b, StandardCharsets.UTF_8)); } finally { - Files.deleteIfExists(export.path()); + export.close(); } } @@ -343,8 +441,23 @@ void incompatibleCalendarContextsExportLosslesslyWithoutCombiningTimezoneDefinit void importRechecksWritePermissionAndReportsRejectedItemsWithoutMutation() throws Exception { management.share(auth(owner, true), collection, "portal-reader", "WRITE"); var preview = portability.preview(auth(reader, true), collection, event("safe")); + var client = browser(reader, true); + String csrf = csrf(get(client, "/portability").body()); management.share(auth(owner, true), collection, "portal-reader", "READ"); denied(() -> portability.confirm(auth(reader, true), preview.token(), true)); + assertThat( + post( + client, + "/portability/import/" + preview.token(), + Map.of("_csrf", csrf, "confirmed", "true")) + .statusCode()) + .isEqualTo(403); + management.share(auth(owner, true), collection, "portal-reader", "REVOKE"); + var hidden = get(client, "/portability/import/" + preview.token()); + assertThat(hidden.statusCode()).isIn(403, 404); + assertThat(hidden.body()).doesNotContain("New UID series", "DTSTART", "Untitled item"); + assertThat(get(client, "/portability").body()) + .doesNotContain("/portability/import/" + preview.token()); denied(() -> portability.preview(auth(reader, true), collection, event("safe"))); denied(() -> portability.export(auth(admin, true), collection)); byte[] malformed = @@ -379,6 +492,689 @@ void importRollbackNeverLeavesPartialResources() throws Exception { jdbc.execute("DROP FUNCTION portal_fail_second()"); } assertThat(calendars.metadataBatch(owner, collection, "", 10)).isEmpty(); + assertThat(portability.confirm(auth(owner, true), preview.token(), true).imported()) + .isEqualTo(2); + denied(() -> portability.confirm(auth(owner, true), preview.token(), true)); + assertThat(calendars.metadataBatch(owner, collection, "", 10)).hasSize(2); + } + + private static byte[] mediumStreamBody(int n, String type) { + String zone = + "BEGIN:VTIMEZONE\r\nTZID:Same/Local\r\nBEGIN:STANDARD\r\nDTSTART:19700101T000000\r\nTZOFFSETFROM:" + + (n % 2 == 0 ? "+0200" : "+0300") + + "\r\nTZOFFSETTO:" + + (n % 2 == 0 ? "+0200" : "+0300") + + "\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n"; + String uid = "medium-" + n; + String value = + calendarBody(uid) + .replace("BEGIN:VEVENT", zone + "BEGIN:VEVENT") + .replace("DTSTART:20261028T000000Z", "DTSTART;TZID=Same/Local:20261028T000000") + .replace("X-CLIENT:preserve", "X-CLIENT:" + "p".repeat(8500)) + .replace("VERSION:2.0", "VERSION:2.0\r\nX-CALENDAR-CONTEXT:" + n); + if (type.equals("VTODO")) + value = + value.replace("VEVENT", "VTODO").replace("SUMMARY:", "STATUS:NEEDS-ACTION\r\nSUMMARY:"); + else if (n % 100 == 0) { + String exception = + calendarBody(uid) + .substring( + calendarBody(uid).indexOf("BEGIN:VEVENT"), + calendarBody(uid).indexOf("END:VCALENDAR")) + .replace( + "DTSTART:20261028T000000Z", + "RECURRENCE-ID;TZID=Same/Local:20261029T000000\r\nDTSTART;TZID=Same/Local:20261029T020000"); + value = + value + .replace("X-CLIENT:", "RRULE:FREQ=DAILY;COUNT=3\r\nX-CLIENT:") + .replace("END:VCALENDAR", exception + "END:VCALENDAR"); + } + return value.getBytes(StandardCharsets.UTF_8); + } + + @Test + void realHttpMediumStreamsRoundTripDistinctTimezonesMetadataExceptionsAndTasks() + throws Exception { + for (String type : List.of("VEVENT", "VTODO")) { + UUID source = portal.create(auth(owner, true), "Medium source " + type, type, "", ""); + UUID target = portal.create(auth(owner, true), "Medium target " + type, type, "", ""); + var tx = new org.springframework.transaction.support.TransactionTemplate(transactions); + tx.executeWithoutResult( + status -> { + for (int n = 0; n < 1100; n++) + calendars.put( + owner, + source, + "medium-%04d.ics".formatted(n), + "medium-" + n, + mediumStreamBody(n, type), + WriteCondition.create()); + }); + var client = browser(owner, true); + String csrf = csrf(get(client, "/portability").body()); + var downloaded = Files.createTempFile("busystack-medium-client-", ".ics"); + try { + var response = + client.send( + HttpRequest.newBuilder( + URI.create(base() + "/portability/collections/" + source + "/export")) + .timeout(Duration.ofSeconds(660)) + .GET() + .build(), + HttpResponse.BodyHandlers.ofFile(downloaded)); + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.headers().firstValue("Content-Disposition")) + .hasValue("attachment; filename=\"busystack-collection-stream.ics\""); + assertThat(Files.size(downloaded)).isGreaterThan(8L * 1024 * 1024); + var preview = uploadFile(client, csrf, target, downloaded); + assertThat(preview.statusCode()).isEqualTo(200); + var matcher = + java.util.regex.Pattern.compile("/portability/import/([a-f0-9-]{36})") + .matcher(preview.body()); + assertThat(matcher.find()).isTrue(); + String token = matcher.group(1); + assertThat(get(client, "/portability/import/" + token + "?page=21").body()) + .contains("medium-1099"); + var result = + post( + client, "/portability/import/" + token, Map.of("_csrf", csrf, "confirmed", "true")); + assertThat(result.statusCode()).isEqualTo(200); + assertThat( + jdbc.queryForObject( + "SELECT count(*) FROM calendar_resources WHERE collection_id=?", + Long.class, + target)) + .isEqualTo(1100); + for (var batch = calendars.resourceBatch(owner, target, ""); !batch.isEmpty(); ) { + for (var resource : batch) { + var parsed = + org.busystack.caldav.calendar.CalendarContent.parse(resource.content(), type); + int n = Integer.parseInt(parsed.uid().substring("medium-".length())); + assertThat(resource.content()).isEqualTo(mediumStreamBody(n, type)); + } + batch = calendars.resourceBatch(owner, target, batch.getLast().name()); + } + } finally { + Files.deleteIfExists(downloaded); + } + } + } + + @Test + void realHttpLargeRoundTripHasPagedPreviewAndPreservesAllResourceBytes() throws Exception { + var tx = new org.springframework.transaction.support.TransactionTemplate(transactions); + String padding = "x".repeat(6400); + tx.executeWithoutResult( + status -> { + for (int n = 0; n < 10000; n++) { + byte[] content = + calendarBody("large-" + n) + .replace("X-CLIENT:preserve", "X-CLIENT:" + padding) + .getBytes(StandardCharsets.UTF_8); + dav.putResource( + owner, collection, "large-%04d.ics".formatted(n), content, WriteCondition.create()); + } + }); + UUID target = portal.create(auth(owner, true), "Large migration", "VEVENT", "", ""); + var browser = browser(owner, true); + java.nio.file.Path downloadFile = Files.createTempFile("busystack-qualification-", ".ics"); + var peakDisk = new java.util.concurrent.atomic.AtomicLong(); + var peakReserved = new java.util.concurrent.atomic.AtomicLong(); + var peakHeap = new java.util.concurrent.atomic.AtomicLong(); + var peakRss = new java.util.concurrent.atomic.AtomicLong(); + var sampler = java.util.concurrent.Executors.newSingleThreadScheduledExecutor(); + sampler.scheduleAtFixedRate( + () -> { + try { + for (String line : Files.readAllLines(java.nio.file.Path.of("/proc/self/status"))) { + if (line.startsWith("VmRSS:")) + peakRss.accumulateAndGet( + Long.parseLong(line.replaceAll("[^0-9]", "")) * 1024, Math::max); + } + peakDisk.accumulateAndGet(portabilityStorage.usedBytes(), Math::max); + } catch (java.io.IOException ignored) { + } + peakReserved.accumulateAndGet(portabilityStorage.reservedBytes(), Math::max); + peakHeap.accumulateAndGet( + java.lang.management.ManagementFactory.getMemoryMXBean() + .getHeapMemoryUsage() + .getUsed(), + Math::max); + }, + 0, + 100, + java.util.concurrent.TimeUnit.MILLISECONDS); + try { + var download = + browser.send( + HttpRequest.newBuilder( + URI.create(base() + "/portability/collections/" + collection + "/export")) + .timeout(Duration.ofSeconds(660)) + .GET() + .build(), + HttpResponse.BodyHandlers.ofFile(downloadFile)); + assertThat(download.statusCode()).isEqualTo(200); + assertThat(Files.size(download.body())) + .isGreaterThan(60L * 1024 * 1024) + .isLessThanOrEqualTo(64L * 1024 * 1024); + String csrf = csrf(get(browser, "/portability").body()); + var preview = uploadFile(browser, csrf, target, download.body()); + assertThat(preview.statusCode()).isEqualTo(200); + assertThat(preview.body()).contains("Next", "10000").doesNotContain("large-9999"); + var matcher = + java.util.regex.Pattern.compile("/portability/import/([a-f0-9-]{36})") + .matcher(preview.body()); + assertThat(matcher.find()).isTrue(); + String token = matcher.group(1); + assertThat(get(browser, "/portability/import/" + token + "?page=199").body()) + .contains("large-9999"); + // A retained maximum-size preview and real overlapping downloads share one ledger. + var concurrentOne = Files.createTempFile("busystack-qualification-export-", ".ics"); + var concurrentTwo = Files.createTempFile("busystack-qualification-export-", ".ics"); + try (var downloads = java.util.concurrent.Executors.newFixedThreadPool(2)) { + var request = + HttpRequest.newBuilder( + URI.create(base() + "/portability/collections/" + collection + "/export")) + .timeout(Duration.ofSeconds(660)) + .GET() + .build(); + var one = + downloads.submit( + () -> browser.send(request, HttpResponse.BodyHandlers.ofFile(concurrentOne))); + long waitUntil = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(30); + long retainedSize = Files.size(downloadFile); + while (portabilityStorage.reservedBytes() < retainedSize + PortabilityStorage.FILE_BYTES + && System.nanoTime() < waitUntil) Thread.sleep(10); + assertThat(portabilityStorage.reservedBytes()) + .isGreaterThanOrEqualTo(retainedSize + PortabilityStorage.FILE_BYTES); + var busy = upload(browser, csrf, target, "busy.ics", event("capacity-denied")); + assertThat(busy.statusCode()).isEqualTo(503); + assertThat(busy.headers().firstValue("Retry-After")).isPresent(); + var two = + downloads.submit( + () -> browser.send(request, HttpResponse.BodyHandlers.ofFile(concurrentTwo))); + assertThat(one.get(660, java.util.concurrent.TimeUnit.SECONDS).statusCode()).isEqualTo(200); + assertThat(two.get(660, java.util.concurrent.TimeUnit.SECONDS).statusCode()).isEqualTo(200); + assertThat(Files.mismatch(downloadFile, concurrentOne)).isEqualTo(-1); + assertThat(Files.mismatch(downloadFile, concurrentTwo)).isEqualTo(-1); + assertThat(get(browser, "/portability/import/" + token).statusCode()).isEqualTo(200); + } finally { + Files.deleteIfExists(concurrentOne); + Files.deleteIfExists(concurrentTwo); + } + var outcome = + post(browser, "/portability/import/" + token, Map.of("_csrf", csrf, "confirmed", "true")); + assertThat(outcome.statusCode()).isEqualTo(200); + assertThat(outcome.body()) + .contains("10000", "All reported new items were committed together"); + assertThat( + jdbc.queryForObject( + "SELECT count(*) FROM calendar_resources WHERE collection_id=?", + Long.class, + target)) + .isEqualTo(10000); + for (var batch = calendars.resourceBatch(owner, target, ""); !batch.isEmpty(); ) { + for (var resource : batch) { + String uid = + org.busystack.caldav.calendar.CalendarContent.parse(resource.content(), "VEVENT") + .uid(); + assertThat(resource.content()) + .isEqualTo( + calendarBody(uid) + .replace("X-CLIENT:preserve", "X-CLIENT:" + padding) + .getBytes(StandardCharsets.UTF_8)); + } + batch = calendars.resourceBatch(owner, target, batch.getLast().name()); + } + var replayBrowser = browser(owner, true); + String replayCsrf = csrf(get(replayBrowser, "/portability").body()); + var resultPage = get(replayBrowser, "/portability/import/" + token + "?page=199"); + assertThat(resultPage.statusCode()).isEqualTo(200); + assertThat(resultPage.body()).contains("Imported", "10000"); + assertThat( + post( + replayBrowser, + "/portability/import/" + token, + Map.of("_csrf", replayCsrf, "confirmed", "true")) + .statusCode()) + .isEqualTo(412); + } finally { + sampler.shutdownNow(); + sampler.awaitTermination(5, java.util.concurrent.TimeUnit.SECONDS); + Files.deleteIfExists(downloadFile); + var output = java.nio.file.Path.of("target/qualification/portability"); + Files.createDirectories(output); + Files.writeString( + output.resolve("large-http.json"), + "{\"items\":10000,\"heapLimit\":268435456,\"peakHeap\":" + + peakHeap.get() + + ",\"peakTemporaryDisk\":" + + peakDisk.get() + + ",\"peakRss\":" + + peakRss.get() + + ",\"peakReservation\":" + + peakReserved.get() + + "}\n"); + } + } + + @Test + void concurrentHttpConfirmationsCommitOnceAndFailedReplacementRetainsOriginal() throws Exception { + var browser = browser(owner, true); + var preview = portability.preview(auth(owner, true), collection, event("single-use")); + denied(() -> portability.preview(auth(owner, true), collection, new byte[] {1})); + String csrf = csrf(get(browser, "/portability").body()); + var failedUpload = + upload( + browser, + csrf, + collection, + "invalid.ics", + "invalid calendar".getBytes(StandardCharsets.UTF_8)); + assertThat(failedUpload.statusCode()).isEqualTo(400); + assertThat(failedUpload.body()) + .contains( + "href=\"/team/portability/import/" + preview.token() + "\"", + "Review your latest import preview or results"); + assertThat(get(browser, "/portability/import/" + preview.token()).statusCode()).isEqualTo(200); + try (var executor = java.util.concurrent.Executors.newFixedThreadPool(2)) { + var start = new java.util.concurrent.CountDownLatch(1); + var operation = + (java.util.concurrent.Callable) + () -> { + start.await(); + return post( + browser, + "/portability/import/" + preview.token(), + Map.of("_csrf", csrf, "confirmed", "true")) + .statusCode(); + }; + var one = executor.submit(operation); + var two = executor.submit(operation); + start.countDown(); + assertThat(List.of(one.get(), two.get())).containsExactlyInAnyOrder(200, 412); + } + assertThat(calendars.metadataBatch(owner, collection, "", 10)).hasSize(1); + } + + @Test + void httpRollbackRetainsEditableConfirmationBeforeAndAfterResourceWrites() throws Exception { + var browser = browser(owner, true); + String csrf = csrf(get(browser, "/portability").body()); + for (String failUid : List.of("a", "b")) { + UUID target = portal.create(auth(owner, true), "Rollback " + failUid, "VEVENT", "", ""); + var preview = + portability.preview( + auth(owner, true), + target, + (calendarBody("a") + calendarBody("b")).getBytes(StandardCharsets.UTF_8)); + jdbc.execute( + "CREATE FUNCTION reject_http_import() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.uid='" + + failUid + + "' THEN RAISE EXCEPTION 'injected persistence failure'; END IF; RETURN NEW; END $$"); + jdbc.execute( + "CREATE TRIGGER reject_http_import BEFORE INSERT ON calendar_resources FOR EACH ROW EXECUTE FUNCTION reject_http_import()"); + try { + var failed = + post( + browser, + "/portability/import/" + preview.token(), + Map.of("_csrf", csrf, "confirmed", "true")); + assertThat(failed.statusCode()).isEqualTo(503); + assertThat(failed.body()) + .contains("href=\"/team/portability/import/" + preview.token() + "\"") + .doesNotContain("injected persistence failure", "DTSTART"); + } finally { + jdbc.execute("DROP TRIGGER reject_http_import ON calendar_resources"); + jdbc.execute("DROP FUNCTION reject_http_import()"); + } + assertThat(calendars.metadataBatch(owner, target, "", 10)).isEmpty(); + assertThat(get(browser, "/portability/import/" + preview.token()).statusCode()) + .isEqualTo(200); + assertThat( + post( + browser, + "/portability/import/" + preview.token(), + Map.of("_csrf", csrf, "confirmed", "true")) + .statusCode()) + .isEqualTo(200); + assertThat(calendars.metadataBatch(owner, target, "", 10)).hasSize(2); + } + } + + @Test + void pendingPreviewsRejectDisabledAccountsAndChangedSecurityGenerations() throws Exception { + var old = auth(owner, true); + var preview = portability.preview(old, collection, event("epoch")); + var staleClient = browser(owner, true); + String staleCsrf = csrf(get(staleClient, "/portability").body()); + jdbc.update("UPDATE accounts SET security_epoch=gen_random_uuid() WHERE id=?", owner); + denied(() -> portability.confirm(old, preview.token(), true)); + denied(() -> portability.confirm(auth(owner, true), preview.token(), true)); + assertThat( + post( + staleClient, + "/portability/import/" + preview.token(), + Map.of("_csrf", staleCsrf, "confirmed", "true")) + .statusCode()) + .isEqualTo(403); + var fresh = auth(owner, true); + var valid = portability.preview(fresh, collection, event("disabled")); + var disabledClient = browser(owner, true); + String disabledCsrf = csrf(get(disabledClient, "/portability").body()); + accounts.disable(owner); + denied(() -> portability.confirm(fresh, valid.token(), true)); + assertThat( + post( + disabledClient, + "/portability/import/" + valid.token(), + Map.of("_csrf", disabledCsrf, "confirmed", "true")) + .statusCode()) + .isEqualTo(403); + assertThat( + jdbc.queryForObject( + "SELECT count(*) FROM calendar_resources WHERE collection_id=?", + Long.class, + collection)) + .isZero(); + } + + @Test + void ordinaryErrorsReturnEditableFormsWithAssociatedFieldsAndPreservedNonsecretValues() + throws Exception { + var administrator = browser(admin, true); + var user = browser(owner, true); + String adminCsrf = csrf(get(administrator, "/admin/accounts/new").body()); + String userCsrf = csrf(get(user, "/collections/new").body()); + var accountError = + post( + administrator, + "/admin/accounts", + Map.of( + "_csrf", + adminCsrf, + "username", + "invalid username", + "displayName", + "Retain display", + "password", + "Never redisplay this password")); + fieldError(accountError, 400, "account-create", "username"); + assertThat(accountError.body()) + .contains("value=\"Retain display\"", "value=\"invalid username\"") + .doesNotContain("Never redisplay this password"); + fieldError( + post( + administrator, + "/admin/accounts", + Map.of( + "_csrf", + adminCsrf, + "username", + "portal-owner", + "displayName", + "Retain display", + "password", + "Never redisplay this password")), + 409, + "account-create", + "username"); + fieldError( + post( + administrator, + "/admin/accounts", + Map.of( + "_csrf", + adminCsrf, + "username", + "new-user", + "displayName", + "", + "password", + "short")), + 400, + "account-create", + "password"); + fieldError( + post( + administrator, + "/admin/accounts/" + owner + "/edit", + Map.of( + "_csrf", + adminCsrf, + "expected", + accounts.find(owner).displayName(), + "displayName", + "")), + 400, + "account-edit", + "displayName"); + var collectionError = + post( + user, + "/collections", + Map.of( + "_csrf", + userCsrf, + "name", + "Retain name", + "description", + "Retain description", + "color", + "invalid", + "component", + "VTODO")); + fieldError(collectionError, 400, "collection-create", "color"); + assertThat(collectionError.body()) + .contains( + "value=\"Retain name\"", + ">Retain description", + "value=\"VTODO\" selected=\"selected\""); + fieldError( + post( + user, + "/collections/" + collection + "/edit", + Map.of( + "_csrf", + userCsrf, + "state", + portal.collection(auth(owner, true), collection).state(), + "name", + "", + "description", + "Retain description")), + 400, + "collection-edit", + "name"); + fieldError( + post(administrator, "/admin/groups", Map.of("_csrf", adminCsrf, "name", "")), + 400, + "group-create", + "name"); + UUID group = groups.create(auth(admin, true), "Form group", Set.of()); + fieldError( + post(administrator, "/admin/groups", Map.of("_csrf", adminCsrf, "name", "Form group")), + 409, + "group-create", + "name"); + fieldError( + post( + administrator, + "/admin/groups/" + group, + Map.of("_csrf", adminCsrf, "expected", "Form group", "name", "x".repeat(201))), + 400, + "group-rename", + "name"); + fieldError( + post( + administrator, + "/admin/groups/" + group + "/members", + Map.of("_csrf", adminCsrf, "username", "missing-account", "confirmed", "true")), + 400, + "member-add", + "username"); + fieldError( + post( + administrator, + "/admin/groups/" + group + "/members", + Map.of("_csrf", adminCsrf, "username", "portal-reader")), + 400, + "member-add", + "confirmed"); + fieldError( + post( + user, + "/shares", + Map.of( + "_csrf", + userCsrf, + "collection", + collection.toString(), + "username", + "missing-account", + "permission", + "READ", + "expected", + "NONE")), + 400, + "direct-add", + "username"); + fieldError( + post( + user, + "/credentials", + Map.of("_csrf", userCsrf, "label", "Retain device", "days", "366")), + 400, + "credential-create", + "days"); + fieldError( + post( + user, + "/credentials", + Map.of("_csrf", userCsrf, "label", "Retain device", "days", "abc")), + 400, + "credential-create", + "days"); + fieldError( + post(user, "/credentials", Map.of("_csrf", userCsrf, "label", "", "days", "90")), + 400, + "credential-create", + "label"); + var preview = portability.preview(auth(owner, true), collection, event("confirmation")); + fieldError( + post(user, "/portability/import/" + preview.token(), Map.of("_csrf", userCsrf)), + 400, + "import-confirm", + "confirmed"); + var primaryOnly = browser(owner, false); + assertThat( + post( + primaryOnly, + "/collections", + Map.of( + "_csrf", + csrf(get(primaryOnly, "/collections").body()), + "name", + "", + "component", + "VEVENT")) + .statusCode()) + .isEqualTo(403); + } + + private static void fieldError( + HttpResponse response, int status, String form, String field) { + assertThat(response.statusCode()).isEqualTo(status); + assertThat(response.body()) + .contains( + "data-error-summary", + "id=\"" + form + "-" + field + "\"", + "aria-describedby=\"" + form + "-" + field + "-error\"", + "id=\"" + form + "-" + field + "-error\"", + "aria-invalid=\"true\""); + assertThat(response.headers().firstValue("Cache-Control").orElse("")).contains("no-store"); + } + + @Test + void administrativeAuditUsesOpaqueTargetsAndMembershipContextWithoutPrivateData() + throws Exception { + UUID created = + administration.create( + auth(admin, true), + "audit-created", + "Private personal label", + "Never record this password"); + administration.edit( + auth(admin, true), created, "Private personal label", "Another private label"); + administration.disable(auth(admin, true), created, true); + UUID group = groups.create(auth(admin, true), "Private group label", Set.of()); + groups.rename(auth(admin, true), group, "Private group label", "Another group label"); + groups.changeMember(auth(admin, true), group, "portal-reader", null, true, true); + groups.changeMember(auth(admin, true), group, null, reader, false, true); + groups.delete(auth(admin, true), group); + for (String action : + List.of( + "ACCOUNT_CREATED", + "ACCOUNT_PROFILE_UPDATED", + "ACCOUNT_DISABLED", + "GROUP_CREATED", + "GROUP_UPDATED", + "GROUP_MEMBER_ADDED", + "GROUP_MEMBER_REMOVED", + "GROUP_DELETED")) { + var event = + administration.audit(auth(admin, true), action, "SUCCESS", "portal-admin", 0).rows(); + assertThat(event).hasSize(1); + var entry = event.getFirst(); + assertThat(entry.actor()).isEqualTo(admin); + assertThat(entry.targetType()).isEqualTo(action.startsWith("ACCOUNT") ? "ACCOUNT" : "GROUP"); + assertThat(entry.targetId()).isEqualTo(action.startsWith("ACCOUNT") ? created : group); + assertThat(entry.time()).isNotNull(); + assertThat(entry.relatedAccount()) + .isEqualTo(action.startsWith("GROUP_MEMBER_") ? reader : null); + } + var historical = + administration.audit(auth(admin, true), "COLLECTION_CREATED", "", "", 0).rows().getFirst(); + assertThat(historical.targetType()).isNull(); + assertThat(historical.targetId()).isNull(); + var response = get(browser(admin, true), "/admin/audit"); + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.body()) + .contains( + created.toString(), group.toString(), "Not recorded (historical or untargeted event)") + .doesNotContain( + "Never record this password", + "Private personal label", + "Another private label", + "Private group label", + "Another group label", + hostile, + "DTSTART", + collection.toString()); + assertThat(get(browser(owner, true), "/admin/audit").statusCode()).isEqualTo(403); + } + + @Test + void targetedAuditFailureRollsBackTheAdministrativeMutation() { + var original = accounts.find(owner); + jdbc.execute( + "CREATE FUNCTION reject_admin_audit() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.action='ACCOUNT_PROFILE_UPDATED' THEN RAISE EXCEPTION 'injected audit failure'; END IF; RETURN NEW; END $$"); + jdbc.execute( + "CREATE TRIGGER reject_admin_audit BEFORE INSERT ON security_audit FOR EACH ROW EXECUTE FUNCTION reject_admin_audit()"); + try { + assertThatThrownBy( + () -> + administration.edit( + auth(admin, true), owner, original.displayName(), "Must roll back")) + .isInstanceOf(org.springframework.dao.DataAccessException.class); + assertThat(accounts.find(owner).displayName()).isEqualTo(original.displayName()); + assertThat( + administration.audit(auth(admin, true), "ACCOUNT_PROFILE_UPDATED", "", "", 0).rows()) + .isEmpty(); + } finally { + jdbc.execute("DROP TRIGGER reject_admin_audit ON security_audit"); + jdbc.execute("DROP FUNCTION reject_admin_audit()"); + } } @Test @@ -463,6 +1259,30 @@ void browserMutationsRequireCsrfAndServerConfirmation() throws Exception { assertThat(created.headers().firstValue("Location").orElse("")).contains("/team/collections/"); } + @Test + void multipartUploadsAreRejectedOutsideTheReservedPortabilityRoute() throws Exception { + var client = browser(owner, true); + String boundary = "BusyStackOutsideRoute"; + String body = + "--" + + boundary + + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"unused.ics\"\r\n\r\nprivate fixture\r\n--" + + boundary + + "--\r\n"; + for (String route : + List.of("/login", "/collections", "/credentials", "/dav/calendars/unused.ics")) { + var response = + client.send( + HttpRequest.newBuilder(URI.create(base() + route)) + .header("Content-Type", "multipart/form-data; boundary=" + boundary) + .POST(HttpRequest.BodyPublishers.ofString(body)) + .build(), + HttpResponse.BodyHandlers.ofString()); + assertThat(response.statusCode()).isEqualTo(415); + assertThat(response.body()).doesNotContain("private fixture"); + } + } + @Test void multipartAdmissionChecksRealBytesSizeAndDestinationWithoutLeakingContent() throws Exception { var browser = browser(owner, true); @@ -478,12 +1298,12 @@ void multipartAdmissionChecksRealBytesSizeAndDestinationWithoutLeakingContent() assertThat(invalid.body()) .contains("/team/assets/account.css") .doesNotContain("", "../../unsafe.ics"); - var oversized = upload(browser, csrf, collection, "large.ics", new byte[8 * 1024 * 1024 + 1]); + var oversized = upload(browser, csrf, collection, "large.ics", new byte[64 * 1024 * 1024 + 1]); assertThat(oversized.statusCode()).isEqualTo(413); assertThat(oversized.body()).contains("/team/assets/account.css", "Upload too large"); assertThat(oversized.headers().firstValue("Cache-Control").orElse("")).contains("no-store"); var oversizedForm = - upload(browser, csrf, collection, "large.ics", new byte[8 * 1024 * 1024 + 1], false); + upload(browser, csrf, collection, "large.ics", new byte[64 * 1024 * 1024 + 1], false); assertThat(oversizedForm.statusCode()).isEqualTo(413); assertThat(oversizedForm.body()).contains("/team/assets/account.css", "Upload too large"); assertThat(problems.recent()) @@ -567,7 +1387,7 @@ void nativeCalendarAndTaskFixturesRoundTripWithoutByteChanges() throws Exception try { exported = Files.readAllBytes(export.path()); } finally { - Files.deleteIfExists(export.path()); + export.close(); } assertThat(exported).isEqualTo(original); UUID target = portal.create(auth(owner, true), "Migrated " + type, type, "", ""); @@ -673,7 +1493,7 @@ private HttpClient browser(UUID id, boolean mfa) throws Exception { private HttpResponse get(HttpClient browser, String path) throws Exception { return browser.send( HttpRequest.newBuilder(URI.create(base() + path)) - .timeout(Duration.ofSeconds(30)) + .timeout(Duration.ofSeconds(660)) .GET() .build(), HttpResponse.BodyHandlers.ofString()); @@ -691,7 +1511,7 @@ private HttpResponse post(HttpClient browser, String path, Map upload( + filename + "\"\r\nContent-Type: text/calendar\r\n\r\n") .getBytes(StandardCharsets.UTF_8)); - body.write(content); - body.write(("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); var request = HttpRequest.newBuilder(URI.create(base() + "/portability/preview")) - .timeout(Duration.ofSeconds(30)) + .timeout(Duration.ofSeconds(660)) .header("Content-Type", "multipart/form-data; boundary=" + boundary) .header("Accept", "text/html") - .POST(HttpRequest.BodyPublishers.ofByteArray(body.toByteArray())); + .POST( + HttpRequest.BodyPublishers.concat( + HttpRequest.BodyPublishers.ofByteArray(body.toByteArray()), + HttpRequest.BodyPublishers.ofByteArray(content), + HttpRequest.BodyPublishers.ofString("\r\n--" + boundary + "--\r\n"))); if (header) request.header("X-CSRF-TOKEN", csrf); return browser.send(request.build(), HttpResponse.BodyHandlers.ofString()); } + private HttpResponse uploadFile( + HttpClient browser, String csrf, UUID destination, java.nio.file.Path file) throws Exception { + String boundary = "BusyStack" + UUID.randomUUID().toString().replace("-", ""); + String head = + "--" + + boundary + + "\r\nContent-Disposition: form-data; name=\"destination\"\r\n\r\n" + + destination + + "\r\n--" + + boundary + + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"export.ics\"\r\nContent-Type: text/calendar\r\n\r\n"; + return browser.send( + HttpRequest.newBuilder(URI.create(base() + "/portability/preview")) + .timeout(Duration.ofSeconds(660)) + .header("Content-Type", "multipart/form-data; boundary=" + boundary) + .header("X-CSRF-TOKEN", csrf) + .POST( + HttpRequest.BodyPublishers.concat( + HttpRequest.BodyPublishers.ofString(head), + HttpRequest.BodyPublishers.ofFile(file), + HttpRequest.BodyPublishers.ofString("\r\n--" + boundary + "--\r\n"))) + .build(), + HttpResponse.BodyHandlers.ofString()); + } + private String base() { return "https://localhost:" + port + "/team"; } diff --git a/src/test/java/org/busystack/caldav/protocol/IndependentClientIT.java b/src/test/java/org/busystack/caldav/protocol/IndependentClientIT.java index 281b705..0ccdbc9 100644 --- a/src/test/java/org/busystack/caldav/protocol/IndependentClientIT.java +++ b/src/test/java/org/busystack/caldav/protocol/IndependentClientIT.java @@ -147,7 +147,7 @@ void independentPythonCalendarAndTaskClientUsesActualHttpsPostgresqlServer() thr .isFalse(); Files.copy(download.path(), privateDirectory.resolve(name + ".ics")); } finally { - Files.deleteIfExists(download.path()); + download.close(); } } Files.createFile(privateDirectory.resolve("export-complete")); diff --git a/src/test/java/org/busystack/caldav/sharing/GroupServiceIT.java b/src/test/java/org/busystack/caldav/sharing/GroupServiceIT.java index 70beea2..f95b812 100644 --- a/src/test/java/org/busystack/caldav/sharing/GroupServiceIT.java +++ b/src/test/java/org/busystack/caldav/sharing/GroupServiceIT.java @@ -70,6 +70,61 @@ void prepare() { calendar = calendars.createCollection(owner, "Shared calendar", "VEVENT"); } + @Test + void replacementMembershipAuditIdentifiesEveryActualDeltaAndRollsBackWithMutation() { + UUID id = group("Audit delta", Set.of("bob")); + groups.update(auth(administrator, true), id, "Audit delta", Set.of("carol")); + groups.grant(auth(owner, true), calendar, id, "READ"); + assertThat( + jdbc.queryForObject( + "SELECT account_id FROM security_audit WHERE target_id=? AND action='GROUP_SHARING_CHANGED'", + UUID.class, + id)) + .isEqualTo(owner); + assertThat( + jdbc.queryForList( + "SELECT related_account_id FROM security_audit WHERE target_id=? AND action='GROUP_MEMBER_ADDED' ORDER BY id", + UUID.class, + id)) + .containsExactly(bob, carol); + assertThat( + jdbc.queryForList( + "SELECT related_account_id FROM security_audit WHERE target_id=? AND action='GROUP_MEMBER_REMOVED'", + UUID.class, + id)) + .containsExactly(bob); + assertThat( + jdbc.queryForObject( + "SELECT count(*) FROM security_audit WHERE target_id=? AND action<>'GROUP_SHARING_CHANGED' AND (account_id<>? OR outcome<>'SUCCESS' OR target_type<>'GROUP' OR peer_hash IS NOT NULL)", + Long.class, + id, + administrator)) + .isZero(); + jdbc.execute( + "CREATE FUNCTION reject_membership_audit() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.action='GROUP_MEMBER_REMOVED' THEN RAISE EXCEPTION 'injected audit failure'; END IF; RETURN NEW; END $$"); + jdbc.execute( + "CREATE TRIGGER reject_membership_audit BEFORE INSERT ON security_audit FOR EACH ROW EXECUTE FUNCTION reject_membership_audit()"); + try { + assertThatThrownBy( + () -> groups.update(auth(administrator, true), id, "Must roll back", Set.of("bob"))) + .isInstanceOf(org.springframework.dao.DataAccessException.class); + assertThat(groups.detail(auth(administrator, true), id).name()).isEqualTo("Audit delta"); + assertThat(groups.members(auth(administrator, true), id, "", 0).rows()) + .singleElement() + .extracting(GroupService.MemberView::account) + .isEqualTo(carol); + assertThat( + jdbc.queryForList( + "SELECT related_account_id FROM security_audit WHERE target_id=? AND action='GROUP_MEMBER_ADDED' ORDER BY id", + UUID.class, + id)) + .containsExactly(bob, carol); + } finally { + jdbc.execute("DROP TRIGGER reject_membership_audit ON security_audit"); + jdbc.execute("DROP FUNCTION reject_membership_audit()"); + } + } + private Authentication auth(UUID id, boolean mfa) { var account = accounts.find(id); List authorities = new ArrayList<>(); @@ -100,6 +155,84 @@ private void denied(Runnable operation) { .isInstanceOfAny(AccessDeniedException.class, StoreException.class); } + @Test + void nameOnlyChangesPreserveBindingsPermissionsAndStableAndContinuationTokens() { + UUID group = group("Team", Set.of("bob", "carol")); + groups.grant(auth(owner, true), calendar, group, "WRITE"); + dav.putResource(owner, calendar, "a.ics", event("a"), WriteCondition.create()); + dav.putResource(owner, calendar, "b.ics", event("b"), WriteCondition.create()); + String stable = calendars.currentSyncToken(bob, calendar); + String continuation = calendars.sync(carol, calendar, "", 1).token(); + var bindings = + jdbc.queryForList( + "SELECT home_id,path,collection_id,display_name FROM dav_bindings WHERE collection_id=? ORDER BY home_id", + calendar); + groups.rename(auth(administrator, true), group, "Team", "Renamed"); + assertThat(groups.detail(auth(administrator, true), group).name()).isEqualTo("Renamed"); + assertThat(groups.detail(auth(administrator, true), group).members()).isEqualTo(2); + assertThat(calendars.currentSyncToken(bob, calendar)).isEqualTo(stable); + assertThat(calendars.sync(bob, calendar, stable, 10).changes()).isEmpty(); + assertThat(calendars.sync(carol, calendar, continuation, 10).changes()).hasSize(1); + assertThat( + jdbc.queryForList( + "SELECT home_id,path,collection_id,display_name FROM dav_bindings WHERE collection_id=? ORDER BY home_id", + calendar)) + .isEqualTo(bindings); + assertThat(dav.permission(bob, calendar)).isEqualTo("WRITE"); + assertThat(dav.permission(carol, calendar)).isEqualTo("WRITE"); + assertThat(calendars.get(bob, calendar, "a.ics").content()).isEqualTo(event("a")); + assertThatThrownBy(() -> groups.rename(auth(administrator, true), group, "Team", "Stale")) + .isInstanceOf(StoreException.class); + groups.update(auth(administrator, true), group, "Replacement name", Set.of("bob", "carol")); + assertThat(calendars.currentSyncToken(bob, calendar)).isEqualTo(stable); + groups.changeMember(auth(administrator, true), group, null, carol, false, true); + assertThat(calendars.currentSyncToken(bob, calendar)).isNotEqualTo(stable); + denied(() -> calendars.sync(bob, calendar, stable, 10)); + denied(() -> calendars.get(carol, calendar, "a.ics")); + String afterRemoval = calendars.currentSyncToken(bob, calendar); + groups.changeMember(auth(administrator, true), group, "carol", null, true, true); + assertThat(calendars.currentSyncToken(bob, calendar)).isNotEqualTo(afterRemoval); + assertThat(calendars.get(carol, calendar, "a.ics").content()).isEqualTo(event("a")); + } + + @Test + void simultaneousRenamesUseExpectedNameAndMembershipMutationRemainsSerialized() throws Exception { + UUID group = group("Team", Set.of("bob")); + groups.grant(auth(owner, true), calendar, group, "READ"); + String token = calendars.currentSyncToken(bob, calendar); + try (var workers = java.util.concurrent.Executors.newFixedThreadPool(3)) { + var start = new java.util.concurrent.CountDownLatch(1); + var rename = + (java.util.concurrent.Callable) + () -> { + start.await(); + try { + groups.rename( + auth(administrator, true), group, "Team", UUID.randomUUID().toString()); + return true; + } catch (StoreException stale) { + assertThat(stale.kind()).isEqualTo(StoreException.Kind.PRECONDITION); + return false; + } + }; + var one = workers.submit(rename); + var two = workers.submit(rename); + var membership = + workers.submit( + () -> { + start.await(); + groups.changeMember(auth(administrator, true), group, "carol", null, true, true); + return true; + }); + start.countDown(); + assertThat(java.util.List.of(one.get(), two.get())).containsExactlyInAnyOrder(true, false); + assertThat(membership.get()).isTrue(); + } + assertThat(groups.detail(auth(administrator, true), group).members()).isEqualTo(2); + assertThat(dav.permission(carol, calendar)).isEqualTo("READ"); + assertThat(calendars.currentSyncToken(bob, calendar)).isNotEqualTo(token); + } + @Test void individualGrantListingIsOwnerScopedAndDisabledTargetsCanBeRevoked() { management.share(auth(owner, true), calendar, "bob", "READ"); diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties index cfc0b3e..067a211 100644 --- a/src/test/resources/application.properties +++ b/src/test/resources/application.properties @@ -1,2 +1,5 @@ # Real embedded HTTP/TLS fixtures are local, including tests that use demonstration accounts. server.address=127.0.0.1 + +# Each cached test application owns a distinct private staging directory. +busystack.portability.directory=${java.io.tmpdir}/busystack-test-${random.uuid} From af8d81e2123d94d9a72db89e414b02e31f9e88c6 Mon Sep 17 00:00:00 2001 From: albert Date: Tue, 3 Nov 2026 18:18:16 -0700 Subject: [PATCH 09/82] Terminate safely on actual JVM allocation failure Use the official ExitOnOutOfMemoryError option in container and supported JAR launch commands so fatal allocation failure cannot leave a live process with partially established reservation or confirmation state. Keep PostgreSQL atomicity and the explicit restart/orphan-cleanup policy. Add a real bounded 16 MiB allocation-failure positive control, requiring JVM exit code 3, and check the deployed entrypoint policy. The actual selected unmodified Java 25 runtime passed the probe; distribution, release and passkey tooling checks passed. Complete final-commit qualification is rerun after this change. --- Dockerfile | 2 +- docs/operations.md | 12 ++++++++++-- docs/portability.md | 6 ++++++ qualification/portability/README.md | 9 +++++++++ .../portability/temporary_storage.py | 19 +++++++++++++++++-- 5 files changed, 43 insertions(+), 5 deletions(-) diff --git a/Dockerfile b/Dockerfile index 30f063b..4f7b465 100644 --- a/Dockerfile +++ b/Dockerfile @@ -16,4 +16,4 @@ ENV SERVER_ADDRESS=0.0.0.0 RUN groupadd --gid 10001 busystack && useradd --uid 10001 --gid 10001 --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin busystack && chown -R 10001:10001 /opt/busystack USER 10001:10001 EXPOSE 8080 -ENTRYPOINT ["java", "-XX:MaxRAMPercentage=40.0", "-Djava.io.tmpdir=/tmp", "-jar", "/opt/busystack/application.jar"] +ENTRYPOINT ["java", "-XX:MaxRAMPercentage=40.0", "-XX:+ExitOnOutOfMemoryError", "-Djava.io.tmpdir=/tmp", "-jar", "/opt/busystack/application.jar"] diff --git a/docs/operations.md b/docs/operations.md index 0b54df3..93ef239 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -22,7 +22,7 @@ docker compose pull docker compose up -d --no-build --wait ``` -For the JAR alternative, download and checksum `caldav-server-@VERSION@.jar`, use Java 25 (selected Temurin 25.0.5+8) and PostgreSQL 18.6 with a dedicated non-superuser owner role, file-backed Spring config-tree credentials, loopback HTTP and an HTTPS reverse proxy. Substitute its absolute downloaded path for `target/caldav-server-@VERSION@.jar` in command examples below. No native service manager or database installer is supplied. +For the JAR alternative, download and checksum `caldav-server-@VERSION@.jar`, use Java 25 (selected Temurin 25.0.5+8), launch with `-XX:+ExitOnOutOfMemoryError`, and use PostgreSQL 18.6 with a dedicated non-superuser owner role, file-backed Spring config-tree credentials, loopback HTTP and an HTTPS reverse proxy. Substitute its absolute downloaded path for `target/caldav-server-@VERSION@.jar` in command examples below. No native service manager or database installer is supplied. The portability directory defaults to `${java.io.tmpdir}/busystack-portability`, owned by the application user with mode 0700 (files 0600). Standalone operators @@ -35,6 +35,14 @@ ledger reserves at most 272 MiB, including multipart buffers, retained previews, active exports and parser indexes; cleanup failures retain their reservations. See [portability](portability.md) for precise bounds and retry behavior. +The supported launch policy terminates the JVM on a real allocation failure using +Java's `-XX:+ExitOnOutOfMemoryError`. This prevents a damaged live process from +retaining unusable in-memory reservations or confirmation claims. Compose restarts +the application; standalone operators must restart the JAR. PostgreSQL still +controls transaction commit/rollback, pending preview tokens are invalid after +restart, and recognized private-file remnants are cleaned at startup. A stopped +standalone JAR cannot remove those files before its next start. + ## Developer build and verification Install Java 25 and `unzip`, then use the checked-in wrapper. Keep `.mvn/jvm.config` in the checkout: it pins the build JVM to UTC so executable JAR timestamp metadata is reproducible across host timezones. It does not change application timezone semantics. @@ -165,7 +173,7 @@ The metadata URL follows [RFC 8414 §3](https://www.rfc-editor.org/rfc/rfc8414.h There is no default administrator password or unauthenticated setup endpoint. The local bootstrap command requires an empty account database, a private owner-only password file, and `--spring.main.web-application-type=none`. Use the executable JAR with database configuration supplied securely through environment/configuration: ```sh -java -jar target/caldav-server-@VERSION@.jar \ +java -XX:+ExitOnOutOfMemoryError -jar target/caldav-server-@VERSION@.jar \ --spring.main.web-application-type=none \ --busystack.bootstrap=true \ --busystack.bootstrap-username=administrator \ diff --git a/docs/portability.md b/docs/portability.md index 14f65dc..cb9a0de 100644 --- a/docs/portability.md +++ b/docs/portability.md @@ -95,6 +95,12 @@ private directory; it preserves unrelated files and refuses unexpected unsafe entries. A stopped standalone JAR cannot delete files: the next startup cleans crash remnants. Compose's `/tmp` tmpfs also disappears when the container stops. The deployment remains a single application instance. +The supported container and standalone launch commands use +`-XX:+ExitOnOutOfMemoryError`: actual allocation failure terminates the JVM rather +than leaving a live process with partially established in-memory work state. +Compose restarts it; a standalone operator restarts the JAR. Pending previews +then become invalid and startup cleanup applies. Ordinary database rollback +continues to preserve a valid preview for retry without restarting. ## Processing and deployment limits diff --git a/qualification/portability/README.md b/qualification/portability/README.md index 3dd63a8..2e79870 100644 --- a/qualification/portability/README.md +++ b/qualification/portability/README.md @@ -51,3 +51,12 @@ verifies the old preview is invalid and a fresh import commits exactly two items The fixture removes its trigger/function and writes an image-bound interruption receipt. No production endpoint, authentication bypass or durable preview recovery is added. This differs from merely seeding orphan files for startup cleanup. + +The storage fixture also verifies the supported fatal allocation-failure policy: +its own tiny Java program really exhausts a 16 MiB heap and must terminate with +exit code 3 under the same `-XX:+ExitOnOutOfMemoryError` option used by the image +and standalone command. This is a passing positive control only when that exit +is observed. The subsequent standalone startup removes the recognized private +remnants. Actual in-flight transaction interruption is verified separately by +`--portability-crash`; the memory probe does not claim to reproduce a full portal +import under artificial heap pressure. diff --git a/qualification/portability/temporary_storage.py b/qualification/portability/temporary_storage.py index 2ed3b1e..d16db11 100644 --- a/qualification/portability/temporary_storage.py +++ b/qualification/portability/temporary_storage.py @@ -40,6 +40,16 @@ def ready(base, process): raise RuntimeError('Standalone JAR readiness deadline exceeded') +def memory_failure_probe(java_home, directory): + """Actual bounded HotSpot allocation failure, rather than a manually thrown Error.""" + source = directory / 'HeapExhaustionProbe.java' + source.write_text('public final class HeapExhaustionProbe { public static void main(String[] args) { var retained = new java.util.ArrayList(); for (;;) retained.add(new byte[1024 * 1024]); } }\n') + subprocess.run([str(java_home.resolve() / 'bin/javac'), '-d', str(directory), str(source)], check=True, capture_output=True, timeout=30) + result = subprocess.run([str(java_home.resolve() / 'bin/java'), '-Xmx16m', '-XX:+ExitOnOutOfMemoryError', '-cp', str(directory), 'HeapExhaustionProbe'], capture_output=True, text=True, timeout=30) + assert result.returncode == 3, 'The selected JVM must terminate on actual allocation failure' + return {'exitCode': result.returncode, 'heapLimitBytes': 16 * 1024 * 1024, 'policy': '-XX:+ExitOnOutOfMemoryError', 'actualAllocationFailure': True} + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--application-image', required=True) @@ -72,6 +82,7 @@ def main(): application = operations.compose(env, 'ps', '--quiet', 'application') state = json.loads(operations.execute(['docker', 'inspect', application], env))[0] assert state['HostConfig']['ReadonlyRootfs'] + assert '-XX:+ExitOnOutOfMemoryError' in state['Config']['Entrypoint'] assert '/tmp' in state['HostConfig']['Tmpfs'] blocks, block_size = map(int, operations.compose(env, 'exec', '-T', 'application', 'stat', '-f', '-c', '%b %S', '/tmp').split()) assert blocks * block_size == 384 * 1024 * 1024 @@ -93,7 +104,7 @@ def main(): SPRING_DATASOURCE_URL='jdbc:postgresql://' + database + '/busystack', SPRING_DATASOURCE_USERNAME='busystack', SERVER_PORT=str(port), SERVER_ADDRESS='127.0.0.1', BUSYSTACK_PUBLIC_BASE_URL=f'https://localhost:{port}', BUSYSTACK_ISSUER=f'https://localhost:{port}') - command = [str(args.java_home.resolve() / 'bin/java'), '-Xmx256m', '-Djava.io.tmpdir=' + str(temp), '-jar', str(args.jar.resolve())] + command = [str(args.java_home.resolve() / 'bin/java'), '-Xmx256m', '-XX:+ExitOnOutOfMemoryError', '-Djava.io.tmpdir=' + str(temp), '-jar', str(args.jar.resolve())] with (root / 'standalone.log').open('wb') as log: process = subprocess.Popen(command, env=jar_env, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT) ready(f'http://127.0.0.1:{port}', process) @@ -111,6 +122,10 @@ def main(): process.kill() assert process.wait(timeout=30) == -9 assert orphan.exists() and multipart.exists(), 'Standalone remnants remain until application startup' + probe_directory = root / 'memory-probe' + probe_directory.mkdir(mode=0o700) + memory_probe = memory_failure_probe(args.java_home, probe_directory) + assert orphan.exists() and multipart.exists() process = subprocess.Popen(command, env=jar_env, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT) ready(f'http://127.0.0.1:{port}', process) assert not orphan.exists() and not multipart.exists() @@ -121,7 +136,7 @@ def main(): composeReadOnly=True, composeTmpfsBytes=384 * 1024 * 1024, composeForcedTerminationClean=True, standaloneForcedTerminationRemnantsObserved=True, standaloneStartupOrphansRemoved=True, unrelatedFilePreserved=True, - directoryMode='0700', seededFileMode='0600', gracefulShutdown=True, + directoryMode='0700', seededFileMode='0600', gracefulShutdown=True, memoryFailureProbe=memory_probe, scope='Real packaged startup/shutdown; seeded crash remnants. HTTP imports and transaction interruption are separate tests.') args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(result, indent=2) + '\n') From 48cd5723c9d872ce6864f0eb2f9c7fdc66710b9c Mon Sep 17 00:00:00 2001 From: albert Date: Tue, 3 Nov 2026 18:33:58 -0700 Subject: [PATCH 10/82] Retain multipart reservations until private buffers are deleted --- docs/portability.md | 3 + qualification/passkeys/groups.mjs | 7 ++ .../caldav/management/PortabilityStorage.java | 57 ++++++++++++-- .../config/PortabilityWorkFilterTest.java | 20 +++++ .../management/PortabilityStorageTest.java | 76 +++++++++++++++++++ 5 files changed, 156 insertions(+), 7 deletions(-) diff --git a/docs/portability.md b/docs/portability.md index cb9a0de..557ce2f 100644 --- a/docs/portability.md +++ b/docs/portability.md @@ -127,6 +127,9 @@ reconstructed resource retains the existing parser limits (2,000 components, 20,000 properties, 40,000 parameters) and recurrence/timezone validation bounds. The item, file, index and deadline bounds also limit total file-processing work. +Multipart buffer reservations remain charged through deletion, including early +security rejection. Cleanup waits until no synchronous upload can still read a +part; failed deletion retains capacity and is retried with other cleanup. Capacity is reserved before multipart parsing or processing, transferred to retained files and released only after deletion. Two maximum uploads cannot run together. Retained previews may prevent an otherwise allowed operation: 503 with diff --git a/qualification/passkeys/groups.mjs b/qualification/passkeys/groups.mjs index ec578e7..28e79bf 100644 --- a/qualification/passkeys/groups.mjs +++ b/qualification/passkeys/groups.mjs @@ -50,6 +50,13 @@ export async function qualifyGroups(page,base,privateValues) { await captureWorkflow(page,'group-detail'); const collection=await openCollection(page,base,'Browser-qualified tasks'); await page.goto(base+'/collections/'+collection+'/sharing'); + const direct=page.locator(`form[action="${prefix}/shares"]`).filter({has:page.locator('input[name=username]:not([type=hidden])')}); + await direct.locator('..').locator('summary').click(); + await direct.locator('[name=username]').fill('missing-account'); + await direct.locator('[name=permission]').selectOption('WRITE'); + await expectFieldError(page,direct,'username',400,'direct-sharing'); + assert.equal(await direct.locator('[name=username]').inputValue(),'missing-account'); + assert.equal(await direct.locator('[name=permission]').inputValue(),'WRITE'); const sharing=page.locator(`form[action="${prefix}/group-shares"]`).filter({has:page.locator('select[name=group]')}); await sharing.locator('..').locator('summary').click(); await sharing.locator('select[name=group]').selectOption(group); diff --git a/src/main/java/org/busystack/caldav/management/PortabilityStorage.java b/src/main/java/org/busystack/caldav/management/PortabilityStorage.java index 7c8deb2..261b7af 100644 --- a/src/main/java/org/busystack/caldav/management/PortabilityStorage.java +++ b/src/main/java/org/busystack/caldav/management/PortabilityStorage.java @@ -28,7 +28,8 @@ public final class PortabilityStorage implements AutoCloseable { private final Semaphore operations = new Semaphore(2); private final Set files = new HashSet<>(); private final ThreadLocal current = new ThreadLocal<>(); - private long reserved; + private long reserved, multipartPending; + private int uploads; public PortabilityStorage( @Value("${busystack.portability.directory:${java.io.tmpdir}/busystack-portability}") @@ -100,7 +101,7 @@ public Path multipartDirectory() throws IOException { } public Work begin(boolean upload) { - if (current.get() != null) return new Work(false, 0); + if (current.get() != null) return new Work(false, 0, false); long bytes = upload ? UPLOAD_BYTES + FILE_BYTES + INDEX_BYTES : FILE_BYTES; if (!operations.tryAcquire()) throw new CapacityException(); synchronized (this) { @@ -109,27 +110,41 @@ public Work begin(boolean upload) { throw new CapacityException(); } reserved += bytes; + if (upload) uploads++; } - var work = new Work(true, bytes); + var work = new Work(true, bytes, upload); current.set(work); return work; } public final class Work implements AutoCloseable { - private final boolean owner; + private final boolean owner, upload; private long remaining; + private boolean finished; - private Work(boolean owner, long remaining) { + private Work(boolean owner, long remaining, boolean upload) { this.owner = owner; this.remaining = remaining; + this.upload = upload; } @Override public void close() { if (!owner) return; synchronized (PortabilityStorage.this) { - reserved -= remaining; - remaining = 0; + if (finished) return; + finished = true; + if (upload) { + uploads--; + long retained = Math.min(UPLOAD_BYTES, remaining); + multipartPending += retained; + reserved -= remaining - retained; + remaining = 0; + cleanupMultipart(); + } else { + reserved -= remaining; + remaining = 0; + } } current.remove(); operations.release(); @@ -201,6 +216,32 @@ public void close() { } } + /** No request can still read a part once all synchronous upload work has returned. */ + private void cleanupMultipart() { + if (uploads != 0 || multipartPending == 0) return; + Path directory = root.resolve("multipart"); + try { + if (!Files.notExists(directory, LinkOption.NOFOLLOW_LINKS)) { + if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) + throw new IOException("Invalid multipart directory"); + try (var entries = Files.newDirectoryStream(directory)) { + for (Path entry : entries) { + if (Files.notExists(entry, LinkOption.NOFOLLOW_LINKS)) continue; + if (!entry.getFileName().toString().matches("upload_[A-Za-z0-9_-]+\\.tmp") + || !Files.isRegularFile(entry, LinkOption.NOFOLLOW_LINKS)) + throw new IOException("Unexpected multipart entry"); + Files.deleteIfExists(entry); + } + } + } + reserved -= multipartPending; + multipartPending = 0; + } catch (IOException | RuntimeException failure) { + org.slf4j.LoggerFactory.getLogger(PortabilityStorage.class) + .warn("Private multipart cleanup pending"); + } + } + /** Qualification/operator observation contains counts only, never file names or contents. */ public synchronized long usedBytes() throws IOException { long total = 0; @@ -223,11 +264,13 @@ public synchronized long reservedBytes() { @Scheduled(fixedDelay = 30000) public synchronized void cleanup() { for (var file : List.copyOf(files)) if (file.deleting) file.close(); + cleanupMultipart(); } @PreDestroy public synchronized void close() throws IOException { for (var file : List.copyOf(files)) file.close(); + cleanupMultipart(); lock.release(); lockChannel.close(); } diff --git a/src/test/java/org/busystack/caldav/config/PortabilityWorkFilterTest.java b/src/test/java/org/busystack/caldav/config/PortabilityWorkFilterTest.java index 6ee04b6..22885d2 100644 --- a/src/test/java/org/busystack/caldav/config/PortabilityWorkFilterTest.java +++ b/src/test/java/org/busystack/caldav/config/PortabilityWorkFilterTest.java @@ -13,6 +13,26 @@ class PortabilityWorkFilterTest { @TempDir Path temporary; + @Test + void earlySecurityRejectionRemovesParsedMultipartBuffersBeforeReleasingCapacity() + throws Exception { + try (var storage = new PortabilityStorage(temporary.resolve("private").toString())) { + var multipart = storage.multipartDirectory().resolve("upload_rejected_0001.tmp"); + var filter = new PortabilityWorkFilter(storage); + var response = new MockHttpServletResponse(); + filter.doFilter( + request("/team", "/portability/preview", "multipart/form-data; boundary=fixture"), + response, + (req, res) -> { + java.nio.file.Files.writeString(multipart, "private rejected upload"); + ((jakarta.servlet.http.HttpServletResponse) res).sendError(403); + }); + assertThat(response.getStatus()).isEqualTo(403); + assertThat(multipart).doesNotExist(); + assertThat(storage.reservedBytes()).isZero(); + } + } + @Test void unsupportedMultipartSurfacesNeverReachParsingOrAuthentication() throws Exception { try (var storage = new PortabilityStorage(temporary.resolve("private").toString())) { diff --git a/src/test/java/org/busystack/caldav/management/PortabilityStorageTest.java b/src/test/java/org/busystack/caldav/management/PortabilityStorageTest.java index b2b770b..ba49df8 100644 --- a/src/test/java/org/busystack/caldav/management/PortabilityStorageTest.java +++ b/src/test/java/org/busystack/caldav/management/PortabilityStorageTest.java @@ -12,6 +12,82 @@ class PortabilityStorageTest { @TempDir Path temporary; + @Test + void failedMultipartCleanupKeepsItsCapacityUntilDeletionCanSucceed() throws Exception { + try (var storage = new PortabilityStorage(temporary.resolve("private").toString())) { + Path directory = storage.multipartDirectory(); + Path blocked = directory.resolve("upload_fixture_0001.tmp"); + try (var work = storage.begin(true)) { + Files.createDirectory(blocked); + Files.writeString(blocked.resolve("block"), "fixture"); + } + assertThat(storage.reservedBytes()).isEqualTo(PortabilityStorage.UPLOAD_BYTES); + Files.delete(blocked.resolve("block")); + Files.delete(blocked); + storage.cleanup(); + assertThat(storage.reservedBytes()).isZero(); + } + } + + @Test + void concurrentUploadCleanupNeverDeletesAnotherLiveUploadAndRetainsCompletedBuffers() + throws Exception { + try (var storage = new PortabilityStorage(temporary.resolve("private").toString()); + var pool = Executors.newFixedThreadPool(2)) { + Path directory = storage.multipartDirectory(); + Path first = directory.resolve("upload_first_0001.tmp"), + second = directory.resolve("upload_second_0002.tmp"); + var ready = new CountDownLatch(1); + var otherReady = new CountDownLatch(1); + var finish = new CountDownLatch(1); + var finished = new CountDownLatch(1); + var finishOther = new CountDownLatch(1); + var one = + pool.submit( + () -> { + var work = storage.begin(true); + var data = storage.create(PortabilityStorage.FILE_BYTES); + try (var index = storage.create(PortabilityStorage.INDEX_BYTES)) { + Files.writeString(data.path(), "x"); + data.compact(); + } + Files.writeString(first, "first buffer"); + ready.countDown(); + finish.await(10, TimeUnit.SECONDS); + work.close(); + finished.countDown(); + return data; + }); + var two = + pool.submit( + () -> { + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + try (var work = storage.begin(true)) { + Files.writeString(second, "live buffer"); + otherReady.countDown(); + finishOther.await(10, TimeUnit.SECONDS); + } + return null; + }); + try { + assertThat(otherReady.await(10, TimeUnit.SECONDS)).isTrue(); + finish.countDown(); + assertThat(finished.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(first).exists(); + assertThat(second).exists(); + assertThat(storage.reservedBytes()).isEqualTo(226 * PortabilityStorage.MIB + 1); + } finally { + finish.countDown(); + finishOther.countDown(); + } + one.get().close(); + two.get(); + assertThat(first).doesNotExist(); + assertThat(second).doesNotExist(); + assertThat(storage.reservedBytes()).isZero(); + } + } + @Test void fileCountIsBoundedEvenWhenFilesAreTiny() throws Exception { try (var storage = new PortabilityStorage(temporary.resolve("private").toString())) { From 96c290b0c90a9fcee82d95f6f04d6883df4f93fb Mon Sep 17 00:00:00 2001 From: albert Date: Tue, 3 Nov 2026 19:34:25 -0700 Subject: [PATCH 11/82] Clean exported files when snapshot transactions cannot commit --- docs/portability.md | 3 ++ .../caldav/management/PortabilityService.java | 10 ++++ .../caldav/management/PortalManagementIT.java | 51 +++++++++++++++++++ 3 files changed, 64 insertions(+) diff --git a/docs/portability.md b/docs/portability.md index 557ce2f..a824fd2 100644 --- a/docs/portability.md +++ b/docs/portability.md @@ -14,6 +14,9 @@ temporary file is completed and validated before download success headers are sent. Errors never return a silently incomplete successful export. The download uses `text/calendar; charset=utf-8`, a fixed safe attachment filename and `Cache-Control: no-store`; the file is removed after delivery. +If the snapshot transaction cannot commit, transaction completion discards the +completed file before any download is issued. Failed deletion remains charged to +the shared capacity budget until cleanup succeeds. An empty export snapshot returns to the collection with a notice; no unusable empty interchange file is downloaded. diff --git a/src/main/java/org/busystack/caldav/management/PortabilityService.java b/src/main/java/org/busystack/caldav/management/PortabilityService.java index 6480f11..1278b6a 100644 --- a/src/main/java/org/busystack/caldav/management/PortabilityService.java +++ b/src/main/java/org/busystack/caldav/management/PortabilityService.java @@ -375,6 +375,16 @@ public Export export(Authentication auth, UUID id) throws IOException { length = Files.size(file); } var result = new Export(managed, length, !compatible); + if (org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + org.springframework.transaction.support.TransactionSynchronizationManager + .registerSynchronization( + new org.springframework.transaction.support.TransactionSynchronization() { + @Override + public void afterCompletion(int status) { + if (status != STATUS_COMMITTED) result.close(); + } + }); transferred = true; return result; } finally { diff --git a/src/test/java/org/busystack/caldav/management/PortalManagementIT.java b/src/test/java/org/busystack/caldav/management/PortalManagementIT.java index 7618c41..df33309 100644 --- a/src/test/java/org/busystack/caldav/management/PortalManagementIT.java +++ b/src/test/java/org/busystack/caldav/management/PortalManagementIT.java @@ -94,6 +94,57 @@ void prepare() { "#126A5EFF"); } + @Test + void exportSnapshotCommitFailureReleasesCompletedFileAndReservation() throws Exception { + dav.putResource( + owner, collection, "commit.ics", event("export-commit"), WriteCondition.create()); + long before = portabilityStorage.reservedBytes(); + var completed = new java.util.concurrent.atomic.AtomicReference(); + jdbc.execute( + "CREATE FUNCTION qualification_export_commit_failure() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.action='EXPORT_COMMIT_TEST' THEN RAISE EXCEPTION 'Qualification export commit failure'; END IF; RETURN NEW; END $$"); + jdbc.execute( + "CREATE CONSTRAINT TRIGGER qualification_export_commit_failure AFTER INSERT ON security_audit DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION qualification_export_commit_failure()"); + try { + var tx = new org.springframework.transaction.support.TransactionTemplate(transactions); + tx.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThatThrownBy( + () -> + tx.execute( + status -> { + try { + completed.set(portability.export(auth(owner, true), collection)); + } catch (java.io.IOException failure) { + throw new java.io.UncheckedIOException(failure); + } + assertThat(completed.get().path()).isRegularFile(); + jdbc.update( + "INSERT INTO security_audit(account_id,action,outcome) VALUES (?,'EXPORT_COMMIT_TEST','SUCCESS')", + owner); + return completed.get(); + })) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining("Qualification export commit failure"); + assertThat(completed.get()).isNotNull(); + assertThat(completed.get().path()).doesNotExist(); + assertThat(portabilityStorage.reservedBytes()).isLessThanOrEqualTo(before); + assertThat( + jdbc.queryForObject( + "SELECT count(*) FROM security_audit WHERE action='EXPORT_COMMIT_TEST'", + Long.class)) + .isZero(); + } finally { + jdbc.execute("DROP TRIGGER qualification_export_commit_failure ON security_audit"); + jdbc.execute("DROP FUNCTION qualification_export_commit_failure()"); + if (completed.get() != null) completed.get().close(); + } + try (var successful = portability.export(auth(owner, true), collection)) { + assertThat(successful.path()).isRegularFile(); + assertThat(successful.length()).isPositive(); + } + assertThat(portabilityStorage.reservedBytes()).isLessThanOrEqualTo(before); + } + @Test void invalidRowFormsRetainTheirPageAndMemberFilter() throws Exception { var names = new HashSet(); From 742cdecafb779cf4291f7eaeac6e716ac9529fd0 Mon Sep 17 00:00:00 2001 From: albert Date: Tue, 3 Nov 2026 20:58:35 -0700 Subject: [PATCH 12/82] Select the group mutation form precisely during browser qualification --- qualification/passkeys/groups.mjs | 2 +- qualification/passkeys/run.py | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/qualification/passkeys/groups.mjs b/qualification/passkeys/groups.mjs index 28e79bf..0e0c5ff 100644 --- a/qualification/passkeys/groups.mjs +++ b/qualification/passkeys/groups.mjs @@ -24,7 +24,7 @@ export async function qualifyGroups(page,base,privateValues) { assert.equal(await page.locator('tbody tr').count(),1); assert.equal(await page.getByRole('link',{name:member,exact:true}).count(),1); await page.goto(base+'/admin/groups'); - const create=page.locator(`form[action="${prefix}/admin/groups"]`); + const create=page.locator(`form[method="post"][action="${prefix}/admin/groups"]`); await create.locator('input[name=name]').fill(''); await expectFieldError(page,create,'name',400,'group-create'); await create.locator('input[name=name]').fill('Browser sharing group'); diff --git a/qualification/passkeys/run.py b/qualification/passkeys/run.py index 208e2f9..22f43cd 100644 --- a/qualification/passkeys/run.py +++ b/qualification/passkeys/run.py @@ -357,6 +357,26 @@ def main(): assert "HTTPS_RESTORE_SHARED_RECIPIENT_FRESH_MFA_READ_WRITE_DENIAL_AND_REVOCATION_PASSED" in signals print("PASS: trusted test-CA HTTPS, Chromium virtual CTAP2 enrollment/assertion, password+passkey MFA enforcement, session rotation, persistence across restart, disabled-session/passkey denial.") except Exception: + # Coarse fixture liveness only: never print environment, request bodies or credentials. + for service in ("application", "reverse-proxy") if args.proxy else ("application",): + try: + identifiers = operations.compose(environment, "ps", "--all", "--quiet", service).splitlines() + if not identifiers: + raise RuntimeError("Fixture service unavailable") + state = json.loads(operations.execute(["docker", "inspect", identifiers[0]], environment))[0] + print("QUALIFICATION_SERVICE_STATE=" + json.dumps({ + "service": service, "image": state["Image"], + "status": state["State"]["Status"], "running": state["State"]["Running"], + "oomKilled": state["State"]["OOMKilled"], "exitCode": state["State"]["ExitCode"], + "restartCount": state["RestartCount"], + }, sort_keys=True), flush=True) + except (RuntimeError, subprocess.TimeoutExpired, ValueError, KeyError, IndexError): + print("QUALIFICATION_SERVICE_STATE_UNAVAILABLE=" + service, flush=True) + try: + with tls.opener(directory / "ca.pem").open(base + "/login", timeout=5) as diagnostic: + print("QUALIFICATION_HOST_LOGIN_STATUS=" + str(diagnostic.status), flush=True) + except Exception as diagnostic_failure: + print("QUALIFICATION_HOST_LOGIN_FAILURE=" + type(diagnostic_failure).__name__, flush=True) # Emit only sanitized error diagnostics from this disposable application, before cleanup. try: raw = operations.compose(environment, "logs", "--no-log-prefix", "--tail", "120", "application") From 67a01d5cfd04cd7d5b0257e0a148282e51403a57 Mon Sep 17 00:00:00 2001 From: albert Date: Tue, 3 Nov 2026 21:22:29 -0700 Subject: [PATCH 13/82] Preserve canonical portability entry routes through Nginx --- deployment/nginx-root.conf.example | 1 + deployment/nginx-subpath.conf.example | 1 + docs/operations.md | 2 ++ docs/portability.md | 3 +++ qualification/passkeys/groups.mjs | 26 ++++++++++++------------- qualification/passkeys/proxy.py | 10 ++++++---- qualification/proxy/nginx.conf.template | 11 +++++++++++ 7 files changed, 37 insertions(+), 17 deletions(-) diff --git a/deployment/nginx-root.conf.example b/deployment/nginx-root.conf.example index 05f12ac..bb965db 100644 --- a/deployment/nginx-root.conf.example +++ b/deployment/nginx-root.conf.example @@ -13,6 +13,7 @@ server { proxy_set_header Forwarded ""; proxy_set_header X-Forwarded-Host ""; proxy_set_header X-Forwarded-Proto ""; + location = /portability { proxy_pass http://127.0.0.1:8080; } location = /portability/preview { client_max_body_size 65m; proxy_http_version 1.1; proxy_request_buffering off; proxy_buffering off; proxy_read_timeout 660s; proxy_pass http://127.0.0.1:8080; } location ^~ /portability/ { proxy_http_version 1.1; proxy_request_buffering off; proxy_buffering off; proxy_read_timeout 660s; proxy_pass http://127.0.0.1:8080; } location = /actuator { return 404; } diff --git a/deployment/nginx-subpath.conf.example b/deployment/nginx-subpath.conf.example index 3f92de5..881b826 100644 --- a/deployment/nginx-subpath.conf.example +++ b/deployment/nginx-subpath.conf.example @@ -19,6 +19,7 @@ server { proxy_pass http://127.0.0.1:8080/calendar/.well-known/oauth-authorization-server; } location = /calendar { return 308 https://calendar.example.org/calendar/; } + location = /calendar/portability { proxy_pass http://127.0.0.1:8080; } location = /calendar/portability/preview { client_max_body_size 65m; proxy_http_version 1.1; proxy_request_buffering off; proxy_buffering off; proxy_read_timeout 660s; proxy_pass http://127.0.0.1:8080; } location ^~ /calendar/portability/ { proxy_http_version 1.1; proxy_request_buffering off; proxy_buffering off; proxy_read_timeout 660s; proxy_pass http://127.0.0.1:8080; } location = /actuator { return 404; } diff --git a/docs/operations.md b/docs/operations.md index 93ef239..d7e82f1 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -219,6 +219,8 @@ at `/portability/preview`, preserving any application prefix. The supplied `deployment/nginx-*.conf.example` files include it. DAV continues to use its existing 1 MiB body limit. See [portability](portability.md) for bounded temporary storage, preview expiry, transactional writes and export format. +Retain the examples' exact `/portability` location as well as the processing +prefix; it preserves the portal entry URI and its canonical login redirect. ## Client access and sync compatibility diff --git a/docs/portability.md b/docs/portability.md index a824fd2..c48c235 100644 --- a/docs/portability.md +++ b/docs/portability.md @@ -151,6 +151,9 @@ are rejected at other application routes before buffering. Ordinary DAV 1 MiB an authentication 64 KiB request limits remain unchanged. Supplied root/subpath and qualification proxy fixtures implement this policy. Protect staging, snapshots and backups as described in [operations](operations.md). +Keep the exact `/portability` entry location alongside the processing prefix, +including any application subpath. It forwards the portal URI unchanged and lets +the application's configured public origin govern login redirects. Focused service/HTTPS tests and native fixtures exercise byte-preserving export → import → retrieve comparisons, UID/resource counts, recurrence, tasks, diff --git a/qualification/passkeys/groups.mjs b/qualification/passkeys/groups.mjs index 0e0c5ff..5f50a53 100644 --- a/qualification/passkeys/groups.mjs +++ b/qualification/passkeys/groups.mjs @@ -6,13 +6,13 @@ export async function qualifyGroups(page,base,privateValues) { const prefix=prefixOf(base),member='browsergroupmember',password=randomBytes(32).toString('base64url'); privateValues.push(password); await page.goto(base+'/admin/accounts/new'); - const accountForm=page.locator(`form[action="${prefix}/admin/accounts"]`); + const accountForm=page.locator(`form[method="post"][action="${prefix}/admin/accounts"]`); await accountForm.locator('[name=username]').fill('invalid username'); await accountForm.locator('[name=displayName]').fill('Retain account label'); await accountForm.locator('[name=password]').fill(password); await expectFieldError(page,accountForm,'username',400,'account-create'); assert.equal(await accountForm.locator('[name=displayName]').inputValue(),'Retain account label'); const account=await provisionAccount(page,base,member,'Browser Group Member',password); const display='Group member '; - const profile=page.locator(`form[action="${prefix}/admin/accounts/${account}/edit"]`); + const profile=page.locator(`form[method="post"][action="${prefix}/admin/accounts/${account}/edit"]`); await profile.locator('input[name=displayName]').fill(''); await expectFieldError(page,profile,'displayName',400,'account-edit'); await profile.locator('input[name=displayName]').fill(display); @@ -30,7 +30,7 @@ export async function qualifyGroups(page,base,privateValues) { await create.locator('input[name=name]').fill('Browser sharing group'); await Promise.all([page.waitForURL(/\/admin\/groups\/[a-f0-9-]{36}$/i),create.getByRole('button',{name:'Create group',exact:true}).click()]); const group=new URL(page.url()).pathname.split('/').at(-1); - const add=page.locator(`form[action="${prefix}/admin/groups/${group}/members"]`); + const add=page.locator(`form[method="post"][action="${prefix}/admin/groups/${group}/members"]`); await add.locator('input[name=username]').fill('missing-account');await add.locator('input[name=confirmed]').check(); await expectFieldError(page,add,'username',400,'member-add'); await add.locator('input[name=username]').fill(member);await add.locator('input[name=confirmed]').check(); @@ -41,7 +41,7 @@ export async function qualifyGroups(page,base,privateValues) { assert.equal(await row.count(),0); await add.locator('input[name=username]').fill(member);await add.locator('input[name=confirmed]').check(); await Promise.all([page.waitForURL(base+'/admin/groups/'+group),add.getByRole('button',{name:'Add member',exact:true}).click()]); - const rename=page.locator(`form[action="${prefix}/admin/groups/${group}"]`); + const rename=page.locator(`form[method="post"][action="${prefix}/admin/groups/${group}"]`); await rename.locator('input[name=name]').fill(''); await expectFieldError(page,rename,'name',400,'group-rename'); await rename.locator('input[name=name]').fill('Browser group renamed'); @@ -50,15 +50,15 @@ export async function qualifyGroups(page,base,privateValues) { await captureWorkflow(page,'group-detail'); const collection=await openCollection(page,base,'Browser-qualified tasks'); await page.goto(base+'/collections/'+collection+'/sharing'); - const direct=page.locator(`form[action="${prefix}/shares"]`).filter({has:page.locator('input[name=username]:not([type=hidden])')}); - await direct.locator('..').locator('summary').click(); + const direct=page.locator(`form[method="post"][action="${prefix}/shares"]`).filter({has:page.locator('input[name=username]:not([type=hidden])')}); + if(!await direct.locator('..').evaluate(element=>element.open)) await direct.locator('..').locator('summary').click(); await direct.locator('[name=username]').fill('missing-account'); await direct.locator('[name=permission]').selectOption('WRITE'); await expectFieldError(page,direct,'username',400,'direct-sharing'); assert.equal(await direct.locator('[name=username]').inputValue(),'missing-account'); assert.equal(await direct.locator('[name=permission]').inputValue(),'WRITE'); - const sharing=page.locator(`form[action="${prefix}/group-shares"]`).filter({has:page.locator('select[name=group]')}); - await sharing.locator('..').locator('summary').click(); + const sharing=page.locator(`form[method="post"][action="${prefix}/group-shares"]`).filter({has:page.locator('select[name=group]')}); + if(!await sharing.locator('..').evaluate(element=>element.open)) await sharing.locator('..').locator('summary').click(); await sharing.locator('select[name=group]').selectOption(group); await sharing.locator('select[name=permission]').selectOption('READ'); await Promise.all([page.waitForURL(base+'/collections/'+collection+'/sharing'),sharing.getByRole('button',{name:'Grant group access',exact:true}).click()]); @@ -77,14 +77,14 @@ export async function qualifyGroups(page,base,privateValues) { } assert.equal(await grant.count(),0); await page.goto(base+'/admin/groups/'+group); - const remove=page.locator(`form[action="${prefix}/admin/groups/${group}/delete"]`); + const remove=page.locator(`form[method="post"][action="${prefix}/admin/groups/${group}/delete"]`); await remove.locator('input[name=confirmed]').check(); await Promise.all([page.waitForURL(base+'/admin/groups'),remove.getByRole('button',{name:'Delete group',exact:true}).click()]); assert.equal(await page.getByRole('link',{name:'Browser group renamed',exact:true}).count(),0); await page.goto(base+'/collections/'+collection+'/sharing'); assert.equal(await page.locator(`option[value="${group}"]`).count(),0); await page.goto(base+'/admin/accounts/'+account); - const disable=page.locator(`form[action="${prefix}/admin/accounts/${account}/disable"]`); + const disable=page.locator(`form[method="post"][action="${prefix}/admin/accounts/${account}/disable"]`); await disable.locator('input[name=confirmed]').check(); await Promise.all([page.waitForURL(base+'/admin/accounts/'+account),disable.getByRole('button',{name:'Disable account',exact:true}).click()]); assert.equal(await page.getByText('Disabled',{exact:true}).count(),1); @@ -124,18 +124,18 @@ export async function qualifySharingCapacity(page,administratorPage,base,fixture await Promise.all([page.waitForURL(base+'/collections/'+id+'/sharing'),remove.getByRole('button',{name:'Save group grant',exact:true}).click()]); assert.equal(await rows.count(),50); await administratorPage.goto(base+'/admin/groups/'+fixture.firstGroup); - const rename=administratorPage.locator(`form[action="${prefix}/admin/groups/${fixture.firstGroup}"]`); + const rename=administratorPage.locator(`form[method="post"][action="${prefix}/admin/groups/${fixture.firstGroup}"]`); await rename.locator('input[name=name]').fill('Capacity group updated'); await Promise.all([administratorPage.waitForURL(base+'/admin/groups/'+fixture.firstGroup),rename.getByRole('button',{name:'Save group name',exact:true}).click()]); const member=administratorPage.locator('tbody tr').filter({has:administratorPage.getByText('restorereader',{exact:true})}); await member.locator('input[name=confirmed]').check(); await Promise.all([administratorPage.waitForURL(base+'/admin/groups/'+fixture.firstGroup),member.getByRole('button',{name:'Remove member',exact:true}).click()]); - const add=administratorPage.locator(`form[action="${prefix}/admin/groups/${fixture.firstGroup}/members"]`); + const add=administratorPage.locator(`form[method="post"][action="${prefix}/admin/groups/${fixture.firstGroup}/members"]`); await add.locator('input[name=username]').fill('restorewriter');await add.locator('input[name=confirmed]').check(); await Promise.all([administratorPage.waitForURL(base+'/admin/groups/'+fixture.firstGroup),add.getByRole('button',{name:'Add member',exact:true}).click()]); const members=administratorPage.locator('tbody tr'); assert.equal(await members.count(),1);assert.ok((await members.innerText()).includes('restorewriter')); - const deletion=administratorPage.locator(`form[action="${prefix}/admin/groups/${fixture.firstGroup}/delete"]`); + const deletion=administratorPage.locator(`form[method="post"][action="${prefix}/admin/groups/${fixture.firstGroup}/delete"]`); await deletion.locator('input[name=confirmed]').check(); await Promise.all([administratorPage.waitForURL(base+'/admin/groups'),deletion.getByRole('button',{name:'Delete group',exact:true}).click()]); console.log('BROWSER_12500_GRANTS_PAGINATION_REVOCATION_MEMBERSHIP_AND_GROUP_DELETE_PASSED'); diff --git a/qualification/passkeys/proxy.py b/qualification/passkeys/proxy.py index 0e8ade4..c6cc9ca 100644 --- a/qualification/passkeys/proxy.py +++ b/qualification/passkeys/proxy.py @@ -69,10 +69,12 @@ def call(url, method="GET", headers=None, data=None): assert status == 200 and json.loads(body)["issuer"] == base status, headers, _ = call(base, headers=forged) assert status == 308 and headers["Location"] == base + "/" - status, headers, _ = call(base + "/security/passkeys", headers={**forged, "Accept": "text/html"}) - target = urllib.parse.urlsplit(headers.get("Location", "")) - assert status == 302 and (target.scheme, target.netloc, target.path) == (public.scheme, public.netloc, public.path + "/login"), f"Expected configured browser login redirect; status={status}, location={headers.get('Location')}" - assert urllib.parse.parse_qs(target.query) in ({}, {"factor": ["required"]}) and not target.fragment + for path in ("/security/passkeys", "/portability", "/portability?destination=11111111-1111-4111-8111-111111111111"): + status, headers, _ = call(base + path, headers={**forged, "Accept": "text/html"}) + target = urllib.parse.urlsplit(headers.get("Location", "")) + assert status == 302 and (target.scheme, target.netloc, target.path) == (public.scheme, public.netloc, public.path + "/login"), f"Expected configured browser login redirect for {path}; status={status}, location={headers.get('Location')}" + assert urllib.parse.parse_qs(target.query) in ({}, {"factor": ["required"]}) and not target.fragment + print("PROXY_PORTABILITY_BASE_ROUTE_CANONICAL_LOCATION_PASSED", flush=True) for path in ("/actuator", "/actuator/health", public.path + "/actuator", public.path + "/actuator/health/readiness"): assert call(origin + path)[0] == 404 for method in ("OPTIONS", "PROPFIND", "PROPPATCH", "REPORT", "MKCALENDAR", "MKCOL", "GET", "HEAD", "PUT", "DELETE", "COPY", "MOVE", "ACL"): diff --git a/qualification/proxy/nginx.conf.template b/qualification/proxy/nginx.conf.template index f1853f0..8cc649c 100644 --- a/qualification/proxy/nginx.conf.template +++ b/qualification/proxy/nginx.conf.template @@ -34,6 +34,17 @@ http { proxy_set_header X-Forwarded-Proto ""; proxy_set_header X-Request-ID $request_id; } + location = @@PREFIX@@/portability { + proxy_http_version 1.1; + proxy_connect_timeout 5s; + proxy_read_timeout 120s; + proxy_pass http://application:8080; + proxy_set_header Host @@AUTHORITY@@; + proxy_set_header Forwarded ""; + proxy_set_header X-Forwarded-Host ""; + proxy_set_header X-Forwarded-Proto ""; + proxy_set_header X-Request-ID $request_id; + } location = @@PREFIX@@/portability/preview { client_max_body_size 65m; proxy_http_version 1.1; From 395b7faa4fae0f2a36010cb9d372d02db206aa8f Mon Sep 17 00:00:00 2001 From: albert Date: Tue, 3 Nov 2026 22:39:05 -0700 Subject: [PATCH 14/82] Create servlet multipart buffers with private process permissions --- Dockerfile | 4 +++- docs/operations.md | 13 ++++++++++++- docs/portability.md | 5 ++++- qualification/portability/temporary_storage.py | 14 +++++++++++--- 4 files changed, 30 insertions(+), 6 deletions(-) diff --git a/Dockerfile b/Dockerfile index 4f7b465..2722622 100644 --- a/Dockerfile +++ b/Dockerfile @@ -16,4 +16,6 @@ ENV SERVER_ADDRESS=0.0.0.0 RUN groupadd --gid 10001 busystack && useradd --uid 10001 --gid 10001 --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin busystack && chown -R 10001:10001 /opt/busystack USER 10001:10001 EXPOSE 8080 -ENTRYPOINT ["java", "-XX:MaxRAMPercentage=40.0", "-XX:+ExitOnOutOfMemoryError", "-Djava.io.tmpdir=/tmp", "-jar", "/opt/busystack/application.jar"] +# The shell only establishes private creation modes, then Java remains PID 1. +# Keep each argument separate so bootstrap/recovery arguments pass through unchanged. +ENTRYPOINT ["/bin/sh", "-ec", "umask 077; exec \"$@\"", "busystack", "java", "-XX:MaxRAMPercentage=40.0", "-XX:+ExitOnOutOfMemoryError", "-Djava.io.tmpdir=/tmp", "-jar", "/opt/busystack/application.jar"] diff --git a/docs/operations.md b/docs/operations.md index d7e82f1..11f5396 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -22,7 +22,17 @@ docker compose pull docker compose up -d --no-build --wait ``` -For the JAR alternative, download and checksum `caldav-server-@VERSION@.jar`, use Java 25 (selected Temurin 25.0.5+8), launch with `-XX:+ExitOnOutOfMemoryError`, and use PostgreSQL 18.6 with a dedicated non-superuser owner role, file-backed Spring config-tree credentials, loopback HTTP and an HTTPS reverse proxy. Substitute its absolute downloaded path for `target/caldav-server-@VERSION@.jar` in command examples below. No native service manager or database installer is supplied. +For the JAR alternative, download and checksum `caldav-server-@VERSION@.jar`, use Java 25 (selected Temurin 25.0.5+8), set `umask 077` before launching with `-XX:+ExitOnOutOfMemoryError`, and use PostgreSQL 18.6 with a dedicated non-superuser owner role, file-backed Spring config-tree credentials, loopback HTTP and an HTTPS reverse proxy. Substitute its absolute downloaded path for `target/caldav-server-@VERSION@.jar` in command examples below. No native service manager or database installer is supplied. + +The container sets this private umask before executing Java as PID 1. Standalone +process supervision must likewise use umask 0077 (for example, systemd `UMask=0077`). +This also makes servlet multipart buffers 0600 at creation, independently of their +0700 containing directory. A standalone shell launch is: + +```sh +umask 077 +java -XX:+ExitOnOutOfMemoryError -jar target/caldav-server-@VERSION@.jar +``` The portability directory defaults to `${java.io.tmpdir}/busystack-portability`, owned by the application user with mode 0700 (files 0600). Standalone operators @@ -173,6 +183,7 @@ The metadata URL follows [RFC 8414 §3](https://www.rfc-editor.org/rfc/rfc8414.h There is no default administrator password or unauthenticated setup endpoint. The local bootstrap command requires an empty account database, a private owner-only password file, and `--spring.main.web-application-type=none`. Use the executable JAR with database configuration supplied securely through environment/configuration: ```sh +umask 077 java -XX:+ExitOnOutOfMemoryError -jar target/caldav-server-@VERSION@.jar \ --spring.main.web-application-type=none \ --busystack.bootstrap=true \ diff --git a/docs/portability.md b/docs/portability.md index c48c235..aac0ddf 100644 --- a/docs/portability.md +++ b/docs/portability.md @@ -85,7 +85,10 @@ attachment fetch or alarm execution occurs. All portability and servlet multipart files live beneath an application-controlled private directory, defaulting to `${java.io.tmpdir}/busystack-portability`. Override `busystack.portability.directory` only with a dedicated directory owned by the -application user with mode 0700; staged data files use 0600. This location must not +application user with mode 0700; staged data files use 0600. The container sets +umask 0077 before executing Java, so servlet multipart files also start at 0600. +Standalone JAR supervision must set the same umask; see [operations](operations.md). +This location must not be served by a web server. Paths and random filenames never derive from uploaded names or calendar data. Symbolic-link directories are refused. A process lock prevents two instances sharing the directory. diff --git a/qualification/portability/temporary_storage.py b/qualification/portability/temporary_storage.py index d16db11..518b9fa 100644 --- a/qualification/portability/temporary_storage.py +++ b/qualification/portability/temporary_storage.py @@ -83,6 +83,11 @@ def main(): state = json.loads(operations.execute(['docker', 'inspect', application], env))[0] assert state['HostConfig']['ReadonlyRootfs'] assert '-XX:+ExitOnOutOfMemoryError' in state['Config']['Entrypoint'] + java_command = operations.compose(env, 'exec', '-T', 'application', 'cat', '/proc/1/cmdline').split('\0') + assert java_command[0] == 'java', 'The private-umask launcher must exec Java as PID1' + assert '-XX:+ExitOnOutOfMemoryError' in java_command + status = operations.compose(env, 'exec', '-T', 'application', 'cat', '/proc/1/status') + assert any(line.split() == ['Umask:', '0077'] for line in status.splitlines()), 'The application process must create owner-only multipart files' assert '/tmp' in state['HostConfig']['Tmpfs'] blocks, block_size = map(int, operations.compose(env, 'exec', '-T', 'application', 'stat', '-f', '-c', '%b %S', '/tmp').split()) assert blocks * block_size == 384 * 1024 * 1024 @@ -106,8 +111,9 @@ def main(): BUSYSTACK_PUBLIC_BASE_URL=f'https://localhost:{port}', BUSYSTACK_ISSUER=f'https://localhost:{port}') command = [str(args.java_home.resolve() / 'bin/java'), '-Xmx256m', '-XX:+ExitOnOutOfMemoryError', '-Djava.io.tmpdir=' + str(temp), '-jar', str(args.jar.resolve())] with (root / 'standalone.log').open('wb') as log: - process = subprocess.Popen(command, env=jar_env, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT) + process = subprocess.Popen(command, env=jar_env, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, umask=0o077) ready(f'http://127.0.0.1:{port}', process) + assert any(line.split() == ['Umask:', '0077'] for line in Path('/proc', str(process.pid), 'status').read_text().splitlines()) staging = temp / 'busystack-portability' assert staging.stat().st_mode & 0o777 == 0o700 orphan = staging / ('data-' + str(uuid.uuid4()) + '.private') @@ -126,7 +132,7 @@ def main(): probe_directory.mkdir(mode=0o700) memory_probe = memory_failure_probe(args.java_home, probe_directory) assert orphan.exists() and multipart.exists() - process = subprocess.Popen(command, env=jar_env, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT) + process = subprocess.Popen(command, env=jar_env, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, umask=0o077) ready(f'http://127.0.0.1:{port}', process) assert not orphan.exists() and not multipart.exists() assert unrelated.read_text() == 'preserve unrelated file' @@ -136,7 +142,9 @@ def main(): composeReadOnly=True, composeTmpfsBytes=384 * 1024 * 1024, composeForcedTerminationClean=True, standaloneForcedTerminationRemnantsObserved=True, standaloneStartupOrphansRemoved=True, unrelatedFilePreserved=True, - directoryMode='0700', seededFileMode='0600', gracefulShutdown=True, memoryFailureProbe=memory_probe, + directoryMode='0700', seededFileMode='0600', composeJavaPid1=True, + composeProcessUmask='0077', standaloneProcessUmask='0077', + gracefulShutdown=True, memoryFailureProbe=memory_probe, scope='Real packaged startup/shutdown; seeded crash remnants. HTTP imports and transaction interruption are separate tests.') args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(result, indent=2) + '\n') From 3f74590cd8d22341ae1a496af41377a8521733fa Mon Sep 17 00:00:00 2001 From: albert Date: Wed, 4 Nov 2026 00:31:13 -0700 Subject: [PATCH 15/82] Preserve bounded resource framing across calendar round trips --- docs/portability.md | 19 +++-- .../caldav/calendar/CalendarInterchange.java | 36 +++++--- .../caldav/management/PortabilityService.java | 4 +- .../calendar/CalendarInterchangeTest.java | 51 +++++++++++ .../caldav/management/PortalManagementIT.java | 85 +++++++++++++++++++ 5 files changed, 177 insertions(+), 18 deletions(-) diff --git a/docs/portability.md b/docs/portability.md index aac0ddf..8000df5 100644 --- a/docs/portability.md +++ b/docs/portability.md @@ -20,13 +20,14 @@ the shared capacity budget until cleanup succeeds. An empty export snapshot returns to the collection with a notice; no unusable empty interchange file is downloaded. -For multiple resources with byte-identical calendar headers and embedded timezone -definitions, export produces one VCALENDAR containing all their components. Headers, +For multiple resources with byte-identical calendar headers, embedded timezone +definitions and closing framing, export produces one VCALENDAR containing all their components. Headers, VTIMEZONEs and every event/task component retain their original bytes; only repeated -identical wrappers and timezone definitions are removed. A single resource exports -unchanged. No serializer rewrites recurrence, properties or parameter values. +identical wrappers and timezone definitions are removed. A single resource retains +its calendar content; terminal transport line endings may be completed. No serializer +rewrites recurrence, properties or parameter values. -When headers or timezone definitions differ, combining them could lose calendar +When headers, timezone definitions or closing framing differ, combining them could lose calendar properties or conflate different definitions of the same TZID. Export instead emits a lossless [RFC 5545 §3.4 iCalendar stream](https://www.rfc-editor.org/rfc/rfc5545.html#section-3.4) of complete stored VCALENDAR objects, with a `-stream.ics` filename. A missing final @@ -53,6 +54,14 @@ CalendarAdmission and the existing VEVENT/VTODO validation. All exceptions for a UID remain with the master. Unsupported components and wrong-destination types are reported explicitly. Malformed framing rejects the file before mutation. +The 1 MiB bound applies to each constructed UID resource. If only one or two +terminal CR/LF framing bytes would exceed that bound, the importer uses the +EOF-terminated form already accepted by DAV admission. Component, property and +timezone bytes are not removed. The resulting resource still passes the unchanged +1 MiB validator; a payload that cannot fit without removing calendar information +is rejected. This also preserves round trips for admitted resources exactly at +the limit when an interchange stream adds a line-ending separator. + Preview and actual results show 50 entries per page with whole-file counts. An identical existing UID/resource is **Skipped**. Different content with an existing UID is **Conflicting** and is preserved. Multiple masters or repeated valid UIDs in diff --git a/src/main/java/org/busystack/caldav/calendar/CalendarInterchange.java b/src/main/java/org/busystack/caldav/calendar/CalendarInterchange.java index 6315a16..8b52c62 100644 --- a/src/main/java/org/busystack/caldav/calendar/CalendarInterchange.java +++ b/src/main/java/org/busystack/caldav/calendar/CalendarInterchange.java @@ -76,6 +76,7 @@ public String contextFingerprint() { digest.update(java.nio.ByteBuffer.allocate(4).putInt(header.length).array()); digest.update(header); digest.update(zones); + digest.update(closing); return java.util.HexFormat.of().formatHex(digest.digest()); } catch (java.security.NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); @@ -160,7 +161,23 @@ public Item item(int number, String destination, CalendarAdmission admission) throws java.io.IOException { checkTime(); var s = series.get(number); - long size = s.frame.header.size + s.frame.zones.size + s.parts.size + s.frame.closing.size; + long size = + s.frame.groups == 1 + ? s.frame.end - s.frame.start + : s.frame.header.size + s.frame.zones.size + s.parts.size + s.frame.closing.size; + int framing = 0; + if (size > CalendarContent.MAX_BYTES && size <= CalendarContent.MAX_BYTES + 2L) { + // A calendar file's terminal line ending is transport framing. Use the existing accepted + // EOF-terminated representation if only that framing prevents a UID resource fitting. + // No component/property bytes are omitted, and unchanged admission still runs below. + source.seek(s.frame.end - 1); + int last = source.readUnsignedByte(); + if (last == '\n') { + framing = 1; + source.seek(s.frame.end - 2); + if (source.readUnsignedByte() == '\r') framing = 2; + } else if (last == '\r') framing = 1; + } String rejection = s.duplicate ? "UID occurs in multiple calendar objects; combine its recurrence series before importing" @@ -169,26 +186,23 @@ public Item item(int number, String destination, CalendarAdmission admission) rejection = "Unsupported component type"; else if (!s.type.equals(destination)) rejection = "Does not match the destination collection type"; - else if (size > CalendarContent.MAX_BYTES) + else if (size - framing > CalendarContent.MAX_BYTES) rejection = "UID series exceeds the 1 MiB resource limit"; byte[] content = new byte[0]; String uid = s.uid; if (rejection.isEmpty()) { - var out = new ByteArrayOutputStream((int) size); if (s.frame.groups == 1) { - if (s.frame.end - s.frame.start > CalendarContent.MAX_BYTES) - rejection = "UID series exceeds the 1 MiB resource limit"; - else { - source.seek(s.frame.start); - content = new byte[(int) (s.frame.end - s.frame.start)]; - source.readFully(content); - } + source.seek(s.frame.start); + content = new byte[(int) (size - framing)]; + source.readFully(content); } else { + var out = new ByteArrayOutputStream((int) size); copy(s.frame.header, out); copy(s.frame.zones, out); copy(s.parts, out); copy(s.frame.closing, out); content = out.toByteArray(); + if (framing != 0) content = Arrays.copyOf(content, content.length - framing); } if (rejection.isEmpty()) { try { @@ -314,7 +328,7 @@ public IndexedFile open(java.nio.file.Path input, java.nio.file.Path index, long offset += line.length; String value; try { - value = CalendarParsingInput.decode(line).replaceFirst("[\\r]?\\n$", ""); + value = CalendarParsingInput.decode(line).replaceFirst("(?:\\r?\\n|\\r)$", ""); CalendarTextProfile.validate(value); } catch (java.nio.charset.CharacterCodingException failure) { throw invalid(); diff --git a/src/main/java/org/busystack/caldav/management/PortabilityService.java b/src/main/java/org/busystack/caldav/management/PortabilityService.java index 1278b6a..86f91df 100644 --- a/src/main/java/org/busystack/caldav/management/PortabilityService.java +++ b/src/main/java/org/busystack/caldav/management/PortabilityService.java @@ -345,9 +345,9 @@ public Export export(Authentication auth, UUID id) throws IOException { output.write(body); length += body.length; if (body[body.length - 1] != '\n') { - output.write('\r'); + if (body[body.length - 1] != '\r') output.write('\r'); output.write('\n'); - length += 2; + length += body[body.length - 1] == '\r' ? 1 : 2; } after = resource.name(); } diff --git a/src/test/java/org/busystack/caldav/calendar/CalendarInterchangeTest.java b/src/test/java/org/busystack/caldav/calendar/CalendarInterchangeTest.java index 0ae3fd0..e090ae9 100644 --- a/src/test/java/org/busystack/caldav/calendar/CalendarInterchangeTest.java +++ b/src/test/java/org/busystack/caldav/calendar/CalendarInterchangeTest.java @@ -28,6 +28,57 @@ private static String event(String uid) { @org.junit.jupiter.api.io.TempDir java.nio.file.Path temporary; + @Test + void exportContextsKeepDifferentCalendarClosingBytesDistinct() { + byte[] crlf = bytes(object(event("closing"))); + var fingerprints = new java.util.HashSet(); + for (String ending : java.util.List.of("\r\n", "\n", "", "\r")) { + byte[] resource = + new String(crlf, StandardCharsets.UTF_8) + .replace("END:VCALENDAR\r\n", "END:VCALENDAR" + ending) + .getBytes(StandardCharsets.UTF_8); + assertThat(CalendarContent.parse(resource, "VEVENT").uid()).isEqualTo("closing"); + assertThat(read(resource, "VEVENT").getFirst().content()).isEqualTo(resource); + fingerprints.add(CalendarInterchange.exportParts(resource).contextFingerprint()); + } + assertThat(fingerprints).hasSize(4); + assertThat(CalendarInterchange.exportParts(crlf).contextFingerprint()) + .isEqualTo(CalendarInterchange.exportParts(crlf.clone()).contextFingerprint()); + } + + @Test + void transportLineEndingsNeverIncreaseTheAdmittedResourceLimit() { + String body = object(event("boundary")).replace("END:VCALENDAR\n", "END:VCALENDAR"); + byte[] original = bytes(body); + int padding = CalendarContent.MAX_BYTES - original.length; + original = bytes(body.replace("X-DATA:preserve", "X-DATA:preserve" + "x".repeat(padding))); + assertThat(original).hasSize(CalendarContent.MAX_BYTES); + assertThat(CalendarContent.parse(original, "VEVENT").uid()).isEqualTo("boundary"); + var wire = new java.io.ByteArrayOutputStream(); + wire.writeBytes(original); + wire.writeBytes(bytes("\n")); + byte[] framed = wire.toByteArray(); + assertThatThrownBy(() -> CalendarContent.parse(framed, "VEVENT")) + .isInstanceOf(CalendarValidationException.class); + // Interchange may choose the already accepted EOF-terminated representation. The DAV + // validator and its byte bound stay unchanged; no component/property bytes are removed. + var candidate = read(framed, "VEVENT").getFirst(); + assertThat(candidate.rejection()).isEmpty(); + assertThat(candidate.content()).isEqualTo(original); + wire.writeBytes(bytes(object(event("neighbor")))); + var stream = read(wire.toByteArray(), "VEVENT"); + assertThat(stream).hasSize(2).allSatisfy(item -> assertThat(item.rejection()).isEmpty()); + assertThat(stream.getFirst().content()).isEqualTo(original); + var tooLarge = new java.io.ByteArrayOutputStream(); + tooLarge.writeBytes( + bytes(body.replace("X-DATA:preserve", "X-DATA:preserve" + "x".repeat(padding + 1)))); + tooLarge.writeBytes(bytes("\n")); + tooLarge.writeBytes(bytes(object(event("neighbor")))); + var rejected = read(tooLarge.toByteArray(), "VEVENT"); + assertThat(rejected.getFirst().rejection()).contains("1 MiB"); + assertThat(rejected.getLast().rejection()).isEmpty(); + } + private java.util.List read(byte[] bytes, String component) { var source = temporary.resolve(java.util.UUID.randomUUID() + ".ics"); var index = temporary.resolve(java.util.UUID.randomUUID() + ".index"); diff --git a/src/test/java/org/busystack/caldav/management/PortalManagementIT.java b/src/test/java/org/busystack/caldav/management/PortalManagementIT.java index df33309..36daf31 100644 --- a/src/test/java/org/busystack/caldav/management/PortalManagementIT.java +++ b/src/test/java/org/busystack/caldav/management/PortalManagementIT.java @@ -583,6 +583,91 @@ else if (n % 100 == 0) { return value.getBytes(StandardCharsets.UTF_8); } + @Test + void differentCalendarClosingsPreserveResourceLimitOnHttpRoundTrip() throws Exception { + var client = browser(owner, true); + String csrf = csrf(get(client, "/portability").body()); + int scenario = 0; + for (String ending : List.of("\r\n", "\n", "", "\r")) { + for (int order = 0; order < 3; order++) { + boolean neighbor = order != 0; + UUID source = + portal.create( + auth(owner, true), "Closing boundary source " + scenario, "VEVENT", "", ""); + UUID target = + portal.create( + auth(owner, true), "Closing boundary target " + scenario++, "VEVENT", "", ""); + byte[] small = event("closing-small"); + String text = + calendarBody("closing-limit").replace("END:VCALENDAR\r\n", "END:VCALENDAR" + ending); + int padding = + org.busystack.caldav.calendar.CalendarContent.MAX_BYTES + - text.getBytes(StandardCharsets.UTF_8).length; + byte[] large = + text.replace("X-CLIENT:preserve", "X-CLIENT:preserve" + "x".repeat(padding)) + .getBytes(StandardCharsets.UTF_8); + assertThat(large).hasSize(org.busystack.caldav.calendar.CalendarContent.MAX_BYTES); + assertThat(org.busystack.caldav.calendar.CalendarContent.parse(large, "VEVENT").uid()) + .isEqualTo("closing-limit"); + calendars.put( + owner, + source, + order == 1 ? "a-limit.ics" : "b-limit.ics", + "closing-limit", + large, + WriteCondition.create()); + if (neighbor) + calendars.put( + owner, + source, + order == 1 ? "b-small.ics" : "a-small.ics", + "closing-small", + small, + WriteCondition.create()); + var response = + client.send( + HttpRequest.newBuilder( + URI.create(base() + "/portability/collections/" + source + "/export")) + .GET() + .build(), + HttpResponse.BodyHandlers.ofByteArray()); + assertThat(response.statusCode()).isEqualTo(200); + boolean stream = neighbor && !ending.equals("\r\n"); + assertThat(response.headers().firstValue("Content-Disposition")) + .hasValue( + "attachment; filename=\"busystack-collection" + + (stream ? "-stream" : "") + + ".ics\""); + var preview = upload(client, csrf, target, "closing-boundary.ics", response.body()); + assertThat(preview.statusCode()).isEqualTo(200); + assertThat(preview.body()).doesNotContain("UID series exceeds the 1 MiB resource limit"); + var matcher = + java.util.regex.Pattern.compile("/portability/import/([a-f0-9-]{36})") + .matcher(preview.body()); + assertThat(matcher.find()).isTrue(); + var result = + post( + client, + "/portability/import/" + matcher.group(1), + Map.of("_csrf", csrf, "confirmed", "true")); + assertThat(result.statusCode()).isEqualTo(200); + var resources = calendars.metadataBatch(owner, target, "", 10); + assertThat(resources).hasSize(neighbor ? 2 : 1); + for (var resource : resources) { + byte[] stored = calendars.get(owner, target, resource.name()).content(); + assertThat(stored.length) + .isLessThanOrEqualTo(org.busystack.caldav.calendar.CalendarContent.MAX_BYTES); + assertThat(org.busystack.caldav.calendar.CalendarContent.parse(stored, "VEVENT").uid()) + .isEqualTo(resource.uid()); + byte[] expected = resource.uid().equals("closing-limit") ? large : small; + if (resource.uid().equals("closing-limit") && ending.equals("\r")) + expected = java.util.Arrays.copyOf(expected, expected.length - 1); + assertThat(stored).isEqualTo(expected); + } + } + } + } + @Test void realHttpMediumStreamsRoundTripDistinctTimezonesMetadataExceptionsAndTasks() throws Exception { From 39fa4e7caa95f7f4b0da28e2f307ed7baf7a0fc0 Mon Sep 17 00:00:00 2001 From: albert Date: Wed, 4 Nov 2026 19:19:30 -0700 Subject: [PATCH 16/82] Implement protected browser initialization and staged account onboarding --- README.md | 2 + deployment/INSTALL.md | 23 +- docs/GETTING_STARTED.md | 694 ++++++++++++++++++ docs/account-security.md | 3 +- docs/operations.md | 39 +- docs/passkeys-and-mfa.md | 2 +- docs/portal.md | 6 +- qualification/release/test_release.py | 2 +- scripts/initialize.sh | 8 + scripts/release-bundle.py | 34 +- scripts/restore.sh | 9 +- scripts/verify-operations.py | 6 +- .../caldav/BusyStackApplication.java | 1 + .../caldav/account/AccountService.java | 7 +- .../account/BootstrapAdministrator.java | 6 +- .../account/InitializationController.java | 45 ++ .../caldav/account/InitializationService.java | 102 +++ .../account/IssueInitializationCode.java | 24 + .../caldav/management/FormRecovery.java | 4 + .../management/ManagementController.java | 20 + .../caldav/management/ManagementService.java | 27 + .../caldav/management/PortalController.java | 20 +- .../caldav/management/PortalPageAdvice.java | 6 + .../security/AuthenticationJourney.java | 92 +++ .../security/SecurityConfiguration.java | 10 +- .../security/oidc/OidcConfiguration.java | 9 +- .../passkey/PasskeyCeremonyGuard.java | 15 +- .../passkey/PasskeyConfiguration.java | 4 +- .../caldav/security/passkey/PasskeyPages.java | 58 +- .../security/session/SessionEpochFilter.java | 1 + .../V15__protected_initialization.sql | 27 + src/main/resources/static/assets/portal.js | 19 +- src/main/resources/static/assets/security.js | 88 ++- .../templates/administrator-welcome.html | 2 + .../templates/authentication-complete.html | 7 + src/main/resources/templates/connections.html | 13 +- src/main/resources/templates/credentials.html | 8 +- src/main/resources/templates/dashboard.html | 2 +- .../resources/templates/enroll-passkey.html | 9 + .../resources/templates/fragments/layout.html | 8 +- .../templates/issued-credential.html | 2 +- src/main/resources/templates/login.html | 23 +- src/main/resources/templates/passkeys.html | 4 +- src/main/resources/templates/security.html | 4 +- .../templates/setup-administrator.html | 17 + .../resources/templates/setup-complete.html | 4 + src/main/resources/templates/setup.html | 10 + .../resources/templates/verify-passkey.html | 8 + .../caldav/account/InitializationIT.java | 256 +++++++ .../security/AuthenticationJourneyTest.java | 33 + .../caldav/testing/SignedPasskeyClient.java | 4 + 51 files changed, 1729 insertions(+), 98 deletions(-) create mode 100644 docs/GETTING_STARTED.md create mode 100755 scripts/initialize.sh create mode 100644 src/main/java/org/busystack/caldav/account/InitializationController.java create mode 100644 src/main/java/org/busystack/caldav/account/InitializationService.java create mode 100644 src/main/java/org/busystack/caldav/account/IssueInitializationCode.java create mode 100644 src/main/java/org/busystack/caldav/security/AuthenticationJourney.java create mode 100644 src/main/resources/db/migration/V15__protected_initialization.sql create mode 100644 src/main/resources/templates/administrator-welcome.html create mode 100644 src/main/resources/templates/authentication-complete.html create mode 100644 src/main/resources/templates/enroll-passkey.html create mode 100644 src/main/resources/templates/setup-administrator.html create mode 100644 src/main/resources/templates/setup-complete.html create mode 100644 src/main/resources/templates/setup.html create mode 100644 src/main/resources/templates/verify-passkey.html create mode 100644 src/test/java/org/busystack/caldav/account/InitializationIT.java create mode 100644 src/test/java/org/busystack/caldav/security/AuthenticationJourneyTest.java diff --git a/README.md b/README.md index 513a9aa..23c712e 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # BusyStack CalDAV Server +Start with the illustrated [Getting Started guide](docs/GETTING_STARTED.md) for installation, protected administrator setup, account security and CalDAV client connection. + A self-hosted CalDAV server for calendars and tasks, with PostgreSQL persistence and built-in account administration. It supports local accounts and optional OpenID Connect login through an existing identity provider. diff --git a/deployment/INSTALL.md b/deployment/INSTALL.md index c814476..0117b9b 100644 --- a/deployment/INSTALL.md +++ b/deployment/INSTALL.md @@ -22,9 +22,7 @@ cp .env.example .env Edit `.env` with the actual HTTPS URL/issuer and private absolute secret paths. Create distinct database secrets as shown in `docs/operations.md` (private parent -directory mode 0700, database files readable by container UIDs). Do not put secrets -in `.env`, command lines or the archive. Keep the administrator bootstrap file -owner-only. Then, from this extracted directory: +directory mode 0700, database files readable by container UIDs). Do not put secrets in `.env`, command lines or the archive. Then, from this extracted directory: ```sh docker compose config --quiet @@ -40,12 +38,19 @@ the hostname and certificate paths. Validate the proxy configuration before reload. Do not expose the database or application HTTP port to the network. For a subpath, set both URLs to the same `/calendar` suffix and preserve that path. -Follow the included `docs/operations.md` for the exact local administrator -bootstrap command, first HTTPS sign-in, passkey enrollment and MFA, first user, -event/task collections and named DAV credential. Connect the real client to the -account page's displayed HTTPS CalDAV address using its named credential. -The primary account password is not the DAV password. See the included account, -OAuth and optional external-identity guides for those workflows. +Follow the complete illustrated [Getting Started guide](docs/GETTING_STARTED.md). +After HTTPS is configured, a fresh server shows **Set up BusyStack**. Issue its +15-minute, single-use code locally from this deployment directory: + +```sh +bash scripts/initialize.sh +``` + +Choose **Create administrator account**, enter the code and choose your username +and password in the browser. Setup does not sign you in. Sign in normally, create +your first passkey, then verify it. Follow the guide for recovery codes, personal +calendars or account administration, and application passwords/client setup. +The account password is not the DAV application password. ## Updates, backup, restoration and removal diff --git a/docs/GETTING_STARTED.md b/docs/GETTING_STARTED.md new file mode 100644 index 0000000..34e5cba --- /dev/null +++ b/docs/GETTING_STARTED.md @@ -0,0 +1,694 @@ +# Getting started with BusyStack CalDAV Server + +This is the complete operator, administrator and user guide for BusyStack 0.2.0. +Release packages replace `@VERSION@` below with their exact version. When reading +this file in the source repository, substitute `0.2.0` for that placeholder. +Only download a version whose official release assets are available. + +## 1 — What BusyStack does + +BusyStack stores calendars and task lists on a server you control. CalDAV is the +protocol that compatible calendar applications use to discover and synchronize +those collections. Edit events and tasks in a connected application, such as +Thunderbird. The web portal manages accounts, collections, sharing, application +access, security, and iCalendar import/export; it is not an event or task editor. + +Standalone operation needs no Keycloak, email delivery, cloud service, vendor +account, telemetry, analytics, licensing server, or remote frontend assets. +Your database and backups contain your data; control access to both. + +## 2 — Requirements + +The release container distribution supports **Linux AMD64**, Docker Engine, and +**Docker Compose 2.24.4 or newer**. Other operating systems and architectures are +not qualified by these instructions. Check the host before downloading: + +```sh +uname -s -m +docker version +docker compose version +``` + +Expect `Linux x86_64`, a responding Docker server, and an adequate Compose version. +Your operator account needs access to Docker; that access controls this server. +The command examples also use a shell, curl, tar, sha256sum, OpenSSL and standard +Linux file utilities. No host Java, Maven, source checkout or compilation is +needed. The image supplies Java 25, Spring Boot and the application. Compose +supplies private PostgreSQL 18.6. + +Provide persistent disk space for PostgreSQL, growing calendar/synchronization +history and separate backups. No measured minimum host RAM/disk specification is +published. The application container has a 1 GiB memory limit and a 384 MiB `/tmp` +allocation; those defaults are not a whole-host capacity guarantee. PostgreSQL, +Docker, the proxy and backups need additional resources. Monitor usage. + +Provide a stable hostname, appropriate DNS, and a trusted HTTPS certificate and +private key matching that hostname. A private deployment may use its own CA only +when every client trusts that CA normally. The package does **not** obtain public +certificates automatically. Supply and maintain the HTTPS reverse proxy yourself; +working Nginx configurations are included. Certificate issuance, DNS and firewall +administration remain operator responsibilities. + +Allow HTTPS from intended clients to the proxy. Allow outbound access needed to +download release assets and pinned images. Do not expose PostgreSQL or the internal +HTTP listener publicly. The supplied Compose binds application HTTP to loopback +and publishes no PostgreSQL port. Use persistent volumes, protected configuration, +and secure local operator access. Keep time correct for TLS, expiry and passkeys. + +## 3 — Download and verify + +Choose an official version. In a new directory, run: + +```sh +VERSION=@VERSION@ +curl -fLO "https://github.com/busystack/caldav-server/releases/download/v${VERSION}/caldav-server-${VERSION}-deploy.tar.gz" +curl -fLO "https://github.com/busystack/caldav-server/releases/download/v${VERSION}/SHA256SUMS" +curl -fLO "https://github.com/busystack/caldav-server/releases/download/v${VERSION}/release-manifest.json" +sha256sum --check --ignore-missing SHA256SUMS +tar -xzf "caldav-server-${VERSION}-deploy.tar.gz" +cd "caldav-server-${VERSION}-deploy" +``` + +Continue only when the archive and `release-manifest.json` report `OK`, with no +checksum failure. Other assets not downloaded are skipped. Checksums detect +corruption; obtain them from the official immutable release, whose attestation +binds the publisher's assets. The manifest records source, JAR checksum, tested +image identity and qualification evidence. Do not run unverified remote scripts. + +All remaining deployment commands run **inside this extracted directory** unless +stated otherwise. It contains `INSTALL.md`, this guide and screenshots, Compose, +proxy examples and scripts. Its Compose pulls the published version **and immutable +registry digest**. Preserve that identity; do not substitute `latest` or a locally +built image for ordinary installation. + +## 4 — Configure the server + +```sh +cp .env.example .env +install -d -m 700 "$HOME/.config/busystack-caldav" +(umask 077; openssl rand -base64 48 > "$HOME/.config/busystack-caldav/database-password") +(umask 077; openssl rand -base64 48 > "$HOME/.config/busystack-caldav/postgres-admin-password") +chmod 444 "$HOME/.config/busystack-caldav/database-password" "$HOME/.config/busystack-caldav/postgres-admin-password" +``` + +Use new secret files for a new installation; do not overwrite secrets belonging +to an existing deployment. OpenSSL generates the two independent passwords. +Never paste them into `.env`, process arguments, browser pages, Git or logs. +The containing directory stays mode 0700; file mode 0444 lets the non-root +container users read bind-mounted Compose secrets without exposing them to other +host users through that private directory. Do not make the directory public. +Protect backups of configuration and secrets separately from database backups. + +Edit `.env` with your values. For a hostname-root installation: + +```dotenv +BUSYSTACK_PUBLIC_BASE_URL=https://calendar.example.org +BUSYSTACK_ISSUER=https://calendar.example.org +BUSYSTACK_DATABASE_PASSWORD_FILE=/home/OPERATOR/.config/busystack-caldav/database-password +BUSYSTACK_POSTGRES_ADMIN_PASSWORD_FILE=/home/OPERATOR/.config/busystack-caldav/postgres-admin-password +BUSYSTACK_HTTP_PORT=8080 +``` + +Replace the hostname and both absolute paths. Shell expressions such as `$HOME` +are not a substitute for writing the intended absolute paths here. Public URL +and OAuth issuer must be equal, without trailing slash, query or fragment. These +are externally visible HTTPS addresses, not container network addresses. + +For a subpath, set **both** URLs to `https://calendar.example.org/calendar` and use +`nginx-subpath.conf.example`. The application derives its servlet prefix from this +configuration. The proxy must preserve `/calendar`; it must not strip the prefix. +It must also handle host-root discovery using the supplied explicit mappings. +Use canonical ASCII prefixes. Choose the hostname deliberately: changing it can +make previously registered passkeys unusable. + +Use [the complete root proxy example](../deployment/nginx-root.conf.example) or +[the complete subpath proxy example](../deployment/nginx-subpath.conf.example) in an extracted +package. In the source repository these examples are in `deployment/`. Replace +`calendar.example.org`, certificate paths and, if changed, loopback upstream port. +Install the chosen example through your existing Nginx administration procedure; +run `sudo nginx -t` before reloading it. Both examples restrict health endpoints, +disable compression, and supply the larger bounded import route. Do not enable +blanket forwarded-header trust. [Operations](operations.md#https-and-proxy-paths) +explains the configuration and other operator considerations. + +PostgreSQL data lives in the Compose `database` volume at `/var/lib/postgresql`. +Initialization scripts only run on an empty volume. Changing a secret file later +does not change an existing database role password; rotate the role and file +together during controlled maintenance. + +For an isolated trial, set a new `COMPOSE_PROJECT_NAME` and unused +`BUSYSTACK_HTTP_PORT` in `.env` before the first Compose command. Point the trial's +proxy at that port. Never use a production project's volume for a trial or restore. + +## 5 — Start BusyStack + +```sh +docker compose config --quiet +docker compose pull +docker compose up -d --no-build --wait --wait-timeout 240 +docker compose ps +``` + +Configuration validation must exit successfully. Pull must obtain the configured +pinned images. PostgreSQL becomes healthy before the application starts; application +readiness includes database connectivity. Both services should show healthy. + +Check actual HTTPS, including the configured subpath if any: + +```sh +curl --fail --show-error --silent --location --output /dev/null https://calendar.example.org/ +curl --head https://calendar.example.org/.well-known/caldav +``` + +For a `/calendar` deployment, use `https://calendar.example.org/calendar/` in the +first command. Discovery should redirect to the configured `/calendar/dav/`. +Check certificate validity and hostname with normal validation; do not use `-k`. +Open the public URL in a browser. A fresh database must show **Set up BusyStack**. +A running container alone does not prove DNS, HTTPS, proxy paths or isolation. + +Inspect listeners with your host's network tools, for example `ss -ltn`. +The application port should be `127.0.0.1:8080` (or your selected loopback port), +with no published database port. Check the host firewall from a permitted client. +Use `docker compose logs --tail 100 application database` for startup diagnostics; +keep diagnostic output private and never enable request-body/credential logging. +See chapter 19 if startup or HTTPS fails. + +## 6 — Create the first administrator + +![Fresh deployment showing Set up BusyStack](images/getting-started/01-initial-setup.png) + +This page confirms the server is running and needs its first administrator. Merely +visiting it gives no administrative permission. With local access to the deployment +directory, issue a short-lived initialization code: + +```sh +bash scripts/initialize.sh +``` + +This runs the installed application inside a one-off Compose container against +this deployment's database. No host Java is required. The command prints a code +valid for **15 minutes**, once, to the operator's terminal. Keep that terminal +private. Do not put the code in a URL, screenshot, chat, log file or shell history. +The long-running server never prints it. Every replacement invalidates the previous +code. After five invalid submissions, a fresh local code is required. + +Choose **Create administrator account** in the browser. + +![Protected administrator form with empty secret fields](images/getting-started/02-create-administrator.png) + +Enter the code, a username, a password and its confirmation. Usernames contain +1–64 letters, numbers, dots, underscores or hyphens, starting with a letter or +number. Passwords need at least **14 characters** and at most **72 UTF-8 bytes**; +some characters use more than one byte. Use your password manager to generate and +store a suitable password. Passwords and codes are never redisplayed after errors. + +Submit **Create administrator account**. An expired or unavailable code requires +running `bash scripts/initialize.sh` again locally; no database reset is needed. + +![Administrator account created confirmation](images/getting-started/03-setup-complete.png) + +**Administrator account created** means setup is permanently closed for this +database. Choose **Sign in**. Setup does not sign you in automatically. Restart, +account disabling, or restoring this initialized database does not reopen setup. +Existing initialized installations go directly to normal login after upgrade. +Offline account recovery remains a separate controlled operation (chapter 16). + +## 7 — Secure the administrator account + +![Conventional username and password sign-in](images/getting-started/04-sign-in.png) + +Sign in with the account you just created. You then see **Secure your account**. + +![First-passkey enrollment without credential-management controls](images/getting-started/05-create-passkey.png) + +Choose **Create passkey**. Your browser or supported password manager offers its +normal passkey interface. Follow that interface. BusyStack does not require a +particular password manager, fingerprint reader or USB device. The passkey provider +must support the verification requested by the browser. No passkey name is required +for this first enrollment. + +![Passkey created and the next verification action](images/getting-started/06-passkey-created.png) + +Wait for **Passkey created**, then choose **Verify your passkey**. Saving a passkey +and proving you can use it are separate steps; creating it alone does not authorize +sensitive operations. + +![Passkey verification for the signed-in account](images/getting-started/07-verify-passkey.png) + +Choose **Verify passkey** and complete the provider's prompt using this account's +passkey. After **Authentication successful**, choose **Continue** to return to your +intended operation. Protected form submissions are not replayed automatically. +If a prompt does not finish, read the contextual status and retry when ready. +A browser `NotAllowedError` can mean cancellation, timeout or unavailable credentials; +it does not identify one exact cause. If a registration response was lost, BusyStack +checks authoritative enrollment state before suggesting another registration. + +Primary sign-in and passkey verification must each be within **ten minutes** for +sensitive changes/downloads. A session can remain active after that interval; +follow the indicated sign-in or verification action when required. Returning users +sign in normally and verify their existing passkey; they do not enroll again. +A recovered account whose old passkeys were revoked enrolls a new one. + +Open **Security → Recovery** after verification. Generate recovery codes through +the existing protected workflow, save them securely offline, then leave the one-time +screen. They provide a second-factor recovery path when you still have primary +sign-in. They do not replace a forgotten primary password. You may continue using +the service without generating them, but losing all factors then needs local +operator recovery. Chapter 13 explains recovery and revocation. + +## 8 — Personal and organizational use + +![First administrator welcome with two activity choices](images/getting-started/08-administrator-welcome.png) + +The first browser-created administrator sees **Welcome to BusyStack** after MFA. +Recovery codes are available from this screen. Choose one activity: + +* **Set up my calendar** opens available collections. Use this same administrator + account for personal calendars or shared collections; no separate account is needed. +* **Manage users** opens administrator account management. Create accounts for + other people without creating a personal calendar first. + +These are navigation choices, not account types or server modes. Completing a +choice dismisses this initial welcome. Returning administrators use the normal +portal, with **Server administration** always available according to their role. + +## 9 — Manage users + +![Administrator account list](images/getting-started/09-manage-users.png) + +Open **Server administration → Accounts → Create account**. + +![Ordinary local account creation form](images/getting-started/10-create-user.png) + +Supply username, display name and an initial password meeting the same policy. +Choose **Create account**. This creates an ordinary local account, not another +administrator. Transfer the URL, username and password through a secure channel +available to you, such as an approved password-manager sharing feature or direct +handoff. No email invitation service is required. Let the user enroll and verify +their own passkey; do not enroll it on their behalf. + +Select an account to maintain its display name or disable it. Disabling requires +explicit confirmation and invalidates sessions and independently issued client +access while retaining stored data and membership. There is no public reactivation +or password-reset endpoint. Controlled recovery is described in chapter 16. + +Use **Server administration → Groups** to create a group, add exact active usernames, +review membership consequences, rename it or confirm deletion. Membership affects +all collections granted to the group, including future grants. Owners decide which +collections to share. Removing one grant or membership may leave access supplied +by another grant; check effective permissions. [Groups](groups.md) has details. + +Administrators manage accounts, membership, OAuth client registrations and safe +operational metadata. Administrator status does **not** automatically permit +reading other users' private calendars. Sharing and local account authorization +remain authoritative. Ordinary users do not see server-administration controls or +an unrestricted account directory. + +## 10 — An ordinary user's first login + +The administrator supplies your BusyStack URL and credentials. Open that HTTPS +URL, sign in, choose **Create passkey**, then verify it as in chapter 7. If your +organization manages primary sign-in, use its organizational sign-in instead; +local BusyStack passkeys still follow it. + +![Ordinary user first-use screen](images/getting-started/11-user-onboarding.png) + +Prepare recovery codes under **Security → Recovery** if possible. The account +screen uses your actual collections and application-password state to offer the +next action. If you already have shared access, continue directly to +**Connect an application**. Otherwise create a calendar/task list, or ask an owner +to share one with your exact username. You do not have to duplicate shared data. +Account recovery can revoke previous passkeys and application access; follow the +same enrollment/verification sequence afterward. + +## 11 — Calendars and tasks + +![Calendars and task lists with collection types and access](images/getting-started/12-calendars.png) + +Open **Calendars & Tasks**. Use owned/shared filters and search. Choose +**Create a collection**, enter a name and choose **Calendar** for events or +**Task list** for tasks. Optional description and colour can help clients identify +it. Type is fixed after creation. Actual event/task editing occurs in a CalDAV app. +GNOME Calendar provides event editing; use a VTODO-capable application for tasks. + +Select a collection to view its address, owner and access. Authorized read/write +recipients can edit shared metadata and import content. Metadata changes preserve +collection identity and contents; clients may maintain their own colour preference. + +![Owner-managed direct and group sharing](images/getting-started/19-sharing.png) + +Owners choose **Manage sharing**, supply an exact recipient username or an available +group, then choose read-only or read/write access. Read-only permits reading; +read/write permits content changes. Only the owner manages sharing and deletes the +whole collection. Review effective access after changes; direct and group grants +combine. Clients may need rediscovery or a fresh synchronization after changes. + +Deletion uses a separate review/confirmation screen and removes the collection, +contents, synchronization history, bindings and sharing grants. Export or obtain +an operator backup first if the data must be retained. If the form is stale, reload +and review current state instead of repeating a destructive submission. + +## 12 — Connect applications + +![Application selection for Thunderbird, GNOME Calendar or generic CalDAV](images/getting-started/13-connect-application.png) + +Open **Connections**, choose **Thunderbird**, **GNOME Calendar**, or **Generic CalDAV**. +The selected screen displays the configured server address, username and instructions. +Addresses include any configured subpath and come from deployment configuration. +Never remove the prefix or substitute an internal container hostname. + +Choose **Create application password**. If verification expired, complete it, then +return to the form. Your BusyStack account password is **not** the ordinary DAV +client password. + +![Application-password label and expiration form](images/getting-started/14-create-application-password.png) + +Enter an **Application/device label** such as “Thunderbird on my laptop”, and an +**Expiration period (days)** from 1 through 365. Choose **Create application password**. + +![One-time application-password confirmation with the password redacted](images/getting-started/15-password-created.png) + +The screenshot is from the real confirmation page; the secret is deterministically +redacted during capture. The actual page shows label, username, password and expiry. +**The password will not be shown again.** Use **Copy password** and paste into the +client's password field or store securely before leaving. **Password copied.** +appears beside the action only if copying succeeded. If copying fails, select the +text manually and use your browser's Copy command. Username and server-address +copy actions give their own nearby status; no action moves keyboard focus. + +Choose **Continue to application setup** to return to the chosen instructions. +Leaving the one-time screen means the secret cannot be retrieved. If lost, create +a replacement and revoke the previous password. Issuing a password does not prove +that an external application has connected; BusyStack does not track device setup. + +![Selected client connection settings and instructions](images/getting-started/16-client-configuration.png) + +### Thunderbird + +Version-scoped existing evidence covers Thunderbird 159.0 graphical workflows and +157.0.1 native-provider tests; final engineering evidence records which profiles +were rerun against this implementation. To configure: + +1. Open Calendar and choose **New Calendar → On the Network**. +2. Enter the displayed username and server address as **Location**. Keep + **This location doesn't require credentials** unchecked. Choose **Find Calendars**. +3. Enter the **application password**, not your primary BusyStack password, when + prompted. Optionally retain it in Thunderbird's Password Manager. +4. Select CalDAV and the discovered calendars/task lists, then **Subscribe**. + Use Thunderbird's task view for VTODO task lists. + +Create a synthetic event and task, refresh, edit them, complete a task, and verify +changes from another authorized client/profile. Test deletion only on synthetic +data. After an application restart, confirm the data remains synchronized. + +### GNOME Calendar / Evolution Data Server + +Existing version-scoped evidence covers Calendar **50.0** / EDS **3.56.2**. Use the +portal's **GNOME connection address**, which includes your username but no password; +this wizard needs it to retain the authentication user after discovery. + +1. Choose **Manage Calendars → Add Calendar**. +2. Paste that address under **Connect to an Online Calendar**. +3. In **Credentials**, enter your username in **User** and your application password + in **Password**, then **Connect**. +4. After validation, choose **Add Calendar**. If synchronization prompts again, + enter the same application password. Refresh and check a synthetic event. + +GNOME Calendar has no task editor. Do not infer a task workflow from event discovery. +Existing EDS qualification is distinct from unqualified Evolution graphical setup. + +### Generic CalDAV + +Choose CalDAV/password authentication over HTTPS. Use the displayed server address, +username and application password. Discovery should show owned/shared collections. +If the application requires a collection URL, copy the appropriate address from +Connections. Task handling and wizard labels vary; an untested client is not +qualified merely because it offers a CalDAV field. BusyMax is not listed as a +verified connection option. + +Use **Security → Application passwords** to review expiration/revocation metadata. +To replace a password, create a new one, update the client, then revoke the old one. +Revocation denies future authentication; a request already authorized may finish. +Registered OAuth-capable clients may instead use browser authorization with consent; +ordinary CalDAV discovery does not provide OAuth support automatically. + +## 13 — Security management + +![Account security controls](images/getting-started/17-security.png) + +**Security** links to passkeys, application passwords, sessions, recovery, OAuth +grants and local-password changes. Sensitive actions require current primary and +passkey authentication. Sign out on shared computers. Sessions expire after thirty +minutes of inactivity; the ten-minute verification policy is separate. + +Manage extra passkeys only after recent MFA. Labels are user-supplied descriptions, +not verified hardware/provider identities. Removing a passkey removes that stored +credential. Existing recent authentication remains governed by its ten-minute +factor lifetime; removal alone is not an account-wide security reset. If all +passkeys are removed, enroll/verify another before the next verification is needed. +Use controlled recovery if you cannot. Password changes and recovery invalidate +sessions/security generations and revoke independently issued access. + +![Recovery-code workflow without disclosed codes](images/getting-started/18-recovery.png) + +After recent MFA, recovery generates ten high-entropy one-use codes, shown once, +expiring after one year. Save them privately offline. Generating a replacement set +revokes the prior unused set. A lost-passkey recovery submission needs recent +primary sign-in plus one unused code. Successful recovery revokes old passkeys, +client credentials/grants and browser sessions. Sign in again and enroll/verify a +new passkey. If primary sign-in is also lost, contact the operator; do not share +recovery codes with another user. + +**Sessions** shows your sessions without bearer identifiers and allows revocation +of owned sessions after MFA. **OAuth applications** lists grants without tokens; +revoke unwanted access there. The account password-change form uses the same +14-character/72-byte policy. Organization-managed accounts change primary +credentials through their provider, with no local-password fallback. +[Account security](account-security.md) and [OAuth](oauth.md) explain exact limits. + +## 14 — Import and export + +![Existing import and export interface](images/getting-started/20-import-export.png) + +Use **Import & Export** with recent MFA. Select an authorized writable destination, +upload an iCalendar `.ics` file, review the preview, confirm, and inspect the result. +Calendars take VEVENT series; task lists take VTODO. Exceptions stay with their UID +series. At most **64 MiB**, **10,000 UID series/resources**, and **1 MiB per constructed +resource** are supported, with additional parsing/processing bounds. + +New valid series are imported. Identical existing resources are skipped; different +content with the same UID conflicts and is preserved. There is no implicit merge +or overwrite. Preview and confirmation can differ if data/access changed. Database +failure rolls back writes; review the retained preview where offered. A preview +expires after ten minutes and does not survive restart. If outcome is uncertain, +inspect destination contents before uploading again. Invalid replacement uploads +preserve a previous valid preview. The portal provides a link to the current review. + +Read-authorized users may export a collection. Matching calendar headers/timezones +produce one VCALENDAR; otherwise lossless export contains a stream of complete +VCALENDAR objects (`-stream.ics`). BusyStack can import both. Thunderbird 159.0's +native file importer does not consume multi-VCALENDAR streams; other clients may +also differ. Native CalDAV support does not establish file-import support. +An empty collection returns a notice instead of an unusable export. Operator +backups preserve more than an interchange file. See [portability](portability.md). + +## 15 — Optional Keycloak + +Keycloak is useful when an organization already operates an identity provider. +Standalone BusyStack works without it. Establish the first administrator through +chapter 6 before enabling federation. Keep an independently recoverable local +administrator for provider outages. + +The operator registers an OIDC confidential client with authorization-code flow, +S256 PKCE and the exact callback `/login/oauth2/code/upstream`. Disable +unused provider flows. Configure issuer, client ID, protected client secret and a +closed subject allowlist using [the complete Keycloak configuration](keycloak.md). +Compose has no mandatory Keycloak service. Mount protected operator configuration +and file-backed secrets through your deployment configuration; the detailed guide +provides the actual property names. Do not put provider secrets in a public file. + +Allowlisted subjects are verified immutable issuer/subject identities, not emails +or matching display names. They provision ordinary local authorization identities. +Upstream roles do not grant BusyStack administrator privileges. Existing users may +explicitly link an organization identity only after recent MFA. Linking removes +local-password fallback, preserves local collection identity/passkeys, rotates the +security generation and revokes existing independent access. + +Users choose organizational sign-in, then the same local passkey enrollment or +verification appropriate to actual account state. They do not configure Keycloak. +Provider tokens are not DAV passwords. BusyStack discards upstream access/refresh +tokens after login and uses its own application-access mechanisms. + +Local login remains available during a provider outage. Managed users cannot fall +back to a local password. Already issued managed-user access may continue within +its existing freshness bound; an outage does not extend it. Default upstream +freshness is 24 hours (operator-configurable down to one minute). Upstream disabling +is not immediate push revocation of all BusyStack access; local disabling and local +revocation remain available. Recovery preserves the exact issuer/subject mapping. + +## 16 — Backups and recovery + +From the deployment directory, create a new private backup destination: + +```sh +install -d -m 700 /private/backups +bash scripts/backup.sh /private/backups/busystack-before-update.dump +(cd /private/backups && sha256sum --check busystack-before-update.dump.sha256) +``` + +Replace `/private/backups` with an operator-owned backup directory. Expect +`Created database archive and checksum...` and a checksum `OK`. The script refuses +to overwrite an existing archive or checksum. Keep both files, configuration, +secret files and exact release/image identity securely, separately and preferably +off-host. Backups contain sensitive account/content/security state. A checksum +proves file integrity, not successful restoration; rehearse recovery. + +Restore only into an **isolated empty deployment**, with a different project name +and port, its own correctly configured secrets, and every application instance +stopped. Do not restore over a production database. In that new extracted/configured +release directory: + +```sh +docker compose config --quiet +docker compose pull +docker compose up -d --no-build --wait database +bash scripts/restore.sh /private/backups/busystack-before-update.dump +``` + +The script checks the checksum, refuses a running application/nonempty target, +and accepts complete successful histories from V1 through V15. It preserves data, +ownership, shares and identity mappings, disables every account, changes recovery +and account epochs, removes restored sessions/passkeys/recovery codes/DAV credentials +and OAuth grants, revokes refresh families, and invalidates outstanding initialization +codes. An initialized database remains initialized. Expect the explicit restoration +and invalidation confirmation. On any failure keep the application stopped. + +For an older supported schema, start the current image once with every account +disabled to apply forward migrations, then stop it before recovery: + +```sh +docker compose up -d --no-build --wait --wait-timeout 240 application +docker compose stop application +``` + +After independently verifying each local user's identity, prepare an owner-only +file containing a **new** password. Use a password manager or protected local +editor; never put its value in command arguments. Mount it using the host owner's +UID so the owner-only permission check is meaningful: + +```sh +docker compose run --rm --no-deps --user "$(id -u):$(id -g)" \ + --volume /private/path/new-password:/recovery-password:ro \ + application --spring.main.web-application-type=none \ + --busystack.recover-account=true \ + --busystack.recovery-username=administrator \ + --busystack.recovery-password-file=/recovery-password +``` + +Use the exact existing username and actual private absolute file path (mode 0600, +private parent). Recover accounts individually; never bulk-enable restored accounts. +Delete the temporary password file after securely recording the replacement. +Start the application, sign in and enroll fresh passkeys, then reissue application +access. Review restored administrator roles, sharing and OAuth registrations, which +may reflect old permissions. Verify actual event/task contents, rejected old +credentials, shared read/write boundaries, and fresh synchronization. + +Externally managed accounts need provider-side recovery and the separate offline +command with their **existing exact** issuer/subject, without a replacement password: + +```sh +docker compose run --rm --no-deps application \ + --spring.main.web-application-type=none \ + --busystack.recover-external-account=true \ + --busystack.recovery-username=organization-user \ + --busystack.recovery-issuer=https://identity.example.org/realms/organization \ + --busystack.recovery-subject=verified-existing-subject +``` + +Keep applications stopped during this operation. It does not change identity mapping +or create a local-password fallback. Follow [operations](operations.md#backup-and-isolated-restoration) +for recovery safeguards, ownership and verification scope. The established offline +bootstrap remains available only for an untouched empty database; ordinary new +installations use protected browser initialization. + +## 17 — Updates + +Read target release/migration notes. Back up and verify a restoration rehearsal +before updating. Obtain and verify the newer deployment archive as in chapter 3. +Keep the same intended Compose project/database volume, public URL and secret paths; +changing the extraction directory must not accidentally select a new project. +Copy your reviewed configuration into the new extracted package. Keep secret files +outside either package. Preserve optional operator overrides deliberately, reviewing +them against the new Compose file rather than replacing the new file wholesale. + +From the old deployment directory stop the application. From the configured new +one validate, pull and start: + +```sh +docker compose config --quiet +docker compose pull +docker compose up -d --no-build --wait --wait-timeout 240 +docker compose ps +``` + +Flyway validates published migration checksums and applies forward migrations. +This implementation adds V15 protected setup state after V1–V14. Existing accounts, +including disabled ones, close initialization on upgrade. Verify HTTPS, normal +returning-user sign-in, an existing calendar/task, sharing and synchronization. +Keep the previous artifact and backup for a controlled recovery plan; changing an +image does not undo database migrations. Automatic downgrade is not promised. + +## 18 — Stopping and uninstalling + +`docker compose stop` stops services while retaining containers and storage. +`docker compose up -d --no-build --wait` starts them again. +`docker compose down` removes this project's containers/network and retains the +database volume. Keep `.env`, secrets and proxy configuration to resume later. + +**Destructive:** `docker compose down --volumes` also deletes this project's +persistent database. Run it only after independently verifying backups and +explicitly deciding to destroy that installation. Confirm the selected project +first with `docker compose ps`. It is not an update or ordinary restart command. + +After deliberately uninstalling, remove the corresponding proxy configuration and +private configuration/secrets when no longer needed, following your retention +policy. Backups and copied secret material need separate secure disposal. + +## 19 — Troubleshooting + +Use the symptom to choose a safe check. Keep credentials, backups and detailed +infrastructure diagnostics private. Do not disable TLS, CSRF or passkey verification +to make an error disappear. + +| Symptom | Supported causes and safe verification | Corrective action | +| --- | --- | --- | +| `docker version` cannot contact the daemon | Docker is stopped or operator access is unavailable. Check local service status and approved Docker permissions. | Start Docker using host administration; obtain authorized daemon access. Do not make its socket public. | +| Compose configuration fails | Required `.env` values/absolute secret files are missing, wrong working directory, or Compose is too old. | Run `docker compose config --quiet` in the extracted directory, check paths and Compose ≥2.24.4. | +| PostgreSQL stays unhealthy | Secret mount access, failed first initialization, storage or existing-role password mismatch. Check `docker compose ps` and private database startup logs. | Correct permissions/storage or coordinate role/secret rotation. Preserve the volume; changing a file alone does not rotate a role. | +| Application readiness fails | Database unavailable, invalid public URL/issuer, migration failure or resource limits. Check application startup logs and health status. | Correct the actual configuration/database problem and restart; do not edit applied migrations or bypass Flyway validation. | +| Browser/curl certificate error | Wrong hostname, expired/incomplete chain, or CA not trusted. Check the configured URL and certificate through normal client diagnostics. | Install/renew the correct chain and establish intended CA trust. Never disable validation. | +| Redirects or discovery use the wrong address | Wrong configured public URL/issuer or mismatched proxy prefix. Compare `.env`, proxy examples and Connections. | Set equal canonical URLs; preserve prefix; recreate application with `docker compose up -d --no-build --wait`. | +| `/calendar` links fail or discovery is missing | Prefix was stripped or host-root discovery mapping omitted. Check selected proxy example and `curl --head` discovery. | Restore the preserved prefix and explicit well-known mappings; validate proxy before reload. | +| Initialization code is unavailable | Expired, replaced, used, absent or invalidated after repeated failures. It is intentionally not distinguished publicly. | Issue a replacement locally with `bash scripts/initialize.sh`, then re-enter it within 15 minutes. | +| Local initialization refuses after setup | Database already has initialization/account history. Check normal sign-in and your deployment project. | Use ordinary sign-in or controlled recovery. Never delete accounts/setup state to reopen registration. | +| Login fails | Incorrect local credentials, disabled account, wrong primary method or throttle cooldown. | Check username/manager entry, use organization sign-in for managed accounts, allow cooldown, or ask the administrator/operator for controlled recovery. | +| Passkey prompt does not appear | Insecure/wrong URL, unavailable browser capability/provider or expired primary sign-in. | Use configured HTTPS in a supported browser, unlock the intended provider, check account status and sign in again if needed. | +| Prompt closes or reports interaction incomplete | Cancellation, timeout or no available credential can produce the same browser error. | Retry deliberately, select this account's passkey, or use recovery. Do not assume every error is cancellation. | +| Challenge expired/already used | Ceremony exceeded five minutes or was submitted again/from stale state. | Request a fresh prompt. Never replay an old assertion. | +| Network failed after enrollment | Server may have committed while its response was lost. | Use **Check account status**; if enrolled, verify the saved passkey. Review management before creating another. | +| MFA expires while a page remains open | Ten-minute factors expired independently of session idle timeout. | Follow the contextual sign-in/verification action, return to the intended page, and review/resubmit forms yourself. | +| Session invalidated | Password change, recovery, disabling or epoch change ended access. | Sign in again; contact administrator if disabled. A stale page cannot authorize a protected mutation. | +| Application password rejected | Account password used instead, wrong username, expired/revoked password, disabled account or managed-user upstream freshness expired. | Check metadata in Security; issue a replacement after MFA, update client, revoke old access; managed users may need organization sign-in. | +| Client discovers no calendars | No collection/shared grant, wrong URL/prefix, discovery route or client-specific username retention. | Check Calendars & Tasks and configured address; use GNOME's username-bearing address; ask owner to review effective access and refresh discovery. | +| Keycloak unavailable | Provider discovery/login cannot complete. Local startup remains independent. | Restore the provider/certificate/configuration. Use a local administrator for operator work; managed users have no password fallback. Existing freshness is not extended. | +| Import rejected or busy | Wrong collection type, invalid file, UID conflict, 64 MiB/10,000-series/1 MiB-resource bounds, processing budget or temporary capacity. | Read preview/error, preserve original, correct/split the migration, discard an unused preview or retry later. Never assume a conflict overwrote data. | +| Import preview expired after restart | Preview tokens are temporary and do not survive restart. | Check destination if an outcome was uncertain, upload again, review and confirm the new preview. | +| Backup refuses to overwrite | Archive or `.sha256` already exists. | Choose a new private filename. Preserve the earlier backup. | +| Restore refuses running/nonempty target | Safety checks protect existing data. | Stop all application instances and use a separately configured empty database/project. Never remove production data to satisfy the check. | +| Restore reports unsupported/failed/gapped history | Archive history is outside reviewed schema V1–V15 or invalid. | Keep application stopped; use the matching reviewed recovery procedure and original archive. Do not suppress the check. | +| Restored accounts cannot sign in | Restore deliberately disables accounts and revokes credentials. | Independently verify each user and run the documented local/external recovery command, then re-enroll factors. | + +For deeper reference: [operations](operations.md), [portal](portal.md), +[administration](administration.md), [passkeys](passkeys-and-mfa.md), +[account security](account-security.md), [Keycloak](keycloak.md), +[OAuth](oauth.md), [groups](groups.md), and [portability](portability.md). diff --git a/docs/account-security.md b/docs/account-security.md index f9ab274..6eef4a9 100644 --- a/docs/account-security.md +++ b/docs/account-security.md @@ -60,8 +60,7 @@ accepted without current primary authentication and the correct internal account An externally managed account retains its verified issuer/subject mapping. Recovery does not create a local password or bypass upstream account restrictions. If the primary credential is also lost, use the controlled administrator-assisted local -operation documented in [operations](operations.md); the public server does not -provide a first-run or password-reset takeover endpoint. +operation documented in [operations](operations.md); the public server offers only operator-code-protected first initialization, with no password-reset takeover endpoint. ## Password changes and upgrades diff --git a/docs/operations.md b/docs/operations.md index 11f5396..a437bc4 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -178,9 +178,36 @@ location /calendar/ { The metadata URL follows [RFC 8414 §3](https://www.rfc-editor.org/rfc/rfc8414.html#section-3): the well-known segment is inserted before the issuer's path. The Spring application's local metadata endpoint remains inside its servlet context. Use literal configured authority/prefix values in these mappings. The embedded TLS security suite exercises a servlet subpath. The final packaged image passed actual pinned Nginx `/team`, root TLS, cross-site Keycloak and local/federated HTTPS restoration profiles with normal test-CA validation; see [exact image/evidence scope](https://github.com/busystack/caldav-server/blob/f3ba60d360117c44b3dfeb6dc9848778a98ef06a/qualification/evidence/README.md). Later protocol/schema changes require corresponding artifact reruns. +## Protected browser initialization + +Use [Getting Started](GETTING_STARTED.md) as the canonical installation and user +sequence. After startup and HTTPS verification, open the configured URL. On a new +database the dedicated setup screen directs the local operator to run: + +```sh +bash scripts/initialize.sh +``` + +Run from the extracted deployment directory against its healthy database. Only +that one-off local command prints a 256-bit random code. The database stores a +purpose-separated SHA-256 verifier for 15 minutes. Each issuance replaces the +previous code; five invalid attempts invalidate it. The browser form uses CSRF, +no-store and no-referrer. The code is never supplied in a URL. Initialization +locks a singleton database row and uses AccountService transactionally. V15 +permanently closes setup when any account is inserted, including offline bootstrap +and allowlisted federation. Existing accounts, including disabled ones, seed the +closed latch on upgrade. Restore invalidates pending codes and preserves closure. +The first-administrator welcome dismissal is retained only in that installation +record; ordinary-user progress comes from existing resource/security state. + +After browser creation, use normal sign-in, first-passkey enrollment, then a +separate assertion. Registration never grants WebAuthn authentication authority. +The ten-minute policy and management guards are unchanged. A dedicated verification +page avoids refreshing directly into a guarded management page after registration. + ## Local administrator bootstrap -There is no default administrator password or unauthenticated setup endpoint. The local bootstrap command requires an empty account database, a private owner-only password file, and `--spring.main.web-application-type=none`. Use the executable JAR with database configuration supplied securely through environment/configuration: +There is no default administrator password. The official installation uses protected browser setup above; the established offline bootstrap below remains available for controlled operator use only on an untouched empty database. The local bootstrap command requires an empty account database, a private owner-only password file, and `--spring.main.web-application-type=none`. Use the executable JAR with database configuration supplied securely through environment/configuration: ```sh umask 077 @@ -315,7 +342,7 @@ Keep history intact under the supported default. Any future operator pruning int The database contains account/principal mappings, ownership, memberships, calendar representations, revisions, history, DAV credential verifiers, and the implemented OAuth persistence tables. Back up it and the deployment configuration/secret files. Store encrypted backups outside the server, control access, and periodically test restoration. The selected OAuth access-token model uses opaque reference tokens, so it does not require a JWT signing-key file. Any future cryptographic material must be added to the recovery contract before functionality relying on it is released. -From the checkout with the same Compose configuration environment: +From the extracted deployment directory with the same Compose project and configuration: ```sh install -d -m 700 /private/backups @@ -324,16 +351,16 @@ install -d -m 700 /private/backups The script creates a consistent PostgreSQL custom-format archive and a SHA-256 checksum with private file permissions. It refuses to overwrite an existing archive. Retain the exact application version, Compose configuration, and secret material separately. Never publish backups as CI artifacts. -Restore only to a newly initialized, isolated database. Stop every application instance first. The script accepts a complete, unique, successful migration history from V1 through at most V14; failed, missing, duplicate, gapped and future histories fail closed. It refuses a running application or any nonempty target database and never removes an existing volume or database: +Restore only to a newly initialized, isolated database. Stop every application instance first. The script accepts a complete, unique, successful migration history from V1 through at most V15; failed, missing, duplicate, gapped and future histories fail closed. It refuses a running application or any nonempty target database and never removes an existing volume or database: ```sh docker compose stop application ./scripts/restore.sh /private/backups/caldav-2026-10-27.dump ``` -After loading an archive at schema versions 1 through 13, restoration disables all accounts, changes the durable `system_state.recovery_epoch`, deletes all restored DAV credentials, passkeys and OAuth authorizations/consents, and revokes refresh-token families. It also deletes JDBC browser sessions, single-use recovery codes, WebAuthn ceremony records and login-throttle state, rotates every account security epoch and records the restore in the security audit. It preserves external issuer/subject mappings but expires their upstream-authentication timestamps. Sync tokens include the changed epoch; pre-restore tokens must be rejected. Disabling restored accounts and removing restored credentials/grants prevents passwords or credentials changed/revoked after the backup from silently becoming valid again. DAV bindings, folders, dead properties, sharing groups, group memberships/grants and the retired-principal identity registry remain authoritative data and are retained. Registered OAuth clients remain registered, but users must authorize fresh grants. If loading or invalidation fails, leave the application stopped and investigate. This script refuses later migrations until the recovery policy is updated for new persisted security state. +After loading an archive at schema versions 1 through 15, restoration disables all accounts, changes the durable `system_state.recovery_epoch`, deletes all restored DAV credentials, passkeys and OAuth authorizations/consents, and revokes refresh-token families. It also deletes JDBC browser sessions, single-use recovery codes, WebAuthn ceremony records and login-throttle state, rotates every account security epoch and records the restore in the security audit. It preserves external issuer/subject mappings but expires their upstream-authentication timestamps. Sync tokens include the changed epoch; pre-restore tokens must be rejected. Disabling restored accounts and removing restored credentials/grants prevents passwords or credentials changed/revoked after the backup from silently becoming valid again. DAV bindings, folders, dead properties, sharing groups, group memberships/grants and the retired-principal identity registry remain authoritative data and are retained. Registered OAuth clients remain registered, but users must authorize fresh grants. If loading or invalidation fails, leave the application stopped and investigate. This script refuses later migrations until the recovery policy is updated for new persisted security state. -Keep **all** application instances stopped while loading and invalidating restored state. For a supported older archive, including the reviewed V9 schema, the current image can then start with every account disabled to apply forward migrations; stop it again before controlled account recovery. This is an offline upgrade arrangement, not a rolling upgrade. Do not start another older application instance against the upgraded database. The required operations harness exercises both same-version restoration and V9 restoration followed by migration to V14. +Keep **all** application instances stopped while loading and invalidating restored state. For a supported older archive, including the reviewed V9 schema, the current image can then start with every account disabled to apply forward migrations; stop it again before controlled account recovery. This is an offline upgrade arrangement, not a rolling upgrade. Do not start another older application instance against the upgraded database. The required operations harness exercises both same-version restoration and V9 restoration followed by migration to V15. After independently verifying a user's identity, use the controlled local recovery operation with an owner-only file containing a fresh password: @@ -371,6 +398,6 @@ Take and verify a backup, retain the previous application artifact/configuration python3 scripts/build-image.py --compose up -d --no-build --no-deps --wait application ``` -Keep the same Compose project, secret paths and public URL. Inspect startup/migration status and verify discovery, an existing resource and synchronization before reopening access. Flyway applies versioned migrations and validates their checksums at startup; production schema auto-mutation is not enabled. Migrations are forward-only unless a particular migration has a separately tested reversal. Rolling back a JAR does not safely roll back a database schema. Version @VERSION@ uses migrations V1–V14. V14 adds nullable opaque administrative audit targets and preserves historical entries; published migrations remain unchanged. +Keep the same Compose project, secret paths and public URL. Inspect startup/migration status and verify discovery, an existing resource and synchronization before reopening access. Flyway applies versioned migrations and validates their checksums at startup; production schema auto-mutation is not enabled. Migrations are forward-only unless a particular migration has a separately tested reversal. Rolling back a JAR does not safely roll back a database schema. Version @VERSION@ uses migrations V1–V15. V14 adds nullable opaque administrative audit targets; V15 adds protected installation state and invalidates outstanding initialization codes during restore; published migrations remain unchanged. The native Thunderbird and Python client results are scoped to their recorded versions and interoperability profile; see [client evidence](../qualification/clients/README.md). This Compose arrangement provides no high availability, automatic failover or measured user-capacity guarantee. The [executed workload record](performance.md) reports the actual host/image/dataset, end-to-end latency, sampled memory/CPU and PostgreSQL behavior; raw evidence is retained separately. It is one sequential client, not a user-capacity or concurrency guarantee. diff --git a/docs/passkeys-and-mfa.md b/docs/passkeys-and-mfa.md index 4824524..60a078a 100644 --- a/docs/passkeys-and-mfa.md +++ b/docs/passkeys-and-mfa.md @@ -14,7 +14,7 @@ The application binds an assertion to the account and credential selected by its The server serializes each session's registration/authentication ceremonies and consumes their challenges once. Challenges expire after five minutes on the server. Registration challenges remain associated with the authenticated session. Failed assertions consume their challenge and require requesting fresh options. PostgreSQL transactions serialize writes for a credential; credential ownership and public key are immutable, counters cannot regress, and deletion records prevent a previously read assertion from reinserting a removed credential. Session IDs rotate after successful password or passkey authentication. Account disabling is checked for existing browser sessions and during passkey authentication. -The local operator recovery command is documented in [operations](operations.md). It resets the selected account's password and revokes independently issued access, including registered passkeys. Use the documented offline procedure with a private password file. Recovery requires control of the server and database; there is no public first-run or recovery endpoint. Stop all application instances before this offline operation and restart afterward, as required by the supported procedure. Persistent account security epochs also reject old sessions and ceremonies; assertions check the captured epoch before updating credential state. This does not create an online recovery endpoint. Keep another administrator and more than one authenticator where appropriate. +The local operator recovery command is documented in [operations](operations.md). It resets the selected account's password and revokes independently issued access, including registered passkeys. Use the documented offline procedure with a private password file. Recovery requires control of the server and database; initial setup uses a locally issued single-use code; there is no public account-recovery bypass. Stop all application instances before this offline operation and restart afterward, as required by the supported procedure. Persistent account security epochs also reject old sessions and ceremonies; assertions check the captured epoch before updating credential state. This does not create an online recovery endpoint. Keep another administrator and more than one authenticator where appropriate. Implementation evidence is in `PasskeyCeremonyGuardTest`, `PasskeyPersistenceIT`, and the separate Chromium virtual-authenticator qualification harness. Check the qualification record for actual executed results. Database round-trip tests do not establish cryptographic verification, and a virtual authenticator does not qualify every hardware or synced passkey provider. diff --git a/docs/portal.md b/docs/portal.md index af64a80..d25d5c9 100644 --- a/docs/portal.md +++ b/docs/portal.md @@ -7,8 +7,7 @@ provider, email service or vendor account. ## First sign-in Open your operator's configured HTTPS address. Verify your local password, or use -the configured organization sign-in. Enroll your first passkey under **Security → -Passkeys**, then verify that passkey to complete MFA. Registration alone does not +the configured organization sign-in. After primary sign-in, **Secure your account** guides first enrollment. Create the passkey, then choose **Verify your passkey** to complete MFA. Returning users verify the existing passkey. Registration alone does not complete authentication. Sensitive changes require primary sign-in and passkey verification within ten minutes. The overview and security pages explain which step is needed. Renew both factors for the same account when they expire. @@ -56,8 +55,7 @@ clients must perform initial synchronization when a token is rejected. ## Connect an application -Open **Connections**, then issue a named credential under **Security → DAV -credentials**. Copy its once-shown secret directly into the application's password +Open **Connections**, select the application, then create an application password under **Security → Application passwords**. Copy its once-shown secret directly into the application's password settings. The account password is not the DAV password. Secrets cannot be retrieved later. Credential labels, creation/expiration and active/expired/revoked status are available without displaying verifiers. To replace one, issue a replacement, diff --git a/qualification/release/test_release.py b/qualification/release/test_release.py index 7ee0732..c0eeca7 100644 --- a/qualification/release/test_release.py +++ b/qualification/release/test_release.py @@ -74,7 +74,7 @@ def fixture(version='0.1.0'): root.mkdir() git(root, 'init', '--quiet', '--initial-branch=main') paths = ['pom.xml', 'Dockerfile', 'compose.yaml', 'LICENSE', 'NOTICE', 'THIRD-PARTY-NOTICES', - 'scripts/init-db.sh', 'scripts/backup.sh', 'scripts/restore.sh', *bundle.OPERATOR_DOCUMENTS] + 'scripts/init-db.sh', 'scripts/backup.sh', 'scripts/restore.sh', 'scripts/initialize.sh', *bundle.OPERATOR_DOCUMENTS, *bundle.SCREENSHOTS] for base in ('deployment', 'licenses', 'src/main/resources/META-INF/licenses'): paths.extend(str(p.relative_to(ROOT)) for p in (ROOT / base).rglob('*') if p.is_file()) for name in paths: diff --git a/scripts/initialize.sh b/scripts/initialize.sh new file mode 100755 index 0000000..fc5a3f4 --- /dev/null +++ b/scripts/initialize.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +# Run from the extracted deployment directory. Only this local one-off process +# prints the secret, after the verifier transaction has committed. +docker compose run --rm --no-deps -T application \ + --spring.main.web-application-type=none \ + --spring.main.banner-mode=off --logging.level.root=OFF \ + --busystack.issue-initialization-code=true diff --git a/scripts/release-bundle.py b/scripts/release-bundle.py index 8fe6e6a..fe0496f 100644 --- a/scripts/release-bundle.py +++ b/scripts/release-bundle.py @@ -7,6 +7,7 @@ import io import json import os +import posixpath from pathlib import Path import re import shutil @@ -18,6 +19,10 @@ ROOT = Path(__file__).resolve().parents[1] OPERATOR_DOCUMENTS = ( + 'docs/GETTING_STARTED.md', + 'docs/portal.md', + 'docs/administration.md', + 'docs/portability.md', 'docs/operations.md', 'docs/account-security.md', 'docs/calendar-semantics.md', @@ -31,6 +36,27 @@ 'docs/versions.md', 'docs/adr/0004-resumable-synchronization.md', ) +SCREENSHOTS = tuple(f'docs/images/getting-started/{number:02d}-{name}.png' for number, name in enumerate(( + 'initial-setup', 'create-administrator', 'setup-complete', 'sign-in', 'create-passkey', + 'passkey-created', 'verify-passkey', 'administrator-welcome', 'manage-users', 'create-user', + 'user-onboarding', 'calendars', 'connect-application', 'create-application-password', + 'password-created', 'client-configuration', 'security', 'recovery', 'sharing', 'import-export'), 1)) + + +def validate_guide(files): + """Missing illustrations or broken local guide links fail artifact validation.""" + guide = 'docs/GETTING_STARTED.md' + text = files[guide].decode() + for name in SCREENSHOTS: + assert name in files, 'Missing guide screenshot: ' + name + assert files[name].startswith(b'\x89PNG\r\n\x1a\n'), 'Invalid guide PNG: ' + name + for target in re.findall(r'!?\[[^\]]*\]\(([^)]+)\)', text): + if target.startswith(('https://', 'http://', '#', 'mailto:')): + continue + path = posixpath.normpath(posixpath.join('docs', target.split('#')[0])) + assert path in files, 'Broken guide reference: ' + target + for name in SCREENSHOTS: + assert name.removeprefix('docs/') in text, 'Unreferenced guide screenshot: ' + name spec = importlib.util.spec_from_file_location('candidate', ROOT / 'scripts/release-candidate.py') candidate = importlib.util.module_from_spec(spec) spec.loader.exec_module(candidate) @@ -72,10 +98,15 @@ def content(name, render=False): return data.replace(b'@VERSION@', version.encode()) if render else data for name in qualified.under('deployment'): files[name.removeprefix('deployment/')] = content(name, render=True) - for name in ('init-db.sh', 'backup.sh', 'restore.sh'): + for name in ('init-db.sh', 'backup.sh', 'restore.sh', 'initialize.sh'): files['scripts/' + name] = content('scripts/' + name) for name in (*OPERATOR_DOCUMENTS, f'docs/releases/{version}.md'): files[name] = content(name, render=True) + for name in SCREENSHOTS: + files[name] = content(name) + for name in ('nginx-root.conf.example', 'nginx-subpath.conf.example'): + files['deployment/' + name] = content('deployment/' + name, render=True) + validate_guide(files) receipt = versions.receipt_path(version) files[receipt] = content(receipt) notices = {name: content(name) for name in ('LICENSE', 'NOTICE', 'THIRD-PARTY-NOTICES')} @@ -147,6 +178,7 @@ def validate_assets(directory, version=None, source_sha=None): contents = {p.name.removeprefix(prefix): archive.extractfile(p).read() for p in members} assert len(contents) == len(members), 'Duplicate deployment entries' assert {name: hashlib.sha256(data).hexdigest() for name, data in contents.items()} == manifest['deploymentFiles'], 'Deployment content mismatch' + validate_guide(contents) assert 'build:' not in contents['compose.yaml'].decode() and manifest['container']['image'].encode() in contents['compose.yaml'] with tarfile.open(directory / 'notices.tar.gz') as archive: for member in archive: diff --git a/scripts/restore.sh b/scripts/restore.sh index d191506..1748a40 100755 --- a/scripts/restore.sh +++ b/scripts/restore.sh @@ -39,8 +39,8 @@ BEGIN IF NOT EXISTS (SELECT 1 FROM flyway_schema_history WHERE version='1' AND success) THEN RAISE EXCEPTION 'Missing V1 migration history; leave application stopped'; END IF; - IF EXISTS (SELECT 1 FROM flyway_schema_history WHERE version IS NOT NULL AND version NOT IN ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14')) THEN - RAISE EXCEPTION 'This recovery script supports schema versions 1 through 14 only; leave application stopped and update recovery procedure'; + IF EXISTS (SELECT 1 FROM flyway_schema_history WHERE version IS NOT NULL AND version NOT IN ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15')) THEN + RAISE EXCEPTION 'This recovery script supports schema versions 1 through 15 only; leave application stopped and update recovery procedure'; END IF; IF EXISTS (SELECT version FROM flyway_schema_history WHERE version IS NOT NULL GROUP BY version HAVING count(*) <> 1) THEN RAISE EXCEPTION 'Duplicate migration versions; leave application stopped'; @@ -52,6 +52,11 @@ BEGIN IF to_regclass('public.sync_continuations') IS NOT NULL THEN DELETE FROM sync_continuations; END IF; + IF to_regclass('public.installation_state') IS NOT NULL THEN + UPDATE installation_state SET code_verifier=NULL,expires_at=NULL,failed_attempts=0, + initialized=initialized OR EXISTS(SELECT 1 FROM accounts), + welcome_completed_at=CASE WHEN initialized THEN now() ELSE welcome_completed_at END; + END IF; UPDATE system_state SET recovery_epoch = gen_random_uuid(); GET DIAGNOSTICS affected = ROW_COUNT; IF affected <> 1 THEN diff --git a/scripts/verify-operations.py b/scripts/verify-operations.py index ecb7236..09e1346 100644 --- a/scripts/verify-operations.py +++ b/scripts/verify-operations.py @@ -346,9 +346,9 @@ def verify(args, initial_version): compose(restored, "up", "-d", "--no-build", "--wait", "--wait-timeout", "240", "application") checks(restored) assert sql(restored, "SELECT count(*) FROM accounts WHERE enabled;") == "0" - assert sql(restored, "SELECT string_agg(version,',' ORDER BY installed_rank) FROM flyway_schema_history WHERE success AND version IS NOT NULL;") == "1,2,3,4,5,6,7,8,9,10,11,12,13,14" + assert sql(restored, "SELECT string_agg(version,',' ORDER BY installed_rank) FROM flyway_schema_history WHERE success AND version IS NOT NULL;") == "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15" compose(restored, "stop", "application") - print("OPERATIONS_V9_INVALIDATION_THEN_STARTUP_UPGRADE_TO_V14_PASSED", flush=True) + print("OPERATIONS_V9_INVALIDATION_THEN_STARTUP_UPGRADE_TO_V15_PASSED", flush=True) result = json.loads( sql( restored, @@ -462,7 +462,7 @@ def negative_restores(source, private, projects): restore_history = "DELETE FROM flyway_schema_history; INSERT INTO flyway_schema_history SELECT * FROM json_populate_recordset(NULL::flyway_schema_history,'" + escaped + "'::json);" appended = "INSERT INTO flyway_schema_history(installed_rank,version,description,type,script,checksum,installed_by,execution_time,success) SELECT max(installed_rank)+1,{version},'Deliberate negative fixture','SQL','negative.sql',0,'busystack',0,true FROM flyway_schema_history;" cases = [ - ("future", appended.format(version="'15'"), "supports schema versions 1 through 14"), + ("future", appended.format(version="'16'"), "supports schema versions 1 through 15"), ("failed", "UPDATE flyway_schema_history SET success=false WHERE version='13';", "Failed migration history"), ("gap", "DELETE FROM flyway_schema_history WHERE version='6';", "Gap in migration history"), ("duplicate", appended.format(version="'13'"), "Duplicate migration versions"), diff --git a/src/main/java/org/busystack/caldav/BusyStackApplication.java b/src/main/java/org/busystack/caldav/BusyStackApplication.java index da9bc80..65b3bbd 100644 --- a/src/main/java/org/busystack/caldav/BusyStackApplication.java +++ b/src/main/java/org/busystack/caldav/BusyStackApplication.java @@ -17,6 +17,7 @@ public static void main(String[] args) { long operations = java.util.stream.Stream.of( "busystack.bootstrap", + "busystack.issue-initialization-code", "busystack.recover-account", "busystack.recover-external-account") .filter(name -> environment.getProperty(name, Boolean.class, false)) diff --git a/src/main/java/org/busystack/caldav/account/AccountService.java b/src/main/java/org/busystack/caldav/account/AccountService.java index fcd31dc..c6e9847 100644 --- a/src/main/java/org/busystack/caldav/account/AccountService.java +++ b/src/main/java/org/busystack/caldav/account/AccountService.java @@ -70,8 +70,7 @@ public boolean isExternallyManaged(UUID accountId) { public UUID provision( String username, String displayName, String password, boolean administrator) { validatePassword(password); - if (username == null - || !username.matches("[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}") + if (!validUsername(username) || displayName == null || displayName.isBlank() || displayName.codePointCount(0, displayName.length()) > 200 @@ -93,6 +92,10 @@ private static void validatePassword(String password) { org.busystack.caldav.security.password.PasswordPolicy.validate(password); } + public static boolean validUsername(String username) { + return username != null && username.matches("[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}"); + } + /** Operator-only recovery entry point. No controller exposes this operation. */ @Transactional public void recoverOffline(String username, String replacementPassword) { diff --git a/src/main/java/org/busystack/caldav/account/BootstrapAdministrator.java b/src/main/java/org/busystack/caldav/account/BootstrapAdministrator.java index 82fff07..7b9c45c 100644 --- a/src/main/java/org/busystack/caldav/account/BootstrapAdministrator.java +++ b/src/main/java/org/busystack/caldav/account/BootstrapAdministrator.java @@ -33,7 +33,11 @@ public void run(ApplicationArguments args) throws Exception { if (!"none".equals(environment.getProperty("spring.main.web-application-type"))) throw new IllegalArgumentException( "Bootstrap requires --spring.main.web-application-type=none"); - jdbc.execute("LOCK TABLE accounts IN EXCLUSIVE MODE"); + jdbc.queryForObject("SELECT id FROM installation_state WHERE id=1 FOR UPDATE", Integer.class); + if (Boolean.TRUE.equals( + jdbc.queryForObject( + "SELECT initialized FROM installation_state WHERE id=1", Boolean.class))) + throw new IllegalStateException("Bootstrap is unavailable after initialization"); if (jdbc.queryForObject("SELECT count(*) FROM accounts", Long.class) != 0) throw new IllegalStateException("Bootstrap is permitted only on an empty account database"); String username = environment.getRequiredProperty("busystack.bootstrap-username"); diff --git a/src/main/java/org/busystack/caldav/account/InitializationController.java b/src/main/java/org/busystack/caldav/account/InitializationController.java new file mode 100644 index 0000000..ec4fcc5 --- /dev/null +++ b/src/main/java/org/busystack/caldav/account/InitializationController.java @@ -0,0 +1,45 @@ +package org.busystack.caldav.account; + +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; + +@Controller +public class InitializationController { + private final InitializationService initialization; + + public InitializationController(InitializationService initialization) { + this.initialization = initialization; + } + + @GetMapping({"/setup", "/setup/administrator"}) + public String setup( + jakarta.servlet.http.HttpServletRequest request, HttpServletResponse response) { + protect(response); + if (!initialization.available()) return "redirect:/login"; + return request.getServletPath().endsWith("/administrator") ? "setup-administrator" : "setup"; + } + + @PostMapping("/setup/administrator") + public String create( + @RequestParam(defaultValue = "") String code, + @RequestParam(defaultValue = "") String username, + @RequestParam(defaultValue = "") String password, + @RequestParam(defaultValue = "") String confirmation, + Model model, + HttpServletResponse response) { + protect(response); + var errors = initialization.initialize(code, username, password, confirmation); + if (errors.isEmpty()) return "setup-complete"; + response.setStatus(400); + model.addAttribute("errors", errors); + model.addAttribute("username", username.length() <= 64 ? username : ""); + return "setup-administrator"; + } + + private static void protect(HttpServletResponse response) { + response.setHeader("Cache-Control", "no-store"); + response.setHeader("Referrer-Policy", "no-referrer"); + } +} diff --git a/src/main/java/org/busystack/caldav/account/InitializationService.java b/src/main/java/org/busystack/caldav/account/InitializationService.java new file mode 100644 index 0000000..f129746 --- /dev/null +++ b/src/main/java/org/busystack/caldav/account/InitializationService.java @@ -0,0 +1,102 @@ +package org.busystack.caldav.account; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.sql.Timestamp; +import java.time.Instant; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; +import org.busystack.caldav.security.password.PasswordPolicy; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** Local issuance and a bounded, transactional browser claim. Never logs supplied values. */ +@Service +public class InitializationService { + private final JdbcTemplate jdbc; + private final AccountService accounts; + + public InitializationService(JdbcTemplate jdbc, AccountService accounts) { + this.jdbc = jdbc; + this.accounts = accounts; + } + + public boolean available() { + return Boolean.TRUE.equals( + jdbc.queryForObject( + "SELECT NOT initialized FROM installation_state WHERE id=1", Boolean.class)); + } + + @Transactional + public String issueCode() { + lock(); + if (!available()) + throw new IllegalStateException("Administrator initialization is unavailable"); + byte[] random = new byte[32]; + new SecureRandom().nextBytes(random); + String code = Base64.getUrlEncoder().withoutPadding().encodeToString(random); + jdbc.update( + "UPDATE installation_state SET code_verifier=?,expires_at=?,failed_attempts=0 WHERE id=1", + verifier(code), + Timestamp.from(Instant.now().plusSeconds(900))); + return code; + } + + /** Invalid attempts return normally so their durable counters are committed. */ + @Transactional + public Map initialize( + String code, String username, String password, String confirmation) { + lock(); + var row = jdbc.queryForMap("SELECT * FROM installation_state WHERE id=1"); + byte[] expected = (byte[]) row.get("code_verifier"); + boolean matches = + code != null + && code.matches("[A-Za-z0-9_-]{43}") + && expected != null + && MessageDigest.isEqual(expected, verifier(code)); + if (Boolean.TRUE.equals(row.get("initialized")) + || !matches + || !((Timestamp) row.get("expires_at")).toInstant().isAfter(Instant.now())) { + jdbc.update( + "UPDATE installation_state SET failed_attempts=LEAST(5,failed_attempts+1)," + + "code_verifier=CASE WHEN failed_attempts>=4 THEN NULL ELSE code_verifier END," + + "expires_at=CASE WHEN failed_attempts>=4 THEN NULL ELSE expires_at END WHERE id=1"); + return Map.of( + "code", "Initialization code is unavailable. Obtain a fresh code locally and try again."); + } + Map errors = new LinkedHashMap<>(); + if (!AccountService.validUsername(username)) + errors.put( + "username", + "Use 1–64 letters, numbers, dots, underscores or hyphens, starting with a letter or number."); + try { + PasswordPolicy.validate(password); + } catch (IllegalArgumentException invalid) { + errors.put("password", invalid.getMessage()); + } + if (password == null || !password.equals(confirmation)) + errors.put("confirmation", "The passwords must match."); + if (!errors.isEmpty()) return errors; + var id = accounts.provision(username, username, password, true); + jdbc.update( + "UPDATE installation_state SET initial_administrator=?,code_verifier=NULL,expires_at=NULL WHERE id=1", + id); + return Map.of(); + } + + private void lock() { + jdbc.queryForObject("SELECT id FROM installation_state WHERE id=1 FOR UPDATE", Integer.class); + } + + private static byte[] verifier(String code) { + try { + return MessageDigest.getInstance("SHA-256") + .digest(("busystack-initialization-v1:" + code).getBytes(StandardCharsets.US_ASCII)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } +} diff --git a/src/main/java/org/busystack/caldav/account/IssueInitializationCode.java b/src/main/java/org/busystack/caldav/account/IssueInitializationCode.java new file mode 100644 index 0000000..8803f11 --- /dev/null +++ b/src/main/java/org/busystack/caldav/account/IssueInitializationCode.java @@ -0,0 +1,24 @@ +package org.busystack.caldav.account; + +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Component; + +/** Only activated by the local, non-web operator invocation. */ +@Component +@ConditionalOnProperty(name = "busystack.issue-initialization-code", havingValue = "true") +public class IssueInitializationCode implements ApplicationRunner { + private final InitializationService initialization; + + public IssueInitializationCode(InitializationService initialization) { + this.initialization = initialization; + } + + @Override + public void run(ApplicationArguments args) { + String code = initialization.issueCode(); // Transaction commits before disclosure. + System.out.println("Initialization code (single use, valid for 15 minutes):"); + System.out.println(code); + } +} diff --git a/src/main/java/org/busystack/caldav/management/FormRecovery.java b/src/main/java/org/busystack/caldav/management/FormRecovery.java index 822276a..7cc0242 100644 --- a/src/main/java/org/busystack/caldav/management/FormRecovery.java +++ b/src/main/java/org/busystack/caldav/management/FormRecovery.java @@ -79,6 +79,10 @@ else if (path.matches("/collections/[a-f0-9-]{36}/edit")) { model.addAttribute("groupChoices", groups.choices(auth)); view = "collection-sharing"; } else if (path.equals("/credentials")) { + model.addAttribute( + "client", + PortalController.client( + Objects.requireNonNullElse(request.getParameter("client"), "generic"))); model.addAttribute("credentialPage", portal.credentials(auth, 0)); view = "credentials"; } else if (path.equals("/portability/preview")) { diff --git a/src/main/java/org/busystack/caldav/management/ManagementController.java b/src/main/java/org/busystack/caldav/management/ManagementController.java index 91741e1..cbaddc2 100644 --- a/src/main/java/org/busystack/caldav/management/ManagementController.java +++ b/src/main/java/org/busystack/caldav/management/ManagementController.java @@ -25,9 +25,25 @@ String dashboard(Authentication auth, Model model) { model.addAttribute("account", management.current(auth)); model.addAttribute("setup", portal.setup(auth)); model.addAttribute("recentCollections", portal.collections(auth, "all", "", 0)); + if (management.administratorWelcome(auth)) { + if (!org.busystack.caldav.security.RecentAuthentication.mfaCurrent(auth)) + return "redirect:/auth/continue"; + return "administrator-welcome"; + } return "dashboard"; } + @PostMapping("/welcome") + String welcome(Authentication auth, @RequestParam String activity) { + if (!java.util.Set.of("personal", "users").contains(activity)) + throw new IllegalArgumentException("Choose an activity"); + if (activity.equals("users")) management.requireAdministrator(auth); + management.completeWelcome(auth); + return activity.equals("users") + ? "redirect:/admin/accounts" + : "redirect:/collections?scope=all"; + } + @PostMapping("/collections") String createCollection( Authentication auth, @@ -62,10 +78,14 @@ String issue( Authentication auth, @RequestParam(defaultValue = "") String label, @RequestParam int days, + @RequestParam(defaultValue = "generic") String client, Model model, jakarta.servlet.http.HttpServletResponse response) { + model.addAttribute("client", PortalController.client(client)); + model.addAttribute("label", label); model.addAttribute("credential", management.issue(auth, label, days)); response.setHeader("Cache-Control", "no-store"); + response.setHeader("Referrer-Policy", "no-referrer"); return "issued-credential"; } diff --git a/src/main/java/org/busystack/caldav/management/ManagementService.java b/src/main/java/org/busystack/caldav/management/ManagementService.java index dbbac7c..758a2f8 100644 --- a/src/main/java/org/busystack/caldav/management/ManagementService.java +++ b/src/main/java/org/busystack/caldav/management/ManagementService.java @@ -64,6 +64,33 @@ public boolean externallyManaged(Authentication auth) { return accounts.isExternallyManaged(requireAccount(auth).id()); } + public boolean hasPasskeys(Authentication auth) { + return Boolean.TRUE.equals( + jdbc.queryForObject( + "SELECT EXISTS(SELECT 1 FROM user_credentials c JOIN user_entities u ON u.id=c.user_entity_user_id JOIN accounts a ON a.id=u.account_id WHERE a.username=?)", + Boolean.class, + auth.getName())); + } + + public boolean administratorWelcome(Authentication auth) { + var account = requireAccount(auth); + return account.administrator() + && Boolean.TRUE.equals( + jdbc.queryForObject( + "SELECT initial_administrator=? AND welcome_completed_at IS NULL FROM installation_state WHERE id=1", + Boolean.class, + account.id())); + } + + @Transactional + public void completeWelcome(Authentication auth) { + RecentAuthentication.requireMfa(auth); + var account = requireAccount(auth); + jdbc.update( + "UPDATE installation_state SET welcome_completed_at=now() WHERE initial_administrator=? AND welcome_completed_at IS NULL", + account.id()); + } + public List collections(Authentication auth) { return calendars.collections(requireAccount(auth).id()); } diff --git a/src/main/java/org/busystack/caldav/management/PortalController.java b/src/main/java/org/busystack/caldav/management/PortalController.java index a707147..4af731c 100644 --- a/src/main/java/org/busystack/caldav/management/PortalController.java +++ b/src/main/java/org/busystack/caldav/management/PortalController.java @@ -94,7 +94,12 @@ String sharing( } @GetMapping("/connections") - String connections(Authentication auth, @RequestParam(defaultValue = "0") int page, Model model) { + String connections( + Authentication auth, + @RequestParam(defaultValue = "0") int page, + @RequestParam(required = false) String client, + Model model) { + if (client != null) model.addAttribute("client", client(client)); model.addAttribute("collectionPage", portal.collections(auth, "all", "", page)); return "connections"; } @@ -106,8 +111,19 @@ String security(Authentication auth, Model model) { } @GetMapping("/security/credentials") - String credentials(Authentication auth, @RequestParam(defaultValue = "0") int page, Model model) { + String credentials( + Authentication auth, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "generic") String client, + Model model) { + model.addAttribute("client", client(client)); model.addAttribute("credentialPage", portal.credentials(auth, page)); return "credentials"; } + + static String client(String client) { + return java.util.Set.of("thunderbird", "gnome", "generic").contains(client) + ? client + : "generic"; + } } diff --git a/src/main/java/org/busystack/caldav/management/PortalPageAdvice.java b/src/main/java/org/busystack/caldav/management/PortalPageAdvice.java index 5cfde53..eec1bcc 100644 --- a/src/main/java/org/busystack/caldav/management/PortalPageAdvice.java +++ b/src/main/java/org/busystack/caldav/management/PortalPageAdvice.java @@ -23,6 +23,11 @@ void layout(Authentication auth, HttpServletRequest request, Model model) { String path = request.getServletPath(); if (path.equals("/dav") || path.startsWith("/dav/") || path.startsWith("/.well-known/")) return; model.addAttribute("portalPath", path); + model.addAttribute( + "authenticationNext", + request.getContextPath() + + path + + (request.getQueryString() == null ? "" : "?" + request.getQueryString())); model.addAttribute("administrationArea", path.startsWith("/admin")); model.addAttribute("viewer", null); model.addAttribute("primaryCurrent", RecentAuthentication.primaryCurrent(auth)); @@ -31,6 +36,7 @@ void layout(Authentication auth, HttpServletRequest request, Model model) { try { model.addAttribute("viewer", management.current(auth)); model.addAttribute("externallyManaged", management.externallyManaged(auth)); + model.addAttribute("hasPasskeys", management.hasPasskeys(auth)); } catch (org.springframework.security.access.AccessDeniedException | org.springframework.dao.DataAccessException unavailable) { // Safe error layouts remain renderable after account revocation or a database outage. diff --git a/src/main/java/org/busystack/caldav/security/AuthenticationJourney.java b/src/main/java/org/busystack/caldav/security/AuthenticationJourney.java new file mode 100644 index 0000000..3ff6bbb --- /dev/null +++ b/src/main/java/org/busystack/caldav/security/AuthenticationJourney.java @@ -0,0 +1,92 @@ +package org.busystack.caldav.security; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.net.URI; +import org.busystack.caldav.config.DeploymentProperties; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.savedrequest.HttpSessionRequestCache; +import org.springframework.stereotype.Component; + +/** Continuations are application paths, never request-host-derived absolute redirects. */ +@Component +public class AuthenticationJourney { + private static final String DESTINATION = "BUSYSTACK_CONTINUATION"; + private final String prefix; + private final HttpSessionRequestCache cache = new HttpSessionRequestCache(); + + public AuthenticationJourney(DeploymentProperties deployment) { + prefix = deployment.publicBaseUrl().getPath(); + } + + public String safe(String candidate) { + if (candidate == null + || !candidate.startsWith(prefix + "/") + || candidate.contains("\\") + || candidate.contains("//") + || candidate.matches(".*(?:^|/)\\.{1,2}(?:/|[?]|$).*") + || candidate.contains("%") + || candidate.codePoints().anyMatch(Character::isISOControl)) return prefix + "/"; + try { + URI uri = URI.create(candidate); + String path = uri.getPath(); + if (uri.isAbsolute() + || uri.getRawAuthority() != null + || uri.getFragment() != null + || !uri.normalize().getPath().equals(path)) return prefix + "/"; + String local = path.substring(prefix.length()); + if (local.startsWith("/login") + || local.startsWith("/setup") + || local.startsWith("/auth/") + || local.startsWith("/webauthn/") + || local.equals("/logout")) return prefix + "/"; + return candidate; + } catch (IllegalArgumentException invalid) { + return prefix + "/"; + } + } + + public void remember(HttpServletRequest request, String destination) { + request.getSession().setAttribute(DESTINATION, safe(destination)); + } + + public void capture(HttpServletRequest request, HttpServletResponse response) { + var saved = cache.getRequest(request, response); + if (saved != null) { + if ("GET".equals(saved.getMethod())) { + URI uri = URI.create(saved.getRedirectUrl()); + // Keep encoded query values (OAuth state/PKCE), but validate the path separately. + String path = safe(uri.getRawPath()); + String query = uri.getRawQuery(); + remember(request, path); + if (path.equals(uri.getRawPath()) + && query != null + && !query.codePoints().anyMatch(Character::isISOControl)) + request.getSession().setAttribute(DESTINATION, path + "?" + query); + } + cache.removeRequest(request, response); + } + } + + public String destination(HttpServletRequest request) { + Object value = request.getSession().getAttribute(DESTINATION); + return value instanceof String path ? path : prefix + "/"; + } + + public void primarySuccess( + HttpServletRequest request, HttpServletResponse response, Authentication auth) + throws IOException { + capture(request, response); + response.sendRedirect(prefix + "/auth/continue"); + } + + public void passkeySuccess( + HttpServletRequest request, HttpServletResponse response, Authentication auth) + throws IOException { + capture(request, response); + response.setHeader("Cache-Control", "no-store"); + response.setContentType("application/json"); + response.getWriter().write("{\"redirectUrl\":\"" + prefix + "/auth/continue?verified\"}"); + } +} diff --git a/src/main/java/org/busystack/caldav/security/SecurityConfiguration.java b/src/main/java/org/busystack/caldav/security/SecurityConfiguration.java index 83a2d00..33d0b30 100644 --- a/src/main/java/org/busystack/caldav/security/SecurityConfiguration.java +++ b/src/main/java/org/busystack/caldav/security/SecurityConfiguration.java @@ -145,6 +145,7 @@ SecurityFilterChain browserSecurity( org.busystack.caldav.security.passkey.CeremonyStore ceremonies, org.busystack.caldav.security.session.SessionSecurity sessions, org.busystack.caldav.security.throttle.LoginThrottleService throttle, + AuthenticationJourney journey, org.springframework.beans.factory.ObjectProvider< org.busystack.caldav.security.oidc.OidcLoginSupport> upstreamUsers, @@ -158,6 +159,8 @@ SecurityFilterChain browserSecurity( "/.well-known/caldav", "/assets/**", "/login", + "/setup", + "/setup/administrator", "/login/webauthn", "/oauth2/authorization/**", "/login/oauth2/code/**", @@ -171,7 +174,8 @@ SecurityFilterChain browserSecurity( .hasRole("ADMIN") .anyRequest() .authenticated()) - .formLogin(login -> login.loginPage("/login").permitAll()) + .formLogin( + login -> login.loginPage("/login").successHandler(journey::primarySuccess).permitAll()) // This endpoint only returns a configured 308; it has no cookie-authenticated mutation. .csrf(csrf -> csrf.ignoringRequestMatchers("/.well-known/caldav")) .logout(logout -> logout.invalidateHttpSession(true).deleteCookies("JSESSIONID")) @@ -195,11 +199,11 @@ SecurityFilterChain browserSecurity( UserDetailsService.class, org.busystack.caldav.security.oidc.OidcConfiguration.passkeyUsers(accounts)); org.busystack.caldav.security.passkey.PasskeyConfiguration.configure( - http, deployment, passkeyUsers, ceremonies); + http, deployment, passkeyUsers, ceremonies, journey); var upstream = upstreamUsers.getIfAvailable(); if (upstream != null) org.busystack.caldav.security.oidc.OidcConfiguration.configure( - http, upstreamRegistrations.getObject(), upstream); + http, upstreamRegistrations.getObject(), upstream, journey); return http.build(); } } diff --git a/src/main/java/org/busystack/caldav/security/oidc/OidcConfiguration.java b/src/main/java/org/busystack/caldav/security/oidc/OidcConfiguration.java index 9f5444f..7bd5353 100644 --- a/src/main/java/org/busystack/caldav/security/oidc/OidcConfiguration.java +++ b/src/main/java/org/busystack/caldav/security/oidc/OidcConfiguration.java @@ -16,7 +16,6 @@ import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizationRequestResolver; import org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizedClientRepository; import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestCustomizers; -import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; @Configuration public class OidcConfiguration { @@ -40,7 +39,10 @@ OidcLoginSupport upstreamUsers( } public static void configure( - HttpSecurity http, ClientRegistrationRepository registrations, OidcLoginSupport users) + HttpSecurity http, + ClientRegistrationRepository registrations, + OidcLoginSupport users, + org.busystack.caldav.security.AuthenticationJourney journey) throws Exception { var resolver = new DefaultOAuth2AuthorizationRequestResolver(registrations, "/oauth2/authorization"); @@ -54,7 +56,6 @@ public static void configure( }); }); var repository = new HttpSessionOAuth2AuthorizedClientRepository(); - var success = new SavedRequestAwareAuthenticationSuccessHandler(); http.oauth2Login( login -> login @@ -71,7 +72,7 @@ public static void configure( // tokens. repository.removeAuthorizedClient( "upstream", authentication, request, response); - success.onAuthenticationSuccess(request, response, authentication); + journey.primarySuccess(request, response, authentication); })); } diff --git a/src/main/java/org/busystack/caldav/security/passkey/PasskeyCeremonyGuard.java b/src/main/java/org/busystack/caldav/security/passkey/PasskeyCeremonyGuard.java index e7874f7..3b6bca9 100644 --- a/src/main/java/org/busystack/caldav/security/passkey/PasskeyCeremonyGuard.java +++ b/src/main/java/org/busystack/caldav/security/passkey/PasskeyCeremonyGuard.java @@ -42,9 +42,18 @@ protected void doFilterInternal( if (users.hasCredentials(authentication.getName())) RecentAuthentication.requireMfa(authentication); } catch (AccessDeniedException ex) { - if ("GET".equals(request.getMethod())) + if ("GET".equals(request.getMethod())) { + new org.springframework.security.web.savedrequest.HttpSessionRequestCache() + .saveRequest(request, response); response.sendRedirect(request.getContextPath() + "/login?factor=required"); - else response.sendError(403, "Recent authentication is required"); + } else { + response.setHeader( + "X-BusyStack-Auth-State", + RecentAuthentication.primaryCurrent(authentication) + ? "verification-required" + : "primary-required"); + response.sendError(403, "Recent authentication is required"); + } return; } } @@ -73,6 +82,7 @@ protected void doFilterInternal( if (session == null || !(challenge instanceof String hash) || !ceremonies.consume(session.getId(), purpose, hash)) { + response.setHeader("X-BusyStack-Auth-State", "challenge-expired"); response.sendError( path.equals("/login/webauthn") ? 401 : 400, "Challenge expired or already used"); return; @@ -114,6 +124,7 @@ protected void doFilterInternal( // The configured registration filter has no failure handler. Its supported RP operation // has already unwound (including transaction rollback) before this boundary is reached. if (!post || !path.equals("/webauthn/register") || response.isCommitted()) throw ex; + response.setHeader("X-BusyStack-Auth-State", "registration-rejected"); response.sendError(400, "Invalid passkey registration"); } } diff --git a/src/main/java/org/busystack/caldav/security/passkey/PasskeyConfiguration.java b/src/main/java/org/busystack/caldav/security/passkey/PasskeyConfiguration.java index 1bc54c4..f3d9aa4 100644 --- a/src/main/java/org/busystack/caldav/security/passkey/PasskeyConfiguration.java +++ b/src/main/java/org/busystack/caldav/security/passkey/PasskeyConfiguration.java @@ -71,7 +71,8 @@ public static void configure( HttpSecurity http, DeploymentProperties properties, AccountPasskeyUsers users, - CeremonyStore ceremonies) { + CeremonyStore ceremonies, + org.busystack.caldav.security.AuthenticationJourney journey) { var base = properties.publicBaseUrl(); http.webAuthn( web -> { @@ -84,6 +85,7 @@ public static void configure( @Override public O postProcess(O filter) { filter.setSessionAuthenticationStrategy(new SessionFixationProtectionStrategy()); + filter.setAuthenticationSuccessHandler(journey::passkeySuccess); return filter; } }); diff --git a/src/main/java/org/busystack/caldav/security/passkey/PasskeyPages.java b/src/main/java/org/busystack/caldav/security/passkey/PasskeyPages.java index ee0139c..09a7a62 100644 --- a/src/main/java/org/busystack/caldav/security/passkey/PasskeyPages.java +++ b/src/main/java/org/busystack/caldav/security/passkey/PasskeyPages.java @@ -11,23 +11,75 @@ public class PasskeyPages { private final AccountPasskeyUsers users; private final AccountPasskeyCredentials credentials; + private final org.busystack.caldav.account.InitializationService initialization; + private final org.busystack.caldav.security.AuthenticationJourney journey; - public PasskeyPages(AccountPasskeyUsers users, AccountPasskeyCredentials credentials) { + public PasskeyPages( + AccountPasskeyUsers users, + AccountPasskeyCredentials credentials, + org.busystack.caldav.account.InitializationService initialization, + org.busystack.caldav.security.AuthenticationJourney journey) { this.users = users; this.credentials = credentials; + this.initialization = initialization; + this.journey = journey; } @GetMapping("/login") - public String login() { + public String login( + Authentication auth, + jakarta.servlet.http.HttpServletRequest request, + jakarta.servlet.http.HttpServletResponse response) { + response.setHeader("Cache-Control", "no-store"); + if (initialization.available()) return "redirect:/setup"; + journey.capture(request, response); + if (org.busystack.caldav.security.RecentAuthentication.primaryCurrent(auth)) + return "redirect:/auth/continue"; return "login"; } + @GetMapping("/auth/continue") + public String progress( + Authentication auth, + jakarta.servlet.http.HttpServletRequest request, + jakarta.servlet.http.HttpServletResponse response, + Model model, + @org.springframework.web.bind.annotation.RequestParam(required = false) String next) { + response.setHeader("Cache-Control", "no-store"); + response.setHeader("Referrer-Policy", "no-referrer"); + journey.capture(request, response); + if (next != null) journey.remember(request, next); + if (!org.busystack.caldav.security.RecentAuthentication.primaryCurrent(auth)) + return "redirect:/login"; + boolean enrolled = users.hasCredentials(auth.getName()); + model.addAttribute("enrolled", enrolled); + model.addAttribute("destination", journey.destination(request)); + return !enrolled + ? "enroll-passkey" + : org.busystack.caldav.security.RecentAuthentication.mfaCurrent(auth) + ? "authentication-complete" + : "verify-passkey"; + } + + @GetMapping("/auth/state") + @org.springframework.web.bind.annotation.ResponseBody + public java.util.Map state( + Authentication auth, jakarta.servlet.http.HttpServletResponse response) { + response.setHeader("Cache-Control", "no-store"); + org.busystack.caldav.security.RecentAuthentication.requirePrimary(auth); + return java.util.Map.of( + "enrolled", + users.hasCredentials(auth.getName()), + "verified", + org.busystack.caldav.security.RecentAuthentication.mfaCurrent(auth)); + } + @GetMapping("/security/passkeys") public String passkeys(Authentication authentication, Model model) { var user = users.findByUsername(authentication.getName()); List records = user == null ? List.of() : credentials.findByUserId(user.getId()); model.addAttribute("credentials", records); - return "passkeys"; + return records.isEmpty() ? "enroll-passkey" : "passkeys"; } } diff --git a/src/main/java/org/busystack/caldav/security/session/SessionEpochFilter.java b/src/main/java/org/busystack/caldav/security/session/SessionEpochFilter.java index 268838d..6b2542a 100644 --- a/src/main/java/org/busystack/caldav/security/session/SessionEpochFilter.java +++ b/src/main/java/org/busystack/caldav/security/session/SessionEpochFilter.java @@ -32,6 +32,7 @@ protected void doFilterInternal( SecurityContextHolder.clearContext(); var session = request.getSession(false); if (session != null) session.invalidate(); + response.setHeader("X-BusyStack-Auth-State", "session-ended"); response.sendError(403, "Account session has ended"); return; } diff --git a/src/main/resources/db/migration/V15__protected_initialization.sql b/src/main/resources/db/migration/V15__protected_initialization.sql new file mode 100644 index 0000000..53cbaea --- /dev/null +++ b/src/main/resources/db/migration/V15__protected_initialization.sql @@ -0,0 +1,27 @@ +-- A singleton permanent latch. Existing installations, including disabled accounts, +-- are initialized. No account deletion or recovery can reopen this latch. +CREATE TABLE installation_state ( + id integer PRIMARY KEY CHECK (id = 1), + initialized boolean NOT NULL, + code_verifier bytea, + expires_at timestamptz, + failed_attempts integer NOT NULL DEFAULT 0 CHECK (failed_attempts BETWEEN 0 AND 5), + initial_administrator uuid, + welcome_completed_at timestamptz, + CHECK ((code_verifier IS NULL) = (expires_at IS NULL)), + CHECK (NOT initialized OR code_verifier IS NULL) +); +INSERT INTO installation_state(id, initialized) +VALUES (1, EXISTS(SELECT 1 FROM accounts)); + +-- Also cover established offline bootstrap and closed OIDC provisioning. Serialize +-- against browser claims and code issuance even when another process inserts. +CREATE FUNCTION close_initialization() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + UPDATE installation_state SET initialized=true, code_verifier=NULL, expires_at=NULL + WHERE id=1; + RETURN NEW; +END; +$$; +CREATE TRIGGER close_initialization BEFORE INSERT ON accounts +FOR EACH ROW EXECUTE FUNCTION close_initialization(); diff --git a/src/main/resources/static/assets/portal.js b/src/main/resources/static/assets/portal.js index a6a89bf..0180079 100644 --- a/src/main/resources/static/assets/portal.js +++ b/src/main/resources/static/assets/portal.js @@ -2,13 +2,19 @@ document.querySelectorAll('[data-copy]').forEach(button => { button.addEventListener('click', async () => { const target = document.getElementById(button.dataset.copy); - const status = document.getElementById('copy-status'); + let status = button.parentElement.querySelector('[data-copy-feedback]'); + if (!status) { + status = document.createElement('span'); + status.dataset.copyFeedback = ''; + status.setAttribute('role', 'status'); + status.setAttribute('aria-live', 'polite'); + button.insertAdjacentElement('afterend', status); + } try { await navigator.clipboard.writeText(target.value ?? target.textContent); - status.textContent = 'Copied. Paste it into your application settings.'; + status.textContent = button.dataset.copyMessage || (button.dataset.copy.includes('username') ? 'Username copied.' : button.dataset.copy === 'issued-secret' ? 'Password copied.' : 'Server address copied.'); } catch { - if (target.select) { target.focus(); target.select(); } - status.textContent = 'Select the field and use your browser’s Copy command.'; + status.textContent = 'Copy failed. Select the text and use your browser’s Copy command.'; } }); }); @@ -21,3 +27,8 @@ if (errorSummary) { if (field) { event.preventDefault(); field.closest('details')?.setAttribute('open', ''); field.focus(); } })); } + +window.addEventListener('pagehide', () => { + const secret = document.getElementById('issued-secret'); + if (secret) secret.textContent = 'This password is no longer displayed. Create a replacement if needed.'; +}); diff --git a/src/main/resources/static/assets/security.js b/src/main/resources/static/assets/security.js index b1c6963..c068d5f 100644 --- a/src/main/resources/static/assets/security.js +++ b/src/main/resources/static/assets/security.js @@ -1,31 +1,70 @@ 'use strict'; (() => { const status = document.getElementById('security-status'); + if (!status) return; const csrfToken = document.querySelector('meta[name="csrf-token"]').content; const csrfHeader = document.querySelector('meta[name="csrf-header"]').content; + let busy = false; function decode(value) { - const raw = atob(value.replace(/-/g, '+').replace(/_/g, '/')); - return Uint8Array.from(raw, character => character.charCodeAt(0)); + return Uint8Array.from(atob(value.replace(/-/g, '+').replace(/_/g, '/')), c => c.charCodeAt(0)); } function encode(value) { return btoa(String.fromCharCode(...new Uint8Array(value))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); } async function call(base, path, method, body) { - const response = await fetch(base + path, {method, credentials: 'same-origin', - headers: {[csrfHeader]: csrfToken, 'Content-Type': 'application/json'}, - body: body === undefined ? undefined : JSON.stringify(body)}); - if (!response.ok) throw new Error('Request failed (' + response.status + '). Verify your primary sign-in and existing passkey, then try again.'); + let response; + try { + response = await fetch(base + path, {method, credentials: 'same-origin', cache: 'no-store', + headers: {[csrfHeader]: csrfToken, 'Content-Type': 'application/json'}, + body: body === undefined ? undefined : JSON.stringify(body)}); + } catch { throw new Error('The network response is uncertain. Check your connection and account status before retrying.'); } + const state = response.headers.get('X-BusyStack-Auth-State'); + const messages = { + 'challenge-expired': 'This challenge expired or was already used. Try again to request a new prompt.', + 'primary-required': 'Primary sign-in expired. Sign in again, then return to this step.', + 'verification-required': 'Verify your existing passkey before managing passkeys.', + 'session-ended': 'Your session was invalidated. Sign in again to check current account access.', + 'registration-rejected': 'The server rejected this registration. Check your account status, then try again.' + }; + if (state) throw new Error(messages[state] || 'Check your account status before continuing.'); + if (response.redirected || response.headers.get('Content-Type')?.includes('text/html') && response.ok) + throw new Error('Your session changed or expired. Sign in again to continue.'); + if (!response.ok) { + if (response.status === 401) throw new Error('Passkey verification was rejected. Use a passkey for this account and request a new prompt.'); + if (response.status === 403) throw new Error('This operation is no longer authorized. Check account status or sign in again.'); + if (response.status === 400) throw new Error('The server rejected this ceremony. Request a new prompt and use a passkey for this account.'); + throw new Error('The server could not complete this operation. Check account status before retrying.'); + } return response.status === 204 ? null : response.json(); } + function explain(error) { + if (error.name === 'NotAllowedError') return 'The passkey interaction did not complete. It may have been cancelled, timed out, or no available passkey was selected. Try again when ready.'; + if (error.name === 'InvalidStateError') return 'This authenticator may already have a passkey for this account. Check account status before creating another.'; + if (error.name === 'NotSupportedError') return 'This browser or authenticator cannot complete the requested passkey operation. Try a supported browser or passkey provider.'; + if (error.name === 'SecurityError') return 'Passkeys require the configured secure BusyStack address. Check the HTTPS hostname with your operator.'; + if (error.name === 'AbortError') return 'The passkey interaction was interrupted. Try again when ready.'; + return error.message || 'The passkey interaction could not complete. Check account status and try again.'; + } function run(button, action) { button.addEventListener('click', async () => { - button.disabled = true; - status.textContent = 'Waiting for your authenticator…'; - try { await action(button.dataset.context); } - catch (error) { status.textContent = error.message || 'Authentication failed.'; } - finally { button.disabled = false; } + if (busy) return; + busy = true; + const buttons = [...document.querySelectorAll('#register-passkey, #authenticate-passkey, .remove-passkey')]; + buttons.forEach(b => { b.disabled = true; }); + status.textContent = 'Waiting for your browser or authenticator…'; + try { + if (!window.isSecureContext || !window.PublicKeyCredential || !navigator.credentials) + throw new Error('Passkeys are unavailable in this browser or address. Use a supported browser at the configured HTTPS URL.'); + await action(button.dataset.context); + } catch (error) { status.textContent = explain(error); } + finally { busy = false; buttons.forEach(b => { b.disabled = false; }); } }); } + function registered() { + document.getElementById('enrollment-stage').hidden = true; + document.getElementById('registration-success').hidden = false; + status.textContent = 'Passkey created. Verify your passkey to continue.'; + } const register = document.getElementById('register-passkey'); if (register) run(register, async base => { const options = await call(base, 'webauthn/register/options', 'POST'); @@ -36,9 +75,20 @@ response: {attestationObject: encode(credential.response.attestationObject), clientDataJSON: encode(credential.response.clientDataJSON), transports: credential.response.getTransports()}, clientExtensionResults: credential.getClientExtensionResults(), authenticatorAttachment: credential.authenticatorAttachment}; - await call(base, 'webauthn/register', 'POST', {publicKey: {credential: data, - label: document.getElementById('passkey-label').value.trim() || 'Passkey'}}); - status.textContent = 'Passkey registered. Verify it below to complete MFA.'; + const first = !!document.getElementById('enrollment-stage'); + try { + await call(base, 'webauthn/register', 'POST', {publicKey: {credential: data, + label: document.getElementById('passkey-label')?.value.trim() || 'Passkey'}}); + } catch (error) { + // A committed first registration with a lost response must not encourage another one. + if (first) { + try { if ((await call(base, 'auth/state', 'GET')).enrolled) { registered(); return; } } + catch { /* Preserve the original uncertain response; never claim success. */ } + } + throw error; + } + if (first) registered(); + else { status.textContent = 'Passkey created. Updating registered passkeys…'; window.location.reload(); } }); const authenticate = document.getElementById('authenticate-passkey'); if (authenticate) run(authenticate, async base => { @@ -53,13 +103,15 @@ clientExtensionResults: credential.getClientExtensionResults(), authenticatorAttachment: credential.authenticatorAttachment}); const destination = new URL(result.redirectUrl || base, window.location.href); const application = new URL(base, window.location.href); - if (destination.origin !== application.origin || !destination.pathname.startsWith(application.pathname)) { - throw new Error('The authentication redirect is outside this application. Return to account management.'); - } + if (destination.origin !== application.origin || !destination.pathname.startsWith(application.pathname)) + throw new Error('The authentication destination is unavailable. Return to account management.'); + status.textContent = 'Authentication successful. Continuing…'; window.location.assign(destination.href); }); for (const button of document.querySelectorAll('.remove-passkey')) run(button, async base => { await call(base, 'webauthn/register/' + encodeURIComponent(button.dataset.id), 'DELETE'); - window.location.reload(); + status.textContent = 'Passkey removed. Checking current account state…'; + window.location.assign(base + 'auth/continue?next=' + encodeURIComponent(new URL(base, location.href).pathname + 'security/passkeys')); }); + window.addEventListener('pageshow', event => { if (event.persisted) window.location.reload(); }); })(); diff --git a/src/main/resources/templates/administrator-welcome.html b/src/main/resources/templates/administrator-welcome.html new file mode 100644 index 0000000..40a68aa --- /dev/null +++ b/src/main/resources/templates/administrator-welcome.html @@ -0,0 +1,2 @@ + +

Welcome to BusyStack

Your server is ready. Choose what you want to do first.

Save recovery codes so you can recover from a lost passkey. Keep them securely offline; generating codes requires current verification.

Set up my calendar

Use your administrator account for your own calendars and task lists. You can also access collections shared with you.

Manage users

Create accounts for other people and prepare shared access. Personal calendars are optional.

diff --git a/src/main/resources/templates/authentication-complete.html b/src/main/resources/templates/authentication-complete.html new file mode 100644 index 0000000..f2e0f4d --- /dev/null +++ b/src/main/resources/templates/authentication-complete.html @@ -0,0 +1,7 @@ + +Sign in · BusyStack + + +
+

Authentication successful

Your primary sign-in and passkey verification are current.

Continue +

diff --git a/src/main/resources/templates/connections.html b/src/main/resources/templates/connections.html index 64cfcd5..046bdc4 100644 --- a/src/main/resources/templates/connections.html +++ b/src/main/resources/templates/connections.html @@ -2,11 +2,12 @@
-
My account

Connect your applications

Use a dedicated DAV credential as the application password. Your browser sign-in password does not authenticate CalDAV.

Issue an application credential
-

Your connection settings

Authentication: named DAV credential using Basic over HTTPS. A registered application that supports BusyStack OAuth may use browser authorization instead.

-

Thunderbird

Previously verified: 159.0 Native calendar and task workflows were qualified on the 0.1.0 executable in Vancouver and Berlin. Verification of a later executable is recorded separately.

  1. Open the Calendar tab, choose New Calendar → On the Network.
  2. Enter the username above and the server address as Location. Leave This location doesn't require credentials unchecked, then choose Find Calendars.
  3. Enter your dedicated DAV credential in the password prompt. Use Password Manager if you want Thunderbird to retain it.
  4. Choose CalDAV, select discovered calendars and task lists, then choose Subscribe. Use Thunderbird's task view for tasks.
-

GNOME Calendar / Evolution Data Server

Previously verified: Calendar 50.0 / EDS 3.56.2 Event editing and synchronization were qualified on 0.1.0 in Vancouver. GNOME Calendar does not provide a task editor.

Verified workflow: Calendar 50.0 / EDS 3.56.2 These steps follow GNOME Calendar 50.0's connection wizard. Use the GNOME connection address below; it includes your username so the application retains it after discovery. Task lists belong in a VTODO-capable application.

This address contains your username, never your password. Use a dedicated DAV credential only in the password prompt.

  1. Open Manage Calendars → Add Calendar.
  2. Under Connect to an Online Calendar, paste the GNOME connection address above.
  3. When Credentials opens, enter your BusyStack username in User and a dedicated DAV credential in Password, then choose Connect.
  4. When the address validates and the button becomes available, choose Add Calendar. If the application asks for the credential again when synchronizing, enter the same dedicated DAV credential. Refresh and verify the calendar in the application.
-

Collection addresses

Create a collection or ask an owner to share one before connecting.

+
My account

Connect an application

Create an application password for each application. Your browser sign-in password does not authenticate CalDAV.

Create application password
+

Choose your application

These clients have version-specific qualification evidence. See the setup instructions for tested versions and limits.

+

Choose another application

Your connection settings

Authentication: application password using Basic over HTTPS. A registered application that supports BusyStack OAuth may use browser authorization instead.

+

Thunderbird

Previously verified: 159.0 Native calendar and task workflows were qualified on the 0.1.0 executable in Vancouver and Berlin. Verification of a later executable is recorded separately.

  1. Open the Calendar tab, choose New Calendar → On the Network.
  2. Enter the username above and the server address as Location. Leave This location doesn't require credentials unchecked, then choose Find Calendars.
  3. Enter your application password in the password prompt. Use Password Manager if you want Thunderbird to retain it.
  4. Choose CalDAV, select discovered calendars and task lists, then choose Subscribe. Use Thunderbird's task view for tasks.
+

GNOME Calendar / Evolution Data Server

Previously verified: Calendar 50.0 / EDS 3.56.2 Event editing and synchronization were qualified on 0.1.0 in Vancouver. GNOME Calendar does not provide a task editor.

Verified workflow: Calendar 50.0 / EDS 3.56.2 These steps follow GNOME Calendar 50.0's connection wizard. Use the GNOME connection address below; it includes your username so the application retains it after discovery. Task lists belong in a VTODO-capable application.

This address contains your username, never your password. Use a application password only in the password prompt.

  1. Open Manage Calendars → Add Calendar.
  2. Under Connect to an Online Calendar, paste the GNOME connection address above.
  3. When Credentials opens, enter your BusyStack username in User and a application password in Password, then choose Connect.
  4. When the address validates and the button becomes available, choose Add Calendar. If the application asks for the credential again when synchronizing, enter the same application password. Refresh and verify the calendar in the application.
+

Generic CalDAV

Choose CalDAV with password authentication over HTTPS. Enter the server address and username above, then use a BusyStack application password. Discovery normally finds owned and shared collections; clients requiring a collection URL can use the addresses below. Calendar and task support depends on your client; untested clients are not qualified by these instructions.

Collection addresses

Create a collection or ask an owner to share one before connecting.

Connection troubleshooting

Authentication fails

Check the username and dedicated credential. Issue a replacement if it expired or was lost. Revocation and account disabling deny future authentication. Organization-managed accounts also need periodic provider sign-in within the operator's configured freshness limit; provider disabling does not immediately revoke every BusyStack credential.

Collections are missing or access changed

Check Calendars & Tasks. A collection owner must grant access directly or through a group. Refresh discovery after a change. If a synchronization token becomes invalid after sharing changes, let the client perform a fresh initial synchronization.

TLS, address or synchronization problems

Use exactly the configured HTTPS address, including any application prefix. Do not disable certificate validation. Ask the operator to check certificates and proxy configuration.

Strict synchronization-depth mode is enabled. The project's tested Thunderbird and python-caldav versions use Depth: 1 and need the documented default accommodation; ask the operator to review this deployment choice.

BusyMax has not been qualified against this implementation. No connection or OAuth compatibility claim is made.

- +

BusyStack does not track whether your external application is connected. Check synchronization in the application, then return to account management.

diff --git a/src/main/resources/templates/credentials.html b/src/main/resources/templates/credentials.html index da51d66..7be2120 100644 --- a/src/main/resources/templates/credentials.html +++ b/src/main/resources/templates/credentials.html @@ -1,9 +1,9 @@ - +
-Back to security

DAV credentials

Issue a separate credential for each application or device. These are credentials, not a list of verified device connections. Secrets appear once and cannot be retrieved later.

-

Issue a credential

Choose 1–365 days. Expiration stops future authentication. For replacement, issue a new credential, configure the application, then revoke the old one.

-

Issued credentials

No DAV credentials have been issued. Create one above, then follow Connections.

Credential metadata
LabelCreatedExpiresStatusAction
+Back to security

Application passwords

Issue a separate credential for each application or device. These are credentials, not a list of verified device connections. Secrets appear once and cannot be retrieved later.

+

Create application password

Choose 1–365 days. Expiration stops future authentication. For replacement, issue a new credential, configure the application, then revoke the old one.

+

Application passwords

No Application passwords have been issued. Create one above, then follow Connections.

Credential metadata
LabelCreatedExpiresStatusAction
diff --git a/src/main/resources/templates/dashboard.html b/src/main/resources/templates/dashboard.html index fcbfc0e..197cedf 100644 --- a/src/main/resources/templates/dashboard.html +++ b/src/main/resources/templates/dashboard.html @@ -4,7 +4,7 @@
My account

Welcome,

·

Connect an application

My collections

Calendars and task lists you own.

Manage my collections

Shared with me

Collections available through direct or group access.

View shared collections

Account security

Review security
-

Finish setting up your account

  1. Enroll and verify your first passkey. Your primary sign-in and passkey protect account changes.
  2. Create a calendar or task list, or ask an owner to share one with your username.
  3. Issue an application credential for a CalDAV client, unless your application uses registered OAuth authorization.
  4. Save recovery codes offline so a lost passkey does not lock you out.

Follow the client connection guide. The server does not track whether you have configured an application.

+

Get started with your calendars

Prepare recovery codes to keep access if you lose a passkey. You can return to this at any time.

Create a calendar or task list, or ask an owner to share an existing collection with your username.

Create a calendar or task list

Your calendars and task lists are ready, including any collections shared with you. Connect an application to edit events and tasks.

Connect an application

Your calendars and task lists

You have no collections yet. Create your first calendar or task list.

Up to 50 available collections
NameTypeAccess

Open collection management to edit details, manage sharing or export your data.

diff --git a/src/main/resources/templates/enroll-passkey.html b/src/main/resources/templates/enroll-passkey.html new file mode 100644 index 0000000..f272a81 --- /dev/null +++ b/src/main/resources/templates/enroll-passkey.html @@ -0,0 +1,9 @@ + +Sign in · BusyStack + + +
+

Secure your account

BusyStack requires a passkey for additional verification when managing calendars, application passwords and security.

Your browser or a supported password manager may offer to save the passkey. Follow its instructions to create one for this account.

+ +

Check account status if you completed this step in another tab.

+

diff --git a/src/main/resources/templates/fragments/layout.html b/src/main/resources/templates/fragments/layout.html index e46f3ba..d2dddd7 100644 --- a/src/main/resources/templates/fragments/layout.html +++ b/src/main/resources/templates/fragments/layout.html @@ -33,9 +33,13 @@

-
Security verification needed. Portal downloads and sensitive changes require primary sign-in and a passkey verified within ten minutes. Verify sign-in or set up a passkey.
+
+ Sign in again before continuing. Sign in. + Secure your account before making changes. Create passkey. + Your passkey verification is needed for changes on this page. Verify passkey. +
- +
BusyStack · Your server. Your data.Calendar and task contents are managed in your CalDAV applications.

diff --git a/src/main/resources/templates/dashboard.html b/src/main/resources/templates/dashboard.html index 197cedf..2ea10df 100644 --- a/src/main/resources/templates/dashboard.html +++ b/src/main/resources/templates/dashboard.html @@ -3,8 +3,8 @@
My account

Welcome,

·

Connect an application
-

My collections

Calendars and task lists you own.

Manage my collections

Shared with me

Collections available through direct or group access.

View shared collections

Account security

Review security
-

Get started with your calendars

Prepare recovery codes to keep access if you lose a passkey. You can return to this at any time.

Create a calendar or task list, or ask an owner to share an existing collection with your username.

Create a calendar or task list

Your calendars and task lists are ready, including any collections shared with you. Connect an application to edit events and tasks.

Connect an application
-

Your calendars and task lists

You have no collections yet. Create your first calendar or task list.

Up to 50 available collections
NameTypeAccess

Open collection management to edit details, manage sharing or export your data.

+

My collections

Calendars, task lists, and journals you own.

Manage my collections

Shared with me

Collections available through direct or group access.

View shared collections

Account security

Review security
+

Get started with your collections

Prepare recovery codes to keep access if you lose a passkey. You can return to this at any time.

Create a collection, or ask an owner to share an existing collection with your username.

Create a collection

Your collections are ready, including any collections shared with you. Connect an application to edit events, tasks, and journal entries.

Connect an application
+

Your collections

You have no collections yet. Create your first collection.

Up to 50 available collections
NameTypeAccess

Open collection management to edit details, manage sharing or export your data.

diff --git a/src/main/resources/templates/fragments/layout.html b/src/main/resources/templates/fragments/layout.html index d2dddd7..4d46252 100644 --- a/src/main/resources/templates/fragments/layout.html +++ b/src/main/resources/templates/fragments/layout.html @@ -17,7 +17,7 @@