-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpressApp.js
317 lines (288 loc) · 11.2 KB
/
expressApp.js
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
const https = require('https')
const fs = require('fs')
const path = require('path')
const { createProbot } = require('probot')
const { createNodeMiddleware: createWebhooksMiddleware } = require('@octokit/webhooks')
const app = require('./index.js')
const { pino } = require('pino')
const { getTransformStream } = require('./lib/getPinoTransform')
const ecsFormat = require('@elastic/ecs-pino-format')
const pinoHttp = require('pino-http')
const { v4: uuidv4 } = require('uuid')
const isBase64 = require('is-base64')
const express = require('express')
const { githubAppJwt } = require('universal-github-app-jwt')
const { ProbotOctokit, getProbotOctoKitWithLog } = require('./lib/proxy-aware-probot-octokit')
// const { ProbotOctokit } = require('probot')
const ProxyAgent = require('proxy-agent')
const appInfo = require('./package.json')
const PolicyManager = require('./lib/policyManager')
const Validator = require('./lib/validator')
const EnvHelper = require('./lib/envHelper')
// Extract relevant Env vars
const {
appId,
privateKey,
webhookSecret,
logFormat,
logLevel,
logMessageKey,
logLevelInString,
csp,
cloudAvailabilityZone,
cloudInstanceId,
containerId,
applicationId,
productId,
productLineId,
organization,
environment
} = EnvHelper.getEnv()
const logOptions = {
logLevel: logLevel || 'trace',
logMessageKey: logMessageKey || 'msg',
logFormat: logFormat || 'json',
logLevelInString
}
const defaultLogEntries = {
csp,
cloud_availability_zone: cloudAvailabilityZone,
cloud_instance_id: cloudInstanceId,
container_id: containerId,
applicationid: applicationId,
productid: productId,
productlineid: productLineId,
organization,
environment
}
const appNameVersion = `${appInfo.name} (${appInfo.version})`
// Create Logger
const probotlog = getLog(logOptions).child(Object.assign({}, defaultLogEntries, { name: appNameVersion, childloggername: 'application' }))
// Get GitHub App private key
let privateKeyDecoded
if (isBase64(privateKey)) {
// Decode base64-encoded certificate
privateKeyDecoded = Buffer.from(privateKey, 'base64')
} else {
privateKeyDecoded = privateKey
}
const probotOptions = {
appId,
privateKey: privateKeyDecoded,
secret: webhookSecret,
log: probotlog,
name: 'probot',
Octokit: getProbotOctoKitWithLog(probotlog),
request: { agent: new ProxyAgent() }
}
// Creating the Probot App
const probotApp = createProbot({ overrides: probotOptions })
probotApp.load(app)
function createExpressApp () {
const expressApp = express()
// Express Handlers Configuration
expressApp.use(getLoggingMiddleware(probotlog))
// Not usual to handle any path, but for this app we are agnostic of anything in the path by default
expressApp.use(
'*',
createWebhooksMiddleware(probotApp.webhooks, {
path: '/'
})
)
// API to trigger a repository dispatch at the end of Migration
// and to trigger post migration tasks (loose coupling)
expressApp.get('/trigger/:repo/:branch', async (req, res, next) => {
const repo = req.params.repo
const branch = req.params.branch
try {
// Input validations
Validator.isValidRepoName(req.params.repo)
const context = await createContext(repo)
const runCheck = {
event_type: 'compliance-check',
client_payload: {
head_branch: branch
}
}
const report = await context.octokit.repos.createDispatchEvent(context.repo(runCheck))
res.send(`Triggered a repository dispatch of event_type 'compliance-check' for repo ${encodeURIComponent(repo)} with branch ${encodeURIComponent(branch)} and got response ${report.status}`)
} catch (error) {
if (error.status === 404) {
res.status(404).send(`Repository '${encodeURIComponent(repo)}' is not visibile to the Compliance App. \nPlease check if the repo exists and the app is installed on it`)
} else {
probotlog.error(`Unexpected error in the trigger endpoint handler ${error.stack}`)
res.status(500).send(`Unexpected error in the trigger endpoint handler for repo ${encodeURIComponent(repo)} with branch ${encodeURIComponent(branch)} ${encodeURIComponent(error.stack)}`)
}
}
})
// API to trigger a repository dispatch at the end of Migration
// and to trigger post migration tasks (loose coupling)
expressApp.get('/enable/:repo/', async (req, res, next) => {
const repo = req.params.repo
const branch = req.params.branch
try {
// Input validations
Validator.isValidRepoName(req.params.repo)
const context = await createContext(repo)
const enable = {
event_type: 'ghas-enable',
client_payload: {
createInitialCheck: true,
createBranchProtection: true,
enableAdvSec: true
}
}
const report = await context.octokit.repos.createDispatchEvent(context.repo(enable))
res.send(`Triggered a repository dispatch of event_type 'ghas-enable' for repo ${encodeURIComponent(repo)} and got response ${report.status}`)
} catch (error) {
if (error.status === 404) {
res.status(404).send(`Repository '${encodeURIComponent(repo)}' is not visibile to the Compliance App. \nPlease check if the repo exists and the app is installed on it`)
} else {
probotlog.error(`Unexpected error in the trigger endpoint handler ${error.stack}`)
res.status(500).send(`Unexpected error in the trigger endpoint handler for repo ${encodeURIComponent(repo)} with branch ${encodeURIComponent(branch)} ${encodeURIComponent(error.stack)}`)
}
}
})
expressApp.get('/health', async (req, res, next) => {
const output = []
await (async () => {
try {
output.push('=================================================================================\n')
output.push(` ${appNameVersion} Health Check\n`)
output.push('=================================================================================\n')
output.push(`Environment Vars = ${EnvHelper.toString()}\n`)
let privateKeyNew
if (isBase64(privateKey)) {
// Decode base64-encoded certificate
privateKeyNew = Buffer.from(privateKey, 'base64')
output.push(`Creating a JWT token using appId:${appId}\n privateKey:${privateKeyNew.subarray(0, 75)}...\n`)
} else {
privateKeyNew = privateKey
output.push(`Creating a JWT token using appId:${appId}\n privateKey:${privateKeyNew.slice(0, 75)}...\n`)
}
const { token } = await githubAppJwt({
id: appId,
privateKey: privateKeyNew
})
output.push(`Successfully generated a JWT token ${token.slice(0, 75)}...\n`)
const github = await probotApp.auth()
probotlog.debug('Fetching the 100 Webhook Deliveries')
let failedDeliveries = await github.apps.listWebhookDeliveries({ per_page: 100 })
// let deliveries = await basicOctokit.apps.listWebhookDeliveries({ per_page: 100 })
failedDeliveries = failedDeliveries.data.filter(delivery => { return delivery.status !== 'OK' })
output.push(`Failed Deliveries count (In the top 100 results) = ${failedDeliveries.length}\n`)
probotlog.debug('Fetching the App Installations')
const installations = await github.paginate(
github.apps.listInstallations.endpoint.merge({ per_page: 100 })
)
if (installations.length > 0) {
const installation = installations[0]
probotlog.debug(`Installation ID: ${installation.id}`)
probotlog.debug('Fetching the App Details')
const github = await probotApp.auth(installation.id)
const app = await github.apps.getAuthenticated()
// probotlog.debug(`App details = \n${JSON.stringify(app, null, 2)}`)
probotlog.debug(`Validated the app is configured properly = \n${JSON.stringify(app.data, null, 2)}`)
output.push(`Registered App name = ${app.data.slug}\n`)
output.push(`Permissions = ${JSON.stringify(app.data.permissions)}\n`)
output.push(`Events = ${app.data.events}\n`)
const context = {
payload: {
installation
},
octokit: github,
log: probotlog,
repo: (object) => {
return Object.assign(
{
owner: installation.account.login,
repo: ''
},
object
)
},
config: (filename) => { return null }
}
const policyManager = new PolicyManager(context, probotlog)
const runtime = await policyManager.getRuntimeSettings()
// const policyPath = await policyManager.getPolicyPath()
// const policy = await policyManager.getPolicy()
output.push(`Runtime settings = ${JSON.stringify(runtime, null, 2)}\n`)
// output.push(`PolicyPath = ${JSON.stringify(policyPath, null, 2)}\n`)
// output.push(`Policy = ${JSON.stringify(policy, null, 2)}\n`)
}
res.end(`${output}`.replace(/,/g, '\n'))
} catch (error) {
probotlog.error(`Unexpected error in the health endpoint handler ${error}`)
next(error)
}
})()
})
expressApp.get('/ping', async (req, res, next) => {
try {
probotlog.info('Received ping; sending pong')
res.end(`${appNameVersion}...PONG`)
} catch (error) {
probotlog.error(`Unexpected error in the ping endpoint handler ${error}`)
next(error)
}
})
return { expressApp, probotlog }
}
// Function Declarations
function getLog (options) {
const { logLevel, logMessageKey, ...getTransformStreamOptions } = options
const pinoOptions = {
level: logLevel || 'trace',
name: 'probot',
messageKey: logMessageKey || 'msg'
}
const transform = getTransformStream(getTransformStreamOptions)
transform.pipe(pino.destination(1))
return pino(Object.assign({}, pinoOptions, ecsFormat()))
}
function getLoggingMiddleware (logger) {
return pinoHttp({
logger: logger.child({ childloggername: 'http' }),
customSuccessMessage (res) {
const responseTime = Date.now() - res[pinoHttp.startTime]
return `${res.req.method} ${res.req.url} ${res.statusCode} - ${responseTime}ms`
},
customErrorMessage (_, res) {
const responseTime = Date.now() - res[pinoHttp.startTime]
return `${res.req.method} ${res.req.url} ${res.req.headers} ${res.statusCode} - ${responseTime}ms`
},
genReqId: (req) =>
req.headers['x-request-id'] ||
req.headers['x-github-delivery'] ||
uuidv4()
})
}
async function createContext (repo) {
probotlog.debug('Fetching installations')
let github = await probotApp.auth()
const installations = await github.paginate(
github.apps.listInstallations.endpoint.merge({ per_page: 100 })
)
const installation = installations[0]
probotlog.debug(`The installation for this app is ${JSON.stringify(installation)}`)
github = await probotApp.auth(installation.id)
const context = {
payload: {
installation
},
octokit: github,
log: probotlog,
repo: (object) => {
return Object.assign(
{
owner: installation.account.login,
repo
},
object
)
}
}
return context
}
module.exports = { createExpressApp }