Commit Graph
227 Commits
Author SHA1 Message Date
kolaente d727c61f54 fix(user)!: give ErrCodeAccountLocked a unique error code
1026 was already taken by ErrorCodeUsernameReserved, which is older, so a
locked account was reported as a reserved username in clients.

BREAKING CHANGE: a locked account now returns 1040 instead of 1026.
2026-09-15 18:38:59 +02:00
kolaente 0336497d94 fix(user)!: give ErrCodeTOTPPasscodeUsed a unique error code
1025 was already taken by ErrorCodeInvalidTimezone, which is older, so
reusing a TOTP passcode (e.g. logging in right after enabling 2FA) showed
"The timezone '' is invalid." in the frontend.

Refs #3900

BREAKING CHANGE: a reused TOTP passcode now returns 1039 instead of 1025.
2026-09-15 18:38:59 +02:00
kolaente 27ccdba7a0 feat(invites): add admin-managed user invite links 2026-09-12 18:21:35 +02:00
kolaente 07e99dca0b test(db): cover the session memo
A behind-the-back write from a second session makes a memo hit the only way
the loader tests can pass.
2026-09-08 20:28:52 +02:00
kolaente 5baf839ded perf(db): memoize single-row task, project and user lookups per session
One GET /tasks/{id} loaded the task twice (Task.CanRead, then ReadOne), its
project twice and users by id several times, each a round trip.
GetTaskByIDSimple, GetProjectSimpleByID, GetProjectsMapByIDs,
user.GetUserByID and user.GetUsersByIDs now go through the per-session memo,
which drops itself as soon as that session writes anything.

db.Remember and db.RememberEach hold the get-or-fetch dance, mirroring
keyvalue.Remember; the two pre-existing memo sites in project_access.go use
them too. Callers get copies: Project.memoCopy re-allocates ParentProjectID,
and the user memo holds the raw row so the disabled/locked gate runs on
every hit rather than only on the first load.
2026-09-08 20:28:52 +02:00
kolaente 5ff724fe3e fix(user)!: move ErrCodeOpenIDCustomScopeMalformed off the username code
1022 was already taken by ErrCodeUsernameMustNotContainSpaces, which is
the older of the two, so a malformed OIDC scope rendered "The username
must not contain spaces." in clients.

BREAKING CHANGE: a malformed OIDC custom scope now returns 1038 instead
of 1022.
2026-09-06 00:12:30 +02:00
kolaente 50b68e1d3d fix(auth): hide enabled totp secrets 2026-08-31 18:37:03 +02:00
kolaente 170a5b7011 refactor(bots): take a verified user, not any web.Auth
Both helpers compared a.GetID() against users.id, but *LinkSharing also
satisfies web.Auth and its GetID() is a link_shares.id - a different id
namespace. Passing one would have emitted users.id = <share id> and lent
that share another user's identity, which is the confusion behind
GHSA-vvcv-vpph-h844. Guarded at every call site, but the helpers moved
out of models and into user, so the guard drifted away from the code
needing it. Taking *User makes the case unrepresentable.

Also fail closed on a zero id: humans store bot_owner_id = 0, so an
unguarded zero would have matched all of them.

The doc claimed JWT and CalDAV auth carry no BotOwnerID, but bots can
reach neither path, and claimed bots-cannot-own-bots as an invariant when
the guard is inert for JWT principals. Reworded to chain-safety by
construction, which holds regardless.
2026-08-29 23:29:46 +02:00
kolaente 86957c1bbd fix(labels): share labels between all bots of the same owner
The label access condition covered owner-to-bot and bot-to-owner, so two bots
of the same human could not use each other's labels: bot A seeded a label and
bot B got a 403 on it.

