|
| 1 | +/** |
| 2 | + * Copyright (c) 2022 Gitpod GmbH. All rights reserved. |
| 3 | + * Licensed under the Gitpod Enterprise Source Code License, |
| 4 | + * See License.enterprise.txt in the project root folder. |
| 5 | + */ |
| 6 | + |
| 7 | +import * as express from 'express'; |
| 8 | +import { createHmac } from 'crypto'; |
| 9 | +import { postConstruct, injectable, inject } from 'inversify'; |
| 10 | +import { ProjectDB, TeamDB, UserDB } from '@gitpod/gitpod-db/lib'; |
| 11 | +import { PrebuildManager } from '../prebuilds/prebuild-manager'; |
| 12 | +import { TraceContext } from '@gitpod/gitpod-protocol/lib/util/tracing'; |
| 13 | +import { TokenService } from '../../../src/user/token-service'; |
| 14 | +import { HostContextProvider } from '../../../src/auth/host-context-provider'; |
| 15 | +import { log } from '@gitpod/gitpod-protocol/lib/util/logging'; |
| 16 | +import { Project, StartPrebuildResult, User } from '@gitpod/gitpod-protocol'; |
| 17 | +import { GitHubService } from './github-service'; |
| 18 | +import { URL } from 'url'; |
| 19 | + |
| 20 | +@injectable() |
| 21 | +export class GitHubEnterpriseApp { |
| 22 | + |
| 23 | + @inject(UserDB) protected readonly userDB: UserDB; |
| 24 | + @inject(PrebuildManager) protected readonly prebuildManager: PrebuildManager; |
| 25 | + @inject(TokenService) protected readonly tokenService: TokenService; |
| 26 | + @inject(HostContextProvider) protected readonly hostContextProvider: HostContextProvider; |
| 27 | + @inject(ProjectDB) protected readonly projectDB: ProjectDB; |
| 28 | + @inject(TeamDB) protected readonly teamDB: TeamDB; |
| 29 | + |
| 30 | + protected _router = express.Router(); |
| 31 | + public static path = '/apps/ghe/'; |
| 32 | + |
| 33 | + @postConstruct() |
| 34 | + protected init() { |
| 35 | + this._router.post('/', async (req, res) => { |
| 36 | + const event = req.header('X-Github-Event'); |
| 37 | + if (event === 'push') { |
| 38 | + const payload = req.body as GitHubEnterprisePushPayload; |
| 39 | + const span = TraceContext.startSpan("GitHubEnterpriseApp.handleEvent", {}); |
| 40 | + span.setTag("payload", payload); |
| 41 | + let user: User | undefined; |
| 42 | + try { |
| 43 | + user = await this.findUser({ span }, payload, req); |
| 44 | + } catch (error) { |
| 45 | + log.error("Cannot find user.", error, { req }) |
| 46 | + } |
| 47 | + if (!user) { |
| 48 | + res.statusCode = 401; |
| 49 | + res.send(); |
| 50 | + return; |
| 51 | + } |
| 52 | + await this.handlePushHook({ span }, payload, user); |
| 53 | + } else { |
| 54 | + log.info("Unknown GitHub Enterprise event received", { event }); |
| 55 | + } |
| 56 | + res.send('OK'); |
| 57 | + }); |
| 58 | + } |
| 59 | + |
| 60 | + protected async findUser(ctx: TraceContext, payload: GitHubEnterprisePushPayload, req: express.Request): Promise<User> { |
| 61 | + const span = TraceContext.startSpan("GitHubEnterpriseApp.findUser", ctx); |
| 62 | + try { |
| 63 | + const host = req.header('X-Github-Enterprise-Host'); |
| 64 | + const hostContext = this.hostContextProvider.get(host || ''); |
| 65 | + if (!host || !hostContext) { |
| 66 | + throw new Error('Unsupported GitHub Enterprise host: ' + host); |
| 67 | + } |
| 68 | + const { authProviderId } = hostContext.authProvider; |
| 69 | + const authId = payload.sender.id; |
| 70 | + const user = await this.userDB.findUserByIdentity({ authProviderId, authId }); |
| 71 | + if (!user) { |
| 72 | + throw new Error(`No user found with identity ${authProviderId}/${authId}.`); |
| 73 | + } else if (!!user.blocked) { |
| 74 | + throw new Error(`Blocked user ${user.id} tried to start prebuild.`); |
| 75 | + } |
| 76 | + const gitpodIdentity = user.identities.find(i => i.authProviderId === TokenService.GITPOD_AUTH_PROVIDER_ID); |
| 77 | + if (!gitpodIdentity) { |
| 78 | + throw new Error(`User ${user.id} has no identity for '${TokenService.GITPOD_AUTH_PROVIDER_ID}'.`); |
| 79 | + } |
| 80 | + // Verify the webhook signature |
| 81 | + const signature = req.header('X-Hub-Signature-256'); |
| 82 | + const body = (req as any).rawBody; |
| 83 | + const tokenEntries = (await this.userDB.findTokensForIdentity(gitpodIdentity)).filter(tokenEntry => { |
| 84 | + return tokenEntry.token.scopes.includes(GitHubService.PREBUILD_TOKEN_SCOPE); |
| 85 | + }); |
| 86 | + const signingToken = tokenEntries.find(tokenEntry => { |
| 87 | + const sig = 'sha256=' + createHmac('sha256', user.id + '|' + tokenEntry.token.value) |
| 88 | + .update(body) |
| 89 | + .digest('hex'); |
| 90 | + return sig === signature; |
| 91 | + }); |
| 92 | + if (!signingToken) { |
| 93 | + throw new Error(`User ${user.id} has no token matching the payload signature.`); |
| 94 | + } |
| 95 | + return user; |
| 96 | + } finally { |
| 97 | + span.finish(); |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + protected async handlePushHook(ctx: TraceContext, payload: GitHubEnterprisePushPayload, user: User): Promise<StartPrebuildResult | undefined> { |
| 102 | + const span = TraceContext.startSpan("GitHubEnterpriseApp.handlePushHook", ctx); |
| 103 | + try { |
| 104 | + const contextURL = this.createContextUrl(payload); |
| 105 | + span.setTag('contextURL', contextURL); |
| 106 | + const config = await this.prebuildManager.fetchConfig({ span }, user, contextURL); |
| 107 | + if (!this.prebuildManager.shouldPrebuild(config)) { |
| 108 | + log.info('GitHub Enterprise push event: No config. No prebuild.'); |
| 109 | + return undefined; |
| 110 | + } |
| 111 | + |
| 112 | + log.debug('GitHub Enterprise push event: Starting prebuild.', { contextURL }); |
| 113 | + |
| 114 | + const cloneURL = payload.repository.clone_url; |
| 115 | + const projectAndOwner = await this.findProjectAndOwner(cloneURL, user); |
| 116 | + |
| 117 | + const ws = await this.prebuildManager.startPrebuild({ span }, { |
| 118 | + user: projectAndOwner.user, |
| 119 | + project: projectAndOwner?.project, |
| 120 | + branch: this.getBranchFromRef(payload.ref), |
| 121 | + contextURL, |
| 122 | + cloneURL, |
| 123 | + commit: payload.after, |
| 124 | + }); |
| 125 | + return ws; |
| 126 | + } finally { |
| 127 | + span.finish(); |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + /** |
| 132 | + * Finds the relevant user account and project to the provided webhook event information. |
| 133 | + * |
| 134 | + * First of all it tries to find the project for the given `cloneURL`, then it tries to |
| 135 | + * find the installer, which is also supposed to be a team member. As a fallback, it |
| 136 | + * looks for a team member which also has a connection with this GitHub Enterprise server. |
| 137 | + * |
| 138 | + * @param cloneURL of the webhook event |
| 139 | + * @param webhookInstaller the user account known from the webhook installation |
| 140 | + * @returns a promise which resolves to a user account and an optional project. |
| 141 | + */ |
| 142 | + protected async findProjectAndOwner(cloneURL: string, webhookInstaller: User): Promise<{ user: User, project?: Project }> { |
| 143 | + const project = await this.projectDB.findProjectByCloneUrl(cloneURL); |
| 144 | + if (project) { |
| 145 | + if (project.userId) { |
| 146 | + const user = await this.userDB.findUserById(project.userId); |
| 147 | + if (user) { |
| 148 | + return { user, project }; |
| 149 | + } |
| 150 | + } else if (project.teamId) { |
| 151 | + const teamMembers = await this.teamDB.findMembersByTeam(project.teamId || ''); |
| 152 | + if (teamMembers.some(t => t.userId === webhookInstaller.id)) { |
| 153 | + return { user: webhookInstaller, project }; |
| 154 | + } |
| 155 | + const hostContext = this.hostContextProvider.get(new URL(cloneURL).host); |
| 156 | + const authProviderId = hostContext?.authProvider.authProviderId; |
| 157 | + for (const teamMember of teamMembers) { |
| 158 | + const user = await this.userDB.findUserById(teamMember.userId); |
| 159 | + if (user && user.identities.some(i => i.authProviderId === authProviderId)) { |
| 160 | + return { user, project }; |
| 161 | + } |
| 162 | + } |
| 163 | + } |
| 164 | + } |
| 165 | + return { user: webhookInstaller }; |
| 166 | + } |
| 167 | + |
| 168 | + protected getBranchFromRef(ref: string): string | undefined { |
| 169 | + const headsPrefix = "refs/heads/"; |
| 170 | + if (ref.startsWith(headsPrefix)) { |
| 171 | + return ref.substring(headsPrefix.length); |
| 172 | + } |
| 173 | + |
| 174 | + return undefined; |
| 175 | + } |
| 176 | + |
| 177 | + protected createContextUrl(payload: GitHubEnterprisePushPayload) { |
| 178 | + return `${payload.repository.url}/tree/${this.getBranchFromRef(payload.ref)}`; |
| 179 | + } |
| 180 | + |
| 181 | + get router(): express.Router { |
| 182 | + return this._router; |
| 183 | + } |
| 184 | +} |
| 185 | + |
| 186 | +interface GitHubEnterprisePushPayload { |
| 187 | + ref: string; |
| 188 | + after: string; |
| 189 | + repository: { |
| 190 | + url: string; |
| 191 | + clone_url: string; |
| 192 | + }; |
| 193 | + sender: { |
| 194 | + login: string; |
| 195 | + id: string; |
| 196 | + }; |
| 197 | +} |
0 commit comments