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

Secure https plugins #48

Merged
merged 5 commits into from
Jun 4, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
23 changes: 23 additions & 0 deletions src/github/github-event-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,29 @@ export class GitHubEventHandler {
});
}

async importRsaPrivateKey(pem: string) {
const pemContents = pem.replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "").trim();
const binaryDer = Uint8Array.from(atob(pemContents), (c) => c.charCodeAt(0));

return await crypto.subtle.importKey(
"pkcs8",
binaryDer.buffer,
{
name: "RSASSA-PKCS1-v1_5",
hash: "SHA-256",
},
true,
["sign"]
);
}

async signPayload(payload: string) {
const data = new TextEncoder().encode(payload);
const privateKey = await this.importRsaPrivateKey(this._privateKey);
const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, data);
return btoa(String.fromCharCode(...new Uint8Array(signature)));
}

transformEvent(event: EmitterWebhookEvent) {
if ("installation" in event.payload && event.payload.installation?.id !== undefined) {
const octokit = this.getAuthenticatedOctokit(event.payload.installation.id);
Expand Down
8 changes: 4 additions & 4 deletions src/github/handlers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { GitHubEventHandler } from "../github-event-handler";
import { getConfig } from "../utils/config";
import { repositoryDispatch } from "./repository-dispatch";
import { dispatchWorker, dispatchWorkflow, getDefaultBranch } from "../utils/workflow-dispatch";
import { DelegatedComputeInputs } from "../types/plugin";
import { PluginInput } from "../types/plugin";
import { isGithubPlugin, PluginConfiguration } from "../types/plugin-configuration";

function tryCatchWrapper(fn: (event: EmitterWebhookEvent) => unknown) {
Expand Down Expand Up @@ -86,20 +86,20 @@ async function handleEvent(event: EmitterWebhookEvent, eventHandler: InstanceTyp

const ref = isGithubPluginObject ? plugin.ref ?? (await getDefaultBranch(context, plugin.owner, plugin.repo)) : plugin;
const token = await eventHandler.getToken(event.payload.installation.id);
const inputs = new DelegatedComputeInputs(stateId, context.key, event.payload, settings, token, ref);
const inputs = new PluginInput(context.eventHandler, stateId, context.key, event.payload, settings, token, ref);

state.inputs[0] = inputs;
await eventHandler.pluginChainState.put(stateId, state);

if (!isGithubPluginObject) {
await dispatchWorker(plugin, inputs.getInputs());
await dispatchWorker(plugin, await inputs.getWorkerInputs());
} else {
await dispatchWorkflow(context, {
owner: plugin.owner,
repository: plugin.repo,
workflowId: plugin.workflowId,
ref: plugin.ref,
inputs: inputs.getInputs(),
inputs: inputs.getWorkflowInputs(),
});
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/github/handlers/repository-dispatch.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { GitHubContext } from "../github-context";
import { dispatchWorker, dispatchWorkflow, getDefaultBranch } from "../utils/workflow-dispatch";
import { Value } from "@sinclair/typebox/value";
import { DelegatedComputeInputs, PluginChainState, expressionRegex, pluginOutputSchema } from "../types/plugin";
import { PluginInput, PluginChainState, expressionRegex, pluginOutputSchema } from "../types/plugin";
import { isGithubPlugin } from "../types/plugin-configuration";

export async function repositoryDispatch(context: GitHubContext<"repository_dispatch">) {
Expand Down Expand Up @@ -61,7 +61,7 @@ export async function repositoryDispatch(context: GitHubContext<"repository_disp
} else {
ref = nextPlugin.plugin;
}
const inputs = new DelegatedComputeInputs(pluginOutput.state_id, state.eventName, state.eventPayload, settings, token, ref);
const inputs = new PluginInput(context.eventHandler, pluginOutput.state_id, state.eventName, state.eventPayload, settings, token, ref);

state.currentPlugin++;
state.inputs[state.currentPlugin] = inputs;
Expand All @@ -73,10 +73,10 @@ export async function repositoryDispatch(context: GitHubContext<"repository_disp
repository: nextPlugin.plugin.repo,
ref: nextPlugin.plugin.ref,
workflowId: nextPlugin.plugin.workflowId,
inputs: inputs.getInputs(),
inputs: inputs.getWorkflowInputs(),
});
} else {
await dispatchWorker(nextPlugin.plugin, inputs.getInputs());
await dispatchWorker(nextPlugin.plugin, await inputs.getWorkerInputs());
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/github/types/plugin-configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const pluginChainSchema = T.Array(
id: T.Optional(T.String()),
plugin: githubPluginType(),
type: T.Union([T.Literal("github")], { default: "github" }),
with: T.Record(T.String(), T.Unknown()),
with: T.Record(T.String(), T.Unknown(), { default: {} }),
}),
{ minItems: 1 }
);
Expand Down
35 changes: 31 additions & 4 deletions src/github/types/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { EmitterWebhookEvent, EmitterWebhookEventName } from "@octokit/webhooks";
import { StaticDecode, Type } from "@sinclair/typebox";
import { PluginChain } from "./plugin-configuration";
import { GitHubEventHandler } from "../github-event-handler";

export const expressionRegex = /^\s*\${{\s*(\S+)\s*}}\s*$/;

Expand All @@ -17,15 +18,25 @@ export const pluginOutputSchema = Type.Object({

export type PluginOutput = StaticDecode<typeof pluginOutputSchema>;

export class DelegatedComputeInputs<T extends EmitterWebhookEventName = EmitterWebhookEventName> {
export class PluginInput<T extends EmitterWebhookEventName = EmitterWebhookEventName> {
public eventHandler: GitHubEventHandler;
public stateId: string;
public eventName: T;
public eventPayload: EmitterWebhookEvent<T>["payload"];
public settings: unknown;
public authToken: string;
public ref: string;

constructor(stateId: string, eventName: T, eventPayload: EmitterWebhookEvent<T>["payload"], settings: unknown, authToken: string, ref: string) {
constructor(
eventHandler: GitHubEventHandler,
stateId: string,
eventName: T,
eventPayload: EmitterWebhookEvent<T>["payload"],
settings: unknown,
authToken: string,
ref: string
) {
this.eventHandler = eventHandler;
this.stateId = stateId;
this.eventName = eventName;
this.eventPayload = eventPayload;
Expand All @@ -34,7 +45,7 @@ export class DelegatedComputeInputs<T extends EmitterWebhookEventName = EmitterW
this.ref = ref;
}

public getInputs() {
public getWorkflowInputs() {
return {
stateId: this.stateId,
eventName: this.eventName,
Expand All @@ -44,6 +55,22 @@ export class DelegatedComputeInputs<T extends EmitterWebhookEventName = EmitterW
ref: this.ref,
};
}

public async getWorkerInputs() {
const inputs = {
stateId: this.stateId,
eventName: this.eventName,
eventPayload: this.eventPayload,
settings: this.settings,
authToken: this.authToken,
ref: this.ref,
};
const signature = await this.eventHandler.signPayload(JSON.stringify(inputs));
return {
...inputs,
signature,
};
}
}

export type PluginChainState<T extends EmitterWebhookEventName = EmitterWebhookEventName> = {
Expand All @@ -52,6 +79,6 @@ export type PluginChainState<T extends EmitterWebhookEventName = EmitterWebhookE
eventPayload: EmitterWebhookEvent<T>["payload"];
currentPlugin: number;
pluginChain: PluginChain;
inputs: DelegatedComputeInputs[];
inputs: PluginInput[];
outputs: PluginOutput[];
};
3 changes: 1 addition & 2 deletions src/github/utils/config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Value } from "@sinclair/typebox/value";
import { generateConfiguration } from "@ubiquibot/configuration";
gentlementlegen marked this conversation as resolved.
Show resolved Hide resolved
import YAML from "yaml";
import { GitHubContext } from "../github-context";
import { expressionRegex } from "../types/plugin";
Expand All @@ -10,7 +9,7 @@ const UBIQUIBOT_CONFIG_FULL_PATH = ".github/.ubiquibot-config.yml";

export async function getConfig(context: GitHubContext): Promise<PluginConfiguration> {
const payload = context.payload;
const defaultConfiguration = generateConfiguration();
const defaultConfiguration = Value.Decode(configSchema, Value.Default(configSchema, {}));
if (!("repository" in payload) || !payload.repository) {
console.warn("Repository is not defined");
return defaultConfiguration;
Expand Down
2 changes: 1 addition & 1 deletion src/github/utils/workflow-dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export async function dispatchWorkflow(context: GitHubContext, options: Workflow
});
}

export async function dispatchWorker(targetUrl: string, payload: WorkflowDispatchOptions["inputs"]) {
export async function dispatchWorker(targetUrl: string, payload?: { [key: string]: unknown }) {
whilefoo marked this conversation as resolved.
Show resolved Hide resolved
const result = await fetch(targetUrl, {
body: JSON.stringify(payload),
method: "POST",
Expand Down
Loading