Replacing it with SameBotIdentityCond resolves every caller to an identity root
- a bot's owner, or a human themselves - and matches everyone under that root,
which covers all three directions in a single condition. Write access is
unchanged: only the creator and the human owner can update or delete a label.
2026-08-29 23:29:46 +02:00
kolaente 9c0fa73f3a feat(user): add shared bot identity helpers
IsBotOwnedBy and SameBotIdentityCond replace the ad-hoc bot ownership checks
scattered across labels and api tokens.
2026-08-29 23:29:46 +02:00
kolaente dc6365f0f4 fix(user): expire used TOTP passcodes via keyvalue TTL
Replaces the hand-rolled timestamp check and cleanup goroutine. The old
int64 type assertion never matched on redis (Get returns a string), so
passcode replay protection was silently disabled there.
2026-08-19 17:29:35 +02:00
kolaente bd704c347a feat(user): notify the current address when an email change is requested
Gives the account owner an out-of-band signal if someone with their
password starts moving the login address, with a link to the settings
page where the change can be cancelled. Sent after the confirmation mail
so a throttled request mails nothing.
2026-08-18 22:03:38 +02:00
kolaente 52bcd3e093 fix(user): keep old email active until new one is confirmed
Changing the email no longer overwrites the address and flips the account
to StatusEmailConfirmationRequired. The new address is stored as
pending_email and only applied when the confirm token is used (valid 24h),
so a lost or misaddressed confirmation mail can no longer lock the user
out. The change can be repeated to fix typos, cancelled, or the mail
resent; confirmation mails are throttled to one per minute per user, and
stale change tokens are swept by the cleanup cron.

Fixes #3481
2026-08-18 22:03:38 +02:00
kolaente 7677e70419 feat(user): add pending_email column
Stores a new address awaiting confirmation. A direct email update via
UpdateUser (admin, LDAP/OIDC sync) supersedes and clears it.
2026-08-18 22:03:38 +02:00
kolaente 3833b34d37 fix(user): keep email confirmation status after registration
The default-project creation triggered by the user-created event wrote the
stale in-memory user back with a full UpdateUser, racing registration and
sometimes resetting the status from "email confirmation required" back to
active. Only update the default_project_id column and keep the returned
user's status in sync with what was persisted.
2026-08-18 11:30:03 +02:00
kolaente ccba2e4546 fix: avoid panic on null jwt claim values
reflect.TypeOf returns a nil Type for a null claim value, so building the
error message panicked.
2026-08-04 13:40:11 +02:00
kolaente dbe664dec5 fix(security): reject non-user tokens in GetUserFromClaims
GetUserFromClaims read the id claim straight into User.ID without checking the
token type. A link share JWT carries the raw, positive share id in that claim
and reaches every authenticated route, so the only thing preventing
impersonation was the incidental absence of a username claim in link share
tokens. Adding one would have reintroduced the confusion with a positive id,
bypassing the GetID negation entirely.

