Identity, authentication, and access control
Memos turns a sign-in method into a local user identity and then uses that identity to control API and memo access. Password credentials and external identity providers establish the user. Short-lived access tokens, refresh-token sessions, and personal access tokens carry that result to later requests. The API places the result in request context, while resource rules make the final decision for users, memos, comments, notifications, and shared links.
Authentication model
Authentication answers who is making a request. The shared authenticator accepts a Bearer access token or personal access token and can also resolve a browser refresh-token cookie for flows that need the local user record. It rejects expired, revoked, or archived-user credentials before the request reaches a protected service. server/…/authenticator.go• L18-24 server/…/authenticator.go• L215-235
Credential types
Each credential has a different job in the session model:
| Credential | Main use | Validation source | Lifetime or revocation behavior |
|---|---|---|---|
| Access token | Normal API calls | Signed JWT claims plus an active local user lookup and password-bound session check | Short lived; a password change invalidates previously issued tokens |
| Refresh token | Renewing a browser session | Signed JWT claims plus a stored token record | Stored for revocation and rotated on refresh |
| Personal access token | CLI, mobile, and other programmatic clients | SHA-256 token hash stored with the user | Optional expiry; deletion revokes it |
The access token carries the local user ID, username, role, and status. Its authentication hash binds it to the user's current password hash, so the server can reject tokens issued before a password change. The refresh token carries a token ID so the server can revoke one session without revoking the user. A personal access token returns its full value only when it is created. Later requests use its stored hash to resolve the local user, then the authentication layer checks expiry and account state. A missing token setting, an empty token list, a removed token, or a token whose user no longer exists is an authentication miss. server/…/token.go• L35-53 server/…/token.go• L70-87 server/…/token.go• L135-170 store/user_setting.go• L129-150
References: server/…/authenticator.go• L40-84 server/…/authenticator.go• L86-156 server/…/token.go• L35-53 server/…/token.go• L70-87 server/…/token.go• L135-170 store/user_setting.go• L129-150 store/…/user_setting_test.go• L360-435
Session lifecycle
Sign-in creates both sides of a browser session: a short-lived access token for API calls and a longer-lived refresh token in an HttpOnly cookie. Refresh validates the cookie against stored session data, replaces the old refresh token, and returns a new access token. Sign-out removes the identified refresh session and clears the cookie. server/…/auth_service_session.go• L25-63 server/…/auth_service_session.go• L66-183
Stored refresh sessions drop expired entries as new sessions are added. Session updates are serialized so concurrent sign-ins do not lose one another's tokens. Password changes can revoke all other sessions while preserving the caller's current session when the caller changes that user's own password. store/user_setting.go• L153-229 store/…/user_setting_test.go• L171-205
The refresh cookie uses browser protections that fit the request scheme. A secure request receives a Secure cookie, while both secure and local HTTP requests use HttpOnly and SameSite=Lax. Session records also keep client details so a user can recognize and revoke a session from a device they do not trust. The recorded address comes from the trusted client-IP context rather than a client-supplied forwarding header. server/…/auth_service_session.go• L207-323 server/…/auth_service_client_info_test.go• L95-124
This sequence shows how a browser keeps a session active without using the long-lived credential as an API header.
sequenceDiagram
participant B as Browser
participant A as Auth API
participant S as Session store
B->>A: Sign in with password or SSO result
A->>S: Store refresh-token session
A-->>B: Access token + HttpOnly refresh cookie
B->>A: API request with access token
A-->>B: Protected response
B->>A: Refresh request with cookie
A->>S: Check and rotate refresh session
A-->>B: New access token + replacement cookie
The web client restores a token when possible and uses the refresh cookie when local token storage is empty. It publishes the verified identity before display-related user settings finish loading, so identity-dependent routes can start while settings load. The client keeps identity readiness separate from full settings readiness. It clears the local token, cached user data, and query state after confirmed logout or authentication failure. See Web application experience for the wider browser data and route lifecycle. web/…/AuthContext.tsx• L35-157 web/…/AuthContext.tsx• L157-199
References: server/…/token.go• L135-194 server/…/authenticator.go• L86-124 server/…/auth_service_session.go• L25-267 server/…/auth_service_client_info_test.go• L95-124 store/user_setting.go• L153-229 store/…/user_setting_test.go• L171-205 web/…/AuthContext.tsx• L35-199
Identity-provider integration
An identity provider is an external system that confirms a user account. Memos uses the provider's stable subject identifier to find or create a local user, so the local account remains the owner of memos and permissions even when sign-in happens elsewhere. The provider returns a required identifier plus optional display data. server/…/auth_service_sso.go• L19-61
OAuth sign-in flow
The web flow protects the authorization-code exchange with a state value and uses PKCE when the browser has secure cryptographic APIs. The server exchanges the code with the selected provider, requests user information, applies the provider's identifier filter, and maps the result to a local account. An empty external subject is rejected before it can identify or create an account. server/…/auth_service_sso.go• L188-231 server/…/auth_service_sso.go• L19-26
The account mapping has two paths:
- A known pair of provider and external subject signs in to its linked local user.
- A new subject links to the current user during account linking, or creates a new local user when registration is allowed.
The link is stored separately from the local username. One local user can have identities from several providers. A provider and external subject can belong to only one local user. A provider email is used for a new account only when it is valid and not already held by another local account. It does not prove ownership of an existing local account, so a conflict causes provisioning without that email rather than an automatic account link. Concurrent first logins reconcile to the account that wins the identity uniqueness check. New accounts prefer a valid external identifier as the local username and use an opaque fallback when that name is not valid or is already taken. User and identity creation is treated as one operation, so a username race cannot attach the identity to an unrelated account. The store maps database-specific uniqueness errors to typed email, username, and identity conflicts so this flow can distinguish those races across supported databases. server/…/auth_service_sso.go• L19-186 server/…/auth_service_sso.go• L234-305 store/user_unique.go• L10-67 store/user_identity.go• L32-65
For provider setup, account linking, and provider-specific behavior, see Identity provider integration. The authentication API surface is described in API contracts and services.
References: server/…/auth_service.go• L44-134 server/…/auth_service_sso.go• L19-305 store/user_identity.go• L32-65 store/user_unique.go• L10-67 store/user_unique_test.go• L10-52
Request identity context
Request identity context is the server-side handoff between credential checks and service logic. API middleware authenticates the Authorization header, applies the result to the request context, and lets service methods read the local user ID or access-token claims without parsing credentials again. Anonymous requests keep an empty identity. server/…/authz.go• L20-28
The context carries different information based on the credential:
| Context value | Meaning |
|---|---|
| User ID | The local user resolved for the request; zero means no user |
| User claims | Claims from a JWT access token |
| Access token | The Bearer token used for token-based authentication |
| Refresh-token ID | The session token ID when a flow needs to identify that session |
Services use the user ID to load the current user. They use the current user record for roles and current account state. This keeps authorization tied to current local data instead of trusting all user properties in an old token. A missing, archived, or unknown account fails closed when the current user is resolved. server/…/auth_service_session.go• L269-291 server/…/auth_service_session_status_test.go• L11-26
References: server/…/authz.go• L20-28 server/…/auth_service_session.go• L269-291 server/…/auth_service_session_status_test.go• L11-26
API access policy
The API authorizer makes the first access decision before a service method runs. It separates authentication from policy: valid access-token and personal-access-token callers pass this layer, while anonymous callers can reach only bootstrap methods or methods allowed by the instance access mode. Admin checks and resource checks stay in the service or access layer. server/…/authz.go• L20-28 server/…/authz.go• L83-117
After access is allowed, the authorizer can apply a request budget. Authenticated requests use the local user as the budget key. Anonymous requests use the client address. Batch work adds its item count to the request cost, so one caller cannot avoid the limit by grouping work. server/…/authz.go• L47-80
The public method list is the shared policy for both API transports. Authentication bootstrap methods remain reachable on a private instance so a user can view sign-in settings, authenticate, register when allowed, and follow share links. Other public methods require the instance to allow anonymous access. An unresolved gateway route is treated as protected. server/…/acl_config.go• L3-87 server/…/v1.go• L95-138
Instance authentication settings also protect reachability. The system does not allow an update that disables password sign-in for regular users when no effective identity provider remains. This prevents an authentication configuration change from locking all regular users out. store/auth_config.go• L13-28 store/auth_config.go• L88-148
User account access
User account operations use the same local identity after the API authorizer admits the request. The first account can become an administrator. Later self-service registration depends on instance settings and the deployment's signup controls. Self-service signup is also bounded by per-address throttling, challenge checks, and an optional signup policy. Administrator-created users and first-user setup bypass these self-service gates, while an administrator can assign the requested role. server/…/user_service.go• L194-328
User lists are administrator-only. A signed-in user can update or delete that user's own account, while an administrator can manage other users. Role and account-state changes remain administrator actions. A password change also revokes the user's other refresh sessions. The current browser session survives when the user changes that user's own password. server/…/user_service.go• L66-76 server/…/user_service.go• L331-467 server/…/user_service.go• L470-509
Browser-facing account settings and management flows are described in Web settings and account management.
References: server/…/user_service.go• L66-76 server/…/user_service.go• L194-328 server/…/user_service.go• L331-467 server/…/user_service.go• L470-509
Memo authorization
Memo authorization decides whether a request may read or change a memo after the request identity is known. Read access is shared by API and file-serving paths through a transport-independent decision model. Write access uses the memo creator, the admin role, and the active membership of an assigned space. Notifications apply the same read boundary to the memo content they expose. server/…/memo.go• L1-119 server/…/memo_access.go• L15-183 server/…/user_service_notifications.go• L358-414
Memo read decisions
The memo visibility model has four levels. A public memo can be read anonymously only when the instance permits anonymous access. A protected memo needs a signed-in user. A private memo is limited to its creator, except for an exact share token. A space-audience memo is limited to active members of its valid space. Archived memos remain visible to their creator but appear as not found to other viewers. server/…/memo.go• L55-119 server/…/memo_resolve.go• L26-78
Comments inherit the parent's effective visibility. A viewer must pass both the comment state check and the parent memo check. A share for a parent or comment does not bypass this relationship. This prevents stale comment data or a share token from exposing a comment after the parent becomes restricted. server/…/memo.go• L42-70
The read decision maps to a small set of outcomes:
| Decision | API meaning |
|---|---|
| Allowed | The caller may read the memo |
| Not found | The memo is absent, archived for this viewer, or in an invalid state |
| Unauthenticated | The memo needs a signed-in user |
| Permission denied | The signed-in user is not allowed to read a private or space-audience memo |
This flow shows how identity, instance policy, memo state, and space membership combine into a read result.
flowchart TD
R[Memo read request] --> I[Resolve current user]
I --> S{Memo state and placement valid?}
S -- No --> N[Not found]
S -- Yes --> C{Comment?}
C -- Yes --> P[Check parent memo]
C -- No --> V[Check memo visibility]
P --> V
V --> A{Caller and visibility allow read?}
A -- Yes --> Y[Allow]
A -- No credentials --> U[Unauthenticated]
A -- Wrong user or space member --> D[Permission denied]
The API applies this decision to direct memo reads and to memo lists. Anonymous lists contain only public memos. Signed-in users can see their own memos plus public and protected memos. Space-audience results require current membership, and archived lists are limited to the current creator. The list scope is applied before pagination so hidden rows do not change counts or page boundaries. server/…/memo_service.go• L207-265 server/…/memo_service.go• L376-430 server/…/memo_access.go• L64-92
References: server/…/memo.go• L42-119 server/…/memo_resolve.go• L26-89 server/…/memo_access.go• L15-92 server/…/memo_service.go• L207-265 server/…/memo_service.go• L376-430 server/…/memo_test.go• L11-55
Memo write decisions
Memo creation requires a current user. Updates and deletes require the memo creator or an admin. The same ownership rule applies to related operations such as memo shares, reactions, relations, and attachments, with read checks applied where the operation exposes memo content. server/…/memo_service.go• L86-107 server/…/memo_service.go• L601-626 server/…/common.go• L77-82
Saved memo views are user-owned resources rather than shared memo resources. Their list, read, create, update, and delete operations resolve the user in the resource name and require the current user to be that owner. This prevents one signed-in user from reading or changing another user's saved filters. server/…/user_service_memo_views.go• L20-71 server/…/user_service_memo_views.go• L74-123 server/…/user_service_memo_views.go• L125-234
An assigned memo also needs a valid space and an active membership for the acting user. Space-audience changes must preserve that boundary and cannot proceed while active shares conflict with the new audience. The API maps lost space access and memo state conflicts to distinct client errors so callers do not mistake a rejected mutation for a server failure. server/…/memo_access.go• L94-182
Memo lifecycle and collaboration details are in Memo lifecycle and collaboration. Account usage budgets and quotas are described in Usage limits and quotas.
References: server/…/memo.go• L7-119 server/…/memo_access.go• L94-182 server/…/memo_service.go• L39-107 server/…/memo_service.go• L207-265 server/…/memo_service.go• L376-465 server/…/memo_service.go• L601-626 server/…/common.go• L77-82 server/…/user_service_memo_views.go• L20-234
Notification access decisions
User notifications are private inbox records. A user can list, update, or delete only notifications addressed to that user. The service also checks the current state of every memo named by a notification before it returns the notification or changes its status. server/…/user_service_notifications.go• L21-38 server/…/user_service_notifications.go• L93-142 server/…/user_service_notifications.go• L184-216
This keeps an old notification from becoming a side channel for content that the user can no longer read. Comment and mention notifications require access to each referenced memo. Space invitations remain visible only while the invitation has a valid pending or accepted state. server/…/user_service_notifications.go• L358-414
References: server/…/user_service_notifications.go• L21-88 server/…/user_service_notifications.go• L93-181 server/…/user_service_notifications.go• L184-224 server/…/user_service_notifications.go• L358-414
Filter access checks
Memo and attachment filters can name a space. A filter with a space condition is accepted only when it uses a direct equality to a resource name or null, and every named space must be writable by the active user. This keeps a query from using filter syntax to cross a space boundary. server/…/filter_access.go• L15-61
Anonymous callers can use filters that do not name a space. A filter that names a space requires authentication, and a caller without active membership receives the same not-found result used for an unknown space. server/…/filter_access.go• L40-61 server/…/memo_access.go• L94-132
References: server/…/filter_access.go• L15-145 server/…/memo_access.go• L94-132
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the access-token, refresh-token, and personal-access-token contracts aligned across token parsing, request middleware, refresh rotation, user-setting lookup, and the web token client.
- When changing access-token claims or password-session binding, preserve the current-password check and the rejection of old unbound access tokens.
- When changing personal access token storage or lookup, preserve hash-based lookup, expiry checks at authentication time, removal revocation, and the no-match behavior for missing or empty user settings.
- When changing identity-provider subject mapping or linkage rules, preserve the uniqueness of the provider-plus-external-subject pair, empty-subject rejection, registration gating before provisioning, safe email handling, preferred-username fallback, atomic account creation, and account-linking conflict behavior.
- When changing database error handling for user or external-identity writes, preserve typed email, username, and identity conflicts across supported driver message formats. Do not classify a duplicate value by text from the value itself.
- When adding or changing an API route, update the shared authorization classification used by both Connect and gRPC-Gateway. Keep authentication bootstrap methods within the public method set.
- When changing request budgets or batch costs, keep the authenticated and anonymous budget keys aligned with the identity result used by every transport.
- When changing user registration or account-management rules, preserve the first-user bootstrap path, the self-service throttling and challenge gates, and the separate self-owner and administrator boundaries.
- When changing password update behavior, preserve the refresh-session revocation rule and the exception that keeps the caller's current session when the caller changes that user's own password.
- When changing browser auth startup, preserve the distinction between settled identity and settings readiness. Do not let a new identity consume stale settings from the prior identity.
- When changing memo visibility, space placement, or comment relationships, update the shared memo decision used by API, file access, and notification paths.
- When changing notification ownership or payload rules, preserve the check that the current user owns the inbox record and can still read every referenced memo.
- When changing saved memo views or their resource names, preserve the rule that only the named user can list or change that user's views.
- When changing memo list filters, preserve the rule that named spaces require active membership and that the access scope is applied before pagination.
- When changing password or provider settings, keep the safe-state check that prevents regular users from losing every sign-in method.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Expired or revoked refresh token | The session cannot mint a new access token | Validate JWT claims and the stored refresh-token record before rotation |
| Password changes after an access token is issued | The old access token no longer authenticates | Bind the access token to the current password hash through the authentication hash |
| Pre-upgrade access token has no authentication hash | The token is rejected even if its other JWT claims are valid | Require the password-bound authentication hash; use the refresh session to obtain a new token |
| Deleted or expired personal access token | Bearer authentication resolves to no user | Store only the token hash and check expiry and user state on each use |
| Missing or empty personal-access-token setting | The token lookup returns no user | Treat absent settings and empty lists as normal misses |
| Corrupt personal-access-token setting | The lookup fails instead of silently accepting or ignoring bad token data | Surface the decode error and fail the lookup closed |
| OAuth state mismatch or expired state | The callback is rejected and the pending flow is removed | Match the callback state and enforce the ten-minute state lifetime |
| Identity provider returns an empty subject | Sign-in or provisioning stops before any account lookup or creation | Reject empty external identifiers before resolving the local user |
| Identity provider email is malformed or already belongs to another account | The new account is created without that email instead of being linked to the holder | Normalize and check the email, then rely on the database conflict guard |
| Concurrent first logins use the same external subject | One request may fail or link to the wrong account if the race is not reconciled | Enforce provider-subject uniqueness, classify the driver conflict as an identity conflict, and reload the winning local user |
| External identifier is invalid or its preferred local username is taken | Provisioning could collide with an existing local account | Validate the preferred name, retry with an opaque fallback, and create the user and identity atomically |
| A database reports a duplicate for another table or a duplicate value contains a driver marker | A valid user conflict could be misreported or an unrelated write could be treated as an identity conflict | Classify only the driver-reported constraint target and return no typed result for unrelated targets |
| Anonymous request to a protected or unknown API method | The request is rejected before the service runs | Use the shared authorizer and fail closed for unresolved routes |
| Request budget is spent | The request receives a resource-exhausted response | Charge the budget after access is allowed and include batch item cost |
| Registration is disabled or signup controls reject a request | Self-service account creation stops without creating a user | Apply instance settings, address limits, challenge checks, and signup policy before the write |
| Password is changed or reset | Other refresh sessions for that user stop working | Revoke all other refresh sessions and keep only the caller's current session for a self-change |
| Browser refresh cookie is valid but local token storage is empty | The browser could appear signed out in isolated storage | Attempt refresh before declaring the request unauthenticated |
| Browser identity changes while old settings are still loading | The new identity can render with stale settings | Reset full readiness and publish settings only for the current user |
| Comment parent becomes restricted | The comment is not exposed through its old visibility or share | Recheck the current parent decision for every comment read |
| Notification owner differs from the current user | The notification cannot be listed, changed, or deleted | Compare the current user with the addressed user and inbox receiver |
| A notification references a memo the viewer cannot read | The notification is hidden or treated as not found | Recheck access to every referenced memo before conversion or update |
| Space invitation is no longer pending or accepted | The invitation notification is hidden | Require a valid space and invitation state |
| Memo-view resource names target another user | The request cannot read or change that user's saved views | Resolve the named user and require the current user to be the owner |
| Space placement is missing or the viewer is not an active member | A space-audience memo is hidden or a space-scoped filter is rejected | Resolve placement and membership before granting access |
| Assigned memo loses writable space membership | The memo mutation stops instead of changing a resource outside the user's space | Require active membership for the acting user at write time |
| Active share conflicts with a SPACE audience change | The audience change is rejected until the share is revoked | Block the change while active shares remain |
| Password sign-in disabled with no effective provider | Regular users could lose all sign-in paths | Reject the unsafe authentication configuration mutation |
Key files
| File | Why to read it |
|---|---|
| server/…/authenticator.go | Shared credential resolution for API and file requests |
| server/…/token.go | Token kinds, claims, validation, password binding, and lifetimes |
| server/…/token_test.go | Guarantees for token shape, audience separation, expiry, hashing, and access-token lifecycle |
| server/…/context.go | Request identity values used by service code |
| server/…/authz.go | Method-level authentication, anonymous-access policy, and request budgets |
| server/…/acl_config.go | Public and authentication-bootstrap method policy |
| server/…/connect_interceptors.go | Connect request authentication and context propagation |
| server/…/v1.go | Shared authorization wiring for gateway and Connect transports |
| server/…/auth_service.go | Password and SSO sign-in entry points |
| server/…/auth_service_session.go | Session creation, refresh rotation, cookie policy, and sign-out |
| server/…/auth_service_sso.go | External subject validation, registration gating, account creation, email handling, username fallback, and account linking |
| store/user_identity.go | Local-to-external identity linkage contract and typed conflict propagation |
| store/user_unique.go | Cross-database classification of user and identity uniqueness conflicts |
| store/user_unique_test.go | Guarantees for driver-specific conflict classification and marker-safe matching |
| store/user_setting.go | Refresh-session and personal-access-token storage and lookup |
| store/…/user_setting_test.go | Guarantees for token lookup, revocation, missing settings, and concurrent session updates |
| server/…/user_service.go | User creation, account ownership, administrator boundaries, and password-session revocation |
| server/…/memo.go | Central memo read decision model |
| server/…/memo_resolve.go | Memo placement and viewer membership inputs for read decisions |
| server/…/memo_access.go | Memo read scopes, space membership, and write access mapping |
| server/…/user_service_memo_views.go | User ownership checks for saved memo views and their filters |
| server/…/filter_access.go | Space access checks for memo and attachment filters |
| server/…/memo_service.go | Memo list, read, create, update, and delete authorization points |
| server/…/user_service_notifications.go | Notification ownership and current memo or invitation access checks |
| server/…/user_service_access_tokens.go | Personal access token management |
| web/…/AuthContext.tsx | Browser identity initialization, refresh fallback, settings readiness, cache updates, and logout state |
| web/…/auth-state.ts | Browser access-token persistence and refresh coordination |
| web/…/oauth.ts | Browser OAuth state and PKCE flow protection |