Commit Graph
209 Commits
Author SHA1 Message Date
kolaente 57bfd1cae2 feat(api/v2): add bulk task creation endpoint
POST /api/v2/projects/{project}/tasks/bulk creates up to 100 tasks in
one atomic request. The URL project wins over any body project_id, and
rich-text descriptions honor the format query param like single create.
Bucket limits are only enforced for explicitly provided bucket ids.

The route files under the tasks API-token group as create_bulk,
matching the v1 bulk naming, so a token scoped to tasks can use it.
2026-08-02 16:21:50 +02:00
4abda62a99 fix(labels): allow attaching labels via inherited child-project access (#3374)
Users with access to parent project could remove labels from tasks in
child projects but not add them back — 403 "Tried to create while not
having the permissions for it". Label attach check used direct shares
only; task write permission and label picker both walk project
hierarchy. Fix: label access now uses same recursive subquery.

Reported: https://community.vikunja.io/t/permissions-on-labels/4460

## How to verify

1. As user A, create a parent project with a child project, and add a
task in the child project.
2. Share the parent project with a team that has write access and
contains user B.
3. As user A, add a label to the task in the child project.
4. As user B, open that task, remove the label, then try to add it back.
5. **Expected:** the label can be added again; the API returns 201.

**Before this PR:** step 4 failed with 403 even though user B could edit
the task and remove the label.

Co-authored-by: kolaente <k@knt.li>
2026-07-30 12:03:30 +02:00
kolaente 4c5ec6a4d8 fix(caldav): don't wipe fields the parser doesn't understand on update
CalDAV PUT called unrestricted Task.Update, so it wiped repeat_after/repeat_mode,
percent_done and dates the parsed VTODO didn't carry, plus assignees, reminders,
favorites and relations. Parse now reports which fields the VTODO actually spoke
to and UpdateResource overlays only those onto the stored task, re-read inside the
update transaction. A UID can match several tasks, so the write targets the one the
permission check covered.

Fixes #544
Fixes #1422
2026-07-30 11:32:24 +02:00
kolaente 7e310be332 fix(caldav): remove double trailing slash from current-user-principal href 2026-07-30 00:13:07 +02:00
TinkandGitHub 0b46adfa88 fix(caldav): return 404 for principal sub-paths and foreign usernames (#3371) 2026-07-29 23:44:49 +02:00
TinkandGitHub b487a4099c fix(caldav): answer PROPPATCH with 207/403 instead of a blanket 501 (#3364) 2026-07-29 21:33:02 +00:00
kolaente 767be216e6 fix(subscriptions): declare subscription entity as string enum in v2 OpenAPI schema
SubscriptionEntityType is an int in Go but its custom MarshalJSON emits
"project"/"task" strings. Huma reflected it as an integer schema, so
AutoPatch's GET-to-PUT echo failed request validation with
"subscription.entity: expected integer" whenever the requesting user had
a task or project subscription, blocking all v2 task and project PATCH
writes for subscribed users.

Add a Schema override reflecting it as a string enum, same pattern as
ProjectViewKind and BucketConfigurationModeKind.

Fixes #3316
2026-07-29 22:28:31 +02:00
kolaenteandkolaente 0638200ac0 fix(notifications): check project access when reading notifications
Notification rows outlived access. A subscription survives a project being
unshared, so every notification already written for a revoked user stayed
readable — comment bodies, task titles, project names, deletion notices. The
read paths filtered on notifiable_id alone, with no permission check anywhere.
#3325 stopped the sender writing new ones; this is the other half.

The project a notification is about is persisted on the row when it is written
and the read paths filter on it in SQL, so LIMIT, OFFSET and total are all
computed on the filtered set. Notification types declare their project through
a capability interface in pkg/notifications, the same way they already declare
SubjectID, ThreadID and ToTitle — which is what lets the package below
pkg/models stay ignorant of what a project is.

project_id 0 means account-scoped and always visible, a positive value is
checked against the projects the caller can read, and -1 marks a project-scoped
row whose project could not be determined, so it is visible to nobody. Filtering
reuses the existing accessibleProjectIDsSubquery, so the page query and the
count cannot drift apart. A migration backfills existing rows from their stored
payloads, resolving through soft-deleted tasks so task.deleted rows still land
on their project.

Covers every read path: the v1 and v2 list endpoints, mark-as-read (which
echoes the payload back), the Atom feed, and the websocket push — the last of
which is load-bearing, since a row is still written for a revoked subscriber.
Deliberately no instance-admin bypass: notifications are always the caller's
own, and being an admin says nothing about whether they should still read a
comment out of a project they were removed from.
2026-07-29 07:58:17 +00:00
kolaente 1f23add574 fix(api/v2): stop leaking the healthcheck cause to unauthenticated callers
GET /api/v2/health passed the raw error from health.Check() into
huma.Error500InternalServerError, which serialized it into the response
body. The endpoint is public, so a routine DB or Redis outage exposed
internal hostnames, private IPs, ports, the DB technology and DB usernames
to anyone who asked:

    {"title":"Internal Server Error","status":500,
     "detail":"Internal server error",
     "errors":[{"message":"dial tcp 127.0.0.1:6390: connect: connection refused"}]}

Log the cause with context instead and return a bare generic 500.
2026-07-28 19:26:15 +02:00
kolaente e987811a75 fix(auth): gate the v2 login route on local or ldap auth being enabled
v1 only registers /login when local or LDAP auth is enabled, but v2
registered it unconditionally. With auth.local.enabled=false a
pre-existing local password still authenticated on /api/v2/login.

/logout stays unconditional - it terminates any session, OIDC included.
2026-07-28 17:25:37 +02:00
TinkandGitHub 584ddd99a2 fix(oauth2): burn authorization code even when validation fails (#3350) 2026-07-28 17:13:15 +02:00
TinkandGitHub ccc46508b0 fix(security): rate limit the websocket upgrade endpoint (#3348) 2026-07-28 17:12:18 +02:00
kolaenteandkolaente 2025d8c4f8 fix(api tokens): guard GetTokenFromTokenString against short token strings
GetTokenFromTokenString sliced token[len(token)-8:] without checking the
length, so any string with the "tk_" prefix but shorter than 8 characters
panicked with "slice bounds out of range".

The helper is reachable with attacker-controlled input from three
unauthenticated call sites: the main API bearer-token middleware
(/api/v1 and /api/v2) and CalDAV basic auth on /dav/ and
/.well-known/caldav. Each request was turned into a 500 by the global
panic recovery, at the cost of a full stack unwind, an error-level log
line and a Sentry event. On the main API the token middleware also runs
before the rate limiter, and the CalDAV routes are not rate limited at
all.

The same guard already existed in the feeds auth path; fixing it at the
shared choke point closes all sites at once. Real tokens are the prefix
plus 40 hex characters, so no legitimate token is affected — a too-short
token now gets the same rejection as any other invalid one.
2026-07-28 06:59:04 +00:00
kolaenteandkolaente 05e9bac9e7 test(ratelimit): assert exact statuses instead of absence of 500
Asserting only "not 500" let the test pass on a 404, 401 or 403, so it
would have kept passing if the public v2 endpoints broke another way.
Assert 200 per path plus the remaining budget counting down across them,
which is what proves both unauthenticated requests share one ip key.
2026-07-27 22:31:06 +00:00
kolaenteandkolaente 2c9e71a2b3 fix(ratelimit): don't panic on unauthenticated requests
With ratelimit.kind at its default value of "user", the rate limit
middleware logged the error from GetAuthFromClaims and then dereferenced
the nil web.Auth anyway. Every unauthenticated /api/v2 request produces
exactly that state, since v2 attaches the limiter to the single group
serving its public routes too - so enabling rate limiting turned
/api/v2/info, /api/v2/health and /api/v2/login into 500s. v1 is
unaffected because it splits its unauthenticated routes into their own
ip-keyed subgroups before the "user" limiter is attached.

Fall back to keying by IP, matching the "ip" kind and v1's
unauthenticated groups. Authenticated requests are unchanged.
2026-07-27 22:31:06 +00:00
kolaenteandkolaente aa62c00b78 test: guard parent_project_id in project responses
Route-level tests on both api versions, since the pseudo-projects only get
their parent through the read path. The v2 read body embeds models.Project and
Huma's $schema wrapper copies its fields into a generated struct, so a custom
MarshalJSON on the model would not have applied there — assert the raw JSON
instead of the struct.
2026-07-26 09:39:41 +00:00
kolaente 6895a7765e fix(security): reject cross-project views in ProjectView Can{Delete,Update} (GHSA-gg93-x632-9ccv) 2026-07-19 18:59:34 +02:00
kolaente 781ffac198 fix(security): require Admin to detach a project from its parent (GHSA-44v6-7fxq-vgf4) 2026-07-19 18:59:34 +02:00
kolaente 1c13624a8e fix(api): reject link shares on reaction and task-read endpoints (consistency; GHSA-vvcv-vpph-h844) 2026-07-19 18:59:34 +02:00
kolaente 3a0ea15d8c fix(security): hash password-reset, email-confirm and deletion tokens at rest (GHSA-r6w9-259g-gwrv) 2026-07-19 18:59:34 +02:00
kolaente 4ae2e09301 fix(auth): reject API tokens at the OAuth authorize endpoint (GHSA-v3p6-34mc-hj7v) 2026-07-19 18:59:34 +02:00
kolaente be36c11e67 fix(api): derive API-token ownership from a verified user principal (GHSA-vvcv-vpph-h844) 2026-07-19 18:59:34 +02:00
kolaente d911caaa11 fix(projects): enforce write permission on target parent when duplicating a project (GHSA-f27p-pw2p-9pr4) 2026-07-19 18:59:34 +02:00
kolaente cfb9c24519 fix(kanban): pin link-share task collection view to the share's project (GHSA-rj9j-8772-4h6c) 2026-07-19 18:59:34 +02:00
kolaente b31d606b88 fix(kanban): prevent cross-tenant bucket relocation via project_view_id mass-assignment (GHSA-569v-q83c-3j3g) 2026-07-19 18:59:34 +02:00
kolaente 36cdc2ce2b fix(kanban): authorize body task_id when moving a task into a bucket (GHSA-5pg6-m483-7vrg) 2026-07-19 18:59:34 +02:00
TinkandGitHub e2c09d593c fix: hide license-gated routes from api token scope list (#3216) 2026-07-18 10:00:37 +02:00
TinkandGitHub 4425e0d146 fix(attachments): keep blob mime type so pdf previews open inline (#3157) 2026-07-11 18:53:09 +02:00
kolaenteandGitHub 85231284ab feat(auth): add OpenID provider availability monitoring and retry logic (#3145) 2026-07-10 17:52:01 +02:00
kallegrensandkolaente 82ee780161 feat(caldav): implement RFC 6578 sync-collection REPORT to sync task deletions
iOS Reminders (and other RFC 6578 clients) never learned about tasks
deleted on the Vikunja side: caldav-go answers unknown REPORT types
with 412, which makes iOS silently stop syncing, and deleted tasks left
no protocol-level trace a client could observe.

Intercept sync-collection REPORTs before caldav-go sees them and answer
per RFC 6578: tasks changed since the sync token as 200 entries and
deleted tasks as 404 entries. Deletion records come from task
soft-deletes, which are kept for 30 days before being purged.

Token edge cases: delta comparisons are inclusive because tokens have
second granularity (re-reported items keep their etag, so clients skip
the download), and tokens older than the soft-delete retention answer
403 + valid-sync-token to force a full resync instead of a delta that
would silently miss purged deletions.
2026-07-07 11:57:04 +00:00
TinkandGitHub d83e90541c feat(tasks): soft-delete tasks with permanent deletion after 30 days (#3119) 2026-07-07 11:38:33 +02:00
kolaenteandkolaente 3a666da860 feat: audit admin reads and denied admin access
GET /admin/users returns every user's email address; compliance
regimes commonly require admin PII access to be logged, so the list
read now emits admin.users.listed. The admin gate additionally emits
admin.access.denied (outcome=failure, with method and path) whenever
an authenticated user without the instance-admin flag probes an
/admin/* route — dispatched directly with the request context since
there is no transaction.

Both entries have no single affected resource, so the entry target is
now omitted when empty instead of serialising a zero value.
2026-07-03 16:56:03 +00:00
kolaenteandkolaente 39bbf8d006 fix: dispatch pending events in admin handlers
Neither the v1 nor the v2 admin handlers called events.DispatchPending
after commit, so events queued via DispatchOnCommit were silently
dropped: admin-created users never fired user.created (no webhook,
notification or audit entry) and mode=now user deletion dropped the
cascaded project.deleted events. Each dropped queue also leaked an
entry in the pendingEvents map keyed on the dead session.

Dispatch after commit, clean up on rollback, and thread the real
request context through the v2 handlers so request metadata flows onto
the events.
2026-07-03 16:56:03 +00:00
TinkandGitHub d0dccf2736 feat(pro): admin password reset for existing users (#3085) 2026-07-02 19:39:00 +02:00
bdb07799d3 fix(api): return 200 instead of 500 when listing attachments on a task with none
ReadAll used a bare return when len(attachments) == 0, which returned
nil for the interface{} result. The v2 handler's type assertion then
failed on nil, producing an untyped error that Huma surfaced as 500.

Return the empty slice explicitly so the assertion succeeds.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-07-01 12:42:32 +00:00
kolaente fa0c9a8584 feat(api): exchange rich-text fields as markdown on v2
Wire the conversion helpers into every rich-text handler: read/list/echo
convert HTML to markdown, create/update convert markdown to HTML before
persisting, and each op documents the format query field. Opt-in via
?format=markdown or the X-Vikunja-Format header.
2026-06-29 08:12:35 +02:00
kolaenteandkolaente 0d043e80e4 feat(api/v2): add kanban bucket CRUD endpoints
Port the standalone bucket list/create/update/delete from v1 to the
Huma-backed /api/v2, under /projects/{project}/views/{view}/buckets,
using v2 verb conventions (POST creates, PUT updates). The handlers
reuse the generic handler.Do* functions, so permissions are enforced
by the Bucket model's existing Can* methods.

Mirrors v1: no read-one route (the model has no ReadOne/CanRead), so
AutoPatch synthesises no PATCH. No model changes.
2026-06-26 08:56:15 +00:00
TinkandGitHub 7208694960 fix(auth): build OIDC end-session URL with RP-Initiated Logout params (#2943) 2026-06-19 18:27:33 +02:00
kolaenteandkolaente 6e1b15e344 fix(tasks): add labels sequentially when the backend db serializes writes
Quick Add Magic with multiple labels (`*a *b *c`) fired all
`PUT /tasks/{id}/labels` requests concurrently via `Promise.all`. On
SQLite these overlap as read-then-write upgrade transactions, which the
busy_timeout can't resolve, so some requests fail with HTTP 500
("database is locked") and the labels are silently dropped while the
quick-add input gets stuck.

Expose a `concurrent_writes` flag on the shared `/info` response (true
for Postgres/MySQL, false for SQLite). The frontend config store reads
it and `addLabelsToTask` now branches: parallel `Promise.all` when the
backend supports concurrent writes, sequential awaits otherwise.

Fixes #2680
2026-06-19 14:19:19 +00:00
kolaenteandkolaente 9cad4f388c feat(api/v2): expose websocket endpoint under /api/v2
Adds GET /api/v2/ws as a raw echo route reusing the v1 upgrade handler.
WebSockets can't be modeled in OpenAPI and Huma has no WS support, so it
stays outside the Huma spec; it authenticates via its first message, so
unauthenticatedAPIPaths exempts it from the group's JWT middleware.

Also adds webtests covering all three /api/v2 non-CRUD endpoints: health
returns OK, ws is reachable without a JWT, and the atom feed is
basic-auth-gated. A spec test asserts /health and /notifications.atom
appear in the generated OpenAPI paths (atom with its application/atom+xml
response and BasicAuth security) while /ws is absent.
2026-06-17 20:35:28 +00:00
kolaenteandkolaente 7c11c2dc29 feat(api/v2): port refresh-token endpoint to /api/v2
POST /api/v2/user/token/refresh reads the HttpOnly refresh cookie, rotates
the session, mints a new JWT, and sets the new cookie — reusing the shared
auth.RefreshSession core (no v1 change) and the #2912 cookie helpers /
authTokenBody response shape. The cookie is set via the unwrapped echo ctx,
not the OpenAPI spec.

translateDomainError now maps *echo.HTTPError (which RefreshSession returns
for missing/invalid/expired/replayed tokens) so those land as the right
status instead of a 500. Completes the v1→v2 REST migration.
2026-06-17 20:34:38 +00:00
kolaenteandkolaente 5b7924b1f6 fix(auth): return ErrAccountLocked for locked accounts on login
The login status check mapped a locked account to ErrAccountDisabled,
surfacing the disabled-account error code and message even though a
dedicated ErrAccountLocked exists (and the OIDC flow already uses it). Map
the locked status to ErrAccountLocked so credential login is consistent with
OIDC across both /api/v1 and /api/v2. Disabled accounts still return
ErrAccountDisabled.

This changes the v1 login error code for locked accounts on the wire (1020 ->
1026); the change is intentional and approved.
2026-06-17 19:43:41 +00:00
kolaenteandkolaente 9aa0687288 test(api/v2): cover v2 login, logout and OIDC gating
Login asserts the token, the HttpOnly refresh cookie, the no-store header
and the credential/TOTP gates. Logout asserts the session is deleted and the
cookie cleared. OIDC coverage is the registrar gate (404 when disabled,
public route when enabled) — the full provider flow needs a live OIDC server,
as the existing openid package tests show.
2026-06-17 19:43:41 +00:00
kolaenteandkolaente 4b92f23329 fix(files): never cache file downloads in v1 or v2
Move the Cache-Control: no-cache header into the shared WriteFileDownload
so every export and attachment download carries it, and add it to the
standalone v1 export download writer too. Downloads must never be cached.
2026-06-17 18:39:38 +00:00
kolaenteandkolaente 8c72e83a4d feat(api/v2): add user data export endpoints
Port POST /user/export/request, POST /user/export/download (zip stream) and
GET /user/export (status) to v2. Extract the export-file loader and status
builder into pkg/models (GetUserDataExportFile, GetUserDataExportStatus) with
a shared ErrUserDataExportDoesNotExist, and refactor v1 onto them. The v2
download streams via the shared WriteFileDownload writer; local users confirm
with their password, external-provider users are passed through.
2026-06-17 18:39:38 +00:00
kolaenteandkolaente ac5e94252b feat(api/v2): add totp qr code endpoint
Port GET /user/settings/totp/qrcode to v2 as an image/jpeg blob, modeled in
the OpenAPI spec. Extract the qr-to-jpeg encoding into user.GetTOTPQrCodeAsJpegForUser
so v1 and v2 share it; refactor v1 onto it. The handler reuses the existing
local-account guard, rejecting non-local users with 412.
2026-06-17 18:39:38 +00:00
kolaenteandkolaente c4819631e2 test(api/v2): use cross-engine datetime literals in testing webtest
MariaDB strict mode rejects the RFC3339 T/Z form for DATETIME columns. The space-separated form is accepted by MariaDB, Postgres and SQLite alike; the test only asserts on title and row counts, never the datetime.
2026-06-17 12:13:50 +00:00
kolaenteandkolaente 4737114b12 feat(api/v2): add e2e testing-support endpoints on /api/v2
Port the testing fixture endpoints to /api/v2: PUT /test/{table} resets a
table to a posted fixture set and DELETE /test/all truncates everything.
Both authenticate with the configured testing token via a custom
Authorization header (not JWT/API-token) and only mount when that token is
set. Reuses the shared reset/truncate logic extracted from v1.
2026-06-17 12:13:50 +00:00
kolaenteandkolaente c5d615843d test(api/v2): cover background download and unsplash proxy routes
- Download: upload-then-download (real bytes), content-type, If-Modified-Since
  304, read-only access allowed, no-access 403, unauthenticated 401, no
  background 404, and the config-disabled route being absent.
- Unsplash proxies: routes absent when the provider is disabled, and 401 when
  unauthenticated. The live Unsplash fetch is not exercised, matching v1.
2026-06-17 11:31:50 +00:00
kolaenteandkolaente a8a53c9581 test(api/v2): cover the v2 file and CSV migrator endpoints
Webtests for the file migrators (status, migrate, auth, missing-file) and the
CSV importer (status, detect, preview, migrate happy path, missing/malformed
config, empty file, auth). Each rejected upload is asserted to map to a 4xx
domain error rather than a 500.
2026-06-12 08:51:19 +00:00