Merge remote-tracking branch 'origin/main' into pki-revamp

This commit is contained in:
Carlos Monastyrski
2025-10-16 12:33:45 -03:00
211 changed files with 3325 additions and 322 deletions

View File

@@ -135,7 +135,9 @@ jobs:
TAG_NAME="${{ github.ref_name }}" TAG_NAME="${{ github.ref_name }}"
echo "Checking for tag: $TAG_NAME" echo "Checking for tag: $TAG_NAME"
if gh api repos/Infisical/infisical-omnibus/git/refs/tags/$TAG_NAME --silent 2>/dev/null; then EXACT_MATCH=$(gh api repos/Infisical/infisical-omnibus/git/refs/tags/$TAG_NAME | jq -r 'if type == "array" then .[].ref else .ref end' | grep -x "refs/tags/$TAG_NAME")
if [ "$EXACT_MATCH" == "refs/tags/$TAG_NAME" ]; then
echo "Tag $TAG_NAME already exists, skipping..." echo "Tag $TAG_NAME already exists, skipping..."
else else
echo "Creating tag in Infisical/infisical-omnibus: $TAG_NAME" echo "Creating tag in Infisical/infisical-omnibus: $TAG_NAME"

View File

@@ -6,7 +6,7 @@ ARG CAPTCHA_SITE_KEY=captcha-site-key
FROM node:20.19.5-trixie-slim AS base FROM node:20.19.5-trixie-slim AS base
# Fixes NPM vulnerability: https://security.snyk.io/vuln/SNYK-JS-CROSSSPAWN-8303230 # Fixes NPM vulnerability: https://security.snyk.io/vuln/SNYK-JS-CROSSSPAWN-8303230
RUN npm install -g npm@11 RUN npm install -g npm@10.9.0
FROM base AS frontend-dependencies FROM base AS frontend-dependencies
WORKDIR /app WORKDIR /app

View File

@@ -6,7 +6,7 @@ ARG CAPTCHA_SITE_KEY=captcha-site-key
FROM node:20.19.5-trixie-slim AS base FROM node:20.19.5-trixie-slim AS base
# Fixes NPM vulnerability: https://security.snyk.io/vuln/SNYK-JS-CROSSSPAWN-8303230 # Fixes NPM vulnerability: https://security.snyk.io/vuln/SNYK-JS-CROSSSPAWN-8303230
RUN npm install -g npm@11 RUN npm install -g npm@10.9.0
FROM base AS frontend-dependencies FROM base AS frontend-dependencies

View File

@@ -2,7 +2,9 @@ import knex, { Knex } from "knex";
const parseSslConfig = (dbConnectionUri: string, dbRootCert?: string) => { const parseSslConfig = (dbConnectionUri: string, dbRootCert?: string) => {
let modifiedDbConnectionUri = dbConnectionUri; let modifiedDbConnectionUri = dbConnectionUri;
let sslConfig: { rejectUnauthorized: boolean; ca: string } | boolean = false; let sslConfig: { rejectUnauthorized: boolean; ca: string } | boolean = dbRootCert
? { rejectUnauthorized: true, ca: Buffer.from(dbRootCert, "base64").toString("ascii") }
: false;
if (dbRootCert) { if (dbRootCert) {
const url = new URL(dbConnectionUri); const url = new URL(dbConnectionUri);

View File

@@ -0,0 +1,23 @@
import { Knex } from "knex";
import { TableName } from "../schemas";
export async function up(knex: Knex): Promise<void> {
const hasScopeColumn = await knex.schema.hasColumn(TableName.Membership, "scope");
const hasActorIdentityColumn = await knex.schema.hasColumn(TableName.Membership, "actorIdentityId");
if (hasScopeColumn && hasActorIdentityColumn) {
await knex.schema.alterTable(TableName.Membership, (t) => {
t.index(["scope", "actorIdentityId"]);
});
}
}
export async function down(knex: Knex): Promise<void> {
const hasScopeColumn = await knex.schema.hasColumn(TableName.Membership, "scope");
const hasActorIdentityColumn = await knex.schema.hasColumn(TableName.Membership, "actorIdentityId");
if (hasScopeColumn && hasActorIdentityColumn) {
await knex.schema.alterTable(TableName.Membership, (t) => {
t.dropIndex(["scope", "actorIdentityId"]);
});
}
}

View File

@@ -2,7 +2,6 @@ import net from "node:net";
import { ForbiddenError } from "@casl/ability"; import { ForbiddenError } from "@casl/ability";
import * as x509 from "@peculiar/x509"; import * as x509 from "@peculiar/x509";
import { CronJob } from "cron";
import { OrgMembershipRole, TRelays } from "@app/db/schemas"; import { OrgMembershipRole, TRelays } from "@app/db/schemas";
import { PgSqlLock } from "@app/keystore/keystore"; import { PgSqlLock } from "@app/keystore/keystore";
@@ -891,7 +890,7 @@ export const gatewayV2ServiceFactory = ({
}); });
}; };
const $healthcheckNotify = async () => { const healthcheckNotify = async () => {
const unhealthyGateways = await gatewayV2DAL.find({ const unhealthyGateways = await gatewayV2DAL.find({
isHeartbeatStale: true isHeartbeatStale: true
}); });
@@ -945,18 +944,6 @@ export const gatewayV2ServiceFactory = ({
} }
}; };
const initializeHealthcheckNotify = async () => {
logger.info("Setting up background notification process for gateway v2 health-checks");
await $healthcheckNotify();
// run every 5 minutes
const job = new CronJob("*/5 * * * *", $healthcheckNotify);
job.start();
return job;
};
return { return {
listGateways, listGateways,
registerGateway, registerGateway,
@@ -965,6 +952,6 @@ export const gatewayV2ServiceFactory = ({
deleteGatewayById, deleteGatewayById,
heartbeat, heartbeat,
getPamSessionKey, getPamSessionKey,
initializeHealthcheckNotify healthcheckNotify
}; };
}; };

View File

