-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathosoauth-service.ts
353 lines (298 loc) · 11.4 KB
/
osoauth-service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import { userService } from '@hawtio/react'
import * as fetchIntercept from 'fetch-intercept'
import $ from 'jquery'
import { OAuthProtoService, UserProfile } from '../api'
import { log } from '../globals'
import { CLUSTER_CONSOLE_KEY } from '../metadata'
import { fetchPath, getCookie, isBlank, redirect } from '../utils'
import {
CLUSTER_VERSION_KEY,
DEFAULT_CLUSTER_VERSION,
EXPIRES_IN_KEY,
OAUTH_OS_PROTOCOL_MODULE,
OBTAINED_AT_KEY,
OpenShiftOAuthConfig,
ResolveUser,
TOKEN_TYPE_KEY,
} from './globals'
import {
buildLoginUrl,
buildUserInfoUri,
checkToken,
currentTimeSeconds,
forceRelogin,
tokenHasExpired,
} from './support'
interface UserObject {
kind: string
apiVersion: string
metadata: {
name: string
selfLink: string
creationTimestamp: string | null
}
groups: string[]
}
interface Headers {
Authorization: string
'X-XSRF-TOKEN'?: string
}
export class OSOAuthService implements OAuthProtoService {
private userInfoUri = ''
private keepaliveInterval = 10
private keepAliveHandler: NodeJS.Timeout | null = null
private userProfile: UserProfile
private readonly adaptedConfig: Promise<OpenShiftOAuthConfig | null>
private readonly login: Promise<boolean>
private fetchUnregister: (() => void) | null
constructor(openShiftConfig: OpenShiftOAuthConfig, userProfile: UserProfile) {
log.debug('Initialising Openshift OAuth Service')
this.userProfile = userProfile
this.userProfile.setOAuthType(OAUTH_OS_PROTOCOL_MODULE)
this.adaptedConfig = this.processConfig(openShiftConfig)
this.login = this.createLogin()
this.fetchUnregister = null
}
private async processConfig(config: OpenShiftOAuthConfig): Promise<OpenShiftOAuthConfig | null> {
if (!config) {
this.userProfile.setError(new Error('Cannot find the openshift auth configuration'))
return null
}
log.debug('OS OAuth config to be processed: ', config)
if (config.oauth_authorize_uri) return config
// Try to fetch authorize uri from metadata uri
if (!config.oauth_metadata_uri) {
this.userProfile.setError(new Error('Cannot determine authorize uri as no metadata uri'))
return null
}
// See if web_console_url has been added to config
if (config.web_console_url && config.web_console_url.length > 0) {
log.debug(`Adding web console URI to user profile ${config.web_console_url}`)
this.userProfile.addMetadata(CLUSTER_CONSOLE_KEY, config.web_console_url)
}
log.debug('Fetching OAuth server metadata from:', config.oauth_metadata_uri)
return fetchPath<OpenShiftOAuthConfig | null>(config.oauth_metadata_uri, {
success: (data: string) => {
log.debug('Loaded', config.oauth_metadata_uri, ':', data)
const metadata = JSON.parse(data)
config.oauth_authorize_uri = metadata.authorization_endpoint
config.issuer = metadata.issuer
if (isBlank(config.oauth_authorize_uri) || isBlank(config.oauth_client_id)) {
this.userProfile.setError(new Error('Invalid openshift auth config'))
return null
}
this.userInfoUri = buildUserInfoUri(this.userProfile.getMasterUri(), config)
return config
},
error: err => {
const e: Error = new Error('Failed to contact the oauth metadata uri', { cause: err })
this.userProfile.setError(e)
return null
},
})
}
private setupFetch(config: OpenShiftOAuthConfig) {
if (!config || this.userProfile.hasError()) {
return
}
log.debug('Intercept Fetch API to attach Openshift auth token to authorization header')
const unregister = fetchIntercept.register({
request: (url, config) => {
log.debug('Fetch intercepted for oAuth authentication')
if (tokenHasExpired(this.userProfile)) {
const reason = `Cannot navigate to ${url} as token expired so need to logout`
log.debug(reason)
// Unregister this fetch handler before logging out
unregister()
this.doLogout(config)
}
let headers: Headers = {
Authorization: `Bearer ${this.userProfile.getToken()}`,
}
// For CSRF protection with Spring Security
const token = getCookie('XSRF-TOKEN')
if (token) {
log.debug('Set XSRF token header from cookies')
headers = {
...headers,
'X-XSRF-TOKEN': token,
}
}
return [url, { headers, ...config }]
},
})
}
private setupJQueryAjax(config: OpenShiftOAuthConfig) {
if (!config || this.userProfile.hasError()) {
return
}
log.debug('Set authorization header to Openshift auth token for AJAX requests')
const beforeSend = (xhr: JQueryXHR, settings: JQueryAjaxSettings) => {
if (tokenHasExpired(this.userProfile)) {
log.debug(`Cannot navigate to ${settings.url} as token expired so need to logout`)
this.doLogout(config)
return
}
// Set bearer token is used
xhr.setRequestHeader('Authorization', `Bearer ${this.userProfile.getToken()}`)
// For CSRF protection with Spring Security
const token = getCookie('XSRF-TOKEN')
if (token) {
log.debug('Set XSRF token header from cookies')
xhr.setRequestHeader('X-XSRF-TOKEN', token)
}
return // To suppress ts(7030)
}
$.ajaxSetup({ beforeSend })
}
private setupKeepAlive(config: OpenShiftOAuthConfig) {
const keepAlive = async () => {
log.debug('Running oAuth keepAlive function')
const response = await fetch(this.userInfoUri, { method: 'GET' })
if (response.ok) {
const keepaliveJson = await response.json()
if (!keepaliveJson) {
this.userProfile.setError(new Error('Cannot parse the keepalive json response'))
return
}
const obtainedAt = this.userProfile.metadataValue<number>(OBTAINED_AT_KEY) || 0
const expiry = this.userProfile.metadataValue<number>(EXPIRES_IN_KEY) || 0
if (obtainedAt) {
const remainingTime = obtainedAt + expiry - currentTimeSeconds()
if (remainingTime > 0) {
this.keepaliveInterval = Math.min(Math.round(remainingTime / 4), 24 * 60 * 60)
log.debug('Resetting keepAlive interval to ' + this.keepaliveInterval)
}
}
if (!this.keepaliveInterval) {
this.keepaliveInterval = 10
}
log.debug('userProfile:', this.userProfile)
} else {
log.debug('keepAlive response failure so re-login')
// The request may have been cancelled as the browser refresh request in
// extractToken may be triggered before getting the AJAX response.
// In that case, let's just skip the error and go through another refresh cycle.
// See http://stackoverflow.com/questions/2000609/jquery-ajax-status-code-0 for more details.
log.error('Failed to fetch user info, status: ', response.statusText)
this.doLogout(config)
}
}
this.keepAliveHandler = setTimeout(keepAlive, this.keepaliveInterval)
}
private clearKeepAlive() {
if (!this.keepAliveHandler) return
clearTimeout(this.keepAliveHandler)
this.keepAliveHandler = null
}
private checkTokenExpired(config: OpenShiftOAuthConfig) {
if (!this.userProfile.hasToken()) return true // no token so must be expired
if (tokenHasExpired(this.userProfile)) {
log.debug('Token has expired so logging out')
this.doLogout(config)
return true
}
log.debug('User Profile has good token so nothing to do')
return false
}
private async createLogin(): Promise<boolean> {
const config = await this.adaptedConfig
if (!config) {
return false
}
if (this.userProfile.hasError()) {
log.debug('Cannot login as user profile has an error: ', this.userProfile.getError())
return false
}
const currentURI = new URL(window.location.href)
try {
this.clearKeepAlive()
log.debug('Checking token for validity')
const tokenParams = await checkToken(currentURI)
if (!tokenParams) {
log.debug('No Token so initiating new login')
this.tryLogin(config, currentURI)
return false
}
log.debug('Populating user profile with token metadata')
/* Populate the profile with the new token */
this.userProfile.addMetadata<number>(EXPIRES_IN_KEY, tokenParams.expires_in || 0)
this.userProfile.addMetadata<string>(TOKEN_TYPE_KEY, tokenParams.token_type || '')
this.userProfile.addMetadata<number>(OBTAINED_AT_KEY, tokenParams.obtainedAt || 0)
this.userProfile.setToken(tokenParams.access_token || '')
if (this.checkTokenExpired(config)) return false
/* Promote the hawtio mode to expose to third-parties */
log.debug('Adding cluster version to profile metadata')
this.userProfile.addMetadata<string>(CLUSTER_VERSION_KEY, config.cluster_version || DEFAULT_CLUSTER_VERSION)
// Need fetch for keepalive
this.setupFetch(config)
this.setupJQueryAjax(config)
this.setupKeepAlive(config)
return true
} catch (error) {
this.userProfile.setError(error instanceof Error ? error : new Error('Error from checking token'))
return false
}
}
private tryLogin(config: OpenShiftOAuthConfig, uri: URL) {
const targetUri = buildLoginUrl(config, { uri: uri.toString() })
redirect(targetUri)
}
private doLogout(config: OpenShiftOAuthConfig): void {
if (this.fetchUnregister) this.fetchUnregister()
const currentURI = new URL(window.location.href)
// The following request returns 403 when delegated authentication with an
// OAuthClient is used, as possible scopes do not grant permissions to access the OAuth API:
// See https://github.com/openshift/origin/issues/7011
//
// So little point in trying to delete the token. Lets do in client-side only
//
forceRelogin(currentURI, config)
}
async isLoggedIn(): Promise<boolean> {
return await this.login
}
registerUserHooks() {
log.debug('Registering oAuth user hooks')
const fetchUser = async (resolve: ResolveUser) => {
const config = await this.adaptedConfig
const login = await this.login
if (!config || !login || this.userProfile.hasError()) {
resolve({ username: '', isLogin: false })
return false
}
if (this.userProfile.getToken()) {
const userInfo = await fetchPath<UserObject | null>(this.userInfoUri, {
success: (data: string) => {
return JSON.parse(data)
},
error: () => null,
})
let username = this.userProfile.getToken() // default
if (userInfo && userInfo.metadata?.name) {
username = userInfo.metadata?.name
}
resolve({ username: username, isLogin: true })
userService.setToken(this.userProfile.getToken())
}
return true
}
userService.addFetchUserHook(OAUTH_OS_PROTOCOL_MODULE, fetchUser)
const logout = async () => {
log.debug('Running oAuth logout hook')
const config = await this.adaptedConfig
const login = await this.login
if (!config || !login || this.userProfile.hasError()) {
return false
}
log.info('Log out Openshift')
try {
this.doLogout(config)
} catch (error) {
log.error('Error logging out Openshift:', error)
}
return true
}
userService.addLogoutHook(OAUTH_OS_PROTOCOL_MODULE, logout)
}
}