ActivityPub-federated video streaming platform using P2P directly in your web browser
Refactor oauth handlers
Chocobozzz0b11d62f4803
diff --git a/server/core/controllers/api/users/token.ts b/server/core/controllers/api/users/token.tsindex 9760aa213a..4c8f701946 100644--- a/server/core/controllers/api/users/token.ts+++ b/server/core/controllers/api/users/token.ts@@ -4,9 +4,11 @@ import { buildUUID } from '@peertube/peertube-node-utils'import { logger } from '@server/helpers/logger.js'import { CONFIG } from '@server/initializers/config.js'import { OTP } from '@server/initializers/constants.js'+import { BypassLogin } from '@server/lib/auth/bypass-login.model.js'import { consumeBypassFromExternalAuth, getAuthNameFromRefreshGrant, getBypassFromPasswordGrant } from '@server/lib/auth/external-auth.js'-import { BypassLogin, revokeToken } from '@server/lib/auth/oauth-model.js'-import { handleOAuthToken, MissingTwoFactorError, TooManyLoginFailuresError } from '@server/lib/auth/oauth.js'+import { MissingTwoFactorError, TooManyLoginFailuresError } from '@server/lib/auth/oauth-errors.js'+import { handleOAuthToken } from '@server/lib/auth/oauth-handlers.js'+import { revokeToken } from '@server/lib/auth/oauth-token.js'import { Hooks } from '@server/lib/plugins/hooks.js'import {asyncMiddleware,diff --git a/server/core/lib/auth/auth-utils.ts b/server/core/lib/auth/auth-utils.tsnew file mode 100644index 0000000000..267fb970cf--- /dev/null+++ b/server/core/lib/auth/auth-utils.ts@@ -0,0 +1,6 @@+import { CONFIG } from '@server/initializers/config.js'+import { MUser } from '@server/types/models/index.js'++export function isRootAuthDisabled (user: Pick<MUser, 'username'>) {+ return CONFIG.USER.DISABLE_ROOT_AUTH === true && user.username === 'root'+}diff --git a/server/core/lib/auth/bypass-login.model.ts b/server/core/lib/auth/bypass-login.model.tsnew file mode 100644index 0000000000..61fde0562a--- /dev/null+++ b/server/core/lib/auth/bypass-login.model.ts@@ -0,0 +1,10 @@+import { RegisterServerAuthenticatedResult } from '@server/types/index.js'+import { ExternalUser } from './external-user.model.js'++export type BypassLogin = {+ bypass: boolean+ pluginName: string+ authName?: string+ user: ExternalUser+ userUpdater: RegisterServerAuthenticatedResult['userUpdater']+}diff --git a/server/core/lib/auth/external-auth.ts b/server/core/lib/auth/external-auth.tsindex b05065859e..45597cee93 100644--- a/server/core/lib/auth/external-auth.ts+++ b/server/core/lib/auth/external-auth.ts@@ -14,17 +14,13 @@ import { generateRandomString } from '@server/helpers/utils.js'import { PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME } from '@server/initializers/constants.js'import { PluginManager } from '@server/lib/plugins/plugin-manager.js'import { OAuthTokenModel } from '@server/models/oauth/oauth-token.js'-import { MUser } from '@server/types/models/index.js'import {RegisterServerAuthenticatedResult,RegisterServerAuthPassOptions,RegisterServerExternalAuthenticatedResult} from '@server/types/plugins/register-server-auth.model.js'-import { BypassLogin } from './oauth-model.js'--export type ExternalUser =- & Pick<MUser, 'username' | 'email' | 'role' | 'adminFlags' | 'videoQuotaDaily' | 'videoQuota' | 'language'>- & { displayName: string, externalId?: string }+import { BypassLogin } from './bypass-login.model.js'+import { ExternalUser } from './external-user.model.js'// Token is the key, expiration date is the valueconst authBypassTokens = new Map<string, {diff --git a/server/core/lib/auth/external-user.model.ts b/server/core/lib/auth/external-user.model.tsnew file mode 100644index 0000000000..202f324c57--- /dev/null+++ b/server/core/lib/auth/external-user.model.ts@@ -0,0 +1,5 @@+import { MUser } from '@server/types/models/index.js'++export type ExternalUser =+ & Pick<MUser, 'username' | 'email' | 'role' | 'adminFlags' | 'videoQuotaDaily' | 'videoQuota' | 'language'>+ & { displayName: string, externalId?: string }diff --git a/server/core/lib/auth/oauth-errors.ts b/server/core/lib/auth/oauth-errors.tsnew file mode 100644index 0000000000..99605e36a3--- /dev/null+++ b/server/core/lib/auth/oauth-errors.ts@@ -0,0 +1,41 @@+import { HttpStatusCode, ServerErrorCode } from '@peertube/peertube-models'++export class MissingTwoFactorError extends Error {+ code = HttpStatusCode.UNAUTHORIZED_401+ name = ServerErrorCode.MISSING_TWO_FACTOR+}++export class TooLongPasswordError extends Error {+ code = HttpStatusCode.BAD_REQUEST_400+ name = ServerErrorCode.TOO_LONG_PASSWORD+}++export class AccountBlockedError extends Error {+ code = HttpStatusCode.BAD_REQUEST_400+ name = ServerErrorCode.ACCOUNT_BLOCKED+}++export class EmailNotVerifiedError extends Error {+ code = HttpStatusCode.BAD_REQUEST_400+ name = ServerErrorCode.EMAIL_NOT_VERIFIED+}++export class InvalidTwoFactorError extends Error {+ code = HttpStatusCode.BAD_REQUEST_400+ name = ServerErrorCode.INVALID_TWO_FACTOR+}++export class TooManyLoginFailuresError extends Error {+ code = HttpStatusCode.TOO_MANY_REQUESTS_429+ name = ServerErrorCode.TOO_MANY_LOGIN_FAILURES+}++export class RegistrationWaitingForApproval extends Error {+ code = HttpStatusCode.BAD_REQUEST_400+ name = ServerErrorCode.ACCOUNT_WAITING_FOR_APPROVAL+}++export class RegistrationApprovalRejected extends Error {+ code = HttpStatusCode.BAD_REQUEST_400+ name = ServerErrorCode.ACCOUNT_APPROVAL_REJECTED+}diff --git a/server/core/lib/auth/oauth.ts b/server/core/lib/auth/oauth-handlers.tssimilarity index 52%rename from server/core/lib/auth/oauth.tsrename to server/core/lib/auth/oauth-handlers.tsindex f989f3591b..60f9faa548 100644--- a/server/core/lib/auth/oauth.ts+++ b/server/core/lib/auth/oauth-handlers.ts@@ -7,59 +7,16 @@ import OAuth2Server, {UnauthorizedClientError,UnsupportedGrantTypeError} from '@node-oauth/oauth2-server'-import { pick } from '@peertube/peertube-core-utils'-import { HttpStatusCode, ServerErrorCode, UserRegistrationState } from '@peertube/peertube-models'-import { sha1 } from '@peertube/peertube-node-utils'-import { randomBytesPromise } from '@server/helpers/core-utils.js'-import { isOTPValid } from '@server/helpers/otp.js'-import { CONFIG } from '@server/initializers/config.js'-import { Redis } from '@server/lib/redis.js'-import { UserRegistrationModel } from '@server/models/user/user-registration.js'+import { maskSecret } from '@peertube/peertube-core-utils'import { MOAuthClient } from '@server/types/models/index.js'import express from 'express'-import { OTP } from '../../initializers/constants.js'+import { logger } from '../../helpers/logger.js'+import { CONFIG } from '../../initializers/config.js'+import { OAuthClientModel } from '../../models/oauth/oauth-client.js'import { Hooks } from '../plugins/hooks.js'-import { BypassLogin, getAccessToken, getClient, getRefreshToken, getUser, revokeToken, saveToken } from './oauth-model.js'--class MissingTwoFactorError extends Error {- code = HttpStatusCode.UNAUTHORIZED_401- name = ServerErrorCode.MISSING_TWO_FACTOR-}--class TooLongPasswordError extends Error {- code = HttpStatusCode.BAD_REQUEST_400- name = ServerErrorCode.TOO_LONG_PASSWORD-}--class AccountBlockedError extends Error {- code = HttpStatusCode.BAD_REQUEST_400- name = ServerErrorCode.ACCOUNT_BLOCKED-}--class EmailNotVerifiedError extends Error {- code = HttpStatusCode.BAD_REQUEST_400- name = ServerErrorCode.EMAIL_NOT_VERIFIED-}--class InvalidTwoFactorError extends Error {- code = HttpStatusCode.BAD_REQUEST_400- name = ServerErrorCode.INVALID_TWO_FACTOR-}--class TooManyLoginFailuresError extends Error {- code = HttpStatusCode.TOO_MANY_REQUESTS_429- name = ServerErrorCode.TOO_MANY_LOGIN_FAILURES-}--class RegistrationWaitingForApproval extends Error {- code = HttpStatusCode.BAD_REQUEST_400- name = ServerErrorCode.ACCOUNT_WAITING_FOR_APPROVAL-}--class RegistrationApprovalRejected extends Error {- code = HttpStatusCode.BAD_REQUEST_400- name = ServerErrorCode.ACCOUNT_APPROVAL_REJECTED-}+import { BypassLogin } from './bypass-login.model.js'+import { buildToken, getAccessToken, getRefreshToken, revokeToken, saveToken } from './oauth-token.js'+import { getUserOrThrow } from './oauth-user.js'/*** Reimplement some functions of OAuth2Server to inject external auth methods@@ -69,20 +26,15 @@ const oAuthServer = new OAuth2Server({accessTokenLifetime: CONFIG.OAUTH2.TOKEN_LIFETIME.ACCESS_TOKEN / 1000,refreshTokenLifetime: CONFIG.OAUTH2.TOKEN_LIFETIME.REFRESH_TOKEN / 1000,+ // oAuthServer is only used for .authenticate() below, which only calls model.getAccessToken()+ // (getClient/getRefreshToken/revokeToken/saveToken are called directly, bypassing the OAuth2Server model contract)// See https://github.com/oauthjs/node-oauth2-server/wiki/Model-specification for the model specifications- model: {- getAccessToken,- getClient,- getRefreshToken,- getUser,- revokeToken,- saveToken- } as any // FIXME: typings+ model: { getAccessToken } as any // FIXME: typings})// ----------------------------------------------------------------------------async function handleOAuthToken (req: express.Request, options: { refreshTokenAuthName?: string, bypassLogin?: BypassLogin }) {+export async function handleOAuthToken (req: express.Request, options: { refreshTokenAuthName?: string, bypassLogin?: BypassLogin }) {const oauthRequest = new Request(req)const { refreshTokenAuthName, bypassLogin } = options@@ -143,24 +95,13 @@ async function handleOAuthToken (req: express.Request, options: { refreshTokenAu})}-function handleOAuthAuthenticate (+export function handleOAuthAuthenticate (req: express.Request,res: express.Response) {return oAuthServer.authenticate(new Request(req), new Response(res))}-export {- handleOAuthAuthenticate,- handleOAuthToken,- InvalidTwoFactorError,- MissingTwoFactorError,- TooLongPasswordError,- TooManyLoginFailuresError,- AccountBlockedError,- EmailNotVerifiedError-}-// ---------------------------------------------------------------------------async function handlePasswordGrant (options: {@@ -187,34 +128,7 @@ async function handlePasswordGrant (options: {throw new InvalidRequestError(req.t('Missing parameter: `password`'))}- const user = await getUser(usernameOrEmail, password, { bypassLogin, req })- if (!user) {- const registrations = await UserRegistrationModel.listByEmailCaseInsensitiveOrUsername(usernameOrEmail)-- if (registrations.length === 1) {- if (registrations[0].state === UserRegistrationState.REJECTED) {- throw new RegistrationApprovalRejected(req.t('Registration approval for this account has been rejected'))- } else if (registrations[0].state === UserRegistrationState.PENDING) {- throw new RegistrationWaitingForApproval(req.t('Registration for this account is awaiting approval'))- }- }-- throw new InvalidGrantError(req.t('Invalid grant: user credentials are invalid'))- }-- if (user.otpSecret) {- if (!options.oauthRequest.headers[OTP.HEADER_NAME]) {- throw new MissingTwoFactorError(req.t('Missing two factor header'))- }-- if (await isOTPValid({ encryptedSecret: user.otpSecret, token: options.oauthRequest.headers[OTP.HEADER_NAME] }) !== true) {- await Redis.Instance.addLoginFailure(user.id)-- throw new InvalidTwoFactorError(req.t('Invalid two factor header'))- }- }-- await Redis.Instance.deleteLoginFailures(user.id)+ const user = await getUserOrThrow({ usernameOrEmail, password, bypassLogin, req, oauthHeaders: options.oauthRequest.headers })const now = new Date()@@ -273,42 +187,12 @@ async function handleRefreshGrant (options: {return saveToken(token, client, refreshToken.user, { refreshTokenAuthName })}-function generateRandomToken () {- return randomBytesPromise(256)- .then(buffer => sha1(buffer))-}--function getTokenExpiresAt (type: 'access' | 'refresh') {- const lifetime = type === 'access'- ? CONFIG.OAUTH2.TOKEN_LIFETIME.ACCESS_TOKEN- : CONFIG.OAUTH2.TOKEN_LIFETIME.REFRESH_TOKEN+// ---------------------------------------------------------------------------+// Private+// ---------------------------------------------------------------------------- return new Date(Date.now() + lifetime)-}+function getClient (clientId: string, clientSecret: string) {+ logger.debug('Getting Client (clientId: ' + clientId + ', clientSecret: ' + maskSecret(clientSecret) + ').')-async function buildToken (options: {- loginDevice: string- loginIP: string- loginDate: Date- lastActivityDevice: string- lastActivityIP: string- lastActivityDate: Date-}) {- const [ accessToken, refreshToken ] = await Promise.all([ generateRandomToken(), generateRandomToken() ])-- return {- accessToken,- refreshToken,- accessTokenExpiresAt: getTokenExpiresAt('access'),- refreshTokenExpiresAt: getTokenExpiresAt('refresh'),-- ...pick(options, [- 'loginDevice',- 'loginIP',- 'loginDate',- 'lastActivityDevice',- 'lastActivityIP',- 'lastActivityDate'- ])- }+ return OAuthClientModel.getByIdAndSecret(clientId, clientSecret)}diff --git a/server/core/lib/auth/oauth-model.ts b/server/core/lib/auth/oauth-model.tsdeleted file mode 100644index 95ffd4560a..0000000000--- a/server/core/lib/auth/oauth-model.ts+++ /dev/null@@ -1,417 +0,0 @@-import { AccessDeniedError } from '@node-oauth/oauth2-server'-import { maskSecret, pick } from '@peertube/peertube-core-utils'-import { AttributesOnly } from '@peertube/peertube-typescript-utils'-import { isUserPasswordTooLong } from '@server/helpers/custom-validators/users.js'-import { PluginManager } from '@server/lib/plugins/plugin-manager.js'-import { AccountModel } from '@server/models/account/account.js'-import { AuthenticatedResultUpdaterFieldName, RegisterServerAuthenticatedResult } from '@server/types/index.js'-import { MOAuthClient } from '@server/types/models/index.js'-import { MUser, MUserDefault } from '@server/types/models/user/user.js'-import express from 'express'-import { logger } from '../../helpers/logger.js'-import { CONFIG } from '../../initializers/config.js'-import { LOGIN_LOCKOUT } from '../../initializers/constants.js'-import { OAuthClientModel } from '../../models/oauth/oauth-client.js'-import { OAuthTokenModel } from '../../models/oauth/oauth-token.js'-import { UserModel } from '../../models/user/user.js'-import { findAvailableLocalActorName } from '../local-actor.js'-import { Redis } from '../redis.js'-import { buildUser, createUserAccountAndChannelAndPlaylist, getByEmailPermissive } from '../user.js'-import { ExternalUser } from './external-auth.js'-import { AccountBlockedError, EmailNotVerifiedError, TooLongPasswordError, TooManyLoginFailuresError } from './oauth.js'-import { TokensCache } from './tokens-cache.js'--type TokenInfo = {- accessToken: string- refreshToken: string- accessTokenExpiresAt: Date- refreshTokenExpiresAt: Date- loginDevice: string- loginIP: string- loginDate: Date- lastActivityDevice: string- lastActivityIP: string- lastActivityDate: Date-}--export type BypassLogin = {- bypass: boolean- pluginName: string- authName?: string- user: ExternalUser- userUpdater: RegisterServerAuthenticatedResult['userUpdater']-}--async function getAccessToken (bearerToken: string) {- logger.debug('Getting access token.')-- if (!bearerToken) return undefined-- let tokenModel = TokensCache.Instance.getToken(bearerToken)-- if (!tokenModel) {- tokenModel = await OAuthTokenModel.getByTokenAndPopulateUser(bearerToken)-- if (tokenModel) TokensCache.Instance.setToken(tokenModel)- }-- if (!tokenModel) return undefined-- if (isRootAuthDisabled(tokenModel.User)) return undefined-- if (tokenModel.User.pluginAuth) {- const valid = await PluginManager.Instance.isTokenValid(tokenModel, 'access')-- if (valid !== true) return undefined- }-- return tokenModel-}--function getClient (clientId: string, clientSecret: string) {- logger.debug('Getting Client (clientId: ' + clientId + ', clientSecret: ' + maskSecret(clientSecret) + ').')-- return OAuthClientModel.getByIdAndSecret(clientId, clientSecret)-}--async function getRefreshToken (refreshToken: string) {- logger.debug('Getting RefreshToken (refreshToken: ' + maskSecret(refreshToken) + ').')-- const tokenInfo = await OAuthTokenModel.getByRefreshTokenAndPopulateClient(refreshToken)- if (!tokenInfo) return undefined-- const tokenModel = tokenInfo.token-- if (isRootAuthDisabled(tokenModel.User)) return undefined-- if (tokenModel.User.pluginAuth) {- const valid = await PluginManager.Instance.isTokenValid(tokenModel, 'refresh')-- if (valid !== true) return undefined- }-- return tokenInfo-}--// Keep this function signature, required by oauth2-server-async function getUser (usernameOrEmail?: string, password?: string, options?: {- bypassLogin?: BypassLogin- req: express.Request-}) {- const { bypassLogin, req } = options-- // Special treatment coming from a plugin- if (bypassLogin?.bypass === true) {- logger.info('Bypassing oauth login by plugin %s.', bypassLogin.pluginName)-- const { pluginName, user: externalUser, userUpdater } = bypassLogin-- const user = await findExternalUserOrThrow({ externalUser, pluginName, userUpdater, req })-- // If the user does not belongs to a plugin, it was created before its installation- // Then we just go through a regular login process- if (user.pluginAuth !== null) {- // This user does not belong to this plugin- if (user.pluginAuth !== pluginName) {- if (CONFIG.USER.ALLOW_CROSS_PROVIDER_AUTH !== true) {- logger.info(- 'Cannot bypass oauth login by plugin %s because %s has another plugin auth method (%s).',- pluginName,- externalUser.email,- user.pluginAuth- )-- return null- } else {- logger.info(- 'Allowing cross authentication login for %s using plugin %s despite being known from plugin %s',- bypassLogin.user.email,- bypassLogin.pluginName,- user.pluginAuth- )-- user.pluginAuth = pluginName- await updateUserFromExternal({ user, userOptions: externalUser, userUpdater, syncEmail: true })-- // Tokens issued under the previous auth plugin can no longer have their validity checked by that- // plugin's hookTokenValidity (the user is not registered under it anymore), so force a fresh login- await OAuthTokenModel.deleteUserToken({ userId: user.id })- }- }-- checkUserValidityOrThrow(user, req)-- return user- }- }-- logger.debug('Getting User (username/email: ' + usernameOrEmail + ', password: ******).')-- const users = await UserModel.loadByUsernameOrEmailCaseInsensitive(usernameOrEmail)- let user: MUserDefault-- if (usernameOrEmail.includes('@')) {- user = getByEmailPermissive(users, usernameOrEmail)- } else if (users.length === 1) {- user = users[0]- }-- // If we don't find the user, or if the user belongs to a plugin- if (user?.pluginAuth !== null || !password) return null-- if (isRootAuthDisabled(user)) return null-- // Check the per-account login failures counter so a locked account cannot have its password/OTP brute-forced- if (await Redis.Instance.getLoginFailures(user.id) >= LOGIN_LOCKOUT.MAX_FAILURES) {- throw new TooManyLoginFailuresError(req.t('Too many login attempts for this account. Please try again later.'))- }-- const passwordMatch = await user.isPasswordMatch(password)- if (passwordMatch !== true) {- await Redis.Instance.addLoginFailure(user.id)-- return null- }-- if (isUserPasswordTooLong(password)) {- throw new TooLongPasswordError(req.t('Password is too long. Please reset it using the password reset procedure.'))- }-- checkUserValidityOrThrow(user, req)-- if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION && user.emailVerified === false) {- // Keep this message sync with the client- throw new EmailNotVerifiedError(req.t('User email is not verified.'))- }-- return user-}--async function revokeToken (- tokenInfo: { refreshToken: string },- options: {- req?: express.Request- explicitLogout?: boolean- } = {}-): Promise<{ success: boolean, redirectUrl?: string }> {- const { req, explicitLogout } = options-- const token = await OAuthTokenModel.getByRefreshTokenAndPopulateUser(tokenInfo.refreshToken)-- if (token) {- let redirectUrl: string-- if (explicitLogout === true && token.User.pluginAuth && token.authName) {- redirectUrl = await PluginManager.Instance.onLogout(token.User.pluginAuth, token.authName, token.User, req)- }-- TokensCache.Instance.deleteToken(token.accessToken)-- try {- await token.destroy()- } catch (err) {- logger.error('Cannot destroy token when revoking token.', { err })- }-- return { success: true, redirectUrl }- }-- return { success: false }-}--async function saveToken (- token: TokenInfo,- client: MOAuthClient,- user: MUser,- options: {- refreshTokenAuthName?: string- bypassLogin?: BypassLogin- } = {}-) {- const { refreshTokenAuthName, bypassLogin } = options- let authName: string = null-- if (bypassLogin?.bypass === true) {- authName = bypassLogin.authName- } else if (refreshTokenAuthName) {- authName = refreshTokenAuthName- }-- logger.debug(`Saving token ${maskSecret(token.accessToken)} for client ${client.id} and user ${user.id}.`)-- const tokenToCreate = {- ...pick(token, [- 'accessToken',- 'refreshToken',- 'accessTokenExpiresAt',- 'refreshTokenExpiresAt',- 'loginDevice',- 'loginIP',- 'loginDate',- 'lastActivityDate',- 'lastActivityDevice',- 'lastActivityIP'- ]),- authName,- oAuthClientId: client.id,- userId: user.id- }-- const tokenCreated = await OAuthTokenModel.create(tokenToCreate)-- user.lastLoginDate = new Date()- await user.save()-- return {- accessToken: tokenCreated.accessToken,- accessTokenExpiresAt: tokenCreated.accessTokenExpiresAt,- refreshToken: tokenCreated.refreshToken,- refreshTokenExpiresAt: tokenCreated.refreshTokenExpiresAt,- client,- user,- accessTokenExpiresIn: buildExpiresIn(tokenCreated.accessTokenExpiresAt),- refreshTokenExpiresIn: buildExpiresIn(tokenCreated.refreshTokenExpiresAt)- }-}--export {- getAccessToken,- getClient,- getRefreshToken,- getUser,- revokeToken,- saveToken-}--// -----------------------------------------------------------------------------async function findExternalUserOrThrow (options: {- externalUser: ExternalUser- pluginName: string- userUpdater: RegisterServerAuthenticatedResult['userUpdater']- req: express.Request-}): Promise<MUserDefault> {- const { externalUser, pluginName, userUpdater, req } = options-- if (externalUser.externalId) {- const userByExternalId = await UserModel.loadByPluginAuthExternalId(pluginName, externalUser.externalId)-- if (userByExternalId) {- // Authoritative match by stable external id: trust it even if the email changed at the identity provider- return updateUserFromExternal({ user: userByExternalId, userOptions: externalUser, userUpdater, syncEmail: true })- }- }-- // Plugin does not supply a stable external id: unchanged email-only behavior- const userByEmail = getByEmailPermissive(await UserModel.loadByEmailCaseInsensitive(externalUser.email), externalUser.email)- if (!userByEmail) return createUserFromExternal(pluginName, externalUser)-- if (userByEmail.pluginAuth === pluginName) {- if (externalUser.externalId && userByEmail.pluginAuthExternalId !== null) {- // This account is already linked to a different external id for this plugin- // Refuse to silently relink (identity provider email reuse, or a possible hijack attempt)- throw new AccessDeniedError(- req.t(- `Refusing external auth bypass for plugin {pluginName}: {email} is already linked to a different external id.`,- { pluginName, email: externalUser.email }- )- )- }-- return updateUserFromExternal({ user: userByEmail, userOptions: externalUser, userUpdater, syncEmail: false })- }-- return userByEmail-}--async function createUserFromExternal (pluginAuth: string, userOptions: ExternalUser) {- const username = await findAvailableLocalActorName(userOptions.username)-- const userToCreate = buildUser({- ...pick(userOptions, [ 'email', 'role', 'adminFlags', 'videoQuota', 'videoQuotaDaily', 'language' ]),-- username,- emailVerified: null,- password: null,- pluginAuth,- pluginAuthExternalId: userOptions.externalId- })-- const { user } = await createUserAccountAndChannelAndPlaylist({- userToCreate,- userDisplayName: userOptions.displayName- })-- return user-}--async function updateUserFromExternal (options: {- user: MUserDefault- userOptions: ExternalUser- userUpdater: RegisterServerAuthenticatedResult['userUpdater']- syncEmail: boolean-}) {- const { user, userOptions, userUpdater, syncEmail } = options-- if (userUpdater) {- {- type UserAttributeKeys = keyof AttributesOnly<UserModel>- const mappingKeys: { [id in UserAttributeKeys]?: AuthenticatedResultUpdaterFieldName } = {- role: 'role',- adminFlags: 'adminFlags',- videoQuota: 'videoQuota',- videoQuotaDaily: 'videoQuotaDaily',- language: 'language'- }-- for (const modelKey of Object.keys(mappingKeys)) {- const pluginOptionKey = mappingKeys[modelKey]-- const newValue = userUpdater({ fieldName: pluginOptionKey, currentValue: user[modelKey], newValue: userOptions[pluginOptionKey] })- user.set(modelKey, newValue)- }- }-- {- type AccountAttributeKeys = keyof Partial<AttributesOnly<AccountModel>>- const mappingKeys: { [id in AccountAttributeKeys]?: AuthenticatedResultUpdaterFieldName } = {- name: 'displayName'- }-- for (const modelKey of Object.keys(mappingKeys)) {- const optionKey = mappingKeys[modelKey]-- const newValue = userUpdater({ fieldName: optionKey, currentValue: user.Account[modelKey], newValue: userOptions[optionKey] })- user.Account.set(modelKey, newValue)- }- }-- logger.debug('Updated user %s with plugin userUpdated function.', user.email, { user, userOptions })- }-- if (userOptions.externalId && user.pluginAuthExternalId !== userOptions.externalId) {- logger.info('Linking external id for user %s (plugin %s).', user.email, user.pluginAuth)- user.set('pluginAuthExternalId', userOptions.externalId)- }-- if (syncEmail && userOptions.email && user.email !== userOptions.email) {- logger.info('Updating email of user %s to %s after successful external auth.', user.email, userOptions.email)- user.email = userOptions.email- }-- user.Account = await user.Account.save()-- return user.save()-}--function checkUserValidityOrThrow (user: MUser, req: express.Request) {- if (user.blocked) throw new AccountBlockedError(req.t('User is blocked.'))-}--function buildExpiresIn (expiresAt: Date) {- return Math.floor((expiresAt.getTime() - new Date().getTime()) / 1000)-}--function isRootAuthDisabled (user: Pick<MUser, 'username'>) {- return CONFIG.USER.DISABLE_ROOT_AUTH === true && user.username === 'root'-}diff --git a/server/core/lib/auth/oauth-token.ts b/server/core/lib/auth/oauth-token.tsnew file mode 100644index 0000000000..2b5d135029--- /dev/null+++ b/server/core/lib/auth/oauth-token.ts@@ -0,0 +1,206 @@+import { maskSecret, pick } from '@peertube/peertube-core-utils'+import { sha1 } from '@peertube/peertube-node-utils'+import { randomBytesPromise } from '@server/helpers/core-utils.js'+import { PluginManager } from '@server/lib/plugins/plugin-manager.js'+import { MOAuthClient } from '@server/types/models/index.js'+import { MUser } from '@server/types/models/user/user.js'+import express from 'express'+import { logger } from '../../helpers/logger.js'+import { CONFIG } from '../../initializers/config.js'+import { OAuthTokenModel } from '../../models/oauth/oauth-token.js'+import { isRootAuthDisabled } from './auth-utils.js'+import { BypassLogin } from './bypass-login.model.js'+import { TokensCache } from './tokens-cache.js'++export async function getAccessToken (bearerToken: string) {+ logger.debug('Getting access token.')++ if (!bearerToken) return undefined++ let tokenModel = TokensCache.Instance.getToken(bearerToken)++ if (!tokenModel) {+ tokenModel = await OAuthTokenModel.getByTokenAndPopulateUser(bearerToken)++ if (tokenModel) TokensCache.Instance.setToken(tokenModel)+ }++ if (!tokenModel) return undefined++ if (isRootAuthDisabled(tokenModel.User)) return undefined++ if (tokenModel.User.pluginAuth) {+ const valid = await PluginManager.Instance.isTokenValid(tokenModel, 'access')++ if (valid !== true) return undefined+ }++ return tokenModel+}++export async function getRefreshToken (refreshToken: string) {+ logger.debug('Getting RefreshToken (refreshToken: ' + maskSecret(refreshToken) + ').')++ const tokenInfo = await OAuthTokenModel.getByRefreshTokenAndPopulateClient(refreshToken)+ if (!tokenInfo) return undefined++ const tokenModel = tokenInfo.token++ if (isRootAuthDisabled(tokenModel.User)) return undefined++ if (tokenModel.User.pluginAuth) {+ const valid = await PluginManager.Instance.isTokenValid(tokenModel, 'refresh')++ if (valid !== true) return undefined+ }++ return tokenInfo+}++export async function revokeToken (+ tokenInfo: { refreshToken: string },+ options: {+ req?: express.Request+ explicitLogout?: boolean+ } = {}+): Promise<{ success: boolean, redirectUrl?: string }> {+ const { req, explicitLogout } = options++ const token = await OAuthTokenModel.getByRefreshTokenAndPopulateUser(tokenInfo.refreshToken)++ if (token) {+ let redirectUrl: string++ if (explicitLogout === true && token.User.pluginAuth && token.authName) {+ redirectUrl = await PluginManager.Instance.onLogout(token.User.pluginAuth, token.authName, token.User, req)+ }++ TokensCache.Instance.deleteToken(token.accessToken)++ try {+ await token.destroy()+ } catch (err) {+ logger.error('Cannot destroy token when revoking token.', { err })+ }++ return { success: true, redirectUrl }+ }++ return { success: false }+}++export type TokenInfo = {+ accessToken: string+ refreshToken: string+ accessTokenExpiresAt: Date+ refreshTokenExpiresAt: Date+ loginDevice: string+ loginIP: string+ loginDate: Date+ lastActivityDevice: string+ lastActivityIP: string+ lastActivityDate: Date+}++export async function buildToken (options: {+ loginDevice: string+ loginIP: string+ loginDate: Date+ lastActivityDevice: string+ lastActivityIP: string+ lastActivityDate: Date+}) {+ const [ accessToken, refreshToken ] = await Promise.all([ generateRandomToken(), generateRandomToken() ])++ return {+ accessToken,+ refreshToken,+ accessTokenExpiresAt: getTokenExpiresAt('access'),+ refreshTokenExpiresAt: getTokenExpiresAt('refresh'),++ ...pick(options, [+ 'loginDevice',+ 'loginIP',+ 'loginDate',+ 'lastActivityDevice',+ 'lastActivityIP',+ 'lastActivityDate'+ ])+ }+}++export async function saveToken (+ token: TokenInfo,+ client: MOAuthClient,+ user: MUser,+ options: {+ refreshTokenAuthName?: string+ bypassLogin?: BypassLogin+ } = {}+) {+ const { refreshTokenAuthName, bypassLogin } = options+ let authName: string = null++ if (bypassLogin?.bypass === true) {+ authName = bypassLogin.authName+ } else if (refreshTokenAuthName) {+ authName = refreshTokenAuthName+ }++ logger.debug(`Saving token ${maskSecret(token.accessToken)} for client ${client.id} and user ${user.id}.`)++ const tokenToCreate = {+ ...pick(token, [+ 'accessToken',+ 'refreshToken',+ 'accessTokenExpiresAt',+ 'refreshTokenExpiresAt',+ 'loginDevice',+ 'loginIP',+ 'loginDate',+ 'lastActivityDate',+ 'lastActivityDevice',+ 'lastActivityIP'+ ]),+ authName,+ oAuthClientId: client.id,+ userId: user.id+ }++ const tokenCreated = await OAuthTokenModel.create(tokenToCreate)++ user.lastLoginDate = new Date()+ await user.save()++ return {+ accessToken: tokenCreated.accessToken,+ accessTokenExpiresAt: tokenCreated.accessTokenExpiresAt,+ refreshToken: tokenCreated.refreshToken,+ refreshTokenExpiresAt: tokenCreated.refreshTokenExpiresAt,+ client,+ user,+ accessTokenExpiresIn: buildExpiresIn(tokenCreated.accessTokenExpiresAt),+ refreshTokenExpiresIn: buildExpiresIn(tokenCreated.refreshTokenExpiresAt)+ }+}++// ---------------------------------------------------------------------------+// Private+// ---------------------------------------------------------------------------++function buildExpiresIn (expiresAt: Date) {+ return Math.floor((expiresAt.getTime() - new Date().getTime()) / 1000)+}++function generateRandomToken () {+ return randomBytesPromise(256)+ .then(buffer => sha1(buffer))+}++function getTokenExpiresAt (type: 'access' | 'refresh') {+ const lifetime = type === 'access'+ ? CONFIG.OAUTH2.TOKEN_LIFETIME.ACCESS_TOKEN+ : CONFIG.OAUTH2.TOKEN_LIFETIME.REFRESH_TOKEN++ return new Date(Date.now() + lifetime)+}diff --git a/server/core/lib/auth/oauth-user.ts b/server/core/lib/auth/oauth-user.tsnew file mode 100644index 0000000000..e960fb7448--- /dev/null+++ b/server/core/lib/auth/oauth-user.ts@@ -0,0 +1,302 @@+import { AccessDeniedError, InvalidGrantError } from '@node-oauth/oauth2-server'+import { pick } from '@peertube/peertube-core-utils'+import { UserRegistrationState } from '@peertube/peertube-models'+import { AttributesOnly } from '@peertube/peertube-typescript-utils'+import { isUserPasswordTooLong } from '@server/helpers/custom-validators/users.js'+import { isOTPValid } from '@server/helpers/otp.js'+import { AccountModel } from '@server/models/account/account.js'+import { UserRegistrationModel } from '@server/models/user/user-registration.js'+import { AuthenticatedResultUpdaterFieldName, RegisterServerAuthenticatedResult } from '@server/types/index.js'+import { MUser, MUserDefault } from '@server/types/models/user/user.js'+import express from 'express'+import { logger } from '../../helpers/logger.js'+import { CONFIG } from '../../initializers/config.js'+import { LOGIN_LOCKOUT, OTP } from '../../initializers/constants.js'+import { OAuthTokenModel } from '../../models/oauth/oauth-token.js'+import { UserModel } from '../../models/user/user.js'+import { findAvailableLocalActorName } from '../local-actor.js'+import { Redis } from '../redis.js'+import { buildUser, createUserAccountAndChannelAndPlaylist, getByEmailPermissive } from '../user.js'+import { isRootAuthDisabled } from './auth-utils.js'+import { BypassLogin } from './bypass-login.model.js'+import { ExternalUser } from './external-user.model.js'+import {+ AccountBlockedError,+ EmailNotVerifiedError,+ InvalidTwoFactorError,+ MissingTwoFactorError,+ RegistrationApprovalRejected,+ RegistrationWaitingForApproval,+ TooLongPasswordError,+ TooManyLoginFailuresError+} from './oauth-errors.js'++export async function getUserOrThrow (options: {+ usernameOrEmail?: string+ password?: string+ bypassLogin?: BypassLogin+ req: express.Request+ oauthHeaders: Record<string, string>+}) {+ const { bypassLogin, req, usernameOrEmail, password, oauthHeaders } = options++ const throwInvalidGrantError = () => {+ throw new InvalidGrantError(req.t('Invalid grant: user credentials are invalid'))+ }++ // Special treatment coming from a plugin+ if (bypassLogin?.bypass === true) {+ const user = await handleGetUserBypass({ bypassLogin, req })++ // Continue the password process if handleGetUserBypass returns undefined,+ // which means the user does not belong to the plugin and we should go through a regular login process+ if (user) return user+ }++ logger.debug('Getting User (username/email: ' + usernameOrEmail + ', password: ******).')++ const users = await UserModel.loadByUsernameOrEmailCaseInsensitive(usernameOrEmail)+ const user = usernameOrEmail.includes('@')+ ? getByEmailPermissive(users, usernameOrEmail)+ : users[0]++ if (!user) {+ const registrations = await UserRegistrationModel.listByEmailCaseInsensitiveOrUsername(usernameOrEmail)++ if (registrations.length === 1) {+ if (registrations[0].state === UserRegistrationState.REJECTED) {+ throw new RegistrationApprovalRejected(req.t('Registration approval for this account has been rejected'))+ } else if (registrations[0].state === UserRegistrationState.PENDING) {+ throw new RegistrationWaitingForApproval(req.t('Registration for this account is awaiting approval'))+ }+ }++ throwInvalidGrantError()+ }++ // If we don't find the user, or if the user belongs to a plugin -> error+ if (user?.pluginAuth !== null || !password) throwInvalidGrantError()++ if (isRootAuthDisabled(user)) throwInvalidGrantError()++ // Check the per-account login failures counter so a locked account cannot have its password/OTP brute-forced+ if (await Redis.Instance.getLoginFailures(user.id) >= LOGIN_LOCKOUT.MAX_FAILURES) {+ throw new TooManyLoginFailuresError(req.t('Too many login attempts for this account. Please try again later.'))+ }++ const passwordMatch = await user.isPasswordMatch(password)+ if (passwordMatch !== true) {+ await Redis.Instance.addLoginFailure(user.id)++ throwInvalidGrantError()+ }++ if (isUserPasswordTooLong(password)) {+ throw new TooLongPasswordError(req.t('Password is too long. Please reset it using the password reset procedure.'))+ }++ checkUserNotBlockedOrThrow(user, req)++ if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION && user.emailVerified === false) {+ // Keep this message sync with the client+ throw new EmailNotVerifiedError(req.t('User email is not verified.'))+ }++ if (user.otpSecret) {+ if (!oauthHeaders[OTP.HEADER_NAME]) {+ throw new MissingTwoFactorError(req.t('Missing two factor header'))+ }++ if (await isOTPValid({ encryptedSecret: user.otpSecret, token: oauthHeaders[OTP.HEADER_NAME] }) !== true) {+ await Redis.Instance.addLoginFailure(user.id)++ throw new InvalidTwoFactorError(req.t('Invalid two factor header'))+ }+ }++ await Redis.Instance.deleteLoginFailures(user.id)++ return user+}++async function handleGetUserBypass (options: {+ bypassLogin?: BypassLogin+ req: express.Request+}) {+ const { bypassLogin, req } = options++ logger.info('Bypassing oauth login by plugin %s.', bypassLogin.pluginName)++ const { pluginName, user: externalUser, userUpdater } = bypassLogin++ const user = await findExternalUserOrThrow({ externalUser, pluginName, userUpdater, req })++ // If the user does not belongs to a plugin, it was created before its installation+ // Then we just go through a regular login process+ if (user.pluginAuth !== null) {+ // This user does not belong to this plugin+ if (user.pluginAuth !== pluginName) {+ if (CONFIG.USER.ALLOW_CROSS_PROVIDER_AUTH !== true) {+ logger.info(+ 'Cannot bypass oauth login by plugin %s because %s has another plugin auth method (%s).',+ pluginName,+ externalUser.email,+ user.pluginAuth+ )++ throw new AccessDeniedError(+ req.t('Cannot bypass oauth login by plugin {pluginName}: this account already uses another auth plugin.', { pluginName })+ )+ } else {+ logger.info(+ 'Allowing cross authentication login for %s using plugin %s despite being known from plugin %s',+ bypassLogin.user.email,+ bypassLogin.pluginName,+ user.pluginAuth+ )++ user.pluginAuth = pluginName+ await updateUserFromExternal({ user, userOptions: externalUser, userUpdater, syncEmail: true })++ // Tokens issued under the previous auth plugin can no longer have their validity checked by that+ // plugin's hookTokenValidity (the user is not registered under it anymore), so force a fresh login+ await OAuthTokenModel.deleteUserToken({ userId: user.id })+ }+ }++ checkUserNotBlockedOrThrow(user, req)++ return user+ }++ return undefined+}++// ---------------------------------------------------------------------------++async function findExternalUserOrThrow (options: {+ externalUser: ExternalUser+ pluginName: string+ userUpdater: RegisterServerAuthenticatedResult['userUpdater']+ req: express.Request+}): Promise<MUserDefault> {+ const { externalUser, pluginName, userUpdater, req } = options++ if (externalUser.externalId) {+ const userByExternalId = await UserModel.loadByPluginAuthExternalId(pluginName, externalUser.externalId)++ if (userByExternalId) {+ // Authoritative match by stable external id: trust it even if the email changed at the identity provider+ return updateUserFromExternal({ user: userByExternalId, userOptions: externalUser, userUpdater, syncEmail: true })+ }+ }++ // Plugin does not supply a stable external id: unchanged email-only behavior+ const userByEmail = getByEmailPermissive(await UserModel.loadByEmailCaseInsensitive(externalUser.email), externalUser.email)+ if (!userByEmail) return createUserFromExternal(pluginName, externalUser)++ if (userByEmail.pluginAuth === pluginName) {+ if (externalUser.externalId && userByEmail.pluginAuthExternalId !== null) {+ // This account is already linked to a different external id for this plugin+ // Refuse to silently relink (identity provider email reuse, or a possible hijack attempt)+ throw new AccessDeniedError(+ req.t(+ `Refusing external auth bypass for plugin {pluginName}: {email} is already linked to a different external id.`,+ { pluginName, email: externalUser.email }+ )+ )+ }++ return updateUserFromExternal({ user: userByEmail, userOptions: externalUser, userUpdater, syncEmail: false })+ }++ return userByEmail+}++async function createUserFromExternal (pluginAuth: string, userOptions: ExternalUser) {+ const username = await findAvailableLocalActorName(userOptions.username)++ const userToCreate = buildUser({+ ...pick(userOptions, [ 'email', 'role', 'adminFlags', 'videoQuota', 'videoQuotaDaily', 'language' ]),++ username,+ emailVerified: null,+ password: null,+ pluginAuth,+ pluginAuthExternalId: userOptions.externalId+ })++ const { user } = await createUserAccountAndChannelAndPlaylist({+ userToCreate,+ userDisplayName: userOptions.displayName+ })++ return user+}++async function updateUserFromExternal (options: {+ user: MUserDefault+ userOptions: ExternalUser+ userUpdater: RegisterServerAuthenticatedResult['userUpdater']+ syncEmail: boolean+}) {+ const { user, userOptions, userUpdater, syncEmail } = options++ if (userUpdater) {+ {+ type UserAttributeKeys = keyof AttributesOnly<UserModel>+ const mappingKeys: { [id in UserAttributeKeys]?: AuthenticatedResultUpdaterFieldName } = {+ role: 'role',+ adminFlags: 'adminFlags',+ videoQuota: 'videoQuota',+ videoQuotaDaily: 'videoQuotaDaily',+ language: 'language'+ }++ for (const modelKey of Object.keys(mappingKeys)) {+ const pluginOptionKey = mappingKeys[modelKey]++ const newValue = userUpdater({ fieldName: pluginOptionKey, currentValue: user[modelKey], newValue: userOptions[pluginOptionKey] })+ user.set(modelKey, newValue)+ }+ }++ {+ type AccountAttributeKeys = keyof Partial<AttributesOnly<AccountModel>>+ const mappingKeys: { [id in AccountAttributeKeys]?: AuthenticatedResultUpdaterFieldName } = {+ name: 'displayName'+ }++ for (const modelKey of Object.keys(mappingKeys)) {+ const optionKey = mappingKeys[modelKey]++ const newValue = userUpdater({ fieldName: optionKey, currentValue: user.Account[modelKey], newValue: userOptions[optionKey] })+ user.Account.set(modelKey, newValue)+ }+ }++ logger.debug('Updated user %s with plugin userUpdated function.', user.email, { user, userOptions })+ }++ if (userOptions.externalId && user.pluginAuthExternalId !== userOptions.externalId) {+ logger.info('Linking external id for user %s (plugin %s).', user.email, user.pluginAuth)+ user.set('pluginAuthExternalId', userOptions.externalId)+ }++ if (syncEmail && userOptions.email && user.email !== userOptions.email) {+ logger.info('Updating email of user %s to %s after successful external auth.', user.email, userOptions.email)+ user.email = userOptions.email+ }++ user.Account = await user.Account.save()++ return user.save()+}++// ---------------------------------------------------------------------------+// Private+// ---------------------------------------------------------------------------++function checkUserNotBlockedOrThrow (user: MUser, req: express.Request) {+ if (user.blocked) throw new AccountBlockedError(req.t('User is blocked.'))+}diff --git a/server/core/middlewares/auth.ts b/server/core/middlewares/auth.tsindex 9bd52d7c0d..d519af0c14 100644--- a/server/core/middlewares/auth.ts+++ b/server/core/middlewares/auth.ts@@ -1,11 +1,11 @@import { HttpStatusCode, HttpStatusCodeType, ServerErrorCodeType } from '@peertube/peertube-models'-import { getAccessToken } from '@server/lib/auth/oauth-model.js'+import { getAccessToken } from '@server/lib/auth/oauth-token.js'+import { UpdateTokenSessionScheduler } from '@server/lib/schedulers/update-token-session-scheduler.js'import { RunnerModel } from '@server/models/runner/runner.js'import express from 'express'import { Socket } from 'socket.io'import { logger } from '../helpers/logger.js'-import { handleOAuthAuthenticate } from '../lib/auth/oauth.js'-import { UpdateTokenSessionScheduler } from '@server/lib/schedulers/update-token-session-scheduler.js'+import { handleOAuthAuthenticate } from '../lib/auth/oauth-handlers.js'export function authenticate (req: express.Request, res: express.Response, next: express.NextFunction) {handleOAuthAuthenticate(req, res)