Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(wip): add support for onedev as a provider #210

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
273 changes: 273 additions & 0 deletions src/git/onedev.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,273 @@
import debug from 'debug';
import * as crypto from "crypto"
import { Repo } from "./repo";
import { IWebhook, IRepository, IWebhookR, IDeploykeyR } from './types';
import axios from 'axios';
import { OneDevWrapper } from '../wrappers/onedev';
debug('app:kubero:onedev:api')

export class OneDevApi extends Repo {
private onedev: OneDevWrapper;

constructor(baseURL: string, username: string, token: string) {
super("onedev");
this.onedev = new OneDevWrapper(baseURL, username, token);
}

private async getProjectIdFromURL(oneDevUrl: string): Promise<number | null> {
let projectNameWithParents = '';
const parts = oneDevUrl.split('/');

for (let i = 1; i < parts.length; ++i) { // starting from 1 since 0th element would be baseURL
if (parts[i].startsWith('~')) break;
projectNameWithParents += '/' + parts[i];
}

projectNameWithParents = projectNameWithParents.slice(1);

// getting projectIds of all the parents since there can be multiple projects with a single name
let parentId: number | null = null;

projectNameWithParents.split('/').forEach(async (projectName: string, idx: number): Promise<void> => {
// no need of try-catch here since the wrapper handles that
const projects = await this.onedev.getProjectsFromName(projectName, parentId); // since the parentId of a top level project is null
console.log('projects', projects);

if (!projects || projects.length === 0) throw new Error(`Project with name ${projectName} and parentId ${parentId} not found`);
else if (projects.length > 1) throw new Error(`Multilple projects with name ${projectName} and parentId ${parentId} found, kindly provide the projectId directly.`);

parentId = projects[0].id;
});

return parentId;
}


protected async getRepository(gitrepo: string): Promise<IRepository> {
let ret: IRepository = {
status: 500,
statusText: 'error',
data: {
owner: 'unknown',
name: 'unknown',
admin: false,
push: false,
}
}

const projectId = await this.getProjectIdFromURL(gitrepo);

if (projectId === null || projectId === undefined) {
ret.status = 404;
ret.statusText = 'not found';
return ret;
};

const projectInfo = await this.onedev.getProjectInfoByProjectId(projectId);

// TODO: Need to discuss this with kubero's maintainer and if possible review onedev's API with them to make sure we get everything we need
ret = {
status: 200,
statusText: 'found',
data: {
id: projectId,
name: projectInfo.name,
description: projectInfo.description,
owner: this.onedev.username,
push: true,
admin: true,
default_branch: await this.onedev.getRepositoryDefaultBranch(projectId),
}
}

return ret;
}

protected async addWebhook(owner: string, repo: string, url: string, secret: string): Promise<IWebhookR> {

let ret: IWebhookR = {
status: 500,
statusText: 'error',
data: {
id: 0,
active: false,
created_at: '2020-01-01T00:00:00Z',
url: '',
insecure: true,
events: [],
}
}

//https://try.gitea.io/api/swagger#/repository/repoListHooks
const webhooksList = await this.onedev.repos.repoListHooks(owner, repo)
.catch((error: any) => {
console.log(error)
return ret;
})

// try to find the webhook
for (let webhook of webhooksList.data) {
if (webhook.config.url === url &&
webhook.config.content_type === 'json' &&
webhook.active === true) {
ret = {
status: 422,
statusText: 'found',
data: webhook,
}
return ret;
}
}
//console.log(webhooksList)

// create the webhook since it does not exist
try {

//https://try.gitea.io/api/swagger#/repository/repoCreateHook
let res = await this.onedev.repos.repoCreateHook(owner, repo, {
active: true,
config: {
url: url,
content_type: "json",
secret: secret,
insecure_ssl: '0'
},
events: [
"push",
"pull_request"
],
type: "gitea"
});

ret = {
status: res.status,
statusText: 'created',
data: {
id: res.data.id,
active: res.data.active,
created_at: res.data.created_at,
url: res.data.url,
insecure: res.data.config.insecure_ssl,
events: res.data.events,
}
}
} catch (e) {
console.log(e)
}
return ret;
}


protected async addDeployKey(owner: string, repo: string): Promise<IDeploykeyR> {

const keyPair = this.createDeployKeyPair();

const title: string = "bot@kubero." + crypto.randomBytes(4).toString('hex');

let ret: IDeploykeyR = {
status: 500,
statusText: 'error',
data: {
id: 0,
title: title,
verified: false,
created_at: new Date().toISOString(),
url: '',
read_only: true,
pub: keyPair.pubKeyBase64,
priv: keyPair.privKeyBase64
}
}

try {
//https://try.gitea.io/api/swagger#/repository/repoCreateKey
let res = await this.onedev.repos.repoCreateKey(owner, repo, {
title: title,
key: keyPair.pubKey,
read_only: true
});

ret = {
status: res.status,
statusText: 'created',
data: {
id: res.data.id,
title: res.data.title,
verified: res.data.verified,
created_at: res.data.created_at,
url: res.data.url,
read_only: res.data.read_only,
pub: keyPair.pubKeyBase64,
priv: keyPair.privKeyBase64
}
}
} catch (e) {
console.log(e)
}

return ret
}

public getWebhook(event: string, delivery: string, signature: string, body: any): IWebhook | boolean {
//https://docs.github.com/en/developers/webhooks-and-events/webhooks/securing-your-webhooks
let secret = process.env.KUBERO_WEBHOOK_SECRET as string;
let hash = 'sha256=' + crypto.createHmac('sha256', secret).update(JSON.stringify(body, null, ' ')).digest('hex')

let verified = false;
if (hash === signature) {
debug.debug('Gitea webhook signature is valid for event: ' + delivery);
verified = true;
} else {
debug.log('ERROR: invalid signature for event: ' + delivery);
debug.log('Hash: ' + hash);
debug.log('Signature: ' + signature);
verified = false;
return false;
}

let branch: string = 'main';
let ssh_url: string = '';
let action;
if (body.pull_request == undefined) {
let ref = body.ref
let refs = ref.split('/')
branch = refs[refs.length - 1]
ssh_url = body.repository.ssh_url
} else if (body.pull_request != undefined) {
action = body.action,
branch = body.pull_request.head.ref
ssh_url = body.pull_request.head.repo.ssh_url
} else {
ssh_url = body.repository.ssh_url
}

try {
let webhook: IWebhook = {
repoprovider: 'gitea',
action: action,
event: event,
delivery: delivery,
body: body,
branch: branch,
verified: verified,
repo: {
ssh_url: ssh_url,
}
}

return webhook;
} catch (error) {
console.log(error)
return false;
}
}

public async getBranches(gitrepo: string): Promise<string[]> {
// no need of try-catch here since the wrapper takes care of that
let projectId = await this.getProjectIdFromURL(gitrepo);
if (projectId === null || projectId === undefined) throw new Error('Failed to get projectId for project');

return await this.onedev.getProjectBranches(projectId as number);
}

}
30 changes: 15 additions & 15 deletions src/routes/pipelines.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import express, { Request, Response } from 'express';
import { Auth } from '../modules/auth';
import { gitLink } from '../types';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was searching for this one a while now 😄

