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: Enable Zitadel Integration for API Authentication #4147

Merged
merged 8 commits into from
Aug 9, 2024
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
"use server";
import crypto from "crypto";
import { prisma } from "@lib/integration/prismaConnector";
import { logMessage } from "@lib/logger";
import { revalidatePath } from "next/cache";
import { logEvent } from "@lib/auditLogs";
import { authCheckAndThrow } from "@lib/actions";
import { checkUserHasTemplateOwnership } from "@lib/templates";
import { getZitadelClient } from "@lib/integration/zitadelConnector";

const createUser = async (templateId: string): Promise<string> => {
const zitadel = await getZitadelClient();
const { userId } = await zitadel
.addMachineUser({
userName: templateId,
name: templateId,
description: `API Service account for form ${templateId}`,
// Access Token Type 1 is JWT
accessTokenType: 1,
})
.catch((err) => {
logMessage.error(err);
throw new Error("Could not create User on Identity Provider");
});

logMessage.debug(`Service User ID: ${userId} `);
return userId;
};

const uploadKey = async (publicKey: string, userId: string): Promise<string> => {
const zitadel = await getZitadelClient();
const { keyId } = await zitadel
.addMachineKey({
userId: userId,
// Key type 1 is JSON
type: 1,
expirationDate: undefined,
publicKey: Buffer.from(publicKey),
})
.catch((err) => {
logMessage.error(err);
throw new Error("Failed to create key");
});

logMessage.debug(`Key ID: ${keyId}`);
return keyId;
};

export const deleteKey = async (templateId: string) => {
const { ability } = await authCheckAndThrow();
await checkUserHasTemplateOwnership(ability, templateId);

const { id: serviceAccountId, publicKeyId } =
(await prisma.apiServiceAccount.findUnique({
where: {
templateId: templateId,
},
select: { id: true, publicKeyId: true },
})) ?? {};

if (!serviceAccountId || !publicKeyId) {
throw new Error("No Key Exists in GCForms DB");
}

const zitadel = await getZitadelClient();
await zitadel
.removeMachineKey({
userId: serviceAccountId,
keyId: publicKeyId,
})
.catch((err) => {
logMessage.error(err);
throw new Error("Failed to delete key");
});

await prisma.apiServiceAccount.delete({
where: {
templateId: templateId,
},
});

logEvent(
ability.userID,
{ type: "ServiceAccount" },
"DeleteAPIKey",
`User :${ability.userID} deleted service account ${serviceAccountId} `
);

revalidatePath(
"/app/(gcforms)/[locale]/(form administration)/form-builder/[id]/settings/api",
"page"
);
};
export const checkKeyExists = async (templateId: string) => {
const { ability } = await authCheckAndThrow();
await checkUserHasTemplateOwnership(ability, templateId);

const { id: userId, publicKeyId } =
(await prisma.apiServiceAccount.findUnique({
where: {
templateId: templateId,
},
select: { id: true, publicKeyId: true },
})) ?? {};

if (!userId || !publicKeyId) {
return false;
}

const zitadel = await getZitadelClient();
const remoteKey = await zitadel
.getMachineKeyByIDs({
userId,
keyId: publicKeyId,
})
.catch((err) => {
logMessage.error(err);
return null;
});

if (publicKeyId === remoteKey?.key?.id) {
return true;
}
// Key are out of sync or user does not exist
return false;
};

export const refreshKey = async (templateId: string) => {
const { ability } = await authCheckAndThrow();
await checkUserHasTemplateOwnership(ability, templateId);

const { id: serviceAccountId, publicKeyId } =
(await prisma.apiServiceAccount.findUnique({
where: {
templateId: templateId,
},
select: { id: true, publicKeyId: true },
})) ?? {};

if (!serviceAccountId || !publicKeyId) {
throw new Error("No Key Exists in GCForms DB");
}

const zitadel = await getZitadelClient();
await zitadel
.removeMachineKey({
userId: serviceAccountId,
keyId: publicKeyId,
})
.catch((err) => {
logMessage.error(err);
throw new Error("Failed to delete key");
});

const { privateKey, publicKey } = generateKeys();

const keyId = await uploadKey(publicKey, serviceAccountId);
await prisma.apiServiceAccount.update({
where: {
templateId,
},
data: {
publicKey: publicKey,
publicKeyId: keyId,
},
});

logEvent(
ability.userID,
{ type: "ServiceAccount" },
"RefreshAPIKey",
`User :${ability.userID} refreshed API key for service account ${serviceAccountId} `
);

return { type: "serviceAccount", keyId, key: privateKey, userId: serviceAccountId };
};

export const createKey = async (templateId: string) => {
const { ability } = await authCheckAndThrow();
await checkUserHasTemplateOwnership(ability, templateId);

const serviceAccountId = await createUser(templateId);

const { privateKey, publicKey } = generateKeys();

const keyId = await uploadKey(publicKey, serviceAccountId);

await prisma.apiServiceAccount.create({
data: {
id: serviceAccountId,
publicKeyId: keyId,
templateId,
publicKey,
},
});

logEvent(
ability.userID,
{ type: "ServiceAccount" },
"CreateAPIKey",
`User :${ability.userID} created API key for service account ${serviceAccountId} `
);

revalidatePath(
"/app/(gcforms)/[locale]/(form administration)/form-builder/[id]/settings/api",
"page"
);

return { type: "serviceAccount", keyId, key: privateKey, userId: serviceAccountId };
};

