-
Notifications
You must be signed in to change notification settings - Fork 13
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
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
5ea023e
feat: enable integration with zitadel
wmoussa-gc f18680f
Merge branch 'develop' into feature/service_account2
wmoussa-gc d3fc912
Merge branch 'develop' into feature/service_account2
wmoussa-gc 854e7e5
Merge branch 'develop' into feature/service_account2
wmoussa-gc 64029a7
fix wrongly moved files
wmoussa-gc e48cf33
Merge branch 'develop' into feature/service_account2
wmoussa-gc e147018
Merge branch 'develop' into feature/service_account2
wmoussa-gc 3cab000
Merge branch 'develop' into feature/service_account2
wmoussa-gc File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
228 changes: 228 additions & 0 deletions
228
app/(gcforms)/[locale]/(form administration)/form-builder/[id]/settings/api/actions.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; | ||
}; |
66 changes: 66 additions & 0 deletions
66
...locale]/(form administration)/form-builder/[id]/settings/api/components/client/ApiKey.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
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)}> | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The |
||
{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> | ||
); | ||
}; |
34 changes: 34 additions & 0 deletions
34
app/(gcforms)/[locale]/(form administration)/form-builder/[id]/settings/api/page.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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} />; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,5 @@ | ||
{ | ||
"experimentalBlocks": false, | ||
"conditionalLogic": false | ||
"conditionalLogic": false, | ||
"zitadelAuth": false | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.