Introducing a new way to review your PRs.

Read the announcement

usememos / memos

Memos is an open-source, self-hosted note-taking app that brings your everyday thoughts together in a personal timeline. Your data stays yours, and you choose what to keep private or share.

View on GitHub

25 documents · Updated Nov 20, 2026

docs / identity-authentication-and-access

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:

CredentialMain useValidation sourceLifetime or revocation behavior
Access tokenNormal API callsSigned JWT claims plus an active local user lookup and password-bound session checkShort lived; a password change invalidates previously issued tokens
Refresh tokenRenewing a browser sessionSigned JWT claims plus a stored token recordStored for revocation and rotated on refresh
Personal access tokenCLI, mobile, and other programmatic clientsSHA-256 token hash stored with the userOptional 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 valueMeaning
User IDThe local user resolved for the request; zero means no user
User claimsClaims from a JWT access token
Access tokenThe Bearer token used for token-based authentication
Refresh-token IDThe 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:

DecisionAPI meaning
AllowedThe caller may read the memo
Not foundThe memo is absent, archived for this viewer, or in an invalid state
UnauthenticatedThe memo needs a signed-in user
Permission deniedThe 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

TriggerConsequenceGuard
Expired or revoked refresh tokenThe session cannot mint a new access tokenValidate JWT claims and the stored refresh-token record before rotation
Password changes after an access token is issuedThe old access token no longer authenticatesBind the access token to the current password hash through the authentication hash
Pre-upgrade access token has no authentication hashThe token is rejected even if its other JWT claims are validRequire the password-bound authentication hash; use the refresh session to obtain a new token
Deleted or expired personal access tokenBearer authentication resolves to no userStore only the token hash and check expiry and user state on each use
Missing or empty personal-access-token settingThe token lookup returns no userTreat absent settings and empty lists as normal misses
Corrupt personal-access-token settingThe lookup fails instead of silently accepting or ignoring bad token dataSurface the decode error and fail the lookup closed
OAuth state mismatch or expired stateThe callback is rejected and the pending flow is removedMatch the callback state and enforce the ten-minute state lifetime
Identity provider returns an empty subjectSign-in or provisioning stops before any account lookup or creationReject empty external identifiers before resolving the local user
Identity provider email is malformed or already belongs to another accountThe new account is created without that email instead of being linked to the holderNormalize and check the email, then rely on the database conflict guard
Concurrent first logins use the same external subjectOne request may fail or link to the wrong account if the race is not reconciledEnforce 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 takenProvisioning could collide with an existing local accountValidate 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 markerA valid user conflict could be misreported or an unrelated write could be treated as an identity conflictClassify only the driver-reported constraint target and return no typed result for unrelated targets
Anonymous request to a protected or unknown API methodThe request is rejected before the service runsUse the shared authorizer and fail closed for unresolved routes
Request budget is spentThe request receives a resource-exhausted responseCharge the budget after access is allowed and include batch item cost
Registration is disabled or signup controls reject a requestSelf-service account creation stops without creating a userApply instance settings, address limits, challenge checks, and signup policy before the write
Password is changed or resetOther refresh sessions for that user stop workingRevoke 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 emptyThe browser could appear signed out in isolated storageAttempt refresh before declaring the request unauthenticated
Browser identity changes while old settings are still loadingThe new identity can render with stale settingsReset full readiness and publish settings only for the current user
Comment parent becomes restrictedThe comment is not exposed through its old visibility or shareRecheck the current parent decision for every comment read
Notification owner differs from the current userThe notification cannot be listed, changed, or deletedCompare the current user with the addressed user and inbox receiver
A notification references a memo the viewer cannot readThe notification is hidden or treated as not foundRecheck access to every referenced memo before conversion or update
Space invitation is no longer pending or acceptedThe invitation notification is hiddenRequire a valid space and invitation state
Memo-view resource names target another userThe request cannot read or change that user's saved viewsResolve the named user and require the current user to be the owner
Space placement is missing or the viewer is not an active memberA space-audience memo is hidden or a space-scoped filter is rejectedResolve placement and membership before granting access
Assigned memo loses writable space membershipThe memo mutation stops instead of changing a resource outside the user's spaceRequire active membership for the acting user at write time
Active share conflicts with a SPACE audience changeThe audience change is rejected until the share is revokedBlock the change while active shares remain
Password sign-in disabled with no effective providerRegular users could lose all sign-in pathsReject the unsafe authentication configuration mutation

Key files

FileWhy to read it
server/…/authenticator.goShared credential resolution for API and file requests
server/…/token.goToken kinds, claims, validation, password binding, and lifetimes
server/…/token_test.goGuarantees for token shape, audience separation, expiry, hashing, and access-token lifecycle
server/…/context.goRequest identity values used by service code
server/…/authz.goMethod-level authentication, anonymous-access policy, and request budgets
server/…/acl_config.goPublic and authentication-bootstrap method policy
server/…/connect_interceptors.goConnect request authentication and context propagation
server/…/v1.goShared authorization wiring for gateway and Connect transports
server/…/auth_service.goPassword and SSO sign-in entry points
server/…/auth_service_session.goSession creation, refresh rotation, cookie policy, and sign-out
server/…/auth_service_sso.goExternal subject validation, registration gating, account creation, email handling, username fallback, and account linking
store/user_identity.goLocal-to-external identity linkage contract and typed conflict propagation
store/user_unique.goCross-database classification of user and identity uniqueness conflicts
store/user_unique_test.goGuarantees for driver-specific conflict classification and marker-safe matching
store/user_setting.goRefresh-session and personal-access-token storage and lookup
store/…/user_setting_test.goGuarantees for token lookup, revocation, missing settings, and concurrent session updates
server/…/user_service.goUser creation, account ownership, administrator boundaries, and password-session revocation
server/…/memo.goCentral memo read decision model
server/…/memo_resolve.goMemo placement and viewer membership inputs for read decisions
server/…/memo_access.goMemo read scopes, space membership, and write access mapping
server/…/user_service_memo_views.goUser ownership checks for saved memo views and their filters
server/…/filter_access.goSpace access checks for memo and attachment filters
server/…/memo_service.goMemo list, read, create, update, and delete authorization points
server/…/user_service_notifications.goNotification ownership and current memo or invitation access checks
server/…/user_service_access_tokens.goPersonal access token management
web/…/AuthContext.tsxBrowser identity initialization, refresh fallback, settings readiness, cache updates, and logout state
web/…/auth-state.tsBrowser access-token persistence and refresh coordination
web/…/oauth.tsBrowser OAuth state and PKCE flow protection