AuthTypeUser moves to pkg/user, which parses the claims and cannot import
pkg/modules/auth, so the value exists once.
2026-08-04 13:40:11 +02:00
kolaente 11b4b59ed5 fix(auth): use configured bcrypt rounds everywhere 2026-07-28 08:43:26 +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
Evan BakerandGitHub d0dad0437f fix(user): stop double-encoding FrontendSettings on UpdateUser (#2793) 2026-07-19 12:13:35 +02:00
kolaenteandkolaente f388015dda fix: interpolate dynamic values into translated error toasts
Parametrised error translations (invalid api token permission, invalid
timezone, invalid claim data) rendered their placeholders as empty text
because the backend only baked the values into the English message and
the frontend translated the error code without any interpolation params.

Carry the values as i18n_params on error responses, keyed by the
placeholder names of the frontend's error translations, on both v1 and
the v2 problem+json body, and pass them through when translating the
toast. A 14002 toast now reads e.g. "The permission time_entries of
group tasks is invalid." instead of "The permission of group is
invalid."
2026-07-18 13:41:15 +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 f33cde82e2 feat(audit): attribute failed logins to the originating request
Thread the request context through CheckUserCredentials so the
LoginFailedEvent carries IP, user agent and request id — without it,
failed logins were the one auth event useless for brute-force tracing.
All four callers have the request at hand.
2026-06-12 08:56:08 +00:00
kolaenteandkolaente 5f4a21a4c5 feat(events): add auth boundary events
LoginSucceededEvent fires from NewUserAuthTokenResponse (the chokepoint
where local, LDAP and OIDC logins converge), LoginFailedEvent from
handleFailedPassword on every failed password check, LogoutEvent from
the logout handler, and APIToken issued/revoked/used events from the
token model and auth middleware. The token events carry IDs only since
the freshly created token struct holds the raw token string and the
poison queue logs message payloads.

None of these events have a listener yet — the audit registration adds
them. Dispatching to a topic without subscribers is a no-op.
2026-06-12 08:56:08 +00:00
kolaenteandkolaente 5807f2e7b4 refactor(user): share user-search logic between v1 and v2
Extract the duplicated user-search business logic into two helpers both API
versions call, and refactor v1's handlers onto them:
- user.SearchUsers wraps ListUsers + email obfuscation (global search)
- models.SearchUsersForProject wraps the project read check + ListUsersFromProject

Each handler keeps its own forbidden mapping (v1 echo.ErrForbidden vs v2
huma) so v1 stays byte-identical on the wire.
2026-06-11 20:07:43 +00:00
kolaenteandkolaente 46b07a019c refactor(user): extract shared account orchestration into models/user/shared for v1+v2
Pull the business logic out of the v1 current-user account/settings handlers
into reusable functions so both v1 and the upcoming v2 handlers call one
implementation. No behavior change — the v1 handlers keep their HTTP-layer
quirks (input binding, validation, error mapping); only orchestration moves.

Homes are forced by the import graph:
- shared.GetAuthProviderName  (new pkg/routes/api/shared, above openid+user so it
                              can combine both without a cycle; routes-only helper)
- user.ChangeUserEmail        (CheckUserCredentials + UpdateEmail, both in user)
- models.ChangeUserPassword   (needs models.DeleteAllUserSessions; user can't import models)
- models.UpdateUserGeneralSettings / UpdateUserAvatarProvider
                              (need avatar.FlushAllCaches; user can't import avatar)

The general settings get a single shared wire struct, models.UserGeneralSettings
(tagged for both swaggo/govalidator and Huma): it is the update request body and
the nested settings on GET /user for v1 (replacing v1's UserSettings) and v2.
ExtraSettingsLinks is readOnly — populated from the user on read, ignored on
write. A dedicated struct is required because user.User's settings fields are
json:"-" so they don't leak when it is embedded in other responses.
2026-06-11 07:02:31 +00:00
kolaenteandkolaente 4afcfa4441 docs(api/v2): tag TOTP fields for the v2 schema 2026-06-10 17:58:16 +00:00
kolaenteandkolaente da3bf0e7cd docs(api/v2): tag CalDAV token fields for the v2 schema 2026-06-10 17:55:52 +00:00
kolaenteandkolaente cae89caef2 feat(api/v2): add bot user CRUD on /api/v2
Port the BotUser resource from /api/v1's /user/bots routes to the
Huma-backed /api/v2, preserving every v1 behavior:

- Full CRUD at /user/bots and /user/bots/{bot} with v2 verbs (POST
  creates, PUT updates; PATCH is synthesised by AutoPatch).
- ReadAll returns only the caller's own bots; read/update/delete of an
  unowned or missing bot is refused with 403, since ownership is resolved
  by loading the user (no existence disclosure, no 404 branch).
- Create requires a real user account and rejects link shares, the
  bot- username prefix is enforced, and bots are created without an
  email or password — all delegated to the unchanged model layer.
- ReadOne surfaces max_permission via the shared value-embed pattern and
  carries an ETag for conditional requests.

doc/readOnly tags are added to the exposed user.User fields the bot
response surfaces, and to BotUser.Status, so the v2 OpenAPI schema is
documented. The model and v1 routes are untouched.

The webtest ports the v1 model-level permission matrix to the v2 HTTP
surface and adds the v2-only ETag/304 and merge-patch coverage.
2026-06-05 08:51:39 +00:00
kolaente 78ca1904b5 docs(api/v2): mark server-controlled label and user fields read-only 2026-05-31 15:27:44 +02:00
kolaenteandkolaente 9a810f7632 refactor(user): remove the now-empty listeners file
The user package no longer registers any event listeners, so drop the
empty RegisterListeners hook and its caller.
2026-05-30 13:48:01 +00:00
kolaenteandkolaente 06000b7a03 refactor(metrics): drop the user count listener
The user count is now counted on demand, so the increment-on-create
listener is no longer needed.
2026-05-30 13:48:01 +00:00
Claudeandkolaente d9a5958bb8 feat: always enable bot users
Removes the `service.enablebotusers` config flag, the matching
`bot_users_enabled` field on /info, and the now-unused
`ErrBotUsersDisabled` error. Bot user routes and the frontend
settings tab are now always available.

https://claude.ai/code/session_01VhAR6xnoCdG1fpX52bzaCC
2026-05-04 10:38:53 +00:00
kolaenteandkolaente 22d82e292b feat(user): always include own bots in user search
User search previously filtered bots only when they happened to match the
search string. That produced two bad behaviours:

1. Bots owned by other users could surface on an exact-username match,
   leaking them into assignee pickers and similar UI.
2. A user could not reliably find their own bots by typing a partial
   name, so bots became awkward to assign to tasks.

Change ListUsers to treat bot ownership explicitly: the existing match
branch excludes rows owned by someone else, and a second branch always
returns bots owned by the calling user. The own-bots branch also
respects any AdditionalCond passed in so project-scoped listings don't
start leaking bots from outside the project.
2026-05-01 14:44:10 +00:00
kolaenteandkolaente 3415981d1c feat(models): add BotUser CRUD wrapper 2026-05-01 14:44:10 +00:00
kolaenteandkolaente 1637ecd0c7 feat(user): add CreateBotUser 2026-05-01 14:44:10 +00:00
kolaenteandkolaente 506bfa2549 feat(user): reserve bot- username prefix for regular signup 2026-05-01 14:44:10 +00:00
kolaenteandkolaente a262c6a848 feat(user): add bot-related error types 2026-05-01 14:44:10 +00:00
kolaenteandkolaente 83c5190c9b feat(user): add BotOwnerID field and IsBot helper 2026-05-01 14:44:10 +00:00
kolaenteandkolaente af8beb5758 fix(user): skip last-admin guard when target is already unreachable
GuardLastAdmin counted only active, non-deletion-scheduled admins, but gated only on target.IsAdmin. Demoting or deleting an already-disabled or deletion-scheduled admin would then be blocked whenever exactly one active admin remained, even though removing a user who isn't in the reachable set can't reduce the count. Return early when the target isn't part of the counted set.
2026-04-20 18:55:06 +00:00
kolaenteandkolaente d24b96b99c feat(user): extract last-admin guard and close invariant gaps 2026-04-20 18:55:06 +00:00
kolaenteandkolaente 7c7e060d16 feat(auth): include is_admin in JWT claims 2026-04-20 18:55:06 +00:00
kolaenteandkolaente deccc9d29b feat(user): add IsAdmin field to User struct 2026-04-20 18:55:06 +00:00
kolaenteandkolaente 75629158cb test(user): cover TOTP lockout persistence and password-reset unlock
Verifies that HandleFailedTOTPAuth locks the account after 10 rolled-back
caller sessions (the regression from GHSA-fgfv-pv97-6cmj), and that the
persisted password reset token can unlock the account via ResetPassword.
2026-04-09 16:08:26 +00:00
kolaenteandkolaente d435c50df3 fix(security): persist TOTP lockout across login rollback
The failed-TOTP handler shared the login request's xorm session, and the
login handler rolled that session back after a failed login. The status
change to StatusAccountLocked was silently discarded, so the account was
never locked regardless of how many failed TOTP attempts arrived.

HandleFailedTOTPAuth now opens its own session and commits independently
of the caller. The login handler rolls back its session before invoking
the handler so the lockout write can acquire a write lock on SQLite
shared-cache.

Also handles the Redis keyvalue backend returning the attempt counter as
a string instead of int64, which would have prevented the lockout path
from ever running on Redis.

See GHSA-fgfv-pv97-6cmj.
2026-04-09 16:08:26 +00:00
kolaenteandkolaente 39e16653aa fix: add ORDER BY to ListUsers query for deterministic ordering
The query had no ORDER BY clause, causing non-deterministic result
ordering on PostgreSQL where row order is not guaranteed.
2026-03-27 23:05:04 +00:00
kolaenteandkolaente 0b04768d83 test(auth): add comprehensive disabled/locked user auth tests
Add locked user fixture (user18, status=3) and test that both disabled
and locked users are rejected across all auth paths: API tokens,
CalDAV basic auth, CheckUserCredentials.

Ref: GHSA-94xm-jj8x-3cr4
2026-03-23 16:37:26 +00:00
kolaenteandkolaente 033922309f fix(auth): reject disabled/locked users in CheckUserCredentials
Defense-in-depth: CheckUserCredentials now checks user status after
validating credentials. While current callers are already protected
by upstream checks, this prevents future auth bypass if new code
calls CheckUserCredentials without a subsequent status check.

Ref: GHSA-94xm-jj8x-3cr4
2026-03-23 16:37:26 +00:00
kolaenteandkolaente c7740fc4aa fix(user): use unique error code for ErrCodeAccountLocked
Was 1025 which collides with ErrorCodeInvalidTimezone. Changed to 1026.
2026-03-23 12:06:16 +00:00
kolaenteandkolaente 37394fb336 fix(user): use getUser directly for uniqueness checks in UpdateUser
The username and email uniqueness checks don't need status filtering —
they just need to know if the name/email exists regardless of account
status. Use getUser (which skips the status check) instead of the
public wrappers, reducing cyclomatic complexity back under the threshold.
2026-03-23 12:06:16 +00:00