@@ -25,7 +25,9 @@ export const initializeHsmModule = (envConfig: Pick<TEnvConfig, "isHsmConfigured
logger.info("PKCS#11 module initialized"); logger.info("PKCS#11 module initialized");
} catch (error) { } catch (error) {
if (error instanceof pkcs11js.Pkcs11Error && error.code === pkcs11js.CKR_CRYPTOKI_ALREADY_INITIALIZED) { logger.error(error, "Failed to initialize PKCS#11 module");
if ((error as { message?: string })?.message === "CKR_CRYPTOKI_ALREADY_INITIALIZED") {
logger.info("Skipping HSM initialization because it's already initialized."); logger.info("Skipping HSM initialization because it's already initialized.");
} else { } else {
logger.error(error, "Failed to initialize PKCS#11 module"); logger.error(error, "Failed to initialize PKCS#11 module");

View File

@@ -44,7 +44,7 @@ export const licenseDALFactory = (db: TDbClient) => {
// count org identities // count org identities
const identityDoc = await (tx || db.replicaNode())(TableName.Membership) const identityDoc = await (tx || db.replicaNode())(TableName.Membership)
.where({ status: OrgMembershipStatus.Accepted, scope: AccessScope.Organization }) .where({ scope: AccessScope.Organization })
.whereNotNull(`${TableName.Membership}.actorIdentityId`) .whereNotNull(`${TableName.Membership}.actorIdentityId`)
.where((bd) => { .where((bd) => {
if (orgId) { if (orgId) {

View File

@@ -2,7 +2,6 @@ import { isIP } from "node:net";
import { ForbiddenError } from "@casl/ability"; import { ForbiddenError } from "@casl/ability";
import * as x509 from "@peculiar/x509"; import * as x509 from "@peculiar/x509";
import { CronJob } from "cron";
import { OrgMembershipRole, TRelays } from "@app/db/schemas"; import { OrgMembershipRole, TRelays } from "@app/db/schemas";
import { PgSqlLock } from "@app/keystore/keystore"; import { PgSqlLock } from "@app/keystore/keystore";
@@ -1209,7 +1208,7 @@ export const relayServiceFactory = ({
return deletedRelay; return deletedRelay;
}; };
const $healthcheckNotify = async () => { const healthcheckNotify = async () => {
const unhealthyRelays = await relayDAL.find({ const unhealthyRelays = await relayDAL.find({
isHeartbeatStale: true isHeartbeatStale: true
}); });
@@ -1283,18 +1282,6 @@ export const relayServiceFactory = ({
} }
}; };
const initializeHealthcheckNotify = async () => {
logger.info("Setting up background notification process for relay health-checks");
await $healthcheckNotify();
// run every 5 minutes
const job = new CronJob("*/5 * * * *", $healthcheckNotify);
job.start();
return job;
};
return { return {
registerRelay, registerRelay,
getCredentialsForGateway, getCredentialsForGateway,
@@ -1302,6 +1289,6 @@ export const relayServiceFactory = ({
getRelays, getRelays,
deleteRelay, deleteRelay,
heartbeat, heartbeat,
initializeHealthcheckNotify healthcheckNotify
}; };
}; };

View File

@@ -2356,6 +2356,9 @@ export const AppConnections = {
sslRejectUnauthorized: sslRejectUnauthorized:
"Whether or not to reject unauthorized SSL certificates (true/false). Set to false only in test environments with self-signed certificates.", "Whether or not to reject unauthorized SSL certificates (true/false). Set to false only in test environments with self-signed certificates.",
sslCertificate: "The SSL certificate (PEM format) to use for secure connection." sslCertificate: "The SSL certificate (PEM format) to use for secure connection."
},
LARAVEL_FORGE: {
apiToken: "The API token used to authenticate with Laravel Forge."
} }
} }
}; };
@@ -2508,6 +2511,14 @@ export const SecretSyncs = {
branch: "The branch to sync preview secrets to.", branch: "The branch to sync preview secrets to.",
teamId: "The ID of the Vercel team to sync secrets to." teamId: "The ID of the Vercel team to sync secrets to."
}, },
LARAVEL_FORGE: {
orgSlug: "The slug of the Laravel Forge org to sync secrets to.",
orgName: "The name of the Laravel Forge org to sync secrets to.",
serverId: "The ID of the Laravel Forge server to sync secrets to.",
serverName: "The name of the Laravel Forge server to sync secrets to.",
siteId: "The ID of the Laravel Forge site to sync secrets to.",
siteName: "The name of the Laravel Forge site to sync secrets to."
},
WINDMILL: { WINDMILL: {
workspace: "The Windmill workspace to sync secrets to.", workspace: "The Windmill workspace to sync secrets to.",
path: "The Windmill workspace path to sync secrets to." path: "The Windmill workspace path to sync secrets to."

View File

@@ -76,7 +76,8 @@ export enum QueueName {
TelemetryAggregatedEvents = "telemetry-aggregated-events", TelemetryAggregatedEvents = "telemetry-aggregated-events",
DailyReminders = "daily-reminders", DailyReminders = "daily-reminders",
SecretReminderMigration = "secret-reminder-migration", SecretReminderMigration = "secret-reminder-migration",
UserNotification = "user-notification" UserNotification = "user-notification",
HealthAlert = "health-alert"
} }
export enum QueueJobs { export enum QueueJobs {
@@ -124,7 +125,8 @@ export enum QueueJobs {
TelemetryAggregatedEvents = "telemetry-aggregated-events", TelemetryAggregatedEvents = "telemetry-aggregated-events",
DailyReminders = "daily-reminders", DailyReminders = "daily-reminders",
SecretReminderMigration = "secret-reminder-migration", SecretReminderMigration = "secret-reminder-migration",
UserNotification = "user-notification-job" UserNotification = "user-notification-job",
HealthAlert = "health-alert"
} }
export type TQueueJobTypes = { export type TQueueJobTypes = {
@@ -351,6 +353,10 @@ export type TQueueJobTypes = {
name: QueueJobs.UserNotification; name: QueueJobs.UserNotification;
payload: { notifications: TCreateUserNotificationDTO[] }; payload: { notifications: TCreateUserNotificationDTO[] };
}; };
[QueueName.HealthAlert]: {
name: QueueJobs.HealthAlert;
payload: undefined;
};
}; };
const SECRET_SCANNING_JOBS = [ const SECRET_SCANNING_JOBS = [

View File

@@ -194,6 +194,7 @@ import { folderTreeCheckpointDALFactory } from "@app/services/folder-tree-checkp
import { folderTreeCheckpointResourcesDALFactory } from "@app/services/folder-tree-checkpoint-resources/folder-tree-checkpoint-resources-dal"; import { folderTreeCheckpointResourcesDALFactory } from "@app/services/folder-tree-checkpoint-resources/folder-tree-checkpoint-resources-dal";
import { groupProjectDALFactory } from "@app/services/group-project/group-project-dal"; import { groupProjectDALFactory } from "@app/services/group-project/group-project-dal";
import { groupProjectServiceFactory } from "@app/services/group-project/group-project-service"; import { groupProjectServiceFactory } from "@app/services/group-project/group-project-service";
import { healthAlertServiceFactory } from "@app/services/health-alert/health-alert-queue";
import { identityDALFactory } from "@app/services/identity/identity-dal"; import { identityDALFactory } from "@app/services/identity/identity-dal";
import { identityMetadataDALFactory } from "@app/services/identity/identity-metadata-dal"; import { identityMetadataDALFactory } from "@app/services/identity/identity-metadata-dal";
import { identityOrgDALFactory } from "@app/services/identity/identity-org-dal"; import { identityOrgDALFactory } from "@app/services/identity/identity-org-dal";
@@ -1619,9 +1620,9 @@ export const registerRoutes = async (
const identityAccessTokenService = identityAccessTokenServiceFactory({ const identityAccessTokenService = identityAccessTokenServiceFactory({
identityAccessTokenDAL, identityAccessTokenDAL,
identityOrgMembershipDAL,
accessTokenQueue, accessTokenQueue,
identityDAL identityDAL,
membershipIdentityDAL
}); });
const identityTokenAuthService = identityTokenAuthServiceFactory({ const identityTokenAuthService = identityTokenAuthServiceFactory({
@@ -1807,6 +1808,7 @@ export const registerRoutes = async (
identityDAL identityDAL
}); });
// DAILY
const dailyResourceCleanUp = dailyResourceCleanUpQueueServiceFactory({ const dailyResourceCleanUp = dailyResourceCleanUpQueueServiceFactory({
auditLogDAL, auditLogDAL,
queueService, queueService,
@@ -1823,6 +1825,12 @@ export const registerRoutes = async (
keyValueStoreDAL keyValueStoreDAL
}); });
const healthAlert = healthAlertServiceFactory({
gatewayV2Service,
queueService,
relayService
});
const dailyReminderQueueService = dailyReminderQueueServiceFactory({ const dailyReminderQueueService = dailyReminderQueueServiceFactory({
reminderService, reminderService,
queueService, queueService,
@@ -2256,6 +2264,7 @@ export const registerRoutes = async (
await telemetryQueue.startTelemetryCheck(); await telemetryQueue.startTelemetryCheck();
await telemetryQueue.startAggregatedEventsJob(); await telemetryQueue.startAggregatedEventsJob();
await dailyResourceCleanUp.init(); await dailyResourceCleanUp.init();
await healthAlert.init();
await pkiSyncCleanup.init(); await pkiSyncCleanup.init();
await dailyReminderQueueService.startDailyRemindersJob(); await dailyReminderQueueService.startDailyRemindersJob();
await dailyReminderQueueService.startSecretReminderMigrationJob(); await dailyReminderQueueService.startSecretReminderMigrationJob();
@@ -2420,16 +2429,6 @@ export const registerRoutes = async (
cronJobs.push(configSyncJob); cronJobs.push(configSyncJob);
} }
const gatewayHealthcheckNotifyJob = await gatewayV2Service.initializeHealthcheckNotify();
if (gatewayHealthcheckNotifyJob) {
cronJobs.push(gatewayHealthcheckNotifyJob);
}
const relayHealthcheckNotifyJob = await relayService.initializeHealthcheckNotify();
if (relayHealthcheckNotifyJob) {
cronJobs.push(relayHealthcheckNotifyJob);
}
const oauthConfigSyncJob = await initializeOauthConfigSync(); const oauthConfigSyncJob = await initializeOauthConfigSync();
if (oauthConfigSyncJob) { if (oauthConfigSyncJob) {
cronJobs.push(oauthConfigSyncJob); cronJobs.push(oauthConfigSyncJob);

View File

@@ -77,6 +77,10 @@ import {
HumanitecConnectionListItemSchema, HumanitecConnectionListItemSchema,
SanitizedHumanitecConnectionSchema SanitizedHumanitecConnectionSchema
} from "@app/services/app-connection/humanitec"; } from "@app/services/app-connection/humanitec";
import {
LaravelForgeConnectionListItemSchema,
SanitizedLaravelForgeConnectionSchema
} from "@app/services/app-connection/laravel-forge";
import { LdapConnectionListItemSchema, SanitizedLdapConnectionSchema } from "@app/services/app-connection/ldap"; import { LdapConnectionListItemSchema, SanitizedLdapConnectionSchema } from "@app/services/app-connection/ldap";
import { MsSqlConnectionListItemSchema, SanitizedMsSqlConnectionSchema } from "@app/services/app-connection/mssql"; import { MsSqlConnectionListItemSchema, SanitizedMsSqlConnectionSchema } from "@app/services/app-connection/mssql";
import { MySqlConnectionListItemSchema, SanitizedMySqlConnectionSchema } from "@app/services/app-connection/mysql"; import { MySqlConnectionListItemSchema, SanitizedMySqlConnectionSchema } from "@app/services/app-connection/mysql";
@@ -158,7 +162,8 @@ const SanitizedAppConnectionSchema = z.union([
...SanitizedNetlifyConnectionSchema.options, ...SanitizedNetlifyConnectionSchema.options,
...SanitizedOktaConnectionSchema.options, ...SanitizedOktaConnectionSchema.options,
...SanitizedAzureADCSConnectionSchema.options, ...SanitizedAzureADCSConnectionSchema.options,
...SanitizedRedisConnectionSchema.options ...SanitizedRedisConnectionSchema.options,
...SanitizedLaravelForgeConnectionSchema.options
]); ]);
const AppConnectionOptionsSchema = z.discriminatedUnion("app", [ const AppConnectionOptionsSchema = z.discriminatedUnion("app", [
@@ -200,7 +205,8 @@ const AppConnectionOptionsSchema = z.discriminatedUnion("app", [
NetlifyConnectionListItemSchema, NetlifyConnectionListItemSchema,
OktaConnectionListItemSchema, OktaConnectionListItemSchema,
AzureADCSConnectionListItemSchema, AzureADCSConnectionListItemSchema,
RedisConnectionListItemSchema RedisConnectionListItemSchema,
LaravelForgeConnectionListItemSchema
]); ]);
export const registerAppConnectionRouter = async (server: FastifyZodProvider) => { export const registerAppConnectionRouter = async (server: FastifyZodProvider) => {

View File

@@ -24,6 +24,7 @@ import { registerGitLabConnectionRouter } from "./gitlab-connection-router";
import { registerHCVaultConnectionRouter } from "./hc-vault-connection-router"; import { registerHCVaultConnectionRouter } from "./hc-vault-connection-router";
import { registerHerokuConnectionRouter } from "./heroku-connection-router"; import { registerHerokuConnectionRouter } from "./heroku-connection-router";
import { registerHumanitecConnectionRouter } from "./humanitec-connection-router"; import { registerHumanitecConnectionRouter } from "./humanitec-connection-router";
import { registerLaravelForgeConnectionRouter } from "./laravel-forge-connection-router";
import { registerLdapConnectionRouter } from "./ldap-connection-router"; import { registerLdapConnectionRouter } from "./ldap-connection-router";
import { registerMsSqlConnectionRouter } from "./mssql-connection-router"; import { registerMsSqlConnectionRouter } from "./mssql-connection-router";
import { registerMySqlConnectionRouter } from "./mysql-connection-router"; import { registerMySqlConnectionRouter } from "./mysql-connection-router";
@@ -71,6 +72,7 @@ export const APP_CONNECTION_REGISTER_ROUTER_MAP: Record<AppConnection, (server:
[AppConnection.OnePass]: registerOnePassConnectionRouter, [AppConnection.OnePass]: registerOnePassConnectionRouter,
[AppConnection.Heroku]: registerHerokuConnectionRouter, [AppConnection.Heroku]: registerHerokuConnectionRouter,
[AppConnection.Render]: registerRenderConnectionRouter, [AppConnection.Render]: registerRenderConnectionRouter,
[AppConnection.LaravelForge]: registerLaravelForgeConnectionRouter,
[AppConnection.Flyio]: registerFlyioConnectionRouter, [AppConnection.Flyio]: registerFlyioConnectionRouter,
[AppConnection.GitLab]: registerGitLabConnectionRouter, [AppConnection.GitLab]: registerGitLabConnectionRouter,
[AppConnection.Cloudflare]: registerCloudflareConnectionRouter, [AppConnection.Cloudflare]: registerCloudflareConnectionRouter,

View File

@@ -0,0 +1,128 @@
import z from "zod";
import { readLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import {
CreateLaravelForgeConnectionSchema,
SanitizedLaravelForgeConnectionSchema,
UpdateLaravelForgeConnectionSchema
} from "@app/services/app-connection/laravel-forge";
import { AuthMode } from "@app/services/auth/auth-type";
import { registerAppConnectionEndpoints } from "./app-connection-endpoints";
export const registerLaravelForgeConnectionRouter = async (server: FastifyZodProvider) => {
registerAppConnectionEndpoints({
app: AppConnection.LaravelForge,
server,
sanitizedResponseSchema: SanitizedLaravelForgeConnectionSchema,
createSchema: CreateLaravelForgeConnectionSchema,
updateSchema: UpdateLaravelForgeConnectionSchema
});
server.route({
method: "GET",
url: `/:connectionId/organizations`,
config: {
rateLimit: readLimit
},
schema: {
params: z.object({
connectionId: z.string().uuid()
}),
response: {
200: z
.object({
id: z.string(),
name: z.string(),
slug: z.string()
})
.array()
}
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
const { connectionId } = req.params;
const organizations = await server.services.appConnection.laravelForge.listOrganizations(
connectionId,
req.permission
);
return organizations;
}
});
server.route({
method: "GET",
url: `/:connectionId/servers`,
config: {
rateLimit: readLimit
},
schema: {
params: z.object({
connectionId: z.string().uuid()
}),
querystring: z.object({
organizationSlug: z.string()
}),
response: {
200: z
.object({
id: z.string(),
name: z.string()
})
.array()
}
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
const { connectionId } = req.params;
const { organizationSlug } = req.query;
const servers = await server.services.appConnection.laravelForge.listServers(
connectionId,
req.permission,
organizationSlug
);
return servers;
}
});
server.route({
method: "GET",
url: `/:connectionId/sites`,
config: {
rateLimit: readLimit
},
schema: {
params: z.object({
connectionId: z.string().uuid()
}),
querystring: z.object({
organizationSlug: z.string(),
serverId: z.string()
}),
response: {
200: z
.object({
id: z.string(),
name: z.string()
})
.array()
}
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
const { connectionId } = req.params;
const { organizationSlug, serverId } = req.query;
const sites = await server.services.appConnection.laravelForge.listSites(
connectionId,
req.permission,
organizationSlug,
serverId
);
return sites;
}
});
};

View File

@@ -21,6 +21,7 @@ import { registerGitLabSyncRouter } from "./gitlab-sync-router";
import { registerHCVaultSyncRouter } from "./hc-vault-sync-router"; import { registerHCVaultSyncRouter } from "./hc-vault-sync-router";
import { registerHerokuSyncRouter } from "./heroku-sync-router"; import { registerHerokuSyncRouter } from "./heroku-sync-router";
import { registerHumanitecSyncRouter } from "./humanitec-sync-router"; import { registerHumanitecSyncRouter } from "./humanitec-sync-router";
import { registerLaravelForgeSyncRouter } from "./laravel-forge-sync-router";
import { registerNetlifySyncRouter } from "./netlify-sync-router"; import { registerNetlifySyncRouter } from "./netlify-sync-router";
import { registerRailwaySyncRouter } from "./railway-sync-router"; import { registerRailwaySyncRouter } from "./railway-sync-router";
import { registerRenderSyncRouter } from "./render-sync-router"; import { registerRenderSyncRouter } from "./render-sync-router";
@@ -63,5 +64,6 @@ export const SECRET_SYNC_REGISTER_ROUTER_MAP: Record<SecretSync, (server: Fastif
[SecretSync.Checkly]: registerChecklySyncRouter, [SecretSync.Checkly]: registerChecklySyncRouter,
[SecretSync.DigitalOceanAppPlatform]: registerDigitalOceanAppPlatformSyncRouter, [SecretSync.DigitalOceanAppPlatform]: registerDigitalOceanAppPlatformSyncRouter,
[SecretSync.Netlify]: registerNetlifySyncRouter, [SecretSync.Netlify]: registerNetlifySyncRouter,
[SecretSync.Bitbucket]: registerBitbucketSyncRouter [SecretSync.Bitbucket]: registerBitbucketSyncRouter,
[SecretSync.LaravelForge]: registerLaravelForgeSyncRouter
}; };

View File

@@ -0,0 +1,17 @@
import {
CreateLaravelForgeSyncSchema,
LaravelForgeSyncSchema,
UpdateLaravelForgeSyncSchema
} from "@app/services/secret-sync/laravel-forge";
import { SecretSync } from "@app/services/secret-sync/secret-sync-enums";
import { registerSyncSecretsEndpoints } from "./secret-sync-endpoints";
export const registerLaravelForgeSyncRouter = async (server: FastifyZodProvider) =>
registerSyncSecretsEndpoints({
destination: SecretSync.LaravelForge,
server,
responseSchema: LaravelForgeSyncSchema,
createSchema: CreateLaravelForgeSyncSchema,
updateSchema: UpdateLaravelForgeSyncSchema
});

View File

@@ -44,6 +44,7 @@ import { GitLabSyncListItemSchema, GitLabSyncSchema } from "@app/services/secret
import { HCVaultSyncListItemSchema, HCVaultSyncSchema } from "@app/services/secret-sync/hc-vault"; import { HCVaultSyncListItemSchema, HCVaultSyncSchema } from "@app/services/secret-sync/hc-vault";
import { HerokuSyncListItemSchema, HerokuSyncSchema } from "@app/services/secret-sync/heroku"; import { HerokuSyncListItemSchema, HerokuSyncSchema } from "@app/services/secret-sync/heroku";
import { HumanitecSyncListItemSchema, HumanitecSyncSchema } from "@app/services/secret-sync/humanitec"; import { HumanitecSyncListItemSchema, HumanitecSyncSchema } from "@app/services/secret-sync/humanitec";
import { LaravelForgeSyncListItemSchema, LaravelForgeSyncSchema } from "@app/services/secret-sync/laravel-forge";
import { NetlifySyncListItemSchema, NetlifySyncSchema } from "@app/services/secret-sync/netlify"; import { NetlifySyncListItemSchema, NetlifySyncSchema } from "@app/services/secret-sync/netlify";
import { RailwaySyncListItemSchema, RailwaySyncSchema } from "@app/services/secret-sync/railway/railway-sync-schemas"; import { RailwaySyncListItemSchema, RailwaySyncSchema } from "@app/services/secret-sync/railway/railway-sync-schemas";
import { RenderSyncListItemSchema, RenderSyncSchema } from "@app/services/secret-sync/render/render-sync-schemas"; import { RenderSyncListItemSchema, RenderSyncSchema } from "@app/services/secret-sync/render/render-sync-schemas";
@@ -84,7 +85,8 @@ const SecretSyncSchema = z.discriminatedUnion("destination", [
ChecklySyncSchema, ChecklySyncSchema,
DigitalOceanAppPlatformSyncSchema, DigitalOceanAppPlatformSyncSchema,
NetlifySyncSchema, NetlifySyncSchema,
BitbucketSyncSchema BitbucketSyncSchema,
LaravelForgeSyncSchema
]); ]);
const SecretSyncOptionsSchema = z.discriminatedUnion("destination", [ const SecretSyncOptionsSchema = z.discriminatedUnion("destination", [
@@ -117,7 +119,8 @@ const SecretSyncOptionsSchema = z.discriminatedUnion("destination", [
ChecklySyncListItemSchema, ChecklySyncListItemSchema,
SupabaseSyncListItemSchema, SupabaseSyncListItemSchema,
NetlifySyncListItemSchema, NetlifySyncListItemSchema,
BitbucketSyncListItemSchema BitbucketSyncListItemSchema,
LaravelForgeSyncListItemSchema
]); ]);
export const registerSecretSyncRouter = async (server: FastifyZodProvider) => { export const registerSecretSyncRouter = async (server: FastifyZodProvider) => {

View File

@@ -37,7 +37,8 @@ export enum AppConnection {
DigitalOcean = "digital-ocean", DigitalOcean = "digital-ocean",
Netlify = "netlify", Netlify = "netlify",
Okta = "okta", Okta = "okta",
Redis = "redis" Redis = "redis",
LaravelForge = "laravel-forge"
} }
export enum AWSRegion { export enum AWSRegion {

View File

@@ -103,6 +103,11 @@ import {
HumanitecConnectionMethod, HumanitecConnectionMethod,
validateHumanitecConnectionCredentials validateHumanitecConnectionCredentials
} from "./humanitec"; } from "./humanitec";
import {
getLaravelForgeConnectionListItem,
LaravelForgeConnectionMethod,
validateLaravelForgeConnectionCredentials
} from "./laravel-forge";
import { getLdapConnectionListItem, LdapConnectionMethod, validateLdapConnectionCredentials } from "./ldap"; import { getLdapConnectionListItem, LdapConnectionMethod, validateLdapConnectionCredentials } from "./ldap";
import { getMsSqlConnectionListItem, MsSqlConnectionMethod } from "./mssql"; import { getMsSqlConnectionListItem, MsSqlConnectionMethod } from "./mssql";
import { MySqlConnectionMethod } from "./mysql/mysql-connection-enums"; import { MySqlConnectionMethod } from "./mysql/mysql-connection-enums";
@@ -187,6 +192,7 @@ export const listAppConnectionOptions = (projectType?: ProjectType) => {
getOnePassConnectionListItem(), getOnePassConnectionListItem(),
getHerokuConnectionListItem(), getHerokuConnectionListItem(),
getRenderConnectionListItem(), getRenderConnectionListItem(),
getLaravelForgeConnectionListItem(),
getFlyioConnectionListItem(), getFlyioConnectionListItem(),
getGitLabConnectionListItem(), getGitLabConnectionListItem(),
getCloudflareConnectionListItem(), getCloudflareConnectionListItem(),
@@ -316,6 +322,7 @@ export const validateAppConnectionCredentials = async (
[AppConnection.OnePass]: validateOnePassConnectionCredentials as TAppConnectionCredentialsValidator, [AppConnection.OnePass]: validateOnePassConnectionCredentials as TAppConnectionCredentialsValidator,
[AppConnection.Heroku]: validateHerokuConnectionCredentials as TAppConnectionCredentialsValidator, [AppConnection.Heroku]: validateHerokuConnectionCredentials as TAppConnectionCredentialsValidator,
[AppConnection.Render]: validateRenderConnectionCredentials as TAppConnectionCredentialsValidator, [AppConnection.Render]: validateRenderConnectionCredentials as TAppConnectionCredentialsValidator,
[AppConnection.LaravelForge]: validateLaravelForgeConnectionCredentials as TAppConnectionCredentialsValidator,
[AppConnection.Flyio]: validateFlyioConnectionCredentials as TAppConnectionCredentialsValidator, [AppConnection.Flyio]: validateFlyioConnectionCredentials as TAppConnectionCredentialsValidator,
[AppConnection.GitLab]: validateGitLabConnectionCredentials as TAppConnectionCredentialsValidator, [AppConnection.GitLab]: validateGitLabConnectionCredentials as TAppConnectionCredentialsValidator,
[AppConnection.Cloudflare]: validateCloudflareConnectionCredentials as TAppConnectionCredentialsValidator, [AppConnection.Cloudflare]: validateCloudflareConnectionCredentials as TAppConnectionCredentialsValidator,
@@ -368,6 +375,7 @@ export const getAppConnectionMethodName = (method: TAppConnection["method"]) =>
case ZabbixConnectionMethod.ApiToken: case ZabbixConnectionMethod.ApiToken:
case DigitalOceanConnectionMethod.ApiToken: case DigitalOceanConnectionMethod.ApiToken:
case OktaConnectionMethod.ApiToken: case OktaConnectionMethod.ApiToken:
case LaravelForgeConnectionMethod.ApiToken:
return "API Token"; return "API Token";
case PostgresConnectionMethod.UsernameAndPassword: case PostgresConnectionMethod.UsernameAndPassword:
case MsSqlConnectionMethod.UsernameAndPassword: case MsSqlConnectionMethod.UsernameAndPassword:
@@ -463,7 +471,8 @@ export const TRANSITION_CONNECTION_CREDENTIALS_TO_PLATFORM: Record<
[AppConnection.DigitalOcean]: platformManagedCredentialsNotSupported, [AppConnection.DigitalOcean]: platformManagedCredentialsNotSupported,
[AppConnection.Netlify]: platformManagedCredentialsNotSupported, [AppConnection.Netlify]: platformManagedCredentialsNotSupported,
[AppConnection.Okta]: platformManagedCredentialsNotSupported, [AppConnection.Okta]: platformManagedCredentialsNotSupported,
[AppConnection.Redis]: platformManagedCredentialsNotSupported [AppConnection.Redis]: platformManagedCredentialsNotSupported,
[AppConnection.LaravelForge]: platformManagedCredentialsNotSupported
}; };
export const enterpriseAppCheck = async ( export const enterpriseAppCheck = async (

View File

@@ -28,6 +28,7 @@ export const APP_CONNECTION_NAME_MAP: Record<AppConnection, string> = {
[AppConnection.OnePass]: "1Password", [AppConnection.OnePass]: "1Password",
[AppConnection.Heroku]: "Heroku", [AppConnection.Heroku]: "Heroku",
[AppConnection.Render]: "Render", [AppConnection.Render]: "Render",
[AppConnection.LaravelForge]: "Laravel Forge",
[AppConnection.Flyio]: "Fly.io", [AppConnection.Flyio]: "Fly.io",
[AppConnection.GitLab]: "GitLab", [AppConnection.GitLab]: "GitLab",
[AppConnection.Cloudflare]: "Cloudflare", [AppConnection.Cloudflare]: "Cloudflare",
@@ -70,6 +71,7 @@ export const APP_CONNECTION_PLAN_MAP: Record<AppConnection, AppConnectionPlanTyp
[AppConnection.MySql]: AppConnectionPlanType.Regular, [AppConnection.MySql]: AppConnectionPlanType.Regular,
[AppConnection.Heroku]: AppConnectionPlanType.Regular, [AppConnection.Heroku]: AppConnectionPlanType.Regular,
[AppConnection.Render]: AppConnectionPlanType.Regular, [AppConnection.Render]: AppConnectionPlanType.Regular,
[AppConnection.LaravelForge]: AppConnectionPlanType.Regular,
[AppConnection.Flyio]: AppConnectionPlanType.Regular, [AppConnection.Flyio]: AppConnectionPlanType.Regular,
[AppConnection.GitLab]: AppConnectionPlanType.Regular, [AppConnection.GitLab]: AppConnectionPlanType.Regular,
[AppConnection.Cloudflare]: AppConnectionPlanType.Regular, [AppConnection.Cloudflare]: AppConnectionPlanType.Regular,

View File

@@ -89,6 +89,8 @@ import { ValidateHerokuConnectionCredentialsSchema } from "./heroku";
import { herokuConnectionService } from "./heroku/heroku-connection-service"; import { herokuConnectionService } from "./heroku/heroku-connection-service";
import { ValidateHumanitecConnectionCredentialsSchema } from "./humanitec"; import { ValidateHumanitecConnectionCredentialsSchema } from "./humanitec";
import { humanitecConnectionService } from "./humanitec/humanitec-connection-service"; import { humanitecConnectionService } from "./humanitec/humanitec-connection-service";
import { ValidateLaravelForgeConnectionCredentialsSchema } from "./laravel-forge";
import { laravelForgeConnectionService } from "./laravel-forge/laravel-forge-connection-service";
import { ValidateLdapConnectionCredentialsSchema } from "./ldap"; import { ValidateLdapConnectionCredentialsSchema } from "./ldap";
import { ValidateMsSqlConnectionCredentialsSchema } from "./mssql"; import { ValidateMsSqlConnectionCredentialsSchema } from "./mssql";
import { ValidateMySqlConnectionCredentialsSchema } from "./mysql"; import { ValidateMySqlConnectionCredentialsSchema } from "./mysql";
@@ -157,6 +159,7 @@ const VALIDATE_APP_CONNECTION_CREDENTIALS_MAP: Record<AppConnection, TValidateAp
[AppConnection.OnePass]: ValidateOnePassConnectionCredentialsSchema, [AppConnection.OnePass]: ValidateOnePassConnectionCredentialsSchema,
[AppConnection.Heroku]: ValidateHerokuConnectionCredentialsSchema, [AppConnection.Heroku]: ValidateHerokuConnectionCredentialsSchema,
[AppConnection.Render]: ValidateRenderConnectionCredentialsSchema, [AppConnection.Render]: ValidateRenderConnectionCredentialsSchema,
[AppConnection.LaravelForge]: ValidateLaravelForgeConnectionCredentialsSchema,
[AppConnection.Flyio]: ValidateFlyioConnectionCredentialsSchema, [AppConnection.Flyio]: ValidateFlyioConnectionCredentialsSchema,
[AppConnection.GitLab]: ValidateGitLabConnectionCredentialsSchema, [AppConnection.GitLab]: ValidateGitLabConnectionCredentialsSchema,
[AppConnection.Cloudflare]: ValidateCloudflareConnectionCredentialsSchema, [AppConnection.Cloudflare]: ValidateCloudflareConnectionCredentialsSchema,
@@ -864,6 +867,7 @@ export const appConnectionServiceFactory = ({
supabase: supabaseConnectionService(connectAppConnectionById), supabase: supabaseConnectionService(connectAppConnectionById),
digitalOcean: digitalOceanAppPlatformConnectionService(connectAppConnectionById), digitalOcean: digitalOceanAppPlatformConnectionService(connectAppConnectionById),
netlify: netlifyConnectionService(connectAppConnectionById), netlify: netlifyConnectionService(connectAppConnectionById),
okta: oktaConnectionService(connectAppConnectionById) okta: oktaConnectionService(connectAppConnectionById),
laravelForge: laravelForgeConnectionService(connectAppConnectionById)
}; };
}; };

View File

@@ -148,6 +148,12 @@ import {
THumanitecConnectionInput, THumanitecConnectionInput,
TValidateHumanitecConnectionCredentialsSchema TValidateHumanitecConnectionCredentialsSchema
} from "./humanitec"; } from "./humanitec";
import {
TLaravelForgeConnection,
TLaravelForgeConnectionConfig,
TLaravelForgeConnectionInput,
TValidateLaravelForgeConnectionCredentialsSchema
} from "./laravel-forge";
import { import {
TLdapConnection, TLdapConnection,
TLdapConnectionConfig, TLdapConnectionConfig,
@@ -256,6 +262,7 @@ export type TAppConnection = { id: string } & (
| TOnePassConnection | TOnePassConnection
| THerokuConnection | THerokuConnection
| TRenderConnection | TRenderConnection
| TLaravelForgeConnection
| TFlyioConnection | TFlyioConnection
| TGitLabConnection | TGitLabConnection
| TCloudflareConnection | TCloudflareConnection
@@ -302,6 +309,7 @@ export type TAppConnectionInput = { id: string } & (
| TOnePassConnectionInput | TOnePassConnectionInput
| THerokuConnectionInput | THerokuConnectionInput
| TRenderConnectionInput | TRenderConnectionInput
| TLaravelForgeConnectionInput
| TFlyioConnectionInput | TFlyioConnectionInput
| TGitLabConnectionInput | TGitLabConnectionInput
| TCloudflareConnectionInput | TCloudflareConnectionInput
@@ -366,6 +374,7 @@ export type TAppConnectionConfig =
| TOnePassConnectionConfig | TOnePassConnectionConfig
| THerokuConnectionConfig | THerokuConnectionConfig
| TRenderConnectionConfig | TRenderConnectionConfig
| TLaravelForgeConnectionConfig
| TFlyioConnectionConfig | TFlyioConnectionConfig
| TGitLabConnectionConfig | TGitLabConnectionConfig
| TCloudflareConnectionConfig | TCloudflareConnectionConfig
@@ -407,6 +416,7 @@ export type TValidateAppConnectionCredentialsSchema =
| TValidateOnePassConnectionCredentialsSchema | TValidateOnePassConnectionCredentialsSchema
| TValidateHerokuConnectionCredentialsSchema | TValidateHerokuConnectionCredentialsSchema
| TValidateRenderConnectionCredentialsSchema | TValidateRenderConnectionCredentialsSchema
| TValidateLaravelForgeConnectionCredentialsSchema
| TValidateFlyioConnectionCredentialsSchema | TValidateFlyioConnectionCredentialsSchema
| TValidateGitLabConnectionCredentialsSchema | TValidateGitLabConnectionCredentialsSchema
| TValidateCloudflareConnectionCredentialsSchema | TValidateCloudflareConnectionCredentialsSchema

View File

@@ -0,0 +1,4 @@
export * from "./laravel-forge-connection-enums";
export * from "./laravel-forge-connection-fns";
export * from "./laravel-forge-connection-schemas";
export * from "./laravel-forge-connection-types";

View File

@@ -0,0 +1,3 @@
export enum LaravelForgeConnectionMethod {
ApiToken = "api-token"
}

View File

@@ -0,0 +1,165 @@
/* eslint-disable no-await-in-loop */
import { AxiosError } from "axios";
import { request } from "@app/lib/config/request";
import { BadRequestError, InternalServerError } from "@app/lib/errors";
import { IntegrationUrls } from "@app/services/integration-auth/integration-list";
import { AppConnection } from "../app-connection-enums";
import { LaravelForgeConnectionMethod } from "./laravel-forge-connection-enums";
import {
TLaravelForgeConnection,
TLaravelForgeConnectionConfig,
TLaravelForgeOrganization,
TLaravelForgeServer,
TLaravelForgeSite,
TRawLaravelForgeOrganization,
TRawLaravelForgeServer,
TRawLaravelForgeSite
} from "./laravel-forge-connection-types";
export const getLaravelForgeConnectionListItem = () => {
return {
name: "Laravel Forge" as const,
app: AppConnection.LaravelForge as const,
methods: Object.values(LaravelForgeConnectionMethod) as [LaravelForgeConnectionMethod.ApiToken]
};
};
export const validateLaravelForgeConnectionCredentials = async (config: TLaravelForgeConnectionConfig) => {
const { credentials: inputCredentials } = config;
try {
// Using the /api/me endpoint to validate the API token
await request.get(`${IntegrationUrls.LARAVELFORGE_API_URL}/api/me`, {
headers: {
Authorization: `Bearer ${inputCredentials.apiToken}`,
Accept: "application/json",
"Content-Type": "application/json"
}
});
} catch (error) {
if (error instanceof AxiosError) {
throw new BadRequestError({
message: `Failed to validate credentials: ${error.message || "Unknown error"}`
});
}
throw new BadRequestError({
message: "Unable to validate connection: verify credentials"
});
}
return inputCredentials;
};
type TLaravelForgeApiResponse<T> = {
data: T[];
links?: {
next?: string;
};
meta?: {
next_cursor?: string;
prev_cursor?: string | null;
};
};
const fetchAllPages = async <T>(
apiToken: string,
url: string,
params?: Record<string, string | number>
): Promise<T[]> => {
const allItems: T[] = [];
let nextUrl: string | null = url;
const queryParams = params || {};
while (nextUrl) {
try {
const response: { data: TLaravelForgeApiResponse<T> } = await request.get<TLaravelForgeApiResponse<T>>(nextUrl, {
params: queryParams,
headers: {
Authorization: `Bearer ${apiToken}`,
Accept: "application/json",
"Content-Type": "application/json"
}
});
if (!response?.data?.data) {
throw new InternalServerError({
message: `Failed to fetch data from ${url}: Response was empty or malformed`
});
}
allItems.push(...response.data.data);
if (response.data.links?.next) {
nextUrl = response.data.links.next;
} else {
nextUrl = null;
}
} catch (error) {
if (error instanceof AxiosError) {
throw new BadRequestError({
message: `Failed to fetch data from ${url}: ${error.message || "Unknown error"}`
});
}
throw error;
}
}
return allItems;
};
export const listLaravelForgeOrganizations = async (
appConnection: TLaravelForgeConnection
): Promise<TLaravelForgeOrganization[]> => {
const { credentials } = appConnection;
const { apiToken } = credentials;
const rawOrganizations = await fetchAllPages<TRawLaravelForgeOrganization>(
apiToken,
`${IntegrationUrls.LARAVELFORGE_API_URL}/api/orgs`
);
return rawOrganizations.map((org: TRawLaravelForgeOrganization) => ({
id: org.id,
name: org.attributes.name,
slug: org.attributes.slug
}));
};
export const listLaravelForgeServers = async (
appConnection: TLaravelForgeConnection,
organizationSlug: string
): Promise<TLaravelForgeServer[]> => {
const { credentials } = appConnection;
const { apiToken } = credentials;
const rawServers = await fetchAllPages<TRawLaravelForgeServer>(
apiToken,
`${IntegrationUrls.LARAVELFORGE_API_URL}/api/orgs/${organizationSlug}/servers`
);
return rawServers.map((server: TRawLaravelForgeServer) => ({
id: server.id,
name: server.attributes.name
}));
};
export const listLaravelForgeSites = async (
appConnection: TLaravelForgeConnection,
organizationSlug: string,
serverId: string
): Promise<TLaravelForgeSite[]> => {
const { credentials } = appConnection;
const { apiToken } = credentials;
const rawSites = await fetchAllPages<TRawLaravelForgeSite>(
apiToken,
`${IntegrationUrls.LARAVELFORGE_API_URL}/api/orgs/${organizationSlug}/servers/${serverId}/sites`
);
return rawSites.map((site: TRawLaravelForgeSite) => ({
id: site.id,
name: site.attributes.name
}));
};

View File

@@ -0,0 +1,58 @@
import z from "zod";
import { AppConnections } from "@app/lib/api-docs";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import {
BaseAppConnectionSchema,
GenericCreateAppConnectionFieldsSchema,
GenericUpdateAppConnectionFieldsSchema
} from "@app/services/app-connection/app-connection-schemas";
import { LaravelForgeConnectionMethod } from "./laravel-forge-connection-enums";
export const LaravelForgeConnectionApiTokenCredentialsSchema = z.object({
apiToken: z.string().trim().min(1, "API token required").describe(AppConnections.CREDENTIALS.LARAVEL_FORGE.apiToken)
});
const BaseLaravelForgeConnectionSchema = BaseAppConnectionSchema.extend({ app: z.literal(AppConnection.LaravelForge) });
export const LaravelForgeConnectionSchema = BaseLaravelForgeConnectionSchema.extend({
method: z.literal(LaravelForgeConnectionMethod.ApiToken),
credentials: LaravelForgeConnectionApiTokenCredentialsSchema
});
export const SanitizedLaravelForgeConnectionSchema = z.discriminatedUnion("method", [
BaseLaravelForgeConnectionSchema.extend({
method: z.literal(LaravelForgeConnectionMethod.ApiToken),
credentials: LaravelForgeConnectionApiTokenCredentialsSchema.pick({})
})
]);
export const ValidateLaravelForgeConnectionCredentialsSchema = z.discriminatedUnion("method", [
z.object({
method: z
.literal(LaravelForgeConnectionMethod.ApiToken)
.describe(AppConnections.CREATE(AppConnection.LaravelForge).method),
credentials: LaravelForgeConnectionApiTokenCredentialsSchema.describe(
AppConnections.CREATE(AppConnection.LaravelForge).credentials
)
})
]);
export const CreateLaravelForgeConnectionSchema = ValidateLaravelForgeConnectionCredentialsSchema.and(
GenericCreateAppConnectionFieldsSchema(AppConnection.LaravelForge)
);
export const UpdateLaravelForgeConnectionSchema = z
.object({
credentials: LaravelForgeConnectionApiTokenCredentialsSchema.optional().describe(
AppConnections.UPDATE(AppConnection.LaravelForge).credentials
)
})
.and(GenericUpdateAppConnectionFieldsSchema(AppConnection.LaravelForge));
export const LaravelForgeConnectionListItemSchema = z.object({
name: z.literal("Laravel Forge"),
app: z.literal(AppConnection.LaravelForge),
methods: z.nativeEnum(LaravelForgeConnectionMethod).array()
});

View File

@@ -0,0 +1,74 @@
import { logger } from "@app/lib/logger";
import { OrgServiceActor } from "@app/lib/types";
import { AppConnection } from "../app-connection-enums";
import {
listLaravelForgeOrganizations,
listLaravelForgeServers,
listLaravelForgeSites
} from "./laravel-forge-connection-fns";
import {
TLaravelForgeConnection,
TLaravelForgeOrganization,
TLaravelForgeServer,
TLaravelForgeSite
} from "./laravel-forge-connection-types";
type TGetAppConnectionFunc = (
app: AppConnection,
connectionId: string,
actor: OrgServiceActor
) => Promise<TLaravelForgeConnection>;
export const laravelForgeConnectionService = (getAppConnection: TGetAppConnectionFunc) => {
const listOrganizations = async (
connectionId: string,
actor: OrgServiceActor
): Promise<TLaravelForgeOrganization[]> => {
const appConnection = await getAppConnection(AppConnection.LaravelForge, connectionId, actor);
try {
const organizations = await listLaravelForgeOrganizations(appConnection);
return organizations;
} catch (error) {
logger.error(error, "Failed to list organizations for Laravel Forge connection");
return [];
}
};
const listServers = async (
connectionId: string,
actor: OrgServiceActor,
organizationSlug: string
): Promise<TLaravelForgeServer[]> => {
const appConnection = await getAppConnection(AppConnection.LaravelForge, connectionId, actor);
try {
const servers = await listLaravelForgeServers(appConnection, organizationSlug);
return servers;
} catch (error) {
logger.error(error, "Failed to list servers for Laravel Forge connection");
return [];
}
};
const listSites = async (
connectionId: string,
actor: OrgServiceActor,
organizationSlug: string,
serverId: string
): Promise<TLaravelForgeSite[]> => {
const appConnection = await getAppConnection(AppConnection.LaravelForge, connectionId, actor);
try {
const sites = await listLaravelForgeSites(appConnection, organizationSlug, serverId);
return sites;
} catch (error) {
logger.error(error, "Failed to list sites for Laravel Forge connection");
return [];
}
};
return {
listOrganizations,
listServers,
listSites
};
};

View File

@@ -0,0 +1,63 @@
import z from "zod";
import { DiscriminativePick } from "@app/lib/types";
import { AppConnection } from "../app-connection-enums";
import {
CreateLaravelForgeConnectionSchema,
LaravelForgeConnectionSchema,
ValidateLaravelForgeConnectionCredentialsSchema
} from "./laravel-forge-connection-schemas";
export type TLaravelForgeConnection = z.infer<typeof LaravelForgeConnectionSchema>;
export type TLaravelForgeConnectionInput = z.infer<typeof CreateLaravelForgeConnectionSchema> & {
app: AppConnection.LaravelForge;
};
export type TValidateLaravelForgeConnectionCredentialsSchema = typeof ValidateLaravelForgeConnectionCredentialsSchema;
export type TLaravelForgeConnectionConfig = DiscriminativePick<
TLaravelForgeConnectionInput,
"method" | "app" | "credentials"
> & {
orgSlug: string;
};
export type TLaravelForgeOrganization = {
id: string;
name: string;
slug: string;
};
export type TLaravelForgeServer = {
id: string;
name: string;
};
export type TLaravelForgeSite = {
id: string;
name: string;
};
export type TRawLaravelForgeOrganization = {
id: string;
attributes: {
name: string;
slug: string;
};
};
export type TRawLaravelForgeServer = {
id: string;
attributes: {
name: string;
};
};
export type TRawLaravelForgeSite = {
id: string;
attributes: {
name: string;
};
};

View File

@@ -0,0 +1,65 @@
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { TRelayServiceFactory } from "@app/ee/services/relay/relay-service";
import { getConfig } from "@app/lib/config/env";
import { logger } from "@app/lib/logger";
import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
type THealthAlertServiceFactoryDep = {
queueService: TQueueServiceFactory;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "healthcheckNotify">;
relayService: Pick<TRelayServiceFactory, "healthcheckNotify">;
};
export type THealthAlertServiceFactory = ReturnType<typeof healthAlertServiceFactory>;
export const healthAlertServiceFactory = ({
queueService,
gatewayV2Service,
relayService
}: THealthAlertServiceFactoryDep) => {
const appCfg = getConfig();
const init = async () => {
if (appCfg.isSecondaryInstance) {
return;
}
await queueService.stopRepeatableJob(
QueueName.HealthAlert,
QueueJobs.HealthAlert,
{ pattern: "*/5 * * * *", utc: true },
QueueName.HealthAlert // job id
);
await queueService.startPg<QueueName.HealthAlert>(
QueueJobs.HealthAlert,
async () => {
try {
logger.info(`${QueueName.HealthAlert}: health check alert task started`);
await gatewayV2Service.healthcheckNotify();
await relayService.healthcheckNotify();
logger.info(`${QueueName.HealthAlert}: health check alert task completed`);
} catch (error) {
logger.error(error, `${QueueName.HealthAlert}: health check alert failed`);
throw error;
}
},
{
batchSize: 1,
workerCount: 1,
pollingIntervalSeconds: 60
}
);
await queueService.schedulePg(
QueueJobs.HealthAlert,
"*/5 * * * *", // Schedule to run every 5 minutes
undefined,
{ tz: "UTC" }
);
};
return {
init
};
};

View File

@@ -1,4 +1,4 @@
import { IdentityAuthMethod, TableName, TIdentityAccessTokens } from "@app/db/schemas"; import { AccessScope, IdentityAuthMethod, TableName, TIdentityAccessTokens } from "@app/db/schemas";
import { getConfig } from "@app/lib/config/env"; import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto"; import { crypto } from "@app/lib/crypto";
import { BadRequestError, UnauthorizedError } from "@app/lib/errors"; import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
@@ -7,27 +7,27 @@ import { checkIPAgainstBlocklist, TIp } from "@app/lib/ip";
import { TAccessTokenQueueServiceFactory } from "../access-token-queue/access-token-queue"; import { TAccessTokenQueueServiceFactory } from "../access-token-queue/access-token-queue";
import { AuthTokenType } from "../auth/auth-type"; import { AuthTokenType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal"; import { TIdentityDALFactory } from "../identity/identity-dal";
import { TIdentityOrgDALFactory } from "../identity/identity-org-dal"; import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";
import { TIdentityAccessTokenDALFactory } from "./identity-access-token-dal"; import { TIdentityAccessTokenDALFactory } from "./identity-access-token-dal";
import { TIdentityAccessTokenJwtPayload, TRenewAccessTokenDTO } from "./identity-access-token-types"; import { TIdentityAccessTokenJwtPayload, TRenewAccessTokenDTO } from "./identity-access-token-types";
type TIdentityAccessTokenServiceFactoryDep = { type TIdentityAccessTokenServiceFactoryDep = {
identityAccessTokenDAL: TIdentityAccessTokenDALFactory; identityAccessTokenDAL: TIdentityAccessTokenDALFactory;
identityDAL: Pick<TIdentityDALFactory, "getTrustedIpsByAuthMethod">; identityDAL: Pick<TIdentityDALFactory, "getTrustedIpsByAuthMethod">;
identityOrgMembershipDAL: TIdentityOrgDALFactory;
accessTokenQueue: Pick< accessTokenQueue: Pick<
TAccessTokenQueueServiceFactory, TAccessTokenQueueServiceFactory,
"updateIdentityAccessTokenStatus" | "getIdentityTokenDetailsInCache" "updateIdentityAccessTokenStatus" | "getIdentityTokenDetailsInCache"
>; >;
membershipIdentityDAL: Pick<TMembershipIdentityDALFactory, "findOne">;
}; };
export type TIdentityAccessTokenServiceFactory = ReturnType<typeof identityAccessTokenServiceFactory>; export type TIdentityAccessTokenServiceFactory = ReturnType<typeof identityAccessTokenServiceFactory>;
export const identityAccessTokenServiceFactory = ({ export const identityAccessTokenServiceFactory = ({
identityAccessTokenDAL, identityAccessTokenDAL,
identityOrgMembershipDAL,
accessTokenQueue, accessTokenQueue,
identityDAL identityDAL,
membershipIdentityDAL
}: TIdentityAccessTokenServiceFactoryDep) => { }: TIdentityAccessTokenServiceFactoryDep) => {
const validateAccessTokenExp = async (identityAccessToken: TIdentityAccessTokens) => { const validateAccessTokenExp = async (identityAccessToken: TIdentityAccessTokens) => {
const { const {
@@ -202,8 +202,8 @@ export const identityAccessTokenServiceFactory = ({
trustedIps: trustedIps as TIp[] trustedIps: trustedIps as TIp[]
}); });
} }
const identityOrgMembership = await membershipIdentityDAL.findOne({
const identityOrgMembership = await identityOrgMembershipDAL.findOne({ scope: AccessScope.Organization,
actorIdentityId: identityAccessToken.identityId actorIdentityId: identityAccessToken.identityId
}); });

View File

@@ -742,23 +742,27 @@ export const kmsServiceFactory = ({
if (!project.kmsSecretManagerEncryptedDataKey) { if (!project.kmsSecretManagerEncryptedDataKey) {
const lock = await keyStore const lock = await keyStore
.acquireLock([KeyStorePrefixes.KmsProjectDataKeyCreation, projectId], 3000, { retryCount: 0 }) .acquireLock([KeyStorePrefixes.KmsProjectDataKeyCreation, projectId], 3000, { retryCount: 0 })
.catch(() => null); .catch((err) => {
logger.error(err, "KMS. Failed to acquire lock.");
return null;
});
try { try {
if (!lock) { if (!lock) {
await keyStore.waitTillReady({ await keyStore.waitTillReady({
key: `${KeyStorePrefixes.WaitUntilReadyKmsProjectDataKeyCreation}${projectId}`, key: `${KeyStorePrefixes.WaitUntilReadyKmsProjectDataKeyCreation}${projectId}`,
keyCheckCb: (val) => val === "true", keyCheckCb: (val) => val === "true",
waitingCb: () => logger.debug("KMS. Waiting for secret manager data key to be created"), waitingCb: () => logger.info("KMS. Waiting for secret manager data key to be created"),
delay: 500 delay: 500
}); });
project = await projectDAL.findById(projectId, trx); project = await projectDAL.findById(projectId, trx);
} else { } else {
logger.info(`KMS. Generating KMS key for project ${projectId}`);
const projectDataKey = await (trx || projectDAL).transaction(async (tx) => { const projectDataKey = await (trx || projectDAL).transaction(async (tx) => {
project = await projectDAL.findById(projectId, tx); project = await projectDAL.findById(projectId, tx);
if (project.kmsSecretManagerEncryptedDataKey) { if (project.kmsSecretManagerEncryptedDataKey) {
return; return project.kmsSecretManagerEncryptedDataKey;
} }
const dataKey = crypto.randomBytes(32); const dataKey = crypto.randomBytes(32);

View File

@@ -5,6 +5,7 @@ import {
AccessScope, AccessScope,
OrganizationsSchema, OrganizationsSchema,
OrgMembershipRole, OrgMembershipRole,
OrgMembershipStatus,
TableName, TableName,
TMemberships, TMemberships,
TMembershipsInsert, TMembershipsInsert,
@@ -346,6 +347,7 @@ export const orgDALFactory = (db: TDbClient) => {
.replicaNode()(TableName.Membership) .replicaNode()(TableName.Membership)
.where(`${TableName.Membership}.scopeOrgId`, orgId) .where(`${TableName.Membership}.scopeOrgId`, orgId)
.where(`${TableName.Membership}.scope`, AccessScope.Organization) .where(`${TableName.Membership}.scope`, AccessScope.Organization)
.where(`${TableName.Membership}.status`, OrgMembershipStatus.Accepted)
.whereNotNull(`${TableName.Membership}.actorUserId`) .whereNotNull(`${TableName.Membership}.actorUserId`)
.count("*") .count("*")
.join(TableName.Users, `${TableName.Membership}.actorUserId`, `${TableName.Users}.id`) .join(TableName.Users, `${TableName.Membership}.actorUserId`, `${TableName.Users}.id`)

View File

@@ -258,10 +258,6 @@ export const fnSecretsV2FromImports = async ({
})[]; })[];
}[] = [{ secretImports: rootSecretImports, depth: 0, parentImportedSecrets: [] }]; }[] = [{ secretImports: rootSecretImports, depth: 0, parentImportedSecrets: [] }];
const processedSecretImports = await processReservedImports(rootSecretImports, secretImportDAL);
stack[0] = { secretImports: processedSecretImports, depth: 0, parentImportedSecrets: [] };
const processedImports: TSecretImportSecretsV2[] = []; const processedImports: TSecretImportSecretsV2[] = [];
while (stack.length) { while (stack.length) {
@@ -299,7 +295,9 @@ export const fnSecretsV2FromImports = async ({
); );
const importedSecretsGroupByFolderId = groupBy(importedSecrets, (i) => i.folderId); const importedSecretsGroupByFolderId = groupBy(importedSecrets, (i) => i.folderId);
sanitizedImports.forEach(({ importPath, importEnv }) => { const processedBatchImports = await processReservedImports(sanitizedImports, secretImportDAL);
processedBatchImports.forEach(({ importPath, importEnv }) => {
cyclicDetector.add(getImportUniqKey(importEnv.slug, importPath)); cyclicDetector.add(getImportUniqKey(importEnv.slug, importPath));
}); });
// now we need to check recursively deeper imports made inside other imports // now we need to check recursively deeper imports made inside other imports
@@ -308,7 +306,7 @@ export const fnSecretsV2FromImports = async ({
const deeperImportsGroupByFolderId = groupBy(deeperImports, (i) => i.folderId); const deeperImportsGroupByFolderId = groupBy(deeperImports, (i) => i.folderId);
const isFirstIteration = !processedImports.length; const isFirstIteration = !processedImports.length;
sanitizedImports.forEach(({ importPath, importEnv, id, folderId }, i) => { processedBatchImports.forEach(({ importPath, importEnv, id, folderId }, i) => {
const sourceImportFolder = importedFolderGroupBySourceImport[`${importEnv.id}-${importPath}`]?.[0]; const sourceImportFolder = importedFolderGroupBySourceImport[`${importEnv.id}-${importPath}`]?.[0];
const secretsWithDuplicate = (importedSecretsGroupByFolderId?.[importedFolders?.[i]?.id as string] || []) const secretsWithDuplicate = (importedSecretsGroupByFolderId?.[importedFolders?.[i]?.id as string] || [])
.filter((item) => .filter((item) =>

View File

@@ -0,0 +1,4 @@
export * from "./laravel-forge-sync-constants";
export * from "./laravel-forge-sync-fns";
export * from "./laravel-forge-sync-schemas";
export * from "./laravel-forge-sync-types";

View File

@@ -0,0 +1,10 @@
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { SecretSync } from "@app/services/secret-sync/secret-sync-enums";
import { TSecretSyncListItem } from "@app/services/secret-sync/secret-sync-types";
export const LARAVEL_FORGE_SYNC_LIST_OPTION: TSecretSyncListItem = {
name: "Laravel Forge",
destination: SecretSync.LaravelForge,
connection: AppConnection.LaravelForge,
canImportSecrets: true
};

View File

@@ -0,0 +1,207 @@
import { request } from "@app/lib/config/request";
import { IntegrationUrls } from "@app/services/integration-auth/integration-list";
import { matchesSchema } from "@app/services/secret-sync/secret-sync-fns";
import { TSecretMap } from "@app/services/secret-sync/secret-sync-types";
import {
LaravelForgeSecret,
TGetLaravelForgeSecrets,
TLaravelForgeSecrets,
TLaravelForgeSyncWithCredentials
} from "./laravel-forge-sync-types";
const getLaravelForgeSecretsRaw = async ({ apiToken, orgSlug, serverId, siteId }: TGetLaravelForgeSecrets) => {
const { data } = await request.get<TLaravelForgeSecrets>(
`${IntegrationUrls.LARAVELFORGE_API_URL}/api/orgs/${orgSlug}/servers/${serverId}/sites/${siteId}/environment`,
{
headers: {
Authorization: `Bearer ${apiToken}`,
Accept: "application/json",
"Content-Type": "application/json"
}
}
);
return data.data.attributes.content;
};
const parseEnv = (str: string) => {
const lines = str.split("\n");
const parsed: { key: string; value: string }[] = [];
let i = 0;
while (i < lines.length) {
const trimmed = lines[i].trim();
// Skip empty lines and comments
if (trimmed === "" || trimmed.startsWith("#")) {
i += 1;
// eslint-disable-next-line no-continue
continue;
}
if (trimmed.includes("=")) {
const equalIndex = trimmed.indexOf("=");
const key = trimmed.substring(0, equalIndex).trim();
const valueRaw = trimmed.substring(equalIndex + 1).trim();
// Check if value starts with a quote
const startsWithDoubleQuote = valueRaw.startsWith('"');
const startsWithSingleQuote = valueRaw.startsWith("'");
if (startsWithDoubleQuote || startsWithSingleQuote) {
const quoteChar = startsWithDoubleQuote ? '"' : "'";
const closingQuoteIndex = valueRaw.indexOf(quoteChar, 1);
if (closingQuoteIndex !== -1) {
// Single-line quoted value
const value = valueRaw.slice(1, closingQuoteIndex);
parsed.push({ key, value });
i += 1;
} else {
// Multiline quoted value - collect lines until closing quote
let value = valueRaw.slice(1);
i += 1;
while (i < lines.length) {
const nextLine = lines[i];
const closingIndex = nextLine.indexOf(quoteChar);
if (closingIndex !== -1) {
value += `\n${nextLine.substring(0, closingIndex)}`;
parsed.push({ key, value });
i += 1;
break;
} else {
value += `\n${nextLine}`;
i += 1;
}
}
}
} else {
// Unquoted value
parsed.push({ key, value: valueRaw });
i += 1;
}
} else {
i += 1;
}
}
return parsed;
};
const getLaravelForgeSecrets = async (secretSync: TLaravelForgeSyncWithCredentials): Promise<LaravelForgeSecret[]> => {
const {
connection,
destinationConfig: { orgSlug, serverId, siteId }
} = secretSync;
const { apiToken } = connection.credentials;
const secrets = await getLaravelForgeSecretsRaw({ apiToken, orgSlug, serverId, siteId });
const parsedSecrets = parseEnv(secrets);
return parsedSecrets;
};
const buildEnvString = (secrets: LaravelForgeSecret[]) => {
if (secrets.length === 0) {
return "# .env";
}
return secrets
.map((secret) => {
const { value } = secret;
if (value.includes(`"`)) {
return `${secret.key}='${value}'`;
}
if (value.includes(" ") || value.includes("\n") || value.includes(`'`)) {
return `${secret.key}="${value}"`;
}
return `${secret.key}=${value}`;
})
.join("\n");
};
const updateLaravelForgeSecrets = async (secretSync: TLaravelForgeSyncWithCredentials, envString: string) => {
const {
connection,
destinationConfig: { orgSlug, serverId, siteId }
} = secretSync;
const { apiToken } = connection.credentials;
await request.put(
`${IntegrationUrls.LARAVELFORGE_API_URL}/api/orgs/${orgSlug}/servers/${serverId}/sites/${siteId}/environment`,
{
environment: envString
},
{
headers: {
Authorization: `Bearer ${apiToken}`,
Accept: "application/json",
"Content-Type": "application/json"
}
}
);
};
export const LaravelForgeSyncFns = {
async syncSecrets(secretSync: TLaravelForgeSyncWithCredentials, secretMap: TSecretMap) {
const {
environment,
syncOptions: { disableSecretDeletion, keySchema }
} = secretSync;
const secrets = await getLaravelForgeSecrets(secretSync);
// Create a map of the existing secrets
const updatedSecretsMap = new Map(secrets.map((secret) => [secret.key, secret.value]));
for (const [key, { value }] of Object.entries(secretMap)) {
// Add the new secrets to the map
updatedSecretsMap.set(key, value);
}
if (!disableSecretDeletion) {
secrets.forEach((secret) => {
if (!matchesSchema(secret.key, environment?.slug || "", keySchema)) return;
if (!secretMap[secret.key]) {
updatedSecretsMap.delete(secret.key);
}
});
}
const updatedSecrets = Array.from(updatedSecretsMap.entries()).map(([key, value]) => ({ key, value }));
const envString = buildEnvString(updatedSecrets);
await updateLaravelForgeSecrets(secretSync, envString);
},
async getSecrets(secretSync: TLaravelForgeSyncWithCredentials): Promise<TSecretMap> {
const secrets = await getLaravelForgeSecrets(secretSync);
return Object.fromEntries(secrets.map((secret) => [secret.key, { value: secret.value }]));
},
async removeSecrets(secretSync: TLaravelForgeSyncWithCredentials, secretMap: TSecretMap) {
const existingSecrets = await getLaravelForgeSecrets(secretSync);
const newSecrets = existingSecrets.filter((secret) => !Object.hasOwn(secretMap, secret.key));
if (newSecrets.length === existingSecrets.length) {
return;
}
const envString = buildEnvString(newSecrets);
await updateLaravelForgeSecrets(secretSync, envString);
}
};

View File

@@ -0,0 +1,68 @@
import RE2 from "re2";
import { z } from "zod";
import { SecretSyncs } from "@app/lib/api-docs";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { SecretSync } from "@app/services/secret-sync/secret-sync-enums";
import {
BaseSecretSyncSchema,
GenericCreateSecretSyncFieldsSchema,
GenericUpdateSecretSyncFieldsSchema
} from "@app/services/secret-sync/secret-sync-schemas";
import { TSyncOptionsConfig } from "@app/services/secret-sync/secret-sync-types";
const slugValidator = (val: string) => {
return new RE2("^[a-z0-9.-]+$").test(val) && !new RE2(".[-]$").test(val);
};
const LaravelForgeSyncDestinationConfigSchema = z.object({
orgSlug: z
.string()
.min(1, "Org Slug is required")
.max(512, "Org Slug cannot exceed 512 characters")
.refine(
(val) => slugValidator(val),
"Org Slug can only contain lowercase letters, numbers, dots, and dashes, and cannot end with a dot or dash."
)
.describe(SecretSyncs.DESTINATION_CONFIG.LARAVEL_FORGE.orgSlug),
orgName: z.string().optional().describe(SecretSyncs.DESTINATION_CONFIG.LARAVEL_FORGE.orgName),
serverId: z
.string()
.min(1, "Server ID is required")
.refine((val) => !Number.isNaN(Number(val)), "Server ID must be a valid integer")
.describe(SecretSyncs.DESTINATION_CONFIG.LARAVEL_FORGE.serverId),
serverName: z.string().optional().describe(SecretSyncs.DESTINATION_CONFIG.LARAVEL_FORGE.serverName),
siteId: z.string().min(1, "Site ID is required").describe(SecretSyncs.DESTINATION_CONFIG.LARAVEL_FORGE.siteId),
siteName: z.string().optional().describe(SecretSyncs.DESTINATION_CONFIG.LARAVEL_FORGE.siteName)
});
const LaravelForgeSyncOptionsConfig: TSyncOptionsConfig = { canImportSecrets: true };
export const LaravelForgeSyncSchema = BaseSecretSyncSchema(
SecretSync.LaravelForge,
LaravelForgeSyncOptionsConfig
).extend({
destination: z.literal(SecretSync.LaravelForge),
destinationConfig: LaravelForgeSyncDestinationConfigSchema
});
export const CreateLaravelForgeSyncSchema = GenericCreateSecretSyncFieldsSchema(
SecretSync.LaravelForge,
LaravelForgeSyncOptionsConfig
).extend({
destinationConfig: LaravelForgeSyncDestinationConfigSchema
});
export const UpdateLaravelForgeSyncSchema = GenericUpdateSecretSyncFieldsSchema(
SecretSync.LaravelForge,
LaravelForgeSyncOptionsConfig
).extend({
destinationConfig: LaravelForgeSyncDestinationConfigSchema.optional()
});
export const LaravelForgeSyncListItemSchema = z.object({
name: z.literal("Laravel Forge"),
connection: z.literal(AppConnection.LaravelForge),
destination: z.literal(SecretSync.LaravelForge),
canImportSecrets: z.literal(true)
});

View File

@@ -0,0 +1,41 @@
import z from "zod";
import { TLaravelForgeConnection } from "@app/services/app-connection/laravel-forge";
import {
CreateLaravelForgeSyncSchema,
LaravelForgeSyncListItemSchema,
LaravelForgeSyncSchema
} from "./laravel-forge-sync-schemas";
export type TLaravelForgeSyncListItem = z.infer<typeof LaravelForgeSyncListItemSchema>;
export type TLaravelForgeSync = z.infer<typeof LaravelForgeSyncSchema>;
export type TLaravelForgeSyncInput = z.infer<typeof CreateLaravelForgeSyncSchema>;
export type TLaravelForgeSyncWithCredentials = TLaravelForgeSync & {
connection: TLaravelForgeConnection;
};
export type TGetLaravelForgeSecrets = {
apiToken: string;
orgSlug: string;
serverId: string;
siteId: string;
};
export type TLaravelForgeSecrets = {
data: {
id: string;
type: string;
attributes: {
content: string;
};
};
};
export type LaravelForgeSecret = {
key: string;
value: string;
};

View File

@@ -28,7 +28,8 @@ export enum SecretSync {
Checkly = "checkly", Checkly = "checkly",
DigitalOceanAppPlatform = "digital-ocean-app-platform", DigitalOceanAppPlatform = "digital-ocean-app-platform",
Netlify = "netlify", Netlify = "netlify",
Bitbucket = "bitbucket" Bitbucket = "bitbucket",
LaravelForge = "laravel-forge"
} }
export enum SecretSyncInitialSyncBehavior { export enum SecretSyncInitialSyncBehavior {

View File

@@ -49,6 +49,8 @@ import { HC_VAULT_SYNC_LIST_OPTION, HCVaultSyncFns } from "./hc-vault";
import { HEROKU_SYNC_LIST_OPTION, HerokuSyncFns } from "./heroku"; import { HEROKU_SYNC_LIST_OPTION, HerokuSyncFns } from "./heroku";
import { HUMANITEC_SYNC_LIST_OPTION } from "./humanitec"; import { HUMANITEC_SYNC_LIST_OPTION } from "./humanitec";
import { HumanitecSyncFns } from "./humanitec/humanitec-sync-fns"; import { HumanitecSyncFns } from "./humanitec/humanitec-sync-fns";
import { LARAVEL_FORGE_SYNC_LIST_OPTION } from "./laravel-forge";
import { LaravelForgeSyncFns } from "./laravel-forge/laravel-forge-sync-fns";
import { NETLIFY_SYNC_LIST_OPTION, NetlifySyncFns } from "./netlify"; import { NETLIFY_SYNC_LIST_OPTION, NetlifySyncFns } from "./netlify";
import { RAILWAY_SYNC_LIST_OPTION } from "./railway/railway-sync-constants"; import { RAILWAY_SYNC_LIST_OPTION } from "./railway/railway-sync-constants";
import { RailwaySyncFns } from "./railway/railway-sync-fns"; import { RailwaySyncFns } from "./railway/railway-sync-fns";
@@ -91,7 +93,8 @@ const SECRET_SYNC_LIST_OPTIONS: Record<SecretSync, TSecretSyncListItem> = {
[SecretSync.Checkly]: CHECKLY_SYNC_LIST_OPTION, [SecretSync.Checkly]: CHECKLY_SYNC_LIST_OPTION,
[SecretSync.DigitalOceanAppPlatform]: DIGITAL_OCEAN_APP_PLATFORM_SYNC_LIST_OPTION, [SecretSync.DigitalOceanAppPlatform]: DIGITAL_OCEAN_APP_PLATFORM_SYNC_LIST_OPTION,
[SecretSync.Netlify]: NETLIFY_SYNC_LIST_OPTION, [SecretSync.Netlify]: NETLIFY_SYNC_LIST_OPTION,
[SecretSync.Bitbucket]: BITBUCKET_SYNC_LIST_OPTION [SecretSync.Bitbucket]: BITBUCKET_SYNC_LIST_OPTION,
[SecretSync.LaravelForge]: LARAVEL_FORGE_SYNC_LIST_OPTION
}; };
export const listSecretSyncOptions = () => { export const listSecretSyncOptions = () => {
@@ -277,6 +280,8 @@ export const SecretSyncFns = {
return NetlifySyncFns.syncSecrets(secretSync, schemaSecretMap); return NetlifySyncFns.syncSecrets(secretSync, schemaSecretMap);
case SecretSync.Bitbucket: case SecretSync.Bitbucket:
return BitbucketSyncFns.syncSecrets(secretSync, schemaSecretMap); return BitbucketSyncFns.syncSecrets(secretSync, schemaSecretMap);
case SecretSync.LaravelForge:
return LaravelForgeSyncFns.syncSecrets(secretSync, schemaSecretMap);
default: default:
throw new Error( throw new Error(
`Unhandled sync destination for sync secrets fns: ${(secretSync as TSecretSyncWithCredentials).destination}` `Unhandled sync destination for sync secrets fns: ${(secretSync as TSecretSyncWithCredentials).destination}`
@@ -393,6 +398,9 @@ export const SecretSyncFns = {
case SecretSync.Bitbucket: case SecretSync.Bitbucket:
secretMap = await BitbucketSyncFns.getSecrets(secretSync); secretMap = await BitbucketSyncFns.getSecrets(secretSync);
break; break;
case SecretSync.LaravelForge:
secretMap = await LaravelForgeSyncFns.getSecrets(secretSync);
break;
default: default:
throw new Error( throw new Error(
`Unhandled sync destination for get secrets fns: ${(secretSync as TSecretSyncWithCredentials).destination}` `Unhandled sync destination for get secrets fns: ${(secretSync as TSecretSyncWithCredentials).destination}`
@@ -486,6 +494,8 @@ export const SecretSyncFns = {
return NetlifySyncFns.removeSecrets(secretSync, schemaSecretMap); return NetlifySyncFns.removeSecrets(secretSync, schemaSecretMap);
case SecretSync.Bitbucket: case SecretSync.Bitbucket:
return BitbucketSyncFns.removeSecrets(secretSync, schemaSecretMap); return BitbucketSyncFns.removeSecrets(secretSync, schemaSecretMap);
case SecretSync.LaravelForge:
return LaravelForgeSyncFns.removeSecrets(secretSync, schemaSecretMap);
default: default:
throw new Error( throw new Error(
`Unhandled sync destination for remove secrets fns: ${(secretSync as TSecretSyncWithCredentials).destination}` `Unhandled sync destination for remove secrets fns: ${(secretSync as TSecretSyncWithCredentials).destination}`

View File

@@ -32,7 +32,8 @@ export const SECRET_SYNC_NAME_MAP: Record<SecretSync, string> = {
[SecretSync.Checkly]: "Checkly", [SecretSync.Checkly]: "Checkly",
[SecretSync.DigitalOceanAppPlatform]: "Digital Ocean App Platform", [SecretSync.DigitalOceanAppPlatform]: "Digital Ocean App Platform",
[SecretSync.Netlify]: "Netlify", [SecretSync.Netlify]: "Netlify",
[SecretSync.Bitbucket]: "Bitbucket" [SecretSync.Bitbucket]: "Bitbucket",
[SecretSync.LaravelForge]: "Laravel Forge"
}; };
export const SECRET_SYNC_CONNECTION_MAP: Record<SecretSync, AppConnection> = { export const SECRET_SYNC_CONNECTION_MAP: Record<SecretSync, AppConnection> = {
@@ -65,7 +66,8 @@ export const SECRET_SYNC_CONNECTION_MAP: Record<SecretSync, AppConnection> = {
[SecretSync.Checkly]: AppConnection.Checkly, [SecretSync.Checkly]: AppConnection.Checkly,
[SecretSync.DigitalOceanAppPlatform]: AppConnection.DigitalOcean, [SecretSync.DigitalOceanAppPlatform]: AppConnection.DigitalOcean,
[SecretSync.Netlify]: AppConnection.Netlify, [SecretSync.Netlify]: AppConnection.Netlify,
[SecretSync.Bitbucket]: AppConnection.Bitbucket [SecretSync.Bitbucket]: AppConnection.Bitbucket,
[SecretSync.LaravelForge]: AppConnection.LaravelForge
}; };
export const SECRET_SYNC_PLAN_MAP: Record<SecretSync, SecretSyncPlanType> = { export const SECRET_SYNC_PLAN_MAP: Record<SecretSync, SecretSyncPlanType> = {
@@ -98,7 +100,8 @@ export const SECRET_SYNC_PLAN_MAP: Record<SecretSync, SecretSyncPlanType> = {
[SecretSync.Checkly]: SecretSyncPlanType.Regular, [SecretSync.Checkly]: SecretSyncPlanType.Regular,
[SecretSync.DigitalOceanAppPlatform]: SecretSyncPlanType.Regular, [SecretSync.DigitalOceanAppPlatform]: SecretSyncPlanType.Regular,
[SecretSync.Netlify]: SecretSyncPlanType.Regular, [SecretSync.Netlify]: SecretSyncPlanType.Regular,
[SecretSync.Bitbucket]: SecretSyncPlanType.Regular [SecretSync.Bitbucket]: SecretSyncPlanType.Regular,
[SecretSync.LaravelForge]: SecretSyncPlanType.Regular
}; };
export const SECRET_SYNC_SKIP_FIELDS_MAP: Record<SecretSync, string[]> = { export const SECRET_SYNC_SKIP_FIELDS_MAP: Record<SecretSync, string[]> = {
@@ -140,7 +143,8 @@ export const SECRET_SYNC_SKIP_FIELDS_MAP: Record<SecretSync, string[]> = {
[SecretSync.Checkly]: ["groupName", "accountName"], [SecretSync.Checkly]: ["groupName", "accountName"],
[SecretSync.DigitalOceanAppPlatform]: ["appName"], [SecretSync.DigitalOceanAppPlatform]: ["appName"],
[SecretSync.Netlify]: ["accountName", "siteName"], [SecretSync.Netlify]: ["accountName", "siteName"],
[SecretSync.Bitbucket]: [] [SecretSync.Bitbucket]: [],
[SecretSync.LaravelForge]: []
}; };
const defaultDuplicateCheck: DestinationDuplicateCheckFn = () => true; const defaultDuplicateCheck: DestinationDuplicateCheckFn = () => true;
@@ -199,5 +203,6 @@ export const DESTINATION_DUPLICATE_CHECK_MAP: Record<SecretSync, DestinationDupl
[SecretSync.Checkly]: defaultDuplicateCheck, [SecretSync.Checkly]: defaultDuplicateCheck,
[SecretSync.DigitalOceanAppPlatform]: defaultDuplicateCheck, [SecretSync.DigitalOceanAppPlatform]: defaultDuplicateCheck,
[SecretSync.Netlify]: defaultDuplicateCheck, [SecretSync.Netlify]: defaultDuplicateCheck,
[SecretSync.Bitbucket]: defaultDuplicateCheck [SecretSync.Bitbucket]: defaultDuplicateCheck,
[SecretSync.LaravelForge]: defaultDuplicateCheck
}; };

View File

@@ -117,6 +117,12 @@ import {
THumanitecSyncListItem, THumanitecSyncListItem,
THumanitecSyncWithCredentials THumanitecSyncWithCredentials
} from "./humanitec"; } from "./humanitec";
import {
TLaravelForgeSync,
TLaravelForgeSyncInput,
TLaravelForgeSyncListItem,
TLaravelForgeSyncWithCredentials
} from "./laravel-forge";
import { TNetlifySync, TNetlifySyncInput, TNetlifySyncListItem, TNetlifySyncWithCredentials } from "./netlify"; import { TNetlifySync, TNetlifySyncInput, TNetlifySyncListItem, TNetlifySyncWithCredentials } from "./netlify";
import { import {
TRailwaySync, TRailwaySync,
@@ -164,6 +170,7 @@ export type TSecretSync =
| TTerraformCloudSync | TTerraformCloudSync
| TCamundaSync | TCamundaSync
| TVercelSync | TVercelSync
| TLaravelForgeSync
| TWindmillSync | TWindmillSync
| THCVaultSync | THCVaultSync
| TTeamCitySync | TTeamCitySync
@@ -212,7 +219,8 @@ export type TSecretSyncWithCredentials =
| TSupabaseSyncWithCredentials | TSupabaseSyncWithCredentials
| TDigitalOceanAppPlatformSyncWithCredentials | TDigitalOceanAppPlatformSyncWithCredentials
| TNetlifySyncWithCredentials | TNetlifySyncWithCredentials
| TBitbucketSyncWithCredentials; | TBitbucketSyncWithCredentials
| TLaravelForgeSyncWithCredentials;
export type TSecretSyncInput = export type TSecretSyncInput =
| TAwsParameterStoreSyncInput | TAwsParameterStoreSyncInput
@@ -244,7 +252,8 @@ export type TSecretSyncInput =
| TSupabaseSyncInput | TSupabaseSyncInput
| TDigitalOceanAppPlatformSyncInput | TDigitalOceanAppPlatformSyncInput
| TNetlifySyncInput | TNetlifySyncInput
| TBitbucketSyncInput; | TBitbucketSyncInput
| TLaravelForgeSyncInput;
export type TSecretSyncListItem = export type TSecretSyncListItem =
| TAwsParameterStoreSyncListItem | TAwsParameterStoreSyncListItem
@@ -259,6 +268,7 @@ export type TSecretSyncListItem =
| TTerraformCloudSyncListItem | TTerraformCloudSyncListItem
| TCamundaSyncListItem | TCamundaSyncListItem
| TVercelSyncListItem | TVercelSyncListItem
| TLaravelForgeSyncListItem
| TWindmillSyncListItem | TWindmillSyncListItem
| THCVaultSyncListItem | THCVaultSyncListItem
| TTeamCitySyncListItem | TTeamCitySyncListItem

View File

@@ -1,24 +1,24 @@
# Contributing to the documentation # Contributing to the documentation
## Getting familiar with Mintlify ## Getting familiar with Mintlify
New to Mintlify. [Start Here](https://mintlify.com/docs/quickstart)
New to Mintlify. [Start Here](https://mintlify.com/docs/quickstart)
## 👩‍💻 Development ## 👩‍💻 Development
Install the [Mintlify CLI](https://www.npmjs.com/package/mintlify) to preview the documentation changes locally. To install, use the following command Install the [Mint CLI](https://www.npmjs.com/package/mint) to preview the documentation changes locally. To install, use the following command
``` ```
npm i -g mintlify npm i -g mint
``` ```
Run the following command at the root of your documentation (where mint.json is) Run the following command at the root of your documentation (where mint.json is)
``` ```
mintlify dev mint dev
``` ```
## Troubleshooting ## Troubleshooting
- Mintlify dev isn't running - Run `mintlify install` it'll re-install dependencies. - `mint dev` isn't running - Run `mint update` to update the Mint CLI.
- Page loads as a 404 - Make sure you are running in a folder with `mint.json`. Check the `/docs` folder - Page loads as a 404 - Make sure you are running in a folder with `mint.json`. Check the `/docs` folder

View File

@@ -0,0 +1,4 @@
---
title: "Available"
openapi: "GET /api/v1/app-connections/laravel-forge/available"
---

View File

@@ -0,0 +1,10 @@
---
title: "Create"
openapi: "POST /api/v1/app-connections/laravel-forge"
---
<Note>
Check out the configuration docs for [Laravel Forge
Connections](/integrations/app-connections/laravel-forge) to learn how to
obtain the required credentials.
</Note>

View File

@@ -0,0 +1,4 @@
---
title: "Delete"
openapi: "DELETE /api/v1/app-connections/laravel-forge/{connectionId}"
---

View File

@@ -0,0 +1,4 @@
---
title: "Get by ID"
openapi: "GET /api/v1/app-connections/laravel-forge/{connectionId}"
---

View File

@@ -0,0 +1,4 @@
---
title: "Get by Name"
openapi: "GET /api/v1/app-connections/laravel-forge/connection-name/{connectionName}"
---

View File

@@ -0,0 +1,4 @@
---
title: "List"
openapi: "GET /api/v1/app-connections/laravel-forge"
---

View File

@@ -0,0 +1,10 @@
---
title: "Update"
openapi: "PATCH /api/v1/app-connections/laravel-forge/{connectionId}"
---
<Note>
Check out the configuration docs for [Laravel Forge
Connections](/integrations/app-connections/laravel-forge) to learn how to
obtain the required credentials.
</Note>

View File

@@ -0,0 +1,4 @@
---
title: "Create"
openapi: "POST /api/v1/secret-syncs/laravel-forge"
---

View File

@@ -0,0 +1,4 @@
---
title: "Delete"
openapi: "DELETE /api/v1/secret-syncs/laravel-forge/{syncId}"
---

View File

@@ -0,0 +1,4 @@
---
title: "Get by ID"
openapi: "GET /api/v1/secret-syncs/laravel-forge/{syncId}"
---

View File

@@ -0,0 +1,4 @@
---
title: "Get by Name"
openapi: "GET /api/v1/secret-syncs/laravel-forge/sync-name/{syncName}"
---

View File

@@ -0,0 +1,4 @@
---
title: "Import Secrets"
openapi: "POST /api/v1/secret-syncs/laravel-forge/{syncId}/import-secrets"
---

View File

@@ -0,0 +1,4 @@
---
title: "List"
openapi: "GET /api/v1/secret-syncs/laravel-forge"
---

View File

@@ -0,0 +1,4 @@
---
title: "Remove Secrets"
openapi: "POST /api/v1/secret-syncs/laravel-forge/{syncId}/remove-secrets"
---

View File

@@ -0,0 +1,4 @@
---
title: "Sync Secrets"
openapi: "POST /api/v1/secret-syncs/laravel-forge/{syncId}/sync-secrets"
---

View File

@@ -0,0 +1,4 @@
---
title: "Update"
openapi: "PATCH /api/v1/secret-syncs/laravel-forge/{syncId}"
---

View File

@@ -43,23 +43,23 @@ docker compose -f docker-compose.dev.yml down
We use [Mintlify](https://mintlify.com/) for our docs. We use [Mintlify](https://mintlify.com/) for our docs.
#### Install Mintlify CLI. #### Install Mint CLI.
```bash ```bash
npm i -g mintlify npm i -g mint
``` ```
or or
```bash ```bash
yarn global add mintlify yarn global add mint
``` ```
#### Running the docs #### Running the docs
Go to `docs` directory and run `mintlify dev`. This will start up the docs on `localhost:3000` Go to `docs` directory and run `mint dev`. This will start up the docs on `localhost:3000`
```bash ```bash
# From the root directory # From the root directory
cd docs; mintlify dev; cd docs; mint dev;
``` ```

View File

@@ -125,6 +125,7 @@
"integrations/app-connections/hashicorp-vault", "integrations/app-connections/hashicorp-vault",
"integrations/app-connections/heroku", "integrations/app-connections/heroku",
"integrations/app-connections/humanitec", "integrations/app-connections/humanitec",
"integrations/app-connections/laravel-forge",
"integrations/app-connections/ldap", "integrations/app-connections/ldap",
"integrations/app-connections/mssql", "integrations/app-connections/mssql",
"integrations/app-connections/mysql", "integrations/app-connections/mysql",
@@ -316,6 +317,7 @@
"self-hosting/deployment-options/linux-upgrade" "self-hosting/deployment-options/linux-upgrade"
] ]
}, },
"self-hosting/guides/replication",
"self-hosting/guides/upgrading-infisical", "self-hosting/guides/upgrading-infisical",
"self-hosting/configuration/envars", "self-hosting/configuration/envars",
"self-hosting/guides/releases", "self-hosting/guides/releases",
@@ -549,6 +551,7 @@
"integrations/secret-syncs/hashicorp-vault", "integrations/secret-syncs/hashicorp-vault",
"integrations/secret-syncs/heroku", "integrations/secret-syncs/heroku",
"integrations/secret-syncs/humanitec", "integrations/secret-syncs/humanitec",
"integrations/secret-syncs/laravel-forge",
"integrations/secret-syncs/netlify", "integrations/secret-syncs/netlify",
"integrations/secret-syncs/oci-vault", "integrations/secret-syncs/oci-vault",
"integrations/secret-syncs/railway", "integrations/secret-syncs/railway",
@@ -1777,6 +1780,18 @@
"api-reference/endpoints/app-connections/humanitec/delete" "api-reference/endpoints/app-connections/humanitec/delete"
] ]
}, },
{
"group": "Laravel Forge",
"pages": [
"api-reference/endpoints/app-connections/laravel-forge/list",
"api-reference/endpoints/app-connections/laravel-forge/available",
"api-reference/endpoints/app-connections/laravel-forge/get-by-id",
"api-reference/endpoints/app-connections/laravel-forge/get-by-name",
"api-reference/endpoints/app-connections/laravel-forge/create",
"api-reference/endpoints/app-connections/laravel-forge/update",
"api-reference/endpoints/app-connections/laravel-forge/delete"
]
},
{ {
"group": "LDAP", "group": "LDAP",
"pages": [ "pages": [
@@ -2257,6 +2272,19 @@
"api-reference/endpoints/secret-syncs/humanitec/remove-secrets" "api-reference/endpoints/secret-syncs/humanitec/remove-secrets"
] ]
}, },
{
"group": "Laravel Forge",
"pages": [
"api-reference/endpoints/secret-syncs/laravel-forge/list",
"api-reference/endpoints/secret-syncs/laravel-forge/get-by-id",
"api-reference/endpoints/secret-syncs/laravel-forge/get-by-name",
"api-reference/endpoints/secret-syncs/laravel-forge/create",
"api-reference/endpoints/secret-syncs/laravel-forge/update",
"api-reference/endpoints/secret-syncs/laravel-forge/delete",
"api-reference/endpoints/secret-syncs/laravel-forge/sync-secrets",
"api-reference/endpoints/secret-syncs/laravel-forge/remove-secrets"
]
},
{ {
"group": "Netlify", "group": "Netlify",
"pages": [ "pages": [

View File

@@ -3,10 +3,10 @@ title: "Folders"
description: "Learn how to organize secrets with folders." description: "Learn how to organize secrets with folders."
--- ---
Infisical Folders enable users to organize secrets using custom structures dependent on the intended use case (also known as **path-based secret storage**). Infisical Folders enable users to organize secrets using custom structures dependent on the intended use case (also known as **path-based secret storage**).
It is great for organizing secrets around hierarchies with multiple services or types of secrets involved at large quantities. It is great for organizing secrets around hierarchies with multiple services or types of secrets involved at large quantities.
Infisical Folders can be infinitely nested to mirror your application architecture  whether it's microservices, monorepos, Infisical Folders can be infinitely nested to mirror your application architecture  whether it's microservices, monorepos,
or any logical grouping that best suits your needs. or any logical grouping that best suits your needs.
Consider the following structure for a microservice architecture: Consider the following structure for a microservice architecture:
@@ -22,7 +22,7 @@ Consider the following structure for a microservice architecture:
... ...
``` ```
In this example, we store environment variables for each microservice under each respective `/envars` folder. In this example, we store environment variables for each microservice under each respective `/envars` folder.
We also store user-specific secrets for micro-service 1 under `/service1/users`. With this folder structure in place, your applications only need to specify a path like `/microservice1/envars` to fetch secrets from there. We also store user-specific secrets for micro-service 1 under `/service1/users`. With this folder structure in place, your applications only need to specify a path like `/microservice1/envars` to fetch secrets from there.
By extending this example, you can see how path-based secret storage provides a versatile approach to manage secrets for any architecture. By extending this example, you can see how path-based secret storage provides a versatile approach to manage secrets for any architecture.
@@ -45,7 +45,27 @@ To delete a folder, hover over it and press the **X** button that appears on the
It's possible to compare the contents of folders across environments in the **Secrets Overview** page. It's possible to compare the contents of folders across environments in the **Secrets Overview** page.
When you click on a folder, the table will display the items within it across environments. When you click on a folder, the table will display the items within it across environments.
In the image below, you can see that the **Development** environment is the only one that contains items In the image below, you can see that the **Development** environment is the only one that contains items
in the `/users` folder, being other folders `/user-a`, `/user-b`, ... `/user-f`. in the `/users` folder, being other folders `/user-a`, `/user-b`, ... `/user-f`.
![comparing folders](../../images/platform/folder/folders-secrets-overview.png) ![comparing folders](../../images/platform/folder/folders-secrets-overview.png)
### Replicating Folder Contents
If you want to copy secrets or folders from one path to another, you can utilize the **Replicate Secrets** functionality located in the **Add Secret** dropdown.
![replicate secrets](../../images/platform/folder/replicate-secrets.png)
![replicate secrets modal](../../images/platform/folder/replicate-secrets-modal.png)
First, select the **Source Environment** and the **Source Root Path** you want to copy secrets *from*. In the example provided, we select `/dev-folder` as the source root path from the Development environment. This means any secrets within `/dev-folder` from Development will be replicated. By default, these secrets are copied into the *currently active* folder/path in your target environment (e.g., the root folder of your Staging environment in this scenario).
As a final step, you can select the specific secrets you wish to copy and then click **Replicate Secrets**.
![replicate secrets modal](../../images/platform/folder/replicate-secrets-result.png)
The result shows two secrets successfully copied from the `/dev-folder` in the Development environment into the root folder of the Staging environment.
<Info>
If you do not select a **Source Root Path**, the replication will consider the contents of the *entire root* of the **Source Environment** (e.g., the Development environment). In this example that would mean copying the `/dev-folder` itself rather than just its contents.
</Info>

View File

@@ -36,7 +36,6 @@ Enabling HSM encryption has a set of key benefits:
### Requirements ### Requirements
- An Infisical instance with a version number that is equal to or greater than `v0.91.0`. - An Infisical instance with a version number that is equal to or greater than `v0.91.0`.
- If you are using Docker, your instance must be using the `infisical/infisical-fips` image.
- An HSM device from a provider such as [Thales Luna HSM](https://cpl.thalesgroup.com/encryption/data-protection-on-demand/services/luna-cloud-hsm), [AWS CloudHSM](https://aws.amazon.com/cloudhsm/), [Fortanix HSM](https://www.fortanix.com/platform/data-security-manager), or others. - An HSM device from a provider such as [Thales Luna HSM](https://cpl.thalesgroup.com/encryption/data-protection-on-demand/services/luna-cloud-hsm), [AWS CloudHSM](https://aws.amazon.com/cloudhsm/), [Fortanix HSM](https://www.fortanix.com/platform/data-security-manager), or others.
@@ -238,7 +237,7 @@ Enabling HSM encryption has a set of key benefits:
-e DB_CONNECTION_URI="<>" \ -e DB_CONNECTION_URI="<>" \
-e REDIS_URL="<>" \ -e REDIS_URL="<>" \
-e SITE_URL="<>" \ -e SITE_URL="<>" \
infisical/infisical-fips:<version> # Replace <version> with the version you want to use infisical/infisical:<version> # Replace <version> with the version you want to use
``` ```
We recommend reading further about [using Infisical with Docker](/self-hosting/deployment-options/standalone-infisical). We recommend reading further about [using Infisical with Docker](/self-hosting/deployment-options/standalone-infisical).
@@ -309,7 +308,7 @@ Enabling HSM encryption has a set of key benefits:
-e DB_CONNECTION_URI="<>" \ -e DB_CONNECTION_URI="<>" \
-e REDIS_URL="<>" \ -e REDIS_URL="<>" \
-e SITE_URL="<>" \ -e SITE_URL="<>" \
infisical/infisical-fips:<version> # Replace <version> with the version you want to use infisical/infisical:<version> # Replace <version> with the version you want to use
``` ```
<Warning> <Warning>
@@ -319,6 +318,192 @@ Enabling HSM encryption has a set of key benefits:
</Steps> </Steps>
After following these steps, your Docker setup will be ready to use Fortanix HSM encryption. After following these steps, your Docker setup will be ready to use Fortanix HSM encryption.
</Tab> </Tab>
<Tab title="AWS CloudHSM">
### Prerequisites
- An [activated AWS CloudHSM cluster](https://docs.aws.amazon.com/cloudhsm/latest/userguide/activate-cluster.html) with at least 1 HSM device.
- A [HSM user with the `Crypto User` role](https://docs.aws.amazon.com/cloudhsm/latest/userguide/cloudhsm_cli-user-create.html). In this guide we are using a user with the username `testUser` and the password `testPassword`.
<Steps>
<Step title="Configure CloudHSM client">
Before using the CloudHSM client, it must be configured properly so Infisical can use it for cryptographic operations.
**1. Download the AWS CloudHSM client**
You can download the AWS CloudHSM client from [the AWS documentation](https://docs.aws.amazon.com/cloudhsm/latest/userguide/pkcs11-library-install.html).
<Note>
Note that the AWS CloudHSM client is only available for Linux and Windows.
If you're on a different operating system, you'll need to access a Linux machine to configure the client, such as an AWS EC2 Debian instance.
</Note>
**2. Configure the CloudHSM client**
After installing the CloudHSM client, you should see all related files in the `/opt/cloudhsm/` directory on your machine.
You need to run the `configure-pkcs11` binary which will configure the client to connect with your AWS CloudHSM cluster. Depending on if you have multiple HSM's inside your cluster, you'll need to run the command with different arguments. Below you'll find the appropriate command for your use case:
<AccordionGroup>
<Accordion title="Single HSM">
```bash
sudo /opt/cloudhsm/bin/configure-pkcs11 -a <HSM_ENI_IPV4_ADDRESS> --disable-key-availability-check
```
<Info>
To use a single HSM, you must first manage client key durability settings by setting `disable_key_availability_check` to true by passing the `--disable-key-availability-check` flag. For more information read the [Key Synchronization](https://docs.aws.amazon.com/cloudhsm/latest/userguide/manage-key-sync.html) section in the AWS CloudHSM documentation.
</Info>
</Accordion>
<Accordion title="Multiple HSM's">
```bash
sudo /opt/cloudhsm/bin/configure-pkcs11 -a <HSM_ENI_IPV4_ADDRESS_1> <HSM_ENI_IPV4_ADDRESS_2> ... --disable-key-availability-check
```
</Accordion>
</AccordionGroup>
At this point you should have:
1. [Activated the CloudHSM cluster](https://docs.aws.amazon.com/cloudhsm/latest/userguide/activate-cluster.html)
2. [Created a Crypto User HSM user](https://docs.aws.amazon.com/cloudhsm/latest/userguide/cloudhsm_cli-user-create.html)
3. Downloaded and configured the CloudHSM client as described in the previous steps.
**3. Download the configured HSM client files**
After configuring the CloudHSM client, you should notice that the PKCS11 configuration file has been updated to include the HSM's ENI IP address. You can find this file in the `/opt/cloudhsm/etc/cloudhsm-pkcs11.cfg` directory, and it should look like this:
```json cloudhsm-pkcs11.cfg
{
"clusters": [
{
"type": "hsm1",
"cluster": {
// Your issuing CA certificate.
// As per AWS documentation, this defaults to `/opt/cloudhsm/etc/customerCA.crt`.
"hsm_ca_file": "/opt/cloudhsm/etc/customerCA.crt",
"servers": [
{
"hostname": "<HSM_ENI_IPV4_ADDRESS_1>",
"port": 2223,
"enable": true
},
{
"hostname": "<HSM_ENI_IPV4_ADDRESS_2>",
"port": 2223,
"enable": true
}
],
// Only relevant if you passed the --disable-key-availability-check flag
"options": {
"disable_key_availability_check": true
}
}
}
],
"logging": {
"log_type": "file",
"log_file": "/opt/cloudhsm/run/cloudhsm-pkcs11.log",
"log_level": "info",
"log_interval": "daily"
}
}
```
Save the entire `/opt/cloudhsm` folder, as you will need to mount this to your Infisical Docker container in the later steps. In this guide we will be saving all the files from the folder as `/etc/cloudhsm` and mounting it to the `/etc/cloudhsm` directory in the Docker container.
</Step>
<Step title="Find HSM slot number">
On the same machine that you configured the CloudHSM client, you can use `pkcs11-tool` to find the HSM slot number and to verify that the client is working correctly.
First, install the `pkcs11-tool` package:
```bash
sudo apt-get install opensc -y
```
Then, run the following command to find the HSM slot number:
```bash
pkcs11-tool --module /opt/cloudhsm/lib/libcloudhsm_pkcs11.so --list-slots --login
```
It'll prompt you to log in with your PIN, which is your username and password separated by a colon. Example: `testUser:testPassword`.
This will output the HSM slot number like so:
```bash
ubuntu@ec-2:~$ pkcs11-tool --module /opt/cloudhsm/lib/libcloudhsm_pkcs11.so --list-slots
Available slots:
Slot 0 (0x2000000000000001): hsm1
token label : hsm1
token manufacturer : Marvell Semiconductors, Inc.
token model : LS2
token flags : login required, rng, token initialized
hardware version : 66.48
firmware version : 10.2
serial num :
pin min/max : 8/32
```
In this case we see that the HSM has a slot in the position of `0`. This slot number will be used in the later steps to set the `HSM_SLOT` environment variable.
</Step>
<Step title="Download the HSM issuing CA certificate">
When you initialized your HSM, you were prompted to download the cluster CSR and sign it.
In order to use the HSM with Infisical, you need to obtain the issuer CA certificate that was used to sign the cluster CSR.
If you followed [the official AWS documentation](https://docs.aws.amazon.com/cloudhsm/latest/userguide/initialize-cluster.html), you should have a CA certificate called `customerCA.crt`.
Save the CA certificate to a path, as this will need to be mounted as a Docker volume in the next step. For this example, we'll save it to `/aws-files/customerCA.crt`.
</Step>
<Step title="Run Docker">
Running Docker with HSM encryption requires setting the HSM-related environment variables as mentioned previously in the [HSM setup instructions](#setup-instructions). You can set these environment variables in your Docker run command.
We are setting the environment variables for Docker via the command line in this example, but you can also pass in a `.env` file to set these environment variables.
<Warning>
If no key is found with the provided key label, the HSM will create a new key with the provided label.
Infisical depends on an AES and HMAC key to be present in the HSM. If these keys are not present, Infisical will create them. The AES key label will be the value of the `HSM_KEY_LABEL` environment variable, and the HMAC key label will be the value of the `HSM_KEY_LABEL` environment variable with the suffix `_HMAC`.
</Warning>
```bash
docker run -p 80:8080 \
# Mount the HSM client files to "/opt/cloudhsm"
-v /etc/cloudhsm:/opt/cloudhsm \
# Mount the issuer CA certificate to "/opt/cloudhsm/etc/customerCA.crt"
-v /aws-files/customerCA.crt:/opt/cloudhsm/etc/customerCA.crt \
# Set the HSM library path to whats expected within Docker (/opt/cloudhsm/lib/libcloudhsm_pkcs11.so)
-e HSM_LIB_PATH="/opt/cloudhsm/lib/libcloudhsm_pkcs11.so" \
# Set the HSM PIN to the username and password of the HSM user, separated by a colon
-e HSM_PIN=CryptoUserUsername:CryptoUserPassword \
# Set the HSM slot number to the slot number of the HSM device as found in the previous step
-e HSM_SLOT=<hsm-device-slot> \
# Set the HSM key label to a label that will be used to identify the encryption key in the HSM. This key label does not need to exist before hand.
-e HSM_KEY_LABEL=infisical-crypto-key \
# The rest of your environment variables ...
# -e ...
infisical/infisical:<version> # Replace <version> with the version you want to use
```
We recommend reading further about [using Infisical with Docker](/self-hosting/deployment-options/standalone-infisical).
</Step>
</Steps>
After following these steps, your Docker setup will be ready to use HSM encryption.
</Tab>
</Tabs> </Tabs>
</Tab> </Tab>
<Tab title="Kubernetes"> <Tab title="Kubernetes">
@@ -326,8 +511,9 @@ Enabling HSM encryption has a set of key benefits:
<Tabs> <Tabs>
<Tab title="Thales Luna Cloud HSM"> <Tab title="Thales Luna Cloud HSM">
<Note> <Note>
This is only supported on helm chart version `1.4.1` and above. Please see the [Helm Chart Changelog](https://github.com/Infisical/infisical/blob/main/helm-charts/infisical-standalone-postgres/CHANGELOG.md#141-march-19-2025) for more information. This is only supported on helm chart version `1.7.1` and above. Please see the [Helm Chart Changelog](https://github.com/Infisical/infisical/blob/main/helm-charts/infisical-standalone-postgres/CHANGELOG.md#141-march-19-2025) for more information.
</Note> </Note>
<Steps> <Steps>
@@ -591,13 +777,11 @@ Enabling HSM encryption has a set of key benefits:
<Step title="Updating the Deployment"> <Step title="Updating the Deployment">
After we've successfully configured the PVC and updated our environment variables, we are ready to update the deployment configuration so that the pods it creates can access the HSM client files. After we've successfully configured the PVC and updated our environment variables, we are ready to update the deployment configuration so that the pods it creates can access the HSM client files.
We need to update the Docker image of the deployment to use `infisical/infisical-fips`. The `infisical/infisical-fips` image is a functionally identical image to the `infisical/infisical` image, but it is built with HSM support.
```yaml ```yaml
# ... The rest of the values.yaml file ... # ... The rest of the values.yaml file ...
image: image:
repository: infisical/infisical-fips # Very important: Must use "infisical/infisical-fips" repository: infisical/infisical
tag: "v0.117.1-postgres" tag: "v0.117.1-postgres"
pullPolicy: IfNotPresent pullPolicy: IfNotPresent
@@ -757,13 +941,13 @@ Enabling HSM encryption has a set of key benefits:
</Step> </Step>
<Step title="Update Helm Values"> <Step title="Update Helm Values">
Update your Helm values to use the FIPS-compliant image and mount the Fortanix HSM files: Update your Helm values to mount the Fortanix HSM files:
```yaml ```yaml
# ... The rest of the values.yaml file ... # ... The rest of the values.yaml file ...
image: image:
repository: infisical/infisical-fips # Must use "infisical/infisical-fips" repository: infisical/infisical
tag: "v0.117.1-postgres" tag: "v0.117.1-postgres"
pullPolicy: IfNotPresent pullPolicy: IfNotPresent
@@ -800,6 +984,493 @@ Enabling HSM encryption has a set of key benefits:
</Steps> </Steps>
After following these steps, your Kubernetes setup will be ready to use Fortanix HSM encryption. After following these steps, your Kubernetes setup will be ready to use Fortanix HSM encryption.
</Tab> </Tab>
<Tab title="AWS CloudHSM">
### Prerequisites
- An [activated AWS CloudHSM cluster](https://docs.aws.amazon.com/cloudhsm/latest/userguide/activate-cluster.html) with at least 1 HSM device.
- A [HSM user with the `Crypto User` role](https://docs.aws.amazon.com/cloudhsm/latest/userguide/cloudhsm_cli-user-create.html). In this guide we are using a user with the username `testUser` and the password `testPassword`.
- A Kubernetes cluster
<Note>
AWS CloudHSM is supported on helm chart version `1.7.1` and above. Please see the [Helm Chart Changelog](https://github.com/Infisical/infisical/blob/main/helm-charts/infisical-standalone-postgres/CHANGELOG.md#141-march-19-2025) for more information.
</Note>
<Steps>
<Step title="Creating Persistent Volume Claim (PVC)">
<Accordion title="Prerequisites for using AWS EKS">
If you're using AWS EKS, you need to specify a storage class for the PVC and ensure that the EBS CSI Driver is installed and running.
By default, EKS exposes `gp2` as the default storage class. Below are the steps required for setting the default storage class and ensuring the EBS CSI Driver is installed and running:
<Steps>
<Step title="Enable OIDC authentication">
Enable OIDC authentication for the EKS cluster:
```bash
eksctl utils associate-iam-oidc-provider \
--region <your-region> \
--cluster <your-cluster-name> \
--approve
```
* Replace `<your-region>` with your AWS region.
* Replace `<your-cluster-name>` with your cluster name.
</Step>
<Step title="Check if the EBS CSI Driver is installed and running">
1. Check if EBS CSI Driver is installed and running by running the following command:
```bash
kubectl get pods -n kube-system | grep ebs-csi
```
If you see no pods, you need to install the EBS CSI Driver as seen in the next step.
</Step>
<Step title="Install EBS CSI Driver using eksctl">
Create a new IAM service account for the EBS CSI Driver:
```bash
eksctl create iamserviceaccount \
--name ebs-csi-controller-sa \
--namespace kube-system \
--region <your-region> \
--cluster <your-cluster-name> \
--attach-policy-arn arn:aws:iam::aws:policy/service-role/AmazonEBSCSIDriverPolicy \
--approve \
--role-name AmazonEKS_EBS_CSI_DriverRole
```
* Replace `<your-cluster-name>` with your cluster name.
* Replace `<your-region>` with your AWS region.
Install the EBS CSI Driver:
```bash
eksctl create addon \
--name aws-ebs-csi-driver \
--cluster <your-cluster-name> \
--region <your-region> \
--service-account-role-arn arn:aws:iam::<account-id>:role/AmazonEKS_EBS_CSI_DriverRole \
--force
```
* Replace `<your-cluster-name>` with your cluster name.
* Replace `<your-region>` with your AWS region.
* Replace `<account-id>` with your actual account ID. Can be obtained by running `aws sts get-caller-identity --query Account --output text`.
</Step>
<Step title="Verify the EBS CSI Driver is installed and running">
Verify the EBS CSI Driver is installed and running by running the following command:
```bash
kubectl get pods -n kube-system | grep ebs-csi
```
You should see an output like this:
```bash
kubectl get pods -n kube-system | grep ebs-csi
ebs-csi-controller-6b6bbf996-rvf8r 6/6 Running 0 21s
ebs-csi-controller-6b6bbf996-vk4ng 6/6 Running 0 21s
ebs-csi-node-c6vbb 3/3 Running 0 21s
ebs-csi-node-s9zlr 3/3 Running 0 21s
```
</Step>
<Step title="Find the enabled storage class">
You can find the enabled storage class by running the following command:
```bash
kubectl get storageclass
```
You should see an output like this:
```bash
$ kubectl get storageclass
NAME PROVISIONER RECLAIMPOLICY VOLUMEBINDINGMODE ALLOWVOLUMEEXPANSION AGE
gp2 kubernetes.io/aws-ebs Delete WaitForFirstConsumer false 65m
```
In this case, the enabled storage class is `gp2`.
</Step>
<Step title="Set the default storage class">
You can set the default PVC storage class by patching the storage class with the following command:
```bash
kubectl patch storageclass gp2 -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}'
```
This will set the `gp2` storage class as the default storage class.
Now when you run `kubectl get storageclass`, you should see that `gp2` is the default storage class.
```bash
$ kubectl get storageclass
NAME PROVISIONER RECLAIMPOLICY VOLUMEBINDINGMODE ALLOWVOLUMEEXPANSION AGE
gp2 (default) kubernetes.io/aws-ebs Delete WaitForFirstConsumer false 68m
```
Notice the `(default)` next to the `gp2` storage class.
</Step>
</Steps>
</Accordion>
You need to create a Persistent Volume Claim (PVC) to mount the HSM client files to the Infisical deployment.
```bash
kubectl apply -f - <<EOF
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: cloudhsm-data-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 500Mi
EOF
```
The above command will create a PVC named `cloudhsm-data-pvc` with a storage size of `500Mi`. You can change the storage size if needed.
Next we need to create a temporary pod with the PVC mounted as a volume, allowing us to copy the HSM client files into this mounted storage.
```bash
kubectl apply -f - <<EOF
apiVersion: v1
kind: Pod
metadata:
name: cloudhsm-setup-pod
spec:
containers:
- name: setup
image: debian:bookworm
command: ["/bin/sh", "-c", "sleep 7200"]
volumeMounts:
- name: cloudhsm-data
mountPath: /data
volumes:
- name: cloudhsm-data
persistentVolumeClaim:
claimName: cloudhsm-data-pvc
EOF
```
The above command will create a pod named `cloudhsm-setup-pod` with a Debian image. The pod will sleep for 7200 seconds _(two hours)_, which is enough time to set up the PVC and configure the HSM client.
Ensure that the pod is running and is healthy by running the following command:
```bash
kubectl wait --for=condition=Ready pod/cloudhsm-setup-pod --timeout=120s
```
</Step>
<Step title="Configure the PVC">
We need to configure the PVC to work with the CloudHSM, so Infisical can consume the HSM client files.
**2.1. Start a shell in the PVC pod:**
This will allow us to run commands directly within the setup pod. We'll use this to configure the CloudHSM client and to validate that it's working correctly.
```bash
kubectl exec -it cloudhsm-setup-pod -- /bin/sh
```
**2.2. Install the necessary packages:**
This will install the necessary packages to allow us to test and install the CloudHSM client.
```bash
apt-get update -y
apt-get install opensc telnet wget -y
```
**2.3. Try to reach the HSM device:**
We need to validate that we're able to reach the HSM device from within Kubernetes. You can use telnet to ping the HSM device like so:
```bash
telnet <HSM_ENI_IPV4_ADDRESS> 2223
```
You should see an output like this:
```bash
$ telnet <HSM_ENI_IPV4_ADDRESS> 2223
Trying <HSM_ENI_IPV4_ADDRESS>...
Connected to <HSM_ENI_IPV4_ADDRESS>.
```
If it gets stuck on `Trying ....`, you may have configured your HSM client's security group incorrectly. Make sure you configure the security group to allow traffic from EKS on port 2223-2225.
**2.4. Install the AWS CloudHSM client:**
The Infisical images run on Debian, so we need to install a Debian-compatible version of the AWS CloudHSM client.
```bash
wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/Jammy/cloudhsm-pkcs11_latest_u22.04_amd64.deb
apt-get install ./cloudhsm-pkcs11_latest_u22.04_amd64.deb -y
```
**2.5. Configure the CloudHSM client:**
After installing the CloudHSM client, you should see all related files in the `/opt/cloudhsm/` directory on the CloudHSM setup pod.
You need to run the `configure-pkcs11` binary which will configure the client to connect with your AWS CloudHSM cluster. Depending on if you have multiple HSM's inside your cluster, you'll need to run the command with different arguments. Below you'll find the appropriate command for your use case:
<AccordionGroup>
<Accordion title="Single HSM">
```bash
/opt/cloudhsm/bin/configure-pkcs11 -a <HSM_ENI_IPV4_ADDRESS> --disable-key-availability-check
```
<Info>
To use a single HSM, you must first manage client key durability settings by setting `disable_key_availability_check` to true by passing the `--disable-key-availability-check` flag. For more information read the [Key Synchronization](https://docs.aws.amazon.com/cloudhsm/latest/userguide/manage-key-sync.html) section in the AWS CloudHSM documentation.
</Info>
</Accordion>
<Accordion title="Multiple HSM's">
```bash
/opt/cloudhsm/bin/configure-pkcs11 -a <HSM_ENI_IPV4_ADDRESS_1> <HSM_ENI_IPV4_ADDRESS_2> ... --disable-key-availability-check
```
</Accordion>
</AccordionGroup>
**2.6. Verify the CloudHSM client is configured correctly:**
You can verify the CloudHSM client is configured correctly by running the following command:
```bash
cat /opt/cloudhsm/etc/cloudhsm-pkcs11.cfg
```
You should see an output like this:
```json
{
"clusters": [
{
"type": "hsm1",
"cluster": {
"hsm_ca_file": "/opt/cloudhsm/etc/customerCA.crt",
"servers": [
{
"hostname": "172.31.39.155",
"port": 2223,
"enable": true
}
],
"options": {
"disable_key_availability_check": true
}
}
}
],
"logging": {
"log_type": "file",
"log_file": "/opt/cloudhsm/run/cloudhsm-pkcs11.log",
"log_level": "info",
"log_interval": "daily"
}
}
```
**2.7. Exit the pod:**
Exit the pod by running the following command:
```bash
exit
```
**2.8. Copy your issuer CA certificate to the PVC:**
When you initialized your HSM, you were prompted to download the cluster CSR and sign it.
In order to use the HSM with Infisical, you need to obtain the issuer CA certificate that was used to sign the cluster CSR.
If you followed [the official AWS documentation](https://docs.aws.amazon.com/cloudhsm/latest/userguide/initialize-cluster.html), you should have a CA certificate called `customerCA.crt`.
Copy the CA certificate from your local machine to the setup pod:
```bash
kubectl cp /path/to/customerCA.crt cloudhsm-setup-pod:/opt/cloudhsm/etc/customerCA.crt
```
Ensure that the file is at `/opt/cloudhsm/etc/customerCA.crt` inside the setup pod by running the following command:
```bash
kubectl exec -it cloudhsm-setup-pod -- cat /opt/cloudhsm/etc/customerCA.crt
```
**2.9. Test the HSM client:**
Finally, after we're done configuring the HSM client, we need to test it to ensure that it's working correctly.
First, start a new shell into the setup pod by running the same shell command as before:
```bash
kubectl exec -it cloudhsm-setup-pod -- /bin/sh
```
Next, try generating a random 32 bytes long string by running the following command:
```bash
pkcs11-tool --module /opt/cloudhsm/lib/libcloudhsm_pkcs11.so \
--login --pin <crypto-user-username>:<crypto-user-password> \
--generate-random 32 | base64
```
You should see an output like this:
```bash
Using slot 0 with a present token (0x2000000000000001)
av1dlhVEsssjpcTNS+ysGUoKWH6+/PCaEDIdal5oQc0=
```
<Note>
Replace the `<crypto-user-username>:<crypto-user-password>` with your username and password combination of the Crypto user you have created that you want to use to perform cryptographic operations.
In AWS CloudHSM, the PIN is always the username and password separated by a colon.
</Note>
**2.10. Copy the configured client to the PVC:**
Copy from the HSM files into the `/data` directory in the PVC, which is what will be mounted for the Infisical deployment.
```bash
cp -r /opt/cloudhsm/. /data/
```
Verify the files were copied correctly by running the following command:
```bash
ls -la /data/
```
You should see an output like this:
```bash
drwxr-xr-x. 8 root root 4096 Oct 13 18:50 .
drwxr-xr-x. 1 root root 131 Oct 13 18:29 ..
drwxr-xr-x. 2 root root 4096 Oct 13 18:50 bin
drwxr-xr-x. 3 root root 4096 Oct 13 18:50 doc
drwxr-xr-x. 2 root root 4096 Oct 13 18:50 etc
drwxr-xr-x. 3 root root 4096 Oct 13 18:50 include
drwxr-xr-x. 2 root root 4096 Oct 13 18:50 lib
drwxr-xr-t. 2 root root 4096 Oct 13 18:50 run
```
**2.11. Set the correct permissions for the HSM client files:**
```bash
chmod -R 755 /data/
```
**2.12. Exit the pod:**
Exit the pod by running the following command:
```bash
exit
```
**2.13. Delete the setup pod:**
Delete the setup pod by running the following command:
```bash
kubectl delete pod cloudhsm-setup-pod
```
</Step>
<Step title="Updating your environment variables">
Next we need to update the environment variables used for the deployment. If you followed the [setup instructions for Kubernetes deployments](/self-hosting/deployment-options/kubernetes-helm), you should have a Kubernetes secret called `infisical-secrets`.
We need to update the secret with the following environment variables:
- `HSM_LIB_PATH` - The path to the CloudHSM PKCS#11 library _(mapped to `/opt/cloudhsm/lib/libcloudhsm_pkcs11.so`)_
- `HSM_PIN` - The PIN for the HSM device, which is the username and password of your Crypto User separated by a colon (e.g., `testUser:testPassword`)
- `HSM_SLOT` - The slot number for the HSM device that you found in the previous step
- `HSM_KEY_LABEL` - The label for the HSM key. If no key is found with the provided key label, the HSM will create a new key with the provided label.
The following is an example of the secret that you should update:
```yaml
apiVersion: v1
kind: Secret
metadata:
name: infisical-secrets
type: Opaque
stringData:
# ... Other environment variables ...
HSM_LIB_PATH: "/opt/cloudhsm/lib/libcloudhsm_pkcs11.so"
HSM_PIN: "testUser:testPassword" # Replace with your actual Crypto User credentials
HSM_SLOT: "0" # Replace with your actual slot number
HSM_KEY_LABEL: "infisical-crypto-key"
```
Save the file after updating the environment variables, and apply the secret changes
```bash
kubectl apply -f ./secret-file-name.yaml
```
</Step>
<Step title="Updating the Deployment">
After we've successfully configured the PVC and updated our environment variables, we are ready to update the deployment configuration so that the pods it creates can access the HSM client files.
```yaml
# ... The rest of the values.yaml file ...
infisical:
image:
repository: infisical/infisical
tag: "v0.151.0-nightly-20251013.1"
pullPolicy: IfNotPresent
extraVolumeMounts:
- name: cloudhsm-data
mountPath: /opt/cloudhsm # The path we will mount the HSM client files to
extraVolumes:
- name: cloudhsm-data
persistentVolumeClaim:
claimName: cloudhsm-data-pvc # The PVC we created in the previous step
# ... The rest of the values.yaml file ...
```
<Warning>
Make sure to set the `tag` to **`v0.151.0-nightly-20251013.1` or above**, as this is the minimum Infisical version that supports AWS CloudHSM.
</Warning>
<Warning>
Ensure that the configuration file at `/opt/cloudhsm/etc/cloudhsm-pkcs11.cfg` references the correct path for the issuer CA certificate (`/opt/cloudhsm/etc/customerCA.crt`). This should already be configured correctly if you followed the previous steps.
</Warning>
</Step>
<Step title="Upgrading the Helm Chart">
After updating the values.yaml file, you need to upgrade the Helm chart in order for the changes to take effect.
```bash
helm repo update
helm upgrade --install infisical infisical-helm-charts/infisical-standalone --values /path/to/values.yaml
```
</Step>
<Step title="Restarting the Deployment">
After upgrading the Helm chart, you need to restart the deployment in order for the changes to take effect.
```bash
kubectl rollout restart deployment/infisical-infisical-standalone-infisical
```
</Step>
</Steps>
After following these steps, your Kubernetes setup will be ready to use AWS CloudHSM encryption.
</Tab>
</Tabs> </Tabs>
</Tab> </Tab>
</Tabs> </Tabs>

Binary file not shown.

After

Width:  |  Height:  |  Size: 176 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 333 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 504 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 296 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 200 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 577 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 919 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 934 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 293 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 527 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 357 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 322 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 373 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 360 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 306 KiB

View File

@@ -0,0 +1,107 @@
---
title: "Laravel Forge Connection"
description: "Learn how to configure a Laravel Forge Connection for Infisical."
---
Infisical supports the use of [API Tokens](https://forge.laravel.com/docs/api#create-a-new-api-token) to connect with Laravel Forge.
## Create Laravel Forge API Token
<Steps>
<Step title="From your Laravel Forge dashboard, click on your user avatar and go to 'API'">
![Laravel Forge User Settings](/images/app-connections/laravel-forge/app-connection-profile.png)
</Step>
<Step title="Click 'Create Token'">
![Applications Tab](/images/app-connections/laravel-forge/app-connection-create-api-token.png)
</Step>
<Step title="Provide Token Information">
Provide a name for your token and select the following permissions:
- `user:view`
- `organization:view`
- `server:view`
- `site:manage-environment`
Then click 'Add token'.
![Token Form](/images/app-connections/laravel-forge/api-token-create-form.png)
</Step>
<Step title="Copy the token securely">
Make sure to copy the token now—you wont be able to access it again.
![Token Generated](/images/app-connections/laravel-forge/api-token-generated.png)
</Step>
</Steps>
## Create a Laravel Forge Connection in Infisical
<Tabs>
<Tab title="Infisical UI">
<Steps>
<Step title="Navigate to App Connections">
In your Infisical dashboard, navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
<Step title="Select Laravel Forge Connection">
Click **+ Add Connection** and choose **Laravel Forge** Connection from the list of integrations.
![Select Laravel Forge Connection](/images/app-connections/laravel-forge/app-connection-option.png)
</Step>
<Step title="Fill out the Laravel Forge Connection form">
Complete the form by providing:
- A descriptive name for the connection
- An optional description
- The API Token from the previous step
![Laravel Forge Connection Modal](/images/app-connections/laravel-forge/app-connection-form.png)
</Step>
<Step title="Connection created">
After submitting the form, your **Laravel Forge Connection** will be successfully created and ready to use with your Infisical project.
![Laravel Forge Connection Created](/images/app-connections/laravel-forge/app-connection-generated.png)
</Step>
</Steps>
</Tab>
<Tab title="API">
To create a Laravel Forge Connection via API, send a request to the [Create Laravel Forge Connection](/api-reference/endpoints/app-connections/laravel-forge/create) endpoint.
### Sample request
```bash Request
curl --request POST \
--url https://app.infisical.com/api/v1/app-connections/laravel-forge \
--header 'Content-Type: application/json' \
--data '{
"name": "my-laravel-forge-connection",
"method": "api-token",
"projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"apiToken": "[API TOKEN]"
}
}'
```
### Sample response
```bash Response
{
"appConnection": {
"id": "a1b2c3d4-5678-90ab-cdef-1234567890ab",
"name": "my-laravel-forge-connection",
"description": null,
"projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"version": 1,
"orgId": "abcdef12-3456-7890-abcd-ef1234567890",
"createdAt": "2025-10-13T10:15:00.000Z",
"updatedAt": "2025-10-13T10:15:00.000Z",
"isPlatformManagedCredentials": false,
"credentialsHash": "d41d8cd98f00b204e9800998ecf8427e",
"app": "laravel-forge",
"method": "api-token",
"credentials": {}
}
}
```
</Tab>
</Tabs>

View File

@@ -0,0 +1,157 @@
---
title: "Laravel Forge Sync"
description: "Learn how to configure a Laravel Forge Sync for Infisical."
---
**Prerequisites:**
- Create a [Laravel Forge Connection](/integrations/app-connections/laravel-forge)
<Tabs>
<Tab title="Infisical UI">
<Steps>
<Step title="Add Sync">
Navigate to **Project** > **Integrations** and select the **Secret Syncs** tab. Click on the **Add Sync** button.
![Secret Syncs Tab](/images/secret-syncs/general/secret-sync-tab.png)
</Step>
<Step title="Select 'Laravel Forge'">
![Select Laravel Forge](/images/secret-syncs/laravel-forge/select-option.png)
</Step>
<Step title="Configure source">
Configure the **Source** from where secrets should be retrieved, then click **Next**.
![Configure Source](/images/secret-syncs/laravel-forge/sync-source.png)
- **Environment**: The project environment to retrieve secrets from.
- **Secret Path**: The folder path to retrieve secrets from.
<Tip>
If you need to sync secrets from multiple folder locations, check out [secret imports](/documentation/platform/secret-reference#secret-imports).
</Tip>
</Step>
<Step title="Configure destination">
Configure the **Destination** to where secrets should be deployed, then click **Next**.
![Configure Destination](/images/secret-syncs/laravel-forge/sync-destination.png)
- **Laravel Forge Connection**: The Laravel Forge Connection to authenticate with.
- **Organization**: The Organization in which the server and site reside.
- **Server**: The Server on which the site resides.
- **Site**: The Site for which secrets should be synced.
</Step>
<Step title="Configure Sync Options">
Configure the **Sync Options** to specify how secrets should be synced, then click **Next**.
![Configure Options](/images/secret-syncs/laravel-forge/sync-options.png)
- **Initial Sync Behavior**: Determines how Infisical should resolve the initial sync.
- **Overwrite Destination Secrets**: Removes any secrets at the destination endpoint not present in Infisical.
- **Import Secrets (Prioritize Infisical)**: Imports secrets from the destination endpoint before syncing, prioritizing values from Infisical over Laravel Forge when keys conflict.
- **Import Secrets (Prioritize Laravel Forge)**: Imports secrets from the destination endpoint before syncing, prioritizing values from Laravel Forge over Infisical when keys conflict.
- **Key Schema**: Template that determines how secret names are transformed when syncing, using `{{secretKey}}` as a placeholder for the original secret name and `{{environment}}` for the environment.
<Note>
We highly recommend using a Key Schema to ensure that Infisical only manages the specific keys you intend, keeping everything else untouched.
</Note>
- **Auto-Sync Enabled**: If enabled, secrets will automatically be synced from the source location when changes occur. Disable to enforce manual syncing only.
- **Disable Secret Deletion**: If enabled, Infisical will not remove secrets from the sync destination. Enable this option if you intend to manage some secrets manually outside of Infisical.
</Step>
<Step title="Configure details">
Configure the **Details** of your Laravel Forge Sync, then click **Next**.
![Configure Details](/images/secret-syncs/laravel-forge/sync-details.png)
- **Name**: The name of your sync. Must be slug-friendly.
- **Description**: An optional description for your sync.
</Step>
<Step title="Review configuration">
Review your Laravel Forge Sync configuration, then click **Create Sync**.
![Review Configuration](/images/secret-syncs/laravel-forge/sync-review.png)
</Step>
<Step title="Sync created">
If enabled, your Laravel Forge Sync will begin syncing your secrets to the destination endpoint.
![Sync Created](/images/secret-syncs/laravel-forge/sync-created.png)
</Step>
</Steps>
</Tab>
<Tab title="API">
To create a **Laravel Forge Sync**, make an API request to the [Create Laravel Forge Sync](/api-reference/endpoints/secret-syncs/laravel-forge/create) API endpoint.
### Sample request
```bash Request
curl --request POST \
--url https://app.infisical.com/api/v1/secret-syncs/laravel-forge \
--header 'Content-Type: application/json' \
--data '{
"name": "my-laravel-forge-sync",
"projectId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"description": "sync to laravel forge site",
"connectionId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"environment": "dev",
"secretPath": "/",
"isEnabled": true,
"isAutoSyncEnabled": true,
"syncOptions": {
"initialSyncBehavior": "overwrite-destination",
"disableSecretDeletion": false
},
"destinationConfig": {
"orgSlug": "org-abc123",
"serverId": "123",
"siteId": "site-abc123"
}
}'
```
### Sample response
```bash Response
{
"secretSync": {
"id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"name": "my-laravel-forge-sync",
"description": "sync to laravel forge site",
"folderId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"connectionId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"createdAt": "2025-07-19T12:00:00Z",
"updatedAt": "2025-07-19T12:00:00Z",
"syncStatus": "succeeded",
"lastSyncJobId": "job-1234",
"lastSyncMessage": null,
"lastSyncedAt": "2025-07-19T12:00:00Z",
"syncOptions": {
"initialSyncBehavior": "overwrite-destination",
"disableSecretDeletion": false
},
"projectId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"connection": {
"app": "laravel-forge",
"name": "my-laravel-forge-connection",
"id": "3c90c3cc-0d44-4b50-8888-8dd25736052a"
},
"environment": {
"slug": "dev",
"name": "Development",
"id": "3c90c3cc-0d44-4b50-8888-8dd25736052a"
},
"folder": {
"id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"path": "/"
},
"destination": "laravel-forge",
"destinationConfig": {
"orgSlug": "org-abc123",
"serverId": "123",
"siteId": "site-abc123"
}
}
}
```
</Tab>
</Tabs>

View File

@@ -78,6 +78,7 @@ description: "Learn how to configure a Netlify Sync for Infisical."
![Sync Created](/images/secret-syncs/netlify/sync-created.png) ![Sync Created](/images/secret-syncs/netlify/sync-created.png)
</Step> </Step>
</Steps> </Steps>
</Tab> </Tab>
<Tab title="API"> <Tab title="API">
@@ -157,5 +158,6 @@ description: "Learn how to configure a Netlify Sync for Infisical."
} }
} }
``` ```
</Tab> </Tab>
</Tabs> </Tabs>

View File

@@ -0,0 +1,162 @@
---
title: "Replication"
description: "Learn how Infisical supports multi-region replication"
---
<Info>
Infisical replication is a paid feature.
If you're using Infisical Cloud, then it is available under the **Enterprise Tier**. If you're self-hosting Infisical,
then you should contact team@infisical.com to purchase an enterprise license to use it.
</Info>
Multi-region replication is available in Infisical Enterprise to support globally distributed deployments. Understanding the architecture, use cases, and operational considerations is essential before implementing this feature in production environments.
Infisical uses a primary/secondary (1:N) architecture with asynchronous PostgreSQL replication. This design prioritizes high availability and minimal read latency for applications deployed across multiple geographic regions.
## Use cases
- **Multi-Region Deployments**: Serving secrets to applications distributed across continents from a single region introduces unacceptable latency. A centralized deployment also creates a single point of failure: regional outages can render secrets inaccessible globally, and network connectivity issues impact availability.
- **Geographic Data Locality**: Global organizations need to minimize the time it takes for applications to retrieve secrets and configurations. Regional replicas enable applications to fetch data from nearby instances rather than making cross-continental requests.
- **Disaster Recovery**: Organizations need resilience against primary region failures. Secondary regions with read replicas can be promoted to primary status when needed, maintaining operations during outages or disasters.
## Design Goals
In order to address the common use cases, the implementation reflects several core goals:
- **Optimized Read Performance**: Applications need fast access to secrets regardless of their location. Regional instances use Redis for aggressive caching and read from local PostgreSQL replicas, eliminating cross-region round trips for most read operations.
- **Conflict-Free Architecture**: All mutations flow through the primary instance exclusively. This prevents write conflicts and split-brain scenarios that plague multi-master systems. The trade-off ensures data integrity without requiring conflict resolution strategies.
- **Zero Client Changes**: Existing Infisical integrations, SDKs, and CLI tools work without modification. Regional instances route write operations to the primary while handling reads locally. Authentication tokens and API keys function identically across all instances.
- **Operational Simplicity**: Deploying additional regions requires minimal configuration. PostgreSQL handles replication complexity, and the stateless application tier scales horizontally without coordination overhead.
# Architecture
Infisical distinguishes between _primary_ and _secondary_ instances. The primary holds write authority and is the sole instance permitted to modify the PostgreSQL database. Secondary instances handle read traffic locally and proxy write operations to the primary.
## Infrastructure components
Two data stores form Infisical's persistence layer:
- **PostgreSQL** maintains the authoritative dataset including secrets with their version history, authentication credentials, user identities, project configurations, access policies, audit trails, and integration settings. All persistent state lives in PostgreSQL.
- **Redis** accelerates read operations through caching and manages asynchronous job queues. Each regional deployment maintains an independent Redis instance optimized for local access patterns.
The Infisical application servers are stateless and therefore hold no persistent data internally. This design simplifies regional deployment and horizontal scaling.
<Tabs>
<Tab title="Primary region configuration">
A primary deployment consists of three core components:
- **Application Servers**: Process all API requests directly, handling both read and write operations without forwarding
- **PostgreSQL Primary Database**: Accepts read and write queries, serving as the authoritative source of truth
- **Redis Cache**: Stores frequently accessed data and executes all background jobs including secret synchronization, scheduled tasks, and audit log processing
</Tab>
<Tab title="Secondary region configuration">
Each secondary deployment mirrors the primary structure with key differences:
- **Application Servers**: Service read requests from local infrastructure but forward any write requests to the primary region
- **PostgreSQL Read Replica**: Continuously streams changes from the primary database via PostgreSQL replication
- **PostgreSQL Primary Database**: Connection string to the primary database for write forwarding
- **Redis Cache**: Maintains a local cache but processes only audit logs (other background jobs remain disabled)
Configuring a secondary region requires four main environment variables:
1. `INFISICAL_PRIMARY_INSTANCE_URL`: The primary region's Infisical API endpoint
2. Postgres primary instance connection details. View related [environment variables](/self-hosting/configuration/envars#postgresql).
3. Postgres read replica connection details. View related [environment variables](/self-hosting/configuration/envars#postgresql).
4. Redis connection details. View related [environment variables](/self-hosting/configuration/envars#redis).
</Tab>
</Tabs>
## How requests are processed
When a client sends a read request to a secondary instance, the application first checks the local Redis cache for the requested data. If the data exists in cache, it's returned immediately to the client. Otherwise, the application queries the local PostgreSQL read replica, caches the result in Redis for future requests, and returns the response to the client.
Write operations follow a different path. When a secondary receives a write request, it forwards the complete request to the primary instance URL. The primary processes the mutation against the authoritative database and returns a response, which the secondary then forwards back to the client. PostgreSQL subsequently streams these changes to all replicas asynchronously.
Operations against the primary instance are more straightforward, as both reads and writes execute directly against local infrastructure without any forwarding.
## Replication mechanism
PostgreSQL streaming replication handles all data synchronization. When transactions commit on the primary, changes are written to the write-ahead log (WAL) and streamed to all configured replicas, which apply the entries to maintain consistency. Replication lag typically remains under one second.
This approach replicates all data stored in PostgreSQL: secrets and their version histories, user accounts and permissions, authentication tokens, project configurations, access policies, audit logs, integration settings, and all other application metadata. Replicas are eventually consistent. This means that all replicas eventually converge to the same state, typically under 1 second. The application layer remains unaware of replication mechanics and operates identically across all instances.
## Caching behavior
Redis caches are regional and independent (no coordination occurs between instances):
- Secondary instances populate caches on demand from read requests
- Cache hits serve data without touching PostgreSQL
- Cache misses fetch from the local replica and populate the cache
- Each region maintains its own hot dataset based on local access patterns
Secrets use versioned caching. When a secret changes, its version identifier changes, causing automatic cache misses. This ensures subsequent reads fetch the updated value from PostgreSQL without requiring active cache invalidation.
# Technical Details
Understanding the implementation details can help evaluate whether Infisical's replication characteristics align with your requirements.
The following sections provide deeper insight into performance behavior, failure modes, and the underlying mechanisms that drive the replication system.
### PostgreSQL streaming replication
Infisical relies on PostgreSQL's native replication, which provides:
- **Asynchronous operation**: The primary commits transactions immediately without waiting for replicas to confirm receipt. Replicas receive and apply changes continuously with typical lag measured in milliseconds to low seconds, depending on network conditions and write volume.
- **Binary-level consistency**: Replication occurs at the storage layer using write-ahead logs, guaranteeing replicas are byte-for-byte identical to the primary at the block level.
- **Promotion capability**: Read replicas can be promoted to primary during disaster recovery. Promotion requires updating Infisical configuration to designate the promoted instance as primary and reconfiguring other secondaries.
Consult PostgreSQL's official documentation for replication setup instructions specific to your hosting environment (RDS, Cloud SQL, self-managed, etc.).
### Version management
All Infisical instances must run identical versions (mixing versions risks database schema mismatches or incompatible API behavior). Database migrations execute only on the primary and replicate to secondaries through standard PostgreSQL mechanisms.
During upgrades:
1. Upgrade the primary instance (migrations run automatically)
2. Upgrade secondary instances to match
3. All instances can continue running during the upgrade process since database migrations don't immediately drop tables/columns
### Request proxying
When a secondary receives a mutation request (POST, PUT, PATCH, DELETE), it functions as a transparent proxy:
1. Preserve the original request completely (headers, authentication context, request body)
2. Forward to the primary instance URL specified in configuration
3. Primary processes the request as a direct client request
4. Return the primary's response unmodified to the client
### Cache management
Infisical uses versioned caching rather than active invalidation:
1. Secrets and other cached entities include version identifiers
2. When data mutates, its version changes in the database
3. Cache lookups include the version in the cache key
4. Version changes cause automatic cache misses
5. Cache misses fetch updated data from PostgreSQL
6. Fresh data populates the cache with the new version
This strategy ensures correctness without requiring cross-region cache invalidation protocols.
### Background job processing
Secondary instances run with restricted background job capabilities:
**Active**: Audit log processing
**Disabled**: Secret synchronization to third-party systems, scheduled tasks, cron jobs, time-triggered operations
Limiting background jobs to the primary prevents duplicate processing and ensures integrations execute once.

View File

@@ -45,7 +45,8 @@ export const AppConnectionsBrowser = () => {
{"name": "Redis", "slug": "redis", "path": "/integrations/app-connections/redis", "description": "Learn how to connect Redis to pull secrets from Infisical.", "category": "Databases"}, {"name": "Redis", "slug": "redis", "path": "/integrations/app-connections/redis", "description": "Learn how to connect Redis to pull secrets from Infisical.", "category": "Databases"},
{"name": "LDAP", "slug": "ldap", "path": "/integrations/app-connections/ldap", "description": "Learn how to connect your LDAP to pull secrets from Infisical.", "category": "Directory Services"}, {"name": "LDAP", "slug": "ldap", "path": "/integrations/app-connections/ldap", "description": "Learn how to connect your LDAP to pull secrets from Infisical.", "category": "Directory Services"},
{"name": "Auth0", "slug": "auth0", "path": "/integrations/app-connections/auth0", "description": "Learn how to connect your Auth0 to pull secrets from Infisical.", "category": "Identity & Auth"}, {"name": "Auth0", "slug": "auth0", "path": "/integrations/app-connections/auth0", "description": "Learn how to connect your Auth0 to pull secrets from Infisical.", "category": "Identity & Auth"},
{"name": "Okta", "slug": "okta", "path": "/integrations/app-connections/okta", "description": "Learn how to connect your Okta to pull secrets from Infisical.", "category": "Identity & Auth"} {"name": "Okta", "slug": "okta", "path": "/integrations/app-connections/okta", "description": "Learn how to connect your Okta to pull secrets from Infisical.", "category": "Identity & Auth"},
{"name": "Laravel Forge", "slug": "laravel-forge", "path": "/integrations/app-connections/laravel-forge", "description": "Learn how to connect your Laravel Forge to pull secrets from Infisical.", "category": "Hosting"},
].sort(function(a, b) { ].sort(function(a, b) {
return a.name.toLowerCase().localeCompare(b.name.toLowerCase()); return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
}); });

View File

@@ -36,7 +36,8 @@ export const SecretSyncsBrowser = () => {
{"name": "Camunda", "slug": "camunda", "path": "/integrations/secret-syncs/camunda", "description": "Learn how to sync secrets from Infisical to Camunda.", "category": "DevOps Tools"}, {"name": "Camunda", "slug": "camunda", "path": "/integrations/secret-syncs/camunda", "description": "Learn how to sync secrets from Infisical to Camunda.", "category": "DevOps Tools"},
{"name": "Humanitec", "slug": "humanitec", "path": "/integrations/secret-syncs/humanitec", "description": "Learn how to sync secrets from Infisical to Humanitec.", "category": "DevOps Tools"}, {"name": "Humanitec", "slug": "humanitec", "path": "/integrations/secret-syncs/humanitec", "description": "Learn how to sync secrets from Infisical to Humanitec.", "category": "DevOps Tools"},
{"name": "OCI Vault", "slug": "oci-vault", "path": "/integrations/secret-syncs/oci-vault", "description": "Learn how to sync secrets from Infisical to OCI Vault.", "category": "Cloud Providers"}, {"name": "OCI Vault", "slug": "oci-vault", "path": "/integrations/secret-syncs/oci-vault", "description": "Learn how to sync secrets from Infisical to OCI Vault.", "category": "Cloud Providers"},
{"name": "Zabbix", "slug": "zabbix", "path": "/integrations/secret-syncs/zabbix", "description": "Learn how to sync secrets from Infisical to Zabbix.", "category": "Monitoring"} {"name": "Zabbix", "slug": "zabbix", "path": "/integrations/secret-syncs/zabbix", "description": "Learn how to sync secrets from Infisical to Zabbix.", "category": "Monitoring"},
{"name": "Laravel Forge", "slug": "laravel-forge", "path": "/integrations/secret-syncs/laravel-forge", "description": "Learn how to sync secrets from Infisical to Laravel Forge.", "category": "Hosting"}
].sort(function(a, b) { ].sort(function(a, b) {
return a.name.toLowerCase().localeCompare(b.name.toLowerCase()); return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
}); });

View File

@@ -270,7 +270,7 @@
"description": "This page shows the members of the selected project, and allows you to modify their permissions." "description": "This page shows the members of the selected project, and allows you to modify their permissions."
}, },
"org": { "org": {
"title": "Organization Settings", "title": "Settings",
"description": "Manage members of your organization. These users could afterwards be formed into projects." "description": "Manage members of your organization. These users could afterwards be formed into projects."
}, },
"personal": { "personal": {
@@ -290,7 +290,7 @@
} }
}, },
"project": { "project": {
"title": "Project Settings", "title": "Settings",
"description": "These settings only apply to the currently selected Project.", "description": "These settings only apply to the currently selected Project.",
"danger-zone": "Danger Zone", "danger-zone": "Danger Zone",
"delete-project": "Delete Project", "delete-project": "Delete Project",

View File

@@ -17,7 +17,7 @@ export const SecretSyncModalHeader = ({ destination, isConfigured }: Props) => {
<img <img
alt={`${destinationDetails.name} logo`} alt={`${destinationDetails.name} logo`}
src={`/images/integrations/${destinationDetails.image}`} src={`/images/integrations/${destinationDetails.image}`}
className="h-12 w-12 rounded-md bg-bunker-500 p-2" className="h-12 w-12 rounded-md bg-bunker-500 object-contain p-2"
/> />
<div> <div>
<div className="flex items-center text-mineshaft-300"> <div className="flex items-center text-mineshaft-300">

View File

@@ -0,0 +1,138 @@
import { Controller, useFormContext, useWatch } from "react-hook-form";
import { SingleValue } from "react-select";
import { SecretSyncConnectionField } from "@app/components/secret-syncs/forms/SecretSyncConnectionField";
import { FilterableSelect, FormControl } from "@app/components/v2";
import {
TLaravelForgeOrganization,
TLaravelForgeServer,
TLaravelForgeSite,
useLaravelForgeConnectionListOrganizations,
useLaravelForgeConnectionListServers,
useLaravelForgeConnectionListSites
} from "@app/hooks/api/appConnections/laravel-forge";
import { SecretSync } from "@app/hooks/api/secretSyncs";
import { TSecretSyncForm } from "../schemas";
export const LaravelForgeSyncFields = () => {
const { control, setValue } = useFormContext<
TSecretSyncForm & { destination: SecretSync.LaravelForge }
>();
const connectionId = useWatch({ name: "connection.id", control });
const orgSlug = useWatch({ name: "destinationConfig.orgSlug", control });
const serverId = useWatch({ name: "destinationConfig.serverId", control });
const { data: organizations, isLoading: isOrganizationsLoading } =
useLaravelForgeConnectionListOrganizations(connectionId, {
enabled: Boolean(connectionId)
});
const { data: servers, isLoading: isServersLoading } = useLaravelForgeConnectionListServers(
connectionId,
orgSlug,
{
enabled: Boolean(connectionId && orgSlug)
}
);
const { data: sites, isLoading: isSitesLoading } = useLaravelForgeConnectionListSites(
connectionId,
orgSlug,
serverId,
{
enabled: Boolean(connectionId && orgSlug && serverId)
}
);
const handleChangeConnection = () => {
setValue("destinationConfig.orgSlug", "");
setValue("destinationConfig.serverId", "");
setValue("destinationConfig.siteId", "");
setValue("destinationConfig.orgName", "");
setValue("destinationConfig.serverName", "");
setValue("destinationConfig.siteName", "");
};
return (
<>
<SecretSyncConnectionField onChange={handleChangeConnection} />
<Controller
name="destinationConfig.orgSlug"
control={control}
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl isError={Boolean(error)} errorText={error?.message} label="Organization">
<FilterableSelect
menuPlacement="top"
isLoading={isOrganizationsLoading && Boolean(connectionId)}
isDisabled={!connectionId}
value={organizations?.find((org) => org.slug === value) ?? null}
onChange={(option) => {
const selectedOrg = option as SingleValue<TLaravelForgeOrganization>;
onChange(selectedOrg?.slug ?? "");
setValue("destinationConfig.orgName", selectedOrg?.name ?? "");
setValue("destinationConfig.serverId", "");
setValue("destinationConfig.siteId", "");
}}
options={organizations}
placeholder="Select an organization..."
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.id}
/>
</FormControl>
)}
/>
<Controller
name="destinationConfig.serverId"
control={control}
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl isError={Boolean(error)} errorText={error?.message} label="Server">
<FilterableSelect
menuPlacement="top"
isLoading={isServersLoading && Boolean(connectionId && orgSlug)}
isDisabled={!connectionId || !orgSlug}
value={servers?.find((server) => server.id === value) ?? null}
onChange={(option) => {
const selectedServer = option as SingleValue<TLaravelForgeServer>;
onChange(selectedServer?.id ?? "");
setValue("destinationConfig.serverName", selectedServer?.name ?? "");
setValue("destinationConfig.siteId", "");
}}
options={servers}
placeholder="Select a server..."
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.id}
/>
</FormControl>
)}
/>
<Controller
name="destinationConfig.siteId"
control={control}
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl isError={Boolean(error)} errorText={error?.message} label="Site">
<FilterableSelect
menuPlacement="top"
isLoading={isSitesLoading && Boolean(connectionId && orgSlug && serverId)}
isDisabled={!connectionId || !orgSlug || !serverId}
value={sites?.find((site) => site.id === value) ?? null}
onChange={(option) => {
const selectedSite = option as SingleValue<TLaravelForgeSite>;
onChange(selectedSite?.id ?? "");
setValue("destinationConfig.siteName", selectedSite?.name ?? "");
}}
options={sites}
placeholder="Select a site..."
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.id}
/>
</FormControl>
)}
/>
</>
);
};

View File

@@ -23,6 +23,7 @@ import { GitLabSyncFields } from "./GitLabSyncFields";
import { HCVaultSyncFields } from "./HCVaultSyncFields"; import { HCVaultSyncFields } from "./HCVaultSyncFields";
import { HerokuSyncFields } from "./HerokuSyncFields"; import { HerokuSyncFields } from "./HerokuSyncFields";
import { HumanitecSyncFields } from "./HumanitecSyncFields"; import { HumanitecSyncFields } from "./HumanitecSyncFields";
import { LaravelForgeSyncFields } from "./LaravelForgeSyncFields";
import { NetlifySyncFields } from "./NetlifySyncFields"; import { NetlifySyncFields } from "./NetlifySyncFields";
import { OCIVaultSyncFields } from "./OCIVaultSyncFields"; import { OCIVaultSyncFields } from "./OCIVaultSyncFields";
import { RailwaySyncFields } from "./RailwaySyncFields"; import { RailwaySyncFields } from "./RailwaySyncFields";
@@ -100,6 +101,8 @@ export const SecretSyncDestinationFields = () => {
return <NetlifySyncFields />; return <NetlifySyncFields />;
case SecretSync.Bitbucket: case SecretSync.Bitbucket:
return <BitbucketSyncFields />; return <BitbucketSyncFields />;
case SecretSync.LaravelForge:
return <LaravelForgeSyncFields />;
default: default:
throw new Error(`Unhandled Destination Config Field: ${destination}`); throw new Error(`Unhandled Destination Config Field: ${destination}`);
} }

View File

@@ -69,6 +69,7 @@ export const SecretSyncOptionsFields = ({ hideInitialSync }: Props) => {
case SecretSync.DigitalOceanAppPlatform: case SecretSync.DigitalOceanAppPlatform:
case SecretSync.Netlify: case SecretSync.Netlify:
case SecretSync.Bitbucket: case SecretSync.Bitbucket:
case SecretSync.LaravelForge:
AdditionalSyncOptionsFieldsComponent = null; AdditionalSyncOptionsFieldsComponent = null;
break; break;
default: default:

View File

@@ -0,0 +1,23 @@
import { useFormContext } from "react-hook-form";
import { TSecretSyncForm } from "@app/components/secret-syncs/forms/schemas";
import { GenericFieldLabel } from "@app/components/v2";
import { SecretSync } from "@app/hooks/api/secretSyncs";
export const LaravelForgeSyncReviewFields = () => {
const { watch } = useFormContext<TSecretSyncForm & { destination: SecretSync.LaravelForge }>();
const orgName = watch("destinationConfig.orgName");
const orgSlug = watch("destinationConfig.orgSlug");
const serverName = watch("destinationConfig.serverName");
const serverId = watch("destinationConfig.serverId");
const siteName = watch("destinationConfig.siteName");
const siteId = watch("destinationConfig.siteId");
return (
<>
<GenericFieldLabel label="Account">{orgName || orgSlug}</GenericFieldLabel>
<GenericFieldLabel label="Server">{serverName || serverId || "None"}</GenericFieldLabel>
<GenericFieldLabel label="Site">{siteName || siteId || "None"}</GenericFieldLabel>
</>
);
};

View File

@@ -35,6 +35,7 @@ import { GitLabSyncReviewFields } from "./GitLabSyncReviewFields";
import { HCVaultSyncReviewFields } from "./HCVaultSyncReviewFields"; import { HCVaultSyncReviewFields } from "./HCVaultSyncReviewFields";
import { HerokuSyncReviewFields } from "./HerokuSyncReviewFields"; import { HerokuSyncReviewFields } from "./HerokuSyncReviewFields";
import { HumanitecSyncReviewFields } from "./HumanitecSyncReviewFields"; import { HumanitecSyncReviewFields } from "./HumanitecSyncReviewFields";
import { LaravelForgeSyncReviewFields } from "./LaravelForgeSyncReviewFields";
import { NetlifySyncReviewFields } from "./NetlifySyncReviewFields"; import { NetlifySyncReviewFields } from "./NetlifySyncReviewFields";
import { OCIVaultSyncReviewFields } from "./OCIVaultSyncReviewFields"; import { OCIVaultSyncReviewFields } from "./OCIVaultSyncReviewFields";
import { OnePassSyncReviewFields } from "./OnePassSyncReviewFields"; import { OnePassSyncReviewFields } from "./OnePassSyncReviewFields";
@@ -168,6 +169,9 @@ export const SecretSyncReviewFields = () => {
case SecretSync.Bitbucket: case SecretSync.Bitbucket:
DestinationFieldsComponent = <BitbucketSyncReviewFields />; DestinationFieldsComponent = <BitbucketSyncReviewFields />;
break; break;
case SecretSync.LaravelForge:
DestinationFieldsComponent = <LaravelForgeSyncReviewFields />;
break;
default: default:
throw new Error(`Unhandled Destination Review Fields: ${destination}`); throw new Error(`Unhandled Destination Review Fields: ${destination}`);
} }

View File

@@ -0,0 +1,18 @@
import { z } from "zod";
import { BaseSecretSyncSchema } from "@app/components/secret-syncs/forms/schemas/base-secret-sync-schema";
import { SecretSync } from "@app/hooks/api/secretSyncs";
export const LaravelForgeSyncDestinationSchema = BaseSecretSyncSchema().merge(
z.object({
destination: z.literal(SecretSync.LaravelForge),
destinationConfig: z.object({
orgSlug: z.string().trim().min(1, "Org Slug required"),
orgName: z.string().trim().min(1, "Org Name required"),
serverId: z.string().trim().min(1, "Server ID required"),
serverName: z.string().trim().min(1, "Server Name required"),
siteId: z.string().trim().min(1, "Site ID required"),
siteName: z.string().trim().min(1, "Site Name required")
})
})
);

View File

@@ -20,6 +20,7 @@ import { GitlabSyncDestinationSchema } from "./gitlab-sync-destination-schema";
import { HCVaultSyncDestinationSchema } from "./hc-vault-sync-destination-schema"; import { HCVaultSyncDestinationSchema } from "./hc-vault-sync-destination-schema";
import { HerokuSyncDestinationSchema } from "./heroku-sync-destination-schema"; import { HerokuSyncDestinationSchema } from "./heroku-sync-destination-schema";
import { HumanitecSyncDestinationSchema } from "./humanitec-sync-destination-schema"; import { HumanitecSyncDestinationSchema } from "./humanitec-sync-destination-schema";
import { LaravelForgeSyncDestinationSchema } from "./laravel-forge-sync-destination-schema";
import { NetlifySyncDestinationSchema } from "./netlify-sync-destination-schema"; import { NetlifySyncDestinationSchema } from "./netlify-sync-destination-schema";
import { OCIVaultSyncDestinationSchema } from "./oci-vault-sync-destination-schema"; import { OCIVaultSyncDestinationSchema } from "./oci-vault-sync-destination-schema";
import { RailwaySyncDestinationSchema } from "./railway-sync-destination-schema"; import { RailwaySyncDestinationSchema } from "./railway-sync-destination-schema";
@@ -61,7 +62,8 @@ const SecretSyncUnionSchema = z.discriminatedUnion("destination", [
ChecklySyncDestinationSchema, ChecklySyncDestinationSchema,
DigitalOceanAppPlatformSyncDestinationSchema, DigitalOceanAppPlatformSyncDestinationSchema,
NetlifySyncDestinationSchema, NetlifySyncDestinationSchema,
BitbucketSyncDestinationSchema BitbucketSyncDestinationSchema,
LaravelForgeSyncDestinationSchema
]); ]);
export const SecretSyncFormSchema = SecretSyncUnionSchema; export const SecretSyncFormSchema = SecretSyncUnionSchema;

View File

@@ -17,6 +17,7 @@ import {
} from "@app/components/v2"; } from "@app/components/v2";
import { useProject } from "@app/context"; import { useProject } from "@app/context";
import { useCreateWsTag } from "@app/hooks/api"; import { useCreateWsTag } from "@app/hooks/api";
import { SecretV3RawSanitized, WsTag } from "@app/hooks/api/types";
import { slugSchema } from "@app/lib/schemas"; import { slugSchema } from "@app/lib/schemas";
export const secretTagsColors = [ export const secretTagsColors = [
@@ -85,6 +86,8 @@ const isValidHexColor = (hexColor: string) => {
type Props = { type Props = {
isOpen?: boolean; isOpen?: boolean;
onToggle: (isOpen: boolean) => void; onToggle: (isOpen: boolean) => void;
append: (data: WsTag) => void;
currentSecret?: SecretV3RawSanitized;
}; };
const createTagSchema = z.object({ const createTagSchema = z.object({
@@ -100,7 +103,7 @@ type TagColor = {
name: string; name: string;
}; };
export const CreateTagModal = ({ isOpen, onToggle }: Props): JSX.Element => { export const CreateTagModal = ({ isOpen, onToggle, append, currentSecret }: Props): JSX.Element => {
const { const {
control, control,
reset, reset,
@@ -128,11 +131,12 @@ export const CreateTagModal = ({ isOpen, onToggle }: Props): JSX.Element => {
const onFormSubmit = async ({ slug, color }: FormData) => { const onFormSubmit = async ({ slug, color }: FormData) => {
try { try {
await createWsTag({ const data = await createWsTag({
projectId, projectId,
tagColor: color, tagColor: color,
tagSlug: slug tagSlug: slug
}); });
append(data);
onToggle(false); onToggle(false);
reset(); reset();
createNotification({ createNotification({
@@ -151,8 +155,12 @@ export const CreateTagModal = ({ isOpen, onToggle }: Props): JSX.Element => {
return ( return (
<Modal isOpen={isOpen} onOpenChange={onToggle}> <Modal isOpen={isOpen} onOpenChange={onToggle}>
<ModalContent <ModalContent
title="Create tag" title={currentSecret ? `Create tag for ${currentSecret.key}` : "Create tag"}
subTitle="Specify your tag name, and the slug will be created automatically." subTitle={
currentSecret
? `Create a new tag, and it will be automatically linked to secret: ${currentSecret.key}.`
: "Specify your tag name, and the slug will be created automatically."
}
> >
<form onSubmit={handleSubmit(onFormSubmit)}> <form onSubmit={handleSubmit(onFormSubmit)}>
<Controller <Controller
@@ -253,7 +261,7 @@ export const CreateTagModal = ({ isOpen, onToggle }: Props): JSX.Element => {
isDisabled={isSubmitting} isDisabled={isSubmitting}
isLoading={isSubmitting} isLoading={isSubmitting}
> >
Create {currentSecret ? "Create and Add" : "Create"}
</Button> </Button>
<ModalClose asChild> <ModalClose asChild>
<Button variant="plain" colorSchema="secondary"> <Button variant="plain" colorSchema="secondary">

View File

@@ -17,7 +17,14 @@ const badgeVariants = cva(
variant: { variant: {
primary: "bg-yellow/20 text-yellow", primary: "bg-yellow/20 text-yellow",
danger: "bg-red/20 text-red", danger: "bg-red/20 text-red",
success: "bg-green/20 text-green" success: "bg-green/20 text-green",
org: "bg-org-v1/20 text-org-v1 [&_svg]:text-org-v1 flex items-center opacity-100 hover:bg-org-v1/10 [&_svg]:size-3 gap-x-1 w-min whitespace-nowrap",
namespace:
"bg-namespace-v1/20 text-namespace-v1 [&_svg]:text-namespace-v1 flex opacity-100 hover:bg-namespace-v1/10 items-center [&_svg]:size-3.5 gap-x-1 w-min whitespace-nowrap",
project:
"bg-primary/10 text-primary [&_svg]:text-primary opacity-100 hover:bg-primary/10 flex items-center [&_svg]:size-3 gap-x-1 w-min whitespace-nowrap",
instance:
"bg-mineshaft-200/20 text-mineshaft-200 [&_svg]:text-mineshaft-200 opacity-100 hover:bg-mineshaft-200/20 flex items-center [&_svg]:size-3 gap-x-1 w-min whitespace-nowrap"
} }
} }
} }

View File

@@ -33,16 +33,21 @@ export const MenuItem = <T extends ElementType = "button">({
description, description,
// wrapping in forward ref with generic component causes the loss of ts definitions on props // wrapping in forward ref with generic component causes the loss of ts definitions on props
inputRef, inputRef,
variant,
...props ...props
}: MenuItemProps<T> & ComponentPropsWithRef<T>): JSX.Element => { }: MenuItemProps<T> &
ComponentPropsWithRef<T> & { variant?: "project" | "namespace" | "org" }): JSX.Element => {
return ( return (
<Item <Item
type="button" type="button"
role="menuitem" role="menuitem"
className={twMerge( className={twMerge(
"group relative mt-0.5 flex w-full cursor-pointer items-center rounded-sm px-2 py-2 font-inter text-sm text-bunker-100 transition-all duration-50 hover:bg-mineshaft-700", "group relative mt-0.5 box-border flex w-full cursor-pointer items-center rounded-[2px] border-l-2 border-transparent px-2 py-2 font-inter text-sm text-bunker-100 transition-all duration-50 hover:bg-mineshaft-700",
isSelected && "bg-mineshaft-600 hover:bg-mineshaft-600", isSelected && "bg-mineshaft-600 hover:bg-mineshaft-600",
isDisabled && "cursor-not-allowed hover:bg-transparent", isDisabled && "cursor-not-allowed hover:bg-transparent",
isSelected && variant === "org" && "border-org-v1",
isSelected && variant === "namespace" && "border-namespace-v1",
isSelected && variant === "project" && "border-primary",
className className
)} )}
ref={inputRef} ref={inputRef}

View File

@@ -1,18 +1,37 @@
import { IconDefinition } from "@fortawesome/free-brands-svg-icons";
import { faCube, faCubes, faGlobe, faServer } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { ReactNode } from "@tanstack/react-router"; import { ReactNode } from "@tanstack/react-router";
import { twMerge } from "tailwind-merge"; import { twMerge } from "tailwind-merge";
import { Badge } from "@app/components/v2";
type Props = { type Props = {
title: ReactNode; title: ReactNode;
description?: ReactNode; description?: ReactNode;
children?: ReactNode; children?: ReactNode;
className?: string; className?: string;
scope: "org" | "project" | "namespace" | "instance";
}; };
export const PageHeader = ({ title, description, children, className }: Props) => ( const SCOPE_NAME: Record<NonNullable<Props["scope"]>, { label: string; icon: IconDefinition }> = {
org: { label: "Organization", icon: faGlobe },
project: { label: "Project", icon: faCube },
namespace: { label: "Namespace", icon: faCubes },
instance: { label: "Server", icon: faServer }
};
export const PageHeader = ({ title, description, children, className, scope }: Props) => (
<div className={twMerge("mb-4 w-full", className)}> <div className={twMerge("mb-4 w-full", className)}>
<div className="flex w-full justify-between"> <div className="flex w-full justify-between">
<div className="w-full"> <div className="mr-4 flex w-full items-center">
<h1 className="mr-4 text-3xl font-medium text-white capitalize">{title}</h1> <h1 className="text-3xl font-medium text-white capitalize">{title}</h1>
{scope && (
<Badge variant={scope} className="mt-1 ml-2.5">
<FontAwesomeIcon icon={SCOPE_NAME[scope].icon} />
{SCOPE_NAME[scope].label}
</Badge>
)}
</div> </div>
<div className="flex items-center gap-2">{children}</div> <div className="flex items-center gap-2">{children}</div>
</div> </div>

Some files were not shown because too many files have changed in this diff Show More