diff --git a/ross/docs/docs/authentication/api-key.md b/ross/docs/docs/authentication/api-key.md index 93632d94..f112c895 100644 --- a/ross/docs/docs/authentication/api-key.md +++ b/ross/docs/docs/authentication/api-key.md @@ -49,7 +49,7 @@ Rules enforced at startup: - `userModel` is not used. There is no identity table. - `rbac.enabled: true` is rejected: RBAC needs per-user roles, which a shared key cannot provide. -A valid minimal configuration therefore needs only `enabled` and `providers`. `jwtSecret` must be absent, and `userModel` / `tokenExpiration` have no effect. +A valid minimal configuration therefore needs only `enabled` and `providers`. `jwtSecret` must be absent, and `userModel` / `accessTokenExpiration` / `refreshTokenExpiration` / `sessionStorage` have no effect. ## Using the key diff --git a/ross/docs/docs/authentication/introduction.md b/ross/docs/docs/authentication/introduction.md index 8c9f13cb..a46be6d1 100644 --- a/ross/docs/docs/authentication/introduction.md +++ b/ross/docs/docs/authentication/introduction.md @@ -9,16 +9,16 @@ ROSS has a built-in authentication layer that is entirely configuration-driven. The authentication surface is built around a single contract: ```text -provider verifies the caller → ROSS resolves a local user row → ROSS issues one JWT +provider verifies the caller → ROSS resolves a local user row → ROSS issues access + refresh tokens ``` -Password login, OAuth2, OIDC, and SAML differ only in how the caller is verified. They all converge on the same user table, the same access token, the same `Authorization: Bearer ` header, and the same RBAC claims. An `api-key` provider is the exception: it authenticates the caller statically, without a user row or a JWT. +Password login, OAuth2, OIDC, and SAML differ only in how the caller is verified. They all converge on the same user table, the same access and refresh tokens, the same `Authorization: Bearer ` header, and the same RBAC claims. An `api-key` provider is the exception: it authenticates the caller statically, without a user row, a JWT, or a refresh token. -Authentication is optional at the top level. When it is omitted, ROSS starts normally and every generated API is public unless you opt into route-level authorization. +Authentication is optional at the top level. When it is omitted or disabled, ROSS starts normally with every generated API public, and setting route-level `authorization: true` is rejected at startup. ## Supported providers -| Provider | Identifier | Caller verified by | Access token | Documentation | +| Provider | Identifier | Caller verified by | Token | Documentation | | --- | --- | --- | --- | --- | | Local password | `"up-auth"` | Username and password (bcrypt) | JWT | [Password authentication](./up-auth.md) | | OAuth2 | `"sso"` with `"protocol": "oauth2"` | External OAuth2 authorization server | JWT | [OAuth2](./oauth2.md) | @@ -35,7 +35,9 @@ Authentication lives at the top level of your configuration file: "authentication": { "enabled": true, "jwtSecret": "env:JWT_SECRET", - "tokenExpiration": "1d", + "accessTokenExpiration": "15m", + "refreshTokenExpiration": "7d", + "sessionStorage": "db", "userModel": { "modelName": "users", "idField": "id", @@ -73,7 +75,9 @@ Authentication lives at the top level of your configuration file: | --- | --- | --- | --- | --- | | `enabled` | `boolean` | **Yes** | — | Enables the auth layer. When `false`, no other key may be present. | | `jwtSecret` | `string` | Conditional | — | Secret used to sign access tokens. Minimum 32 characters. Required when an identity provider is configured, forbidden when only `api-key` is configured. | -| `tokenExpiration` | `string` | No | `"1d"` | Access-token lifetime. Pattern: digits followed by `s`, `m`, `h`, or `d` (for example `"15m"`, `"8h"`, `"7d"`). | +| `accessTokenExpiration` | `string` | No | `"15m"` | Access-token lifetime. Pattern: digits followed by `s`, `m`, `h`, or `d` (for example `"15m"`, `"8h"`, `"7d"`). | +| `refreshTokenExpiration` | `string` | No | `"7d"` | Refresh-token session lifetime. Pattern: digits followed by `s`, `m`, `h`, or `d`. | +| `sessionStorage` | `"db" \| "cache"` | No | `"db"` | Backend used to store refresh token sessions (`"db"` uses an internal `_ross_sessions` table; `"cache"` uses the configured cache backend). | | `userModel` | `object` | Conditional | — | The table that stores identities. Required when `up-auth` or `sso` is configured. | | `providers` | `array` | **Yes** | — | One or more provider entries. Minimum one item. | @@ -119,7 +123,7 @@ Validation runs before the server starts, so configuration mistakes fail fast: - At most **one** `up-auth` provider and at most **one** `api-key` provider may be configured. - `api-key` cannot be combined with any identity provider. An application either authenticates users or accepts a shared key. - Every identity provider requires `jwtSecret` and a `userModel` whose fields exist in the referenced model. -- SSO provider `name` values are lowercase alphanumeric with optional hyphens, up to 32 characters, and must be unique. Names that collide with auth route segments are reserved: `api-key`, `callback`, `change-email`, `change-password`, `edit-me`, `forgot-password`, `login`, `me`, `metadata`, `providers`, `register`, `registration`, `resend-otp`, `sso`, `token`, `up-auth`, `user`, `verify`. +- SSO provider `name` values are lowercase alphanumeric with optional hyphens, up to 32 characters, and must be unique. Names that collide with auth route segments are reserved: `api-key`, `callback`, `change-email`, `change-password`, `edit-me`, `forgot-password`, `login`, `logout`, `me`, `metadata`, `providers`, `refresh`, `register`, `registration`, `resend-otp`, `sso`, `token`, `up-auth`, `user`, `verify`. - `up-auth` and SSO providers can be combined. `api-key` cannot. ## Access tokens @@ -141,7 +145,7 @@ Every identity provider issues the same JWT. The payload is built from `userMode - `providerId` holds the external SSO subject identifier (for SSO logins) or `null` (for `up-auth` logins). - `email` holds the user's email/username (or `null` if unconfigured or absent). If a custom `usernameField` is configured (such as `"username"`), that property is also included. - `role` or `roles` appear only when RBAC is enabled. They are extracted from `rbac.roleField`, falling back to `rbac.defaultRole`. -- The token is signed with `jwtSecret` and expires after `tokenExpiration`. +- The token is signed with `jwtSecret` and expires after `accessTokenExpiration`. - Clients send it as `Authorization: Bearer `. Protected routes validate the token before the handler runs. A missing or invalid token returns `401` with `"Invalid or expired authentication token"`. @@ -152,6 +156,70 @@ Rotating `jwtSecret` invalidates every access token, every in-flight SSO flow, a ::: +## Refresh tokens and session storage + +Every identity login (`POST /auth/login`, `POST /auth/login/verify/otp`, and SSO callback or token exchange) issues a `refreshToken` alongside `accessToken`: + +```json +{ + "accessToken": "eyJhbGciOi...", + "refreshToken": "xK9..." +} +``` + +- Refresh tokens are opaque 32-byte random strings (`base64url`). ROSS stores only their SHA-256 hex digest, never the raw token. +- Each session expires after `refreshTokenExpiration` (default `"7d"`). +- Refresh tokens are **single-use and rotated**: exchanging a refresh token deletes the consumed session and issues a new `accessToken` and `refreshToken` pair. Replaying an already-used or expired token returns `401`. + +### Session storage backends + +Configure where refresh token sessions live with `authentication.sessionStorage`: + +- **`"db"` (default)**: Stores sessions in an internal `_ross_sessions` table (`id`, `user_id`, `token_hash`, `expires_at`, `created_at`). ROSS automatically includes `_ross_sessions` in database migrations when `sessionStorage` is `"db"`, and deletes all of a user's sessions when they call `DELETE /auth/user/me`. `_ross_sessions` is reserved and cannot be used as a model name under `data.models`. +- **`"cache"`**: Stores sessions in the configured cache under `session:refresh:` with a TTL matching `refreshTokenExpiration`. When no distributed cache (Redis or Memcached) is configured, sessions are stored in in-memory `node-cache` (not shared across processes and lost on restart), and ROSS logs a startup warning. + +### Refreshing tokens + +```http +POST /api/v1/auth/refresh +Content-Type: application/json + +{"refreshToken": "xK9..."} +``` + +```json +{ + "code": 200, + "message": "Token refreshed successfully", + "data": { + "accessToken": "eyJhbGciOi...", + "refreshToken": "mP4..." + } +} +``` + +If the token is missing, invalid, expired, already consumed, or belongs to a deleted user, the endpoint returns `401` with `"Invalid or expired refresh token"`. + +### Logging out + +```http +POST /api/v1/auth/logout +Authorization: Bearer +Content-Type: application/json + +{"refreshToken": "mP4..."} +``` + +```json +{ + "code": 200, + "message": "Logged out successfully", + "data": {"success": true} +} +``` + +Revokes the given refresh token session if it belongs to the authenticated user. + ## Provider discovery When at least one identity provider (`up-auth` or `sso`) is configured, ROSS exposes a discovery document: @@ -202,6 +270,8 @@ Auth routes are mounted under the API prefix and variant, so the default base pa | Route | Requires | | --- | --- | | `GET /auth/providers` | At least one identity provider | +| `POST /auth/refresh` | At least one identity provider | +| `POST /auth/logout` | At least one identity provider | | `POST /auth/register` | `up-auth` | | `POST /auth/login` | `up-auth` | | `POST /auth/change-password` | `up-auth` | diff --git a/ross/docs/docs/authentication/oauth2.md b/ross/docs/docs/authentication/oauth2.md index caefe1b1..8063a2dc 100644 --- a/ross/docs/docs/authentication/oauth2.md +++ b/ross/docs/docs/authentication/oauth2.md @@ -15,7 +15,9 @@ ROSS starts the flow, exchanges the authorization code for an access token, read "authentication": { "enabled": true, "jwtSecret": "env:JWT_SECRET", - "tokenExpiration": "1d", + "accessTokenExpiration": "15m", + "refreshTokenExpiration": "7d", + "sessionStorage": "db", "userModel": { "modelName": "users", "idField": "id", @@ -99,7 +101,7 @@ The path is the login route with `/login` replaced by `/callback`. Register that 4. ROSS POST https://github.com/login/oauth/access_token 5. ROSS GET https://api.github.com/user (Bearer token) 6. ROSS find-or-create the local user for (github, ) -7. ROSS 200 {"accessToken": "..."} or 302 ?code= +7. ROSS 200 {"accessToken": "...", "refreshToken": "..."} or 302 ?code= ``` ### 1. Start the flow @@ -170,7 +172,7 @@ When `redirectUrl` is not configured, the callback responds directly with the ac { "code": 200, "message": "SSO authentication successful", - "data": {"accessToken": "eyJhbGciOi..."} + "data": {"accessToken": "eyJhbGciOi...", "refreshToken": "xK9..."} } ``` @@ -196,7 +198,7 @@ Content-Type: application/json { "code": 200, "message": "SSO authentication successful", - "data": {"accessToken": "eyJhbGciOi..."} + "data": {"accessToken": "eyJhbGciOi...", "refreshToken": "xK9..."} } ``` diff --git a/ross/docs/docs/authentication/oidc.md b/ross/docs/docs/authentication/oidc.md index 75dcabe2..a4c250d7 100644 --- a/ross/docs/docs/authentication/oidc.md +++ b/ross/docs/docs/authentication/oidc.md @@ -15,7 +15,9 @@ ROSS discovers the provider's endpoints and signing keys from `{issuerUrl}/.well "authentication": { "enabled": true, "jwtSecret": "env:JWT_SECRET", - "tokenExpiration": "1d", + "accessTokenExpiration": "15m", + "refreshTokenExpiration": "7d", + "sessionStorage": "db", "userModel": { "modelName": "users", "idField": "id", @@ -97,7 +99,7 @@ When `callbackUrl` is omitted, ROSS derives it per request from the login route, 5. ROSS POST token endpoint with code + PKCE verifier 6. ROSS validate ID token signature, issuer, audience, nonce, and state 7. ROSS find-or-create the local user for (google, sub) -8. ROSS 200 {"accessToken": "..."} or 302 ?code= +8. ROSS 200 {"accessToken": "...", "refreshToken": "..."} or 302 ?code= ``` ### 1. Discovery and authorization @@ -160,7 +162,7 @@ Without `redirectUrl`, the callback returns the token directly: { "code": 200, "message": "SSO authentication successful", - "data": {"accessToken": "eyJhbGciOi..."} + "data": {"accessToken": "eyJhbGciOi...", "refreshToken": "xK9..."} } ``` @@ -184,7 +186,7 @@ Content-Type: application/json { "code": 200, "message": "SSO authentication successful", - "data": {"accessToken": "eyJhbGciOi..."} + "data": {"accessToken": "eyJhbGciOi...", "refreshToken": "xK9..."} } ``` diff --git a/ross/docs/docs/authentication/saml.md b/ross/docs/docs/authentication/saml.md index 42e7497f..09298d06 100644 --- a/ross/docs/docs/authentication/saml.md +++ b/ross/docs/docs/authentication/saml.md @@ -15,7 +15,9 @@ SAML is the right choice for enterprise identity providers that do not expose OA "authentication": { "enabled": true, "jwtSecret": "env:JWT_SECRET", - "tokenExpiration": "1d", + "accessTokenExpiration": "15m", + "refreshTokenExpiration": "7d", + "sessionStorage": "db", "userModel": { "modelName": "users", "idField": "id", @@ -111,7 +113,7 @@ The path is the login route with `/login` replaced by `/callback`, or the metada SAMLResponse=&RelayState=... 5. ROSS validate signature, audience, conditions, and InResponseTo 6. ROSS find-or-create the local user for (corp, NameID) -7. ROSS 200 {"accessToken": "..."} or 302 ?code= +7. ROSS 200 {"accessToken": "...", "refreshToken": "..."} or 302 ?code= ``` ### 1. Start the flow @@ -170,7 +172,7 @@ Without `redirectUrl`, the ACS responds with the token: { "code": 200, "message": "SSO authentication successful", - "data": {"accessToken": "eyJhbGciOi..."} + "data": {"accessToken": "eyJhbGciOi...", "refreshToken": "xK9..."} } ``` @@ -194,7 +196,7 @@ Content-Type: application/json { "code": 200, "message": "SSO authentication successful", - "data": {"accessToken": "eyJhbGciOi..."} + "data": {"accessToken": "eyJhbGciOi...", "refreshToken": "xK9..."} } ``` diff --git a/ross/docs/docs/authentication/up-auth.md b/ross/docs/docs/authentication/up-auth.md index 4e6c0ffd..5b45e995 100644 --- a/ross/docs/docs/authentication/up-auth.md +++ b/ross/docs/docs/authentication/up-auth.md @@ -15,7 +15,9 @@ This is the only provider that owns a password. It also provides registration, p "authentication": { "enabled": true, "jwtSecret": "env:JWT_SECRET", - "tokenExpiration": "1d", + "accessTokenExpiration": "15m", + "refreshTokenExpiration": "7d", + "sessionStorage": "db", "userModel": { "modelName": "users", "idField": "id", @@ -147,7 +149,10 @@ The body accepts exactly the two configured fields; any additional property is r { "code": 200, "message": "Login successful", - "data": {"accessToken": "eyJhbGciOi..."} + "data": { + "accessToken": "eyJhbGciOi...", + "refreshToken": "xK9..." + } } ``` @@ -191,7 +196,10 @@ Content-Type: application/json { "code": 200, "message": "OTP verification successful", - "data": {"accessToken": "eyJhbGciOi..."} + "data": { + "accessToken": "eyJhbGciOi...", + "refreshToken": "xK9..." + } } ``` @@ -199,7 +207,7 @@ The same route behaviour is used for the three OTP flows: | Route | Action | Body | | --- | --- | --- | -| `POST /auth/login/verify/otp` | Completes login and returns `accessToken` | `ulid`, `otp`, username | +| `POST /auth/login/verify/otp` | Completes login and returns `accessToken` and `refreshToken` | `ulid`, `otp`, username | | `POST /auth/register/verify/otp` | Marks the account verified, returns `data: null` | `ulid`, `otp`, username | | `POST /auth/forgot-password/verify/otp` | Sets the new password, returns `{success: true}` | `ulid`, `otp`, username, `newPassword` | @@ -411,7 +419,7 @@ Deletion runs inside a transaction. The row is removed permanently; ROSS does no | `` | The username column, when it has a value | | `role` | `rbac.roleField` when RBAC is enabled and the value is a scalar | | `roles` | `rbac.roleField` when the value is an array or a JSON-encoded array | -| `iat`, `exp` | Issued-at and `tokenExpiration` | +| `iat`, `exp` | Issued-at and `accessTokenExpiration` | ## Full example with MFA and verification @@ -429,7 +437,7 @@ Deletion runs inside a transaction. The row is removed permanently; ROSS does no "authentication": { "enabled": true, "jwtSecret": "env:JWT_SECRET", - "tokenExpiration": "8h", + "accessTokenExpiration": "8h", "userModel": { "modelName": "users", "idField": "id", @@ -505,6 +513,8 @@ Password routes use the API policy identifiers `auth...unkno | --- | --- | | Registration | `auth.v1.users.unknown.registration` | | Login | `auth.v1.users.unknown.login` | +| Refresh token | `auth.v1.users.unknown.refresh` | +| Logout | `auth.v1.users.unknown.logout` | | Change password | `auth.v1.users.unknown.changePassword` | | Forgot password | `auth.v1.users.unknown.forgotPassword` | | OTP verify (login) | `auth.v1.users.unknown.otpVerifyLogin` | diff --git a/ross/e2e/auth.spec.ts b/ross/e2e/auth.spec.ts index 1a1b0341..e7f47f55 100644 --- a/ross/e2e/auth.spec.ts +++ b/ross/e2e/auth.spec.ts @@ -324,7 +324,7 @@ const upAuthE2EConfig: AppConfigInput = { authentication: { enabled: true, jwtSecret: 'e2e-up-auth-jwt-secret-at-least-32-chars-long!', - tokenExpiration: '1h', + accessTokenExpiration: '1h', userModel: { modelName: 'users', idField: 'id', @@ -422,6 +422,7 @@ test.describe .serial('Playwright E2E: Username & Password Authentication (up-auth)', () => { let server: E2EServer; let authToken: string; + let refreshToken: string; const testUser = { email: 'alice@example.com', @@ -512,7 +513,7 @@ test.describe expect(res.status()).toBe(401); }); - test('Authenticates successfully with valid credentials and issues accessToken (HTTP 200)', async () => { + test('Authenticates successfully with valid credentials and issues accessToken & refreshToken (HTTP 200)', async () => { const res = await server.request.post('/api/v1/auth/login', { data: { email: testUser.email, @@ -524,8 +525,59 @@ test.describe expect(body.code).toBe(200); expect(body.data).toBeDefined(); expect(typeof body.data.accessToken).toBe('string'); + expect(typeof body.data.refreshToken).toBe('string'); authToken = body.data.accessToken; + refreshToken = body.data.refreshToken; expect(authToken.length).toBeGreaterThan(20); + expect(refreshToken.length).toBeGreaterThan(20); + }); + + test('Refreshes tokens via POST /api/v1/auth/refresh and rotates refreshToken (HTTP 200)', async () => { + const res = await server.request.post('/api/v1/auth/refresh', { + data: {refreshToken}, + }); + expect(res.status()).toBe(200); + const body = await res.json(); + expect(typeof body.data.accessToken).toBe('string'); + expect(typeof body.data.refreshToken).toBe('string'); + expect(body.data.refreshToken).not.toBe(refreshToken); + + // Reusing old refresh token must fail with 401 + const replayRes = await server.request.post('/api/v1/auth/refresh', { + data: {refreshToken}, + }); + expect(replayRes.status()).toBe(401); + + authToken = body.data.accessToken; + refreshToken = body.data.refreshToken; + }); + + test('Revokes refresh token on POST /api/v1/auth/logout (HTTP 200)', async () => { + const logoutRes = await server.request.post('/api/v1/auth/logout', { + headers: {Authorization: `Bearer ${authToken}`}, + data: {refreshToken}, + }); + expect(logoutRes.status()).toBe(200); + + const refreshAfterLogout = await server.request.post( + '/api/v1/auth/refresh', + { + data: {refreshToken}, + }, + ); + expect(refreshAfterLogout.status()).toBe(401); + + // Re-login to leave authToken & refreshToken valid for subsequent tests + const loginRes = await server.request.post('/api/v1/auth/login', { + data: { + email: testUser.email, + password: testUser.password, + }, + }); + expect(loginRes.status()).toBe(200); + const loginBody = await loginRes.json(); + authToken = loginBody.data.accessToken; + refreshToken = loginBody.data.refreshToken; }); }); diff --git a/ross/src/constants.ts b/ross/src/constants.ts index d7e6320a..e8e66f9f 100644 --- a/ross/src/constants.ts +++ b/ross/src/constants.ts @@ -9,3 +9,5 @@ export const OTP_LENGTH = 6; export const OTP_EMAIL_SUBJECT = 'Your OTP Code'; export const NODE_CACHE_OTP_WARNING = 'No distributed cache configured; OTPs are stored in node-cache (in-memory). OTPs are not shared across processes and will be lost on restart.'; +export const NODE_CACHE_SESSION_WARNING = + 'No distributed cache configured; refresh token sessions are stored in node-cache (in-memory). Sessions are not shared across processes and will be lost on restart.'; diff --git a/ross/src/interfaces/config.ts b/ross/src/interfaces/config.ts index c1d927a9..da0eb0fc 100644 --- a/ross/src/interfaces/config.ts +++ b/ross/src/interfaces/config.ts @@ -362,10 +362,14 @@ export type AuthProviderInput = /** Convenience aliases kept for readability at call sites. */ export type AuthProvider = AuthProviderInput; +export type SessionStorageBackend = 'db' | 'cache'; + export interface AuthenticationConfigInput { enabled?: boolean; jwtSecret?: string; - tokenExpiration?: string; + accessTokenExpiration?: string; + refreshTokenExpiration?: string; + sessionStorage?: SessionStorageBackend; userModel?: AuthUserModelConfig; providers?: AuthProviderInput[]; } @@ -674,7 +678,9 @@ export type ResolvedAuthenticationConfig = | { enabled: true; jwtSecret?: string; - tokenExpiration: string; + accessTokenExpiration: string; + refreshTokenExpiration: string; + sessionStorage: SessionStorageBackend; userModel?: AuthUserModelConfig; providers: ResolvedAuthProvider[]; }; diff --git a/ross/src/lib/auth/session.ts b/ross/src/lib/auth/session.ts new file mode 100644 index 00000000..7d4095bb --- /dev/null +++ b/ross/src/lib/auth/session.ts @@ -0,0 +1,282 @@ +import crypto from 'crypto'; + +import {FastifyInstance} from 'fastify'; + +import {resolveModelField} from '@/lib/config/resolve'; + +import {ResolvedAppConfig, ResolvedModelConfig} from '@/interfaces/config'; + +import {parseDuration} from '@/utils/duration'; +import {sha256} from '@/utils/hash'; + +export const SESSION_TABLE_NAME = '_ross_sessions'; +const SESSION_CACHE_PREFIX = 'session:refresh:'; + +interface CacheSessionPayload { + sessionId: string; + userId: string; + expiresAt: string; +} + +export interface IssuedSession { + sessionId: string; + refreshToken: string; + expiresAt: string; +} + +export interface RotatedSession extends IssuedSession { + userId: string; +} + +/** + * Internal Drizzle model definition for the `_ross_sessions` table when + * `authentication.sessionStorage` is `"db"`. + */ +export function getSessionModelConfig(): ResolvedModelConfig { + return { + timestamps: false, + fields: { + id: resolveModelField({ + type: 'string', + primaryKey: true, + nullable: false, + }), + user_id: resolveModelField({type: 'string', nullable: false}), + token_hash: resolveModelField({ + type: 'string', + nullable: false, + unique: true, + }), + expires_at: resolveModelField({type: 'string', nullable: false}), + created_at: resolveModelField({type: 'string', nullable: false}), + }, + indexes: { + idx_ross_sessions_user_id: { + fields: ['user_id'], + unique: false, + }, + }, + relations: {}, + }; +} + +function generateRefreshToken(): string { + return crypto.randomBytes(32).toString('base64url'); +} + +function getSessionCacheKey(tokenHash: string): string { + return `${SESSION_CACHE_PREFIX}${tokenHash}`; +} + +function getAuthSessionConfig(config: ResolvedAppConfig): { + sessionStorage: 'db' | 'cache'; + ttlMs: number; +} { + const {authentication} = config; + + if (!authentication.enabled) { + throw new Error('Authentication is not enabled'); + } + + return { + sessionStorage: authentication.sessionStorage, + ttlMs: parseDuration(authentication.refreshTokenExpiration), + }; +} + +/** + * Create a new refresh token session in the configured backend (`db` or `cache`). + */ +export async function createSession( + app: Pick, + config: ResolvedAppConfig, + userId: unknown, +): Promise { + const {sessionStorage, ttlMs} = getAuthSessionConfig(config); + const sessionId = crypto.randomUUID(); + const refreshToken = generateRefreshToken(); + const tokenHash = sha256(refreshToken); + const now = Date.now(); + const expiresAt = new Date(now + ttlMs).toISOString(); + const createdAt = new Date(now).toISOString(); + const userIdStr = String(userId); + + if (sessionStorage === 'cache') { + const ttlSeconds = Math.max(1, Math.ceil(ttlMs / 1000)); + const payload: CacheSessionPayload = { + sessionId, + userId: userIdStr, + expiresAt, + }; + await app.cache.set(getSessionCacheKey(tokenHash), payload, ttlSeconds); + return {sessionId, refreshToken, expiresAt}; + } + + await app.db.query( + `INSERT INTO "${SESSION_TABLE_NAME}" ("id", "user_id", "token_hash", "expires_at", "created_at") VALUES ($1, $2, $3, $4, $5);`, + [sessionId, userIdStr, tokenHash, expiresAt, createdAt], + ); + + return {sessionId, refreshToken, expiresAt}; +} + +/** + * Validate a refresh token, delete the consumed session, and issue a rotated + * refresh token session. Returns `null` if the token is missing, invalid, or + * expired. + */ +export async function rotateSession( + app: Pick, + config: ResolvedAppConfig, + refreshToken: string, +): Promise { + if (!refreshToken || typeof refreshToken !== 'string') { + return null; + } + + const {sessionStorage, ttlMs} = getAuthSessionConfig(config); + const tokenHash = sha256(refreshToken); + + if (sessionStorage === 'cache') { + const cacheKey = getSessionCacheKey(tokenHash); + const entry = await app.cache.get(cacheKey); + + if (!entry) { + return null; + } + + await app.cache.delete(cacheKey); + + if (Date.parse(entry.expiresAt) <= Date.now()) { + return null; + } + + const next = await createSession(app, config, entry.userId); + return { + userId: entry.userId, + ...next, + }; + } + + let tx; + try { + tx = await app.db.beginTransaction(); + + const selectRes = await tx.query<{ + id: string; + user_id: string; + expires_at: string; + }>( + `SELECT "id", "user_id", "expires_at" FROM "${SESSION_TABLE_NAME}" WHERE "token_hash" = $1 LIMIT 1;`, + [tokenHash], + ); + + const row = selectRes.rows[0]; + if (!row) { + await tx.commit(); + return null; + } + + const deleteRes = await tx.query( + `DELETE FROM "${SESSION_TABLE_NAME}" WHERE "token_hash" = $1;`, + [tokenHash], + ); + + if (deleteRes.changes === 0 || Date.parse(row.expires_at) <= Date.now()) { + await tx.commit(); + return null; + } + + const newSessionId = crypto.randomUUID(); + const newRefreshToken = generateRefreshToken(); + const newTokenHash = sha256(newRefreshToken); + const now = Date.now(); + const newExpiresAt = new Date(now + ttlMs).toISOString(); + const createdAt = new Date(now).toISOString(); + const userIdStr = String(row.user_id); + + await tx.query( + `INSERT INTO "${SESSION_TABLE_NAME}" ("id", "user_id", "token_hash", "expires_at", "created_at") VALUES ($1, $2, $3, $4, $5);`, + [newSessionId, userIdStr, newTokenHash, newExpiresAt, createdAt], + ); + + await tx.commit(); + + return { + userId: userIdStr, + sessionId: newSessionId, + refreshToken: newRefreshToken, + expiresAt: newExpiresAt, + }; + } catch (err) { + if (tx) await tx.rollback().catch(() => {}); + throw err; + } finally { + tx?.release(); + } +} + +/** + * Delete a refresh token session from the configured backend. When `userId` is + * provided, only deletes the session if it belongs to that user. + */ +export async function revokeSession( + app: Pick, + config: ResolvedAppConfig, + refreshToken: string, + userId?: unknown, +): Promise { + if (!refreshToken || typeof refreshToken !== 'string') { + return false; + } + + const {sessionStorage} = getAuthSessionConfig(config); + const tokenHash = sha256(refreshToken); + + if (sessionStorage === 'cache') { + const cacheKey = getSessionCacheKey(tokenHash); + if (userId !== undefined) { + const entry = await app.cache.get(cacheKey); + if (!entry || entry.userId !== String(userId)) { + return false; + } + } + await app.cache.delete(cacheKey); + return true; + } + + if (userId !== undefined) { + const res = await app.db.query( + `DELETE FROM "${SESSION_TABLE_NAME}" WHERE "token_hash" = $1 AND "user_id" = $2;`, + [tokenHash, String(userId)], + ); + return res.changes > 0; + } + + const res = await app.db.query( + `DELETE FROM "${SESSION_TABLE_NAME}" WHERE "token_hash" = $1;`, + [tokenHash], + ); + return res.changes > 0; +} + +/** + * Delete all DB-backed sessions for a user (used when a user deletes their account). + */ +export async function revokeAllUserSessions( + app: Pick, + config: ResolvedAppConfig, + userId: unknown, +): Promise { + if ( + !config.authentication.enabled || + config.authentication.sessionStorage !== 'db' + ) { + return; + } + + await app.db.query( + `DELETE FROM "${SESSION_TABLE_NAME}" WHERE "user_id" = $1;`, + [String(userId)], + ); +} diff --git a/ross/src/lib/auth/token.ts b/ross/src/lib/auth/token.ts index 6f8341cd..87c4c135 100644 --- a/ross/src/lib/auth/token.ts +++ b/ross/src/lib/auth/token.ts @@ -72,7 +72,7 @@ export function issueAccessToken( } return signer.sign(payload, { - expiresIn: authentication.tokenExpiration, + expiresIn: authentication.accessTokenExpiration, }); } diff --git a/ross/src/lib/config/resolve.ts b/ross/src/lib/config/resolve.ts index f2be6bb2..bd5a1cef 100644 --- a/ross/src/lib/config/resolve.ts +++ b/ross/src/lib/config/resolve.ts @@ -96,7 +96,11 @@ export const DEFAULT_DEV_DATABASE = { /** Resolved shape used whenever no Redis cache is configured. */ export const DEFAULT_MEMORY_CACHE = {engine: 'memory'} as const; -export const DEFAULT_TOKEN_EXPIRATION = '1d'; +export const DEFAULT_ACCESS_TOKEN_EXPIRATION = '15m'; + +export const DEFAULT_REFRESH_TOKEN_EXPIRATION = '7d'; + +export const DEFAULT_SESSION_STORAGE = 'db' as const; /** Boolean template merged into every resolved model field. */ export const DEFAULT_MODEL_FIELD = { @@ -406,7 +410,11 @@ export function resolveAuthentication( return { enabled: true, ...(input.jwtSecret ? {jwtSecret: input.jwtSecret} : {}), - tokenExpiration: input.tokenExpiration ?? DEFAULT_TOKEN_EXPIRATION, + accessTokenExpiration: + input.accessTokenExpiration ?? DEFAULT_ACCESS_TOKEN_EXPIRATION, + refreshTokenExpiration: + input.refreshTokenExpiration ?? DEFAULT_REFRESH_TOKEN_EXPIRATION, + sessionStorage: input.sessionStorage ?? DEFAULT_SESSION_STORAGE, ...(userModel ? {userModel: {...userModel}} : {}), providers: providers .filter( diff --git a/ross/src/lib/config/route-registry.ts b/ross/src/lib/config/route-registry.ts index c74f09f7..8e43fd58 100644 --- a/ross/src/lib/config/route-registry.ts +++ b/ross/src/lib/config/route-registry.ts @@ -88,7 +88,14 @@ export function getGeneratedApiIdentifiers( const authModel = authentication.userModel?.modelName; if (authModel) { - const sharedOperations = ['providers', 'me', 'deleteMe', 'editMe']; + const sharedOperations = [ + 'providers', + 'me', + 'deleteMe', + 'editMe', + 'refresh', + 'logout', + ]; for (const operation of sharedOperations) { addTargets('auth', authModel, 'unknown', operation); diff --git a/ross/src/lib/config/tags.ts b/ross/src/lib/config/tags.ts index ea336b27..4294ea31 100644 --- a/ross/src/lib/config/tags.ts +++ b/ross/src/lib/config/tags.ts @@ -12,7 +12,13 @@ const MODEL_OPERATION_TAGS: Record = { }; function getAuthOperationTag(operation: string): string { - if (operation === 'login') return 'Login'; + if ( + operation === 'login' || + operation === 'refresh' || + operation === 'logout' + ) { + return 'Login'; + } if (operation === 'registration') return 'Register'; if (operation === 'changePassword' || operation === 'forgotPassword') { return 'Password'; diff --git a/ross/src/migrator/index.ts b/ross/src/migrator/index.ts index a423cb11..41022032 100644 --- a/ross/src/migrator/index.ts +++ b/ross/src/migrator/index.ts @@ -12,6 +12,8 @@ import { resolveDrizzleOrmDir, } from '@/migrator/drizzle-paths'; +import {getSessionModelConfig, SESSION_TABLE_NAME} from '@/lib/auth/session'; +import {getActiveUserModel} from '@/lib/auth/up-auth'; import {resolveModelField} from '@/lib/config/resolve'; import { @@ -425,6 +427,17 @@ const migrateDatabase = async (config: ResolvedAppConfig): Promise => { model, })); + if ( + config.authentication?.enabled && + config.authentication.sessionStorage === 'db' && + getActiveUserModel(config) + ) { + models.push({ + name: SESSION_TABLE_NAME, + model: getSessionModelConfig(), + }); + } + await generateMigrationSQL( models, engine, diff --git a/ross/src/routes/auth/delete-me.ts b/ross/src/routes/auth/delete-me.ts index fee2cb53..e04c3762 100644 --- a/ross/src/routes/auth/delete-me.ts +++ b/ross/src/routes/auth/delete-me.ts @@ -1,5 +1,6 @@ import {FastifyInstance, FastifyReply, FastifyRequest} from 'fastify'; +import {revokeAllUserSessions} from '@/lib/auth/session'; import {getActiveUserModel} from '@/lib/auth/up-auth'; import {getApiRouteTargets, ResolvedApiPolicy} from '@/lib/config/api'; import {getResponseStructureSchema} from '@/lib/schema/response'; @@ -100,6 +101,8 @@ function registerDeleteMeEndpoint( await tx.commit(); + await revokeAllUserSessions(app, config, userId); + return reply.status(200).send( app.buildResponse(200, 'User profile deleted successfully', { success: true, diff --git a/ross/src/routes/auth/login.ts b/ross/src/routes/auth/login.ts index 3e1bce58..f0a83743 100644 --- a/ross/src/routes/auth/login.ts +++ b/ross/src/routes/auth/login.ts @@ -1,6 +1,7 @@ import {FastifyInstance, FastifyReply, FastifyRequest} from 'fastify'; import {blockPasswordManagement} from '@/lib/auth/guards'; +import {createSession} from '@/lib/auth/session'; import {issueAccessToken} from '@/lib/auth/token'; import {getUpAuth, UpAuthRuntime} from '@/lib/auth/up-auth'; import {getApiRouteTargets, ResolvedApiPolicy} from '@/lib/config/api'; @@ -146,9 +147,16 @@ function registerLoginEndpoint( rbacUser, ); + const {refreshToken} = await createSession( + app, + config, + user[upAuth.idField], + ); + return reply.status(200).send( app.buildResponse(200, 'Login successful', { accessToken: token, + refreshToken, }), ); }, @@ -184,6 +192,7 @@ function generateSchema( } : { accessToken: {type: 'string', description: 'JWT access token'}, + refreshToken: {type: 'string', description: 'Refresh token'}, }, }; diff --git a/ross/src/routes/auth/logout.ts b/ross/src/routes/auth/logout.ts new file mode 100644 index 00000000..e88742bb --- /dev/null +++ b/ross/src/routes/auth/logout.ts @@ -0,0 +1,110 @@ +import {FastifyInstance, FastifyReply, FastifyRequest} from 'fastify'; + +import {revokeSession} from '@/lib/auth/session'; +import {getActiveUserModel} from '@/lib/auth/up-auth'; +import {getApiRouteTargets, ResolvedApiPolicy} from '@/lib/config/api'; +import {getResponseStructureSchema} from '@/lib/schema/response'; +import {buildPreValidation} from '@/lib/server/prevalidation'; + +import {ResolvedAppConfig} from '@/interfaces/config'; + +import {capitalizeFirstLetter} from '@/utils/string'; + +export function registerLogoutRoute( + app: FastifyInstance, + config: ResolvedAppConfig, +): void { + const userModel = getActiveUserModel(config); + + if (!userModel) { + return; + } + + const {modelName: model} = userModel; + + if (!config.data.models[model]) { + return; + } + + const targets = getApiRouteTargets( + config, + 'auth', + model, + 'unknown', + 'logout', + ); + + for (const {identifier, variant, policy} of targets) { + registerLogoutEndpoint(app, config, model, variant, identifier, policy); + } +} + +function registerLogoutEndpoint( + app: FastifyInstance, + config: ResolvedAppConfig, + model: string, + variant: string, + apiIdentifier: string, + policy: ResolvedApiPolicy, +): void { + const schema = generateSchema(model, policy); + const path = `/${variant}/auth/logout`; + + app.post( + path, + { + schema, + config: {apiIdentifier}, + preValidation: buildPreValidation(app, config, true), + }, + async (request: FastifyRequest, reply: FastifyReply) => { + const userId = (request.user as Record | undefined)?.id; + + if (!userId) { + return reply + .status(401) + .send( + app.buildResponse(401, 'User ID missing in token payload', null), + ); + } + + const {refreshToken} = request.body as {refreshToken: string}; + + await revokeSession(app, config, refreshToken, userId); + + return reply.status(200).send( + app.buildResponse(200, 'Logged out successfully', { + success: true, + }), + ); + }, + ); +} + +function generateSchema(model: string, policy: ResolvedApiPolicy) { + return { + summary: `Logout for ${capitalizeFirstLetter(model)}`, + description: + 'Revokes the provided refresh token session for the authenticated user.', + tags: policy.tags, + body: { + type: 'object', + required: ['refreshToken'], + properties: { + refreshToken: { + type: 'string', + minLength: 1, + description: 'Refresh token to revoke', + }, + }, + additionalProperties: false, + }, + response: getResponseStructureSchema([200], { + type: 'object', + properties: { + success: {type: 'boolean'}, + }, + }), + security: [{bearerAuth: []}], + }; +} diff --git a/ross/src/routes/auth/otp-verify.ts b/ross/src/routes/auth/otp-verify.ts index 8e239153..e7f3b7e7 100644 --- a/ross/src/routes/auth/otp-verify.ts +++ b/ross/src/routes/auth/otp-verify.ts @@ -1,5 +1,6 @@ import {FastifyInstance, FastifyReply, FastifyRequest} from 'fastify'; +import {createSession} from '@/lib/auth/session'; import {issueAccessToken} from '@/lib/auth/token'; import {getUpAuth, UpAuthRuntime} from '@/lib/auth/up-auth'; import {getApiRouteTargets, ResolvedApiPolicy} from '@/lib/config/api'; @@ -202,9 +203,16 @@ function registerOtpVerifyEndpoint( await tx.commit(); + const {refreshToken} = await createSession( + app, + config, + user[upAuth.idField], + ); + return reply.status(200).send( app.buildResponse(200, 'OTP verification successful', { accessToken: token, + refreshToken, }), ); } catch (err) { @@ -269,6 +277,7 @@ function generateSchema( type: 'object', properties: { accessToken: {type: 'string', description: 'JWT access token'}, + refreshToken: {type: 'string', description: 'Refresh token'}, }, } : action === 'forgotPassword' diff --git a/ross/src/routes/auth/refresh.ts b/ross/src/routes/auth/refresh.ts new file mode 100644 index 00000000..ceedc956 --- /dev/null +++ b/ross/src/routes/auth/refresh.ts @@ -0,0 +1,198 @@ +import {FastifyInstance, FastifyReply, FastifyRequest} from 'fastify'; + +import {revokeSession, rotateSession} from '@/lib/auth/session'; +import {issueAccessToken} from '@/lib/auth/token'; +import { + getActiveUserModel, + getSsoProviders, + getUpAuth, +} from '@/lib/auth/up-auth'; +import {getApiRouteTargets, ResolvedApiPolicy} from '@/lib/config/api'; +import {getResponseStructureSchema} from '@/lib/schema/response'; + +import {ResolvedAppConfig} from '@/interfaces/config'; + +import {capitalizeFirstLetter} from '@/utils/string'; + +export function registerRefreshRoute( + app: FastifyInstance, + config: ResolvedAppConfig, +): void { + const userModel = getActiveUserModel(config); + + if (!userModel) { + return; + } + + const {modelName: model, idField, providerField} = userModel; + + if (!config.data.models[model]) { + return; + } + + const targets = getApiRouteTargets( + config, + 'auth', + model, + 'unknown', + 'refresh', + ); + + for (const {identifier, variant, policy} of targets) { + registerRefreshEndpoint( + app, + config, + model, + idField, + providerField, + variant, + identifier, + policy, + ); + } +} + +function resolveTokenFields( + config: ResolvedAppConfig, + user: Record, + providerField: string, +): {usernameField?: string; providerIdField?: string} { + const providerValue = user[providerField]; + const ssoProvider = getSsoProviders(config).find( + provider => provider.name === providerValue, + ); + + if (ssoProvider) { + return { + usernameField: ssoProvider.config.fields.usernameField, + providerIdField: ssoProvider.config.fields.providerIdField, + }; + } + + const upAuth = getUpAuth(config); + if (upAuth) { + return {usernameField: upAuth.usernameField}; + } + + return {}; +} + +function registerRefreshEndpoint( + app: FastifyInstance, + config: ResolvedAppConfig, + model: string, + idField: string, + providerField: string, + variant: string, + apiIdentifier: string, + policy: ResolvedApiPolicy, +): void { + const schema = generateSchema(model, policy); + const path = `/${variant}/auth/refresh`; + + app.post( + path, + { + schema, + config: {apiIdentifier}, + }, + async ( + request: FastifyRequest<{Body: {refreshToken?: string}}>, + reply: FastifyReply, + ) => { + const refreshToken = request.body?.refreshToken; + + if (!refreshToken || typeof refreshToken !== 'string') { + return reply + .status(401) + .send( + app.buildResponse(401, 'Invalid or expired refresh token', null), + ); + } + + const rotated = await rotateSession(app, config, refreshToken); + + if (!rotated) { + return reply + .status(401) + .send( + app.buildResponse(401, 'Invalid or expired refresh token', null), + ); + } + + const res = await app.db.query>( + `SELECT * FROM "${model}" WHERE "${idField}" = $1 LIMIT 1;`, + [rotated.userId], + ); + + const user = res.rows[0]; + + if (!user) { + await revokeSession(app, config, rotated.refreshToken); + return reply + .status(401) + .send( + app.buildResponse(401, 'Invalid or expired refresh token', null), + ); + } + + let rbacUser = user; + if ( + config.rbac?.enabled && + config.rbac.modelName && + config.rbac.modelName !== model + ) { + const rbacRes = await app.db.query>( + `SELECT * FROM "${config.rbac.modelName}" WHERE "${idField}" = $1 LIMIT 1;`, + [user[idField]], + ); + rbacUser = rbacRes.rows[0] ?? user; + } + + const {usernameField, providerIdField} = resolveTokenFields( + config, + user, + providerField, + ); + + const accessToken = issueAccessToken( + app.jwt, + config, + user, + usernameField, + rbacUser, + providerIdField, + ); + + return reply.status(200).send( + app.buildResponse(200, 'Token refreshed successfully', { + accessToken, + refreshToken: rotated.refreshToken, + }), + ); + }, + ); +} + +function generateSchema(model: string, policy: ResolvedApiPolicy) { + return { + summary: `Refresh token for ${capitalizeFirstLetter(model)}`, + description: + 'Validates a refresh token and returns a new access token and rotated refresh token.', + tags: policy.tags, + body: { + type: 'object', + properties: { + refreshToken: {type: 'string', description: 'Refresh token'}, + }, + additionalProperties: false, + }, + response: getResponseStructureSchema([200], { + type: 'object', + properties: { + accessToken: {type: 'string', description: 'JWT access token'}, + refreshToken: {type: 'string', description: 'Rotated refresh token'}, + }, + }), + }; +} diff --git a/ross/src/routes/auth/sso.ts b/ross/src/routes/auth/sso.ts index 3db68769..27d56307 100644 --- a/ross/src/routes/auth/sso.ts +++ b/ross/src/routes/auth/sso.ts @@ -9,6 +9,7 @@ import { } from '@/lib/auth/cookie'; import {getAdapter} from '@/lib/auth/providers'; import {buildRedirectUrl} from '@/lib/auth/redirect'; +import {createSession} from '@/lib/auth/session'; import { openState, randomToken, @@ -377,11 +378,18 @@ async function completeLogin( provider.config.fields.providerIdField, ); - return reply - .status(200) - .send( - app.buildResponse(200, 'SSO authentication successful', {accessToken}), - ); + const {refreshToken} = await createSession( + app, + config, + user[authentication.userModel.idField], + ); + + return reply.status(200).send( + app.buildResponse(200, 'SSO authentication successful', { + accessToken, + refreshToken, + }), + ); } catch (err) { if ((err as {code?: string}).code === 'ACCOUNT_COLLISION') { return fail( @@ -445,11 +453,14 @@ async function exchange( provider.config.fields.providerIdField, ); - return reply - .status(200) - .send( - app.buildResponse(200, 'SSO authentication successful', {accessToken}), - ); + const {refreshToken} = await createSession(app, config, user[idField]); + + return reply.status(200).send( + app.buildResponse(200, 'SSO authentication successful', { + accessToken, + refreshToken, + }), + ); } function failure( @@ -513,6 +524,7 @@ function buildTokenSchema(policy: ResolvedApiPolicy) { type: 'object', properties: { accessToken: {type: 'string', description: 'JWT access token'}, + refreshToken: {type: 'string', description: 'Refresh token'}, }, }), }; diff --git a/ross/src/server.ts b/ross/src/server.ts index d2612178..f4c14317 100644 --- a/ross/src/server.ts +++ b/ross/src/server.ts @@ -27,6 +27,7 @@ import {registerDeleteMeRoute} from '@/routes/auth/delete-me'; import {registerEditMeRoute} from '@/routes/auth/edit-me'; import {registerForgotPasswordRoute} from '@/routes/auth/forgot-password'; import {registerLoginRoute} from '@/routes/auth/login'; +import {registerLogoutRoute} from '@/routes/auth/logout'; import {registerMeRoute} from '@/routes/auth/me'; import { registerForgotPasswordOtpVerifyRoute, @@ -34,6 +35,7 @@ import { registerRegistrationOtpVerifyRoute, } from '@/routes/auth/otp-verify'; import {registerProvidersRoute} from '@/routes/auth/providers'; +import {registerRefreshRoute} from '@/routes/auth/refresh'; import {registerRegistrationRoute} from '@/routes/auth/registration'; import { registerForgotPasswordResendOtpRoute, @@ -45,7 +47,7 @@ import {registerHealthRoute} from '@/routes/health'; import {ResolvedAppConfig} from '@/interfaces/config'; -import {NODE_CACHE_OTP_WARNING} from '@/constants'; +import {NODE_CACHE_OTP_WARNING, NODE_CACHE_SESSION_WARNING} from '@/constants'; export interface StartServerResult { app: FastifyInstance; @@ -77,6 +79,11 @@ export async function startServer( const usesAccountOtp = Boolean( upAuth && (upAuth.mfaRequired || upAuth.isVerifiedField), ); + const usesCacheSessionStorage = Boolean( + resolvedConfig.authentication.enabled && + resolvedConfig.authentication.userModel && + resolvedConfig.authentication.sessionStorage === 'cache', + ); if (usesAccountOtp && !isDistributedCacheConfigured(resolvedConfig)) { app.addHook('onListen', () => { @@ -84,6 +91,15 @@ export async function startServer( }); } + if ( + usesCacheSessionStorage && + !isDistributedCacheConfigured(resolvedConfig) + ) { + app.addHook('onListen', () => { + app.log.warn(NODE_CACHE_SESSION_WARNING); + }); + } + // Must be installed before routes are registered, otherwise Fastify keeps // the default error handler for those routes. registerErrorHandler(app); @@ -161,6 +177,8 @@ export async function startServer( registerMeRoute(app, resolvedConfig); registerDeleteMeRoute(app, resolvedConfig); registerEditMeRoute(app, resolvedConfig); + registerRefreshRoute(app, resolvedConfig); + registerLogoutRoute(app, resolvedConfig); } if (resolvedConfig.authentication.enabled && ssoProviders.length > 0) { diff --git a/ross/src/utils/hash.ts b/ross/src/utils/hash.ts index e52e7a9c..318a2bd3 100644 --- a/ross/src/utils/hash.ts +++ b/ross/src/utils/hash.ts @@ -1,3 +1,5 @@ +import crypto from 'crypto'; + import bcrypt from 'bcrypt'; import {BCRYPT_SALT_ROUNDS} from '@/constants'; @@ -27,3 +29,10 @@ export async function compare( ): Promise { return bcrypt.compare(data, encrypted); } + +/** + * Computes a deterministic SHA-256 hex digest (used for high-entropy tokens). + */ +export function sha256(data: string): string { + return crypto.createHash('sha256').update(data).digest('hex'); +} diff --git a/ross/src/validators/config/schema.ts b/ross/src/validators/config/schema.ts index 0f3a155b..ad31bdcd 100644 --- a/ross/src/validators/config/schema.ts +++ b/ross/src/validators/config/schema.ts @@ -901,10 +901,18 @@ const authenticationSchema = { type: 'string', minLength: 32, }, - tokenExpiration: { + accessTokenExpiration: { type: 'string', pattern: '^\\d+[smhd]$', }, + refreshTokenExpiration: { + type: 'string', + pattern: '^\\d+[smhd]$', + }, + sessionStorage: { + type: 'string', + enum: ['cache', 'db'], + }, userModel: authUserModelSchema, providers: { type: 'array', diff --git a/ross/src/validators/config/validate-auth.ts b/ross/src/validators/config/validate-auth.ts index 6d39b11e..1258dac0 100644 --- a/ross/src/validators/config/validate-auth.ts +++ b/ross/src/validators/config/validate-auth.ts @@ -22,9 +22,11 @@ const RESERVED_PROVIDER_NAMES = new Set([ 'edit-me', 'forgot-password', 'login', + 'logout', 'me', 'metadata', 'providers', + 'refresh', 'register', 'registration', 'resend-otp', @@ -206,6 +208,12 @@ function validateAuthConstraints(config: AppConfig): string[] { return errors; } + if (config.data.models['_ross_sessions']) { + errors.push( + '/data/models/_ross_sessions: model name is reserved for internal session storage', + ); + } + assertField( errors, targetModel, diff --git a/ross/tests/fixtures/config/__goldens__/full.resolved.json b/ross/tests/fixtures/config/__goldens__/full.resolved.json index d44ad761..89fb537a 100644 --- a/ross/tests/fixtures/config/__goldens__/full.resolved.json +++ b/ross/tests/fixtures/config/__goldens__/full.resolved.json @@ -586,7 +586,9 @@ "authentication": { "enabled": true, "jwtSecret": "your-super-secret-key-must-be-long-enough", - "tokenExpiration": "1d", + "accessTokenExpiration": "15m", + "refreshTokenExpiration": "7d", + "sessionStorage": "db", "userModel": { "modelName": "users", "idField": "id", diff --git a/ross/tests/lib/auth/guards.test.ts b/ross/tests/lib/auth/guards.test.ts index a53775e5..77b13401 100644 --- a/ross/tests/lib/auth/guards.test.ts +++ b/ross/tests/lib/auth/guards.test.ts @@ -46,7 +46,9 @@ describe('isPasswordAccount', () => { { authentication: { enabled: true, - tokenExpiration: '1d', + accessTokenExpiration: '15m', + refreshTokenExpiration: '7d', + sessionStorage: 'db', providers: [{type: 'api-key', config: {key: 'k'}}], }, } as never, diff --git a/ross/tests/lib/auth/session.test.ts b/ross/tests/lib/auth/session.test.ts new file mode 100644 index 00000000..96d01cdd --- /dev/null +++ b/ross/tests/lib/auth/session.test.ts @@ -0,0 +1,343 @@ +import {describe, expect, test, vi} from 'vitest'; + +import { + createSession, + getSessionModelConfig, + revokeAllUserSessions, + revokeSession, + rotateSession, + SESSION_TABLE_NAME, +} from '@/lib/auth/session'; + +import {sha256} from '@/utils/hash'; + +import { + buildEnabledAuth, + upAuthAuthentication, +} from '@tests/helpers/auth-config'; + +function createMockCache() { + const store = new Map(); + return { + store, + get: vi.fn(async (key: string) => store.get(key)?.value ?? null), + set: vi.fn(async (key: string, value: unknown, ttl?: number) => { + store.set(key, {value, ttl}); + }), + delete: vi.fn(async (key: string) => { + store.delete(key); + }), + has: vi.fn(async (key: string) => store.has(key)), + clear: vi.fn(async () => store.clear()), + ping: vi.fn(async () => {}), + close: vi.fn(async () => {}), + raw: null, + }; +} + +function createMockDb() { + const rows = new Map< + string, + { + id: string; + user_id: string; + token_hash: string; + expires_at: string; + created_at: string; + } + >(); + + const query = vi.fn(async (sql: string, params: unknown[] = []) => { + if (sql.startsWith('INSERT INTO "_ross_sessions"')) { + const [id, user_id, token_hash, expires_at, created_at] = + params as string[]; + rows.set(token_hash, {id, user_id, token_hash, expires_at, created_at}); + return {changes: 1, rows: []}; + } + + if (sql.startsWith('SELECT "id", "user_id", "expires_at"')) { + const [token_hash] = params as string[]; + const row = rows.get(token_hash); + return {changes: 0, rows: row ? [row] : []}; + } + + if ( + sql.startsWith( + 'DELETE FROM "_ross_sessions" WHERE "token_hash" = $1 AND "user_id" = $2', + ) + ) { + const [token_hash, user_id] = params as string[]; + const row = rows.get(token_hash); + if (row && row.user_id === user_id) { + rows.delete(token_hash); + return {changes: 1, rows: []}; + } + return {changes: 0, rows: []}; + } + + if ( + sql.startsWith('DELETE FROM "_ross_sessions" WHERE "token_hash" = $1') + ) { + const [token_hash] = params as string[]; + const existed = rows.delete(token_hash); + return {changes: existed ? 1 : 0, rows: []}; + } + + if (sql.startsWith('DELETE FROM "_ross_sessions" WHERE "user_id" = $1')) { + const [user_id] = params as string[]; + let count = 0; + for (const [k, v] of rows.entries()) { + if (v.user_id === user_id) { + rows.delete(k); + count++; + } + } + return {changes: count, rows: []}; + } + + return {changes: 0, rows: []}; + }); + + return { + rows, + query, + beginTransaction: vi.fn(async () => ({ + query, + commit: vi.fn(async () => {}), + rollback: vi.fn(async () => {}), + release: vi.fn(), + })), + close: vi.fn(async () => {}), + }; +} + +describe('session management', () => { + test('getSessionModelConfig defines _ross_sessions schema', () => { + const model = getSessionModelConfig(); + expect(SESSION_TABLE_NAME).toBe('_ross_sessions'); + expect(model.fields.id.primaryKey).toBe(true); + expect(model.fields.token_hash.unique).toBe(true); + expect(model.fields.user_id.nullable).toBe(false); + expect(model.indexes.idx_ross_sessions_user_id.fields).toEqual(['user_id']); + }); + + test('db backend: create, rotate, and revoke sessions', async () => { + const db = createMockDb(); + const cache = createMockCache(); + const config = buildEnabledAuth([upAuthAuthentication.providers[0]]); + + const issued = await createSession({db, cache} as never, config, 42); + expect(issued.refreshToken).toBeTruthy(); + expect(db.rows.size).toBe(1); + expect(db.rows.has(sha256(issued.refreshToken))).toBe(true); + + const rotated = await rotateSession( + {db, cache} as never, + config, + issued.refreshToken, + ); + expect(rotated).not.toBeNull(); + expect(rotated?.userId).toBe('42'); + expect(rotated?.refreshToken).not.toBe(issued.refreshToken); + + // Old token cannot be reused + const replay = await rotateSession( + {db, cache} as never, + config, + issued.refreshToken, + ); + expect(replay).toBeNull(); + + // Wrong user cannot revoke + await expect( + revokeSession({db, cache} as never, config, rotated!.refreshToken, 99), + ).resolves.toBe(false); + + // Owner can revoke + await expect( + revokeSession({db, cache} as never, config, rotated!.refreshToken, 42), + ).resolves.toBe(true); + expect(db.rows.size).toBe(0); + }); + + test('db backend: rejects expired session and cleans it up', async () => { + const db = createMockDb(); + const cache = createMockCache(); + const config = buildEnabledAuth([upAuthAuthentication.providers[0]]); + + const issued = await createSession({db, cache} as never, config, 7); + const entry = db.rows.get(sha256(issued.refreshToken))!; + entry.expires_at = new Date(Date.now() - 1000).toISOString(); + + const rotated = await rotateSession( + {db, cache} as never, + config, + issued.refreshToken, + ); + expect(rotated).toBeNull(); + expect(db.rows.size).toBe(0); + }); + + test('db backend: revokeAllUserSessions removes all sessions for user', async () => { + const db = createMockDb(); + const cache = createMockCache(); + const config = buildEnabledAuth([upAuthAuthentication.providers[0]]); + + await createSession({db, cache} as never, config, 1); + await createSession({db, cache} as never, config, 1); + await createSession({db, cache} as never, config, 2); + expect(db.rows.size).toBe(3); + + await revokeAllUserSessions({db} as never, config, 1); + expect(db.rows.size).toBe(1); + }); + + test('cache backend: create, rotate, and revoke sessions with TTL', async () => { + const db = createMockDb(); + const cache = createMockCache(); + const config = buildEnabledAuth([upAuthAuthentication.providers[0]]); + if (config.authentication.enabled) { + config.authentication.sessionStorage = 'cache'; + config.authentication.refreshTokenExpiration = '2h'; + } + + const issued = await createSession({db, cache} as never, config, 42); + expect(cache.set).toHaveBeenCalledWith( + expect.stringContaining('session:refresh:'), + expect.objectContaining({userId: '42'}), + 7200, + ); + + const rotated = await rotateSession( + {db, cache} as never, + config, + issued.refreshToken, + ); + expect(rotated?.userId).toBe('42'); + expect(rotated?.refreshToken).not.toBe(issued.refreshToken); + + // Old token rejected + await expect( + rotateSession({db, cache} as never, config, issued.refreshToken), + ).resolves.toBeNull(); + + // Wrong user cannot revoke + await expect( + revokeSession({db, cache} as never, config, rotated!.refreshToken, 99), + ).resolves.toBe(false); + + // Owner can revoke + await expect( + revokeSession({db, cache} as never, config, rotated!.refreshToken, 42), + ).resolves.toBe(true); + expect(cache.store.size).toBe(0); + }); + + test('returns null for missing or empty refresh token', async () => { + const db = createMockDb(); + const cache = createMockCache(); + const config = buildEnabledAuth([upAuthAuthentication.providers[0]]); + + await expect( + rotateSession({db, cache} as never, config, ''), + ).resolves.toBeNull(); + await expect(revokeSession({db, cache} as never, config, '')).resolves.toBe( + false, + ); + }); + + test('throws when authentication is disabled', async () => { + const db = createMockDb(); + const cache = createMockCache(); + const disabled = buildEnabledAuth([]); + + await expect( + createSession({db, cache} as never, disabled, 1), + ).rejects.toThrow('Authentication is not enabled'); + }); + + test('cache backend: rejects expired session and cleans it up', async () => { + const db = createMockDb(); + const cache = createMockCache(); + const config = buildEnabledAuth([upAuthAuthentication.providers[0]]); + if (config.authentication.enabled) { + config.authentication.sessionStorage = 'cache'; + } + + const issued = await createSession({db, cache} as never, config, 7); + const key = `session:refresh:${sha256(issued.refreshToken)}`; + const entry = cache.store.get(key)!.value as { + sessionId: string; + userId: string; + expiresAt: string; + }; + entry.expiresAt = new Date(Date.now() - 1000).toISOString(); + + await expect( + rotateSession({db, cache} as never, config, issued.refreshToken), + ).resolves.toBeNull(); + expect(cache.store.size).toBe(0); + }); + + test('revokeSession without userId deletes in both db and cache', async () => { + const db = createMockDb(); + const cache = createMockCache(); + const dbConfig = buildEnabledAuth([upAuthAuthentication.providers[0]]); + const issuedDb = await createSession({db, cache} as never, dbConfig, 1); + await expect( + revokeSession({db, cache} as never, dbConfig, issuedDb.refreshToken), + ).resolves.toBe(true); + expect(db.rows.size).toBe(0); + + const cacheConfig = buildEnabledAuth([upAuthAuthentication.providers[0]]); + if (cacheConfig.authentication.enabled) { + cacheConfig.authentication.sessionStorage = 'cache'; + } + const issuedCache = await createSession( + {db, cache} as never, + cacheConfig, + 1, + ); + await expect( + revokeSession( + {db, cache} as never, + cacheConfig, + issuedCache.refreshToken, + ), + ).resolves.toBe(true); + expect(cache.store.size).toBe(0); + }); + + test('revokeAllUserSessions is a no-op when sessionStorage is cache', async () => { + const db = createMockDb(); + const config = buildEnabledAuth([upAuthAuthentication.providers[0]]); + if (config.authentication.enabled) { + config.authentication.sessionStorage = 'cache'; + } + + await revokeAllUserSessions({db} as never, config, 1); + expect(db.query).not.toHaveBeenCalled(); + }); + + test('db backend: rolls back transaction when query throws during rotation', async () => { + const rollback = vi.fn().mockRejectedValueOnce(new Error('rollback err')); + const release = vi.fn(); + const db = { + query: vi.fn(), + beginTransaction: vi.fn(async () => ({ + query: vi.fn().mockRejectedValueOnce(new Error('DB failure')), + commit: vi.fn(async () => {}), + rollback, + release, + })), + }; + const cache = createMockCache(); + const config = buildEnabledAuth([upAuthAuthentication.providers[0]]); + + await expect( + rotateSession({db, cache} as never, config, 'some-token'), + ).rejects.toThrow('DB failure'); + expect(rollback).toHaveBeenCalledTimes(1); + expect(release).toHaveBeenCalledTimes(1); + }); +}); diff --git a/ross/tests/lib/auth/token.test.ts b/ross/tests/lib/auth/token.test.ts index c7d813e0..275e72e9 100644 --- a/ross/tests/lib/auth/token.test.ts +++ b/ross/tests/lib/auth/token.test.ts @@ -31,7 +31,7 @@ describe('issueAccessToken', () => { expect(token).toBe('signed-token'); expect(signer.sign).toHaveBeenCalledWith( {id: 7, email: 'user@example.com', providerId: null}, - {expiresIn: '1d'}, + {expiresIn: '15m'}, ); }); @@ -43,7 +43,7 @@ describe('issueAccessToken', () => { expect(signer.sign).toHaveBeenCalledWith( {id: 7, email: null, providerId: null}, - {expiresIn: '1d'}, + {expiresIn: '15m'}, ); }); @@ -59,7 +59,7 @@ describe('issueAccessToken', () => { expect(signer.sign).toHaveBeenCalledWith( {id: 7, email: null, providerId: null, role: 'admin'}, - {expiresIn: '1d'}, + {expiresIn: '15m'}, ); }); @@ -78,7 +78,7 @@ describe('issueAccessToken', () => { expect(signer.sign).toHaveBeenCalledWith( {id: 7, email: 'sso@example.com', providerId: 'sub-123'}, - {expiresIn: '1d'}, + {expiresIn: '15m'}, ); }); @@ -95,7 +95,7 @@ describe('issueAccessToken', () => { expect(signer.sign).toHaveBeenCalledWith( {id: 7, username: 'alice', email: 'alice', providerId: null}, - {expiresIn: '1d'}, + {expiresIn: '15m'}, ); }); @@ -110,7 +110,7 @@ describe('issueAccessToken', () => { expect(signer.sign).toHaveBeenCalledWith( {id: 7, email: 'fallback@example.com', providerId: null}, - {expiresIn: '1d'}, + {expiresIn: '15m'}, ); }); diff --git a/ross/tests/lib/auth/up-auth.test.ts b/ross/tests/lib/auth/up-auth.test.ts index bfd9709a..da060356 100644 --- a/ross/tests/lib/auth/up-auth.test.ts +++ b/ross/tests/lib/auth/up-auth.test.ts @@ -59,7 +59,9 @@ describe('getUpAuth', () => { getUpAuth({ authentication: { enabled: true, - tokenExpiration: '1d', + accessTokenExpiration: '15m', + refreshTokenExpiration: '7d', + sessionStorage: 'db', providers: [ { type: 'up-auth', diff --git a/ross/tests/lib/config/api.test.ts b/ross/tests/lib/config/api.test.ts index b6b74e2d..01c91a0f 100644 --- a/ross/tests/lib/config/api.test.ts +++ b/ross/tests/lib/config/api.test.ts @@ -556,7 +556,9 @@ test('getAuthModel tolerates a config without a userModel', () => { apis: {}, authentication: { enabled: true, - tokenExpiration: '1d', + accessTokenExpiration: '15m', + refreshTokenExpiration: '7d', + sessionStorage: 'db', providers: [ { type: 'sso', diff --git a/ross/tests/lib/config/resolve.test.ts b/ross/tests/lib/config/resolve.test.ts index 9f5b36fc..371f57bd 100644 --- a/ross/tests/lib/config/resolve.test.ts +++ b/ross/tests/lib/config/resolve.test.ts @@ -849,7 +849,7 @@ test('explicitly disabled authentication never materialises a provider', () => { expect('provider' in config.authentication).toBe(false); }); -test('up-auth is normalized with tokenExpiration and mfaRequired', () => { +test('up-auth is normalized with accessTokenExpiration, refreshTokenExpiration, sessionStorage, and mfaRequired', () => { const config = resolveConfig( devInput({ authentication: upAuth as unknown as AppConfigInput['authentication'], @@ -862,7 +862,9 @@ test('up-auth is normalized with tokenExpiration and mfaRequired', () => { if (!auth.enabled) throw new Error('authentication should be enabled'); expect(auth.jwtSecret).toBe('a-very-long-secret-used-for-testing-purposes'); - expect(auth.tokenExpiration).toBe('1d'); + expect(auth.accessTokenExpiration).toBe('15m'); + expect(auth.refreshTokenExpiration).toBe('7d'); + expect(auth.sessionStorage).toBe('db'); expect(auth.userModel).toEqual(upAuth.userModel); const provider = auth.providers[0]; @@ -874,13 +876,15 @@ test('up-auth is normalized with tokenExpiration and mfaRequired', () => { expect(getProviderCapabilities(provider)).toContain('register'); }); -test('up-auth explicit tokenExpiration and mfaRequired are preserved', () => { +test('up-auth explicit accessTokenExpiration, refreshTokenExpiration, sessionStorage, and mfaRequired are preserved', () => { const config = resolveConfig( devInput({ authentication: { enabled: true, jwtSecret: 'a-very-long-secret-used-for-testing-purposes', - tokenExpiration: '8h', + accessTokenExpiration: '8h', + refreshTokenExpiration: '30d', + sessionStorage: 'cache', userModel: { modelName: 'users', idField: 'id', @@ -906,7 +910,9 @@ test('up-auth explicit tokenExpiration and mfaRequired are preserved', () => { const auth = config.authentication; if (!auth.enabled) throw new Error('authentication should be enabled'); - expect(auth.tokenExpiration).toBe('8h'); + expect(auth.accessTokenExpiration).toBe('8h'); + expect(auth.refreshTokenExpiration).toBe('30d'); + expect(auth.sessionStorage).toBe('cache'); const provider = auth.providers[0]; if (provider.type !== 'up-auth') throw new Error('expected up-auth'); diff --git a/ross/tests/lib/server/prevalidation.test.ts b/ross/tests/lib/server/prevalidation.test.ts index 0f32662e..c09b602e 100644 --- a/ross/tests/lib/server/prevalidation.test.ts +++ b/ross/tests/lib/server/prevalidation.test.ts @@ -185,7 +185,9 @@ describe('buildPreValidation', () => { ...baseAppConfig, authentication: { enabled: true, - tokenExpiration: '1d', + accessTokenExpiration: '15m', + refreshTokenExpiration: '7d', + sessionStorage: 'db', providers: [ { type: 'api-key', diff --git a/ross/tests/migrator/index.test.ts b/ross/tests/migrator/index.test.ts index d4a4b8be..12ab2676 100644 --- a/ross/tests/migrator/index.test.ts +++ b/ross/tests/migrator/index.test.ts @@ -1051,7 +1051,7 @@ describe('migrateDatabase', () => { return {applied: ['01_init.sql'], skipped: []}; }); - await runMigrate(config); + await runMigrate(config as unknown as MigratorTestConfig); expect(callOrder).toEqual([ 'drizzle-push', @@ -1092,7 +1092,7 @@ describe('migrateDatabase', () => { ]; vi.mocked(discoverMigrations).mockReturnValue(mockDiscovered); - await runMigrate(config); + await runMigrate(config as unknown as MigratorTestConfig); expect(discoverMigrations).toHaveBeenCalledWith({ migrationsDir: '/app/custom-migrations', @@ -1112,7 +1112,7 @@ describe('migrateDatabase', () => { const config = getBaseConfig('postgres'); config.infrastructure.database.migrations = undefined; - await runMigrate(config); + await runMigrate(config as unknown as MigratorTestConfig); expect(discoverMigrations).not.toHaveBeenCalled(); expect(validateMigrations).not.toHaveBeenCalled(); @@ -1125,7 +1125,7 @@ describe('migrateDatabase', () => { dangerouslyAllowDDL: false, } as unknown as {directory: string; dangerouslyAllowDDL: boolean}; - await runMigrate(config); + await runMigrate(config as unknown as MigratorTestConfig); expect(discoverMigrations).not.toHaveBeenCalled(); expect(validateMigrations).not.toHaveBeenCalled(); @@ -1139,7 +1139,7 @@ describe('migrateDatabase', () => { dangerouslyAllowDDL: false, }; - await runMigrate(config); + await runMigrate(config as unknown as MigratorTestConfig); expect(discoverMigrations).not.toHaveBeenCalled(); expect(validateMigrations).not.toHaveBeenCalled(); @@ -1165,7 +1165,7 @@ describe('migrateDatabase', () => { ]; vi.mocked(discoverMigrations).mockReturnValue(mockDiscovered); - await runMigrate(config); + await runMigrate(config as unknown as MigratorTestConfig); expect(discoverMigrations).toHaveBeenCalledWith({ migrationsDir: '/app/sqlite-migrations', @@ -1227,4 +1227,61 @@ describe('migrateDatabase', () => { ); }); }); + + describe('internal session table migration', () => { + it('includes _ross_sessions when authentication is enabled with db sessionStorage', async () => { + const config = { + infrastructure: { + database: { + engine: 'sqlite', + connection: {url: './test.db'}, + timeout: 10000, + }, + }, + data: { + models: { + users: { + fields: { + id: {type: 'integer', primaryKey: true}, + email: {type: 'string', unique: true, nullable: false}, + password: {type: 'string', nullable: false}, + provider: {type: 'string'}, + }, + }, + }, + }, + authentication: { + enabled: true, + jwtSecret: 'a-very-long-secret-used-for-testing-purposes', + accessTokenExpiration: '15m', + refreshTokenExpiration: '7d', + sessionStorage: 'db' as const, + userModel: { + modelName: 'users', + idField: 'id', + providerField: 'provider', + }, + providers: [ + { + type: 'up-auth' as const, + config: { + fields: { + usernameField: 'email', + passwordField: 'password', + }, + mfaRequired: false, + }, + }, + ], + }, + }; + + await runMigrate(config as unknown as MigratorTestConfig); + + expect(fs.writeFileSync).toHaveBeenCalledWith( + expect.stringContaining('schema.ts'), + expect.stringContaining('_ross_sessions'), + ); + }); + }); }); diff --git a/ross/tests/plugin/auth.test.ts b/ross/tests/plugin/auth.test.ts index 56d97c03..06654861 100644 --- a/ross/tests/plugin/auth.test.ts +++ b/ross/tests/plugin/auth.test.ts @@ -28,7 +28,9 @@ const upAuthFixture = (): ResolvedAppConfig => authentication: { enabled: true, jwtSecret: 'this-will-never-be-used', - tokenExpiration: '1d', + accessTokenExpiration: '15m', + refreshTokenExpiration: '7d', + sessionStorage: 'db', userModel: { modelName: 'users', idField: 'id', @@ -94,7 +96,9 @@ describe('Auth Plugin — up-auth engine', () => { authentication: { enabled: true, jwtSecret: 'this-is-a-long-enough-secret-key-for-testing', - tokenExpiration: '1d', + accessTokenExpiration: '15m', + refreshTokenExpiration: '7d', + sessionStorage: 'db', userModel: { modelName: 'users', idField: 'id', @@ -190,7 +194,9 @@ describe('Auth Plugin — api-key engine', () => { data: {models: {}}, authentication: { enabled: true, - tokenExpiration: '1d', + accessTokenExpiration: '15m', + refreshTokenExpiration: '7d', + sessionStorage: 'db', providers: [ { type: 'api-key', @@ -234,7 +240,9 @@ describe('Auth Plugin — api-key engine', () => { data: {models: {}}, authentication: { enabled: true, - tokenExpiration: '1d', + accessTokenExpiration: '15m', + refreshTokenExpiration: '7d', + sessionStorage: 'db', providers: [ { type: 'api-key', @@ -282,7 +290,9 @@ describe('Auth Plugin — api-key engine', () => { data: {models: {}}, authentication: { enabled: true, - tokenExpiration: '1d', + accessTokenExpiration: '15m', + refreshTokenExpiration: '7d', + sessionStorage: 'db', providers: [ { type: 'api-key', diff --git a/ross/tests/routes/login.test.ts b/ross/tests/routes/login.test.ts index 587c4584..faad5d83 100644 --- a/ross/tests/routes/login.test.ts +++ b/ross/tests/routes/login.test.ts @@ -307,11 +307,11 @@ describe('POST /auth/login', () => { await app.close(); }); - test('should use custom tokenExpiration when configured', async () => { + test('should use custom accessTokenExpiration when configured', async () => { const authWithExpiration: AuthenticationConfig = { ...upAuthConfig, jwtSecret: 'this-will-never-be-used', - tokenExpiration: '2h', + accessTokenExpiration: '2h', userModel: { modelName: 'users', idField: 'id', @@ -367,7 +367,7 @@ describe('POST /auth/login', () => { await app.close(); }); - test('should use default 1d expiration when tokenExpiration not set', async () => { + test('should use default 15m expiration when accessTokenExpiration not set', async () => { const app = await createAuthApp(upAuthConfig); pgQueryMock.mockResolvedValueOnce({ @@ -387,16 +387,17 @@ describe('POST /auth/login', () => { expect(response.statusCode).toBe(200); const body = response.json(); expect(body.data.accessToken).toBeDefined(); + expect(body.data.refreshToken).toBeDefined(); const secret = 'this-will-never-be-used'; const decoded = jwt.verify(body.data.accessToken, secret) as Record< string, unknown >; - // 1 day = 86400 seconds, allow 1 second tolerance + // 15 minutes = 900 seconds const iat = decoded.iat as number; const exp = decoded.exp as number; - expect(exp - iat).toBe(86400); + expect(exp - iat).toBe(900); await app.close(); }); diff --git a/ross/tests/routes/refresh.test.ts b/ross/tests/routes/refresh.test.ts new file mode 100644 index 00000000..bb301d41 --- /dev/null +++ b/ross/tests/routes/refresh.test.ts @@ -0,0 +1,348 @@ +import Fastify from 'fastify'; +import jwt from 'jsonwebtoken'; +import {beforeEach, describe, expect, test, vi} from 'vitest'; + +import authPlugin from '@/plugin/auth'; +import cachePlugin from '@/plugin/cache'; +import databasePlugin from '@/plugin/database'; +import responsePlugin from '@/plugin/response'; + +import {createSession} from '@/lib/auth/session'; +import {resolveConfig} from '@/lib/config/resolve'; + +import {registerLogoutRoute} from '@/routes/auth/logout'; +import {registerRefreshRoute} from '@/routes/auth/refresh'; + +import {AuthenticationConfig, ModelConfig} from '@/interfaces/config'; + +import {pgQueryMock} from '@tests/helpers/db-mocks'; + +const authModels: Record = { + users: { + fields: { + id: {type: 'integer', primaryKey: true}, + email: {type: 'string', nullable: false}, + password: {type: 'string', nullable: false}, + provider: {type: 'string', nullable: false}, + provider_id: {type: 'string', nullable: true}, + }, + }, +}; + +const baseAuth: AuthenticationConfig = { + enabled: true, + jwtSecret: 'this-will-never-be-used-in-production-32chars', + accessTokenExpiration: '15m', + refreshTokenExpiration: '7d', + sessionStorage: 'cache', + userModel: { + modelName: 'users', + idField: 'id', + providerField: 'provider', + }, + providers: [ + { + type: 'up-auth', + config: { + fields: {usernameField: 'email', passwordField: 'password'}, + }, + }, + ], +}; + +async function createTestApp(authOverride: Partial = {}) { + const app = Fastify(); + const config = resolveConfig( + { + application: {name: 'Refresh Test'}, + infrastructure: { + database: {engine: 'postgres', connection: {url: 'postgres://mock'}}, + }, + data: {models: authModels}, + authentication: {...baseAuth, ...authOverride}, + }, + {mode: 'dev'}, + ); + + app.appConfig = config; + await app.register(databasePlugin); + await app.register(cachePlugin); + await app.register(responsePlugin); + await app.register(authPlugin); + registerRefreshRoute(app, config); + registerLogoutRoute(app, config); + await app.ready(); + return {app, config}; +} + +describe('POST /v1/auth/refresh & POST /v1/auth/logout', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + test('rotates refresh token and issues a new accessToken (cache backend)', async () => { + const {app, config} = await createTestApp({sessionStorage: 'cache'}); + const {refreshToken} = await createSession(app, config, 1); + + pgQueryMock.mockResolvedValueOnce({ + rows: [{id: 1, email: 'alice@example.com', provider: 'up-auth'}], + rowCount: 1, + }); + + const res = await app.inject({ + method: 'POST', + url: '/v1/auth/refresh', + payload: {refreshToken}, + }); + + expect(res.statusCode).toBe(200); + const body = res.json(); + expect(body.data.accessToken).toBeDefined(); + expect(body.data.refreshToken).toBeDefined(); + expect(body.data.refreshToken).not.toBe(refreshToken); + + const decoded = jwt.verify( + body.data.accessToken, + baseAuth.jwtSecret!, + ) as Record; + expect(decoded.id).toBe(1); + expect(decoded.email).toBe('alice@example.com'); + + // Reusing old refresh token must fail with 401 + const replay = await app.inject({ + method: 'POST', + url: '/v1/auth/refresh', + payload: {refreshToken}, + }); + expect(replay.statusCode).toBe(401); + + await app.close(); + }); + + test('returns 401 when refreshToken is missing or invalid', async () => { + const {app} = await createTestApp(); + + const missing = await app.inject({ + method: 'POST', + url: '/v1/auth/refresh', + payload: {}, + }); + expect(missing.statusCode).toBe(401); + + const invalid = await app.inject({ + method: 'POST', + url: '/v1/auth/refresh', + payload: {refreshToken: 'non-existent-token'}, + }); + expect(invalid.statusCode).toBe(401); + + await app.close(); + }); + + test('returns 401 and revokes session if user no longer exists', async () => { + const {app, config} = await createTestApp({sessionStorage: 'cache'}); + const {refreshToken} = await createSession(app, config, 999); + + pgQueryMock.mockResolvedValueOnce({rows: [], rowCount: 0}); + + const res = await app.inject({ + method: 'POST', + url: '/v1/auth/refresh', + payload: {refreshToken}, + }); + expect(res.statusCode).toBe(401); + + await app.close(); + }); + + test('POST /v1/auth/logout requires bearer token and revokes the session', async () => { + const {app, config} = await createTestApp({sessionStorage: 'cache'}); + const {refreshToken} = await createSession(app, config, 1); + const accessToken = app.jwt.sign({id: 1, email: 'alice@example.com'}); + + const unauth = await app.inject({ + method: 'POST', + url: '/v1/auth/logout', + payload: {refreshToken}, + }); + expect(unauth.statusCode).toBe(401); + + const logoutRes = await app.inject({ + method: 'POST', + url: '/v1/auth/logout', + headers: {authorization: `Bearer ${accessToken}`}, + payload: {refreshToken}, + }); + expect(logoutRes.statusCode).toBe(200); + expect(logoutRes.json().data).toEqual({success: true}); + + const refreshAfterLogout = await app.inject({ + method: 'POST', + url: '/v1/auth/refresh', + payload: {refreshToken}, + }); + expect(refreshAfterLogout.statusCode).toBe(401); + + await app.close(); + }); + + test('resolves SSO provider fields and separate RBAC model on refresh', async () => { + const app = Fastify(); + const config = resolveConfig( + { + application: {name: 'Refresh SSO+RBAC Test'}, + infrastructure: { + database: {engine: 'postgres', connection: {url: 'postgres://mock'}}, + }, + data: { + models: { + ...authModels, + roles: { + fields: { + id: {type: 'integer', primaryKey: true}, + role: {type: 'string'}, + }, + }, + }, + }, + rbac: { + enabled: true, + modelName: 'roles', + roleField: 'role', + defaultRole: 'viewer', + }, + authentication: { + enabled: true, + jwtSecret: 'this-will-never-be-used-in-production-32chars', + sessionStorage: 'cache', + userModel: { + modelName: 'users', + idField: 'id', + providerField: 'provider', + }, + providers: [ + { + type: 'sso', + name: 'google', + protocol: 'oidc', + config: { + fields: { + providerIdField: 'provider_id', + usernameField: 'email', + }, + issuerUrl: 'https://accounts.google.com', + clientId: 'cid', + clientSecret: 'csec', + }, + }, + ], + }, + }, + {mode: 'dev'}, + ); + + app.appConfig = config; + await app.register(databasePlugin); + await app.register(cachePlugin); + await app.register(responsePlugin); + await app.register(authPlugin); + registerRefreshRoute(app, config); + await app.ready(); + + const {refreshToken} = await createSession(app, config, 5); + pgQueryMock + .mockResolvedValueOnce({ + rows: [ + { + id: 5, + email: 'sso@example.com', + provider: 'google', + provider_id: 'g-123', + }, + ], + rowCount: 1, + }) + .mockResolvedValueOnce({ + rows: [{id: 5, role: 'admin'}], + rowCount: 1, + }); + + const res = await app.inject({ + method: 'POST', + url: '/v1/auth/refresh', + payload: {refreshToken}, + }); + expect(res.statusCode).toBe(200); + const decoded = jwt.verify( + res.json().data.accessToken, + 'this-will-never-be-used-in-production-32chars', + ) as Record; + expect(decoded.providerId).toBe('g-123'); + expect(decoded.role).toBe('admin'); + + // Fallback when user.provider does not match any configured SSO or up-auth provider + const {refreshToken: rt2} = await createSession(app, config, 6); + pgQueryMock + .mockResolvedValueOnce({ + rows: [{id: 6, email: 'other@example.com', provider: 'unknown'}], + rowCount: 1, + }) + .mockResolvedValueOnce({rows: [], rowCount: 0}); + const res2 = await app.inject({ + method: 'POST', + url: '/v1/auth/refresh', + payload: {refreshToken: rt2}, + }); + expect(res2.statusCode).toBe(200); + + await app.close(); + }); + + test('logout returns 401 when JWT payload is missing id', async () => { + const {app} = await createTestApp({sessionStorage: 'cache'}); + const tokenWithoutId = app.jwt.sign({email: 'no-id@example.com'}); + + const res = await app.inject({ + method: 'POST', + url: '/v1/auth/logout', + headers: {authorization: `Bearer ${tokenWithoutId}`}, + payload: {refreshToken: 'some-token'}, + }); + expect(res.statusCode).toBe(401); + + await app.close(); + }); + + test('skips route registration when auth disabled or userModel missing', async () => { + const app = Fastify(); + const disabledConfig = resolveConfig( + { + application: {name: 'Disabled'}, + infrastructure: { + database: {engine: 'postgres', connection: {url: 'postgres://mock'}}, + }, + data: {models: authModels}, + }, + {mode: 'dev'}, + ); + registerRefreshRoute(app, disabledConfig); + registerLogoutRoute(app, disabledConfig); + + const missingModelConfig = resolveConfig( + { + application: {name: 'Missing Model'}, + infrastructure: { + database: {engine: 'postgres', connection: {url: 'postgres://mock'}}, + }, + data: {models: authModels}, + authentication: baseAuth, + }, + {mode: 'dev'}, + ); + delete missingModelConfig.data.models.users; + registerRefreshRoute(app, missingModelConfig); + registerLogoutRoute(app, missingModelConfig); + + expect(true).toBe(true); + }); +}); diff --git a/ross/tests/server.test.ts b/ross/tests/server.test.ts index 4e9d37e1..52cdeeb4 100644 --- a/ross/tests/server.test.ts +++ b/ross/tests/server.test.ts @@ -46,7 +46,7 @@ import { ResolvedAppConfig, } from '@/interfaces/config'; -import {NODE_CACHE_OTP_WARNING} from '@/constants'; +import {NODE_CACHE_OTP_WARNING, NODE_CACHE_SESSION_WARNING} from '@/constants'; vi.mock('fastify', () => { let appConfig: ResolvedAppConfig | undefined; @@ -941,6 +941,38 @@ describe('Server', () => { expect(mockApp.log.warn).toHaveBeenCalledWith(NODE_CACHE_OTP_WARNING); }); + it('should warn when sessionStorage is cache without a distributed cache', async () => { + const configWithCacheSessions: AppConfig = { + ...mockConfig, + authentication: { + enabled: true, + jwtSecret: 'test-secret-at-least-32-chars-long!', + sessionStorage: 'cache', + userModel: { + modelName: 'users', + idField: 'id', + providerField: 'provider', + }, + providers: [ + { + type: 'up-auth', + config: { + fields: { + usernameField: 'email', + passwordField: 'password', + }, + }, + }, + ], + }, + }; + + await startServer(resolve(configWithCacheSessions, 'dev')); + await runLastOnListenHook(); + + expect(mockApp.log.warn).toHaveBeenCalledWith(NODE_CACHE_SESSION_WARNING); + }); + it('should warn when isVerifiedField is configured without a cache', async () => { const configWithVerification: AppConfig = { ...mockConfig, @@ -978,6 +1010,38 @@ describe('Server', () => { expect(mockApp.log.warn).toHaveBeenCalledWith(NODE_CACHE_OTP_WARNING); }); + it('should warn when sessionStorage is cache without a distributed cache', async () => { + const configWithCacheSessions: AppConfig = { + ...mockConfig, + authentication: { + enabled: true, + jwtSecret: 'test-secret-at-least-32-chars-long!', + sessionStorage: 'cache', + userModel: { + modelName: 'users', + idField: 'id', + providerField: 'provider', + }, + providers: [ + { + type: 'up-auth', + config: { + fields: { + usernameField: 'email', + passwordField: 'password', + }, + }, + }, + ], + }, + }; + + await startServer(resolve(configWithCacheSessions, 'dev')); + await runLastOnListenHook(); + + expect(mockApp.log.warn).toHaveBeenCalledWith(NODE_CACHE_SESSION_WARNING); + }); + it('should not warn when a cache is configured', async () => { const configWithRedis: AppConfig = { ...mockConfig, diff --git a/ross/tests/utils/hash.test.ts b/ross/tests/utils/hash.test.ts index 79e451e3..ca568da9 100644 --- a/ross/tests/utils/hash.test.ts +++ b/ross/tests/utils/hash.test.ts @@ -1,6 +1,6 @@ import {describe, expect, test} from 'vitest'; -import {compare, hash} from '@/utils/hash'; +import {compare, hash, sha256} from '@/utils/hash'; import {BCRYPT_SALT_ROUNDS, DUMMY_PASSWORD_HASH} from '@/constants'; describe('hash utility', () => { @@ -61,4 +61,15 @@ describe('hash utility', () => { const isMatch = await compare('any-random-password', DUMMY_PASSWORD_HASH); expect(isMatch).toBe(false); }); + + test('sha256 returns a deterministic 64-char hex digest', () => { + const a = sha256('token-value'); + const b = sha256('token-value'); + const c = sha256('other-value'); + + expect(a).toHaveLength(64); + expect(a).toMatch(/^[a-f0-9]{64}$/); + expect(a).toBe(b); + expect(a).not.toBe(c); + }); }); diff --git a/ross/tests/validators/config.test.ts b/ross/tests/validators/config.test.ts index 815cb191..1526489a 100644 --- a/ross/tests/validators/config.test.ts +++ b/ross/tests/validators/config.test.ts @@ -4015,15 +4015,38 @@ describe('validateInvalidAuthConfig', () => { '/authentication/jwtSecret must NOT have fewer than 32 characters', }, { - name: 'invalid tokenExpiration pattern', + name: 'invalid accessTokenExpiration pattern', patch: { authentication: { ...authBase().authentication, - tokenExpiration: 'one day', + accessTokenExpiration: 'one day', providers: [upAuthProvider], }, }, - expected: '/authentication/tokenExpiration must match pattern', + expected: '/authentication/accessTokenExpiration must match pattern', + }, + { + name: 'invalid refreshTokenExpiration pattern', + patch: { + authentication: { + ...authBase().authentication, + refreshTokenExpiration: 'seven days', + providers: [upAuthProvider], + }, + }, + expected: '/authentication/refreshTokenExpiration must match pattern', + }, + { + name: 'invalid sessionStorage value', + patch: { + authentication: { + ...authBase().authentication, + sessionStorage: 'redis', + providers: [upAuthProvider], + }, + }, + expected: + '/authentication/sessionStorage must be equal to one of the allowed values', }, { name: 'api-key combined with an identity provider', @@ -4366,6 +4389,25 @@ describe('validateInvalidAuthConfig', () => { expected: '/authentication/providers/up-auth/config/fields/usernameField: field must not be nullable when SSO is not configured', }, + { + name: 'reserved _ross_sessions model name', + models: { + ...upAuthOnlyModels, + _ross_sessions: { + fields: { + id: {type: 'string', primaryKey: true}, + }, + }, + }, + patch: { + authentication: { + ...authBase().authentication, + providers: [upAuthProvider], + }, + }, + expected: + '/data/models/_ross_sessions: model name is reserved for internal session storage', + }, { name: 'sso usernameField does not exist in model', patch: { @@ -4451,9 +4493,13 @@ describe('validateValidAuthConfig', () => { providers: [{type: 'api-key', config: {key: 'my-key'}}], }, { - name: 'valid up-auth with tokenExpiration', + name: 'valid up-auth with accessTokenExpiration, refreshTokenExpiration, and sessionStorage', providers: [upAuthProvider], - extra: {tokenExpiration: '8h'}, + extra: { + accessTokenExpiration: '8h', + refreshTokenExpiration: '14d', + sessionStorage: 'cache', + }, models: upAuthOnlyModels, }, {