diff --git a/backend/package-lock.json b/backend/package-lock.json index 6ec28ed63..3a15d6857 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -61,10 +61,12 @@ "jwks-rsa": "^3.1.0", "knex": "^3.0.1", "ldapjs": "^3.0.7", + "ldif": "^0.5.1", "libsodium-wrappers": "^0.7.13", "lodash.isequal": "^4.5.0", "mongodb": "^6.8.1", "ms": "^2.1.3", + "mustache": "^4.2.0", "mysql2": "^3.9.8", "nanoid": "^3.3.4", "nodemailer": "^6.9.9", @@ -109,6 +111,7 @@ "@types/jsrp": "^0.2.6", "@types/libsodium-wrappers": "^0.7.13", "@types/lodash.isequal": "^4.5.8", + "@types/mustache": "^4.2.5", "@types/node": "^20.9.5", "@types/nodemailer": "^6.4.14", "@types/passport-github": "^1.1.12", @@ -7076,6 +7079,13 @@ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-0.7.34.tgz", "integrity": "sha512-nG96G3Wp6acyAgJqGasjODb+acrI7KltPiRxzHPXnP3NgI28bpQDRv53olbqGXbfcgF5aiiHmO3xpwEpS5Ld9g==" }, + "node_modules/@types/mustache": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/@types/mustache/-/mustache-4.2.5.tgz", + "integrity": "sha512-PLwiVvTBg59tGFL/8VpcGvqOu3L4OuveNvPi0EYbWchRdEVP++yRUXJPFl+CApKEq13017/4Nf7aQ5lTtHUNsA==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/node": { "version": "20.9.5", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.9.5.tgz", @@ -13017,6 +13027,12 @@ "verror": "^1.10.1" } }, + "node_modules/ldif": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/ldif/-/ldif-0.5.1.tgz", + "integrity": "sha512-8s46m/r2lSFO2+DqMxqWiJ10iiL4tuR5LC/KndV+E5//OAOzOx5s3HS5O34PJ5+kyaCA+K2oCaEPaDRfXUnQow==", + "license": "MIT" + }, "node_modules/leven": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/leven/-/leven-2.1.0.tgz", @@ -13713,6 +13729,15 @@ "node": ">= 6" } }, + "node_modules/mustache": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/mustache/-/mustache-4.2.0.tgz", + "integrity": "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==", + "license": "MIT", + "bin": { + "mustache": "bin/mustache" + } + }, "node_modules/mylas": { "version": "2.1.13", "resolved": "https://registry.npmjs.org/mylas/-/mylas-2.1.13.tgz", diff --git a/backend/package.json b/backend/package.json index 217817edf..dfa293e71 100644 --- a/backend/package.json +++ b/backend/package.json @@ -71,6 +71,7 @@ "@types/jsrp": "^0.2.6", "@types/libsodium-wrappers": "^0.7.13", "@types/lodash.isequal": "^4.5.8", + "@types/mustache": "^4.2.5", "@types/node": "^20.9.5", "@types/nodemailer": "^6.4.14", "@types/passport-github": "^1.1.12", @@ -159,10 +160,12 @@ "jwks-rsa": "^3.1.0", "knex": "^3.0.1", "ldapjs": "^3.0.7", + "ldif": "^0.5.1", "libsodium-wrappers": "^0.7.13", "lodash.isequal": "^4.5.0", "mongodb": "^6.8.1", "ms": "^2.1.3", + "mustache": "^4.2.0", "mysql2": "^3.9.8", "nanoid": "^3.3.4", "nodemailer": "^6.9.9", diff --git a/backend/src/ee/services/dynamic-secret/providers/index.ts b/backend/src/ee/services/dynamic-secret/providers/index.ts index 8f2dbdc13..b3c243b5e 100644 --- a/backend/src/ee/services/dynamic-secret/providers/index.ts +++ b/backend/src/ee/services/dynamic-secret/providers/index.ts @@ -3,6 +3,7 @@ import { AwsIamProvider } from "./aws-iam"; import { AzureEntraIDProvider } from "./azure-entra-id"; import { CassandraProvider } from "./cassandra"; import { ElasticSearchProvider } from "./elastic-search"; +import { LdapProvider } from "./ldap"; import { DynamicSecretProviders } from "./models"; import { MongoAtlasProvider } from "./mongo-atlas"; import { MongoDBProvider } from "./mongo-db"; @@ -20,5 +21,6 @@ export const buildDynamicSecretProviders = () => ({ [DynamicSecretProviders.MongoDB]: MongoDBProvider(), [DynamicSecretProviders.ElasticSearch]: ElasticSearchProvider(), [DynamicSecretProviders.RabbitMq]: RabbitMqProvider(), - [DynamicSecretProviders.AzureEntraID]: AzureEntraIDProvider() + [DynamicSecretProviders.AzureEntraID]: AzureEntraIDProvider(), + [DynamicSecretProviders.Ldap]: LdapProvider() }); diff --git a/backend/src/ee/services/dynamic-secret/providers/ldap.ts b/backend/src/ee/services/dynamic-secret/providers/ldap.ts new file mode 100644 index 000000000..0d47c530c --- /dev/null +++ b/backend/src/ee/services/dynamic-secret/providers/ldap.ts @@ -0,0 +1,213 @@ +/* eslint-disable */ + +import ldapjs from "ldapjs"; +import { render } from "mustache"; +import { customAlphabet } from "nanoid"; +import { z } from "zod"; + +import { alphaNumericNanoId } from "@app/lib/nanoid"; + +import { LdapSchema, TDynamicProviderFns } from "./models"; +import { BadRequestError } from "@app/lib/errors"; +const ldif = require("ldif"); + +const generatePassword = () => { + const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~!*$#"; + return customAlphabet(charset, 64)(); +}; + +const encodePassword = (password?: string) => { + const quotedPassword = `"${password}"`; + const utf16lePassword = Buffer.from(quotedPassword, "utf16le"); + const base64Password = utf16lePassword.toString("base64"); + return base64Password; +} + +const generateUsername = () => { + return alphaNumericNanoId(20); +}; + +const generateLDIF = ({ + username, + password, + ldifTemplate +}: { + username: string; + password?: string; + ldifTemplate: string; +}): string => { + + const data = { + Username: username, + Password: password, + EncodedPassword: encodePassword(password) + }; + + const ldif = render(ldifTemplate, data); + + return ldif; +}; + +export const LdapProvider = (): TDynamicProviderFns => { + const validateProviderInputs = async (inputs: unknown) => { + const providerInputs = await LdapSchema.parseAsync(inputs); + return providerInputs; + }; + + const getClient = async (providerInputs: z.infer): Promise => { + return new Promise((resolve, reject) => { + const client = ldapjs.createClient({ + url: providerInputs.url, + tlsOptions: { + ca: providerInputs.ca ? providerInputs.ca : null, + rejectUnauthorized: !!providerInputs.ca + }, + reconnect: true, + bindDN: providerInputs.binddn, + bindCredentials: providerInputs.bindpass, + }); + + client.on("error", (err) => { + client.unbind(); + reject(new BadRequestError({ message: err.message })); + }); + + client.bind(providerInputs.binddn, providerInputs.bindpass, (err) => { + if (err) { + client.unbind(); + reject(new BadRequestError({ message: err.message })); + } else { + resolve(client); + } + }); + }); + }; + + const validateConnection = async (inputs: unknown) => { + const providerInputs = await validateProviderInputs(inputs); + const client = await getClient(providerInputs); + return client.connected; + }; + + const executeLdif = async (client: ldapjs.Client, ldif_file: string) => { + let parsedEntries; + try { + parsedEntries = ldif.parse(ldif_file).entries as any[]; + } catch (err) { + throw new BadRequestError({ message: "Invalid LDIF format, refer to the documentation at Dynamic secrets > LDAP > LDIF Entries." }); + } + + const dnArray: string[] = []; + + for (const entry of parsedEntries) { + const { dn } = entry; + let response_dn: string; + + if (entry.type === "add") { + const attributes: any = {}; + + entry.changes.forEach((change: any) => { + const attrName = change.attribute.attribute; + const attrValue = change.value.value; + + attributes[attrName] = Array.isArray(attrValue) ? attrValue : [attrValue]; + }); + + response_dn = await new Promise((resolve, reject) => { + client.add(dn, attributes, (err) => { + if (err) { + reject(new BadRequestError({ message: err.message })); + } else { + resolve(dn); + } + }); + }); + } else if (entry.type === "modify") { + const changes: any = []; + + entry.changes.forEach((change: any) => { + changes.push( + new ldapjs.Change({ + operation: change.operation || "replace", + modification: { + type: change.attribute.attribute, + values: change.values.map((value: any) => value.value) + } + }) + ); + }); + + response_dn = await new Promise((resolve, reject) => { + client.modify(dn, changes, (err) => { + if (err) { + reject(new BadRequestError({ message: err.message })); + } else { + resolve(dn); + } + }); + }); + } else if (entry.type === "delete") { + response_dn = await new Promise((resolve, reject) => { + client.del(dn, (err) => { + if (err) { + reject(new BadRequestError({ message: err.message })); + } else { + resolve(dn); + } + }); + }); + } else { + client.unbind(); + throw new BadRequestError({ message: `Unsupported operation type ${entry.type}` }); + } + + dnArray.push(response_dn); + } + client.unbind(); + return dnArray; + }; + + const create = async (inputs: unknown) => { + const providerInputs = await validateProviderInputs(inputs); + const client = await getClient(providerInputs); + + const username = generateUsername(); + const password = generatePassword(); + const ldif = generateLDIF({ username, password, ldifTemplate: providerInputs.creationLdif }); + + try { + const dnArray = await executeLdif(client, ldif); + + return { entityId: username, data: { DN_ARRAY: dnArray, USERNAME: username, PASSWORD: password } }; + } catch (err) { + if (providerInputs.rollbackLdif) { + const rollbackLdif = generateLDIF({ username, password, ldifTemplate: providerInputs.rollbackLdif }); + await executeLdif(client, rollbackLdif); + } + throw new BadRequestError({ message: (err as Error).message }); + } + }; + + const revoke = async (inputs: unknown, entityId: string) => { + const providerInputs = await validateProviderInputs(inputs); + const connection = await getClient(providerInputs); + const revocationLdif = generateLDIF({ username: entityId, ldifTemplate: providerInputs.revocationLdif }); + + await executeLdif(connection, revocationLdif); + + return { entityId }; + }; + + const renew = async (inputs: unknown, entityId: string) => { + // Do nothing + return { entityId }; + }; + + return { + validateProviderInputs, + validateConnection, + create, + revoke, + renew + }; +}; diff --git a/backend/src/ee/services/dynamic-secret/providers/models.ts b/backend/src/ee/services/dynamic-secret/providers/models.ts index 18a7b3dc9..c204333ce 100644 --- a/backend/src/ee/services/dynamic-secret/providers/models.ts +++ b/backend/src/ee/services/dynamic-secret/providers/models.ts @@ -174,6 +174,17 @@ export const AzureEntraIDSchema = z.object({ clientSecret: z.string().trim().min(1) }); +export const LdapSchema = z.object({ + url: z.string().trim().min(1), + binddn: z.string().trim().min(1), + bindpass: z.string().trim().min(1), + ca: z.string().optional(), + + creationLdif: z.string().min(1), + revocationLdif: z.string().min(1), + rollbackLdif: z.string().optional() +}); + export enum DynamicSecretProviders { SqlDatabase = "sql-database", Cassandra = "cassandra", @@ -184,7 +195,8 @@ export enum DynamicSecretProviders { ElasticSearch = "elastic-search", MongoDB = "mongo-db", RabbitMq = "rabbit-mq", - AzureEntraID = "azure-entra-id" + AzureEntraID = "azure-entra-id", + Ldap = "ldap" } export const DynamicSecretProviderSchema = z.discriminatedUnion("type", [ @@ -197,7 +209,8 @@ export const DynamicSecretProviderSchema = z.discriminatedUnion("type", [ z.object({ type: z.literal(DynamicSecretProviders.ElasticSearch), inputs: DynamicSecretElasticSearchSchema }), z.object({ type: z.literal(DynamicSecretProviders.MongoDB), inputs: DynamicSecretMongoDBSchema }), z.object({ type: z.literal(DynamicSecretProviders.RabbitMq), inputs: DynamicSecretRabbitMqSchema }), - z.object({ type: z.literal(DynamicSecretProviders.AzureEntraID), inputs: AzureEntraIDSchema }) + z.object({ type: z.literal(DynamicSecretProviders.AzureEntraID), inputs: AzureEntraIDSchema }), + z.object({ type: z.literal(DynamicSecretProviders.Ldap), inputs: LdapSchema }) ]); export type TDynamicProviderFns = { diff --git a/docs/documentation/platform/dynamic-secrets/ldap.mdx b/docs/documentation/platform/dynamic-secrets/ldap.mdx new file mode 100644 index 000000000..2dc51d74e --- /dev/null +++ b/docs/documentation/platform/dynamic-secrets/ldap.mdx @@ -0,0 +1,168 @@ +--- +title: "LDAP" +description: "Learn how to dynamically generate user credentials via LDAP." +--- + +The Infisical LDAP dynamic secret allows you to generate user credentials on demand via LDAP. The integration is general to any LDAP implementation but has been tested with OpenLDAP and Active directory as of now. + +## Prerequisites + +1. Create a user with the necessary permissions to create users in your LDAP server. +2. Ensure your LDAP server is reachable via Infisical instance. + +## Set up Dynamic Secrets with LDAP + + + + Open the Secret Overview dashboard and select the environment in which you would like to add a dynamic secret. + + + ![Add Dynamic Secret Button](../../../images/platform/dynamic-secrets/add-dynamic-secret-button.png) + + + ![Dynamic Secret Modal](../../../images/platform/dynamic-secrets/dynamic-secret-ldap-select.png) + + + + + Name by which you want the secret to be referenced + + + + Default time-to-live for a generated secret (it is possible to modify this value when a secret is generate) + + + + Maximum time-to-live for a generated secret. + + + + LDAP url to connect to. _(Example: ldap://your-ldap-ip:389 or ldaps://domain:636)_ + + + + DN to bind to. This should have permissions to create a new users. + + + + Password for the given DN. + + + + CA certificate to use for TLS in case of a secure connection. + + + + LDIF to run while creating a user in LDAP. This can include extra steps to assign the user to groups or set permissions. + Here `{{Username}}`, `{{Password}}` and `{{EncodedPassword}}` are templatized variables for the username and password generated by the dynamic secret. + + `{{EncodedPassword}}` is the encoded password required for the `unicodePwd` field in Active Directory as described [here](https://learn.microsoft.com/en-us/troubleshoot/windows-server/active-directory/change-windows-active-directory-user-password). + + **OpenLDAP** Example: + ``` + dn: uid={{Username}},dc=infisical,dc=com + changetype: add + objectClass: top + objectClass: person + objectClass: organizationalPerson + objectClass: inetOrgPerson + cn: John Doe + sn: Doe + uid: jdoe + mail: jdoe@infisical.com + userPassword: {{Password}} + ``` + + **Active Directory** Example: + ``` + dn: CN={{Username}},OU=Test Create,DC=infisical,DC=com + changetype: add + objectClass: top + objectClass: person + objectClass: organizationalPerson + objectClass: user + userPrincipalName: {{Username}}@infisical.com + sAMAccountName: {{Username}} + unicodePwd::{{EncodedPassword}} + userAccountControl: 66048 + + dn: CN=test-group,OU=Test Create,DC=infisical,DC=com + changetype: modify + add: member + member: CN={{Username}},OU=Test Create,DC=infisical,DC=com + - + ``` + + + + LDIF to run while revoking a user in LDAP. This can include extra steps to remove the user from groups or set permissions. + Here `{{Username}}` is a templatized variable for the username generated by the dynamic secret. + + **OpenLDAP / Active Directory** Example: + ``` + dn: CN={{Username}},OU=Test Create,DC=infisical,DC=com + changetype: delete + ``` + + + + LDIF to run incase Creation LDIF fails midway. + + For the creation example shown above, if the user is created successfully but not added to a group, this LDIF can be used to remove the user. + Here `{{Username}}`, `{{Password}}` and `{{EncodedPassword}}` are templatized variables for the username generated by the dynamic secret. + + **OpenLDAP / Active Directory** Example: + ``` + dn: CN={{Username}},OU=Test Create,DC=infisical,DC=com + changetype: delete + ``` + + + + + + After submitting the form, you will see a dynamic secret created in the dashboard. + + + Once you've successfully configured the dynamic secret, you're ready to generate on-demand credentials. + To do this, simply click on the 'Generate' button which appears when hovering over the dynamic secret item. + Alternatively, you can initiate the creation of a new lease by selecting 'New Lease' from the dynamic secret lease list section. + + ![Dynamic Secret](/images/platform/dynamic-secrets/dynamic-secret-generate-redis.png) + ![Dynamic Secret](/images/platform/dynamic-secrets/dynamic-secret-lease-empty-redis.png) + + When generating these secrets, it's important to specify a Time-to-Live (TTL) duration. This will dictate how long the credentials are valid for. + + ![Provision Lease](/images/platform/dynamic-secrets/provision-lease.png) + + + Ensure that the TTL for the lease fall within the maximum TTL defined when configuring the dynamic secret. + + + + Once you click the `Submit` button, a new secret lease will be generated and the credentials from it will be shown to you with an array of DN's altered depending on the Creation LDIF. + + ![Provision Lease](/images/platform/dynamic-secrets/dynamic-secret-ldap-lease.png) + + + + + +## Active Directory Integration + +- Passwords in Active Directory are set using the `unicodePwd` field. This must be proceeded by two colons `::` as shown in the example. [Source](https://learn.microsoft.com/en-us/troubleshoot/windows-server/active-directory/change-windows-active-directory-user-password) +- Active directory uses the `userAccountControl` field to enable account. [Read More](https://learn.microsoft.com/en-us/troubleshoot/windows-server/active-directory/useraccountcontrol-manipulate-account-properties) + - `userAccountControl` set to `512` enables a user. + - To disable AD's password expiration for this dynamic user account. The `userAccountControl` value for this is: `65536`. + - Since `userAccountControl` flag is cumulative set it to `512 + 65536` = `66048` to do both. +- Active Directory does not permit direct modification of a user's `memberOf` attribute. The member attribute of a group and the `memberOf` attribute of a user are [linked attributes](https://learn.microsoft.com/en-us/windows/win32/ad/linked-attributes), where the member attribute represents the forward link, which can be modified. In the context of AD group membership, the group's `member` attribute serves as the forward link. Therefore, to add a newly created dynamic user to a group, a modification request must be issued to the desired group, updating its membership to include the new user. + +## LDIF Entries + +User account management is handled through **LDIF entries**. + +#### Things to Remember + +- **No trailing spaces:** Ensure there are no trailing spaces on any line, including blank lines. +- **Empty lines before modify blocks:** Every modify block must be preceded by an empty line. +- **Multiple modifications:** You can define multiple modifications for a DN within a single modify block. Each modification should end with a single dash (`-`). diff --git a/docs/images/platform/dynamic-secrets/dynamic-secret-ldap-lease.png b/docs/images/platform/dynamic-secrets/dynamic-secret-ldap-lease.png new file mode 100644 index 000000000..e053a8ddc Binary files /dev/null and b/docs/images/platform/dynamic-secrets/dynamic-secret-ldap-lease.png differ diff --git a/docs/images/platform/dynamic-secrets/dynamic-secret-ldap-select.png b/docs/images/platform/dynamic-secrets/dynamic-secret-ldap-select.png new file mode 100644 index 000000000..7694a3fef Binary files /dev/null and b/docs/images/platform/dynamic-secrets/dynamic-secret-ldap-select.png differ diff --git a/docs/mint.json b/docs/mint.json index d2ca12605..5cc30d6e4 100644 --- a/docs/mint.json +++ b/docs/mint.json @@ -168,7 +168,8 @@ "documentation/platform/dynamic-secrets/aws-iam", "documentation/platform/dynamic-secrets/mongo-atlas", "documentation/platform/dynamic-secrets/mongo-db", - "documentation/platform/dynamic-secrets/azure-entra-id" + "documentation/platform/dynamic-secrets/azure-entra-id", + "documentation/platform/dynamic-secrets/ldap" ] }, { diff --git a/frontend/src/hooks/api/dynamicSecret/types.ts b/frontend/src/hooks/api/dynamicSecret/types.ts index e97234bc4..792fad8d3 100644 --- a/frontend/src/hooks/api/dynamicSecret/types.ts +++ b/frontend/src/hooks/api/dynamicSecret/types.ts @@ -25,7 +25,8 @@ export enum DynamicSecretProviders { ElasticSearch = "elastic-search", MongoDB = "mongo-db", RabbitMq = "rabbit-mq", - AzureEntraId = "azure-entra-id" + AzureEntraId = "azure-entra-id", + Ldap = "ldap" } export enum SqlProviders { @@ -188,7 +189,20 @@ export type TDynamicSecretProvider = applicationId: string; clientSecret: string; }; - }; + } + | { + type: DynamicSecretProviders.Ldap; + inputs: { + url: string; + binddn: string; + bindpass: string; + ca?: string | undefined; + creationLdif: string; + revocationLdif: string; + rollbackLdif?: string; + }; + }; + ; export type TCreateDynamicSecretDTO = { projectSlug: string; diff --git a/frontend/src/views/SecretMainPage/components/ActionBar/CreateDynamicSecretForm/CreateDynamicSecretForm.tsx b/frontend/src/views/SecretMainPage/components/ActionBar/CreateDynamicSecretForm/CreateDynamicSecretForm.tsx index a28544a33..029ab6251 100644 --- a/frontend/src/views/SecretMainPage/components/ActionBar/CreateDynamicSecretForm/CreateDynamicSecretForm.tsx +++ b/frontend/src/views/SecretMainPage/components/ActionBar/CreateDynamicSecretForm/CreateDynamicSecretForm.tsx @@ -1,6 +1,6 @@ import { useState } from "react"; import { DiRedis } from "react-icons/di"; -import { SiApachecassandra, SiElasticsearch, SiMicrosoftazure, SiMongodb, SiRabbitmq } from "react-icons/si"; +import { SiApachecassandra, SiElasticsearch, SiFiles, SiMicrosoftazure, SiMongodb, SiRabbitmq } from "react-icons/si"; import { faAws } from "@fortawesome/free-brands-svg-icons"; import { faDatabase } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; @@ -14,6 +14,7 @@ import { AwsIamInputForm } from "./AwsIamInputForm"; import { AzureEntraIdInputForm } from "./AzureEntraIdInputForm"; import { CassandraInputForm } from "./CassandraInputForm"; import { ElasticSearchInputForm } from "./ElasticSearchInputForm"; +import { LdapInputForm } from "./LdapInputForm"; import { MongoAtlasInputForm } from "./MongoAtlasInputForm"; import { MongoDBDatabaseInputForm } from "./MongoDBInputForm"; import { RabbitMqInputForm } from "./RabbitMqInputForm"; @@ -83,6 +84,11 @@ const DYNAMIC_SECRET_LIST = [ icon: , provider: DynamicSecretProviders.AzureEntraId, title: "Azure Entra ID", + }, + { + icon: , + provider: DynamicSecretProviders.Ldap, + title: "LDAP", } ]; @@ -325,6 +331,26 @@ export const CreateDynamicSecretForm = ({ ) } + {wizardStep === WizardSteps.ProviderInputs && + selectedProvider === DynamicSecretProviders.Ldap && ( + + + + ) + } + diff --git a/frontend/src/views/SecretMainPage/components/ActionBar/CreateDynamicSecretForm/LdapInputForm.tsx b/frontend/src/views/SecretMainPage/components/ActionBar/CreateDynamicSecretForm/LdapInputForm.tsx new file mode 100644 index 000000000..b78161aa5 --- /dev/null +++ b/frontend/src/views/SecretMainPage/components/ActionBar/CreateDynamicSecretForm/LdapInputForm.tsx @@ -0,0 +1,297 @@ +import { Controller, useForm } from "react-hook-form"; +import Link from "next/link"; +import { faArrowUpRightFromSquare, faBookOpen } from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { zodResolver } from "@hookform/resolvers/zod"; +import ms from "ms"; +import { z } from "zod"; + +import { TtlFormLabel } from "@app/components/features"; +import { createNotification } from "@app/components/notifications"; +import { Button, FormControl, Input, TextArea } from "@app/components/v2"; +import { useCreateDynamicSecret } from "@app/hooks/api"; +import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types"; + +const formSchema = z.object({ + provider: z.object({ + url: z.string().trim().min(1), + binddn: z.string().trim().min(1), + bindpass: z.string().trim().min(1), + ca: z.string().optional(), + + creationLdif: z.string().min(1), + revocationLdif: z.string().min(1), + rollbackLdif: z.string().optional() + }), + + defaultTTL: z.string().superRefine((val, ctx) => { + const valMs = ms(val); + if (valMs < 60 * 1000) + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be a greater than 1min" }); + // a day + if (valMs > 24 * 60 * 60 * 1000) + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than a day" }); + }), + maxTTL: z + .string() + .optional() + .superRefine((val, ctx) => { + if (!val) return; + const valMs = ms(val); + if (valMs < 60 * 1000) + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be a greater than 1min" }); + // a day + if (valMs > 24 * 60 * 60 * 1000) + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than a day" }); + }), + name: z.string().refine((val) => val.toLowerCase() === val, "Must be lowercase") +}); + +type TForm = z.infer; + +type Props = { + onCompleted: () => void; + onCancel: () => void; + secretPath: string; + projectSlug: string; + environment: string; +}; + +export const LdapInputForm = ({ + onCompleted, + onCancel, + secretPath, + projectSlug, + environment +}: Props) => { + const { + control, + formState: { isSubmitting }, + handleSubmit + } = useForm({ + resolver: zodResolver(formSchema), + defaultValues: { + provider: { + url: "", + binddn: "", + bindpass: "", + ca: "", + creationLdif: "", + revocationLdif: "", + rollbackLdif: "" + } + } + }); + + const createDynamicSecret = useCreateDynamicSecret(); + + const handleCreateDynamicSecret = async ({ name, maxTTL, provider, defaultTTL }: TForm) => { + // wait till previous request is finished + if (createDynamicSecret.isLoading) return; + try { + await createDynamicSecret.mutateAsync({ + provider: { type: DynamicSecretProviders.Ldap, inputs: provider }, + maxTTL, + name, + path: secretPath, + defaultTTL, + projectSlug, + environmentSlug: environment + }); + onCompleted(); + } catch (err) { + createNotification({ + type: "error", + text: "Failed to create dynamic secret" + }); + } + }; + + return ( +
+
+
+
+ ( + + + + )} + /> +
+
+ ( + } + isError={Boolean(error?.message)} + errorText={error?.message} + > + + + )} + /> +
+
+ ( + } + isError={Boolean(error?.message)} + errorText={error?.message} + > + + + )} + /> +
+
+
+
+ Configuration + + +
+ + Docs + +
+
+ +
+
+
+
+ ( + + + + )} + /> + + ( + + + + )} + /> + + ( + + + + )} + /> + + ( + +