import { IgitLink } from '../types';
import { IApp, IPipeline } from '../types';
import { App } from '../modules/application';
import { Webhooks } from '@octokit/webhooks';
Expand All @@ -12,7 +12,7 @@ auth.init();
export const authMiddleware = auth.getAuthMiddleware();
export const bearerMiddleware = auth.getBearerMiddleware();

Router.post('/cli/pipelines',bearerMiddleware, async function (req: Request, res: Response) {
Router.post('/cli/pipelines', bearerMiddleware, async function (req: Request, res: Response) {
// #swagger.tags = ['Pipeline']
// #swagger.summary = 'Create a new pipeline'
// #swagger.parameters['body'] = { in: 'body', description: 'Pipeline object', required: true, type: 'object' }
Expand All @@ -25,10 +25,10 @@ Router.post('/cli/pipelines',bearerMiddleware, async function (req: Request, res
}] */

const con = await req.app.locals.kubero.connectRepo(
req.body.git.repository.provider.toLowerCase(),
req.body.git.repository.ssh_url);
req.body.git.repository.provider.toLowerCase(),
req.body.git.repository.ssh_url);

let git: gitLink = {
let git: IgitLink = {
keys: {
priv: "Zm9v",
pub: "YmFy"
Expand All @@ -45,8 +45,8 @@ Router.post('/cli/pipelines',bearerMiddleware, async function (req: Request, res
console.log("ERROR: connecting Gitrepository", con.error);
} else {
git.keys = con.keys.data,
git.webhook = con.webhook.data,
git.repository = con.repository.data
git.webhook = con.webhook.data,
git.repository = con.repository.data
}

const buildpackList = req.app.locals.kubero.getBuildpacks()
Expand All @@ -67,7 +67,7 @@ Router.post('/cli/pipelines',bearerMiddleware, async function (req: Request, res
res.send(pipeline);
});

Router.post('/pipelines',authMiddleware, async function (req: Request, res: Response) {
Router.post('/pipelines', authMiddleware, async function (req: Request, res: Response) {
// #swagger.tags = ['UI']
// #swagger.summary = 'Create a new pipeline'
// #swagger.parameters['body'] = { in: 'body', description: 'Pipeline object', required: true, type: 'object' }
Expand All @@ -86,7 +86,7 @@ Router.post('/pipelines',authMiddleware, async function (req: Request, res: Resp
});


Router.put('/pipelines/:pipeline',authMiddleware, async function (req: Request, res: Response) {
Router.put('/pipelines/:pipeline', authMiddleware, async function (req: Request, res: Response) {
// #swagger.tags = ['UI']
// #swagger.summary = 'Edit a pipeline'
// #swagger.parameters['body'] = { in: 'body', description: 'Pipeline object', required: true, type: 'object' }
Expand Down Expand Up @@ -122,9 +122,9 @@ Router.get('/pipelines', authMiddleware, async function (req: Request, res: Resp
// #swagger.tags = ['UI']
// #swagger.summary = 'Get a list of available pipelines'
let pipelines = await req.app.locals.kubero.listPipelines()
.catch((err: any) => {
console.log(err)
});
.catch((err: any) => {
console.log(err)
});
res.send(pipelines);
});

Expand Down Expand Up @@ -153,7 +153,7 @@ Router.delete('/pipelines/:pipeline', authMiddleware, async function (req: Reque
// #swagger.tags = ['UI']
// #swagger.summary = 'Delete a pipeline'
await req.app.locals.kubero.deletePipeline(encodeURI(req.params.pipeline));
res.send("pipeline "+encodeURI(req.params.pipeline)+" deleted");
res.send("pipeline " + encodeURI(req.params.pipeline) + " deleted");
});

Router.delete('/cli/pipelines/:pipeline', bearerMiddleware, async function (req: Request, res: Response) {
Expand All @@ -167,7 +167,7 @@ Router.delete('/cli/pipelines/:pipeline', bearerMiddleware, async function (req:
}
}] */
await req.app.locals.kubero.deletePipeline(encodeURI(req.params.pipeline));
res.send("pipeline "+encodeURI(req.params.pipeline)+" deleted");
res.send("pipeline " + encodeURI(req.params.pipeline) + " deleted");
});

Router.delete('/pipelines/:pipeline/:phase/:app', authMiddleware, async function (req: Request, res: Response) {
Expand All @@ -194,7 +194,7 @@ Router.delete('/cli/pipelines/:pipeline/:phase/:app', bearerMiddleware, async fu
const phase = encodeURI(req.params.phase);
const app = encodeURI(req.params.app);
const response = {
message: "deleted "+pipeline+" "+phase+" "+app,
message: "deleted " + pipeline + " " + phase + " " + app,
pipeline: pipeline,
phase: phase,
app: app
Expand Down
Loading