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/Dockerfile b/Dockerfile index 4025460..1f214ce 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ # Use python3 scripts/build-image.py to supply the verified Maven artifact. -FROM eclipse-temurin:25-jdk@sha256:3ab7fc8d0b4ade8fef96903fb36767c1dbb4fd1535dcfad85b59c17afbbb5857 AS runtime +FROM eclipse-temurin:25.0.5.1_2-jdk-resolute@sha256:d1b500f1a2a8e2cb1b0fa84e21c4a52963050cbd46b8a53fcb6a8eec0f57675f AS runtime ARG APPLICATION_VERSION ARG SOURCE_REVISION WORKDIR /opt/busystack @@ -13,7 +13,14 @@ LABEL org.opencontainers.image.title="BusyStack CalDAV Server" \ org.opencontainers.image.source="https://github.com/busystack/caldav-server" \ org.opencontainers.image.revision="${SOURCE_REVISION}" 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 +# The executable and notices are public artifacts, including for operator UID overrides. +RUN find /opt/busystack -type d -exec chmod 0755 {} + \ + && find /opt/busystack -type f -exec chmod 0644 {} + \ + && 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=70.0", "-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/README.md b/README.md index 96f13b1..273626c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ # BusyStack CalDAV Server -A self-hosted CalDAV server for calendars and tasks, with PostgreSQL persistence +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, task lists and journals, with PostgreSQL persistence and built-in account administration. It supports local accounts and optional OpenID Connect login through an existing identity provider. @@ -45,6 +47,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/compose.yaml b/compose.yaml index 8e29102..ede385b 100644 --- a/compose.yaml +++ b/compose.yaml @@ -53,7 +53,7 @@ services: - '127.0.0.1:${BUSYSTACK_HTTP_PORT:-8080}:8080' read_only: true tmpfs: - - /tmp:rw,nosuid,nodev,noexec,size=128m,uid=10001,gid=10001 + - /tmp:rw,nosuid,nodev,noexec,size=384m,uid=10001,gid=10001 cap_drop: - ALL security_opt: @@ -77,6 +77,17 @@ services: start_period: 60s retries: 5 + initialization: + profiles: [operator] + extends: + service: application + command: [--spring.main.web-application-type=none, --spring.main.banner-mode=off, --logging.level.root=OFF] + ports: !override [] + restart: "no" + # Operator output must never enter the deployment's container log driver. + logging: + driver: none + volumes: database: diff --git a/deployment/INSTALL.md b/deployment/INSTALL.md index c814476..e2d0c9b 100644 --- a/deployment/INSTALL.md +++ b/deployment/INSTALL.md @@ -22,13 +22,11 @@ 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 -docker compose pull +docker compose pull --policy missing docker compose up -d --no-build --wait docker compose ps ``` @@ -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 @@ -71,11 +76,11 @@ and private secrets when no longer needed. Keep backups under your retention pol ## JAR alternative Download `caldav-server-@VERSION@.jar` and verify its SHA-256. Use official Java 25 -(the selected qualified runtime is Temurin 25.0.4.1+1) and PostgreSQL 18.6. Configure +(the selected qualified runtime is Temurin 25.0.5.1+2) and PostgreSQL 18.6. Configure an application-owned PostgreSQL database/role, file-backed Spring config-tree secrets, equal canonical HTTPS public URL and issuer, and loopback listener. Use the operations guide's bootstrap/recovery commands with the downloaded JAR -path in place of `target/caldav-server-@VERSION@.jar`. Run `java -jar +path in place of `target/caldav-server-@VERSION@.jar`. Set `umask 0077` and run `java -XX:+ExitOnOutOfMemoryError -jar /path/caldav-server-@VERSION@.jar`. A JAR needs a host JDK/runtime and an operator-managed process; it does not install a service manager or database. Container deployment above needs neither host Java nor a compiler. diff --git a/deployment/nginx-root.conf.example b/deployment/nginx-root.conf.example index 5b50ecd..bb965db 100644 --- a/deployment/nginx-root.conf.example +++ b/deployment/nginx-root.conf.example @@ -13,6 +13,9 @@ 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; } 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..881b826 100644 --- a/deployment/nginx-subpath.conf.example +++ b/deployment/nginx-subpath.conf.example @@ -19,6 +19,9 @@ 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; } location ^~ /actuator/ { return 404; } location = /calendar/actuator { return 404; } diff --git a/docs/GETTING_STARTED.md b/docs/GETTING_STARTED.md new file mode 100644 index 0000000..96864fc --- /dev/null +++ b/docs/GETTING_STARTED.md @@ -0,0 +1,744 @@ +# Getting started with BusyStack CalDAV Server + +These operator, administrator and user instructions apply to BusyStack @VERSION@. +In a source checkout, run `python3 scripts/release_version.py` to resolve the +version used when generating the installation guide. Download only versions +whose official release assets are available. + +The illustrations show a disposable deployment in Chromium 149.0.7827.55 +with Playwright 1.61.1 and a CTAP2 virtual authenticator. They use synthetic +accounts and resources. One-time passwords and recovery codes were masked +before capture. Your browser and passkey provider supply their own prompts. + +## 1 — What BusyStack does + +BusyStack stores calendars, task lists and journals on a server you control. CalDAV is the +protocol that compatible calendar applications use to discover and synchronize +those collections. Edit events, tasks and journal entries in a connected application, such as +Thunderbird. The web portal manages accounts, collections, sharing, application +access, security, and iCalendar import/export; item editing happens in the connected app. + +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 --policy missing +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 + +![Protected setup form with empty initialization code and password fields](images/getting-started/01-protected-setup.png) + +Open the configured URL. **Set up BusyStack** confirms that the server is running +and needs its first administrator. On the server, in the extracted deployment +directory containing `compose.yaml`, run: + +```sh +bash scripts/initialize.sh +``` + +The command runs a one-off Compose container and prints a code once to the +operator's terminal. The code lasts **15 minutes**. Keep it private. Run the same +command to replace an expired code or unlock setup after five invalid attempts. +A replacement invalidates the previous code. **Setup and recovery help** links +to the local help page. + +Enter the code, username, password and confirmation on the same setup page. +Usernames use 1–64 ASCII letters, digits, dots, underscores or hyphens and must +start with a letter or digit. Passwords need at least 14 Unicode characters and +at most 72 UTF-8 bytes. A password manager can fill the fields. If the entries +differ, correct them in the form. After server validation errors, enter any +required code and password again. + +Select **Create administrator account**. BusyStack opens normal sign-in with a +confirmation and the username. The account is created without a browser session or +passkey. Setup stays closed for this installation after restart, upgrade, account +disabling and restore. Existing installations use normal sign-in. Offline +operator recovery is described in chapter 16. + +## 7 — Sign in with a passkey + +![Sign-in showing the confirmation that the first administrator was created](images/getting-started/02-sign-in.png) + +Sign in with the account's password or use the organization sign-in link if your +operator configured it. Organization-managed accounts use the provider for their +primary sign-in and a BusyStack passkey for verification. + +![First passkey page with a Create passkey button and no portal navigation](images/getting-started/03-create-passkey.png) + +Select **Create passkey**. Follow the browser's prompt using an available password +manager, device unlock, phone or security key. Options depend on your browser, +device and provider. + +![Saved passkey with the Verify and continue action](images/getting-started/04-passkey-saved.png) + +When **Passkey saved** appears, select **Verify and continue**, then use the +passkey in the native prompt. BusyStack opens the authorized task you started from, +or **Overview**. Registration and verification use separate browser prompts. +Returning users start with **Verify and continue** after primary sign-in. + +![Returning-user verification with recovery available](images/getting-started/26-returning-verification.png) + +If a prompt closes, review the status and request a new prompt when ready. If the +connection drops after creating a passkey, return to the page so BusyStack can +check whether it was saved. Reopen sign-in if the session ended. If you lost your +passkey, select **Use a saved recovery code** or contact the operator. + +A completed browser session expires after 30 minutes of inactivity or at its +eight-hour overall limit. Sensitive actions, including private imports and +exports, require both factors to be under ten minutes old. When asked to confirm +your identity, follow the prompt, return to the task and submit it again. If the +draft needs a password, code or file, enter or select it again. Use **Stay signed +in** for an approaching idle limit, or sign in again for the overall limit. + +## 8 — Choose what to do from Overview + +![Administrator Overview with personal setup and server administration choices](images/getting-started/05-overview.png) + +Use **Create a resource** for personal setup or **Import existing data** to select +a destination. To administer the server, use **Open server administration**. +You can do this before creating a personal resource. Recovery codes are optional +preparation available through Security. + +![Server administration overview with account and resource totals](images/getting-started/06-server-administration.png) + +**Server administration** has separate Accounts, Groups, Security & audit and +System & diagnostics sections. Administration shows account and operational +metadata. Owners grant access to private resources separately. + +## 9 — Create and manage user accounts + +![Account directory with separate status and sign-in method filters](images/getting-started/07-accounts.png) + +Open **Server administration → Accounts → Create account**. You can combine +status and sign-in method filters when searching the directory. + +![Create account form with username, display name and initial password](images/getting-started/08-create-account.png) + +Choose the immutable username, editable display name and an initial password +meeting the setup policy. Select **Create account**. + +![New account details showing the nonsecret handoff instructions](images/getting-started/09-account-handoff.png) + +On the account page, use **Copy sign-in instructions** to share the configured URL +and username. Give the initial password separately through a trusted channel. +The recipient registers and verifies their own passkey. They can change the +initial password in Security. + +To disable another account, open its details and review **Disable account**. +Confirming ends sessions and revokes client access while retaining stored data +and membership. Recovery is an offline operator task. Administrators cannot +disable their own account from the browser. + +## 10 — Use resources shared with you + +![User Overview showing a shared calendar and the Connect an app action](images/getting-started/25-shared-overview.png) + +Open the URL supplied by the administrator, sign in and finish the passkey steps +from chapter 7. **Overview** shows the resources you can use and their access +levels. You can connect an app before creating anything. If someone needs to share +a resource with you, give them your exact username. + +## 11 — Calendars, task lists and journals + +![Resource form with Calendar, Task list and Journal choices](images/getting-started/10-resource-type.png) + +Open **Calendars, tasks & journals → Create a resource**. Select **Calendar** for +events, **Task list** for tasks, or **Journal** for journal entries. Enter a name. +Description and color are optional. A color can be six hex digits or eight if it +includes opacity. **Choose a color** keeps the opacity digits you entered. +Clear the value to remove the color. The type is fixed after creation. + +![Empty task list explaining how to add tasks and why there is no export](images/getting-started/11-empty-task-list.png) + +On a resource's detail page, use **Connect an app** or **Import an iCalendar +file** to start adding content. **Settings** is available to owners and read/write +recipients. Changing metadata leaves the client address and contents intact. +Read-only recipients can read details and export available content. + +![All resources with calendars, task lists and journals](images/getting-started/12-resources.png) + +Use **All**, **Owned by me** or **Shared with me** and search by name to find +resources. Select the resource name to open its details. Owners can review +deletion there. A confirmed deletion removes contents, synchronization history, +bindings and grants. Export or obtain a backup before deleting data you need. + +![A calendar with a direct grant and its access controls](images/getting-started/13-sharing.png) + +Owners open **Manage sharing** and choose an account by exact username, or an +available group. **Read-only** allows reading and export. **Read and write** +also allows permitted content and metadata changes and import. The owner alone +manages sharing or deletes the resource. Any read/write grant makes read/write +access effective. Removing one grant leaves other grants in effect. + +Choose **Remove direct grant** or **Remove group grant** in the existing row. +Review the recipient, resource, permission and remaining access. **Cancel** +returns to sharing with the grant intact. If BusyStack asks you to verify again, +review the grant before confirming its removal. + +![Named sharing removal review with the resource, permission and cancellation](images/getting-started/28-share-removal-review.png) + +![Sharing error with the typed username, linked correction and signed-in navigation](images/getting-started/27-sharing-error.png) + +If BusyStack cannot find the recipient, check their exact username, correct the +highlighted field and submit again. + +Administrators create and manage groups from **Server administration → Groups**. +Open the group, find or enter the member's account, and review how many current +grants apply. The account lookup shows enabled accounts eligible to join. +Existing members stay listed on the group page. When you create a group from +sharing, BusyStack returns you to the resource. Choose whether to grant access +there. Future grants follow membership. Group deletion removes memberships and +grants while retaining underlying resources. See [Groups](groups.md). + +## 12 — Connect an app + +![App selection showing Thunderbird, GNOME Calendar and Generic CalDAV](images/getting-started/16-connect-an-app.png) + +Open **Connect an app** and choose your app. The server address includes any +configured subpath. Use the exact address, username and a separate application +password. Supported registered apps may use browser authorization. + +Choose **Connect an app** from a resource's detail page to keep its individual +address available during setup and after signing in again. +If a password is rejected, retry from the same sign-in page to return to that +resource. When BusyStack asks you to verify before saving a change, review the +reopened form and submit again. + +![GNOME Calendar settings with the configured username-bearing address](images/getting-started/17-client-configuration.png) + +Choose **I already have an application password** to use existing settings, or +**Create application password**. Enter a label and choose a lifetime between +1 and 365 days. The form defaults to 90 days. + +![Application password form showing the label and expiration period](images/getting-started/18-create-application-password.png) + +Keep the one-time result open while configuring your app. **Copy password** +copies the secret. If your browser prevents copying, select the text manually. +Use the settings and instructions on the same page. Select **Done** when ready. + +![Application password result with the secret masked and setup steps on the same page](images/getting-started/19-password-created.png) + +If you lose the password, review existing credentials and deliberately issue a +replacement. BusyStack cannot display an issued password again. Configure your +app with the replacement before revoking its previous password. Verify actual +synchronization in the app with a synthetic item. + +![Application password management with a separate creation action and a revoke link](images/getting-started/29-credential-management.png) + +Open **Security → Application passwords** to check active credentials or revoke +one. This list stays available while issuance is busy. Use an already open +creation form or wait for unused requests to expire before starting another. + +### Thunderbird + +The release qualification covers Thunderbird 159.0 graphical workflows and the +verification workflow uses Thunderbird 157.0.1 for native-provider tests. See the +[release's client record](../qualification/evidence/releases/@VERSION@/verification.json). +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 + +The release qualification covers Calendar **50.0** / EDS **3.56.2** in America/Vancouver. 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 +Connect an app. Choose a client that supports the resource types you need. Task and journal handling and wizard labels vary by app. + +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 and administrative audit + +![Security overview with six account security topics](images/getting-started/14-security.png) + +Open **Security** to review passkeys, application passwords, sessions, recovery +codes, authorized applications and password or organization sign-in. + +- **Passkeys** shows each name and recorded creation and last-used time. Add a + replacement before removing your last passkey. Removing a passkey ends the + assurance of sessions verified with that key. After removing the last passkey, + create and verify a new one to resume browser access. +- **Application passwords** shows expiry and revocation. A revoked password can + no longer authenticate a new client request. +- **Browser sessions** distinguishes **This browser** from other sessions. You + can end one after verification. Ending the current browser session signs you out. +- **Authorized applications** shows browser-approved app grants. Revoke one to + remove that grant. An app can ask you to authorize again. +- **Password and organization sign-in** lets local accounts change the password. + A local password change retains passkeys and invalidates existing sessions, + recovery codes and client authorization. For a managed account, change primary + credentials with your organization. Linking an organization identity replaces + local-password sign-in and revokes affected access while retaining passkeys and + resource identity. See [Account security](account-security.md) and [OAuth](oauth.md). + +![Recovery-code result with all ten secret values masked](images/getting-started/15-recovery-codes.png) + +Under **Recovery**, generate and save ten single-use codes offline. Codes expire +after a year and appear once. Replacing the set invalidates its unused codes. +To recover from a lost passkey, first sign in with your password or organization +provider, then select **Use a saved recovery code**. Recovery consumes one code, +removes all passkeys, revokes client access and ends browser sessions. Sign in +again and create and verify a passkey. If you also lost primary sign-in, ask the +operator about offline recovery. + +![Security audit with readable events, actors, targets and outcomes](images/getting-started/23-audit.png) + +Administrators use **Security & audit** to filter bounded UTC records and see +current directory labels for recorded targets. **Recorded references** shows +stored identifiers. **Registered applications** manages native app registration. +Removing a registration revokes all grants for that app. + +![System diagnostics with configured origin, schema and HTTP observations](images/getting-started/24-diagnostics.png) + +Use **System & diagnostics** to check the configured URL and issuer, versions, +database query availability for the current request, HTTP observations since +startup and the bounded list of recent server errors. Use the request reference +when checking operator logs. Backup and HTTPS renewal are tracked separately. + +## 14 — Import and export + +![Import form showing a journal destination and the iCalendar file upload](images/getting-started/20-import-destination.png) + +Open a writable resource and select **Import an iCalendar file**. For an initial +migration, use **Import existing data** from Overview, then create or choose a +destination. Calendars take VEVENT, task lists VTODO and journals VJOURNAL. Check +the destination before choosing the file. Limits are 64 MiB per file, 10,000 UID +series and 1 MiB per series. Recurrence exceptions stay with their UID. If asked +to confirm identity, do that before choosing the file. + +![Import preview identifying the destination and the ready and conflict totals](images/getting-started/21-import-preview.png) + +Review ready, skipped, conflicting and rejected entries. Identical items are +skipped. A different item with an existing UID is a conflict. Existing items +are preserved. The preview expires after ten minutes, and a newer successfully +staged import replaces it. Discard a preview to return without importing. +Choose **Confirm import** only after reviewing the ready items. + +![Committed import report with one imported journal entry](images/getting-started/22-import-result.png) + +The report shows committed results. If the browser loses the response, open the +retained report again. If it has expired or the server restarted, check the +destination in a connected app before trying again. A still-valid preview can +be retried when BusyStack can establish a rollback. + +![Unavailable import report with a working route back to destination selection](images/getting-started/30-import-report-unavailable.png) + +An unavailable report returns you to import selection. Check the destination +before choosing another file if you submitted confirmation. + +For export, open a resource and select **Export events**, **Export tasks** or +**Export journal entries** when content is available. An empty resource explains +how to add content. Matching calendar contexts produce one VCALENDAR. Distinct +contexts require a stream of complete VCALENDAR objects (`-stream.ics`). +BusyStack imports both. Thunderbird 159.0's native file importer requires a +single VCALENDAR. 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. +Start linking from **Security** and continue from that page to the provider. If +you cancel the provider prompt, return to Security to begin again. The passkey +that verified the current browser session must remain active until linking +finishes. + +Users choose organizational sign-in, then the same local passkey enrollment or +verification appropriate to actual account state. They do not configure Keycloak. +Organization sign-in requests fresh provider authentication (`prompt=login`, +`max_age=0`) and requires a recent verified authentication time. The ten-minute +primary-sign-in and passkey policy still applies to sensitive portal operations; +complete a fresh provider sign-in when primary authentication expires. +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 --policy missing +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 V18. 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, clears one-time issuance intents, 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 and journal 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 --policy missing +docker compose up -d --no-build --wait --wait-timeout 240 +docker compose ps +``` + +Flyway validates published migration checksums and applies forward migrations. +V17 added journals. V18 adds transactionally consumed browser issuance intents +and a recovery-code generation marker. Existing accounts close initialization on +upgrade. Verify HTTPS, returning-user sign-in, resource contents, 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, return to the sign-in page when 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. | Return to the enrollment page so BusyStack can check whether it was saved. Verify the saved passkey if it appears. | +| 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 & journals 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–V19 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). + +## 20 — Advanced JAR operation + +For direct JAR operation, supply an isolated PostgreSQL database, trusted HTTPS +proxy and the private configuration described in [Operations](operations.md). +Use the verified release JAR and Java 25 specified for the release. From the +directory containing the JAR, after configuring the environment, run: + +```sh +umask 0077 +java -XX:+ExitOnOutOfMemoryError -jar caldav-server-@VERSION@.jar +``` + +For the primary Compose installation, continue using the bundled scripts and +health checks. The JAR path requires the operator to manage startup, private +temporary storage, database access and recovery separately. diff --git a/docs/P0_ENGINEERING_REPORT.md b/docs/P0_ENGINEERING_REPORT.md new file mode 100644 index 0000000..c84a5ce --- /dev/null +++ b/docs/P0_ENGINEERING_REPORT.md @@ -0,0 +1,422 @@ +# v0.2.0 P0 engineering report + +Implementation and complete local automated qualification passed. The final runtime +has 685 passing Maven tests, zero SpotBugs findings, and successful packaged, +browser, real-Keycloak and native-client profiles. Firefox/Bitwarden acceptance +and public release qualification remain separate conditions below. + +## Repository and preservation + +Work uses the existing `release/v0.2.0` checkout. Starting HEAD was +`3f74590cd8d22341ae1a496af41377a8521733fa`, matching the requested qualified runtime. +No development branch, worktree or additional application checkout was created. +No push, merge, tag, release publication or public deployment was performed. + +The three pre-existing modifications remain separate from development commits: + +| Preserved file | Original and retained SHA-256 | +| --- | --- | +| `qualification/passkeys/README.md` | `185237c93242b01afbff712aea76e84226df2752d068f5cba86c7690be9cc8bc` | +| `qualification/passkeys/recovery.py` | `d9d10f88fcd7ab02f0ca53287c412b4525908f42aece7910d14e5cca2d8f4403` | +| `qualification/passkeys/test_recovery_refresh.py` | `168b179887f90c6506c1f538209abe186a7ad69a5409bab3d36520020361297c` | + +Local development commits (the final report/evidence commit is identified by repository HEAD): + +* `39fa4e7caa95f7f4b0da28e2f307ed7baf7a0fc0`: Implement protected browser initialization and staged account onboarding +* `9fb1eb50f180ebd906698d1945afb6277c6cc910`: Add illustrated guide and end-to-end P0 qualification +* `f25b9c520cbe6a8c5562c4ccf22df4c4e5f5cff1`: Preserve safe continuation through session renewal without replaying POSTs +* `f0ca56579dfde4d622f912e6b8a1c5fb5d5484a4`: Harden operator output and qualify initialization across deployment profiles +* `01760f7baa03275267b8aea9a360ddce2669fba9`: Reuse the secure initialization-code entropy source +* `78443582d587969b9661172b6115bb4fbea8bf05`: Capture final onboarding screens and stage verifiable local deployment assets +* `fbc86b72b0a3cb61aa0893f7fbe842c04cbaf8f9`: Describe protected setup and the forward-only V15 upgrade +* `984dd487dd33dc4f7aa57b74692a141d9b4e4a43`: Keep root-path revoked-passkey assertions on the application origin +* `fac5e63e5243ea967d8028dc0d677d9fcf30a2e2`: Include and validate supporting documentation references in deployment archives +* `42bc581bbfd5ef27ee51c24a4422fb18b52dbdf0`: Qualify the documented startup command and both administrator choices +* `161fc2aa2c3a296fd44b347f308df543890f0a05`: Expect fresh passkey enrollment after restored-account primary sign-in +* `b01333a1866e9292a17f801e17922a2ae4930566`: Explain organizational sign-in freshness in the canonical guide +* `358a1ed2903d8d51622ecad00de6c973c9a94375`: Bound cached group reconciliation plans without extending mutation deadlines +* `7c8f36b8676b10186822432ecaa20a098e8c8144`: Record green V16 verification and final production-image screenshots +* `40176d20800c7d0a75f692f15a0d782cfcf6d5c5`: Record final packaged, browser and native-client qualification evidence + +## Implemented behavior + +The production release archive retains digest-pinned Compose deployment, +PostgreSQL, file-backed secrets, HTTPS proxy examples and backup/restore tooling. +It now includes the canonical [Getting Started guide](GETTING_STARTED.md), its +20 screenshots and the necessary portal/administration/portability references. +Packaging rejects missing guide files, missing/invalid PNGs and broken local +references. Normal deployment requires neither a checkout nor Java/Maven on the +host. Public certificate issuance remains the operator's responsibility. + +A new database opens **Set up BusyStack**. The local command +`bash scripts/initialize.sh` issues a code from an operator-only one-off process. +The code is not printed by normal startup or returned by HTTP. Its Compose profile +disables container logging while retaining attached operator output. The browser +collects code, username, password and confirmation. Successful setup shows +**Administrator account created** and requires ordinary sign-in; it does not create +an authenticated browser session. + +Authentication uses actual account/passkey/factor state. Primary sign-in leads to +**Secure your account** when no passkey exists, or **Verify your passkey** when one +does. First enrollment has no management table or required credential label. +Registration displays **Passkey created**, followed by a separate assertion. +Management remains guarded by the existing recent-MFA policy. A dedicated +verification route prevents the former registration/management redirect loop. + +The first browser-created administrator receives **Welcome to BusyStack**, with +**Set up my calendar**, **Manage users**, and optional recovery-code access. +Only this initial administrator welcome dismissal is retained; ordinary-user +progress is derived from actual credentials, recovery information and owned/shared +collections. Shared recipients can connect applications without creating another +collection. Ordinary users receive no server-administration navigation. + +Connections selects Thunderbird, GNOME Calendar or generic CalDAV. Settings come +from validated deployment configuration and retain root/subpath behavior. A +selected client survives application-password issuance and continuation. Labels, +username, one-time password and expiry are displayed with no-store/no-referrer. +Clipboard feedback is local to the action and distinguishes password, username +and server address; failures offer manual selection without moving focus. +Passwords are not put in browser storage, URLs or new database fields. The UI +never claims a device is connected merely because a password was issued. + +Authentication failures distinguish capability, incomplete interaction, unavailable +authenticator, challenge expiry, primary expiry, revoked session, server rejection +and uncertain network response where the browser/server supply enough information. +A `NotAllowedError` is not equated solely with cancellation. A lost first-registration +response can reconcile against authenticated server enrollment state. Historical +POST pages navigate with GET when restored; authentication does not replay POSTs. + +## Qualified runtime and deployment identities + +The final application runtime is built from +`358a1ed2903d8d51622ecad00de6c973c9a94375`. Subsequent commits change qualification +and documentation only; packaging compares every main/runtime input with that +image revision before accepting it. + +* Production JAR SHA-256: `ce7b72f10ed342129d8b60b319b78ea091d9a03f20f029120e29eb6cf304ea62`. +* Local application image/index: `sha256:7d3a07b372ec3ffa161b3ef2aa33c1564d524652c88ae011d1b4956629ee5699`. +* Delivery archive source: `40176d20800c7d0a75f692f15a0d782cfcf6d5c5`. +* Delivery archive SHA-256: `af932106d114655593dbff909b9315faaa66185444e3b235cef8d217e2e612d9`. + +The six production-format local assets contain real checksums, source inputs, +deployment-file hashes, embedded SBOM and notices. Their metadata explicitly says +**local-unpublished** and invents no CI run or registry publication. The shared +production validator accepts them; the public publisher still requires its normal +CI and client-matrix evidence. Both the earlier `7844358` package and the final `40176d2` delivery package +reproduced all six assets byte for byte. The complete package additionally includes +the supporting documents' relative-link targets and validates every packaged +Markdown link, beyond the canonical guide's twenty required PNGs. + +The full eight-profile packaged matrix used archive source +`7c8f36b8676b10186822432ecaa20a098e8c8144`, SHA-256 +`99100b1f9e30ef9910f74b34e9afb0487ce0dcf650cb8898f220368c143d7473`. +Root installation passed 49 assertions; `/team` passed 48. Each passed real +python-caldav 3.6.0 and Thunderbird 159.0 native-provider correctness checks using +a browser-issued application password. The source-image capture separately +passed 49 assertions and produced the twenty final guide images. + +The delivery archive updates only `SOURCE.json` and the qualification receipt. +Every other deployment file, including Compose, scripts, guide and images, is +byte-identical to the archive that passed the full matrix. All six delivery assets reproduced byte for byte. Its separate clean HTTPS +installation exited 0 with 49 browser assertions and both independent clients +passing. Source and extracted-package validation passed for the guide, all twenty +PNGs, and every relative Markdown link in the archive. No source compilation is +used inside an installation. These are unpublished local-package tests, not +anonymous download/pull of a public release. + +## Security design + +V15 adds initialization state; V16 corrects a demonstrated cached group-plan timeout. +V1–V15 remain unchanged after their recorded qualification. A singleton installation +row holds a permanent initialized latch, code verifier/expiry, bounded failed-attempt +counter, initial-administrator UUID and welcome-dismissal timestamp. + +Code generation uses `SecureRandom` for 32 bytes (256 unpredictable bits), encoded +as 43 URL-safe Base64 characters. Only a purpose-separated SHA-256 verifier is +stored. Validity is fifteen minutes; replacements invalidate predecessors. Five +invalid attempts invalidate the outstanding code. Invalid, expired and consumed +codes receive the same public error. No universal setup secret or default password +is introduced. + +Issuance and claims lock the same database row with `FOR UPDATE`. Account creation +uses existing `AccountService` inside that transaction. An account-insertion +trigger closes the latch and clears the verifier, also covering offline bootstrap +and closed federation provisioning. Failed account writes roll back consumption +and closure. Concurrent claims have at most one winner. Existing accounts, +including disabled accounts, close initialization on migration. Account deletion +does not reopen it. Restoring V15 clears pending codes and preserves closure; +older initialized backups close it when forward migrations run. + +CSRF remains enabled. Setup responses use no-store/no-referrer and never redisplay +codes or passwords. The existing username policy and fourteen-character/seventy-two +UTF-8-byte password policy are reused. Organizational login is held at setup until +local operator initialization is complete. Optional OIDC still uses verified +issuer/subject mapping, closed allowlisting, local authorization and local passkeys. +Realm roles do not grant administration; managed users gain no password fallback. + +`RecentAuthentication` retains its ten-minute policy. Registration grants no new +WebAuthn authentication authority. Assertions retain framework verification, +account binding, single-use challenges, security generations and session rotation. +Validated application GET destinations survive Spring's new-session strategy as +security routing state; ordinary session attributes are still discarded. +Administrator status does not grant private collection access. Existing session, +DAV, OAuth, recovery and sharing services remain authoritative. + +## Group-plan defect found during complete regression + +Two complete-suite attempts reached the existing 30-second deadline while adding +one member to 10,001 granted collections. The isolated case had completed add in +2.324 seconds. A disposable PostgreSQL reproduction cached the membership INSERT +plan before bulk growth: EXPLAIN showed the same one-row estimates and nested-loop +scans afterward, and execution reached SQLSTATE 57014 at the diagnostic deadline. +A cold plan selected hash joins and completed promptly. This establishes a cached +plan defect rather than evidence for extending the deadline. + +The function-local `enable_nestloop=off` correction completed the same cached-plan +reproduction in 2.657 seconds and produced all 10,001 bindings. V16 applies that +preference only to the existing first-party reconciliation function. PostgreSQL +restores the caller's setting on return/error. Existing SQL permissions, mutation +locks, atomicity and the 30-second transaction deadline remain unchanged. No +third-party binaries, published migrations or authorization semantics changed. +The existing capacity regression now warms a generic plan before bulk growth. + +The second full attempt was deliberately stopped after this already-fatal error, +before its long portal suite: exit 143, 424 unit tests passed, 229 integration tests +completed with this single error. It is not a successful complete run. The earlier +full attempt completed 261 integration tests with the six documented failures. +The corrected full run at `358a1ed` passed all 685 tests. Its complete group suite +measured add/remove/re-add/delete at 2120/980/2346/1070 ms and verified that the +caller's planning preference was restored. The diagnostic plans and measurements +are retained in [group-plan evidence](../qualification/evidence/releases/0.2.0/group-plan/result.json). + +## Investigation of passkey/credential state + +The automated browser journey reproduced an issued application password followed +by no enrolled passkeys after a legitimate last-passkey deletion. The previously +completed WebAuthn factor remains recent under the established ten-minute policy; +removal alone is not an account-wide security reset. A new password-only session +with no passkeys was denied issuance. Registration alone was also denied issuance; +completed MFA permitted it. No MFA bypass was demonstrated, and this does not +establish the exact history of the earlier manual observation. + +Recovery and password changes retain their stronger session/security-generation +and independent-access invalidation behavior. Once verification expires, an account +without a passkey must enroll and assert a new one after appropriate primary +sign-in, or use controlled recovery. UI state after enrollment/deletion is rebuilt +from server records instead of retaining a contradictory empty table. + +## Verification evidence + +Detailed logs are retained locally under `.qualification-runs/p0/`; they are not +public release attestations. Disposable fixtures use synthetic accounts and private +secret files. Log output is sanitized when a test tool would otherwise print +headers. Real-browser screenshots are captured with production CSS/JavaScript; +secret blocks are masked during capture. No third-party code or browser binaries +were modified and no dependencies were added. + +Executed results (all rows marked passed exited 0): + +| Check | Result and scope | +| --- | --- | +| Complete Maven `clean verify`, source `358a1ed` | Exit 0; 424 unit + 261 integration tests, no failures/errors/skips; SpotBugs 0; 41:50 elapsed | +| Focused V16 correction gate | Exit 0; 2 unit + 24 integration tests, including the entire 16-test group suite and 8-test initialization suite; SpotBugs 0 | +| Release-tool tests | 33 passed; missing guide/image/supporting-link cases included; publisher transports mocked | +| Qualification fixture unit tests | 14 passed; provided pre-existing fixture edits preserved | +| Final production-image P0 capture | 49 assertions, 20 real screenshots; Python CalDAV 3.6.0 and native Thunderbird 159.0 passed | +| Packaged root, personal administrator activity | 49 assertions, 20 screenshots, both independent clients passed | +| Packaged `/team`, manage-users activity | 48 assertions, 20 screenshots, both independent clients passed | +| Root browser regression | Passed real enrollment/assertion, recovery, OAuth, sharing, process-kill import rollback, restart and disabled-account denial | +| Proxy + restore + clients | Passed actual backup/restore, old-session/DAV/Bearer/refresh/sync rejection, fresh MFA, byte-exact audit fixtures, shared READ/WRITE boundaries, revocation and both clients | +| Real cross-site Keycloak + restore | Passed provider password login, local passkeys, nonadministrator provisioning despite upstream role, local-password denial, recovery, restoration, sharing and disabled-account denial | +| GNOME Calendar 50.0-1 / EDS 3.56.2-8 | Passed actual connection wizard, normal private-CA TLS, event synchronization and native EDS create/modify/delete independently observed over HTTPS | +| Packaged operations | Passed corrective V14 image replacement and V9 restore/forward migration to V16, initialization closure, backup/checksum, non-root/read-only runtime, controlled local/external recovery and every malformed-history safeguard | +| Distribution integrity | Passed exact image/JAR, dependency integrity and license/notices inspection; 112 runtime components | + +Exact matrix command arrays, exit codes, timestamps, log digests, client versions, +artifact identities and screenshot hashes are in the committed +[P0 result record](../qualification/evidence/releases/0.2.0/p0-results.json). +All eight final matrix commands exited 0. The metadata-only delivery successor +also passed its own fresh installation. Local raw logs use the `v16-` prefix +under `.qualification-runs/p0/`; Maven uses `full-maven-v16.log/json`. + +The two administrator activities were exercised on separate fresh deployments. +Ordinary-user coverage includes an existing shared collection without forced +creation, administrator-route denial, returning authentication with the existing +passkey, last-key deletion and renewed password-only issuance denial. + +Browser presentation checks cover production local assets, desktop/mobile reflow, +associated labels, keyboard access, focus indicators and error association. The P0 +journey checks each of its twenty screens at 390px and checks clipboard success +and failure, including focus retention. These are targeted accessibility checks, +not a complete WCAG 2.2 AA audit. + +An early test-harness exception exposed a disposable session cookie in diagnostics. +That fixture was destroyed, retained diagnostics were sanitized, and subsequent +failure handling avoids printing credential headers. No usable test secret was +committed. Normal application-log checks passed for the operator code, account +password and issued application password. + +The complete Maven command is: + +```sh +BUSYSTACK_THUNDERBIRD_BINARY="$PWD/.client-tools/thunderbird/thunderbird" \ +BUSYSTACK_CLIENT_PYTHON="$PWD/.client-venv/bin/python" \ +JAVA_HOME="$PWD/.qualification-runs/corrective-jdk" \ +PATH="$PWD/.qualification-runs/corrective-jdk/bin:$PATH" \ +./mvnw -B -ntp clean verify +``` + +The selected build runtime is unchanged official Temurin 25.0.5+8; Maven 3.9.12 is +provided by the pinned wrapper. PostgreSQL 18.6 and real Keycloak 26.8.1 use the +existing pinned distributions. Browser evidence uses Playwright 1.61.1 / +Chromium 149.0.7827.55 with a CTAP2 virtual authenticator. That does not qualify +Firefox/Bitwarden, synced-provider behavior generally or physical authenticators. + +Two earlier runs were interrupted by host restarts and are not counted as successful +verification. The first completed full run (`f25b9c5`) exited 1 with 424 passing +unit tests and 261 integration tests containing one failure and five errors. It +exposed V14-fixture search-path handling, OIDC fixtures without the now-required +initial administrator, and the group-plan timeout. Fixture corrections preserved +the initialization gate and published migrations. A subsequent targeted run passed +36 integration tests but failed SpotBugs for one-use `SecureRandom`; retaining the +entropy source fixed that finding. The next full attempt (`b01333a`) was stopped +with exit 143 after the reproduced group timeout (229 completed integration tests, +one error). V16 fixes that demonstrated production defect; the final full run is +green. Two browser fixture corrections removed a root-path network-reference URL +and an obsolete post-recovery dashboard expectation; affected final profiles passed. + +The `NotAllowedError` cancellation presentation check uses an injected browser API +error; it does not claim a person cancelled a native password-manager dialog. +Actual enrollment/assertion use Chromium's virtual CTAP2 authenticator. The lost +registration-response check interrupts a real committed HTTP response, then verifies +authoritative reconciliation and the continuing requirement for an assertion. + +## Packaged and manual acceptance + +The local qualification tools are described in +[qualification/p0/README.md](../qualification/p0/README.md). They assemble an +explicitly unpublished archive through the production file-selection/archive +functions and record real source, JAR and image identities. They do not fabricate +CI runs, published assets or a completed historical graphical-client release +matrix. The existing publisher must continue to reject a pending client receipt. + +All browser, packaged, upgrade, restore and native-client profiles above passed. +The final archive was installed from an arbitrary extracted directory with an empty +database, operator-supplied HTTPS and no pre-created administrator. Tests use a +disposable trusted CA and loopback hostname; they do not qualify public DNS or a +production certificate deployment. The application runs from the immutable local +image reference in the generated release package, without source compilation in +the installation. The local cache replaces the unavailable publication step; no +authentication exception or test-only runtime mode is used. + +Anonymous public release download/pull acceptance requires published assets and is separate from +local pre-publication qualification; publication is explicitly outside authorization. + +## Documentation deliverables and acceptance + +* Canonical guide: [docs/GETTING_STARTED.md](GETTING_STARTED.md), nineteen chapters + covering the complete operator, administrator and ordinary-user journey. +* Screenshots: `docs/images/getting-started/`, twenty PNGs captured from runtime + `358a1ed` with production CSS/JavaScript at a 1280×900 browser viewport. The + one-time secret blocks in images 15 and 18 are deterministically masked. +* Release payload: `INSTALL.md`, the complete guide, all twenty referenced PNGs, + and supporting operator documents and relative-link targets. +* Validation: source and extracted-guide references passed; every relative + Markdown link in the package resolves. Missing guides/images/targets fail the + automated release-tool tests. All six final assets reproduced byte for byte. +* Installation acceptance: isolated empty Compose databases, normal trusted test-CA + HTTPS, browser-only initial administrator creation, first/returning authentication, + both administrator choices, ordinary shared-user onboarding, application-password + issuance and working real CalDAV clients. Root passed 49 assertions, `/team` 48; + the delivery archive's independent clean root installation passed 49 again. + +The tested delivery assets are retained locally in +`.qualification-runs/p0/package-v16-delivery/assets/`; the extracted deployment is +its sibling `caldav-server-0.2.0-deploy/`. This is an unpublished qualification +artifact. The official publication and immutable-image distribution controls remain +in force; no external release was created. + +## Manual Firefox/Bitwarden acceptance — prepared, pending + +The isolated delivery-package deployment is ready at **https://localhost:49681**. +Preparation exited 0; SQL inspection confirmed zero accounts, `initialized=false`, +and no code verifier. No existing Firefox profile, Bitwarden vault or host trust +store was modified. No administrator or password-manager credential was prepared. + +Use a **new Firefox profile** (for example through `about:profiles`). Import only +this disposable CA into that profile's certificate authorities and trust it for +websites; do not bypass certificate validation: + +```text +/home/albert/Projects/busystack/caldav-server/.qualification-runs/p0-manual-v16/ca.pem +``` + +CA SHA-256 fingerprint: +`38:01:75:12:D9:02:97:E1:83:02:38:A4:4C:C3:2E:9B:54:F8:7E:24:ED:26:69:3E:C7:92:4D:AF:FD:72:8F:78`. +The server certificate expires **2026-11-07 12:57:11 UTC**. Install/configure +Bitwarden in that isolated profile yourself. The agent has not accessed your vault. + +Perform and record these steps, keeping passwords, codes and tokens private: + +1. Open the HTTPS URL and confirm **Set up BusyStack**. +2. From the local installation directory below, issue a code and create a synthetic + administrator in the browser with a fresh password you choose. +3. Sign in normally with that account. +4. Choose **Create passkey** and save it through Bitwarden's normal interface. +5. Choose **Verify your passkey**, complete the assertion, then **Continue**. +6. Choose **Set up my calendar** and create a disposable collection as a protected operation. +7. Create an application password and check its one-time display/copy/expiry information. +8. Sign out. +9. Sign in again with the same administrator. +10. Verify the existing Bitwarden passkey again; another enrollment should not be required. + +The exact initialization command is: + +```sh +cd /home/albert/Projects/busystack/caldav-server/.qualification-runs/p0-manual-v16/install +bash scripts/initialize.sh +``` + +Record actual Firefox/Bitwarden versions, completed steps and any prompt/cancellation +behavior. Do not send authentication secrets. Until the user performs the test, +its result remains **pending**; Chromium virtual-authenticator results are separate. +Bitwarden behavior does not establish hardware-backed user presence. + +The fixture remains running for acceptance. When finished, remove only this owned +project and its disposable database, from the same installation directory: + +```sh +docker compose down --volumes --remove-orphans +``` + +This cleanup is destructive to **this test project's data**. It does not remove +an existing Firefox profile or Bitwarden item. If the certificate expires, prepare +a new fixture with `qualification/p0/manual.py` and a new output directory; follow +its new CA/address rather than bypassing TLS validation. + +## Remaining acceptance and scope + +No known functional P0 defect remains in the qualified paths. The user's real +Firefox/Bitwarden procedure is pending. Anonymous public release download/pull +was not executed because this work is unpublished and publication is not authorized. +The existing four graphical release-matrix profiles remain pending for the new +executable; native Thunderbird and GNOME wizard/backend checks do not substitute +for every graphical editor/timezone profile. The publisher's gate remains strict. +These conditions prevent a public release-readiness claim. + + +No complete WCAG conformance, independent security assessment, physical-authenticator +qualification or public release readiness is claimed. + +## Final repository state + +All implementation, guide, screenshot and evidence changes are committed locally +on `release/v0.2.0`; the final report/evidence commit is repository HEAD, also +identified in the completion message. Runtime qualification is bound to `358a1ed`, +the full-matrix package to `7c8f36b`, and the delivery package to `40176d2`. +The final signoff changes report/evidence only. The only remaining working-tree +modifications are the three original qualification files listed at the start; +their hashes and their absence from development commits were checked again. +No additional application branch, worktree or checkout, dependency, third-party +software modification, push, merge, Git tag, release publication or public +production deployment was introduced. diff --git a/docs/UX_REPAIR_ACCEPTANCE.json b/docs/UX_REPAIR_ACCEPTANCE.json new file mode 100644 index 0000000..8cfa365 --- /dev/null +++ b/docs/UX_REPAIR_ACCEPTANCE.json @@ -0,0 +1,1162 @@ +{ + "branch": "release/v0.2.0", + "artifacts": { + "baselineCommit": "230c59b3302689200ad79a116b5d64ee06686bcf", + "runtimeCommit": "7f6568fa7990e7e35220430e8952cfb9186626b8", + "packageSourceCommit": "7f6568fa7990e7e35220430e8952cfb9186626b8", + "jarSha256": "8de40c38d57c6b55bc1cc5197ccb8f2967206c8cf8dc9907ef97f46c5293ff61", + "localImageId": "sha256:f0ed8a6efee98572cf227875a01d61fb3d9c1617d909c03582dfaf789a245f96", + "browserImageId": "sha256:e81f60d1e3848e7a5702a209b21cf4c2dd87df7cc261ec5521c29bf087a67f99", + "registryDigest": null, + "deploymentSha256": "48d6ea7ad56db0ef40137303d6a07e107ac72e7a438ca18c9256fa8ea6f20912", + "sourceSnapshotSha256": "d552c1bcc492360dd535bef41a35df082266b5aaba2605a5777e415a09d3f3d7", + "manifest": ".qualification-runs/ux-independent-review/qualified/delivery/assets/release-manifest.json", + "evidenceArchive": ".qualification-runs/ux-independent-review/delivery-evidence.tar.gz" + }, + "evidence": { + "reviewSourceProbes": ".qualification-runs/ux-independent-review/baseline-probes/source-probes-result.json", + "reviewLinkProbe": ".qualification-runs/ux-independent-review/baseline-probes/linking-resolver-probe-result.json", + "baselineCapacity": ".qualification-runs/ux-independent-review/baseline-capacity.log", + "diskFullExport": ".qualification-runs/ux-independent-review/disk-probe.log", + "oneTimeHistory": ".qualification-runs/ux-independent-review/history-and-export/history-result.json", + "baselineLiveKey": ".qualification-runs/ux-independent-review/baseline-live-key.log", + "baselineLinkTabs": ".qualification-runs/ux-independent-review/baseline-keycloak-rerun.log", + "browser": ".qualification-runs/ux-independent-review/qualified/delivery-root/browser-result.json", + "clients": ".qualification-runs/ux-independent-review/qualified/delivery-root/clients-result.json", + "rootBundle": ".qualification-runs/ux-independent-review/qualified/delivery-root.log", + "teamBundle": ".qualification-runs/ux-independent-review/qualified/delivery-team.log", + "maven": ".qualification-runs/ux-independent-review/qualified/maven-stable.log", + "additionalContinuation": ".qualification-runs/ux-independent-review/additional-continuation.log", + "followupTests": ".qualification-runs/ux-independent-review/additional-continuation.log", + "operations": ".qualification-runs/ux-independent-review/qualified/operations.log", + "previousV19Operations": ".qualification-runs/ux-independent-review/operations-v19.log", + "upgradeV18": ".qualification-runs/ux-independent-review/qualified/operations.log", + "previousUpgradeV18": ".qualification-runs/ux-independent-review/operations-v18-v9.log", + "distribution": ".qualification-runs/ux-independent-review/qualified/distribution.json", + "releaseTools": ".qualification-runs/ux-independent-review/qualified/tooling-status.txt", + "manual": ".qualification-runs/ux-independent-review/qualified/manual/acceptance.json", + "standardBrowser": ".qualification-runs/ux-independent-review/ci-browser-root.log", + "strictBrowser": ".qualification-runs/ux-independent-review/ci-browser-strict-final.log", + "proxyBrowser": ".qualification-runs/ux-independent-review/ci-browser-proxy-final.log", + "oidcBrowser": ".qualification-runs/ux-independent-review/qualified/keycloak-restore.log", + "standaloneOidcAttempt": ".qualification-runs/ux-independent-review/ci-browser-oidc-standalone.log", + "localBrowserRestore": ".qualification-runs/ux-independent-review/ci-browser-local-restore.log", + "providerBrowserRestore": ".qualification-runs/ux-independent-review/qualified/keycloak-restore.log", + "previousProviderBrowserRestore": ".qualification-runs/ux-independent-review/ci-browser-provider-restore.log", + "previousCleanVerify": ".qualification-runs/ux-independent-review/maven-clean-verify-certified.log", + "diskConstrainedVerify": ".qualification-runs/ux-independent-review/qualified/maven.log", + "nativeGnome": ".qualification-runs/ux-independent-review/ci-browser-gnome-final.log", + "nativeAppReview": ".qualification-runs/ux-independent-review/qualified/delivery-team.log", + "reproducibleBundle": ".qualification-runs/ux-independent-review/qualified/package-reproducible.log", + "runtimeInputs": ".qualification-runs/ux-independent-review/qualified/p0-image-inputs.json", + "maximumPortability": ".qualification-runs/ux-independent-review/qualified/large-http.json", + "temporaryStorage": ".qualification-runs/ux-independent-review/temporary-storage.json", + "mavenAdvisories": ".qualification-runs/ux-independent-review/qualified/osv-runtime.json", + "advisoryPositiveControl": ".qualification-runs/ux-independent-review/osv-positive-control.json", + "containerAdvisories": ".qualification-runs/ux-independent-review/qualified/container-os-advisories.json", + "containerRawScan": ".qualification-runs/ux-independent-review/qualified/container-os-advisories-raw.json", + "officialCveStatus": ".qualification-runs/ux-independent-review/ubuntu-upstream-status.json", + "signedSnapshot": ".qualification-runs/ux-independent-review/ubuntu-pinned-snapshot.log", + "releaseManifest": ".qualification-runs/ux-independent-review/qualified/delivery/assets/release-manifest.json", + "emptyExport": ".qualification-runs/ux-independent-review/history-and-export/empty-export-result.json", + "imageCaptures": ".qualification-runs/ux-independent-review/guide-screenshots.sha256", + "manualVerification": ".qualification-runs/ux-independent-review/qualified/manual-verification.log" + }, + "issues": { + "UX-01": { + "criteria": "Setup intro and form are separate; guide reference is not a working help link; avoidable invalid submission clears secret fields.", + "status": "Passed", + "acceptance": [ + "A01", + "A02", + "A03" + ] + }, + "UX-02": { + "criteria": "Full portal navigation appears while sign-in is incomplete.", + "status": "Passed", + "acceptance": [ + "A04", + "A05" + ] + }, + "UX-03": { + "criteria": "Admin reads require ten-minute fresh MFA; missing assurance is presented as generic forbidden access. Groups have an independent equivalent check.", + "status": "Blocked", + "acceptance": [ + "A04", + "A07", + "A09" + ] + }, + "UX-04": { + "criteria": "Browser-session authentication and factor freshness are conflated.", + "status": "Blocked", + "acceptance": [ + "A07", + "A08", + "A09" + ] + }, + "UX-05": { + "criteria": "Registration → verify link → verify page/button → success page → Continue; permanent manual account-status link.", + "status": "Blocked", + "acceptance": [ + "A05", + "A06" + ] + }, + "UX-06": { + "criteria": "A global continuation remains in the session rather than being consumed as a particular flow completes.", + "status": "Blocked", + "acceptance": [ + "A11", + "A12", + "A13" + ] + }, + "UX-07": { + "criteria": "The same Overview route substitutes a different welcome page.", + "status": "Blocked", + "acceptance": [ + "A05", + "A15" + ] + }, + "UX-08": { + "criteria": "Repeated empty states, competing next actions, and misleading all/owned/shared state.", + "status": "Blocked", + "acceptance": [ + "A15", + "A16" + ] + }, + "UX-09": { + "criteria": "Type-first creation, useful detail hierarchy and journal terminology are inconsistent.", + "status": "Passed", + "acceptance": [ + "A17", + "A18" + ] + }, + "UX-10": { + "criteria": "Sharing displays three empty projections and page-one footers; some role guidance is wrong.", + "status": "Passed", + "acceptance": [ + "A18", + "A19" + ] + }, + "UX-11": { + "criteria": "Normal validation errors can lose identity/navigation; only some forms receive complete editable recovery.", + "status": "Blocked", + "acceptance": [ + "A13", + "A14" + ] + }, + "UX-12": { + "criteria": "Empty export uses generic wording and green success treatment.", + "status": "Passed", + "acceptance": [ + "A26" + ] + }, + "UX-13": { + "criteria": "Selected client is lost through generic pagination; one-time password and detailed setup instructions are separated.", + "status": "Blocked", + "acceptance": [ + "A20" + ] + }, + "UX-14": { + "criteria": "App-password and recovery-code generation lack server-enforced same-intent replay protection.", + "status": "Blocked", + "acceptance": [ + "A21", + "A22", + "A23", + "A37" + ] + }, + "UX-15": { + "criteria": "Security copy conflates configured protection and recent verification; adjacent security forms/confirmations need consistency.", + "status": "Blocked", + "acceptance": [ + "A24", + "A25" + ] + }, + "UX-16": { + "criteria": "Standalone portability navigation duplicates resource context; successful preview/confirm render from POST despite a GET report route.", + "status": "Passed", + "acceptance": [ + "A27", + "A28", + "A29" + ] + }, + "UX-17": { + "criteria": "Accounts filter mixes enabledness with sign-in method; handoff is incomplete; self/last-admin disable can lock out the operator.", + "status": "Passed", + "acceptance": [ + "A30", + "A31" + ] + }, + "UX-18": { + "criteria": "Group renaming dominates membership work; generic confirmations and messages are inaccurate for some states.", + "status": "Passed", + "acceptance": [ + "A19", + "A32" + ] + }, + "UX-19": { + "criteria": "Audit renders database codes/UUIDs as primary content. Native-app removal has no adequate final consequence confirmation.", + "status": "Blocked", + "acceptance": [ + "A33", + "A34" + ] + }, + "UX-20": { + "criteria": "Admin overview contains outdated bootstrap wording and duplicate navigation. Diagnostics need clearer interpretation, not fabricated metrics.", + "status": "Blocked", + "acceptance": [ + "A35" + ] + }, + "UX-21": { + "criteria": "Guide, screenshot manifests and packaging checks encode obsolete flows; journal/restore documentation has drifted.", + "status": "Passed", + "acceptance": [ + "A38" + ] + } + }, + "reviewFindings": { + "R01": { + "priority": "P1", + "baselineStatus": "Failed", + "baselineObservation": "Keycloak completed identity linking after removal of the passkey that established the initiating proof.", + "baselineEvidence": [ + "baselineLiveKey" + ], + "baselineSource": "Independent review §3, R01", + "status": "Passed", + "changedFiles": [ + "src/main/java/org/busystack/caldav/security/oidc/ExternalIdentityService.java", + "src/main/java/org/busystack/caldav/security/session/BrowserSession.java" + ], + "implementationReferences": [ + "BrowserSession.java", + "ExternalIdentityService.java" + ], + "regressions": [ + "KeycloakOidcIT#removingTheProvingKeyBeforeTheProviderCallbackPreservesTheLocalAccount" + ], + "evidence": [ + "maven" + ], + "acceptance": [ + "A09", + "A10", + "A25" + ] + }, + "R02": { + "priority": "P1", + "baselineStatus": "Failed", + "baselineObservation": "Ordinary Keycloak login consumed another tab’s pending linking intent.", + "baselineEvidence": [ + "reviewLinkProbe", + "baselineLinkTabs" + ], + "baselineSource": "Independent review §3, R02", + "status": "Passed", + "changedFiles": [ + "src/main/java/org/busystack/caldav/security/oidc/OidcConfiguration.java", + "src/main/java/org/busystack/caldav/security/oidc/OidcLinkController.java", + "src/main/java/org/busystack/caldav/security/oidc/ProviderNavigation.java" + ], + "implementationReferences": [ + "ProviderNavigation.java", + "OidcLinkController.java", + "OidcConfiguration.java" + ], + "regressions": [ + "KeycloakOidcIT#explicitMfaLinkingKeepsOwnershipAndReplacesTheOldSecurityContext", + "LinkingAuthorizationRequestResolverTest" + ], + "evidence": [ + "maven" + ], + "acceptance": [ + "A09", + "A10", + "A25" + ] + }, + "R03": { + "priority": "P2", + "baselineStatus": "Failed", + "baselineObservation": "Read navigation reserved all eight pending issuance slots and then blocked access to revocation.", + "baselineEvidence": [ + "baselineCapacity" + ], + "baselineSource": "Independent review §3, R03", + "status": "Passed", + "changedFiles": [ + "src/main/java/org/busystack/caldav/management/ManagementController.java", + "src/main/resources/templates/connections.html", + "src/main/resources/templates/credentials.html" + ], + "implementationReferences": [ + "ManagementController.java", + "credentials.html", + "connections.html" + ], + "regressions": [ + "PortalManagementIT#credentialInspectionAndRevocationStayAvailableAtIssuanceCapacity" + ], + "evidence": [ + "maven", + "browser" + ], + "acceptance": [ + "A21", + "A23", + "A25" + ] + }, + "R04": { + "priority": "P2", + "baselineStatus": "Failed", + "baselineObservation": "The bad-password redirect dropped the explicit return handle.", + "baselineEvidence": [ + "reviewSourceProbes" + ], + "baselineSource": "Independent review §3, R04", + "status": "Passed", + "changedFiles": [ + "src/main/java/org/busystack/caldav/security/AuthenticationJourney.java", + "src/main/java/org/busystack/caldav/security/passkey/PasskeyPages.java", + "src/main/resources/templates/login.html" + ], + "implementationReferences": [ + "AuthenticationJourney.java", + "PasskeyPages.java", + "login.html" + ], + "regressions": [ + "PortalManagementIT#simultaneousAnonymousDestinationsAndWrongPasswordKeepTheirOwnFlow" + ], + "evidence": [ + "maven", + "additionalContinuation" + ], + "acceptance": [ + "A11", + "A13" + ] + }, + "R05": { + "priority": "P2", + "baselineStatus": "Failed", + "baselineObservation": "Concurrent writes could lose one journey, and provider state shared one callback slot.", + "baselineEvidence": [ + "reviewSourceProbes" + ], + "baselineSource": "Independent review §3, R05", + "status": "Passed", + "changedFiles": [ + "src/main/java/org/busystack/caldav/security/AuthenticationJourney.java", + "src/main/java/org/busystack/caldav/security/BrowserFlowStore.java", + "src/main/java/org/busystack/caldav/security/oidc/ProviderNavigation.java", + "src/main/resources/db/migration/V19__browser_navigation_flows.sql" + ], + "implementationReferences": [ + "BrowserFlowStore.java", + "AuthenticationJourney.java", + "ProviderNavigation.java", + "V19__browser_navigation_flows.sql" + ], + "regressions": [ + "PortalManagementIT#simultaneousAnonymousDestinationsAndWrongPasswordKeepTheirOwnFlow", + "PortalManagementIT#anonymousContinuationEvictsTheOldestAndRejectsExpiredRows", + "KeycloakOidcIT#explicitMfaLinkingKeepsOwnershipAndReplacesTheOldSecurityContext" + ], + "evidence": [ + "maven", + "additionalContinuation", + "proxyBrowser" + ], + "acceptance": [ + "A11", + "A12", + "A37" + ] + }, + "R06": { + "priority": "P2", + "baselineStatus": "Failed", + "baselineObservation": "Member removal, native-app registration, pending consent and recovery-code use lost context at reauthentication.", + "baselineEvidence": [ + "reviewSourceProbes", + "reviewLinkProbe" + ], + "baselineSource": "Independent review §3, R06", + "status": "Passed", + "changedFiles": [ + "src/main/java/org/busystack/caldav/management/ReviewFormController.java", + "src/main/java/org/busystack/caldav/security/BrowserFormDrafts.java", + "src/main/java/org/busystack/caldav/security/oauth/RecentMfaAuthorizationFilter.java", + "src/main/java/org/busystack/caldav/security/recovery/RecoveryController.java" + ], + "implementationReferences": [ + "BrowserFormDrafts.java", + "ReviewFormController.java", + "OAuthConsentController.java", + "RecentMfaAuthorizationFilter.java", + "RecoveryController.java" + ], + "regressions": [ + "PortalManagementIT#aStaleMemberDraftRetainsTheOriginalGrantReviewAfterReauthentication", + "PortalManagementIT#nativeAppDraftRetainsOnlyEditableRegistrationFields", + "PortalManagementIT#staleConsentGetAndPostReturnToTheSamePendingAppRequest", + "PortalManagementIT#stalePrimaryReturnsToRecoveryCodeEntryWithoutARegisteredKey" + ], + "evidence": [ + "maven", + "teamBundle" + ], + "acceptance": [ + "A12", + "A13", + "A24", + "A34" + ] + }, + "R07": { + "priority": "P2", + "baselineStatus": "Failed", + "baselineObservation": "Membership review could recompute the grant version after explicit confirmation had already been requested.", + "baselineEvidence": [], + "baselineSource": "Independent review §3, R07", + "status": "Passed", + "changedFiles": [ + "src/main/java/org/busystack/caldav/management/GroupManagementController.java", + "src/main/java/org/busystack/caldav/management/ReviewFormController.java" + ], + "implementationReferences": [ + "ReviewFormController.java", + "GroupManagementController.java" + ], + "regressions": [ + "PortalManagementIT#aStaleMemberDraftRetainsTheOriginalGrantReviewAfterReauthentication" + ], + "evidence": [ + "maven" + ], + "acceptance": [ + "A13", + "A32" + ] + }, + "R08": { + "priority": "P2", + "baselineStatus": "Failed", + "baselineObservation": "The primary Connect action omitted the selected resource and safe destinations discarded its parameter.", + "baselineEvidence": [ + "reviewSourceProbes" + ], + "baselineSource": "Independent review §3, R08", + "status": "Passed", + "changedFiles": [ + "src/main/java/org/busystack/caldav/management/ManagementController.java", + "src/main/java/org/busystack/caldav/security/AuthenticationJourney.java", + "src/main/resources/templates/collection.html", + "src/main/resources/templates/connections.html" + ], + "implementationReferences": [ + "collection.html", + "AuthenticationJourney.java", + "ManagementController.java", + "connections.html" + ], + "regressions": [ + "PortalManagementIT#clientAndAuthorizedResourceSurvivePagingValidationAndCredentialIssuance", + "P0 shared-resource sign-in and assertion" + ], + "evidence": [ + "maven", + "rootBundle", + "teamBundle" + ], + "acceptance": [ + "A20" + ] + }, + "R09": { + "priority": "P2", + "baselineStatus": "Failed", + "baselineObservation": "Group creation lost the originating sharing page after errors or reauthentication.", + "baselineEvidence": [], + "baselineSource": "Independent review §3, R09", + "status": "Passed", + "changedFiles": [ + "src/main/java/org/busystack/caldav/management/GroupManagementController.java", + "src/main/java/org/busystack/caldav/management/ReviewFormController.java", + "src/main/java/org/busystack/caldav/security/BrowserFormDrafts.java" + ], + "implementationReferences": [ + "GroupManagementController.java", + "BrowserFormDrafts.java", + "ReviewFormController.java" + ], + "regressions": [ + "PortalManagementIT#groupCreationReturnsToSharingAfterValidationAndFreshAuthentication" + ], + "evidence": [ + "maven" + ], + "acceptance": [ + "A13", + "A32" + ] + }, + "R10": { + "priority": "P2", + "baselineStatus": "Failed", + "baselineObservation": "Membership and sharing additions offered already-added accounts and groups.", + "baselineEvidence": [], + "baselineSource": "Independent review §3, R10", + "status": "Passed", + "changedFiles": [ + "src/main/java/org/busystack/caldav/management/GroupManagementController.java", + "src/main/java/org/busystack/caldav/management/SharingManagementService.java", + "src/main/java/org/busystack/caldav/sharing/GroupService.java", + "src/main/resources/templates/collection-sharing.html" + ], + "implementationReferences": [ + "GroupService.java", + "SharingManagementService.java", + "GroupManagementController.java", + "collection-sharing.html" + ], + "regressions": [ + "PortalManagementIT#groupCreationReturnsToSharingAfterValidationAndFreshAuthentication", + "Maintained Groups browser traversal" + ], + "evidence": [ + "maven", + "standardBrowser" + ], + "acceptance": [ + "A19", + "A32" + ] + }, + "R11": { + "priority": "P2", + "baselineStatus": "Failed", + "baselineObservation": "The unavailable import report’s recovery link returned to the same unavailable report.", + "baselineEvidence": [], + "baselineSource": "Independent review §3, R11", + "status": "Passed", + "changedFiles": [ + "src/main/java/org/busystack/caldav/management/ImportStaging.java", + "src/main/java/org/busystack/caldav/management/PortalErrors.java" + ], + "implementationReferences": [ + "ImportStaging.java", + "PortalErrors.java", + "portal-error.html" + ], + "regressions": [ + "PortalManagementIT#aReplacedImportReportLeadsToTheAuthorizedImportPicker", + "PortalManagementIT#httpRollbackRetainsEditableConfirmationBeforeAndAfterResourceWrites", + "Packaged proxy transaction interruption" + ], + "evidence": [ + "maven", + "rootBundle", + "teamBundle", + "proxyBrowser" + ], + "acceptance": [ + "A28" + ] + }, + "R12": { + "priority": "P2", + "baselineStatus": "Failed", + "baselineObservation": "Direct and group grant removal lacked the required named confirmation.", + "baselineEvidence": [], + "baselineSource": "Independent review §3, R12", + "status": "Passed", + "changedFiles": [ + "src/main/java/org/busystack/caldav/management/SharingReviewController.java", + "src/main/java/org/busystack/caldav/security/BrowserFormDrafts.java", + "src/main/resources/templates/collection-sharing.html" + ], + "implementationReferences": [ + "SharingReviewController.java", + "confirm-action.html", + "collection-sharing.html", + "BrowserFormDrafts.java" + ], + "regressions": [ + "PortalManagementIT#sharingRemovalNamesThePermissionAndRequiresUnchangedGrantAfterVerification", + "P0 named review and Cancel", + "Maintained overlapping group/direct grant browser walkthrough" + ], + "evidence": [ + "maven", + "rootBundle", + "teamBundle", + "standardBrowser" + ], + "acceptance": [ + "A19", + "A25", + "A32" + ] + } + }, + "acceptance": { + "A01": { + "status": "Passed", + "criteria": "Fresh setup at root and /team: operator command, valid code, account creation, PRG to login, no auto-login/passkey; legacy setup URL remains safe.", + "evidence": [ + "rootBundle", + "teamBundle", + "maven" + ], + "observation": "Operator issuance, trusted HTTPS setup, sign-in redirect and preservation of the legacy setup entry were exercised at the root and /team.", + "previousStatus": "Passed" + }, + "A02": { + "status": "Passed", + "criteria": "Setup mismatch, invalid username, Unicode/code-point/byte limits, expired/replaced code, five failures, concurrent claims and rollback: correct form recovery and one permanent initialization winner.", + "evidence": [ + "browser", + "maven" + ], + "observation": "The browser corrected a password mismatch without clearing the form. InitializationIT exercised malformed usernames, Unicode password byte limits, five failures, code replacement and expiry, both concurrent claims and transaction rollback.", + "previousStatus": "Passed" + }, + "A03": { + "status": "Passed", + "criteria": "Setup never reopens after account disable/delete, restart, upgrade or restore; OIDC cannot provision the first administrator before protected initialization.", + "evidence": [ + "maven", + "operations", + "upgradeV18" + ], + "observation": "Initialization and OIDC boundary tests ran. Both upgrade and restore retained the closed initialization latch.", + "previousStatus": "Passed" + }, + "A04": { + "status": "Passed", + "criteria": "Primary-only, registered-but-unverified and completed sessions: proper shell and direct-URL handling; no protected authority before accepted assertion.", + "evidence": [ + "browser", + "rootBundle", + "teamBundle", + "maven" + ], + "observation": "Primary-only, registered and asserted sessions were exercised using accepted WebAuthn signatures. Incomplete sessions exposed the authentication shell.", + "previousStatus": "Passed" + }, + "A05": { + "status": "Passed", + "criteria": "First sign-in invokes one registration and one explicit assertion; returning sign-in invokes one assertion; no duplicate Verify page or final Continue page.", + "evidence": [ + "browser", + "rootBundle", + "teamBundle" + ], + "observation": "First sign-in progressed through registration and one explicit assertion to Overview. Returning sign-in used one assertion.", + "previousStatus": "Passed" + }, + "A06": { + "status": "Blocked", + "criteria": "Cancel/timeout/unavailable API/provider/expired challenge/network uncertainty: accurate messages, focus, retry and authoritative outcome reconciliation; no false success or duplicate registration.", + "evidence": [ + "browser", + "maven" + ], + "observation": "The browser exercised cancelled registration and reconciled an actual committed registration after response loss. WebAuthn challenge validation also ran over HTTPS.", + "previousStatus": "Blocked", + "previousObservation": "The browser exercised registration cancellation and reconciled a genuinely committed registration with an intercepted response. HTTP and unit tests exercised challenge validation.", + "remaining": "Real provider/API unavailability, authenticator expiry messaging and physical ceremonies still need direct user-environment evidence.", + "reviewFindings": [] + }, + "A07": { + "status": "Blocked", + "criteria": "At 9:59, exactly 10:00 and 10:01: ordinary authorized metadata navigation works in a completed session, sensitive admission preserves the existing strict freshness boundary for BOTH factors. New assertion alone does not rejuvenate stale primary.", + "evidence": [ + "maven", + "browser" + ], + "observation": "The shared deterministic predicate tests both factor timestamps at ages 599, 600 and 601 seconds. Actual HTTP tests separately exercise stale primary and passkey recovery, including native registration, member removal, consent and recovery-code entry.", + "previousStatus": "Blocked", + "previousObservation": "Typed factor and session tests separate factor freshness from completed browser access.", + "remaining": "The same exact-boundary matrix for every sensitive route over a live browser/HTTP clock remains open.", + "reviewFindings": [] + }, + "A08": { + "status": "Passed", + "criteria": "Thirty-minute idle/eight-hour overall boundaries and explicit Stay signed in: server enforcement, no background keepalive, no refreshed factor time, no overall extension from page views. Test actual overall reauthentication.", + "evidence": [ + "maven", + "browser" + ], + "observation": "The production JDBC session expiry was advanced in the HTTPS fixture. Explicit extension preserved both factors and the eight-hour deadline. The test then reauthenticated to the original resource and exercised idle expiration.", + "previousStatus": "Blocked", + "previousObservation": "BrowserSessionTest tested the exact eight-hour proof deadline and a removed authenticating credential.", + "reviewFindings": [] + }, + "A09": { + "status": "Passed", + "criteria": "Disabled account, stale epoch, revoked session, removed authenticating key, removed last key, wrong-account key, forged/future factor evidence: fail closed with safe recovery. No old proof survives key removal.", + "evidence": [ + "maven", + "browser", + "standardBrowser", + "localBrowserRestore", + "operations" + ], + "observation": "Reopened for R01/R02. The corrected real provider callback rejected a link after removal of the original proving key and preserved the other proving key and current credential. Existing wrong-account, future proof, disable and restore cases remain covered.", + "previousStatus": "Passed", + "previousObservation": "Signed HTTP WebAuthn rejected cross-account, forged and disabled credentials. Factor and browser-session tests checked future evidence, revocation, epoch changes and the original live key. The browser removed the last key and denied sensitive actions until new enrollment. Restore rejected the previously live cookie.", + "reviewFindings": [ + "R01", + "R02" + ] + }, + "A10": { + "status": "Passed", + "criteria": "Real Keycloak authentication/linking, allowlist, managed-account restrictions, verified auth_time, outage, disabling and recovery: existing boundaries preserved; no local fallback or upstream role escalation.", + "evidence": [ + "maven", + "oidcBrowser", + "operations", + "providerBrowserRestore" + ], + "observation": "Reopened for R01/R02. The real Keycloak tests separated ordinary sign-in from the associated linking ceremony and still verified allowlisting, outage, local fallback denial, replay and managed roles. The restore fixture uses a username and display name that differ.", + "previousStatus": "Passed", + "previousObservation": "Real Keycloak browser and HTTP profiles exercised allowlisted subject mapping, linking, fresh upstream auth_time, outage and disablement. The final browser rerun passed code recovery and re-enrollment while preserving local-password fallback and upstream role denials.", + "reviewFindings": [ + "R01", + "R02" + ] + }, + "A11": { + "status": "Passed", + "criteria": "Anonymous safe continuation, authenticated draft, fixation rotation, two tabs, changed account, expired/evicted intent and unsafe next values: proper binding, single consumption, no cross-account leakage or POST replay.", + "evidence": [ + "maven", + "browser", + "additionalContinuation" + ], + "observation": "Reopened for R04/R05. Real same-cookie concurrent HTTPS starts preserve both handles in PostgreSQL. The wrong-password retry and WebAuthn rotation retain each target. Additional HTTPS regressions verify exactly one simultaneous claimant, eviction and expiry. Provider-state and changed-account checks also ran.", + "previousStatus": "Blocked", + "previousObservation": "AuthenticationJourneyTest exercised path validation, session rotation, independent handles, rejection of replay and changed accounts.", + "reviewFindings": [ + "R04", + "R05" + ] + }, + "A12": { + "status": "Passed", + "criteria": "OAuth continuation with encoded redirect/state/PKCE at root and /team: legitimate request preserved; external/path-prefix/encoding/auth-loop attacks rejected.", + "evidence": [ + "maven", + "teamBundle" + ], + "observation": "Reopened for R05/R06. HTTPS consent retains the exact authorization request and explicit decision through fresh MFA under /team. The root and reverse-proxy OAuth profiles exercised S256 and the original native token flows. Rejected URL inputs are covered by the continuation and security tests.", + "previousStatus": "Blocked", + "previousObservation": "Root and /team path validation, OAuth boundary and continuation tests ran.", + "reviewFindings": [ + "R05", + "R06" + ] + }, + "A13": { + "status": "Blocked", + "criteria": "Freshness expires while editing: only safe fields return, original version conflict preserved, new CSRF, real reauthorization, explicit resubmit; passwords/codes/uploads are not retained.", + "evidence": [ + "maven" + ], + "observation": "Reopened for R04/R06/R07/R09/R12. HTTP cases cover membership version conflicts, safe registration fields, consent re-entry/CSRF, group-create and named share-removal re-entry. Recovery codes are deliberately entered again after primary sign-in.", + "previousStatus": "Blocked", + "previousObservation": "Safe form drafts are route- and account-bound and require a GET review before resubmission.", + "remaining": "A separate interruption and exact factor boundary check still needs evidence for every supported mutation and account-change permutation.", + "reviewFindings": [ + "R04", + "R06", + "R07", + "R09" + ] + }, + "A14": { + "status": "Blocked", + "criteria": "Shared layout survives ordinary 400/409 errors for all covered forms; active section/object identity preserved. Revocation/outage error paths never restore unauthorized metadata.", + "evidence": [ + "browser", + "maven" + ], + "observation": "Invalid sharing preserved the signed-in shell. HTTP form tests exercised field associations and retained safe values.", + "remaining": "Exercise every browser-facing form and its revocation and outage paths. The follow-up test covered the oversized multipart form and header paths.", + "previousStatus": "Blocked" + }, + "A15": { + "status": "Blocked", + "criteria": "Overview for initial admin, ordinary empty, shared-only, owned-only and mixed accounts: one page identity, useful next action, no mandatory personal collection, no stale-auth “unprotected” claim.", + "evidence": [ + "browser", + "rootBundle", + "teamBundle" + ], + "observation": "One Overview identity was observed for the initialized administrator and a shared-only account. A shared-only account can proceed without creating an owned resource.", + "remaining": "Record the ordinary-empty, owned-only and mixed next-action choices and stale-auth text as explicit assertions.", + "previousStatus": "Blocked" + }, + "A16": { + "status": "Blocked", + "criteria": "Lists at 0,1,50,51+ rows, no-match, nonzero empty page, long/hostile names, all scope/filter combinations: accurate states, bounded queries, context-preserving pagination.", + "evidence": [ + "maven", + "browser" + ], + "observation": "HTTP tests exercised bounded isolation, row recovery, search and paging. The browser exercised All and Shared scopes.", + "remaining": "Cover every scope/filter combination and all exact edge counts in the revised UI.", + "previousStatus": "Blocked" + }, + "A17": { + "status": "Passed", + "criteria": "Calendar/task/journal create and edit: type choice, optional fields, six/eight-digit color including alpha/empty values, fixed component type, unchanged identities, XSS resistance and stale writes.", + "evidence": [ + "browser", + "maven", + "clients" + ], + "observation": "Calendar, task list and journal creation, metadata and color paths exercised type labels, stable identifiers, escaped text and stale writes. Clients exercised the calendar color and content round trips.", + "previousStatus": "Passed" + }, + "A18": { + "status": "Passed", + "criteria": "Owner/read-write/read-only/unrelated admin: controls and backend permissions agree. No private content/metadata access from admin role alone.", + "evidence": [ + "maven", + "browser" + ], + "observation": "HTTP tests exercised owner, writable and read-only recipient actions, DAV permissions and role separation. Signed-in sharing controls matched scoped access in the browser.", + "previousStatus": "Passed" + }, + "A19": { + "status": "Passed", + "criteria": "Sharing empty/direct/group/overlapping/disabled cases: correct effective access, precise removal result, ordinary-user directory privacy, admin group guidance and stale/concurrent grant behavior.", + "evidence": [ + "maven", + "browser", + "standardBrowser", + "rootBundle", + "teamBundle" + ], + "observation": "R12 replaced inline revocation with named direct and group reviews that show the resource, recipient, permission and continuing access. Actual HTTPS and browser checks exercised cancellation, effective access, stale review and current authority.", + "previousStatus": "Failed", + "previousObservation": "Direct, group and overlapping effective access have an authoritative backend projection with separate pagination.", + "reviewFindings": [ + "R10", + "R12" + ] + }, + "A20": { + "status": "Blocked", + "criteria": "Connections per supported client, no resources/shared-only, existing password/new password, root/subpath and selected-client paging/error/step-up: actual correct settings with secret and instructions together.", + "evidence": [ + "browser", + "clients", + "teamBundle", + "followupTests", + "nativeGnome" + ], + "observation": "R08 preserved the resource chosen on the actual Connect link through shared-user sign-in, session rotation and app setup. Tests checked resource scope on paging, validation and issuance at root and /team. The native GNOME result is indexed separately.", + "previousStatus": "Blocked", + "previousObservation": "Client-specific setup and a one-time secret were shown together and worked in both clients. HTTP exercised authorized resource context through paging, validation recovery and issuance, and denied cross-account access.", + "reviewFindings": [ + "R08" + ], + "remaining": "The pinned native GNOME Calendar 50.0 and EDS 3.56.2 profile could not run on this host’s 46.1 and 3.52.3 versions. The browser resource/context path passed in both packages." + }, + "A21": { + "status": "Blocked", + "criteria": "Same-intent app-password/recovery-code double-click, sequential replay, browser refresh, concurrent requests, rollback, commit response loss and expiry: one effect, no plaintext retention/replay or automatic replacement.", + "evidence": [ + "maven", + "browser", + "operations" + ], + "observation": "R03 separated credential inspection from issuance. HTTPS verifies eight mixed pending intentions leave contextual navigation and revocation usable. Real browser interception drops successful password and recovery-set issuance responses. The repeated intent returns only the safe receipt, and the interrupted application credential appears once.", + "previousStatus": "Blocked", + "previousObservation": "Concurrent transactional service requests and sequential browser replays exercised the issuance ledger. The browser checked that the secret did not appear after leaving the result.", + "remaining": "A dedicated forced issuance rollback with browser refresh and both intent expiry cases remains open.", + "reviewFindings": [ + "R03" + ] + }, + "A22": { + "status": "Passed", + "criteria": "Two DIFFERENT recovery-generation intents/tabs: expected-set conflict prevents silent invalidation of the first generated set; replacement requires new explicit confirmation.", + "evidence": [ + "maven" + ], + "observation": "ConcurrentIssuanceAndRecoveryGenerationRejectReplayAndStaleSets exercised different intents and rejected the stale generation.", + "previousStatus": "Passed" + }, + "A23": { + "status": "Blocked", + "criteria": "Secret-page normal refresh and Back/Forward cache; page departure versus simple focus loss; clipboard denied/unavailable: no reissuance or secret resurrection, useful copy fallback, no premature secret loss.", + "evidence": [ + "browser", + "oneTimeHistory" + ], + "observation": "The browser checked focus-only loss, clipboard denial, keyboard focus, regular departure, Back and normal reload for both one-time results. Values did not reappear or regenerate. The screenshots were masked before capture.", + "previousStatus": "Blocked", + "previousObservation": "Page-departure and clipboard fallback logic exists. Guide screenshots redact one-time values before capture.", + "remaining": "Chromium diagnostics report HTTPMethodNotGET for both POST results. A browser/provider configuration that actually restores such results from BFCache remains unverified.", + "reviewFindings": [ + "R03" + ] + }, + "A24": { + "status": "Passed", + "criteria": "Recovery preparation, replace, code use, invalid/consumed/expired/cross-account cases and atomic reset: can recover without the missing passkey; documented effects and fresh enrollment correct.", + "evidence": [ + "maven", + "operations", + "standardBrowser", + "oidcBrowser" + ], + "observation": "R06 added a primary-only refresh return with no passkey. The signed HTTPS test returns to a clean code field and the browser profiles tested replay denial, security reset and fresh enrollment. Transactional code and offline recovery checks remain in the verification set.", + "previousStatus": "Passed", + "previousObservation": "Browser profiles used a code without the old passkey, denied anonymous use and replay, revoked the old DAV/OAuth grants, and reenrolled. Transactional integration covered replacement of the existing set, invalid and cross-account secrets, expiration and rollback. Offline local and external recovery also ran.", + "reviewFindings": [ + "R06" + ] + }, + "A25": { + "status": "Blocked", + "criteria": "Password change, current/other-session revocation, application-password/grant revocation and identity linking: specific confirmations and existing revocation semantics retained.", + "evidence": [ + "maven", + "browser" + ], + "observation": "R01/R02 protect the original linking browser and distinguish ordinary sign-in. Targeted signed tests exercised the affected linking, named revoke and fresh review paths.", + "previousStatus": "Blocked", + "previousObservation": "Typed Security actions render named reviews and preserve account-generation invalidation.", + "remaining": "Complete real browser evidence for each password-change and current/other-session revocation permutation remains open.", + "reviewFindings": [ + "R01", + "R02", + "R03", + "R12" + ] + }, + "A26": { + "status": "Passed", + "criteria": "Empty export for all three types and a content-change race: no false download success, neutral correct guidance and authorization before revealing emptiness.", + "evidence": [ + "browser", + "maven", + "emptyExport" + ], + "observation": "The packaged browser exercised empty calendars, task lists and journals. A real DAV deletion after rendering an export action led to neutral empty feedback without a download, and an unrelated account could not inspect the empty state.", + "previousStatus": "Blocked", + "previousObservation": "The revised empty Task list returns neutral resource-specific feedback and no download.", + "reviewFindings": [] + }, + "A27": { + "status": "Passed", + "criteria": "Populated imports/exports for all three types, duplicate UID/conflict/wrong type/malformed/zero-ready data: accurate previews, preserved data/format, no unsupported overwrite.", + "evidence": [ + "browser", + "maven", + "clients" + ], + "observation": "HTTP import/export tests exercised conflicts, malformed input, denied destinations, preserved bytes and native fixtures. Browser evidence includes a populated Journal with a GET import result.", + "previousStatus": "Passed" + }, + "A28": { + "status": "Passed", + "criteria": "Preview/confirm PRG, report paging, preview replacement, stale auth, expired token, revoked access, known rollback, uncertain result/restart: correct stage identity/lifetime and no duplicate/partial import.", + "evidence": [ + "maven", + "browser", + "proxyBrowser" + ], + "observation": "R11 corrected the unreachable recovery action. The browser followed the rendered link to import selection. HTTPS exercises preview replacement and rollback/retry. The packaged /team interruption proved rollback, rejected the old preview after restart and imported from a new preview.", + "previousStatus": "Passed", + "previousObservation": "The revised browser follows preview and confirm to GET reports. HTTP and staging tests exercised paging, preview replacement, stale authority, expiry, concurrent confirmation and rollback. The proxy profile interrupted a real transaction, restarted, rejected the old preview and imported from a fresh preview.", + "reviewFindings": [ + "R11" + ] + }, + "A29": { + "status": "Passed", + "criteria": "Maximum-size/overlapping/capacity/disk-exhaustion/crash cases required by the existing portability gates: resource budget, private permissions, cleanup, retry and immutable source data remain correct.", + "evidence": [ + "maven", + "proxyBrowser", + "maximumPortability", + "temporaryStorage", + "diskFullExport" + ], + "observation": "The maximum-size HTTPS case provisions 10,000 resources and more than 60 MiB with overlapping exports and admission failure. The exact image passed crash/restart, private temporary storage and actual ENOSPC. The isolated 8 MiB export filesystem produced 503 with no partial download or leaked staging file. After space was restored, the export matched its original bytes.", + "previousStatus": "Blocked", + "previousObservation": "HTTP capacity and upload checks exercised real byte limits. The proxy fixture interrupted a transaction and checked rollback, restart and a fresh import.", + "reviewFindings": [] + }, + "A30": { + "status": "Passed", + "criteria": "Account creation/handoff/errors, status+method filters and disabled/external accounts: truthful instructions, no plaintext success data, no unimplemented temporary-password claim.", + "evidence": [ + "browser", + "teamBundle", + "maven" + ], + "observation": "Account creation, safe handoff, combinations of directory status and identity method, and separation of managed and local accounts ran across the browser and HTTP suites.", + "previousStatus": "Passed" + }, + "A31": { + "status": "Passed", + "criteria": "Self-disable/last-admin disable and concurrent opposing administrator disable requests: browser path preserves at least one enabled administrator; valid other-account disable still revokes access and retains content; offline recovery unaffected.", + "evidence": [ + "maven", + "operations" + ], + "observation": "OpposingBrowserDisablesKeepAnEnabledAdministrator exercised concurrent administrators. Offline recovery ran in its own extracted fixture.", + "previousStatus": "Passed" + }, + "A32": { + "status": "Passed", + "criteria": "Group create/rename/member selection/add/remove/delete: exact consequences, bounded authorized lookup, conflicts/limits and privacy. Rename does not change sync; membership does reconcile correctly.", + "evidence": [ + "browser", + "maven", + "standardBrowser", + "followupTests" + ], + "observation": "Reopened for R06/R07/R09/R10. Tests verified eligibility, duplicate membership, redirects back to sharing, stale member-removal review and the original grant precondition. The maintained browser flow exercised add/remove, rename and deletion.", + "previousStatus": "Passed", + "previousObservation": "The maintained browser profile exercised group creation, validation, rename, membership add/remove, named group deletion and overlapping grants. The HTTP suite exercised bounded capacity, reconciliation, disabled membership and rejection of a stale grant review at the same count.", + "reviewFindings": [ + "R07", + "R09", + "R10", + "R12" + ] + }, + "A33": { + "status": "Blocked", + "criteria": "Audit mapping for all/unknown/historical/deleted targets, current-name joins, XSS, filter/paging, pruning and audit-failure rollback: IDs preserved, no expanded sensitive persistence.", + "evidence": [ + "browser", + "maven" + ], + "observation": "Audit page uses human labels, current names where available and technical details. Audit pruning and transactional rollback tests ran.", + "remaining": "Verify every historical/unknown/deleted category and filtering and pagination edge case in the revised view.", + "previousStatus": "Blocked" + }, + "A34": { + "status": "Passed", + "criteria": "Native-app registration invalid fields/cancel/remove: editable form and named server-wide effect; full grant revocation atomic; OAuth protocol/security regression gates unchanged.", + "evidence": [ + "maven", + "standardBrowser", + "proxyBrowser", + "nativeAppReview" + ], + "observation": "Reopened for R06. Safe fields survive stale native-app registration. Packaged browser cases cover invalid redirect, accessible field correction, cancel and named removal. The authoritative protocol and grant-revocation tests also ran.", + "previousStatus": "Passed", + "previousObservation": "The final extracted /team fixture exercised invalid redirect recovery with an associated field error, cancellation, and named application removal. OAuth HTTP and storage tests exercised atomic removal with active grants and in-flight exchanges and refreshes.", + "reviewFindings": [ + "R06" + ] + }, + "A35": { + "status": "Blocked", + "criteria": "Diagnostics root/subpath/local origin, spoofed forwarding headers, database outage, metrics windows and bounded problem buffer: honest labels, no secrets/private paths or invented health.", + "evidence": [ + "browser", + "maven", + "teamBundle" + ], + "observation": "Diagnostics were rendered for root and /team and security/diagnostics tests checked real origin and bounded request records.", + "remaining": "Verify history windows and database outage against the exact extracted proxy fixture.", + "previousStatus": "Blocked" + }, + "A36": { + "status": "Blocked", + "criteria": "Every primary journey with keyboard, accessible form/status/focus behavior, screen reader where available, 320px/390px/desktop, zoom/text resizing, light/dark, forced colors and reduced motion.", + "evidence": [ + "browser", + "manual" + ], + "observation": "Keyboard menu opening and Escape/focus, 320px/390px/desktop, dark, forced colors and reduced motion were exercised.", + "remaining": "Manual keyboard coverage of every primary task, screen reader announcements, browser zoom/text sizing and the actual passkey provider remain.", + "previousStatus": "Blocked" + }, + "A37": { + "status": "Passed", + "criteria": "New and upgraded schema, current restore invalidation, durable issuance intents, pending-flow cleanup and backup/restore: new persistence cannot revive old browser authority/credentials.", + "evidence": [ + "maven", + "operations", + "upgradeV18", + "localBrowserRestore", + "providerBrowserRestore" + ], + "observation": "V19 and V18 same-version/upgrade fixtures preserved data and ETags, rejected unsupported history, and cleared pending V18/V19 state on restore. A V9-only archive was invalidated and upgraded. Local and provider browser restoration checked live credentials before backup and fresh access after restore.", + "previousStatus": "Passed", + "previousObservation": "Fresh V18 and V9/V17 migrations, journal preservation and closed initialization were tested. Restoring a real pending issuance row cleared it and invalidated old credentials.", + "reviewFindings": [ + "R05" + ] + }, + "A38": { + "status": "Passed", + "criteria": "Complete final guide/images/links/anchors/package; source-free extracted-bundle walkthrough; actual client content round trip; final manual acceptance fixture and truthful remaining gates.", + "evidence": [ + "browser", + "clients", + "releaseTools", + "distribution", + "rootBundle", + "teamBundle", + "manual", + "reproducibleBundle", + "manualVerification" + ], + "observation": "The final guide validates with 30 screenshots, the two asset sets matched byte-for-byte, and the exact image was walked through from extracted root and /team directories. Native client results and the fresh uninitialized manual fixture are indexed separately.", + "previousStatus": "Passed", + "previousObservation": "Validated guide links, anchors and 27 reviewed captures, built the unpublished archive, walked through extracted root and /team installs, completed independent client content operations, and verified a fresh uninitialized manual fixture. The receipt marks manual testing pending.", + "reviewFindings": [] + } + }, + "summary": { + "reviewFindings": { + "Passed": 12 + }, + "acceptance": { + "Passed": 25, + "Blocked": 13 + }, + "publicAssetDownload": "Not applicable to unpublished local acceptance", + "manualAcceptance": "Pending user browser, provider and assistive-technology validation" + } +} diff --git a/docs/UX_REPAIR_ENGINEERING_REPORT.md b/docs/UX_REPAIR_ENGINEERING_REPORT.md new file mode 100644 index 0000000..15dd763 --- /dev/null +++ b/docs/UX_REPAIR_ENGINEERING_REPORT.md @@ -0,0 +1,171 @@ +# BusyStack CalDAV UX corrective engineering report + +The corrective pass started from the clean `release/v0.2.0` checkout at +`230c59b3302689200ad79a116b5d64ee06686bcf`. The independent review and its +companion archive agree byte for byte on the review text. The two supplied +probes were rerun against the starting source and reproduced the continuation, +draft and provider-binding failures. Their isolated Java results establish the +failure mechanisms. Real application tests exercise the corrected Spring, +PostgreSQL, HTTPS and Keycloak boundaries. + +The [acceptance register](UX_REPAIR_ACCEPTANCE.json) records the original 38 +acceptance criteria, the 12 corrective findings, previous evidence and the +specific checks that still need evidence. The [illustrated Getting Started +guide](GETTING_STARTED.md) follows the updated workflows. + +## Findings, corrections and regression evidence + +The baseline reproductions, final test logs and build receipts are indexed in +the register. Java test names identify exact cases in the local reports. + +| Finding | Starting behavior and cause | Correction and regression | +| --- | --- | --- | +| R01 | A real Keycloak callback linked an account after a second signed browser session removed the original proving key. The callback trusted an intent created while MFA was valid. | `BrowserSession` and `ExternalIdentityService` bind the intent to its original session, account epoch, accepted key and verification time. The conversion transaction locks and rechecks the current account and key before mutation. `removingTheProvingKeyBeforeTheProviderCallbackPreservesTheLocalAccount` checks the callback fails while the second key, local password and independently issued DAV authorization remain valid. | +| R02 | On the baseline, a normal provider start consumed a pending linking intent from another tab. The isolated resolver and real provider regressions reproduced the mismatch. | `ProviderNavigation` gives linking its own single-use start handle, binds it to one provider state, and keeps ordinary sign-in independent. `explicitMfaLinkingKeepsOwnershipAndReplacesTheOldSecurityContext` uses the actual provider, two starts and differing callback order. Resolver tests cover cancellation, expired handles and actor mismatch. | +| R03 | Inspecting the password list implicitly took an issuance slot. Over baseline HTTPS, eight mixed issuance intentions made the ordinary list return 503 and blocked the path to revocation. | `ManagementController` and the credential templates split listing from explicit creation. `credentialInspectionAndRevocationStayAvailableAtIssuanceCapacity` fills the ledger with mixed intentions, checks a contextual 503, uses the signed-in navigation and revokes from the list. | +| R04 | Spring's default bad-password redirect lost the explicit flow. The supplied source probe returned a login retry with no handle. | `AuthenticationJourney` retries with that specific handle and bounded valid username. `simultaneousAnonymousDestinationsAndWrongPasswordKeepTheirOwnFlow` uses actual HTTPS/password/MFA and verifies the other tab's destination is unaffected. | +| R05 | Two writes copied and replaced a common session map. A second provider start overwrote the single return association. Both mechanisms reproduced in the baseline probes. | `BrowserFlowStore` uses a stable hashed JDBC session scope and PostgreSQL transaction locks. The journey and provider states have independent sections. The concurrent HTTPS test overlaps two same-cookie requests, verifies both handles in the database, and resumes them after rotation. The real provider and repository tests exercise independent callbacks and single-use intent association. | +| R06 | Member removal lacked a recoverable review, registration lost the entered fields, consent lost its pending context, and stale primary recovery returned generic denial. | `BrowserFormDrafts`, `RecentMfaAuthorizationFilter`, `OAuthConsentController` and `RecoveryController` restore the named member review, safe native app fields and verified pending consent. Recovery prompts for primary sign-in and then asks for the code again. The HTTPS tests exercise stale member intent, registration, stale consent GET and POST and recovery without a registered key. Recovered pages require their own explicit submission. | +| R07 | Form recovery could rebuild a membership confirmation against new grants and implicitly approve different access. | `ReviewFormController` carries the original grant digest and links to the relevant workflow on conflict. `aStaleMemberDraftRetainsTheOriginalGrantReviewAfterReauthentication` lets another request change a grant during reauthentication and checks the original removal is rejected. | +| R08 | The resource page's primary Connect action omitted its ID and the continuation sanitizer discarded a supplied ID. | `collection.html`, `AuthenticationJourney` and the connection/credential controllers carry the canonical resource through authorized stages. The browser follows the actual resource link and completes primary sign-in and passkey enrollment as a shared reader. HTTP tests also check paging, validation, issuance and denial after access changes. | +| R09 | Group creation reset the user's return from sharing when validation or MFA interrupted it. | `GroupManagementController` and the draft controller preserve the original collection UUID and recheck ownership before return. `groupCreationReturnsToSharingAfterValidationAndFreshAuthentication` resumes the resource from both interruptions. | +| R10 | The UI offered current members and already-granted groups in addition lists. Duplicate member submission could look successful. | `GroupService`, `SharingManagementService` and the group/sharing views filter eligible choices and surface an explicit duplicate-member error. The HTTP group test checks duplicate handling and that the existing group remains available for managing its grant. | +| R11 | An unavailable import report linked to the same unavailable URL. Generic validation obscured terminal report loss and left no usable next action. | `ImportStaging` and `PortalErrors` render a typed unavailable result and a working authorized picker, with separate in-place retry after known rollback. The HTTP and browser tests follow that link and the proxy interruption profile exercises restart after an interrupted confirmation. | +| R12 | Removing access was an inline permission change without a final named review. | `SharingReviewController`, `confirm-action.html` and `collection-sharing.html` identify the resource, recipient, old permission and effective-access consequences. The confirmed POST checks fresh authority, CSRF and the original grant state. HTTP and browser cases cover cancellation and the changed-grant recovery path. | + +The collection settings form now uses the creation color control and preserves +empty values, six-digit colors and eight-digit values with alpha. Optional +labels, empty read-only guidance, the app-specific page heading and group +navigation wording match their current UI. Operations and restore +documentation now describes V19. + +## Security, recovery and privacy + +V19 stores short-lived browser navigation separately from content and durable +authorization. Per-journey limits remain eight handles, a 15-minute lifetime +and a 32 KiB destination and draft budget. Draft fields are allowlisted by +route. Passwords, application secrets, recovery codes, uploaded contents and +consent POSTs are excluded. Keycloak's temporary protocol state is scoped to +the original browser and callback. Application-level mutations reload current +authority and require fresh CSRF and explicit resubmission. Existing idle and +overall browser deadlines, the strict ten-minute rule for each factor, and +CalDAV and OAuth authorization rules continue to apply. + +Backups restore with prior browser authority invalidated. Successful recovery +clears pending V18 issuance intentions and V19 navigation state. Current and +old data-schema fixtures preserve calendar and journal bytes, ETags, immutable +history and share bindings. Operators still require the protected +initialization code from the local command for a new installation. + +The previous Keycloak restore fixture made a disposable account's display +name equal its login name. The protected restore parser checks the exact +username as a visible HTML text node and a working CSRF-bearing form before the +backup. The repaired Overview renders both values as separately readable text. +The fixture again uses the login `federated-browser` and display name +`Federated Browser`. The published trust model still uses verified issuer and +subject, with no role elevation from Keycloak or local-password fallback for a +managed account. + +The protected SHA-256 values, checked at the start and end, are: + +| File | SHA-256 | +| --- | --- | +| `qualification/passkeys/README.md` | `e8de08d838411e5a25fa19709ed9ab6f96dad8b04ae1a7be500ff215954e5c1b` | +| `qualification/passkeys/recovery.py` | `45d9ca63c2519c3a5ced5e182e2a352cb306511d5f01135c94f16a163f93099a` | +| `qualification/passkeys/test_recovery_refresh.py` | `7407ba56c278bae926e066ce127618dfb78ecaebe4ae34d327e674097c77dc90` | + +## Container advisories and official fixes + +Trivy 0.76.1 inventoried 115 Ubuntu 26.04 runtime packages. The exact image +produced 253 package/CVE findings across 65 CVE IDs, with 248 Medium and 5 Low. +There were zero High, Critical or Unknown findings under the established gate. +The raw scan and all severity rows are retained. The scan covers the OS package +inventory. The separately executed OSV query covered all 112 resolved Maven +coordinates, returned no advisories and detected the existing Log4j positive +control. The optional NVD audit requires an unavailable feed credential. + +Canonical's Ubuntu 26.04 records were checked for all 65 CVEs and matched to +the source package behind each binary. Canonical marks 123 package/CVE rows +released, 89 deferred and 41 needed. The Ubuntu archive snapshot at +`20261127T180000Z`, verified with the Ubuntu archive keyring, resolved all +released upgrades across 15 binary packages in an APT simulation. These builds are available upstream. +The local delivery still uses the current pinned dependency and OS layer +inventory. [Canonical snapshot service](https://snapshot.ubuntu.com/) + +| Source package | Tested → signed Ubuntu candidate | Canonical security notice | +| --- | --- | --- | +| binutils | `2.46-3ubuntu2` → `2.46-3ubuntu2.1` | [USN-9214-1](https://ubuntu.com/security/notices/USN-9214-1) | +| glibc | `2.43-2ubuntu2.4` → `2.43-2ubuntu2.7` | [USN-9065-1](https://ubuntu.com/security/notices/USN-9065-1) | +| Expat | `2.7.4-1ubuntu0.2` → `2.7.4-1ubuntu0.3` | [USN-9196-1](https://ubuntu.com/security/notices/USN-9196-1) | +| PCRE2 | `10.46-1build1` → `10.46-1ubuntu0.1` | [USN-8974-1](https://ubuntu.com/security/notices/USN-8974-1) | +| Perl | `5.40.1-7ubuntu0.3` → `5.40.1-7ubuntu0.4` | [USN-9006-1](https://ubuntu.com/security/notices/USN-9006-1) | + +## Final verification + +| Gate | Result | +| --- | --- | +| Maven clean verify, Eclipse Temurin 25.0.5+8 | Passed with 653 unit and 288 integration tests. There were no failures, errors or skips. SpotBugs reported zero findings. The full Maven run includes 47 portal cases. | +| JDBC continuation follow-up | Both added HTTPS cases passed, covering concurrent claims, wrong-password retry, eviction and expiry. | +| Python tooling | 76 passed across release (34), distribution (11), P0 (6), passkeys (14) and security (11). | +| Protocol and OAuth investigations | Six protocol cases and four OAuth cases passed, unchanged from their established qualification definitions. | +| Extracted root bundle | 119 browser assertions and 30 captures passed, including independent Python CalDAV 3.6.0 and Thunderbird 157.0.1 round trips. | +| Extracted `/team` bundle | 119 browser assertions and 30 captures passed behind Nginx, including resource-specific sign-in, issuance response loss and import report recovery. | +| Maintained root and strict-sync browser profiles | Passed protected routes, group management, recovery and restart. Strict mode rejected the Depth: 1 accommodation. | +| Maintained proxy and transaction interruption | Passed real TLS and forwarding boundaries. Killing the disposable application after an uncommitted database write rolled the transaction back. A restarted application rejected the old preview, and a new preview imported successfully. | +| Local browser restoration and clients | Passed with Python CalDAV and native Thunderbird against a browser-issued password. Stale browser and DAV/OAuth credentials, pre-restore sync state and revoked readers were rejected after restore. | +| Real Keycloak browser restoration | Passed using the distinct names above. The protected checkpoint verified a previously live session before backup, rejected old credentials and sync state after restore, and verified fresh MFA, private and shared content, revoked-reader denial and journal synchronization. The provider-restore profile exercised ordinary Keycloak sign-in and local-fallback denial. The separate standalone attempts ended in a Chromium network-interface change and a navigation wait timeout. The complete restore profile supplied the normal sign-in and recovery evidence. | +| Portability | A 10,000-resource, more-than-60-MiB round trip overlapped with real exports. The private 8-MiB export mount also reached actual ENOSPC. BusyStack returned 503 before exposing a partial download, cleaned its staging file and exported the same bytes after space returned. The temporary-storage and fatal-allocation probes passed. | +| Empty export and stale link | All three resource types and a real last-object removal race passed over packaged HTTPS. | +| Secret-page history | Both one-time results stayed clear during Back and normal refresh. Chromium supplied persisted page events for 0 of the two results and reported `HTTPMethodNotGET` for both. [Chromium cache eligibility](https://chromium.googlesource.com/chromium/src/%2B/18aacd316ac7976d3336362b4d2dd8ad51022fe9/content/browser/back_forward_cache/back_forward_cache_impl.cc) | +| Old and current database schemas | V18 upgraded to V19. V9 restore and V19 same-version restore passed. Unsupported history left the application stopped. Pending V18 issuance intentions and V19 navigation rows were cleared. | +| Exact distribution and advisory inventory | The packaged JAR content matches the image. Maven advisory and container blocking gates passed, with individual OS findings retained. | +| Native GNOME | The graphical profile reached the application handoff. The established fixture requires Calendar `50.0-1` and Evolution Data Server `3.56.2-8`. The host provides `46.1-0ubuntu2` and `3.52.3-0ubuntu1.2`, respectively, so native GNOME qualification remains open. | + +The build used the project Maven wrapper. The automated port, cross-site +Keycloak, database and native profile jobs each used owned disposable projects. +An earlier full test run shared the portal test login quota across unrelated +cases, producing 429 responses. It also exposed outdated credential-link and +OAuth redirect expectations in two fixtures. The suite now gives each portal +case a fresh throttle table, follows the explicit creation link from setup and +checks separate canonical OAuth handles together with the exact saved request. +A later stress schedule showed one atomic claimant could reach Overview without an interruption notice. The final build returns the same recovery notice for both ways a claim can lose. The case still requires exactly one claimant to resume the task. Production limits and assertions about application authority remain in force. The first repeat on the corrected image also recorded database storage errors while the scanner cached its feed. The scanner cache was removed after its successful verification, and the full Java suite ran again without that concurrent scan. + +### Commands and evidence + +- `./mvnw -B -ntp -DforkCount=2 clean verify` used the pinned JDK, independent-client environment and existing PostgreSQL/Testcontainers configuration. The raw Maven logs include exit codes, suite totals and class-level reports. +- `python3 -m unittest discover -s qualification/ -p 'test_*.py'` ran the five tooling suites. The independent protocol and OAuth POMs ran with the same Java toolchain. +- `qualification/p0/package.py` staged and validated both local asset sets at the current package source. The extracted workflows used `qualification/p0/run.py --proxy` with the exact application and browser image IDs. The maintained browser profiles used `qualification/passkeys/run.py` with locally retained evidence. +- The startup, V18 and V9 fixture logs were generated by `scripts/verify-operations.py`. The packaged disk-full probe used an additional private 8-MiB tmpfs, filled only inside its disposable container, and recorded the rejection and successful retry. +- The retained [acceptance register](UX_REPAIR_ACCEPTANCE.json) indexes raw logs and records individual R and A states. Its evidence archive includes the actual package receipts, the baseline source probes and HTTPS reproductions, the protected hashes, scanner outputs and the official upstream status mapping. + +## Artifact identity and local handoff + +| Artifact | Verified identity | +| --- | --- | +| Runtime source commit | `7f6568fa7990e7e35220430e8952cfb9186626b8` | +| Package source commit | `7f6568fa7990e7e35220430e8952cfb9186626b8` | +| JAR SHA-256 | `8de40c38d57c6b55bc1cc5197ccb8f2967206c8cf8dc9907ef97f46c5293ff61` | +| Local application image ID | `sha256:f0ed8a6efee98572cf227875a01d61fb3d9c1617d909c03582dfaf789a245f96` | +| Local browser image ID | `sha256:e81f60d1e3848e7a5702a209b21cf4c2dd87df7cc261ec5521c29bf087a67f99` | +| Runtime source archive SHA-256 | `b44acce8e307fcf6ab5c8d3baa1b56f132674d363c1ea6ede5a47920b0e28052` | +| Package source snapshot SHA-256 | `d552c1bcc492360dd535bef41a35df082266b5aaba2605a5777e415a09d3f3d7` | +| Deployment archive SHA-256 | `48d6ea7ad56db0ef40137303d6a07e107ac72e7a438ca18c9256fa8ea6f20912` | + +Two independent package assemblies produced identical assets. All image +runtime inputs match the package source snapshot. The manual installation was extracted from the final archive. +The fixture has its own Compose project, +private PostgreSQL volume and localhost-only proxy. At handoff no accounts +or initialization code existed, and protected setup rendered over verified TLS. + +Visit [https://localhost:56145](https://localhost:56145) after trusting the fixture's public CA +in a disposable browser profile. From the fixture's `manual/install` directory, +run `bash scripts/initialize.sh` to obtain the operator code, then complete the +protected setup page. The [Getting Started guide](GETTING_STARTED.md) covers +passkey setup and ordinary administration. The leaf certificate is valid through November 30, 2026 at 05:02 UTC. The fixture's public CA and verified certificate dates are recorded in its handoff evidence. + +The register records **12 passed** of 12 reviewed corrections and +**25 passed, 13 blocked** across the original 38 acceptance rows. Manual browser +and authenticator acceptance remains pending, including a user-controlled +software provider, any physical key ceremonies and assistive technology. +The register identifies each remaining exhaustive-case check. This is a local +unpublished qualification bundle. diff --git a/docs/account-security.md b/docs/account-security.md index f9ab274..376ff6b 100644 --- a/docs/account-security.md +++ b/docs/account-security.md @@ -1,7 +1,7 @@ # Account security workflows Account management provides **Sessions**, **Recovery**, **Password**, and passkey -settings. These are account controls; calendar and task content remains in CalDAV +settings. These are account controls; event, task and journal content remains in CalDAV clients. Local accounts work without an identity provider or email service. ## Browser sessions @@ -17,9 +17,7 @@ for concurrent attribute creation. The `JSESSIONID` cookie is Secure and HttpOnly, with SameSite=Lax. Lax permits the safe top-level redirect back from an upstream OIDC provider. Cookie-authenticated mutations still require CSRF tokens; relaxing SameSite does not remove that -protection. Sessions expire after thirty minutes of inactivity. Recent primary and -passkey factors expire for sensitive-operation authorization after ten minutes, -even when a browser session remains active. +protection. Sessions expire after thirty minutes of inactivity or eight hours since completed sign-in. The Stay signed in action extends idle time only. Recent primary and passkey factors expire for sensitive actions after ten minutes. A completed session refers to the verified active key and captured account epoch. `/security/sessions` lists creation, last-access and expiration times, and marks the current browser. It does not reveal session bearer values. Ending a session @@ -40,12 +38,12 @@ there is no process-local revocation cache. After recent primary and passkey verification, `/security/recovery` generates ten independent high-entropy recovery codes. They are shown once on a response marked `Cache-Control: no-store`. Store them securely offline. Generating another set -revokes every unused code in the earlier set. Each code expires after one year. +revokes every unused code in the earlier set after explicit confirmation. The server consumes the issuance intent with the password or code transaction. Repeating the same intent returns a safe receipt. An older recovery-code form cannot replace a newer set without a new review. Each code expires after one year. The database stores a SHA-256 verifier of the random credential, not the credential itself; human passwords use adaptive password hashing instead. If a passkey is lost, first complete a recent primary sign-in, then submit one -code at `/security/recovery`. Recovery is an alternative second-factor operation; +code at `/security/recovery/use`. Recovery is an alternative second-factor operation; it does not replace a password or a trusted upstream sign-in. The code is consumed atomically with removing passkeys, recording their revocation tombstones, revoking DAV and OAuth access, and ending all browser sessions. Sign in again and enroll a @@ -60,8 +58,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 @@ -123,7 +120,7 @@ challenge guards. No telemetry or remote audit service is required. Normal restarts retain session, credential and revocation state. Restoring older database state uses the explicit recovery policy in the operations procedure: -clear browser sessions and recovery codes, change the global recovery epoch and +clear browser sessions, recovery codes and issuance intents, change the global recovery epoch and account generations, and revoke other independently issued credentials. Old backups must never silently revive a previously revoked session or recovery code. diff --git a/docs/administration.md b/docs/administration.md new file mode 100644 index 0000000..e0094c7 --- /dev/null +++ b/docs/administration.md @@ -0,0 +1,60 @@ +# Server administration + +Complete browser sign-in, then select **Server administration**. Ordinary +administrative reads remain available in a completed browser session. Protected +actions prompt for recent verification. Resource owners control private access. + +The overview shows enabled and disabled account counts, groups, calendars, +task lists, journals and stored UID series. **System & diagnostics** shows +versions, the applied schema and HTTP observations. + +## Accounts + +Search **Accounts** in 50-row pages. Combine Status and Sign-in method filters. 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** creates a local account. Copy the nonsecret sign-in instructions from the new account’s detail page. Share the initial password separately through a trusted channel. The user registers and verifies their own passkey. Organization accounts use the configured closed allowlist or protected +user identity linking. Provider roles do not grant application administration. + +Disabling requires confirmation, ends sessions, revokes client access and retains stored data and membership. Browser administration prevents self-disable and lockout of the last enabled administrator. After the protected first-administrator setup, there is no browser +reactivation, password reset or further administrator creation. Use controlled offline +[bootstrap/recovery](operations.md) after independent identity verification. + +## Groups + +Search groups and page through members. Use the bounded administrator account lookup to find a new member. +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. + +Review how membership affects current and future grants before adding or removing members. 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. Administrative targets show current authorized directory labels. Recorded references retain the opaque target and affected-account UUIDs. Deleted or unavailable targets keep their IDs. Internal atomic membership +replacement records each actual addition/removal in a bounded batch; unchanged +members do not produce membership events. The actor UUID remains available +when its username no longer exists. Historical entries without targets are labelled +explicitly. Collection events do not expose collection identifiers or metadata. +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/calendar-semantics.md b/docs/calendar-semantics.md index ef424a2..1279d0d 100644 --- a/docs/calendar-semantics.md +++ b/docs/calendar-semantics.md @@ -1,5 +1,35 @@ # Calendar semantics and bounded work +RFC 10051 §§11.1–11.2 updates the task data rules: VTODO may contain DURATION +without DTSTART, and STATUS may be PENDING or FAILED. DUE and DURATION remain +mutually exclusive; VEVENT constraints are unchanged. A duration-only task remains +undated: validation, time-range filtering and report expansion do not invent a +start or due timestamp. Accepted source bytes remain authoritative for these tasks. +The first-party parser registers task/status factories through official iCal4j +interfaces and retains original property and alarm validation. It also registers +the upstream task metadata models (ESTIMATED-DURATION, TASK-MODE, REASON, SUBSTATE +and VSTATUS), with first-party structural checks for VSTATUS. REASON requires +an absolute URI in VSTATUS or PARTICIPANT; SUBSTATE requires a token in VSTATUS. +PARTICIPANT permits at most one REASON and PERCENT-COMPLETE. Unknown property +parameters remain opaque; those property rules are not imposed on similarly +named unregistered parameters. Storage and +preservation of these fields does not implement automatic task execution. + +Known URI/CAL-ADDRESS values and their defined address/URI parameters require an +absolute URI (RFC5545 §§3.3.3,3.3.13). Text identifiers, binary attachments and +untyped unknown extensions retain their own rules. REQUEST-STATUS uses its defined +two- or three-level numeric code and escaped text fields. Calendar-data timezone +validation uses an application factory retaining upstream required fields and +property validation while allowing repeated TZNAMEs under RFC5545 §3.6.5. It does +not apply the upstream iTIP-only singleton-name rule to stored calendar data. +Open CUTYPE, ROLE, PARTSTAT, RELTYPE and VALUE vocabularies still require valid +tokens; unknown valid tokens remain preserved. RANGE uses THISANDFUTURE under +RFC5545 §3.2.13; the retired THISANDPRIOR value is not interpreted as a single +occurrence or silently retained as a current range operation. +UTC offsets -0000 and -000000 are rejected before typed offset parsing can lose +their sign (RFC5545 §3.3.14). Valid positive zero retains its submitted precision +in the authoritative stored representation. + The [independent-audit correction record](standards-corrections.md) supersedes the earlier blanket validation claims. The later IV-CAL-01 follow-up checks original BYDAY ordinals, RFC duration alternatives and the exact ASCII initial calendar structure before typed normalization. Shared duration checks include relative triggers and duration-ended periods; valid ASCII structural case and the supported leading BOM affect only the derived reader, never authoritative bytes. `CalendarConstraints` enforces component and cross-property requirements at the write boundary, and `RecurrenceRuleSyntax` checks original RRULE parts before library normalization can discard duplicates. No event series is expanded for write validation. The parsing input adapter unfolds octets before strict UTF-8 decoding, including folds inside a multibyte character, and canonicalizes only structural identifier spelling in a derived reader. Already-valid input octets, case-sensitive identifiers and values remain unchanged. The default [local observance UNTIL input exception](observance-until-compatibility.md) runs before strict validation and makes corrected bytes authoritative for that narrow case; disabling it restores rejection. These corrections do not modify the upstream-derived parser or timezone-builder sources. `ObservanceZoneRules` constructs chronological rules from the submitted observances. Finite eras and explicit dates determine the final regime; an unbounded annual tail is admitted only after checking its ordering and offset continuity across the Gregorian cycle. Today's active STANDARD/DAYLIGHT pair is not used to select future rules. Unproven complex shapes retain explicit coverage limits and fail beyond coverage instead of returning guessed instants. List-TEXT filters use decoded values once, while URI and other non-TEXT properties retain their own representation. @@ -21,3 +51,39 @@ Input is limited to 1 MiB, with separate component/property/parameter/nesting bo Evidence: `CalendarAuditCorrectionsTest`, `CalendarAuditAtomicityIT`, `CalendarSemanticsTest`, `CalendarFreeBusySourcesTest`, `CalendarParameterSemanticsTest`, `CalendarEdgeSemanticsTest`, `CalendarTextProfileTest`, `CalendarExpansionSemanticsTest`, `CalendarTimezoneRdateTest`, `CalendarTimezoneCoverageTest`, `CalendarDuplicateRecurrenceTest`, `CalendarTimezoneRequirementTest`, `CalendarDataProjectionTest`, and `ThunderbirdCalendarFixturesTest`. The Thunderbird fixtures preserve real native-provider output from qualification; their provenance is in `src/test/resources/calendar/clients/README.md`. HTTP/client evidence is maintained separately in the conformance and interoperability matrices. Normative references: [RFC 4791](https://www.rfc-editor.org/rfc/rfc4791.html), particularly sections 7.3, 7.5, 7.10 and 9.9; [RFC 5545](https://www.rfc-editor.org/rfc/rfc5545.html), particularly sections 3.3.6, 3.8.4.4 and 3.8.5.3; [RFC 6868](https://www.rfc-editor.org/rfc/rfc6868.html). The official unmodified parser and narrowly scoped application-owned parameter adapter are documented in `ical4j-parser-patch.md`; former copied implementations remain only in Git history. + +Attendee participation and identity parameters remain valid on events/tasks, but +RFC5545 §3.8.4.1 prohibits them on VALARM delivery addresses. Plain addresses and +unknown extension parameters remain accepted; no alarm delivery engine is added. + +DTEND, DUE and RECURRENCE-ID retain the floating local form if and only if the +related DTSTART is floating (RFC5545 §§3.8.2.2–3,3.8.4.4). A report timezone +interprets valid floating pairs; it does not make mixed floating/absolute pairs +valid. RDATE/EXDATE and observance UNTIL keep their separate existing rules. + +### Remaining value-type and end-date clauses (9 November 2026) + +Explicit `VALUE=TIME` extension data follows RFC 5545 §3.3.12: six digits, +valid hour/minute/second ranges, optional UTC suffix, and no numeric UTC offset. +UTC TIME values cannot also carry TZID. Floating and embedded-zone forms retain +their representation; the server does not derive a date or execute unknown +extension fields. A syntactic leap-second value can be retained without inventing +its date. Unknown experimental value types on extension properties remain opaque. + +ATTACH supports its defined URI/default and BINARY alternatives (§§3.3,3.8.1.1). +BINARY still requires BASE64; FMTTYPE remains recommended rather than mandatory. +Explicit default `ENCODING=8BIT` URI attachments use the official URI constructor +through a first-party factory, retaining parameters and model-copy/report behavior. +The upstream validators and binary decoder remain unchanged. Repeated event/task +and email-alarm attachments remain supported; AUDIO retains its one-attachment +limit. Attachment URIs are stored without retrieving their targets. + +The VEVENT grammar does not explicitly prohibit repeated DTEND: its comment +excludes coexistence with DURATION but omits the preceding group's singleton +restriction. Section 3.8.2.2 likewise omits a once-only conformance rule. Verified +erratum6109 corrects an exclusive-end example, not cardinality. Accepted repeated +ends are preserved; every supplied DTEND must independently satisfy the explicit +DTSTART type, floating-form and later-than constraints. No singleton restriction +was added merely to satisfy the former qualification hypothesis. The existing +first-end interpretation for report calculations is unchanged where several valid +ends are supplied; such ambiguous data is best avoided by producers. diff --git a/docs/conformance.md b/docs/conformance.md index c74523c..bf48995 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -29,6 +29,21 @@ The primary RFCs, their verified errata and relevant update boundaries are recor ## iCalendar representation and semantics +VJOURNAL collections hold one journal UID set per CalDAV resource. RFC 4791 +section 9.9 applies a point predicate to DATE-TIME, a nominal local day to DATE, +and excludes journals without DTSTART from time-range matches. Component-only +inventory includes undated entries. For RDATE PERIOD values, the server uses +the start for journal REPORT matching. RFC 5545 section 3.8.5.2 defines generic +PERIOD duration overrides without a journal-specific interaction with the +CalDAV table. Report expansion leaves journal end and duration properties +absent. Journal resources do not contribute to busy time. Storage admission and +the release's provider qualification are tracked separately in the +[journal admission record](../qualification/evidence/vjournal-admission.md). + +Journals can carry nested VSTATUS components with a parent STATUS and one +STATUS in each child. The VTODO status values PENDING and FAILED remain +task-specific. [RFC 10051 sections 8 and 12.1](https://www.rfc-editor.org/rfc/rfc10051.html#section-8). + | Obligation — RFC5545 / RFC6868 | Evidence and boundaries | | --- | --- | | Complete resources, properties and parameters | `CalendarContent` validates with iCal4j while PostgreSQL keeps accepted UTF-8 bytes. GET/HEAD validators and ordinary round trips do not reconstruct objects from derived indexes. Independent-client fixtures cover Unicode, unknown X-properties and alarms. Synthetic parser/parameter tests additionally cover unknown parameters, organizer/attendee and ATTACH preservation; these are distinct evidence sources. No external ATTACH/TZURL retrieval is performed; a local socket test verifies the non-fetch boundary. | @@ -46,7 +61,7 @@ The primary RFCs, their verified errata and relevant update boundaries are recor | Scoped tokens and invalid state | Stable tokens include collection identity, state generation and global recovery epoch. Opaque continuation state is additionally bound to the requesting account, fixed lower/upper revisions, cursor, retention floor and 24-hour expiry; every page rechecks account state and current collection authorization; sharing/group changes and restoration invalidate affected state. Invalid/wrong-collection/old-generation/retention-expired tokens fail with valid-sync-token. Revoked permissions cannot use old tokens to access content. | | Limited results and interrupted responses | Initial and incremental pages honor the RFC 6578 truncated 207/collection-507/continuation-token contract. Valid positive client result ceilings above the server page cap are accepted and capped, including integers larger than a Java int. An explicit empty property selection still produces a successful empty propstat for each changed member. The cursor records the last delivered name at a frozen watermark; incomplete pages never append the latest live revision. Retry does not consume a token. Writes above the watermark, deletions, delete/recreate and names across cursor boundaries are delivered by the subsequent stable-token traversal. Metadata requests do not fetch bodies. Calendar-data pages additionally bound retained raw bodies and charge selected serialized XML, escaping, properties and construction work. A first item that cannot fit fails explicitly without a successful token; a truncated page must make progress. `SyncPagingIT` covers more than 10,000 resources and 32 MiB, small pages, metadata/content, concurrent mutations, retries, retention, revocation and restart. No separate pagination API or PROPFIND pagination is invented. | | History retention | Change records, immutable resource bodies and property snapshots are retained indefinitely by default; protect historical private data in PostgreSQL backups. Transactional `CalendarStore.pruneHistory` minimum-token invalidation is tested; there is no automatic history-pruning job or exposed operator API. Expired continuation rows are independently reclaimed in bounded batches; expiry enforcement does not depend on that cleanup. Monitor growth as described in [operations](operations.md). | -| Restart/restore | Durable PostgreSQL state survives process restarts. Offline restore rotates recovery/account epochs, disables every account and clears restored factors/sessions/DAV/OAuth credentials before individually verified recovery; restoration also clears durable continuation rows while retaining authoritative version/property history, so old tokens and credentials cannot silently revive. Forward migrations V10–V13 preserve already-applied V1–V9 checksums. `SyncPagingIT` exercises V9 upgrade; the packaged operation and HTTPS restoration entry points cover the new schema and inherited property metadata. Prior local and real-provider HTTPS restoration passed old-token rejection, fresh synchronization, authoritative task bytes and separately recovered READ-recipient access/revocation; these are separate from database-only checks. | +| Restart/restore | Durable PostgreSQL state survives process restarts. Offline restore rotates recovery/account epochs, disables every account and clears restored factors/sessions/DAV/OAuth credentials before individually verified recovery; restoration also clears durable continuation rows while retaining authoritative version/property history, so old tokens and credentials cannot silently revive. Forward migrations V10–V14 preserve already-applied V1–V9 checksums. `SyncPagingIT` exercises V9 upgrade; the packaged operation and HTTPS restoration entry points cover the new schema and inherited property metadata. Prior local and real-provider HTTPS restoration passed old-token rejection, fresh synchronization, authoritative task bytes and separately recovered READ-recipient access/revocation; these are separate from database-only checks. | ## Authentication and application scope @@ -86,4 +101,4 @@ version-specific client checks and archived historical results. Thunderbird 159. manifest records source, CI attempt, image/JAR identities and deployment checks. These results are not certification or claims about untested clients/platforms. Third-party licenses remain independent; [operating limits](performance.md) do not -constitute capacity or high-availability guarantees. \ No newline at end of file +constitute capacity or high-availability guarantees. 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..b63abf0 100644 --- a/docs/groups.md +++ b/docs/groups.md @@ -1,16 +1,18 @@ # 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 **Server administration → 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. +Renaming changes only group metadata under the existing mutation lock and stale-name check; it preserves bindings, effective permissions and stable/continuation synchronization tokens. + Membership/grant changes reconcile shared collection bindings and change affected collection synchronization generations. A client with an invalidated stable or continuation token must perform an initial synchronization again; continuation state cannot retain access after account disabling or permission revocation. Removing group access preserves any access separately granted to the same account. Backup/restoration retains groups, grants, memberships and retired principal identifiers; operators must review these restored permissions before re-enabling accounts. 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/images/getting-started/01-protected-setup.png b/docs/images/getting-started/01-protected-setup.png new file mode 100644 index 0000000..f42b9b7 Binary files /dev/null and b/docs/images/getting-started/01-protected-setup.png differ diff --git a/docs/images/getting-started/02-sign-in.png b/docs/images/getting-started/02-sign-in.png new file mode 100644 index 0000000..100f285 Binary files /dev/null and b/docs/images/getting-started/02-sign-in.png differ diff --git a/docs/images/getting-started/03-create-passkey.png b/docs/images/getting-started/03-create-passkey.png new file mode 100644 index 0000000..c850343 Binary files /dev/null and b/docs/images/getting-started/03-create-passkey.png differ diff --git a/docs/images/getting-started/04-passkey-saved.png b/docs/images/getting-started/04-passkey-saved.png new file mode 100644 index 0000000..bd7aa4e Binary files /dev/null and b/docs/images/getting-started/04-passkey-saved.png differ diff --git a/docs/images/getting-started/05-overview.png b/docs/images/getting-started/05-overview.png new file mode 100644 index 0000000..39fea4d Binary files /dev/null and b/docs/images/getting-started/05-overview.png differ diff --git a/docs/images/getting-started/06-server-administration.png b/docs/images/getting-started/06-server-administration.png new file mode 100644 index 0000000..b176d3d Binary files /dev/null and b/docs/images/getting-started/06-server-administration.png differ diff --git a/docs/images/getting-started/07-accounts.png b/docs/images/getting-started/07-accounts.png new file mode 100644 index 0000000..8b9fa0b Binary files /dev/null and b/docs/images/getting-started/07-accounts.png differ diff --git a/docs/images/getting-started/08-create-account.png b/docs/images/getting-started/08-create-account.png new file mode 100644 index 0000000..decc635 Binary files /dev/null and b/docs/images/getting-started/08-create-account.png differ diff --git a/docs/images/getting-started/09-account-handoff.png b/docs/images/getting-started/09-account-handoff.png new file mode 100644 index 0000000..810cb57 Binary files /dev/null and b/docs/images/getting-started/09-account-handoff.png differ diff --git a/docs/images/getting-started/10-resource-type.png b/docs/images/getting-started/10-resource-type.png new file mode 100644 index 0000000..1235b4c Binary files /dev/null and b/docs/images/getting-started/10-resource-type.png differ diff --git a/docs/images/getting-started/11-empty-task-list.png b/docs/images/getting-started/11-empty-task-list.png new file mode 100644 index 0000000..acbd3ec Binary files /dev/null and b/docs/images/getting-started/11-empty-task-list.png differ diff --git a/docs/images/getting-started/12-resources.png b/docs/images/getting-started/12-resources.png new file mode 100644 index 0000000..afddb01 Binary files /dev/null and b/docs/images/getting-started/12-resources.png differ diff --git a/docs/images/getting-started/13-sharing.png b/docs/images/getting-started/13-sharing.png new file mode 100644 index 0000000..7baa3d4 Binary files /dev/null and b/docs/images/getting-started/13-sharing.png differ diff --git a/docs/images/getting-started/14-security.png b/docs/images/getting-started/14-security.png new file mode 100644 index 0000000..c7cbee4 Binary files /dev/null and b/docs/images/getting-started/14-security.png differ diff --git a/docs/images/getting-started/15-recovery-codes.png b/docs/images/getting-started/15-recovery-codes.png new file mode 100644 index 0000000..4013dc0 Binary files /dev/null and b/docs/images/getting-started/15-recovery-codes.png differ diff --git a/docs/images/getting-started/16-connect-an-app.png b/docs/images/getting-started/16-connect-an-app.png new file mode 100644 index 0000000..9a6f908 Binary files /dev/null and b/docs/images/getting-started/16-connect-an-app.png differ diff --git a/docs/images/getting-started/17-client-configuration.png b/docs/images/getting-started/17-client-configuration.png new file mode 100644 index 0000000..cc586f0 Binary files /dev/null and b/docs/images/getting-started/17-client-configuration.png differ diff --git a/docs/images/getting-started/18-create-application-password.png b/docs/images/getting-started/18-create-application-password.png new file mode 100644 index 0000000..158676f Binary files /dev/null and b/docs/images/getting-started/18-create-application-password.png differ diff --git a/docs/images/getting-started/19-password-created.png b/docs/images/getting-started/19-password-created.png new file mode 100644 index 0000000..1c1b0a1 Binary files /dev/null and b/docs/images/getting-started/19-password-created.png differ diff --git a/docs/images/getting-started/20-import-destination.png b/docs/images/getting-started/20-import-destination.png new file mode 100644 index 0000000..f080c2e Binary files /dev/null and b/docs/images/getting-started/20-import-destination.png differ diff --git a/docs/images/getting-started/21-import-preview.png b/docs/images/getting-started/21-import-preview.png new file mode 100644 index 0000000..3a9424a Binary files /dev/null and b/docs/images/getting-started/21-import-preview.png differ diff --git a/docs/images/getting-started/22-import-result.png b/docs/images/getting-started/22-import-result.png new file mode 100644 index 0000000..39d65f5 Binary files /dev/null and b/docs/images/getting-started/22-import-result.png differ diff --git a/docs/images/getting-started/23-audit.png b/docs/images/getting-started/23-audit.png new file mode 100644 index 0000000..6937722 Binary files /dev/null and b/docs/images/getting-started/23-audit.png differ diff --git a/docs/images/getting-started/24-diagnostics.png b/docs/images/getting-started/24-diagnostics.png new file mode 100644 index 0000000..1a073d8 Binary files /dev/null and b/docs/images/getting-started/24-diagnostics.png differ diff --git a/docs/images/getting-started/25-shared-overview.png b/docs/images/getting-started/25-shared-overview.png new file mode 100644 index 0000000..178f482 Binary files /dev/null and b/docs/images/getting-started/25-shared-overview.png differ diff --git a/docs/images/getting-started/26-returning-verification.png b/docs/images/getting-started/26-returning-verification.png new file mode 100644 index 0000000..6bd78e3 Binary files /dev/null and b/docs/images/getting-started/26-returning-verification.png differ diff --git a/docs/images/getting-started/27-sharing-error.png b/docs/images/getting-started/27-sharing-error.png new file mode 100644 index 0000000..892f366 Binary files /dev/null and b/docs/images/getting-started/27-sharing-error.png differ diff --git a/docs/images/getting-started/28-share-removal-review.png b/docs/images/getting-started/28-share-removal-review.png new file mode 100644 index 0000000..f49ec80 Binary files /dev/null and b/docs/images/getting-started/28-share-removal-review.png differ diff --git a/docs/images/getting-started/29-credential-management.png b/docs/images/getting-started/29-credential-management.png new file mode 100644 index 0000000..34bbe52 Binary files /dev/null and b/docs/images/getting-started/29-credential-management.png differ diff --git a/docs/images/getting-started/30-import-report-unavailable.png b/docs/images/getting-started/30-import-report-unavailable.png new file mode 100644 index 0000000..b0f42a0 Binary files /dev/null and b/docs/images/getting-started/30-import-report-unavailable.png differ diff --git a/docs/operations.md b/docs/operations.md index dcf272e..3d8b369 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -18,11 +18,40 @@ cd caldav-server-@VERSION@-deploy cp .env.example .env # Edit .env and create private secrets using the instructions below. docker compose config --quiet -docker compose pull +docker compose pull --policy missing 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.4.1+1) 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.1+2), 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 +must provide at least 384 MiB available temporary space and protect that directory +from web serving and unrelated writers. Restart invalidates pending previews and +cleans recognized orphan files under an exclusive instance lock; a stopped JAR +cannot clean crash remnants until its next start. Compose provides a 384 MiB `/tmp` +tmpfs and a 40% heap ceiling within the 1 GiB memory limit. The shared portability +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 @@ -71,7 +100,7 @@ docker compose ps The base URL and issuer must be equal, canonical absolute URLs with no trailing slash, query, credentials, fragment, or percent-encoded path. Configuration is validated at startup. These are external addresses, not `http://application:8080` or `http://database:5432`. Loopback HTTP is accepted only with the explicit development switch `BUSYSTACK_ALLOW_INSECURE_LOCAL=true`; that setting does not make HTTP suitable for network credential use. -The application runs as UID/GID 10001, with a read-only root filesystem, a bounded temporary directory, dropped Linux capabilities, and a 1 GiB container memory limit. That memory limit is a conservative engineering default, not a measured production capacity claim. PostgreSQL data is persisted at `/var/lib/postgresql`, the PostgreSQL 18 image's volume root. No database port is published. The application listener is published only on `127.@VERSION@`, port 8080 by default (`BUSYSTACK_HTTP_PORT` can change the host port). +The application runs as UID/GID 10001, with a read-only root filesystem, a bounded temporary directory, dropped Linux capabilities, and a 1 GiB container memory limit. That memory limit is a conservative engineering default, not a measured production capacity claim. PostgreSQL data is persisted at `/var/lib/postgresql`, the PostgreSQL 18 image's volume root. No database port is published. The application listener is published only on `127.0.0.1`, port 8080 by default (`BUSYSTACK_HTTP_PORT` can change the host port). PostgreSQL administration uses a separate secret. Initialization creates a non-superuser `busystack` database owner for application migrations and runtime. Initialization scripts run only on an empty database volume. Replacing a password file does not rotate an already initialized PostgreSQL role; rotate the database role and secret together during controlled downtime. @@ -79,7 +108,7 @@ Compose secret mounts supply `spring.datasource.password` through Spring's confi ## HTTPS and proxy paths -Terminate TLS at a configured reverse proxy and allow its local connection to `127.@VERSION@:8080`. Deny public access to `/actuator/`; health probes are for local/container monitoring. Set request-size and timeout limits at the proxy as well as the application. Use valid certificates and clients' normal certificate validation. +Terminate TLS at a configured reverse proxy and allow its local connection to `127.0.0.1:8080`. Deny public access to `/actuator/`; health probes are for local/container monitoring. Set request-size and timeout limits at the proxy as well as the application. Use valid certificates and clients' normal certificate validation. Put either location arrangement below inside your proxy's HTTPS virtual host, using its real certificate chain and private key. For example, the surrounding Nginx configuration is: @@ -111,7 +140,7 @@ location / { client_max_body_size 1m; proxy_connect_timeout 5s; proxy_read_timeout 120s; - proxy_pass http://127.@VERSION@:8080; + proxy_pass http://127.0.0.1:8080; proxy_set_header Host calendar.example.org; proxy_set_header Forwarded ""; proxy_set_header X-Forwarded-Host ""; @@ -130,7 +159,7 @@ location = /.well-known/caldav { return 308 https://calendar.example.org/calendar/dav/; } location = /.well-known/oauth-authorization-server/calendar { - proxy_pass http://127.@VERSION@:8080/calendar/.well-known/oauth-authorization-server; + proxy_pass http://127.0.0.1:8080/calendar/.well-known/oauth-authorization-server; proxy_set_header Host calendar.example.org; proxy_set_header Forwarded ""; proxy_set_header X-Forwarded-Host ""; @@ -139,7 +168,7 @@ location = /.well-known/oauth-authorization-server/calendar { location ^~ /calendar/actuator/ { return 404; } location /calendar/ { client_max_body_size 1m; - proxy_pass http://127.@VERSION@:8080; + proxy_pass http://127.0.0.1:8080; proxy_set_header Host calendar.example.org; proxy_set_header Forwarded ""; proxy_set_header X-Forwarded-Host ""; @@ -149,12 +178,39 @@ 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. Its operator-profile +container disables the Docker log driver so the code cannot be retained in +container logs; normal application logging is unchanged. 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. +After browser creation, BusyStack redirects to normal sign-in. Register the first +passkey and use Verify and continue to supply the separate assertion. BusyStack +then opens Overview or the saved task. Registration alone leaves the browser +session incomplete. Sensitive actions use the ten-minute freshness policy. + ## 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 -java -jar target/caldav-server-@VERSION@.jar \ +umask 077 +java -XX:+ExitOnOutOfMemoryError -jar target/caldav-server-@VERSION@.jar \ --spring.main.web-application-type=none \ --busystack.bootstrap=true \ --busystack.bootstrap-username=administrator \ @@ -187,14 +243,20 @@ 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. +The account detail page supplies nonsecret handoff instructions. A completed browser session has thirty minutes of idle time and an eight-hour overall limit. + +For portal imports, add a proxy location allowing a 65 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. +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 @@ -230,7 +292,7 @@ The default accepts `Depth: 1` only with XML sync-level 1. Missing Depth and `De `/actuator/health/liveness` and `/actuator/health/readiness` return probe status without details. The Compose application health check calls readiness locally. Readiness includes the database check. Only health endpoints are exposed by Actuator; there is no public diagnostic dump. -The database connection pool is bounded to 10 connections; connection acquisition times out after 10 seconds. Servlet form bodies are limited to 64 KiB, accepted calendar objects to 1 MiB in the persistence schema, and the container temporary filesystem to 128 MiB. DAV request bodies are streamed with a 1 MiB cap; compressed Content-Encoding is rejected with 415 rather than decompressed. The principal protocol/query limits are below; exceeding a budget returns an explicit failure rather than incomplete matching data. These are work bounds, not measured capacity guarantees. +The database connection pool is bounded to 10 connections; connection acquisition times out after 10 seconds. Servlet form bodies are limited to 64 KiB, accepted calendar objects to 1 MiB in the persistence schema, and the container temporary filesystem to 384 MiB. DAV request bodies are streamed with a 1 MiB cap; compressed Content-Encoding is rejected with 415 rather than decompressed. The principal protocol/query limits are below; exceeding a budget returns an explicit failure rather than incomplete matching data. These are work bounds, not measured capacity guarantees. | Boundary | Current limit | | --- | --- | @@ -278,7 +340,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 @@ -287,16 +349,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 V13; 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 V19; 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 in the supported V1–V19 range, 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, pending navigation and provider flows, issuance intents, 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 V13. +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 V19. After independently verifying a user's identity, use the controlled local recovery operation with an owner-only file containing a fresh password: @@ -334,6 +396,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–V13 and introduces no migration during final release preparation. +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–V19. V19 stores short-lived browser navigation and provider flows separately from session attributes. Restore clears all pending browser flows. V18 adds browser issuance intents and a recovery-code generation marker; restore deletes issuance receipts. V17 adds VJOURNAL to the collection constraint and does not add security state. V14 adds nullable opaque administrative audit targets; V15 adds protected installation state and invalidates outstanding initialization codes during restore; V16 scopes group reconciliation to non-nested-loop join planning after a reproduced cached-plan timeout; its thirty-second deadline and authorization remain unchanged. 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..166b0cc 100644 --- a/docs/passkeys-and-mfa.md +++ b/docs/passkeys-and-mfa.md @@ -2,9 +2,9 @@ BusyStack connects Spring Security 7.1.2's WebAuthn mechanisms and WebAuthn4j verification to PostgreSQL. Account configuration is available at `/security/passkeys`. The interface uses local JavaScript and has no CDN or analytics dependency. Event and task content is managed by CalDAV clients. -Sign in at `/login` using your account password. The first passkey enrollment requires a primary factor verified in the last ten minutes: a password for local users, or verified organization OIDC login for externally managed users. Enroll a resident passkey using an authenticator that supports user verification; BusyStack requires verification for registration and authentication. Then use **Verify passkey** to complete password plus WebAuthn MFA for the same account. Additional passkey enrollment and credential removal require the appropriate primary factor and WebAuthn within the same ten-minute period. See [optional Keycloak configuration](keycloak.md) for the externally managed policy. +Sign in at `/login` using your account password. The first passkey enrollment requires a primary factor verified in the last ten minutes: a password for local users, or verified organization OIDC login for externally managed users. Enroll a resident passkey using an authenticator that supports user verification; BusyStack requires verification for registration and authentication. Then use **Verify and continue** to complete password plus WebAuthn MFA for the same account. Additional passkey enrollment and credential removal require the appropriate primary factor and WebAuthn within the same ten-minute period. See [optional Keycloak configuration](keycloak.md) for the externally managed policy. -Account mutations and client authorization require recent MFA. The account overview can be read with a single authenticated factor, so an account without a passkey can reach enrollment. These explicit rules do not claim that a password-only overview is MFA. Losing the password or all authenticators does not grant an HTTP recovery bypass. +Account mutations and client authorization require recent MFA. A password-only or organization-only session can reach passkey enrollment, verification and recovery. Account pages require a completed session tied to an active assertion key, the account identity and its epoch. A completed session has a 30-minute idle limit and an eight-hour overall limit. Losing the password or all authenticators does not grant an HTTP recovery bypass. The relying-party ID is the hostname of the validated public base URL; the allowed origin is its exact scheme, hostname and port. A reverse-proxy path is not part of an origin. Changing the public hostname can make existing authenticator registrations unusable. Deployment URLs must therefore be selected deliberately. Production uses HTTPS; explicitly enabled HTTP loopback development is separate configuration. @@ -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/portability.md b/docs/portability.md new file mode 100644 index 0000000..d8b97e7 --- /dev/null +++ b/docs/portability.md @@ -0,0 +1,172 @@ +# iCalendar import and export + +The account portal exposes data portability through the same CalendarStore, +DavStore and CalendarAdmission used by DAV. Use a compatible CalDAV app to edit events, tasks and journal entries. + +## Export + +An owner or current read-authorized recipient can export a collection after +primary sign-in and passkey verification within ten minutes. 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. +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 resource explains how to add or import content. If the resource becomes empty after opening its details, the export returns to the resource with a neutral notice. + +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 or journal component retain their original bytes; only repeated +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, 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 +line ending receives a separator. BusyStack imports both representations. + +**Thunderbird 159.0's native file parser does not consume multiple VCALENDAR roots.** +Its CalICSService wraps ICAL.parse's multi-root array as a single component. Use a +single-VCALENDAR export for its file importer; a lossless stream requires an importer +that accepts RFC 5545 streams, such as BusyStack. Native DAV synchronization remains +independent of file import. Do not assume another application's file-import support +from its protocol support. + +Export and import both support at most 10,000 resources / UID series and 64 MiB. +Every successful export can be uploaded directly into an authorized destination of +the same component type. No manual splitting, recurrence reconstruction or +calendar-context merging is required. Arbitrary larger migrations are not supported. + +## Preview, confirm and results + +Open a writable destination and choose Import an iCalendar file. Verify your sign-in when prompted before selecting the file. 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 or VJOURNAL 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 confirmation redirect to the same authorized report address. The preview and final 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 +separate input objects are rejected rather than guessed or discarded. Unsupported +and invalid items are reported. No replacement or implicit merge is offered. + +A preview uses an opaque account/security-generation-bound token. One preview per +account is retained for ten minutes, with at most 32 previews/results per instance. +Successful result pagination remains available for ten minutes after commit. +A replacement is installed only after validation and staging succeed; a bad upload +preserves the existing preview. **Review your latest import preview or results** +returns to it from the portability page or a failed replacement upload. The link +is shown only after current MFA and destination access checks. Retained report metadata has a separate 32 MiB +aggregate bound. Expiration or cancellation removes the private data. + +Confirmation requires the checkbox, current account state, recent MFA and current +destination write permission again. The service takes the existing DAV +namespace/collection locks, claims the preview exclusively and reclassifies +conflicts. New valid series use create-only preconditions in one PostgreSQL +transaction. Any database failure rolls back every write. A known rollback restores +the preview for retry while it remains valid; follow the error page's review link. +A successful commit consumes it before filesystem cleanup, so cleanup failure +cannot permit replay. An indeterminate transaction outcome invalidates the preview; +review the collection before uploading again. Successful results explicitly show +imported, skipped, conflicting and rejected items. No invitation, outbound +attachment fetch or alarm execution occurs. + +## Private temporary storage + +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. 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. + +Completion, cancellation, expiration and graceful shutdown attempt deletion. +Failed deletion retains its storage reservation and is retried every thirty +seconds. Pending previews are intentionally invalid after JVM restart. Startup +removes only recognized application data/multipart orphan files under the locked +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 + +| Budget | Bound | +| --- | --- | +| Individual input / export | 64 MiB | +| UID series / exported resources | 10,000 | +| Individual admitted DAV resource | 1 MiB (unchanged) | +| Aggregate reconstructed import resources | 64 MiB | +| On-disk parser index | 32 MiB | +| Portability private files, including pending cleanup | 72 | +| Concurrent portability requests | 2 | +| Aggregate temporary reservations | 272 MiB | +| Upload reservation before multipart parsing | 161 MiB (65 multipart + 64 input + 32 index) | +| Other operation reservation | 64 MiB (including export or confirmation index) | +| Parsing / transaction processing deadline | 600 seconds | + +The importer reads logical lines and top-level components incrementally and uses a +binary disk index of original byte ranges. It reconstructs and admits one UID +resource at a time, preserving recurrence order and each VCALENDAR's own metadata +and timezone context. It never retains the whole upload plus all reconstructed +resources in memory. Nesting is bounded to eight, logical lines to 1 MiB, and each +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 +Retry-After means retry or cancel an unused preview. Exports complete under their +reservation before sending success headers, never as truncated successful files. +The 384 MiB Compose `/tmp` tmpfs leaves 112 MiB outside the portability ledger for +operational headroom. The 1 GiB container uses a 40% JVM heap ceiling so tmpfs and +native memory have room; this is a bounded configuration, not a capacity promise. +A standalone JAR must provision at least 384 MiB free on its private staging +filesystem, separately from PostgreSQL, backups and other processes. + +The proxy allows 65 MiB multipart requests **only** at `/portability/preview` +(including an application prefix). Portability proxy request/response disk +buffering is disabled and its response deadline is 660 seconds. Multipart bodies +are rejected at other application routes before buffering. Ordinary DAV 1 MiB and +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, +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..3a47b92 --- /dev/null +++ b/docs/portal.md @@ -0,0 +1,100 @@ +# Your BusyStack account + +BusyStack manages your account, collections and client access. Edit events, tasks and journal entries in your CalDAV application. Local authentication requires no identity +provider, email service or vendor account. + +## First sign-in + +Open the configured HTTPS address. Enter your account password or use +organization sign-in. On first sign-in, select **Create passkey**, then **Verify +and continue**. Returning users verify an existing passkey. After verification, +BusyStack opens Overview or the task that prompted sign-in. + +A completed session supports ordinary navigation for up to 30 minutes of +inactivity and eight hours overall. Protected actions require both factors to +be under ten minutes old. BusyStack prompts when you initiate a protected +action and returns you to the task to review and submit again. Recovery codes +are available in [Security](account-security.md). + +## Calendars, tasks & journals + +Open **Calendars, tasks & journals** and choose **All**, **Owned by me** or +**Shared with me**. Search by name. Open a result for its details, access and +CalDAV address. + +Use **Create a resource** to choose Calendar, Task list or Journal. Provide a +name and optional description and color. The type stays fixed. Metadata edits +preserve identity, address and stored resources. Use #RRGGBB or #RRGGBBAA for +the color property. A client can maintain its own local color preference. + +Read/write recipients can edit shared metadata and import. Read-only recipients +can read and export accessible contents. Owners can manage sharing and delete +a resource. Confirming deletion removes its contents, history, bindings and +sharing grants. For important data, export or obtain an operator backup before +deletion. Reload a stale form and review the current state. + +## 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 **Connect an app** and select your app. Use an existing application +password or create a separate one for this app or device. The one-time result +has the selected app’s setup steps, addresses, username, expiry and password. +Keep it open while setting up the app. The original password cannot be retrieved +afterward. To replace it, issue another, configure the client and revoke the +previous password when ready. + +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 under Connect an app 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 historical GNOME record uses a source provisioned through EDS's supported API. +The GNOME 50.0 wizard has also passed a private-profile graphical setup and native +EDS read/write-permission check on the 0.2.0 development server. Use **Manage +Calendars → Add Calendar**, paste the portal's **GNOME connection address** under +**Connect to an Online Calendar**, supply the username and dedicated DAV credential +in **Credentials**, and choose **Connect**. When validation completes, choose **Add +Calendar**. Enter the same DAV credential in the native calendar-authentication +prompt when synchronization begins. The address includes only the username, never +the password: GNOME otherwise fails to retain the authentication user after +discovery. The qualification requires both imported UIDs, the recurrence exception, +extension data and native owner write permission; it does not claim full native +editor or assistive-technology coverage. Exact artifact/configuration results are +recorded separately. + +Registered OAuth applications may use browser consent instead of a DAV credential. +Review them under **Security → Authorized 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). + +Open a resource to **Import an iCalendar file** or export available contents. Use the [portability guide](portability.md) for conflict handling, limits and representation. + +Ordinary form errors return to the editable form, preserve nonsensitive values and +associate fixed explanations with the affected controls. The focused validation +summary links to those controls. Passwords and issued secrets are never restored. +Duplicates return a conflict; stale forms require reloading the current state. +Authentication, authorization, capacity and operational failures retain their +separate error handling rather than masquerading as invalid field values. diff --git a/docs/releases/0.2.0.md b/docs/releases/0.2.0.md new file mode 100644 index 0000000..3a15073 --- /dev/null +++ b/docs/releases/0.2.0.md @@ -0,0 +1,66 @@ +# BusyStack CalDAV Server 0.2.0 + +This release adds a server-rendered account and administration portal for +collection management, direct and group sharing, client connections, security +settings, diagnostics and confirmed iCalendar import and export. CalDAV +collections support events, tasks and journals. Edit calendar items in a +connected client. + +Start with the illustrated [Getting Started guide](../GETTING_STARTED.md), +[portal guide](../portal.md), [administration guide](../administration.md) +and [portability guide](../portability.md). + +## Changes + +- Fresh installations open a protected setup form. Issue a single-use + fifteen-minute code with `bash scripts/initialize.sh`, then create the + administrator in the browser. Sign in and enroll and verify a passkey to + open Overview or resume the saved task. +- Application passwords appear with client-specific connection instructions. + PostgreSQL issuance receipts prevent duplicate credentials on retries. + Browser navigation preserves safe return paths across sign-in and follow-up + verification. Browser sessions have a thirty-minute idle limit and an + eight-hour overall limit. +- Imports use bounded private storage and support up to 64 MiB and 10,000 + series per file. Confirmations keep committed results across retries. + Use the documented proxy location and upload limits for import. +- CalDAV reports use collection or request timezones for floating values and + include detached occurrences moved into the requested window. Recurrence + searches account for reachable offsets while retaining work limits. +- Offline Compose administration commands support operator numeric UIDs + without a container account. Private staging still checks directory + ownership and permissions. + +## Upgrading from 0.1.0 + +Back up the database and rehearse restoration in a separate project before +upgrading. Keep the existing Compose project, volume, secrets, public HTTPS URL +and OAuth issuer. Follow the [update and recovery procedure](../operations.md). + +The published V1–V13 migrations retain their original checksums. V14 adds opaque +administrative audit targets, V15 adds protected installation state and V16 +corrects cached-plan timeouts in group reconciliation. V17 admits journals, +V18 adds browser issuance receipts and a recovery-code generation marker, and +V19 stores short-lived browser navigation and provider flows. These migrations run +forward only. Recover from a failed upgrade using a verified pre-upgrade backup. + +Isolated restore supports complete schema histories through V19. It preserves +an initialized installation and its data, disables restored accounts pending +individual recovery, and invalidates restored credentials, sessions, pending +browser flows and setup codes. + +## Supported configurations + +Use Linux AMD64 with Docker Compose 2.24.4 or newer and PostgreSQL 18.6, or the +standalone JAR with Java 25. The selected runtime is official Temurin 25.0.5.1+2. +Use trusted HTTPS at the hostname root or a preserved proxy subpath. Local +accounts and optional Keycloak OIDC use local passkey MFA. + +The desktop profiles cover Thunderbird 159.0 with system and explicit +America/Vancouver settings and explicit Europe/Berlin, plus GNOME Calendar +50.0 with Evolution Data Server 3.56.2 in America/Vancouver. GNOME Calendar's +profile covers events. The browser tests use a virtual CTAP2 authenticator. + +The portal manages collections and accounts. It supplies no item editor, +CardDAV, invitation delivery or reminder execution. See the [client and protocol scope](../conformance.md) +and [version-specific client qualification](../../qualification/evidence/releases/0.2.0/verification.json). diff --git a/docs/security-verification.md b/docs/security-verification.md index 4b9f615..be4d60e 100644 --- a/docs/security-verification.md +++ b/docs/security-verification.md @@ -41,4 +41,4 @@ The project is licensed under Apache-2.0. Project and applicable third-party lic Default DAV synchronization accepts the narrowly bounded `Depth: 1` accommodation only with XML `sync-level=1`; ordinary omitted/zero depth remains supported and explicit `false` enables strict mode. This deliberate RFC 6578 header exception changes neither collection scope nor authorization. Continuations are scoped to actor, collection generation, recovery epoch and retained history, and every page checks current access. Immutable version snapshots and a fixed high watermark prevent a page token advancing beyond changes absent from the response. Restore clears continuation state with the existing account/credential invalidation policy. -The current qualified source repeats Thunderbird 157.0.1/native-provider and python-caldav 3.6.0 cross-client calendar/task round trips without an enabling depth override, including recurring exceptions, all-day/floating data, alarms, extensions and completed tasks. Current root/proxy/Keycloak and local/federated restoration records identify actual configuration, fresh post-workload public refresh/MFA and denial of restored old credentials/sessions/sync state. Java advisories cover 112 runtime Maven versions with no returned advisories; the distinct final-image OS scan reports 46 MEDIUM and 12 LOW findings, zero HIGH/CRITICAL/UNKNOWN and no suppressions. Manual graphical setup, physical authenticators and additional platforms remain unexecuted. Independent review is not an added certification prerequisite. +The historical qualification source repeated Thunderbird 157.0.1/native-provider and python-caldav 3.6.0 cross-client calendar/task round trips without an enabling depth override, including recurring exceptions, all-day/floating data, alarms, extensions and completed tasks. Current root/proxy/Keycloak and local/federated restoration records identify actual configuration, fresh post-workload public refresh/MFA and denial of restored old credentials/sessions/sync state. Java advisories cover 112 runtime Maven versions with no returned advisories; the distinct final-image OS scan reports 46 MEDIUM and 12 LOW findings, zero HIGH/CRITICAL/UNKNOWN and no suppressions. Manual graphical setup, physical authenticators and additional platforms remain unexecuted. Independent review is not an added certification prerequisite. diff --git a/docs/standards-review.md b/docs/standards-review.md index fe0addb..e9c86e3 100644 --- a/docs/standards-review.md +++ b/docs/standards-review.md @@ -55,6 +55,27 @@ Property retrieval selects only requested values; `propname` retrieves names dir RFC4791’s [information page](https://www.rfc-editor.org/info/rfc4791/) lists RFC5689,6638,6764,7809,7953,8996. RFC6764 discovery is implemented. TLS1.2/1.3 at the documented proxy arrangement follows RFC8996’s removal of TLS1.0/1.1. Extended MKCOL, automatic scheduling, timezone-by-reference and availability components are not advertised. Explicit embedded VTIMEZONE remains required for TZID-bearing accepted resources. Adding a dependency class does not enable an extension. -RFC5545’s [information page](https://www.rfc-editor.org/info/rfc5545/) lists RFC5546,6868,7529,7953,7986,9073,9074,9253. RFC6868 parameter encoding is implemented. iTIP/scheduling execution, availability and specialized new-component services remain outside this calendar-access profile; valid supported-resource extension properties are retained without promising to execute them. Non-Gregorian RSCALE processing is not advertised. RFC4918’s RFC5689 update does not require advertising extended collection creation. RFC5397,6578,6764 had no errata records in the checked inventory. +RFC5545’s [information page](https://www.rfc-editor.org/info/rfc5545/) lists RFC5546,6868,7529,7953,7986,9073,9074,9253,10051. RFC6868 parameter encoding is implemented. RFC10051 task data updates (duration without start, PENDING/FAILED, and preserved registered task metadata) are implemented through the official upstream model interfaces; optional server task automation is not advertised. iTIP/scheduling execution, availability and specialized new-component services remain outside this calendar-access profile; valid supported-resource extension properties are retained without promising to execute them. Non-Gregorian RSCALE processing is not advertised. RFC4918’s RFC5689 update does not require advertising extended collection creation. RFC5397,6578,6764 had no errata records in the checked inventory. Recheck the linked primary inventories when updating this contract or its libraries. Current test results, deliberate Digest/security and optional sync-Depth compatibility deviations remain explicit in the conformance matrix; no claim of literal compliance with every historical HTTP/WebDAV provision is made. + +Known RSVP values are checked before model construction so invalid booleans cannot +be coerced into FALSE. LANGUAGE values are checked for BCP47 syntax through the +supported JDK Locale.Builder API, including valid private-use and grandfathered +forms. Validation does not rewrite accepted source spelling or query parameters. + +### Closure of CAL-R022, CAL-R037 and CAL-R050 + +The completion qualification adds clause-derived positive/negative TIME and +ATTACH tests, same-resource HTTP readback/report/update controls, and tests of +all supplied DTEND values. TIME applies to explicitly declared extension values; +it does not require a time-only event feature. ATTACH's current defined alternatives +are URI and BINARY; generic unknown-type preservation does not introduce new +allowable types for that defined property. Unknown extension-property data and +unknown attachment parameters remain preserved. + +RFC 5545 §§3.6.1 and3.8.2.2 contain no explicit DTEND singleton requirement for +VEVENT. No applicable verified erratum adds one. Independent implementation +behavior is comparative evidence, not a normative rule. The previous duplicate +DTEND rejection hypothesis must remain visible as a non-normative hypothesis, +while the actual per-value mandatory constraints are independently tested. diff --git a/docs/versions.md b/docs/versions.md index fbe16b7..1f8502a 100644 --- a/docs/versions.md +++ b/docs/versions.md @@ -4,7 +4,7 @@ The versions below describe the maintained build and runtime inputs. Maven's app | Component | Selected version | Source and license | | --- | --- | --- | -| Eclipse Temurin OpenJDK | 25.0.4.1+1, Java 25 LTS | [Adoptium releases](https://adoptium.net/temurin/releases/?version=25), [OpenJDK license](https://openjdk.org/legal/gplv2+ce.html): GPL-2.0 with Classpath Exception | +| Eclipse Temurin OpenJDK | 25.0.5.1+2, Java 25 LTS | [Adoptium release](https://github.com/adoptium/temurin25-binaries/releases/tag/jdk-25.0.5.1%2B2), [OpenJDK license](https://openjdk.org/legal/gplv2+ce.html): GPL-2.0 with Classpath Exception | | Maven | 3.9.12 | [Maven release history](https://maven.apache.org/docs/history.html): Apache-2.0 | | Maven Wrapper | 3.3.4 | [Wrapper](https://maven.apache.org/wrapper/): Apache-2.0; distribution and SHA-256 pinned in `.mvn/wrapper/maven-wrapper.properties` | | Spring Boot | 4.1.2 | [Published parent](https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-starter-parent/4.1.2/), [requirements](https://docs.spring.io/spring-boot/system-requirements.html): Apache-2.0 | @@ -37,20 +37,22 @@ The Dockerfiles and Compose file use immutable registry digests, with descriptiv | Image | Digest | | --- | --- | -| `eclipse-temurin:25-jdk` | `sha256:3ab7fc8d0b4ade8fef96903fb36767c1dbb4fd1535dcfad85b59c17afbbb5857` | +| `eclipse-temurin:25.0.5.1_2-jdk-resolute` (Linux AMD64) | `sha256:d1b500f1a2a8e2cb1b0fa84e21c4a52963050cbd46b8a53fcb6a8eec0f57675f` | | `mcr.microsoft.com/playwright:v1.61.1-noble` | `sha256:5b8f294aff9041b7191c34a4bab3ac270157a28774d4b0660e9743297b697e48` | | `nginx:1.30.6-alpine` | `sha256:47928bf67eb62a1863cb08d9ecb52d3e704304ba614eaee17884204677702951` | | `quay.io/keycloak/keycloak:26.8.1` | `sha256:a78d6b79572168cb25886b80a8b5b8d4ed4390743e3eecb810538683e209dd6b` | | `testcontainers/ryuk:0.14.0` | `sha256:7c1a8a9a47c780ed0f983770a662f80deb115d95cce3e2daa3d12115b8cd28f0` | | `postgres:18.6` | `sha256:edb0c08dc33befd0262ab3b5cf1c4f3f8cfd8b09e88c05b45adee29d6761ddb6` | -Residual qualification on 2026-10-29 found HIGH [CVE-2026-111497](https://ubuntu.com/security/notices/USN-8956-1) in the previous official Temurin image (`libbrotli1` 1.2.0-3build1). The refreshed official digest above supplies Ubuntu’s fixed 1.2.0-3ubuntu0.1 package while retaining **Temurin 25.0.4.1+1** and the identical Java executable SHA-256 `7380ce48ed5013735d2c8414db54adb8f981e7933ff594bd36f3baccddaafba3`. The application, CI JDK installer and optional Keycloak fixture use the same refreshed pin. No advisory suppression or third-party patch is applied; the failed scan and subsequent qualification are retained separately. +Residual qualification on 2026-10-29 found HIGH [CVE-2026-111497](https://ubuntu.com/security/notices/USN-8956-1) in the previous official Temurin image (`libbrotli1` 1.2.0-3build1). A subsequent official image supplied Ubuntu’s fixed 1.2.0-3ubuntu0.1 package with Temurin 25.0.4.1+1. Those scans and later Temurin 25.0.5+8 qualification remain historical evidence. + +The current official Temurin image includes `apt` and `libapt-pkg7.0` at Ubuntu's fixed 3.2.1ubuntu0.1 version. The application, CI installer and optional Keycloak fixture take Java from this same digest. The Java executable SHA-256 is `119be7dc09c11c805f4face21d268d4b05f807a56d5c6fca1956fc35f6d2c35b`. [Ubuntu security notice USN-8996-1](https://ubuntu.com/security/notices/USN-8996-1) The supported developer build runs the Maven wrapper with the selected JDK and passes the verified JAR to Docker. The runtime image uses the same pinned Temurin release; no Maven builder image is needed. The Keycloak fixture copies the pinned official distribution onto the pinned Temurin JDK for a consistent test runtime. No Keycloak application code is changed. The production deployment does not contain Keycloak. Browser certificate tooling is pinned to Ubuntu `libnss3-tools=2:3.98-1ubuntu0.3`; generated certificates and trust databases exist only in disposable private fixture directories. -CI installs the exact JDK from the pinned Temurin image through `scripts/install-ci-jdk.sh`, validates its release/runtime version and exports it for Maven. This avoids setup-java's SemVer rejection of the four-part 25.0.4.1 version without selecting another patch. +CI installs the exact JDK from the pinned Temurin image through `scripts/install-ci-jdk.sh`, validates its release/runtime version and exports it for Maven. No JDK or third-party application code is patched. CI actions use immutable Git commit references in [ci.yml](../.github/workflows/ci.yml). Updating a digest or dependency is a reviewed repository change followed by the required suites; pins do not remove the need to apply security updates. 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/README.md b/qualification/clients/README.md index 9dc78c5..6b9eea9 100644 --- a/qualification/clients/README.md +++ b/qualification/clients/README.md @@ -1,29 +1,38 @@ # Independent clients -`IndependentClientIT` starts the actual application with PostgreSQL 18.6 and TLS signed by a disposable CA. Its account and named DAV credential are fixture setup through application services; the separate Python process performs discovery, calendar/task creation, reads, writes, queries and synchronization through `python-caldav:3.6.0` and `icalendar:7.3.0`. It shares neither HTTP/XML request builders nor calendar parsing with the server. Missing Python/dependencies fail this required test. +`IndependentClientIT` starts the actual application with PostgreSQL 18.6 and TLS signed by a disposable CA. Its account and named DAV credential are fixture setup through application services; separate Python and native Thunderbird processes perform the independent checks. The Python client uses `python-caldav:3.6.0` and `icalendar:7.3.0` and shares neither HTTP/XML request builders nor calendar parsing with the server. Both clients are mandatory in the maintained verification gate: missing Python/dependencies or `BUSYSTACK_THUNDERBIRD_BINARY` fail the test. -The independent-client fixture leaves the synchronization-depth setting **absent**. Both python-caldav 3.6.0 and Thunderbird 157 send HTTP `Depth: 1`, whereas [RFC 6578 section 3.2](https://www.rfc-editor.org/rfc/rfc6578.html#section-3.2) requires rejection of nonzero Depth. The server default deliberately accommodates Depth 1 only with XML sync-level 1. Missing Depth and Depth 0 work normally; unsupported/malformed/duplicate/infinite values remain rejected. Explicit `BUSYSTACK_DAV_ALLOW_SYNC_DEPTH_ONE=false` selects strict mode and has a separate real-HTTPS qualification profile. Scope, authorization, continuation and computation limits are unchanged. This is a documented exception to that RFC requirement, not strict compliance with it. Each independent runner performs actual authenticated missing/0/1 REPORTs and wrong-level rejection, records observed effective behavior, and separately records the calling harness's configuration input. Client synchronization fallback remains disabled. +The independent-client fixture leaves the synchronization-depth setting **absent**. Both python-caldav 3.6.0 and Thunderbird 157 send HTTP `Depth: 1`, whereas [RFC 6578 section 3.3](https://www.rfc-editor.org/rfc/rfc6578.html#section-3.3) requires rejection of nonzero Depth. The server default deliberately accommodates Depth 1 only with XML sync-level 1. Missing Depth and Depth 0 work normally; unsupported/malformed/duplicate/infinite values remain rejected. Explicit `BUSYSTACK_DAV_ALLOW_SYNC_DEPTH_ONE=false` selects strict mode and has a separate real-HTTPS qualification profile. Scope, authorization, continuation and computation limits are unchanged. This is a documented exception to that RFC requirement, not strict compliance with it. Each independent runner performs actual authenticated missing/0/1 REPORTs and wrong-level rejection, records observed effective behavior, and separately records the calling harness's configuration input. Client synchronization fallback remains disabled. ```sh python3 -m venv .client-venv -.client-venv/bin/pip install -r qualification/clients/requirements.txt -BUSYSTACK_CLIENT_PYTHON="$PWD/.client-venv/bin/python" ./mvnw verify +.client-venv/bin/pip install -r qualification/clients/requirements.txt -r qualification/clients/desktop-requirements.txt +bash qualification/clients/install-thunderbird.sh .client-tools +BUSYSTACK_CLIENT_PYTHON="$PWD/.client-venv/bin/python" \ +BUSYSTACK_THUNDERBIRD_BINARY="$PWD/.client-tools/thunderbird/thunderbird" \ + ./mvnw -B -ntp clean verify ``` -For the desktop-client provider profile, install the additional pinned Mozilla driver dependencies and a published Thunderbird 157.0.1 Linux binary. The installer checks the exact [official SHA512SUMS](https://archive.mozilla.org/pub/thunderbird/releases/157.0.1/SHA512SUMS) entry before extraction. It requires an empty tooling destination and changes no installed Thunderbird/profile. +The setup above installs the pinned Mozilla driver dependencies and published Thunderbird 157.0.1 Linux binary. The installer checks the exact [official SHA512SUMS](https://archive.mozilla.org/pub/thunderbird/releases/157.0.1/SHA512SUMS) entry before extraction. It requires an empty tooling destination and changes no installed Thunderbird/profile. To repeat only the independent-client integration profile after setup: ```sh -.client-venv/bin/pip install -r qualification/clients/desktop-requirements.txt -bash qualification/clients/install-thunderbird.sh .client-tools BUSYSTACK_CLIENT_PYTHON="$PWD/.client-venv/bin/python" \ BUSYSTACK_THUNDERBIRD_BINARY="$PWD/.client-tools/thunderbird/thunderbird" \ ./mvnw -Dit.test=IndependentClientIT verify ``` -This launches Thunderbird's native CalDAV provider in its real desktop executable under headless Marionette control, in a new private temporary profile. The fixture adds its test CA to that profile's normal certificate database; it never disables certificate validation. It exercises recurring-event and undated-VTODO CRUD, task completion, Unicode, alarms, unknown properties, refresh and deletion. It does not qualify the graphical account wizard, visual rendering, or a person using the interface. Without the binary setting, desktop qualification is explicitly recorded as unexecuted. +This launches Thunderbird's native CalDAV provider in its real desktop executable under headless Marionette control, in a new private temporary profile. The fixture adds its test CA to that profile's normal certificate database; it never disables certificate validation. It exercises recurring-event and undated-VTODO CRUD, task completion, Unicode, alarms, unknown properties, refresh and deletion. It does not qualify the graphical account wizard, visual rendering, or a person using the interface. Without the binary setting, verification fails; it is not a passing skipped desktop profile. The same-object round-trip profile also requires Thunderbird to create a recurring event, a completed undated task, an all-day event and a floating-time event. The separate python-caldav/icalendar client reads and modifies those exact resources; Thunderbird refreshes and verifies the modifications, edits them again, and Python verifies the final data and unchanged resource URLs. Assertions retain recurrence count, alarm trigger, extension properties, task completion timestamp, exclusive all-day end, and floating values without invented UTC/TZID qualifiers. A passing JSON result includes `crossClient.sameResources: 4`. The recorded IndependentClientIT run passed this complete profile; subsequent application artifacts must run the process again before extending that claim. This profile uses isolated test-CA trust and the unmodified server defaults, with observed depth behavior recorded alongside configuration provenance. +IndependentClientIT also exports the live resources through PortabilityService after +Python's edits. Thunderbird's native file parser must consume all four UIDs across +the event/task downloads and retain the detached recurrence exception. The result +records `nativePortalExportItems: 4`. Compatible calendar contexts export one +VCALENDAR; distinct contexts retain a lossless stream. Thunderbird 159.0's file +parser cannot consume multiple VCALENDAR roots; this limitation does not affect +its native DAV provider. See [portability](../../docs/portability.md). + Results and native-client serialized fixtures are written under `target/qualification` and retained as CI artifacts. The [qualification index](../evidence/README.md) identifies concise version-specific @@ -39,3 +48,49 @@ 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, xauth and Docker, `qualification/passkeys/run.py --gnome` adds a real native +connection wizard to the existing packaged HTTPS browser profile. The existing +browser fixture supplies an authenticated private Xvfb display; no host desktop +or existing graphical session is accessed. 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, normal native password prompting, +and retrieval through the installed public ECalClient API: two UID series, three +event components, one recurrence exception, preserved extensions and owner write +permission. The corrective fixture also creates, edits and deletes a native EDS +event through the installed public ECalClient API and independently verifies each +state through trusted HTTPS; this does not qualify the graphical event editor. The password is entered through the GUI; it is never injected into the +EDS API. The connection URI comes directly from the portal's dedicated GNOME +field and includes the username without a password. It uses a disposable home, private +session/accessibility buses, keyring and namespace-only fixture CA trust. The +private buses use their documented AppArmor setting because policy queries cannot +operate against the namespace's read-only security filesystem; host policy is +unchanged. The pinned GNOME 50 Add Calendar row has no activation action and +reports local coordinates as screen coordinates; the fixture uses the visually +checked native dialog layout and standard X11 input within that private display. 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. +`--gnome-only` is an explicit targeted profile for native setup; the full browser, +security and restore profiles must still run separately. `BUSYSTACK_GNOME_DEBUG=1` +optionally runs only the isolated native client under the installed GDB, stopping +on GLib criticals and retaining function-only backtraces without arguments or +locals. This diagnoses upstream crashes without changing installed binaries. + +The private fixture initializes its own unlocked login keyring and default alias +through supported GNOME Keyring / Secret Service interfaces. GTK 4.22 can fail +when its root accessible child count becomes stale as a credential window closes; +the driver retains known application windows during that transition. It bounds all +visited nodes and prunes hidden trees. EDS's native password prompt exposes a text +role with the accessible label `Password:`; the driver uses that label. These are +fixture adaptations through public interfaces, with no upstream software patches. diff --git a/qualification/clients/gnome.py b/qualification/clients/gnome.py new file mode 100644 index 0000000..a98f744 --- /dev/null +++ b/qualification/clients/gnome.py @@ -0,0 +1,654 @@ +#!/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 base64 +import configparser +import ctypes +import json +import os +from pathlib import Path +import shutil +import secrets +import subprocess +import sys +import tempfile +import threading +import time +import ssl +import urllib.request +import xml.etree.ElementTree as ET +from urllib.parse import unquote, urlsplit + + +def read_native_source(uid, root): + """Use the installed public EDS C API; no additional GIR or test parser is needed.""" + pointer = ctypes.c_void_p + glib = ctypes.CDLL('libglib-2.0.so.0') + objects = ctypes.CDLL('libgobject-2.0.so.0') + gio = ctypes.CDLL('libgio-2.0.so.0') + sources = ctypes.CDLL('libedataserver-1.2.so.27') + calendars = ctypes.CDLL('libecal-2.0.so.3') + ical = ctypes.CDLL('libical-glib.so.3') + def api(library, name, returns, *arguments): + function = getattr(library, name) + function.restype, function.argtypes = returns, list(arguments) + return function + unref = api(objects, 'g_object_unref', None, pointer) + free = api(glib, 'g_free', None, pointer) + free_error = api(glib, 'g_error_free', None, pointer) + free_list = api(glib, 'g_slist_free_full', None, pointer, pointer) + cancellable = api(gio, 'g_cancellable_new', pointer)() + cancel = api(gio, 'g_cancellable_cancel', None, pointer) + deadline = threading.Timer(45, lambda: cancel(cancellable)) + deadline.daemon = True + deadline.start() + retained, head = [], pointer() + class Link(ctypes.Structure): + pass + Link._fields_ = [('data', pointer), ('next', ctypes.POINTER(Link))] + def checked(function, label, *arguments): + error = pointer() + value = function(*arguments, ctypes.byref(error)) + if error: + free_error(error) + raise RuntimeError('Native EDS ' + label + ' failed') + assert value, 'Native EDS ' + label + ' did not succeed' + return value + try: + registry = checked(api(sources, 'e_source_registry_new_sync', pointer, pointer, ctypes.POINTER(pointer)), + 'registry', cancellable) + retained.append(registry) + source = api(sources, 'e_source_registry_ref_source', pointer, pointer, ctypes.c_char_p)(registry, uid.encode()) + assert source, 'The wizard source must be present in the native registry' + retained.append(source) + client = checked(api(calendars, 'e_cal_client_connect_sync', pointer, pointer, ctypes.c_int, + ctypes.c_uint32, pointer, ctypes.POINTER(pointer)), + 'connection', source, 0, 20, cancellable) # E_CAL_CLIENT_SOURCE_TYPE_EVENTS + retained.append(client) + state = {'phase':'connecting', 'online':bool(api(sources,'e_client_is_online',ctypes.c_int,pointer)(client)), + 'readonly':bool(api(sources,'e_client_is_readonly',ctypes.c_int,pointer)(client))} + (root / 'backend-state.json').write_text(json.dumps(state,indent=2)) + checked(api(sources, 'e_client_refresh_sync', ctypes.c_int, pointer, pointer, ctypes.POINTER(pointer)), + 'refresh', client, cancellable) + get_objects = api(calendars, 'e_cal_client_get_object_list_sync', ctypes.c_int, pointer, ctypes.c_char_p, + ctypes.POINTER(pointer), pointer, ctypes.POINTER(pointer)) + serialize = api(ical, 'i_cal_component_as_ical_string', pointer, pointer) + get_uid = api(ical, 'i_cal_component_get_uid', ctypes.c_char_p, pointer) + while True: + checked(get_objects, 'object retrieval', client, b'#t', ctypes.byref(head), cancellable) + components, uids = [], [] + link = ctypes.cast(head, ctypes.POINTER(Link)) + while link: + assert len(components) < 20, 'Unexpected native fixture resource count' + component = link.contents.data + text = serialize(component) + assert text + try: + components.append(ctypes.string_at(text).decode('utf-8')) + uids.append(get_uid(component).decode('utf-8')) + finally: + free(text) + link = link.contents.next + if set(uids) == {'portal-series', 'portal-second'}: + state.update(phase='data-retrieved',cachedComponents=len(components), + readonly=bool(api(sources,'e_client_is_readonly',ctypes.c_int,pointer)(client))) + (root / 'backend-state.json').write_text(json.dumps(state,indent=2)) + break + if state.get('cachedComponents') != len(components): + state['cachedComponents'] = len(components) + (root / 'backend-state.json').write_text(json.dumps(state,indent=2)) + # Refresh initiates asynchronous backend work. Wait for actual cached data, + # including any native credential prompt, under the existing 45-second cancellation. + if head: + free_list(head, ctypes.cast(unref, pointer)) + head.value = None + time.sleep(.25) + content = '\n'.join(components) + assert content.count('BEGIN:VEVENT') == 3 and content.count('RECURRENCE-ID') == 1 + assert all(value in content for value in ('SUMMARY:Family time', 'SUMMARY:Moved occurrence', + 'SUMMARY:Second event', 'X-PRIVATE:preserve', 'DURATION:P1D', 'COUNT=3', 'FREQ=DAILY')) + assert all(value in content for value in ('DTSTART;TZID=Fixture/Fixed:20261102T090000', + 'RECURRENCE-ID;TZID=Fixture/Fixed:20261103T090000', 'DTSTART;TZID=Fixture/Fixed:20261103T110000')) + assert not api(sources, 'e_client_is_readonly', ctypes.c_int, pointer)(client), 'The owner calendar must remain writable in the native client' + fixture=json.loads((root/'client.json').read_text()) + event_uid='gnome-native-'+secrets.token_hex(8) + def representation(summary): + return ('BEGIN:VEVENT\r\nUID:'+event_uid+'\r\nDTSTAMP:20261101T000000Z\r\n' + 'DTSTART:20261102T130000Z\r\nDTEND:20261102T140000Z\r\nSUMMARY:'+summary+ + '\r\nX-NATIVE-QUALIFICATION:preserve\r\nEND:VEVENT\r\n').encode() + def component(content): + value=api(ical,'i_cal_component_new_from_string',pointer,ctypes.c_char_p)(content) + assert value,'The native iCalendar parser must construct the write fixture' + retained.append(value) + return value + # Public EDS 3.56.2 API: E_CAL_OPERATION_FLAG_NONE=0, E_CAL_OBJ_MOD_ALL=7. + # Each API write is independently observed at the real HTTPS server, not merely in EDS cache. + authorization='Basic '+base64.b64encode((fixture['username']+':'+fixture['credential']).encode()).decode() + tls=ssl.create_default_context(cafile=str(root/'ca.pem')) + def request(address,method='GET',body=None): + parsed=urlsplit(address) + expected=urlsplit(fixture['address']) + assert (parsed.scheme,parsed.hostname,parsed.port)==(expected.scheme,expected.hostname,expected.port) + req=urllib.request.Request(address,data=body,method=method,headers={'Authorization':authorization,'Content-Type':'application/xml; charset=utf-8','Depth':'1'}) + with urllib.request.urlopen(req,context=tls,timeout=10) as response: + data=response.read(1024*1024+1) + assert len(data)<=1024*1024 + return response.status,data + def remote(): + body=('' + '' + ''+event_uid+'').encode() + status,data=request(fixture['address'],'REPORT',body) + assert status==207 + hrefs=[element.text for element in ET.fromstring(data).findall('.//{DAV:}response/{DAV:}href')] + if not hrefs:return None + assert len(hrefs)==1 + from urllib.parse import urljoin + status,data=request(urljoin(fixture['address'],hrefs[0])) + assert status==200 + return data.decode() + def observe(summary): + until=time.monotonic()+10 + while time.monotonic() 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] in owned_pids: + 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: + if label == 'initial': + x.XRaiseWindow(display, wid) + x.XSetInputFocus(display, wid, 2, 0) + x.XFlush(display) + 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) + owned_windows = [] + freeze_windows = False + def nodes(showing=True): + nonlocal owned_windows + 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 [] + application = candidates[0] + # GTK 4.22's root GetChildAtIndex can return an unrealized/closed toplevel when + # an AT-SPI child count is stale. Keep the known windows across modal closure; + # ordinary widget contexts safely report defunct children through the same API. + if not freeze_windows: + application.clear_cache() + owned_windows = [application.get_child_at_index(i) + for i in range(min(application.get_child_count(), 16))] + result = [application] + visited = 0 + def visit(item, depth=0): + nonlocal visited + if item is None or depth > 40 or visited >= 2000: + return + visited += 1 + try: + if showing and not item.get_state_set().contains(Atspi.StateType.SHOWING): + return + 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 + for owned in owned_windows: + visit(owned) + 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).replace(fixture['credential'], '[redacted]')) + if label in ('initial', 'discovered', 'connected', 'failed-network-address', 'failed-native-sync'): + capture(label) + def wait(condition, label, seconds=35): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if process.poll() is not None: + raise RuntimeError('The native client exited during ' + label + ' with status ' + str(process.returncode)) + try: + found = condition() + except GLib.Error: + # Dialog closure can invalidate accessibility objects during a tree traversal. + found = None + 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] + if item.get_name() == 'Add Calendar' and rect.x == 0 and rect.y == 0: + # This pinned AdwButtonRow reports a local rectangle as SCREEN coordinates. + # Use the visually checked 50.0 centered dialog and its documented 15px bottom margin. + dialogs = [n for n in nodes() if n.get_role_name() == 'dialog' and n.get_name() == 'Calendar Settings'] + assert len(dialogs) == 1 and len(bounds) == 1 + assert 700 <= bounds[0].width <= 1400 and 550 <= bounds[0].height <= 1000 + x = bounds[0].x + bounds[0].width // 2 + y = bounds[0].y + bounds[0].height // 2 + 500 // 2 - 15 - rect.height // 2 + 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) + import ctypes + native_x = ctypes.CDLL('libX11.so.6') + native_x.XOpenDisplay.restype = ctypes.c_void_p + native_x.XFlush.argtypes = [ctypes.c_void_p] + native_x.XCloseDisplay.argtypes = [ctypes.c_void_p] + xtest = ctypes.CDLL('libXtst.so.6') + xtest.XTestFakeMotionEvent.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_ulong] + xtest.XTestFakeButtonEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_int, ctypes.c_ulong] + native_display = native_x.XOpenDisplay(None) + assert native_display + try: + assert xtest.XTestFakeMotionEvent(native_display, 0, x, y, 0) + assert xtest.XTestFakeButtonEvent(native_display, 1, 1, 10) + assert xtest.XTestFakeButtonEvent(native_display, 1, 0, 20) + native_x.XFlush(native_display) + finally: + native_x.XCloseDisplay(native_display) + 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':'XTEST click in authenticated private display within active owned application bounds', 'point':[x,y]}) + 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') + wait(lambda: named('Calendar Settings'), 'calendar-settings') + # The row is exposed to AT-SPI while the libadwaita modal is still + # animating into place. Its pinned SCREEN-coordinate workaround must + # run after that transition, not against the intermediate position. + time.sleep(.5) + pump() + click('Add Calendar') + wait(lambda: len(editable()) >= 2, 'network-address') + connection_uri = fixture['connectionAddress'] + discovery = urlsplit(connection_uri) + assert discovery.scheme == 'https' and discovery.password is None + assert unquote(discovery.username or '') == fixture['username'] + assert discovery.hostname == urlsplit(fixture['address']).hostname + assert discovery.port == urlsplit(fixture['address']).port + editable()[-1].get_editable_text_iface().set_text_contents(connection_uri) + wait(lambda: named('Credentials'), 'credential-dialog') + snapshot('credential-prompt') + fields = editable() + password_fields = [n for n in fields if 'password' in n.get_role_name()] + user_fields = [n for n in fields if n.get_name() == 'User'] + assert len(password_fields) == 1 and len(user_fields) == 1 + user_fields[0].get_editable_text_iface().set_text_contents(fixture['username']) + password_fields[0].get_editable_text_iface().set_text_contents(fixture['credential']) + freeze_windows = True + click('Connect') + wait(lambda: any(n.get_role_name() == 'button' and n.get_name() == 'Add Calendar' + and n.get_state_set().contains(Atspi.StateType.SENSITIVE) for n in nodes()), 'validated-source', 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] + (root / 'source-metadata.json').write_text(json.dumps({ + 'parent':config.get('Data Source','Parent',fallback=''), + 'user':config.get('Authentication','User',fallback=''), + 'method':config.get('Authentication','Method',fallback=''), + 'host':config.get('Authentication','Host',fallback=''), + 'path':config.get('WebDAV Backend','ResourcePath',fallback='')},indent=2)) + 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.getint('Authentication', 'Port') == (urlsplit(fixture['address']).port or 443) + assert config.get('WebDAV Backend', 'ResourcePath') == urlsplit(fixture['address']).path + colour = config.get('Calendar', 'Color', fallback='') + assert colour.upper() == '#126A5EFF', 'Native discovery must preserve the portal colour' + # Finish the real wizard, then authenticate the backend if it prompts separately. + def in_settings(item): + for _ in range(20): + if item is None: return False + if item.get_role_name() == 'dialog' and item.get_name() == 'Calendar Settings': return True + item = item.get_parent() + return False + close = [n for n in named('Close') if n.get_role_name() == 'button' and in_settings(n)] + assert len(close) == 1 + action(close[0]) + freeze_windows = False + native = {} + def retrieve(): + try: + native['result'] = read_native_source(source.stem, root) + except Exception as failure: + native['error'] = str(failure) + worker = threading.Thread(target=retrieve, daemon=True) + worker.start() + def synced(): + nonlocal freeze_windows + if 'error' in native: raise RuntimeError(native['error']) + if 'result' in native: return native['result'] + desktop = Atspi.get_desktop(0) + apps = [desktop.get_child_at_index(i) for i in range(min(desktop.get_child_count(),20))] + (root / 'backend-applications.json').write_text(json.dumps([ + {'name':app.get_name(),'pid':app.get_process_id()} for app in apps if app],indent=2)) + passwords = [n for n in editable() if 'password' in n.get_role_name() + or n.get_name().strip().rstrip(':').casefold() == 'password'] + if passwords: + assert len(passwords) == 1 + snapshot('backend-credential-prompt') + passwords[0].get_editable_text_iface().set_text_contents(fixture['credential']) + buttons = [n for n in nodes() if n.get_role_name() == 'button' and n.get_name() in ('Connect','Authenticate','OK') + and n.get_state_set().contains(Atspi.StateType.SENSITIVE)] + assert len(buttons) == 1 + freeze_windows = True + action(buttons[0]) + return None + try: + synchronization = wait(synced, 'native-event-synchronization', 60) + except Exception: + snapshot('failed-native-sync') + raise + 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', 'trusted HTTPS discovery URL with username', 'Credentials User/Password', 'Connect', 'native discovery', 'Add Calendar', 'native backend password prompt', 'native event synchronization', 'EDS create/modify/delete independently verified over HTTPS'], + 'nativeBackend': 'caldav', 'nativeColour': colour, 'synchronization':synchronization} + (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 shutil.which('bwrap') or not shutil.which('xauth'): + raise SystemExit('GNOME qualification requires bubblewrap, xauth and installed 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', 'X11'): + (root / name).mkdir(mode=0o700) + (root / 'X11').chmod(0o1777) + 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', GSK_RENDERER='cairo', + GTK_A11Y='atspi', NO_AT_BRIDGE='0', TZ='America/Vancouver', LANG='C.UTF-8', LC_ALL='C.UTF-8', + GNOME_KEYRING_CONTROL=str(root / 'run/keyring'), XDG_SESSION_TYPE='x11') + display = ':' + str(100 + secrets.randbelow(9000)) + (root / 'xauth').touch(mode=0o600) + subprocess.run(['xauth', '-f', str(root / 'xauth'), 'source', '-'], + input='add ' + display + ' . ' + secrets.token_hex(16) + '\n', text=True, check=True, capture_output=True) + env.update(DISPLAY=display, XAUTHORITY=str(root / 'xauth')) + display_name = 'busystack-gnome-display-' + secrets.token_hex(6) + display_log = (root / 'xvfb.log').open('w') + display_process = subprocess.Popen(['docker', 'run', '--rm', '--name', display_name, '--network', 'none', + '--user', str(os.getuid()) + ':' + str(os.getgid()), + '--volume', str(root / 'X11') + ':/tmp/.X11-unix:rw', '--volume', str(root / 'xauth') + ':/fixture/xauth:ro', + '--entrypoint', '/usr/bin/Xvfb', fixture['displayImage'], display, '-screen', '0', '1366x900x24', + '-nolisten', 'tcp', '-auth', '/fixture/xauth', '-noreset'], stdout=display_log, stderr=subprocess.STDOUT) + command = ['bwrap', '--ro-bind', '/', '/', '--tmpfs', '/tmp', '--bind', str(root), str(root), + '--ro-bind', str(root / 'X11'), '/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)] + try: + deadline = time.monotonic() + 30 + while not (root / 'X11' / ('X' + display[1:])).exists(): + if display_process.poll() is not None or time.monotonic() > deadline: + raise RuntimeError('The private authenticated Xvfb display did not start') + time.sleep(.1) + try: + result = subprocess.run(command, env=env, capture_output=True, text=True, timeout=240) + except subprocess.TimeoutExpired as failure: + def decoded(value): + return value.decode(errors='replace') if isinstance(value, bytes) else (value or '') + result = subprocess.CompletedProcess(command, 124, decoded(failure.stdout), decoded(failure.stderr)) + finally: + subprocess.run(['docker', 'rm', '--force', display_name], capture_output=True, timeout=15) + try: + display_process.wait(timeout=15) + except subprocess.TimeoutExpired: + display_process.terminate() + try: + display_process.wait(timeout=5) + except subprocess.TimeoutExpired: + display_process.kill() + display_process.wait(timeout=5) + display_log.close() + args.output.mkdir(parents=True, exist_ok=True) + shutil.copyfile(root / 'xvfb.log', args.output / 'gnome-display.log') + 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) + application_log = (root / 'application.log').read_text(errors='replace') if (root / 'application.log').exists() else '' + for secret in (fixture['credential'], base64.b64encode((fixture['username'] + ':' + fixture['credential']).encode()).decode()): + application_log = application_log.replace(secret, '[redacted]') + (args.output / 'gnome-application.log').write_text(application_log) + 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/clients/journal-admission.py b/qualification/clients/journal-admission.py new file mode 100644 index 0000000..556a641 --- /dev/null +++ b/qualification/clients/journal-admission.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python3 +"""Independent storage-admission test against a dedicated CalDAV fixture account.""" + +import argparse +import base64 +from collections import Counter +import hashlib +import http.client +import json +from pathlib import Path +import re +import ssl +from urllib.parse import urljoin, urlsplit +from uuid import uuid4 +from xml.etree import ElementTree as ET + +D = '{DAV:}' +C = '{urn:ietf:params:xml:ns:caldav}' +FIXTURE = Path(__file__).resolve().parents[1] / 'fixtures/vjournal/admission-v1.json' +XML = {'Content-Type': 'application/xml; charset=utf-8'} +ICAL = {'Content-Type': 'text/calendar; charset=utf-8'} + + +class Dav: + def __init__(self, endpoint, username, password, ca_file): + self.endpoint = endpoint + origin = urlsplit(endpoint) + if origin.scheme != 'https' and not ( + origin.scheme == 'http' and origin.hostname == '127.0.0.1' + ): + raise ValueError('Fixture endpoint requires HTTPS or IPv4 loopback HTTP') + self.origin = origin.scheme, origin.netloc + self.authorization = 'Basic ' + base64.b64encode( + f'{username}:{password}'.encode()).decode('ascii') + self.context = ssl.create_default_context(cafile=ca_file) + + def request(self, method, reference, body=None, headers=None): + uri = urlsplit(urljoin(self.endpoint, reference)) + if (uri.scheme, uri.netloc) != self.origin or uri.query or uri.fragment: + raise ValueError('Unexpected DAV fixture href') + if uri.scheme == 'https': + client = http.client.HTTPSConnection(uri.netloc, timeout=20, context=self.context) + else: + client = http.client.HTTPConnection(uri.netloc, timeout=20) + try: + client.request(method, uri.path, body, { + 'Authorization': self.authorization, **(headers or {}) + }) + response = client.getresponse() + return response.status, response.headers, response.read() + finally: + client.close() + + def properties(self, href, fields, depth=0): + body = ('' + f'{fields}') + status, _, content = self.request('PROPFIND', href, body, {**XML, 'Depth': str(depth)}) + if status != 207: + raise RuntimeError(f'Fixture PROPFIND failed with HTTP {status}') + result = {} + for response in ET.fromstring(content).findall(f'{D}response'): + properties = {} + for propstat in response.findall(f'{D}propstat'): + if (propstat.findtext(f'{D}status') or '').split()[1:2] == ['200']: + properties.update({child.tag: child for child in propstat.find(f'{D}prop')}) + result[response.findtext(f'{D}href')] = properties + return result + + +def representation(uid, case, summary=None): + lines = ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//BusyStack//Journal QA//EN', + *case.get('calendar', []), 'BEGIN:VJOURNAL', f'UID:{uid}', + 'DTSTAMP:20261125T080000Z'] + if summary: + lines.append(f'SUMMARY:{summary}') + lines += [*case['journal'], 'END:VJOURNAL', 'END:VCALENDAR'] + folded = ['\r\n '.join([line[:75], *[line[i:i + 74] for i in range(75, len(line), 74)]]) + for line in lines] + return ('\r\n'.join(folded) + '\r\n').encode('ascii') + + +def semantic_lines(body): + # The admission corpus uses ASCII values without ambiguous escaping. Retain each + # complete property, parameter list and component path while ignoring folding/order. + path = [] + properties = Counter() + unfolded = re.sub(rb'\r?\n[ \t]', b'', body) + for line in unfolded.splitlines(): + if line.startswith(b'BEGIN:'): + path.append(line[6:]) + properties[tuple(path), b'BEGIN'] += 1 + elif line.startswith(b'END:'): + if not path or path.pop() != line[4:]: + raise ValueError('Malformed readback component structure') + else: + properties[tuple(path), line] += 1 + if path: + raise ValueError('Unclosed readback component') + return properties + + +def error_names(body): + try: + root = ET.fromstring(body) + except ET.ParseError: + return [] + return [child.tag for child in root] if root.tag == D + 'error' else [] + + +def probe(dav, collection, case, conditional): + case_id = case['id'] + suffix = 'update' if conditional else 'create' + href = collection + f'{case_id}-{suffix}.ics' + uid = f'{case_id}-{suffix}-fixture' + before = None + if conditional: + status, _, _ = dav.request('PUT', href, representation(uid, {'journal': []}), + {**ICAL, 'If-None-Match': '*'}) + if status != 201: + raise RuntimeError(f'Conditional PUT setup failed with HTTP {status}') + before = dav.request('GET', href) + if before[0] != 200 or not before[1].get('ETag') or before[1]['ETag'].startswith('W/'): + raise RuntimeError('Fixture did not return a strong baseline ETag') + expected = representation(uid, case, 'Updated fixture' if conditional else None) + condition = {'If-Match': before[1]['ETag']} if conditional else {'If-None-Match': '*'} + fields = '' + inventory_before = dav.properties(collection, fields, 1) + status, _, response = dav.request('PUT', href, expected, {**ICAL, **condition}) + read_status, read_headers, read_body = dav.request('GET', href) + if status in (200, 201, 204): + issue = None if ( + read_status == 200 and read_headers.get('ETag') + and semantic_lines(read_body) == semantic_lines(expected) + ) else 'authoritative readback mismatch' + else: + inventory_after = dav.properties(collection, fields, 1) + snapshot = lambda inventory: { + name: {key: prop.text for key, prop in props.items()} + for name, props in inventory.items() + } + same_inventory = snapshot(inventory_before) == snapshot(inventory_after) + same_resource = ( + read_status == 200 and read_body == before[2] + and read_headers.get('ETag') == before[1]['ETag'] + ) if before else read_status == 404 + issue = ('admission rejected; original state unchanged' if same_inventory and same_resource + else 'admission rejected; original state changed') + print(json.dumps({'case': case_id, 'operation': suffix, 'put': status, 'get': read_status, + 'dav_errors': error_names(response), + 'response_sha256': hashlib.sha256(response).hexdigest(), + 'issue': issue}), flush=True) + return issue is None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('endpoint', help='CalDAV service URL of a disposable fixture account') + parser.add_argument('username') + parser.add_argument('password_file', type=Path) + parser.add_argument('--ca-file', help='PEM trust anchor for the fixture endpoint') + args = parser.parse_args() + dav = Dav(args.endpoint, args.username, args.password_file.read_text().strip(), args.ca_file) + principal, = dav.properties(args.endpoint, '').values() + principal_href = principal[D + 'current-user-principal'].findtext(D + 'href') + home, = dav.properties(principal_href, '').values() + home_href = home[C + 'calendar-home-set'].findtext(D + 'href') + collection = home_href.rstrip('/') + '/journal-admission-' + uuid4().hex + '/' + body = ('' + 'Journal admission fixture' + '' + '') + status, _, _ = dav.request('MKCALENDAR', collection, body, XML) + if status != 201: + raise RuntimeError(f'Fixture MKCALENDAR failed with HTTP {status}') + try: + caps, = dav.properties(collection, '' + '').values() + components = [tag.get('name') for tag in caps[C + 'supported-calendar-component-set']] + if components != ['VJOURNAL'] or D + 'current-user-privilege-set' not in caps: + raise RuntimeError('Fixture did not discover a dedicated journal collection') + status, _, _ = dav.request('PUT', collection + 'target.ics', + representation('target-fixture', {'journal': []}), + {**ICAL, 'If-None-Match': '*'}) + if status != 201: + raise RuntimeError(f'UID reference target creation failed with HTTP {status}') + fixture_bytes = FIXTURE.read_bytes() + fixtures = json.loads(fixture_bytes) + print(json.dumps({'fixture_version': fixtures['version'], + 'fixture_sha256': hashlib.sha256(fixture_bytes).hexdigest()}), flush=True) + results = [probe(dav, collection, case, conditional) + for case in fixtures['cases'] for conditional in (False, True)] + print(json.dumps({'executed': len(results), 'passed': sum(results), + 'failed': len(results) - sum(results)}), flush=True) + return 0 if all(results) else 1 + finally: + status, _, _ = dav.request('DELETE', collection) + if status not in (200, 204): + raise RuntimeError(f'Fixture cleanup failed with HTTP {status}') + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/qualification/clients/thunderbird.py b/qualification/clients/thunderbird.py index c57f4ed..e3d9e01 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,28 @@ 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) + imported = None + if os.environ.get("BUSYSTACK_EXPORT_EXCHANGE"): + exchange = Path(os.environ["BUSYSTACK_EXPORT_EXCHANGE"]) + (exchange / 'export-ready').touch() + deadline = time.monotonic() + 60 + while not (exchange / 'export-complete').exists(): + assert time.monotonic() < deadline, 'Actual portal export did not become ready' + time.sleep(.1) + imported = [] + for kind in ('events', 'tasks'): + document = (exchange / (kind + '.ics')).read_text() + assert document.count('BEGIN:VCALENDAR') == 1 + items = 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', + exceptions:item.recurrenceInfo?.getExceptionIds().length??0})); + """, script_args=[document], new_sandbox=False) + imported.extend(items) + assert {item["id"] for item in imported} == {"thunderbird-event", "thunderbird-task", "thunderbird-all-day", "thunderbird-floating"}, imported + assert sum(item["type"] == "VEVENT" for item in imported) == 3 + assert next(item for item in imported if item['id']=='thunderbird-event')['exceptions'] == 1 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 +361,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"], "nativePortalExportItems": len(imported) if imported is not None else 'not executed in this profile', "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/evidence/README.md b/qualification/evidence/README.md index bd17001..14c6bde 100644 --- a/qualification/evidence/README.md +++ b/qualification/evidence/README.md @@ -4,6 +4,9 @@ Maintained tests and protocol fixtures live in `src/test`, `qualification/` and `investigation/`. Generated logs, screenshots and intermediate execution records belong in CI artifacts or the external project audit archive. +- [This release's client qualification](releases/@VERSION@/verification.json) + identifies the exact executable and runtime inputs for the Thunderbird and GNOME + editor profiles. - [v0.1.0 qualification](releases/0.1.0/README.md) records the qualified executable, runtime inputs, real-client scope, results and successful CI references. - [v0.0.1 summary](releases/0.0.1/summary.json) preserves historical identity and @@ -12,6 +15,15 @@ belong in CI artifacts or the external project audit archive. successful verification run/attempt, JAR checksum, registry manifest digest and deployment archive checksum. Local Docker IDs are not registry digests. +## Corrective engineering receipts + +Local v0.2.0 corrective receipts live under `.qualification-runs/`, with a final +`corrective-final-report.json` identifying the exact corrective commit, preserved +qualification-file hashes, runtime artifact hashes, commands, counts and remaining +gates. Generated evidence is not a release manifest. Consult +[portability qualification](../portability/README.md) for the additional storage +and HTTP regressions. Historical passing records do not qualify changed source. + ## Historical records The detailed pre-cleanup records remain unchanged in diff --git a/qualification/evidence/releases/0.2.0/group-plan/after.json b/qualification/evidence/releases/0.2.0/group-plan/after.json new file mode 100644 index 0000000..c9708ab --- /dev/null +++ b/qualification/evidence/releases/0.2.0/group-plan/after.json @@ -0,0 +1,392 @@ +[ + { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "dav_bindings", + "Alias": "dav_bindings", + "Startup Cost": 16.11, + "Total Cost": 17.29, + "Plan Rows": 0, + "Plan Width": 0, + "Disabled": false, + "Plans": [ + { + "Node Type": "Nested Loop", + "Parent Relationship": "InitPlan", + "Subplan Name": "CTE affected", + "Parallel Aware": false, + "Async Capable": false, + "Join Type": "Inner", + "Startup Cost": 0.0, + "Total Cost": 1.02, + "Plan Rows": 1, + "Plan Width": 32, + "Disabled": false, + "Inner Unique": true, + "Join Filter": "(c_1.id = grant_row.collection_id)", + "Plans": [ + { + "Node Type": "Seq Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "collections", + "Alias": "c_1", + "Startup Cost": 0.0, + "Total Cost": 1.01, + "Plan Rows": 1, + "Plan Width": 32, + "Disabled": false + }, + { + "Node Type": "Seq Scan", + "Parent Relationship": "Inner", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "collection_group_members", + "Alias": "grant_row", + "Startup Cost": 0.0, + "Total Cost": 0.0, + "Plan Rows": 1, + "Plan Width": 16, + "Disabled": false, + "Filter": "(group_id = $1)" + } + ] + }, + { + "Node Type": "Unique", + "Parent Relationship": "InitPlan", + "Subplan Name": "CTE effective", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 12.84, + "Total Cost": 12.88, + "Plan Rows": 5, + "Plan Width": 32, + "Disabled": false, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 12.84, + "Total Cost": 12.85, + "Plan Rows": 5, + "Plan Width": 32, + "Disabled": false, + "Sort Key": [ + "direct.collection_id", + "direct.account_id" + ], + "Plans": [ + { + "Node Type": "Append", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4.18, + "Total Cost": 12.78, + "Plan Rows": 5, + "Plan Width": 32, + "Disabled": false, + "Subplans Removed": 0, + "Plans": [ + { + "Node Type": "Nested Loop", + "Parent Relationship": "Member", + "Parallel Aware": false, + "Async Capable": false, + "Join Type": "Inner", + "Startup Cost": 4.18, + "Total Cost": 12.71, + "Plan Rows": 4, + "Plan Width": 32, + "Disabled": false, + "Inner Unique": false, + "Plans": [ + { + "Node Type": "CTE Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "CTE Name": "affected", + "Alias": "a", + "Startup Cost": 0.0, + "Total Cost": 0.02, + "Plan Rows": 1, + "Plan Width": 32, + "Disabled": false + }, + { + "Node Type": "Bitmap Heap Scan", + "Parent Relationship": "Inner", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "collection_members", + "Alias": "direct", + "Startup Cost": 4.18, + "Total Cost": 12.65, + "Plan Rows": 4, + "Plan Width": 32, + "Disabled": false, + "Recheck Cond": "(collection_id = a.id)", + "Filter": "(account_id <> a.owner_id)", + "Plans": [ + { + "Node Type": "Bitmap Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Index Name": "collection_members_pkey", + "Startup Cost": 0.0, + "Total Cost": 4.18, + "Plan Rows": 4, + "Plan Width": 0, + "Disabled": false, + "Index Cond": "(collection_id = a.id)" + } + ] + } + ] + }, + { + "Node Type": "Nested Loop", + "Parent Relationship": "Member", + "Parallel Aware": false, + "Async Capable": false, + "Join Type": "Inner", + "Startup Cost": 0.0, + "Total Cost": 0.05, + "Plan Rows": 1, + "Plan Width": 32, + "Disabled": false, + "Inner Unique": false, + "Join Filter": "((member.account_id <> a_1.owner_id) AND (granted.group_id = member.group_id))", + "Plans": [ + { + "Node Type": "Nested Loop", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Join Type": "Inner", + "Startup Cost": 0.0, + "Total Cost": 0.03, + "Plan Rows": 1, + "Plan Width": 48, + "Disabled": false, + "Inner Unique": false, + "Join Filter": "(granted.collection_id = a_1.id)", + "Plans": [ + { + "Node Type": "CTE Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "CTE Name": "affected", + "Alias": "a_1", + "Startup Cost": 0.0, + "Total Cost": 0.02, + "Plan Rows": 1, + "Plan Width": 32, + "Disabled": false + }, + { + "Node Type": "Seq Scan", + "Parent Relationship": "Inner", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "collection_group_members", + "Alias": "granted", + "Startup Cost": 0.0, + "Total Cost": 0.0, + "Plan Rows": 1, + "Plan Width": 32, + "Disabled": false + } + ] + }, + { + "Node Type": "Seq Scan", + "Parent Relationship": "Inner", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "sharing_group_members", + "Alias": "member", + "Startup Cost": 0.0, + "Total Cost": 0.0, + "Plan Rows": 1, + "Plan Width": 32, + "Disabled": false + } + ] + } + ] + } + ] + } + ] + }, + { + "Node Type": "SetOp", + "Strategy": "Hashed", + "Parent Relationship": "InitPlan", + "Subplan Name": "CTE missing", + "Parallel Aware": false, + "Async Capable": false, + "Command": "Except", + "Startup Cost": 1.17, + "Total Cost": 1.19, + "Plan Rows": 5, + "Plan Width": 32, + "Disabled": false, + "Plans": [ + { + "Node Type": "CTE Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "CTE Name": "effective", + "Alias": "e", + "Startup Cost": 0.0, + "Total Cost": 0.1, + "Plan Rows": 5, + "Plan Width": 32, + "Disabled": false + }, + { + "Node Type": "Nested Loop", + "Parent Relationship": "Inner", + "Parallel Aware": false, + "Async Capable": false, + "Join Type": "Inner", + "Startup Cost": 0.0, + "Total Cost": 1.04, + "Plan Rows": 1, + "Plan Width": 32, + "Disabled": false, + "Inner Unique": false, + "Join Filter": "(a_2.id = b.collection_id)", + "Plans": [ + { + "Node Type": "Seq Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "dav_bindings", + "Alias": "b", + "Startup Cost": 0.0, + "Total Cost": 1.01, + "Plan Rows": 1, + "Plan Width": 32, + "Disabled": false + }, + { + "Node Type": "CTE Scan", + "Parent Relationship": "Inner", + "Parallel Aware": false, + "Async Capable": false, + "CTE Name": "affected", + "Alias": "a_2", + "Startup Cost": 0.0, + "Total Cost": 0.02, + "Plan Rows": 1, + "Plan Width": 16, + "Disabled": false + } + ] + } + ] + }, + { + "Node Type": "Nested Loop", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Join Type": "Left", + "Startup Cost": 1.02, + "Total Cost": 2.2, + "Plan Rows": 1, + "Plan Width": 69, + "Disabled": false, + "Inner Unique": true, + "Join Filter": "((occupied.home_id = m.account_id) AND (occupied.path = (c.id)::text))", + "Plans": [ + { + "Node Type": "Hash Join", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Join Type": "Inner", + "Startup Cost": 1.02, + "Total Cost": 1.15, + "Plan Rows": 1, + "Plan Width": 37, + "Disabled": false, + "Inner Unique": true, + "Hash Cond": "(m.collection_id = c.id)", + "Plans": [ + { + "Node Type": "CTE Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "CTE Name": "missing", + "Alias": "m", + "Startup Cost": 0.0, + "Total Cost": 0.1, + "Plan Rows": 5, + "Plan Width": 32, + "Disabled": false + }, + { + "Node Type": "Hash", + "Parent Relationship": "Inner", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1.01, + "Total Cost": 1.01, + "Plan Rows": 1, + "Plan Width": 21, + "Disabled": false, + "Plans": [ + { + "Node Type": "Seq Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "collections", + "Alias": "c", + "Startup Cost": 0.0, + "Total Cost": 1.01, + "Plan Rows": 1, + "Plan Width": 21, + "Disabled": false + } + ] + } + ] + }, + { + "Node Type": "Seq Scan", + "Parent Relationship": "Inner", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "dav_bindings", + "Alias": "occupied", + "Startup Cost": 0.0, + "Total Cost": 1.01, + "Plan Rows": 1, + "Plan Width": 53, + "Disabled": false + } + ] + } + ] + } + } +] \ No newline at end of file diff --git a/qualification/evidence/releases/0.2.0/group-plan/before.json b/qualification/evidence/releases/0.2.0/group-plan/before.json new file mode 100644 index 0000000..c9708ab --- /dev/null +++ b/qualification/evidence/releases/0.2.0/group-plan/before.json @@ -0,0 +1,392 @@ +[ + { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "dav_bindings", + "Alias": "dav_bindings", + "Startup Cost": 16.11, + "Total Cost": 17.29, + "Plan Rows": 0, + "Plan Width": 0, + "Disabled": false, + "Plans": [ + { + "Node Type": "Nested Loop", + "Parent Relationship": "InitPlan", + "Subplan Name": "CTE affected", + "Parallel Aware": false, + "Async Capable": false, + "Join Type": "Inner", + "Startup Cost": 0.0, + "Total Cost": 1.02, + "Plan Rows": 1, + "Plan Width": 32, + "Disabled": false, + "Inner Unique": true, + "Join Filter": "(c_1.id = grant_row.collection_id)", + "Plans": [ + { + "Node Type": "Seq Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "collections", + "Alias": "c_1", + "Startup Cost": 0.0, + "Total Cost": 1.01, + "Plan Rows": 1, + "Plan Width": 32, + "Disabled": false + }, + { + "Node Type": "Seq Scan", + "Parent Relationship": "Inner", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "collection_group_members", + "Alias": "grant_row", + "Startup Cost": 0.0, + "Total Cost": 0.0, + "Plan Rows": 1, + "Plan Width": 16, + "Disabled": false, + "Filter": "(group_id = $1)" + } + ] + }, + { + "Node Type": "Unique", + "Parent Relationship": "InitPlan", + "Subplan Name": "CTE effective", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 12.84, + "Total Cost": 12.88, + "Plan Rows": 5, + "Plan Width": 32, + "Disabled": false, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 12.84, + "Total Cost": 12.85, + "Plan Rows": 5, + "Plan Width": 32, + "Disabled": false, + "Sort Key": [ + "direct.collection_id", + "direct.account_id" + ], + "Plans": [ + { + "Node Type": "Append", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4.18, + "Total Cost": 12.78, + "Plan Rows": 5, + "Plan Width": 32, + "Disabled": false, + "Subplans Removed": 0, + "Plans": [ + { + "Node Type": "Nested Loop", + "Parent Relationship": "Member", + "Parallel Aware": false, + "Async Capable": false, + "Join Type": "Inner", + "Startup Cost": 4.18, + "Total Cost": 12.71, + "Plan Rows": 4, + "Plan Width": 32, + "Disabled": false, + "Inner Unique": false, + "Plans": [ + { + "Node Type": "CTE Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "CTE Name": "affected", + "Alias": "a", + "Startup Cost": 0.0, + "Total Cost": 0.02, + "Plan Rows": 1, + "Plan Width": 32, + "Disabled": false + }, + { + "Node Type": "Bitmap Heap Scan", + "Parent Relationship": "Inner", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "collection_members", + "Alias": "direct", + "Startup Cost": 4.18, + "Total Cost": 12.65, + "Plan Rows": 4, + "Plan Width": 32, + "Disabled": false, + "Recheck Cond": "(collection_id = a.id)", + "Filter": "(account_id <> a.owner_id)", + "Plans": [ + { + "Node Type": "Bitmap Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Index Name": "collection_members_pkey", + "Startup Cost": 0.0, + "Total Cost": 4.18, + "Plan Rows": 4, + "Plan Width": 0, + "Disabled": false, + "Index Cond": "(collection_id = a.id)" + } + ] + } + ] + }, + { + "Node Type": "Nested Loop", + "Parent Relationship": "Member", + "Parallel Aware": false, + "Async Capable": false, + "Join Type": "Inner", + "Startup Cost": 0.0, + "Total Cost": 0.05, + "Plan Rows": 1, + "Plan Width": 32, + "Disabled": false, + "Inner Unique": false, + "Join Filter": "((member.account_id <> a_1.owner_id) AND (granted.group_id = member.group_id))", + "Plans": [ + { + "Node Type": "Nested Loop", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Join Type": "Inner", + "Startup Cost": 0.0, + "Total Cost": 0.03, + "Plan Rows": 1, + "Plan Width": 48, + "Disabled": false, + "Inner Unique": false, + "Join Filter": "(granted.collection_id = a_1.id)", + "Plans": [ + { + "Node Type": "CTE Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "CTE Name": "affected", + "Alias": "a_1", + "Startup Cost": 0.0, + "Total Cost": 0.02, + "Plan Rows": 1, + "Plan Width": 32, + "Disabled": false + }, + { + "Node Type": "Seq Scan", + "Parent Relationship": "Inner", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "collection_group_members", + "Alias": "granted", + "Startup Cost": 0.0, + "Total Cost": 0.0, + "Plan Rows": 1, + "Plan Width": 32, + "Disabled": false + } + ] + }, + { + "Node Type": "Seq Scan", + "Parent Relationship": "Inner", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "sharing_group_members", + "Alias": "member", + "Startup Cost": 0.0, + "Total Cost": 0.0, + "Plan Rows": 1, + "Plan Width": 32, + "Disabled": false + } + ] + } + ] + } + ] + } + ] + }, + { + "Node Type": "SetOp", + "Strategy": "Hashed", + "Parent Relationship": "InitPlan", + "Subplan Name": "CTE missing", + "Parallel Aware": false, + "Async Capable": false, + "Command": "Except", + "Startup Cost": 1.17, + "Total Cost": 1.19, + "Plan Rows": 5, + "Plan Width": 32, + "Disabled": false, + "Plans": [ + { + "Node Type": "CTE Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "CTE Name": "effective", + "Alias": "e", + "Startup Cost": 0.0, + "Total Cost": 0.1, + "Plan Rows": 5, + "Plan Width": 32, + "Disabled": false + }, + { + "Node Type": "Nested Loop", + "Parent Relationship": "Inner", + "Parallel Aware": false, + "Async Capable": false, + "Join Type": "Inner", + "Startup Cost": 0.0, + "Total Cost": 1.04, + "Plan Rows": 1, + "Plan Width": 32, + "Disabled": false, + "Inner Unique": false, + "Join Filter": "(a_2.id = b.collection_id)", + "Plans": [ + { + "Node Type": "Seq Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "dav_bindings", + "Alias": "b", + "Startup Cost": 0.0, + "Total Cost": 1.01, + "Plan Rows": 1, + "Plan Width": 32, + "Disabled": false + }, + { + "Node Type": "CTE Scan", + "Parent Relationship": "Inner", + "Parallel Aware": false, + "Async Capable": false, + "CTE Name": "affected", + "Alias": "a_2", + "Startup Cost": 0.0, + "Total Cost": 0.02, + "Plan Rows": 1, + "Plan Width": 16, + "Disabled": false + } + ] + } + ] + }, + { + "Node Type": "Nested Loop", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Join Type": "Left", + "Startup Cost": 1.02, + "Total Cost": 2.2, + "Plan Rows": 1, + "Plan Width": 69, + "Disabled": false, + "Inner Unique": true, + "Join Filter": "((occupied.home_id = m.account_id) AND (occupied.path = (c.id)::text))", + "Plans": [ + { + "Node Type": "Hash Join", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Join Type": "Inner", + "Startup Cost": 1.02, + "Total Cost": 1.15, + "Plan Rows": 1, + "Plan Width": 37, + "Disabled": false, + "Inner Unique": true, + "Hash Cond": "(m.collection_id = c.id)", + "Plans": [ + { + "Node Type": "CTE Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "CTE Name": "missing", + "Alias": "m", + "Startup Cost": 0.0, + "Total Cost": 0.1, + "Plan Rows": 5, + "Plan Width": 32, + "Disabled": false + }, + { + "Node Type": "Hash", + "Parent Relationship": "Inner", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1.01, + "Total Cost": 1.01, + "Plan Rows": 1, + "Plan Width": 21, + "Disabled": false, + "Plans": [ + { + "Node Type": "Seq Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "collections", + "Alias": "c", + "Startup Cost": 0.0, + "Total Cost": 1.01, + "Plan Rows": 1, + "Plan Width": 21, + "Disabled": false + } + ] + } + ] + }, + { + "Node Type": "Seq Scan", + "Parent Relationship": "Inner", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "dav_bindings", + "Alias": "occupied", + "Startup Cost": 0.0, + "Total Cost": 1.01, + "Plan Rows": 1, + "Plan Width": 53, + "Disabled": false + } + ] + } + ] + } + } +] \ No newline at end of file diff --git a/qualification/evidence/releases/0.2.0/group-plan/result.json b/qualification/evidence/releases/0.2.0/group-plan/result.json new file mode 100644 index 0000000..adff19b --- /dev/null +++ b/qualification/evidence/releases/0.2.0/group-plan/result.json @@ -0,0 +1,36 @@ +{ + "qualificationKind": "local-unpublished", + "baselineRuntimeCommit": "01760f7baa03275267b8aea9a360ddce2669fba9", + "dataset": { + "additionalCollections": 10001, + "membershipBindingsAfterCorrection": 10001 + }, + "baseline": { + "cachedGenericPlanEstimatedRows": 1, + "diagnosticDeadlineSeconds": 10, + "sqlState": "57014", + "coldPlan": "hash joins; completed within ten seconds" + }, + "corrected": { + "functionSetting": "enable_nestloop=off", + "scope": "only dav_reconcile_group_memberships(uuid)", + "callerSettingRestoredByPostgreSQL": true, + "existingServiceTransactionDeadlineSeconds": 30, + "milliseconds": 2657.378 + }, + "migration": { + "file": "src/main/resources/db/migration/V16__bounded_group_join_plans.sql", + "sha256": "ceced2d692a76740beca0b3388850cd83c5b697d8ee68e8d42321c2f1bf5e28c" + }, + "fullGroupSuiteCapacityMilliseconds": { + "add": 2001, + "remove": 910, + "readd": 2093, + "delete": 967 + }, + "notes": [ + "SQL-only reproduction is plan evidence, not authentication or authorization evidence.", + "The existing full group integration suite separately verifies permissions, rollback and membership effects.", + "Before and after plans show the cached generic INSERT retaining its original estimates across bulk growth; the corrected execution follows a function-local planning change." + ] +} diff --git a/qualification/evidence/releases/0.2.0/p0-results.json b/qualification/evidence/releases/0.2.0/p0-results.json new file mode 100644 index 0000000..62dcf26 --- /dev/null +++ b/qualification/evidence/releases/0.2.0/p0-results.json @@ -0,0 +1,1369 @@ +{ + "branch": "release/v0.2.0", + "deliveryArchive": { + "allOtherDeploymentFilesByteIdentical": true, + "freshBrowser": { + "assertions": 49, + "base": "https://localhost:56239", + "chromium": "149.0.7827.55", + "manualFirefoxBitwarden": "pending", + "playwright": "1.61.1", + "screenshots": 20, + "status": "passed" + }, + "freshClients": { + "clients": [ + { + "client": "python-caldav", + "icalendar": "7.3.0", + "operations": [ + "principal and home discovery", + "calendar and VTODO collection creation", + "Unicode event CRUD", + "unknown-property round trip", + "event time-range query", + "server recurrence expansion", + "same-resource detached exception CRUD and RECURRENCE-ID preservation", + "EXDATE exclusion in server expansion", + "undated task CRUD and completion", + "initial and incremental synchronization", + "resource and collection deletion" + ], + "status": "passed", + "syncConfiguration": { + "allowSyncDepthOne": true, + "configurationInput": "setting omitted; packaged application default", + "depthOneWithOtherSyncLevelStatus": 400, + "observedDepthStatus": { + "0": 207, + "1": 207, + "missing": 207 + }, + "verifiedBy": "actual authenticated REPORTs to this collection" + }, + "syncFallbackDisabled": true, + "version": "3.6.0" + }, + { + "client": "Thunderbird", + "crossClient": { + "excludedOccurrences": 1, + "icalendar": "7.3.0", + "nativeDetachedExceptions": 1, + "nativeRecurrenceInstances": 3, + "python-caldav": "3.6.0", + "sameResources": 4 + }, + "driver": "3.7.1", + "mode": "isolated headless native desktop CalDAV provider", + "nativeAppleCalendarColor": "#126A5E", + "nativePortalExportItems": "not executed in this profile", + "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" + ], + "status": "passed", + "syncConfiguration": { + "allowSyncDepthOne": true, + "configurationInput": "setting omitted; packaged application default", + "depthOneWithOtherSyncLevelStatus": 400, + "observedDepthStatus": { + "0": 207, + "1": 207, + "missing": 207 + }, + "verifiedBy": "actual authenticated REPORTs to this collection" + }, + "version": "159.0" + } + ], + "credentialOrigin": "application password issued after protected browser initialization and real virtual-authenticator MFA", + "image": "busystack-caldav:p0-v16" + }, + "freshInstallationCommand": [ + "python3", + "qualification/p0/run.py", + "--application-image", + "busystack-caldav:p0-v16", + "--browser-image", + "busystack-passkey-browser:p0", + "--deployment-directory", + ".qualification-runs/p0/package-v16-delivery/caldav-server-0.2.0-deploy", + "--proxy", + "--administrator-activity", + "personal", + "--clients", + "--thunderbird-binary", + "/home/albert/Projects/busystack/caldav-server/.client-tools/thunderbird159/thunderbird/thunderbird", + "--output", + ".qualification-runs/p0/v16-delivery-install" + ], + "freshInstallationExitCode": 0, + "freshInstallationLogSha256": "089ab4685d786a14079b84725af571807ec16ed99b3f70c5812643c55513ca5c", + "matrixArchivePayloadDifferences": [ + "SOURCE.json", + "qualification/evidence/releases/0.2.0/verification.json" + ], + "reproducibleAssets": 6, + "sha256": "af932106d114655593dbff909b9315faaa66185444e3b235cef8d217e2e612d9", + "sourceCommit": "40176d20800c7d0a75f692f15a0d782cfcf6d5c5" + }, + "distribution": { + "image": { + "id": "sha256:7d3a07b372ec3ffa161b3ef2aa33c1564d524652c88ae011d1b4956629ee5699", + "jarSha256": "ce7b72f10ed342129d8b60b319b78ea091d9a03f20f029120e29eb6cf304ea62", + "jdkLegalDirectory": "/opt/java/openjdk/legal", + "labels": { + "org.opencontainers.image.created": "2026-10-25T10:26:07.538865+00:00", + "org.opencontainers.image.description": "Independent calendar and task server", + "org.opencontainers.image.licenses": "Apache-2.0", + "org.opencontainers.image.revision": "358a1ed2903d8d51622ecad00de6c973c9a94375", + "org.opencontainers.image.source": "https://github.com/busystack/caldav-server", + "org.opencontainers.image.title": "BusyStack CalDAV Server", + "org.opencontainers.image.version": "0.2.0" + }, + "osLicenseDirectory": "/usr/share/doc" + }, + "jarSha256": "ce7b72f10ed342129d8b60b319b78ea091d9a03f20f029120e29eb6cf304ea62", + "nestedArtifacts": [ + { + "artifact": "HdrHistogram-2.2.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "ba550515c77c9e6f8b6a400381eacd3c47569297f8f27884801a95dff5309483" + } + }, + { + "artifact": "HikariCP-7.0.2.jar", + "deliveredLicenseAndNoticeFiles": {} + }, + { + "artifact": "accessors-smart-2.6.0.jar", + "deliveredLicenseAndNoticeFiles": {} + }, + { + "artifact": "asm-9.7.1.jar", + "deliveredLicenseAndNoticeFiles": {} + }, + { + "artifact": "attoparser-2.0.7.RELEASE.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", + "META-INF/NOTICE.txt": "02ab16ab9bbb0d360481ffb8158745fafddd43a38cd74cf469acae7bd287f4bd" + } + }, + { + "artifact": "checker-qual-3.55.1.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "e90eaa08dea089df10f2bf7f9dba63a5f6237c01562c4741e2e86773e78582d5" + } + }, + { + "artifact": "classmate-1.7.3.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE": "7d8d549eb31995fe67822c860acc7ac3dd958a03a5a71aef4069033e7df72d94", + "META-INF/NOTICE": "1a8c67aaade274bc7bf06a7044571ab280d59fe3686941b6499b2176a072ea6d" + } + }, + { + "artifact": "commons-codec-1.21.0.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "b1d2870f1a00e4d7f56576e5f0870cba109e041f8af66866cf5b499478e654e7", + "META-INF/NOTICE.txt": "d82503df1b65173afe535a2f753d27c25377f7f6e9d0b19b4665af617df14750" + } + }, + { + "artifact": "commons-lang3-3.20.0.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "b1d2870f1a00e4d7f56576e5f0870cba109e041f8af66866cf5b499478e654e7", + "META-INF/NOTICE.txt": "64bc8696af3f6c770521412b85d3a733fa44b2ef5b0f4bd739e0c4d02eca492a" + } + }, + { + "artifact": "commons-logging-1.3.6.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "b1d2870f1a00e4d7f56576e5f0870cba109e041f8af66866cf5b499478e654e7", + "META-INF/NOTICE.txt": "d649e220dd0497197a266b7d7304a009d06bcefce3141fa6ff4f2ceddb438237" + } + }, + { + "artifact": "content-type-2.3.jar", + "deliveredLicenseAndNoticeFiles": {} + }, + { + "artifact": "flyway-core-12.4.0.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "6707b7b3ba3220ab64a81a5ab869ffecc3a6a023e9488ea08b897471b069c078", + "org/flywaydb/core/extensibility/LicenseGuard.class": "d9b3046e245a9e6cdb74decc14afbb83544e5f4014de75635292c7f693f5cdd4" + } + }, + { + "artifact": "flyway-database-postgresql-12.4.0.jar", + "deliveredLicenseAndNoticeFiles": {} + }, + { + "artifact": "hibernate-validator-9.1.5.Final.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/license.txt": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30" + } + }, + { + "artifact": "ical4j-4.4.0.jar", + "deliveredLicenseAndNoticeFiles": {} + }, + { + "artifact": "jackson-annotations-2.21.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", + "META-INF/NOTICE": "612b14bc77c944ce229cbba0d14919162cfea8ed802cbf06a8e865e032d03201" + } + }, + { + "artifact": "jackson-core-3.1.7.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", + "META-INF/NOTICE": "a8eb9ab6d21e719ba217c6367621a7ab5baa3d38df896ef258a9754a6b97527d" + } + }, + { + "artifact": "jackson-databind-3.1.7.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", + "META-INF/NOTICE": "d3fa47349b4ba4a3763bf635b930f8877073aa3915a3f3e45fe4b1842fc60302" + } + }, + { + "artifact": "jackson-dataformat-cbor-3.1.7.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE": "3b7ec3d73de1ac4eee9af17fd70239e8c226209713b7bc761821e5384acf0a9d", + "META-INF/NOTICE": "5828ffe74ea0ee4bf896654026f05fed1ead1d22acd577cc1eec9be0bc0de1ed" + } + }, + { + "artifact": "jakarta.annotation-api-3.0.0.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.md": "6e1f002892b81cbe0647019b150c8a056efc1add565671a4f8af629b6cd2cc7b", + "META-INF/NOTICE.md": "20bf986a153cc3095639379c99ef0a5a3bf99ac4895429920d380414a3eecf08" + } + }, + { + "artifact": "jakarta.validation-api-3.1.1.jar", + "deliveredLicenseAndNoticeFiles": {} + }, + { + "artifact": "jboss-logging-3.6.3.Final.jar", + "deliveredLicenseAndNoticeFiles": {} + }, + { + "artifact": "jcip-annotations-1.0-1.jar", + "deliveredLicenseAndNoticeFiles": {} + }, + { + "artifact": "json-smart-2.6.0.jar", + "deliveredLicenseAndNoticeFiles": {} + }, + { + "artifact": "jspecify-1.0.1.jar", + "deliveredLicenseAndNoticeFiles": {} + }, + { + "artifact": "jul-to-slf4j-2.0.20.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "4e7f90c86ab51278228bce153122f1d8df30149d13ce9ef524c8444a84c32dcc" + } + }, + { + "artifact": "lang-tag-1.7.jar", + "deliveredLicenseAndNoticeFiles": {} + }, + { + "artifact": "log4j-api-2.25.5.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", + "META-INF/NOTICE": "0b23e26a6260c82e2608899128a81a0c82e81f15d708779d0639227f6a2f801f" + } + }, + { + "artifact": "log4j-to-slf4j-2.25.5.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", + "META-INF/NOTICE": "0ccd7e8250b33edc64612733af1b614c40eec22505446b6faec1c7a40cbeda95" + } + }, + { + "artifact": "logback-classic-1.5.38.jar", + "deliveredLicenseAndNoticeFiles": {} + }, + { + "artifact": "logback-core-1.5.38.jar", + "deliveredLicenseAndNoticeFiles": {} + }, + { + "artifact": "micrometer-commons-1.17.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE": "62fb8a3a9621dc2388174caaabe9c2317b694bb9a1d46c98bcf5655b68f51be3", + "META-INF/NOTICE": "df207ca1a2ea3794caf112d7c1f024c87b4ddfe91d3f243977ad1d3cd085d538" + } + }, + { + "artifact": "micrometer-core-1.17.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE": "62fb8a3a9621dc2388174caaabe9c2317b694bb9a1d46c98bcf5655b68f51be3", + "META-INF/NOTICE": "df207ca1a2ea3794caf112d7c1f024c87b4ddfe91d3f243977ad1d3cd085d538" + } + }, + { + "artifact": "micrometer-jakarta9-1.17.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE": "62fb8a3a9621dc2388174caaabe9c2317b694bb9a1d46c98bcf5655b68f51be3", + "META-INF/NOTICE": "df207ca1a2ea3794caf112d7c1f024c87b4ddfe91d3f243977ad1d3cd085d538" + } + }, + { + "artifact": "micrometer-observation-1.17.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE": "62fb8a3a9621dc2388174caaabe9c2317b694bb9a1d46c98bcf5655b68f51be3", + "META-INF/NOTICE": "df207ca1a2ea3794caf112d7c1f024c87b4ddfe91d3f243977ad1d3cd085d538" + } + }, + { + "artifact": "nimbus-jose-jwt-10.9.1.jar", + "deliveredLicenseAndNoticeFiles": {} + }, + { + "artifact": "oauth2-oidc-sdk-11.38.2.jar", + "deliveredLicenseAndNoticeFiles": {} + }, + { + "artifact": "postgresql-42.7.14.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE": "08bb580d3cb8f9a4a05f008466a294fdb019e0e177d03a035d46f1eb94077de5", + "META-INF/licenses/com.ongres.scram/scram-client-3.2/META-INF/LICENSE": "7c89807167a03a92d2fbfc936aff4f87d8ce31434637381c89e38282c8c99198", + "META-INF/licenses/com.ongres.scram/scram-common-3.2/META-INF/LICENSE": "7c89807167a03a92d2fbfc936aff4f87d8ce31434637381c89e38282c8c99198", + "META-INF/licenses/com.ongres.stringprep/saslprep-2.2/META-INF/LICENSE": "5c49fc155ebccd206277e0d1f424aadbf365f0a9ccfb54d400d728a375d523f9", + "META-INF/licenses/com.ongres.stringprep/stringprep-2.2/META-INF/LICENSE": "5c49fc155ebccd206277e0d1f424aadbf365f0a9ccfb54d400d728a375d523f9" + } + }, + { + "artifact": "slf4j-api-2.0.20.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "6632f550c207be8d7d6b5e87f5d7b905bee218d18392d531df457bf60bec1447" + } + }, + { + "artifact": "snakeyaml-2.6.jar", + "deliveredLicenseAndNoticeFiles": {} + }, + { + "artifact": "spring-aop-7.0.10.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/license.txt": "222dd5e84501f80ca9e334f843659471001c40762073efc29f351e2d53e57e38", + "META-INF/notice.txt": "dd0c7dcb434e06953bcf6677e8b67922f09bf79f1b477cd16868da59b68b928b" + } + }, + { + "artifact": "spring-beans-7.0.10.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/license.txt": "222dd5e84501f80ca9e334f843659471001c40762073efc29f351e2d53e57e38", + "META-INF/notice.txt": "dd0c7dcb434e06953bcf6677e8b67922f09bf79f1b477cd16868da59b68b928b" + } + }, + { + "artifact": "spring-boot-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-actuator-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-actuator-autoconfigure-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-autoconfigure-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-flyway-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-health-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-http-converter-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-jackson-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-jarmode-tools-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-jdbc-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-micrometer-metrics-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-micrometer-observation-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-persistence-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-security-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-security-oauth2-authorization-server-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-security-oauth2-client-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-security-oauth2-resource-server-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-servlet-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-session-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-session-jdbc-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-sql-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-thymeleaf-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-tomcat-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-transaction-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-validation-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-web-server-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-boot-webmvc-4.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628", + "META-INF/NOTICE.txt": "33ed49a8e57825e3497d5e4ad4ad67815dec123fadff99ffee9705bd1564deca" + } + }, + { + "artifact": "spring-context-7.0.10.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/license.txt": "222dd5e84501f80ca9e334f843659471001c40762073efc29f351e2d53e57e38", + "META-INF/notice.txt": "dd0c7dcb434e06953bcf6677e8b67922f09bf79f1b477cd16868da59b68b928b" + } + }, + { + "artifact": "spring-core-7.0.10.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/license.txt": "222dd5e84501f80ca9e334f843659471001c40762073efc29f351e2d53e57e38", + "META-INF/notice.txt": "dd0c7dcb434e06953bcf6677e8b67922f09bf79f1b477cd16868da59b68b928b" + } + }, + { + "artifact": "spring-expression-7.0.10.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/license.txt": "222dd5e84501f80ca9e334f843659471001c40762073efc29f351e2d53e57e38", + "META-INF/notice.txt": "dd0c7dcb434e06953bcf6677e8b67922f09bf79f1b477cd16868da59b68b928b" + } + }, + { + "artifact": "spring-jdbc-7.0.10.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/license.txt": "222dd5e84501f80ca9e334f843659471001c40762073efc29f351e2d53e57e38", + "META-INF/notice.txt": "dd0c7dcb434e06953bcf6677e8b67922f09bf79f1b477cd16868da59b68b928b" + } + }, + { + "artifact": "spring-security-config-7.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628" + } + }, + { + "artifact": "spring-security-core-7.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628" + } + }, + { + "artifact": "spring-security-crypto-7.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628" + } + }, + { + "artifact": "spring-security-oauth2-authorization-server-7.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628" + } + }, + { + "artifact": "spring-security-oauth2-client-7.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628" + } + }, + { + "artifact": "spring-security-oauth2-core-7.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628" + } + }, + { + "artifact": "spring-security-oauth2-jose-7.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628" + } + }, + { + "artifact": "spring-security-oauth2-resource-server-7.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628" + } + }, + { + "artifact": "spring-security-web-7.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628" + } + }, + { + "artifact": "spring-security-webauthn-7.1.2.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "7200000367e0e8b47822d563a5ddd2dd3a97cc05b32bd7dbcc7b4eeb92b76628" + } + }, + { + "artifact": "spring-session-core-4.1.1.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "aac73b3148f6d1d7111dbca32099f68d26c644c6813ae1e4f05f6579aa2663fe" + } + }, + { + "artifact": "spring-session-jdbc-4.1.1.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "aac73b3148f6d1d7111dbca32099f68d26c644c6813ae1e4f05f6579aa2663fe" + } + }, + { + "artifact": "spring-tx-7.0.10.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/license.txt": "222dd5e84501f80ca9e334f843659471001c40762073efc29f351e2d53e57e38", + "META-INF/notice.txt": "dd0c7dcb434e06953bcf6677e8b67922f09bf79f1b477cd16868da59b68b928b" + } + }, + { + "artifact": "spring-web-7.0.10.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/license.txt": "222dd5e84501f80ca9e334f843659471001c40762073efc29f351e2d53e57e38", + "META-INF/notice.txt": "dd0c7dcb434e06953bcf6677e8b67922f09bf79f1b477cd16868da59b68b928b" + } + }, + { + "artifact": "spring-webmvc-7.0.10.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/license.txt": "222dd5e84501f80ca9e334f843659471001c40762073efc29f351e2d53e57e38", + "META-INF/notice.txt": "dd0c7dcb434e06953bcf6677e8b67922f09bf79f1b477cd16868da59b68b928b" + } + }, + { + "artifact": "threeten-extra-1.8.0.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "ff3c303a06b9007bf90c7c2c2acac3afdd2af2b504fad21e8b27c9605e1fbcd4" + } + }, + { + "artifact": "thymeleaf-3.1.5.RELEASE.jar", + "deliveredLicenseAndNoticeFiles": {} + }, + { + "artifact": "thymeleaf-spring6-3.1.5.RELEASE.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", + "META-INF/NOTICE.txt": "c940b6d5fba859e2773fb9568f6b3c328a396684b65dae023fb3f38ee5b0f3b3" + } + }, + { + "artifact": "tomcat-embed-core-11.0.27.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE": "8c39166d578175fb936229613e48de47d9e494b8c7c2fda6da717a1be29c8724", + "META-INF/NOTICE": "234d3234bb332895157270092fa2a11e80aa0b3d70d59e13de0eed4c2adb1790" + } + }, + { + "artifact": "tomcat-embed-el-11.0.27.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", + "META-INF/NOTICE": "0317acaa42a5e48bec061cf009cb5c8b4b8ff845f3c6ba548f67c5c22c29fc96" + } + }, + { + "artifact": "tomcat-embed-websocket-11.0.27.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", + "META-INF/NOTICE": "0317acaa42a5e48bec061cf009cb5c8b4b8ff845f3c6ba548f67c5c22c29fc96" + } + }, + { + "artifact": "unbescape-1.1.6.RELEASE.jar", + "deliveredLicenseAndNoticeFiles": { + "META-INF/LICENSE.txt": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", + "META-INF/NOTICE.txt": "df671a4abf4562cff42b0aacd7cf95461d7cee9df15e984eb838531031063d41" + } + }, + { + "artifact": "webauthn4j-core-0.31.10.RELEASE.jar", + "deliveredLicenseAndNoticeFiles": {} + } + ], + "projectLicense": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "projectVersion": "0.2.0", + "recordedAt": "2026-11-05T12:48:38.196514+00:00", + "runtimeComponents": 112, + "sourceArchiveSha256": "fe08f7f410822b143d95d6e177bc741528c4617e55a23495b560dcb821109450", + "sourceRevision": "358a1ed2903d8d51622ecad00de6c973c9a94375", + "status": "passed" + }, + "documentation": { + "captureRuntimeCommit": "358a1ed2903d8d51622ecad00de6c973c9a94375", + "chapters": 19, + "guide": "docs/GETTING_STARTED.md", + "guideSha256": "9d1d9b7e1c00c0fc837f95fe5fda1e6fc7452ea377972df7961f6a4e339550ac", + "redacted": [ + "15-password-created.png", + "18-recovery.png" + ], + "screenshots": { + "01-initial-setup.png": "c48654c33e52ad17d32540fff70ab203bab01ad726c09c0f63a1a12c68fc7f6f", + "02-create-administrator.png": "11d1fb6ff71e92d7edf2b597aa7442635141d9fdb9c03a63062e22f409b84f60", + "03-setup-complete.png": "ddb03f84a8103fc01f03d1e64e53a71b03b1a30f590f44cf1382073b82118414", + "04-sign-in.png": "9b6771fe3d8cbfaf8e826e1b1dc9c27bac4865e769234a76ddd9fcea127af358", + "05-create-passkey.png": "d224c3f67e7e9c5582e168216d14a89f989b1efb0e0d403dbb94c327767fc694", + "06-passkey-created.png": "2d0d173f2be1797f6451692220b75faef4780c54a0830b646b30b904a97a1cd6", + "07-verify-passkey.png": "470ad3d7bf81c5e7600cd22fd96ddee9bb42615199758350eb265eb119c7ee25", + "08-administrator-welcome.png": "b50ef6d937414682863352eae79de2efc68a84f5de690cad0ba8ba7c3ff05099", + "09-manage-users.png": "c51f946a29b07145a9b93f00fbc52298d55628ddf1a8850e9a11040fde156230", + "10-create-user.png": "093661891fb4cf38f64abff18bbd10a6ba0e5cca0420fba9d89ee2603b37b430", + "11-user-onboarding.png": "e0f4472f0441e8927443d78fb8bf52d4599bec96599251286bcafa871e2309d1", + "12-calendars.png": "61597809c588b456b88a582af3510ebe81d2828a54afca1fba3d2a9a01eea283", + "13-connect-application.png": "ad068af4542b46854fbee07ad79e6b09c4bb71d8a03b35f8ac2c58caab9825b5", + "14-create-application-password.png": "cde675b5e8bd78a8cbb569ecf11ad020cf37f497d2764811536dbf09d8a3aebd", + "15-password-created.png": "de4e0b31d0285546ebecb4ad331324f43bdfbf35c3c870b040517bfe9c54e7a4", + "16-client-configuration.png": "47200bb88bdb54e549178669305a1e999dc19db32c2ea50e802c19935d4881ae", + "17-security.png": "8c3d94824ee6201be6ad641544951b12c02a31b3460f69e423f6e124ce7d9269", + "18-recovery.png": "35805a4129620080250f1f7caa859d8189351a2b9b1a8e3b4e5f8a8573fd2373", + "19-sharing.png": "341e6064ba870ae53ffb57319efc93ad25528c6fdb8bc7b9a3ddef9fc46aef0a", + "20-import-export.png": "97e617f164d26a135c2c9312eeb320f7a0ab44fd34db4236781deeadee6d3bc6" + } + }, + "historicalGraphicalReleaseMatrix": "pending; native-provider/wizard results do not qualify every graphical editor profile", + "imageBuildCommand": { + "command": [ + "python3", + "qualification/p0/build.py", + "--image", + "busystack-caldav:p0-v16" + ], + "exitCode": 0 + }, + "imageDescriptorDigest": "sha256:7d3a07b372ec3ffa161b3ef2aa33c1564d524652c88ae011d1b4956629ee5699", + "imageId": "sha256:7d3a07b372ec3ffa161b3ef2aa33c1564d524652c88ae011d1b4956629ee5699", + "jarSha256": "ce7b72f10ed342129d8b60b319b78ea091d9a03f20f029120e29eb6cf304ea62", + "manualFirefoxBitwarden": { + "actualUserTestStatus": "pending", + "ca": "/home/albert/Projects/busystack/caldav-server/.qualification-runs/p0-manual-v16/ca.pem", + "caSha256Fingerprint": "38:01:75:12:D9:02:97:E1:83:02:38:A4:4C:C3:2E:9B:54:F8:7E:24:ED:26:69:3E:C7:92:4D:AF:FD:72:8F:78", + "certificateExpiresUtc": "2026-11-07T12:57:11Z", + "cleanup": "docker compose down --volumes --remove-orphans", + "directory": "/home/albert/Projects/busystack/caldav-server/.qualification-runs/p0-manual-v16/install", + "initializationCommand": "bash scripts/initialize.sh", + "noAccountCreated": true, + "preparationExitCode": 0, + "status": "ready-manual-acceptance-pending", + "url": "https://localhost:49681", + "verifiedInitialState": { + "accounts": 0, + "codeVerifierIsNull": true, + "initialized": false + } + }, + "maven": { + "command": [ + "./mvnw", + "-B", + "-ntp", + "clean", + "verify" + ], + "exitCode": 0, + "failsafe-reports": { + "errors": 0, + "failures": 0, + "skipped": 0, + "tests": 261 + }, + "finishedAt": "2026-11-05T11:58:31.138071+00:00", + "jarSha256": "ce7b72f10ed342129d8b60b319b78ea091d9a03f20f029120e29eb6cf304ea62", + "sourceCommit": "358a1ed2903d8d51622ecad00de6c973c9a94375", + "startedAt": "2026-11-05T11:16:36.342034+00:00", + "surefire-reports": { + "errors": 0, + "failures": 0, + "skipped": 0, + "tests": 424 + } + }, + "mavenLogSha256": "40f6471cb8396c9a83af6e3a1cb1059e289783c0a9335f94af5263fb953822a0", + "nativeGnome": { + "client": "GNOME Calendar", + "dataServerVersion": "3.56.2-8", + "mode": "real native connection wizard in private home/DBus/X11 namespace", + "nativeBackend": "caldav", + "nativeColour": "#126A5EFF", + "status": "passed", + "steps": [ + "Manage Calendars", + "Add Calendar", + "trusted HTTPS discovery URL with username", + "Credentials User/Password", + "Connect", + "native discovery", + "Add Calendar", + "native backend password prompt", + "native event synchronization", + "EDS create/modify/delete independently verified over HTTPS" + ], + "synchronization": { + "eventComponents": 3, + "interface": "installed EDS public ECalClient API after native wizard provisioning", + "nativeCreateModifyDeleteVerifiedOverHttps": true, + "recurrenceExceptions": 1, + "uidSeries": 2, + "writable": true + }, + "tls": "normal verification with fixture CA only in private namespace", + "version": "50.0-1" + }, + "newApplicationBranchOrWorktree": false, + "newDependencies": false, + "packagedMatrix": [ + { + "command": [ + "python3", + "qualification/p0/run.py", + "--application-image", + "busystack-caldav:p0-v16", + "--browser-image", + "busystack-passkey-browser:p0", + "--deployment-directory", + "/home/albert/Projects/busystack/caldav-server/.qualification-runs/p0/package-v16-final/caldav-server-0.2.0-deploy", + "--proxy", + "--clients", + "--thunderbird-binary", + "/home/albert/Projects/busystack/caldav-server/.client-tools/thunderbird159/thunderbird/thunderbird", + "--administrator-activity", + "personal", + "--output", + "/home/albert/Projects/busystack/caldav-server/.qualification-runs/p0/v16-package-root" + ], + "exitCode": 0, + "finished": "2026-11-05T12:06:41.504489+00:00", + "logSha256": "089ab4685d786a14079b84725af571807ec16ed99b3f70c5812643c55513ca5c", + "name": "package-root", + "started": "2026-11-05T12:04:14.491922+00:00" + }, + { + "command": [ + "python3", + "qualification/p0/run.py", + "--application-image", + "busystack-caldav:p0-v16", + "--browser-image", + "busystack-passkey-browser:p0", + "--deployment-directory", + "/home/albert/Projects/busystack/caldav-server/.qualification-runs/p0/package-v16-final/caldav-server-0.2.0-deploy", + "--proxy", + "--clients", + "--thunderbird-binary", + "/home/albert/Projects/busystack/caldav-server/.client-tools/thunderbird159/thunderbird/thunderbird", + "--context-path", + "/team", + "--output", + "/home/albert/Projects/busystack/caldav-server/.qualification-runs/p0/v16-package-team" + ], + "exitCode": 0, + "finished": "2026-11-05T12:09:08.994592+00:00", + "logSha256": "20be9903394a434ff5c8daf840d0706f4756df56767d7ad35c76f9d9b765c91a", + "name": "package-team", + "started": "2026-11-05T12:06:41.505461+00:00" + }, + { + "command": [ + "python3", + "qualification/passkeys/run.py", + "--application-image", + "busystack-caldav:p0-v16", + "--browser-image", + "busystack-passkey-browser:p0", + "--groups", + "--portability-crash" + ], + "exitCode": 0, + "finished": "2026-11-05T12:14:18.085958+00:00", + "logSha256": "c82f264e952ca8a8fa6e93e85c11202c531343b3a5b9a98a51db223fa576eadc", + "name": "browser-root", + "started": "2026-11-05T12:09:08.995756+00:00" + }, + { + "command": [ + "python3", + "qualification/passkeys/run.py", + "--application-image", + "busystack-caldav:p0-v16", + "--browser-image", + "busystack-passkey-browser:p0", + "--proxy", + "--groups", + "--restore", + "--clients", + "--thunderbird-binary", + "/home/albert/Projects/busystack/caldav-server/.client-tools/thunderbird159/thunderbird/thunderbird" + ], + "exitCode": 0, + "finished": "2026-11-05T12:21:42.954725+00:00", + "logSha256": "6bc91b3c7927fc29efb47c1f753eaebca0dfefa25f897778a24b4753d3324c63", + "name": "browser-proxy", + "started": "2026-11-05T12:14:18.087133+00:00" + }, + { + "command": [ + "python3", + "qualification/passkeys/run.py", + "--application-image", + "busystack-caldav:p0-v16", + "--browser-image", + "busystack-passkey-browser:p0", + "--oidc", + "--groups", + "--restore" + ], + "exitCode": 0, + "finished": "2026-11-05T12:32:51.483126+00:00", + "logSha256": "256196a731f7175daac9ea6316bad4451299b8fdb6a84c27e8802e2b1ebf23ca", + "name": "browser-oidc", + "started": "2026-11-05T12:21:42.956083+00:00" + }, + { + "command": [ + "python3", + "qualification/passkeys/run.py", + "--application-image", + "busystack-caldav:p0-v16", + "--browser-image", + "busystack-passkey-browser:p0", + "--gnome-only" + ], + "exitCode": 0, + "finished": "2026-11-05T12:36:17.773782+00:00", + "logSha256": "e1b7a35a5843d3189f8125585313631d67258895fb1194d22a152f5c4b871430", + "name": "gnome", + "started": "2026-11-05T12:32:51.484367+00:00" + }, + { + "command": [ + "python3", + "-c", + "import importlib.util,sys;from pathlib import Path;s=importlib.util.spec_from_file_location('ops','scripts/verify-operations.py');m=importlib.util.module_from_spec(s);s.loader.exec_module(m);m.ROOT=Path(sys.argv[1]);sys.argv=['verify-operations','--image','busystack-caldav:p0-v16','--baseline-image','busystack-caldav:corrective-3f74590cd8d2'];m.main()", + "/home/albert/Projects/busystack/caldav-server/.qualification-runs/p0/package-v16-final/caldav-server-0.2.0-deploy" + ], + "exitCode": 0, + "finished": "2026-11-05T12:48:38.002152+00:00", + "logSha256": "5d364f0a331730e38adfbf9a0385ae8adc8ad26c36c535d3a6be6ebb162b00e6", + "name": "operations", + "started": "2026-11-05T12:36:17.775238+00:00" + }, + { + "command": [ + "python3", + "scripts/verify-distribution.py", + "--image", + "busystack-caldav:p0-v16", + "--revision", + "358a1ed2903d8d51622ecad00de6c973c9a94375", + "--output", + "/home/albert/Projects/busystack/caldav-server/.qualification-runs/p0/v16-evidence/distribution.json" + ], + "exitCode": 0, + "finished": "2026-11-05T12:49:02.929091+00:00", + "logSha256": "b04e2caf854439ee88d7a5bf09d99555379602e63000f55c2b109baf8c475b33", + "name": "distribution", + "started": "2026-11-05T12:48:38.003446+00:00" + } + ], + "preservedUncommittedQualificationPaths": [ + "qualification/passkeys/README.md", + "qualification/passkeys/recovery.py", + "qualification/passkeys/test_recovery_refresh.py" + ], + "profiles": { + "capture": { + "browser": { + "assertions": 49, + "base": "https://localhost:47151", + "chromium": "149.0.7827.55", + "manualFirefoxBitwarden": "pending", + "playwright": "1.61.1", + "screenshots": 20, + "status": "passed" + }, + "clients": { + "clients": [ + { + "client": "python-caldav", + "icalendar": "7.3.0", + "operations": [ + "principal and home discovery", + "calendar and VTODO collection creation", + "Unicode event CRUD", + "unknown-property round trip", + "event time-range query", + "server recurrence expansion", + "same-resource detached exception CRUD and RECURRENCE-ID preservation", + "EXDATE exclusion in server expansion", + "undated task CRUD and completion", + "initial and incremental synchronization", + "resource and collection deletion" + ], + "status": "passed", + "syncConfiguration": { + "allowSyncDepthOne": true, + "configurationInput": "setting omitted; packaged application default", + "depthOneWithOtherSyncLevelStatus": 400, + "observedDepthStatus": { + "0": 207, + "1": 207, + "missing": 207 + }, + "verifiedBy": "actual authenticated REPORTs to this collection" + }, + "syncFallbackDisabled": true, + "version": "3.6.0" + }, + { + "client": "Thunderbird", + "crossClient": { + "excludedOccurrences": 1, + "icalendar": "7.3.0", + "nativeDetachedExceptions": 1, + "nativeRecurrenceInstances": 3, + "python-caldav": "3.6.0", + "sameResources": 4 + }, + "driver": "3.7.1", + "mode": "isolated headless native desktop CalDAV provider", + "nativeAppleCalendarColor": "#126A5E", + "nativePortalExportItems": "not executed in this profile", + "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" + ], + "status": "passed", + "syncConfiguration": { + "allowSyncDepthOne": true, + "configurationInput": "setting omitted; packaged application default", + "depthOneWithOtherSyncLevelStatus": 400, + "observedDepthStatus": { + "0": 207, + "1": 207, + "missing": 207 + }, + "verifiedBy": "actual authenticated REPORTs to this collection" + }, + "version": "159.0" + } + ], + "credentialOrigin": "application password issued after protected browser initialization and real virtual-authenticator MFA", + "image": "busystack-caldav:p0-v16" + } + }, + "packagedRoot": { + "browser": { + "assertions": 49, + "base": "https://localhost:56503", + "chromium": "149.0.7827.55", + "manualFirefoxBitwarden": "pending", + "playwright": "1.61.1", + "screenshots": 20, + "status": "passed" + }, + "clients": { + "clients": [ + { + "client": "python-caldav", + "icalendar": "7.3.0", + "operations": [ + "principal and home discovery", + "calendar and VTODO collection creation", + "Unicode event CRUD", + "unknown-property round trip", + "event time-range query", + "server recurrence expansion", + "same-resource detached exception CRUD and RECURRENCE-ID preservation", + "EXDATE exclusion in server expansion", + "undated task CRUD and completion", + "initial and incremental synchronization", + "resource and collection deletion" + ], + "status": "passed", + "syncConfiguration": { + "allowSyncDepthOne": true, + "configurationInput": "setting omitted; packaged application default", + "depthOneWithOtherSyncLevelStatus": 400, + "observedDepthStatus": { + "0": 207, + "1": 207, + "missing": 207 + }, + "verifiedBy": "actual authenticated REPORTs to this collection" + }, + "syncFallbackDisabled": true, + "version": "3.6.0" + }, + { + "client": "Thunderbird", + "crossClient": { + "excludedOccurrences": 1, + "icalendar": "7.3.0", + "nativeDetachedExceptions": 1, + "nativeRecurrenceInstances": 3, + "python-caldav": "3.6.0", + "sameResources": 4 + }, + "driver": "3.7.1", + "mode": "isolated headless native desktop CalDAV provider", + "nativeAppleCalendarColor": "#126A5E", + "nativePortalExportItems": "not executed in this profile", + "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" + ], + "status": "passed", + "syncConfiguration": { + "allowSyncDepthOne": true, + "configurationInput": "setting omitted; packaged application default", + "depthOneWithOtherSyncLevelStatus": 400, + "observedDepthStatus": { + "0": 207, + "1": 207, + "missing": 207 + }, + "verifiedBy": "actual authenticated REPORTs to this collection" + }, + "version": "159.0" + } + ], + "credentialOrigin": "application password issued after protected browser initialization and real virtual-authenticator MFA", + "image": "busystack-caldav:p0-v16" + } + }, + "packagedSubpath": { + "browser": { + "assertions": 48, + "base": "https://localhost:38345/team", + "chromium": "149.0.7827.55", + "manualFirefoxBitwarden": "pending", + "playwright": "1.61.1", + "screenshots": 20, + "status": "passed" + }, + "clients": { + "clients": [ + { + "client": "python-caldav", + "icalendar": "7.3.0", + "operations": [ + "principal and home discovery", + "calendar and VTODO collection creation", + "Unicode event CRUD", + "unknown-property round trip", + "event time-range query", + "server recurrence expansion", + "same-resource detached exception CRUD and RECURRENCE-ID preservation", + "EXDATE exclusion in server expansion", + "undated task CRUD and completion", + "initial and incremental synchronization", + "resource and collection deletion" + ], + "status": "passed", + "syncConfiguration": { + "allowSyncDepthOne": true, + "configurationInput": "setting omitted; packaged application default", + "depthOneWithOtherSyncLevelStatus": 400, + "observedDepthStatus": { + "0": 207, + "1": 207, + "missing": 207 + }, + "verifiedBy": "actual authenticated REPORTs to this collection" + }, + "syncFallbackDisabled": true, + "version": "3.6.0" + }, + { + "client": "Thunderbird", + "crossClient": { + "excludedOccurrences": 1, + "icalendar": "7.3.0", + "nativeDetachedExceptions": 1, + "nativeRecurrenceInstances": 3, + "python-caldav": "3.6.0", + "sameResources": 4 + }, + "driver": "3.7.1", + "mode": "isolated headless native desktop CalDAV provider", + "nativeAppleCalendarColor": "#126A5E", + "nativePortalExportItems": "not executed in this profile", + "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" + ], + "status": "passed", + "syncConfiguration": { + "allowSyncDepthOne": true, + "configurationInput": "setting omitted; packaged application default", + "depthOneWithOtherSyncLevelStatus": 400, + "observedDepthStatus": { + "0": 207, + "1": 207, + "missing": 207 + }, + "verifiedBy": "actual authenticated REPORTs to this collection" + }, + "version": "159.0" + } + ], + "credentialOrigin": "application password issued after protected browser initialization and real virtual-authenticator MFA", + "image": "busystack-caldav:p0-v16" + } + } + }, + "publicAnonymousDownloadAndPull": "not executed; this work is unpublished and publication is not authorized", + "qualificationKind": "local-unpublished", + "qualifiedArchive": { + "image": "ghcr.io/busystack/caldav-server:0.2.0@sha256:7d3a07b372ec3ffa161b3ef2aa33c1564d524652c88ae011d1b4956629ee5699", + "sha256": "99100b1f9e30ef9910f74b34e9afb0487ce0dcf650cb8898f220368c143d7473", + "sourceCommit": "7c8f36b8676b10186822432ecaa20a098e8c8144" + }, + "recordedAt": "2026-11-05T12:49:20.160503+00:00", + "runtimeCommit": "358a1ed2903d8d51622ecad00de6c973c9a94375", + "schemaVersion": 1, + "sourceCaptureCommand": { + "command": [ + "python3", + "qualification/p0/run.py", + "--application-image", + "busystack-caldav:p0-v16", + "--browser-image", + "busystack-passkey-browser:p0", + "--proxy", + "--administrator-activity", + "personal", + "--clients", + "--thunderbird-binary", + "/home/albert/Projects/busystack/caldav-server/.client-tools/thunderbird159/thunderbird/thunderbird", + "--output", + "/home/albert/Projects/busystack/caldav-server/.qualification-runs/p0/v16-capture" + ], + "exitCode": 0 + }, + "startingCommit": "3f74590cd8d22341ae1a496af41377a8521733fa", + "thirdPartySoftwareModified": false, + "toolTests": { + "fixtureTools": { + "command": [ + "python3", + "-m", + "unittest", + "discover", + "-s", + "qualification/passkeys", + "-p", + "test_*.py" + ], + "exitCode": 0, + "logSha256": "1379b5aab71c9ca77a2459d403f8e21a6a675292c107441a36fcb878175421f4", + "tests": 14 + }, + "releaseTools": { + "command": [ + "python3", + "-m", + "unittest", + "discover", + "-s", + "qualification/release", + "-v" + ], + "exitCode": 0, + "logSha256": "4f77622923734430ef0e1a3d7b01a4cfdf9711de69f5452fc23f5df58f7f3df6", + "tests": 33 + } + } +} diff --git a/qualification/evidence/releases/0.2.0/verification.json b/qualification/evidence/releases/0.2.0/verification.json new file mode 100644 index 0000000..6a87583 --- /dev/null +++ b/qualification/evidence/releases/0.2.0/verification.json @@ -0,0 +1,95 @@ +{ + "version": "0.2.0", + "status": "passed", + "qualificationKind": "real-desktop-editors-over-trusted-https", + "recordedAt": "2026-11-30T07:56:24.562403+00:00", + "runtimeVerificationCommit": "610d83b3bae1962ff21a7b9356703cd3cfc380e5", + "jarSha256": "3f06168b844ea13f2de1a1614f673051c23fbfd991e5f57744105b7f1bc434a5", + "localTestedImageId": "sha256:7a51add7e74be625e0dc502e36c6dacf07b41e2a337c9395f2acf32d1d404fe0", + "runtimeInputs": { + "Dockerfile": "46264ee831ccd41bb78e0694bad57742a6557ce4a155c9eee9d531427556fb1e", + "compose.yaml": "843834fdeab4dbe73e1243e4b87fb6d51f5d5b669b4e15de53bea4aa62b48901" + }, + "clients": { + "thunderbird-system-vancouver": { + "status": "passed", + "client": "Thunderbird", + "version": "159.0", + "buildId": "20261026161902", + "effectiveTimeZone": "America/Vancouver", + "systemSelection": true, + "tzdata": "2026e", + "operations": [ + "native wizard and credential prompt", + "timed creation and conditional change", + "finite recurrence and detached occurrence edit", + "restart and reopen", + "task completion and deletion", + "event deletion" + ], + "evidenceSha256": "54f29d3f210279ddc194ed0e978424f45ddcf07237c62bc4c435b7992d65583e" + }, + "thunderbird-explicit-vancouver": { + "status": "passed", + "client": "Thunderbird", + "version": "159.0", + "buildId": "20261026161902", + "effectiveTimeZone": "America/Vancouver", + "systemSelection": false, + "tzdata": "2026e", + "operations": [ + "native wizard and credential prompt", + "timed creation and conditional change", + "finite recurrence and detached occurrence edit", + "restart and reopen", + "task completion and deletion", + "event deletion" + ], + "evidenceSha256": "29ee9d39867110ebebf59cd44367cdf9b9c477c430f8eab2c671e4d460a619c4" + }, + "thunderbird-explicit-berlin": { + "status": "passed", + "client": "Thunderbird", + "version": "159.0", + "buildId": "20261026161902", + "effectiveTimeZone": "Europe/Berlin", + "systemSelection": false, + "tzdata": "2026e", + "operations": [ + "native wizard and credential prompt", + "timed creation and conditional change", + "finite recurrence and detached occurrence edit", + "restart and reopen", + "task completion and deletion", + "event deletion" + ], + "evidenceSha256": "beef7bdc8b292efc108e50e8648c36297c34b92952ed3ab38138e7b0ea9dbbef" + }, + "gnome-vancouver": { + "status": "passed", + "client": "GNOME Calendar", + "version": "50.0-1", + "edsVersion": "3.56.2-8", + "effectiveTimeZone": "America/Vancouver", + "operations": [ + "native connection wizard", + "independent EDS CRUD over HTTPS", + "timed event creation and time edit", + "reopen after client and server restarts", + "three native daily occurrences verified by server expansion", + "delete all occurrences, then GET 404" + ], + "editorEvidenceSha256": "5c6c5443caa906fd70b3285ee6d6de0bc83224046327c9ce3a9fdaf893bd6ba6", + "wizardEvidenceSha256": "d928f38f08ba8dea5e8a098ec8744d284ce24a8440636a09cd2459a440a92e3e", + "restartEvidenceSha256": "8d99fd1c33ba04f498d21906bc9a128fbeb5505e51adba02dd6983b683defafe" + } + }, + "limitations": [ + "The real desktop editors ran in disposable, automated X11 profiles on Linux AMD64.", + "The browser provisioned test credentials with a virtual CTAP2 authenticator.", + "GNOME restart and whole-series deletion checks were retained from separate disposable runs with the same executable and runtime inputs.", + "The native provider probe during Thunderbird discovery received HTTP 409 at the DAV root. Calendar-item writes, recurrence edits and task completion passed.", + "Other desktop versions, platforms and physical passkey devices were outside this run." + ], + "previousRecord": "https://github.com/busystack/caldav-server/blob/e36d74c614e400273f7083029d8a3fa0b10975ab/qualification/evidence/releases/0.2.0/verification.json" +} diff --git a/qualification/evidence/vjournal-admission.md b/qualification/evidence/vjournal-admission.md new file mode 100644 index 0000000..c133bd1 --- /dev/null +++ b/qualification/evidence/vjournal-admission.md @@ -0,0 +1,45 @@ +# Stock Nextcloud journal storage admission + +On 2026-11-26, the independent loopback DAV probe used official Nextcloud +35.0.3 (internal version 35.0.3.2), PHP 8.5.13, SabreDAV 4.7.0 and +Sabre VObject 4.5.6 on a disposable SQLite installation. The official +`nextcloud:35.0.3-apache` manifest digest was +`sha256:f44180601f18e7664557232b4c5edb0eb4a82d649c05b93313f4e15909553d42`. +The running image ID was +`sha256:7d7c1ecc23d6d3848a44b1502cd7011082d1299466ad169de758aadf74fbb555`. + +The fixture program discovered the principal and home, created and discovered +a VJOURNAL-only collection, and verified create, conditional replace, and +authoritative GET for 11 cases. It exited 1, with 12 passing operations and +10 rejected operations. Every rejected write left the prior resource state, +inventory and sync token unchanged. The program removed its test collection. +[Sanitized results](vjournal-nextcloud-35.0.3.jsonl) record both HTTP statuses, +the error element names and the response hash. + +| Fixture | Source | Observed create / replace | +| --- | --- | --- | +| J01 minimal undated | [RFC 5545 §3.6.3](https://www.rfc-editor.org/rfc/rfc5545.html#section-3.6.3) | 201 / 204 and complete GET | +| J10 colour, image, wrapper, unknown parameter | [RFC 7986 §§4–5](https://www.rfc-editor.org/rfc/rfc7986.html#section-4) | 201 / 204 and complete GET | +| J11 structured, styled and nested | [RFC 9073 §§4–7](https://www.rfc-editor.org/rfc/rfc9073.html#section-4) | 201 / 204 and complete GET | +| J12 LINK URI, legacy and URI RELATED-TO | [RFC 9253 §§7, 9.1](https://www.rfc-editor.org/rfc/rfc9253.html#section-7) | 201 / 204 and complete GET | +| J12 LINK UID, LINK XML-REFERENCE, RELATED-TO UID | [RFC 9253 §§2, 7, 9.1](https://www.rfc-editor.org/rfc/rfc9253.html#section-2) | 500 / 500 for each | +| J15 PERIOD start/end and start/duration | [RFC 5545 §3.8.5.2](https://www.rfc-editor.org/rfc/rfc5545.html#section-3.8.5.2) | 500 / 500 for each | + +Run the probe against a disposable fixture account with a private file +containing its application password. For a private TLS fixture, also pass +`--ca-file /path/to/test-ca.pem`. + +```sh +python3 qualification/clients/journal-admission.py \ + https://fixture.example/remote.php/dav/ fixture-user /private/app-password +``` + +The fixture process returns a failure for an incompatible provider even when +the prior state is intact. The tagged Nextcloud backend invokes +`getDateTimes()` for an RDATE attached to a dated component. Sabre's shipped +PERIOD property lacks that accessor, and the shipped VCalendar value map +does not include UID or XML-REFERENCE. Those are independent of date-range +REPORT behavior. +[Backend](https://github.com/nextcloud/server/blob/v35.0.3/apps/dav/lib/CalDAV/CalDavBackend.php) +[Period](https://github.com/nextcloud/3rdparty/blob/8d85b94d76506730b13deac503e12ed79234ee22/sabre/vobject/lib/Property/ICalendar/Period.php) +[VCalendar](https://github.com/nextcloud/3rdparty/blob/8d85b94d76506730b13deac503e12ed79234ee22/sabre/vobject/lib/Component/VCalendar.php). diff --git a/qualification/evidence/vjournal-nextcloud-35.0.3.jsonl b/qualification/evidence/vjournal-nextcloud-35.0.3.jsonl new file mode 100644 index 0000000..a4e64e9 --- /dev/null +++ b/qualification/evidence/vjournal-nextcloud-35.0.3.jsonl @@ -0,0 +1,24 @@ +{"fixture_version": 1, "fixture_sha256": "68fe8ab310463333ddc6371c3b8b58744223b3f78f3a41152b47d15e498847a0"} +{"case": "J01", "operation": "create", "put": 201, "get": 200, "dav_errors": [], "response_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "issue": null} +{"case": "J01", "operation": "update", "put": 204, "get": 200, "dav_errors": [], "response_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "issue": null} +{"case": "J10", "operation": "create", "put": 201, "get": 200, "dav_errors": [], "response_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "issue": null} +{"case": "J10", "operation": "update", "put": 204, "get": 200, "dav_errors": [], "response_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "issue": null} +{"case": "J11", "operation": "create", "put": 201, "get": 200, "dav_errors": [], "response_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "issue": null} +{"case": "J11", "operation": "update", "put": 204, "get": 200, "dav_errors": [], "response_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "issue": null} +{"case": "J12-link-uri", "operation": "create", "put": 201, "get": 200, "dav_errors": [], "response_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "issue": null} +{"case": "J12-link-uri", "operation": "update", "put": 204, "get": 200, "dav_errors": [], "response_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "issue": null} +{"case": "J12-link-uid", "operation": "create", "put": 500, "get": 404, "dav_errors": ["{http://sabredav.org/ns}exception", "{http://sabredav.org/ns}message"], "response_sha256": "8de1a8d7c32e76ea7f6a6e5f52aab81a5ece5c6c0983fb9dcbfb6a8ce1919d1c", "issue": "admission rejected; original state unchanged"} +{"case": "J12-link-uid", "operation": "update", "put": 500, "get": 200, "dav_errors": ["{http://sabredav.org/ns}exception", "{http://sabredav.org/ns}message"], "response_sha256": "8de1a8d7c32e76ea7f6a6e5f52aab81a5ece5c6c0983fb9dcbfb6a8ce1919d1c", "issue": "admission rejected; original state unchanged"} +{"case": "J12-link-xml", "operation": "create", "put": 500, "get": 404, "dav_errors": ["{http://sabredav.org/ns}exception", "{http://sabredav.org/ns}message"], "response_sha256": "9227d428b0207c957b27c75ddf94137a87d446137e62a7ff1489bb4e20716ecc", "issue": "admission rejected; original state unchanged"} +{"case": "J12-link-xml", "operation": "update", "put": 500, "get": 200, "dav_errors": ["{http://sabredav.org/ns}exception", "{http://sabredav.org/ns}message"], "response_sha256": "9227d428b0207c957b27c75ddf94137a87d446137e62a7ff1489bb4e20716ecc", "issue": "admission rejected; original state unchanged"} +{"case": "J12-related-legacy", "operation": "create", "put": 201, "get": 200, "dav_errors": [], "response_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "issue": null} +{"case": "J12-related-legacy", "operation": "update", "put": 204, "get": 200, "dav_errors": [], "response_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "issue": null} +{"case": "J12-related-uri", "operation": "create", "put": 201, "get": 200, "dav_errors": [], "response_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "issue": null} +{"case": "J12-related-uri", "operation": "update", "put": 204, "get": 200, "dav_errors": [], "response_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "issue": null} +{"case": "J12-related-uid", "operation": "create", "put": 500, "get": 404, "dav_errors": ["{http://sabredav.org/ns}exception", "{http://sabredav.org/ns}message"], "response_sha256": "4314b7711ca3e5d1801cb4f34b11b8a017fa34b898f6be867f3324707d74ad86", "issue": "admission rejected; original state unchanged"} +{"case": "J12-related-uid", "operation": "update", "put": 500, "get": 200, "dav_errors": ["{http://sabredav.org/ns}exception", "{http://sabredav.org/ns}message"], "response_sha256": "4314b7711ca3e5d1801cb4f34b11b8a017fa34b898f6be867f3324707d74ad86", "issue": "admission rejected; original state unchanged"} +{"case": "J15-start-end", "operation": "create", "put": 500, "get": 404, "dav_errors": ["{http://sabredav.org/ns}exception", "{http://sabredav.org/ns}message"], "response_sha256": "f1882b3cfc20ecfa0afcfdd764bd3f9d3c7146c3dc66eebb90962398ef3fbc5e", "issue": "admission rejected; original state unchanged"} +{"case": "J15-start-end", "operation": "update", "put": 500, "get": 200, "dav_errors": ["{http://sabredav.org/ns}exception", "{http://sabredav.org/ns}message"], "response_sha256": "f1882b3cfc20ecfa0afcfdd764bd3f9d3c7146c3dc66eebb90962398ef3fbc5e", "issue": "admission rejected; original state unchanged"} +{"case": "J15-start-duration", "operation": "create", "put": 500, "get": 404, "dav_errors": ["{http://sabredav.org/ns}exception", "{http://sabredav.org/ns}message"], "response_sha256": "f1882b3cfc20ecfa0afcfdd764bd3f9d3c7146c3dc66eebb90962398ef3fbc5e", "issue": "admission rejected; original state unchanged"} +{"case": "J15-start-duration", "operation": "update", "put": 500, "get": 200, "dav_errors": ["{http://sabredav.org/ns}exception", "{http://sabredav.org/ns}message"], "response_sha256": "f1882b3cfc20ecfa0afcfdd764bd3f9d3c7146c3dc66eebb90962398ef3fbc5e", "issue": "admission rejected; original state unchanged"} +{"executed": 22, "passed": 12, "failed": 10} diff --git a/qualification/fixtures/vjournal/admission-v1.json b/qualification/fixtures/vjournal/admission-v1.json new file mode 100644 index 0000000..c354584 --- /dev/null +++ b/qualification/fixtures/vjournal/admission-v1.json @@ -0,0 +1,61 @@ +{ + "version": 1, + "cases": [ + { + "id": "J01", + "clause": "RFC 5545 §3.6.3", + "journal": [] + }, + { + "id": "J10", + "clause": "RFC 7986 §§4, 5.1, 5.9–5.10", + "calendar": ["NAME:Fixture calendar"], + "journal": ["COLOR:darkblue", "IMAGE;VALUE=URI;DISPLAY=BADGE:https://example.invalid/image.png", "X-JOURNAL;X-QUOTED=\"a,b\":opaque"] + }, + { + "id": "J11", + "clause": "RFC 9073 §§4–7", + "journal": ["STYLED-DESCRIPTION;VALUE=TEXT;FMTTYPE=text/html:Fixture", "STRUCTURED-DATA;VALUE=URI;SCHEMA=\"https://schema.org/Thing\":https://example.invalid/record.json", "BEGIN:PARTICIPANT", "UID:participant-fixture", "PARTICIPANT-TYPE:CONTACT", "CALENDAR-ADDRESS:mailto:participant@example.invalid", "BEGIN:VLOCATION", "UID:participant-location-fixture", "NAME:Participant venue", "END:VLOCATION", "END:PARTICIPANT", "BEGIN:VLOCATION", "UID:location-fixture", "NAME:Journal venue", "END:VLOCATION", "BEGIN:VRESOURCE", "UID:resource-fixture", "NAME:Journal resource", "RESOURCE-TYPE:ROOM", "END:VRESOURCE"] + }, + { + "id": "J12-link-uri", + "clause": "RFC 9253 §§2, 7", + "journal": ["LINK;VALUE=URI:https://example.invalid/journal"] + }, + { + "id": "J12-link-uid", + "clause": "RFC 9253 §§2, 7", + "journal": ["LINK;VALUE=UID:target-fixture"] + }, + { + "id": "J12-link-xml", + "clause": "RFC 9253 §§2, 7", + "journal": ["LINK;VALUE=XML-REFERENCE:https://example.invalid/journal.xml#xpointer(/journal)"] + }, + { + "id": "J12-related-legacy", + "clause": "RFC 9253 §9.1", + "journal": ["RELATED-TO;RELTYPE=PARENT:target-fixture"] + }, + { + "id": "J12-related-uri", + "clause": "RFC 9253 §9.1", + "journal": ["RELATED-TO;VALUE=URI:https://example.invalid/journal"] + }, + { + "id": "J12-related-uid", + "clause": "RFC 9253 §9.1", + "journal": ["RELATED-TO;VALUE=UID:target-fixture"] + }, + { + "id": "J15-start-end", + "clause": "RFC 5545 §§3.3.9, 3.8.5.2", + "journal": ["DTSTART:20261125T090000Z", "RDATE;VALUE=PERIOD:20261126T090000Z/20261126T110000Z"] + }, + { + "id": "J15-start-duration", + "clause": "RFC 5545 §§3.3.9, 3.8.5.2", + "journal": ["DTSTART:20261125T090000Z", "RDATE;VALUE=PERIOD:20261126T090000Z/PT2H"] + } + ] +} diff --git a/qualification/keycloak/Dockerfile b/qualification/keycloak/Dockerfile index 91f34df..9e51ed0 100644 --- a/qualification/keycloak/Dockerfile +++ b/qualification/keycloak/Dockerfile @@ -2,7 +2,7 @@ # Copy the identical pinned Keycloak distribution onto the Java 25 runtime # already qualified for this workspace's older CPU. No server code is changed. FROM quay.io/keycloak/keycloak:26.8.1@sha256:a78d6b79572168cb25886b80a8b5b8d4ed4390743e3eecb810538683e209dd6b AS distribution -FROM eclipse-temurin:25-jdk@sha256:3ab7fc8d0b4ade8fef96903fb36767c1dbb4fd1535dcfad85b59c17afbbb5857 +FROM eclipse-temurin:25.0.5.1_2-jdk-resolute@sha256:d1b500f1a2a8e2cb1b0fa84e21c4a52963050cbd46b8a53fcb6a8eec0f57675f COPY --from=distribution --chown=1000:1000 /opt/keycloak /opt/keycloak ENV KC_RUN_IN_CONTAINER=true USER 1000:1000 diff --git a/qualification/p0/README.md b/qualification/p0/README.md new file mode 100644 index 0000000..ac1d6e7 --- /dev/null +++ b/qualification/p0/README.md @@ -0,0 +1,82 @@ +# P0 journey qualification + +Use the existing branch and a local development commit containing the runtime and +these tests. No public release or push is performed. The official release builder +continues to require a clean tree. The local image helper permits unrelated +qualification edits only after proving every runtime/build input equals HEAD; +its receipt explicitly records the uncommitted qualification paths. + +Run the repository's complete Maven verification first with its documented Java 25, +Docker and independent-client prerequisites. Preserve the Maven log and XML results. +Then, sequentially (browser fixtures require stable host networking): + +```sh +python3 qualification/p0/build.py --image busystack-caldav:p0-local +python3 qualification/p0/run.py --application-image busystack-caldav:p0-local +``` + +The latter uses an empty isolated Compose database, actual TLS with normal +certificate validation, the exact operator code command, and Chromium's CTAP2 +virtual authenticator. It never pre-creates an administrator. It captures twenty-seven +screens at 1280×900 with light production CSS, checks reflow at 320px and 390px, masks the +one-time application password's containing block, and destroys only its owned +project/volume. No native browser/password-manager dialog is fabricated. Fixture +secrets exist only in a private temporary directory; no secrets enter screenshots +or the success receipt. Do not print HTTP client exception headers or dump cookies. + +A passing run writes `target/qualification/p0/browser-result.json` and PNGs. Copy +only the twenty-seven named PNGs to `docs/images/getting-started/`, inspect them, and +commit them. The final capture must use the final qualified runtime. Qualification +results must distinguish Chromium virtual-authenticator evidence from manual +Firefox/Bitwarden acceptance. + +`package.py` assembles an **unpublished local** deployment archive through the same +file-selection and deterministic archive functions as `scripts/release-bundle.py`. +It validates all guide links and twenty-seven PNGs, verifies source/runtime equivalence +and the exact container JAR checksum, and records actual image/source identities. +Its metadata does not invent a CI run or a published release. When Docker has no +OCI descriptor, the local archive uses the verified immutable image ID and records +a null registry digest. Only this explicit unpublished mode accepts that identity; +public release validation still requires a registry manifest digest: + +```sh +python3 qualification/p0/package.py --image busystack-caldav:p0-local --output target/p0-local-package +python3 qualification/p0/run.py --application-image busystack-caldav:p0-local \ + --deployment-directory target/p0-local-package/caldav-server-0.2.0-deploy \ + --proxy --output target/qualification/p0-package +``` + +The proxy profile uses the guide's complete `up -d --no-build --wait +--wait-timeout 240` command and both production health checks. Run it again with +`--context-path /team` to check the packaged subpath example. The browser enters the administrator area from the same Overview used by personal accounts. + +For final manual acceptance, prepare a separate fresh project using the extracted +package. The following starts an isolated Nginx HTTPS deployment using the package's +actual root proxy example. It creates no accounts and does not issue a code: + +```sh +python3 qualification/p0/manual.py \ + --deployment-directory target/p0-local-package/caldav-server-0.2.0-deploy \ + --output .qualification-runs/p0-manual +``` + +The resulting private `acceptance.json` identifies the exact HTTPS address, +installation directory and disposable CA. Use a new Firefox profile; trust the CA +in that profile through Firefox's certificate settings and select your usual +passkey provider for this test. Do not change an existing profile or vault automatically. +From the displayed installation directory, issue `bash scripts/initialize.sh` and +follow Getting Started chapters 6–7. Choose a fresh test password yourself; the +agent has not prepared a login or registered a passkey in a password manager. + +Manually record: setup → administrator creation → password sign-in → Bitwarden +registration → separate verification → protected collection creation → application +password issuance → sign out → returning sign-in → existing-passkey verification. +Record exact Firefox/Bitwarden versions, result and any cancellation/provider +behavior. Bitwarden qualification is not a hardware user-presence claim. Until the +user performs this procedure, that acceptance is **pending**. + +Cleanup only the isolated project: from its displayed installation directory run +`docker compose down --volumes --remove-orphans`. Its disposable CA expires after +two days; regenerate a new fixture for later acceptance. Public anonymous download +and registry-pull acceptance requires actual published assets and is distinct +from these explicitly local pre-publication tests. diff --git a/qualification/p0/browser.mjs b/qualification/p0/browser.mjs new file mode 100644 index 0000000..a28a8bd --- /dev/null +++ b/qualification/p0/browser.mjs @@ -0,0 +1,285 @@ +import {chromium} from 'playwright'; +import assert from 'node:assert/strict'; +import {readFileSync, mkdirSync, writeFileSync} from 'node:fs'; +import {createCollection, provisionAccount, grantDirect} from './portal-helpers.mjs'; +const base=process.env.BUSYSTACK_BROWSER_URL, prefix=new URL(base).pathname.replace(/\/$/,''); +const password=readFileSync('/fixture/password','utf8').trimEnd(); +const code=readFileSync('/fixture/initialization-code','utf8').trim(); +const privateValues=[password,code]; +const output='/evidence'; mkdirSync(output,{recursive:true}); +const browser=await chromium.launch({headless:true}); +let assertions=0; +const check=(condition,message)=>{assert.ok(condition,message); assertions++;}; +async function virtual(context,page) { + const cdp=await context.newCDPSession(page);await cdp.send('WebAuthn.enable'); + await cdp.send('WebAuthn.addVirtualAuthenticator',{options:{protocol:'ctap2',transport:'internal',hasResidentKey:true,hasUserVerification:true,isUserVerified:true,automaticPresenceSimulation:true}}); + return cdp; +} +async function shot(page,name,mask=[]) { + await page.screenshot({path:output+'/'+name+'.png',fullPage:true,mask,maskColor:'#172b38'}); + console.log('P0_SCREEN_CAPTURED '+name); + for (const width of [320, 390]) { + await page.setViewportSize({width,height:900}); + check(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1),name+' fits '+width+'px'); + } + await page.setViewportSize({width:1280,height:900}); +} +async function signIn(page,username,preserveContinuation=false) { + if(preserveContinuation) { + await page.waitForURL(url=>url.pathname===prefix+'/login' && url.searchParams.has('flow')); + } else { + await page.goto(base+'/login'); + } + await page.locator('[name=username]').fill(username); + await page.locator('[name=password]').fill(password); + await Promise.all([page.waitForURL(url => url.pathname === prefix + '/auth/continue'),page.getByRole('button',{name:'Sign in',exact:true}).click()]); +} +async function enroll(page) { + await page.getByRole('button',{name:'Create passkey',exact:true}).click(); + await page.getByRole('heading',{name:'Passkey saved',exact:true}).waitFor(); +} +async function verify(page) { + const cookie=(await page.context().cookies()).find(c=>c.name==='JSESSIONID').value; + await Promise.all([ + page.waitForURL(url => !url.pathname.endsWith('/auth/continue') && !url.pathname.endsWith('/login')), + page.getByRole('button',{name:'Verify and continue',exact:true}).click() + ]); + check(cookie!==(await page.context().cookies()).find(c=>c.name==='JSESSIONID').value,'Session rotates after passkey assertion'); +} +async function mutate(page,path,values) { + return page.evaluate(async ({path,values})=>{ + const token=document.querySelector('meta[name=csrf-token]')?.content||document.querySelector('[name=_csrf]').value; + const response=await fetch(path,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded','X-CSRF-TOKEN':token},body:new URLSearchParams(values)}); + return response.status; + },{path:prefix+path,values}); +} +async function lostIssuance(page,expectedReceipt) { + const form = page.locator('form[data-single-submit]'); + const endpoint = await form.evaluate(element=>element.action); + let committedStatus; + await page.route(endpoint, async route=>{ + const response=await route.fetch(); + committedStatus=response.status(); + await route.abort('failed'); + }, {times:1}); + const submit=element=>fetch(element.action,{method:'POST',body:new URLSearchParams(new FormData(element))}) + .then(response=>response.text()).catch(()=>null); + check(await form.evaluate(submit)===null && committedStatus===200,'Issuance committed but the caller lost the response'); + const retry=await form.evaluate(submit); + check(typeof retry==='string' && retry.includes(expectedReceipt) && !retry.includes('data-one-time-secret'),'Retry receives a receipt without any one-time value'); +} +try { + const context=await browser.newContext({viewport:{width:1280,height:900},colorScheme:'light'}); + await context.grantPermissions(['clipboard-read','clipboard-write']); + const page=await context.newPage(); const cdp=await virtual(context,page); + const errors=[];page.on('pageerror',error=>errors.push(error.message)); + const remoteAssets=[];page.on('request',request=>{if(new URL(request.url()).origin!==new URL(base).origin)remoteAssets.push(request.resourceType());}); + await page.goto(base+'/'); await page.getByRole('heading',{name:'Set up BusyStack',exact:true}).waitFor(); + await shot(page,'01-protected-setup'); + check((await page.request.get(base+'/setup/administrator',{maxRedirects:0})).status()===302,'Legacy setup leads to the canonical page'); + check((await page.request.get(base+'/help/setup')).ok(),'Local setup help is served'); + check(await mutate(page,'/setup/administrator',{code:'wrong',username:'rejected',password,confirmation:password})===400,'Invalid operator code rejected'); + await page.locator('[name=code]').fill(code);await page.locator('[name=username]').fill('demo-admin'); + await page.locator('[name=password]').fill(password);await page.locator('[name=confirmation]').fill(password+'!'); + await page.getByRole('button',{name:'Create administrator account',exact:true}).click(); + check(page.url()===base+'/setup','Password mismatch is caught before submission'); + check(await page.locator('[name=password]').inputValue()===password,'Mismatch retains the password in the current DOM'); + await page.locator('[name=confirmation]').fill(password); + await Promise.all([page.waitForURL(base+'/login'),page.getByRole('button',{name:'Create administrator account',exact:true}).click()]); + await page.getByText('Administrator account created. Sign in to continue.').waitFor(); + await shot(page,'02-sign-in'); + await signIn(page,'demo-admin');await shot(page,'03-create-passkey'); + check(await page.locator('.section-nav').count()===0,'Primary-only layout has no portal navigation'); + check((await page.request.get(base+'/admin/accounts',{maxRedirects:0})).status()===302,'Primary-only direct admin request is routed to verification'); + check(await mutate(page,'/credentials',{label:'Denied password only',days:'1'})===403,'No passkeys: issuance denied'); + await page.evaluate(()=>{window.savedCreate=navigator.credentials.create.bind(navigator.credentials);navigator.credentials.create=async()=>{throw new DOMException('Interaction did not complete','NotAllowedError');};}); + await page.getByRole('button',{name:'Create passkey',exact:true}).click(); + try { + await page.locator('#security-status').filter({hasText:'may have been cancelled'}).waitFor(); + } catch (error) { + console.error('P0_PASSKEY_CANCELLATION_STATUS',await page.locator('#security-status').textContent()); + throw error; + } + await page.evaluate(()=>{navigator.credentials.create=window.savedCreate;}); + let lostRegistrationResponse=false; + await cdp.send('Fetch.enable',{patterns:[{urlPattern:'*webauthn/register',requestStage:'Response'}]}); + cdp.on('Fetch.requestPaused',async event=>{ + if(event.responseStatusCode===200){lostRegistrationResponse=true;await cdp.send('Fetch.failRequest',{requestId:event.requestId,errorReason:'Failed'});} + else await cdp.send('Fetch.continueResponse',{requestId:event.requestId}); + }); + await enroll(page);await cdp.send('Fetch.disable'); + check(lostRegistrationResponse,'A real committed registration with a lost response is reconciled'); + await shot(page,'04-passkey-saved'); + check(!(await page.locator('main').innerText()).includes('No passkeys are enrolled.'),'Registration clears stale empty state'); + check(await mutate(page,'/credentials',{label:'Denied registration only',days:'1'})===403,'Registration alone: issuance denied'); + await verify(page);await page.getByRole('heading',{name:'Overview',exact:true}).waitFor(); + await shot(page,'05-overview'); + await page.setViewportSize({width:320,height:900}); + const menu = page.getByText('Menu',{exact:true}).and(page.locator('summary')); + await page.waitForFunction(()=>!document.querySelector('.section-disclosure').open); + await menu.focus(); + await menu.press('Enter'); + await page.waitForFunction(()=>document.querySelector('.section-disclosure').open); + check(await menu.evaluate(element=>document.activeElement===element),'Keyboard opens mobile navigation'); + await menu.press('Escape'); + check(await menu.evaluate(element=>document.activeElement===element && !element.parentElement.open),'Escape closes navigation and returns focus'); + await page.emulateMedia({colorScheme:'dark',reducedMotion:'reduce',forcedColors:'active'}); + check(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1),'Dark forced-color view fits width with reduced motion'); + await page.emulateMedia({colorScheme:'light',reducedMotion:'no-preference',forcedColors:'none'}); + await page.setViewportSize({width:1280,height:900}); + await page.getByRole('link',{name:'Open server administration',exact:true}).click(); + await shot(page,'06-server-administration'); + await page.goto(base+'/admin/accounts');await shot(page,'07-accounts'); + await page.goto(base+'/admin/accounts/new');await shot(page,'08-create-account'); + await provisionAccount(page,base,'demo-user','Demo User',password); + await shot(page,'09-account-handoff'); + await page.goto(base+'/collections/new?component=VJOURNAL');await shot(page,'10-resource-type'); + const calendar=await createCollection(page,base,'Demo calendar','VEVENT'); + await createCollection(page,base,'Demo tasks','VTODO');await shot(page,'11-empty-task-list'); + const journal=await createCollection(page,base,'Demo journal','VJOURNAL'); + await page.goto(base+'/collections/'+calendar); + const contextualConnect = page.locator('main').getByRole('link',{name:'Connect an app',exact:true}); + const connectionStart = new URL(await contextualConnect.getAttribute('href'),base); + check(connectionStart.searchParams.get('resource')===calendar,'The primary resource action carries the selected resource'); + await page.goto(base+'/collections');await shot(page,'12-resources'); + await grantDirect(page,base,calendar,'demo-user','READ');await shot(page,'13-sharing'); + const grant = page.locator('form').filter({has:page.locator('input[name=username]:not([type=hidden])')}); + await grant.locator('..').locator('summary').click(); + await grant.locator('input[name=username]').fill('unknown-demo-user'); + const shareError = await Promise.all([page.waitForNavigation(),grant.getByRole('button',{name:'Grant account access',exact:true}).click()]); + check(shareError[0].status()===400,'Unknown recipient returns the editable form'); + check(await page.locator('.section-nav [aria-current=page]').textContent()==='Calendars, tasks & journals','Collection navigation stays current after validation'); + check(await page.locator('#direct-add-username').inputValue()==='unknown-demo-user','Recipient input survives validation'); + await shot(page,'27-sharing-error'); + await page.getByRole('link',{name:'Remove direct grant',exact:true}).click(); + await page.getByRole('heading',{name:'Remove direct access for demo-user?',exact:true}).waitFor(); + check(await page.getByRole('button',{name:'Remove direct grant',exact:true}).isVisible(),'Sharing removal requires a named final action'); + await shot(page,'28-share-removal-review'); + await page.getByRole('link',{name:'Cancel',exact:true}).click(); + check(await page.getByText('demo-user',{exact:true}).count()>=1,'Cancel preserves the grant'); + await page.goto(base+'/security');await shot(page,'14-security'); + await page.goto(base+'/security/recovery/codes/new'); + await page.getByRole('button',{name:'Generate ten codes',exact:true}).click(); + await page.getByRole('heading',{name:'Save your recovery codes',exact:true}).waitFor(); + await shot(page,'15-recovery-codes',[page.locator('[data-one-time-secret] code')]); + check(await page.locator('main ol code').count()===10,'Protected recovery workflow issues ten one-time codes'); + await page.goto(base+'/security/recovery/codes/new'); + await page.locator('input[name=replace]').check(); + await lostIssuance(page,'already generated recovery codes'); + await page.goto(base+'/connections');await shot(page,'16-connect-an-app'); + await page.getByRole('link',{name:'GNOME Calendar',exact:true}).click();await shot(page,'17-client-configuration'); + check(await page.locator('#server-address').inputValue()===base+'/dav/','Configured root/subpath server address is correct'); + check(await page.locator('#gnome-address').inputValue()===base.replace('://','://demo-admin@')+'/dav/','GNOME address retains username and prefix'); + await page.getByRole('button',{name:'Copy username',exact:true}).click(); + await page.getByRole('status').filter({hasText:'Username copied.'}).waitFor(); + check(await page.evaluate(()=>navigator.clipboard.readText())==='demo-admin','Username copied accurately'); + await page.getByRole('button',{name:'Copy address',exact:true}).click(); + await page.getByRole('status').filter({hasText:'Server address copied.'}).waitFor(); + check(await page.evaluate(()=>navigator.clipboard.readText())===base+'/dav/','Server address copied accurately'); + await page.getByRole('link',{name:'Create application password',exact:true}).click();await shot(page,'18-create-application-password'); + await page.locator('[name=label]').fill('GNOME on demo laptop'); + const intent=await page.locator('[name=intent]').inputValue(); + await page.getByRole('button',{name:'Create application password',exact:true}).click(); + await page.getByRole('heading',{name:'Application password created',exact:true}).waitFor(); + const secret=await page.locator('#issued-secret').innerText();privateValues.push(secret); + writeFileSync('/fixture/issued-password',secret,{mode:0o600}); + await shot(page,'19-password-created',[page.locator('#issued-secret')]); + await page.evaluate(()=>window.dispatchEvent(new Event('blur'))); + check(await page.locator('#issued-secret').innerText()===secret,'Focus loss keeps the one-time password in the open result'); + await page.getByRole('button',{name:'Copy password',exact:true}).click(); + await page.getByRole('status').filter({hasText:'Password copied.'}).waitFor(); + check(await page.evaluate(()=>navigator.clipboard.readText())===secret,'Clipboard contains issued password'); + await page.evaluate(()=>{window.savedClipboard=navigator.clipboard.writeText.bind(navigator.clipboard);navigator.clipboard.writeText=async()=>{throw new DOMException('Denied','NotAllowedError');};}); + await page.getByRole('button',{name:'Copy password',exact:true}).click(); + await page.getByRole('status').filter({hasText:'Copy failed.'}).waitFor(); + check(await page.getByRole('button',{name:'Copy password',exact:true}).evaluate(button=>document.activeElement===button),'Clipboard failure keeps keyboard focus at the action'); + await page.evaluate(()=>{navigator.clipboard.writeText=window.savedClipboard;}); + const receipt = await page.evaluate(async ({path,intent})=>{ + const token=document.querySelector('meta[name=csrf-token]').content; + const response=await fetch(path,{method:'POST',headers:{'X-CSRF-TOKEN':token},body:new URLSearchParams({label:'GNOME on demo laptop',days:90,client:'gnome',from:'connect',intent})}); + return await response.text(); + },{path:prefix+'/credentials',intent}); + check(receipt.includes('already created an application password') && !receipt.includes(secret),'Same intent produces a safe receipt'); + await page.getByRole('link',{name:'Done',exact:true}).click(); + check(page.url().includes('client=gnome'),'Selected client preserved through issuance'); + check(!(await page.content()).includes(secret),'Secret absent from subsequent response'); + await page.goto(base+'/security/credentials'); + check(await page.getByRole('link',{name:'Create application password',exact:true}).isVisible(),'Password inspection has a separate creation link'); + await shot(page,'29-credential-management'); + await page.getByRole('link',{name:'Create application password',exact:true}).click(); + await page.locator('[name=label]').fill('Interrupted browser request'); + await lostIssuance(page,'already created an application password'); + await page.goto(base+'/security/credentials'); + check(await page.getByText('Interrupted browser request',{exact:true}).count()===1,'Ambiguous issuance creates exactly one visible credential'); + await page.goto(base+'/portability?destination='+journal);await shot(page,'20-import-destination'); + await page.locator('input[type=file]').setInputFiles({name:'synthetic-journal.ics',mimeType:'text/calendar',buffer:Buffer.from('BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//BusyStack//Acceptance//EN\r\nBEGIN:VJOURNAL\r\nUID:ux-journal-fixture\r\nDTSTAMP:20261126T180000Z\r\nDTSTART;VALUE=DATE:20261126\r\nSUMMARY:Demo journal entry\r\nEND:VJOURNAL\r\nEND:VCALENDAR\r\n')}); + await Promise.all([page.waitForURL(/\/portability\/import\/[0-9a-f-]+/),page.getByRole('button',{name:'Validate and preview import'}).click()]); + await shot(page,'21-import-preview'); + await page.locator('input[name=confirmed]').check(); + await Promise.all([page.waitForNavigation(),page.getByRole('button',{name:'Confirm import'}).click()]); + await page.getByRole('heading',{name:'Import results',exact:true}).waitFor(); + await shot(page,'22-import-result'); + const unavailable = await page.goto(base+'/portability/import/00000000-0000-4000-8000-000000000000'); + check(unavailable.status()===412,'An unavailable import report keeps its error status'); + await page.getByRole('heading',{name:'Import report unavailable',exact:true}).waitFor(); + await shot(page,'30-import-report-unavailable'); + await page.getByRole('link',{name:'Return to this workflow',exact:true}).click(); + check(new URL(page.url()).pathname===prefix+'/portability','Terminal report recovery opens a usable import picker'); + await page.goto(base+'/admin/audit');await shot(page,'23-audit'); + await page.goto(base+'/admin/diagnostics');await shot(page,'24-diagnostics'); + await page.goto(base+'/admin/oauth-clients'); + const nativeName = 'Demo native app'; + await page.getByLabel('Client ID',{exact:true}).fill('demo-native'); + await page.getByLabel('Name',{exact:true}).fill(nativeName); + const nativeRedirects = page.locator('#native-app-redirects'); + await nativeRedirects.fill('not a URI'); + const [invalidRegistration] = await Promise.all([ + page.waitForResponse(response=>response.url()===base+'/admin/oauth-clients' && response.request().method()==='POST'), + page.getByRole('button',{name:'Register application',exact:true}).click() + ]); + check(invalidRegistration.status()===400,'Invalid native application redirect returns editable validation'); + check(await page.getByLabel('Name',{exact:true}).inputValue()===nativeName,'Native application name survives validation'); + check(await nativeRedirects.getAttribute('aria-describedby')==='native-app-redirects-error','Native redirect error is associated with its editable field'); + await nativeRedirects.fill('http://127.0.0.1:32123/callback'); + await Promise.all([page.waitForNavigation(),page.getByRole('button',{name:'Register application',exact:true}).click()]); + const nativeRow = page.getByRole('row').filter({hasText:nativeName}); + await nativeRow.getByRole('link',{name:'Remove registration',exact:true}).click(); + await page.getByRole('heading',{name:'Remove '+nativeName+'?',exact:true}).waitFor(); + check(await page.getByText('All user grants for this application will be revoked.',{exact:false}).isVisible(),'Application registration review names the server-wide effect'); + await page.getByRole('link',{name:'Cancel',exact:true}).click(); + check(await nativeRow.count()===1,'Cancel preserves the application registration'); + await nativeRow.getByRole('link',{name:'Remove registration',exact:true}).click(); + await Promise.all([page.waitForNavigation(),page.getByRole('button',{name:'Remove application registration',exact:true}).click()]); + check(await nativeRow.count()===0,'Explicit confirmation removes the application registration'); + const userContext=await browser.newContext({viewport:{width:1280,height:900},colorScheme:'light'}); + const user=await userContext.newPage();await virtual(userContext,user); + connectionStart.searchParams.set('client','thunderbird'); + await user.goto(connectionStart.toString()); + await signIn(user,'demo-user',true);await enroll(user);await verify(user); + const continued=new URL(user.url()); + check(continued.origin===new URL(base).origin && continued.pathname===prefix+'/connections' && continued.searchParams.get('client')==='thunderbird' && continued.searchParams.get('resource')===calendar, 'Primary/session rotation preserves the selected client and shared resource'); + check(await user.locator('#selected-resource-address').count()===1,'The shared resource address is available after verification'); + await user.goto(base+'/');await shot(user,'25-shared-overview'); + check(await user.getByRole('link',{name:'Server administration',exact:true}).count()===0,'No administrator UI for ordinary user'); + check(/shared/i.test(await user.locator('main').innerText()),'Shared collections offered in onboarding'); + check(!(await user.locator('main').innerText()).includes('Create a calendar or task list'),'Shared recipient not forced to create collection'); + const clientStatus=await user.evaluate(async path=>(await fetch(path)).status,prefix+'/admin/accounts');check(clientStatus===403,'Ordinary account denied administration'); + await user.getByRole('button',{name:'Sign out',exact:true}).click(); + await signIn(user,'demo-user');await user.getByRole('heading',{name:'Verify your passkey',exact:true}).waitFor();await shot(user,'26-returning-verification'); + check(await user.getByRole('button',{name:'Create passkey',exact:true}).count()===0,'Returning user verifies existing passkey');await verify(user); + await user.goto(base+'/security/passkeys');await user.getByRole('link',{name:/Remove passkey/}).click(); + await user.getByRole('button',{name:'Remove passkey',exact:true}).click(); + await user.getByRole('heading',{name:'Create a passkey',exact:true}).waitFor(); + const after=await user.evaluate(async path=>(await fetch(path)).json(),prefix+'/auth/state'); + check(!after.enrolled && !after.verified,'Last removal invalidates the completed browser proof'); + check(await mutate(user,'/credentials',{label:'Removed factor',days:'1'})===403,'Removed key does not authorize issuance'); + check(errors.length===0,'No page script errors'); + check(remoteAssets.length===0,'No externally loaded frontend resources'); + writeFileSync(output+'/browser-result.json',JSON.stringify({status:'passed',assertions,playwright:'1.61.1',chromium:browser.version(),base,manualFirefoxBitwarden:'pending',screenshots:30},null,2)); + console.log('P0_BROWSER_PASSED assertions='+assertions+' screenshots=30'); +} catch(error) { + let diagnostic=String(error.stack||error); + for(const value of privateValues)diagnostic=diagnostic.replaceAll(value,'[redacted]'); + diagnostic=diagnostic.replace(/JSESSIONID=[^;\s'"]+/g,'JSESSIONID=[redacted]'); + console.error('P0_BROWSER_FAILED '+diagnostic);process.exitCode=1; +} finally {await browser.close();} diff --git a/qualification/p0/build.py b/qualification/p0/build.py new file mode 100644 index 0000000..2d62372 --- /dev/null +++ b/qualification/p0/build.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +"""Local qualification build with committed runtime inputs; leaves unrelated qualification edits intact. + +The official release builder still requires a completely clean tree. This local helper +checks every runtime/build input against HEAD and records that distinction explicitly. +""" +import argparse,hashlib,importlib.util,json,re,shutil,subprocess,zipfile +from pathlib import Path +ROOT=Path(__file__).resolve().parents[2] + +def descriptor_digest(config): + """A classic local Docker image need not have an OCI descriptor/registry digest.""" + descriptor=config.get('Descriptor') + if descriptor is None:return None + digest=descriptor.get('digest') if isinstance(descriptor,dict) else None + assert isinstance(digest,str) and re.fullmatch(r'sha256:[0-9a-f]{64}',digest),'Invalid OCI descriptor digest' + return digest + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + output=parser.add_mutually_exclusive_group(required=True) + output.add_argument('--image',help='Optional named local test image') + output.add_argument('--iidfile',type=Path,help='Write an immutable image ID without adding a tag') + args=parser.parse_args() + revision=subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True).strip() + dirty=subprocess.check_output(['git','status','--porcelain=v1','--untracked-files=all'],cwd=ROOT,text=True).splitlines() + assert all(line[3:].startswith('qualification/') for line in dirty),'Commit implementation and documentation before a local qualification image build' + names=subprocess.check_output(['git','ls-files','src/main','pom.xml','Dockerfile','.mvn','mvnw','LICENSE','NOTICE','THIRD-PARTY-NOTICES','licenses'],cwd=ROOT,text=True).splitlines() + for name in names:assert (ROOT/name).read_bytes()==subprocess.check_output(['git','show',revision+':'+name],cwd=ROOT),'Uncommitted runtime input: '+name + spec=importlib.util.spec_from_file_location('builder',ROOT/'scripts/build-image.py');builder=importlib.util.module_from_spec(spec);spec.loader.exec_module(builder) + version=builder.versions.resolve(ROOT);jar=ROOT/'target'/builder.versions.jar_name(version);checksum,sbom=builder.inspect_jar(jar,version) + context=ROOT/'target/p0-image-context' + if context.exists():shutil.rmtree(context) + inputs=context/'.image-input';inputs.mkdir(parents=True) + shutil.copyfile(ROOT/'Dockerfile',context/'Dockerfile');shutil.copyfile(jar,inputs/'application.jar');(inputs/'runtime-dependency-inventory.json').write_bytes(sbom) + for name in ('LICENSE','NOTICE','THIRD-PARTY-NOTICES'):shutil.copyfile(ROOT/name,inputs/name) + with zipfile.ZipFile(jar) as archive: + for name in archive.namelist(): + if name.startswith('META-INF/licenses/') and not name.endswith('/'): + target=inputs/'third-party'/name.removeprefix('META-INF/licenses/');target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(archive.read(name)) + (inputs/'version').write_text(version+'\n');(inputs/'revision').write_text(revision+'\n');(inputs/'SHA256SUMS').write_text(checksum+' application.jar\n') + image_output=['--tag',args.image] if args.image else ['--iidfile',str(args.iidfile.resolve())] + subprocess.run(['docker','build','--platform','linux/amd64','--build-arg','APPLICATION_VERSION='+version,'--build-arg','SOURCE_REVISION='+revision,*image_output,str(context)],check=True) + image=args.image if args.image else args.iidfile.read_text().strip() + config=builder.identity(image,version,revision,checksum) + proof={'qualificationKind':'local-unpublished','sourceCommit':revision,'imageId':config['Id'],'descriptorDigest':descriptor_digest(config),'jarSha256':checksum,'runtimeInputs':{name:hashlib.sha256((ROOT/name).read_bytes()).hexdigest() for name in names},'uncommittedQualificationPaths':[line[3:] for line in dirty]} + (ROOT/'target/p0-image-inputs.json').write_text(json.dumps(proof,indent=2,sort_keys=True)+'\n');print(json.dumps({k:v for k,v in proof.items() if k!='runtimeInputs'},indent=2)) +if __name__=='__main__':main() diff --git a/qualification/p0/manual.py b/qualification/p0/manual.py new file mode 100644 index 0000000..dfdbc42 --- /dev/null +++ b/qualification/p0/manual.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +"""Prepare a fresh operator-controlled browser and passkey acceptance deployment; no account seeding.""" +import argparse,json,os,secrets,shutil,socket,subprocess,sys +from pathlib import Path +from ipaddress import IPv4Network +ROOT=Path(__file__).resolve().parents[2];sys.path.insert(0,str(ROOT/'qualification/passkeys'));import run as established +ops=established.operations + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--deployment-directory',type=Path,required=True);parser.add_argument('--output',type=Path,required=True);parser.add_argument('--network-subnet',type=IPv4Network,help='Optional disposable fixture subnet when Docker default pools are exhausted');args=parser.parse_args() + directory=args.output.resolve();directory.mkdir(mode=0o700,parents=True,exist_ok=False);install=directory/'install';shutil.copytree(args.deployment_directory,install) + environment=os.environ.copy() + for name in ('database-password','admin-password'): + path=directory/name;path.write_text(secrets.token_urlsafe(32)+'\n');path.chmod(0o444) + established.certificates(directory,environment) + with socket.socket() as listener:listener.bind(('127.0.0.1',0));port=listener.getsockname()[1] + base=f'https://localhost:{port}' + template=(install/'nginx-root.conf.example').read_text().replace('listen 443 ssl;','listen 8443 ssl;').replace('server_name calendar.example.org;','server_name localhost;').replace('calendar.example.org',f'localhost:{port}').replace('/etc/ssl/caldav/fullchain.pem','/tls/server.pem').replace('/etc/ssl/caldav/privkey.pem','/tls/server.key').replace('http://127.0.0.1:8080','http://application:8080') + config='worker_processes 1;\npid /tmp/nginx.pid;\nerror_log /dev/stderr warn;\nevents {worker_connections 128;}\nhttp {access_log off;client_body_temp_path /tmp/client_temp;proxy_temp_path /tmp/proxy_temp;fastcgi_temp_path /tmp/fastcgi_temp;uwsgi_temp_path /tmp/uwsgi_temp;scgi_temp_path /tmp/scgi_temp;\n'+template+'}\n';(directory/'nginx.conf').write_text(config);(directory/'server.key').chmod(0o444) + proxy={'image':established.proxy.IMAGE,'user':'101:101','entrypoint':['nginx','-g','daemon off;'],'ports':[f'127.0.0.1:{port}:8443'],'depends_on':{'application':{'condition':'service_healthy'}},'volumes':[f'{directory}/nginx.conf:/etc/nginx/nginx.conf:ro',f'{directory}/server.pem:/tls/server.pem:ro',f'{directory}/server.key:/tls/server.key:ro'],'read_only':True,'tmpfs':['/tmp:rw,nosuid,nodev,noexec,size=32m'],'mem_limit':'128m','cap_drop':['ALL'],'security_opt':['no-new-privileges:true']} + (install/'compose.manual.yaml').write_text('services:\n application:\n ports: !override []\n reverse-proxy: '+json.dumps(proxy)+'\n') + if args.network_subnet: + assert args.network_subnet.is_private, 'Choose a private unallocated fixture subnet' + with (install/'compose.manual.yaml').open('a') as settings: + settings.write('networks:\n default:\n ipam:\n config:\n - subnet: '+str(args.network_subnet)+'\n') + values={'COMPOSE_PROJECT_NAME':'busystack-p0-manual-'+secrets.token_hex(6),'COMPOSE_FILE':'compose.yaml:compose.manual.yaml','BUSYSTACK_DATABASE_PASSWORD_FILE':str(directory/'database-password'),'BUSYSTACK_POSTGRES_ADMIN_PASSWORD_FILE':str(directory/'admin-password'),'BUSYSTACK_PUBLIC_BASE_URL':base,'BUSYSTACK_ISSUER':base} + (install/'.env').write_text(''.join(name+'='+value+'\n' for name,value in values.items()));(install/'.env').chmod(0o600) + def command(*args):subprocess.run(args,cwd=install,check=True) + command('docker','compose','config','--quiet');command('docker','compose','pull','--policy','missing');command('docker','compose','up','-d','--no-build','--wait','--wait-timeout','240') + established.ready(base,directory/'ca.pem',True) + subprocess.run(['openssl','x509','-checkend','60','-noout','-in',str(directory/'server.pem')],check=True) + with established.tls.opener(directory/'ca.pem').open(base+'/setup',timeout=10) as setup: + assert setup.status==200 and b'Set up BusyStack' in setup.read(), 'Protected setup did not render' + (directory/'acceptance.json').write_text(json.dumps({'status':'ready-manual-acceptance-pending','url':base,'directory':str(install),'ca':str(directory/'ca.pem'),'noAccountCreated':True,'setupVerifiedOverTrustedTls':True,'initializationCommand':'bash scripts/initialize.sh','cleanup':'docker compose down --volumes --remove-orphans'},indent=2)+'\n') + print((directory/'acceptance.json').read_text()) +if __name__=='__main__':main() diff --git a/qualification/p0/package.py b/qualification/p0/package.py new file mode 100644 index 0000000..f8d81d6 --- /dev/null +++ b/qualification/p0/package.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +"""Stage an explicitly unpublished local release in the production asset format.""" +import argparse,gzip,hashlib,importlib.util,json,shutil,subprocess,sys,tarfile +from pathlib import Path +ROOT=Path(__file__).resolve().parents[2];sys.path.insert(0,str(ROOT/'scripts')) +import release_source,release_version +spec=importlib.util.spec_from_file_location('bundle',ROOT/'scripts/release-bundle.py');bundle=importlib.util.module_from_spec(spec);spec.loader.exec_module(bundle) +spec=importlib.util.spec_from_file_location('local_builder',Path(__file__).with_name('build.py'));local_builder=importlib.util.module_from_spec(spec);spec.loader.exec_module(local_builder) + +def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest() + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--image',required=True);parser.add_argument('--output',type=Path,required=True);args=parser.parse_args() + revision=subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True).strip();source=release_source.Snapshot(revision,ROOT);version=source.version + config=json.loads(subprocess.check_output(['docker','image','inspect',args.image],text=True))[0] + manifest_digest=local_builder.descriptor_digest(config);repository='ghcr.io/'+release_version.REPOSITORY + # An owned local alias exercises the official image-reference shape without a push. + if manifest_digest is not None: + alias=repository+':p0-local-'+revision[:12] + subprocess.run(['docker','image','tag',args.image,alias],check=True) + image=repository+':'+version+'@'+manifest_digest if manifest_digest is not None else config['Id'] + resolved=json.loads(subprocess.check_output(['docker','image','inspect',image],text=True))[0] + assert resolved['Id']==config['Id'],'Local canonical digest must resolve to the tested image' + runtime=config['Config']['Labels']['org.opencontainers.image.revision'] + for name in source.files: + if name.startswith(('src/main/','licenses/')) or name in ('pom.xml','Dockerfile','LICENSE','NOTICE','THIRD-PARTY-NOTICES'): + assert source.read(name)==subprocess.check_output(['git','show',runtime+':'+name],cwd=ROOT),'Runtime differs from image source: '+name + jar=ROOT/'target'/release_version.jar_name(version);checksum,sbom=bundle.candidate.builder.inspect_jar(jar,version) + actual=subprocess.check_output(['docker','run','--rm','--network','none','--entrypoint','sha256sum',args.image,'/opt/busystack/application.jar'],text=True).split()[0];assert actual==checksum + args.output.mkdir(parents=True,exist_ok=False);assets=args.output/'assets';assets.mkdir() + sbom_path=assets/'sbom.cdx.json';sbom_path.write_bytes(sbom) + identity={'qualificationKind':'local-unpublished','version':version,'sourceCommit':revision,'runtimeCommit':runtime,'image':image,'imageId':config['Id'],'jarSha256':checksum,'publicDownloadAcceptance':'not-performed; no publication authorized'} + compose=source.read('compose.yaml').decode();a=compose.index(' build:\n');b=compose.index('\n',compose.index(' image: ${BUSYSTACK_APPLICATION_IMAGE:',a))+1 + compose=compose[:a]+f' image: {image}\n platform: linux/amd64\n'+compose[b:] + files,used,notices=bundle.deployment_files(source,version,compose,identity,sbom_path) + name=release_version.deployment_name(version);archive=assets/name;archive.write_bytes(bundle.tar_bytes(files,f'caldav-server-{version}-deploy/')) + (assets/'notices.tar.gz').write_bytes(bundle.tar_bytes(notices));shutil.copyfile(jar,assets/jar.name) + asset_hashes={p.name:digest(p) for p in assets.iterdir()} + manifest={**identity,'schemaVersion':2,'sourceTree':subprocess.check_output(['git','rev-parse',revision+'^{tree}'],text=True).strip(), + 'sourceSnapshotSha256':hashlib.sha256(gzip.compress(release_source.archive(revision,ROOT),mtime=0)).hexdigest(), + 'sourceInputs':{name:hashlib.sha256(source.read(name)).hexdigest() for name in sorted(used)}, + 'deploymentFiles':{name:hashlib.sha256(data).hexdigest() for name,data in files.items()}, + 'repository':'https://github.com/'+release_version.REPOSITORY, + 'verification':{'status':'local-unpublished','run':None,'attempt':None,'url':None}, + 'container':{'image':image,'registryManifestDigest':manifest_digest,'localTestedImageId':config['Id'],'platform':'linux/amd64','published':False}, + 'jar':{'name':jar.name,'sha256':checksum},'deployment':{'name':name,'sha256':digest(archive)},'assets':asset_hashes} + manifest_file=assets/'release-manifest.json';manifest_file.write_text(json.dumps(manifest,indent=2,sort_keys=True)+'\n') + sums={**asset_hashes,'release-manifest.json':digest(manifest_file)} + (assets/'SHA256SUMS').write_text(''.join(sha+' '+name+'\n' for name,sha in sorted(sums.items()))) + bundle.validate_assets(assets,version,revision,allow_local_unpublished=True) + with tarfile.open(archive) as packed:packed.extractall(args.output,filter='data') + extracted=args.output/f'caldav-server-{version}-deploy' + bundle.validate_guide({str(p.relative_to(extracted)):p.read_bytes() for p in extracted.rglob('*') if p.is_file()}) + print(json.dumps({'status':'validated-local-unpublished','source':revision,'runtime':runtime,'image':image,'deploymentSha256':digest(archive),'assets':str(assets),'directory':str(extracted)},indent=2)) +if __name__=='__main__':main() diff --git a/qualification/p0/run.py b/qualification/p0/run.py new file mode 100644 index 0000000..ae222d0 --- /dev/null +++ b/qualification/p0/run.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Real HTTPS protected initialization and screenshot qualification; owned disposable projects only.""" +import argparse, importlib.util, json, os +from pathlib import Path +from ipaddress import IPv4Network +import re, secrets, socket, subprocess, sys, tempfile +ROOT=Path(__file__).resolve().parents[2] +sys.path.insert(0,str(ROOT/'qualification/passkeys')) +import run as established +operations=established.operations + +def proxy_override(deployment, fixture, base, port): + from urllib.parse import urlsplit + public = urlsplit(base) + name = 'nginx-subpath.conf.example' if public.path else 'nginx-root.conf.example' + example = deployment / name + if not example.exists(): example = deployment / 'deployment' / name + template = example.read_text().replace('listen 443 ssl;', 'listen 8443 ssl;') + template = template.replace('server_name calendar.example.org;', 'server_name localhost;') + template = template.replace('calendar.example.org', public.netloc) + if public.path: template = template.replace('/calendar', public.path) + template = template.replace('/etc/ssl/caldav/fullchain.pem', '/tls/server.pem').replace('/etc/ssl/caldav/privkey.pem', '/tls/server.key') + template = template.replace('http://127.0.0.1:8080', 'http://application:8080') + (fixture / 'server.key').chmod(0o444) + (fixture / 'nginx.conf').write_text('worker_processes 1;\npid /tmp/nginx.pid;\nerror_log /dev/stderr warn;\nevents {worker_connections 128;}\nhttp {access_log off;client_body_temp_path /tmp/client_temp;proxy_temp_path /tmp/proxy_temp;fastcgi_temp_path /tmp/fastcgi_temp;uwsgi_temp_path /tmp/uwsgi_temp;scgi_temp_path /tmp/scgi_temp;\n' + template + '}\n') + proxy = {'image': established.proxy.IMAGE, 'user': '101:101', 'entrypoint': ['nginx', '-g', 'daemon off;'], + 'ports': [f'127.0.0.1:{port}:8443'], 'depends_on': {'application': {'condition': 'service_healthy'}}, + 'volumes': [str(fixture / 'nginx.conf') + ':/etc/nginx/nginx.conf:ro', str(fixture / 'server.pem') + ':/tls/server.pem:ro', str(fixture / 'server.key') + ':/tls/server.key:ro'], + 'read_only': True, 'tmpfs': ['/tmp:rw,nosuid,nodev,noexec,size=32m'], 'mem_limit': '128m', + 'cap_drop': ['ALL'], 'security_opt': ['no-new-privileges:true']} + return 'services:\n application:\n ports: !override []\n reverse-proxy: ' + json.dumps(proxy) + '\n' + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('--application-image',required=True) + parser.add_argument('--browser-image',default='busystack-passkey-browser:corrective') + parser.add_argument('--deployment-directory',type=Path,default=ROOT) + parser.add_argument('--context-path',default='',choices=('', '/team')) + parser.add_argument('--clients',action='store_true',help='Run real Python and native Thunderbird profiles using the browser-issued application password') + parser.add_argument('--client-python',default=str(ROOT/'.client-venv/bin/python')) + parser.add_argument('--thunderbird-binary',default=str(ROOT/'.client-tools/thunderbird/thunderbird')) + parser.add_argument('--proxy',action='store_true',help='Use the package HTTPS proxy example, preserving root or /team paths') + parser.add_argument('--network-subnet',type=IPv4Network,help='Optional disposable fixture subnet when Docker default pools are exhausted') + parser.add_argument('--output',type=Path,default=ROOT/'target/qualification/p0') + args=parser.parse_args(); args.output.mkdir(parents=True,exist_ok=True) + operations.ROOT=args.deployment_directory.resolve() + environment=os.environ.copy();environment.update(operations.development_environment(args.application_image)) + with tempfile.TemporaryDirectory(prefix='busystack-p0-') as temporary: + fixture=Path(temporary);fixture.chmod(0o700) + for name in ('database-password','admin-password','password'): + f=fixture/name;f.write_text(secrets.token_urlsafe(32)+'\n');f.chmod(0o600 if name=='password' else 0o444) + established.certificates(fixture,environment) + with socket.socket() as listener:listener.bind(('127.0.0.1',0));port=listener.getsockname()[1] + base=f'https://localhost:{port}'+args.context_path + override=fixture/'override.yaml' + override.write_text('services:\n application:\n ports: !override\n - "127.0.0.1:'+str(port)+':8443"\n environment:\n SERVER_PORT: "8443"\n SERVER_SSL_ENABLED: "true"\n SERVER_SSL_KEY_STORE: file:/tls/server.p12\n SERVER_SSL_KEY_STORE_TYPE: PKCS12\n volumes:\n - '+json.dumps(str(fixture/'server.p12')+':/tls/server.p12:ro')+'\n secrets:\n - source: tls_password\n target: server.ssl.key-store-password\n healthcheck:\n disable: true\nsecrets:\n tls_password:\n file: '+json.dumps(str(fixture/'server-password'))+'\n') + if args.proxy: override.write_text(proxy_override(operations.ROOT,fixture,base,port)) + if args.network_subnet: + assert args.network_subnet.is_private, 'Choose a private unallocated fixture subnet' + with override.open('a') as settings: + settings.write('networks:\n default:\n ipam:\n config:\n - subnet: '+str(args.network_subnet)+'\n') + environment.update(COMPOSE_FILE=str(operations.ROOT/'compose.yaml')+':'+str(override),COMPOSE_PROJECT_NAME='busystack-p0-'+secrets.token_hex(6),COMPOSE_PATH_SEPARATOR=':',BUSYSTACK_DATABASE_PASSWORD_FILE=str(fixture/'database-password'),BUSYSTACK_POSTGRES_ADMIN_PASSWORD_FILE=str(fixture/'admin-password'),BUSYSTACK_PUBLIC_BASE_URL=base,BUSYSTACK_ISSUER=base) + try: + print('P0_CONFIG_VALIDATION',flush=True) + operations.compose(environment,'config','--quiet') + configuration=json.loads(operations.execute(['docker','compose','--profile','operator','config','--format','json'],environment)) + assert configuration['services']['initialization']['logging']['driver']=='none' + assert configuration['services']['application'].get('logging',{}).get('driver')!='none' + if args.proxy: operations.compose(environment,'pull','--policy','missing') + if args.proxy: + # Exercise the guide's complete startup command, including both + # production health checks and the fixture's supplied HTTPS proxy. + operations.compose(environment,'up','-d','--no-build','--wait','--wait-timeout','240') + operations.compose(environment,'ps') + else: + operations.compose(environment,'up','-d','--no-build','--wait','--wait-timeout','120','database') + operations.compose(environment,'up','-d','--no-build','application') + established.ready(base,fixture/'ca.pem',args.proxy) + print('P0_HTTPS_READY',flush=True) + print('P0_LOCAL_ISSUANCE',flush=True) + result=operations.execute(['bash','scripts/initialize.sh'],environment) + codes=re.findall(r'(?m)^[A-Za-z0-9_-]{43}$',result);assert len(codes)==1,'Expected exactly one operator-only code' + code=fixture/'initialization-code';code.write_text(codes[0]);code.chmod(0o600) + issued=fixture/'issued-password';issued.touch(mode=0o600) + command=['docker','run','--rm','--network','host','--volume',str(fixture/'ca.pem')+':/fixture/ca.pem:ro','--volume',str(fixture/'password')+':/fixture/password:ro','--volume',str(code)+':/fixture/initialization-code:ro','--volume',str(issued)+':/fixture/issued-password:rw','--volume',str(args.output.resolve())+':/evidence','--volume',str(ROOT/'qualification/p0/browser.mjs')+':/qualification/passkeys.mjs:ro','--volume',str(ROOT/'qualification/passkeys/portal-helpers.mjs')+':/qualification/portal-helpers.mjs:ro','--env','BUSYSTACK_BROWSER_CA_FILE=/fixture/ca.pem','--env','NODE_EXTRA_CA_CERTS=/fixture/ca.pem','--env','BUSYSTACK_BROWSER_URL='+base,args.browser_image] + print('P0_BROWSER_START',flush=True) + subprocess.run(command,check=True,timeout=600) + if args.clients: + client_environment=os.environ.copy() + client_environment.update(BUSYSTACK_CLIENT_URL=base+'/dav/',BUSYSTACK_CLIENT_USER='demo-admin', + BUSYSTACK_CLIENT_SECRET_FILE=str(issued),BUSYSTACK_CLIENT_CA=str(fixture/'ca.pem'), + BUSYSTACK_CLIENT_SYNC_DEPTH_INPUT='setting omitted; packaged application default',BUSYSTACK_THUNDERBIRD_BINARY=args.thunderbird_binary) + client_results=[] + for script,deadline in [('python_caldav.py',180),('thunderbird.py',360)]: + result=subprocess.run([args.client_python,str(ROOT/'qualification/clients'/script)],cwd=ROOT,env=client_environment,text=True,capture_output=True,timeout=deadline) + if result.returncode: + raise RuntimeError('P0 independent client failed: '+operations.sanitized_diagnostic(result.stdout+result.stderr,[issued.read_text()])) + value=json.loads(result.stdout.strip().splitlines()[-1]);assert value['status']=='passed' + client_results.append(value) + print('P0_INDEPENDENT_CLIENT_PASSED='+script,flush=True) + (args.output/'clients-result.json').write_text(json.dumps({'image':args.application_image,'clients':client_results,'credentialOrigin':'application password issued after protected browser initialization and real virtual-authenticator MFA'},indent=2)+'\n') + logs=operations.compose(environment,'logs','--no-log-prefix','application') + assert codes[0] not in logs and (fixture/'password').read_text().strip() not in logs and issued.read_text() not in logs,'Secret appeared in application logs' + assert operations.sql(environment,'SELECT initialized AND code_verifier IS NULL FROM installation_state;')=='t' + print('P0_LOCAL_CODE_AND_SECRET_LOG_CHECK_PASSED',flush=True) + finally: + operations.compose(environment,'down','--volumes','--remove-orphans','--timeout','10') +if __name__=='__main__':main() diff --git a/qualification/p0/test_build_identity.py b/qualification/p0/test_build_identity.py new file mode 100644 index 0000000..daebafd --- /dev/null +++ b/qualification/p0/test_build_identity.py @@ -0,0 +1,20 @@ +"""The image ID and optional OCI descriptor are distinct identities.""" +import importlib.util +from pathlib import Path +import unittest + +spec=importlib.util.spec_from_file_location('p0_build',Path(__file__).with_name('build.py')) +builder=importlib.util.module_from_spec(spec);spec.loader.exec_module(builder) + +class LocalImageIdentityTest(unittest.TestCase): + def test_missing_descriptor_does_not_invent_registry_identity(self): + self.assertIsNone(builder.descriptor_digest({'Id':'sha256:'+'1'*64})) + + def test_supplied_descriptor_is_retained(self): + digest='sha256:'+'2'*64 + self.assertEqual(builder.descriptor_digest({'Descriptor':{'digest':digest}}),digest) + + def test_supplied_malformed_descriptor_is_not_silently_ignored(self): + for value in ({}, {'digest':'invented'}, 'invalid'): + with self.subTest(value=value), self.assertRaises(AssertionError): + builder.descriptor_digest({'Descriptor':value}) diff --git a/qualification/p0/test_package_identity.py b/qualification/p0/test_package_identity.py new file mode 100644 index 0000000..c61d196 --- /dev/null +++ b/qualification/p0/test_package_identity.py @@ -0,0 +1,35 @@ +"""A local image ID cannot become a registry digest or bypass public validation.""" +import copy +import importlib.util +from pathlib import Path +import unittest + +spec=importlib.util.spec_from_file_location('local_package',Path(__file__).with_name('package.py')) +package=importlib.util.module_from_spec(spec);spec.loader.exec_module(package) + +class PackageIdentityTest(unittest.TestCase): + def manifest(self): + image='sha256:'+'1'*64 + return {'qualificationKind':'local-unpublished', + 'verification':{'status':'local-unpublished','run':None,'attempt':None,'url':None}, + 'container':{'registryManifestDigest':None,'image':image,'localTestedImageId':image,'published':False}} + + def test_explicit_local_mode_retains_actual_image_identity(self): + value=self.manifest() + package.bundle.validate_container_identity(value,'0.2.0',allow_local_unpublished=True) + self.assertIsNone(value['container']['registryManifestDigest']) + + def test_public_validator_never_accepts_missing_registry_digest(self): + with self.assertRaises(AssertionError): + package.bundle.validate_container_identity(self.manifest(),'0.2.0') + + def test_local_mode_rejects_false_publication_provenance_and_wrong_image(self): + original=self.manifest() + for field,value in [('qualificationKind','release'),('verification',{'status':'passed','run':1,'attempt':1,'url':'https://example.invalid'})]: + manifest=copy.deepcopy(original);manifest[field]=value + with self.subTest(field=field),self.assertRaises(AssertionError): + package.bundle.validate_container_identity(manifest,'0.2.0',allow_local_unpublished=True) + for field,value in [('published',True),('image','sha256:'+'2'*64),('localTestedImageId','fabricated')]: + manifest=copy.deepcopy(original);manifest['container'][field]=value + with self.subTest(field=field),self.assertRaises(AssertionError): + package.bundle.validate_container_identity(manifest,'0.2.0',allow_local_unpublished=True) diff --git a/qualification/passkeys/README.md b/qualification/passkeys/README.md index 89bf759..84a3ea1 100644 --- a/qualification/passkeys/README.md +++ b/qualification/passkeys/README.md @@ -11,6 +11,8 @@ python3 qualification/passkeys/run.py --application-image "busystack-caldav:$(py python3 qualification/passkeys/run.py --application-image "busystack-caldav:$(python3 scripts/release_version.py)" --proxy --groups ``` +Run local browser profiles sequentially, after other Docker qualification jobs finish. These fixtures use host networking: another fixture creating or removing Docker network interfaces can interrupt Chromium navigation with `net::ERR_NETWORK_CHANGED`, including an OIDC redirect. Keep networking stable for the whole profile rather than retrying authentication callbacks or relaxing assertions. CI matrix jobs have separate hosts. + The default profile uses direct embedded TLS at the hostname root. `--context-path /team` tests embedded TLS under a servlet prefix. `--proxy` uses the pinned non-root Nginx fixture with TLS termination, preserved `/team` paths, host-root CalDAV discovery and RFC 8414 metadata mapping, private management routes and bounded declared/chunked bodies. The ordinary production Compose deployment still consists of the application and PostgreSQL. The checks cover password-only mutation denial; actual passkey enrollment/assertion and MFA session rotation; a collection explicitly selecting and displaying `VTODO`; named DAV credential issuance, display-once semantics and revocation; administrator-controlled public native client registration; real browser authorization/consent with S256 PKCE and a cookie-authenticated missing-CSRF denial; ordinary recovery-code issuance/display-once, anonymous denial, recent-primary use, replay rejection, access reset and fresh factor enrollment; code exchange without a client secret; refresh rotation and grant revocation; JDBC browser-session and passkey persistence across JVM restart; and disabled-session/passkey rejection. Authentication of `/dav/missing` proves routing and credential enforcement, not calendar/task content synchronization. diff --git a/qualification/passkeys/account-recovery.mjs b/qualification/passkeys/account-recovery.mjs index 0459cfa..0057ff2 100644 --- a/qualification/passkeys/account-recovery.mjs +++ b/qualification/passkeys/account-recovery.mjs @@ -1,9 +1,11 @@ +import {verifyPasskey,assertRejectedPasskey} from './authentication.mjs'; import assert from 'node:assert/strict'; import {readFileSync} from 'node:fs'; import {call, json} from './transport.mjs'; import {issueDavCredential} from './dav-credentials.mjs'; import {qualifyOAuth} from './oauth.mjs'; import {organizationPrimary, primaryCannotMutate, signOut} from './oidc.mjs'; +import {captureWorkflow} from './portal-helpers.mjs'; export async function qualifyAccountRecovery({page, base, privateValues, administratorPage, username, cdp, authenticatorId}) { @@ -16,19 +18,21 @@ export async function qualifyAccountRecovery({page, base, privateValues, adminis const password = readFileSync(process.env.BUSYSTACK_BROWSER_PASSWORD_FILE, 'utf8').trimEnd(); await page.locator('input[name=username]').fill(username); await page.locator('input[name=password]').fill(password); - await Promise.all([page.waitForURL(base + '/'), page.getByRole('button', {name: 'Verify password', exact: true}).click()]); + await Promise.all([page.waitForURL(url => url.pathname === new URL(base).pathname.replace(/\/$/,'') + '/auth/continue'), page.getByRole('button', {name: 'Sign in', exact: true}).click()]); } } const device = await issueDavCredential(page, base, privateValues, 'Recovery-code reset device', username); const grant = await qualifyOAuth(page, base, privateValues, administratorPage, {clientId: 'browser-code-recovery-qualification', clientName: 'Browser Recovery Reset', retainGrant: true}); - await page.goto(base + '/security/recovery'); + await page.goto(base + '/security/recovery/codes/new'); const [issued] = await Promise.all([page.waitForResponse(response => response.request().method() === 'POST' && response.url() === base + '/security/recovery/codes'), page.getByRole('button', {name: 'Generate ten codes', exact: true}).click()]); assert.ok((issued.headers()['cache-control'] || '').includes('no-store')); await page.getByRole('heading', {name: 'Save your recovery codes', exact: true}).waitFor(); const codes = await page.locator('ol code').allInnerTexts(); privateValues.push(...codes); + // Mask the block: an inline code element can wrap beyond its screenshot mask rectangle. + await captureWorkflow(page,'recovery-codes-once',[page.locator('main ol')]); assert.equal(codes.length, 10); assert.equal(new Set(codes).size, 10); assert.ok(codes.every(value => value.length === 80)); @@ -51,8 +55,8 @@ export async function qualifyAccountRecovery({page, base, privateValues, adminis await primary(); await primaryCannotMutate(page, base); await cdp.send('WebAuthn.setAutomaticPresenceSimulation', {authenticatorId, enabled: false}); - await page.goto(base + '/security/recovery'); - assert.equal(await page.locator('main strong').innerText(), '10', 'Anonymous recovery must not consume a valid code'); + await page.goto(base + '/security/recovery/use'); + assert.equal(await page.locator('.section-nav').count(), 0, 'Recovery use is available after primary sign-in without the portal shell'); await page.getByLabel('Recovery code', {exact: true}).fill(codes[0]); await Promise.all([page.waitForURL(url => url.pathname === prefix + '/login' && url.searchParams.has('recovered')), page.getByRole('button', {name: 'Use code and reset account access', exact: true}).click()]); @@ -64,19 +68,20 @@ export async function qualifyAccountRecovery({page, base, privateValues, adminis assert.equal(refresh.status, 400); assert.equal(json(refresh).error, 'invalid_grant'); await cdp.send('WebAuthn.setAutomaticPresenceSimulation', {authenticatorId, enabled: true}); - await page.getByRole('button', {name: 'Verify passkey', exact: true}).click(); - await page.locator('#security-status').filter({hasText: '(401)'}).waitFor(); + await assertRejectedPasskey(page,base); await cdp.send('WebAuthn.clearCredentials', {authenticatorId}); await primary(); - await page.goto(base + '/security/recovery'); - assert.equal(await page.locator('main strong').innerText(), '9'); + await page.goto(base + '/security/recovery/use'); await page.getByLabel('Recovery code', {exact: true}).fill(codes[0]); const [replay] = await Promise.all([page.waitForResponse(response => response.request().method() === 'POST' && response.url() === base + '/security/recovery/use'), page.getByRole('button', {name: 'Use code and reset account access', exact: true}).click()]); - assert.equal(replay.status(), 403, 'A consumed recovery code must not be reusable'); + assert.equal(replay.status(), 400, 'A consumed recovery code must not be reusable'); await page.goto(base + '/security/passkeys'); - await page.getByRole('button', {name: 'Register passkey', exact: true}).click(); - 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()]); + await page.getByRole('button', {name: 'Create passkey', exact: true}).click(); + await page.locator('#security-status').filter({hasText: 'Passkey saved.'}).waitFor(); + await verifyPasskey(page,base); + await page.goto(base + '/security/recovery'); + assert.equal(await page.locator('main p').filter({hasText:/^Unused codes:/}).locator('strong').innerText(), '9', + 'Only the accepted recovery consumed a code; anonymous and replay attempts did not'); console.log('BROWSER_SINGLE_USE_PRIMARY_PLUS_RECOVERY_CODE_RESET_AND_FRESH_MFA_PASSED'); } diff --git a/qualification/passkeys/audit_corpus.py b/qualification/passkeys/audit_corpus.py index 5af2164..c97630c 100644 --- a/qualification/passkeys/audit_corpus.py +++ b/qualification/passkeys/audit_corpus.py @@ -12,6 +12,8 @@ class Corpus: "valid-lowercase-delimiters.ics", "valid-rfc9073-location.ics", "valid-rfc9074-alarm.ics", "valid-rfc9253-relationship.ics", "valid-text-list.ics", "valid-unknown-x-properties.ics", + # The unchanged historical fixture is valid since RFC 10051 §11.1. + "invalid-todo-no-start-duration.ics", ) # Independently derived from the unchanged captured uploads by UTC = local - TZOFFSETFROM. # These are fixed expected digests, not a second runtime repair used to prepare requests. @@ -58,6 +60,20 @@ def seed(self, environment): status, headers, raw = self.call(encoded, path) assert status == 200 and raw == content, name self.resources[path] = {"content": content, "etag": headers["ETag"], "component": component} + for status in ("PENDING", "FAILED"): + # Current task data must survive the same packaged database restore, + # immutable history and synchronization checks as the original corpus. + content = ("BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Task restore regression//EN\r\n" + "BEGIN:VTODO\r\nUID:restore-task-" + status.lower() + "\r\n" + "DTSTAMP:20261108T000000Z\r\nSTATUS:" + status + "\r\nDURATION:PT1H\r\n" + "ESTIMATED-DURATION:PT30M\r\nTASK-MODE:CLIENT\r\nX-RESTORE-TASK:preserved\r\n" + "END:VTODO\r\nEND:VCALENDAR\r\n").encode() + path = self.collections["VTODO"]["path"] + "current-task-" + status.lower() + ".ics" + assert self.call(encoded, path, "PUT", content, + **{"Content-Type": "text/calendar", "If-None-Match": "*"})[0] == 201 + code, headers, raw = self.call(encoded, path) + assert code == 200 and raw == content + self.resources[path] = {"content": content, "etag": headers["ETag"], "component": "VTODO"} for zone, (original_digest, corrected_digest) in self.OBSERVANCE_UPLOADS.items(): name = "thunderbird159-" + zone + ".ics" original = (self.fixture.parent / "observance-until" / name).read_bytes() @@ -73,6 +89,8 @@ def seed(self, environment): self.resources[path] = {"content": corrected, "etag": headers["ETag"], "component": "VEVENT"} # The invalid originals are rejection controls, never silently introduced into this dump. for fixture in sorted(self.fixture.glob("invalid-*.ics")): + if fixture.name in self.VALID: + continue # Accepted and independently read back above, never dropped from coverage. content = fixture.read_bytes() component = "VTODO" if b"BEGIN:VTODO" in content else "VEVENT" collection = self.collections[component] @@ -111,7 +129,8 @@ def seed(self, environment): self.verify_owner(encoded) self.database_snapshot = self.database_state(environment) print("HTTPS_AUDIT_CORPUS_CREATED=" + json.dumps({ - "acceptedOriginals": len(self.VALID), "rejectedOriginals": 9, + "acceptedOriginals": len(self.VALID), "rejectedOriginals": 8, + "rfc10051DurationOnlyStatuses": ["PENDING", "FAILED"], "repairedObservanceUploads": len(self.OBSERVANCE_UPLOADS), "contentSha256": {Path(path).name: hashlib.sha256(value["content"]).hexdigest() for path, value in self.resources.items()}, diff --git a/qualification/passkeys/authentication.mjs b/qualification/passkeys/authentication.mjs new file mode 100644 index 0000000..8935dba --- /dev/null +++ b/qualification/passkeys/authentication.mjs @@ -0,0 +1,26 @@ +import assert from 'node:assert/strict'; +export async function verifyPasskey(page,base) { + const button = page.getByRole('button',{name:'Verify and continue',exact:true}); + await Promise.all([ + page.waitForURL(url => !url.pathname.endsWith('/auth/continue') && !url.pathname.endsWith('/login')), + button.click() + ]); +} +// A normal signed anonymous browser assertion still exercises revoked/disabled +// cryptography even though primary login no longer offers an unordered passkey button. +export async function assertRejectedPasskey(page,base) { + await page.goto(base+'/login'); + const status=await page.evaluate(async prefix=>{ + const token=document.querySelector('meta[name=csrf-token]').content; + const call=(path,body)=>fetch(prefix+path,{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-TOKEN':token},body:body===undefined?undefined:JSON.stringify(body)}); + const optionsResponse=await call('/webauthn/authenticate/options'); + if(!optionsResponse.ok)return optionsResponse.status; + const options=await optionsResponse.json(); + const decode=x=>Uint8Array.from(atob(x.replace(/-/g,'+').replace(/_/g,'/')),c=>c.charCodeAt(0)); + const encode=x=>btoa(String.fromCharCode(...new Uint8Array(x))).replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,''); + options.challenge=decode(options.challenge);for(const c of options.allowCredentials||[])c.id=decode(c.id); + const credential=await navigator.credentials.get({publicKey:options}),r=credential.response; + return (await call('/login/webauthn',{id:credential.id,rawId:encode(credential.rawId),type:credential.type,response:{authenticatorData:encode(r.authenticatorData),clientDataJSON:encode(r.clientDataJSON),signature:encode(r.signature),userHandle:r.userHandle?encode(r.userHandle):null},clientExtensionResults:credential.getClientExtensionResults(),authenticatorAttachment:credential.authenticatorAttachment})).status; + },new URL(base).pathname.replace(/\/$/,'')); + assert.equal(status,401,'Revoked or disabled passkey authentication must fail'); +} diff --git a/qualification/passkeys/dav-credentials.mjs b/qualification/passkeys/dav-credentials.mjs index 98e0a8e..01726f6 100644 --- a/qualification/passkeys/dav-credentials.mjs +++ b/qualification/passkeys/dav-credentials.mjs @@ -1,21 +1,24 @@ import assert from 'node:assert/strict'; import {randomUUID} from 'node:crypto'; import {call} from './transport.mjs'; +import {captureWorkflow} from './portal-helpers.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'); + await page.getByRole('link', {name: 'Create application password', exact: true}).click(); 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'); const [response] = await Promise.all([page.waitForResponse(value => value.request().method() === 'POST' && value.url() === base + '/credentials'), - form.getByRole('button', {name: 'Issue credential', exact: true}).click()]); + form.getByRole('button', {name: 'Create application password', exact: true}).click()]); assert.ok((response.headers()['cache-control'] || '').includes('no-store')); - await page.getByRole('heading', {name: 'New DAV credential', exact: true}).waitFor(); - const credential = await page.locator('code').innerText(); + await page.getByRole('heading', {name: 'Application password created', exact: true}).waitFor(); + const credential = await page.locator('#issued-secret').innerText(); assert.equal(credential.length, 80); const encoded = Buffer.from(username + ':' + credential).toString('base64'); privateValues.push(credential, encoded); - await page.goto(base + '/'); + await captureWorkflow(page,'credential-once',[page.locator('[data-one-time-secret]')]); + 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 +28,11 @@ 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 entry.getByRole('link', {name: 'Revoke', exact: true}).click(); + await Promise.all([page.waitForURL(base + '/security/credentials'), page.getByRole('button', {name: 'Revoke application password', 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..d1b200e 100644 --- a/qualification/passkeys/groups.mjs +++ b/qualification/passkeys/groups.mjs @@ -1,83 +1,159 @@ import assert from 'node:assert/strict'; import {randomBytes} from 'node:crypto'; +import {createCollection,openCollection,provisionAccount,prefixOf,grantDirect,revokeDirect,captureWorkflow,expectFieldError} 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"]`); + await page.goto(base+'/admin/accounts/new'); + 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[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); + 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 captureWorkflow(page,'account-detail'); + 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/new'); + 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'); - 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[method="post"][action="${prefix}/admin/groups/${group}/members"]`); + await add.locator('input[name=username]').fill('missing-account'); + await expectFieldError(page,add,'username',400,'member-add'); + await add.locator('input[name=username]').fill(member); + 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.getByRole('link',{name:'Remove member',exact:true}).click(); + await Promise.all([page.waitForURL(base+'/admin/groups/'+group),page.getByRole('button',{name:'Remove member',exact:true}).click()]); + assert.equal(await row.count(),0); + await add.locator('input[name=username]').fill(member); + await Promise.all([page.waitForURL(base+'/admin/groups/'+group),add.getByRole('button',{name:'Add member',exact:true}).click()]); + const rename=page.locator(`form[method="post"][action="${prefix}/admin/groups/${group}"]`); + await page.getByText('Rename group',{exact:true}).click(); + 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'); + 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(); + 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[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[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); - 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)); - } - 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); + 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'}); + await grant.locator('select[name=permission]').selectOption('WRITE'); + await Promise.all([page.waitForURL(base+'/collections/'+collection+'/sharing'),grant.getByRole('button',{name:'Save group grant',exact:true}).click()]); + 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 captureWorkflow(page,'effective-direct-group-access'); + 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'); + await removeGroupGrant(page,base,collection,grant); + assert.equal(await grant.count(),0); + const journal=await createCollection(page,base,'Journal group QA','VJOURNAL'); + await page.goto(base+'/collections/'+journal+'/sharing'); + 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('WRITE'); + await Promise.all([page.waitForURL(base+'/collections/'+journal+'/sharing'),sharing.getByRole('button',{name:'Grant group access',exact:true}).click()]); + await grantDirect(page,base,journal,member,'READ'); + const journalEffective=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 journalEffective.innerText()).includes('Read and write')); + await removeGroupGrant(page,base,journal,grant); + await revokeDirect(page,base,journal,member); + console.log('PORTAL_JOURNAL_DIRECT_READER_GROUP_WRITER_AND_REVOCATION_PASSED'); + await page.goto(base+'/admin/groups/'+group); + await page.getByRole('link',{name:'Delete group',exact:true}).click(); + const remove=page.locator(`form[method="post"][action="${prefix}/admin/groups/${group}/delete"]`); + 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); + await page.getByRole('link',{name:'Disable account',exact:true}).click(); + const disable=page.locator(`form[method="post"][action="${prefix}/admin/accounts/${account}/disable"]`); + 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:'Sign in',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'); } +async function removeGroupGrant(page,base,collection,row) { + await row.getByRole('link',{name:'Remove group grant',exact:true}).click(); + await Promise.all([page.waitForURL(url=>url.pathname===prefixOf(base)+'/collections/'+collection+'/sharing'), + page.getByRole('button',{name:'Remove group grant',exact:true}).click()]); +} -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(); + const removedGroup=await remove.locator('input[name=group]').inputValue(); + await removeGroupGrant(page,base,id,remove); + assert.equal(await rows.count(),50); + await administratorPage.goto(base+'/admin/groups/'+fixture.firstGroup); + await administratorPage.getByText('Rename group',{exact:true}).click(); + 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.getByRole('link',{name:'Remove member',exact:true}).click(); + await Promise.all([administratorPage.waitForURL(base+'/admin/groups/'+fixture.firstGroup),administratorPage.getByRole('button',{name:'Remove member',exact:true}).click()]); + 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')); + await administratorPage.getByRole('link',{name:'Delete group',exact:true}).click(); + const deletion=administratorPage.locator(`form[method="post"][action="${prefix}/admin/groups/${fixture.firstGroup}/delete"]`); + 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/oauth.mjs b/qualification/passkeys/oauth.mjs index 81e7ca7..78a6506 100644 --- a/qualification/passkeys/oauth.mjs +++ b/qualification/passkeys/oauth.mjs @@ -2,6 +2,7 @@ import assert from 'node:assert/strict'; import {createServer} from 'node:http'; import {randomBytes, createHash} from 'node:crypto'; import {call, json} from './transport.mjs'; +import {captureWorkflow} from './portal-helpers.mjs'; export async function qualifyOAuth(page, base, privateValues, administratorPage = page, options = {}) { const clientId = options.clientId || 'browser-native-qualification'; @@ -46,6 +47,7 @@ export async function qualifyOAuth(page, base, privateValues, administratorPage const headings = await page.locator('h1').allInnerTexts(); throw new Error(`Consent page unavailable: status=${authorizationPage.status()}, path=${new URL(page.url()).pathname}, headings=${JSON.stringify(headings)}`); } + await captureWorkflow(page,'oauth-consent'); const consentState = await page.locator('form').filter({has: page.getByRole('button', {name: 'Authorize application', exact: true})}).locator('input[name=state]').inputValue(); privateValues.push(consentState); const missingCsrf = await page.evaluate(async values => (await fetch(values.target, { @@ -91,7 +93,8 @@ export async function qualifyOAuth(page, base, privateValues, administratorPage } await page.goto(base + '/oauth-grants'); const grant = page.locator('tbody tr').filter({hasText: clientId}); - await Promise.all([page.waitForURL(base + '/oauth-grants'), grant.getByRole('button', {name: 'Revoke access', exact: true}).click()]); + await grant.getByRole('link', {name: 'Revoke access', exact: true}).click(); + await Promise.all([page.waitForURL(base + '/oauth-grants'), page.getByRole('button', {name: 'Revoke app access', exact: true}).click()]); assert.equal((await call(base, '/dav/missing', {headers: {Authorization: 'Bearer ' + current.access_token}})).status, 401); const revokedRefresh = await call(base, '/oauth2/token', {method: 'POST', form: { grant_type: 'refresh_token', client_id: clientId, refresh_token: current.refresh_token diff --git a/qualification/passkeys/oidc.mjs b/qualification/passkeys/oidc.mjs index 5bdd4e0..c40d1c5 100644 --- a/qualification/passkeys/oidc.mjs +++ b/qualification/passkeys/oidc.mjs @@ -1,25 +1,36 @@ +import {verifyPasskey,assertRejectedPasskey} from './authentication.mjs'; +import {createCollection} from './portal-helpers.mjs'; import assert from 'node:assert/strict'; import {readFileSync} from 'node:fs'; export function accountLocation(url, base) { const publicUrl = new URL(base); const prefix = publicUrl.pathname.replace(/\/$/, ''); - return url.origin === publicUrl.origin && url.pathname === prefix + '/' && !url.hash - && (url.search === '' || (url.searchParams.size === 1 && url.searchParams.get('continue') === '')); + if (url.origin !== publicUrl.origin || url.pathname !== prefix + '/auth/continue' || url.hash) return false; + if (new Set(url.searchParams.keys()).size !== url.searchParams.size) return false; + return [...url.searchParams].every(([key, value]) => + key === 'continue' && value === '' + || key === 'flow' && /^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(value)); } export async function organizationPrimary(page, base, privateValues, requirePasswordForm = false) { const password = readFileSync(process.env.BUSYSTACK_UPSTREAM_PASSWORD_FILE, 'utf8').trimEnd(); 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 failedRequests = []; + const recordFailure = request => { + if (!request.isNavigationRequest()) return; + const url = new URL(request.url()); + failedRequests.push({origin: url.origin, path: url.pathname, error: request.failure()?.errorText}); + }; + page.on('requestfailed', recordFailure); + const dashboard = page.getByRole('heading', {name: /^(Create a passkey|Verify your passkey|Overview)$/}); + const providerLogin = page.locator('#kc-login'); let destination; try { - destination = await Promise.race([ - page.locator('#kc-login').waitFor().then(() => 'provider-password'), - dashboard.waitFor().then(() => 'application') - ]); + await page.getByRole('link', {name: "Sign in with your organization's identity provider", exact: true}).click(); + await providerLogin.or(dashboard).first().waitFor(); + destination = await providerLogin.isVisible() ? 'provider-password' : 'application'; } catch (error) { // No URL query, form values, cookies or tokens enter retained diagnostics. const location = new URL(page.url()); @@ -27,9 +38,11 @@ export async function organizationPrimary(page, base, privateValues, requirePass console.error('ORGANIZATION_PRIMARY_FAILURE=' + JSON.stringify({ origin: location.origin, path: location.pathname, headings: headings.map(value => privateValues.reduce((text, secret) => text.replaceAll(secret, '[redacted]'), value)).slice(0, 8), - requirePasswordForm + requirePasswordForm, failedRequests: failedRequests.slice(-6) })); throw error; + } finally { + page.off('requestfailed', recordFailure); } if (requirePasswordForm) assert.equal(destination, 'provider-password', 'The first organization login must exercise real upstream password authentication'); if (destination === 'provider-password') { @@ -44,7 +57,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(); + assert.ok(await page.locator('form[action$="/logout"]').count(),'Provider login retains authenticated logout and CSRF'); 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'); } @@ -76,16 +89,11 @@ export async function newFederatedUser(browser, base, privateValues) { await organizationPrimary(page, base, privateValues, true); await primaryCannotMutate(page, base); await page.goto(base + '/security/passkeys'); - await page.getByRole('button', {name: 'Register passkey', exact: true}).click(); - 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()]); + await page.getByRole('button', {name: 'Create passkey', exact: true}).click(); + await page.locator('#security-status').filter({hasText: 'Passkey saved.'}).waitFor(); + await verifyPasskey(page,base); 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'); @@ -95,11 +103,11 @@ export async function newFederatedUser(browser, base, privateValues) { const upstreamPassword = readFileSync(process.env.BUSYSTACK_UPSTREAM_PASSWORD_FILE, 'utf8').trimEnd(); await page.locator('input[name=password]').fill(upstreamPassword); await Promise.all([page.waitForURL(url => url.pathname === prefix + '/login' && url.searchParams.has('error')), - page.getByRole('button', {name: 'Verify password', exact: true}).click()]); + page.getByRole('button', {name: 'Sign in', exact: true}).click()]); await organizationPrimary(page, base, privateValues); await primaryCannotMutate(page, base); await page.goto(base + '/login'); - await Promise.all([page.waitForURL(base + '/'), page.getByRole('button', {name: 'Verify passkey', exact: true}).click()]); + await verifyPasskey(page,base); console.log('FEDERATED_LOCAL_PASSWORD_FALLBACK_DENIED'); console.log('CROSS_SITE_ORGANIZATION_PLUS_PASSKEY_AND_NONADMIN_PROVISIONING_PASSED'); return {context, page, cdp, authenticatorId: authenticator.authenticatorId}; diff --git a/qualification/passkeys/passkeys.mjs b/qualification/passkeys/passkeys.mjs index 68b4aa2..99afdee 100644 --- a/qualification/passkeys/passkeys.mjs +++ b/qualification/passkeys/passkeys.mjs @@ -1,7 +1,11 @@ +import {verifyPasskey,assertRejectedPasskey} from './authentication.mjs'; +import {qualifyImportProcessInterruption} from './portability-crash.mjs'; +import {qualifyPersonalPortal,qualifyPortalPresentation} from './portal.mjs'; +import {createCollection, openCollection, captureWorkflow} 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'; @@ -31,10 +35,11 @@ try { const localAuthenticator = await cdp.send('WebAuthn.addVirtualAuthenticator', {options: {protocol: 'ctap2', transport: 'internal', hasResidentKey: true, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true}}); await page.goto(base + '/login'); + await captureWorkflow(page,'sign-in'); assert.equal(await page.locator('meta[name=csrf-token]').count(), 1); await page.locator('input[name=username]').fill(process.env.BUSYSTACK_BROWSER_USERNAME); await page.locator('input[name=password]').fill(password); - await Promise.all([page.waitForURL(base + '/'), page.getByRole('button', {name: 'Verify password', exact: true}).click()]); + await Promise.all([page.waitForURL(url => url.pathname === new URL(base).pathname.replace(/\/$/,'') + '/auth/continue'), page.getByRole('button', {name: 'Sign in', exact: true}).click()]); const passwordSession = (await context.cookies()).find(cookie => cookie.name === 'JSESSIONID')?.value; assert.ok(passwordSession); privateValues.push(passwordSession); @@ -47,20 +52,26 @@ try { }, prefix + '/collections'); assert.equal(passwordOnly, 403, 'Password alone must not authorize account mutations'); await page.goto(base + '/security/passkeys'); - await page.getByRole('button', {name: 'Register passkey', exact: true}).click(); - 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()]); + await page.getByRole('button', {name: 'Create passkey', exact: true}).click(); + await page.locator('#security-status').filter({hasText: 'Passkey saved.'}).waitFor(); + await verifyPasskey(page,base); 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); + if (process.env.BUSYSTACK_GNOME_ONLY !== 'true') await qualifyPortalPresentation(page,base,localPortal,true); + if (process.env.BUSYSTACK_GNOME_EXCHANGE) { + writeFileSync(process.env.BUSYSTACK_GNOME_EXCHANGE, JSON.stringify({address:localPortal.address,connectionAddress:localPortal.gnomeAddress, + 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_GNOME_ONLY === 'true') { + console.log('NATIVE_CONNECTION_SETUP_ONLY_PASSED'); + } else { + if (process.env.BUSYSTACK_PORTABILITY_CRASH === 'true') await qualifyImportProcessInterruption(page,base,waitFor); if (process.env.BUSYSTACK_BROWSER_GROUPS === 'true') await qualifyGroups(page, base, privateValues); const administratorPage = page; let activeCdp = cdp; @@ -76,6 +87,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 +103,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: 'Overview'}).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'); @@ -99,16 +112,17 @@ try { await organizationPrimary(page, base, privateValues); await primaryCannotMutate(page, base); } else { + await signOut(page,base); await page.goto(base + '/login'); await page.locator('input[name=username]').fill(process.env.BUSYSTACK_BROWSER_USERNAME); const currentPassword = process.env.BUSYSTACK_BROWSER_RESTORE === 'true' ? readFileSync(process.env.BUSYSTACK_BROWSER_RECOVERY_PASSWORD_FILE, 'utf8').trimEnd() : password; privateValues.push(currentPassword); await page.locator('input[name=password]').fill(currentPassword); - await Promise.all([page.waitForURL(base + '/'), page.getByRole('button', {name: 'Verify password', exact: true}).click()]); + await Promise.all([page.waitForURL(url => url.pathname === new URL(base).pathname.replace(/\/$/,'') + '/auth/continue'), page.getByRole('button', {name: 'Sign in', exact: true}).click()]); } 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 verifyPasskey(page,base); + await openCollection(page,base,collectionName); console.log('PERSISTED_PASSKEY_AFTER_RESTART_PASSED'); console.log('READY_DISABLE'); await waitFor('DISABLED'); @@ -116,9 +130,9 @@ try { assert.equal(disabled.status(), 403); // Existing sessions and independent passkey authentication must both reject disabled users. await page.goto(base + '/login'); - await page.getByRole('button', {name: 'Verify passkey', exact: true}).click(); - await page.locator('#security-status').filter({hasText: '(401)'}).waitFor(); + await assertRejectedPasskey(page,base); console.log('DISABLED_SESSION_AND_PASSKEY_PASSED'); + } } catch (error) { let diagnostic = String(error.stack || error); for (const value of privateValues) diagnostic = diagnostic.replaceAll(value, '[redacted]'); diff --git a/qualification/passkeys/portability-crash.mjs b/qualification/passkeys/portability-crash.mjs new file mode 100644 index 0000000..de19781 --- /dev/null +++ b/qualification/passkeys/portability-crash.mjs @@ -0,0 +1,35 @@ +import assert from 'node:assert/strict'; +import {createCollection, prefixOf} from './portal-helpers.mjs'; + +export async function qualifyImportProcessInterruption(page,base,waitFor) { + const id=await createCollection(page,base,'Interrupted import fixture','VEVENT'); + const file=['interrupted-a','interrupted-b'].map(uid=>'BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//BusyStack crash qualification//EN\r\nBEGIN:VEVENT\r\nUID:'+uid+'\r\nDTSTAMP:20261101T000000Z\r\nDTSTART:20261102T090000Z\r\nSUMMARY:Disposable interruption fixture\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n').join(''); + async function preview() { + await page.goto(base+'/portability?destination='+id); + const upload=page.locator('form').filter({has:page.locator(`input[name=destination][value="${id}"]`)}); + await upload.locator('[name=file]').setInputFiles({name:'interruption.ics',mimeType:'text/calendar',buffer:Buffer.from(file)}); + await Promise.all([page.waitForURL(url=>url.pathname.startsWith(prefixOf(base)+'/portability/import/')),upload.getByRole('button',{name:'Validate and preview import',exact:true}).click()]); + const form=page.locator('form').filter({has:page.getByRole('button',{name:'Confirm import',exact:true})}); + await form.locator('[name=confirmed]').check(); + return form; + } + let form=await preview(); + const oldPath=await form.getAttribute('action'); + assert.match(oldPath,/\/portability\/import\/[a-f0-9-]{36}$/); + console.log('READY_PORTABILITY_CRASH_ARM'); + await waitFor('PORTABILITY_CRASH_ARMED'); + // The owned PostgreSQL fixture pauses the second insert after the first write. + const pending=Promise.allSettled([page.waitForNavigation({timeout:180000}),form.getByRole('button',{name:'Confirm import',exact:true}).click({timeout:180000})]); + console.log('READY_PORTABILITY_CRASH_REQUESTED'); + await waitFor('PORTABILITY_CRASH_RESTARTED'); + await pending; + const old=await page.goto(new URL(oldPath,base).toString()); + assert.equal(old.status(),412,'A process restart invalidates pending previews'); + form=await preview(); + await Promise.all([page.waitForURL(url=>url.pathname.startsWith(prefixOf(base)+'/portability/import/')),form.getByRole('button',{name:'Confirm import',exact:true}).click()]); + await page.getByRole('heading',{name:'Import results',exact:true}).waitFor(); + assert.equal(await page.getByRole('cell',{name:'Imported',exact:true}).count(),2); + console.log('READY_PORTABILITY_CRASH_VERIFY'); + await waitFor('PORTABILITY_CRASH_VERIFIED'); + console.log('PORTABILITY_PROCESS_INTERRUPTION_ROLLBACK_RESTART_AND_FRESH_IMPORT_PASSED'); +} diff --git a/qualification/passkeys/portal-helpers.mjs b/qualification/passkeys/portal-helpers.mjs new file mode 100644 index 0000000..ee24292 --- /dev/null +++ b/qualification/passkeys/portal-helpers.mjs @@ -0,0 +1,109 @@ +import assert from 'node:assert/strict'; +import {mkdirSync,writeFileSync} from 'node:fs'; +export async function captureWorkflow(page,label,mask=[]) { + const output=process.env.BUSYSTACK_PORTAL_EVIDENCE; + if(!output || process.env.BUSYSTACK_GNOME_ONLY==='true') return; + mkdirSync(output,{recursive:true}); + const initial=page.viewportSize(); + try { + for(const width of [1280,390]) { + await page.setViewportSize({width,height:900}); + const fits=await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1); + if(!fits) { + await page.screenshot({path:output+'/workflow-'+label+'-'+width+'-overflow.png',fullPage:true,mask}); + writeFileSync(output+'/workflow-'+label+'-'+width+'-overflow.json',JSON.stringify(await page.evaluate(()=>({ + viewport:innerWidth,documentWidth:document.documentElement.scrollWidth, + elements:[...document.querySelectorAll('body *')].filter(element=>element.getBoundingClientRect().right>innerWidth+1 && (!element.closest('.table-scroll') || getComputedStyle(element).position==='absolute')) + .slice(0,40).map(element=>({tag:element.tagName,classes:[...element.classList], + left:element.getBoundingClientRect().left,right:element.getBoundingClientRect().right, + width:element.getBoundingClientRect().width,minWidth:getComputedStyle(element).minWidth, + position:getComputedStyle(element).position,containingBlock:element.offsetParent?.tagName})) + })),null,2)); + } + assert.ok(fits,label+' must fit the viewport'); + for(const region of await page.locator('.table-scroll').all()) { + if(await region.evaluate(element=>element.scrollWidth>element.clientWidth+1)) { + await region.focus(); + await page.keyboard.press('ArrowRight'); + const handle=await region.elementHandle(); + try {await page.waitForFunction(element=>element.scrollLeft>0,handle);} + finally {await handle.dispose();} + await page.keyboard.press('Tab'); + assert.ok(await region.evaluate(element=>document.activeElement!==element),'Scrollable tables must not trap keyboard focus'); + await region.evaluate(element=>{element.scrollLeft=0;}); + } + } + await page.screenshot({path:output+'/workflow-'+label+'-'+width+'.png',fullPage:true,mask}); + } + } finally { + await page.setViewportSize(initial); + } +} + +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(`input[name=component][value=${component}]`).check(); + await Promise.all([page.waitForURL(/\/collections\/[a-f0-9-]{36}$/i),form.getByRole('button',{name:/^Create (calendar|task list|journal)$/}).click()]); + assert.equal(await page.getByRole('heading',{name,exact:true}).count(),1); + assert.ok((await page.locator('main').innerText()).includes({VEVENT:'Calendar',VTODO:'Task list',VJOURNAL:'Journal'}[component])); + 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}).and(page.locator('dd')).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.getByRole('link',{name:'Remove direct grant',exact:true}).click(); + await page.getByRole('heading',{name:'Remove direct access for '+username+'?',exact:true}).waitFor(); + await Promise.all([page.waitForURL(url=>url.pathname===prefixOf(base)+'/collections/'+collection+'/sharing'), + page.getByRole('button',{name:'Remove direct grant',exact:true}).click()]); +} + +export async function expectFieldError(page,form,field,status,label) { + // Submit through the native form serializer to exercise authoritative server errors. + const [response]=await Promise.all([page.waitForNavigation(),form.evaluate(element=>HTMLFormElement.prototype.submit.call(element))]); + assert.equal(response.status(),status,label); + const summary=page.locator('[data-error-summary]'); + await summary.waitFor(); + await page.waitForFunction(()=>document.activeElement===document.querySelector('[data-error-summary]')); + const control=page.locator('[aria-invalid="true"]').filter({hasNot:page.locator('[type=hidden]')}); + const target=page.locator(`[name="${field}"][aria-invalid="true"]`); + assert.equal(await target.count(),1,label+' has one invalid editable field'); + const id=await target.getAttribute('id'),description=await target.getAttribute('aria-describedby'); + assert.ok(id && description); + assert.equal(await target.evaluate(element=>element.labels.length>0),true); + assert.ok((await page.locator('[id="'+description+'"]').innerText()).trim()); + await summary.locator(`a[href="#${id}"]`).click(); + assert.equal(await target.evaluate(element=>document.activeElement===element),true,'Error link moves keyboard focus to its field'); + for(const password of await page.locator('input[type=password]').all()) assert.equal(await password.inputValue(),'','Passwords must never be redisplayed'); + assert.ok(await control.count()>0); + await captureWorkflow(page,'form-error-'+label); +} diff --git a/qualification/passkeys/portal.mjs b/qualification/passkeys/portal.mjs new file mode 100644 index 0000000..b43a539 --- /dev/null +++ b/qualification/passkeys/portal.mjs @@ -0,0 +1,234 @@ +import assert from 'node:assert/strict'; +import {readFileSync, mkdirSync, writeFileSync} from 'node:fs'; +import {createCollection,openCollection,provisionAccount,grantDirect,revokeDirect,prefixOf,captureWorkflow,expectFieldError} 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(/\/portability\/import\/[a-f0-9-]{36}$/i),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; + await page.goto(base+'/collections/new'); + const create=page.locator('form').filter({has:page.getByRole('button',{name:/^Create (calendar|task list|journal)$/})}); + await create.locator('[name=name]').fill(name); await create.locator('[name=description]').fill('Retain description'); await create.locator('[name=color]').fill('invalid'); + await expectFieldError(page,create,'color',400,'collection-create'); + assert.equal(await create.locator('[name=name]').inputValue(),name); + assert.equal(await create.locator('[name=description]').inputValue(),'Retain description'); + await create.locator('[name=color]').fill('#123456'); + await Promise.all([page.waitForURL(/\/collections\/[a-f0-9-]{36}$/i),create.getByRole('button',{name:/^Create (calendar|task list|journal)$/}).click()]); + const id=new URL(page.url()).pathname.split('/').at(-1); + 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(''); + await expectFieldError(page,edit,'name',400,'collection-edit'); + 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 page.getByText('There are no events to export yet.', {exact:false}).waitFor(); + assert.equal(await page.getByRole('link',{name:'Export events (.ics)',exact:true}).count(),0); + await page.goto(base+'/portability?destination='+id); + const upload=page.locator('form').filter({has:page.locator(`input[name=destination][value="${id}"]`)}); + await upload.locator('[name=file]').setInputFiles({name:'invalid.ics',mimeType:'text/calendar',buffer:Buffer.from('not iCalendar')}); + await expectFieldError(page,upload,'file',400,'import-file'); + await importFile(page,base,id,series); + const confirmation=page.locator('form').filter({has:page.getByRole('button',{name:'Confirm import',exact:true})}); + await expectFieldError(page,confirmation,'confirmed',400,'import-confirm'); + await captureWorkflow(page,'import-preview'); + assert.equal(await page.getByRole('cell',{name:'Ready',exact:true}).count(),2); + await confirmImport(page,base); + await captureWorkflow(page,'import-results'); + assert.equal(await page.getByRole('cell',{name:'Imported',exact:true}).count(),2); + await page.goto(base+'/security/credentials/new'); + const credential=page.locator('form').filter({has:page.getByRole('button',{name:'Create application password',exact:true})}); + await credential.locator('[name=label]').fill('Retain device'); await credential.locator('[name=days]').fill('366'); + await expectFieldError(page,credential,'days',400,'credential-create'); + assert.equal(await credential.locator('[name=label]').inputValue(),'Retain device'); + 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 (events|tasks|journal entries) \(\.ics\)$/}).click(); + const download=await downloadPromise; + const exported=readFileSync(await download.path()); + assert.equal(download.suggestedFilename(),'busystack-collection.ics'); + const document=exported.toString(); + assert.equal(document.split('BEGIN:VCALENDAR\r\n').length-1,1); + assert.equal(document.split('BEGIN:VTIMEZONE\r\n').length-1,1); + assert.equal(document.split('BEGIN:VEVENT\r\n').length-1,3); + assert.ok(document.endsWith('END:VCALENDAR\r\n')); + for(const body of originalBodies) { + for(const component of body.matchAll(/BEGIN:(VEVENT|VTIMEZONE)\r\n[\s\S]*?END:\1\r\n/g)) + assert.ok(document.includes(component[0]),'Export must preserve every original component byte'); + } + 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 captureWorkflow(page,'import-duplicate'); + 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 captureWorkflow(page,'import-conflict'); + 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'); + await captureWorkflow(page,'delete-confirmation'); + 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); + await qualifyJournalPortal(page,base,device.encoded,suffix); + await page.goto(base+'/connections?client=gnome'); + const serverAddress=await page.locator('#server-address').inputValue(); + const gnomeAddress=await page.locator('#gnome-address').inputValue(); + return {id,address:originalAddress,serverAddress,gnomeAddress,device,name:name+' renamed'}; +} + +async function qualifyJournalPortal(page,base,credential,suffix) { + const name='Portal journal '+suffix; + const id=await createCollection(page,base,name,'VJOURNAL'); + const address=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 Promise.all([page.waitForURL(base+'/collections/'+id),edit.getByRole('button',{name:'Save details',exact:true}).click()]); + await page.getByRole('heading',{name:name+' renamed',exact:true}).waitFor(); + assert.equal(await page.locator('#collection-address').inputValue(),address); + const envelope=['BEGIN:VCALENDAR','VERSION:2.0','PRODID:-//BusyStack//Portal journal fixture//EN']; + const component=['BEGIN:VJOURNAL','UID:portal-journal','DTSTAMP:20261126T000000Z', + 'DTSTART;VALUE=DATE:20261126','RRULE:FREQ=DAILY;COUNT=2','STATUS:DRAFT', + 'DESCRIPTION;LANGUAGE=en:First block','DESCRIPTION;LANGUAGE=fr:Deuxième bloc', + 'X-JOURNAL;X-PARAM=kept:opaque','END:VJOURNAL'].join('\r\n'); + const detached=['BEGIN:VJOURNAL','UID:portal-journal','DTSTAMP:20261126T000000Z', + 'RECURRENCE-ID;VALUE=DATE:20261127','DTSTART;VALUE=DATE:20261128','STATUS:FINAL', + 'DESCRIPTION:Moved occurrence','END:VJOURNAL'].join('\r\n'); + const input=[...envelope,component,detached,'END:VCALENDAR',''].join('\r\n'); + await importFile(page,base,id,input); + assert.equal(await page.getByRole('cell',{name:'Ready',exact:true}).count(),1); + await confirmImport(page,base); + assert.equal(await page.getByRole('cell',{name:'Imported',exact:true}).count(),1); + const urls=await resourceUrls(page,base,address,credential); + assert.equal(urls.length,1); + const path=new URL(urls[0],base).pathname.slice(prefixOf(base).length); + const raw=await call(base,path,{headers:{Authorization:'Basic '+credential}}); + assert.equal(raw.status,200); + assert.ok(raw.body.includes(component)); + assert.ok(raw.body.includes(detached)); + await page.goto(base+'/collections/'+id); + const downloadPromise=page.waitForEvent('download'); + await page.getByRole('link',{name:/^Export (events|tasks|journal entries) \(\.ics\)$/}).click(); + const exported=readFileSync(await (await downloadPromise).path(),'utf8'); + assert.ok(exported.includes(component)); + assert.ok(exported.includes(detached)); + await page.goto(base+'/collections/'+id+'/delete'); + 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,path,{headers:{Authorization:'Basic '+credential}})).status)); + console.log('PORTAL_JOURNAL_CREATE_RENAME_IMPORT_EXPORT_AND_DELETE_PASSED '+suffix); +} + +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'); + pages.push('/collections?scope=shared'); + const visits=pages.map(path=>[path,200]); + visits.push(['/collections?page=-1',400],['/missing-portal-page',404],['/portability/preview',403,'POST']); + if(!administrator) visits.push(['/admin',403]); + 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},{width:320,height:844}]) { + await page.setViewportSize(viewport); + for(const [path,status,method] of visits) { + const response=method==='POST' + ? (await Promise.all([page.waitForNavigation(),page.evaluate(target=>{ + const form=document.createElement('form');form.method='POST';form.action=target; + document.body.append(form);form.submit(); + },base+path)]))[0] + : await page.goto(base+path); + assert.equal(response.status(),status,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'); + if(output) { + const filename=path.replaceAll('/','_').replaceAll('?','_'); + await page.screenshot({path:output+'/'+suffix+'-'+viewport.width+'-'+filename+'.png',fullPage:true}); + if(viewport.width===1280) writeFileSync(output+'/'+suffix+'-'+filename+'-accessibility.txt',await page.locator('main').ariaSnapshot()); + } + 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.classList.contains('skip-link')),'The skip link must be the first keyboard stop'); + await Promise.all([page.waitForURL(url=>url.hash==='#main'),page.keyboard.press('Enter')]); + assert.equal(new URL(page.url()).hash,'#main'); + await page.waitForFunction(()=>document.activeElement.id==='main'); + 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}); + await page.goto(base+'/connections?client=gnome'); + await page.getByRole('button',{name:'Copy address',exact:true}).focus(); + assert.ok(await page.evaluate(()=>getComputedStyle(document.activeElement).outlineStyle!=='none')); + await page.context().grantPermissions(['clipboard-read','clipboard-write'],{origin:new URL(base).origin}); + await page.getByRole('button',{name:'Copy address',exact:true}).click(); + assert.equal(await page.evaluate(()=>navigator.clipboard.readText()),await page.locator('#server-address').inputValue()); + await page.getByRole('button',{name:'Copy GNOME address',exact:true}).click(); + assert.equal(await page.evaluate(()=>navigator.clipboard.readText()),await page.locator('#gnome-address').inputValue()); + await page.getByRole('button',{name:'Copy username',exact:true}).click(); + assert.equal(await page.evaluate(()=>navigator.clipboard.readText()),await page.locator('#dav-username').inputValue()); + await page.evaluate(()=>navigator.clipboard.writeText('')); + 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}); + 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/proxy.py b/qualification/passkeys/proxy.py index 0e8ade4..6ac2084 100644 --- a/qualification/passkeys/proxy.py +++ b/qualification/passkeys/proxy.py @@ -3,6 +3,7 @@ import http.client import json from pathlib import Path +import re import ssl import urllib.error import urllib.parse @@ -69,10 +70,18 @@ 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 + flows = set() + 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')}" + query = urllib.parse.parse_qs(target.query, keep_blank_values=True) + assert set(query) == {"flow"} and len(query["flow"]) == 1 and not target.fragment + handle = query["flow"][0] + assert re.fullmatch(r"[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}", handle) + assert handle not in flows, 'Each request must receive its own continuation' + flows.add(handle) + 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/passkeys/recovery.mjs b/qualification/passkeys/recovery.mjs index 1249a93..6721fff 100644 --- a/qualification/passkeys/recovery.mjs +++ b/qualification/passkeys/recovery.mjs @@ -1,3 +1,5 @@ +import {verifyPasskey,assertRejectedPasskey} from './authentication.mjs'; +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 +15,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, @@ -73,18 +62,20 @@ export async function qualifyRestoration({page, base, privateValues, administrat await page.locator('input[name=username]').fill(username); await page.locator('input[name=password]').fill(primaryPassword); await Promise.all([page.waitForURL(url => accountLocation(url, base)), - page.getByRole('button', {name: 'Verify password', exact: true}).click()]); + page.getByRole('button', {name: 'Sign in', exact: true}).click()]); } await page.goto(base + '/login'); - await Promise.all([page.waitForURL(base + '/'), page.getByRole('button', {name: 'Verify passkey', exact: true}).click()]); + await verifyPasskey(page,base); 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 device.getByRole('link', {name: 'Revoke', exact: true}).click(); + await Promise.all([page.waitForURL(base + '/security/credentials'), page.getByRole('button', {name: 'Revoke application password', 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()]); + await authorization.getByRole('link', {name: 'Revoke access', exact: true}).click(); + await Promise.all([page.waitForURL(base + '/oauth-grants'), page.getByRole('button', {name: 'Revoke app access', exact: true}).click()]); assert.equal((await call(base, '/dav/missing', {headers: {Authorization: 'Basic ' + credential.encoded}})).status, 401); assert.equal((await call(base, '/dav/missing', {headers: {Authorization: 'Bearer ' + grant.accessToken}})).status, 401); console.log('READY_RESTORE_APPLY'); @@ -97,8 +88,7 @@ export async function qualifyRestoration({page, base, privateValues, administrat await page.goto(base + '/'); await page.waitForURL(url => url.pathname === prefix + '/login'); assert.notEqual((await page.context().cookies()).find(value => value.name === 'JSESSIONID')?.value, oldCookie); - await page.getByRole('button', {name: 'Verify passkey', exact: true}).click(); - await page.locator('#security-status').filter({hasText: '(401)'}).waitFor(); + await assertRejectedPasskey(page,base); await cdp.send('WebAuthn.clearCredentials', {authenticatorId}); await page.goto(base + '/login'); const oldPasswordFile = federated ? process.env.BUSYSTACK_UPSTREAM_PASSWORD_FILE : process.env.BUSYSTACK_BROWSER_PASSWORD_FILE; @@ -107,7 +97,7 @@ export async function qualifyRestoration({page, base, privateValues, administrat await page.locator('input[name=username]').fill(username); await page.locator('input[name=password]').fill(oldPassword); await Promise.all([page.waitForURL(url => url.pathname === prefix + '/login' && url.searchParams.has('error')), - page.getByRole('button', {name: 'Verify password', exact: true}).click()]); + page.getByRole('button', {name: 'Sign in', exact: true}).click()]); if (federated) { await page.context().clearCookies({domain: /(^|\.)idp\.identity\.test$/}); await organizationPrimary(page, base, privateValues, true); @@ -117,14 +107,14 @@ export async function qualifyRestoration({page, base, privateValues, administrat await page.locator('input[name=username]').fill(username); 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(); + page.getByRole('button', {name: 'Sign in', exact: true}).click()]); + await page.getByRole('heading', {name: 'Create a passkey', exact: true}).waitFor(); } await primaryCannotMutate(page, base); await page.goto(base + '/security/passkeys'); - await page.getByRole('button', {name: 'Register passkey', exact: true}).click(); - 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()]); + await page.getByRole('button', {name: 'Create passkey', exact: true}).click(); + await page.locator('#security-status').filter({hasText: 'Passkey saved.'}).waitFor(); + await verifyPasskey(page,base); const fresh = await issueDavCredential(page, base, privateValues, 'Recovered device', username); await qualifyOAuth(page, base, privateValues, administratorPage, {clientId: grant.clientId, clientName: 'Browser Native Restore', existingClient: true}); @@ -144,13 +134,13 @@ export async function qualifyRestoration({page, base, privateValues, administrat await readerPage.goto(base + '/login'); await readerPage.locator('input[name=username]').fill(readerUsername); await readerPage.locator('input[name=password]').fill(readerPassword); - await Promise.all([readerPage.waitForURL(base + '/'), readerPage.getByRole('button', {name: 'Verify password', exact: true}).click()]); + await Promise.all([readerPage.waitForURL(url => url.pathname === new URL(base).pathname.replace(/\/$/,'') + '/auth/continue'), readerPage.getByRole('button', {name: 'Sign in', exact: true}).click()]); await primaryCannotMutate(readerPage, base); await readerPage.goto(base + '/security/passkeys'); - 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 readerPage.getByRole('button', {name: 'Create passkey', exact: true}).click(); + await readerPage.locator('#security-status').filter({hasText: 'Passkey saved.'}).waitFor(); + await verifyPasskey(readerPage,base); + 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 +151,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/recovery.py b/qualification/passkeys/recovery.py index a887426..0f0c66f 100644 --- a/qualification/passkeys/recovery.py +++ b/qualification/passkeys/recovery.py @@ -1,6 +1,7 @@ """Real HTTPS recovery checkpoint; state and credentials stay in the private fixture directory.""" import hashlib +from html.parser import HTMLParser import json import time import urllib.error @@ -78,6 +79,7 @@ def backup(self, environment): self.writer = self.operations.sql(environment, "SELECT id FROM accounts WHERE username='" + self.saved['writerUsername'] + "';") self.reader_path = '/dav/calendars/' + self.reader + '/' + self.saved['collection'] + '/restoration-fixture.ics' self.permissions(environment) + self.seed_journal(environment) self.audit_corpus.seed(environment) self.epoch = self.operations.sql(environment, 'SELECT recovery_epoch FROM system_state WHERE id=1;') if self.clients is not None: @@ -87,9 +89,7 @@ def backup(self, environment): # Use the supported public-client refresh flow after long measurements; never extend token policy. self.refresh_retained_grant() # The dump must contain a demonstrably live authenticated session, not an expired cookie. - cookie=self.saved['snapshotCookie'] - status,_,body=self.request('/', headers={'Cookie':'JSESSIONID='+cookie}) - assert status==200 and b'BusyStack account' in body, 'Snapshot browser session must be valid at backup' + self.verify_snapshot_session() print('HTTPS_RECOVERY_LIVE_SNAPSHOT_SESSION_VERIFIED',flush=True) # Benchmarking must not turn the revoked-credential proof into an accidental expiry test. assert self.request(self.resource_path, headers=basic)[0] == 200, 'Snapshot DAV credential expired before backup' @@ -98,6 +98,121 @@ def backup(self, environment): self.operations.execute(['./scripts/backup.sh', str(self.archive)], environment) print('HTTPS_RECOVERY_SNAPSHOT_WITH_VALID_DAV_OAUTH_AND_SYNC_CREATED', flush=True) + def seed_journal(self, environment): + basic = {'Authorization': 'Basic ' + self.saved['encoded']} + + def discover(path, namespace, property_name): + document = XML.Element('{DAV:}propfind') + XML.SubElement(XML.SubElement(document, '{DAV:}prop'), namespace + property_name) + status, _, payload = self.request(path, 'PROPFIND', + {**basic, 'Depth': '0', 'Content-Type': 'application/xml'}, XML.tostring(document)) + assert status == 207 + href = XML.fromstring(payload).findtext(f'.//{namespace}{property_name}/{{DAV:}}href') + assert href + candidate = urllib.parse.urlsplit(urllib.parse.urljoin(self.base + path, href)) + origin = urllib.parse.urlsplit(self.base) + prefix = origin.path.rstrip('/') + assert (candidate.scheme, candidate.netloc) == (origin.scheme, origin.netloc) + assert candidate.path.startswith(prefix + '/dav/') + return candidate.path[len(prefix):] + + principal = discover('/dav/', '{DAV:}', 'current-user-principal') + home = discover(principal, '{urn:ietf:params:xml:ns:caldav}', 'calendar-home-set') + self.journal_path = home.rstrip('/') + '/restoration-journals/' + self.journal_member = self.journal_path + 'kept-journal.ics' + deleted = self.journal_path + 'deleted-journal.ics' + create = (b'' + b'Restoration journals' + b'' + b'') + assert self.request(self.journal_path, 'MKCALENDAR', + {**basic, 'Content-Type': 'application/xml'}, create)[0] == 201 + raw = (b'BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//BusyStack//Recovery journal//EN\r\n' + b'BEGIN:VJOURNAL\r\nUID:recovery-journal\r\nDTSTAMP:20261126T000000Z\r\n' + b'DESCRIPTION;LANGUAGE=en:Original\r\nDESCRIPTION;LANGUAGE=fr:Second\r\n' + b'X-RESTORE:Preserved\r\nEND:VJOURNAL\r\nEND:VCALENDAR\r\n') + put = {**basic, 'Content-Type': 'text/calendar; charset=utf-8'} + status, headers, _ = self.request(self.journal_member, 'PUT', {**put, 'If-None-Match': '*'}, raw) + assert status == 201 + self.journal_content = raw.replace(b'Original', b'Updated before backup') + status, changed, _ = self.request(self.journal_member, 'PUT', {**put, 'If-Match': headers['ETag']}, + self.journal_content) + assert status == 204 and changed['ETag'] != headers['ETag'] + self.journal_etag = changed['ETag'] + status, tombstone, _ = self.request(deleted, 'PUT', {**put, 'If-None-Match': '*'}, + raw.replace(b'UID:recovery-journal', b'UID:recovery-journal-deleted')) + assert status == 201 + assert self.request(deleted, 'DELETE', {**basic, 'If-Match': tombstone['ETag']})[0] == 204 + principal_base = self.base + '/dav/principals/' + ace = ''.join(f'{principal_base}{account}/' + f'{write}' + for account, write in [(self.reader, ''), (self.writer, '')]) + assert self.request(self.journal_path, 'ACL', {**basic, 'Content-Type': 'application/xml'}, + f'{ace}'.encode())[0] == 200 + status, _, inventory = self.report(self.saved['encoded'], path=self.journal_path) + assert status == 207 + self.journal_token = XML.fromstring(inventory).findtext('{DAV:}sync-token') + assert self.journal_token + self.journal_collection = self.operations.sql(environment, + "SELECT id FROM collections WHERE name='Restoration journals' AND component='VJOURNAL';") + + def verify_journal(self, current): + owner = {'Authorization': 'Basic ' + current['recoveredEncoded']} + assert self.request(self.journal_member, headers={'Authorization': 'Basic ' + self.saved['encoded']})[0] == 401 + status, headers, content = self.request(self.journal_member, headers=owner) + assert status == 200 and headers['ETag'] == self.journal_etag and content == self.journal_content + status, _, invalid = self.report(current['recoveredEncoded'], self.journal_token, path=self.journal_path) + assert status == 403 and XML.fromstring(invalid).find('{DAV:}valid-sync-token') is not None + status, _, rebuilt = self.report(current['recoveredEncoded'], path=self.journal_path) + assert status == 207 + doc = XML.fromstring(rebuilt) + assert doc.findtext('{DAV:}sync-token') not in ('', None, self.journal_token) + members = [node.text.rsplit('/', 1)[-1] for node in doc.findall('.//{DAV:}href') if node.text] + assert 'kept-journal.ics' in members and 'deleted-journal.ics' not in members + assert self.request(self.journal_path + 'deleted-journal.ics', headers=owner)[0] == 404 + reader = {'Authorization': 'Basic ' + current['readerEncoded']} + path = f'/dav/calendars/{self.reader}/{self.journal_collection}/kept-journal.ics' + status, _, content = self.request(path, headers=reader) + assert status == 200 and content == self.journal_content + assert self.request(path, 'DELETE', {**reader, 'If-Match': self.journal_etag})[0] == 403 + print('HTTPS_RECOVERY_DAV_JOURNAL_UPDATE_SHARED_READBACK_FRESH_SYNC_AND_NO_RESURRECTION_PASSED', flush=True) + + def verify_snapshot_session(self): + """Prove the current authenticated account page, independent of obsolete page copy.""" + class AccountPage(HTMLParser): + def __init__(self): + super().__init__() + self.main = self.identity = self.logout = self.csrf = self.in_logout = False + self.paragraph = None + def handle_data(self, value): + if self.paragraph is not None and value.strip(): + self.paragraph.append(value.strip()) + def handle_starttag(self, tag, attributes): + attributes = dict(attributes) + if tag == 'main' and attributes.get('id') == 'main': + self.main = True + if tag == 'p' and self.main: + self.paragraph = [] + if tag == 'form': + self.in_logout = (attributes.get('method', '').lower() == 'post' + and urllib.parse.urlsplit(attributes.get('action', '')).path == logout) + self.logout |= self.in_logout + if tag == 'input' and self.in_logout: + self.csrf |= attributes.get('name') == '_csrf' and bool(attributes.get('value')) + def handle_endtag(self, tag): + if tag == 'p' and self.paragraph is not None: + self.identity |= (len(self.paragraph) >= 3 + and self.paragraph[0] == 'Signed in as' and self.paragraph[-2] == username) + self.paragraph = None + if tag == 'main': self.main = False + if tag == 'form': self.in_logout = False + logout = urllib.parse.urlsplit(self.base).path.rstrip('/') + '/logout' + username = self.saved['username'] + status, _, body = self.request('/', headers={'Cookie':'JSESSIONID='+self.saved['snapshotCookie']}) + page = AccountPage() + page.feed(body.decode('utf-8')) + assert status == 200 and page.identity and page.logout and page.csrf, 'Snapshot browser session must identify its authenticated account and protected logout form at backup' + def refresh_retained_grant(self): old=self.saved['grant'] status,_,body=self.request('/oauth2/token','POST',{'Content-Type':'application/x-www-form-urlencoded'}, @@ -243,6 +358,7 @@ def verify(self): print('HTTPS_RECOVERY_RESTORED_READ_SHARE_GET_ALLOWED_PUT_DENIED', flush=True) print('HTTPS_RECOVERY_OLD_CREDENTIALS_AND_SYNC_REJECTED_FRESH_ACCESS_PRESERVES_TASK', flush=True) self.audit_corpus.verify_restored(current['recoveredEncoded'], current['readerEncoded']) + self.verify_journal(current) def verify_revoked_reader(self): current = json.loads(self.exchange.read_text()) diff --git a/qualification/passkeys/run.py b/qualification/passkeys/run.py index cea6b12..91fea3d 100644 --- a/qualification/passkeys/run.py +++ b/qualification/passkeys/run.py @@ -73,13 +73,24 @@ 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("--portability-crash", action="store_true", help="Kill the owned application during an actual import transaction and verify rollback/restart/fresh import") + parser.add_argument("--gnome", action="store_true", help="Also drive the installed GNOME connection wizard in an isolated home/DBus/private Xvfb session") + parser.add_argument("--gnome-only", action="store_true", help="Target only real MFA, portal collection/credential setup and the native GNOME connection wizard") 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"))) + parser.add_argument("--evidence-directory", type=Path, default=ROOT / "target/qualification/portal-browser", + help="Parent directory for local browser qualification evidence") parser.add_argument("--workload-output", default=str(ROOT / "target/qualification/workload.json")) 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_only: + if args.groups or args.oidc or args.restore or args.workload or args.clients or args.strict_sync_depth or args.portability_crash: + parser.error("--gnome-only is a separate targeted setup profile; run full browser/security profiles independently") + args.gnome = True + 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)): @@ -160,7 +171,8 @@ def main(): issuer = None if args.oidc: operations.execute(["docker", "image", "inspect", oidc.IMAGE], environment) - upstream_override, issuer = oidc.configure(ROOT, directory, base, operations.execute, environment) + upstream_override, issuer = oidc.configure( + ROOT, directory, base, operations.execute, environment) environment["COMPOSE_FILE"] += ":" + str(upstream_override) environments = [environment.copy()] checkpoint = recovery.Checkpoint(ROOT, directory, operations, base, oidc if args.oidc else None, issuer, environments) if args.restore else None @@ -171,6 +183,8 @@ def main(): checkpoint.exchange.touch(mode=0o600) if args.workload: checkpoint.workload = {"python": args.client_python, "output": args.workload_output, "thunderbird": args.thunderbird_binary} + evidence = args.evidence_directory.resolve() / project + evidence.mkdir(parents=True, mode=0o700) browser = None sharing_load = None try: @@ -208,12 +222,22 @@ def main(): browser_command += ["--env", "BUSYSTACK_BROWSER_CAPACITY=true"] if args.groups: browser_command += ["--env", "BUSYSTACK_BROWSER_GROUPS=true"] + if args.portability_crash: + browser_command += ["--env", "BUSYSTACK_PORTABILITY_CRASH=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 args.gnome_only: + browser_command += ["--env", "BUSYSTACK_GNOME_ONLY=true"] 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", "--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"] + browser_command += ["--volume", f"{evidence}:/evidence:rw", "--env", "BUSYSTACK_PORTAL_EVIDENCE=/evidence"] browser_command.append(args.browser_image) browser = subprocess.Popen( browser_command, @@ -226,7 +250,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) @@ -243,7 +267,40 @@ 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_PORTABILITY_CRASH_ARM" and args.portability_crash: + operations.sql(environment, "CREATE FUNCTION qualification_import_pause() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.uid='interrupted-b' THEN PERFORM pg_sleep(30); END IF; RETURN NEW; END $$; CREATE TRIGGER qualification_import_pause BEFORE INSERT ON calendar_resources FOR EACH ROW EXECUTE FUNCTION qualification_import_pause();") + browser.stdin.write(b"PORTABILITY_CRASH_ARMED\n") + browser.stdin.flush() + elif line == "READY_PORTABILITY_CRASH_REQUESTED" and args.portability_crash: + stop = time.monotonic() + 45 + while operations.sql(environment, "SELECT count(*) FROM pg_stat_activity WHERE wait_event='PgSleep' AND query LIKE 'INSERT INTO calendar_resources%';") != "1": + if time.monotonic() > stop: + raise RuntimeError("The real import did not reach the second-write interruption checkpoint") + threading.Event().wait(.25) + operations.compose(environment, "kill", "--signal", "SIGKILL", "application") + # DDL waits for the interrupted backend to release its transaction locks. + operations.sql(environment, "DROP TRIGGER qualification_import_pause ON calendar_resources; DROP FUNCTION qualification_import_pause();") + assert operations.sql(environment, "SELECT count(*) FROM calendar_resources WHERE uid IN ('interrupted-a','interrupted-b');") == "0" + operations.compose(environment, "up", "-d", "--no-build", "--wait", "--wait-timeout", "240", "application") + ready(base, directory / "ca.pem", args.proxy) + browser.stdin.write(b"PORTABILITY_CRASH_RESTARTED\n") + browser.stdin.flush() + elif line == "READY_PORTABILITY_CRASH_VERIFY" and args.portability_crash: + assert operations.sql(environment, "SELECT count(*) FROM calendar_resources WHERE uid IN ('interrupted-a','interrupted-b');") == "2" + (evidence / "portability-process-interruption.json").write_text(json.dumps({"imageId": args.application_image, "interruptedAt": "PostgreSQL second resource insert; first write was uncommitted", "signal": "SIGKILL", "resourcesAfterRollback": 0, "resourcesAfterFreshImport": 2, "pendingPreviewInvalidAfterRestart": True}, indent=2) + "\n") + browser.stdin.write(b"PORTABILITY_CRASH_VERIFIED\n") + browser.stdin.flush() + elif line == "READY_GNOME" and args.gnome: + gnome_fixture = json.loads(gnome_exchange.read_text()) + gnome_fixture["ca"] = str(directory / "ca.pem") + gnome_fixture["displayImage"] = args.browser_image + 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") @@ -286,17 +343,43 @@ def main(): except subprocess.TimeoutExpired as error: raise RuntimeError("Browser qualification exceeded its deadline") from error assert result == 0, "Browser qualification failed" + if args.gnome_only: + assert "NATIVE_CONNECTION_SETUP_ONLY_PASSED" in signals + print("PASS: targeted real MFA, portal collection/credential setup and native GNOME connection wizard. Recovery, OAuth, groups, restore and restart are unexecuted in this targeted profile.") + return for expected in ("PASSWORD_PLUS_WEBAUTHN_AND_MUTATION_PASSED", "BROWSER_SINGLE_USE_PRIMARY_PLUS_RECOVERY_CODE_RESET_AND_FRESH_MFA_PASSED", "BROWSER_DAV_CREDENTIAL_ISSUANCE_DISPLAY_ONCE_AND_REVOCATION_PASSED", "BROWSER_S256_CONSENT_TOKEN_REFRESH_AND_GRANT_REVOCATION_PASSED", "BROWSER_CONSENT_WITHOUT_CSRF_REJECTED", "PERSISTED_PASSKEY_AFTER_RESTART_PASSED", "DISABLED_SESSION_AND_PASSKEY_PASSED"): assert expected in signals, expected if args.oidc: assert "CROSS_SITE_ORGANIZATION_PLUS_PASSKEY_AND_NONADMIN_PROVISIONING_PASSED" in signals if args.groups: assert "BROWSER_GROUP_MEMBERSHIP_UPDATE_DELETE_AND_OWNER_GRANTS_PASSED" in signals + if args.portability_crash: + assert "PORTABILITY_PROCESS_INTERRUPTION_ROLLBACK_RESTART_AND_FRESH_IMPORT_PASSED" in signals if args.restore: assert "HTTPS_RESTORE_OLD_ACCESS_REJECTED_FRESH_MFA_DAV_OAUTH_CONTENT_AND_SYNC_PASSED" in signals 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") @@ -310,6 +393,14 @@ def main(): if value: raw = raw.replace(value, "[redacted]") raw = re.sub(r"[A-Za-z0-9_+/=-]{40,}", "[redacted-value]", raw) raw = re.sub(r"([?&](?:code|state|code_challenge)=)[^&\s)\"]+", r"\1[redacted]", raw) + if args.gnome: + # Coarse native-client troubleshooting only; never retain paths, headers or bodies. + from collections import Counter + responses = Counter((method,status) for method,status in re.findall( + r"surface=dav method=([A-Z]+) status=(\d+|unavailable)",raw)) + (evidence / 'gnome-dav-response-summary.json').write_text(json.dumps([ + {'method':method,'status':status,'count':count} + for (method,status),count in sorted(responses.items())],indent=2)+'\n') for line in raw.splitlines(): if any(marker in line for marker in (" ERROR ", "Caused by:", "APPLICATION FAILED", "Description:", "Reason:", "Action:")): print("APPLICATION_DIAGNOSTIC " + line, flush=True) 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/passkeys/test_recovery_refresh.py b/qualification/passkeys/test_recovery_refresh.py index 267c987..a7b03a3 100644 --- a/qualification/passkeys/test_recovery_refresh.py +++ b/qualification/passkeys/test_recovery_refresh.py @@ -44,3 +44,29 @@ def test_failed_endpoint_response_does_not_fabricate_fresh_expiry(self): with self.assertRaises(AssertionError): self.checkpoint.refresh_retained_grant() self.assertEqual(self.checkpoint.saved['grant']['accessExpiresAt'],0) self.assertFalse(self.checkpoint.exchange.exists()) + + def test_current_account_page_proves_live_snapshot_without_historical_heading(self): + self.checkpoint.saved.update(username='snapshot-user') + for prefix in ('', '/team'): + self.checkpoint.base='https://localhost:1234'+prefix + body=(f'

Overview

Signed in as Display name ' + f'(snapshot-user).

' + '
').encode() + self.checkpoint.request=lambda *args,**kwargs:(200,{},body) + self.checkpoint.verify_snapshot_session() + + def test_redirect_wrong_account_public_or_unprotected_page_cannot_prove_snapshot(self): + self.checkpoint.base='https://localhost:1234/team' + self.checkpoint.saved.update(username='snapshot-user') + valid=(b'

Signed in as snapshot-user.

' + b'
') + wrong_account=valid.replace(b'snapshot-user',b'other-user').replace( + b'',b'

snapshot-user

') + wrong_username=valid.replace(b'.

',b' (other-user).

') + for status,body in ((302,valid),(200,wrong_account),(200,wrong_username),(200,b'Sign in to BusyStack'), + (200,b'BusyStack account snapshot-user'),(200,valid.replace(b'value="synthetic-csrf"',b'value=""')), + (200,valid.replace(b'name="_csrf"',b'name="unrelated"')), + (200,valid.replace(b'/team/logout',b'/logout'))): + with self.subTest(status=status,body=body): + self.checkpoint.request=lambda *args,**kwargs:(status,{},body) + with self.assertRaises(AssertionError):self.checkpoint.verify_snapshot_session() diff --git a/qualification/portability/README.md b/qualification/portability/README.md new file mode 100644 index 0000000..2e79870 --- /dev/null +++ b/qualification/portability/README.md @@ -0,0 +1,62 @@ +# Portability correction qualification + +`PortalManagementIT` exercises actual PostgreSQL and HTTPS multipart upload, +preview, paginated results, confirmation, rollback/retry, concurrent confirmation, +security epochs, permissions, and a 10,000-resource / more-than-60-MiB round trip. +Its maximum case also overlaps real exports with a retained preview and checks +capacity rejection, byte-identical downloads, disk/reservation/heap/RSS samples. +Measurements are in `target/qualification/portability/large-http.json`. Unit tests +exercise private permissions, recognized-orphan cleanup, symlink rejection, +cleanup failures, reservations, file count, stage expiry and uncertain completion. +These are separate from packaged browser and deployment results. + +After the complete Maven verification and local image build, run: + +```sh +python3 qualification/portability/temporary_storage.py \ + --application-image busystack-caldav:YOUR_VERIFIED_LOCAL_TAG \ + --java-home /absolute/path/to/selected-jdk \ + --jar target/caldav-server-0.2.0.jar +``` + +This fixture creates only its own disposable Compose project and host-private +directory. It verifies the read-only application filesystem, 384 MiB tmpfs, +private permissions, forced container termination and restart, then runs the exact +JAR against that disposable PostgreSQL instance with a persistent private staging +directory. Seeded recognized files model interrupted staging. It proves they +remain while the standalone process is stopped, disappear on its next startup, +and unrelated files survive. It does not substitute for actual HTTP import or +in-flight database-transaction interruption tests. Its receipt includes image/JAR +identity and is written to `target/qualification/portability/temporary-storage.json`. + +Run the documented packaged browser profiles in +[passkeys](../passkeys/README.md) against the same image. Their form checks cover +summary focus, links to invalid controls, accessible error associations, +nonsensitive value preservation, password omission, correction/resubmission and +desktop/mobile screenshots. Recovery uses the checkout's existing qualification +checkpoint changes; do not omit them from the browser image. Run browser profiles +sequentially, after other Docker integration jobs finish, to avoid unrelated +network changes during navigation. Existing native client fixtures qualify DAV +separately from Thunderbird's single-VCALENDAR file-parser limitation. + +Generated receipts qualify only their actual source and artifact. Fixture presence +is not a passing result, and virtual WebAuthn does not qualify physical devices. + +For actual interruption during confirmation, add `--portability-crash` to a full +packaged browser profile (for example root `--groups --portability-crash`). The +owned fixture pauses the second insert after the first uncommitted resource write, +observes PostgreSQL's checkpoint, sends SIGKILL to only that application's +container, and checks zero resources after rollback. The same real browser then +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 new file mode 100644 index 0000000..518b9fa --- /dev/null +++ b/qualification/portability/temporary_storage.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +"""Exercise packaged private staging on Compose tmpfs and a standalone JAR restart. + +Only disposable fixture files/projects are touched. Seeded files model interrupted +staging; actual HTTP preview/confirmation behavior has separate regression tests. +""" +import argparse +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import secrets +import socket +import subprocess +import tempfile +import time +import urllib.error +import urllib.request +import uuid + +ROOT = Path(__file__).resolve().parents[2] +spec = importlib.util.spec_from_file_location('operations', ROOT / 'scripts/verify-operations.py') +operations = importlib.util.module_from_spec(spec) +spec.loader.exec_module(operations) + + +def ready(base, process): + deadline = time.monotonic() + 180 + while time.monotonic() < deadline: + if process.poll() is not None: + raise RuntimeError('Standalone JAR stopped before readiness; inspect private fixture log') + try: + with urllib.request.urlopen(base + '/actuator/health/readiness', timeout=2) as response: + if response.status == 200 and json.load(response)['status'] == 'UP': + return + except (urllib.error.URLError, TimeoutError, ConnectionError): + pass + time.sleep(.25) + 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) + parser.add_argument('--java-home', type=Path, required=True) + parser.add_argument('--jar', type=Path, required=True) + parser.add_argument('--output', type=Path, default=ROOT / 'target/qualification/portability/temporary-storage.json') + args = parser.parse_args() + env = os.environ.copy() + env.update(operations.development_environment(args.application_image)) + image_id = operations.execute(['docker', 'image', 'inspect', '--format', '{{.Id}}', args.application_image], env) + with tempfile.TemporaryDirectory(prefix='busystack-storage-') as temporary: + root = Path(temporary) + root.chmod(0o700) + config = root / 'secrets' + config.mkdir(mode=0o700) + for name in ('spring.datasource.password', 'admin-password'): + path = config / name + path.write_text(secrets.token_urlsafe(32) + '\n') + path.chmod(0o444) + override = root / 'compose.yaml' + override.write_text("services:\n database:\n ports:\n - '127.0.0.1::5432'\n application:\n ports: !override\n - '127.0.0.1::8080'\n") + env.update(COMPOSE_FILE=f'{ROOT / "compose.yaml"}:{override}', COMPOSE_PATH_SEPARATOR=':', + COMPOSE_PROJECT_NAME='busystack-storage-' + secrets.token_hex(6), + BUSYSTACK_DATABASE_PASSWORD_FILE=str(config / 'spring.datasource.password'), + BUSYSTACK_POSTGRES_ADMIN_PASSWORD_FILE=str(config / 'admin-password'), + BUSYSTACK_PUBLIC_BASE_URL='https://calendar.example.test', BUSYSTACK_ISSUER='https://calendar.example.test') + process = None + try: + operations.compose(env, 'up', '-d', '--no-build', '--wait', '--wait-timeout', '240') + 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'] + 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 + operations.compose(env, 'exec', '-T', 'application', 'sh', '-ec', + 'test "$(stat -c %a /tmp/busystack-portability)" = 700; test "$(stat -c %a /tmp/busystack-portability/multipart)" = 700; umask 077; printf fixture > /tmp/busystack-portability/data-11111111-1111-4111-8111-111111111111.private; test "$(stat -c %a /tmp/busystack-portability/data-11111111-1111-4111-8111-111111111111.private)" = 600') + operations.compose(env, 'kill', '--signal', 'SIGKILL', 'application') + operations.compose(env, 'up', '-d', '--no-build', '--wait', '--wait-timeout', '240', 'application') + operations.compose(env, 'exec', '-T', 'application', 'sh', '-ec', + 'test ! -e /tmp/busystack-portability/data-11111111-1111-4111-8111-111111111111.private') + operations.compose(env, 'stop', 'application') + database = operations.compose(env, 'port', 'database', '5432').splitlines()[0] + temp = root / 'jar-temp' + temp.mkdir(mode=0o700) + with socket.socket() as listener: + listener.bind(('127.0.0.1', 0)) + port = listener.getsockname()[1] + jar_env = os.environ.copy() + jar_env.update(SPRING_CONFIG_IMPORT='configtree:' + str(config) + '/', + 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', '-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, 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') + orphan.write_text('BEGIN:VCALENDAR\r\nPRIVATE CRASH FIXTURE\r\nEND:VCALENDAR\r\n') + orphan.chmod(0o600) + multipart = staging / 'multipart/upload_fixture_0001.tmp' + multipart.write_text('private interrupted upload') + multipart.chmod(0o600) + unrelated = staging / 'operator-notes' + unrelated.write_text('preserve unrelated file') + unrelated.chmod(0o600) + 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, 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' + process.terminate() + assert process.wait(timeout=45) == 143 + result = dict(imageId=image_id, jarSha256=hashlib.sha256(args.jar.read_bytes()).hexdigest(), + composeReadOnly=True, composeTmpfsBytes=384 * 1024 * 1024, + composeForcedTerminationClean=True, standaloneForcedTerminationRemnantsObserved=True, + standaloneStartupOrphansRemoved=True, unrelatedFilePreserved=True, + 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') + print(json.dumps(result)) + finally: + if process is not None and process.poll() is None: + process.kill() + process.wait(timeout=30) + operations.compose(env, 'down', '--volumes', '--remove-orphans', '--timeout', '10') + + +if __name__ == '__main__': + main() diff --git a/qualification/proxy/nginx.conf.template b/qualification/proxy/nginx.conf.template index 85d566f..8cc649c 100644 --- a/qualification/proxy/nginx.conf.template +++ b/qualification/proxy/nginx.conf.template @@ -34,6 +34,43 @@ 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; + proxy_connect_timeout 5s; + proxy_read_timeout 660s; + proxy_request_buffering off; + proxy_buffering off; + 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@@/portability/ { + client_max_body_size 1m; + proxy_http_version 1.1; + proxy_connect_timeout 5s; + proxy_read_timeout 660s; + proxy_request_buffering off; + proxy_buffering off; + 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/qualification/release/test_release.py b/qualification/release/test_release.py index c5938fb..955a7e2 100644 --- a/qualification/release/test_release.py +++ b/qualification/release/test_release.py @@ -1,4 +1,5 @@ """Isolated multi-version release and source/controller provenance regressions.""" +import argparse import copy from contextlib import contextmanager, ExitStack import hashlib @@ -34,6 +35,8 @@ def load(name): bundle = load('release-bundle') builder = load('build-image') integrity = load('verify-dependency-integrity') +installation = load('verify-installation-bundle') +operations = load('verify-operations') SHA = 'a' * 40 VERSIONS = ('0.1.0', '0.2.0', '1.0.0') CLIENTS = ('thunderbird-system-vancouver', 'thunderbird-explicit-vancouver', 'thunderbird-explicit-berlin', 'gnome-vancouver') @@ -74,7 +77,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: @@ -290,10 +293,53 @@ def test_every_bundle_input_is_isolated_from_newer_controller(self): self.assertIn(versions.jar_name(version), installation) self.assertIn(versions.deployment_name(version), installation) self.assertNotIn('@VERSION@', installation) + operations = archive.extractfile(prefix + 'docs/operations.md').read().decode() + self.assertIn('proxy_pass http://127.0.0.1:8080;', operations) + self.assertNotIn('127.' + version + ':8080', operations) self.assertIn(prefix + versions.receipt_path(version), archive.getnames()) self.assertFalse(any('website-handoff' in n or 'docs/development/' in n for n in archive.getnames())) self.assertEqual(manifest['container']['localTestedImageId'], record['imageId']) + def test_installation_verifier_accepts_generated_bundle(self): + with fixture('0.2.0') as (directory, root, source, _): + assets = directory / 'assets' + manifest = bundle.build(source, 'sha256:' + '1' * 64, assets) + image = manifest['container']['image'] + receipt = directory / 'installation.json' + with tarfile.open(assets / manifest['deployment']['name']) as archive: + self.assertIn('caldav-server-0.2.0-deploy/pom.xml', archive.getnames()) + image_metadata = json.dumps([{'Architecture': 'amd64', 'Os': 'linux', 'Config': {'Labels': { + 'org.opencontainers.image.version': manifest['version'], + 'org.opencontainers.image.revision': manifest['sourceCommit'], + }}}]).encode() + with ( + patch.object(sys, 'argv', ['verify-installation-bundle.py', '--assets', str(assets), + '--output', str(receipt)]), + patch.object(installation.subprocess, 'run'), + patch.object(installation.subprocess, 'check_output', + side_effect=[image_metadata, manifest['jar']['sha256'] + ' application.jar']), + patch.object(installation, 'load', return_value=operations), + patch.object(operations, 'ROOT', root), + patch.object(operations, 'verify') as verify, + patch.object(installation, 'https_bundle_smoke'), + patch.object(installation, 'jar_smoke', return_value={'status': 'passed'}), + ): + installation.main() + self.assertEqual([(args.image, profile) for (args, profile), _ in verify.call_args_list], + [(image, None), (image, '9')]) + self.assertEqual(json.loads(receipt.read_text())['status'], 'passed') + + def test_operations_accepts_image_only_options_for_both_profiles(self): + for profile in (None, '9'): + with ( + self.subTest(profile=profile), + patch.object(operations, 'development_environment', + side_effect=RuntimeError('Reached operations setup')) as setup, + ): + with self.assertRaisesRegex(RuntimeError, 'Reached operations setup'): + operations.verify(argparse.Namespace(image='test-image'), profile) + setup.assert_called_once_with('test-image') + def test_snapshot_changes_and_missing_source_inputs_reject(self): with fixture() as (directory, root, source, record): snapshot = source / 'source.tar.gz' @@ -603,5 +649,47 @@ def test_packaged_modified_dependency_and_removed_classes_reject(self): integrity.inspect(jar, lock) +class GuideIntegrityTest(unittest.TestCase): + def test_supporting_document_links_require_their_packaged_targets(self): + files = {'docs/operations.md': b'[Security](account-security.md)', + 'docs/account-security.md': b'Security instructions'} + bundle.validate_document_links(files) + files.pop('docs/account-security.md') + with self.assertRaisesRegex(AssertionError, 'Broken deployment document reference'): + bundle.validate_document_links(files) + + def test_heading_anchors_match_document_headings_and_reject_missing_anchors(self): + files = { + 'docs/start.md': b'[Relative](help.md#using-a-passkey) [Local](#use-a-password)\n## Use a password', + 'docs/help.md': '## Using a passkey\n## Using a passkey\n## Setup & recovery'.encode(), + } + self.assertIn('using-a-passkey-1', bundle.heading_anchors(files['docs/help.md'].decode())) + bundle.validate_document_links(files) + files['docs/start.md'] += b'\n[Broken](help.md#gone)' + with self.assertRaisesRegex(AssertionError, 'Broken deployment document heading anchor'): + bundle.validate_document_links(files) + + def test_missing_guide_missing_screenshot_and_broken_link_fail_validation(self): + files = {str(p.relative_to(ROOT)): p.read_bytes() + for base in ('docs', 'deployment') for p in (ROOT / base).rglob('*') if p.is_file()} + version = versions.resolve(ROOT) + files['docs/GETTING_STARTED.md'] = files['docs/GETTING_STARTED.md'].replace(b'@VERSION@', version.encode()) + receipt = versions.receipt_path(version) + files[receipt] = (ROOT / receipt).read_bytes() + bundle.validate_guide(files) + without_guide = files.copy() + without_guide.pop('docs/GETTING_STARTED.md') + with self.assertRaises(KeyError): + bundle.validate_guide(without_guide) + without_image = files.copy() + without_image.pop(bundle.SCREENSHOTS[0]) + with self.assertRaisesRegex(AssertionError, 'Missing guide screenshot'): + bundle.validate_guide(without_image) + broken = files.copy() + broken['docs/GETTING_STARTED.md'] += b'\n[Missing supporting document](missing-guide.md)\n' + with self.assertRaisesRegex(AssertionError, 'Broken guide reference'): + bundle.validate_guide(broken) + + if __name__ == '__main__': unittest.main() diff --git a/scripts/initialize.sh b/scripts/initialize.sh new file mode 100755 index 0000000..3d5f4a0 --- /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 initialization \ + --spring.main.web-application-type=none \ + --spring.main.banner-mode=off --logging.level.root=OFF \ + --busystack.issue-initialization-code=true diff --git a/scripts/install-ci-jdk.sh b/scripts/install-ci-jdk.sh index 386e8bb..7177c02 100755 --- a/scripts/install-ci-jdk.sh +++ b/scripts/install-ci-jdk.sh @@ -1,12 +1,11 @@ #!/usr/bin/env bash set -euo pipefail -# Use the same immutable Temurin distribution as the application image. setup-java's -# SemVer input cannot represent this four-part Java maintenance release exactly. +# Extract the exact immutable Temurin distribution used by the application image. : "${RUNNER_TEMP:?RUNNER_TEMP must be set by the GitHub runner}" : "${GITHUB_ENV:?GITHUB_ENV must be set by the GitHub runner}" : "${GITHUB_PATH:?GITHUB_PATH must be set by the GitHub runner}" -jdk_image='eclipse-temurin:25-jdk@sha256:3ab7fc8d0b4ade8fef96903fb36767c1dbb4fd1535dcfad85b59c17afbbb5857' +jdk_image='eclipse-temurin:25.0.5.1_2-jdk-resolute@sha256:d1b500f1a2a8e2cb1b0fa84e21c4a52963050cbd46b8a53fcb6a8eec0f57675f' jdk_directory=$(mktemp -d "${RUNNER_TEMP}/busystack-jdk.XXXXXXXX") jdk_container='' cleanup() { @@ -30,10 +29,10 @@ jdk = Path(sys.argv[1]) release = dict(line.split('=', 1) for line in (jdk / 'release').read_text().splitlines() if '=' in line) expected = { 'IMPLEMENTOR': 'Eclipse Adoptium', - 'IMPLEMENTOR_VERSION': 'Temurin-25.0.4.1+1', - 'JAVA_VERSION': '25.0.4.1', - 'JAVA_RUNTIME_VERSION': '25.0.4.1+1-LTS', - 'SEMANTIC_VERSION': '25.0.4.1+1', + 'IMPLEMENTOR_VERSION': 'Temurin-25.0.5.1+2', + 'JAVA_VERSION': '25.0.5.1', + 'JAVA_RUNTIME_VERSION': '25.0.5.1+2-LTS', + 'SEMANTIC_VERSION': '25.0.5.1+2', 'IMAGE_TYPE': 'JDK', } for name, value in expected.items(): diff --git a/scripts/release-bundle.py b/scripts/release-bundle.py index 8fe6e6a..5f4912f 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', @@ -30,7 +35,117 @@ 'docs/third-party-licenses.md', 'docs/versions.md', 'docs/adr/0004-resumable-synchronization.md', + 'docs/adr/0001-protocol-engine.md', + 'docs/adr/0002-native-oauth-refresh.md', + 'docs/conformance.md', + 'docs/ical4j-parser-patch.md', + 'docs/ical4j-timezone-patch.md', + 'docs/security-verification.md', + 'docs/standards-corrections.md', + 'docs/standards-review.md', + 'investigation/oauth/README.md', + 'investigation/protocol/src/test/java/org/busystack/caldav/investigation/BedeworkHttpTest.java', + 'qualification/clients/README.md', + 'qualification/evidence/README.md', + 'qualification/evidence/vjournal-admission.md', + 'qualification/evidence/vjournal-nextcloud-35.0.3.jsonl', + 'qualification/evidence/releases/0.0.1/summary.json', + 'qualification/evidence/releases/0.1.0/README.md', + 'qualification/evidence/releases/0.1.0/verification.json', + 'qualification/keycloak/Dockerfile', + 'qualification/passkeys/README.md', + 'qualification/portability/README.md', + 'qualification/security/README.md', + 'pom.xml', + '.github/workflows/ci.yml', ) +SCREENSHOTS = tuple(f'docs/images/getting-started/{name}.png' for name in ( + '01-protected-setup', + '02-sign-in', + '03-create-passkey', + '04-passkey-saved', + '05-overview', + '06-server-administration', + '07-accounts', + '08-create-account', + '09-account-handoff', + '10-resource-type', + '11-empty-task-list', + '12-resources', + '13-sharing', + '14-security', + '15-recovery-codes', + '16-connect-an-app', + '17-client-configuration', + '18-create-application-password', + '19-password-created', + '20-import-destination', + '21-import-preview', + '22-import-result', + '23-audit', + '24-diagnostics', + '25-shared-overview', + '26-returning-verification', + '27-sharing-error', + '28-share-removal-review', + '29-credential-management', + '30-import-report-unavailable', +)) + + +def heading_anchors(document): + """Return GitHub-style ATX heading identifiers, with duplicate suffixes.""" + identifiers = set() + occurrences = {} + fenced = False + for line in document.splitlines(): + if re.match(r'^\s*(?:```|~~~)', line): + fenced = not fenced + if fenced: + continue + heading = re.match(r'^ {0,3}#{1,6}\s+(.+?)\s*#*$', line) + if heading is None: + continue + title = re.sub(r'\[([^]]+)\]\([^)]+\)', r'\1', heading[1]) + identifier = re.sub(r'[^\w -]', '', title.lower()).replace(' ', '-') + occurrence = occurrences.get(identifier, 0) + occurrences[identifier] = occurrence + 1 + identifiers.add(identifier if occurrence == 0 else f'{identifier}-{occurrence}') + identifiers.update(re.findall(r' 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 @@ -73,6 +78,12 @@ BEGIN IF to_regclass('public.external_identities') IS NOT NULL THEN UPDATE external_identities SET last_verified_at = timestamptz '1970-01-01 00:00:00+00'; END IF; + IF to_regclass('public.browser_issuance_intents') IS NOT NULL THEN + DELETE FROM browser_issuance_intents; + END IF; + IF to_regclass('public.browser_flow_state') IS NOT NULL THEN + DELETE FROM browser_flow_state; + END IF; IF to_regclass('public.spring_session') IS NOT NULL THEN DELETE FROM spring_session; DELETE FROM account_recovery_codes; diff --git a/scripts/verify-installation-bundle.py b/scripts/verify-installation-bundle.py index 73bebe8..f28fff3 100644 --- a/scripts/verify-installation-bundle.py +++ b/scripts/verify-installation-bundle.py @@ -186,7 +186,8 @@ def main(): with tarfile.open(assets / manifest['deployment']['name']) as archive: archive.extractall(directory, filter='data') extracted = directory / ('caldav-server-' + manifest['version'] + '-deploy') - assert not (extracted / 'src').exists() and not (extracted / 'pom.xml').exists() + # The operator documentation links to pom.xml as dependency/build metadata. + assert not (extracted / 'src').exists() assert 'build:' not in (extracted / 'compose.yaml').read_text() assert image in (extracted / 'compose.yaml').read_text() # Reuse established procedure assertions while resolving every deployment path diff --git a/scripts/verify-operations.py b/scripts/verify-operations.py index 93ed14d..6436444 100644 --- a/scripts/verify-operations.py +++ b/scripts/verify-operations.py @@ -11,6 +11,7 @@ import json import os import re +from ipaddress import IPv4Network from pathlib import Path import secrets import subprocess @@ -165,7 +166,12 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--image", required=True) parser.add_argument("--baseline-image", help="Existing qualified internal baseline for actual replacement; not an older public release") + parser.add_argument("--fixture-network-pool", type=IPv4Network, help="Available private /24 for disposable /28 fixture networks if Docker default pools are exhausted") args = parser.parse_args() + if args.fixture_network_pool and (not args.fixture_network_pool.is_private or args.fixture_network_pool.prefixlen > 24): + parser.error("--fixture-network-pool must be a private /24 or larger network") + args.fixture_networks = (iter(args.fixture_network_pool.subnets(new_prefix=28)) + if args.fixture_network_pool else None) if not args.image or any(character.isspace() for character in args.image): parser.error("--image must be a single Docker image reference") if args.baseline_image and any(character.isspace() for character in args.baseline_image): @@ -182,6 +188,7 @@ def main(): def verify(args, initial_version): print("OPERATIONS_PROFILE=" + ("same-version" if initial_version is None else "restore-V9-then-upgrade"), flush=True) + fixture_networks = getattr(args, "fixture_networks", None) projects = [] with tempfile.TemporaryDirectory(prefix="busystack-operations-") as directory: private = Path(directory) @@ -198,7 +205,12 @@ def verify(args, initial_version): f" image: {json.dumps(initial_image)}\n" " ports: !override\n - '127.0.0.1::8080'\n" ) + if fixture_networks: + with override.open("a") as settings: + settings.write("networks:\n default:\n ipam:\n config:\n - subnet: ${BUSYSTACK_QUALIFICATION_SUBNET:?fixture subnet required}\n") environment = os.environ.copy() + if fixture_networks: + environment["BUSYSTACK_QUALIFICATION_SUBNET"] = str(next(fixture_networks)) environment.update(development_environment(initial_image)) environment.update( COMPOSE_FILE=f"{ROOT / 'compose.yaml'}:{override}", @@ -214,22 +226,30 @@ def verify(args, initial_version): try: projects.append(environment.copy()) compose(environment, "up", "-d", "--wait", "--wait-timeout", "120", "database") - compose( - environment, - "run", - "--rm", - "--no-deps", - "--user", - f"{os.getuid()}:{os.getgid()}", - "--volume", - f"{private / 'bootstrap-password'}:/bootstrap-password:ro", - "application", - "--spring.main.web-application-type=none", - "--busystack.bootstrap=true", - "--busystack.bootstrap-username=opsadmin", - "--busystack.bootstrap-password-file=/bootstrap-password", - *([] if initial_version is None else ["--spring.flyway.target=" + initial_version]), - ) + if initial_version is not None: + # Create an historical schema, not a current initializer against missing + # future security tables. This is explicitly a database fixture. + compose(environment, "run", "--rm", "--no-deps", "application", + "--spring.main.web-application-type=none", "--spring.flyway.target=" + initial_version) + sql(environment, "INSERT INTO accounts(id,username,display_name,password_hash,administrator) VALUES (gen_random_uuid(),'opsadmin','Operations Administrator','qualification-unusable-verifier',true);") + print("OPERATIONS_V9_SCHEMA_ONLY_FIXTURE_NO_CURRENT_BOOTSTRAP", flush=True) + else: + compose( + environment, + "run", + "--rm", + "--no-deps", + "--user", + f"{os.getuid()}:{os.getgid()}", + "--volume", + f"{private / 'bootstrap-password'}:/bootstrap-password:ro", + "application", + "--spring.main.web-application-type=none", + "--busystack.bootstrap=true", + "--busystack.bootstrap-username=opsadmin", + "--busystack.bootstrap-password-file=/bootstrap-password", + *([] if initial_version is None else ["--spring.flyway.target=" + initial_version]), + ) print("OPERATIONS_SCHEMA_VERSIONS=" + sql(environment, "SELECT string_agg(version,',' ORDER BY installed_rank) FROM flyway_schema_history WHERE success AND version IS NOT NULL;"), flush=True) content = ( "BEGIN:VCALENDAR\r\nVERSION:2.0\r\n" @@ -295,6 +315,24 @@ def verify(args, initial_version): COMMIT; """, ) + journal_checksum = None + if initial_version is None and baseline_image is None: + journal = ( + "BEGIN:VCALENDAR\r\nVERSION:2.0\r\n" + "PRODID:-//BusyStack Operations Fixture//EN\r\n" + "BEGIN:VJOURNAL\r\nUID:operations-journal-fixture\r\n" + "DTSTAMP:20261125T000000Z\r\nDESCRIPTION;LANGUAGE=en:Journal entry\r\n" + "DESCRIPTION;LANGUAGE=fr:Entrée\r\nEND:VJOURNAL\r\nEND:VCALENDAR\r\n" + ).encode() + journal_checksum = hashlib.sha256(journal).hexdigest() + sql(environment, f"""BEGIN; +INSERT INTO collections(id,owner_id,name,component,revision) + SELECT '55555555-5555-4555-8555-555555555555',id,'Journal recovery fixture','VJOURNAL',1 + FROM accounts WHERE username='opsadmin'; +INSERT INTO calendar_resources(collection_id,name,uid,content,etag,revision) + VALUES ('55555555-5555-4555-8555-555555555555','journal.ics','operations-journal-fixture', + decode('{journal.hex()}','hex'),'"{journal_checksum}"',1); +COMMIT;""") epoch = sql(environment, "SELECT recovery_epoch FROM system_state WHERE id=1;") initial_verifier = sql(environment, "SELECT password_hash FROM accounts WHERE username='opsadmin';") has_federation = sql(environment, "SELECT to_regclass('public.external_identities') IS NOT NULL;") == "t" @@ -322,12 +360,24 @@ def verify(args, initial_version): actual = execute(["docker", "inspect", "--format", "{{.Image}}", compose(environment, "ps", "--quiet", "application")], environment) assert actual == args.image assert sql(environment, "SELECT encode(content,'hex') || etag FROM calendar_resources ORDER BY collection_id,name;") == baseline_data - assert sql(environment, "SELECT json_agg(row_to_json(h) ORDER BY installed_rank) FROM flyway_schema_history h;") == baseline_history - print("OPERATIONS_BASELINE_REPLACEMENT_PRESERVED_DATA_ETAGS_AND_MIGRATION_HISTORY", flush=True) + upgraded_history = json.loads(sql(environment, "SELECT json_agg(row_to_json(h) ORDER BY installed_rank) FROM flyway_schema_history h;")) + previous_history = json.loads(baseline_history) + assert upgraded_history[:len(previous_history)] == previous_history + assert [row['version'] for row in upgraded_history] == [str(n) for n in range(1, 20)] + assert sql(environment, "SELECT initialized FROM installation_state WHERE id=1;") == "t" + print("OPERATIONS_BASELINE_REPLACEMENT_PRESERVED_DATA_ETAGS_AND_PRIOR_MIGRATION_HISTORY_ADDED_V15_V16_V17_V18_V19", flush=True) compose(environment, "restart", "application") compose(environment, "up", "-d", "--no-build", "--wait", "--wait-timeout", "240", "application") checks(environment) if initial_version is None: + sql(environment, """INSERT INTO browser_issuance_intents + (id,account_id,security_epoch,purpose,context,expires_at) + SELECT gen_random_uuid(),id,security_epoch,'APPLICATION_PASSWORD','generic:security',now()+interval '15 minutes' + FROM accounts WHERE username='opsadmin';""") + assert sql(environment, "SELECT count(*) FROM browser_issuance_intents;") == "1" + sql(environment, """INSERT INTO browser_flow_state(scope,section,payload,expires_at) + VALUES ('ops-browser-scope','journey','{}',now()+interval '15 minutes');""") + assert sql(environment, "SELECT count(*) FROM browser_flow_state;") == "1" execute(["./scripts/backup.sh", str(archive)], environment) execute(["./scripts/backup.sh", str(archive)], environment, expected=2) compose(environment, "stop", "application") @@ -335,9 +385,25 @@ def verify(args, initial_version): restored = environment.copy() restored["COMPOSE_PROJECT_NAME"] += "-restore" + if fixture_networks: + restored["BUSYSTACK_QUALIFICATION_SUBNET"] = str(next(fixture_networks)) projects.append(restored) compose(restored, "up", "-d", "--wait", "--wait-timeout", "120", "database") execute(["./scripts/restore.sh", str(archive)], restored) + if initial_version is None: + assert sql(restored, "SELECT count(*) FROM browser_issuance_intents;") == "0" + print("OPERATIONS_RESTORED_ISSUANCE_INTENTS_CLEARED", flush=True) + assert sql(restored, "SELECT count(*) FROM browser_flow_state;") == "0" + print("OPERATIONS_RESTORED_BROWSER_FLOWS_CLEARED", flush=True) + if journal_checksum is not None: + assert sql(restored, """SELECT c.component || '|' || encode(sha256(r.content),'hex') + || '|' || r.etag FROM calendar_resources r JOIN collections c ON c.id=r.collection_id + JOIN calendar_resource_versions v ON v.collection_id=r.collection_id + AND v.name=r.name AND v.revision=r.revision AND v.content=r.content AND v.etag=r.etag + JOIN dav_bindings b ON b.collection_id=c.id AND b.home_id=c.owner_id + WHERE r.uid='operations-journal-fixture';""") == ( + f'VJOURNAL|{journal_checksum}|"{journal_checksum}"') + print("OPERATIONS_JOURNAL_BYTES_ETAG_COMPONENT_HISTORY_AND_BINDING_PRESERVED", flush=True) if initial_version is not None: assert sql(restored, "SELECT max(version::integer) FROM flyway_schema_history WHERE version IS NOT NULL;") == "9" assert sql(restored, "SELECT count(*) FROM accounts WHERE enabled;") == "0" @@ -346,18 +412,18 @@ 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" + 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,16,17,18,19" compose(restored, "stop", "application") - print("OPERATIONS_V9_INVALIDATION_THEN_STARTUP_UPGRADE_TO_V13_PASSED", flush=True) + print("OPERATIONS_V9_INVALIDATION_THEN_STARTUP_UPGRADE_TO_V19_PASSED", flush=True) result = json.loads( sql( restored, """SELECT json_build_object( 'accounts',(SELECT count(*) FROM accounts), 'enabled_accounts',(SELECT count(*) FROM accounts WHERE enabled), -'owner',(SELECT a.username FROM accounts a JOIN collections c ON c.owner_id=a.id), +'owner',(SELECT a.username FROM accounts a JOIN collections c ON c.owner_id=a.id WHERE c.component='VEVENT'), 'permission',(SELECT permission FROM collection_members), -'content_sha256',(SELECT encode(sha256(content),'hex') FROM calendar_resources), +'content_sha256',(SELECT encode(sha256(content),'hex') FROM calendar_resources WHERE name='fixture.ics'), 'epoch',(SELECT recovery_epoch::text FROM system_state), 'credentials',(SELECT count(*) FROM dav_credentials), 'continuations',(SELECT count(*) FROM sync_continuations), @@ -376,7 +442,8 @@ def verify(args, initial_version): assert result["registered_clients"] == 1 assert result["permission"] == "READ" and result["content_sha256"] == checksum assert result["epoch"] != epoch and result["history"] == 1 - assert result["continuations"] == 0 and result["versions"] == 1 + assert result["continuations"] == 0 + assert result["versions"] == (2 if journal_checksum is not None else 1) assert result["history_properties"] == 1 for key in ("enabled_accounts", "credentials", "grants", "consents", "passkeys", "active_families", "tables_not_owned_by_app"): assert result[key] == 0, key @@ -400,13 +467,16 @@ def verify(args, initial_version): 'folder_xml',(SELECT xml FROM dav_binding_properties WHERE namespace='urn:busystack:operations'), 'collection_xml',(SELECT xml FROM dav_collection_properties WHERE namespace='urn:busystack:operations'), 'resource_xml',(SELECT xml FROM dav_resource_properties WHERE namespace='urn:busystack:operations'));""")) - assert binding_data['bindings'] == 3 and binding_data['folder'] == 'Recovery folder ü' + assert binding_data['bindings'] == (4 if journal_checksum is not None else 3) + assert binding_data['folder'] == 'Recovery folder ü' assert binding_data['owner_path'] == '11111111-1111-4111-8111-111111111111' for key, value in [('folder_xml', 'folder'), ('collection_xml', 'collection'), ('resource_xml', 'resource')]: assert binding_data[key] == '' + value + '' if has_sessions: assert sql(restored, "SELECT (SELECT count(*) FROM spring_session)+(SELECT count(*) FROM spring_session_attributes)+(SELECT count(*) FROM account_recovery_codes)+(SELECT count(*) FROM webauthn_ceremonies)+(SELECT count(*) FROM login_throttle);") == "0" assert sql(restored, "SELECT security_epoch FROM accounts WHERE username='opsadmin';") != account_generation + assert sql(restored, "SELECT initialized AND code_verifier IS NULL FROM installation_state WHERE id=1;") == "t" + print("OPERATIONS_RESTORED_INITIALIZATION_REMAINS_CLOSED", flush=True) compose( restored, "run", "--rm", "--no-deps", "--user", f"{os.getuid()}:{os.getgid()}", @@ -430,7 +500,7 @@ def verify(args, initial_version): checks(restored) if initial_version is None: compose(environment, "stop", "application") - negative_restores(environment, private, projects) + negative_restores(environment, private, projects, fixture_networks) print("PASS: packaged startup, non-root/read-only runtime, probes, configured discovery/issuer, DAV challenge, restart, database backup/restore, data/ownership/share preservation, restored credential/grant invalidation, controlled local/external account recovery (including rejected external subject mismatch).") print("Not qualified here: interactive authentication, HTTP calendar/task content operations, HTTPS/proxy paths or independent clients.") except Exception: @@ -454,7 +524,7 @@ def verify(args, initial_version): compose(created, "down", "--volumes", "--remove-orphans", "--timeout", "10") -def negative_restores(source, private, projects): +def negative_restores(source, private, projects, networks=None): """Malformed histories are restored only into new owned DBs, never started as applications.""" assert "application" not in compose(source, "ps", "--status", "running", "--services").splitlines() original = sql(source, "SELECT json_agg(row_to_json(h) ORDER BY installed_rank) FROM flyway_schema_history h;") @@ -462,7 +532,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="'14'"), "supports schema versions 1 through 13"), + ("future", appended.format(version="'20'"), "supports schema versions 1 through 19"), ("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"), @@ -477,6 +547,8 @@ def negative_restores(source, private, projects): sql(source, restore_history) target = source.copy() target["COMPOSE_PROJECT_NAME"] += "-negative-" + label + if networks: + target["BUSYSTACK_QUALIFICATION_SUBNET"] = str(next(networks)) projects.append(target) compose(target, "up", "-d", "--wait", "--wait-timeout", "120", "database") result = subprocess.run(["./scripts/restore.sh", str(archive)], cwd=ROOT, env=target, 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 9e421d5..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) { @@ -175,9 +178,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/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..3c98cab --- /dev/null +++ b/src/main/java/org/busystack/caldav/account/InitializationController.java @@ -0,0 +1,60 @@ +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") + public String setup(HttpServletResponse response) { + protect(response); + if (!initialization.available()) return "redirect:/login"; + return "setup"; + } + + @GetMapping("/setup/administrator") + public String legacy() { + return "redirect:/setup"; + } + + @GetMapping("/help/setup") + public String help() { + return "setup-help"; + } + + @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, + org.springframework.web.servlet.mvc.support.RedirectAttributes flash) { + protect(response); + var errors = initialization.initialize(code, username, password, confirmation); + if (errors.isEmpty()) { + flash.addFlashAttribute("notice", "Administrator account created. Sign in to continue."); + flash.addFlashAttribute("initialUsername", username); + return "redirect:/login"; + } + response.setStatus(400); + model.addAttribute("fieldErrors", errors); + model.addAttribute("errorFormKey", "setup"); + model.addAttribute("username", username.length() <= 64 ? username : ""); + return "setup"; + } + + 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/InitializationGateFilter.java b/src/main/java/org/busystack/caldav/account/InitializationGateFilter.java new file mode 100644 index 0000000..bb9d3da --- /dev/null +++ b/src/main/java/org/busystack/caldav/account/InitializationGateFilter.java @@ -0,0 +1,35 @@ +package org.busystack.caldav.account; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import org.springframework.web.filter.OncePerRequestFilter; + +/** A configured provider cannot provision the first account before operator initialization. */ +public final class InitializationGateFilter extends OncePerRequestFilter { + private final InitializationService initialization; + + public InitializationGateFilter(InitializationService initialization) { + this.initialization = initialization; + } + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + return !request.getServletPath().startsWith("/oauth2/authorization/") + && !request.getServletPath().startsWith("/login/oauth2/code/"); + } + + @Override + protected void doFilterInternal( + HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + if (initialization.available()) { + response.setHeader("Cache-Control", "no-store"); + response.sendRedirect(request.getContextPath() + "/setup"); + return; + } + chain.doFilter(request, response); + } +} 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..6215465 --- /dev/null +++ b/src/main/java/org/busystack/caldav/account/InitializationService.java @@ -0,0 +1,103 @@ +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; + private final SecureRandom entropy = new SecureRandom(); + + 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]; + entropy.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..d2ebd7c --- /dev/null +++ b/src/main/java/org/busystack/caldav/account/IssueInitializationCode.java @@ -0,0 +1,30 @@ +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; + private final org.springframework.core.env.Environment environment; + + public IssueInitializationCode( + InitializationService initialization, org.springframework.core.env.Environment environment) { + this.initialization = initialization; + this.environment = environment; + } + + @Override + public void run(ApplicationArguments args) { + if (!"none".equals(environment.getProperty("spring.main.web-application-type"))) + throw new IllegalArgumentException( + "Initialization code issuance requires an offline process"); + 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/calendar/CalendarConstraints.java b/src/main/java/org/busystack/caldav/calendar/CalendarConstraints.java index 8c98c64..91334c3 100644 --- a/src/main/java/org/busystack/caldav/calendar/CalendarConstraints.java +++ b/src/main/java/org/busystack/caldav/calendar/CalendarConstraints.java @@ -24,27 +24,44 @@ static void validate(net.fortuna.ical4j.model.Calendar calendar, Map lexical) { Temporal start = TemporalSupport.date(component, Property.DTSTART); boolean event = component.getName().equals(Component.VEVENT); boolean task = component.getName().equals(Component.VTODO); + boolean journal = component.getName().equals(Component.VJOURNAL); + if (journal) JournalConstraints.validate(component, start); if (event && start == null) invalid(); // METHOD is prohibited for stored calendar objects. if (event || task) { Temporal end = TemporalSupport.date(component, event ? Property.DTEND : Property.DUE); Property duration = component.getProperty(Property.DURATION).orElse(null); - if (duration != null && (end != null || start == null)) invalid(); - if (end != null && start != null) { - sameType(start, end); - if (compare(start, end) >= 0) invalid(); - } + // RFC 10051 §11.1 permits duration-only tasks; events still require DTSTART. + if (duration != null && (end != null || event && start == null)) invalid(); + if (start != null) + // §3.8.2.2 applies to every DTEND; §3.6.1 does not give it the + // singleton restriction used for the preceding property group. + for (var property : component.getProperties(event ? Property.DTEND : Property.DUE)) { + Temporal value = ((DateProperty) property).getDate(); + sameType(start, value); + sameLocalForm(start, value); + if (compare(start, value) >= 0) invalid(); + } if (duration != null) { String value = lexical.getOrDefault(duration, duration.getValue()); positiveDuration(value); if (start instanceof LocalDate && value.toUpperCase(Locale.ROOT).contains("T")) invalid(); } + } + if (event || task || journal) { Temporal id = TemporalSupport.date(component, Property.RECURRENCE_ID); - if (id != null && start != null) sameType(start, id); + if (id != null && start != null) { + validateRecurrenceIdentity(start, id); + } for (String name : List.of(Property.RDATE, Property.EXDATE)) for (var property : component.getProperties(name)) { if (property instanceof RDate date && date.getPeriods().isPresent()) { @@ -59,7 +76,43 @@ private static void validate( } for (var property : component.getProperties()) { String name = property.getName(); - if (Set.of(Property.COMPLETED, Property.PERCENT_COMPLETE).contains(name) && !task) invalid(); + if (name.equals("ESTIMATED-DURATION")) { + if (!task) invalid(); + positiveDuration(lexical.getOrDefault(property, property.getValue())); + } + if (name.equals("TASK-MODE") && (!task || !property.getValue().matches("[A-Za-z0-9-]+"))) + invalid(); + // RFC 10051 §§8,10.2–3: these registered properties have defined + // placement and syntax even though the upstream validators are empty. + if (name.equals("REASON") + && (!Set.of("VSTATUS", "PARTICIPANT").contains(component.getName()) + || !java.net + .URI + .create(lexical.getOrDefault(property, property.getValue())) + .isAbsolute())) invalid(); + if (name.equals("SUBSTATE") + && (!component.getName().equals("VSTATUS") + || !property.getValue().matches("[A-Za-z0-9-]+"))) invalid(); + // RFC 5545 §3.8.4.1 forbids participation/identity parameters on + // alarm and free/busy attendees; a plain alarm delivery address is valid. + if (Property.ATTENDEE.equals(name) + && Set.of(Component.VALARM, Component.VFREEBUSY).contains(component.getName())) + for (String parameter : + List.of( + "CUTYPE", + "MEMBER", + "ROLE", + "PARTSTAT", + "RSVP", + "DELEGATED-TO", + "DELEGATED-FROM", + "SENT-BY", + "CN", + "DIR")) if (property.getParameter(parameter).isPresent()) invalid(); + if (Property.COMPLETED.equals(name) && !task) invalid(); + if (Property.PERCENT_COMPLETE.equals(name) + && !task + && !component.getName().equals("PARTICIPANT")) invalid(); if (Set.of(Property.ACTION, Property.TRIGGER, Property.REPEAT).contains(name) && !component.getName().equals(Component.VALARM)) invalid(); if (property instanceof Geo geo @@ -77,6 +130,19 @@ private static void validate( } } if (component.getName().equals(Component.VALARM)) alarm(component, parent, lexical); + if (component.getName().equals("PARTICIPANT")) + for (String name : List.of("REASON", Property.PERCENT_COMPLETE)) + if (component.getProperties(name).size() > 1) invalid(); + if (component.getName().equals("VSTATUS")) { + if (parent == null + || parent.getProperties(Property.STATUS).size() != 1 + || component.getProperties(Property.STATUS).size() != 1) invalid(); + for (String name : + List.of(Property.DESCRIPTION, Property.DTSTAMP, "REASON", "SUBSTATE", Property.SUMMARY)) + if (component.getProperties(name).size() > 1) invalid(); + // The official VStatus model has no validators yet; validate its original properties. + for (var property : component.getProperties()) if (property.validate().hasErrors()) invalid(); + } if (component instanceof ComponentContainer children) for (Component child : children.getComponents()) validate(child, component, lexical); } @@ -174,6 +240,12 @@ private static void sameType(Temporal first, Temporal second) { if ((first instanceof LocalDate) != (second instanceof LocalDate)) invalid(); } + private static void sameLocalForm(Temporal first, Temporal second) { + // RFC 5545 §§3.8.2.2–3,3.8.4.4: the plain local (floating) + // form is required if and only if DTSTART uses that form. + if ((first instanceof LocalDateTime) != (second instanceof LocalDateTime)) invalid(); + } + /** Floating and absolute DATE-TIMEs cannot be ordered without collection timezone context. */ private static int compare(Temporal first, Temporal second) { if (first instanceof LocalDate a && second instanceof LocalDate b) return a.compareTo(b); diff --git a/src/main/java/org/busystack/caldav/calendar/CalendarContent.java b/src/main/java/org/busystack/caldav/calendar/CalendarContent.java index 5001abe..d29e64f 100644 --- a/src/main/java/org/busystack/caldav/calendar/CalendarContent.java +++ b/src/main/java/org/busystack/caldav/calendar/CalendarContent.java @@ -1,6 +1,7 @@ package org.busystack.caldav.calendar; import java.io.IOException; +import java.time.ZoneId; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; @@ -8,21 +9,32 @@ import net.fortuna.ical4j.model.Calendar; import net.fortuna.ical4j.model.Component; import net.fortuna.ical4j.model.Property; +import net.fortuna.ical4j.model.TimeZoneRegistry; import org.busystack.caldav.calendar.query.BoundedTimeZoneRegistry; /** Strict model validation/indexing; admission supplies the authoritative representation octets. */ public final class CalendarContent { + /** Keeps the calendar's timezone rules alive while its parsed dates are in use. */ public record Parsed( String uid, Calendar calendar, java.util.Map lexicalValues, - java.util.Map zoneCoverage) { + java.util.Map zoneCoverage, + BoundedTimeZoneRegistry timezones) { public Parsed { lexicalValues = java.util.Collections.unmodifiableMap(new java.util.IdentityHashMap<>(lexicalValues)); zoneCoverage = java.util.Map.copyOf(zoneCoverage); } + public Parsed( + String uid, + Calendar calendar, + java.util.Map lexicalValues, + java.util.Map zoneCoverage) { + this(uid, calendar, lexicalValues, zoneCoverage, null); + } + public Parsed(String uid, Calendar calendar) { this(uid, calendar, java.util.Map.of(), java.util.Map.of()); } @@ -34,12 +46,23 @@ public Parsed(String uid, Calendar calendar, java.util.Map lex public String lexicalValue(Property property) { return lexicalValues.getOrDefault(property, property.getValue()); } + + public ZoneId zoneId(String tzid) { + return timezones == null ? TimeZoneRegistry.getGlobalZoneId(tzid) : timezones.getZoneId(tzid); + } } public static final int MAX_BYTES = 1048576; + private static final Set COLLECTION_COMPONENTS = + Set.of(Component.VEVENT, Component.VTODO, Component.VJOURNAL); + private CalendarContent() {} + public static boolean supportsCollectionComponent(String component) { + return component != null && COLLECTION_COMPONENTS.contains(component); + } + public static Parsed parse(byte[] bytes, String supportedComponent) { if (bytes.length == 0 || bytes.length > MAX_BYTES) throw new CalendarValidationException(CalendarValidationException.Reason.INVALID_DATA); @@ -70,6 +93,7 @@ public static Parsed parse(byte[] bytes, String supportedComponent) { CalendarConstraints.validate(model, lexical.values(model)); String uid = null; int masters = 0; + java.time.temporal.Temporal masterStart = null; Set recurrenceIds = new HashSet<>(); for (var component : model.getComponents()) { if (Component.VTIMEZONE.equals(component.getName())) continue; @@ -88,14 +112,21 @@ public static Parsed parse(byte[] bytes, String supportedComponent) { throw new CalendarValidationException(CalendarValidationException.Reason.INVALID_OBJECT); uid = current; var recurrence = component.getProperty(Property.RECURRENCE_ID); - if (recurrence.isEmpty()) masters++; - else if (!recurrenceIds.add( + if (recurrence.isEmpty()) { + masters++; + masterStart = + org.busystack.caldav.calendar.recurrence.TemporalSupport.date( + component, Property.DTSTART); + } else if (!recurrenceIds.add( recurrenceKey((net.fortuna.ical4j.model.property.DateProperty) recurrence.get()))) throw new CalendarValidationException(CalendarValidationException.Reason.INVALID_OBJECT); } if (uid == null || masters > 1) throw new CalendarValidationException(CalendarValidationException.Reason.INVALID_OBJECT); - return new Parsed(uid, model, lexical.values(model), registry.coverage()); + if (masterStart != null) + for (var identity : recurrenceIds) + CalendarConstraints.validateRecurrenceIdentity(masterStart, identity); + return new Parsed(uid, model, lexical.values(model), registry.coverage(), registry); } catch (CalendarValidationException ex) { throw ex; } catch (IllegalArgumentException ex) { 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..e8d15c0 --- /dev/null +++ b/src/main/java/org/busystack/caldav/calendar/CalendarInterchange.java @@ -0,0 +1,609 @@ +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 = 64 * 1024 * 1024; + public static final int MAX_ITEMS = 10000; + public static final int MAX_INDEX_BYTES = 32 * 1024 * 1024; + public static final int MAX_PROCESSING_SECONDS = 600; + + 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) {} + + /** Raw, bounded framing for export; callers first validate the stored resource. */ + public record ExportParts(byte[] header, byte[] zones, byte[] items, byte[] closing) { + public ExportParts { + header = header.clone(); + zones = zones.clone(); + items = items.clone(); + closing = closing.clone(); + } + + @Override + public byte[] header() { + return header.clone(); + } + + @Override + public byte[] zones() { + return zones.clone(); + } + + @Override + public byte[] items() { + return items.clone(); + } + + @Override + public byte[] closing() { + return closing.clone(); + } + + public String contextFingerprint() { + try { + var digest = java.security.MessageDigest.getInstance("SHA-256"); + 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); + } + } + } + + public static ExportParts exportParts(byte[] resource) { + var framed = frames(resource); + if (framed.size() != 1) throw invalid(); + var frame = framed.getFirst(); + var zones = new ByteArrayOutputStream(); + var items = new ByteArrayOutputStream(); + for (byte[] component : frame.components()) { + String first = lines(component).getFirst().value(); + if (first.equalsIgnoreCase("BEGIN:VTIMEZONE")) zones.writeBytes(component); + else items.writeBytes(component); + } + return new ExportParts( + frame.header(), zones.toByteArray(), items.toByteArray(), frame.closing()); + } + + private final CalendarAdmission admission; + + public CalendarInterchange(CalendarAdmission admission) { + this.admission = admission; + } + + /** + * File offsets and linked segments keep bodies and arbitrarily interleaved exceptions on disk. + */ + public static final class IndexedFile implements AutoCloseable { + private final java.io.RandomAccessFile source, index; + private final List series = new ArrayList<>(); + private boolean duplicatesResolved; + private final long deadline; + + private IndexedFile(java.nio.file.Path source, java.nio.file.Path index, long deadline) + throws java.io.IOException { + this.deadline = deadline; + this.source = new java.io.RandomAccessFile(source.toFile(), "r"); + try { + this.index = new java.io.RandomAccessFile(index.toFile(), "rw"); + this.index.setLength(0); + } catch (java.io.IOException | RuntimeException | Error failure) { + this.source.close(); + throw failure; + } + } + + private void resolveDuplicates(String destination, CalendarAdmission admission) + throws java.io.IOException { + if (duplicatesResolved) return; + var candidates = new ArrayList(); + for (int n = 0; n < series.size(); n++) + if (series.get(n).duplicate) { + candidates.add(n); + series.get(n).duplicate = false; + } + Map> valid = new java.util.HashMap<>(); + for (int n : candidates) { + var candidate = item(n, destination, admission); + if (candidate.rejection().isEmpty()) + valid.computeIfAbsent(candidate.uid(), uid -> new ArrayList<>()).add(n); + } + for (var matches : valid.values()) + if (matches.size() > 1) for (int n : matches) series.get(n).duplicate = true; + duplicatesResolved = true; + } + + public int size() { + return series.size(); + } + + public void checkTime() { + if (Thread.currentThread().isInterrupted() || System.nanoTime() > deadline) + throw new org.busystack.caldav.storage.StoreException( + org.busystack.caldav.storage.StoreException.Kind.LIMIT); + } + + public Item item(int number, String destination, CalendarAdmission admission) + throws java.io.IOException { + checkTime(); + var s = series.get(number); + 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" + : ""; + if (!CalendarContent.supportsCollectionComponent(s.type)) + rejection = "Unsupported component type"; + else if (!s.type.equals(destination)) + rejection = "Does not match the destination collection type"; + 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()) { + if (s.frame.groups == 1) { + 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 { + var accepted = admission.admit(content, destination); + content = accepted.content(); + uid = accepted.parsed().uid(); + } catch (IllegalArgumentException + | org.busystack.caldav.calendar.query.QueryException failure) { + rejection = "Invalid or unsupported calendar data in this UID series"; + } + } + } + return new Item( + number + 1, uid, s.type, s.label, rejection.isEmpty() ? content : new byte[0], rejection); + } + + private void copy(Chain chain, ByteArrayOutputStream output) throws java.io.IOException { + long cursor = chain.first; + byte[] buffer = new byte[8192]; + while (cursor >= 0) { + index.seek(cursor); + long offset = index.readLong(); + int length = index.readInt(); + cursor = index.readLong(); + source.seek(offset); + while (length > 0) { + int n = Math.min(length, buffer.length); + source.readFully(buffer, 0, n); + output.write(buffer, 0, n); + length -= n; + } + } + } + + private void append(Chain chain, long offset, int length) throws java.io.IOException { + chain.size += length; + if (chain.last >= 0) { + index.seek(chain.last); + long previous = index.readLong(); + int size = index.readInt(); + if (previous + size == offset) { + index.seek(chain.last + 8); + index.writeInt(size + length); + return; + } + } + long position = index.length(); + if (position + 20 > MAX_INDEX_BYTES) throw invalid(); + index.seek(position); + index.writeLong(offset); + index.writeInt(length); + index.writeLong(-1); + if (chain.last >= 0) { + index.seek(chain.last + 12); + index.writeLong(position); + } else chain.first = position; + chain.last = position; + } + + @Override + public void close() throws java.io.IOException { + try { + source.close(); + } finally { + index.close(); + } + } + } + + private static final class Chain { + long first = -1, last = -1, size; + } + + private static final class FileFrame { + long start, end; + int groups; + final Chain header = new Chain(), zones = new Chain(), closing = new Chain(); + } + + private static final class Series { + final FileFrame frame; + final String type, uid, label; + final Chain parts = new Chain(); + boolean duplicate; + + Series(FileFrame frame, Indexed item) { + this.frame = frame; + type = item.type(); + uid = item.uid(); + label = item.label(); + } + } + + /** Build a bounded disk index; never retain input or resulting resource bodies together. */ + public IndexedFile open(java.nio.file.Path input, java.nio.file.Path index) + throws java.io.IOException { + return open( + input, + index, + System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(MAX_PROCESSING_SECONDS)); + } + + public IndexedFile open(java.nio.file.Path input, java.nio.file.Path index, long deadline) + throws java.io.IOException { + long size = java.nio.file.Files.size(input); + if (size == 0 || size > MAX_FILE_BYTES) throw invalid(); + var result = new IndexedFile(input, index, deadline); + try (var raw = new java.io.BufferedInputStream(java.nio.file.Files.newInputStream(input)); + var stream = new java.io.PushbackInputStream(raw, 1)) { + long offset = 0; + int frames = 0; + Map unique = new java.util.HashMap<>(); + FileFrame frame = null; + Map groups = null; + java.util.ArrayDeque nesting = new java.util.ArrayDeque<>(); + long componentStart = 0; + var component = new ByteArrayOutputStream(); + while (true) { + result.checkTime(); + byte[] line = nextLine(stream); + if (line == null) break; + long start = offset; + offset += line.length; + String value; + try { + value = CalendarParsingInput.decode(line).replaceFirst("(?:\\r?\\n|\\r)$", ""); + CalendarTextProfile.validate(value); + } catch (java.nio.charset.CharacterCodingException failure) { + throw invalid(); + } + if (frame == null) { + if (!value.replaceFirst("^\uFEFF", "").equalsIgnoreCase("BEGIN:VCALENDAR") + || ++frames > MAX_ITEMS) throw invalid(); + frame = new FileFrame(); + frame.start = start; + groups = new LinkedHashMap<>(); + result.append(frame.header, start, line.length); + } else if (nesting.isEmpty() && value.equalsIgnoreCase("END:VCALENDAR")) { + result.append(frame.closing, start, line.length); + frame.end = offset; + frame.groups = groups.size(); + if (groups.isEmpty()) throw invalid(); + frame = null; + } else { + if (nesting.isEmpty() && !value.regionMatches(true, 0, "BEGIN:", 0, 6)) { + if (value.regionMatches(true, 0, "END:", 0, 4)) throw invalid(); + result.append(frame.header, start, line.length); + if (frame.header.size > CalendarContent.MAX_BYTES) throw invalid(); + continue; + } + if (nesting.isEmpty()) { + componentStart = start; + component.reset(); + } + if (component.size() + line.length <= CalendarContent.MAX_BYTES) + component.writeBytes(line); + if (value.regionMatches(true, 0, "BEGIN:", 0, 6)) { + String type = value.substring(6).toUpperCase(java.util.Locale.ROOT); + if (type.equals("VCALENDAR") || nesting.size() >= 8) throw invalid(); + nesting.push(type); + } else if (value.regionMatches(true, 0, "END:", 0, 4)) { + if (nesting.isEmpty() + || !nesting.pop().equals(value.substring(4).toUpperCase(java.util.Locale.ROOT))) + throw invalid(); + if (nesting.isEmpty()) { + int length = Math.toIntExact(offset - componentStart); + var info = + length <= CalendarContent.MAX_BYTES + ? indexComponent(component.toByteArray()) + : new Indexed("OVERSIZED", "", "Oversized component"); + if (info.type().equals("VTIMEZONE")) { + result.append(frame.zones, componentStart, length); + if (frame.zones.size > CalendarContent.MAX_BYTES) throw invalid(); + } else { + String key = info.type() + "\u0000" + info.uid(); + Series series = groups.get(key); + if (series == null) { + if (result.series.size() >= MAX_ITEMS) throw invalid(); + series = new Series(frame, info); + groups.put(key, series); + result.series.add(series); + Series previous = unique.putIfAbsent(info.uid(), series); + if (previous != null) { + previous.duplicate = true; + series.duplicate = true; + } + } + result.append(series.parts, componentStart, length); + } + } + } + } + } + if (frame != null || !nesting.isEmpty() || result.series.isEmpty()) throw invalid(); + return result; + } catch (java.io.IOException | RuntimeException | Error failure) { + result.close(); + throw failure; + } + } + + public Item item(IndexedFile file, int number, String destination) throws java.io.IOException { + file.resolveDuplicates(destination, admission); + return file.item(number, destination, admission); + } + + private static Indexed indexComponent(byte[] component) { + var wrapped = new ByteArrayOutputStream(); + wrapped.writeBytes( + "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//BusyStack indexing//EN\r\n" + .getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + wrapped.writeBytes(component); + if (component[component.length - 1] != '\n') wrapped.writeBytes(new byte[] {'\r', '\n'}); + wrapped.writeBytes("END:VCALENDAR\r\n".getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + var entries = index(wrapped.toByteArray(), new Budget()); + if (entries.size() != 1) throw invalid(); + return entries.getFirst(); + } + + private static byte[] nextLine(java.io.PushbackInputStream stream) throws java.io.IOException { + var bytes = new ByteArrayOutputStream(); + int value; + while ((value = stream.read()) != -1) { + bytes.write(value); + if (bytes.size() > CalendarContent.MAX_BYTES) throw invalid(); + if (value == '\n') { + int next = stream.read(); + if (next != -1) stream.unread(next); + if (next != ' ' && next != '\t') break; + } + } + return bytes.size() == 0 ? null : bytes.toByteArray(); + } + + 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.length() > 1024 ? uid.substring(0, 1025) : uid, + label.length() > 200 ? label.substring(0, 200) : 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/calendar/CalendarTextValues.java b/src/main/java/org/busystack/caldav/calendar/CalendarTextValues.java index 5e41009..cfda221 100644 --- a/src/main/java/org/busystack/caldav/calendar/CalendarTextValues.java +++ b/src/main/java/org/busystack/caldav/calendar/CalendarTextValues.java @@ -44,6 +44,25 @@ public static List list(String lexical) { return List.copyOf(values); } + /** RFC 5545 §3.8.8.3: code;description[;extension], with ordinary TEXT escaping. */ + public static void requestStatus(String lexical) { + List parts = new ArrayList<>(); + int start = 0; + for (int index = 0; index < lexical.length(); index++) { + char value = lexical.charAt(index); + if (value == '\\') index++; + else if (value == ';') { + parts.add(lexical.substring(start, index)); + start = index + 1; + } + } + parts.add(lexical.substring(start)); + if (parts.size() < 2 + || parts.size() > 3 + || !parts.getFirst().matches("[0-9]+\\.[0-9]+(?:\\.[0-9]+)?")) invalid(); + for (String part : parts.subList(1, parts.size())) scalar(part); + } + private static void invalid() { throw new CalendarValidationException(CalendarValidationException.Reason.INVALID_DATA); } diff --git a/src/main/java/org/busystack/caldav/calendar/JournalConstraints.java b/src/main/java/org/busystack/caldav/calendar/JournalConstraints.java new file mode 100644 index 0000000..d4e08ab --- /dev/null +++ b/src/main/java/org/busystack/caldav/calendar/JournalConstraints.java @@ -0,0 +1,120 @@ +package org.busystack.caldav.calendar; + +import static net.fortuna.ical4j.model.Property.*; + +import java.time.temporal.Temporal; +import java.util.Locale; +import java.util.Set; +import net.fortuna.ical4j.model.Component; +import net.fortuna.ical4j.model.ComponentContainer; + +final class JournalConstraints { + private static final Set SINGLETONS = + Set.of( + CLASS, + CREATED, + DTSTART, + LAST_MODIFIED, + ORGANIZER, + RECURRENCE_ID, + SEQUENCE, + STATUS, + SUMMARY, + URL, + "COLOR"); + private static final Set DISALLOWED = + Set.of( + DTEND, + DUE, + DURATION, + COMPLETED, + PERCENT_COMPLETE, + TRANSP, + GEO, + LOCATION, + PRIORITY, + "CONFERENCE", + "NAME", + "REFRESH-INTERVAL", + "SOURCE", + "CALENDAR-ADDRESS", + "PARTICIPANT-TYPE", + "LOCATION-TYPE", + "RESOURCE-TYPE"); + private static final Set STATUSES = Set.of("DRAFT", "FINAL", "CANCELLED"); + private static final Set CHILDREN = + Set.of("PARTICIPANT", "VLOCATION", "VRESOURCE", "VSTATUS"); + + private JournalConstraints() {} + + static void validate(Component journal, Temporal start) { + // RFC 5545 §3.6.3 and RFC 7986 §5.9. RRULE multiplicity is a SHOULD and + // stays representable. The report engine diagnoses undefined expansion. + if (journal.getProperties(UID).size() != 1 + || journal.getProperties(DTSTAMP).size() != 1 + || SINGLETONS.stream().anyMatch(name -> journal.getProperties(name).size() > 1) + || DISALLOWED.stream().anyMatch(name -> !journal.getProperties(name).isEmpty())) invalid(); + for (var status : journal.getProperties(STATUS)) + if (!STATUSES.contains(status.getValue().toUpperCase(Locale.ROOT))) invalid(); + var styled = journal.getProperties("STYLED-DESCRIPTION"); + if (styled.size() > 1 + && styled.stream() + .filter( + property -> + property + .getParameter("DERIVED") + .map(parameter -> !parameter.getValue().equalsIgnoreCase("TRUE")) + .orElse(true)) + .count() + != 1) invalid(); + if (start == null + && (!journal.getProperties(RRULE).isEmpty() + || !journal.getProperties(RDATE).isEmpty() + || !journal.getProperties(EXDATE).isEmpty())) invalid(); + if (journal instanceof ComponentContainer container) + for (Component child : container.getComponents()) { + if (!CHILDREN.contains(child.getName())) invalid(); + validateChild(child); + } + } + + private static void validateChild(Component child) { + // RFC 10051 §12.1 defines VSTATUS without a UID. CalendarConstraints validates it. + if (child.getName().equals("VSTATUS")) return; + if (child.getProperties(UID).size() != 1 || child.getRequiredProperty(UID).getValue().isBlank()) + invalid(); + boolean participant = child.getName().equals("PARTICIPANT"); + if (participant && child.getProperties("PARTICIPANT-TYPE").size() != 1) invalid(); + Set singleton = + switch (child.getName()) { + case "PARTICIPANT" -> + Set.of( + "CALENDAR-ADDRESS", + CREATED, + DESCRIPTION, + DTSTAMP, + GEO, + LAST_MODIFIED, + PRIORITY, + SEQUENCE, + STATUS, + SUMMARY, + URL); + case "VLOCATION" -> Set.of(DESCRIPTION, GEO, "LOCATION-TYPE", "NAME"); + case "VRESOURCE" -> Set.of(DESCRIPTION, GEO, "NAME", "RESOURCE-TYPE"); + default -> throw new IllegalStateException("Unexpected journal child"); + }; + if (singleton.stream().anyMatch(name -> child.getProperties(name).size() > 1)) invalid(); + if (child instanceof ComponentContainer nested) + for (Component component : nested.getComponents()) { + if (!participant + || !Set.of("VLOCATION", "VRESOURCE", "VSTATUS").contains(component.getName())) + invalid(); + validateChild(component); + } + } + + private static void invalid() { + throw new CalendarValidationException(CalendarValidationException.Reason.INVALID_DATA); + } +} diff --git a/src/main/java/org/busystack/caldav/calendar/parser/AttachmentFactory.java b/src/main/java/org/busystack/caldav/calendar/parser/AttachmentFactory.java new file mode 100644 index 0000000..5761427 --- /dev/null +++ b/src/main/java/org/busystack/caldav/calendar/parser/AttachmentFactory.java @@ -0,0 +1,30 @@ +package org.busystack.caldav.calendar.parser; + +import java.net.URI; +import net.fortuna.ical4j.model.Parameter; +import net.fortuna.ical4j.model.ParameterList; +import net.fortuna.ical4j.model.PropertyFactory; +import net.fortuna.ical4j.model.property.Attach; + +/** Keep the default 8BIT URI representation out of the upstream binary decoder. */ +final class AttachmentFactory extends Attach.Factory { + @Override + public Attach createProperty(ParameterList parameters, String value) { + if (parameters + .getParameter(Parameter.ENCODING) + .map(parameter -> parameter.getValue().equalsIgnoreCase("8BIT")) + .orElse(false)) return new UriAttachment(parameters, value); + return super.createProperty(parameters, value); + } + + private static final class UriAttachment extends Attach { + UriAttachment(ParameterList parameters, String value) { + super(parameters, URI.create(value)); + } + + @Override + protected PropertyFactory newFactory() { + return new AttachmentFactory(); + } + } +} diff --git a/src/main/java/org/busystack/caldav/calendar/parser/CalendarTimezoneFactory.java b/src/main/java/org/busystack/caldav/calendar/parser/CalendarTimezoneFactory.java new file mode 100644 index 0000000..b394150 --- /dev/null +++ b/src/main/java/org/busystack/caldav/calendar/parser/CalendarTimezoneFactory.java @@ -0,0 +1,66 @@ +package org.busystack.caldav.calendar.parser; + +import static net.fortuna.ical4j.model.Property.*; +import static net.fortuna.ical4j.validate.ValidationRule.ValidationType.One; + +import net.fortuna.ical4j.model.*; +import net.fortuna.ical4j.model.component.*; +import net.fortuna.ical4j.validate.*; + +/** Calendar-data observances permit repeated TZNAMEs (RFC 5545 §3.6.5). */ +final class CalendarTimezoneFactory extends VTimeZone.Factory { + // Retain upstream mandatory fields and validation of every original property. + // Its iTIP-specific singleton TZNAME restriction does not apply to calendar data. + private static final ComponentValidator OBSERVANCE = + new ComponentValidator<>( + Component.VTIMEZONE, new ValidationRule<>(One, DTSTART, TZOFFSETFROM, TZOFFSETTO)); + + @Override + public VTimeZone createComponent() { + return new Timezone(new PropertyList(), new ComponentList<>()); + } + + @Override + public VTimeZone createComponent(PropertyList properties) { + return new Timezone(properties, new ComponentList<>()); + } + + @Override + public VTimeZone createComponent(PropertyList properties, ComponentList children) { + return new Timezone(properties, children); + } + + private static final class Timezone extends VTimeZone { + Timezone(PropertyList properties, ComponentList children) { + super(properties); + java.util.List observances = new java.util.ArrayList<>(); + for (Component child : children.getAll()) { + if (!(child instanceof Observance observance)) + throw new IllegalArgumentException("Invalid timezone observance"); + observances.add(observance); + } + setComponentList(new ComponentList<>(observances)); + } + + @Override + public ValidationResult validate(boolean recurse) { + var result = ComponentValidator.VTIMEZONE.validate(this); + if (getObservances().isEmpty()) + result + .getEntries() + .add( + new ValidationEntry( + "Timezone requires an observance", + ValidationEntry.Severity.ERROR, + Component.VTIMEZONE)); + for (var observance : getObservances()) + result = result.merge(OBSERVANCE.validate(observance)); + return recurse ? result.merge(validateProperties()) : result; + } + + @Override + protected ComponentFactory newFactory() { + return new CalendarTimezoneFactory(); + } + } +} diff --git a/src/main/java/org/busystack/caldav/calendar/parser/JournalFactory.java b/src/main/java/org/busystack/caldav/calendar/parser/JournalFactory.java new file mode 100644 index 0000000..78376e1 --- /dev/null +++ b/src/main/java/org/busystack/caldav/calendar/parser/JournalFactory.java @@ -0,0 +1,65 @@ +package org.busystack.caldav.calendar.parser; + +import net.fortuna.ical4j.model.Component; +import net.fortuna.ical4j.model.ComponentFactory; +import net.fortuna.ical4j.model.ComponentList; +import net.fortuna.ical4j.model.ParameterList; +import net.fortuna.ical4j.model.Property; +import net.fortuna.ical4j.model.PropertyList; +import net.fortuna.ical4j.model.component.VJournal; +import net.fortuna.ical4j.model.property.Status; +import net.fortuna.ical4j.validate.ValidationResult; + +/** Validates journal extensions and attaches their children through the official VJournal API. */ +final class JournalFactory extends VJournal.Factory { + @Override + public VJournal createComponent() { + return createComponent(new PropertyList()); + } + + @Override + public VJournal createComponent(PropertyList properties) { + return createComponent(properties, new ComponentList<>()); + } + + @Override + public VJournal createComponent(PropertyList properties, ComponentList children) { + return new Journal(properties, children); + } + + private static final class Journal extends VJournal { + Journal(PropertyList properties, ComponentList children) { + super(properties); + setComponentList(new ComponentList(children.getAll())); + } + + @Override + public ValidationResult validate(boolean recurse) { + var status = getProperty(Property.STATUS); + if (status.isEmpty() || status.get().getParameters().isEmpty()) { + return super.validate(recurse); + } + // The pinned VJournal validator compares the whole property to an + // immutable status constant. RFC 5545 §3.8.1.11 permits extension + // parameters, and RFC 9073 §5.3 permits DERIVED. Check applicability on + // a value-only view and retain the original property in the parsed model. + var properties = + getProperties().stream() + .map( + property -> + property.getName().equals(Property.STATUS) + ? new Status.Factory() + .createProperty(new ParameterList(), property.getValue()) + : property) + .toList(); + var applicability = new VJournal(new PropertyList(properties)); + applicability.setComponentList(new ComponentList(getComponents())); + return applicability.validate(recurse).merge(status.get().validate()); + } + + @Override + protected ComponentFactory newFactory() { + return new JournalFactory(); + } + } +} diff --git a/src/main/java/org/busystack/caldav/calendar/parser/ParticipantTypeFactory.java b/src/main/java/org/busystack/caldav/calendar/parser/ParticipantTypeFactory.java new file mode 100644 index 0000000..487b301 --- /dev/null +++ b/src/main/java/org/busystack/caldav/calendar/parser/ParticipantTypeFactory.java @@ -0,0 +1,28 @@ +package org.busystack.caldav.calendar.parser; + +import net.fortuna.ical4j.model.ParameterList; +import net.fortuna.ical4j.model.PropertyFactory; +import net.fortuna.ical4j.model.property.ParticipantType; + +/** The official parser needs a mutable Encodable property while decoding its value. */ +final class ParticipantTypeFactory extends ParticipantType.Factory { + @Override + public ParticipantType createProperty(ParameterList parameters, String value) { + // The upstream ACTIVE constant cannot accept PropertyBuilder's decoded value. + // Its public mutable model retains the same validation and submitted parameters. + return new MutableParticipantType(parameters, value); + } + + private static final class MutableParticipantType extends ParticipantType { + MutableParticipantType(ParameterList parameters, String value) { + super(parameters, value); + } + + @Override + protected PropertyFactory newFactory() { + // Report/model copies must use the same supported mutable constructor; + // the default factory would return ACTIVE without its parameters. + return new ParticipantTypeFactory(); + } + } +} diff --git a/src/main/java/org/busystack/caldav/calendar/parser/StrictContentHandler.java b/src/main/java/org/busystack/caldav/calendar/parser/StrictContentHandler.java index 4035055..0b0c4b4 100644 --- a/src/main/java/org/busystack/caldav/calendar/parser/StrictContentHandler.java +++ b/src/main/java/org/busystack/caldav/calendar/parser/StrictContentHandler.java @@ -12,6 +12,7 @@ public final class StrictContentHandler extends DefaultContentHandler implements ParameterListHandler { private String currentProperty; + private final Deque components = new ArrayDeque<>(); private final Map currentParameters = new HashMap<>(); private static final Set DATE_PROPERTIES = Set.of( @@ -33,16 +34,19 @@ public final class StrictContentHandler extends DefaultContentHandler "CN", "CUTYPE", "DIR", + "DERIVED", "ENCODING", "FMTTYPE", "FBTYPE", "LANGUAGE", + "ORDER", "PARTSTAT", "RANGE", "RELATED", "RELTYPE", "ROLE", "RSVP", + "SCHEMA", "SENT-BY", "TZID", "VALUE"); @@ -54,12 +58,37 @@ public StrictContentHandler( private static ContentHandlerContext context() { return new ContentHandlerContext() + .withComponentFactorySupplier( + () -> { + List> factories = + new ArrayList<>(new DefaultComponentFactorySupplier().get()); + factories.removeIf(factory -> factory.supports(Component.VTODO)); + factories.addFirst(new TaskFactory()); + factories.removeIf(factory -> factory.supports(Component.VJOURNAL)); + factories.addFirst(new JournalFactory()); + factories.addFirst(new net.fortuna.ical4j.model.component.VStatus.Factory()); + factories.removeIf(factory -> factory.supports(Component.VTIMEZONE)); + factories.addFirst(new CalendarTimezoneFactory()); + return factories; + }) .withPropertyFactorySupplier( () -> { List> factories = new ArrayList<>(new DefaultPropertyFactorySupplier().get()); factories.removeIf(factory -> factory.supports(Property.CLASS)); + factories.removeIf(factory -> factory.supports(Property.STATUS)); + factories.removeIf(factory -> factory.supports(Property.PARTICIPANT_TYPE)); + factories.removeIf(factory -> factory.supports(Property.ATTACH)); + factories.addFirst(new AttachmentFactory()); + factories.removeIf(factory -> factory.supports("STRUCTURED-DATA")); + factories.addFirst(new StructuredDataFactory()); factories.addFirst(new ClassificationFactory()); + factories.addFirst(new TaskFactory.StatusFactory()); + factories.addFirst(new TaskFactory.EstimatedDurationFactory()); + factories.addFirst(new net.fortuna.ical4j.model.property.TaskMode.Factory()); + factories.addFirst(new net.fortuna.ical4j.model.property.Reason.Factory()); + factories.addFirst(new TaskFactory.SubstateFactory()); + factories.addFirst(new ParticipantTypeFactory()); return factories; }); } @@ -75,11 +104,72 @@ public void startProperty(String name) { @Override public void propertyValue(String value) { String declared = currentParameters.getOrDefault(Parameter.VALUE, "").toUpperCase(Locale.ROOT); + // RFC 5545 §§3.3,3.8.1.1 define only URI and BINARY for ATTACH. + if (Property.ATTACH.equals(currentProperty) + && !declared.isEmpty() + && !Set.of("URI", "BINARY").contains(declared)) + throw new IllegalArgumentException("Invalid attachment value type"); + if ("STRUCTURED-DATA".equals(currentProperty)) { + // RFC 9073 §6.6 distinguishes linked data from inline text and binary. + if (!Set.of("URI", "TEXT", "BINARY").contains(declared)) + throw new IllegalArgumentException("Structured data requires a supported VALUE"); + if (!declared.equals("URI") + && (!currentParameters.containsKey("SCHEMA") + || !currentParameters.containsKey("FMTTYPE"))) + throw new IllegalArgumentException("Inline structured data requires SCHEMA and FMTTYPE"); + boolean binary = declared.equals("BINARY"); + if (binary != "BASE64".equalsIgnoreCase(currentParameters.get("ENCODING"))) + throw new IllegalArgumentException("Invalid structured data encoding"); + if (binary) { + if (value.length() % 4 != 0) throw new IllegalArgumentException("Invalid binary length"); + Base64.getDecoder().decode(value); + } else if (declared.equals("TEXT")) { + org.busystack.caldav.calendar.CalendarTextValues.scalar(value); + } + } + if ("STYLED-DESCRIPTION".equals(currentProperty)) { + if (!Set.of("URI", "TEXT").contains(declared)) + throw new IllegalArgumentException("Styled descriptions require VALUE=TEXT or URI"); + if (declared.equals("TEXT")) org.busystack.caldav.calendar.CalendarTextValues.scalar(value); + } + if (declared.equals("TIME")) { + // §3.3.12 also applies to explicitly typed extension data. Preserve + // floating/zoned spelling; a time-only value has no date to derive. + for (String time : value.split(",", -1)) { + if (!time.matches("(?i)[0-9]{6}Z?") + || Integer.parseInt(time.substring(0, 2)) > 23 + || Integer.parseInt(time.substring(2, 4)) > 59 + || Integer.parseInt(time.substring(4, 6)) > 60 + || time.toUpperCase(Locale.ROOT).endsWith("Z") + && currentParameters.containsKey(Parameter.TZID)) + throw new IllegalArgumentException("Invalid TIME value"); + } + } + // RFC 5545 §3.3.14 forbids negative zero; parsing to ZoneOffset loses its sign. + if ((Set.of(Property.TZOFFSETFROM, Property.TZOFFSETTO).contains(currentProperty) + || declared.equals("UTC-OFFSET")) + && Set.of("-0000", "-000000").contains(value)) + throw new org.busystack.caldav.calendar.CalendarValidationException( + org.busystack.caldav.calendar.CalendarValidationException.Reason.INVALID_DATA); + if (declared.equals("URI") + || declared.equals("CAL-ADDRESS") + || Set.of( + Property.ATTENDEE, + Property.ORGANIZER, + Property.URL, + Property.TZURL, + "CALENDAR-ADDRESS", + "REASON") + .contains(currentProperty) + || Property.ATTACH.equals(currentProperty) && !declared.equals("BINARY")) uri(value); + if (Property.REQUEST_STATUS.equals(currentProperty)) + org.busystack.caldav.calendar.CalendarTextValues.requestStatus(value); if (Property.RRULE.equals(currentProperty) || Property.EXRULE.equals(currentProperty) || declared.equals("RECUR")) org.busystack.caldav.calendar.RecurrenceRuleSyntax.validate(value); - if (Set.of(Property.DURATION, "REFRESH-INTERVAL").contains(currentProperty) + if (Set.of(Property.DURATION, "REFRESH-INTERVAL", "ESTIMATED-DURATION") + .contains(currentProperty) || Property.TRIGGER.equals(currentProperty) && !declared.equals("DATE-TIME")) org.busystack.caldav.calendar.DurationSyntax.validate(value); else if (declared.equals("DURATION")) @@ -162,12 +252,25 @@ private void validateDateShape(String value) { @Override public void startComponent(String name) { token(name); - super.startComponent(name.toUpperCase(Locale.ROOT)); + String component = name.toUpperCase(Locale.ROOT); + if (components.contains(Component.VJOURNAL)) { + boolean permitted = + switch (components.getFirst()) { + case Component.VJOURNAL -> + Set.of("PARTICIPANT", "VLOCATION", "VRESOURCE", "VSTATUS").contains(component); + case "PARTICIPANT" -> Set.of("VLOCATION", "VRESOURCE", "VSTATUS").contains(component); + default -> false; + }; + if (!permitted) throw new IllegalArgumentException("Invalid journal child component"); + } + components.push(component); + super.startComponent(component); } @Override public void endComponent(String name) { super.endComponent(name.toUpperCase(Locale.ROOT)); + components.pop(); } @Override @@ -192,6 +295,50 @@ && getComponentBuilder() != null QueryException.Kind.INVALID_DATA, "TZID is not permitted on timezone observance properties"); var values = rawValues.stream().map(Rfc6868::value).toList(); + if (Set.of( + Parameter.CUTYPE, + Parameter.ROLE, + Parameter.PARTSTAT, + Parameter.RELTYPE, + Parameter.VALUE) + .contains(name) + && values.stream().anyMatch(value -> !value.matches("[A-Za-z0-9-]+"))) + throw new QueryException( + QueryException.Kind.INVALID_DATA, "Invalid calendar parameter token"); + if (name.equals("SCHEMA")) values.forEach(StrictContentHandler::uri); + if (name.equals("ORDER") && values.stream().anyMatch(value -> Integer.parseInt(value) < 1)) + throw new IllegalArgumentException("Invalid ORDER value"); + if (name.equals("DERIVED") + && values.stream() + .anyMatch(value -> !Set.of("TRUE", "FALSE").contains(value.toUpperCase(Locale.ROOT)))) + throw new IllegalArgumentException("Invalid DERIVED value"); + if (name.equals(Parameter.RANGE) + && values.stream().anyMatch(value -> !value.equalsIgnoreCase("THISANDFUTURE"))) + throw new QueryException(QueryException.Kind.INVALID_DATA, "Invalid recurrence range"); + if (Set.of( + Parameter.ALTREP, + Parameter.DIR, + Parameter.SENT_BY, + Parameter.MEMBER, + Parameter.DELEGATED_FROM, + Parameter.DELEGATED_TO) + .contains(name)) values.forEach(StrictContentHandler::uri); + if (name.equals(Parameter.RSVP) + && values.stream() + .anyMatch(v -> !v.equalsIgnoreCase("TRUE") && !v.equalsIgnoreCase("FALSE"))) + throw new QueryException(QueryException.Kind.INVALID_DATA, "Invalid RSVP boolean"); + if (name.equals(Parameter.LANGUAGE)) { + try { + for (String value : values) { + if (value.isEmpty()) throw new IllformedLocaleException("Empty language tag"); + // Validate BCP47 syntax through the supported JDK API. Do not replace + // the original spelling, grandfathered form or property parameters. + new Locale.Builder().setLanguageTag(value); + } + } catch (IllformedLocaleException error) { + throw new QueryException(QueryException.Kind.INVALID_DATA, "Invalid LANGUAGE tag"); + } + } Parameter parameter; if (name.equals(Parameter.MEMBER) || name.equals(Parameter.DELEGATED_FROM) @@ -242,4 +389,14 @@ private static void token(String name) { QueryException.Kind.INVALID_DATA, "Invalid calendar parameter name"); } } + + private static void uri(String value) { + try { + if (new URI(value).isAbsolute()) return; + } catch (java.net.URISyntaxException invalid) { + // Report only a fixed diagnostic; submitted values may contain private data. + } + throw new org.busystack.caldav.calendar.CalendarValidationException( + org.busystack.caldav.calendar.CalendarValidationException.Reason.INVALID_DATA); + } } diff --git a/src/main/java/org/busystack/caldav/calendar/parser/StructuredDataFactory.java b/src/main/java/org/busystack/caldav/calendar/parser/StructuredDataFactory.java new file mode 100644 index 0000000..b549650 --- /dev/null +++ b/src/main/java/org/busystack/caldav/calendar/parser/StructuredDataFactory.java @@ -0,0 +1,32 @@ +package org.busystack.caldav.calendar.parser; + +import net.fortuna.ical4j.model.ParameterList; +import net.fortuna.ical4j.model.PropertyFactory; +import net.fortuna.ical4j.model.property.StructuredData; +import net.fortuna.ical4j.validate.ValidationResult; + +/** Uses the official value model with admission grammar checked by StrictContentHandler. */ +final class StructuredDataFactory extends StructuredData.Factory { + @Override + public StructuredData createProperty(ParameterList parameters, String value) { + return new CalendarStructuredData(parameters, value); + } + + private static final class CalendarStructuredData extends StructuredData { + CalendarStructuredData(ParameterList parameters, String value) { + super(parameters, value); + } + + @Override + public ValidationResult validate() { + // RFC 9073 §6.6 permits opaque references to arbitrary schemas and URI + // data without a SCHEMA. Storage does not fetch or interpret schemas. + return new ValidationResult(); + } + + @Override + protected PropertyFactory newFactory() { + return new StructuredDataFactory(); + } + } +} diff --git a/src/main/java/org/busystack/caldav/calendar/parser/TaskFactory.java b/src/main/java/org/busystack/caldav/calendar/parser/TaskFactory.java new file mode 100644 index 0000000..2b63080 --- /dev/null +++ b/src/main/java/org/busystack/caldav/calendar/parser/TaskFactory.java @@ -0,0 +1,161 @@ +package org.busystack.caldav.calendar.parser; + +import static net.fortuna.ical4j.model.Property.*; +import static net.fortuna.ical4j.validate.ValidationRule.ValidationType.*; + +import java.util.Locale; +import java.util.Set; +import net.fortuna.ical4j.model.*; +import net.fortuna.ical4j.model.component.VToDo; +import net.fortuna.ical4j.model.property.EstimatedDuration; +import net.fortuna.ical4j.model.property.Status; +import net.fortuna.ical4j.model.property.Substate; +import net.fortuna.ical4j.validate.*; + +/** RFC 10051 task validation composed through the official model/factory/validator APIs. */ +final class TaskFactory extends VToDo.Factory { + // Substate.Factory in this pinned release similarly advertises SUMMARY. + static final class SubstateFactory extends Content.Factory implements PropertyFactory { + SubstateFactory() { + super("SUBSTATE"); + } + + @Override + public Substate createProperty(ParameterList parameters, String value) { + return new Substate.Factory().createProperty(parameters, value); + } + + @Override + public Substate createProperty() { + return new Substate(); + } + } + + // The official EstimatedDuration.Factory advertises DURATION rather than its + // own property name. Correct only the application registry key; delegate parsing. + static final class EstimatedDurationFactory extends Content.Factory + implements PropertyFactory { + EstimatedDurationFactory() { + super("ESTIMATED-DURATION"); + } + + @Override + public EstimatedDuration createProperty(ParameterList parameters, String value) { + return new EstimatedDuration.Factory().createProperty(parameters, value); + } + + @Override + public EstimatedDuration createProperty() { + return new EstimatedDuration(); + } + } + + private static final Set TASK_STATUSES = + Set.of("NEEDS-ACTION", "COMPLETED", "IN-PROCESS", "CANCELLED", "PENDING", "FAILED"); + + // RFC 5545 §3.6.2 cardinalities, with RFC 10051's additions. No library rules or + // validation diagnostics are mutated, removed by message matching, or globally disabled. + private static final PropertyContainerRuleSet TASK_RULES = + new PropertyContainerRuleSet<>( + new ValidationRule<>(One, UID, DTSTAMP), + new ValidationRule<>( + OneOrLess, + CLASS, + COMPLETED, + CREATED, + DESCRIPTION, + DTSTART, + GEO, + LAST_MODIFIED, + LOCATION, + ORGANIZER, + PERCENT_COMPLETE, + PRIORITY, + RECURRENCE_ID, + SEQUENCE, + STATUS, + SUMMARY, + URL, + "ESTIMATED-DURATION", + "TASK-MODE"), + new ValidationRule<>(OneExclusive, DUE, DURATION), + new ValidationRule<>(OneOrLess, DUE, DURATION), + new ValidationRule<>( + t -> + t.getProperties(STATUS).stream() + .anyMatch( + p -> !TASK_STATUSES.contains(p.getValue().toUpperCase(Locale.ROOT))), + "STATUS value not applicable for VTODO", + STATUS)); + + @Override + public VToDo createComponent() { + return new Task(new PropertyList(), new ComponentList<>()); + } + + @Override + public VToDo createComponent(PropertyList properties) { + return new Task(properties, new ComponentList<>()); + } + + @Override + public VToDo createComponent(PropertyList properties, ComponentList children) { + return new Task(properties, children); + } + + private static final class Task extends VToDo { + Task(PropertyList properties, ComponentList children) { + super(properties); + setComponentList(new ComponentList(children.getAll())); + } + + @Override + public ValidationResult validate(boolean recurse) { + var result = new ValidationResult(TASK_RULES.apply(VTODO, this)); + // Validate every original property, with the current STATUS grammar below. + for (var property : getProperties()) result = result.merge(property.validate()); + ComponentValidator.validateAlarms(this, true, result); + for (var child : getComponents()) result = result.merge(child.validate(recurse)); + return result; + } + + @Override + protected ComponentFactory newFactory() { + return new TaskFactory(); + } + } + + static final class StatusFactory extends Status.Factory { + private static final Validator CURRENT_STATUS = + new PropertyValidator<>( + STATUS, + new ValidationRule<>( + ValueMatch, + "(?i)TENTATIVE|CONFIRMED|CANCELLED|NEEDS-ACTION|COMPLETED|IN-PROCESS|DRAFT|FINAL|PENDING|FAILED")); + + @Override + public Status createProperty(ParameterList parameters, String value) { + // Retain upstream parsing/canonicalization for every pre-existing status. + // Only the two newly registered values require a current validator. + if (value.equalsIgnoreCase("PENDING") || value.equalsIgnoreCase("FAILED")) + return new CurrentStatus(parameters, value); + return super.createProperty(parameters, value); + } + + private static final class CurrentStatus extends Status { + CurrentStatus(ParameterList parameters, String value) { + super(parameters, value); + } + + @Override + public ValidationResult validate() { + return CURRENT_STATUS.validate(this); + } + + @Override + protected PropertyFactory newFactory() { + return new StatusFactory(); + } + } + } +} diff --git a/src/main/java/org/busystack/caldav/calendar/query/CalendarFreeBusy.java b/src/main/java/org/busystack/caldav/calendar/query/CalendarFreeBusy.java index dc93fb0..8210316 100644 --- a/src/main/java/org/busystack/caldav/calendar/query/CalendarFreeBusy.java +++ b/src/main/java/org/busystack/caldav/calendar/query/CalendarFreeBusy.java @@ -111,6 +111,7 @@ public List querySources(Iterable sources, TimeRange range) } } } + java.lang.ref.Reference.reachabilityFence(source); } var result = new ArrayList(); for (BusyType type : BusyType.values()) { diff --git a/src/main/java/org/busystack/caldav/calendar/query/CalendarQuery.java b/src/main/java/org/busystack/caldav/calendar/query/CalendarQuery.java index 5d0eb6c..5a1f5b0 100644 --- a/src/main/java/org/busystack/caldav/calendar/query/CalendarQuery.java +++ b/src/main/java/org/busystack/caldav/calendar/query/CalendarQuery.java @@ -31,21 +31,26 @@ public boolean matches(CalendarContent.Parsed parsed, ComponentFilter filter, Zo public boolean matches( CalendarContent.Parsed parsed, ComponentFilter filter, FloatingTimezone timezone) { - validate(filter); - var temporalRanges = new ArrayList(); - collectAllRanges(filter, temporalRanges); - for (var range : temporalRanges) CalendarTemporalCoverage.check(parsed, range, timezone); - if (!filter.name().equals("VCALENDAR")) - throw QueryException.invalid("The root component filter must target VCALENDAR"); - if (filter.notDefined()) return false; - if (filter.timeRange() != null) throw unsupported(); - if (!properties(parsed, parsed.calendar(), null, filter.properties(), timezone.zoneId())) - return false; - for (ComponentFilter child : filter.components()) - if (!components(parsed, parsed.calendar().getComponents(), child, null, timezone)) + try { + validate(filter); + var temporalRanges = new ArrayList(); + collectAllRanges(filter, temporalRanges); + for (var range : temporalRanges) CalendarTemporalCoverage.check(parsed, range, timezone); + if (!filter.name().equals("VCALENDAR")) + throw QueryException.invalid("The root component filter must target VCALENDAR"); + if (filter.notDefined()) return false; + if (filter.timeRange() != null) throw unsupported(); + if (!properties(parsed, parsed.calendar(), null, filter.properties(), timezone.zoneId())) return false; - if (++matchedResources > limits.maximumInstances()) throw QueryException.limit(); - return true; + for (ComponentFilter child : filter.components()) + if (!components(parsed, parsed.calendar().getComponents(), child, null, timezone)) + return false; + if (++matchedResources > limits.maximumInstances()) throw QueryException.limit(); + return true; + } finally { + java.lang.ref.Reference.reachabilityFence(parsed); + java.lang.ref.Reference.reachabilityFence(timezone); + } } private boolean components( @@ -57,8 +62,7 @@ private boolean components( var selected = available.stream().filter(c -> c.getName().equals(filter.name())).toList(); if (filter.notDefined()) return selected.isEmpty(); if (selected.isEmpty()) return false; - boolean primary = - filter.name().equals(Component.VEVENT) || filter.name().equals(Component.VTODO); + boolean primary = CalendarContent.supportsCollectionComponent(filter.name()); TimeRange window = window(filter); List occurrences; if (primary && window != null) diff --git a/src/main/java/org/busystack/caldav/calendar/query/TimeRangeMatcher.java b/src/main/java/org/busystack/caldav/calendar/query/TimeRangeMatcher.java index 9e59503..ebb6826 100644 --- a/src/main/java/org/busystack/caldav/calendar/query/TimeRangeMatcher.java +++ b/src/main/java/org/busystack/caldav/calendar/query/TimeRangeMatcher.java @@ -14,6 +14,13 @@ public static boolean matches(Occurrence occurrence, TimeRange range, ZoneId zon Instant start = occurrence.instant(DTSTART, zone), end = occurrence.instant(DTEND, zone); if (Component.VEVENT.equals(occurrence.component().getName())) return start != null && range.overlaps(start, end == null ? start : end); + if (Component.VJOURNAL.equals(occurrence.component().getName())) { + if (start == null) return false; + if (occurrence.dates().get(DTSTART) instanceof LocalDate date) + return range.startsBefore(date.plusDays(1).atStartOfDay(zone).toInstant()) + && range.endsAfter(start); + return range.contains(start); + } if (!Component.VTODO.equals(occurrence.component().getName())) throw new QueryException( QueryException.Kind.UNSUPPORTED_FILTER, "Time range is undefined for this component"); diff --git a/src/main/java/org/busystack/caldav/calendar/recurrence/CalendarRecurrence.java b/src/main/java/org/busystack/caldav/calendar/recurrence/CalendarRecurrence.java index 2c07a06..c65b0f3 100644 --- a/src/main/java/org/busystack/caldav/calendar/recurrence/CalendarRecurrence.java +++ b/src/main/java/org/busystack/caldav/calendar/recurrence/CalendarRecurrence.java @@ -28,12 +28,14 @@ public net.fortuna.ical4j.model.Calendar expand( finite(range); var result = CalendarReports.copy(parsed); var components = new ArrayList(); - var zones = new HashMap(); for (var occurrence : recurrence.occurrences(parsed, range, timezone)) { if (!TimeRangeMatcher.matches(occurrence, range, timezone.zoneId())) continue; reserveOutput(parsed, occurrence.component()); var copy = CalendarReports.componentCopy(parsed, occurrence.component()); - copy.removeAll(RRULE, RDATE, EXDATE, EXRULE, RECURRENCE_ID, DURATION); + copy.removeAll(RRULE, RDATE, EXDATE, EXRULE, RECURRENCE_ID); + // Only replace a duration with its derived end when there is an actual anchor. + // RFC 10051 duration-only tasks remain undated, including in expanded reports. + if (occurrence.dates().containsKey(DTSTART)) copy.removeAll(DURATION); for (var field : occurrence.dates().entrySet()) { if (field.getKey().equals(RECURRENCE_ID)) continue; Temporal value = reportValue(field.getValue()); @@ -52,10 +54,11 @@ public net.fortuna.ical4j.model.Calendar expand( parameters(occurrence.component(), RECURRENCE_ID), reportValue(occurrence.recurrenceId()))); expandAlarms(parsed, occurrence, copy, timezone); - normalizeTimezones(parsed, copy, zones); + normalizeTimezones(parsed, copy); components.add((net.fortuna.ical4j.model.component.CalendarComponent) copy); } result.setComponentList(new ComponentList<>(components)); + java.lang.ref.Reference.reachabilityFence(parsed); java.lang.ref.Reference.reachabilityFence(timezone); return result; } @@ -77,12 +80,15 @@ public net.fortuna.ical4j.model.Calendar limitRecurrence( if (c.getProperty(RECURRENCE_ID).isEmpty()) continue; boolean current = TimeRangeMatcher.matches(occurrence, range, timezone.zoneId()); boolean original = false; - if (master != null && occurrence.recurrenceId() != null) + Component originalComponent = master; + if (originalComponent == null && c.getName().equals(Component.VJOURNAL)) + originalComponent = c; + if (originalComponent != null && occurrence.recurrenceId() != null) original = TimeRangeMatcher.matches( RecurrenceExpander.single( parsed, - master, + originalComponent, occurrence.recurrenceId(), occurrence.recurrenceId(), timezone.zoneId()), @@ -100,6 +106,7 @@ public net.fortuna.ical4j.model.Calendar limitRecurrence( || keep.contains(original)) retained.add(result.getComponents().get(i)); } result.setComponentList(new ComponentList<>(retained)); + java.lang.ref.Reference.reachabilityFence(parsed); java.lang.ref.Reference.reachabilityFence(timezone); return result; } @@ -112,8 +119,7 @@ private void reserveOutput(CalendarContent.Parsed parsed, Component component) { reportBytes += estimate; } - private void normalizeTimezones( - CalendarContent.Parsed parsed, Component component, Map zones) { + private void normalizeTimezones(CalendarContent.Parsed parsed, Component component) { var properties = new ArrayList(); for (Property property : component.getProperties()) { var id = property.getParameter(Parameter.TZID); @@ -122,17 +128,9 @@ private void normalizeTimezones( continue; } budget.charge(1); - var zone = - zones.computeIfAbsent( - id.get().getValue(), - key -> { - for (var definition : parsed.calendar().getComponents(Component.VTIMEZONE)) - if (definition.getRequiredProperty(TZID).getValue().equals(key)) - return FloatingTimezone.from( - (net.fortuna.ical4j.model.component.VTimeZone) definition); - return FloatingTimezone.of( - net.fortuna.ical4j.model.TimeZoneRegistry.getGlobalZoneId(key)); - }); + String tzid = id.get().getValue(); + ZoneId zone = parsed.zoneId(tzid); + Instant coverageEnd = parsed.zoneCoverage().get(tzid); String type = property .getParameter(Parameter.VALUE) @@ -140,24 +138,21 @@ private void normalizeTimezones( .orElse(property instanceof DateProperty ? "DATE-TIME" : "TEXT"); var values = new ArrayList(); if (type.equals("DATE-TIME")) { - for (String value : property.getValue().split(",", -1)) values.add(utcValue(value, zone)); + for (String value : property.getValue().split(",", -1)) + values.add(utcValue(value, zone, coverageEnd)); } else if (type.equals("PERIOD")) { for (String value : parsed.lexicalValue(property).split(",", -1)) { var period = net.fortuna.ical4j.model.Period.parse(value); Temporal start = period.getStart(); - if (start instanceof LocalDateTime local) start = local.atZone(zone.zoneId()); - String tail = value.substring(value.indexOf('/') + 1); - Temporal end = - tail.startsWith("P") || tail.startsWith("+P") - ? TemporalSupport.duration(tail).addTo(start, zone.zoneId()) - : period.getEnd(); - if (end instanceof LocalDateTime local) end = local.atZone(zone.zoneId()); - CalendarTemporalCoverage.checkTemporal(start, zone.coverageEnd()); - CalendarTemporalCoverage.checkTemporal(end, zone.coverageEnd()); + if (start instanceof LocalDateTime local) start = local.atZone(zone); + Temporal end = TemporalSupport.periodEnd(period, value, start, zone); + if (end instanceof LocalDateTime local) end = local.atZone(zone); + CalendarTemporalCoverage.checkTemporal(start, coverageEnd); + CalendarTemporalCoverage.checkTemporal(end, coverageEnd); values.add( - new TemporalAdapter<>(TemporalSupport.instant(start, zone.zoneId())) + new TemporalAdapter<>(TemporalSupport.instant(start, zone)) + "/" - + new TemporalAdapter<>(TemporalSupport.instant(end, zone.zoneId()))); + + new TemporalAdapter<>(TemporalSupport.instant(end, zone))); } } else throw new QueryException( @@ -174,12 +169,12 @@ private void normalizeTimezones( } component.setPropertyList(new PropertyList(properties)); if (component instanceof ComponentContainer nested) - for (var child : nested.getComponents()) normalizeTimezones(parsed, child, zones); + for (var child : nested.getComponents()) normalizeTimezones(parsed, child); } - private static String utcValue(String value, FloatingTimezone zone) { - var date = TemporalAdapter.parse(value, zone.zoneId()).getTemporal(); - CalendarTemporalCoverage.checkTemporal(date, zone.coverageEnd()); + private static String utcValue(String value, ZoneId zone, Instant coverageEnd) { + var date = TemporalAdapter.parse(value, zone).getTemporal(); + CalendarTemporalCoverage.checkTemporal(date, coverageEnd); return new TemporalAdapter<>(date.toInstant()).toString(); } diff --git a/src/main/java/org/busystack/caldav/calendar/recurrence/RecurrenceExpander.java b/src/main/java/org/busystack/caldav/calendar/recurrence/RecurrenceExpander.java index dd7e84a..199ff35 100644 --- a/src/main/java/org/busystack/caldav/calendar/recurrence/RecurrenceExpander.java +++ b/src/main/java/org/busystack/caldav/calendar/recurrence/RecurrenceExpander.java @@ -5,6 +5,7 @@ import java.time.*; import java.time.Duration; import java.time.temporal.*; +import java.time.zone.ZoneRules; import java.util.*; import net.fortuna.ical4j.model.*; import net.fortuna.ical4j.model.property.*; @@ -16,6 +17,9 @@ * bounds. */ public final class RecurrenceExpander { + private static final Duration MAX_OFFSET_CHANGE = + Duration.ofSeconds(ZoneOffset.MAX.getTotalSeconds() - ZoneOffset.MIN.getTotalSeconds()); + private final WorkBudget budget; public RecurrenceExpander(WorkBudget budget) { @@ -38,6 +42,7 @@ public List occurrences( } catch (java.time.DateTimeException | ArithmeticException ex) { throw QueryException.limit(); } finally { + java.lang.ref.Reference.reachabilityFence(parsed); java.lang.ref.Reference.reachabilityFence(timezone); } } @@ -60,13 +65,16 @@ private List expand( var result = new ArrayList(); for (Component c : components) { budget.charge(1); - result.add(single(parsed, c, null, null, zone)); + result.add(single(parsed, c, null, TemporalSupport.date(c, RECURRENCE_ID), zone)); } return result; } Temporal seed = TemporalSupport.date(master, DTSTART); + boolean journal = Component.VJOURNAL.equals(master.getName()); boolean recurring = - !master.getProperties(RRULE).isEmpty() || !master.getProperties(RDATE).isEmpty(); + !master.getProperties(RRULE).isEmpty() + || !master.getProperties(RDATE).isEmpty() + || seed != null && !master.getProperties(EXDATE).isEmpty(); if (!recurring) { var result = new ArrayList(); // Existing components are consumed one resource at a time. They spend shared candidate @@ -76,7 +84,7 @@ private List expand( for (Component c : components) if (c != master) { budget.charge(1); - result.add(single(parsed, c, null, null, zone)); + result.add(single(parsed, c, null, TemporalSupport.date(c, RECURRENCE_ID), zone)); } return result; } @@ -102,51 +110,50 @@ private List expand( ranges.sort( Comparator.comparing( c -> TemporalSupport.instant(TemporalSupport.date(c, RECURRENCE_ID), zone))); - Duration padding = padding(parsed, components, zone, includeAlarms); + SearchPadding padding = padding(parsed, master, ranges, seed, zone, requested, includeAlarms); Instant first = requested.start() == null ? TemporalSupport.instant(seed, zone) - : requested.start().minus(padding); + : requested.start().minus(padding.before()); Instant last = requested.end() == null ? first.plus(Duration.ofDays(budget.limits().maximumRangeDays())) - : requested.end().plus(padding); + : requested.end().plus(padding.after()); // Explicit RDATEs and detached instances may precede DTSTART; only skip the rule search. boolean searchRules = first.isBefore(last); if (Duration.between(first, last) .compareTo( Duration.ofDays(budget.limits().maximumRangeDays() + 2L) - .plus(padding.multipliedBy(2))) + .plus(padding.before()) + .plus(padding.after())) > 0) throw QueryException.limit(); if (floatingEnd != null && last.isAfter(floatingEnd)) throw QueryException.limit(); for (var bound : parsed.zoneCoverage().values()) if (last.isAfter(bound)) throw QueryException.limit(); - Temporal[] bounds = ruleBounds(first, last, seed, zone); - Temporal nativeFirst = bounds[0]; - Temporal nativeLast = bounds[1]; var dates = new LinkedHashMap(); dates.put(key(seed, seed, zone), seed); var periodEnds = new HashMap(); for (var property : master.getProperties(RDATE)) { RDate rdate = (RDate) property; if (rdate.getPeriods().isPresent()) { + var periodZone = + property.getParameter(Parameter.TZID).map(p -> parsed.zoneId(p.getValue())); // PERIOD has only comma-separated start/end-or-duration values. The established parser // validates each value; retain its lexical duration to distinguish P1D from PT24H. for (String rawPeriod : parsed.lexicalValue(property).split(",", -1)) { var period = net.fortuna.ical4j.model.Period.parse(rawPeriod); budget.charge(1); Temporal value = period.getStart(); - if (value instanceof LocalDateTime && property.getParameter(Parameter.TZID).isPresent()) - value = ((LocalDateTime) value).atZone(zoneFor(parsed, property, zone)); + if (value instanceof LocalDateTime local && periodZone.isPresent()) + value = local.atZone(periodZone.get()); Object id = key(value, seed, zone); dates.put(id, value); - String endValue = rawPeriod.substring(rawPeriod.indexOf('/') + 1); - Temporal end = - endValue.startsWith("P") || endValue.startsWith("+P") - ? TemporalSupport.duration(endValue).addTo(value, zone) - : period.getEnd(); - if (end instanceof LocalDateTime && property.getParameter(Parameter.TZID).isPresent()) - end = ((LocalDateTime) end).atZone(zoneFor(parsed, property, zone)); + // RFC 4791 §9.9 gives journals a point or a nominal-day extent. + // A PERIOD supplies an occurrence start without a serialized end. + if (journal) continue; + Temporal end = TemporalSupport.periodEnd(period, rawPeriod, value, zone); + if (end instanceof LocalDateTime local && periodZone.isPresent()) + end = local.atZone(periodZone.get()); periodEnds.put(id, end); } } else @@ -160,6 +167,9 @@ private List expand( QueryException.Kind.INVALID_DATA, "Multiple RRULE recurrence sets are undefined"); for (var property : searchRules ? master.getProperties(RRULE) : List.of()) { Recur original = ((RRule) property).getRecur(); + Temporal[] bounds = ruleBounds(first, last, seed, zone, padding.includeGapAliases()); + Temporal nativeFirst = bounds[0]; + Temporal nativeLast = bounds[1]; Temporal localSeed = nativeRange(TemporalSupport.instant(seed, zone), seed, zone); if (seed instanceof LocalDateTime || seed instanceof LocalDate) localSeed = seed; Temporal lower = original.getCount() > 0 ? localSeed : nativeFirst; @@ -245,6 +255,7 @@ private List expand( ? original : shifted( original, + seed, TemporalSupport.date(range, RECURRENCE_ID), TemporalSupport.date(range, DTSTART), zone); @@ -331,20 +342,25 @@ private static ChronoUnit frequencyUnit(Recur rule) { }; } - private Temporal[] ruleBounds(Instant first, Instant last, Temporal seed, ZoneId floating) { - ZoneId zone = - seed instanceof ZonedDateTime z - ? z.getZone() - : seed instanceof OffsetDateTime o - ? o.getOffset() - : seed instanceof Instant ? ZoneOffset.UTC : floating; - var rules = zone.getRules(); + private Temporal[] ruleBounds( + Instant first, Instant last, Temporal seed, ZoneId floating, boolean includeGapAliases) { + var rules = seriesZone(seed, floating).getRules(); int smallest = rules.getOffset(first).getTotalSeconds(), largest = smallest; - var transition = rules.nextTransition(first.minusNanos(1)); + Instant scanStart = includeGapAliases ? first.minus(MAX_OFFSET_CHANGE) : first; + var transition = rules.nextTransition(scanStart.minusNanos(1)); while (transition != null && !transition.getInstant().isAfter(last)) { budget.charge(1); - smallest = Math.min(smallest, transition.getOffsetAfter().getTotalSeconds()); - largest = Math.max(largest, transition.getOffsetAfter().getTotalSeconds()); + if (!transition.getInstant().isBefore(first)) { + smallest = Math.min(smallest, transition.getOffsetAfter().getTotalSeconds()); + largest = Math.max(largest, transition.getOffsetAfter().getTotalSeconds()); + } + // A rule can generate a nonexistent local start that resolves into the search window. + if (includeGapAliases + && transition.isGap() + && transition.getInstant().plus(transition.getDuration()).isAfter(first)) { + smallest = Math.min(smallest, transition.getOffsetBefore().getTotalSeconds()); + largest = Math.max(largest, transition.getOffsetBefore().getTotalSeconds()); + } transition = rules.nextTransition(transition.getInstant()); } // Across an overlap, local start/end can run backwards. Search a conservative local @@ -358,13 +374,13 @@ private Temporal[] ruleBounds(Instant first, Instant last, Temporal seed, ZoneId private static Temporal nativeRange(Instant value, Temporal seed, ZoneId zone) { if (seed instanceof LocalDate) return value.atZone(zone).toLocalDate(); - ZoneId actual = - seed instanceof ZonedDateTime z - ? z.getZone() - : seed instanceof OffsetDateTime o - ? o.getOffset() - : seed instanceof Instant ? ZoneOffset.UTC : zone; - return value.atZone(actual).toLocalDateTime(); + return value.atZone(seriesZone(seed, zone)).toLocalDateTime(); + } + + private static ZoneId seriesZone(Temporal seed, ZoneId floating) { + if (seed instanceof ZonedDateTime zoned) return zoned.getZone(); + if (seed instanceof OffsetDateTime offset) return offset.getOffset(); + return seed instanceof Instant ? ZoneOffset.UTC : floating; } private static Temporal resolveCandidate(Temporal candidate, Temporal seed, ZoneId zone) { @@ -393,77 +409,212 @@ private static Object key(Temporal value, Temporal seed, ZoneId zone) { return TemporalSupport.instant(value, zone); } - private static Temporal shifted(Temporal value, Temporal rid, Temporal replacement, ZoneId zone) { + private static Temporal shifted( + Temporal value, Temporal seed, Temporal rid, Temporal replacement, ZoneId zone) { if (replacement == null) return value; if (value instanceof LocalDate d && rid instanceof LocalDate r && replacement instanceof LocalDate s) return d.plusDays(ChronoUnit.DAYS.between(r, s)); - LocalDateTime originalLocal = TemporalSupport.zoned(rid, zone).toLocalDateTime(); - LocalDateTime replacementLocal = TemporalSupport.zoned(replacement, zone).toLocalDateTime(); - Duration difference = Duration.between(originalLocal, replacementLocal); - if (value instanceof LocalDateTime l) return l.plus(difference); - ZonedDateTime original = TemporalSupport.zoned(value, zone); - ZonedDateTime result = original.toLocalDateTime().plus(difference).atZone(original.getZone()); - if (value instanceof OffsetDateTime) return result.toOffsetDateTime(); - if (value instanceof Instant) return result.toInstant(); - return result; + if (value instanceof LocalDateTime local + && rid instanceof LocalDateTime before + && replacement instanceof LocalDateTime after) + return local.plus(Duration.between(before, after)); + ZoneId seriesZone = seriesZone(seed, zone); + var original = TemporalSupport.zoned(value, zone).withZoneSameInstant(seriesZone); + var shift = zonedShift(rid, replacement, seriesZone, zone); + Instant result = + shift.wallClock() + ? ZonedDateTime.ofLocal( + original.toLocalDateTime().plus(shift.amount()), + seriesZone, + original.getOffset()) + .toInstant() + : original.toInstant().plus(shift.amount()); + return TemporalSupport.nativeBound(result, value, zone); } - private static Duration padding( + private record RangeShift(Duration amount, boolean wallClock) {} + + private static RangeShift zonedShift( + Temporal rid, Temporal replacement, ZoneId seriesZone, ZoneId floating) { + var before = TemporalSupport.zoned(rid, floating).withZoneSameInstant(seriesZone); + var after = TemporalSupport.zoned(replacement, floating).withZoneSameInstant(seriesZone); + // Preserve the series' wall-clock displacement even when an override uses another TZID or UTC. + Duration difference = Duration.between(before.toLocalDateTime(), after.toLocalDateTime()); + // The two instants in a repeated wall-clock slot can still represent a real move. + return difference.isZero() + ? new RangeShift(Duration.between(before, after), false) + : new RangeShift(difference, true); + } + + private record SearchPadding(Duration before, Duration after, boolean includeGapAliases) {} + + private SearchPadding padding( CalendarContent.Parsed parsed, - List components, + Component master, + List ranges, + Temporal seed, ZoneId zone, + TimeRange requested, boolean includeAlarms) { - Duration max = Duration.ZERO; - for (Component c : components) { - Temporal start = TemporalSupport.date(c, DTSTART); - if (start == null) continue; - for (String name : List.of(DTEND, DUE, RECURRENCE_ID)) { - Temporal end = TemporalSupport.date(c, name); - if (end != null) { - Duration reach = - start instanceof LocalDate a && end instanceof LocalDate b - ? durationBound( - new TemporalSupport.CalendarDuration( - ChronoUnit.DAYS.between(a, b), Duration.ZERO)) - : Duration.between( - TemporalSupport.instant(start, zone), TemporalSupport.instant(end, zone)) - .abs(); - if (reach.compareTo(max) > 0) max = reach; + Duration before = occurrenceExtent(parsed, master, seed, zone, includeAlarms); + Duration after = before; + ZoneId seriesZone = seriesZone(seed, zone); + var rules = seriesZone.getRules(); + boolean includeGapAliases = false; + // Single-instance overrides are emitted separately. Only these templates affect rule dates. + for (Component range : ranges) { + Temporal start = TemporalSupport.date(range, DTSTART); + Temporal rid = TemporalSupport.date(range, RECURRENCE_ID); + Duration extent = occurrenceExtent(parsed, range, start, zone, includeAlarms); + RangeShift shift = new RangeShift(Duration.ZERO, false); + if (start instanceof LocalDate) + shift = new RangeShift(Duration.ofDays(ChronoUnit.DAYS.between(rid, start)), true); + else if (start instanceof LocalDateTime) + shift = new RangeShift(Duration.between(rid, start), true); + else if (start != null) shift = zonedShift(rid, start, seriesZone, zone); + + // A moved instance can overlap the query by its full extent beyond its shifted start. + before = max(before, extent.plus(max(Duration.ZERO, shift.amount()))); + after = max(after, extent.plus(max(Duration.ZERO, shift.amount().negated()))); + if (shift.wallClock() && !shift.amount().isZero() && !rules.isFixedOffset()) { + includeGapAliases = true; + Instant first = requested.start() == null ? null : requested.start().minus(extent); + Instant last = requested.end() == null ? null : requested.end().plus(extent); + if (first != null) { + Instant bound = wallMoveBound(rules, first, last, shift.amount(), true); + before = max(before, Duration.between(bound, requested.start())); + } + if (last != null) { + Instant bound = wallMoveBound(rules, first, last, shift.amount(), false); + after = max(after, Duration.between(requested.end(), bound)); } } - if (start instanceof LocalDate && c.getName().equals(Component.VEVENT)) - max = max.compareTo(Duration.ofHours(60)) < 0 ? Duration.ofHours(60) : max; - if (c.getProperty(DURATION).isPresent()) { - Duration d = - durationBound(TemporalSupport.duration(parsed, c.getRequiredProperty(DURATION))); - if (d.compareTo(max) > 0) max = d; + } + return new SearchPadding(before, after, includeGapAliases); + } + + private Instant wallMoveBound( + ZoneRules rules, Instant first, Instant last, Duration shift, boolean lower) { + // Elapsed displacement is the wall-clock shift plus the original offset minus the shifted + // offset. A start outside the nominal bound can enter the window only near this edge. + Instant edge = lower ? first : last; + Instant targetFirst = lower ? first : edge.minus(MAX_OFFSET_CHANGE); + Instant targetLast = lower ? edge.plus(MAX_OFFSET_CHANGE) : last; + if (first != null && first.isAfter(targetFirst)) targetFirst = first; + if (last != null && last.isBefore(targetLast)) targetLast = last; + + LocalDateTime originalWallBound = + offsetPeriods(rules, targetFirst, targetLast).stream() + .map(p -> LocalDateTime.ofInstant(lower ? p.first() : p.last(), p.offset())) + .min(lower ? Comparator.naturalOrder() : Comparator.reverseOrder()) + .orElseThrow() + .minus(shift); + Instant nominal = edge.minus(shift); + Instant sourceFirst = lower ? nominal.minus(MAX_OFFSET_CHANGE) : nominal; + Instant sourceLast = lower ? nominal : nominal.plus(MAX_OFFSET_CHANGE); + Instant bound = nominal; + for (var period : offsetPeriods(rules, sourceFirst, sourceLast)) { + Instant candidate = originalWallBound.toInstant(period.offset()); + // Intersect the inverse wall-clock bound with each offset's own period of validity. + if (lower) { + if (candidate.isBefore(period.first())) candidate = period.first(); + if (!candidate.isAfter(period.last()) && candidate.isBefore(bound)) bound = candidate; + } else { + if (candidate.isAfter(period.last())) candidate = period.last(); + if (!candidate.isBefore(period.first()) && candidate.isAfter(bound)) bound = candidate; + } + } + return bound; + } + + private record OffsetPeriod(Instant first, Instant last, ZoneOffset offset) {} + + private List offsetPeriods(ZoneRules rules, Instant first, Instant last) { + List periods = new ArrayList<>(); + Instant periodStart = first; + ZoneOffset offset = rules.getOffset(first); + var transition = rules.nextTransition(first.minus(MAX_OFFSET_CHANGE).minusNanos(1)); + while (transition != null && !transition.getInstant().isAfter(last)) { + budget.charge(1); + Instant onset = transition.getInstant(); + if (onset.isAfter(first)) { + periods.add(new OffsetPeriod(periodStart, onset.minusNanos(1), offset)); + periodStart = onset; + offset = transition.getOffsetAfter(); + } + // Java resolves gap inputs with the pre-transition offset, even though their instants + // follow the transition. Include that wall-clock interpretation only where it can occur. + if (transition.isGap()) { + Instant gapEnd = onset.plus(transition.getDuration()).minusNanos(1); + if (!gapEnd.isBefore(first)) + periods.add( + new OffsetPeriod( + onset.isBefore(first) ? first : onset, + gapEnd.isAfter(last) ? last : gapEnd, + transition.getOffsetBefore())); } + transition = rules.nextTransition(onset); } - if (includeAlarms) { + periods.add(new OffsetPeriod(periodStart, last, offset)); + return periods; + } + + private static Duration occurrenceExtent( + CalendarContent.Parsed parsed, + Component c, + Temporal start, + ZoneId zone, + boolean includeAlarms) { + Duration extent = Duration.ZERO; + if (start != null) { + for (String name : List.of(DTEND, DUE)) { + Temporal end = TemporalSupport.date(c, name); + if (end == null) continue; + Duration reach = + start instanceof LocalDate a && end instanceof LocalDate b + ? durationBound( + new TemporalSupport.CalendarDuration( + ChronoUnit.DAYS.between(a, b), Duration.ZERO)) + : Duration.between( + TemporalSupport.instant(start, zone), TemporalSupport.instant(end, zone)) + .abs(); + extent = max(extent, reach); + } + if (start instanceof LocalDate + && Set.of(Component.VEVENT, Component.VJOURNAL).contains(c.getName())) + extent = max(extent, Duration.ofHours(60)); + if (c.getProperty(DURATION).isPresent()) + extent = + max( + extent, + durationBound(TemporalSupport.duration(parsed, c.getRequiredProperty(DURATION)))); + } + if (includeAlarms && c instanceof ComponentContainer nested) { Duration alarmMax = Duration.ZERO; - for (Component c : components) - if (c instanceof ComponentContainer nested) - for (Component alarm : nested.getComponents()) { - if (!alarm.getName().equals(Component.VALARM)) continue; - Trigger trigger = alarm.getRequiredProperty(TRIGGER); - if (trigger.isAbsolute()) continue; - Duration reach = durationBound(TemporalSupport.duration(parsed, trigger)); - int repeat = alarm.getProperty(REPEAT).map(p -> ((Repeat) p).getCount()).orElse(0); - if (repeat < 0) - throw new QueryException( - QueryException.Kind.INVALID_DATA, "Negative alarm repeat count"); - if (repeat > 0) - reach = - reach.plus( - durationBound( - TemporalSupport.duration(parsed, alarm.getRequiredProperty(DURATION))) - .multipliedBy(repeat)); - if (reach.compareTo(alarmMax) > 0) alarmMax = reach; - } - max = max.plus(alarmMax); + for (Component alarm : nested.getComponents()) { + if (!alarm.getName().equals(Component.VALARM)) continue; + Trigger trigger = alarm.getRequiredProperty(TRIGGER); + if (trigger.isAbsolute()) continue; + Duration reach = durationBound(TemporalSupport.duration(parsed, trigger)); + int repeat = alarm.getProperty(REPEAT).map(p -> ((Repeat) p).getCount()).orElse(0); + if (repeat < 0) + throw new QueryException(QueryException.Kind.INVALID_DATA, "Negative alarm repeat count"); + if (repeat > 0) + reach = + reach.plus( + durationBound( + TemporalSupport.duration(parsed, alarm.getRequiredProperty(DURATION))) + .multipliedBy(repeat)); + alarmMax = max(alarmMax, reach); + } + extent = extent.plus(alarmMax); } - return max; + return extent; + } + + private static Duration max(Duration first, Duration second) { + return first.compareTo(second) >= 0 ? first : second; } private static Duration durationBound(TemporalSupport.CalendarDuration duration) { @@ -472,17 +623,9 @@ private static Duration durationBound(TemporalSupport.CalendarDuration duration) // by at most their 36h span, including custom VTIMEZONE definitions. return Duration.ofDays(Math.abs(duration.days())) .plus(duration.clock().abs()) - .plus(duration.days() == 0 ? Duration.ZERO : Duration.ofHours(36)); + .plus(duration.days() == 0 ? Duration.ZERO : MAX_OFFSET_CHANGE); } catch (ArithmeticException ex) { throw QueryException.limit(); } } - - private static ZoneId zoneFor(CalendarContent.Parsed parsed, Property property, ZoneId fallback) { - String id = property.getParameter(Parameter.TZID).orElseThrow().getValue(); - for (var c : parsed.calendar().getComponents(Component.VTIMEZONE)) - if (c.getRequiredProperty(TZID).getValue().equals(id)) - return FloatingTimezone.from((net.fortuna.ical4j.model.component.VTimeZone) c).zoneId(); - return TimeZoneRegistry.getGlobalZoneId(id); - } } diff --git a/src/main/java/org/busystack/caldav/calendar/recurrence/TemporalSupport.java b/src/main/java/org/busystack/caldav/calendar/recurrence/TemporalSupport.java index 796e4ea..1d48ca2 100644 --- a/src/main/java/org/busystack/caldav/calendar/recurrence/TemporalSupport.java +++ b/src/main/java/org/busystack/caldav/calendar/recurrence/TemporalSupport.java @@ -2,7 +2,9 @@ import java.time.*; import java.time.temporal.*; +import java.util.Locale; import net.fortuna.ical4j.model.Component; +import net.fortuna.ical4j.model.Period; import net.fortuna.ical4j.model.Property; import net.fortuna.ical4j.model.property.DateProperty; import org.busystack.caldav.calendar.CalendarContent; @@ -67,7 +69,7 @@ public static CalendarDuration duration(CalendarContent.Parsed parsed, Property @SuppressWarnings("deprecation") public static CalendarDuration duration(String rawValue) { - var value = new net.fortuna.ical4j.model.Dur(rawValue); + var value = new net.fortuna.ical4j.model.Dur(rawValue.toUpperCase(Locale.ROOT)); long days = Math.addExact(Math.multiplyExact((long) value.getWeeks(), 7), value.getDays()); Duration clock = Duration.ofHours(value.getHours()) @@ -77,6 +79,13 @@ public static CalendarDuration duration(String rawValue) { value.isNegative() ? -days : days, value.isNegative() ? clock.negated() : clock); } + static Temporal periodEnd(Period period, String rawPeriod, Temporal start, ZoneId zone) { + String end = rawPeriod.substring(rawPeriod.indexOf('/') + 1); + char initial = end.charAt(0); + // Explicit date-times start with a year. Durations retain their lexical units. + return initial >= '0' && initial <= '9' ? period.getEnd() : duration(end).addTo(start, zone); + } + public static Temporal exactEnd(Temporal seed, Temporal end, Temporal occurrence, ZoneId zone) { if (seed instanceof LocalDate a && end instanceof LocalDate b 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..186bdca --- /dev/null +++ b/src/main/java/org/busystack/caldav/config/OperationalProblems.java @@ -0,0 +1,26 @@ +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) { + recent.removeIf(p -> p.requestId().equals(requestId)); + 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..b90db8e --- /dev/null +++ b/src/main/java/org/busystack/caldav/config/PortabilityWorkFilter.java @@ -0,0 +1,50 @@ +package org.busystack.caldav.config; + +import jakarta.servlet.*; +import jakarta.servlet.http.*; +import java.io.IOException; +import org.busystack.caldav.management.PortabilityStorage; +import org.springframework.web.filter.OncePerRequestFilter; + +/** Bound concurrent multipart parsing, interchange work and private download files together. */ +final class PortabilityWorkFilter extends OncePerRequestFilter { + private final PortabilityStorage storage; + + PortabilityWorkFilter(PortabilityStorage storage) { + this.storage = storage; + } + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + String path = request.getRequestURI().substring(request.getContextPath().length()); + return !path.startsWith("/portability/") && !multipart(request); + } + + private static boolean multipart(HttpServletRequest request) { + String type = request.getContentType(); + return type != null && type.stripLeading().regionMatches(true, 0, "multipart/", 0, 10); + } + + @Override + protected void doFilterInternal( + HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + if (multipart(request) + && !("POST".equals(request.getMethod()) + && "/portability/preview".equals(request.getServletPath()))) { + response.sendError(415); + return; + } + PortabilityStorage.Work work; + try { + work = storage.begin(request.getServletPath().equals("/portability/preview")); + } catch (PortabilityStorage.CapacityException busy) { + response.setHeader("Retry-After", "5"); + response.sendError(503); + return; + } + try (work) { + chain.doFilter(request, response); + } + } +} diff --git a/src/main/java/org/busystack/caldav/config/RequestDiagnosticsFilter.java b/src/main/java/org/busystack/caldav/config/RequestDiagnosticsFilter.java index f53e7d5..5eb9369 100644 --- a/src/main/java/org/busystack/caldav/config/RequestDiagnosticsFilter.java +++ b/src/main/java/org/busystack/caldav/config/RequestDiagnosticsFilter.java @@ -13,17 +13,45 @@ /** Useful correlation/latency without logging resource paths, identities, headers or bodies. */ final class RequestDiagnosticsFilter extends OncePerRequestFilter { + private static final String CORRELATION = RequestDiagnosticsFilter.class.getName() + ".request"; + + private record Request(String id, String surface, String method, long started) {} + + private final OperationalProblems problems; + + RequestDiagnosticsFilter(OperationalProblems problems) { + this.problems = problems; + } + private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(RequestDiagnosticsFilter.class); + @Override + protected boolean shouldNotFilterErrorDispatch() { + return false; + } + + @Override + protected void doFilterNestedErrorDispatch( + HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + doFilterInternal(request, response, chain); + } + @Override protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { - String id = UUID.randomUUID().toString(), previous = MDC.get("request_id"); - response.setHeader("X-Request-ID", id); - MDC.put("request_id", id); - long start = System.nanoTime(); + var original = (Request) request.getAttribute(CORRELATION); + if (original == null) { + original = + new Request( + UUID.randomUUID().toString(), surface(request), method(request), System.nanoTime()); + request.setAttribute(CORRELATION, original); + } + String previous = MDC.get("request_id"); + response.setHeader("X-Request-ID", original.id()); + MDC.put("request_id", original.id()); boolean failed = false; try { chain.doFilter(request, response); @@ -31,41 +59,49 @@ protected void doFilterInternal( failed = true; throw ex; } finally { - String relative = request.getRequestURI().substring(request.getContextPath().length()); - String surface = - relative.startsWith("/dav") - ? "dav" - : relative.startsWith("/oauth") - ? "oauth" - : relative.startsWith("/actuator") ? "health" : "browser"; - String method = - java.util.Set.of( - "GET", - "HEAD", - "POST", - "PUT", - "DELETE", - "OPTIONS", - "PROPFIND", - "PROPPATCH", - "REPORT", - "MKCALENDAR", - "MKCOL", - "COPY", - "MOVE", - "ACL") - .contains(request.getMethod()) - ? request.getMethod() - : "other"; LOG.info( "event=http_request request_id={} surface={} method={} status={} duration_ms={}", - id, - surface, - method, - failed ? 500 : response.getStatus(), - TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)); + original.id(), + original.surface(), + original.method(), + failed ? "unavailable" : response.getStatus(), + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - original.started())); + // A thrown filter exception has no final HTTP status yet. The container's ERROR + // dispatch records the actual response; e.g. oversized form-body CSRF uploads become 413. + if (!failed) + problems.record(original.id(), original.surface(), original.method(), response.getStatus()); if (previous == null) MDC.remove("request_id"); else MDC.put("request_id", previous); } } + + private static String surface(HttpServletRequest request) { + String relative = request.getRequestURI().substring(request.getContextPath().length()); + return relative.startsWith("/dav") + ? "dav" + : relative.startsWith("/oauth") + ? "oauth" + : relative.startsWith("/actuator") ? "health" : "browser"; + } + + private static String method(HttpServletRequest request) { + return java.util.Set.of( + "GET", + "HEAD", + "POST", + "PUT", + "DELETE", + "OPTIONS", + "PROPFIND", + "PROPPATCH", + "REPORT", + "MKCALENDAR", + "MKCOL", + "COPY", + "MOVE", + "ACL") + .contains(request.getMethod()) + ? request.getMethod() + : "other"; + } } diff --git a/src/main/java/org/busystack/caldav/config/ServletDeploymentConfiguration.java b/src/main/java/org/busystack/caldav/config/ServletDeploymentConfiguration.java index c7bd122..edf5776 100644 --- a/src/main/java/org/busystack/caldav/config/ServletDeploymentConfiguration.java +++ b/src/main/java/org/busystack/caldav/config/ServletDeploymentConfiguration.java @@ -13,11 +13,13 @@ 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); + registration.setDispatcherTypes( + jakarta.servlet.DispatcherType.REQUEST, jakarta.servlet.DispatcherType.ERROR); return registration; } @@ -31,6 +33,26 @@ public class ServletDeploymentConfiguration { return registration; } + @Bean + org.springframework.boot.web.servlet.FilterRegistrationBean + portabilityWork(org.busystack.caldav.management.PortabilityStorage storage) { + var registration = + new org.springframework.boot.web.servlet.FilterRegistrationBean<>( + new PortabilityWorkFilter(storage)); + registration.setOrder(org.springframework.core.Ordered.HIGHEST_PRECEDENCE + 2); + return registration; + } + + @Bean + jakarta.servlet.MultipartConfigElement multipartConfig( + org.busystack.caldav.management.PortabilityStorage storage) throws java.io.IOException { + return new jakarta.servlet.MultipartConfigElement( + storage.multipartDirectory().toString(), + org.busystack.caldav.management.PortabilityStorage.FILE_BYTES, + org.busystack.caldav.management.PortabilityStorage.UPLOAD_BYTES, + 0); + } + @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..a336152 --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/AdministrationController.java @@ -0,0 +1,123 @@ +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; + private final org.busystack.caldav.config.DeploymentProperties deployment; + + public AdministrationController( + AdministrationService administration, + org.busystack.caldav.config.DeploymentProperties deployment) { + this.administration = administration; + this.deployment = deployment; + } + + @GetMapping("/admin/accounts") + String accounts( + Authentication auth, + @RequestParam(defaultValue = "") String q, + @RequestParam(defaultValue = "all") String status, + @RequestParam(defaultValue = "all") String method, + @RequestParam(defaultValue = "0") int page, + Model model) { + if (java.util.Set.of("local", "external").contains(status)) + return "redirect:/admin/accounts?method=" + + status + + org.springframework.web.util.UriComponentsBuilder.newInstance() + .queryParam("q", q) + .queryParam("page", page) + .build() + .encode() + .toUriString() + .replaceFirst("^\\?", "&"); + model.addAttribute("accountPage", administration.accounts(auth, q, status, method, page)); + model.addAttribute("signInMethod", method); + 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)); + model.addAttribute("signInUrl", deployment.publicBaseUrl() + "/login"); + return "account-detail"; + } + + @PostMapping("/admin/accounts") + String provision( + Authentication auth, + @RequestParam(defaultValue = "") String username, + @RequestParam(defaultValue = "") String displayName, + @RequestParam(defaultValue = "") String password, + RedirectAttributes flash) { + UUID id = administration.create(auth, username, displayName, password); + flash.addFlashAttribute("notice", "Account created."); + flash.addFlashAttribute("newAccount", id); + return "redirect:/admin/accounts/" + id; + } + + @PostMapping("/admin/accounts/{id}/edit") + String edit( + Authentication auth, + @PathVariable UUID id, + @RequestParam String expected, + @RequestParam(defaultValue = "") String displayName, + RedirectAttributes flash) { + administration.edit(auth, id, expected, displayName); + flash.addFlashAttribute("notice", "Display name saved."); + return "redirect:/admin/accounts/" + id; + } + + @GetMapping("/admin/accounts/{id}/disable") + String confirmDisable(Authentication auth, @PathVariable UUID id, Model model) { + var account = administration.account(auth, id); + if (!account.enabled() || account.username().equals(auth.getName())) + throw new org.springframework.security.access.AccessDeniedException( + "This account cannot be disabled here."); + model.addAttribute("account", account); + return "account-disable"; + } + + @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..104a546 --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/AdministrationService.java @@ -0,0 +1,225 @@ +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, + UUID actor, + String targetType, + UUID targetId, + UUID relatedAccount, + String targetLabel, + String relatedUsername) { + public String eventLabel() { + try { + return SecurityAudit.Action.valueOf(action).label(); + } catch (IllegalArgumentException unknown) { + return "Other security event"; + } + } + + public String outcomeLabel() { + try { + return SecurityAudit.Outcome.valueOf(outcome).label(); + } catch (IllegalArgumentException unknown) { + return "Unknown"; + } + } + } + + 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) { + String method = Set.of("local", "external").contains(status) ? status : "all"; + return accounts(auth, query, method.equals("all") ? status : "all", method, page); + } + + public PortalPage accounts( + Authentication auth, String query, String status, String method, int page) { + management.requireAdministrator(auth); + PortalService.checkQuery(query); + if (!Set.of("all", "enabled", "disabled").contains(status) + || !Set.of("all", "local", "external").contains(method)) + throw new IllegalArgumentException("Invalid account filter"); + String clause = + switch (status) { + case "enabled" -> " AND a.enabled"; + case "disabled" -> " AND NOT a.enabled"; + default -> ""; + }; + String signIn = + switch (method) { + 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 + + signIn + + " 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) { + org.busystack.caldav.security.RecentAuthentication.requireMfa(auth); + management.requireAdministrator(auth); + FormValidation.account(username, displayName, password); + if (accounts.find(username) != null) + throw FormValidation.conflict( + "username", "This username is already in use. Choose another username."); + UUID id; + try { + id = accounts.provision(username, displayName, password, false); + } catch (org.springframework.dao.DuplicateKeyException duplicate) { + throw FormValidation.conflict( + "username", "This username is already in use. Choose another username."); + } + audit.targeted( + management.current(auth).id(), + SecurityAudit.Action.ACCOUNT_CREATED, + SecurityAudit.Outcome.SUCCESS, + SecurityAudit.TargetType.ACCOUNT, + id, + null); + return id; + } + + @Transactional + public void edit(Authentication auth, UUID id, String expected, String displayName) { + org.busystack.caldav.security.RecentAuthentication.requireMfa(auth); + management.requireAdministrator(auth); + account(auth, id); + if (!FormValidation.displayName(displayName)) + throw FormValidation.field( + "displayName", "Use a display name of 1–200 characters without control characters."); + accounts.updateDisplayName(id, expected, displayName); + audit.targeted( + management.current(auth).id(), + SecurityAudit.Action.ACCOUNT_PROFILE_UPDATED, + SecurityAudit.Outcome.SUCCESS, + SecurityAudit.TargetType.ACCOUNT, + id, + null); + } + + @Transactional + public void disable(Authentication auth, UUID id, boolean confirmed) { + if (!confirmed) + throw new IllegalArgumentException("Confirm disabling this account and revoking its access"); + UUID actor = management.disable(auth, id); + audit.targeted( + actor, + SecurityAudit.Action.ACCOUNT_DISABLED, + SecurityAudit.Outcome.SUCCESS, + SecurityAudit.TargetType.ACCOUNT, + id, + 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,s.account_id,s.target_type,s.target_id, + s.related_account_id,COALESCE(t.display_name,g.name),m.username + FROM security_audit s + LEFT JOIN accounts a ON a.id=s.account_id + LEFT JOIN accounts t ON s.target_type='ACCOUNT' AND t.id=s.target_id + LEFT JOIN sharing_groups g ON s.target_type='GROUP' AND g.id=s.target_id + LEFT JOIN accounts m ON m.id=s.related_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), + rs.getObject(5, UUID.class), + rs.getString(6), + rs.getObject(7, UUID.class), + rs.getObject(8, UUID.class), + rs.getString(9), + rs.getString(10)), + 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..f0648c5 100644 --- a/src/main/java/org/busystack/caldav/management/DavConnectionAdvice.java +++ b/src/main/java/org/busystack/caldav/management/DavConnectionAdvice.java @@ -6,9 +6,30 @@ 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) {} + public record Connection(String url, String username, String home, boolean compatibility) { + /** + * GNOME 50 persists its authentication user from the URI, separately from discovery + * credentials. + */ + public String gnomeUrl() { + var configured = java.net.URI.create(url); + try { + return new java.net.URI( + configured.getScheme(), + username, + configured.getHost(), + configured.getPort(), + configured.getPath(), + null, + null) + .toASCIIString(); + } catch (java.net.URISyntaxException invalid) { + throw new IllegalStateException("Invalid configured DAV connection address", invalid); + } + } + } private final ManagementService management; private final DeploymentProperties deployment; diff --git a/src/main/java/org/busystack/caldav/management/FormRecovery.java b/src/main/java/org/busystack/caldav/management/FormRecovery.java new file mode 100644 index 0000000..02fce6a --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/FormRecovery.java @@ -0,0 +1,211 @@ +package org.busystack.caldav.management; + +import jakarta.servlet.http.HttpServletRequest; +import java.util.*; +import org.busystack.caldav.security.RecentAuthentication; +import org.busystack.caldav.sharing.GroupService; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Component; +import org.springframework.ui.Model; + +/** Rebuild the original authorized form; only allowlisted nonsensitive values are redisplayed. */ +@Component +public final class FormRecovery { + private final ManagementService management; + private final PortalService portal; + private final AdministrationService administration; + private final GroupService groups; + private final PortabilityService portability; + private final SharingManagementService sharing; + private final org.busystack.caldav.security.oauth.OAuthClientService oauthClients; + + public FormRecovery( + ManagementService management, + PortalService portal, + AdministrationService administration, + GroupService groups, + PortabilityService portability, + SharingManagementService sharing, + org.busystack.caldav.security.oauth.OAuthClientService oauthClients) { + this.management = management; + this.portal = portal; + this.administration = administration; + this.groups = groups; + this.portability = portability; + this.sharing = sharing; + this.oauthClients = oauthClients; + } + + private static int page(HttpServletRequest request, String name) { + int page = Integer.parseInt(Objects.requireNonNullElse(request.getParameter(name), "0")); + PortalPage.offset(page); + return page; + } + + public String render( + Authentication auth, HttpServletRequest request, Model model, Map errors) { + RecentAuthentication.requireMfa(auth); + management.current(auth); + String path = request.getServletPath(); + String view; + if (path.equals("/admin/accounts")) { + management.requireAdministrator(auth); + view = "account-new"; + } else if (path.matches("/admin/accounts/[a-f0-9-]{36}/edit")) { + model.addAttribute( + "account", administration.account(auth, UUID.fromString(path.split("/")[3]))); + view = "account-detail"; + } else if (path.equals("/collections")) view = "collection-new"; + else if (path.matches("/collections/[a-f0-9-]{36}/edit")) { + var collection = portal.collection(auth, UUID.fromString(path.split("/")[2])); + if (!collection.writable()) + throw new org.busystack.caldav.storage.StoreException( + org.busystack.caldav.storage.StoreException.Kind.FORBIDDEN); + model.addAttribute("collection", collection); + model.addAttribute("hasItems", portal.hasItems(auth, collection.id())); + view = "collection"; + } else if (path.equals("/admin/groups")) { + groups.search(auth, "", 0); + String target = request.getParameter("returnCollection"); + GroupManagementController.renderReturn( + portal, auth, target == null || target.isBlank() ? null : UUID.fromString(target), model); + view = "group-new"; + } else if (path.matches("/admin/groups/[a-f0-9-]{36}/members/[a-f0-9-]{36}/remove")) { + String[] segments = path.split("/"); + String q = + Objects.requireNonNullElse( + request.getParameter("memberQuery"), + Objects.requireNonNullElse(request.getParameter("q"), "")); + int page = page(request, request.getParameter("memberPage") == null ? "page" : "memberPage"); + return GroupManagementController.memberRemoval( + groups, + auth, + UUID.fromString(segments[3]), + UUID.fromString(segments[5]), + q, + page, + Objects.requireNonNullElse(request.getParameter("expectedGrants"), ""), + model); + } else if (path.matches("/admin/groups/[a-f0-9-]{36}(/members(/[a-f0-9-]{36}/remove)?)?")) { + UUID id = UUID.fromString(path.split("/")[3]); + model.addAttribute("group", groups.detail(auth, id)); + String query = Objects.requireNonNullElse(request.getParameter("memberQuery"), ""); + PortalService.checkQuery(query); + model.addAttribute( + "memberPage", groups.members(auth, id, query, page(request, "memberPage"))); + model.addAttribute("query", query); + view = "group-detail"; + } else if (path.equals("/admin/oauth-clients")) { + model.addAttribute("clients", oauthClients.list(auth)); + model.addAttribute("clientId", request.getParameter("clientId")); + model.addAttribute("clientName", request.getParameter("name")); + model.addAttribute("redirects", request.getParameter("redirects")); + view = "oauth-clients"; + } else if (path.matches("/collections/[a-f0-9-]{36}/sharing/(account|group)/[^/]+/remove")) { + String[] segments = path.split("/"); + return SharingReviewController.review( + sharing, + auth, + UUID.fromString(segments[2]), + segments[4], + segments[5], + page(request, "directPage"), + page(request, "groupPage"), + page(request, "effectivePage"), + Objects.requireNonNullElse(request.getParameter("expected"), ""), + model); + } else if (path.equals("/shares") || path.equals("/group-shares")) { + UUID id = UUID.fromString(Objects.requireNonNullElse(request.getParameter("collection"), "")); + model.addAttribute("collection", portal.owner(auth, id)); + model.addAttribute("directGrants", portal.direct(auth, id, page(request, "directPage"))); + model.addAttribute("groupGrants", portal.groupGrants(auth, id, page(request, "groupPage"))); + model.addAttribute( + "effectiveMembers", portal.effective(auth, id, page(request, "effectivePage"))); + model.addAttribute("groupChoices", groups.eligibleGroups(auth, id)); + view = "collection-sharing"; + } else if (path.equals("/credentials")) { + model.addAttribute( + "client", + PortalController.client( + Objects.requireNonNullElse(request.getParameter("client"), "generic"))); + model.addAttribute( + "credentialOrigin", PortalController.credentialOrigin(request.getParameter("from"))); + String resource = request.getParameter("resource"); + if ("connect".equals(request.getParameter("from")) && resource != null && !resource.isBlank()) + PortalController.connectionResource(portal, auth, UUID.fromString(resource), model); + model.addAttribute("issuanceIntent", request.getParameter("intent")); + model.addAttribute("credentialPage", portal.credentials(auth, 0)); + view = "credentials"; + } else if (path.equals("/portability/preview")) { + UUID id = + UUID.fromString(Objects.requireNonNullElse(request.getParameter("destination"), "")); + var selected = portal.collection(auth, id); + if (!selected.writable()) + throw new org.busystack.caldav.storage.StoreException( + org.busystack.caldav.storage.StoreException.Kind.FORBIDDEN); + model.addAttribute("collectionPage", new PortalPage<>(List.of(selected), 0, false)); + model.addAttribute("selectedDestination", id.toString()); + model.addAttribute("currentImportToken", portability.currentToken(auth)); + view = "portability"; + } else if (path.matches("/portability/import/[a-f0-9-]{36}")) { + UUID token = UUID.fromString(path.split("/")[3]); + var report = portability.review(auth, token, 0); + model.addAttribute("report", report); + model.addAttribute("reportId", token); + model.addAttribute("reportPage", 0); + model.addAttribute("hasNextItems", report.items().size() > 50); + model.addAttribute( + "itemPage", report.items().subList(0, Math.min(50, report.items().size()))); + view = "import-report"; + } else return null; + String key = + switch (view) { + case "account-new" -> "account-create"; + case "account-detail" -> "account-edit"; + case "collection-new" -> "collection-create"; + case "collection" -> "collection-edit"; + case "group-new" -> "group-create"; + case "oauth-clients" -> "native-app"; + case "group-detail" -> + path.endsWith("/remove") + ? "member-remove-" + path.split("/")[5] + : path.endsWith("/members") ? "member-add" : "group-rename"; + case "credentials" -> "credential-create"; + case "portability" -> "import-file-" + request.getParameter("destination"); + case "import-report" -> "import-confirm"; + case "collection-sharing" -> + path.equals("/shares") + ? ("NONE".equals(request.getParameter("expected")) + ? "direct-add" + : "direct-grant-" + request.getParameter("username")) + : ("NONE".equals(request.getParameter("expected")) + ? "group-add" + : "group-grant-" + request.getParameter("group")); + default -> throw new IllegalStateException("Unknown form"); + }; + model.addAttribute("errorFormKey", key); + Map values = new LinkedHashMap<>(); + for (String field : + List.of( + "username", + "displayName", + "name", + "description", + "color", + "component", + "label", + "days", + "permission", + "group", + "expected", + "expectedGrants", + "state")) { + String value = request.getParameter(field); + if (value != null) values.put(field, value.substring(0, Math.min(value.length(), 8001))); + } + model.addAttribute("formValues", values); + model.addAttribute("fieldErrors", errors); + model.addAttribute("errorFormPath", path); + return view; + } +} diff --git a/src/main/java/org/busystack/caldav/management/FormValidation.java b/src/main/java/org/busystack/caldav/management/FormValidation.java new file mode 100644 index 0000000..f60e2aa --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/FormValidation.java @@ -0,0 +1,74 @@ +package org.busystack.caldav.management; + +import java.util.*; +import org.busystack.caldav.xml.XmlCharacters; + +/** Fixed field messages; neither exception text nor submitted secrets become browser output. */ +public final class FormValidation extends IllegalArgumentException { + private final Map errors; + private final boolean conflict; + + public FormValidation(Map errors, boolean conflict) { + super("Invalid form fields"); + this.errors = Collections.unmodifiableMap(new LinkedHashMap<>(errors)); + this.conflict = conflict; + } + + public Map errors() { + return errors; + } + + public boolean conflict() { + return conflict; + } + + public static FormValidation field(String field, String message) { + return new FormValidation(Map.of(field, message), false); + } + + public static FormValidation conflict(String field, String message) { + return new FormValidation(Map.of(field, message), true); + } + + public static final class Checks { + private final Map errors = new LinkedHashMap<>(); + + public Checks require(String field, boolean valid, String message) { + if (!valid) errors.put(field, message); + return this; + } + + public void finish() { + if (!errors.isEmpty()) throw new FormValidation(errors, false); + } + } + + public static boolean displayName(String value) { + return value != null + && !value.isBlank() + && value.codePointCount(0, value.length()) <= 200 + && XmlCharacters.valid(value) + && value.codePoints().noneMatch(Character::isISOControl); + } + + public static void account(String username, String displayName, String password) { + var checks = new Checks(); + checks.require( + "username", + username != null && username.matches("[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}"), + "Use 1–64 letters, digits, dots, underscores or hyphens, starting with a letter or digit."); + checks.require( + "displayName", + displayName(displayName), + "Use a display name of 1–200 characters without control characters."); + try { + org.busystack.caldav.security.password.PasswordPolicy.validate(password); + } catch (IllegalArgumentException invalid) { + checks.require( + "password", + false, + "Use at least fourteen characters and at most seventy-two UTF-8 bytes. Enter the password again."); + } + checks.finish(); + } +} diff --git a/src/main/java/org/busystack/caldav/management/GroupManagementController.java b/src/main/java/org/busystack/caldav/management/GroupManagementController.java index 4d1fc28..0269d41 100644 --- a/src/main/java/org/busystack/caldav/management/GroupManagementController.java +++ b/src/main/java/org/busystack/caldav/management/GroupManagementController.java @@ -1,132 +1,251 @@ 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; + private final PortalService portal; - public GroupManagementController(GroupService groups) { + public GroupManagementController( + GroupService groups, SharingManagementService sharing, PortalService portal) { this.groups = groups; + this.sharing = sharing; + this.portal = portal; } @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/new") + String createForm( + Authentication auth, @RequestParam(required = false) UUID returnCollection, Model model) { + renderReturn(portal, auth, returnCollection, model); + return "group-new"; + } + + @GetMapping("/admin/groups/{id}") + String detail( + Authentication auth, + @PathVariable UUID id, + @RequestParam(defaultValue = "") String q, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "") String member, + Model model) { + model.addAttribute("selectedMember", member.length() <= 64 ? member : ""); + 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"; + Authentication auth, + @RequestParam(defaultValue = "") String name, + @RequestParam(required = false) UUID returnCollection, + RedirectAttributes flash) { + UUID id = groups.create(auth, name, Set.of()); + flash.addFlashAttribute("notice", "Group created."); + if (returnCollection != null) { + var destination = sharingDestination(portal, auth, returnCollection); + if (destination != null) return "redirect:/collections/" + destination.id() + "/sharing"; + flash.addFlashAttribute( + "notice", "Group created. The original resource is no longer available for sharing."); + } + return "redirect:/admin/groups/" + id; + } + + static void renderReturn(PortalService portal, Authentication auth, UUID id, Model model) { + if (id == null) return; + var collection = sharingDestination(portal, auth, id); + if (collection == null) model.addAttribute("sharingReturnUnavailable", true); + else { + model.addAttribute("returnCollection", collection.id()); + model.addAttribute("returnCollectionName", collection.name()); + } + } + + private static PortalService.CollectionView sharingDestination( + PortalService portal, Authentication auth, UUID id) { + try { + return portal.owner(auth, id); + } catch (org.busystack.caldav.storage.StoreException unavailable) { + if (unavailable.kind() == org.busystack.caldav.storage.StoreException.Kind.FORBIDDEN + || unavailable.kind() == org.busystack.caldav.storage.StoreException.Kind.NOT_FOUND) + return null; + throw unavailable; + } } @PostMapping("/admin/groups/{id}") - String update( - Authentication authentication, + String rename( + Authentication auth, @PathVariable UUID id, - @RequestParam String name, - @RequestParam(defaultValue = "") String usernames) { - groups.update(authentication, id, name, members(usernames)); - return "redirect:/admin/groups"; + @RequestParam String expected, + @RequestParam(defaultValue = "") String name, + RedirectAttributes flash) { + groups.rename(auth, id, expected, name); + flash.addFlashAttribute("notice", "Group renamed."); + return "redirect:/admin/groups/" + id; + } + + @GetMapping("/admin/groups/{id}/members/new") + String lookup( + 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("lookupPage", groups.eligibleMembers(auth, id, q, page)); + model.addAttribute("query", q); + return "group-member-lookup"; + } + + @PostMapping("/admin/groups/{id}/members") + String add( + Authentication auth, + @PathVariable UUID id, + @RequestParam(defaultValue = "") String username, + @RequestParam(defaultValue = "false") boolean confirmed, + @RequestParam(defaultValue = "") String expectedGrants, + RedirectAttributes flash) { + var group = groups.detail(auth, id); + groups.changeMember( + auth, id, username, null, true, confirmed || group.grants() == 0, expectedGrants); + flash.addFlashAttribute("notice", "Added " + username + " to " + group.name() + "."); + return "redirect:/admin/groups/" + id; + } + + @GetMapping("/admin/groups/{id}/members/{account}/remove") + String confirmRemove( + Authentication auth, + @PathVariable UUID id, + @PathVariable UUID account, + @RequestParam(defaultValue = "") String q, + @RequestParam(defaultValue = "0") int page, + Model model) { + return memberRemoval(groups, auth, id, account, q, page, null, model); + } + + static String memberRemoval( + GroupService groups, + Authentication auth, + UUID id, + UUID account, + String q, + int page, + String expected, + Model model) { + var group = groups.detail(auth, id); + var member = groups.member(auth, id, account); + if (expected != null && !expected.equals(group.grantState())) + throw new org.busystack.caldav.storage.StoreException( + org.busystack.caldav.storage.StoreException.Kind.PRECONDITION); + String parameters = memberSearch(q, page); + model.addAttribute( + "actionTitle", "Remove " + member.username() + " from " + group.name() + "?"); + model.addAttribute( + "consequence", + "Access granted by this group may end. Other direct or group grants continue to apply."); + model.addAttribute("actionLabel", "Remove member"); + model.addAttribute( + "actionPath", "/admin/groups/" + id + "/members/" + account + "/remove" + parameters); + model.addAttribute("cancelPath", "/admin/groups/" + id + parameters); + model.addAttribute("expectedGrants", group.grantState()); + return "confirm-action"; + } + + @PostMapping("/admin/groups/{id}/members/{account}/remove") + String remove( + Authentication auth, + @PathVariable UUID id, + @PathVariable UUID account, + @RequestParam(defaultValue = "false") boolean confirmed, + @RequestParam(defaultValue = "") String expectedGrants, + @RequestParam(defaultValue = "") String q, + @RequestParam(defaultValue = "0") int page, + @RequestParam(required = false) String memberQuery, + @RequestParam(required = false) Integer memberPage, + RedirectAttributes flash) { + var group = groups.detail(auth, id); + var member = groups.member(auth, id, account); + String parameters = + memberSearch(memberQuery == null ? q : memberQuery, memberPage == null ? page : memberPage); + if (!confirmed) + return "redirect:/admin/groups/" + id + "/members/" + account + "/remove" + parameters; + groups.changeMember(auth, id, null, account, false, true, expectedGrants); + flash.addFlashAttribute( + "notice", "Removed " + member.username() + " from " + group.name() + "."); + return "redirect:/admin/groups/" + id + parameters; + } + + private static String memberSearch(String query, int page) { + PortalService.checkQuery(query); + PortalPage.offset(page); + var parameters = org.springframework.web.util.UriComponentsBuilder.newInstance(); + if (!query.isEmpty()) parameters.queryParam("q", query); + if (page > 0) parameters.queryParam("page", page); + return parameters.build().encode().toUriString(); + } + + @GetMapping("/admin/groups/{id}/delete") + String confirmDelete(Authentication auth, @PathVariable UUID id, Model model) { + var group = groups.detail(auth, id); + model.addAttribute("actionTitle", "Delete " + group.name() + "?"); + model.addAttribute( + "consequence", + "This removes the group, its memberships and grants. The underlying resources remain. Access through other grants continues."); + model.addAttribute("actionLabel", "Delete group"); + model.addAttribute("actionPath", "/admin/groups/" + id + "/delete"); + model.addAttribute("cancelPath", "/admin/groups/" + id); + return "confirm-action"; } @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(defaultValue = "") String permission, + @RequestParam String expected, + RedirectAttributes flash) { + if ("REVOKE".equals(permission)) + return "redirect:/collections/" + collection + "/sharing/group/" + group + "/remove"; + 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..9bc732b --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/ImportStaging.java @@ -0,0 +1,197 @@ +package org.busystack.caldav.management; + +import jakarta.annotation.PreDestroy; +import java.time.Instant; +import java.util.*; +import org.busystack.caldav.storage.StoreException; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +/** Account/epoch-bound previews; filesystem cleanup is deliberately outside database atomicity. */ +@Component +public class ImportStaging { + static final class Unavailable extends StoreException { + Unavailable() { + super(Kind.PRECONDITION); + } + } + + public enum State { + AVAILABLE, + CONFIRMING, + CONSUMED, + EXPIRED, + CANCELLED, + UNAVAILABLE + } + + public static final class Staged { + private final UUID token = UUID.randomUUID(); + private final UUID actor, epoch, destination; + private Instant expires; + private final PortabilityStorage.PrivateFile file; + private final long reportBytes; + private State state = State.AVAILABLE; + private PortabilityService.Report report; + + Staged( + UUID actor, + UUID epoch, + UUID destination, + PortabilityStorage.PrivateFile file, + Instant now, + long reportBytes) { + this.expires = now.plusSeconds(600); + this.reportBytes = reportBytes; + this.actor = actor; + this.epoch = epoch; + this.destination = destination; + this.file = file; + } + + public UUID token() { + return token; + } + + public UUID destination() { + return destination; + } + + public Instant expires() { + return expires; + } + + public java.nio.file.Path path() { + return file.path(); + } + + public State state() { + return state; + } + + public PortabilityService.Report report() { + return report; + } + } + + private final java.time.Clock clock; + + public ImportStaging() { + this(java.time.Clock.systemUTC()); + } + + ImportStaging(java.time.Clock clock) { + this.clock = clock; + } + + private final Map stages = new HashMap<>(); + + /** Called only after the replacement has been completely validated and staged. */ + public synchronized Staged save( + UUID actor, + UUID epoch, + UUID destination, + PortabilityStorage.PrivateFile file, + long reportBytes, + java.util.function.Function prepareReport) { + prune(); + var old = stages.values().stream().filter(s -> s.actor.equals(actor)).toList(); + if (old.stream().anyMatch(s -> s.state == State.CONFIRMING)) + throw new StoreException(StoreException.Kind.PRECONDITION); + long retainedReportBytes = + stages.values().stream().filter(s -> !old.contains(s)).mapToLong(s -> s.reportBytes).sum(); + if (reportBytes < 0 + || retainedReportBytes + reportBytes > 32L * 1024 * 1024 + || stages.size() - old.size() >= 32) throw new PortabilityStorage.CapacityException(); + var stage = new Staged(actor, epoch, destination, file, clock.instant(), reportBytes); + stage.report = Objects.requireNonNull(prepareReport.apply(stage)); + for (var previous : old) { + previous.state = State.CANCELLED; + previous.file.close(); + stages.remove(previous.token); + } + stages.put(stage.token, stage); + return stage; + } + + public synchronized Staged owned(UUID token, UUID actor, UUID epoch) { + prune(); + var stage = stages.get(token); + if (stage == null + || !stage.actor.equals(actor) + || !stage.epoch.equals(epoch) + || stage.state == State.CANCELLED + || stage.state == State.EXPIRED + || stage.state == State.UNAVAILABLE) throw new Unavailable(); + return stage; + } + + public synchronized Staged current(UUID actor, UUID epoch) { + prune(); + return stages.values().stream() + .filter( + stage -> + stage.actor.equals(actor) + && stage.epoch.equals(epoch) + && (stage.state == State.AVAILABLE + || stage.state == State.CONFIRMING + || stage.state == State.CONSUMED)) + .findFirst() + .orElse(null); + } + + public synchronized Staged begin(UUID token, UUID actor, UUID epoch) { + var stage = owned(token, actor, epoch); + if (stage.state != State.AVAILABLE) throw new StoreException(StoreException.Kind.PRECONDITION); + stage.state = State.CONFIRMING; + return stage; + } + + public synchronized void complete( + Staged stage, int completion, PortabilityService.Report result) { + if (stage.state != State.CONFIRMING) return; + if (completion + == org.springframework.transaction.support.TransactionSynchronization.STATUS_COMMITTED) { + stage.state = State.CONSUMED; + stage.expires = clock.instant().plusSeconds(600); + stage.report = result; + stage.file.close(); + } else if (completion + == org.springframework.transaction.support.TransactionSynchronization.STATUS_ROLLED_BACK + && stage.expires.isAfter(clock.instant())) stage.state = State.AVAILABLE; + else { + stage.state = + completion + == org.springframework.transaction.support.TransactionSynchronization + .STATUS_UNKNOWN + ? State.UNAVAILABLE + : State.EXPIRED; + stage.file.close(); + } + } + + public synchronized void cancel(UUID token, UUID actor, UUID epoch) { + var stage = owned(token, actor, epoch); + if (stage.state != State.AVAILABLE) throw new StoreException(StoreException.Kind.PRECONDITION); + stage.state = State.CANCELLED; + stage.file.close(); + stages.remove(token); + } + + @Scheduled(fixedDelay = 30000) + public synchronized void prune() { + for (var stage : List.copyOf(stages.values())) { + if (stage.state != State.CONFIRMING && !stage.expires.isAfter(clock.instant())) { + stage.state = State.EXPIRED; + stage.file.close(); + stages.remove(stage.token); + } + } + } + + @PreDestroy + public synchronized void close() { + for (var stage : stages.values()) stage.file.close(); + stages.clear(); + } +} 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..70eb8e2 100644 --- a/src/main/java/org/busystack/caldav/management/ManagementController.java +++ b/src/main/java/org/busystack/caldav/management/ManagementController.java @@ -5,78 +5,134 @@ 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("/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, @RequestParam String name, @RequestParam String component) { - management.createCollection(auth, name, component); - return "redirect:/"; + Authentication auth, + @RequestParam(defaultValue = "") String name, + @RequestParam(defaultValue = "") String component, + @RequestParam(defaultValue = "") String description, + @RequestParam(defaultValue = "") String color, + RedirectAttributes flash) { + UUID id = portal.create(auth, name, component, description, color); + flash.addFlashAttribute( + "notice", + switch (component) { + case "VTODO" -> "Task list created."; + case "VJOURNAL" -> "Journal created."; + default -> "Calendar created."; + }); + return "redirect:/collections/" + id; } @PostMapping("/shares") String share( Authentication auth, @RequestParam UUID collection, - @RequestParam String username, - @RequestParam String permission) { - management.share(auth, collection, username, permission); - return "redirect:/"; + @RequestParam(defaultValue = "") String username, + @RequestParam(defaultValue = "") String permission, + @RequestParam String expected, + RedirectAttributes flash) { + if ("REVOKE".equals(permission)) { + if (!username.matches("[A-Za-z0-9][A-Za-z0-9._-]{0,63}")) + throw FormValidation.field("username", "Choose the exact username of the recipient."); + return "redirect:/collections/" + collection + "/sharing/account/" + username + "/remove"; + } + 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") String issue( Authentication auth, - @RequestParam String label, + @RequestParam(defaultValue = "") String label, @RequestParam int days, + @RequestParam(defaultValue = "generic") String client, + @RequestParam(defaultValue = "security") String from, + @RequestParam(required = false) UUID intent, + @RequestParam(required = false) UUID resource, Model model, jakarta.servlet.http.HttpServletResponse response) { - model.addAttribute("credential", management.issue(auth, label, days)); - response.setHeader("Cache-Control", "no-store"); + model.addAttribute("client", PortalController.client(client)); + model.addAttribute("label", label); + model.addAttribute("credentialOrigin", PortalController.credentialOrigin(from)); + UUID selected = PortalController.credentialResource(from, resource); + PortalController.connectionResource(portal, auth, selected, model); + var result = + management.issue( + auth, label, days, intent, PortalController.issuanceContext(client, from, selected)); + org.busystack.caldav.security.IssuancePages.protect(response); + if (result.secret() == null) { + model.addAttribute("issuedId", result.credentialId()); + model.addAttribute( + "issuanceMessage", + "This request already created an application password. Its original value is only shown once. Review your passwords before creating a replacement."); + return "issuance-receipt"; + } + model.addAttribute("credential", result.secret()); return "issued-credential"; } - @PostMapping("/credentials/{id}/revoke") - String revoke(Authentication auth, @PathVariable UUID id) { - management.revoke(auth, id); - return "redirect:/"; + @GetMapping("/credentials/{id}/revoke") + String confirmRevoke(Authentication auth, @PathVariable UUID id, Model model) { + var credential = management.credential(auth, id); + model.addAttribute("actionTitle", "Revoke " + credential.label() + "?"); + model.addAttribute( + "consequence", + "Apps using this password will lose access the next time they connect. Other application passwords remain available."); + model.addAttribute("actionLabel", "Revoke application password"); + model.addAttribute("actionPath", "/credentials/" + id + "/revoke"); + model.addAttribute("cancelPath", "/security/credentials"); + return "confirm-action"; } - @GetMapping("/admin") - String admin(Authentication auth, Model model) { - model.addAttribute("accounts", management.users(auth)); - return "administration"; - } - - @PostMapping("/admin/accounts") - String provision( + @PostMapping("/credentials/{id}/revoke") + String revoke( 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"; + @PathVariable UUID id, + @RequestParam(defaultValue = "false") boolean confirmed, + RedirectAttributes flash) { + if (!confirmed) return "redirect:/credentials/" + id + "/revoke"; + management.revoke(auth, id); + 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..e50cd75 100644 --- a/src/main/java/org/busystack/caldav/management/ManagementService.java +++ b/src/main/java/org/busystack/caldav/management/ManagementService.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.UUID; import org.busystack.caldav.account.AccountService; +import org.busystack.caldav.security.IssuanceIntents; import org.busystack.caldav.security.RecentAuthentication; import org.busystack.caldav.storage.CalendarStore; import org.springframework.jdbc.core.JdbcTemplate; @@ -18,7 +19,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) {} @@ -36,7 +41,11 @@ public record SharePage(List rows, int page, boolean hasNext) { } } + public record CredentialResult(AccountService.IssuedCredential secret, UUID credentialId) {} + private final AccountService accounts; + private final IssuanceIntents intents; + private final org.busystack.caldav.security.audit.SecurityAudit audit; private final CalendarStore calendars; private final JdbcTemplate jdbc; private final org.busystack.caldav.security.session.SessionSecurity sessions; @@ -45,11 +54,15 @@ public ManagementService( AccountService accounts, CalendarStore calendars, JdbcTemplate jdbc, - org.busystack.caldav.security.session.SessionSecurity sessions) { + org.busystack.caldav.security.session.SessionSecurity sessions, + IssuanceIntents intents, + org.busystack.caldav.security.audit.SecurityAudit audit) { this.accounts = accounts; this.calendars = calendars; this.jdbc = jdbc; this.sessions = sessions; + this.intents = intents; + this.audit = audit; } public UserView current(Authentication auth) { @@ -60,6 +73,32 @@ 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) { + 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()); } @@ -97,6 +136,25 @@ public List credentials(Authentication auth) { actor); } + public Credential credential(Authentication auth, UUID id) { + var rows = + jdbc.query( + "SELECT label,created_at,expires_at,revoked_at FROM dav_credentials WHERE id=? AND account_id=?", + (rs, row) -> + new Credential( + id, + rs.getString(1), + rs.getTimestamp(2).toInstant(), + rs.getTimestamp(3).toInstant(), + rs.getTimestamp(4) != null), + id, + requireAccount(auth).id()); + if (rows.isEmpty()) + throw new org.busystack.caldav.storage.StoreException( + org.busystack.caldav.storage.StoreException.Kind.NOT_FOUND); + return rows.getFirst(); + } + public List users(Authentication auth) { requireAdministrator(auth); return jdbc.query( @@ -112,29 +170,84 @@ public List users(Authentication auth) { @Transactional public void provision(Authentication auth, String username, String displayName, String password) { + RecentAuthentication.requireMfa(auth); requireAdministrator(auth); accounts.provision(username, displayName, password, false); } @Transactional - public void disable(Authentication auth, UUID id) { + public UUID disable(Authentication auth, UUID id) { + RecentAuthentication.requireMfa(auth); + // Lock in the same order in either direction; check the live actor after acquiring locks. + var locked = + jdbc.queryForList( + "SELECT id FROM accounts WHERE (administrator AND enabled) OR id=? ORDER BY id FOR UPDATE", + UUID.class, + id); requireAdministrator(auth); + UUID actor = sessions.assertForReset(auth).id(); + if (actor.equals(id)) + throw new AccessDeniedException("You cannot disable your own administrator account."); + if (!locked.contains(id)) + throw new org.busystack.caldav.storage.StoreException( + org.busystack.caldav.storage.StoreException.Kind.NOT_FOUND); + var target = accounts.find(id); + if (!target.enabled()) + throw new org.busystack.caldav.storage.StoreException( + org.busystack.caldav.storage.StoreException.Kind.PRECONDITION); + if (target.administrator() && locked.size() <= 1) + throw new AccessDeniedException("At least one enabled administrator must remain."); accounts.disable(id); + return actor; } @Transactional public AccountService.IssuedCredential issue(Authentication auth, String label, int days) { RecentAuthentication.requireMfa(auth); if (days < 1 || days > 365) - throw new IllegalArgumentException("Expiry must be between 1 and 365 days"); - return accounts.issueDavCredential( - requireAccount(auth).id(), label, Instant.now().plusSeconds(days * 86400L)); + throw FormValidation.field("days", "Choose an expiration of 1–365 days."); + UUID actor = requireAccount(auth).id(); + if (label == null + || label.isBlank() + || label.length() > 100 + || !org.busystack.caldav.xml.XmlCharacters.valid(label) + || label.codePoints().anyMatch(Character::isISOControl)) + throw FormValidation.field( + "label", "Use a credential label of 1–100 characters without control characters."); + return accounts.issueDavCredential(actor, label, Instant.now().plusSeconds(days * 86400L)); + } + + @Transactional + public CredentialResult issue( + Authentication auth, String label, int days, UUID intent, String context) { + RecentAuthentication.requireMfa(auth); + var account = sessions.assertForReset(auth); + var claim = + intents.claim(account, intent, IssuanceIntents.Purpose.APPLICATION_PASSWORD, context); + if (claim.consumed()) return new CredentialResult(null, claim.result()); + var issued = issue(auth, label, days); + audit.record( + account.id(), + org.busystack.caldav.security.audit.SecurityAudit.Action.APPLICATION_PASSWORD_ISSUED, + org.busystack.caldav.security.audit.SecurityAudit.Outcome.SUCCESS, + null); + intents.consume(claim, issued.id()); + return new CredentialResult(issued, issued.id()); } @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 @@ -149,10 +262,11 @@ public void share(Authentication auth, UUID collection, String username, String org.busystack.caldav.storage.DavMutationLock.shared(jdbc); RecentAuthentication.requireMfa(auth); if (!java.util.Set.of("READ", "WRITE", "REVOKE").contains(permission)) - throw new IllegalArgumentException("Invalid sharing permission"); + throw FormValidation.field( + "permission", "Choose read-only, read and write, or remove the grant."); var member = accounts.find(username); if (member == null || (!member.enabled() && !"REVOKE".equals(permission))) - throw new IllegalArgumentException("Unknown active account"); + throw FormValidation.field("username", "Enter the exact username of an active account."); calendars.share( requireAccount(auth).id(), collection, @@ -170,8 +284,7 @@ private AccountService.Account requireAccount(Authentication auth) { return account; } - private void requireAdministrator(Authentication auth) { - RecentAuthentication.requireMfa(auth); + public void requireAdministrator(Authentication 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..fcedc90 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,24 @@ 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( + "journalCollections", + jdbc.queryForObject( + "SELECT count(*) FROM collections WHERE component='VJOURNAL'", Long.class)); + model.addAttribute( + "groups", jdbc.queryForObject("SELECT count(*) FROM sharing_groups", 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 +99,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..d78b4e3 --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/PortabilityController.java @@ -0,0 +1,144 @@ +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.ModelAndView; +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) { + if (destination.isEmpty()) + model.addAttribute("collectionPage", portal.collections(auth, "all", "", page)); + else + model.addAttribute( + "collectionPage", + new PortalPage<>( + java.util.List.of(portal.collection(auth, UUID.fromString(destination))), 0, false)); + model.addAttribute("selectedDestination", destination); + model.addAttribute("currentImportToken", portability.currentToken(auth)); + return "portability"; + } + + @GetMapping("/portability/verify") + String verify(Authentication auth, @RequestParam UUID destination) { + var collection = portal.collection(auth, destination); + if (!collection.writable()) + throw new org.busystack.caldav.storage.StoreException( + org.busystack.caldav.storage.StoreException.Kind.FORBIDDEN); + return "redirect:/portability?destination=" + destination; + } + + @PostMapping("/portability/preview") + String preview( + Authentication auth, @RequestParam UUID destination, @RequestParam MultipartFile file) + throws IOException { + if (file.isEmpty()) + throw FormValidation.field("file", "Choose an iCalendar file to validate and preview."); + if (file.getSize() > CalendarInterchange.MAX_FILE_BYTES) + throw new org.busystack.caldav.storage.StoreException( + org.busystack.caldav.storage.StoreException.Kind.LIMIT); + try (var input = file.getInputStream()) { + var report = portability.preview(auth, destination, input); + return "redirect:/portability/import/" + report.token(); + } + } + + @PostMapping("/portability/import/{token}") + String confirm( + Authentication auth, + @PathVariable UUID token, + @RequestParam(defaultValue = "false") boolean confirmed) + throws IOException { + portability.confirm(auth, token, confirmed); + return "redirect:/portability/import/" + token; + } + + @GetMapping("/portability/import/{token}") + String review( + Authentication auth, + @PathVariable UUID token, + @RequestParam(defaultValue = "0") int page, + Model model) { + model.addAttribute("report", portability.review(auth, token, page)); + paginate(model, page, token); + return "import-report"; + } + + private void paginate(Model model, int page, UUID token) { + var report = (PortabilityService.Report) model.getAttribute("report"); + int start = PortalPage.offset(page); + if (start > report.items().size()) + throw new org.busystack.caldav.storage.StoreException( + org.busystack.caldav.storage.StoreException.Kind.PRECONDITION); + model.addAttribute( + "itemPage", report.items().subList(start, Math.min(start + 50, report.items().size()))); + model.addAttribute("reportPage", page); + model.addAttribute("hasNextItems", start + 50 < report.items().size()); + model.addAttribute("reportId", token); + } + + @PostMapping("/portability/import/{token}/cancel") + String cancel(Authentication auth, @PathVariable UUID token, RedirectAttributes flash) { + var report = portability.review(auth, token, 0); + portability.cancel(auth, token); + flash.addFlashAttribute("notice", "Import preview discarded."); + return "redirect:/collections/" + report.destination(); + } + + @GetMapping("/portability/collections/{id}/export") + ModelAndView export( + Authentication auth, + @PathVariable UUID id, + HttpServletResponse response, + RedirectAttributes flash) + throws IOException { + var export = portability.export(auth, id); + try { + response.setHeader("Cache-Control", "no-store"); + if (export.length() == 0) { + String item = + switch (portal.collection(auth, id).component()) { + case "VTODO" -> "tasks"; + case "VJOURNAL" -> "journal entries"; + default -> "events"; + }; + flash.addFlashAttribute("notice", "There are no " + item + " to export yet."); + flash.addFlashAttribute("noticeSeverity", "info"); + return new ModelAndView("redirect:/collections/" + id); + } + response.setContentType("text/calendar; charset=utf-8"); + response.setHeader( + "Content-Disposition", + "attachment; filename=\"busystack-collection" + + (export.stream() ? "-stream" : "") + + ".ics\""); + response.setContentLengthLong(export.length()); + Files.copy(export.path(), response.getOutputStream()); + return null; + } finally { + export.close(); + } + } +} 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..4434d56 --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/PortabilityService.java @@ -0,0 +1,401 @@ +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, + UUID destination, + String component, + 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(PortabilityStorage.PrivateFile file, long length, boolean stream) + implements AutoCloseable { + public Path path() { + return file.path(); + } + + @Override + public void close() { + file.close(); + } + } + + 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 PortabilityStorage storage; + + public PortabilityService( + PortalService portal, + SessionSecurity sessions, + CalendarStore calendars, + DavStore dav, + CalendarInterchange interchange, + ImportStaging staging, + JdbcTemplate jdbc, + SecurityAudit audit, + PortabilityStorage storage) { + this.portal = portal; + this.sessions = sessions; + this.calendars = calendars; + this.dav = dav; + this.interchange = interchange; + this.staging = staging; + this.jdbc = jdbc; + this.audit = audit; + this.storage = storage; + } + + @Transactional( + isolation = Isolation.REPEATABLE_READ, + timeout = CalendarInterchange.MAX_PROCESSING_SECONDS, + rollbackFor = IOException.class) + public Report preview(Authentication auth, UUID destination, java.io.InputStream input) + throws IOException { + long deadline = + System.nanoTime() + + java.util.concurrent.TimeUnit.SECONDS.toNanos( + CalendarInterchange.MAX_PROCESSING_SECONDS); + RecentAuthentication.requireMfa(auth); + var actor = sessions.assertCurrent(auth); + var collection = portal.collection(auth, destination); + if (!collection.writable()) throw new StoreException(StoreException.Kind.FORBIDDEN); + try (var work = storage.begin(true)) { + var file = storage.create(PortabilityStorage.FILE_BYTES); + boolean retained = false; + try (var index = storage.create(PortabilityStorage.INDEX_BYTES)) { + try (var output = Files.newOutputStream(file.path())) { + byte[] buffer = new byte[8192]; + long length = 0; + int n; + while ((n = input.read(buffer)) != -1) { + length += n; + if (length > CalendarInterchange.MAX_FILE_BYTES || System.nanoTime() > deadline) + throw new StoreException(StoreException.Kind.LIMIT); + output.write(buffer, 0, n); + } + } + List results; + try (var items = interchange.open(file.path(), index.path(), deadline)) { + results = classify(actor.id(), destination, items, collection.component(), false); + } + file.compact(); + long reportBytes = + results.stream() + .mapToLong( + i -> + 256L + + 2L + * (i.uid().length() + + i.label().length() + + i.explanation().length())) + .sum(); + var stage = + staging.save( + actor.id(), + actor.epoch(), + destination, + file, + reportBytes, + prepared -> report(prepared.token(), collection, prepared.expires(), results)); + retained = true; + return stage.report(); + } finally { + if (!retained) file.close(); + } + } + } + + // Convenience for small internal fixtures; HTTP always streams from the multipart file. + @Transactional( + isolation = Isolation.REPEATABLE_READ, + timeout = CalendarInterchange.MAX_PROCESSING_SECONDS, + rollbackFor = IOException.class) + public Report preview(Authentication auth, UUID destination, byte[] file) throws IOException { + return preview(auth, destination, new java.io.ByteArrayInputStream(file)); + } + + @Transactional( + timeout = CalendarInterchange.MAX_PROCESSING_SECONDS, + rollbackFor = IOException.class) + public Report confirm(Authentication auth, UUID token, boolean confirmed) throws IOException { + long deadline = + System.nanoTime() + + java.util.concurrent.TimeUnit.SECONDS.toNanos( + CalendarInterchange.MAX_PROCESSING_SECONDS); + RecentAuthentication.requireMfa(auth); + var actor = sessions.assertCurrent(auth); + var available = staging.owned(token, actor.id(), actor.epoch()); + if (!confirmed) + throw FormValidation.field( + "confirmed", "Confirm importing the ready items before continuing."); + dav.lockCollection(actor.id(), available.destination()); + var collection = portal.collection(auth, available.destination()); + if (!collection.writable()) throw new StoreException(StoreException.Kind.FORBIDDEN); + var stage = staging.begin(token, actor.id(), actor.epoch()); + var outcome = new java.util.concurrent.atomic.AtomicReference(); + org.springframework.transaction.support.TransactionSynchronizationManager + .registerSynchronization( + new org.springframework.transaction.support.TransactionSynchronization() { + @Override + public void afterCompletion(int status) { + staging.complete(stage, status, outcome.get()); + } + }); + try (var work = storage.begin(false); + var index = storage.create(PortabilityStorage.INDEX_BYTES); + var items = interchange.open(stage.path(), index.path(), deadline)) { + var results = classify(actor.id(), stage.destination(), items, collection.component(), true); + audit.record( + actor.id(), + SecurityAudit.Action.COLLECTION_IMPORTED, + SecurityAudit.Outcome.SUCCESS, + null); + var report = report(null, collection, null, results); + outcome.set(report); + return report; + } + } + + public UUID currentToken(Authentication auth) { + if (!RecentAuthentication.mfaCurrent(auth)) return null; + var actor = sessions.assertCurrent(auth); + var stage = staging.current(actor.id(), actor.epoch()); + if (stage == null) return null; + try { + portal.collection(auth, stage.destination()); + } catch (StoreException unavailable) { + if (unavailable.kind() == StoreException.Kind.FORBIDDEN + || unavailable.kind() == StoreException.Kind.NOT_FOUND) return null; + throw unavailable; + } + return stage.token(); + } + + public Report review(Authentication auth, UUID token, int page) { + RecentAuthentication.requireMfa(auth); + var actor = sessions.assertCurrent(auth); + var stage = staging.owned(token, actor.id(), actor.epoch()); + // Never redisplay private preview metadata after destination access is revoked. + portal.collection(auth, stage.destination()); + return stage.report(); + } + + 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, + CalendarInterchange.IndexedFile items, + String component, + boolean write) + throws IOException { + List result = new ArrayList<>(); + long resourceBytes = 0; + for (int n = 0; n < items.size(); n++) { + var item = interchange.item(items, n, component); + if (item.rejection().isEmpty()) { + resourceBytes += item.content().length; + if (resourceBytes > PortabilityStorage.FILE_BYTES) + throw new StoreException(StoreException.Kind.LIMIT); + } + 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().substring(0, Math.min(100, item.uid().length())), + status, + explanation)); + } + return List.copyOf(result); + } + + private static Report report( + UUID token, + PortalService.CollectionView collection, + Instant expires, + List results) { + return new Report( + token, + collection.id(), + collection.component(), + collection.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 = CalendarInterchange.MAX_PROCESSING_SECONDS) + public Export export(Authentication auth, UUID id) throws IOException { + RecentAuthentication.requireMfa(auth); + UUID actor = sessions.assertCurrent(auth).id(); + var collection = calendars.collection(actor, id); + PortabilityStorage.PrivateFile managed = null; + boolean transferred = false; + try (var work = storage.begin(false)) { + managed = storage.create(PortabilityStorage.FILE_BYTES); + Path file = managed.path(); + long deadline = + System.nanoTime() + + java.util.concurrent.TimeUnit.SECONDS.toNanos( + CalendarInterchange.MAX_PROCESSING_SECONDS); + long length = 0; + int count = 0; + String after = ""; + CalendarInterchange.ExportParts first = null; + String context = null; + boolean compatible = true; + try (var output = Files.newOutputStream(file)) { + while (true) { + if (System.nanoTime() > deadline || Thread.currentThread().isInterrupted()) + throw new StoreException(StoreException.Kind.LIMIT); + 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()); + var parts = CalendarInterchange.exportParts(body); + if (first == null) { + first = parts; + context = parts.contextFingerprint(); + } else if (!context.equals(parts.contextFingerprint())) compatible = false; + if (++count > CalendarInterchange.MAX_ITEMS + || length + body.length + 2 > PortabilityStorage.FILE_BYTES) + throw new StoreException(StoreException.Kind.LIMIT); + output.write(body); + length += body.length; + if (body[body.length - 1] != '\n') { + if (body[body.length - 1] != '\r') output.write('\r'); + output.write('\n'); + length += body[body.length - 1] == '\r' ? 1 : 2; + } + after = resource.name(); + } + } + } + if (compatible && count > 1) { + // One VCALENDAR is consumed by more migration tools. Combine only identical calendar + // contexts: no property, timezone, component or parameter needs rewriting or dropping. + after = ""; + try (var output = Files.newOutputStream(file)) { + output.write(first.header()); + output.write(first.zones()); + while (true) { + if (System.nanoTime() > deadline || Thread.currentThread().isInterrupted()) + throw new StoreException(StoreException.Kind.LIMIT); + var batch = calendars.resourceBatch(actor, id, after); + if (batch.isEmpty()) break; + for (var resource : batch) { + output.write(CalendarInterchange.exportParts(resource.content()).items()); + after = resource.name(); + } + } + output.write(first.closing()); + } + 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 { + if (!transferred && managed != null) managed.close(); + } + } +} diff --git a/src/main/java/org/busystack/caldav/management/PortabilityStorage.java b/src/main/java/org/busystack/caldav/management/PortabilityStorage.java new file mode 100644 index 0000000..2af6887 --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/PortabilityStorage.java @@ -0,0 +1,290 @@ +package org.busystack.caldav.management; + +import jakarta.annotation.PreDestroy; +import java.io.IOException; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.nio.file.*; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.*; +import java.util.concurrent.Semaphore; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +/** One private filesystem, byte reservation ledger and work gate for portability. */ +@Component +public final class PortabilityStorage implements AutoCloseable { + public static final long MIB = 1024L * 1024; + public static final long FILE_BYTES = + org.busystack.caldav.calendar.CalendarInterchange.MAX_FILE_BYTES; + public static final long INDEX_BYTES = + org.busystack.caldav.calendar.CalendarInterchange.MAX_INDEX_BYTES; + public static final long UPLOAD_BYTES = 65 * MIB; + public static final long TOTAL_BYTES = 272 * MIB; + private final Path root; + private final FileChannel lockChannel; + private final FileLock lock; + private final Semaphore operations = new Semaphore(2); + private final Set files = new HashSet<>(); + private final ThreadLocal current = new ThreadLocal<>(); + private long reserved, multipartPending; + private int uploads; + + public PortabilityStorage( + @Value("${busystack.portability.directory:${java.io.tmpdir}/busystack-portability}") + String directory) + throws IOException { + root = Path.of(directory).toAbsolutePath().normalize(); + if (!Files.exists(root, LinkOption.NOFOLLOW_LINKS)) + Files.createDirectory( + root, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))); + if (!root.equals(root.toRealPath()) + || !Files.isDirectory(root, LinkOption.NOFOLLOW_LINKS) + || !Files.getPosixFilePermissions(root, LinkOption.NOFOLLOW_LINKS) + .equals(PosixFilePermissions.fromString("rwx------")) + || !ownedByProcess(root)) + throw new IOException( + "Portability directory must be private and owned by the application user"); + lockChannel = + FileChannel.open( + root.resolve("instance.lock"), + StandardOpenOption.CREATE, + StandardOpenOption.WRITE, + LinkOption.NOFOLLOW_LINKS); + Files.setPosixFilePermissions( + root.resolve("instance.lock"), PosixFilePermissions.fromString("rw-------")); + lock = lockChannel.tryLock(); + if (lock == null) { + lockChannel.close(); + throw new IOException("Portability directory is already in use"); + } + try { + try (var entries = Files.newDirectoryStream(root, "data-*.private")) { + for (Path entry : entries) { + if (!entry.getFileName().toString().matches("data-[0-9a-f-]{36}\\.private")) continue; + if (!Files.isRegularFile(entry, LinkOption.NOFOLLOW_LINKS)) + throw new IOException("Unexpected portability staging entry"); + Files.delete(entry); + } + } + } catch (IOException | RuntimeException failure) { + lock.release(); + lockChannel.close(); + throw failure; + } + } + + private static boolean ownedByProcess(Path directory) throws IOException { + // One-off Compose commands can run as a numeric UID with no account in the image. + Path probe = Files.createTempFile(directory, "owner-", ".private"); + try { + return Files.getOwner(directory, LinkOption.NOFOLLOW_LINKS) + .equals(Files.getOwner(probe, LinkOption.NOFOLLOW_LINKS)); + } finally { + Files.delete(probe); + } + } + + public Path multipartDirectory() throws IOException { + Path directory = root.resolve("multipart"); + if (!Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) + Files.createDirectory( + directory, + PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))); + if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS) + || !Files.getPosixFilePermissions(directory, LinkOption.NOFOLLOW_LINKS) + .equals(PosixFilePermissions.fromString("rwx------"))) + throw new IOException("Invalid multipart directory"); + try (var entries = Files.newDirectoryStream(directory)) { + for (Path entry : entries) { + if (!Files.isRegularFile(entry, LinkOption.NOFOLLOW_LINKS) + || !entry.getFileName().toString().matches("upload_[A-Za-z0-9_-]+\\.tmp")) + throw new IOException("Unexpected multipart staging entry"); + Files.delete(entry); + } + } + return directory; + } + + public Work begin(boolean upload) { + 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) { + if (reserved + bytes > TOTAL_BYTES) { + operations.release(); + throw new CapacityException(); + } + reserved += bytes; + if (upload) uploads++; + } + var work = new Work(true, bytes, upload); + current.set(work); + return work; + } + + public final class Work implements AutoCloseable { + private final boolean owner, upload; + private long remaining; + private boolean finished; + + 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) { + 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(); + } + } + + public synchronized PrivateFile create(long maximum) throws IOException { + if (maximum <= 0 || maximum > FILE_BYTES || files.size() >= 72) throw new CapacityException(); + var work = current.get(); + if (work != null && work.remaining >= maximum) work.remaining -= maximum; + else { + if (reserved + maximum > TOTAL_BYTES) throw new CapacityException(); + reserved += maximum; + } + try { + Path path = root.resolve("data-" + UUID.randomUUID() + ".private"); + Files.createFile( + path, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))); + var file = new PrivateFile(path, maximum); + files.add(file); + return file; + } catch (IOException | RuntimeException | Error failure) { + reserved -= maximum; + throw failure; + } + } + + public final class PrivateFile implements AutoCloseable { + private final Path path; + private long reservation; + private boolean deleting, closed; + + private PrivateFile(Path path, long reservation) { + this.path = path; + this.reservation = reservation; + } + + public Path path() { + return path; + } + + public void compact() throws IOException { + synchronized (PortabilityStorage.this) { + long size = Files.size(path); + if (size > reservation) throw new IOException("Portability file exceeded its reservation"); + reserved -= reservation - size; + reservation = size; + } + } + + @Override + public void close() { + synchronized (PortabilityStorage.this) { + if (closed) return; + deleting = true; + try { + Files.deleteIfExists(path); + reserved -= reservation; + reservation = 0; + closed = true; + files.remove(this); + } catch (IOException failure) { + // Keep the reservation until deletion succeeds. A committed import never becomes + // retryable. + org.slf4j.LoggerFactory.getLogger(PortabilityStorage.class) + .warn("Private portability cleanup pending"); + } + } + } + } + + /** 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; + for (var file : files) + if (Files.isRegularFile(file.path, LinkOption.NOFOLLOW_LINKS)) total += Files.size(file.path); + Path multipart = root.resolve("multipart"); + if (Files.isDirectory(multipart, LinkOption.NOFOLLOW_LINKS)) { + try (var entries = Files.newDirectoryStream(multipart)) { + for (Path entry : entries) + if (Files.isRegularFile(entry, LinkOption.NOFOLLOW_LINKS)) total += Files.size(entry); + } + } + return total; + } + + public synchronized long reservedBytes() { + return reserved; + } + + @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(); + } + + public static final class CapacityException extends RuntimeException { + public CapacityException() { + super("Temporary portability capacity is busy; retry or discard an unused preview"); + } + } +} 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..74d22f4 --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/PortalController.java @@ -0,0 +1,208 @@ +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; + private final org.busystack.caldav.security.IssuanceIntents intents; + + public PortalController( + PortalService portal, + GroupService groups, + org.busystack.caldav.security.IssuanceIntents intents) { + this.portal = portal; + this.groups = groups; + this.intents = intents; + } + + @GetMapping("/collections") + String collections( + Authentication auth, + @RequestParam(defaultValue = "all") 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("setup", portal.setup(auth)); + model.addAttribute("query", q); + return "collections"; + } + + @GetMapping("/collections/new") + String create(@RequestParam(defaultValue = "VEVENT") String component, Model model) { + model.addAttribute( + "selectedComponent", + org.busystack.caldav.calendar.CalendarContent.supportsCollectionComponent(component) + ? component + : "VEVENT"); + return "collection-new"; + } + + @GetMapping("/collections/{id}") + String collection(Authentication auth, @PathVariable UUID id, Model model) { + model.addAttribute("collection", portal.collection(auth, id)); + model.addAttribute("hasItems", portal.hasItems(auth, id)); + return "collection"; + } + + @PostMapping("/collections/{id}/edit") + String edit( + Authentication auth, + @PathVariable UUID id, + @RequestParam String state, + @RequestParam(defaultValue = "") 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.eligibleGroups(auth, id)); + return "collection-sharing"; + } + + @GetMapping("/connections") + String connections( + Authentication auth, + @RequestParam(defaultValue = "0") int page, + @RequestParam(required = false) String client, + @RequestParam(required = false) UUID resource, + Model model) { + if (client != null) model.addAttribute("client", client(client)); + connectionResource(portal, auth, resource, 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, + @RequestParam(defaultValue = "generic") String client, + @RequestParam(defaultValue = "security") String from, + @RequestParam(required = false) UUID resource, + Model model, + jakarta.servlet.http.HttpServletResponse response) { + return credentialPage(auth, page, client, from, resource, model, response, false); + } + + @GetMapping("/security/credentials/new") + String prepareCredential( + Authentication auth, + @RequestParam(defaultValue = "generic") String client, + @RequestParam(defaultValue = "security") String from, + @RequestParam(required = false) UUID resource, + Model model, + jakarta.servlet.http.HttpServletResponse response) { + return credentialPage(auth, 0, client, from, resource, model, response, true); + } + + private String credentialPage( + Authentication auth, + int page, + String client, + String from, + UUID resource, + Model model, + jakarta.servlet.http.HttpServletResponse response, + boolean prepare) { + model.addAttribute("client", client(client)); + model.addAttribute("credentialOrigin", credentialOrigin(from)); + UUID selected = credentialResource(from, resource); + connectionResource(portal, auth, selected, model); + model.addAttribute("credentialPage", portal.credentials(auth, page)); + org.busystack.caldav.security.IssuancePages.protect(response); + if (!prepare) return "credentials"; + try { + model.addAttribute( + "issuanceIntent", + intents + .prepare( + auth, + org.busystack.caldav.security.IssuanceIntents.Purpose.APPLICATION_PASSWORD, + issuanceContext(client, from, selected)) + .id()); + } catch (org.busystack.caldav.security.IssuanceIntents.Unavailable unavailable) { + if (!unavailable.busy()) throw unavailable; + response.setStatus(503); + model.addAttribute("issuanceMessage", unavailable.getMessage()); + } + return "credentials"; + } + + static String credentialOrigin(String from) { + return "connect".equals(from) ? "connect" : "security"; + } + + static UUID credentialResource(String from, UUID resource) { + return "connect".equals(from) ? resource : null; + } + + static void connectionResource( + PortalService portal, Authentication auth, UUID resource, Model model) { + if (resource == null) return; + model.addAttribute("connectionResource", portal.collection(auth, resource)); + model.addAttribute("connectionResourceId", resource); + } + + static String issuanceContext(String client, String from, UUID resource) { + String context = client(client) + ":" + credentialOrigin(from); + return resource == null ? context : context + ":" + resource; + } + + 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/PortalErrors.java b/src/main/java/org/busystack/caldav/management/PortalErrors.java new file mode 100644 index 0000000..ca1e0d9 --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/PortalErrors.java @@ -0,0 +1,203 @@ +package org.busystack.caldav.management; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +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, + SharingReviewController.class, + PortabilityController.class, + ReviewFormController.class, + OperationalDiagnostics.class, + org.busystack.caldav.security.oauth.OAuthManagementController.class, + org.busystack.caldav.security.passkey.PasskeyPages.class, + org.busystack.caldav.security.session.SessionController.class + }) +public class PortalErrors { + private final FormRecovery forms; + private final PortalPageAdvice pages; + + public PortalErrors(FormRecovery forms, PortalPageAdvice pages) { + this.forms = forms; + this.pages = pages; + } + + @ExceptionHandler({ + IllegalArgumentException.class, + StoreException.class, + DataAccessException.class, + org.springframework.transaction.TransactionException.class, + org.busystack.caldav.calendar.CalendarValidationException.class, + org.springframework.web.bind.MissingServletRequestParameterException.class, + org.springframework.web.multipart.support.MissingServletRequestPartException.class, + org.springframework.web.method.annotation.MethodArgumentTypeMismatchException.class, + AccessDeniedException.class, + java.io.IOException.class, + PortabilityStorage.CapacityException.class + }) + String failure( + Exception failure, + HttpServletRequest request, + HttpServletResponse response, + Model model, + org.springframework.security.core.Authentication auth) { + pages.layout(auth, request, model); + Map errors = null; + if (failure instanceof FormValidation invalid) errors = invalid.errors(); + else if (failure instanceof org.busystack.caldav.calendar.CalendarValidationException + && request.getServletPath().equals("/portability/preview")) + errors = + Map.of( + "file", + "Choose a well-formed iCalendar file within the supported parsing limits. Any previous valid preview is preserved."); + else if (failure + instanceof + org.springframework.web.multipart.support.MissingServletRequestPartException missing) + errors = + Map.of(missing.getRequestPartName(), "Choose an iCalendar file to validate and preview."); + else if (failure + instanceof org.springframework.web.bind.MissingServletRequestParameterException missing) + errors = Map.of(missing.getParameterName(), "Complete this field."); + else if (failure + instanceof + org.springframework.web.method.annotation.MethodArgumentTypeMismatchException mismatch) + errors = Map.of(mismatch.getName(), "Choose a valid value for this field."); + if (errors != null && (errors.containsKey("expected") || errors.containsKey("state"))) { + errors = null; + failure = new StoreException(StoreException.Kind.PRECONDITION); + } + if (errors != null) { + try { + String view = forms.render(auth, request, model, errors); + if (view != null) { + response.setStatus( + failure instanceof FormValidation invalid && invalid.conflict() ? 409 : 400); + response.setHeader("Cache-Control", "no-store"); + return view; + } + } catch (AccessDeniedException | StoreException | DataAccessException authorization) { + failure = authorization; + } catch (IllegalArgumentException invalidContext) { + /* Malformed resource identifiers use the safe generic response. */ + } + } + 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 account cannot perform that action. Return to a page available to your account."; + } 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 no longer available to this account. Return to your available resources or ask the owner to review your access."; + 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 org.springframework.transaction.TransactionException + || failure instanceof java.io.IOException + || failure instanceof PortabilityStorage.CapacityException) { + 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."; + } + if (failure instanceof java.io.IOException) { + message = + "Temporary calendar storage could not complete the operation. Return to the workflow and retry while the preview remains valid; the operator can check private storage and the request identifier."; + } + if (failure instanceof PortabilityStorage.CapacityException) { + response.setHeader("Retry-After", "5"); + message = + "Temporary portability capacity is busy. Retry later or discard an unused preview. Existing data and previews are preserved."; + } + boolean terminalImport = + request.getServletPath().startsWith("/portability/import/") + && (failure instanceof ImportStaging.Unavailable || status == 404 || status == 403); + if (terminalImport) { + title = "Import report unavailable"; + message = + "This report may have expired, been replaced, or been lost after a restart. If you submitted confirmation, inspect the destination before importing again."; + } + response.setStatus(status); + response.setHeader("Cache-Control", "no-store"); + model.addAttribute("errorTitle", title); + model.addAttribute("message", message); + model.addAttribute("requestReference", response.getHeader("X-Request-ID")); + String path = ReviewFormController.route(request); + String retry = "/"; + if (path.equals("/collections")) retry = "/collections/new"; + else if (path.matches("/collections/[a-f0-9-]{36}/sharing/(account|group)/[^/]+/remove")) + retry = path.substring(0, path.indexOf("/sharing/")) + "/sharing"; + 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?client=" + + PortalController.client( + java.util.Objects.requireNonNullElse(request.getParameter("client"), "generic")); + else if (terminalImport) retry = "/portability"; + else if (path.matches("/portability/import/[a-f0-9-]{36}")) retry = path; + 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..395abf2 --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/PortalPageAdvice.java @@ -0,0 +1,99 @@ +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; + private org.busystack.caldav.security.session.BrowserSession browserSessions; + + public PortalPageAdvice(ManagementService management) { + this.management = management; + } + + @org.springframework.beans.factory.annotation.Autowired + void configureBrowserSessions( + org.busystack.caldav.security.session.BrowserSession browserSessions) { + this.browserSessions = browserSessions; + } + + @ModelAttribute + public void layout(Authentication auth, HttpServletRequest request, Model model) { + String path = ReviewFormController.route(request); + 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.equals("/admin") || path.startsWith("/admin/")); + String origin = + path.startsWith("/credentials") || path.startsWith("/security/credentials") + ? request.getParameter("from") + : null; + model.addAttribute("section", section(path, origin)); + model.addAttribute("applicationShell", false); + 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)); + boolean authPage = + path.equals("/login") + || path.startsWith("/auth/") + || path.equals("/security/recovery/use") + || path.startsWith("/setup") + || path.equals("/help/setup"); + model.addAttribute( + "applicationShell", + !authPage && org.busystack.caldav.security.session.BrowserSession.completed(request)); + if (browserSessions != null + && org.busystack.caldav.security.session.BrowserSession.completed(request)) { + var session = request.getSession(false); + var overall = browserSessions.overallDeadline(request); + if (session != null && overall != null) { + model.addAttribute( + "idleDeadline", + java.time.Instant.ofEpochMilli(session.getLastAccessedTime()) + .plusSeconds(session.getMaxInactiveInterval()) + .toEpochMilli()); + model.addAttribute("overallDeadline", overall.toEpochMilli()); + model.addAttribute("serverTime", System.currentTimeMillis()); + } + } + 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. + } + } + } + + private static String section(String path, String origin) { + if (path.equals("/admin")) return "admin-overview"; + if (path.startsWith("/admin/accounts")) return "accounts"; + if (path.startsWith("/admin/groups")) return "groups"; + if (path.startsWith("/admin/audit") || path.startsWith("/admin/oauth-clients")) return "audit"; + if (path.startsWith("/admin")) return "diagnostics"; + if (path.startsWith("/collections") + || path.startsWith("/portability") + || path.equals("/shares") + || path.equals("/group-shares")) return "collections"; + if (path.startsWith("/connections") + || path.startsWith("/credentials") && "connect".equals(origin) + || path.startsWith("/security/credentials") && "connect".equals(origin)) + return "connections"; + return path.equals("/") ? "overview" : "security"; + } +} 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..0dbf959 --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/PortalService.java @@ -0,0 +1,396 @@ +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.calendar.CalendarContent; +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 switch (component) { + case "VEVENT" -> "Calendar"; + case "VTODO" -> "Task list"; + case "VJOURNAL" -> "Journal"; + default -> throw new IllegalStateException("Unknown collection component"); + }; + } + + 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(isolation = org.springframework.transaction.annotation.Isolation.REPEATABLE_READ) + public boolean hasItems(Authentication auth, UUID id) { + // Authorize and inspect the same snapshot, without reading stored content. + var actor = management.current(auth).id(); + calendars.collection(actor, id); + return Boolean.TRUE.equals( + jdbc.queryForObject( + "SELECT EXISTS(SELECT 1 FROM calendar_resources WHERE collection_id=?)", + Boolean.class, + id)); + } + + @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 (!CalendarContent.supportsCollectionComponent(component)) + throw FormValidation.field("component", "Choose a calendar, task list, or journal."); + 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) { + new FormValidation.Checks() + .require( + "name", + name != null && !name.isBlank() && name.length() <= 200 && XmlCharacters.valid(name), + "Use a name of 1–200 characters.") + .require( + "description", + description != null && description.length() <= 8000 && XmlCharacters.valid(description), + "Use a description of at most 8,000 supported characters.") + .require( + "color", + color != null && (color.isEmpty() || color.matches("#[a-fA-F0-9]{6}([a-fA-F0-9]{2})?")), + "Use #RRGGBB or #RRGGBBAA, or leave the colour empty.") + .finish(); + } + + 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/ReviewFormController.java b/src/main/java/org/busystack/caldav/management/ReviewFormController.java new file mode 100644 index 0000000..e4a60da --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/ReviewFormController.java @@ -0,0 +1,79 @@ +package org.busystack.caldav.management; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; +import jakarta.servlet.http.HttpServletResponse; +import java.util.Map; +import java.util.UUID; +import org.busystack.caldav.security.AuthenticationJourney; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; + +@Controller +public class ReviewFormController { + private static final String RECOVERED_PATH = ReviewFormController.class.getName() + ".path"; + private final AuthenticationJourney journey; + private final FormRecovery forms; + private final PortalPageAdvice pages; + private final DavConnectionAdvice connections; + + public ReviewFormController( + AuthenticationJourney journey, + FormRecovery forms, + PortalPageAdvice pages, + DavConnectionAdvice connections) { + this.journey = journey; + this.forms = forms; + this.pages = pages; + this.connections = connections; + } + + @GetMapping("/forms/{handle}") + String review( + Authentication auth, + HttpServletRequest request, + HttpServletResponse response, + @PathVariable UUID handle, + Model model) { + response.setHeader("Cache-Control", "no-store"); + var draft = journey.takeDraft(request, auth, handle.toString()); + if (draft == null) { + response.setStatus(410); + model.addAttribute("errorTitle", "This form is no longer available"); + model.addAttribute("message", "Open the task again to review the current details."); + model.addAttribute("retryPath", "/"); + return "portal-error"; + } + request.setAttribute(RECOVERED_PATH, draft.path()); + var original = + new HttpServletRequestWrapper(request) { + @Override + public String getServletPath() { + return draft.path(); + } + + @Override + public String getParameter(String name) { + return draft.fields().get(name); + } + }; + String view = forms.render(auth, original, model, Map.of()); + pages.layout(auth, original, model); + if ("credentials".equals(view)) + model.addAttribute("davConnection", connections.connection(auth)); + model.addAttribute( + "notice", + "Sign-in confirmed. Review your details, re-enter any required secret and submit again."); + model.addAttribute("noticeSeverity", "info"); + return view; + } + + static String route(HttpServletRequest request) { + return request.getAttribute(RECOVERED_PATH) instanceof String path + ? path + : request.getServletPath(); + } +} 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..0383089 --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/SharingManagementService.java @@ -0,0 +1,144 @@ +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.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 SharingManagementService { + record Removal(String collection, String target, String permission, String consequence) {} + + 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); + } + + Removal directRemoval(Authentication auth, UUID collection, String username) { + var resource = portal.owner(auth, collection); + var rows = + jdbc.query( + """ + SELECT a.username, m.permission, a.enabled, EXISTS ( + SELECT 1 FROM sharing_group_members u + JOIN collection_group_members g ON g.group_id=u.group_id + WHERE u.account_id=a.id AND g.collection_id=m.collection_id + ) + FROM collection_members m JOIN accounts a ON a.id=m.account_id + WHERE m.collection_id=? AND a.username=? + """, + (rs, row) -> + new Removal( + resource.name(), + rs.getString(1), + rs.getString(2), + !rs.getBoolean(3) + ? "This account is disabled. Any separate group grant remains in place." + : rs.getBoolean(4) + ? "The account will continue to have access through one or more group grants." + : "The account will lose access through sharing after this grant is removed."), + collection, + username); + if (rows.isEmpty()) throw new StoreException(StoreException.Kind.NOT_FOUND); + return rows.getFirst(); + } + + Removal groupRemoval(Authentication auth, UUID collection, UUID group) { + var resource = portal.owner(auth, collection); + var rows = + jdbc.query( + """ + SELECT g.name, grant_row.permission, + (SELECT count(*) FROM sharing_group_members m JOIN accounts a ON a.id=m.account_id + WHERE m.group_id=g.id AND a.enabled AND a.id<>? + AND NOT EXISTS (SELECT 1 FROM collection_members d + WHERE d.collection_id=grant_row.collection_id AND d.account_id=a.id) + AND NOT EXISTS (SELECT 1 FROM sharing_group_members m2 + JOIN collection_group_members g2 ON g2.group_id=m2.group_id + WHERE m2.account_id=a.id AND g2.collection_id=grant_row.collection_id + AND g2.group_id<>g.id)) + FROM collection_group_members grant_row JOIN sharing_groups g ON g.id=grant_row.group_id + WHERE grant_row.collection_id=? AND grant_row.group_id=? + """, + (rs, row) -> { + long affected = rs.getLong(3); + return new Removal( + resource.name(), + rs.getString(1), + rs.getString(2), + (affected == 0 + ? "Every enabled recipient keeps any access they have through other grants." + : (affected == 1 + ? "One enabled account will lose access. " + : affected + " enabled accounts will lose access. ") + + "Other direct and group grants will continue to apply.")); + }, + management.current(auth).id(), + collection, + group); + if (rows.isEmpty()) throw new StoreException(StoreException.Kind.NOT_FOUND); + return rows.getFirst(); + } +} diff --git a/src/main/java/org/busystack/caldav/management/SharingReviewController.java b/src/main/java/org/busystack/caldav/management/SharingReviewController.java new file mode 100644 index 0000000..7d7662e --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/SharingReviewController.java @@ -0,0 +1,136 @@ +package org.busystack.caldav.management; + +import java.util.UUID; +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.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.servlet.mvc.support.RedirectAttributes; + +@Controller +final class SharingReviewController { + private static final String ROUTE = + "/collections/{id}/sharing/{kind:account|group}/{target}/remove"; + private final SharingManagementService sharing; + + SharingReviewController(SharingManagementService sharing) { + this.sharing = sharing; + } + + @GetMapping(ROUTE) + String confirm( + Authentication auth, + @PathVariable UUID id, + @PathVariable String kind, + @PathVariable String target, + @RequestParam(defaultValue = "0") int directPage, + @RequestParam(defaultValue = "0") int groupPage, + @RequestParam(defaultValue = "0") int effectivePage, + Model model) { + return review( + sharing, auth, id, kind, target, directPage, groupPage, effectivePage, null, model); + } + + static String review( + SharingManagementService sharing, + Authentication auth, + UUID id, + String kind, + String target, + int directPage, + int groupPage, + int effectivePage, + String expected, + Model model) { + boolean group = kind.equals("group"); + var grant = + group + ? sharing.groupRemoval(auth, id, UUID.fromString(target)) + : sharing.directRemoval(auth, id, account(target)); + if (expected != null) PortalService.checkState(expected, grant.permission()); + String back = sharingPath(id, directPage, groupPage, effectivePage); + String path = removalPath(id, kind, target, directPage, groupPage, effectivePage); + model.addAttribute( + "actionTitle", + "Remove " + (group ? "group" : "direct") + " access for " + grant.target() + "?"); + model.addAttribute( + "consequence", + "This removes the " + + (grant.permission().equals("WRITE") ? "read and write" : "read-only") + + " grant to " + + grant.collection() + + ". " + + grant.consequence()); + model.addAttribute("actionLabel", group ? "Remove group grant" : "Remove direct grant"); + model.addAttribute("actionPath", path); + model.addAttribute("cancelPath", back); + model.addAttribute("expectedRevision", grant.permission()); + return "confirm-action"; + } + + @PostMapping(ROUTE) + String remove( + Authentication auth, + @PathVariable UUID id, + @PathVariable String kind, + @PathVariable String target, + @RequestParam(defaultValue = "0") int directPage, + @RequestParam(defaultValue = "0") int groupPage, + @RequestParam(defaultValue = "0") int effectivePage, + @RequestParam(defaultValue = "false") boolean confirmed, + @RequestParam(defaultValue = "") String expected, + RedirectAttributes flash) { + if (!confirmed) + return "redirect:" + removalPath(id, kind, target, directPage, groupPage, effectivePage); + if (!java.util.Set.of("READ", "WRITE").contains(expected)) + throw new StoreException(StoreException.Kind.PRECONDITION); + boolean group = kind.equals("group"); + if (group) sharing.group(auth, id, UUID.fromString(target), "REVOKE", expected); + else sharing.direct(auth, id, account(target), "REVOKE", expected); + flash.addFlashAttribute( + "notice", + (group ? "Group" : "Direct") + + " grant removed. Other grants continue to apply. Review effective permissions below."); + return "redirect:" + sharingPath(id, directPage, groupPage, effectivePage); + } + + private static String sharingPath(UUID id, int directPage, int groupPage, int effectivePage) { + return "/collections/" + id + "/sharing" + pages(directPage, groupPage, effectivePage); + } + + private static String removalPath( + UUID id, String kind, String target, int directPage, int groupPage, int effectivePage) { + String safeTarget = kind.equals("group") ? UUID.fromString(target).toString() : account(target); + return "/collections/" + + id + + "/sharing/" + + kind + + "/" + + safeTarget + + "/remove" + + pages(directPage, groupPage, effectivePage); + } + + private static String pages(int directPage, int groupPage, int effectivePage) { + PortalPage.offset(directPage); + PortalPage.offset(groupPage); + PortalPage.offset(effectivePage); + if (directPage == 0 && groupPage == 0 && effectivePage == 0) return ""; + return "?directPage=" + + directPage + + "&groupPage=" + + groupPage + + "&effectivePage=" + + effectivePage; + } + + private static String account(String username) { + if (!username.matches("[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}")) + throw new StoreException(StoreException.Kind.NOT_FOUND); + return username; + } +} diff --git a/src/main/java/org/busystack/caldav/management/UploadErrors.java b/src/main/java/org/busystack/caldav/management/UploadErrors.java new file mode 100644 index 0000000..98617cb --- /dev/null +++ b/src/main/java/org/busystack/caldav/management/UploadErrors.java @@ -0,0 +1,37 @@ +package org.busystack.caldav.management; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.security.core.Authentication; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.multipart.MaxUploadSizeExceededException; + +/** Multipart admission can fail before Spring resolves the portal controller. */ +@ControllerAdvice +@Order(Ordered.HIGHEST_PRECEDENCE) +public final class UploadErrors { + private final PortalPageAdvice pages; + + public UploadErrors(PortalPageAdvice pages) { + this.pages = pages; + } + + @ExceptionHandler(MaxUploadSizeExceededException.class) + String excessive( + MaxUploadSizeExceededException failure, + Authentication auth, + HttpServletRequest request, + HttpServletResponse response, + Model model) { + if (!request.getServletPath().equals("/portability/preview")) throw failure; + pages.layout(auth, request, model); + response.setStatus(413); + response.setHeader("Cache-Control", "no-store"); + // Render directly: an error dispatch would attempt multipart admission a second time. + return "error/413"; + } +} diff --git a/src/main/java/org/busystack/caldav/protocol/DavController.java b/src/main/java/org/busystack/caldav/protocol/DavController.java index 518a586..cf9dd2b 100644 --- a/src/main/java/org/busystack/caldav/protocol/DavController.java +++ b/src/main/java/org/busystack/caldav/protocol/DavController.java @@ -431,7 +431,8 @@ private ResponseEntity create( var components = children(value, CAL, "comp"); if (components.size() != 1 || !is(components.getFirst(), CAL, "comp") - || !Set.of("VEVENT", "VTODO").contains(components.getFirst().getAttribute("name"))) + || !CalendarContent.supportsCollectionComponent( + components.getFirst().getAttribute("name"))) throw new DavException(403, c("supported-calendar-component")); component = components.getFirst().getAttribute("name"); } else if (name.equals(d("displayname"))) { 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..085d122 --- /dev/null +++ b/src/main/java/org/busystack/caldav/security/AuthenticationJourney.java @@ -0,0 +1,434 @@ +package org.busystack.caldav.security; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.Serializable; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.UUID; +import org.busystack.caldav.config.DeploymentProperties; +import org.busystack.caldav.security.session.SessionSecurity; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Component; +import tools.jackson.databind.json.JsonMapper; + +/** + * Validated, single-use browser destinations retained across a legitimate authentication rotation. + */ +@Component +public class AuthenticationJourney { + private static final String SECTION = "journey"; + private static final String PROVIDER_FLOW = + AuthenticationJourney.class.getName() + ".providerFlow"; + private static final Duration LIFETIME = Duration.ofMinutes(15); + private static final int MAX_FLOWS = 8; + private static final int MAX_PATH_BYTES = 4096; + private final String prefix; + private final SessionSecurity sessions; + private final BrowserFlowStore store; + + private record FlowState( + LinkedHashMap flows, java.util.Map defaults) { + FlowState() { + this(new LinkedHashMap<>(), new java.util.HashMap<>()); + } + } + + private record Owner(UUID account, String username, UUID epoch) implements Serializable {} + + private record Flow( + String destination, + Owner owner, + Instant expires, + Draft draft, + boolean ready, + String retryUsername) + implements Serializable { + boolean belongsTo(Owner current) { + return owner == null || owner.equals(current); + } + + Flow bind(Owner current) { + return new Flow(destination, current, expires, draft, ready, null); + } + } + + public AuthenticationJourney( + DeploymentProperties deployment, SessionSecurity sessions, BrowserFlowStore store) { + prefix = deployment.publicBaseUrl().getPath(); + this.sessions = sessions; + this.store = store; + } + + private Owner owner(Authentication authentication) { + if (authentication == null + || !authentication.isAuthenticated() + || authentication + instanceof org.springframework.security.authentication.AnonymousAuthenticationToken) + return null; + if (sessions == null) + return new Owner( + null, + authentication.getName(), + SessionSecurity.capturedEpoch(authentication.getAuthorities())); + var account = sessions.assertCurrent(authentication); + return new Owner(account.id(), account.username(), account.epoch()); + } + + public String safe(String candidate) { + if (candidate == null + || !candidate.startsWith(prefix + "/") + || candidate.getBytes(StandardCharsets.UTF_8).length > MAX_PATH_BYTES + || candidate.codePoints().anyMatch(Character::isISOControl)) return prefix + "/"; + try { + URI uri = URI.create(candidate); + String path = uri.getRawPath(); + if (uri.isAbsolute() + || uri.getRawAuthority() != null + || uri.getRawFragment() != null + || path.contains("%") + || path.contains("\\") + || path.contains("//") + || path.contains(";") + || java.util.Arrays.stream(path.split("/")) + .anyMatch(part -> part.equals(".") || part.equals("..")) + || !uri.normalize().getRawPath().equals(path)) return prefix + "/"; + String local = path.substring(prefix.length()); + if (local.startsWith("/login") + || local.startsWith("/setup") + || local.equals("/auth") + || local.startsWith("/auth/") + || local.startsWith("/webauthn") + || local.startsWith("/logout")) return prefix + "/"; + String query = uri.getRawQuery(); + if (query == null) return path; + var allowed = + local.equals("/oauth/consent") + ? java.util.Set.of("client_id", "state") + : local.equals("/oauth2/authorize") + ? java.util.Set.of( + "response_type", + "client_id", + "redirect_uri", + "scope", + "state", + "code_challenge", + "code_challenge_method") + : java.util.Set.of( + "client", + "from", + "destination", + "scope", + "q", + "status", + "method", + "page", + "directPage", + "groupPage", + "effectivePage", + "component", + "action", + "outcome", + "username", + "returnCollection", + "member"); + var fields = + java.util.Arrays.stream(query.split("&")) + .filter(parameter -> allowedQuery(allowed, local, parameter)) + .toList(); + return fields.isEmpty() ? path : path + "?" + String.join("&", fields); + } catch (IllegalArgumentException invalid) { + return prefix + "/"; + } + } + + private static boolean allowedQuery( + java.util.Set allowed, String path, String parameter) { + String[] field = parameter.split("=", 2); + if (field.length != 2) return false; + if (field[0].equals("resource")) + return (path.equals("/connections") + || path.equals("/security/credentials") + || path.equals("/security/credentials/new")) + && validHandle(field[1]); + if (field[0].equals("returnCollection")) return validHandle(field[1]); + if (field[0].equals("memberQuery") || field[0].equals("memberPage")) + return path.startsWith("/admin/groups/"); + return allowed.contains(field[0]); + } + + public record Draft(String path, java.util.Map fields) implements Serializable { + public Draft { + fields = java.util.Map.copyOf(fields); + } + } + + public String start(HttpServletRequest request, String destination, Authentication auth) { + return start(request, destination, auth, null); + } + + public String start( + HttpServletRequest request, String destination, Authentication auth, Draft draft) { + return store.update( + request, + true, + SECTION, + FlowState.class, + FlowState::new, + state -> add(state, destination, owner(auth), draft)); + } + + private String add(FlowState state, String destination, Owner owner, Draft draft) { + var flows = flows(state); + String handle = UUID.randomUUID().toString(); + flows.put( + handle, + new Flow(safe(destination), owner, Instant.now().plus(LIFETIME), draft, false, null)); + while (flows.size() > MAX_FLOWS + || flows.values().stream().mapToInt(AuthenticationJourney::bytes).sum() > 32768) + flows.pollFirstEntry(); + return handle; + } + + private static int bytes(Flow flow) { + int size = + flow.destination().getBytes(StandardCharsets.UTF_8).length + + (flow.retryUsername() == null ? 0 : flow.retryUsername().length()); + if (flow.draft() != null) { + size += flow.draft().path().length(); + for (var field : flow.draft().fields().entrySet()) + size += field.getKey().length() + field.getValue().getBytes(StandardCharsets.UTF_8).length; + } + return size; + } + + public void remember(HttpServletRequest request, String destination) { + store.update( + request, + true, + SECTION, + FlowState.class, + FlowState::new, + state -> { + state.defaults().put("default", add(state, destination, null, null)); + return null; + }); + } + + private FlowState state(HttpServletRequest request) { + return store.read(request, SECTION, FlowState.class, FlowState::new); + } + + private static LinkedHashMap flows(FlowState state) { + state.flows().values().removeIf(flow -> !BrowserFlowStore.current(flow.expires())); + return state.flows(); + } + + public static boolean validHandle(String handle) { + return handle != null && handle.matches("[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}"); + } + + public void providerCallback(HttpServletRequest request, String handle) { + request.setAttribute(PROVIDER_FLOW, handle == null ? "" : handle); + } + + public String handle(HttpServletRequest request) { + String explicit = request.getParameter("flow"); + if (explicit != null) return validHandle(explicit) ? explicit : ""; + return state(request).defaults().getOrDefault("default", ""); + } + + public boolean available(HttpServletRequest request, Authentication auth, String handle) { + var flow = flows(state(request)).get(handle); + return flow != null && flow.belongsTo(owner(auth)); + } + + public String destination(HttpServletRequest request) { + var flow = flows(state(request)).get(handle(request)); + return flow != null && flow.owner() == null ? flow.destination() : prefix + "/"; + } + + public void loginRequired( + HttpServletRequest request, + HttpServletResponse response, + org.springframework.security.core.AuthenticationException ignored) + throws IOException { + if (!"GET".equals(request.getMethod()) + || "/".equals(request.getServletPath()) && request.getQueryString() == null) { + response.sendRedirect(prefix + "/login"); + return; + } + response.sendRedirect( + prefix + "/login?flow=" + start(request, BrowserAccessFilter.destination(request), null)); + } + + public void primaryFailure( + HttpServletRequest request, + HttpServletResponse response, + org.springframework.security.core.AuthenticationException ignored) + throws IOException { + String handle = requestedHandle(request); + var flow = flows(state(request)).get(handle); + String target = prefix + "/login?error"; + if (flow != null) { + target += (flow.owner() == null ? "" : "&reauthenticate") + "&flow=" + handle; + String username = request.getParameter("username"); + if (flow.owner() == null + && "/login".equals(request.getServletPath()) + && username != null + && username.matches("[A-Za-z0-9][A-Za-z0-9._-]{0,63}")) { + store.update( + request, + false, + SECTION, + FlowState.class, + FlowState::new, + state -> { + state + .flows() + .computeIfPresent( + handle, + (key, current) -> + current.owner() == null + ? new Flow( + current.destination(), + null, + current.expires(), + current.draft(), + current.ready(), + username) + : current); + return null; + }); + } + } else if (!handle.isEmpty() + || request.getParameter("flow") != null && !request.getParameter("flow").isEmpty()) { + target += "&interrupted"; + } + response.setHeader("Cache-Control", "no-store"); + response.sendRedirect(target); + } + + public String retryUsername( + HttpServletRequest request, Authentication authentication, String handle) { + var flow = flows(state(request)).get(handle); + return flow != null && flow.belongsTo(owner(authentication)) ? flow.retryUsername() : null; + } + + private String requestedHandle(HttpServletRequest request) { + return request.getAttribute(PROVIDER_FLOW) instanceof String handle ? handle : handle(request); + } + + public String action(HttpServletRequest request, Authentication auth, String handle) { + var flow = flows(state(request)).get(handle); + if (flow == null || flow.owner() == null || !flow.belongsTo(owner(auth))) return null; + String path = + flow.draft() == null + ? URI.create(flow.destination()).getPath().substring(prefix.length()) + : flow.draft().path(); + if (path.startsWith("/credentials")) + return path.endsWith("/revoke") + ? "revoke the application password" + : "create an application password"; + if (path.startsWith("/portability")) + return path.endsWith("/export") ? "export your data" : "continue your import"; + if (path.startsWith("/admin")) return "continue this administrator task"; + if (path.startsWith("/security/passkeys")) return "manage your passkeys"; + if (path.startsWith("/security/recovery")) return "manage recovery codes"; + if (path.startsWith("/oauth")) return "authorize or manage application access"; + if (path.startsWith("/shares") || path.startsWith("/group-shares")) return "change sharing"; + return "continue your task"; + } + + public String consume(HttpServletRequest request, Authentication auth, String handle) { + if (!validHandle(handle)) return prefix + "/"; + Owner current = owner(auth); + return store.update( + request, + false, + SECTION, + FlowState.class, + FlowState::new, + state -> { + var flows = flows(state); + var flow = flows.get(handle); + if (flow == null || !flow.belongsTo(current) || flow.ready()) + return prefix + "/?interrupted"; + state.defaults().remove("default", handle); + if (flow.draft() == null) { + flows.remove(handle); + return flow.destination(); + } + flows.put( + handle, + new Flow(flow.destination(), current, flow.expires(), flow.draft(), true, null)); + return prefix + "/forms/" + handle; + }); + } + + public Draft takeDraft(HttpServletRequest request, Authentication auth, String handle) { + if (!validHandle(handle)) return null; + Owner current = owner(auth); + return store.update( + request, + false, + SECTION, + FlowState.class, + FlowState::new, + state -> { + var flows = flows(state); + var flow = flows.get(handle); + if (flow == null || !flow.ready() || !flow.belongsTo(current)) return null; + flows.remove(handle); + return flow.draft(); + }); + } + + public void primarySuccess( + HttpServletRequest request, HttpServletResponse response, Authentication auth) + throws IOException { + String handle = requestedHandle(request); + String target = prefix + "/auth/continue"; + if (validHandle(handle)) { + Owner current = owner(auth); + target = + store.update( + request, + false, + SECTION, + FlowState.class, + FlowState::new, + state -> { + var flows = flows(state); + var flow = flows.get(handle); + if (flow == null || !flow.belongsTo(current) || flow.ready()) + return prefix + "/auth/continue?interrupted"; + if (flow.destination().equals(prefix + "/security/recovery/use")) { + flows.remove(handle); + state.defaults().remove("default", handle); + return flow.destination(); + } + flows.put(handle, flow.bind(current)); + return prefix + "/auth/continue?flow=" + handle; + }); + } + response.sendRedirect(target); + } + + public void passkeySuccess( + HttpServletRequest request, HttpServletResponse response, Authentication auth) + throws IOException { + String handle = handle(request); + response.setHeader("Cache-Control", "no-store"); + response.setContentType("application/json"); + // The GET consumes the flow after the updated session cookie has reached the browser. + JsonMapper.shared() + .writeValue( + response.getWriter(), + java.util.Map.of("redirectUrl", prefix + "/auth/continue?flow=" + handle)); + } +} diff --git a/src/main/java/org/busystack/caldav/security/BrowserAccessFilter.java b/src/main/java/org/busystack/caldav/security/BrowserAccessFilter.java new file mode 100644 index 0000000..340f1a1 --- /dev/null +++ b/src/main/java/org/busystack/caldav/security/BrowserAccessFilter.java @@ -0,0 +1,139 @@ +package org.busystack.caldav.security; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Set; +import org.busystack.caldav.security.session.BrowserSession; +import org.springframework.security.authentication.AnonymousAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.OncePerRequestFilter; + +/** Browser admission, independently from service-level target authorization. */ +public final class BrowserAccessFilter extends OncePerRequestFilter { + private static final Set SIGN_IN_PATHS = + Set.of( + "/login", + "/logout", + "/auth/continue", + "/auth/state", + "/login/webauthn", + "/webauthn/authenticate/options", + "/webauthn/register/options", + "/webauthn/register", + "/security/recovery/use"); + private static final Set PUBLIC_PATHS = + Set.of( + "/setup", + "/setup/administrator", + "/help/setup", + "/.well-known/caldav", + "/error", + "/actuator/health", + "/actuator/health/liveness", + "/actuator/health/readiness"); + + private enum Admission { + OPEN, + COMPLETED, + FRESH + } + + private final BrowserSession sessions; + private final AuthenticationJourney journey; + + public BrowserAccessFilter(BrowserSession sessions, AuthenticationJourney journey) { + this.sessions = sessions; + this.journey = journey; + } + + @Override + protected void doFilterInternal( + HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + String path = request.getServletPath(); + if (PUBLIC_PATHS.contains(path) || path.startsWith("/assets/")) { + chain.doFilter(request, response); + return; + } + var auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth == null || !auth.isAuthenticated() || auth instanceof AnonymousAuthenticationToken) { + chain.doFilter(request, response); + return; + } + var state = sessions.state(request, auth); + if (state == BrowserSession.State.EXPIRED) { + SecurityContextHolder.clearContext(); + request.getSession(false).invalidate(); + response.setHeader("Cache-Control", "no-store"); + if ("GET".equals(request.getMethod())) { + String flow = journey.start(request, destination(request), null); + response.sendRedirect(request.getContextPath() + "/login?session&flow=" + flow); + } else { + response.setHeader("X-BusyStack-Auth-State", "session-ended"); + response.sendError(403, "Your browser session ended. Sign in again."); + } + return; + } + boolean completed = state == BrowserSession.State.CURRENT; + request.setAttribute(BrowserSession.CURRENT, completed); + Admission admission = admission(request, path); + if (admission == Admission.OPEN + || completed + && (admission == Admission.COMPLETED || RecentAuthentication.mfaCurrent(auth))) { + chain.doFilter(request, response); + return; + } + response.setHeader("Cache-Control", "no-store"); + response.setHeader( + "X-BusyStack-Auth-State", + RecentAuthentication.primaryCurrent(auth) ? "verification-required" : "primary-required"); + if ("GET".equals(request.getMethod())) { + String flow = journey.start(request, destination(request), auth); + response.sendRedirect(request.getContextPath() + "/auth/continue?flow=" + flow); + } else if (completed && navigate(request) && "POST".equals(request.getMethod())) { + var draft = BrowserFormDrafts.capture(request); + String target = BrowserFormDrafts.returnPath(request); + if (draft != null || target != null) { + String flow = + journey.start( + request, request.getContextPath() + (target == null ? "/" : target), auth, draft); + response.setStatus(HttpServletResponse.SC_SEE_OTHER); + response.setHeader("Location", request.getContextPath() + "/auth/continue?flow=" + flow); + } else response.sendError(403, "Confirm your sign-in, then return to review this action."); + } else { + response.sendError(403, "Confirm your sign-in, then return to review this action."); + } + } + + private static Admission admission(HttpServletRequest request, String path) { + if (SIGN_IN_PATHS.contains(path) + || path.startsWith("/oauth2/authorization/") + || path.startsWith("/login/oauth2/code/")) return Admission.OPEN; + boolean read = "GET".equals(request.getMethod()) || "HEAD".equals(request.getMethod()); + if (path.equals("/session/stay") || path.equals("/welcome")) return Admission.COMPLETED; + if (!read + || path.startsWith("/portability/import/") + || path.startsWith("/forms/") + || path.endsWith("/export") + || path.equals("/oauth/consent") + || path.equals("/security/identities/link") + || path.equals("/portability/verify") + || path.equals("/security/passkeys/add") + || path.startsWith("/security/passkeys/remove/")) return Admission.FRESH; + return Admission.COMPLETED; + } + + private static boolean navigate(HttpServletRequest request) { + String accept = request.getHeader("Accept"); + return "navigate".equals(request.getHeader("Sec-Fetch-Mode")) + || accept != null && accept.contains("text/html"); + } + + public static String destination(HttpServletRequest request) { + String query = request.getQueryString(); + return request.getRequestURI() + (query == null ? "" : "?" + query); + } +} diff --git a/src/main/java/org/busystack/caldav/security/BrowserFlowStore.java b/src/main/java/org/busystack/caldav/security/BrowserFlowStore.java new file mode 100644 index 0000000..4ce26d1 --- /dev/null +++ b/src/main/java/org/busystack/caldav/security/BrowserFlowStore.java @@ -0,0 +1,109 @@ +package org.busystack.caldav.security; + +import jakarta.servlet.http.HttpServletRequest; +import java.time.Instant; +import java.util.function.Function; +import java.util.function.Supplier; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Component; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.json.JsonMapper; + +/** Serializes navigation updates across JDBC-session wrappers and across application nodes. */ +@Component +public class BrowserFlowStore { + private static final String SCOPE = "SPRING_SECURITY_BUSYSTACK_NAVIGATION_SCOPE"; + private final JdbcTemplate jdbc; + private final TransactionTemplate transactions; + + public BrowserFlowStore(JdbcTemplate jdbc, PlatformTransactionManager transactions) { + this.jdbc = jdbc; + this.transactions = new TransactionTemplate(transactions); + } + + public T read(HttpServletRequest request, String section, Class type, Supplier empty) { + String scope = scope(request, false); + return scope == null ? empty.get() : read(scope, section, type, empty); + } + + public R update( + HttpServletRequest request, + boolean create, + String section, + Class type, + Supplier empty, + Function change) { + String scope = scope(request, create); + if (scope == null) return change.apply(empty.get()); + return transactions.execute( + status -> { + jdbc.query( + "SELECT pg_advisory_xact_lock(hashtextextended(?,0))", + rs -> {}, + "busystack browser flow:" + section + ":" + scope); + T value = read(scope, section, type, empty); + R answer = change.apply(value); + jdbc.update( + """ + INSERT INTO browser_flow_state(scope,section,payload,expires_at) + VALUES (?,?,?,now()+interval '15 minutes') + ON CONFLICT (scope,section) DO UPDATE + SET payload=excluded.payload,expires_at=excluded.expires_at + """, + scope, + section, + JsonMapper.shared().writeValueAsString(value)); + return answer; + }); + } + + @org.springframework.scheduling.annotation.Scheduled(fixedDelay = 30000) + void expire() { + jdbc.update( + """ + DELETE FROM browser_flow_state + WHERE (scope, section) IN ( + SELECT scope, section FROM browser_flow_state WHERE expires_at<=now() + ORDER BY expires_at LIMIT 2048 FOR UPDATE SKIP LOCKED + ) + """); + } + + private T read(String scope, String section, Class type, Supplier empty) { + return jdbc.query( + """ + SELECT payload FROM browser_flow_state + WHERE scope=? AND section=? AND expires_at>now() + """, + rs -> rs.next() ? JsonMapper.shared().readValue(rs.getString(1), type) : empty.get(), + scope, + section); + } + + static String scope(HttpServletRequest request, boolean create) { + var session = request.getSession(create); + if (session == null) return null; + if (session.getAttribute(SCOPE) instanceof String scope) return scope; + // Concurrent first requests from an existing session derive the same scope. + // Spring's newSession fixation strategy migrates Spring Security's attributes. + String scope = fingerprint(session.getId()); + if (create) session.setAttribute(SCOPE, scope); + return scope; + } + + public static boolean current(Instant expires) { + return expires.isAfter(Instant.now()); + } + + public static String fingerprint(String value) { + try { + return java.util.HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(java.nio.charset.StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } +} diff --git a/src/main/java/org/busystack/caldav/security/BrowserFormDrafts.java b/src/main/java/org/busystack/caldav/security/BrowserFormDrafts.java new file mode 100644 index 0000000..603fe3a --- /dev/null +++ b/src/main/java/org/busystack/caldav/security/BrowserFormDrafts.java @@ -0,0 +1,86 @@ +package org.busystack.caldav.security; + +import jakarta.servlet.http.HttpServletRequest; +import java.util.LinkedHashMap; +import java.util.List; + +/** Allowlist by form route. In particular, multipart bodies and credential fields are excluded. */ +final class BrowserFormDrafts { + private static final String ID = "[a-f0-9-]{36}"; + + private BrowserFormDrafts() {} + + static AuthenticationJourney.Draft capture(HttpServletRequest request) { + String path = request.getServletPath(); + List fields; + if (path.equals("/collections")) fields = List.of("name", "component", "description", "color"); + else if (path.matches("/collections/" + ID + "/edit")) + fields = List.of("state", "name", "description", "color"); + else if (path.equals("/admin/accounts")) fields = List.of("username", "displayName"); + else if (path.matches("/admin/accounts/" + ID + "/edit")) + fields = List.of("expected", "displayName"); + else if (path.equals("/admin/groups")) fields = List.of("name", "returnCollection"); + else if (path.matches("/admin/groups/" + ID)) fields = List.of("name", "expected"); + else if (path.matches("/admin/groups/" + ID + "/members")) + fields = List.of("username", "memberPage", "memberQuery", "expectedGrants"); + else if (path.matches("/admin/groups/" + ID + "/members/" + ID + "/remove")) + fields = List.of("expectedGrants", "q", "page", "memberQuery", "memberPage"); + else if (path.equals("/admin/oauth-clients")) fields = List.of("clientId", "name", "redirects"); + else if (path.matches("/collections/" + ID + "/sharing/(account|group)/[^/]+/remove")) + fields = List.of("expected", "directPage", "groupPage", "effectivePage"); + else if (path.equals("/shares")) + fields = + List.of( + "collection", + "username", + "permission", + "expected", + "directPage", + "groupPage", + "effectivePage"); + else if (path.equals("/group-shares")) + fields = + List.of( + "collection", + "group", + "permission", + "expected", + "directPage", + "groupPage", + "effectivePage"); + else if (path.equals("/credentials")) + fields = List.of("label", "days", "client", "from", "intent", "resource"); + else return null; + + var values = new LinkedHashMap(); + for (String name : fields) { + String value = request.getParameter(name); + if (value != null && value.length() <= 8000) values.put(name, value); + } + return new AuthenticationJourney.Draft(path, values); + } + + static String returnPath(HttpServletRequest request) { + String path = request.getServletPath(); + if (path.equals("/portability/preview")) { + String query = request.getQueryString(); + if (query != null && query.matches("uploadTarget=" + ID)) + return "/portability?destination=" + query.substring("uploadTarget=".length()); + return "/portability"; + } + if (path.endsWith("/cancel") && path.startsWith("/portability/import/")) + return path.substring(0, path.length() - "/cancel".length()); + if (path.equals("/security/recovery/codes")) return "/security/recovery/codes/new"; + if (path.matches("/credentials/" + ID + "/revoke")) return path; + if (path.equals("/security/identities/link")) return "/security"; + if (path.matches("/admin/accounts/" + ID + "/disable")) return path; + if (path.matches("/admin/oauth-clients/[^/]+/remove")) return path; + if (path.equals("/admin/oauth-clients") + || path.equals("/security/password") + || path.endsWith("/delete") + || path.startsWith("/portability/import/")) return path; + if (path.startsWith("/security/sessions/")) return path; + if (path.startsWith("/oauth-grants/")) return path; + return null; + } +} diff --git a/src/main/java/org/busystack/caldav/security/IssuanceIntents.java b/src/main/java/org/busystack/caldav/security/IssuanceIntents.java new file mode 100644 index 0000000..7a3538f --- /dev/null +++ b/src/main/java/org/busystack/caldav/security/IssuanceIntents.java @@ -0,0 +1,139 @@ +package org.busystack.caldav.security; + +import java.util.UUID; +import org.busystack.caldav.security.session.SessionSecurity; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** A receipt and its credential mutation share one database transaction. */ +@Service +public class IssuanceIntents { + public enum Purpose { + APPLICATION_PASSWORD, + RECOVERY_CODES + } + + public record Intent(UUID id, UUID expectedGeneration) {} + + public record Claim(UUID id, boolean consumed, UUID result, UUID expectedGeneration) {} + + public static final class Unavailable extends RuntimeException { + private final boolean busy; + + Unavailable(boolean busy, String message) { + super(message); + this.busy = busy; + } + + public boolean busy() { + return busy; + } + } + + private final JdbcTemplate jdbc; + private final SessionSecurity sessions; + + public IssuanceIntents(JdbcTemplate jdbc, SessionSecurity sessions) { + this.jdbc = jdbc; + this.sessions = sessions; + } + + @Transactional + public Intent prepare(Authentication auth, Purpose purpose, String context) { + var account = sessions.assertForReset(auth); + jdbc.query("SELECT pg_advisory_xact_lock(912714321018)", rs -> {}); + jdbc.update("DELETE FROM browser_issuance_intents WHERE expires_at <= clock_timestamp()"); + jdbc.update( + "DELETE FROM browser_issuance_intents WHERE account_id=? AND security_epoch<>?", + account.id(), + account.epoch()); + if (count("SELECT count(*) FROM browser_issuance_intents") >= 8192 + || count( + "SELECT count(*) FROM browser_issuance_intents WHERE account_id=? AND consumed_at IS NULL", + account.id()) + >= 8) + throw new Unavailable( + true, "Issuance is busy. Use a form you already opened or try again after it expires."); + UUID id = UUID.randomUUID(); + UUID generation = purpose == Purpose.RECOVERY_CODES ? recoveryGeneration(account.id()) : null; + jdbc.update( + """ + INSERT INTO browser_issuance_intents(id,account_id,security_epoch,purpose,context,expected_generation,expires_at) + VALUES (?,?,?,?,?,?,clock_timestamp() + interval '15 minutes') + """, + id, + account.id(), + account.epoch(), + purpose.name(), + context, + generation); + return new Intent(id, generation); + } + + public Claim claim(SessionSecurity.Account account, UUID id, Purpose purpose, String context) { + requireTransaction(); + if (id == null) throw expired(); + var rows = + jdbc.query( + """ + SELECT id,consumed_at,result_id,expected_generation FROM browser_issuance_intents + WHERE id=? AND account_id=? AND security_epoch=? AND purpose=? AND context=? + AND expires_at > clock_timestamp() + FOR UPDATE + """, + (rs, row) -> + new Claim( + rs.getObject(1, UUID.class), + rs.getTimestamp(2) != null, + rs.getObject(3, UUID.class), + rs.getObject(4, UUID.class)), + id, + account.id(), + account.epoch(), + purpose.name(), + context); + if (rows.isEmpty()) throw expired(); + return rows.getFirst(); + } + + public void consume(Claim claim, UUID result) { + requireTransaction(); + if (jdbc.update( + """ + UPDATE browser_issuance_intents SET consumed_at=clock_timestamp(),result_id=? + WHERE id=? AND consumed_at IS NULL + """, + result, + claim.id()) + != 1) throw new IllegalStateException("Issuance claim lost"); + } + + public UUID recoveryGeneration(UUID account) { + return jdbc.queryForObject( + "SELECT recovery_code_generation FROM accounts WHERE id=?", UUID.class, account); + } + + public static Unavailable expired() { + return new Unavailable( + false, + "This issuance request is no longer available. Review your existing settings before starting again."); + } + + public static Unavailable changed() { + return new Unavailable( + false, + "A different set of recovery codes was generated. Review the current set before confirming a replacement."); + } + + private long count(String sql, Object... values) { + return java.util.Objects.requireNonNull(jdbc.queryForObject(sql, Long.class, values)); + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) + throw new IllegalStateException("Issuance intent requires a credential transaction"); + } +} diff --git a/src/main/java/org/busystack/caldav/security/IssuancePages.java b/src/main/java/org/busystack/caldav/security/IssuancePages.java new file mode 100644 index 0000000..a4a1d84 --- /dev/null +++ b/src/main/java/org/busystack/caldav/security/IssuancePages.java @@ -0,0 +1,29 @@ +package org.busystack.caldav.security; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +@ControllerAdvice +public class IssuancePages { + @ExceptionHandler(IssuanceIntents.Unavailable.class) + String unavailable( + IssuanceIntents.Unavailable failure, + HttpServletRequest request, + HttpServletResponse response, + Model model) { + response.setStatus(failure.busy() ? 503 : 409); + protect(response); + model.addAttribute("issuanceMessage", failure.getMessage()); + model.addAttribute( + "recoveryIssuance", request.getServletPath().startsWith("/security/recovery")); + return "issuance-receipt"; + } + + public 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/security/RecentAuthentication.java b/src/main/java/org/busystack/caldav/security/RecentAuthentication.java index f323d99..0cbcfd6 100644 --- a/src/main/java/org/busystack/caldav/security/RecentAuthentication.java +++ b/src/main/java/org/busystack/caldav/security/RecentAuthentication.java @@ -12,30 +12,55 @@ 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)) + if (!has(authentication, FactorGrantedAuthority.PASSWORD_AUTHORITY, Instant.now())) throw new AccessDeniedException("Recent password authentication is required"); } public static void requireMfa(Authentication authentication) { - requirePrimary(authentication); - if (!has(authentication, FactorGrantedAuthority.WEBAUTHN_AUTHORITY)) - throw new AccessDeniedException("Recent password and passkey authentication are required"); + requireMfa(authentication, Instant.now()); + } + + static void requireMfa(Authentication authentication, Instant now) { + requirePrimary(authentication, now); + if (!has(authentication, FactorGrantedAuthority.WEBAUTHN_AUTHORITY, now)) + throw new AccessDeniedException("Recent password and passkey authentication is required"); } public static void requirePrimary(Authentication authentication) { + requirePrimary(authentication, Instant.now()); + } + + private static void requirePrimary(Authentication authentication, Instant now) { boolean upstream = - has(authentication, FactorGrantedAuthority.AUTHORIZATION_CODE_AUTHORITY) + has(authentication, FactorGrantedAuthority.AUTHORIZATION_CODE_AUTHORITY, now) && authentication.getAuthorities().stream() .anyMatch( authority -> "BUSYSTACK_TRUSTED_UPSTREAM".equals(authority.getAuthority())); - if (!has(authentication, FactorGrantedAuthority.PASSWORD_AUTHORITY) && !upstream) + if (!has(authentication, FactorGrantedAuthority.PASSWORD_AUTHORITY, now) && !upstream) throw new AccessDeniedException("Recent primary authentication is required"); } - private static boolean has(Authentication authentication, String authority) { + private static boolean has(Authentication authentication, String authority, Instant now) { if (authentication == null || !authentication.isAuthenticated()) return false; - Instant now = Instant.now(); return authentication.getAuthorities().stream() .anyMatch( granted -> diff --git a/src/main/java/org/busystack/caldav/security/SecurityConfiguration.java b/src/main/java/org/busystack/caldav/security/SecurityConfiguration.java index 83a2d00..db4e0b0 100644 --- a/src/main/java/org/busystack/caldav/security/SecurityConfiguration.java +++ b/src/main/java/org/busystack/caldav/security/SecurityConfiguration.java @@ -145,6 +145,11 @@ 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, + BrowserFlowStore flows, + org.busystack.caldav.security.oidc.OidcConfiguration oidc, + org.busystack.caldav.security.session.BrowserSession browserSessions, + org.busystack.caldav.account.InitializationService initialization, org.springframework.beans.factory.ObjectProvider< org.busystack.caldav.security.oidc.OidcLoginSupport> upstreamUsers, @@ -154,10 +159,14 @@ SecurityFilterChain browserSecurity( throws Exception { http.authorizeHttpRequests( auth -> - auth.requestMatchers( + auth.requestMatchers(org.springframework.http.HttpMethod.GET, "/help/setup") + .permitAll() + .requestMatchers( "/.well-known/caldav", "/assets/**", "/login", + "/setup", + "/setup/administrator", "/login/webauthn", "/oauth2/authorization/**", "/login/oauth2/code/**", @@ -171,7 +180,16 @@ SecurityFilterChain browserSecurity( .hasRole("ADMIN") .anyRequest() .authenticated()) - .formLogin(login -> login.loginPage("/login").permitAll()) + .requestCache(cache -> cache.disable()) + .exceptionHandling( + exceptions -> exceptions.authenticationEntryPoint(journey::loginRequired)) + .formLogin( + login -> + login + .loginPage("/login") + .successHandler(journey::primarySuccess) + .failureHandler(journey::primaryFailure) + .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")) @@ -182,6 +200,9 @@ SecurityFilterChain browserSecurity( csp -> csp.policyDirectives( "default-src 'self'; frame-ancestors 'none'; object-src 'none'; base-uri 'none'"))); + http.addFilterBefore( + new org.busystack.caldav.account.InitializationGateFilter(initialization), + org.springframework.security.web.authentication.logout.LogoutFilter.class); http.addFilterBefore( new ActiveAccountFilter(accounts), org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.class); @@ -191,15 +212,17 @@ SecurityFilterChain browserSecurity( http.addFilterBefore( new org.busystack.caldav.security.throttle.LoginThrottleFilter(throttle), org.springframework.security.web.authentication.logout.LogoutFilter.class); + http.addFilterAfter( + new BrowserAccessFilter(browserSessions, journey), + org.springframework.security.web.access.intercept.AuthorizationFilter.class); http.setSharedObject( 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, browserSessions); var upstream = upstreamUsers.getIfAvailable(); if (upstream != null) - org.busystack.caldav.security.oidc.OidcConfiguration.configure( - http, upstreamRegistrations.getObject(), upstream); + oidc.configure(http, upstreamRegistrations.getObject(), upstream, flows, journey); return http.build(); } } 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..1c84e50 100644 --- a/src/main/java/org/busystack/caldav/security/audit/SecurityAudit.java +++ b/src/main/java/org/busystack/caldav/security/audit/SecurityAudit.java @@ -10,24 +10,60 @@ @Service public class SecurityAudit { public enum Action { - PASSWORD_LOGIN, - PASSWORD_CHANGED, - ACCOUNT_DISABLED, - OFFLINE_RECOVERY, - PASSKEY_LOGIN, - SESSION_REVOKED, - RECOVERY_CODES_ISSUED, - RECOVERY_USED, - GROUP_CREATED, - GROUP_UPDATED, - GROUP_DELETED, - GROUP_SHARING_CHANGED + DATABASE_RESTORE("Database restored"), + PASSWORD_LOGIN("Password sign-in"), + PASSWORD_CHANGED("Password changed"), + ACCOUNT_DISABLED("Account disabled"), + OFFLINE_RECOVERY("Offline account recovery"), + PASSKEY_LOGIN("Passkey verification"), + SESSION_REVOKED("Browser session ended"), + APPLICATION_PASSWORD_ISSUED("Application password created"), + RECOVERY_CODES_ISSUED("Recovery codes generated"), + RECOVERY_USED("Recovery code used"), + GROUP_CREATED("Group created"), + GROUP_UPDATED("Group updated"), + GROUP_MEMBER_ADDED("Group member added"), + GROUP_MEMBER_REMOVED("Group member removed"), + GROUP_DELETED("Group deleted"), + GROUP_SHARING_CHANGED("Group share changed"), + COLLECTION_CREATED("Resource created"), + COLLECTION_UPDATED("Resource settings updated"), + COLLECTION_DELETED("Resource deleted"), + COLLECTION_IMPORTED("Resource import"), + INDIVIDUAL_SHARING_CHANGED("Direct share changed"), + ACCOUNT_CREATED("Account created"), + ACCOUNT_PROFILE_UPDATED("Account profile updated"); + + private final String label; + + Action(String label) { + this.label = label; + } + + public String label() { + return label; + } } public enum Outcome { - SUCCESS, - FAILURE, - THROTTLED + SUCCESS("Succeeded"), + FAILURE("Failed"), + THROTTLED("Rate limited"); + + private final String label; + + Outcome(String label) { + this.label = label; + } + + public String label() { + return label; + } + } + + public enum TargetType { + ACCOUNT, + GROUP } private final JdbcTemplate jdbc; @@ -38,16 +74,77 @@ public SecurityAudit(JdbcTemplate jdbc) { @Transactional public void record(UUID account, Action action, Outcome outcome, String peer) { + write(account, action, outcome, peer, null, null, null); + } + + @Transactional + public void targeted( + UUID actor, + Action action, + Outcome outcome, + TargetType type, + UUID target, + UUID relatedAccount) { + java.util.Objects.requireNonNull(type); + java.util.Objects.requireNonNull(target); + if (type != TargetType.GROUP && relatedAccount != null) + throw new IllegalArgumentException("Membership context requires a group"); + write(actor, action, outcome, null, type, target, relatedAccount); + } + + /** Bounded administrative membership replacement; one pruning pass for the complete delta. */ + @Transactional + public void membershipDelta( + UUID actor, UUID group, java.util.Set before, java.util.Set after) { + if (before.size() > 1000 || after.size() > 1000) + throw new IllegalArgumentException("Membership audit limit"); + var rows = new java.util.ArrayList(); + for (UUID member : before.stream().sorted().toList()) { + if (!after.contains(member)) + rows.add( + new Object[] { + actor, Action.GROUP_MEMBER_REMOVED.name(), Outcome.SUCCESS.name(), group, member + }); + } + for (UUID member : after.stream().sorted().toList()) { + if (!before.contains(member)) + rows.add( + new Object[] { + actor, Action.GROUP_MEMBER_ADDED.name(), Outcome.SUCCESS.name(), group, member + }); + } + if (rows.isEmpty()) return; + jdbc.batchUpdate( + "INSERT INTO security_audit(account_id,action,outcome,target_type,target_id,related_account_id) VALUES (?,?,?,'GROUP',?,?)", + rows); + pruneCount(); + } + + private void write( + UUID account, + Action action, + Outcome outcome, + String peer, + TargetType type, + UUID target, + UUID relatedAccount) { String peerHash = peer == null ? null : SecurityHashes.sha256(peer.length() > 128 ? peer.substring(0, 128) : peer); jdbc.update( - "INSERT INTO security_audit(account_id,action,outcome,peer_hash) VALUES (?,?,?,?)", + "INSERT INTO security_audit(account_id,action,outcome,peer_hash,target_type,target_id,related_account_id) VALUES (?,?,?,?,?,?,?)", account, action.name(), outcome.name(), - peerHash); + peerHash, + type == null ? null : type.name(), + target, + relatedAccount); + pruneCount(); + } + + private void pruneCount() { jdbc.update( "DELETE FROM security_audit WHERE id <= (SELECT id FROM security_audit ORDER BY id DESC OFFSET 9999 LIMIT 1)"); } diff --git a/src/main/java/org/busystack/caldav/security/oauth/OAuthClientService.java b/src/main/java/org/busystack/caldav/security/oauth/OAuthClientService.java index 64917aa..69775bd 100644 --- a/src/main/java/org/busystack/caldav/security/oauth/OAuthClientService.java +++ b/src/main/java/org/busystack/caldav/security/oauth/OAuthClientService.java @@ -25,6 +25,8 @@ public class OAuthClientService { public record Client(String id, String name, String redirects) {} + record Registration(String id, String name, String revision) {} + private final RegisteredClientRepository clients; private final AccountService accounts; private final JdbcTemplate jdbc; @@ -63,6 +65,26 @@ public void remove(Authentication authentication, String clientId) { remove(actor(authentication), clientId); } + Registration registration(Authentication auth, String id) { + requireAdministrator(actor(auth)); + var client = clients.findByClientId(id); + if (client == null) + throw new org.busystack.caldav.storage.StoreException( + org.busystack.caldav.storage.StoreException.Kind.NOT_FOUND); + return new Registration(client.getClientId(), client.getClientName(), client.getId()); + } + + @Transactional + public void remove(Authentication auth, String clientId, String expected) { + RecentAuthentication.requireMfa(auth); + clientLocks.lock(clientId); + var current = registration(auth, clientId); + if (!current.revision().equals(expected)) + throw new org.busystack.caldav.storage.StoreException( + org.busystack.caldav.storage.StoreException.Kind.PRECONDITION); + remove(actor(auth), clientId); + } + List list(UUID administrator) { requireAdministrator(administrator); return jdbc.query( @@ -74,19 +96,30 @@ List list(UUID administrator) { void registerNative(UUID administrator, String clientId, String name, Set redirects) { clientLocks.lock(clientId); requireAdministrator(administrator); - if (clientId == null - || !clientId.matches("[A-Za-z0-9._-]{1,100}") - || name == null + if (clientId == null || !clientId.matches("[A-Za-z0-9._-]{1,100}")) + throw org.busystack.caldav.management.FormValidation.field( + "clientId", "Enter 1–100 letters, digits, dots, underscores or hyphens."); + if (name == null || name.isBlank() || name.length() > 100 - || redirects == null + || name.codePoints().anyMatch(Character::isISOControl)) + throw org.busystack.caldav.management.FormValidation.field( + "name", "Enter a name of 1–100 characters without control characters."); + if (redirects == null || redirects.isEmpty() || redirects.size() > 5 || redirects.stream().mapToInt(String::length).sum() > 950) - throw new IllegalArgumentException("Invalid OAuth client registration"); - redirects.forEach(OAuthClientService::validateRedirect); + throw org.busystack.caldav.management.FormValidation.field( + "redirects", "Enter 1–5 redirect addresses, within 950 characters in total."); + try { + redirects.forEach(OAuthClientService::validateRedirect); + } catch (IllegalArgumentException invalid) { + throw org.busystack.caldav.management.FormValidation.field( + "redirects", "Enter redirect addresses in one of the supported formats."); + } if (clients.findByClientId(clientId) != null) - throw new IllegalArgumentException("OAuth client already exists"); + throw org.busystack.caldav.management.FormValidation.conflict( + "clientId", "This client ID is already registered."); var builder = RegisteredClient.withId(UUID.randomUUID().toString()) .clientId(clientId) diff --git a/src/main/java/org/busystack/caldav/security/oauth/OAuthConfiguration.java b/src/main/java/org/busystack/caldav/security/oauth/OAuthConfiguration.java index ac05722..6386ed4 100644 --- a/src/main/java/org/busystack/caldav/security/oauth/OAuthConfiguration.java +++ b/src/main/java/org/busystack/caldav/security/oauth/OAuthConfiguration.java @@ -30,7 +30,6 @@ import org.springframework.security.oauth2.server.authorization.token.OAuth2AccessTokenGenerator; import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator; import org.springframework.security.web.SecurityFilterChain; -import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher; import org.springframework.transaction.PlatformTransactionManager; @@ -117,7 +116,9 @@ SecurityFilterChain authorizationServerSecurity( JdbcTemplate jdbc, PlatformTransactionManager transactions, org.busystack.caldav.security.session.SessionSecurity sessions, - AccountService accounts) + AccountService accounts, + org.busystack.caldav.security.session.BrowserSession browserSessions, + org.busystack.caldav.security.AuthenticationJourney journey) throws Exception { http.oauth2AuthorizationServer( server -> { @@ -223,11 +224,11 @@ SecurityFilterChain authorizationServerSecurity( }))); }) .authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated()) + .requestCache(cache -> cache.disable()) .exceptionHandling( exceptions -> exceptions.defaultAuthenticationEntryPointFor( - new LoginUrlAuthenticationEntryPoint("/login"), - new MediaTypeRequestMatcher(MediaType.TEXT_HTML))); + journey::loginRequired, new MediaTypeRequestMatcher(MediaType.TEXT_HTML))); // Before client authentication replaces a browser principal with the public client's identity. http.addFilterAfter( new ActiveAccountFilter(accounts), @@ -236,7 +237,7 @@ SecurityFilterChain authorizationServerSecurity( new org.busystack.caldav.security.session.SessionEpochFilter(sessions), org.springframework.security.web.context.SecurityContextHolderFilter.class); http.addFilterBefore( - new RecentMfaAuthorizationFilter(), + new RecentMfaAuthorizationFilter(browserSessions, journey), org.springframework.security.web.authentication.logout.LogoutFilter.class); // Framework CSRF protection for the cookie-authenticated consent form. Token exchanges // retain the authorization server's protocol authentication and do not require a cookie. 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..30897ba 100644 --- a/src/main/java/org/busystack/caldav/security/oauth/OAuthManagementController.java +++ b/src/main/java/org/busystack/caldav/security/oauth/OAuthManagementController.java @@ -10,15 +10,21 @@ 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 { private final OAuthClientService clients; private final OAuthGrantService grants; + private final org.busystack.caldav.management.PortalPageAdvice pages; - public OAuthManagementController(OAuthClientService clients, OAuthGrantService grants) { + public OAuthManagementController( + OAuthClientService clients, + OAuthGrantService grants, + org.busystack.caldav.management.PortalPageAdvice pages) { this.clients = clients; this.grants = grants; + this.pages = pages; } @GetMapping("/admin/oauth-clients") @@ -29,25 +35,63 @@ String clients(Authentication authentication, Model model) { @PostMapping("/admin/oauth-clients") String register( - Authentication authentication, - @RequestParam String clientId, - @RequestParam String name, - @RequestParam String redirects) { - clients.registerNative( - authentication, - clientId, - name, - redirects - .lines() - .map(String::strip) - .filter(value -> !value.isEmpty()) - .collect(Collectors.toSet())); + Authentication auth, + @RequestParam(defaultValue = "") String clientId, + @RequestParam(defaultValue = "") String name, + @RequestParam(defaultValue = "") String redirects, + RedirectAttributes flash, + Model model, + jakarta.servlet.http.HttpServletRequest request, + HttpServletResponse response) { + try { + clients.registerNative( + auth, + clientId, + name, + redirects + .lines() + .map(String::strip) + .filter(value -> !value.isEmpty()) + .collect(Collectors.toSet())); + } catch (org.busystack.caldav.management.FormValidation invalid) { + response.setStatus(invalid.conflict() ? 409 : 400); + pages.layout(auth, request, model); + model.addAttribute("fieldErrors", invalid.errors()); + model.addAttribute("errorFormKey", "native-app"); + model.addAttribute("clientId", clientId.length() <= 100 ? clientId : ""); + model.addAttribute("clientName", name.length() <= 100 ? name : ""); + model.addAttribute("redirects", redirects.length() <= 950 ? redirects : ""); + return clients(auth, model); + } + flash.addFlashAttribute("notice", "Application registration saved."); return "redirect:/admin/oauth-clients"; } + @GetMapping("/admin/oauth-clients/{id}/remove") + String confirmRemove(Authentication auth, @PathVariable String id, Model model) { + var client = clients.registration(auth, id); + model.addAttribute("actionTitle", "Remove " + client.name() + "?"); + model.addAttribute( + "consequence", + "All user grants for this application will be revoked. Existing connections using its authorization will stop working."); + model.addAttribute("actionLabel", "Remove application registration"); + model.addAttribute("actionPath", "/admin/oauth-clients/" + id + "/remove"); + model.addAttribute("cancelPath", "/admin/oauth-clients"); + model.addAttribute("expectedRevision", client.revision()); + return "confirm-action"; + } + @PostMapping("/admin/oauth-clients/{id}/remove") - String remove(Authentication authentication, @PathVariable String id) { - clients.remove(authentication, id); + String remove( + Authentication auth, + @PathVariable String id, + RedirectAttributes flash, + @RequestParam(defaultValue = "false") boolean confirmed, + @RequestParam(defaultValue = "") String expected) { + if (!confirmed) return "redirect:/admin/oauth-clients/" + id + "/remove"; + clients.remove(auth, id, expected); + flash.addFlashAttribute( + "notice", "Application registration removed. All associated grants were revoked."); return "redirect:/admin/oauth-clients"; } @@ -58,9 +102,35 @@ String grants(Authentication authentication, Model model, HttpServletResponse re return "oauth-grants"; } + @GetMapping("/oauth-grants/{id}/revoke") + String confirmRevoke(Authentication auth, @PathVariable String id, Model model) { + var grant = + grants.list(auth).stream() + .filter(item -> item.id().equals(id)) + .findFirst() + .orElseThrow( + () -> + new org.busystack.caldav.storage.StoreException( + org.busystack.caldav.storage.StoreException.Kind.NOT_FOUND)); + model.addAttribute("actionTitle", "Revoke access for " + grant.clientName() + "?"); + model.addAttribute( + "consequence", + "This grant will stop working. To connect again, approve access from the application."); + model.addAttribute("actionLabel", "Revoke app access"); + model.addAttribute("actionPath", "/oauth-grants/" + id + "/revoke"); + model.addAttribute("cancelPath", "/oauth-grants"); + return "confirm-action"; + } + @PostMapping("/oauth-grants/{id}/revoke") - String revoke(Authentication authentication, @PathVariable String id) { + String revoke( + Authentication authentication, + @PathVariable String id, + RedirectAttributes flash, + @RequestParam(defaultValue = "false") boolean confirmed) { + if (!confirmed) return "redirect:/oauth-grants/" + id + "/revoke"; 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/oauth/RecentMfaAuthorizationFilter.java b/src/main/java/org/busystack/caldav/security/oauth/RecentMfaAuthorizationFilter.java index f71479a..3f4259f 100644 --- a/src/main/java/org/busystack/caldav/security/oauth/RecentMfaAuthorizationFilter.java +++ b/src/main/java/org/busystack/caldav/security/oauth/RecentMfaAuthorizationFilter.java @@ -15,8 +15,15 @@ * reuse. */ final class RecentMfaAuthorizationFilter extends OncePerRequestFilter { - private final org.springframework.security.web.savedrequest.HttpSessionRequestCache requestCache = - new org.springframework.security.web.savedrequest.HttpSessionRequestCache(); + private final org.busystack.caldav.security.session.BrowserSession sessions; + private final org.busystack.caldav.security.AuthenticationJourney journey; + + RecentMfaAuthorizationFilter( + org.busystack.caldav.security.session.BrowserSession sessions, + org.busystack.caldav.security.AuthenticationJourney journey) { + this.sessions = sessions; + this.journey = journey; + } @Override protected boolean shouldNotFilter(HttpServletRequest request) { @@ -31,16 +38,57 @@ protected void doFilterInternal( if (authentication != null && authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken)) { - try { - org.busystack.caldav.security.RecentAuthentication.requireMfa(authentication); - } catch (org.springframework.security.access.AccessDeniedException ex) { + var state = sessions.state(request, authentication); + if (state != org.busystack.caldav.security.session.BrowserSession.State.CURRENT + || !org.busystack.caldav.security.RecentAuthentication.mfaCurrent(authentication)) { + if (state == org.busystack.caldav.security.session.BrowserSession.State.EXPIRED) { + SecurityContextHolder.clearContext(); + request.getSession(false).invalidate(); + authentication = null; + } if ("GET".equals(request.getMethod())) { - requestCache.saveRequest(request, response); - response.sendRedirect(request.getContextPath() + "/login?factor=required"); + String flow = + journey.start( + request, + org.busystack.caldav.security.BrowserAccessFilter.destination(request), + authentication); + response.sendRedirect( + request.getContextPath() + + (authentication == null ? "/login?session&flow=" : "/auth/continue?flow=") + + flow); + } else if ("POST".equals(request.getMethod()) + && authentication != null + && browserNavigation(request)) { + String client = request.getParameter("client_id"); + String consentState = request.getParameter("state"); + if (client == null + || client.length() > 200 + || consentState == null + || consentState.length() > 1024) { + response.sendError(403); + return; + } + String destination = + org.springframework.web.util.UriComponentsBuilder.fromPath( + request.getContextPath() + "/oauth/consent") + .queryParam("client_id", "{client}") + .queryParam("state", "{state}") + .encode() + .buildAndExpand(client, consentState) + .toUriString(); + String flow = journey.start(request, destination, authentication); + response.setStatus(HttpServletResponse.SC_SEE_OTHER); + response.setHeader("Cache-Control", "no-store"); + response.setHeader("Location", request.getContextPath() + "/auth/continue?flow=" + flow); } else response.sendError(403, "Recent primary and passkey verification required"); return; } } chain.doFilter(request, response); } + + private static boolean browserNavigation(HttpServletRequest request) { + return "navigate".equals(request.getHeader("Sec-Fetch-Mode")) + || request.getHeader("Accept") != null && request.getHeader("Accept").contains("text/html"); + } } diff --git a/src/main/java/org/busystack/caldav/security/oidc/ExternalIdentityService.java b/src/main/java/org/busystack/caldav/security/oidc/ExternalIdentityService.java index af133af..d8056ea 100644 --- a/src/main/java/org/busystack/caldav/security/oidc/ExternalIdentityService.java +++ b/src/main/java/org/busystack/caldav/security/oidc/ExternalIdentityService.java @@ -1,10 +1,14 @@ package org.busystack.caldav.security.oidc; +import jakarta.servlet.http.HttpServletRequest; import java.time.Instant; import java.util.UUID; import org.busystack.caldav.account.AccountService; +import org.busystack.caldav.security.BrowserFlowStore; import org.busystack.caldav.security.RecentAuthentication; +import org.busystack.caldav.security.session.BrowserSession; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.core.OAuth2Error; @@ -14,34 +18,46 @@ /** Only the configured issuer and exact subject pair can select an internal account. */ @Service public class ExternalIdentityService { - public record LinkIntent(UUID accountId, String username, Instant issuedAt) - implements java.io.Serializable {} + public record LinkIntent( + UUID accountId, + String username, + Instant issuedAt, + String sessionBinding, + BrowserSession.Proof proof) {} private final JdbcTemplate jdbc; private final OidcProperties properties; private final AccountService accounts; private final org.busystack.caldav.security.session.ClientAccessRevocation revocation; - private final org.busystack.caldav.security.session.SessionSecurity sessions; + private final BrowserSession browser; public ExternalIdentityService( JdbcTemplate jdbc, OidcProperties properties, AccountService accounts, org.busystack.caldav.security.session.ClientAccessRevocation revocation, - org.busystack.caldav.security.session.SessionSecurity sessions) { + BrowserSession browser) { this.jdbc = jdbc; this.properties = properties; this.accounts = accounts; this.revocation = revocation; - this.sessions = sessions; + this.browser = browser; } - public LinkIntent prepareLink(Authentication authentication) { + public LinkIntent prepareLink(Authentication authentication, HttpServletRequest request) { RecentAuthentication.requireMfa(authentication); - sessions.assertCurrent(authentication); + var proof = browser.requireProof(request, authentication); var account = accounts.find(authentication.getName()); - if (account == null || !account.enabled() || !properties.enabled()) throw denied(); - return new LinkIntent(account.id(), account.username(), Instant.now()); + if (account == null + || !account.enabled() + || !properties.enabled() + || accounts.isExternallyManaged(account.id())) throw denied(); + return new LinkIntent( + account.id(), + account.username(), + Instant.now(), + BrowserFlowStore.fingerprint(request.getSession(false).getId()), + proof); } @Transactional @@ -51,6 +67,17 @@ public AccountService.Account verifiedLogin( Instant authenticatedAt, LinkIntent link, Authentication current) { + return verifiedLogin(issuer, subject, authenticatedAt, link, current, null); + } + + @Transactional + public AccountService.Account verifiedLogin( + String issuer, + String subject, + Instant authenticatedAt, + LinkIntent link, + Authentication current, + HttpServletRequest request) { Instant now = Instant.now(); if (!properties.enabled() || !properties.issuer().toString().equals(issuer) @@ -71,16 +98,17 @@ public AccountService.Account verifiedLogin( subject); UUID accountId; if (link != null) { - RecentAuthentication.requireMfa(current); jdbc.query("SELECT id FROM accounts WHERE id=? FOR UPDATE", rs -> {}, link.accountId()); try { - sessions.assertCurrent(current); - } catch (org.springframework.security.access.AccessDeniedException ex) { + RecentAuthentication.requireMfa(current); + if (request == null + || !link.issuedAt().isAfter(Instant.now().minusSeconds(300)) + || !link.username().equals(current.getName()) + || !link.accountId().equals(link.proof().account())) throw denied(); + browser.lockLinkProof(request, current, link.sessionBinding(), link.proof()); + } catch (AccessDeniedException ex) { throw denied(); } - if (!link.issuedAt().isAfter(now.minusSeconds(300)) - || current == null - || !link.username().equals(current.getName())) throw denied(); var target = accounts.find(link.accountId()); if (target == null || !target.enabled() || !target.username().equals(link.username())) throw denied(); diff --git a/src/main/java/org/busystack/caldav/security/oidc/LinkingAuthorizationRequestResolver.java b/src/main/java/org/busystack/caldav/security/oidc/LinkingAuthorizationRequestResolver.java deleted file mode 100644 index ed4b6a0..0000000 --- a/src/main/java/org/busystack/caldav/security/oidc/LinkingAuthorizationRequestResolver.java +++ /dev/null @@ -1,63 +0,0 @@ -package org.busystack.caldav.security.oidc; - -import jakarta.servlet.http.HttpServletRequest; -import java.io.Serializable; -import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestResolver; -import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; - -/** Associates an explicit linking intent with its own upstream authorization response. */ -final class LinkingAuthorizationRequestResolver implements OAuth2AuthorizationRequestResolver { - static final String PENDING_LINK = - LinkingAuthorizationRequestResolver.class.getName() + ".pending"; - private static final String BOUND_LINK = - LinkingAuthorizationRequestResolver.class.getName() + ".bound"; - - private record BoundLink(String state, ExternalIdentityService.LinkIntent intent) - implements Serializable {} - - private final OAuth2AuthorizationRequestResolver delegate; - - LinkingAuthorizationRequestResolver(OAuth2AuthorizationRequestResolver delegate) { - this.delegate = delegate; - } - - @Override - public OAuth2AuthorizationRequest resolve(HttpServletRequest request) { - return bind(request, delegate.resolve(request)); - } - - @Override - public OAuth2AuthorizationRequest resolve(HttpServletRequest request, String registrationId) { - return bind(request, delegate.resolve(request, registrationId)); - } - - private OAuth2AuthorizationRequest bind( - HttpServletRequest request, OAuth2AuthorizationRequest authorization) { - var session = request.getSession(false); - if (authorization == null || session == null) return authorization; - synchronized (session) { - Object pending = session.getAttribute(PENDING_LINK); - if (pending instanceof ExternalIdentityService.LinkIntent intent) { - if (authorization.getState() == null || authorization.getState().isBlank()) - throw new IllegalStateException("Linking requires authorization response state"); - session.removeAttribute(PENDING_LINK); - session.setAttribute(BOUND_LINK, new BoundLink(authorization.getState(), intent)); - } - } - return authorization; - } - - static ExternalIdentityService.LinkIntent consume(HttpServletRequest request) { - var session = request.getSession(false); - if (session == null) return null; - synchronized (session) { - Object pending = session.getAttribute(BOUND_LINK); - if (pending instanceof BoundLink bound - && bound.state().equals(request.getParameter("state"))) { - session.removeAttribute(BOUND_LINK); - return bound.intent(); - } - return null; - } - } -} 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..3046b45 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 { @@ -39,8 +38,19 @@ OidcLoginSupport upstreamUsers( } } - public static void configure( - HttpSecurity http, ClientRegistrationRepository registrations, OidcLoginSupport users) + @Bean + ProviderNavigation providerNavigation( + org.busystack.caldav.security.BrowserFlowStore store, + org.busystack.caldav.security.AuthenticationJourney journey) { + return new ProviderNavigation(store, journey); + } + + public void configure( + HttpSecurity http, + ClientRegistrationRepository registrations, + OidcLoginSupport users, + org.busystack.caldav.security.BrowserFlowStore flows, + org.busystack.caldav.security.AuthenticationJourney journey) throws Exception { var resolver = new DefaultOAuth2AuthorizationRequestResolver(registrations, "/oauth2/authorization"); @@ -54,27 +64,58 @@ public static void configure( }); }); var repository = new HttpSessionOAuth2AuthorizedClientRepository(); - var success = new SavedRequestAwareAuthenticationSuccessHandler(); http.oauth2Login( login -> login .loginPage("/login") .authorizationEndpoint( endpoint -> - endpoint.authorizationRequestResolver( - new LinkingAuthorizationRequestResolver(resolver))) + endpoint + .authorizationRequestResolver(resolver) + .authorizationRequestRepository(providerNavigation(flows, journey))) .userInfoEndpoint(endpoint -> endpoint.oidcUserService(users)) .authorizedClientRepository(repository) + .failureHandler( + (request, response, failure) -> { + if (ProviderNavigation.link(request) != null) linkEnded(request, response); + else journey.primaryFailure(request, response, failure); + }) .successHandler( (request, response, authentication) -> { // This service uses upstream OIDC only for login, so discard access/refresh // tokens. repository.removeAuthorizedClient( "upstream", authentication, request, response); - success.onAuthenticationSuccess(request, response, authentication); + journey.primarySuccess(request, response, authentication); + }) + .withObjectPostProcessor( + new org.springframework.security.config.ObjectPostProcessor< + org.springframework.security.oauth2.client.web + .OAuth2AuthorizationRequestRedirectFilter>() { + @Override + public < + T extends + org.springframework.security.oauth2.client.web + .OAuth2AuthorizationRequestRedirectFilter> + T postProcess(T filter) { + filter.setAuthenticationFailureHandler( + (request, response, failure) -> { + if (request.getParameter("link") != null) + linkEnded(request, response); + else journey.primaryFailure(request, response, failure); + }); + return filter; + } })); } + private static void linkEnded( + HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) + throws java.io.IOException { + response.setHeader("Cache-Control", "no-store"); + response.sendRedirect(request.getContextPath() + "/login?error&linkEnded"); + } + /** Used only by WebAuthn; the form-password provider retains the local-only service. */ public static UserDetailsService passkeyUsers(AccountService accounts) { return username -> { diff --git a/src/main/java/org/busystack/caldav/security/oidc/OidcLinkController.java b/src/main/java/org/busystack/caldav/security/oidc/OidcLinkController.java index 08ff114..8b4c0dc 100644 --- a/src/main/java/org/busystack/caldav/security/oidc/OidcLinkController.java +++ b/src/main/java/org/busystack/caldav/security/oidc/OidcLinkController.java @@ -11,14 +11,16 @@ public class OidcLinkController { private final ExternalIdentityService identities; - public OidcLinkController(ExternalIdentityService identities) { + private final ProviderNavigation navigation; + + public OidcLinkController(ExternalIdentityService identities, ProviderNavigation navigation) { this.identities = identities; + this.navigation = navigation; } @PostMapping("/security/identities/link") String link(Authentication authentication, HttpServletRequest request) { - var intent = identities.prepareLink(authentication); - request.getSession().setAttribute(LinkingAuthorizationRequestResolver.PENDING_LINK, intent); - return "redirect:/oauth2/authorization/upstream"; + var intent = identities.prepareLink(authentication, request); + return "redirect:/oauth2/authorization/upstream?link=" + navigation.startLink(request, intent); } } diff --git a/src/main/java/org/busystack/caldav/security/oidc/OidcLoginSupport.java b/src/main/java/org/busystack/caldav/security/oidc/OidcLoginSupport.java index 7136000..86a076e 100644 --- a/src/main/java/org/busystack/caldav/security/oidc/OidcLoginSupport.java +++ b/src/main/java/org/busystack/caldav/security/oidc/OidcLoginSupport.java @@ -45,7 +45,7 @@ public OidcUser loadUser(OidcUserRequest request) { OidcUser verified = delegate.loadUser(request); var servletRequest = requests.getObject(); var session = servletRequest.getSession(false); - var link = LinkingAuthorizationRequestResolver.consume(servletRequest); + var link = ProviderNavigation.link(servletRequest); Instant authenticationTime = verified.getClaimAsInstant("auth_time"); org.busystack.caldav.account.AccountService.Account account; try { @@ -55,7 +55,8 @@ public OidcUser loadUser(OidcUserRequest request) { verified.getSubject(), authenticationTime, link, - SecurityContextHolder.getContext().getAuthentication()); + SecurityContextHolder.getContext().getAuthentication(), + servletRequest); } catch (DuplicateKeyException ex) { throw ExternalIdentityService.denied(); } diff --git a/src/main/java/org/busystack/caldav/security/oidc/ProviderNavigation.java b/src/main/java/org/busystack/caldav/security/oidc/ProviderNavigation.java new file mode 100644 index 0000000..e896846 --- /dev/null +++ b/src/main/java/org/busystack/caldav/security/oidc/ProviderNavigation.java @@ -0,0 +1,193 @@ +package org.busystack.caldav.security.oidc; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import org.busystack.caldav.security.AuthenticationJourney; +import org.busystack.caldav.security.BrowserFlowStore; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository; +import org.springframework.security.oauth2.core.OAuth2AuthorizationException; +import org.springframework.security.oauth2.core.OAuth2Error; +import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; + +/** Provider state owns its original authorization request, continuation and optional link. */ +final class ProviderNavigation + implements AuthorizationRequestRepository { + private static final String SECTION = "upstream"; + private static final String CALLBACK_LINK = ProviderNavigation.class.getName() + ".link"; + private static final int LIMIT = 8; + + private record Authorization( + String authorizationUri, + String client, + String redirect, + Set scopes, + String state, + Map parameters, + Map attributes, + String requestUri) { + Authorization(OAuth2AuthorizationRequest request) { + this( + request.getAuthorizationUri(), + request.getClientId(), + request.getRedirectUri(), + request.getScopes(), + request.getState(), + request.getAdditionalParameters(), + request.getAttributes(), + request.getAuthorizationRequestUri()); + } + + OAuth2AuthorizationRequest rebuild() { + return OAuth2AuthorizationRequest.authorizationCode() + .authorizationUri(authorizationUri) + .clientId(client) + .redirectUri(redirect) + .scopes(scopes) + .state(state) + .additionalParameters(parameters) + .attributes(attributes) + .authorizationRequestUri(requestUri) + .build(); + } + } + + private record Pending( + Authorization authorization, + String flow, + ExternalIdentityService.LinkIntent link, + Instant expires) {} + + private record State( + LinkedHashMap links, + LinkedHashMap requests) { + State() { + this(new LinkedHashMap<>(), new LinkedHashMap<>()); + } + + void prune() { + links.values().removeIf(link -> !BrowserFlowStore.current(link.issuedAt().plusSeconds(300))); + requests.values().removeIf(request -> !BrowserFlowStore.current(request.expires())); + } + } + + private final BrowserFlowStore store; + private final AuthenticationJourney journey; + + ProviderNavigation(BrowserFlowStore store, AuthenticationJourney journey) { + this.store = store; + this.journey = journey; + } + + String startLink(HttpServletRequest request, ExternalIdentityService.LinkIntent intent) { + return store.update( + request, + true, + SECTION, + State.class, + State::new, + state -> { + state.prune(); + String handle = UUID.randomUUID().toString(); + state.links().put(handle, intent); + while (state.links().size() > LIMIT) state.links().pollFirstEntry(); + return handle; + }); + } + + @Override + public OAuth2AuthorizationRequest loadAuthorizationRequest(HttpServletRequest request) { + var state = store.read(request, SECTION, State.class, State::new); + state.prune(); + var pending = state.requests().get(request.getParameter("state")); + return pending == null ? null : pending.authorization().rebuild(); + } + + @Override + public void saveAuthorizationRequest( + OAuth2AuthorizationRequest authorization, + HttpServletRequest request, + HttpServletResponse response) { + if (authorization == null) { + removeAuthorizationRequest(request, response); + return; + } + String flow = journey.handle(request); + String linkHandle = request.getParameter("link"); + store.update( + request, + true, + SECTION, + State.class, + State::new, + state -> { + state.prune(); + ExternalIdentityService.LinkIntent link = null; + if (linkHandle != null) { + if (!AuthenticationJourney.validHandle(linkHandle)) throw unavailable(); + link = state.links().get(linkHandle); + var current = SecurityContextHolder.getContext().getAuthentication(); + if (link == null + || current == null + || !link.username().equals(current.getName()) + || !link.sessionBinding() + .equals(BrowserFlowStore.fingerprint(request.getSession(false).getId())) + || !link.proof() + .epoch() + .equals( + org.busystack.caldav.security.session.SessionSecurity.capturedEpoch( + current.getAuthorities()))) throw unavailable(); + state.links().remove(linkHandle); + } + state + .requests() + .put( + authorization.getState(), + new Pending( + new Authorization(authorization), + flow, + link, + link == null + ? Instant.now().plusSeconds(900) + : link.issuedAt().plusSeconds(300))); + while (state.requests().size() > LIMIT) state.requests().pollFirstEntry(); + return null; + }); + } + + @Override + public OAuth2AuthorizationRequest removeAuthorizationRequest( + HttpServletRequest request, HttpServletResponse response) { + String incoming = request.getParameter("state"); + if (incoming == null || incoming.length() > 256) return null; + Pending pending = + store.update( + request, + false, + SECTION, + State.class, + State::new, + state -> { + state.prune(); + return state.requests().remove(incoming); + }); + if (pending == null) return null; + journey.providerCallback(request, pending.flow()); + request.setAttribute(CALLBACK_LINK, pending.link()); + return pending.authorization().rebuild(); + } + + static ExternalIdentityService.LinkIntent link(HttpServletRequest request) { + return (ExternalIdentityService.LinkIntent) request.getAttribute(CALLBACK_LINK); + } + + private static OAuth2AuthorizationException unavailable() { + return new OAuth2AuthorizationException( + new OAuth2Error("invalid_request"), "Link request ended"); + } +} diff --git a/src/main/java/org/busystack/caldav/security/passkey/AcceptedAssertion.java b/src/main/java/org/busystack/caldav/security/passkey/AcceptedAssertion.java new file mode 100644 index 0000000..627ca39 --- /dev/null +++ b/src/main/java/org/busystack/caldav/security/passkey/AcceptedAssertion.java @@ -0,0 +1,24 @@ +package org.busystack.caldav.security.passkey; + +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.security.web.webauthn.api.Bytes; + +/** Bridges a single framework assertion to its success handler on the same request. */ +final class AcceptedAssertion implements AutoCloseable { + static final String KEY = AcceptedAssertion.class.getName(); + private static final ThreadLocal REQUEST = new ThreadLocal<>(); + + AcceptedAssertion(HttpServletRequest request) { + REQUEST.set(request); + } + + static void record(Bytes credential) { + var request = REQUEST.get(); + if (request != null) request.setAttribute(KEY, credential.toBase64UrlString()); + } + + @Override + public void close() { + REQUEST.remove(); + } +} diff --git a/src/main/java/org/busystack/caldav/security/passkey/AccountRelyingPartyOperations.java b/src/main/java/org/busystack/caldav/security/passkey/AccountRelyingPartyOperations.java index c7fe9a8..8e4396c 100644 --- a/src/main/java/org/busystack/caldav/security/passkey/AccountRelyingPartyOperations.java +++ b/src/main/java/org/busystack/caldav/security/passkey/AccountRelyingPartyOperations.java @@ -135,6 +135,7 @@ var record = credentials.findByCredentialId(key.getRawId()); .backupState(backupState) .uvInitialized(record.isUvInitialized() || (flags & 0x04) != 0) .build()); + AcceptedAssertion.record(verified.getCredentialId()); return authenticated; } } 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..9624478 100644 --- a/src/main/java/org/busystack/caldav/security/passkey/PasskeyCeremonyGuard.java +++ b/src/main/java/org/busystack/caldav/security/passkey/PasskeyCeremonyGuard.java @@ -16,18 +16,21 @@ public class PasskeyCeremonyGuard extends OncePerRequestFilter { private static final int MAX_JSON_BYTES = 65536; private final AccountPasskeyUsers users; private final CeremonyStore ceremonies; + private final org.busystack.caldav.security.session.BrowserSession sessions; - public PasskeyCeremonyGuard(AccountPasskeyUsers users, CeremonyStore ceremonies) { + public PasskeyCeremonyGuard( + AccountPasskeyUsers users, + CeremonyStore ceremonies, + org.busystack.caldav.security.session.BrowserSession sessions) { this.users = users; this.ceremonies = ceremonies; + this.sessions = sessions; } @Override protected boolean shouldNotFilter(HttpServletRequest request) { String path = request.getServletPath(); - return !(path.startsWith("/webauthn/") - || path.equals("/login/webauthn") - || path.equals("/security/passkeys")); + return !(path.startsWith("/webauthn/") || path.equals("/login/webauthn")); } @Override @@ -35,16 +38,29 @@ protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String path = request.getServletPath(); - if (path.startsWith("/webauthn/register") || path.equals("/security/passkeys")) { + if (path.startsWith("/webauthn/register")) { var authentication = SecurityContextHolder.getContext().getAuthentication(); try { RecentAuthentication.requirePrimary(authentication); - if (users.hasCredentials(authentication.getName())) + if (users.hasCredentials(authentication.getName())) { RecentAuthentication.requireMfa(authentication); + if (sessions.state(request, authentication) + != org.busystack.caldav.security.session.BrowserSession.State.CURRENT) + throw new AccessDeniedException("Verify a current passkey to manage passkeys"); + } } 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 +89,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; @@ -108,12 +125,13 @@ protected void doFilterInternal( && (path.equals("/webauthn/authenticate/options") || path.equals("/webauthn/register/options"))) processed = new ChallengeRecordingRequest(processed, ceremonies); - try { + try (var assertion = new AcceptedAssertion(processed)) { chain.doFilter(processed, response); } catch (VerificationException | PasskeyRegistrationRejectedException ex) { // 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..f4d678d 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,9 @@ public static void configure( HttpSecurity http, DeploymentProperties properties, AccountPasskeyUsers users, - CeremonyStore ceremonies) { + CeremonyStore ceremonies, + org.busystack.caldav.security.AuthenticationJourney journey, + org.busystack.caldav.security.session.BrowserSession browserSessions) { var base = properties.publicBaseUrl(); http.webAuthn( web -> { @@ -84,11 +86,19 @@ public static void configure( @Override public O postProcess(O filter) { filter.setSessionAuthenticationStrategy(new SessionFixationProtectionStrategy()); + filter.setAuthenticationSuccessHandler( + (request, response, auth) -> { + if (org.busystack.caldav.security.RecentAuthentication.mfaCurrent(auth)) + browserSessions.complete( + request, auth, (String) request.getAttribute(AcceptedAssertion.KEY)); + journey.passkeySuccess(request, response, auth); + }); return filter; } }); }); http.addFilterBefore( - new PasskeyCeremonyGuard(users, ceremonies), UsernamePasswordAuthenticationFilter.class); + new PasskeyCeremonyGuard(users, ceremonies, browserSessions), + UsernamePasswordAuthenticationFilter.class); } } 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..e9ecfa8 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,128 @@ 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, + Model model, + jakarta.servlet.http.HttpServletRequest request, + jakarta.servlet.http.HttpServletResponse response) { + response.setHeader("Cache-Control", "no-store"); + if (initialization.available()) return "redirect:/setup"; + String next = request.getParameter("next"); + String flow = next == null ? journey.handle(request) : journey.start(request, next, auth); + model.addAttribute("signInFlow", flow); + model.addAttribute("verifiedAction", journey.action(request, auth, flow)); + String retryUsername = journey.retryUsername(request, auth, flow); + if (retryUsername != null && !model.containsAttribute("initialUsername")) + model.addAttribute("initialUsername", retryUsername); + if (org.busystack.caldav.security.session.BrowserSession.completed(request) + && request.getParameter("reauthenticate") == null + && flow.isEmpty()) return "redirect:/"; + if (org.busystack.caldav.security.RecentAuthentication.primaryCurrent(auth) + && request.getParameter("reauthenticate") == null) + return "redirect:/auth/continue?flow=" + flow; 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"); + String flow = next == null ? journey.handle(request) : journey.start(request, next, auth); + boolean completed = org.busystack.caldav.security.session.BrowserSession.completed(request); + boolean interrupted = + request.getParameter("interrupted") != null + || !flow.isEmpty() && !journey.available(request, auth, flow); + if (interrupted) { + if (completed) return "redirect:/?interrupted"; + model.addAttribute("continuationUnavailable", true); + flow = ""; + } + if (completed + && (flow.isEmpty() || org.busystack.caldav.security.RecentAuthentication.mfaCurrent(auth))) + return "redirect:" + stripContext(request, journey.consume(request, auth, flow)); + if (!org.busystack.caldav.security.RecentAuthentication.primaryCurrent(auth)) + return "redirect:/login?reauthenticate&flow=" + flow + (interrupted ? "&interrupted" : ""); + model.addAttribute("signInFlow", flow); + model.addAttribute("verifiedAction", journey.action(request, auth, flow)); + model.addAttribute("confirmingAction", completed); + return users.hasCredentials(auth.getName()) ? "verify-passkey" : "enroll-passkey"; + } + + private static String stripContext(jakarta.servlet.http.HttpServletRequest request, String path) { + return path.substring(request.getContextPath().length()); + } + + @GetMapping("/auth/state") + @org.springframework.web.bind.annotation.ResponseBody + public java.util.Map state( + Authentication auth, + jakarta.servlet.http.HttpServletRequest request, + 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.session.BrowserSession.completed(request) + && org.busystack.caldav.security.RecentAuthentication.mfaCurrent(auth)); + } + + @GetMapping("/security/passkeys/remove/{id}") + public String confirmRemove( + Authentication auth, + @org.springframework.web.bind.annotation.PathVariable String id, + Model model) { + var user = users.findByUsername(auth.getName()); + if (user == null || !id.matches("[A-Za-z0-9_-]{1,2048}")) + throw new org.busystack.caldav.storage.StoreException( + org.busystack.caldav.storage.StoreException.Kind.NOT_FOUND); + var records = credentials.findByUserId(user.getId()); + var key = + records.stream() + .filter(record -> record.getCredentialId().toBase64UrlString().equals(id)) + .findFirst() + .orElseThrow( + () -> + new org.busystack.caldav.storage.StoreException( + org.busystack.caldav.storage.StoreException.Kind.NOT_FOUND)); + model.addAttribute("credential", key); + model.addAttribute("lastKey", records.size() == 1); + return "passkey-remove"; + } + + @GetMapping("/security/passkeys/add") + public String add() { + return "redirect:/security/passkeys#passkey-label"; + } + @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/password/PasswordController.java b/src/main/java/org/busystack/caldav/security/password/PasswordController.java index 4c7c7b8..4b0e3d2 100644 --- a/src/main/java/org/busystack/caldav/security/password/PasswordController.java +++ b/src/main/java/org/busystack/caldav/security/password/PasswordController.java @@ -14,9 +14,12 @@ @Controller public class PasswordController { private final AccountPasswordService passwords; + private final org.busystack.caldav.management.PortalPageAdvice pages; - public PasswordController(AccountPasswordService passwords) { + public PasswordController( + AccountPasswordService passwords, org.busystack.caldav.management.PortalPageAdvice pages) { this.passwords = passwords; + this.pages = pages; } @GetMapping("/security/password") @@ -27,11 +30,12 @@ String page() { @PostMapping("/security/password") String change( Authentication authentication, - @RequestParam String password, - @RequestParam String confirmation, + @RequestParam(defaultValue = "") String password, + @RequestParam(defaultValue = "") String confirmation, HttpServletRequest request) { if (!password.equals(confirmation)) - throw new IllegalArgumentException("The new password entries must match"); + throw org.busystack.caldav.management.FormValidation.field( + "confirmation", "Enter the same password in both fields."); passwords.change(authentication, password, request.getRemoteAddr()); SecurityContextHolder.clearContext(); var session = request.getSession(false); @@ -40,9 +44,22 @@ String change( } @ExceptionHandler(IllegalArgumentException.class) - String invalid(IllegalArgumentException failure, Model model, HttpServletResponse response) { + String invalid( + IllegalArgumentException failure, + Model model, + HttpServletResponse response, + HttpServletRequest request, + Authentication auth) { response.setStatus(400); - model.addAttribute("error", failure.getMessage()); + pages.layout(auth, request, model); + response.setHeader("Cache-Control", "no-store"); + model.addAttribute( + "fieldErrors", + failure instanceof org.busystack.caldav.management.FormValidation validation + ? validation.errors() + : java.util.Map.of( + "password", "Use at least 14 Unicode characters and at most 72 UTF-8 bytes.")); + model.addAttribute("errorFormKey", "password-change"); return "password"; } } diff --git a/src/main/java/org/busystack/caldav/security/recovery/RecoveryController.java b/src/main/java/org/busystack/caldav/security/recovery/RecoveryController.java index c321c66..77c7a51 100644 --- a/src/main/java/org/busystack/caldav/security/recovery/RecoveryController.java +++ b/src/main/java/org/busystack/caldav/security/recovery/RecoveryController.java @@ -13,9 +13,16 @@ @Controller public class RecoveryController { private final RecoveryService recovery; + private final org.busystack.caldav.security.IssuanceIntents intents; + private final org.busystack.caldav.security.AuthenticationJourney journey; - public RecoveryController(RecoveryService recovery) { + public RecoveryController( + RecoveryService recovery, + org.busystack.caldav.security.IssuanceIntents intents, + org.busystack.caldav.security.AuthenticationJourney journey) { this.recovery = recovery; + this.intents = intents; + this.journey = journey; } @GetMapping("/security/recovery") @@ -25,24 +32,81 @@ String page(Authentication authentication, Model model, HttpServletResponse resp return "recovery"; } + @GetMapping("/security/recovery/codes/new") + String prepare(Authentication auth, Model model, HttpServletResponse response) { + model.addAttribute("status", recovery.status(auth)); + model.addAttribute( + "issuanceIntent", + intents + .prepare(auth, org.busystack.caldav.security.IssuanceIntents.Purpose.RECOVERY_CODES, "") + .id()); + org.busystack.caldav.security.IssuancePages.protect(response); + return "recovery-generate"; + } + @PostMapping("/security/recovery/codes") String issue( Authentication authentication, Model model, HttpServletRequest request, - HttpServletResponse response) { - model.addAttribute("issued", recovery.issue(authentication, request.getRemoteAddr())); - response.setHeader("Cache-Control", "no-store"); - response.setHeader("Pragma", "no-cache"); + HttpServletResponse response, + @RequestParam(required = false) java.util.UUID intent, + @RequestParam(defaultValue = "false") boolean replace) { + var issued = recovery.issue(authentication, request.getRemoteAddr(), intent, replace); + org.busystack.caldav.security.IssuancePages.protect(response); + if (issued == null) { + model.addAttribute("recoveryIssuance", true); + model.addAttribute( + "issuanceMessage", + "This request already generated recovery codes. Reach the current settings to review how many remain or deliberately replace them."); + return "issuance-receipt"; + } + model.addAttribute("issued", issued); return "recovery-codes"; } + @GetMapping("/security/recovery/use") + String useForm(Authentication auth, HttpServletRequest request, HttpServletResponse response) { + if (!org.busystack.caldav.security.RecentAuthentication.primaryCurrent(auth)) + return primaryAgain(auth, request); + org.busystack.caldav.security.IssuancePages.protect(response); + return "recovery-use"; + } + @PostMapping("/security/recovery/use") - String use(Authentication authentication, @RequestParam String code, HttpServletRequest request) { - recovery.recover(authentication, code, request.getRemoteAddr()); + String use( + Authentication authentication, + @RequestParam String code, + HttpServletRequest request, + HttpServletResponse response, + Model model) { + if (!org.busystack.caldav.security.RecentAuthentication.primaryCurrent(authentication)) + return primaryAgain(authentication, request); + try { + recovery.recover(authentication, code, request.getRemoteAddr()); + } catch (RecoveryService.RejectedCode invalid) { + if (!org.busystack.caldav.security.RecentAuthentication.primaryCurrent(authentication)) + return primaryAgain(authentication, request); + response.setStatus(400); + org.busystack.caldav.security.IssuancePages.protect(response); + model.addAttribute( + "fieldErrors", + java.util.Map.of("code", "Enter an unused recovery code for this account.")); + model.addAttribute("errorFormKey", "recovery-use"); + return "recovery-use"; + } catch (org.springframework.security.access.AccessDeniedException denied) { + if (!org.busystack.caldav.security.RecentAuthentication.primaryCurrent(authentication)) + return primaryAgain(authentication, request); + throw denied; + } SecurityContextHolder.clearContext(); var session = request.getSession(false); if (session != null) session.invalidate(); return "redirect:/login?recovered"; } + + private String primaryAgain(Authentication auth, HttpServletRequest request) { + return "redirect:/login?reauthenticate&flow=" + + journey.start(request, request.getContextPath() + "/security/recovery/use", auth); + } } diff --git a/src/main/java/org/busystack/caldav/security/recovery/RecoveryService.java b/src/main/java/org/busystack/caldav/security/recovery/RecoveryService.java index 53ca113..d9fdf62 100644 --- a/src/main/java/org/busystack/caldav/security/recovery/RecoveryService.java +++ b/src/main/java/org/busystack/caldav/security/recovery/RecoveryService.java @@ -9,6 +9,7 @@ import java.util.List; import java.util.UUID; import org.busystack.caldav.account.AccountService; +import org.busystack.caldav.security.IssuanceIntents; import org.busystack.caldav.security.RecentAuthentication; import org.busystack.caldav.security.audit.SecurityAudit; import org.busystack.caldav.security.audit.SecurityHashes; @@ -41,12 +42,19 @@ public String toString() { } } + static final class RejectedCode extends AccessDeniedException { + RejectedCode() { + super("Recovery code is invalid or expired"); + } + } + public record Status(int remaining, Instant expiresAt) {} private record StoredCode( String hash, Instant expiresAt, boolean available, boolean epochValid) {} private final JdbcTemplate jdbc; + private final IssuanceIntents intents; private final SessionSecurity sessions; private final AccountService accounts; private final org.busystack.caldav.security.session.ClientAccessRevocation clients; @@ -63,13 +71,15 @@ public RecoveryService( AccountPasskeyCredentials passkeys, SecurityAudit audit, PlatformTransactionManager transactions, - org.busystack.caldav.security.session.ClientAccessRevocation clients) { + org.busystack.caldav.security.session.ClientAccessRevocation clients, + IssuanceIntents intents) { this.jdbc = jdbc; this.sessions = sessions; this.accounts = accounts; this.passkeys = passkeys; this.audit = audit; this.clients = clients; + this.intents = intents; this.transaction = new TransactionTemplate(transactions); transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); transaction.setTimeout(15); @@ -89,7 +99,30 @@ public Status status(Authentication authentication) { public IssuedCodes issue(Authentication authentication, String peer) { RecentAuthentication.requireMfa(authentication); var account = sessions.assertForReset(authentication); + return issueSet(account, peer); + } + + @Transactional + public IssuedCodes issue( + Authentication authentication, String peer, UUID intent, boolean replace) { + RecentAuthentication.requireMfa(authentication); + var account = sessions.assertForReset(authentication); + var claim = intents.claim(account, intent, IssuanceIntents.Purpose.RECOVERY_CODES, ""); + if (claim.consumed()) return null; + if (!java.util.Objects.equals( + claim.expectedGeneration(), intents.recoveryGeneration(account.id()))) + throw IssuanceIntents.changed(); + if (status(authentication).remaining() > 0 && !replace) + throw new IllegalArgumentException("Confirm replacement of the current recovery codes."); + var issued = issueSet(account, peer); + intents.consume(claim, null); + return issued; + } + + private IssuedCodes issueSet(SessionSecurity.Account account, String peer) { requireCurrentAccess(account.id()); + jdbc.update( + "UPDATE accounts SET recovery_code_generation=gen_random_uuid() WHERE id=?", account.id()); jdbc.update( "UPDATE account_recovery_codes SET revoked_at=now() WHERE account_id=? AND used_at IS NULL AND revoked_at IS NULL", account.id()); @@ -167,8 +200,7 @@ public void recover(Authentication authentication, String code, String peer) { peer); return true; }); - if (!Boolean.TRUE.equals(accepted)) - throw new AccessDeniedException("Recovery code is invalid or expired"); + if (!Boolean.TRUE.equals(accepted)) throw new RejectedCode(); } private void lock(UUID account) { diff --git a/src/main/java/org/busystack/caldav/security/session/BrowserSession.java b/src/main/java/org/busystack/caldav/security/session/BrowserSession.java new file mode 100644 index 0000000..604c4bf --- /dev/null +++ b/src/main/java/org/busystack/caldav/security/session/BrowserSession.java @@ -0,0 +1,159 @@ +package org.busystack.caldav.security.session; + +import jakarta.servlet.http.HttpServletRequest; +import java.io.Serializable; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.UUID; +import org.busystack.caldav.security.BrowserFlowStore; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.authority.FactorGrantedAuthority; +import org.springframework.stereotype.Component; + +/** A completed browser session is backed by a specific accepted, still-owned assertion key. */ +@Component +public class BrowserSession { + public static final Duration MAX_AGE = Duration.ofHours(8); + private static final String PROOF = BrowserSession.class.getName() + ".proof"; + public static final String CURRENT = BrowserSession.class.getName() + ".current"; + + public enum State { + INCOMPLETE, + CURRENT, + KEY_REMOVED, + EXPIRED + } + + public record Proof(UUID account, UUID epoch, String key, Instant established, Instant asserted) + implements Serializable {} + + private final JdbcTemplate jdbc; + private final SessionSecurity sessions; + private final Clock clock; + + @org.springframework.beans.factory.annotation.Autowired + public BrowserSession(JdbcTemplate jdbc, SessionSecurity sessions) { + this(jdbc, sessions, Clock.systemUTC()); + } + + BrowserSession(JdbcTemplate jdbc, SessionSecurity sessions, Clock clock) { + this.jdbc = jdbc; + this.sessions = sessions; + this.clock = clock; + } + + public void complete( + HttpServletRequest request, Authentication authentication, String verifiedKey) { + var account = sessions.assertCurrent(authentication); + Instant assertion = assertion(authentication); + if (assertion == null + || assertion.isAfter(clock.instant()) + || verifiedKey == null + || !owns(account.id(), verifiedKey)) + throw new org.springframework.security.access.AccessDeniedException( + "Verified passkey unavailable"); + var session = request.getSession(); + Object prior = session.getAttribute(PROOF); + Instant established = + prior instanceof Proof proof + && proof.account().equals(account.id()) + && proof.epoch().equals(account.epoch()) + ? proof.established() + : assertion; + session.setAttribute( + PROOF, new Proof(account.id(), account.epoch(), verifiedKey, established, assertion)); + } + + public State state(HttpServletRequest request, Authentication authentication) { + var session = request.getSession(false); + if (session == null || !(session.getAttribute(PROOF) instanceof Proof proof)) + return State.INCOMPLETE; + Instant now = clock.instant(); + if (proof.established().isAfter(now) || !proof.established().plus(MAX_AGE).isAfter(now)) + return State.EXPIRED; + var account = sessions.assertCurrent(authentication); + if (!proof.account().equals(account.id()) + || !proof.epoch().equals(account.epoch()) + || !proof.asserted().equals(assertion(authentication))) { + session.removeAttribute(PROOF); + return State.INCOMPLETE; + } + if (!owns(account.id(), proof.key())) { + session.removeAttribute(PROOF); + return State.KEY_REMOVED; + } + return State.CURRENT; + } + + public static boolean completed(HttpServletRequest request) { + return Boolean.TRUE.equals(request.getAttribute(CURRENT)); + } + + public Proof requireProof(HttpServletRequest request, Authentication authentication) { + if (state(request, authentication) != State.CURRENT) + throw new org.springframework.security.access.AccessDeniedException( + "Current passkey verification is required"); + return (Proof) request.getSession(false).getAttribute(PROOF); + } + + /** Called with the account locked in the privileged transaction. */ + public void lockLinkProof( + HttpServletRequest request, + Authentication authentication, + String sessionBinding, + Proof bound) { + var session = request.getSession(false); + if (session == null + || !sessionBinding.equals(BrowserFlowStore.fingerprint(session.getId())) + || !bound.equals(requireProof(request, authentication))) + throw new org.springframework.security.access.AccessDeniedException( + "Link verification ended"); + var current = + jdbc.queryForList( + "SELECT session_id FROM spring_session WHERE session_id=? AND expiry_time>? FOR UPDATE", + String.class, + session.getId(), + clock.millis()); + var keys = + jdbc.queryForList( + """ + SELECT c.credential_id FROM user_credentials c + JOIN user_entities u ON u.id=c.user_entity_user_id + WHERE c.credential_id=? AND u.account_id=? FOR UPDATE OF c + """, + String.class, + bound.key(), + bound.account()); + if (current.isEmpty() || keys.isEmpty()) + throw new org.springframework.security.access.AccessDeniedException( + "Link verification ended"); + } + + public Instant overallDeadline(HttpServletRequest request) { + var session = request.getSession(false); + return session != null && session.getAttribute(PROOF) instanceof Proof proof + ? proof.established().plus(MAX_AGE) + : null; + } + + private boolean owns(UUID account, String key) { + 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 WHERE c.credential_id=? AND u.account_id=?)", + Boolean.class, + key, + account)); + } + + private static Instant assertion(Authentication authentication) { + return authentication.getAuthorities().stream() + .filter(FactorGrantedAuthority.class::isInstance) + .map(FactorGrantedAuthority.class::cast) + .filter(factor -> FactorGrantedAuthority.WEBAUTHN_AUTHORITY.equals(factor.getAuthority())) + .map(FactorGrantedAuthority::getIssuedAt) + .max(Instant::compareTo) + .orElse(null); + } +} 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..97cfdb4 100644 --- a/src/main/java/org/busystack/caldav/security/session/SessionController.java +++ b/src/main/java/org/busystack/caldav/security/session/SessionController.java @@ -10,13 +10,16 @@ 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 { private final SessionService sessions; + private final BrowserSession browserSessions; - public SessionController(SessionService sessions) { + public SessionController(SessionService sessions, BrowserSession browserSessions) { this.sessions = sessions; + this.browserSessions = browserSessions; } @GetMapping("/security/sessions") @@ -32,8 +35,60 @@ String list( return "sessions"; } + @PostMapping("/session/stay") + @org.springframework.web.bind.annotation.ResponseBody + java.util.Map stay(HttpServletRequest request, HttpServletResponse response) { + var session = request.getSession(false); + var overall = browserSessions.overallDeadline(request); + if (!BrowserSession.completed(request) || session == null || overall == null) + throw new org.springframework.security.access.AccessDeniedException( + "Completed browser session required"); + response.setHeader("Cache-Control", "no-store"); + long now = System.currentTimeMillis(); + return java.util.Map.of( + "serverTime", + now, + "idleDeadline", + session.getLastAccessedTime() + session.getMaxInactiveInterval() * 1000L, + "overallDeadline", + overall.toEpochMilli()); + } + + @GetMapping("/security/sessions/{id}/revoke") + String confirmRevoke( + Authentication auth, @PathVariable UUID id, HttpServletRequest request, Model model) { + var session = request.getSession(false); + var selected = + sessions.list(auth, session == null ? null : session.getId()).stream() + .filter(item -> item.id().equals(id)) + .findFirst() + .orElseThrow( + () -> + new org.busystack.caldav.storage.StoreException( + org.busystack.caldav.storage.StoreException.Kind.NOT_FOUND)); + model.addAttribute( + "actionTitle", + selected.current() ? "End this browser session?" : "End this other browser session?"); + model.addAttribute( + "consequence", + selected.current() + ? "This signs you out of this browser. Sign in again to return." + : "The other browser will need to sign in again. This browser stays signed in."); + model.addAttribute("actionLabel", "End browser session"); + model.addAttribute("actionPath", "/security/sessions/" + id + "/revoke"); + model.addAttribute("cancelPath", "/security/sessions"); + return "confirm-action"; + } + @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, + @org.springframework.web.bind.annotation.RequestParam(defaultValue = "false") + boolean confirmed) { + if (!confirmed) return "redirect:/security/sessions/" + id + "/revoke"; var session = request.getSession(false); if (sessions.revoke( authentication, id, session == null ? null : session.getId(), request.getRemoteAddr())) { @@ -41,6 +96,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/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/java/org/busystack/caldav/security/session/SessionSecurity.java b/src/main/java/org/busystack/caldav/security/session/SessionSecurity.java index 4b6c2c7..099ef37 100644 --- a/src/main/java/org/busystack/caldav/security/session/SessionSecurity.java +++ b/src/main/java/org/busystack/caldav/security/session/SessionSecurity.java @@ -101,5 +101,6 @@ public void invalidateAll(UUID accountId) { names.getFirst(), accountId.toString()); jdbc.update("DELETE FROM webauthn_ceremonies WHERE account_id=?", accountId); + jdbc.update("DELETE FROM browser_issuance_intents WHERE account_id=?", accountId); } } diff --git a/src/main/java/org/busystack/caldav/sharing/GroupService.java b/src/main/java/org/busystack/caldav/sharing/GroupService.java index 4e34b97..a9e1e01 100644 --- a/src/main/java/org/busystack/caldav/sharing/GroupService.java +++ b/src/main/java/org/busystack/caldav/sharing/GroupService.java @@ -29,6 +29,236 @@ 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, String grantState) {} + + private static final String GRANT_STATE = + "encode(sha256(convert_to(coalesce(string_agg(" + + "c.collection_id::text || ':' || c.permission, ',' ORDER BY c.collection_id)," + + "''), 'UTF8')), 'hex')"; + + 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), + null), + 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), + grants.total, grants.state + FROM sharing_groups g + CROSS JOIN LATERAL ( + SELECT count(*) AS total, %s AS state + FROM collection_group_members c WHERE c.group_id=g.id + ) grants + WHERE g.id=? + """ + .formatted(GRANT_STATE), + (rs, row) -> + new Summary( + rs.getObject(1, UUID.class), + rs.getString(2), + rs.getLong(3), + rs.getLong(4), + rs.getString(5)), + 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); + } + + public org.busystack.caldav.management.PortalPage eligibleMembers( + 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 accounts a + WHERE a.enabled AND NOT EXISTS ( + SELECT 1 FROM sharing_group_members m WHERE m.group_id=? AND m.account_id=a.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); + if (jdbc.update("UPDATE sharing_groups SET name=? WHERE id=? AND name=?", name, group, expected) + != 1) throw new StoreException(StoreException.Kind.PRECONDITION); + audit.targeted( + actor, + org.busystack.caldav.security.audit.SecurityAudit.Action.GROUP_UPDATED, + org.busystack.caldav.security.audit.SecurityAudit.Outcome.SUCCESS, + org.busystack.caldav.security.audit.SecurityAudit.TargetType.GROUP, + group, + null); + } + + @Transactional(timeout = 30) + public void changeMember( + Authentication auth, + UUID group, + String username, + UUID member, + boolean add, + boolean confirmed) { + changeMember(auth, group, username, member, add, confirmed, null); + } + + @Transactional(timeout = 30) + public void changeMember( + Authentication auth, + UUID group, + String username, + UUID member, + boolean add, + boolean confirmed, + String expectedGrants) { + RecentAuthentication.requireMfa(auth); + DavMutationLock.exclusive(jdbc); + UUID actor = administrator(auth); + requireGroup(group); + if (!confirmed) + throw org.busystack.caldav.management.FormValidation.field( + "confirmed", "Confirm the effect on existing and future group access."); + if (expectedGrants != null && !expectedGrants.equals(grantState(group))) + throw new StoreException(StoreException.Kind.PRECONDITION); + 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) { + if (add) + throw org.busystack.caldav.management.FormValidation.conflict( + "username", "This account already belongs to the group. Review the current members."); + throw new StoreException(StoreException.Kind.PRECONDITION); + } + reconcileAffected(group); + jdbc.query("SELECT set_config('busystack.defer_dav_bindings','off',true)", rs -> {}); + audit.targeted( + actor, + add + ? org.busystack.caldav.security.audit.SecurityAudit.Action.GROUP_MEMBER_ADDED + : org.busystack.caldav.security.audit.SecurityAudit.Action.GROUP_MEMBER_REMOVED, + org.busystack.caldav.security.audit.SecurityAudit.Outcome.SUCCESS, + org.busystack.caldav.security.audit.SecurityAudit.TargetType.GROUP, + group, + member); + } + + private String grantState(UUID group) { + return jdbc.queryForObject( + "SELECT " + GRANT_STATE + " FROM collection_group_members c WHERE c.group_id=?", + String.class, + group); + } + + public MemberView member(Authentication auth, UUID group, UUID account) { + administrator(auth); + var rows = + 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 a.id=? + """, + (rs, row) -> + new MemberView( + rs.getObject(1, UUID.class), + rs.getString(2), + rs.getString(3), + rs.getBoolean(4)), + group, + account); + if (rows.isEmpty()) throw new StoreException(StoreException.Kind.NOT_FOUND); + return rows.getFirst(); + } + public record Grant( UUID collection, String collectionName, UUID group, String groupName, String permission) {} @@ -87,6 +317,20 @@ public List choices(Authentication authentication) { return List.copyOf(choices); } + public List eligibleGroups(Authentication auth, UUID collection) { + sessions.assertCurrent(auth); + return jdbc.query( + """ + SELECT g.id,g.name FROM sharing_groups g + WHERE NOT EXISTS ( + SELECT 1 FROM collection_group_members m WHERE m.collection_id=? AND m.group_id=g.id + ) + ORDER BY g.name,g.id LIMIT 1000 + """, + (rs, row) -> new Choice(rs.getObject(1, UUID.class), rs.getString(2)), + collection); + } + public List ownedGrants(Authentication authentication) { return ownedGrants(authentication, 0).rows(); } @@ -128,11 +372,14 @@ public UUID create(Authentication authentication, String name, Set usern for (UUID member : members) jdbc.update( "INSERT INTO sharing_group_members(group_id,account_id) VALUES (?,?)", id, member); - audit.record( + audit.targeted( actor, org.busystack.caldav.security.audit.SecurityAudit.Action.GROUP_CREATED, org.busystack.caldav.security.audit.SecurityAudit.Outcome.SUCCESS, + org.busystack.caldav.security.audit.SecurityAudit.TargetType.GROUP, + id, null); + audit.membershipDelta(actor, id, Set.of(), members); return id; } @@ -168,11 +415,14 @@ public void update( jdbc.update( "INSERT INTO sharing_group_members(group_id,account_id) VALUES (?,?)", group, member); jdbc.query("SELECT set_config('busystack.defer_dav_bindings','off',true)", rs -> {}); - reconcileAffected(group); - audit.record( + if (!Set.copyOf(existing).equals(desired)) reconcileAffected(group); + audit.membershipDelta(actor, group, Set.copyOf(existing), desired); + audit.targeted( actor, org.busystack.caldav.security.audit.SecurityAudit.Action.GROUP_UPDATED, org.busystack.caldav.security.audit.SecurityAudit.Outcome.SUCCESS, + org.busystack.caldav.security.audit.SecurityAudit.TargetType.GROUP, + group, null); } @@ -190,10 +440,12 @@ public void delete(Authentication authentication, UUID group) { reconcileAffected(group); jdbc.update("DELETE FROM sharing_groups WHERE id=?", group); jdbc.query("SELECT set_config('busystack.defer_dav_bindings','off',true)", rs -> {}); - audit.record( + audit.targeted( actor, org.busystack.caldav.security.audit.SecurityAudit.Action.GROUP_DELETED, org.busystack.caldav.security.audit.SecurityAudit.Outcome.SUCCESS, + org.busystack.caldav.security.audit.SecurityAudit.TargetType.GROUP, + group, null); } @@ -215,22 +467,24 @@ public void grant(Authentication authentication, UUID collection, UUID group, St group); else { if (!Set.of("READ", "WRITE").contains(permission)) - throw new IllegalArgumentException("Group permission must be READ, WRITE or REVOKE"); + throw org.busystack.caldav.management.FormValidation.field( + "permission", "Choose read-only, read and write, or remove the group grant."); jdbc.update( "INSERT INTO collection_group_members(collection_id,group_id,permission) VALUES (?,?,?) ON CONFLICT(collection_id,group_id) DO UPDATE SET permission=EXCLUDED.permission", collection, group, permission); } - audit.record( + audit.targeted( actor, org.busystack.caldav.security.audit.SecurityAudit.Action.GROUP_SHARING_CHANGED, org.busystack.caldav.security.audit.SecurityAudit.Outcome.SUCCESS, + org.busystack.caldav.security.audit.SecurityAudit.TargetType.GROUP, + group, null); } private UUID administrator(Authentication authentication) { - RecentAuthentication.requireMfa(authentication); var actor = sessions.assertCurrent(authentication); if (!Boolean.TRUE.equals( jdbc.queryForObject( @@ -250,7 +504,8 @@ private Set accounts(Set usernames) { jdbc.queryForList( "SELECT id FROM accounts WHERE username=? AND enabled", UUID.class, username); if (found.size() != 1) - throw new IllegalArgumentException("Every group member must name an active account"); + throw org.busystack.caldav.management.FormValidation.field( + "username", "Enter the exact username of an active account."); members.add(found.getFirst()); } return Set.copyOf(members); @@ -293,12 +548,15 @@ private void uniqueName(String name, UUID except) { Boolean.class, name, except, - except))) throw new IllegalArgumentException("Group name is already in use"); + except))) + throw org.busystack.caldav.management.FormValidation.conflict( + "name", "This group name is already in use. Choose another name."); } private static void validateName(String name) { if (name == null || name.isBlank() || name.length() > 200 || !XmlCharacters.valid(name)) - throw new IllegalArgumentException("Group name must contain 1–200 characters"); + throw org.busystack.caldav.management.FormValidation.field( + "name", "Use a group name of 1–200 characters."); } private static void limit() { diff --git a/src/main/java/org/busystack/caldav/storage/DavStore.java b/src/main/java/org/busystack/caldav/storage/DavStore.java index 07831a8..e49698a 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); @@ -132,7 +144,7 @@ public Entry create( DavNamespace.binding(path, component != null); checkDisplayName(displayName); lockHomes(home); - if (component != null && !Set.of("VEVENT", "VTODO").contains(component)) + if (component != null && !CalendarContent.supportsCollectionComponent(component)) throw new IllegalArgumentException("Unsupported calendar component"); requireFolder(actor, home, parent(path)); if (bindingExists(home, path)) throw new StoreException(StoreException.Kind.EXISTS); diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index daccb1e..68df876 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: 64MB + max-request-size: 65MB + file-size-threshold: 0 mvc: log-request-details: false dispatch-options-request: true @@ -50,6 +55,7 @@ server: http-only: true same-site: lax tomcat: + max-part-count: 4 max-http-form-post-size: 64KB max-swallow-size: 1MB connection-timeout: 10s diff --git a/src/main/resources/db/migration/V14__administrative_audit_targets.sql b/src/main/resources/db/migration/V14__administrative_audit_targets.sql new file mode 100644 index 0000000..6e66f25 --- /dev/null +++ b/src/main/resources/db/migration/V14__administrative_audit_targets.sql @@ -0,0 +1,11 @@ +-- Opaque administrative targets survive deletion of the target resource. Historical rows +-- intentionally remain unclassified. No names, calendar metadata, secrets or free text. +ALTER TABLE security_audit + ADD COLUMN target_type varchar(16), + ADD COLUMN target_id uuid, + ADD COLUMN related_account_id uuid, + ADD CONSTRAINT security_audit_target CHECK ( + (target_type IS NULL AND target_id IS NULL AND related_account_id IS NULL) + OR (target_type IS NOT NULL AND target_type IN ('ACCOUNT','GROUP') AND target_id IS NOT NULL + AND (related_account_id IS NULL OR target_type='GROUP')) + ); 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..1db8961 --- /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 AND NOT initialized; + RETURN NEW; +END; +$$; +CREATE TRIGGER close_initialization BEFORE INSERT ON accounts +FOR EACH ROW EXECUTE FUNCTION close_initialization(); diff --git a/src/main/resources/db/migration/V16__bounded_group_join_plans.sql b/src/main/resources/db/migration/V16__bounded_group_join_plans.sql new file mode 100644 index 0000000..e003fc1 --- /dev/null +++ b/src/main/resources/db/migration/V16__bounded_group_join_plans.sql @@ -0,0 +1,7 @@ +-- A plan cached while a group is small can retain one-row estimates after bulk +-- growth. Nested-loop scans in the binding INSERT then rescan the growing target +-- relation and can exceed the unchanged thirty-second mutation deadline. +-- These set-based equality joins support hash/merge plans. Scope the planner +-- preference to this first-party function; PostgreSQL restores the caller's +-- setting on both successful return and error. No permissions or data change. +ALTER FUNCTION dav_reconcile_group_memberships(uuid) SET enable_nestloop = off; diff --git a/src/main/resources/db/migration/V17__journal_collections.sql b/src/main/resources/db/migration/V17__journal_collections.sql new file mode 100644 index 0000000..718fdc6 --- /dev/null +++ b/src/main/resources/db/migration/V17__journal_collections.sql @@ -0,0 +1,3 @@ +ALTER TABLE collections DROP CONSTRAINT collections_component_check; +ALTER TABLE collections ADD CONSTRAINT collections_component_check + CHECK (component IN ('VEVENT', 'VTODO', 'VJOURNAL')); diff --git a/src/main/resources/db/migration/V18__browser_issuance_intents.sql b/src/main/resources/db/migration/V18__browser_issuance_intents.sql new file mode 100644 index 0000000..a986260 --- /dev/null +++ b/src/main/resources/db/migration/V18__browser_issuance_intents.sql @@ -0,0 +1,18 @@ +ALTER TABLE accounts ADD COLUMN recovery_code_generation uuid; + +CREATE TABLE browser_issuance_intents ( + id uuid PRIMARY KEY, + account_id uuid NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, + security_epoch uuid NOT NULL, + purpose text NOT NULL CHECK (purpose IN ('APPLICATION_PASSWORD', 'RECOVERY_CODES')), + context varchar(64) NOT NULL, + expected_generation uuid, + expires_at timestamptz NOT NULL, + consumed_at timestamptz, + result_id uuid, + CHECK (result_id IS NULL OR consumed_at IS NOT NULL) +); + +CREATE INDEX browser_issuance_intents_expiry ON browser_issuance_intents (expires_at); +CREATE INDEX browser_issuance_intents_account_pending + ON browser_issuance_intents (account_id) WHERE consumed_at IS NULL; diff --git a/src/main/resources/db/migration/V19__browser_navigation_flows.sql b/src/main/resources/db/migration/V19__browser_navigation_flows.sql new file mode 100644 index 0000000..6492db5 --- /dev/null +++ b/src/main/resources/db/migration/V19__browser_navigation_flows.sql @@ -0,0 +1,9 @@ +-- Short-lived browser flows share a stable scope through legitimate session rotation. +CREATE TABLE browser_flow_state ( + scope varchar(128) NOT NULL, + section varchar(32) NOT NULL, + payload text NOT NULL CHECK (octet_length(payload) <= 262144), + expires_at timestamptz NOT NULL, + PRIMARY KEY (scope, section) +); +CREATE INDEX browser_flow_state_expiry ON browser_flow_state(expires_at); diff --git a/src/main/resources/static/assets/account.css b/src/main/resources/static/assets/account.css index 2f869bf..b13d225 100644 --- a/src/main/resources/static/assets/account.css +++ b/src/main/resources/static/assets/account.css @@ -1,3 +1,766 @@ -: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} +: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); + overflow-wrap:anywhere; +} +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,.button.secondary { + background:var(--surface); + color:var(--accent); + border-color:var(--border); +} +button.danger,.button.danger { + background:var(--danger); +} +button:disabled { + cursor:default; + 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,.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 { + min-width:0; + 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 { + position:relative; + width:100%; + min-width:0; + max-width:100%; + overflow-x:auto; +} +.table-scroll table { + min-width:40rem; + overflow-wrap:normal; +} +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; + flex-wrap:wrap; + gap:.5rem; + align-items:center; +} +.copy-field input { + flex:1 1 12rem; + min-width:0; + max-width:none; +} +.copy-field button { + flex:0 0 auto; + max-width:100%; + overflow-wrap:normal; +} +.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,.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; + } +} +@media(min-width:651px) { + .table-help { + display:none; + } +} +.field-error { + font-weight: 600; + margin-top: .25rem; +} +[aria-invalid="true"] { + border: 2px solid var(--danger, #9b2828); +} +.error-summary:focus { + outline: 3px solid currentColor; + 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} +[hidden] { + display: none !important; +} + +:root { + --rail-width: 15rem; + --space-sm: .5rem; + --space: 1rem; + --space-lg: 1.5rem; + --focus: #a05400; +} + +:focus-visible { + outline-color: var(--focus); +} + +.area-switch, +.actions, +.resource-list li { + display: flex; + gap: var(--space); + flex-wrap: wrap; + align-items: center; +} + +.area-switch span { + color: var(--muted); + font-weight: 650; +} + +.section-disclosure { + margin: 0; + padding: 0 var(--space); +} + +.section-disclosure > summary { + min-height: 44px; + width: fit-content; + padding-inline: var(--space-sm); +} + +.section-nav { + padding: var(--space-sm) 0 var(--space); + align-items: stretch; + gap: .25rem; +} + +.section-nav a { + display: flex; + align-items: center; + min-height: 44px; + font-size: 1rem; + padding: var(--space-sm) var(--space); +} + +.section-nav [aria-current=page] { + border-inline-start: 3px solid var(--accent); +} + +main > form:not(.filters), +section > form:not(.filters) { + max-width: 40rem; +} + +.notice.info { + background: var(--surface); + border-inline-start-color: var(--input-border); +} + +.notice.warning { + background: var(--warning); +} + +.resource-list { + margin: 0 0 var(--space-lg); + padding: 0; + list-style: none; +} + +.resource-list li { + justify-content: space-between; + padding: var(--space-sm) 0; + border-bottom: 1px solid var(--border); +} + +.resource-list li a { + font-weight: 650; +} + +fieldset { + min-inline-size: 0; + border: 1px solid var(--border); + border-radius: .4rem; + padding: var(--space); +} + +fieldset label { + min-height: 44px; + margin: 0; + display: flex; + gap: var(--space-sm); + align-items: center; +} + +[aria-current=true] { + font-weight: 750; +} + +@media (min-width: 58rem) { + body:has(> .application-shell) { + display: grid; + grid-template-columns: minmax(var(--rail-width), 1fr) minmax(0, 72rem) minmax(0, 1fr); + grid-template-rows: auto auto 1fr auto; + min-height: 100vh; + } + + .application-shell { + display: contents; + } + + .application-shell > .brand-row { + grid-column: 1 / -1; + background: var(--surface); + border-bottom: 1px solid var(--border); + width: 100%; + max-width: none; + margin: 0; + padding: .5rem var(--space-lg); + } + + .application-shell > .section-disclosure { + grid-column: 1; + grid-row: 3; + justify-self: end; + width: var(--rail-width); + border-inline-end: 1px solid var(--border); + padding: var(--space-lg) var(--space); + } + + .section-disclosure > summary { + display: none; + } + + .section-nav { + display: grid; + padding: 0; + } + + body:has(> .application-shell) > main { + grid-column: 2; + grid-row: 3; + margin: 0; + min-width: 0; + width: 100%; + } + + body:has(> .application-shell) > footer { + grid-column: 2; + grid-row: 4; + width: 100%; + margin: 0; + } +} + +@media (prefers-color-scheme: dark) { + :root { + --focus: #f1b761; + } +} + +@media (forced-colors: active) { + .section-nav [aria-current=page], + [aria-invalid=true], + .notice { + border-color: CanvasText; + } + + :focus-visible { + outline-color: Highlight; + } +} + +.session-warning { + grid-row: 2; + grid-column: 2; + align-self: start; + justify-self: start; + margin: .75rem; + max-width: min(32rem, calc(100vw - 2rem)); +} + +.session-warning p { + margin-top: 0; +} + +.audit-table td details { + margin: .25rem 0 0; +} diff --git a/src/main/resources/static/assets/portal.js b/src/main/resources/static/assets/portal.js new file mode 100644 index 0000000..582c949 --- /dev/null +++ b/src/main/resources/static/assets/portal.js @@ -0,0 +1,221 @@ +'use strict'; +document.querySelectorAll('[data-copy]').forEach(button => { + button.addEventListener('click', async () => { + const target = document.getElementById(button.dataset.copy); + 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 = button.dataset.copyMessage || (button.dataset.copy.includes('username') ? 'Username copied.' : button.dataset.copy === 'issued-secret' ? 'Password copied.' : 'Server address copied.'); + } catch { + status.textContent = 'Copy failed. Select the text and use your browser’s Copy command.'; + } + }); +}); + +const errorSummary = document.querySelector('[data-error-summary]'); +if (errorSummary) { + errorSummary.focus(); + errorSummary.querySelectorAll('a[href^="#"]').forEach(link => link.addEventListener('click', event => { + const field = document.getElementById(link.hash.slice(1)); + if (field) { event.preventDefault(); field.closest('details')?.setAttribute('open', ''); field.focus(); } + })); +} + +const oneTimeReturn = document.querySelector('[data-one-time-return]'); +if (oneTimeReturn) { + window.addEventListener('pagehide', () => { + document.querySelectorAll('[data-one-time-secret]').forEach(node => { + node.replaceChildren(document.createTextNode('The secret is no longer displayed.')); + }); + }); + window.addEventListener('pageshow', event => { + if (event.persisted) window.location.replace(oneTimeReturn.href); + }); +} + +document.querySelectorAll('form[data-single-submit]').forEach(form => { + let submitted = false; + const button = form.querySelector('button[type="submit"], button:not([type])'); + const original = button?.textContent; + form.addEventListener('submit', event => { + if (event.defaultPrevented) return; + if (submitted) { event.preventDefault(); return; } + submitted = true; + if (button) { button.disabled = true; button.textContent = form.dataset.singleSubmit; } + form.setAttribute('aria-busy', 'true'); + }); + window.addEventListener('pageshow', event => { + if (!event.persisted) return; + submitted = false; + if (button) { button.disabled = false; button.textContent = original; } + form.removeAttribute('aria-busy'); + }); +}); + +const menu = document.querySelector('.section-disclosure'); +if (menu) { + const desktop = window.matchMedia('(min-width: 58rem)'); + const updateMenu = () => { menu.open = desktop.matches; }; + desktop.addEventListener('change', updateMenu); + updateMenu(); + menu.addEventListener('keydown', event => { + if (event.key === 'Escape' && menu.open && !desktop.matches) { + menu.open = false; + menu.querySelector('summary').focus(); + } + }); +} + +document.querySelectorAll('[data-password-policy]').forEach(form => { + const password = form.elements.password; + const confirmation = form.elements.confirmation; + const show = form.querySelector('[data-show-password]'); + if (show) { + show.hidden = false; + show.addEventListener('click', () => { + const visible = password.type === 'password'; + password.type = visible ? 'text' : 'password'; + if (confirmation) confirmation.type = password.type; + show.textContent = visible ? 'Hide passwords' : 'Show passwords'; + }); + } + + let localSummary; + let localMessage; + let invalidField; + let originalDescription; + let originalInvalid; + const clear = () => { + if (!invalidField) return; + if (originalDescription == null) invalidField.removeAttribute('aria-describedby'); + else invalidField.setAttribute('aria-describedby', originalDescription); + if (originalInvalid == null) invalidField.removeAttribute('aria-invalid'); + else invalidField.setAttribute('aria-invalid', originalInvalid); + localSummary.remove(); + localMessage.remove(); + invalidField = null; + }; + [password, confirmation].filter(Boolean).forEach(field => field.addEventListener('input', clear)); + form.addEventListener('submit', event => { + clear(); + let message; + if ([...password.value].length < 14 || new TextEncoder().encode(password.value).length > 72 + || /[\uD800-\uDFFF]/u.test(password.value)) { + invalidField = password; + message = 'Use at least 14 Unicode characters and at most 72 UTF-8 bytes.'; + } else if (confirmation && confirmation.value !== password.value) { + invalidField = confirmation; + message = 'Enter the same password in both fields.'; + } + if (!invalidField) return; + event.preventDefault(); + localSummary = document.createElement('div'); + localSummary.className = 'notice error-summary'; + localSummary.tabIndex = -1; + localSummary.setAttribute('role', 'alert'); + const heading = document.createElement('h2'); + heading.textContent = 'Check the submitted details'; + const link = document.createElement('a'); + link.href = '#' + invalidField.id; + link.textContent = message; + link.addEventListener('click', event => { + event.preventDefault(); + invalidField?.focus(); + }); + localSummary.append(heading, link); + form.before(localSummary); + localMessage = document.createElement('p'); + localMessage.className = 'field-error'; + localMessage.id = invalidField.id + '-local-error'; + localMessage.textContent = message; + const anchor = invalidField.closest('label') || invalidField; + anchor.after(localMessage); + originalDescription = invalidField.getAttribute('aria-describedby'); + originalInvalid = invalidField.getAttribute('aria-invalid'); + invalidField.setAttribute('aria-invalid', 'true'); + invalidField.setAttribute('aria-describedby', [originalDescription, localMessage.id].filter(Boolean).join(' ')); + localSummary.focus(); + }); +}); + +document.querySelectorAll('[data-collection-type]').forEach(form => { + const heading = document.getElementById('creation-title'); + const submit = form.querySelector('button[type=submit]'); + const titles = {VEVENT: 'Create calendar', VTODO: 'Create task list', VJOURNAL: 'Create journal'}; + const update = () => { + const title = titles[form.elements.component.value] || 'Create a resource'; + heading.textContent = title; + submit.textContent = title; + }; + form.addEventListener('change', update); + update(); +}); + +document.querySelectorAll('[data-resource-color]').forEach(form => { + const button = form.querySelector('[data-color-picker]'); + const picker = form.querySelector('input[type=color]'); + button.hidden = false; + button.addEventListener('click', () => { + picker.hidden = false; + const color = form.elements.color.value; + if (/^#[\da-f]{6}([\da-f]{2})?$/i.test(color)) picker.value = color.slice(0, 7); + picker.focus(); + }); + picker.addEventListener('change', () => { + const alpha = /^#[\da-f]{8}$/i.test(form.elements.color.value) ? form.elements.color.value.slice(7) : ''; + form.elements.color.value = picker.value + alpha; + }); +}); + +const sessionWarning = document.querySelector('[data-session-warning]'); +if (sessionWarning) { + const stay = sessionWarning.querySelector('[data-session-stay]'); + const message = sessionWarning.querySelector('[data-session-message]'); + let idle = Number(sessionWarning.dataset.idle); + let overall = Number(sessionWarning.dataset.overall); + let offset = Number(sessionWarning.dataset.server) - Date.now(); + let timer; + const update = () => { + clearTimeout(timer); + const remaining = Math.min(idle, overall) - (Date.now() + offset); + sessionWarning.hidden = remaining > 120000; + if (remaining > 120000) { + timer = setTimeout(update, remaining - 120000); + return; + } + stay.hidden = overall <= idle || remaining <= 0; + message.textContent = remaining <= 0 ? 'This browser session may have ended. Sign in to continue.' + : overall <= idle ? 'Your eight-hour sign-in limit is approaching. Sign in again to continue your work.' + : 'Your browser session may end soon due to inactivity.'; + if (remaining > 0) timer = setTimeout(update, remaining); + }; + stay.addEventListener('click', async () => { + stay.disabled = true; + try { + const response = await fetch(sessionWarning.dataset.stay, { + method: 'POST', cache: 'no-store', credentials: 'same-origin', + headers: {'X-CSRF-TOKEN': sessionWarning.dataset.csrf, 'Accept': 'application/json'} + }); + if (!response.ok || response.redirected) throw new Error(); + const deadlines = await response.json(); + idle = deadlines.idleDeadline; + overall = deadlines.overallDeadline; + offset = deadlines.serverTime - Date.now(); + update(); + } catch { + message.textContent = 'BusyStack could not extend this session. Sign in again to continue.'; + stay.hidden = true; + } finally { + stay.disabled = false; + if (sessionWarning.hidden) document.getElementById('main')?.focus(); + } + }); + update(); +} diff --git a/src/main/resources/static/assets/security.js b/src/main/resources/static/assets/security.js index 4db4965..7cd016a 100644 --- a/src/main/resources/static/assets/security.js +++ b/src/main/resources/static/assets/security.js @@ -1,31 +1,76 @@ 'use strict'; (() => { const status = document.getElementById('security-status'); + if (!status || !document.querySelector('meta[name=csrf-token]')) 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 password 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 === 'NotReadableError') return 'The authenticator could not be accessed. Check that your passkey provider or device is available, then try again.'; + 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; }); + if (button.closest('[hidden]')) document.getElementById('authenticate-passkey')?.focus(); + else button.focus(); + } }); } + function registered() { + document.getElementById('enrollment-stage').hidden = true; + document.getElementById('registration-success').hidden = false; + status.textContent = 'Passkey saved. Verification needed.'; + } const register = document.getElementById('register-passkey'); if (register) run(register, async base => { const options = await call(base, 'webauthn/register/options', 'POST'); @@ -36,10 +81,34 @@ 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(); } }); + let lastReconciliation = 0; + if (register && document.getElementById('enrollment-stage')) { + window.addEventListener('focus', async () => { + if (busy || register.closest('[hidden]') || Date.now() - lastReconciliation < 1500) return; + lastReconciliation = Date.now(); + try { + if ((await call(register.dataset.context, 'auth/state', 'GET')).enrolled) { + registered(); + document.getElementById('authenticate-passkey')?.focus(); + } + } catch { /* The visible action remains available. */ } + }); + } const authenticate = document.getElementById('authenticate-passkey'); if (authenticate) run(authenticate, async base => { const options = await call(base, 'webauthn/authenticate/options', 'POST'); @@ -47,19 +116,32 @@ for (const credential of options.allowCredentials || []) credential.id = decode(credential.id); const credential = await navigator.credentials.get({publicKey: options}); const response = credential.response; - const result = await call(base, 'login/webauthn', 'POST', {id: credential.id, rawId: encode(credential.rawId), type: credential.type, + const flow = encodeURIComponent(authenticate.dataset.flow || ''); + let result; + try { + result = await call(base, 'login/webauthn?flow=' + flow, 'POST', {id: credential.id, rawId: encode(credential.rawId), type: credential.type, response: {authenticatorData: encode(response.authenticatorData), clientDataJSON: encode(response.clientDataJSON), signature: encode(response.signature), userHandle: response.userHandle ? encode(response.userHandle) : null}, clientExtensionResults: credential.getClientExtensionResults(), authenticatorAttachment: credential.authenticatorAttachment}); + } catch (error) { + try { + if ((await call(base, 'auth/state', 'GET')).verified) { + window.location.assign(base + 'auth/continue?flow=' + flow); + return; + } + } catch { /* Keep the original failure if the server cannot confirm the outcome. */ } + throw error; + } 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')); }); })(); diff --git a/src/main/resources/templates/account-detail.html b/src/main/resources/templates/account-detail.html new file mode 100644 index 0000000..16c26c4 --- /dev/null +++ b/src/main/resources/templates/account-detail.html @@ -0,0 +1,18 @@ + + +
+ +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.

+
+

Give the user their sign-in instructions

+

Share the initial password separately through a trusted channel. The user creates and verifies their own passkey at first sign-in.

+ + + +
+

Edit profile

+

+ Disable account +

+
diff --git a/src/main/resources/templates/account-disable.html b/src/main/resources/templates/account-disable.html new file mode 100644 index 0000000..6990e4a --- /dev/null +++ b/src/main/resources/templates/account-disable.html @@ -0,0 +1,13 @@ + + + +
+
+

+

This ends the account’s browser sessions and revokes application passwords and authorized app access. Stored resource contents and memberships are retained. An operator must use offline recovery to enable the account again.

+
+ + + Cancel +
+
diff --git a/src/main/resources/templates/account-error.html b/src/main/resources/templates/account-error.html index 36cb948..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 new file mode 100644 index 0000000..90c85f8 --- /dev/null +++ b/src/main/resources/templates/account-new.html @@ -0,0 +1,7 @@ + + +
+ +Back to accounts

Create an account

Create a local user account, then give the user the initial password securely. 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..004a514 --- /dev/null +++ b/src/main/resources/templates/accounts.html @@ -0,0 +1,14 @@ + + +
+ +
Server administration

Accounts

Create users and manage account status.

Create account
+
+Clear 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..1650a18 100644 --- a/src/main/resources/templates/administration.html +++ b/src/main/resources/templates/administration.html @@ -1,2 +1,27 @@ -BusyStack administration

Administration

Your account

OAuth client registration

Server diagnostics

Sharing groups

Accounts

  • · · administrator · disabled

Provision an account

+ +
+ +
+

Server administration

+ Create account +
+
+

Accounts and resources

+
+
Enabled accounts
+
Disabled accounts
+
Groups
+
Calendars
+
Task lists
+
Journals
+
Stored UID series
+
+
+
+

Deployment

+

+

HTTP 5xx responses observed since startup.

+ Open system diagnostics +
+
diff --git a/src/main/resources/templates/audit.html b/src/main/resources/templates/audit.html new file mode 100644 index 0000000..43be941 --- /dev/null +++ b/src/main/resources/templates/audit.html @@ -0,0 +1,30 @@ + + +
+ +Server administration

Security & audit

Recorded security metadata is retained for up to thirty days and approximately ten thousand rows. Target names are current directory labels. Details show the recorded references.

Registered applications

+
+

No retained events match these filters.

+ + + + + + + + +
Recorded security events
Time (UTC)EventActorTargetOutcome
+ + +
Recorded references +
+
Event code
+
Outcome code
+
Actor ID
+
+
Membership account ID
+
+
+
+ +
diff --git a/src/main/resources/templates/collection-delete.html b/src/main/resources/templates/collection-delete.html new file mode 100644 index 0000000..7b9d4e1 --- /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..9775a11 --- /dev/null +++ b/src/main/resources/templates/collection-new.html @@ -0,0 +1,17 @@ + + +
+ +Back to collections

Create a resource

The resource type stays fixed after creation.

+
+ Resource type + + + +

+
+

Enter #RRGGBB or #RRGGBBAA. The last two digits specify opacity.

+ +
+ +
diff --git a/src/main/resources/templates/collection-sharing.html b/src/main/resources/templates/collection-sharing.html new file mode 100644 index 0000000..ef89ae2 --- /dev/null +++ b/src/main/resources/templates/collection-sharing.html @@ -0,0 +1,16 @@ + + +
+ +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.

+

Only you have access to this resource.

+

Share with a person

Accounts with direct grants
UsernameDirect grantEffective accessChange grant
· disabled

Remove direct grant
+ +
Grant access to an account

Enter the exact username supplied by the recipient. Ask the person for their BusyStack username.

+

Share with a group

Groups with grants for this collection
GroupGrantChange grant

Remove group grant
+ +
Grant access to a group

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

No additional groups are available for sharing. Create a groupAsk an administrator to create a group.

+

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..90ba2b6 --- /dev/null +++ b/src/main/resources/templates/collection.html @@ -0,0 +1,30 @@ + + +
+ +Back to collections +
+

Import and export

+

+

There is nothing to export yet. When someone with write access adds items, you can export them here.

+ +
+

Settings

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.

+
+ CalDAV address + +
+
+

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

Calendars, tasks & journals

Manage your resources and sharing. Use a compatible app to edit the contents.

+ Create a resource +
+ +
+ + + + Clear search +
+
+

+

An owner can share a resource using your username.

+

+ You can also import existing data into a destination you create. +

+
+
+ + + + + + + + + +
Available resources
NameTypeOwnerAccess
+
+ +
diff --git a/src/main/resources/templates/confirm-action.html b/src/main/resources/templates/confirm-action.html new file mode 100644 index 0000000..786aed1 --- /dev/null +++ b/src/main/resources/templates/confirm-action.html @@ -0,0 +1,15 @@ + + + +
+
+

+

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

Connect an app

+
+

Choose your app

+ +

Use a separate BusyStack application password for each app or device. Supported registered applications can use browser authorization instead.

+
+ +

Choose another app

+
+

Application password

+

Your app uses a separate password from your browser sign-in. Set up a new one for this app or use an existing application password.

+ +
+
+
+
+
+
+ Individual resource addresses +

There are no resources on this page. You can connect an app before you create or receive a resource.

+
+ +
+ + +
+
+ +
+
+ Troubleshooting +

Check the configured address, username, credential expiry and whether the resource is visible under Calendars, tasks & journals. Ask your operator about TLS certificate or proxy problems.

+

Strict synchronization-depth mode is enabled. The tested Thunderbird and python-caldav versions require the deployment’s Depth: 1 accommodation.

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

Application passwords

Create a separate password for each app or device. BusyStack shows the original password once.

+ +

Create application password

+

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

You have no application passwords on this page.

Credential metadata
LabelCreatedExpiresStatusAction
Revoke
+ +
diff --git a/src/main/resources/templates/dashboard.html b/src/main/resources/templates/dashboard.html index 8660681..0080c45 100644 --- a/src/main/resources/templates/dashboard.html +++ b/src/main/resources/templates/dashboard.html @@ -1,15 +1,44 @@ -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

-
+ + + +
+
+ +

Overview

+

That task request ended. Open the task again to continue.

+

Signed in as ().

+
+

Start with a calendar, task list or journal

+

Use a compatible CalDAV app to edit events, tasks and journal entries. Resources shared with you will also appear here.

+ +
+
+

+
    +
  • + + +
  • +
+ +
+
+

Server administration

+

Manage accounts and groups, review audit events and check deployment diagnostics.

+ +
+

Prepare recovery codes in case you lose access to your passkey.

+
+
+ + diff --git a/src/main/resources/templates/diagnostics.html b/src/main/resources/templates/diagnostics.html index df5f75f..3d9c341 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 (HTTP 5xx)
Mean duration (ms)
Recent maximum (ms)

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

+

Recent operational problems

No recent server errors recorded. The bounded list clears when the process restarts.

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

Troubleshooting

Setup and recovery help · Operator guide in the deployment folder at docs/operations.md

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/enroll-passkey.html b/src/main/resources/templates/enroll-passkey.html new file mode 100644 index 0000000..3299446 --- /dev/null +++ b/src/main/resources/templates/enroll-passkey.html @@ -0,0 +1,17 @@ + +Sign in · BusyStack + + +
+
+

Create a passkey

+

This task request ended. Verify your sign-in, then open the task again.

+

Your browser will show the available options on this device, such as a password manager, device unlock, a phone or a security key.

+ +
+ +

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/400.html b/src/main/resources/templates/error/400.html new file mode 100644 index 0000000..551feda --- /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..796b82c 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.

Your session may have ended or account access may have been revoked. Sign in again; if access remains unavailable, contact your administrator.

Check sign-in · 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..f116ca6 --- /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/413.html b/src/main/resources/templates/error/413.html new file mode 100644 index 0000000..c72a3d1 --- /dev/null +++ b/src/main/resources/templates/error/413.html @@ -0,0 +1 @@ +

Upload too large

Import files are limited to 64 MiB. Each UID series must fit within the existing 1 MiB resource limit. Supported BusyStack exports fit this upload limit. Review the supported file and item limits before trying again.

diff --git a/src/main/resources/templates/error/500.html b/src/main/resources/templates/error/500.html new file mode 100644 index 0000000..da9c89f --- /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..20e9785 --- /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/connection.html b/src/main/resources/templates/fragments/connection.html new file mode 100644 index 0000000..9ce5afe --- /dev/null +++ b/src/main/resources/templates/fragments/connection.html @@ -0,0 +1,49 @@ + + + +
+

Connection settings

+ +
+ + +
+
+ +
+ + +
+
+ +
+ + +
+
+ +
+ + +
+
+
+
+

+
    +
  1. Open the Calendar tab. Choose New Calendar → On the Network.
  2. +
  3. Enter your username and the server address as Location. Leave This location doesn’t require credentials unchecked, then choose Find Calendars.
  4. +
  5. Enter your BusyStack application password in Thunderbird’s password prompt.
  6. +
  7. Choose CalDAV, select the calendars and task lists you need, then choose Subscribe. Use Thunderbird’s task view for tasks.
  8. +
+
    +
  1. Open Manage Calendars → Add Calendar. GNOME Calendar manages events.
  2. +
  3. Paste the GNOME connection address into Connect to an Online Calendar. The address includes your username.
  4. +
  5. In Credentials, enter your username and application password. Select Connect, then Add Calendar once the address validates.
  6. +
  7. Use the same application password if GNOME prompts again during synchronization.
  8. +
+

Choose CalDAV with password authentication using the configured server address. Enter your username and a BusyStack application password. Discovery can find resources you own or can access by sharing. Select an app that supports the resource types you need.

+

Refresh in your app and check that the expected resources appear. For a writable resource, create a test item and check that it synchronizes before adding important data.

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

+
+

+ + +
BusyStack · Your server. Your data.Manage events, tasks and journal entries in your CalDAV apps.

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

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

+

Add a member

+

+

Find an account

+

Current members

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

Group members — 50 per page
AccountDisplay nameStatusMembership
Remove member
+
Rename group

+

Delete group

+
diff --git a/src/main/resources/templates/group-error.html b/src/main/resources/templates/group-error.html index 02b8fc3..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/group-member-lookup.html b/src/main/resources/templates/group-member-lookup.html new file mode 100644 index 0000000..333c6fb --- /dev/null +++ b/src/main/resources/templates/group-member-lookup.html @@ -0,0 +1,21 @@ + + + +
+
+ Back to group +

+
+ + +
+

No eligible enabled accounts on this page. Existing members are listed on the group page.

+
    +
  • + + Enabled +
  • +
+ +
diff --git a/src/main/resources/templates/group-new.html b/src/main/resources/templates/group-new.html new file mode 100644 index 0000000..9f284a9 --- /dev/null +++ b/src/main/resources/templates/group-new.html @@ -0,0 +1,15 @@ + + + +
+
+ Back to sharing + Back to groups +

Create group

+

After creating the group, return to sharing to decide whether to grant access.

+

The original resource is no longer available for sharing. You can still create a group here.

+

Group membership lets resource owners share access with many accounts at once.

+ +

+ +
diff --git a/src/main/resources/templates/groups.html b/src/main/resources/templates/groups.html index f0b40a7..cd536fe 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 group +
+

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..408763e --- /dev/null +++ b/src/main/resources/templates/import-report.html @@ -0,0 +1,9 @@ + + +
+ +Back to destination

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

+ +
diff --git a/src/main/resources/templates/issuance-receipt.html b/src/main/resources/templates/issuance-receipt.html new file mode 100644 index 0000000..54a9302 --- /dev/null +++ b/src/main/resources/templates/issuance-receipt.html @@ -0,0 +1,15 @@ + + + + +
+
+

Issuance result

+

+

Credential reference

+ Review recovery settings + Review application passwords +
+
+ + diff --git a/src/main/resources/templates/issued-credential.html b/src/main/resources/templates/issued-credential.html index 8a2a78c..0520d8a 100644 --- a/src/main/resources/templates/issued-credential.html +++ b/src/main/resources/templates/issued-credential.html @@ -1,2 +1,19 @@ -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

+ + +
+
+

Application password created

+

Keep this page open while you configure your app. BusyStack displays the password once.

+
+

+

Expires .

+
+
Application password
+ +
+
+
+
+

Done

+
diff --git a/src/main/resources/templates/login.html b/src/main/resources/templates/login.html index 6df2fe7..e298fe9 100644 --- a/src/main/resources/templates/login.html +++ b/src/main/resources/templates/login.html @@ -1,15 +1,18 @@ - -Sign in · BusyStack +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 failed. Check your account details.

-

Sign in with your organization's identity provider

-

- -

-

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

-

Account management

-
+ +
+

Sign in to BusyStack

Enter your account details to continue.

+

Enter your current sign-in details, then verify your passkey to return to your task.

+

Password changed. Sign in with your new password.

+

Recovery completed. Sign in again, then create a new passkey.

+

Your browser session ended. Sign in again.

+ +

This sign-in request ended. After signing in, open the task again.

+

This identity-link request ended. Sign in and verify your passkey, then start a new link from Security.

+

Sign in with your organization's identity provider

+

Your organization manages sign-in. Use the identity provider link above.

+
+

Setup and account recovery help

+

diff --git a/src/main/resources/templates/oauth-clients.html b/src/main/resources/templates/oauth-clients.html index dc50f6a..8660998 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

+ +

Registered applications

Back to Security & audit

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.

-
+

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

+
Registered applications
Client IDNameRedirectsAction
Remove registration
+

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..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 4ac8f54..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 91f6d8d..c082a07 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

-

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.

-
+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 primary sign-in and passkey verification within ten minutes. Applications must sign in again after thirty days.

+
Authorization grants
ApplicationAuthorizedExpiresRevokedAction
()Revoke access

No OAuth applications have been authorized.

+
diff --git a/src/main/resources/templates/passkey-remove.html b/src/main/resources/templates/passkey-remove.html new file mode 100644 index 0000000..285d3f0 --- /dev/null +++ b/src/main/resources/templates/passkey-remove.html @@ -0,0 +1,19 @@ + + + + +
+
+

+

Any browser session verified with this passkey will need to verify again.

+

This is your last passkey. Add a replacement first, or remove it and create and verify a new one before you return to your account.

+
+ + Add a replacement first + Cancel +
+

+
+ +
+ diff --git a/src/main/resources/templates/passkeys.html b/src/main/resources/templates/passkeys.html index 3e3816f..dde8e1b 100644 --- a/src/main/resources/templates/passkeys.html +++ b/src/main/resources/templates/passkeys.html @@ -1,13 +1,14 @@ 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.

+

Confirm it’s you to add a passkey

+
+
+

- -
Registered passkeys
NameCreatedLast usedAction
-

Verify another factor · Account management

-
+
+
Registered passkeys
NameCreatedLast usedAction
Remove
+ +
diff --git a/src/main/resources/templates/password.html b/src/main/resources/templates/password.html index a799dca..51128c0 100644 --- a/src/main/resources/templates/password.html +++ b/src/main/resources/templates/password.html @@ -1,2 +1,26 @@ -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.

+ + +
+
+ Back to Security +

+

Your organization manages primary sign-in. Change your password with its identity provider.

+ +

Changing your password ends browser sessions and revokes application passwords, authorized app grants and recovery codes. Your passkeys remain registered.

+ +
+ + +

Use at least 14 Unicode characters and at most 72 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..a25f3cd --- /dev/null +++ b/src/main/resources/templates/portability.html @@ -0,0 +1,8 @@ + + +
+ +My account

Import iCalendar

Review your latest import preview or results

Move your events, tasks and journal entries using iCalendar files. No invitations, alarms or outbound messages are executed by import.

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 resource

Confirm it’s you to choose a file.

+

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.

File formats, limits and expiry

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/main/resources/templates/portal-error.html b/src/main/resources/templates/portal-error.html new file mode 100644 index 0000000..f5e89d4 --- /dev/null +++ b/src/main/resources/templates/portal-error.html @@ -0,0 +1,11 @@ + + +
+ +

The request could not complete

Request reference

+ +
diff --git a/src/main/resources/templates/recovery-codes.html b/src/main/resources/templates/recovery-codes.html index d3ee169..566440a 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-generate.html b/src/main/resources/templates/recovery-generate.html new file mode 100644 index 0000000..0c8a51c --- /dev/null +++ b/src/main/resources/templates/recovery-generate.html @@ -0,0 +1,17 @@ + + + +
+
+

+

BusyStack displays the ten new codes once. Store them securely offline.

+
+ +

+ +

+ + Cancel +
+
+ diff --git a/src/main/resources/templates/recovery-use.html b/src/main/resources/templates/recovery-use.html new file mode 100644 index 0000000..4b8a186 --- /dev/null +++ b/src/main/resources/templates/recovery-use.html @@ -0,0 +1,18 @@ + + + +
+
+

Use a recovery code

+

This consumes the code, removes all your passkeys, revokes client access and ends every browser session. Sign in again and create a new passkey after recovery.

+ +
+ + +

+ + Cancel +
+
+ diff --git a/src/main/resources/templates/recovery.html b/src/main/resources/templates/recovery.html index 5178790..6c5c1d3 100644 --- a/src/main/resources/templates/recovery.html +++ b/src/main/resources/templates/recovery.html @@ -1,2 +1,4 @@ -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 .

+

Use a saved recovery code

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

Security

+

Passkeys

Manage passkeys

Application passwords

Manage application passwords

Browser sessions

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

Review sessions

Recovery

Manage recovery codes

Authorized applications

Review and revoke browser-authorized application access.

Review authorized applications

Password and organization sign-in

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..613a5fb 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
End session
diff --git a/src/main/resources/templates/setup-help.html b/src/main/resources/templates/setup-help.html new file mode 100644 index 0000000..b229e4d --- /dev/null +++ b/src/main/resources/templates/setup-help.html @@ -0,0 +1,18 @@ + + + + +
+
+

Setup and recovery help

+

Set up a new server

+

From the extracted deployment directory on the server, run bash scripts/initialize.sh. Paste the code into the setup form within 15 minutes. Issuing a replacement invalidates the old code.

+

Open setup

+

Recover an existing account

+

Sign in with your password or organization account. If you lost your passkey, use a saved recovery code at the verification step. Contact the deployment operator for controlled offline recovery if you cannot use that option.

+

The extracted deployment includes docs/GETTING_STARTED.md and docs/operations.md.

+

Open sign-in

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

Set up BusyStack

+

Your server is running and needs its first administrator.

+

On the server, open the extracted deployment folder that contains compose.yaml and the scripts. Run:

+
+ bash scripts/initialize.sh + +
+

The code expires after 15 minutes. Run the command again to replace an expired code or a code locked after repeated unsuccessful attempts.

+

Setup and recovery help · Packaged guide at docs/GETTING_STARTED.md

+ +
+ + +

+ + +

+ + +

Use at least 14 Unicode characters and at most 72 UTF-8 bytes.

+

+ + +

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

Verify your passkey

+

This task request ended. Verify your sign-in, then open the task again.

Continue as .

Use a passkey saved for this BusyStack account. Follow the prompt from your browser or password manager.

+

Lost access to your passkey? Use a saved recovery code after primary sign-in, or contact your operator.

+

diff --git a/src/test/java/org/busystack/caldav/account/InitializationIT.java b/src/test/java/org/busystack/caldav/account/InitializationIT.java new file mode 100644 index 0000000..68873d2 --- /dev/null +++ b/src/test/java/org/busystack/caldav/account/InitializationIT.java @@ -0,0 +1,337 @@ +package org.busystack.caldav.account; + +import static org.assertj.core.api.Assertions.*; + +import java.util.Map; +import java.util.concurrent.Executors; +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.test.context.*; +import org.testcontainers.junit.jupiter.*; +import org.testcontainers.postgresql.PostgreSQLContainer; + +@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 InitializationIT { + @Container static final PostgreSQLContainer POSTGRES = LoopbackContainers.postgres(); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry r) { + r.add("spring.datasource.url", POSTGRES::getJdbcUrl); + r.add("spring.datasource.username", POSTGRES::getUsername); + r.add("spring.datasource.password", POSTGRES::getPassword); + r.add("server.ssl.enabled", () -> true); + r.add("server.ssl.key-store", () -> TestTls.instance().keyStore()); + r.add("server.ssl.key-store-password", () -> TestTls.instance().password()); + } + + @Autowired InitializationService setup; + @Autowired AccountService accounts; + @Autowired JdbcTemplate jdbc; + @LocalServerPort int port; + SignedPasskeyClient http; + static final String PASSWORD = "Synthetic initialization password"; + + @BeforeEach + void reset() { + FixtureDatabase.clearAccounts(jdbc); + jdbc.update( + "UPDATE installation_state SET initialized=false,code_verifier=NULL,expires_at=NULL,failed_attempts=0,initial_administrator=NULL,welcome_completed_at=NULL"); + http = new SignedPasskeyClient(port, "/team", "https://localhost"); + } + + @AfterEach + void close() { + http.close(); + } + + @Test + void freshHttpsSetupRequiresCodeAndCsrfAndNeverEchoesSecrets() throws Exception { + var browser = http.browser(); + assertThat( + http.get(browser, "/oauth2/authorization/upstream") + .headers() + .firstValue("Location") + .orElseThrow()) + .endsWith("/setup"); + assertThat(http.get(browser, "/login").headers().firstValue("Location").orElseThrow()) + .endsWith("/setup"); + var form = http.get(browser, "/setup"); + assertThat(form.body()) + .contains("Set up BusyStack", "scripts/initialize.sh", "name=\"password\""); + assertThat(form.headers().firstValue("Cache-Control").orElseThrow()).isEqualTo("no-store"); + assertThat(form.headers().firstValue("Referrer-Policy").orElseThrow()).isEqualTo("no-referrer"); + assertThat( + http.get(browser, "/setup/administrator") + .headers() + .firstValue("Location") + .orElseThrow()) + .endsWith("/team/setup"); + assertThat(http.get(browser, "/help/setup").statusCode()).isEqualTo(200); + String code = setup.issueCode(); + var values = + Map.of( + "code", + code, + "username", + "fixture-admin", + "password", + PASSWORD, + "confirmation", + PASSWORD); + assertThat( + http.request( + browser, "/setup/administrator", "POST", null, SignedPasskeyClient.form(values)) + .statusCode()) + .isEqualTo(403); + var wrong = + http.request( + browser, + "/setup/administrator", + "POST", + SignedPasskeyClient.csrf(form.body()), + SignedPasskeyClient.form( + Map.of( + "code", + "wrong-code", + "username", + "fixture-admin", + "password", + PASSWORD, + "confirmation", + PASSWORD))); + assertThat(wrong.statusCode()).isEqualTo(400); + assertThat(wrong.body()) + .contains("Initialization code is unavailable", "fixture-admin") + .doesNotContain(PASSWORD, "wrong-code"); + var result = + http.request( + browser, + "/setup/administrator", + "POST", + SignedPasskeyClient.csrf(wrong.body()), + SignedPasskeyClient.form(values)); + assertThat(result.statusCode()).isEqualTo(302); + assertThat(result.headers().firstValue("Location").orElseThrow()).endsWith("/team/login"); + assertThat(http.get(browser, "/login").body()) + .contains("Administrator account created", "Sign in") + .doesNotContain(code, PASSWORD); + assertThat(http.get(browser, "/security").statusCode()) + .isEqualTo(302); // Setup never authenticates. + assertThat(accounts.find("fixture-admin").administrator()).isTrue(); + assertThat(setup.available()).isFalse(); + assertThat(setup.initialize(code, "other", PASSWORD, PASSWORD)).containsKey("code"); + } + + @Test + void randomReplacementExpiryAndBoundedAttempts() { + String first = setup.issueCode(); + String second = setup.issueCode(); + assertThat(first).matches("[A-Za-z0-9_-]{43}").isNotEqualTo(second); + assertThat(java.util.Base64.getUrlDecoder().decode(first)).hasSize(32); + assertThat( + jdbc.queryForObject( + "SELECT encode(code_verifier,'hex') FROM installation_state", String.class)) + .doesNotContain(first, second); + assertThat(setup.initialize(first, "admin", PASSWORD, PASSWORD)).containsKey("code"); + jdbc.update("UPDATE installation_state SET expires_at=now()-interval '1 second'"); + assertThat(setup.initialize(second, "admin", PASSWORD, PASSWORD)).containsKey("code"); + String active = setup.issueCode(); + for (int n = 0; n < 5; n++) + assertThat(setup.initialize("incorrect", "admin", PASSWORD, PASSWORD)).containsKey("code"); + assertThat(setup.initialize(active, "admin", PASSWORD, PASSWORD)).containsKey("code"); + assertThat(jdbc.queryForObject("SELECT failed_attempts FROM installation_state", Integer.class)) + .isEqualTo(5); + String replacement = setup.issueCode(); + assertThat(setup.initialize(replacement, "admin", PASSWORD, PASSWORD)).isEmpty(); + } + + @Test + void fieldValidationAndRollbackLeaveTheCodeUsable() { + String code = setup.issueCode(); + assertThat(setup.initialize(code, "bad user", "short", "different")) + .containsKeys("username", "password", "confirmation"); + assertThat(setup.initialize(code, "admin", "é".repeat(37), "é".repeat(37))) + .containsKey("password"); + assertThat(setup.available()).isTrue(); + assertThat(setup.initialize(code, "admin", PASSWORD, PASSWORD)).isEmpty(); + } + + @Test + void concurrentClaimsHaveExactlyOneWinner() throws Exception { + String code = setup.issueCode(); + try (var pool = Executors.newFixedThreadPool(2)) { + var start = new java.util.concurrent.CountDownLatch(1); + var a = + pool.submit( + () -> { + start.await(); + return setup.initialize(code, "first", PASSWORD, PASSWORD).isEmpty(); + }); + var b = + pool.submit( + () -> { + start.await(); + return setup.initialize(code, "second", PASSWORD, PASSWORD).isEmpty(); + }); + start.countDown(); + assertThat(java.util.List.of(a.get(), b.get())).containsExactlyInAnyOrder(true, false); + } + assertThat( + jdbc.queryForObject("SELECT count(*) FROM accounts WHERE administrator", Integer.class)) + .isEqualTo(1); + } + + @Test + void administratorJourneyKeepsRegistrationSeparateFromVerification() throws Exception { + String code = setup.issueCode(); + assertThat(setup.initialize(code, "journey-admin", PASSWORD, PASSWORD)).isEmpty(); + var browser = http.passwordLogin("journey-admin", PASSWORD); + var enrollment = http.get(browser, "/auth/continue?next=/team/connections?client=gnome"); + assertThat(enrollment.body()) + .contains("Create a passkey", "Create passkey") + .doesNotContain("Registered passkeys", "aria-label=\"Server administration\""); + String csrf = SignedPasskeyClient.csrf(enrollment.body()); + assertThat( + http.request( + browser, + "/credentials", + "POST", + csrf, + SignedPasskeyClient.form(Map.of("label", "Denied", "days", "1"))) + .statusCode()) + .isEqualTo(403); + var key = http.enroll(browser); + assertThat(http.get(browser, "/auth/continue").body()) + .contains("Verify your passkey") + .doesNotContain("Secure your account"); + assertThat(http.get(browser, "/security/passkeys").statusCode()).isEqualTo(302); + assertThat( + http.request( + browser, + "/credentials", + "POST", + http.csrf(browser, "/auth/continue"), + SignedPasskeyClient.form(Map.of("label", "Still denied", "days", "1"))) + .statusCode()) + .isEqualTo(403); + assertThat(http.assertCredential(http.options(browser), key, "correct", 0x0d).statusCode()) + .isEqualTo(200); + var complete = http.get(browser, "/auth/continue"); + assertThat(complete.statusCode()).isEqualTo(302); + assertThat(complete.headers().firstValue("Location").orElseThrow()).endsWith("/team/"); + assertThat(http.get(browser, "/").body()) + .contains("Overview", "Open server administration", "Create a resource"); + String createPath = "/security/credentials/new?client=gnome&from=connect"; + assertThat(http.get(browser, "/connections?client=gnome").body()) + .contains("/team" + createPath.replace("&", "&")); + var credentialForm = http.get(browser, createPath); + var matcher = + java.util.regex.Pattern.compile("name=\"intent\" value=\"([a-f0-9-]{36})\"") + .matcher(credentialForm.body()); + assertThat(matcher.find()).isTrue(); + var issued = + http.request( + browser, + "/credentials", + "POST", + SignedPasskeyClient.csrf(credentialForm.body()), + SignedPasskeyClient.form( + Map.of( + "label", + "Synthetic GNOME", + "days", + "1", + "client", + "gnome", + "from", + "connect", + "intent", + matcher.group(1)))); + assertThat(issued.statusCode()).isEqualTo(200); + assertThat(issued.body()) + .contains("Application password created", "Synthetic GNOME", "client=gnome"); + } + + @Test + void failedAccountWriteRollsBackConsumptionAndThePermanentLatch() { + String code = setup.issueCode(); + jdbc.execute( + "CREATE FUNCTION reject_initialization_fixture() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'Deliberate account write failure'; END $$"); + jdbc.execute( + "CREATE TRIGGER reject_initialization_fixture BEFORE INSERT ON accounts FOR EACH ROW EXECUTE FUNCTION reject_initialization_fixture()"); + try { + assertThatThrownBy(() -> setup.initialize(code, "rollback-admin", PASSWORD, PASSWORD)) + .isInstanceOf(org.springframework.dao.DataAccessException.class); + assertThat(setup.available()).isTrue(); + } finally { + jdbc.execute("DROP TRIGGER reject_initialization_fixture ON accounts"); + jdbc.execute("DROP FUNCTION reject_initialization_fixture()"); + } + assertThat(setup.initialize(code, "rollback-admin", PASSWORD, PASSWORD)).isEmpty(); + } + + @Test + void upgradingAnExistingDisabledAdministratorClosesSetup() { + jdbc.execute("CREATE SCHEMA initialization_upgrade"); + try { + var source = jdbc.getDataSource(); + org.flywaydb.core.Flyway.configure() + .dataSource(source) + .defaultSchema("initialization_upgrade") + .schemas("initialization_upgrade") + .target("14") + .load() + .migrate(); + new org.springframework.transaction.support.TransactionTemplate( + new org.springframework.jdbc.datasource.DataSourceTransactionManager(source)) + .executeWithoutResult( + status -> { + // Published trigger bodies resolve unqualified names in the caller's schema. + jdbc.execute("SET LOCAL search_path TO initialization_upgrade,public"); + jdbc.update( + "INSERT INTO initialization_upgrade.accounts(id,username,display_name,password_hash,administrator,enabled) VALUES (gen_random_uuid(),'legacy-admin','Legacy administrator','non-authenticating-fixture',true,false)"); + }); + org.flywaydb.core.Flyway.configure() + .dataSource(source) + .defaultSchema("initialization_upgrade") + .schemas("initialization_upgrade") + .load() + .migrate(); + assertThat( + jdbc.queryForObject( + "SELECT initialized FROM initialization_upgrade.installation_state", + Boolean.class)) + .isTrue(); + assertThat( + jdbc.queryForObject( + "SELECT count(*) FROM initialization_upgrade.accounts WHERE NOT enabled", + Integer.class)) + .isEqualTo(1); + } finally { + jdbc.execute("DROP SCHEMA initialization_upgrade CASCADE"); + } + } + + @Test + void offlineProvisionDisableAndAccountDeletionCannotReopenInitialization() { + accounts.provision("existing", "Existing", PASSWORD, true); + assertThat(setup.available()).isFalse(); + assertThatThrownBy(setup::issueCode).isInstanceOf(IllegalStateException.class); + accounts.disable(accounts.find("existing").id()); + assertThat(setup.available()).isFalse(); + jdbc.update("DELETE FROM accounts"); + assertThat(setup.available()).isFalse(); + } +} diff --git a/src/test/java/org/busystack/caldav/calendar/CalendarAuditCorrectionsTest.java b/src/test/java/org/busystack/caldav/calendar/CalendarAuditCorrectionsTest.java index ff9e912..22063f5 100644 --- a/src/test/java/org/busystack/caldav/calendar/CalendarAuditCorrectionsTest.java +++ b/src/test/java/org/busystack/caldav/calendar/CalendarAuditCorrectionsTest.java @@ -162,8 +162,7 @@ static byte[] fixture(String name) throws Exception { "invalid-rule-count-and-until.ics", "invalid-rule-repeat-count.ics", "invalid-rule-repeat-freq.ics", - "invalid-rule-until-type.ics", - "invalid-todo-no-start-duration.ics" + "invalid-rule-until-type.ics" }) void originalInvalidFixturesFailAtTheWriteBoundary(String name) throws Exception { byte[] bytes = fixture(name), before = bytes.clone(); @@ -177,6 +176,17 @@ void originalInvalidFixturesFailAtTheWriteBoundary(String name) throws Exception assertThat(bytes).isEqualTo(before); } + @Test + void historicalDurationOnlyTaskIsValidUnderRfc10051() throws Exception { + // Preserve the original fixture and its historical name; §11.1 changes its validity. + byte[] bytes = fixture("invalid-todo-no-start-duration.ics"), before = bytes.clone(); + var task = CalendarContent.parse(bytes, "VTODO").calendar().getComponents().getFirst(); + assertThat(task.getRequiredProperty("DURATION").getValue()).isEqualTo("PT1H"); + assertThat(task.getProperty("DTSTART")).isEmpty(); + assertThat(task.getProperty("DUE")).isEmpty(); + assertThat(bytes).isEqualTo(before); + } + @ParameterizedTest @ValueSource( strings = { @@ -299,7 +309,8 @@ void mixedCaseStructuralNamesRemainDistinctFromCaseSensitiveValues() { @Test void floatingAndAbsoluteDateTimesUseTheReportsTimezoneRatherThanAGuessedWriteZone() { - var parsed = parse("VEVENT", "DTSTART:20261027T100000\r\nDTEND:20261027T140000Z\r\n"); + var parsed = parse("VEVENT", "DTSTART:20261027T100000\r\nDTEND:20261027T140000\r\n"); + var absolute = parse("VEVENT", "DTSTART:20261027T100000Z\r\nDTEND:20261027T140000Z\r\n"); var filter = component( "VCALENDAR", @@ -317,6 +328,9 @@ void floatingAndAbsoluteDateTimesUseTheReportsTimezoneRatherThanAGuessedWriteZon new CalendarQuery(QueryLimits.defaults()) .matches(parsed, filter, ZoneOffset.ofHours(2))) .isTrue(); + for (var zone : List.of(ZoneOffset.UTC, ZoneOffset.ofHours(2))) + assertThat(new CalendarQuery(QueryLimits.defaults()).matches(absolute, filter, zone)) + .isFalse(); } @ParameterizedTest diff --git a/src/test/java/org/busystack/caldav/calendar/CalendarCoreSyntaxTest.java b/src/test/java/org/busystack/caldav/calendar/CalendarCoreSyntaxTest.java new file mode 100644 index 0000000..a4c9fca --- /dev/null +++ b/src/test/java/org/busystack/caldav/calendar/CalendarCoreSyntaxTest.java @@ -0,0 +1,88 @@ +package org.busystack.caldav.calendar; + +import static org.assertj.core.api.Assertions.*; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class CalendarCoreSyntaxTest { + @ParameterizedTest + @ValueSource( + strings = { + "URL:relative", + "ATTENDEE:relative", + "ORGANIZER:relative", + "ATTACH:relative", + "ATTENDEE;MEMBER=\"relative\":mailto:a@example.invalid", + "ATTENDEE;DELEGATED-TO=\"relative\":mailto:a@example.invalid", + "ATTENDEE;DELEGATED-FROM=\"relative\":mailto:a@example.invalid", + "ATTENDEE;DIR=\"relative\":mailto:a@example.invalid", + "ORGANIZER;SENT-BY=\"relative\":mailto:a@example.invalid", + "DESCRIPTION;ALTREP=\"relative\":Description", + "X-URI;VALUE=URI:relative", + "X-ADDRESS;VALUE=CAL-ADDRESS:relative", + "URL:", + "ATTENDEE:" + }) + void uriValuesRequireAnAbsoluteUri(String field) { + assertThatThrownBy( + () -> + CalendarSemanticsTest.parse( + "VEVENT", "DTSTART:20261109T090000Z\r\n" + field + "\r\n")) + .isInstanceOf(RuntimeException.class); + } + + @ParameterizedTest + @ValueSource( + strings = { + "URL:urn:example:event", "ATTENDEE:mailto:synthetic@example.invalid", + "ATTACH;VALUE=BINARY;ENCODING=BASE64:SGVsbG8=", "RELATED-TO:relative-text", + "X-OPAQUE:relative-value", "X-OPAQUE;X-URI=relative-value:opaque", + "ATTENDEE;MEMBER=\"mailto:a@example.invalid\",\"urn:example:group\":mailto:b@example.invalid" + }) + void absoluteAndOpaqueNeighborsStayValid(String field) { + assertThatCode( + () -> + CalendarSemanticsTest.parse( + "VEVENT", "DTSTART:20261109T090000Z\r\n" + field + "\r\n")) + .doesNotThrowAnyException(); + } + + @ParameterizedTest + @ValueSource( + strings = { + "2;Success", + "2.0", + "2.0;Success;Extra;Unexpected", + "2.0;bad\\q", + "-2.0;Success", + "2.;Success", + "2.0;unescaped,comma", + "2.0;Success;bad\\q", + "9.9.9.9;Too many code levels" + }) + void requestStatusRequiresItsStructuredGrammar(String value) { + assertThatThrownBy( + () -> + CalendarSemanticsTest.parse( + "VEVENT", "DTSTART:20261109T090000Z\r\nREQUEST-STATUS:" + value + "\r\n")) + .isInstanceOf(CalendarValidationException.class); + } + + @ParameterizedTest + @ValueSource( + strings = { + "2.0;Success", + "3.1.1;Invalid property;VALUE=DATE", + "2.0;", + "2.0;Semi\\;comma\\,slash\\\\line\\n;Opaque\\;detail", + "9.99.999;Future code" + }) + void requestStatusRetainsEscapedTextAndTwoOrThreeCodeLevels(String value) { + assertThatCode( + () -> + CalendarSemanticsTest.parse( + "VEVENT", "DTSTART:20261109T090000Z\r\nREQUEST-STATUS:" + value + "\r\n")) + .doesNotThrowAnyException(); + } +} diff --git a/src/test/java/org/busystack/caldav/calendar/CalendarEdgeSemanticsTest.java b/src/test/java/org/busystack/caldav/calendar/CalendarEdgeSemanticsTest.java index a348d82..bd0b4b0 100644 --- a/src/test/java/org/busystack/caldav/calendar/CalendarEdgeSemanticsTest.java +++ b/src/test/java/org/busystack/caldav/calendar/CalendarEdgeSemanticsTest.java @@ -2,12 +2,24 @@ import static org.assertj.core.api.Assertions.*; import static org.busystack.caldav.calendar.CalendarSemanticsTest.*; +import static org.junit.jupiter.api.Assertions.assertAll; +import java.nio.charset.StandardCharsets; import java.time.*; import java.util.*; +import java.util.stream.Stream; import org.busystack.caldav.calendar.query.*; import org.busystack.caldav.calendar.query.CalendarFilter.*; +import org.busystack.caldav.calendar.recurrence.CalendarRecurrence; +import org.busystack.caldav.calendar.recurrence.RecurrenceExpander; +import org.busystack.caldav.calendar.recurrence.TemporalSupport; +import org.busystack.caldav.calendar.recurrence.WorkBudget; +import org.busystack.caldav.config.DavCompatibilityProperties; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; class CalendarEdgeSemanticsTest { @Test @@ -54,6 +66,333 @@ void periodRdatesDistinguishNominalAndExactDaysAcrossDst() { .isFalse(); assertThat(point(parse("VEVENT", event + "PT24H\r\n"), "VEVENT", "2026-03-08T16:30:00Z")) .isTrue(); + for (String duration : List.of("pt24h", "+pt24h")) + assertThat( + point(parse("VEVENT", event + duration + "\r\n"), "VEVENT", "2026-03-08T16:30:00Z")) + .as("Elapsed hours in %s", duration) + .isTrue(); + } + + @Test + void manyTimezoneQualifiedRdatePeriodsUseTheSameCalendarTimezone() { + var dates = new StringJoiner(","); + LocalDate first = LocalDate.of(2026, 1, 2); + for (int day = 0; day < 600; day++) + dates.add( + first.plusDays(day).format(java.time.format.DateTimeFormatter.BASIC_ISO_DATE) + + "T090000/PT1H"); + var calendar = + parse( + "VEVENT", + "DTSTART;TZID=America/New_York:20260101T090000\r\n" + + "RDATE;TZID=America/New_York;VALUE=PERIOD:" + + dates + + "\r\n"); + var window = range("2026-01-01T00:00:00Z", "2028-01-01T00:00:00Z"); + var master = calendar.calendar().getComponents("VEVENT").getFirst(); + var registeredZone = ((ZonedDateTime) TemporalSupport.date(master, "DTSTART")).getZone(); + var periods = + new RecurrenceExpander(new WorkBudget(QueryLimits.defaults())) + .occurrences(calendar, window, FloatingTimezone.of(UTC)); + assertThat(periods) + .hasSize(601) + .allSatisfy( + occurrence -> + assertThat(((ZonedDateTime) occurrence.dates().get("DTSTART")).getZone()) + .isEqualTo(registeredZone)); + var busy = new CalendarFreeBusy(QueryLimits.defaults()).query(List.of(calendar), window, UTC); + assertThat(busy).hasSize(600); + assertThat(busy.getFirst().start()).isEqualTo(Instant.parse("2026-01-02T14:00:00Z")); + assertThat(busy) + .allMatch( + period -> Duration.between(period.start(), period.end()).equals(Duration.ofHours(1))); + } + + @Test + void exdateCanExcludeTheOnlyEventTaskOrJournalOccurrence() { + var window = range("2026-01-01T10:00:00Z", "2026-01-01T11:00:00Z"); + String fields = "DTSTART:20260101T100000Z\r\nEXDATE:20260101T100000Z\r\n"; + for (String type : List.of("VEVENT", "VTODO", "VJOURNAL")) { + var calendar = parse(type, fields + (type.equals("VEVENT") ? "DURATION:PT1H\r\n" : "")); + assertThat(match(calendar, type, window)).as(type).isFalse(); + assertThat( + new CalendarRecurrence(QueryLimits.defaults()) + .expand(calendar, window, FloatingTimezone.of(UTC)) + .getComponents()) + .as(type) + .isEmpty(); + if (type.equals("VEVENT")) + assertThat( + new CalendarFreeBusy(QueryLimits.defaults()).query(List.of(calendar), window, UTC)) + .isEmpty(); + } + } + + @Test + void rangeReplacementTimezoneSpellingDoesNotShiftLaterOccurrences() { + String zone = ";TZID=America/New_York"; + String master = + event(null, "20260306T140000Z", "RRULE:FREQ=DAILY;COUNT=4\r\nDURATION:PT1H\r\n") + .replace("DTSTART:20260306T140000Z", "DTSTART" + zone + ":20260306T090000"); + String rid = zone + ";RANGE=THISANDFUTURE:20260307T090000"; + for (String start : + List.of("DTSTART:20260307T140000Z", "DTSTART" + zone + ":20260307T090000")) { + var calendar = + parseComponents( + "VEVENT", + master + + event(rid, "20260307T140000Z", "DURATION:PT1H\r\n") + .replace("DTSTART:20260307T140000Z", start)); + assertThat(point(calendar, "VEVENT", "2026-03-09T13:00:00Z")).as(start).isTrue(); + assertThat(point(calendar, "VEVENT", "2026-03-09T18:00:00Z")).as(start).isFalse(); + } + } + + static Stream movedRangeCases() { + return Stream.of("VEVENT", "VTODO") + .flatMap( + type -> + Stream.of("", ";UNTIL=20260103T100000Z", ";COUNT=10") + .flatMap( + limit -> + Stream.of("DURATION", type.equals("VEVENT") ? "DTEND" : "DUE") + .map(end -> Arguments.of(type, limit, end)))); + } + + @ParameterizedTest + @MethodSource("movedRangeCases") + void narrowReportsKeepTheOverlapOfAMovedOccurrence(String type, String limit, String end) { + String masterEnd = end.equals("DURATION") ? "DURATION:PT1H" : end + ":20260101T110000Z"; + String overrideEnd = end.equals("DURATION") ? "DURATION:PT1H" : end + ":20260102T130000Z"; + var calendar = + admitRangeCalendar( + type, + (event( + null, + "20260101T100000Z", + "RRULE:FREQ=DAILY" + limit + "\r\n" + masterEnd + "\r\n") + + event( + ";RANGE=THISANDFUTURE:20260102T100000Z", + "20260102T120000Z", + overrideEnd + "\r\n")) + .replace("VEVENT", type)); + assertMovedOccurrence( + calendar, + type, + range("2026-01-03T00:00:00Z", "2026-01-04T00:00:00Z"), + range("2026-01-03T12:30:00Z", "2026-01-03T12:45:00Z"), + "20260103T120000Z"); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void narrowReportsKeepWallClockMovesAcrossDaylightSaving(boolean moveLater) { + String from = moveLater ? "20260307T090000" : "20260308T090000"; + String to = moveLater ? "20260308T090000" : "20260307T090000"; + assertMovedOccurrence( + newYorkDailyRange("20260306T090000", from, to), + "VEVENT", + range("2026-03-10T00:00:00Z", "2026-03-11T00:00:00Z"), + range("2026-03-10T13:00:00Z", "2026-03-10T13:15:00Z"), + "20260310T130000Z"); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void narrowReportsKeepMovesBetweenDifferentOffsets(boolean moveLater) { + String replacement = moveLater ? "20261028T090000" : "20261026T090000"; + var calendar = newYorkDailyRange("20261025T090000", "20261027T090000", replacement); + if (moveLater) { + assertMovedOccurrence( + calendar, + "VEVENT", + range("2026-11-01T00:00:00Z", "2026-11-02T00:00:00Z"), + range("2026-11-01T14:05:00Z", "2026-11-01T14:15:00Z"), + "20261101T140000Z"); + } else { + assertMovedOccurrence( + calendar, + "VEVENT", + range("2026-10-31T00:00:00Z", "2026-11-01T00:00:00Z"), + range("2026-10-31T13:05:00Z", "2026-10-31T13:15:00Z"), + "20261031T130000Z"); + } + } + + @Test + void narrowReportsKeepMovesOfOriginalStartsInASpringGap() { + assertMovedOccurrence( + newYorkDailyRange("20260306T023000", "20260307T023000", "20260307T030000"), + "VEVENT", + range("2026-03-08T00:00:00Z", "2026-03-09T00:00:00Z"), + range("2026-03-08T08:10:00Z", "2026-03-08T08:15:00Z"), + "20260308T080000Z"); + } + + private static CalendarContent.Parsed newYorkDailyRange(String start, String from, String to) { + String tzid = ";TZID=America/New_York"; + return admitRangeCalendar( + "VEVENT", + (event(null, start, "RRULE:FREQ=DAILY\r\nDURATION:PT30M\r\n") + + event(tzid + ";RANGE=THISANDFUTURE:" + from, to, "DURATION:PT30M\r\n")) + .replace("DTSTART:", "DTSTART" + tzid + ":")); + } + + @ParameterizedTest + @ValueSource(strings = {"UTC", "TZID", "floating"}) + void shortSecondlyReportsIgnoreOffsetsOutsideTheMove(String dateTimeForm) { + String suffix = dateTimeForm.equals("UTC") ? "Z" : ""; + String tzid = dateTimeForm.equals("TZID") ? ";TZID=America/New_York" : ""; + var calendar = + admitRangeCalendar( + "VEVENT", + (event(null, "20260101T100000" + suffix, "RRULE:FREQ=SECONDLY\r\nDURATION:PT1S\r\n") + + event( + tzid + ";RANGE=THISANDFUTURE:20260101T100100" + suffix, + "20260101T100101" + suffix, + "DURATION:PT1S\r\n")) + .replace("DTSTART:", "DTSTART" + tzid + ":")); + var timezone = + FloatingTimezone.of(dateTimeForm.equals("floating") ? ZoneId.of("America/New_York") : UTC); + String hour = dateTimeForm.equals("UTC") ? "10" : "15"; + String recurrenceHour = dateTimeForm.equals("TZID") ? "15" : "10"; + assertShortReports( + calendar, + timezone, + range("2026-01-01T" + hour + ":02:00Z", "2026-01-01T" + hour + ":02:01Z"), + "20260101T" + recurrenceHour + "0200" + (dateTimeForm.equals("floating") ? "" : "Z"), + "20260101T" + recurrenceHour + "0159" + (dateTimeForm.equals("floating") ? "" : "Z")); + } + + @Test + void shortSecondlyReportsIgnoreANearbyButUnreachedTransition() { + String tzid = ";TZID=America/New_York"; + var calendar = + admitRangeCalendar( + "VEVENT", + (event(null, "20260308T015500", "RRULE:FREQ=SECONDLY\r\nDURATION:PT1S\r\n") + + event( + tzid + ";RANGE=THISANDFUTURE:20260308T015600", + "20260308T015601", + "DURATION:PT1S\r\n")) + .replace("DTSTART:", "DTSTART" + tzid + ":")); + assertShortReports( + calendar, + FloatingTimezone.of(UTC), + range("2026-03-08T06:58:00Z", "2026-03-08T06:58:01Z"), + "20260308T065800Z", + "20260308T065759Z"); + } + + @Test + void shortMinutelyReportsIgnoreAnOldDateLineTransition() { + String timezone = + """ + BEGIN:VTIMEZONE + TZID:Example/DateLine + BEGIN:STANDARD + DTSTART:20111230T000000 + TZOFFSETFROM:-1000 + TZOFFSETTO:+1400 + END:STANDARD + END:VTIMEZONE + """ + .replace("\n", "\r\n"); + String tzid = ";TZID=Example/DateLine"; + var calendar = + admitRangeCalendar( + "VEVENT", + timezone + + (event(null, "20260101T100000", "RRULE:FREQ=MINUTELY\r\nDURATION:PT1M\r\n") + + event( + tzid + ";RANGE=THISANDFUTURE:20260101T100100", + "20260101T100200", + "DURATION:PT1M\r\n")) + .replace("DTSTART:", "DTSTART" + tzid + ":")); + assertShortReports( + calendar, + FloatingTimezone.of(UTC), + range("2025-12-31T20:04:00Z", "2025-12-31T20:05:00Z"), + "20251231T200400Z", + "20251231T200300Z"); + } + + private static void assertShortReports( + CalendarContent.Parsed calendar, + FloatingTimezone timezone, + TimeRange window, + String start, + String recurrenceId) { + var limits = QueryLimits.defaults(); + var filter = + component( + "VCALENDAR", + null, + List.of(), + List.of(component("VEVENT", window, List.of(), List.of()))); + assertAll( + () -> assertThat(new CalendarQuery(limits).matches(calendar, filter, timezone)).isTrue(), + () -> { + var expanded = + new CalendarRecurrence(limits).expand(calendar, window, timezone).getComponents(); + assertThat(expanded).hasSize(1); + assertThat(expanded.getFirst().getRequiredProperty("DTSTART").getValue()) + .isEqualTo(start); + assertThat(expanded.getFirst().getRequiredProperty("RECURRENCE-ID").getValue()) + .isEqualTo(recurrenceId); + }, + () -> + assertThat(new CalendarFreeBusy(limits).query(List.of(calendar), window, timezone)) + .containsExactly( + new CalendarFreeBusy.BusyPeriod( + window.start(), window.end(), CalendarFreeBusy.BusyType.BUSY))); + } + + private static CalendarContent.Parsed admitRangeCalendar(String type, String components) { + byte[] original = + ("BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//BusyStack range overlap fixtures//EN\r\n" + + withBuiltinTimezones(components) + + "END:VCALENDAR\r\n") + .getBytes(StandardCharsets.UTF_8); + var admitted = + new CalendarAdmission(new DavCompatibilityProperties(true, true)).admit(original, type); + assertThat(admitted.content()).isEqualTo(original); + return admitted.parsed(); + } + + private static void assertMovedOccurrence( + CalendarContent.Parsed calendar, + String type, + TimeRange broad, + TimeRange narrow, + String start) { + var timezone = FloatingTimezone.of(UTC); + var expanded = + new CalendarRecurrence(QueryLimits.defaults()) + .expand(calendar, broad, timezone) + .getComponents(); + assertThat(expanded).hasSize(1); + assertThat(expanded.getFirst().getRequiredProperty("DTSTART").getValue()).isEqualTo(start); + assertThat(match(calendar, type, broad)).isTrue(); + assertAll( + () -> assertThat(match(calendar, type, narrow)).as("calendar-query").isTrue(), + () -> + assertThat( + new CalendarRecurrence(QueryLimits.defaults()) + .expand(calendar, narrow, timezone) + .getComponents()) + .as("expanded calendar-data") + .containsExactlyElementsOf(expanded), + () -> { + if (type.equals("VEVENT")) + assertThat( + new CalendarFreeBusy(QueryLimits.defaults()) + .query(List.of(calendar), narrow, timezone)) + .as("free/busy") + .containsExactly( + new CalendarFreeBusy.BusyPeriod( + narrow.start(), narrow.end(), CalendarFreeBusy.BusyType.BUSY)); + }); } @Test diff --git a/src/test/java/org/busystack/caldav/calendar/CalendarEndMultiplicityTest.java b/src/test/java/org/busystack/caldav/calendar/CalendarEndMultiplicityTest.java new file mode 100644 index 0000000..8c226cb --- /dev/null +++ b/src/test/java/org/busystack/caldav/calendar/CalendarEndMultiplicityTest.java @@ -0,0 +1,34 @@ +package org.busystack.caldav.calendar; + +import static org.assertj.core.api.Assertions.*; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class CalendarEndMultiplicityTest { + @ParameterizedTest + @ValueSource(strings = {"DTEND:20261109T100000Z", "DTEND:20261109T110000Z"}) + void repeatedEndsHaveNoInventedSingletonRestrictionAndAllArePreserved(String second) { + var parsed = + CalendarSemanticsTest.parse( + "VEVENT", "DTSTART:20261109T090000Z\r\nDTEND:20261109T100000Z\r\n" + second + "\r\n"); + assertThat(parsed.calendar().getComponents().getFirst().getProperties("DTEND")).hasSize(2); + } + + @ParameterizedTest + @ValueSource( + strings = { + "DTEND:20261109T080000Z", + "DTEND:20261109T090000Z", + "DTEND;VALUE=DATE:20261110", + "DTEND:20261109T110000" + }) + void everyEndMustSatisfyTheExplicitDtstartConstraints(String second) { + assertThatThrownBy( + () -> + CalendarSemanticsTest.parse( + "VEVENT", + "DTSTART:20261109T090000Z\r\nDTEND:20261109T100000Z\r\n" + second + "\r\n")) + .isInstanceOf(CalendarValidationException.class); + } +} diff --git a/src/test/java/org/busystack/caldav/calendar/CalendarExpansionSemanticsTest.java b/src/test/java/org/busystack/caldav/calendar/CalendarExpansionSemanticsTest.java index 2510273..3ea3a72 100644 --- a/src/test/java/org/busystack/caldav/calendar/CalendarExpansionSemanticsTest.java +++ b/src/test/java/org/busystack/caldav/calendar/CalendarExpansionSemanticsTest.java @@ -85,7 +85,8 @@ void explicitPeriodExtensionsPreserveDurationMeaningWhileNormalizingTimezone() { var parsed = parse( "VEVENT", - "DTSTART;TZID=America/New_York:20260308T120000\r\nX-PERIOD;VALUE=PERIOD;TZID=America/New_York:20260307T120000/PT24H\r\n"); + "DTSTART;TZID=America/New_York:20260308T120000\r\n" + + "X-PERIOD;VALUE=PERIOD;TZID=America/New_York:20260307T120000/PT24H,20260307T120000/+pt24h\r\n"); var expanded = new CalendarRecurrence(QueryLimits.defaults()) .expand( @@ -93,7 +94,8 @@ void explicitPeriodExtensionsPreserveDurationMeaningWhileNormalizingTimezone() { range("2026-03-08T00:00:00Z", "2026-03-09T00:00:00Z"), FloatingTimezone.of(UTC)); assertThat(expanded.toString()) - .contains("X-PERIOD;VALUE=PERIOD:20260307T170000Z/20260308T170000Z") + .contains( + "X-PERIOD;VALUE=PERIOD:20260307T170000Z/20260308T170000Z,20260307T170000Z/20260308T170000Z") .doesNotContain("TZID="); } 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..e20bfab --- /dev/null +++ b/src/test/java/org/busystack/caldav/calendar/CalendarInterchangeTest.java @@ -0,0 +1,361 @@ +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"; + } + + @org.junit.jupiter.api.io.TempDir java.nio.file.Path temporary; + + @Test + void currentTaskDataSurvivesImportAndExportFraming() { + for (String status : java.util.List.of("PENDING", "FAILED", "NEEDS-ACTION")) { + byte[] resource = + bytes( + object( + "BEGIN:VTODO\nUID:current-" + + status + + "\nDTSTAMP:20261108T000000Z\n" + + "DURATION:PT1H\nSTATUS:" + + status + + "\nESTIMATED-DURATION:PT30M\nTASK-MODE:CLIENT\n" + + "X-KEEP;X-PARAM=opaque:café 日本語\nEND:VTODO\n")); + var items = read(resource, "VTODO"); + assertThat(items).hasSize(1); + assertThat(items.getFirst().rejection()).isEmpty(); + assertThat(items.getFirst().content()).isEqualTo(resource); + var parts = CalendarInterchange.exportParts(resource); + var output = new java.io.ByteArrayOutputStream(); + output.writeBytes(parts.header()); + output.writeBytes(parts.zones()); + output.writeBytes(parts.items()); + output.writeBytes(parts.closing()); + assertThat(output.toByteArray()).isEqualTo(resource); + assertThat(CalendarContent.parse(output.toByteArray(), "VTODO").calendar().toString()) + .contains("STATUS:" + status); + } + } + + @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"); + 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:"); + String exception = + event("series") + .replace( + "DTSTART:20261102T090000Z", + "RECURRENCE-ID:20261103T090000Z\nDTSTART:20261103T110000Z"); + 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"); + 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 = 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(read(task, "VTODO").getFirst().rejection()).isEmpty(); + assertThat(read(task, "VEVENT").getFirst().rejection()).contains("destination"); + } + + @Test + void journalImportsPreserveBytesAndRequireAJournalDestination() { + var journal = + bytes( + object( + "BEGIN:VJOURNAL\nUID:journal\nDTSTAMP:20261101T000000Z\n" + + "DESCRIPTION;LANGUAGE=en:First\nDESCRIPTION;LANGUAGE=fr:Second\nEND:VJOURNAL\n")); + var imported = read(journal, "VJOURNAL").getFirst(); + assertThat(imported.rejection()).isEmpty(); + assertThat(imported.content()).isEqualTo(journal); + assertThat(read(journal, "VEVENT").getFirst().rejection()).contains("destination"); + } + + @Test + void invalidItemsAreReportedAndDuplicateMastersNeverDiscarded() { + var mixed = + 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(read(bytes(object(event("same") + event("same"))), "VEVENT").getFirst().rejection()) + .isNotEmpty(); + assertThat(read(bytes(object(event("same")) + object(event("same"))), "VEVENT")) + .allSatisfy(i -> assertThat(i.rejection()).contains("multiple")); + } + + @Test + void malformedOversizedAndDeepFilesFailBeforeAnyImport() { + assertThatThrownBy(() -> read(bytes(""), "VEVENT")) + .isInstanceOf(CalendarValidationException.class); + assertThatThrownBy(() -> read(new byte[CalendarInterchange.MAX_FILE_BYTES + 1], "VEVENT")) + .isInstanceOf(CalendarValidationException.class); + assertThatThrownBy(() -> read(bytes(object("BEGIN:VEVENT\n".repeat(9))), "VEVENT")) + .isInstanceOf(CalendarValidationException.class); + assertThatThrownBy(() -> 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 = 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 = + 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/calendar/CalendarJournalTest.java b/src/test/java/org/busystack/caldav/calendar/CalendarJournalTest.java new file mode 100644 index 0000000..b5dda44 --- /dev/null +++ b/src/test/java/org/busystack/caldav/calendar/CalendarJournalTest.java @@ -0,0 +1,188 @@ +package org.busystack.caldav.calendar; + +import static org.assertj.core.api.Assertions.*; +import static org.busystack.caldav.calendar.CalendarSemanticsTest.*; + +import java.time.ZoneId; +import java.util.List; +import org.busystack.caldav.calendar.query.CalendarQuery; +import org.busystack.caldav.calendar.query.FloatingTimezone; +import org.busystack.caldav.calendar.query.QueryLimits; +import org.busystack.caldav.calendar.recurrence.CalendarRecurrence; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class CalendarJournalTest { + private static final String JOURNAL = "VJOURNAL"; + + @Test + void undatedInventoryAndPropertyMultiplicity() { + var journal = + parse( + JOURNAL, + "STATUS:DRAFT\r\nDESCRIPTION;LANGUAGE=en:One\r\nDESCRIPTION;LANGUAGE=fr:Deux\r\n" + + "LINK;VALUE=UID:target\r\nLINK;VALUE=XML-REFERENCE:https://example.invalid/j.xml#xpointer(/j)\r\n" + + "RELATED-TO;VALUE=UID:target\r\nX-KEEP;X-FLAG=original:value\r\n"); + assertThat(match(journal, JOURNAL, null)).isTrue(); + assertThat(point(journal, JOURNAL, "2026-01-01T00:00:00Z")).isFalse(); + final var entry = journal.calendar().getComponents().getFirst(); + assertThat(entry.getProperties("DESCRIPTION")).hasSize(2); + assertThat(entry.getProperties("LINK")) + .extracting(p -> p.getParameter("VALUE").orElseThrow().getValue()) + .containsExactly("UID", "XML-REFERENCE"); + } + + @Test + void journalStatusAllowsExtensionParametersAndStillRequiresAJournalStatus() { + var parsed = parse(JOURNAL, "STATUS;DERIVED=TRUE;X-QA=kept:FINAL\r\n"); + var status = parsed.calendar().getComponents().getFirst().getRequiredProperty("STATUS"); + assertThat(status.getValue()).isEqualTo("FINAL"); + assertThat(status.getParameter("DERIVED").orElseThrow().getValue()).isEqualTo("TRUE"); + assertThat(status.getParameter("X-QA").orElseThrow().getValue()).isEqualTo("kept"); + assertThatThrownBy(() -> parse(JOURNAL, "STATUS;X-QA=kept:PENDING\r\n")) + .isInstanceOf(CalendarValidationException.class); + } + + @Test + void journalStatusChildrenRequireBothStatusesWithoutNeedingUid() { + String review = "BEGIN:VSTATUS\r\nSTATUS:FINAL\r\nCOMMENT:Reviewed\r\nEND:VSTATUS\r\n"; + var parsed = parse(JOURNAL, "STATUS:FINAL\r\n" + review); + assertThat(parsed.calendar().getComponents().getFirst().toString()).contains(review); + assertThatThrownBy(() -> parse(JOURNAL, review)) + .isInstanceOf(CalendarValidationException.class); + assertThatThrownBy( + () -> parse(JOURNAL, "STATUS:FINAL\r\n" + review.replace("STATUS:FINAL\r\n", ""))) + .isInstanceOf(CalendarValidationException.class); + } + + @Test + void publishingExtensionsSurviveNestedReportCopies() { + var journal = + parse( + JOURNAL, + "DTSTART:20261125T090000Z\r\nCOLOR:darkblue\r\n" + + "IMAGE;VALUE=URI;DISPLAY=BADGE:https://example.invalid/image.png\r\n" + + "STYLED-DESCRIPTION;VALUE=TEXT;FMTTYPE=text/html:Fixture\r\n" + + "STRUCTURED-DATA;VALUE=URI;SCHEMA=\"https://schema.org/Thing\":https://example.invalid/data.json\r\n" + + "STRUCTURED-DATA;VALUE=URI:https://example.invalid/data.xml\r\n" + + "BEGIN:PARTICIPANT\r\nUID:person\r\nPARTICIPANT-TYPE:CONTACT\r\n" + + "BEGIN:VLOCATION\r\nUID:place\r\nNAME:Venue\r\nEND:VLOCATION\r\n" + + "END:PARTICIPANT\r\nBEGIN:VRESOURCE\r\nUID:room\r\nRESOURCE-TYPE:ROOM\r\nEND:VRESOURCE\r\n"); + var expanded = + new CalendarRecurrence(QueryLimits.defaults()) + .expand( + journal, + range("2026-11-25T09:00:00Z", "2026-11-25T09:00:01Z"), + FloatingTimezone.of(UTC)); + assertThat(expanded.toString()) + .contains( + "COLOR:darkblue", + "DISPLAY=BADGE", + "STYLED-DESCRIPTION", + "SCHEMA=\"https://schema.org/Thing\"", + "VALUE=URI:https://example.invalid/data.xml", + "BEGIN:PARTICIPANT", + "BEGIN:VLOCATION", + "NAME:Venue", + "BEGIN:VRESOURCE", + "RESOURCE-TYPE:ROOM"); + } + + @ParameterizedTest + @ValueSource( + strings = { + "STATUS:FAILED", + "STATUS:COMPLETED", + "STATUS:CONFIRMED", + "DTEND:20261128T154500Z", + "DUE:20261128T154500Z", + "DURATION:PT1H", + "TRANSP:TRANSPARENT", + "SUMMARY:One\r\nSUMMARY:Two", + "DTSTAMP:20261128T154500Z", + "UID:semantic", + "CONFERENCE:https://example.invalid/join", + "BEGIN:VALARM\r\nACTION:DISPLAY\r\nDESCRIPTION:Alarm\r\nTRIGGER:-PT5M\r\nEND:VALARM" + }) + void rejectsNonJournalProperties(String value) { + assertThatThrownBy(() -> parse(JOURNAL, value + "\r\n")) + .isInstanceOf(CalendarValidationException.class); + } + + @Test + void dateDayEndsAtLocalMidnightAcrossBothDstTransitions() { + var zone = ZoneId.of("America/New_York"); + for (var bounds : + List.of( + List.of( + "20260308", "2026-03-09T03:59:59Z", "2026-03-09T04:00:00Z", "2026-03-09T04:00:01Z"), + List.of( + "20261101", + "2026-11-02T04:59:59Z", + "2026-11-02T05:00:00Z", + "2026-11-02T05:00:01Z"))) { + var parsed = parse(JOURNAL, "DTSTART;VALUE=DATE:" + bounds.getFirst() + "\r\n"); + var filter = + component( + "VCALENDAR", + null, + List.of(), + List.of( + component(JOURNAL, range(bounds.get(1), bounds.get(2)), List.of(), List.of()))); + assertThat(new CalendarQuery(QueryLimits.defaults()).matches(parsed, filter, zone)).isTrue(); + filter = + component( + "VCALENDAR", + null, + List.of(), + List.of( + component(JOURNAL, range(bounds.get(2), bounds.get(3)), List.of(), List.of()))); + assertThat(new CalendarQuery(QueryLimits.defaults()).matches(parsed, filter, zone)).isFalse(); + } + } + + @Test + void periodRdatesMatchStartsWithoutAcquiringAnEnd() { + var parsed = + parse( + JOURNAL, + "DTSTART:20261125T090000Z\r\n" + + "RDATE;VALUE=PERIOD:20261126T090000Z/20261126T110000Z,20261127T090000Z/PT2H\r\n" + + "EXDATE:20261125T090000Z\r\n" + + "DESCRIPTION;LANGUAGE=fr:Texte\r\n"); + assertThat(point(parsed, JOURNAL, "2026-11-25T09:00:00Z")).isFalse(); + assertThat(point(parsed, JOURNAL, "2026-11-26T09:00:00Z")).isTrue(); + assertThat(point(parsed, JOURNAL, "2026-11-26T10:00:00Z")).isFalse(); + assertThat(point(parsed, JOURNAL, "2026-11-27T09:00:00Z")).isTrue(); + var expanded = + new CalendarRecurrence(QueryLimits.defaults()) + .expand( + parsed, + range("2026-11-25T00:00:00Z", "2026-11-28T00:00:00Z"), + FloatingTimezone.of(UTC)); + assertThat(expanded.getComponents(JOURNAL)).hasSize(2); + assertThat(expanded.toString()) + .contains( + "DTSTART:20261126T090000Z", "DTSTART:20261127T090000Z", "DESCRIPTION;LANGUAGE=fr:Texte") + .doesNotContain("DTEND", "DUE", "DURATION", "RDATE", "EXDATE"); + } + + @Test + void detachedResourceAndMovedRecurrenceUseEffectiveDates() { + String detached = + event(":20261028T100000Z", "20261029T140000Z", "STATUS:FINAL\r\n") + .replace("VEVENT", JOURNAL); + var standalone = parseComponents(JOURNAL, detached); + assertThat(point(standalone, JOURNAL, "2026-10-29T14:00:00Z")).isTrue(); + var series = + parseComponents( + JOURNAL, + event(null, "20261027T100000Z", "RRULE:FREQ=DAILY;COUNT=3\r\n") + .replace("VEVENT", JOURNAL) + + detached); + assertThat(point(series, JOURNAL, "2026-10-28T10:00:00Z")).isFalse(); + assertThat(point(series, JOURNAL, "2026-10-29T10:00:00Z")).isTrue(); + assertThat(point(series, JOURNAL, "2026-10-29T14:00:00Z")).isTrue(); + } +} diff --git a/src/test/java/org/busystack/caldav/calendar/CalendarOffsetSyntaxTest.java b/src/test/java/org/busystack/caldav/calendar/CalendarOffsetSyntaxTest.java new file mode 100644 index 0000000..4957403 --- /dev/null +++ b/src/test/java/org/busystack/caldav/calendar/CalendarOffsetSyntaxTest.java @@ -0,0 +1,50 @@ +package org.busystack.caldav.calendar; + +import static org.assertj.core.api.Assertions.*; + +import java.nio.charset.StandardCharsets; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class CalendarOffsetSyntaxTest { + static Stream offsets() { + return Stream.of("TZOFFSETFROM", "TZOFFSETTO") + .flatMap(name -> Stream.of("0000", "000000").map(zero -> Arguments.of(name, zero))); + } + + private static String calendar(String property, String value) { + return "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Offset grammar//EN\r\n" + + "BEGIN:VTIMEZONE\r\nTZID:Qualification/Fixed\r\nBEGIN:STANDARD\r\nDTSTART:19700101T000000\r\n" + + "TZOFFSETFROM:+0000\r\nTZOFFSETTO:+0000\r\nTZNAME:One\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n" + + "BEGIN:VEVENT\r\nUID:offset\r\nDTSTAMP:20261109T000000Z\r\nDTSTART:20261109T090000Z\r\n" + + (property.equals("X-OFFSET") ? "X-OFFSET;VALUE=UTC-OFFSET:" + value + "\r\n" : "") + + "END:VEVENT\r\nEND:VCALENDAR\r\n"; + } + + @ParameterizedTest + @MethodSource("offsets") + void negativeZeroIsRejectedBeforeItsSignCanBeNormalized(String property, String zero) { + String data = + calendar(property, "-" + zero).replace(property + ":+0000", property + ":-" + zero); + assertThatThrownBy(() -> CalendarContent.parse(data.getBytes(StandardCharsets.UTF_8), "VEVENT")) + .isInstanceOf(CalendarValidationException.class); + String extension = calendar("X-OFFSET", "-" + zero); + assertThatThrownBy( + () -> CalendarContent.parse(extension.getBytes(StandardCharsets.UTF_8), "VEVENT")) + .isInstanceOf(CalendarValidationException.class); + } + + @ParameterizedTest + @MethodSource("offsets") + void positiveZeroAndPrecisionRemainAcceptedWithoutInputMutation(String property, String zero) { + byte[] data = + calendar(property, "+" + zero) + .replace(property + ":+0000", property + ":+" + zero) + .getBytes(StandardCharsets.UTF_8); + byte[] before = data.clone(); + assertThat(CalendarContent.parse(data, "VEVENT").uid()).isEqualTo("offset"); + assertThat(data).isEqualTo(before); + } +} diff --git a/src/test/java/org/busystack/caldav/calendar/CalendarParameterSemanticsTest.java b/src/test/java/org/busystack/caldav/calendar/CalendarParameterSemanticsTest.java index 8800081..8e7a078 100644 --- a/src/test/java/org/busystack/caldav/calendar/CalendarParameterSemanticsTest.java +++ b/src/test/java/org/busystack/caldav/calendar/CalendarParameterSemanticsTest.java @@ -8,6 +8,8 @@ import org.busystack.caldav.calendar.query.*; import org.busystack.caldav.calendar.query.CalendarFilter.*; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; class CalendarParameterSemanticsTest { private CalendarContent.Parsed parsed(String parameters) { @@ -140,6 +142,127 @@ void parameterAdapterBoundsListValuesBeforeModelConstruction() { .isInstanceOf(RuntimeException.class); } + @ParameterizedTest + @ValueSource( + strings = { + "CUTYPE=BAD VALUE", + "ROLE=BAD VALUE", + "PARTSTAT=BAD VALUE", + "RELTYPE=BAD VALUE", + "VALUE=BAD VALUE", + "CUTYPE=", + "ROLE=", + "PARTSTAT=", + "RELTYPE=", + "VALUE=" + }) + void openParameterVocabulariesStillRequireTokens(String parameter) { + assertThatThrownBy(() -> tokenParameter(parameter)).isInstanceOf(RuntimeException.class); + } + + @ParameterizedTest + @ValueSource( + strings = { + "CUTYPE=X-ROBOT", + "ROLE=FUTURE-ROLE", + "PARTSTAT=X-FUTURE", + "RELTYPE=FINISHTOSTART", + "VALUE=X-FUTURE" + }) + void openParameterVocabulariesPreserveFutureTokens(String parameter) { + assertThatCode(() -> tokenParameter(parameter)).doesNotThrowAnyException(); + } + + private CalendarContent.Parsed tokenParameter(String parameter) { + if (parameter.startsWith("VALUE=")) + return CalendarSemanticsTest.parse( + "VEVENT", "DTSTART:20261109T090000Z\r\nX-OPAQUE;" + parameter + ":opaque\r\n"); + if (parameter.startsWith("RELTYPE=")) + return CalendarSemanticsTest.parse( + "VEVENT", "DTSTART:20261109T090000Z\r\nRELATED-TO;" + parameter + ":other\r\n"); + return parsed(parameter); + } + + @ParameterizedTest + @ValueSource(strings = {"THISANDPRIOR", "X-FUTURE", "", "BAD VALUE"}) + void recurrenceRangeUsesOnlyTheCurrentStandardValue(String range) { + assertThatThrownBy( + () -> + CalendarSemanticsTest.parse( + "VEVENT", + "DTSTART:20261109T090000Z\r\nRECURRENCE-ID;RANGE=" + + range + + ":20261109T090000Z\r\n")) + .isInstanceOf(RuntimeException.class); + } + + @ParameterizedTest + @ValueSource(strings = {"RSVP=MAYBE", "RSVP=", "LANGUAGE=en_US", "LANGUAGE="}) + void invalidKnownParameterValuesAreRejectedBeforeModelCoercion(String parameter) { + assertThatThrownBy(() -> parsed(parameter)).isInstanceOf(RuntimeException.class); + } + + @ParameterizedTest + @ValueSource( + strings = { + "RSVP=true", + "RSVP=FALSE", + "LANGUAGE=en-US", + "LANGUAGE=zh-Hant-TW", + "LANGUAGE=i-klingon", + "LANGUAGE=x-private" + }) + void validBooleanAndLanguageParametersRemainPreserved(String parameter) { + var parsed = parsed(parameter); + var original = parsed.calendar().getComponents().getFirst().getRequiredProperty("ATTENDEE"); + var copied = + parsed.calendar().copy().getComponents().getFirst().getRequiredProperty("ATTENDEE"); + String name = parameter.substring(0, parameter.indexOf('=')); + assertThat(copied.getRequiredParameter(name).getValue()) + .isEqualTo(original.getRequiredParameter(name).getValue()); + assertThat(original.getRequiredParameter(name).getValue()) + .isEqualToIgnoringCase(parameter.substring(parameter.indexOf('=') + 1)); + } + + @ParameterizedTest + @ValueSource( + strings = { + "CUTYPE=INDIVIDUAL", + "MEMBER=\"mailto:group@example.invalid\"", + "ROLE=REQ-PARTICIPANT", + "PARTSTAT=ACCEPTED", + "RSVP=TRUE", + "DELEGATED-TO=\"mailto:other@example.invalid\"", + "DELEGATED-FROM=\"mailto:other@example.invalid\"", + "SENT-BY=\"mailto:agent@example.invalid\"", + "CN=Synthetic", + "DIR=\"https://example.invalid/directory\"" + }) + void alarmAttendeesDoNotAcquireEventParticipationParameters(String parameter) { + assertThatThrownBy( + () -> + CalendarSemanticsTest.parse( + "VEVENT", "DTSTART:20261109T090000Z\r\n" + emailAlarm(";" + parameter))) + .isInstanceOf(CalendarValidationException.class); + assertThatCode(() -> parsed(parameter)).doesNotThrowAnyException(); + } + + @ParameterizedTest + @ValueSource(strings = {"", ";X-KEEP=opaque", ";LANGUAGE=en"}) + void plainAndExtendedAlarmDeliveryAddressesRemainValid(String parameters) { + var parsed = + CalendarSemanticsTest.parse( + "VEVENT", "DTSTART:20261109T090000Z\r\n" + emailAlarm(parameters)); + assertThat(parsed.calendar().copy().toString()) + .contains("ATTENDEE" + parameters + ":mailto:synthetic@example.invalid"); + } + + private static String emailAlarm(String parameters) { + return "BEGIN:VALARM\r\nACTION:EMAIL\r\nDESCRIPTION:Synthetic reminder\r\nSUMMARY:Synthetic alarm\r\nTRIGGER:-PT5M\r\nATTENDEE" + + parameters + + ":mailto:synthetic@example.invalid\r\nEND:VALARM\r\n"; + } + private boolean matchesParameter(CalendarContent.Parsed parsed, String name, String text) { var property = new PropertyFilter( diff --git a/src/test/java/org/busystack/caldav/calendar/CalendarRemainingValuesTest.java b/src/test/java/org/busystack/caldav/calendar/CalendarRemainingValuesTest.java new file mode 100644 index 0000000..cde2dba --- /dev/null +++ b/src/test/java/org/busystack/caldav/calendar/CalendarRemainingValuesTest.java @@ -0,0 +1,143 @@ +package org.busystack.caldav.calendar; + +import static org.assertj.core.api.Assertions.*; + +import java.util.stream.Stream; +import org.busystack.caldav.calendar.query.QueryException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +class CalendarRemainingValuesTest { + static CalendarContent.Parsed parse(String fields) { + return CalendarSemanticsTest.parse( + "VEVENT", + "DTSTART:20261109T090000Z\r\n" + fields + (fields.endsWith("\r\n") ? "" : "\r\n")); + } + + @Test + void explicitDefaultAttachmentEncodingSurvivesModelCopies() { + var parsed = parse("ATTACH;ENCODING=8BIT:https://example.invalid/file"); + var copied = parsed.calendar().copy(); + assertThat(copied.toString()).contains("ATTACH;ENCODING=8BIT:https://example.invalid/file"); + assertThat(copied.getComponents().getFirst().getRequiredProperty("ATTACH").getValue()) + .isEqualTo("https://example.invalid/file"); + } + + @ParameterizedTest + @ValueSource( + strings = { + "240000", + "236000", + "235961", + "0900", + "09:00:00", + "090000.5", + "090000-0800", + "", + "090000Z,250000" + }) + void declaredTimeRejectsMalformedOrOutOfRangeValues(String value) { + assertThatThrownBy(() -> parse("X-TIME;VALUE=TIME:" + value)) + .isInstanceOf(CalendarValidationException.class); + } + + @ParameterizedTest + @ValueSource(strings = {"000000", "235959", "090000Z", "235960Z", "090000,100000"}) + void declaredTimePreservesValidFloatingUtcAndListValues(String value) { + var parsed = parse("X-TIME;VALUE=TIME:" + value); + var property = parsed.calendar().getComponents().getFirst().getRequiredProperty("X-TIME"); + assertThat(parsed.lexicalValue(property)).isEqualTo(value); + assertThat(property.getParameter("VALUE").orElseThrow().getValue()).isEqualTo("TIME"); + } + + @ParameterizedTest + @ValueSource( + strings = { + "X-TIME;VALUE=TIME;TZID=Europe/Berlin:090000Z", + "X-TIME;VALUE=TIME;TZID=Europe/Berlin:090000,100000Z" + }) + void utcTimeCannotCarryTimezoneReference(String field) { + assertThatThrownBy(() -> parse(field)).isInstanceOf(CalendarValidationException.class); + } + + @ParameterizedTest + @ValueSource( + strings = { + "X-TIME;VALUE=TIME;TZID=Europe/Berlin:090000", + "X-OPAQUE:240000", + "X-OPAQUE;VALUE=X-FUTURE:240000" + }) + void validZonedTimeAndUndeclaredFutureDataRemainPreserved(String field) { + assertThatCode(() -> parse(field)).doesNotThrowAnyException(); + } + + static Stream attachments() { + return Stream.of( + Arguments.of("ATTACH:https://example.invalid/file", true), + Arguments.of("ATTACH;VALUE=URI:urn:example:attachment", true), + Arguments.of("ATTACH;ENCODING=8BIT:https://example.invalid/file", true), + Arguments.of("ATTACH;FMTTYPE=text/plain;X-PARAM=opaque:https://example.invalid/file", true), + Arguments.of("ATTACH;VALUE=BINARY;ENCODING=BASE64;FMTTYPE=text/plain:SGVsbG8=", true), + Arguments.of("ATTACH;ENCODING=BASE64;VALUE=BINARY:SGVsbG8=", true), + Arguments.of("ATTACH;VALUE=BINARY;ENCODING=BASE64:", true), + Arguments.of("ATTACH;VALUE=BINARY;ENCODING=BASE64:AA==", true), + Arguments.of("ATTACH;VALUE=BINARY;ENCODING=BASE64:AAA=", true), + Arguments.of("ATTACH;VALUE=BINARY;ENCODING=BASE64:AAAA", true), + Arguments.of("ATTACH;VALUE=TEXT:https://example.invalid/file", false), + Arguments.of("ATTACH;VALUE=X-FUTURE:https://example.invalid/file", false), + Arguments.of("ATTACH;VALUE=BINARY:SGVsbG8=", false), + Arguments.of("ATTACH;ENCODING=BASE64:https://example.invalid/file", false), + Arguments.of("ATTACH;VALUE=URI;ENCODING=BASE64:SGVsbG8=", false), + Arguments.of("ATTACH;VALUE=BINARY;ENCODING=8BIT:SGVsbG8=", false), + Arguments.of("ATTACH;VALUE=BINARY;ENCODING=BASE64:SGVsbG8", false), + Arguments.of("ATTACH;VALUE=BINARY;ENCODING=BASE64:SGVsbG8!", false), + Arguments.of("ATTACH;VALUE=BINARY;ENCODING=BASE64:A===", false), + Arguments.of("ATTACH;VALUE=BINARY;ENCODING=BASE64:AA=A", false), + Arguments.of("ATTACH;FMTTYPE=malformed:https://example.invalid/file", false)); + } + + @ParameterizedTest + @MethodSource("attachments") + void attachmentsUseOnlyTheirDefinedRepresentationsAndParameters(String field, boolean valid) { + if (valid) { + var parsed = parse(field); + var property = parsed.calendar().getComponents().getFirst().getRequiredProperty("ATTACH"); + assertThat(parsed.lexicalValue(property)).isEqualTo(field.substring(field.indexOf(':') + 1)); + } else assertThatThrownBy(() -> parse(field)).isInstanceOf(CalendarValidationException.class); + } + + @Test + void duplicateAttachmentFormatParameterHasTheRequiredInvalidDataRejection() { + assertThatThrownBy( + () -> parse("ATTACH;FMTTYPE=text/plain;FMTTYPE=text/html:https://example.invalid/file")) + .isInstanceOfSatisfying( + QueryException.class, + error -> assertThat(error.kind()).isEqualTo(QueryException.Kind.INVALID_DATA)); + } + + @Test + void attachmentContextsKeepRepeatedEventTaskAndEmailDataButAudioHasOnlyOne() { + String attachments = + "ATTACH:https://example.invalid/file\r\nATTACH;VALUE=BINARY;ENCODING=BASE64:SGVsbG8=\r\n"; + assertThatCode(() -> parse(attachments)).doesNotThrowAnyException(); + assertThatCode(() -> CalendarSemanticsTest.parse("VTODO", attachments)) + .doesNotThrowAnyException(); + String email = + "BEGIN:VALARM\r\nACTION:EMAIL\r\nTRIGGER:-PT5M\r\nDESCRIPTION:Reminder\r\nSUMMARY:Reminder\r\nATTENDEE:mailto:synthetic@example.invalid\r\n" + + attachments + + "END:VALARM\r\n"; + assertThatCode(() -> parse(email)).doesNotThrowAnyException(); + String audio = + "BEGIN:VALARM\r\nACTION:AUDIO\r\nTRIGGER:-PT5M\r\nATTACH:https://example.invalid/sound\r\nEND:VALARM\r\n"; + assertThatCode(() -> parse(audio)).doesNotThrowAnyException(); + assertThatThrownBy( + () -> + parse( + audio.replace( + "END:VALARM", "ATTACH:https://example.invalid/second\r\nEND:VALARM"))) + .isInstanceOf(CalendarValidationException.class); + } +} diff --git a/src/test/java/org/busystack/caldav/calendar/CalendarTemporalFormTest.java b/src/test/java/org/busystack/caldav/calendar/CalendarTemporalFormTest.java new file mode 100644 index 0000000..00ae76a --- /dev/null +++ b/src/test/java/org/busystack/caldav/calendar/CalendarTemporalFormTest.java @@ -0,0 +1,46 @@ +package org.busystack.caldav.calendar; + +import static org.assertj.core.api.Assertions.*; + +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class CalendarTemporalFormTest { + static Stream fields() { + return Stream.of("DTEND", "DUE", "RECURRENCE-ID") + .flatMap(field -> Stream.of(true, false).map(floating -> Arguments.of(field, floating))); + } + + @ParameterizedTest + @MethodSource("fields") + void linkedDatesDoNotMixFloatingAndAbsoluteForms(String field, boolean floatingStart) { + String start = "20261109T090000" + (floatingStart ? "" : "Z"); + String end = "20261109T100000" + (floatingStart ? "Z" : ""); + assertThatThrownBy( + () -> + CalendarSemanticsTest.parse( + field.equals("DUE") ? "VTODO" : "VEVENT", + "DTSTART:" + start + "\r\n" + field + ":" + end + "\r\n")) + .isInstanceOf(CalendarValidationException.class); + } + + @ParameterizedTest + @MethodSource("fields") + void matchingFloatingAndAbsoluteFormsRemainValid(String field, boolean floatingStart) { + String suffix = floatingStart ? "" : "Z"; + assertThatCode( + () -> + CalendarSemanticsTest.parse( + field.equals("DUE") ? "VTODO" : "VEVENT", + "DTSTART:20261109T090000" + + suffix + + "\r\n" + + field + + ":20261109T100000" + + suffix + + "\r\n")) + .doesNotThrowAnyException(); + } +} diff --git a/src/test/java/org/busystack/caldav/calendar/ParticipantInterchangeTest.java b/src/test/java/org/busystack/caldav/calendar/ParticipantInterchangeTest.java new file mode 100644 index 0000000..2d7c9c2 --- /dev/null +++ b/src/test/java/org/busystack/caldav/calendar/ParticipantInterchangeTest.java @@ -0,0 +1,52 @@ +package org.busystack.caldav.calendar; + +import static org.assertj.core.api.Assertions.*; +import static org.busystack.caldav.calendar.CalendarSemanticsTest.parse; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class ParticipantInterchangeTest { + @ParameterizedTest + @ValueSource(strings = {"ACTIVE", "active", "INACTIVE", "SPONSOR"}) + void participantTypeAndParametersArePreservedThroughTheOfficialMutableModel(String type) { + var parsed = + parse( + "VEVENT", + "DTSTART:20260120T120000Z\r\nBEGIN:PARTICIPANT\r\n" + + "UID:participant\r\nPARTICIPANT-TYPE;X-RETAIN=opaque:" + + type + + "\r\nCALENDAR-ADDRESS:mailto:synthetic@example.invalid\r\nEND:PARTICIPANT\r\n"); + String report = parsed.calendar().copy().toString(); + assertThat(report) + .contains( + "BEGIN:PARTICIPANT", + "UID:participant", + "PARTICIPANT-TYPE;X-RETAIN=opaque:" + type, + "CALENDAR-ADDRESS:mailto:synthetic@example.invalid"); + } + + @Test + void currentParticipantAndEventStatusComponentsRemainDataRatherThanAutomation() { + for (String component : new String[] {"VEVENT", "VTODO"}) { + String fields = + (component.equals("VEVENT") + ? "DTSTART:20260120T120000Z\r\nSTATUS:CONFIRMED\r\n" + : "STATUS:FAILED\r\n") + + "BEGIN:PARTICIPANT\r\nUID:participant\r\nPARTICIPANT-TYPE:ACTIVE\r\n" + + "STATUS:FAILED\r\nPERCENT-COMPLETE:25\r\nREASON:https://example.invalid/reason\r\n" + + "BEGIN:VSTATUS\r\nSTATUS:FAILED\r\nSUBSTATE:ERROR\r\nEND:VSTATUS\r\nEND:PARTICIPANT\r\n" + + "BEGIN:VSTATUS\r\nSTATUS:" + + (component.equals("VEVENT") ? "CONFIRMED" : "FAILED") + + "\r\nCOMMENT:Preserved history\r\nEND:VSTATUS\r\n"; + var parsed = parse(component, fields); + assertThat(parsed.calendar().copy().toString()) + .contains( + "PERCENT-COMPLETE:25", + "STATUS:FAILED", + "REASON:https://example.invalid/reason", + "COMMENT:Preserved history"); + } + } +} diff --git a/src/test/java/org/busystack/caldav/calendar/Rfc10051TaskTest.java b/src/test/java/org/busystack/caldav/calendar/Rfc10051TaskTest.java new file mode 100644 index 0000000..7dd8f7e --- /dev/null +++ b/src/test/java/org/busystack/caldav/calendar/Rfc10051TaskTest.java @@ -0,0 +1,114 @@ +package org.busystack.caldav.calendar; + +import static org.assertj.core.api.Assertions.*; +import static org.busystack.caldav.calendar.CalendarSemanticsTest.*; + +import java.time.ZoneOffset; +import org.busystack.caldav.calendar.query.*; +import org.busystack.caldav.calendar.recurrence.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class Rfc10051TaskTest { + @ParameterizedTest + @ValueSource( + strings = { + "ESTIMATED-DURATION:PT30M\r\n", + "TASK-MODE:CLIENT\r\n", + "ATTENDEE;PARTSTAT=FAILED:mailto:synthetic@example.invalid\r\n", + "BEGIN:VSTATUS\r\nSTATUS:FAILED\r\nSUBSTATE:ERROR\r\nREASON:https://example.invalid/reason\r\nDTSTAMP:20261108T000000Z\r\nEND:VSTATUS\r\n" + }) + void registeredTaskMetadataIsValid(String fields) { + assertThatCode(() -> parse("VTODO", "STATUS:FAILED\r\nDURATION:PT1H\r\n" + fields)) + .doesNotThrowAnyException(); + } + + @ParameterizedTest + @ValueSource(strings = {"PT1H", "P2D", "P1W"}) + void durationOnlyTasksStayUndatedInQueryAndExpansion(String value) { + var parsed = parse("VTODO", "DURATION:" + value + "\r\n"); + var range = range("2030-01-01T00:00:00Z", "2030-01-02T00:00:00Z"); + assertThat(match(parsed, "VTODO", range)).isTrue(); + var recurrence = new CalendarRecurrence(QueryLimits.defaults()); + var expanded = recurrence.expand(parsed, range, FloatingTimezone.of(ZoneOffset.UTC)); + var task = expanded.getComponents().getFirst(); + assertThat(task.getProperty("DTSTART")).isEmpty(); + assertThat(task.getProperty("DUE")).isEmpty(); + assertThat(task.getRequiredProperty("DURATION").getValue()).isEqualTo(value); + } + + @ParameterizedTest + @ValueSource( + strings = {"PENDING", "FAILED", "NEEDS-ACTION", "COMPLETED", "IN-PROCESS", "CANCELLED"}) + void currentStatusesAndTheirParametersSurviveCopiesAndRecurringExpansion(String status) { + var parsed = + parse( + "VTODO", + "DTSTART:20261108T090000Z\r\nDURATION:PT1H\r\n" + + "RRULE:FREQ=DAILY;COUNT=2\r\nSTATUS;X-REASON=retained:" + + status + + "\r\n"); + var copy = parsed.calendar().copy(); + assertThat(copy.validate().hasErrors()).isFalse(); + var expanded = + new CalendarRecurrence(QueryLimits.defaults()) + .expand( + parsed, + range("2026-11-08T00:00:00Z", "2026-11-10T00:00:00Z"), + FloatingTimezone.of(ZoneOffset.UTC)); + assertThat(expanded.getComponents()).hasSize(2); + for (var task : expanded.getComponents()) { + assertThat(task.getRequiredProperty("STATUS").getValue()).isEqualTo(status); + assertThat(task.getRequiredProperty("STATUS").getRequiredParameter("X-REASON").getValue()) + .isEqualTo("retained"); + assertThat(task.getRequiredProperty("DUE").getValue()).endsWith("100000Z"); + } + } + + @Test + void currentTaskMetadataAndStatusComponentsArePreservedWithoutAutomation() { + var parsed = + parse( + "VTODO", + "STATUS:FAILED\r\nDURATION:PT1H\r\n" + + "ESTIMATED-DURATION:PT30M\r\nTASK-MODE:CLIENT\r\n" + + "ATTENDEE;PARTSTAT=FAILED;REASON=\"https://example.invalid/reason\":mailto:synthetic@example.invalid\r\n" + + "BEGIN:VSTATUS\r\nSTATUS:FAILED\r\nSUBSTATE:ERROR\r\n" + + "REASON:https://example.invalid/reason\r\nDTSTAMP:20261108T000000Z\r\nEND:VSTATUS\r\n"); + assertThat(parsed.calendar().toString()) + .contains("STATUS:FAILED", "PARTSTAT=FAILED", "ESTIMATED-DURATION:PT30M", "BEGIN:VSTATUS"); + assertThat(parsed.calendar().copy().toString()).contains("STATUS:FAILED", "SUBSTATE:ERROR"); + } + + @ParameterizedTest + @ValueSource( + strings = { + "DURATION:PT0S", + "DURATION:-PT1H", + "DURATION:P1DT", + "DURATION:P1W2D", + "DUE:20261108T090000Z\r\nDURATION:PT1H", + "DURATION:PT1H\r\nDURATION:PT2H", + "STATUS:BOGUS", + "STATUS:CONFIRMED", + "STATUS:PENDING\r\nSTATUS:FAILED", + "ESTIMATED-DURATION:-PT1H", + "ESTIMATED-DURATION:PT0S", + "STATUS:PENDING\r\nBEGIN:VALARM\r\nACTION:DISPLAY\r\nTRIGGER:-PT1H\r\nEND:VALARM", + "BEGIN:VSTATUS\r\nSTATUS:FAILED\r\nEND:VSTATUS", + "STATUS:PENDING\r\nBEGIN:VSTATUS\r\nEND:VSTATUS" + }) + void currentTaskSupportDoesNotAdmitInvalidData(String fields) { + assertThatThrownBy(() -> parse("VTODO", fields + "\r\n")) + .isInstanceOf(CalendarValidationException.class); + } + + @ParameterizedTest + @ValueSource(strings = {"PENDING", "FAILED", "BOGUS"}) + void taskStatusesDoNotBecomeValidEventStatuses(String status) { + assertThatThrownBy( + () -> parse("VEVENT", "DTSTART:20261108T090000Z\r\nSTATUS:" + status + "\r\n")) + .isInstanceOf(CalendarValidationException.class); + } +} diff --git a/src/test/java/org/busystack/caldav/calendar/TaskStatusMetadataTest.java b/src/test/java/org/busystack/caldav/calendar/TaskStatusMetadataTest.java new file mode 100644 index 0000000..bfca0ee --- /dev/null +++ b/src/test/java/org/busystack/caldav/calendar/TaskStatusMetadataTest.java @@ -0,0 +1,64 @@ +package org.busystack.caldav.calendar; + +import static org.assertj.core.api.Assertions.*; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class TaskStatusMetadataTest { + private static String status(String fields) { + return "STATUS:FAILED\r\nBEGIN:VSTATUS\r\nSTATUS:FAILED\r\n" + fields + "END:VSTATUS\r\n"; + } + + @ParameterizedTest + @ValueSource( + strings = { + "REASON:relative-reason\r\n", + "REASON:/relative/reason\r\n", + "REASON:\r\n", + "REASON:https://example.invalid/with space\r\n", + "SUBSTATE:NOT A TOKEN\r\n", + "SUBSTATE:\r\n", + "SUBSTATE:ERROR!\r\n" + }) + void statusMetadataRequiresUriAndTokenSyntax(String fields) { + assertThatThrownBy(() -> CalendarSemanticsTest.parse("VTODO", status(fields))) + .isInstanceOf(CalendarValidationException.class); + } + + @ParameterizedTest + @ValueSource( + strings = { + "REASON:https://example.invalid/reason\r\n", + "SUBSTATE:ERROR\r\n", + "BEGIN:PARTICIPANT\r\nUID:participant\r\nPARTICIPANT-TYPE:ACTIVE\r\n" + + "REASON:urn:reason:first\r\nREASON:urn:reason:second\r\nEND:PARTICIPANT\r\n", + "BEGIN:PARTICIPANT\r\nUID:participant\r\nPARTICIPANT-TYPE:ACTIVE\r\n" + + "PERCENT-COMPLETE:10\r\nPERCENT-COMPLETE:20\r\nEND:PARTICIPANT\r\n" + }) + void metadataStaysInItsDefinedComponentAndCardinality(String fields) { + assertThatThrownBy(() -> CalendarSemanticsTest.parse("VTODO", fields)) + .isInstanceOf(CalendarValidationException.class); + } + + @ParameterizedTest + @ValueSource( + strings = { + "REASON:https://example.invalid/reason?query=one%20two#fragment\r\n", + "REASON:urn:example:reason\r\n", + "SUBSTATE:OK\r\n", + "SUBSTATE:ERROR\r\n", + "SUBSTATE:SUSPENDED\r\n", + "SUBSTATE:X-WAIT\r\n", + "SUBSTATE:future-token\r\n" + }) + void validStatusMetadataAndUnknownParametersArePreserved(String fields) { + var parsed = + CalendarSemanticsTest.parse( + "VTODO", + status(fields) + + "ATTENDEE;REASON=opaque;SUBSTATE=opaque:mailto:synthetic@example.invalid\r\n"); + assertThat(parsed.calendar().copy().toString()) + .contains(fields.strip(), "REASON=opaque", "SUBSTATE=opaque"); + } +} diff --git a/src/test/java/org/busystack/caldav/calendar/TimezoneNameInterchangeTest.java b/src/test/java/org/busystack/caldav/calendar/TimezoneNameInterchangeTest.java new file mode 100644 index 0000000..2e2443d --- /dev/null +++ b/src/test/java/org/busystack/caldav/calendar/TimezoneNameInterchangeTest.java @@ -0,0 +1,56 @@ +package org.busystack.caldav.calendar; + +import static org.assertj.core.api.Assertions.*; + +import java.nio.charset.StandardCharsets; +import java.time.ZoneOffset; +import org.busystack.caldav.calendar.query.*; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class TimezoneNameInterchangeTest { + private static String calendar(String kind, String fields) { + return "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Repeated timezone names//EN\r\n" + + "BEGIN:VTIMEZONE\r\nTZID:Qualification/Fixed\r\nBEGIN:" + + kind + + "\r\n" + + "DTSTART:19700101T000000\r\nTZOFFSETFROM:+0200\r\nTZOFFSETTO:+0200\r\n" + + fields + + "END:" + + kind + + "\r\nEND:VTIMEZONE\r\nEND:VCALENDAR\r\n"; + } + + @ParameterizedTest + @ValueSource(strings = {"STANDARD", "DAYLIGHT"}) + void multilingualNamesSurviveValidationCopyAndTimezoneUse(String kind) { + String names = "TZNAME;LANGUAGE=en:Fixed\r\nTZNAME;LANGUAGE=de:Fest\r\n"; + String timezone = calendar(kind, names); + assertThat( + FloatingTimezone.parse(timezone) + .zoneId() + .getRules() + .getOffset(java.time.Instant.parse("2026-11-09T00:00:00Z"))) + .isEqualTo(ZoneOffset.ofHours(2)); + String data = + timezone.replace( + "END:VCALENDAR", + "BEGIN:VEVENT\r\nUID:names\r\nDTSTAMP:20261109T000000Z\r\nDTSTART;TZID=Qualification/Fixed:20261109T090000\r\nEND:VEVENT\r\nEND:VCALENDAR"); + var parsed = CalendarContent.parse(data.getBytes(StandardCharsets.UTF_8), "VEVENT"); + assertThat(parsed.calendar().copy().toString()).contains(names); + assertThat(CalendarSemanticsTest.point(parsed, "VEVENT", "2026-11-09T07:00:00Z")).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"STANDARD", "DAYLIGHT"}) + void repeatedNamesDoNotDisableUnrelatedMandatoryOrPropertyValidation(String kind) { + String valid = calendar(kind, "TZNAME:First\r\nTZNAME:Second\r\n"); + for (String invalid : + java.util.List.of( + valid.replace("TZOFFSETFROM:+0200\r\n", ""), + valid.replace("TZOFFSETTO:+0200", "TZOFFSETTO:+2400"), + valid.replace("DTSTART:19700101T000000\r\n", ""))) + assertThatThrownBy(() -> FloatingTimezone.parse(invalid)) + .isInstanceOf(RuntimeException.class); + } +} 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..22885d2 --- /dev/null +++ b/src/test/java/org/busystack/caldav/config/PortabilityWorkFilterTest.java @@ -0,0 +1,104 @@ +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 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())) { + 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/config/RequestDiagnosticsFilterTest.java b/src/test/java/org/busystack/caldav/config/RequestDiagnosticsFilterTest.java new file mode 100644 index 0000000..99bce21 --- /dev/null +++ b/src/test/java/org/busystack/caldav/config/RequestDiagnosticsFilterTest.java @@ -0,0 +1,78 @@ +package org.busystack.caldav.config; + +import static org.assertj.core.api.Assertions.*; + +import jakarta.servlet.DispatcherType; +import jakarta.servlet.ServletException; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +class RequestDiagnosticsFilterTest { + @Test + void recordsFinalErrorStatusWithOriginalCoarseMetadataAndCorrelation() throws Exception { + var problems = new OperationalProblems(); + var filter = new RequestDiagnosticsFilter(problems); + var request = new MockHttpServletRequest("REPORT", "/team/dav/private-resource"); + request.setContextPath("/team"); + var first = new MockHttpServletResponse(); + assertThatThrownBy( + () -> + filter.doFilter( + request, + first, + (r, s) -> { + throw new ServletException("Private contents must never become a diagnostic"); + })) + .isInstanceOf(ServletException.class); + assertThat(problems.recent()).isEmpty(); + request.setMethod("GET"); + request.setRequestURI("/team/error"); + request.setDispatcherType(DispatcherType.ERROR); + var error = new MockHttpServletResponse(); + filter.doFilter(request, error, (r, s) -> error.setStatus(503)); + assertThat(error.getHeader("X-Request-ID")).isEqualTo(first.getHeader("X-Request-ID")); + assertThat(problems.recent()) + .singleElement() + .satisfies( + p -> { + assertThat(p.requestId()).isEqualTo(first.getHeader("X-Request-ID")); + assertThat(p.surface()).isEqualTo("dav"); + assertThat(p.method()).isEqualTo("REPORT"); + assertThat(p.status()).isEqualTo(503); + assertThat(p.toString()).doesNotContain("private-resource", "Private contents"); + }); + } + + @Test + void handledClientErrorsNeverBecomeOperationalServerFailures() throws Exception { + var problems = new OperationalProblems(); + var filter = new RequestDiagnosticsFilter(problems); + var request = new MockHttpServletRequest("POST", "/portability/preview"); + assertThatThrownBy( + () -> + filter.doFilter( + request, + new MockHttpServletResponse(), + (r, s) -> { + throw new ServletException("Upload rejected before MVC"); + })) + .isInstanceOf(ServletException.class); + request.setDispatcherType(DispatcherType.ERROR); + var response = new MockHttpServletResponse(); + filter.doFilter(request, response, (r, s) -> response.setStatus(413)); + assertThat(problems.recent()).isEmpty(); + } + + @Test + void finalDispatchReplacesEarlierStatusAndProblemRetentionRemainsBounded() { + var problems = new OperationalProblems(); + for (int n = 0; n < 60; n++) problems.record("request-" + n, "browser", "POST", 503); + assertThat(problems.recent()).hasSize(50); + problems.record("request-59", "browser", "POST", 500); + assertThat(problems.recent()).hasSize(50); + assertThat(problems.recent().getFirst().status()).isEqualTo(500); + problems.record("request-59", "browser", "POST", 413); + assertThat(problems.recent()).hasSize(49).noneMatch(p -> p.requestId().equals("request-59")); + } +} diff --git a/src/test/java/org/busystack/caldav/management/DavConnectionAdviceTest.java b/src/test/java/org/busystack/caldav/management/DavConnectionAdviceTest.java new file mode 100644 index 0000000..fdb6d1c --- /dev/null +++ b/src/test/java/org/busystack/caldav/management/DavConnectionAdviceTest.java @@ -0,0 +1,28 @@ +package org.busystack.caldav.management; + +import static org.assertj.core.api.Assertions.*; + +import java.net.URI; +import org.junit.jupiter.api.Test; + +class DavConnectionAdviceTest { + @Test + void gnomeAddressRetainsConfiguredOriginSubpathAndOnlyTheAccountUsername() { + for (String address : + java.util.List.of( + "https://calendar.example/dav/", + "https://calendar.example:8443/team/dav/", + "https://[::1]:8443/team/dav/")) { + var expected = URI.create(address); + var connection = new DavConnectionAdvice.Connection(address, "family+one@example", "", true); + var actual = URI.create(connection.gnomeUrl()); + assertThat(actual.getScheme()).isEqualTo(expected.getScheme()); + assertThat(actual.getHost()).isEqualTo(expected.getHost()); + assertThat(actual.getPort()).isEqualTo(expected.getPort()); + assertThat(actual.getPath()).isEqualTo(expected.getPath()); + assertThat(actual.getUserInfo()).isEqualTo("family+one@example"); + assertThat(actual.getQuery()).isNull(); + assertThat(actual.getFragment()).isNull(); + } + } +} 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..30803a7 --- /dev/null +++ b/src/test/java/org/busystack/caldav/management/ImportStagingTest.java @@ -0,0 +1,199 @@ +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(), + new UUID(0, 1), + "VEVENT", + "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..8f7d307 --- /dev/null +++ b/src/test/java/org/busystack/caldav/management/PortabilityStorageTest.java @@ -0,0 +1,222 @@ +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; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.api.parallel.Resources; + +class PortabilityStorageTest { + @TempDir Path temporary; + + @Test + @ResourceLock(Resources.SYSTEM_PROPERTIES) + void privateStorageUsesTheFilesystemOwnerWhenTheProcessUserHasNoAccount() throws Exception { + Path root = temporary.resolve("private"); + String originalName = + System.setProperty("user.name", "busystack-unmapped-" + UUID.randomUUID()); + try (var storage = new PortabilityStorage(root.toString()); + var files = Files.list(root)) { + assertThat(storage.reservedBytes()).isZero(); + assertThat(files).containsExactly(root.resolve("instance.lock")); + } finally { + System.setProperty("user.name", originalName); + } + } + + @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())) { + 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..3ced1bc --- /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), mock(PortalPageAdvice.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 new file mode 100644 index 0000000..d7e8205 --- /dev/null +++ b/src/test/java/org/busystack/caldav/management/PortalManagementIT.java @@ -0,0 +1,2657 @@ +package org.busystack.caldav.management; + +import static org.assertj.core.api.Assertions.*; + +import java.net.URI; +import java.net.URLEncoder; +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.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 PortabilityStorage portabilityStorage; + @Autowired org.busystack.caldav.calendar.CalendarInterchange interchange; + @Autowired AccountService accounts; + @Autowired CalendarStore calendars; + @Autowired DavStore dav; + @Autowired GroupService groups; + @Autowired org.busystack.caldav.config.OperationalProblems problems; + @Autowired JdbcTemplate jdbc; + @Autowired org.busystack.caldav.security.IssuanceIntents issuance; + @Autowired org.busystack.caldav.security.recovery.RecoveryService recovery; + @Autowired org.busystack.caldav.security.oauth.OAuthClientService oauthClients; + + @Autowired + org.springframework.session.SessionRepository + sessions; + + private SignedPasskeyClient transport; + private final Map browserKeys = new HashMap<>(); + @Autowired org.springframework.transaction.PlatformTransactionManager transactions; + @LocalServerPort int port; + UUID admin, owner, reader, other, collection; + final String hostile = ""; + + @BeforeEach + void prepare() { + transport = new SignedPasskeyClient(port, "/team", "https://localhost"); + // Each separate case starts with a new request quota for the shared loopback peer. + FixtureDatabase.reset( + jdbc, + "TRUNCATE spring_session,security_audit,browser_flow_state,login_throttle 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"); + } + + @AfterEach + void closeBrowserFixtures() { + transport.close(); + } + + @Test + void concurrentIssuanceAndRecoveryGenerationRejectReplayAndStaleSets() throws Exception { + var authentication = auth(owner, true); + var purpose = org.busystack.caldav.security.IssuanceIntents.Purpose.APPLICATION_PASSWORD; + var intent = issuance.prepare(authentication, purpose, "generic:security"); + assertThatThrownBy( + () -> management.issue(authentication, "", 90, intent.id(), "generic:security")) + .isInstanceOf(FormValidation.class); + try (var workers = java.util.concurrent.Executors.newFixedThreadPool(2)) { + var ready = new java.util.concurrent.CountDownLatch(1); + java.util.concurrent.Callable submit = + () -> { + ready.await(); + return management.issue( + authentication, "Concurrent fixture", 90, intent.id(), "generic:security"); + }; + var first = workers.submit(submit); + var second = workers.submit(submit); + ready.countDown(); + var a = first.get(); + var b = second.get(); + assertThat(a.credentialId()).isEqualTo(b.credentialId()); + assertThat(java.util.stream.Stream.of(a, b).filter(result -> result.secret() != null)) + .hasSize(1); + } + var recoveryPurpose = org.busystack.caldav.security.IssuanceIntents.Purpose.RECOVERY_CODES; + var left = issuance.prepare(authentication, recoveryPurpose, ""); + var right = issuance.prepare(authentication, recoveryPurpose, ""); + assertThat(recovery.issue(authentication, "127.0.0.1", left.id(), false).codes()).hasSize(10); + assertThat(recovery.issue(authentication, "127.0.0.1", left.id(), false)).isNull(); + assertThatThrownBy(() -> recovery.issue(authentication, "127.0.0.1", right.id(), true)) + .isInstanceOf(org.busystack.caldav.security.IssuanceIntents.Unavailable.class); + assertThat(recovery.status(authentication).remaining()).isEqualTo(10); + } + + @Test + void opposingBrowserDisablesKeepAnEnabledAdministrator() throws Exception { + var second = + accounts.provision( + "second-administrator", "Second administrator", "Second administrator password", true); + var firstAuth = auth(admin, true); + var secondAuth = auth(second, true); + assertThatThrownBy(() -> administration.disable(firstAuth, admin, true)) + .isInstanceOf(AccessDeniedException.class); + try (var workers = java.util.concurrent.Executors.newFixedThreadPool(2)) { + var ready = new java.util.concurrent.CountDownLatch(1); + var left = workers.submit(() -> tryDisable(ready, firstAuth, second)); + var right = workers.submit(() -> tryDisable(ready, secondAuth, admin)); + ready.countDown(); + assertThat(left.get()).isNotEqualTo(right.get()); + } + assertThat( + jdbc.queryForObject( + "SELECT count(*) FROM accounts WHERE enabled AND administrator", Long.class)) + .isEqualTo(1); + } + + private boolean tryDisable( + java.util.concurrent.CountDownLatch ready, Authentication actor, UUID target) + throws InterruptedException { + ready.await(); + try { + administration.disable(actor, target, true); + return true; + } catch (AccessDeniedException denied) { + return false; + } + } + + @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(); + 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(); + var unconfirmed = + post( + administrator, + "/admin/groups/" + group + "/members/" + last + "/remove", + Map.of("_csrf", csrf(members.body()), "memberPage", "1", "memberQuery", "paged-50")); + assertThat(unconfirmed.statusCode()).isEqualTo(302); + String location = unconfirmed.headers().firstValue("Location").orElseThrow(); + assertThat(location).contains("q=paged-50", "page=1"); + assertThat(get(administrator, transport.localPath(location)).body()) + .contains("Remove paged-50 from Paged group"); + assertThat(groups.detail(auth(admin, true), group).members()).isEqualTo(51); + } + + @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); + 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 changedGroupPermissionInvalidatesMembershipReviewEvenWhenGrantCountMatches() + throws Exception { + var administrator = browser(admin, true); + UUID group = groups.create(auth(admin, true), "Review revision", Set.of()); + sharing.group(auth(owner, true), collection, group, "READ", "NONE"); + var review = groups.detail(auth(admin, true), group); + String path = "/admin/groups/" + group; + var form = get(administrator, path); + assertThat(form.body()).contains(review.grantState()); + sharing.group(auth(owner, true), collection, group, "WRITE", "READ"); + var current = groups.detail(auth(admin, true), group); + assertThat(current.grants()).isEqualTo(review.grants()); + assertThat(current.grantState()).isNotEqualTo(review.grantState()); + var stale = + post( + administrator, + path + "/members", + Map.of( + "_csrf", + csrf(form.body()), + "username", + "portal-reader", + "confirmed", + "true", + "expectedGrants", + review.grantState())); + assertThat(stale.statusCode()).isEqualTo(412); + assertThat(groups.members(auth(admin, true), group, "", 0).rows()).isEmpty(); + denied(() -> dav.permission(reader, collection)); + } + + @Test + void clientAndAuthorizedResourceSurvivePagingValidationAndCredentialIssuance() throws Exception { + var browser = browser(owner, true); + var address = portal.collection(auth(owner, true), collection).address(); + String context = "client=thunderbird&resource=" + collection; + var connections = get(browser, "/connections?page=1&" + context); + assertThat(connections.body()) + .contains("Set up Thunderbird", "selected-resource-address", address, "page=0") + .contains("resource=" + collection); + var form = get(browser, "/security/credentials/new?from=connect&" + context); + var intent = + java.util.regex.Pattern.compile("name=\"intent\" value=\"([a-f0-9-]{36})\"") + .matcher(form.body()); + assertThat(intent.find()).isTrue(); + var fields = new java.util.HashMap(); + fields.put("_csrf", csrf(form.body())); + fields.put("from", "connect"); + fields.put("client", "thunderbird"); + fields.put("resource", collection.toString()); + fields.put("days", "90"); + fields.put("intent", intent.group(1)); + fields.put("label", ""); + var invalid = post(browser, "/credentials", fields); + fieldError(invalid, 400, "credential-create", "label"); + assertThat(invalid.body()).contains("name=\"resource\" value=\"" + collection + "\""); + fields.put("label", "Test app"); + var issued = post(browser, "/credentials", fields); + assertThat(issued.statusCode()).isEqualTo(200); + assertThat( + issued.body().contains("Set up Thunderbird") + && issued.body().contains("issued-secret") + && issued.body().contains(address)) + .isTrue(); + assertThat(get(browser(other, true), "/connections?" + context).statusCode()).isEqualTo(403); + } + + @Test + void credentialInspectionAndRevocationStayAvailableAtIssuanceCapacity() throws Exception { + var browser = browser(owner, true); + var credential = + accounts.issueDavCredential( + owner, "Existing app device", java.time.Instant.now().plusSeconds(3600)); + String context = "?from=connect&client=thunderbird&resource=" + collection; + for (int n = 0; n < 9; n++) + assertThat(get(browser, "/security/credentials" + context).statusCode()).isEqualTo(200); + assertThat( + jdbc.queryForObject( + "SELECT count(*) FROM browser_issuance_intents WHERE account_id=?", + Long.class, + owner)) + .isZero(); + for (int n = 0; n < 8; n++) { + String url = + n % 2 == 0 ? "/security/recovery/codes/new" : "/security/credentials/new" + context; + assertThat(get(browser, url).statusCode()).isEqualTo(200); + } + var denied = get(browser, "/security/credentials/new" + context); + assertThat(denied.statusCode()).isEqualTo(503); + assertThat(denied.body()) + .contains( + "Issuance is busy", "Existing app device", "Back to app setup", "application-shell"); + var list = get(browser, "/security/credentials" + context); + assertThat(list.statusCode()).isEqualTo(200); + assertThat(get(browser, "/security/credentials?page=1").statusCode()).isEqualTo(200); + String revoke = "/credentials/" + credential.id() + "/revoke"; + var review = get(browser, revoke); + assertThat(review.body()).contains("Revoke Existing app device?"); + assertThat( + post(browser, revoke, Map.of("_csrf", csrf(review.body()), "confirmed", "true")) + .statusCode()) + .isEqualTo(302); + assertThat(accounts.verifyDav("portal-owner", credential.secret())).isFalse(); + } + + @Test + void simultaneousAnonymousDestinationsAndWrongPasswordKeepTheirOwnFlow() throws Exception { + var browser = transport.browser(); + String password = "correct horse battery staple"; + get(browser, "/login"); + String resource = "/connections?client=thunderbird&resource=" + collection; + String list = "/collections?scope=owned"; + String first; + String second; + try (var requests = java.util.concurrent.Executors.newFixedThreadPool(2)) { + var ready = new java.util.concurrent.CyclicBarrier(2); + var a = + requests.submit( + () -> { + ready.await(); + return get(browser, resource); + }); + var b = + requests.submit( + () -> { + ready.await(); + return get(browser, list); + }); + first = transport.localPath(a.get().headers().firstValue("Location").orElseThrow()); + second = transport.localPath(b.get().headers().firstValue("Location").orElseThrow()); + } + assertThat(first).startsWith("/login?flow=").isNotEqualTo(second); + assertThat(second).startsWith("/login?flow="); + String flow = first.substring(first.indexOf("flow=") + 5); + String otherFlow = second.substring(second.indexOf("flow=") + 5); + assertThat( + jdbc.queryForList( + "SELECT payload FROM browser_flow_state WHERE section='journey' AND payload LIKE ?", + String.class, + "%" + flow + "%")) + .singleElement() + .asString() + .contains(otherFlow); + var originalForm = get(browser, first); + var failed = + post( + browser, + "/login", + Map.of( + "_csrf", + csrf(originalForm.body()), + "flow", + flow, + "username", + "portal-owner", + "password", + "deliberately incorrect")); + String retry = transport.localPath(failed.headers().firstValue("Location").orElseThrow()); + assertThat(retry).contains("error", "flow=" + flow).doesNotContain(otherFlow); + var secondForm = get(browser, retry); + var signed = + post( + browser, + "/login", + Map.of( + "_csrf", + csrf(secondForm.body()), + "flow", + flow, + "username", + "portal-owner", + "password", + password)); + assertThat(signed.headers().firstValue("Location").orElseThrow()) + .contains("/auth/continue", flow); + var key = transport.enroll(browser); + assertThat( + transport + .assertCredential(transport.options(browser), key, "correct", 0x0d) + .statusCode()) + .isEqualTo(200); + String continuePath = "/auth/continue?flow=" + flow; + try (var requests = java.util.concurrent.Executors.newFixedThreadPool(2)) { + var ready = new java.util.concurrent.CyclicBarrier(2); + java.util.concurrent.Callable claim = + () -> { + ready.await(); + return location(get(browser, continuePath)); + }; + var a = requests.submit(claim); + var b = requests.submit(claim); + assertThat(List.of(a.get(), b.get())).containsExactlyInAnyOrder(resource, "/?interrupted"); + } + assertThat( + get(browser, "/auth/continue?flow=" + otherFlow) + .headers() + .firstValue("Location") + .orElseThrow()) + .contains("/team" + list); + assertThat( + get(browser, "/auth/continue?flow=" + flow) + .headers() + .firstValue("Location") + .orElseThrow()) + .endsWith("/team/?interrupted"); + } + + @Test + void anonymousContinuationEvictsTheOldestAndRejectsExpiredRows() throws Exception { + var browser = transport.browser(); + get(browser, "/login"); + var logins = new java.util.ArrayList(); + for (int request = 0; request < 9; request++) { + logins.add(location(get(browser, "/collections?scope=owned"))); + } + assertThat(logins).doesNotHaveDuplicates().allMatch(path -> path.startsWith("/login?flow=")); + String current = logins.getLast(); + String handle = current.substring(current.indexOf("flow=") + 5); + String evicted = logins.getFirst().substring(logins.getFirst().indexOf("flow=") + 5); + assertThat( + jdbc.queryForObject( + "SELECT count(*) FROM browser_flow_state WHERE section='journey' AND payload LIKE ?", + Integer.class, + "%" + evicted + "%")) + .isZero(); + assertThat( + jdbc.update( + "UPDATE browser_flow_state SET expires_at = now() WHERE section = 'journey' AND payload LIKE ?", + "%" + handle + "%")) + .isEqualTo(1); + var expired = get(browser, current); + var signed = + post( + browser, + "/login", + Map.of( + "_csrf", + csrf(expired.body()), + "flow", + handle, + "username", + "portal-owner", + "password", + "correct horse battery staple")); + assertThat(location(signed)).isEqualTo("/auth/continue?interrupted"); + } + + @Test + void aStaleMemberDraftRetainsTheOriginalGrantReviewAfterReauthentication() throws Exception { + var administrator = browser(admin, true); + UUID group = groups.create(auth(admin, true), "Draft grant revision", Set.of()); + sharing.group(auth(owner, true), collection, group, "READ", "NONE"); + String page = "/admin/groups/" + group; + var original = get(administrator, page); + String expected = groups.detail(auth(admin, true), group).grantState(); + ageFactors(administrator, java.time.Duration.ofSeconds(601), null); + assertThat(get(administrator, page).statusCode()).isEqualTo(200); + var pending = + navigatePost( + administrator, + page + "/members", + Map.of( + "_csrf", + csrf(original.body()), + "username", + "portal-reader", + "confirmed", + "true", + "expectedGrants", + expected)); + assertThat(pending.statusCode()).isEqualTo(303); + sharing.group(auth(owner, true), collection, group, "WRITE", "READ"); + var review = resumeDraft(administrator, pending, admin, true); + assertThat(review.statusCode()).isEqualTo(200); + assertThat(review.body()) + .contains("value=\"" + expected + "\"", "portal-reader") + .doesNotContain("value=\"" + groups.detail(auth(admin, true), group).grantState() + "\""); + var rejected = + post( + administrator, + page + "/members", + Map.of( + "_csrf", + csrf(review.body()), + "username", + "portal-reader", + "confirmed", + "true", + "expectedGrants", + expected)); + assertThat(rejected.statusCode()).isEqualTo(412); + assertThat(groups.members(auth(admin, true), group, "", 0).rows()).isEmpty(); + } + + @Test + void stalePrimaryReturnsToRecoveryCodeEntryWithoutARegisteredKey() throws Exception { + var browser = browser(owner, false); + var start = get(browser, "/security/recovery/use"); + assertThat(start.statusCode()).isEqualTo(200); + ageFactors(browser, java.time.Duration.ofSeconds(601), null); + String submittedCode = "private-recovery-fixture-value"; + var pending = + post( + browser, + "/security/recovery/use", + Map.of("_csrf", csrf(start.body()), "code", submittedCode)); + String login = location(pending); + assertThat(login).startsWith("/login?reauthenticate&flow="); + var form = get(browser, login); + assertThat(form.body()).doesNotContain(submittedCode); + var signed = + post( + browser, + "/login", + Map.of( + "_csrf", + csrf(form.body()), + "username", + "portal-owner", + "password", + "correct horse battery staple", + "flow", + login.substring(login.indexOf("flow=") + 5))); + assertThat(location(signed)).isEqualTo("/security/recovery/use"); + var entry = get(browser, location(signed)); + assertThat(entry.statusCode()).isEqualTo(200); + assertThat(entry.body()) + .contains("Recovery code") + .doesNotContain(submittedCode, "class=\"section-nav"); + } + + @Test + void sharingRemovalNamesThePermissionAndRequiresUnchangedGrantAfterVerification() + throws Exception { + var browser = browser(owner, true); + UUID group = groups.create(auth(admin, true), "Review group", Set.of("portal-reader")); + sharing.direct(auth(owner, true), collection, "portal-reader", "READ", "NONE"); + sharing.group(auth(owner, true), collection, group, "WRITE", "NONE"); + String sharingPath = "/collections/" + collection + "/sharing"; + String direct = sharingPath + "/account/portal-reader/remove"; + String groupReview = sharingPath + "/group/" + group + "/remove"; + assertThat(get(browser, sharingPath).body()).contains(direct, groupReview); + var confirm = get(browser, direct); + assertThat(confirm.body()) + .contains("Remove direct access for portal-reader?", "read-only", "group grants", "Cancel"); + assertThat(get(browser, sharingPath).statusCode()).isEqualTo(200); + ageFactors(browser, java.time.Duration.ofSeconds(601), null); + var pending = + navigatePost( + browser, + direct, + Map.of("_csrf", csrf(confirm.body()), "confirmed", "true", "expected", "READ")); + assertThat(pending.statusCode()).isEqualTo(303); + sharing.direct(auth(owner, true), collection, "portal-reader", "WRITE", "READ"); + var outOfDate = resumeDraft(browser, pending, owner, false); + assertThat(outOfDate.statusCode()).isEqualTo(412); + assertThat(outOfDate.body()).contains(sharingPath); + var current = get(browser, direct); + assertThat( + post( + browser, + direct, + Map.of("_csrf", csrf(current.body()), "confirmed", "true", "expected", "WRITE")) + .statusCode()) + .isEqualTo(302); + assertThat(dav.permission(reader, collection)).isEqualTo("WRITE"); + var groupForm = get(browser, groupReview); + assertThat(groupForm.body()) + .contains("Remove group access for Review group?", "One enabled account will lose access"); + assertThat( + post( + browser, + groupReview, + Map.of( + "_csrf", csrf(groupForm.body()), "confirmed", "true", "expected", "WRITE")) + .statusCode()) + .isEqualTo(302); + denied(() -> dav.permission(reader, collection)); + } + + @Test + void aReplacedImportReportLeadsToTheAuthorizedImportPicker() throws Exception { + var browser = browser(owner, true); + String root = "/portability/import/"; + var first = portability.preview(auth(owner, true), collection, event("first-preview")); + var second = portability.preview(auth(owner, true), collection, event("second-preview")); + var gone = get(browser, root + first.token()); + assertThat(gone.statusCode()).isEqualTo(412); + assertThat(gone.body()) + .contains( + "Import report unavailable", "inspect the destination", "href=\"/team/portability\""); + assertThat(get(browser, "/portability").statusCode()).isEqualTo(200); + assertThat(get(browser, root + second.token()).statusCode()).isEqualTo(200); + } + + @Test + void groupCreationReturnsToSharingAfterValidationAndFreshAuthentication() throws Exception { + var browser = browser(admin, true); + UUID resource = portal.create(auth(admin, true), "Group destination", "VTODO", "", ""); + UUID existing = groups.create(auth(admin, true), "Existing group", Set.of("portal-owner")); + sharing.group(auth(admin, true), resource, existing, "READ", "NONE"); + String sharingPage = "/collections/" + resource + "/sharing"; + String entry = "/admin/groups/new?returnCollection=" + resource; + assertThat(get(browser, sharingPage).body()) + .contains(entry) + .doesNotContain("