diff options
Diffstat (limited to 'server/lib/auth.ts')
-rw-r--r-- | server/lib/auth.ts | 286 |
1 files changed, 286 insertions, 0 deletions
diff --git a/server/lib/auth.ts b/server/lib/auth.ts new file mode 100644 index 000000000..8579bdbb4 --- /dev/null +++ b/server/lib/auth.ts | |||
@@ -0,0 +1,286 @@ | |||
1 | import { isUserDisplayNameValid, isUserRoleValid, isUserUsernameValid } from '@server/helpers/custom-validators/users' | ||
2 | import { logger } from '@server/helpers/logger' | ||
3 | import { generateRandomString } from '@server/helpers/utils' | ||
4 | import { OAUTH_LIFETIME, PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME } from '@server/initializers/constants' | ||
5 | import { revokeToken } from '@server/lib/oauth-model' | ||
6 | import { PluginManager } from '@server/lib/plugins/plugin-manager' | ||
7 | import { OAuthTokenModel } from '@server/models/oauth/oauth-token' | ||
8 | import { UserRole } from '@shared/models' | ||
9 | import { | ||
10 | RegisterServerAuthenticatedResult, | ||
11 | RegisterServerAuthPassOptions, | ||
12 | RegisterServerExternalAuthenticatedResult | ||
13 | } from '@shared/models/plugins/register-server-auth.model' | ||
14 | import * as express from 'express' | ||
15 | import * as OAuthServer from 'express-oauth-server' | ||
16 | |||
17 | const oAuthServer = new OAuthServer({ | ||
18 | useErrorHandler: true, | ||
19 | accessTokenLifetime: OAUTH_LIFETIME.ACCESS_TOKEN, | ||
20 | refreshTokenLifetime: OAUTH_LIFETIME.REFRESH_TOKEN, | ||
21 | continueMiddleware: true, | ||
22 | model: require('./oauth-model') | ||
23 | }) | ||
24 | |||
25 | // Token is the key, expiration date is the value | ||
26 | const authBypassTokens = new Map<string, { | ||
27 | expires: Date | ||
28 | user: { | ||
29 | username: string | ||
30 | email: string | ||
31 | displayName: string | ||
32 | role: UserRole | ||
33 | } | ||
34 | authName: string | ||
35 | npmName: string | ||
36 | }>() | ||
37 | |||
38 | async function handleLogin (req: express.Request, res: express.Response, next: express.NextFunction) { | ||
39 | const grantType = req.body.grant_type | ||
40 | |||
41 | if (grantType === 'password') { | ||
42 | if (req.body.externalAuthToken) proxifyExternalAuthBypass(req, res) | ||
43 | else await proxifyPasswordGrant(req, res) | ||
44 | } else if (grantType === 'refresh_token') { | ||
45 | await proxifyRefreshGrant(req, res) | ||
46 | } | ||
47 | |||
48 | return forwardTokenReq(req, res, next) | ||
49 | } | ||
50 | |||
51 | async function handleTokenRevocation (req: express.Request, res: express.Response) { | ||
52 | const token = res.locals.oauth.token | ||
53 | |||
54 | res.locals.explicitLogout = true | ||
55 | await revokeToken(token) | ||
56 | |||
57 | // FIXME: uncomment when https://github.com/oauthjs/node-oauth2-server/pull/289 is released | ||
58 | // oAuthServer.revoke(req, res, err => { | ||
59 | // if (err) { | ||
60 | // logger.warn('Error in revoke token handler.', { err }) | ||
61 | // | ||
62 | // return res.status(err.status) | ||
63 | // .json({ | ||
64 | // error: err.message, | ||
65 | // code: err.name | ||
66 | // }) | ||
67 | // .end() | ||
68 | // } | ||
69 | // }) | ||
70 | |||
71 | return res.json() | ||
72 | } | ||
73 | |||
74 | async function onExternalUserAuthenticated (options: { | ||
75 | npmName: string | ||
76 | authName: string | ||
77 | authResult: RegisterServerExternalAuthenticatedResult | ||
78 | }) { | ||
79 | const { npmName, authName, authResult } = options | ||
80 | |||
81 | if (!authResult.req || !authResult.res) { | ||
82 | logger.error('Cannot authenticate external user for auth %s of plugin %s: no req or res are provided.', authName, npmName) | ||
83 | return | ||
84 | } | ||
85 | |||
86 | const { res } = authResult | ||
87 | |||
88 | if (!isAuthResultValid(npmName, authName, authResult)) { | ||
89 | res.redirect('/login?externalAuthError=true') | ||
90 | return | ||
91 | } | ||
92 | |||
93 | logger.info('Generating auth bypass token for %s in auth %s of plugin %s.', authResult.username, authName, npmName) | ||
94 | |||
95 | const bypassToken = await generateRandomString(32) | ||
96 | |||
97 | const expires = new Date() | ||
98 | expires.setTime(expires.getTime() + PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME) | ||
99 | |||
100 | const user = buildUserResult(authResult) | ||
101 | authBypassTokens.set(bypassToken, { | ||
102 | expires, | ||
103 | user, | ||
104 | npmName, | ||
105 | authName | ||
106 | }) | ||
107 | |||
108 | // Cleanup | ||
109 | const now = new Date() | ||
110 | for (const [ key, value ] of authBypassTokens) { | ||
111 | if (value.expires.getTime() < now.getTime()) { | ||
112 | authBypassTokens.delete(key) | ||
113 | } | ||
114 | } | ||
115 | |||
116 | res.redirect(`/login?externalAuthToken=${bypassToken}&username=${user.username}`) | ||
117 | } | ||
118 | |||
119 | // --------------------------------------------------------------------------- | ||
120 | |||
121 | export { oAuthServer, handleLogin, onExternalUserAuthenticated, handleTokenRevocation } | ||
122 | |||
123 | // --------------------------------------------------------------------------- | ||
124 | |||
125 | function forwardTokenReq (req: express.Request, res: express.Response, next?: express.NextFunction) { | ||
126 | return oAuthServer.token()(req, res, err => { | ||
127 | if (err) { | ||
128 | logger.warn('Login error.', { err }) | ||
129 | |||
130 | return res.status(err.status) | ||
131 | .json({ | ||
132 | error: err.message, | ||
133 | code: err.name | ||
134 | }) | ||
135 | } | ||
136 | |||
137 | if (next) return next() | ||
138 | }) | ||
139 | } | ||
140 | |||
141 | async function proxifyRefreshGrant (req: express.Request, res: express.Response) { | ||
142 | const refreshToken = req.body.refresh_token | ||
143 | if (!refreshToken) return | ||
144 | |||
145 | const tokenModel = await OAuthTokenModel.loadByRefreshToken(refreshToken) | ||
146 | if (tokenModel?.authName) res.locals.refreshTokenAuthName = tokenModel.authName | ||
147 | } | ||
148 | |||
149 | async function proxifyPasswordGrant (req: express.Request, res: express.Response) { | ||
150 | const plugins = PluginManager.Instance.getIdAndPassAuths() | ||
151 | const pluginAuths: { npmName?: string, registerAuthOptions: RegisterServerAuthPassOptions }[] = [] | ||
152 | |||
153 | for (const plugin of plugins) { | ||
154 | const auths = plugin.idAndPassAuths | ||
155 | |||
156 | for (const auth of auths) { | ||
157 | pluginAuths.push({ | ||
158 | npmName: plugin.npmName, | ||
159 | registerAuthOptions: auth | ||
160 | }) | ||
161 | } | ||
162 | } | ||
163 | |||
164 | pluginAuths.sort((a, b) => { | ||
165 | const aWeight = a.registerAuthOptions.getWeight() | ||
166 | const bWeight = b.registerAuthOptions.getWeight() | ||
167 | |||
168 | // DESC weight order | ||
169 | if (aWeight === bWeight) return 0 | ||
170 | if (aWeight < bWeight) return 1 | ||
171 | return -1 | ||
172 | }) | ||
173 | |||
174 | const loginOptions = { | ||
175 | id: req.body.username, | ||
176 | password: req.body.password | ||
177 | } | ||
178 | |||
179 | for (const pluginAuth of pluginAuths) { | ||
180 | const authOptions = pluginAuth.registerAuthOptions | ||
181 | const authName = authOptions.authName | ||
182 | const npmName = pluginAuth.npmName | ||
183 | |||
184 | logger.debug( | ||
185 | 'Using auth method %s of plugin %s to login %s with weight %d.', | ||
186 | authName, npmName, loginOptions.id, authOptions.getWeight() | ||
187 | ) | ||
188 | |||
189 | try { | ||
190 | const loginResult = await authOptions.login(loginOptions) | ||
191 | |||
192 | if (!loginResult) continue | ||
193 | if (!isAuthResultValid(pluginAuth.npmName, authOptions.authName, loginResult)) continue | ||
194 | |||
195 | logger.info( | ||
196 | 'Login success with auth method %s of plugin %s for %s.', | ||
197 | authName, npmName, loginOptions.id | ||
198 | ) | ||
199 | |||
200 | res.locals.bypassLogin = { | ||
201 | bypass: true, | ||
202 | pluginName: pluginAuth.npmName, | ||
203 | authName: authOptions.authName, | ||
204 | user: buildUserResult(loginResult) | ||
205 | } | ||
206 | |||
207 | return | ||
208 | } catch (err) { | ||
209 | logger.error('Error in auth method %s of plugin %s', authOptions.authName, pluginAuth.npmName, { err }) | ||
210 | } | ||
211 | } | ||
212 | } | ||
213 | |||
214 | function proxifyExternalAuthBypass (req: express.Request, res: express.Response) { | ||
215 | const obj = authBypassTokens.get(req.body.externalAuthToken) | ||
216 | if (!obj) { | ||
217 | logger.error('Cannot authenticate user with unknown bypass token') | ||
218 | return res.sendStatus(400) | ||
219 | } | ||
220 | |||
221 | const { expires, user, authName, npmName } = obj | ||
222 | |||
223 | const now = new Date() | ||
224 | if (now.getTime() > expires.getTime()) { | ||
225 | logger.error('Cannot authenticate user with an expired external auth token') | ||
226 | return res.sendStatus(400) | ||
227 | } | ||
228 | |||
229 | if (user.username !== req.body.username) { | ||
230 | logger.error('Cannot authenticate user %s with invalid username %s.', req.body.username) | ||
231 | return res.sendStatus(400) | ||
232 | } | ||
233 | |||
234 | // Bypass oauth library validation | ||
235 | req.body.password = 'fake' | ||
236 | |||
237 | logger.info( | ||
238 | 'Auth success with external auth method %s of plugin %s for %s.', | ||
239 | authName, npmName, user.email | ||
240 | ) | ||
241 | |||
242 | res.locals.bypassLogin = { | ||
243 | bypass: true, | ||
244 | pluginName: npmName, | ||
245 | authName: authName, | ||
246 | user | ||
247 | } | ||
248 | } | ||
249 | |||
250 | function isAuthResultValid (npmName: string, authName: string, result: RegisterServerAuthenticatedResult) { | ||
251 | if (!isUserUsernameValid(result.username)) { | ||
252 | logger.error('Auth method %s of plugin %s did not provide a valid username.', authName, npmName, { username: result.username }) | ||
253 | return false | ||
254 | } | ||
255 | |||
256 | if (!result.email) { | ||
257 | logger.error('Auth method %s of plugin %s did not provide a valid email.', authName, npmName, { email: result.email }) | ||
258 | return false | ||
259 | } | ||
260 | |||
261 | // role is optional | ||
262 | if (result.role && !isUserRoleValid(result.role)) { | ||
263 | logger.error('Auth method %s of plugin %s did not provide a valid role.', authName, npmName, { role: result.role }) | ||
264 | return false | ||
265 | } | ||
266 | |||
267 | // display name is optional | ||
268 | if (result.displayName && !isUserDisplayNameValid(result.displayName)) { | ||
269 | logger.error( | ||
270 | 'Auth method %s of plugin %s did not provide a valid display name.', | ||
271 | authName, npmName, { displayName: result.displayName } | ||
272 | ) | ||
273 | return false | ||
274 | } | ||
275 | |||
276 | return true | ||
277 | } | ||
278 | |||
279 | function buildUserResult (pluginResult: RegisterServerAuthenticatedResult) { | ||
280 | return { | ||
281 | username: pluginResult.username, | ||
282 | email: pluginResult.email, | ||
283 | role: pluginResult.role ?? UserRole.USER, | ||
284 | displayName: pluginResult.displayName || pluginResult.username | ||
285 | } | ||
286 | } | ||