// Look at possibly moving this to the browser so the GCForms System is never in possession
// of the private key.

const generateKeys = () => {
const { privateKey, publicKey } = crypto.generateKeyPairSync("rsa", {
modulusLength: 2048,
publicKeyEncoding: {
type: "spki",
format: "pem",
},
privateKeyEncoding: {
type: "pkcs8",
format: "pem",
},
});
return { privateKey, publicKey };
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
"use client";
import { Button } from "@clientComponents/globals";
import { useTranslation } from "@i18n/client";
import { CircleCheckIcon } from "@serverComponents/icons";
import { deleteKey, createKey, refreshKey } from "../../actions";
import { useParams } from "next/navigation";

const _createKey = async (templateId: string) => {
// In the future this could be done in the browser but we'll need to verify that they key meets the requirements
const key = await createKey(templateId);
downloadKey(JSON.stringify(key), templateId);
};

const _refreshKey = async (templateId: string) => {
const key = await refreshKey(templateId);
Copy link
Contributor

Choose a reason for hiding this comment

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

Do we plan on adding error handling in a future iteration? I noticed the lib code can throw various type of errors at the moment.

downloadKey(JSON.stringify(key), templateId);
};

const downloadKey = (key: string, templateId: string) => {
const blob = new Blob([key], { type: "application/json" });
const href = URL.createObjectURL(blob);

// create "a" HTLM element with href to file
const link = document.createElement("a");
link.href = href;
link.download = `${templateId}_private_api_key.json`;
document.body.appendChild(link);
link.click();

// clean up "a" element & remove ObjectURL
document.body.removeChild(link);
URL.revokeObjectURL(href);
};

export const ApiKey = ({ keyExists }: { keyExists?: boolean }) => {
const { t } = useTranslation("form-builder");
const { id } = useParams();
if (Array.isArray(id)) return null;
return (
<div className="mb-10">
<div className="mb-4">
<h2 className="mb-6">{t("settings.api.title")}</h2>
</div>
<div className="mb-4">
{keyExists ? (
<>
<div className="mb-4">
<CircleCheckIcon className="mr-2 inline-block w-9 fill-green-700" />
{t("settings.api.keyExists")}
</div>
<Button theme="primary" className="mr-4" onClick={() => deleteKey(id)}>
Copy link
Contributor

Choose a reason for hiding this comment

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

The deleteKey function is async and can also throw errors. Not a big deal but it would be good to let the user know whether the key was successfully deleted or not.

{t("settings.api.deleteKey")}
</Button>
<Button theme="primary" onClick={() => _refreshKey(id)}>
{t("settings.api.refreshKey")}
</Button>
</>
) : (
<Button theme="primary" onClick={() => _createKey(id)}>
{t("settings.api.generateKey")}
</Button>
)}
</div>
</div>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { serverTranslation } from "@i18n";
import { Metadata } from "next";
import { ApiKey } from "./components/client/ApiKey";
import { authCheckAndRedirect } from "@lib/actions";
import { checkKeyExists } from "./actions";
import { checkOne } from "@lib/cache/flags";
import { redirect } from "next/navigation";

export async function generateMetadata({
params: { locale },
}: {
params: { locale: string };
}): Promise<Metadata> {
const { t } = await serverTranslation("form-builder", { lang: locale });
return {
title: `${t("gcFormsSettings")} — ${t("gcForms")}`,
};
}

export default async function Page({
params: { id, locale },
}: {
params: { id: string; locale: string };
}) {
await authCheckAndRedirect();
const flag = await checkOne("zitadelAuth");
if (!flag) {
redirect(`/${locale}/form-builder/${id}/settings`);
}

const keyExists = await checkKeyExists(id);

return <ApiKey keyExists={keyExists} />;
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@
import React from "react";
import { useTranslation } from "@i18n/client";
import { SubNavLink } from "@clientComponents/globals/SubNavLink";
import { EmailIcon, BrandIcon, GearIcon } from "@serverComponents/icons";
import { EmailIcon, BrandIcon, GearIcon, ProtectedIcon } from "@serverComponents/icons";
import { useFlag } from "@lib/hooks/useFlag";

export const SettingsNavigation = ({ id }: { id: string }) => {
const {
t,
i18n: { language },
} = useTranslation("form-builder");

const isAPIEnalbed = useFlag("zitadelAuth");

return (
<div className="relative flex">
<div className="flex">
Expand All @@ -32,6 +35,14 @@ export const SettingsNavigation = ({ id }: { id: string }) => {
{t("settings.formManagement")}
</span>
</SubNavLink>
{isAPIEnalbed.status === true && (
<SubNavLink href={`/${language}/form-builder/${id}/settings/api`}>
<span className="text-sm laptop:text-base">
<ProtectedIcon className="mr-2 inline-block laptop:mt-[-2px]" />
{t("settings.api.title")}
</span>
</SubNavLink>
)}
</nav>
</div>
</div>
Expand Down
3 changes: 2 additions & 1 deletion flag_initialization/default_flag_settings.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"experimentalBlocks": false,
"conditionalLogic": false
"conditionalLogic": false,
"zitadelAuth": false
}
4 changes: 4 additions & 0 deletions i18n/translations/en/admin-flags.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@
"conditionalLogic": {
"title": "Conditional logic",
"description": "Enable conditional logic and the right panel"
},
"zitadelAuth": {
"title": "Zitadel Auth",
"description": "Enable API authentication with Zitadel"
}
}
}
Loading
Loading