From be74f4d34c4bd2c4d02b493ff9b0a1e40da4018c Mon Sep 17 00:00:00 2001 From: Daniel Hougaard <62331820+DanielHougaard@users.noreply.github.com> Date: Tue, 16 Apr 2024 17:27:50 +0200 Subject: [PATCH 01/99] Fix: Add import & recursive support to raw fetching --- cli/packages/api/api.go | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/cli/packages/api/api.go b/cli/packages/api/api.go index d45a42db4..01f29a03a 100644 --- a/cli/packages/api/api.go +++ b/cli/packages/api/api.go @@ -512,16 +512,23 @@ func CallUniversalAuthRefreshAccessToken(httpClient *resty.Client, request Unive func CallGetRawSecretsV3(httpClient *resty.Client, request GetRawSecretsV3Request) (GetRawSecretsV3Response, error) { var getRawSecretsV3Response GetRawSecretsV3Response - response, err := httpClient. + req := httpClient. R(). SetResult(&getRawSecretsV3Response). SetHeader("User-Agent", USER_AGENT). SetBody(request). SetQueryParam("workspaceId", request.WorkspaceId). SetQueryParam("environment", request.Environment). - SetQueryParam("secretPath", request.SecretPath). - SetQueryParam("include_imports", "false"). - Get(fmt.Sprintf("%v/v3/secrets/raw", config.INFISICAL_URL)) + SetQueryParam("secretPath", request.SecretPath) + + if request.IncludeImport { + req.SetQueryParam("include_imports", "true") + } + if request.Recursive { + req.SetQueryParam("recursive", "true") + } + + response, err := req.Get(fmt.Sprintf("%v/v3/secrets/raw", config.INFISICAL_URL)) if err != nil { return GetRawSecretsV3Response{}, fmt.Errorf("CallGetRawSecretsV3: Unable to complete api request [err=%w]", err) From 7581b33b3bdb4bad5465f331a58fc7898c2e2cc6 Mon Sep 17 00:00:00 2001 From: Daniel Hougaard <62331820+DanielHougaard@users.noreply.github.com> Date: Tue, 16 Apr 2024 17:28:01 +0200 Subject: [PATCH 02/99] Fix: Add import support for raw fetching --- cli/packages/api/model.go | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/cli/packages/api/model.go b/cli/packages/api/model.go index 0a5bfee6d..56b9807f7 100644 --- a/cli/packages/api/model.go +++ b/cli/packages/api/model.go @@ -371,6 +371,22 @@ type ImportedSecretV3 struct { Secrets []EncryptedSecretV3 `json:"secrets"` } +type ImportedRawSecretV3 struct { + SecretPath string `json:"secretPath"` + Environment string `json:"environment"` + FolderId string `json:"folderId"` + Secrets []struct { + ID string `json:"id"` + Workspace string `json:"workspace"` + Environment string `json:"environment"` + Version int `json:"version"` + Type string `json:"type"` + SecretKey string `json:"secretKey"` + SecretValue string `json:"secretValue"` + SecretComment string `json:"secretComment"` + } `json:"secrets"` +} + type GetEncryptedSecretsV3Response struct { Secrets []EncryptedSecretV3 `json:"secrets"` ImportedSecrets []ImportedSecretV3 `json:"imports,omitempty"` @@ -542,6 +558,6 @@ type GetRawSecretsV3Response struct { SecretValue string `json:"secretValue"` SecretComment string `json:"secretComment"` } `json:"secrets"` - Imports []any `json:"imports"` + Imports []ImportedRawSecretV3 `json:"imports"` ETag string } From 6b473d2b361a7d4b99e0097f8cf5d85876973724 Mon Sep 17 00:00:00 2001 From: Daniel Hougaard <62331820+DanielHougaard@users.noreply.github.com> Date: Tue, 16 Apr 2024 17:28:13 +0200 Subject: [PATCH 03/99] Feat: Integration tests --- cli/packages/cmd/export.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/cli/packages/cmd/export.go b/cli/packages/cmd/export.go index 4e08e5fa8..26c7d0044 100644 --- a/cli/packages/cmd/export.go +++ b/cli/packages/cmd/export.go @@ -117,7 +117,10 @@ var exportCmd = &cobra.Command{ secrets = util.ExpandSecrets(secrets, authParams, "") } + secrets = util.FilterSecretsByTag(secrets, tagSlugs) + util.HandleSendTestSecrets(cmd, secrets) + output, err = formatEnvs(secrets, format) if err != nil { util.HandleError(err) From 7ab8db047112af9da935a894ad46f34ef8ca2edc Mon Sep 17 00:00:00 2001 From: Daniel Hougaard <62331820+DanielHougaard@users.noreply.github.com> Date: Tue, 16 Apr 2024 17:28:18 +0200 Subject: [PATCH 04/99] Feat: Integration tests --- cli/packages/cmd/root.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/cli/packages/cmd/root.go b/cli/packages/cmd/root.go index 06846260f..7fe172c07 100644 --- a/cli/packages/cmd/root.go +++ b/cli/packages/cmd/root.go @@ -87,3 +87,7 @@ func initLog() { zerolog.SetGlobalLevel(zerolog.InfoLevel) } } + +func NewRootCmd() *cobra.Command { + return rootCmd +} From 8bf09789d6626404529385841bcf0231c17a85c9 Mon Sep 17 00:00:00 2001 From: Daniel Hougaard <62331820+DanielHougaard@users.noreply.github.com> Date: Tue, 16 Apr 2024 17:29:05 +0200 Subject: [PATCH 05/99] Feat: Integration tests --- cli/packages/cmd/secrets.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/cli/packages/cmd/secrets.go b/cli/packages/cmd/secrets.go index 7ba6e5411..c3228587e 100644 --- a/cli/packages/cmd/secrets.go +++ b/cli/packages/cmd/secrets.go @@ -39,6 +39,7 @@ var secretsCmd = &cobra.Command{ } token, err := util.GetInfisicalToken(cmd) + if err != nil { util.HandleError(err, "Unable to parse flag") } @@ -116,6 +117,7 @@ var secretsCmd = &cobra.Command{ secrets = util.ExpandSecrets(secrets, authParams, "") } + util.HandleSendTestSecrets(cmd, secrets) visualize.PrintAllSecretDetails(secrets) Telemetry.CaptureEvent("cli-command:secrets", posthog.NewProperties().Set("secretCount", len(secrets)).Set("version", util.CLI_VERSION)) }, @@ -505,6 +507,8 @@ func getSecretsByNames(cmd *cobra.Command, args []string) { } } + util.HandleSendTestSecrets(cmd, requestedSecrets) + if showOnlyValue && len(requestedSecrets) > 1 { util.PrintErrorMessageAndExit("--raw-value only works with one secret.") } From 12d5fb1043ab7e7cb6a72bf18aec33e45e34f5c7 Mon Sep 17 00:00:00 2001 From: Daniel Hougaard <62331820+DanielHougaard@users.noreply.github.com> Date: Tue, 16 Apr 2024 17:29:18 +0200 Subject: [PATCH 06/99] Fix: Add support for imported secrets with raw fetching --- cli/packages/util/secrets.go | 42 ++++++++++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/cli/packages/util/secrets.go b/cli/packages/util/secrets.go index 59d80ea77..bedd77572 100644 --- a/cli/packages/util/secrets.go +++ b/cli/packages/util/secrets.go @@ -186,12 +186,12 @@ func GetPlainTextSecretsViaMachineIdentity(accessToken string, workspaceId strin plainTextSecrets = append(plainTextSecrets, models.SingleEnvironmentVariable{Key: secret.SecretKey, Value: secret.SecretValue, Type: secret.Type, WorkspaceId: secret.Workspace}) } - // if includeImports { - // plainTextSecrets, err = InjectImportedSecret(plainTextWorkspaceKey, plainTextSecrets, encryptedSecrets.ImportedSecrets) - // if err != nil { - // return nil, err - // } - // } + if includeImports { + plainTextSecrets, err = InjectRawImportedSecret(plainTextSecrets, rawSecrets.Imports) + if err != nil { + return models.PlaintextSecretResult{}, err + } + } return models.PlaintextSecretResult{ Secrets: plainTextSecrets, @@ -252,6 +252,36 @@ func InjectImportedSecret(plainTextWorkspaceKey []byte, secrets []models.SingleE return secrets, nil } +func InjectRawImportedSecret(secrets []models.SingleEnvironmentVariable, importedSecrets []api.ImportedRawSecretV3) ([]models.SingleEnvironmentVariable, error) { + if importedSecrets == nil { + return secrets, nil + } + + hasOverriden := make(map[string]bool) + for _, sec := range secrets { + hasOverriden[sec.Key] = true + } + + for i := len(importedSecrets) - 1; i >= 0; i-- { + importSec := importedSecrets[i] + plainTextImportedSecrets := importSec.Secrets + + for _, sec := range plainTextImportedSecrets { + if _, ok := hasOverriden[sec.SecretKey]; !ok { + secrets = append(secrets, models.SingleEnvironmentVariable{ + Key: sec.SecretKey, + WorkspaceId: sec.Workspace, + Value: sec.SecretValue, + Type: sec.Type, + ID: sec.ID, + }) + hasOverriden[sec.SecretKey] = true + } + } + } + return secrets, nil +} + func FilterSecretsByTag(plainTextSecrets []models.SingleEnvironmentVariable, tagSlugs string) []models.SingleEnvironmentVariable { if tagSlugs == "" { return plainTextSecrets From bcb3eaab74cd3363603bf0809ff28b24f3a7c1c1 Mon Sep 17 00:00:00 2001 From: Daniel Hougaard <62331820+DanielHougaard@users.noreply.github.com> Date: Tue, 16 Apr 2024 17:29:31 +0200 Subject: [PATCH 07/99] Feat: Integration tests --- cli/packages/util/tests.go | 26 +++++++++ cli/test/export_test.go | 82 ++++++++++++++++++++++++++++ cli/test/helper.go | 26 +++++++++ cli/test/root_test.go | 107 +++++++++++++++++++++++++++++++++++++ cli/test/secrets_test.go | 93 ++++++++++++++++++++++++++++++++ 5 files changed, 334 insertions(+) create mode 100644 cli/packages/util/tests.go create mode 100644 cli/test/export_test.go create mode 100644 cli/test/helper.go create mode 100644 cli/test/root_test.go create mode 100644 cli/test/secrets_test.go diff --git a/cli/packages/util/tests.go b/cli/packages/util/tests.go new file mode 100644 index 000000000..816df573e --- /dev/null +++ b/cli/packages/util/tests.go @@ -0,0 +1,26 @@ +package util + +import ( + "encoding/json" + "fmt" + "os" + + "github.com/Infisical/infisical-merge/packages/models" + "github.com/spf13/cobra" +) + +func HandleSendTestSecrets(cmd *cobra.Command, secrets []models.SingleEnvironmentVariable) { + isTestMode := os.Getenv("TEST_MODE") + + if isTestMode != "true" { + return + } + + jsonOut, err := json.Marshal(secrets) + if err != nil { + HandleError(err, "Unable to marshal secrets") + } + + fmt.Fprint(cmd.OutOrStdout(), string(jsonOut)) + +} diff --git a/cli/test/export_test.go b/cli/test/export_test.go new file mode 100644 index 000000000..8c4b49ef1 --- /dev/null +++ b/cli/test/export_test.go @@ -0,0 +1,82 @@ +package tests + +import ( + "bytes" + "encoding/json" + "fmt" + "testing" + + "github.com/Infisical/infisical-merge/packages/cmd" + "github.com/Infisical/infisical-merge/packages/models" + "github.com/stretchr/testify/assert" +) + +func ExportSecrets(t *testing.T, authToken string, projectId string, envSlug string) { + + rootCommand := cmd.NewRootCmd() + + commandOutput := new(bytes.Buffer) + rootCommand.SetOut(commandOutput) + rootCommand.SetErr(commandOutput) + + args := []string{ + "export", + } + + args = append(args, fmt.Sprintf("--token=%s", authToken)) + args = append(args, fmt.Sprintf("--projectId=%s", projectId)) + + rootCommand.SetArgs(args) + rootCommand.Execute() + + var secrets []models.SingleEnvironmentVariable + + json.Unmarshal(commandOutput.Bytes(), &secrets) + + expectedLength := len(ALL_SECRETS) - 1 // -1 because the default path is "/", and the secret in /folder will not be found. + + assert.Len(t, secrets, expectedLength) + + for _, secret := range secrets { + if secret.Key == "FOLDER-SECRET-1" { + continue + } + assert.Contains(t, ALL_SECRET_KEYS, secret.Key) + assert.Contains(t, ALL_SECRET_VALUES, secret.Value) + } + +} + +func ExportSecretsWithoutImports(t *testing.T, authToken string, projectId string, envSlug string) { + + rootCommand := cmd.NewRootCmd() + + commandOutput := new(bytes.Buffer) + rootCommand.SetOut(commandOutput) + rootCommand.SetErr(commandOutput) + + args := []string{ + "export", + } + + args = append(args, fmt.Sprintf("--token=%s", authToken)) + args = append(args, fmt.Sprintf("--projectId=%s", projectId)) + args = append(args, "--include-imports=false") + + rootCommand.SetArgs(args) + rootCommand.Execute() + + var secrets []models.SingleEnvironmentVariable + + json.Unmarshal(commandOutput.Bytes(), &secrets) + + assert.Len(t, secrets, len(DEV_SECRETS)) + + allDevSecretKeys, allDevSecretValues := getSecretKeysAndValues(DEV_SECRETS) + + for _, secret := range secrets { + assert.Contains(t, allDevSecretKeys, secret.Key) + assert.Contains(t, allDevSecretValues, secret.Value) + } + +} diff --git a/cli/test/helper.go b/cli/test/helper.go new file mode 100644 index 000000000..912a3a71d --- /dev/null +++ b/cli/test/helper.go @@ -0,0 +1,26 @@ +package tests + +type Secret struct { + Key string + Value string +} + +func Map[T, U any](ts []T, f func(T) U) []U { + us := make([]U, len(ts)) + for i := range ts { + us[i] = f(ts[i]) + } + return us +} + +func getSecretKeysAndValues(secrets []Secret) (keys []string, values []string) { + secretKeys := []string{} + secretValues := []string{} + + for _, secret := range secrets { + secretKeys = append(secretKeys, secret.Key) + secretValues = append(secretValues, secret.Value) + } + + return secretKeys, secretValues +} diff --git a/cli/test/root_test.go b/cli/test/root_test.go new file mode 100644 index 000000000..2fbb788fe --- /dev/null +++ b/cli/test/root_test.go @@ -0,0 +1,107 @@ +package tests + +import ( + "os" + "testing" + + "github.com/Infisical/infisical-merge/packages/util" +) + +var DEV_SECRETS = []Secret{ + { + Key: "TEST-SECRET-1", + Value: "test-value-1", + }, + { + Key: "TEST-SECRET-2", + Value: "test-value-2", + }, + { + Key: "TEST-SECRET-3", + Value: "test-value-3", + }, +} + +var DEV_FOLDER_SECRETS = []Secret{ + { + Key: "FOLDER-SECRET-1", + Value: "folder-value-1", + }, +} + +var STAGING_SECRETS = []Secret{ + { + Key: "STAGING-SECRET-1", + Value: "staging-value-1", + }, + { + Key: "STAGING-SECRET-2", + Value: "staging-value-2", + }, +} + +// Initialize the combined secrets array +var ALL_SECRETS = []Secret{} +var ALL_SECRET_KEYS = []string{} +var ALL_SECRET_VALUES = []string{} + +type Credentials struct { + ClientID string + ClientSecret string + ServiceToken string + ProjectID string + EnvSlug string +} + +var creds = Credentials{ + ClientID: os.Getenv("CLI_TESTS_UA_CLIENT_ID"), + ClientSecret: os.Getenv("CLI_TESTS_UA_CLIENT_SECRET"), + ServiceToken: os.Getenv("CLI_TESTS_SERVICE_TOKEN"), + ProjectID: os.Getenv("CLI_TESTS_PROJECT_ID"), + EnvSlug: os.Getenv("CLI_TESTS_ENV_SLUG"), +} + +func initialize() { + if creds.ClientID == "" || creds.ClientSecret == "" || creds.ServiceToken == "" || creds.ProjectID == "" || creds.EnvSlug == "" { + panic("Missing required environment variables") + } + + ALL_SECRETS = append(ALL_SECRETS, DEV_SECRETS...) + ALL_SECRETS = append(ALL_SECRETS, DEV_FOLDER_SECRETS...) + ALL_SECRETS = append(ALL_SECRETS, STAGING_SECRETS...) + + for _, secret := range ALL_SECRETS { + ALL_SECRET_KEYS = append(ALL_SECRET_KEYS, secret.Key) + ALL_SECRET_VALUES = append(ALL_SECRET_VALUES, secret.Value) + } +} + +func Test_RunTests(t *testing.T) { + initialize() + + res, err := util.UniversalAuthLogin(creds.ClientID, creds.ClientSecret) + if err != nil { + t.Errorf("Error: %v", err) + } + universalAuthAccessToken := res.AccessToken + + t.Run("Export secrets", func(t *testing.T) { + ExportSecrets(t, universalAuthAccessToken, creds.ProjectID, creds.EnvSlug) + ExportSecrets(t, creds.ServiceToken, creds.ProjectID, creds.EnvSlug) + }) + + t.Run("Export secrets (without imports)", func(t *testing.T) { + ExportSecretsWithoutImports(t, universalAuthAccessToken, creds.ProjectID, creds.EnvSlug) + ExportSecretsWithoutImports(t, creds.ServiceToken, creds.ProjectID, creds.EnvSlug) + }) + + t.Run("List Secrets (with imports and recursive)", func(t *testing.T) { + ListSecretsWithImportsAndRecursive(t, universalAuthAccessToken, creds.ProjectID, creds.EnvSlug) + ListSecretsWithImportsAndRecursive(t, creds.ServiceToken, creds.ProjectID, creds.EnvSlug) + }) + + t.Run("Get Secrets by Names", func(t *testing.T) { + GetSecretsByNames(t, universalAuthAccessToken, creds.ProjectID, creds.EnvSlug) + GetSecretsByNames(t, creds.ServiceToken, creds.ProjectID, creds.EnvSlug) + }) +} diff --git a/cli/test/secrets_test.go b/cli/test/secrets_test.go new file mode 100644 index 000000000..b346a3e69 --- /dev/null +++ b/cli/test/secrets_test.go @@ -0,0 +1,93 @@ +package tests + +import ( + "bytes" + "encoding/json" + "fmt" + "testing" + + "github.com/Infisical/infisical-merge/packages/cmd" + "github.com/Infisical/infisical-merge/packages/models" + "github.com/stretchr/testify/assert" +) + +func ListSecretsWithImportsAndRecursive(t *testing.T, authToken string, projectId string, envSlug string) { + + rootCommand := cmd.NewRootCmd() + + commandOutput := new(bytes.Buffer) + rootCommand.SetOut(commandOutput) + rootCommand.SetErr(commandOutput) + + args := []string{ + "secrets", + } + args = append(args, fmt.Sprintf("--token=%s", authToken)) + args = append(args, fmt.Sprintf("--projectId=%s", projectId)) + args = append(args, fmt.Sprintf("--env=%s", envSlug)) + args = append(args, "--include-imports=true") + args = append(args, "--recursive=true") + + rootCommand.SetArgs(args) + rootCommand.Execute() + + var secrets []models.SingleEnvironmentVariable + + json.Unmarshal(commandOutput.Bytes(), &secrets) + + if len(secrets) == 0 { + t.Errorf("No secrets found") + } + + secretKeys := []string{} + secretValues := []string{} + + for _, secret := range secrets { + secretKeys = append(secretKeys, secret.Key) + secretValues = append(secretValues, secret.Value) + } + + // Secrets can have different order and potentially more secrets. but the secrets should at least contain the above secrets. + for _, key := range ALL_SECRET_KEYS { + assert.Contains(t, secretKeys, key) + } + for _, value := range ALL_SECRET_VALUES { + assert.Contains(t, secretValues, value) + } +} + +func GetSecretsByNames(t *testing.T, authToken string, projectId string, envSlug string) { + + rootCommand := cmd.NewRootCmd() + + commandOutput := new(bytes.Buffer) + rootCommand.SetOut(commandOutput) + rootCommand.SetErr(commandOutput) + + args := []string{ + "secrets", + "get", + } + + args = append(args, ALL_SECRET_KEYS...) + args = append(args, fmt.Sprintf("--token=%s", authToken)) + args = append(args, fmt.Sprintf("--projectId=%s", projectId)) + args = append(args, fmt.Sprintf("--env=%s", envSlug)) + + rootCommand.SetArgs(args) + rootCommand.Execute() + + var secrets []models.SingleEnvironmentVariable + + json.Unmarshal(commandOutput.Bytes(), &secrets) + + assert.Len(t, secrets, len(ALL_SECRETS)) + + for _, secret := range secrets { + assert.Contains(t, ALL_SECRET_KEYS, secret.Key) + + if secret.Key == "FOLDER-SECRET-1" { + assert.Equal(t, secret.Value, "*not found*") // Should not be found because recursive isn't enabled in this test, and the default path is "/" + } + } +} From cb6cbafcaedc4da9ddcd7384908ab42bf5d11286 Mon Sep 17 00:00:00 2001 From: Daniel Hougaard <62331820+DanielHougaard@users.noreply.github.com> Date: Wed, 17 Apr 2024 15:17:08 +0200 Subject: [PATCH 08/99] Fix: JSON error check --- cli/test/export_test.go | 10 ++++++++-- cli/test/secrets_test.go | 10 ++++++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/cli/test/export_test.go b/cli/test/export_test.go index 8c4b49ef1..dd156fc39 100644 --- a/cli/test/export_test.go +++ b/cli/test/export_test.go @@ -31,7 +31,10 @@ func ExportSecrets(t *testing.T, authToken string, projectId string, envSlug str var secrets []models.SingleEnvironmentVariable - json.Unmarshal(commandOutput.Bytes(), &secrets) + err := json.Unmarshal(commandOutput.Bytes(), &secrets) + if err != nil { + t.Errorf("Error: %v", err) + } expectedLength := len(ALL_SECRETS) - 1 // -1 because the default path is "/", and the secret in /folder will not be found. @@ -68,7 +71,10 @@ func ExportSecretsWithoutImports(t *testing.T, authToken string, projectId strin var secrets []models.SingleEnvironmentVariable - json.Unmarshal(commandOutput.Bytes(), &secrets) + err := json.Unmarshal(commandOutput.Bytes(), &secrets) + if err != nil { + t.Errorf("Error: %v", err) + } assert.Len(t, secrets, len(DEV_SECRETS)) diff --git a/cli/test/secrets_test.go b/cli/test/secrets_test.go index b346a3e69..39bfd1c07 100644 --- a/cli/test/secrets_test.go +++ b/cli/test/secrets_test.go @@ -33,7 +33,10 @@ func ListSecretsWithImportsAndRecursive(t *testing.T, authToken string, projectI var secrets []models.SingleEnvironmentVariable - json.Unmarshal(commandOutput.Bytes(), &secrets) + err := json.Unmarshal(commandOutput.Bytes(), &secrets) + if err != nil { + t.Errorf("Error: %v", err) + } if len(secrets) == 0 { t.Errorf("No secrets found") @@ -79,7 +82,10 @@ func GetSecretsByNames(t *testing.T, authToken string, projectId string, envSlug var secrets []models.SingleEnvironmentVariable - json.Unmarshal(commandOutput.Bytes(), &secrets) + err := json.Unmarshal(commandOutput.Bytes(), &secrets) + if err != nil { + t.Errorf("Error: %v", err) + } assert.Len(t, secrets, len(ALL_SECRETS)) From d31d98b5e083d449b7f62f11ee8781e862c0ad0b Mon Sep 17 00:00:00 2001 From: Daniel Hougaard <62331820+DanielHougaard@users.noreply.github.com> Date: Thu, 18 Apr 2024 14:58:59 +0200 Subject: [PATCH 09/99] Feat: CLI Integration tests --- cli/packages/cmd/login.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/cli/packages/cmd/login.go b/cli/packages/cmd/login.go index bbb2c3a05..a6401e3d0 100644 --- a/cli/packages/cmd/login.go +++ b/cli/packages/cmd/login.go @@ -191,6 +191,10 @@ var loginCmd = &cobra.Command{ util.HandleError(err) } + if util.IS_TEST_MODE { + util.HandleSendUniversalAuthToken(cmd, res.AccessToken) + return + } if plainOutput { fmt.Println(res.AccessToken) return From b79ce8a8807ec6471c2950d2dd6b661999ea63c1 Mon Sep 17 00:00:00 2001 From: Daniel Hougaard <62331820+DanielHougaard@users.noreply.github.com> Date: Thu, 18 Apr 2024 14:59:13 +0200 Subject: [PATCH 10/99] Feat: Cli integration tests -- login --- cli/test/login_test.go | 43 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 cli/test/login_test.go diff --git a/cli/test/login_test.go b/cli/test/login_test.go new file mode 100644 index 000000000..1d598153a --- /dev/null +++ b/cli/test/login_test.go @@ -0,0 +1,43 @@ +package tests + +import ( + "bytes" + "fmt" + "regexp" + "testing" + + "github.com/Infisical/infisical-merge/packages/cmd" + "github.com/stretchr/testify/assert" +) + +func UALoginCmd(t *testing.T) { + jwtPattern := `^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$` + + rootCommand := cmd.NewRootCmd() + + commandOutput := new(bytes.Buffer) + errorOutput := new(bytes.Buffer) + rootCommand.SetOut(commandOutput) + rootCommand.SetErr(errorOutput) + + args := []string{ + "login", + } + + args = append(args, fmt.Sprintf("--method=%s", "universal-auth")) + args = append(args, fmt.Sprintf("--client-id=%s", creds.ClientID)) + args = append(args, fmt.Sprintf("--client-secret=%s", creds.ClientSecret)) + + rootCommand.SetArgs(args) + rootCommand.Execute() + + token := commandOutput.String() + + // We do a match and compare it against true, instead of using assert.Regexp. + // If the assertion fails, we would be able to see the potential token that was generated in the output console, which would be bad if running in a CI/CD pipeline. + match, err := regexp.MatchString(jwtPattern, token) + assert.Nil(t, err) + assert.True(t, match, "The token does not match the pattern") + + creds.UAAccessToken = token +} From 46a91515b1199837159dd557c02f3883c5ded9f1 Mon Sep 17 00:00:00 2001 From: Daniel Hougaard <62331820+DanielHougaard@users.noreply.github.com> Date: Thu, 18 Apr 2024 14:59:21 +0200 Subject: [PATCH 11/99] Fix: Use login UA token --- cli/test/root_test.go | 50 +++++++++++++++++++++++++------------------ 1 file changed, 29 insertions(+), 21 deletions(-) diff --git a/cli/test/root_test.go b/cli/test/root_test.go index 2fbb788fe..e5e9d7684 100644 --- a/cli/test/root_test.go +++ b/cli/test/root_test.go @@ -3,8 +3,6 @@ package tests import ( "os" "testing" - - "github.com/Infisical/infisical-merge/packages/util" ) var DEV_SECRETS = []Secret{ @@ -46,19 +44,21 @@ var ALL_SECRET_KEYS = []string{} var ALL_SECRET_VALUES = []string{} type Credentials struct { - ClientID string - ClientSecret string - ServiceToken string - ProjectID string - EnvSlug string + ClientID string + ClientSecret string + UAAccessToken string + ServiceToken string + ProjectID string + EnvSlug string } var creds = Credentials{ - ClientID: os.Getenv("CLI_TESTS_UA_CLIENT_ID"), - ClientSecret: os.Getenv("CLI_TESTS_UA_CLIENT_SECRET"), - ServiceToken: os.Getenv("CLI_TESTS_SERVICE_TOKEN"), - ProjectID: os.Getenv("CLI_TESTS_PROJECT_ID"), - EnvSlug: os.Getenv("CLI_TESTS_ENV_SLUG"), + UAAccessToken: "", + ClientID: os.Getenv("CLI_TESTS_UA_CLIENT_ID"), + ClientSecret: os.Getenv("CLI_TESTS_UA_CLIENT_SECRET"), + ServiceToken: os.Getenv("CLI_TESTS_SERVICE_TOKEN"), + ProjectID: os.Getenv("CLI_TESTS_PROJECT_ID"), + EnvSlug: os.Getenv("CLI_TESTS_ENV_SLUG"), } func initialize() { @@ -79,29 +79,37 @@ func initialize() { func Test_RunTests(t *testing.T) { initialize() - res, err := util.UniversalAuthLogin(creds.ClientID, creds.ClientSecret) - if err != nil { - t.Errorf("Error: %v", err) - } - universalAuthAccessToken := res.AccessToken + t.Run("User login command", func(t *testing.T) { + UALoginCmd(t) + }) + + t.Run("Run command", func(t *testing.T) { + RunCmd(t, creds.UAAccessToken, creds.ProjectID, creds.EnvSlug) + RunCmd(t, creds.ServiceToken, creds.ProjectID, creds.EnvSlug) + }) + + t.Run("Run Command (without imports, with recursive)", func(t *testing.T) { + RunCmdWithoutImportsAndWithRecursive(t, creds.UAAccessToken, creds.ProjectID, creds.EnvSlug) + RunCmdWithoutImportsAndWithRecursive(t, creds.ServiceToken, creds.ProjectID, creds.EnvSlug) + }) t.Run("Export secrets", func(t *testing.T) { - ExportSecrets(t, universalAuthAccessToken, creds.ProjectID, creds.EnvSlug) + ExportSecrets(t, creds.UAAccessToken, creds.ProjectID, creds.EnvSlug) ExportSecrets(t, creds.ServiceToken, creds.ProjectID, creds.EnvSlug) }) t.Run("Export secrets (without imports)", func(t *testing.T) { - ExportSecretsWithoutImports(t, universalAuthAccessToken, creds.ProjectID, creds.EnvSlug) + ExportSecretsWithoutImports(t, creds.UAAccessToken, creds.ProjectID, creds.EnvSlug) ExportSecretsWithoutImports(t, creds.ServiceToken, creds.ProjectID, creds.EnvSlug) }) t.Run("List Secrets (with imports and recursive)", func(t *testing.T) { - ListSecretsWithImportsAndRecursive(t, universalAuthAccessToken, creds.ProjectID, creds.EnvSlug) + ListSecretsWithImportsAndRecursive(t, creds.UAAccessToken, creds.ProjectID, creds.EnvSlug) ListSecretsWithImportsAndRecursive(t, creds.ServiceToken, creds.ProjectID, creds.EnvSlug) }) t.Run("Get Secrets by Names", func(t *testing.T) { - GetSecretsByNames(t, universalAuthAccessToken, creds.ProjectID, creds.EnvSlug) + GetSecretsByNames(t, creds.UAAccessToken, creds.ProjectID, creds.EnvSlug) GetSecretsByNames(t, creds.ServiceToken, creds.ProjectID, creds.EnvSlug) }) } From ad6d18a9056331802783904434b63438481235bc Mon Sep 17 00:00:00 2001 From: Daniel Hougaard <62331820+DanielHougaard@users.noreply.github.com> Date: Thu, 18 Apr 2024 14:59:26 +0200 Subject: [PATCH 12/99] Feat: Cli integration tests -- run cmd --- cli/test/run_test.go | 137 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100644 cli/test/run_test.go diff --git a/cli/test/run_test.go b/cli/test/run_test.go new file mode 100644 index 000000000..8ea26e38d --- /dev/null +++ b/cli/test/run_test.go @@ -0,0 +1,137 @@ +package tests + +import ( + "bytes" + "fmt" + "slices" + "strings" + "testing" + + "github.com/Infisical/infisical-merge/packages/cmd" + "github.com/stretchr/testify/assert" +) + +func RunCmd(t *testing.T, authToken string, projectId string, envSlug string) { + + rootCommand := cmd.NewRootCmd() + + commandOutput := new(bytes.Buffer) + errorOutput := new(bytes.Buffer) + rootCommand.SetOut(commandOutput) + rootCommand.SetErr(errorOutput) + + args := []string{ + "run", + } + + args = append(args, fmt.Sprintf("--token=%s", authToken)) + args = append(args, fmt.Sprintf("--projectId=%s", projectId)) + args = append(args, fmt.Sprintf("--env=%s", envSlug)) + args = append(args, "--", "echo", "TEST_COMMAND_BEING_EXECUTED") + + rootCommand.SetArgs(args) + rootCommand.Execute() + + var secrets []Secret + + stringSecrets := commandOutput.String() + arraySecrets := strings.Split(stringSecrets, "\n") + + for idx, secret := range arraySecrets { + if idx == len(arraySecrets)-1 && secret == "" { + continue + } + + secretParts := strings.Split(secret, "=") + + if len(secretParts) != 2 { + t.Errorf("Error: secret at index %d is not formatted correctly", idx) + } + + newSecret := Secret{ + Key: secretParts[0], + Value: secretParts[1], + } + + // make sure the new secret key is at least one of the expected keys + if !slices.Contains(ALL_SECRET_KEYS, newSecret.Key) { + continue + } + + secrets = append(secrets, newSecret) + } + + expectedLength := len(DEV_SECRETS) + len(STAGING_SECRETS) + + assert.Len(t, secrets, expectedLength) + + for _, secret := range secrets { + assert.Contains(t, ALL_SECRET_KEYS, secret.Key) + assert.Contains(t, ALL_SECRET_VALUES, secret.Value) + } +} + +func RunCmdWithoutImportsAndWithRecursive(t *testing.T, authToken string, projectId string, envSlug string) { + + rootCommand := cmd.NewRootCmd() + + commandOutput := new(bytes.Buffer) + errorOutput := new(bytes.Buffer) + rootCommand.SetOut(commandOutput) + rootCommand.SetErr(errorOutput) + + args := []string{ + "run", + } + + args = append(args, fmt.Sprintf("--token=%s", authToken)) + args = append(args, fmt.Sprintf("--projectId=%s", projectId)) + args = append(args, fmt.Sprintf("--env=%s", envSlug)) + args = append(args, "--include-imports=false") + args = append(args, "--recursive") + args = append(args, "--", "echo", "TEST_COMMAND_BEING_EXECUTED_RECURSIVE") + + rootCommand.SetArgs(args) + rootCommand.Execute() + + var secrets []Secret + + stringSecrets := commandOutput.String() + arraySecrets := strings.Split(stringSecrets, "\n") + + for idx, secret := range arraySecrets { + if idx == len(arraySecrets)-1 && secret == "" { + continue + } + + secretParts := strings.Split(secret, "=") + + if len(secretParts) != 2 { + t.Errorf("Error: secret at index %d is not formatted correctly", idx) + } + + newSecret := Secret{ + Key: secretParts[0], + Value: secretParts[1], + } + + // make sure the new secret key is at least one of the expected keys + if !slices.Contains(ALL_SECRET_KEYS, newSecret.Key) { + continue + } + + secrets = append(secrets, newSecret) + } + + nestedDevSecrets := append(DEV_FOLDER_SECRETS, DEV_SECRETS...) + nestedDevSecretsKeys := Map(nestedDevSecrets, func(secret Secret) string { return secret.Key }) + nestedDevSecretsValues := Map(nestedDevSecrets, func(secret Secret) string { return secret.Value }) + + expectedLength := len(nestedDevSecrets) + assert.Len(t, secrets, expectedLength) + + for _, secret := range secrets { + assert.Contains(t, nestedDevSecretsKeys, secret.Key) + assert.Contains(t, nestedDevSecretsValues, secret.Value) + } +} From b598dd3d477ff1d95f8f9eaa079c5a18cbeecb0a Mon Sep 17 00:00:00 2001 From: Daniel Hougaard <62331820+DanielHougaard@users.noreply.github.com> Date: Thu, 18 Apr 2024 14:59:41 +0200 Subject: [PATCH 13/99] Feat: Cli integration tests -- exports --- cli/test/export_test.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/cli/test/export_test.go b/cli/test/export_test.go index dd156fc39..a0f68fa7a 100644 --- a/cli/test/export_test.go +++ b/cli/test/export_test.go @@ -16,8 +16,9 @@ func ExportSecrets(t *testing.T, authToken string, projectId string, envSlug str rootCommand := cmd.NewRootCmd() commandOutput := new(bytes.Buffer) + errorOutput := new(bytes.Buffer) rootCommand.SetOut(commandOutput) - rootCommand.SetErr(commandOutput) + rootCommand.SetErr(errorOutput) args := []string{ "export", @@ -25,6 +26,7 @@ func ExportSecrets(t *testing.T, authToken string, projectId string, envSlug str args = append(args, fmt.Sprintf("--token=%s", authToken)) args = append(args, fmt.Sprintf("--projectId=%s", projectId)) + args = append(args, fmt.Sprintf("--env=%s", envSlug)) rootCommand.SetArgs(args) rootCommand.Execute() @@ -36,7 +38,7 @@ func ExportSecrets(t *testing.T, authToken string, projectId string, envSlug str t.Errorf("Error: %v", err) } - expectedLength := len(ALL_SECRETS) - 1 // -1 because the default path is "/", and the secret in /folder will not be found. + expectedLength := len(DEV_SECRETS) + len(STAGING_SECRETS) assert.Len(t, secrets, expectedLength) @@ -47,7 +49,6 @@ func ExportSecrets(t *testing.T, authToken string, projectId string, envSlug str assert.Contains(t, ALL_SECRET_KEYS, secret.Key) assert.Contains(t, ALL_SECRET_VALUES, secret.Value) } - } func ExportSecretsWithoutImports(t *testing.T, authToken string, projectId string, envSlug string) { @@ -64,6 +65,7 @@ func ExportSecretsWithoutImports(t *testing.T, authToken string, projectId strin args = append(args, fmt.Sprintf("--token=%s", authToken)) args = append(args, fmt.Sprintf("--projectId=%s", projectId)) + args = append(args, fmt.Sprintf("--env=%s", envSlug)) args = append(args, "--include-imports=false") rootCommand.SetArgs(args) From 943945f6d78bcc3ab48a78b6a330e73736e19c2b Mon Sep 17 00:00:00 2001 From: Daniel Hougaard <62331820+DanielHougaard@users.noreply.github.com> Date: Thu, 18 Apr 2024 15:01:28 +0200 Subject: [PATCH 14/99] Feat: Make run testable --- cli/packages/cmd/run.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/cli/packages/cmd/run.go b/cli/packages/cmd/run.go index 04fe2588b..dc123235a 100644 --- a/cli/packages/cmd/run.go +++ b/cli/packages/cmd/run.go @@ -174,6 +174,7 @@ var runCmd = &cobra.Command{ } log.Debug().Msgf("injecting the following environment variables into shell: %v", env) + util.HandleSendTestEnvVars(cmd, env) Telemetry.CaptureEvent("cli-command:run", posthog.NewProperties(). @@ -310,7 +311,10 @@ func execCmd(cmd *exec.Cmd) error { return fmt.Errorf("failed to wait for command termination: %v", err) } - waitStatus := cmd.ProcessState.Sys().(syscall.WaitStatus) - os.Exit(waitStatus.ExitStatus()) + if !util.IS_TEST_MODE { + waitStatus := cmd.ProcessState.Sys().(syscall.WaitStatus) + os.Exit(waitStatus.ExitStatus()) + } + return nil } From 22c589e2cf84cee9a99c7e0829e6a7e4445780ea Mon Sep 17 00:00:00 2001 From: Daniel Hougaard <62331820+DanielHougaard@users.noreply.github.com> Date: Thu, 18 Apr 2024 15:01:31 +0200 Subject: [PATCH 15/99] Update tests.go --- cli/packages/util/tests.go | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/cli/packages/util/tests.go b/cli/packages/util/tests.go index 816df573e..989376e58 100644 --- a/cli/packages/util/tests.go +++ b/cli/packages/util/tests.go @@ -9,10 +9,11 @@ import ( "github.com/spf13/cobra" ) -func HandleSendTestSecrets(cmd *cobra.Command, secrets []models.SingleEnvironmentVariable) { - isTestMode := os.Getenv("TEST_MODE") +var IS_TEST_MODE = os.Getenv("TEST_MODE") == "true" - if isTestMode != "true" { +func HandleSendTestSecrets(cmd *cobra.Command, secrets []models.SingleEnvironmentVariable) { + + if !IS_TEST_MODE { return } @@ -22,5 +23,28 @@ func HandleSendTestSecrets(cmd *cobra.Command, secrets []models.SingleEnvironmen } fmt.Fprint(cmd.OutOrStdout(), string(jsonOut)) +} +func HandleSendTestEnvVars(cmd *cobra.Command, envs []string) { + + if !IS_TEST_MODE { + return + } + + stringEnvVars := "" + + for _, env := range envs { + stringEnvVars += env + "\n" + } + + fmt.Fprint(cmd.OutOrStdout(), string(stringEnvVars)) +} + +func HandleSendUniversalAuthToken(cmd *cobra.Command, token string) { + + if !IS_TEST_MODE { + return + } + + fmt.Fprint(cmd.OutOrStdout(), token) } From ba42aca069b9d5a4192a2371ea9d6958b6cc8a94 Mon Sep 17 00:00:00 2001 From: Daniel Hougaard <62331820+DanielHougaard@users.noreply.github.com> Date: Thu, 18 Apr 2024 15:13:58 +0200 Subject: [PATCH 16/99] Workflow --- .github/workflows/run-cli-tests.yml | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 .github/workflows/run-cli-tests.yml diff --git a/.github/workflows/run-cli-tests.yml b/.github/workflows/run-cli-tests.yml new file mode 100644 index 000000000..aa3edaff6 --- /dev/null +++ b/.github/workflows/run-cli-tests.yml @@ -0,0 +1,22 @@ +name: Go CLI Tests +on: [push] # Test + +jobs: + test: + defaults: + run: + working-directory: ./cli + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - name: Setup Go + uses: actions/setup-go@v4 + with: + go-version: "1.21.x" + - name: Install dependencies + run: go get . + - name: Build + run: go build -v ./... + - name: Test with the Go CLI + run: TEST_MODE=true go test -v -count=1 ./test From 3f68807179e14c483f6f3fd0c8d79242bfdc5477 Mon Sep 17 00:00:00 2001 From: Daniel Hougaard <62331820+DanielHougaard@users.noreply.github.com> Date: Thu, 18 Apr 2024 17:07:37 +0200 Subject: [PATCH 17/99] Update run-cli-tests.yml --- .github/workflows/run-cli-tests.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/workflows/run-cli-tests.yml b/.github/workflows/run-cli-tests.yml index aa3edaff6..1076228cc 100644 --- a/.github/workflows/run-cli-tests.yml +++ b/.github/workflows/run-cli-tests.yml @@ -19,4 +19,11 @@ jobs: - name: Build run: go build -v ./... - name: Test with the Go CLI + env: + CLI_TESTS_UA_CLIENT_ID: ${{ secrets.CLI_TESTS_UA_CLIENT_ID }} + CLI_TESTS_UA_CLIENT_SECRET: ${{ secrets.CLI_TESTS_UA_CLIENT_SECRET }} + CLI_TESTS_SERVICE_TOKEN: ${{ secrets.CLI_TESTS_SERVICE_TOKEN }} + CLI_TESTS_PROJECT_ID: ${{ secrets.CLI_TESTS_PROJECT_ID }} + CLI_TESTS_ENV_SLUG: ${{ secrets.CLI_TESTS_ENV_SLUG }} + run: TEST_MODE=true go test -v -count=1 ./test From e453ddf937b3930f83e8f4e2b43bb04778f5b457 Mon Sep 17 00:00:00 2001 From: Daniel Hougaard <62331820+DanielHougaard@users.noreply.github.com> Date: Thu, 18 Apr 2024 18:04:29 +0200 Subject: [PATCH 18/99] Update secrets.go --- cli/packages/cmd/secrets.go | 1 - 1 file changed, 1 deletion(-) diff --git a/cli/packages/cmd/secrets.go b/cli/packages/cmd/secrets.go index c3228587e..95ac6c5bb 100644 --- a/cli/packages/cmd/secrets.go +++ b/cli/packages/cmd/secrets.go @@ -39,7 +39,6 @@ var secretsCmd = &cobra.Command{ } token, err := util.GetInfisicalToken(cmd) - if err != nil { util.HandleError(err, "Unable to parse flag") } From fa7587900e56a4dcb5a03c52a2d6daa59866e30f Mon Sep 17 00:00:00 2001 From: Tuan Dang Date: Thu, 18 Apr 2024 10:57:25 -0700 Subject: [PATCH 19/99] Finish preliminary capability for adding incomplete users to groups --- backend/src/@types/knex.d.ts | 8 + .../20240417032913_pending-group-addition.ts | 25 + backend/src/db/schemas/index.ts | 1 + backend/src/db/schemas/models.ts | 1 + .../src/db/schemas/pending-group-additions.ts | 20 + backend/src/ee/routes/v1/scim-router.ts | 43 +- backend/src/ee/services/group/group-dal.ts | 62 +- backend/src/ee/services/group/group-fns.ts | 701 ++++++++++++++++++ .../src/ee/services/group/group-service.ts | 202 ++--- backend/src/ee/services/group/group-types.ts | 91 +++ .../group/pending-group-addition-dal.ts | 55 ++ .../group/user-group-membership-dal.ts | 40 +- .../src/ee/services/license/licence-fns.ts | 6 +- .../src/ee/services/license/license-types.ts | 6 +- backend/src/ee/services/scim/scim-service.ts | 248 ++++++- backend/src/ee/services/scim/scim-types.ts | 9 + backend/src/server/routes/index.ts | 14 + .../src/services/auth/auth-signup-service.ts | 57 ++ backend/src/services/project/project-dal.ts | 4 +- backend/src/services/user/user-dal.ts | 14 + .../OrgGroupsSection/OrgGroupMembersModal.tsx | 294 ++++---- 21 files changed, 1510 insertions(+), 391 deletions(-) create mode 100644 backend/src/db/migrations/20240417032913_pending-group-addition.ts create mode 100644 backend/src/db/schemas/pending-group-additions.ts create mode 100644 backend/src/ee/services/group/group-fns.ts create mode 100644 backend/src/ee/services/group/pending-group-addition-dal.ts diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts index 2c8b8be5a..93c8cb1eb 100644 --- a/backend/src/@types/knex.d.ts +++ b/backend/src/@types/knex.d.ts @@ -86,6 +86,9 @@ import { TOrgRoles, TOrgRolesInsert, TOrgRolesUpdate, + TPendingGroupAdditions, + TPendingGroupAdditionsInsert, + TPendingGroupAdditionsUpdate, TProjectBots, TProjectBotsInsert, TProjectBotsUpdate, @@ -212,6 +215,11 @@ declare module "knex/types/tables" { interface Tables { [TableName.Users]: Knex.CompositeTableType; [TableName.Groups]: Knex.CompositeTableType; + [TableName.PendingGroupAddition]: Knex.CompositeTableType< + TPendingGroupAdditions, + TPendingGroupAdditionsInsert, + TPendingGroupAdditionsUpdate + >; [TableName.UserGroupMembership]: Knex.CompositeTableType< TUserGroupMembership, TUserGroupMembershipInsert, diff --git a/backend/src/db/migrations/20240417032913_pending-group-addition.ts b/backend/src/db/migrations/20240417032913_pending-group-addition.ts new file mode 100644 index 000000000..e720abd2f --- /dev/null +++ b/backend/src/db/migrations/20240417032913_pending-group-addition.ts @@ -0,0 +1,25 @@ +import { Knex } from "knex"; + +import { TableName } from "../schemas"; +import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils"; + +export async function up(knex: Knex): Promise { + if (!(await knex.schema.hasTable(TableName.PendingGroupAddition))) { + await knex.schema.createTable(TableName.PendingGroupAddition, (t) => { + t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid()); + t.uuid("userId").notNullable(); + t.foreign("userId").references("id").inTable(TableName.Users).onDelete("CASCADE"); + t.uuid("groupId").notNullable(); + t.foreign("groupId").references("id").inTable(TableName.Groups).onDelete("CASCADE"); + t.unique(["userId", "groupId"]); + t.timestamps(true, true, true); + }); + } + + await createOnUpdateTrigger(knex, TableName.PendingGroupAddition); +} + +export async function down(knex: Knex): Promise { + await knex.schema.dropTableIfExists(TableName.PendingGroupAddition); + await dropOnUpdateTrigger(knex, TableName.PendingGroupAddition); +} diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts index b9dab06ba..9a7772d5d 100644 --- a/backend/src/db/schemas/index.ts +++ b/backend/src/db/schemas/index.ts @@ -27,6 +27,7 @@ export * from "./org-bots"; export * from "./org-memberships"; export * from "./org-roles"; export * from "./organizations"; +export * from "./pending-group-additions"; export * from "./project-bots"; export * from "./project-environments"; export * from "./project-keys"; diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts index d5cf1b886..ea1925eb2 100644 --- a/backend/src/db/schemas/models.ts +++ b/backend/src/db/schemas/models.ts @@ -3,6 +3,7 @@ import { z } from "zod"; export enum TableName { Users = "users", Groups = "groups", + PendingGroupAddition = "pending_group_additions", GroupProjectMembership = "group_project_memberships", GroupProjectMembershipRole = "group_project_membership_roles", UserGroupMembership = "user_group_membership", diff --git a/backend/src/db/schemas/pending-group-additions.ts b/backend/src/db/schemas/pending-group-additions.ts new file mode 100644 index 000000000..b665f8841 --- /dev/null +++ b/backend/src/db/schemas/pending-group-additions.ts @@ -0,0 +1,20 @@ +// Code generated by automation script, DO NOT EDIT. +// Automated by pulling database and generating zod schema +// To update. Just run npm run generate:schema +// Written by akhilmhdh. + +import { z } from "zod"; + +import { TImmutableDBKeys } from "./models"; + +export const PendingGroupAdditionsSchema = z.object({ + id: z.string().uuid(), + userId: z.string().uuid(), + groupId: z.string().uuid(), + createdAt: z.date(), + updatedAt: z.date() +}); + +export type TPendingGroupAdditions = z.infer; +export type TPendingGroupAdditionsInsert = Omit, TImmutableDBKeys>; +export type TPendingGroupAdditionsUpdate = Partial, TImmutableDBKeys>>; diff --git a/backend/src/ee/routes/v1/scim-router.ts b/backend/src/ee/routes/v1/scim-router.ts index 80ece7e85..67209e774 100644 --- a/backend/src/ee/routes/v1/scim-router.ts +++ b/backend/src/ee/routes/v1/scim-router.ts @@ -192,6 +192,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { }, onRequest: verifyAuth([AuthMode.SCIM_TOKEN]), handler: async (req) => { + console.log(`GET /Users/${req.params.userId}`); const user = await req.server.services.scim.getScimUser({ userId: req.params.userId, orgId: req.permission.orgId @@ -246,6 +247,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { }, onRequest: verifyAuth([AuthMode.SCIM_TOKEN]), handler: async (req) => { + console.log(`POST /Users req.body: `, req.body); const primaryEmail = req.body.emails?.find((email) => email.primary)?.value; const user = await req.server.services.scim.createScimUser({ @@ -273,6 +275,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { }, onRequest: verifyAuth([AuthMode.SCIM_TOKEN]), handler: async (req) => { + console.log(`DELETE /Users/${req.params.userId}`); const user = await req.server.services.scim.deleteScimUser({ userId: req.params.userId, orgId: req.permission.orgId @@ -289,14 +292,28 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { body: z.object({ schemas: z.array(z.string()), displayName: z.string().trim(), - members: z.array(z.any()).length(0).optional() // okta-specific + members: z + .array( + z.object({ + value: z.string(), + display: z.string() + }) + ) + .optional() // okta-specific }), response: { 200: z.object({ schemas: z.array(z.string()), id: z.string().trim(), displayName: z.string().trim(), - members: z.array(z.any()).length(0), + members: z + .array( + z.object({ + value: z.string(), + display: z.string() + }) + ) + .optional(), meta: z.object({ resourceType: z.string().trim() }) @@ -305,9 +322,10 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { }, onRequest: verifyAuth([AuthMode.SCIM_TOKEN]), handler: async (req) => { + console.log(`POST /Groups req.body: `, req.body); const group = await req.server.services.scim.createScimGroup({ - displayName: req.body.displayName, - orgId: req.permission.orgId + orgId: req.permission.orgId, + ...req.body }); return group; @@ -345,6 +363,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { }, onRequest: verifyAuth([AuthMode.SCIM_TOKEN]), handler: async (req) => { + console.log(`GET /Groups req.query: `, req.query); const groups = await req.server.services.scim.listScimGroups({ orgId: req.permission.orgId, offset: req.query.startIndex, @@ -381,6 +400,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { }, onRequest: verifyAuth([AuthMode.SCIM_TOKEN]), handler: async (req) => { + console.log(`GET /Groups/${req.params.groupId}`); const group = await req.server.services.scim.getScimGroup({ groupId: req.params.groupId, orgId: req.permission.orgId @@ -400,7 +420,12 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { schemas: z.array(z.string()), id: z.string().trim(), displayName: z.string().trim(), - members: z.array(z.any()).length(0) + members: z.array( + z.object({ + value: z.string(), // infisical userId + display: z.string() + }) + ) // note: is this where members are added to group? }), response: { 200: z.object({ @@ -421,10 +446,11 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { }, onRequest: verifyAuth([AuthMode.SCIM_TOKEN]), handler: async (req) => { + console.log(`PUT /Groups/${req.params.groupId} req.body: `, req.body); const group = await req.server.services.scim.updateScimGroupNamePut({ groupId: req.params.groupId, orgId: req.permission.orgId, - displayName: req.body.displayName + ...req.body }); return group; @@ -482,8 +508,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { }, onRequest: verifyAuth([AuthMode.SCIM_TOKEN]), handler: async (req) => { - // console.log("PATCH /Groups/:groupId req.body: ", req.body); - // console.log("PATCH /Groups/:groupId req.body: ", req.body.Operations[0]); + console.log(`PATCH /Groups/:${req.params.groupId} req.body: `, req.body); const group = await req.server.services.scim.updateScimGroupNamePatch({ groupId: req.params.groupId, orgId: req.permission.orgId, @@ -507,6 +532,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { }, onRequest: verifyAuth([AuthMode.SCIM_TOKEN]), handler: async (req) => { + console.log(`DELETE /Groups/:${req.params.groupId}`); const group = await req.server.services.scim.deleteScimGroup({ groupId: req.params.groupId, orgId: req.permission.orgId @@ -557,6 +583,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { }, onRequest: verifyAuth([AuthMode.SCIM_TOKEN]), handler: async (req) => { + console.log(`PUT /Users/:${req.params.userId} req.body: `, req.body); const user = await req.server.services.scim.replaceScimUser({ userId: req.params.userId, orgId: req.permission.orgId, diff --git a/backend/src/ee/services/group/group-dal.ts b/backend/src/ee/services/group/group-dal.ts index 55afd4e10..3392bad32 100644 --- a/backend/src/ee/services/group/group-dal.ts +++ b/backend/src/ee/services/group/group-dal.ts @@ -59,13 +59,13 @@ export const groupDALFactory = (db: TDbClient) => { } }; - const countAllGroupMembers = async ({ orgId, groupId }: { orgId: string; groupId: string }) => { + const countGroupMembers = async ({ orgId, groupId }: { orgId: string; groupId: string }) => { try { interface CountResult { count: string; } - const doc = await db(TableName.OrgMembership) + const directCount = await db(TableName.OrgMembership) .where(`${TableName.OrgMembership}.orgId`, orgId) .join(TableName.Users, `${TableName.OrgMembership}.userId`, `${TableName.Users}.id`) .leftJoin(TableName.UserGroupMembership, function () { @@ -75,13 +75,18 @@ export const groupDALFactory = (db: TDbClient) => { db.raw("?", [groupId]) ); }) - .where({ isGhost: false }) + .where({ isGhost: false, isAccepted: true }) .count(`${TableName.Users}.id`) .first(); - return parseInt((doc?.count as string) || "0", 10); + const pendingCount = await db(TableName.PendingGroupAddition) + .where(`${TableName.PendingGroupAddition}.groupId`, groupId) + .count("*") + .first(); + + return parseInt((directCount?.count as string) || "0", 10) + parseInt((pendingCount?.count as string) || "0", 10); } catch (err) { - throw new DatabaseError({ error: err, name: "Count all group members" }); + throw new DatabaseError({ error: err, name: "Count all direct group members" }); } }; @@ -110,14 +115,36 @@ export const groupDALFactory = (db: TDbClient) => { db.raw("?", [groupId]) ); }) - .select( + .leftJoin(TableName.PendingGroupAddition, function () { + this.on(`${TableName.PendingGroupAddition}.userId`, "=", `${TableName.Users}.id`).andOn( + `${TableName.PendingGroupAddition}.groupId`, + "=", + db.raw("?", [groupId]) + ); + }) + .select< + { + id: string; + groupId: string; + email: string; + username: string; + firstName: string; + lastName: string; + userId: string; + isPartOfGroup: boolean; + }[] + >( db.ref("id").withSchema(TableName.OrgMembership), db.ref("groupId").withSchema(TableName.UserGroupMembership), db.ref("email").withSchema(TableName.Users), db.ref("username").withSchema(TableName.Users), db.ref("firstName").withSchema(TableName.Users), db.ref("lastName").withSchema(TableName.Users), - db.ref("id").withSchema(TableName.Users).as("userId") + db.ref("id").withSchema(TableName.Users).as("userId"), + db.raw('CASE WHEN ?? IS NOT NULL OR ?? IS NOT NULL THEN TRUE ELSE FALSE END AS "isPartOfGroup"', [ + `${TableName.UserGroupMembership}.groupId`, + `${TableName.PendingGroupAddition}.groupId` + ]) ) .where({ isGhost: false }) .offset(offset); @@ -132,16 +159,15 @@ export const groupDALFactory = (db: TDbClient) => { const members = await query; - return members.map( - ({ email, username: memberUsername, firstName, lastName, userId, groupId: memberGroupId }) => ({ - id: userId, - email, - username: memberUsername, - firstName, - lastName, - isPartOfGroup: !!memberGroupId - }) - ); + return members.map(({ email, username: memberUsername, firstName, lastName, userId, isPartOfGroup }) => ({ + // TODO: fix type + id: userId, + email, + username: memberUsername, + firstName, + lastName, + isPartOfGroup + })); } catch (error) { throw new DatabaseError({ error, name: "Find all org members" }); } @@ -150,7 +176,7 @@ export const groupDALFactory = (db: TDbClient) => { return { findGroups, findByOrgId, - countAllGroupMembers, + countGroupMembers, findAllGroupMembers, ...groupOrm }; diff --git a/backend/src/ee/services/group/group-fns.ts b/backend/src/ee/services/group/group-fns.ts new file mode 100644 index 000000000..ae488edcf --- /dev/null +++ b/backend/src/ee/services/group/group-fns.ts @@ -0,0 +1,701 @@ +import { Knex } from "knex"; + +import { SecretKeyEncoding, TUsers } from "@app/db/schemas"; +import { decryptAsymmetric, encryptAsymmetric, infisicalSymmetricDecrypt } from "@app/lib/crypto/encryption"; +import { BadRequestError, ScimRequestError } from "@app/lib/errors"; + +import { + TAddUsersToGroupByUserIds, + TAddUsersToGroupDirectly, + TAddUsersToPendingGroupAdditions, + TConvertPendingGroupAdditionsToGroupMemberships, + TRemoveUsersFromGroupByUserIds, + TRemoveUsersFromGroupDirectly, + TRemoveUsersFromPendingGroupAdditions +} from "./group-types"; + +// TODO: write docstrings + +/** + * Add users with usernames [usernames] to group [group] + * @param {group} group - group to add user to + * @param {string[]} usernames - username(s) of user(s) to add to group + * @returns {Promise} - user that was added to group + */ +export const addUsersToGroupDirectly = async ({ + group, + usernames, + userDAL, + userGroupMembershipDAL, + orgDAL, + groupProjectDAL, + projectKeyDAL, + projectDAL, + projectBotDAL, + tx: outerTx +}: TAddUsersToGroupDirectly) => { + const processAddition = async (tx: Knex) => { + const users = await userDAL.findUserEncKeyByUsernameBatch( + { + usernames + }, + tx + ); + + const usersUsernamesSet = new Set(users.map((u) => u.username)); + usernames.forEach((username) => { + if (!usersUsernamesSet.has(username)) { + throw new BadRequestError({ + message: `Failed to find user with username ${username}` + }); + } + }); + + const userIds = users.map((u) => { + if (!u.isAccepted) { + throw new BadRequestError({ + message: `User ${u.username} cannot be added to group because they have not confirmed their account` + }); + } + + return u.userId; + }); + + // check if user(s) group membership(s) already exists + const existingUserGroupMemberships = await userGroupMembershipDAL.find( + { + groupId: group.id, + $in: { + userId: userIds + } + }, + { tx } + ); + + if (existingUserGroupMemberships.length) { + throw new BadRequestError({ + message: `User(s) are already part of the group ${group.slug}` + }); + } + + // check if all user(s) are part of the organization + const existingUserOrgMemberships = await orgDAL.findMembership( + { + orgId: group.orgId, + $in: { + userId: userIds + } + }, + { tx } + ); + + const existingUserOrgMembershipsUsernamesSet = new Set(existingUserOrgMemberships.map((u) => u.username)); + + usernames.forEach((username) => { + if (!existingUserOrgMembershipsUsernamesSet.has(username)) + throw new BadRequestError({ + message: `User ${username} is not part of the organization` + }); + }); + + await userGroupMembershipDAL.insertMany( + userIds.map((userId) => ({ + userId, + groupId: group.id + })), + tx + ); + + // check which projects the group is part of + const projectIds = Array.from( + new Set( + ( + await groupProjectDAL.find( + { + groupId: group.id + }, + { tx } + ) + ).map((gp) => gp.projectId) + ) + ); + + const keys = await projectKeyDAL.find( + { + $in: { + projectId: projectIds, + receiverId: userIds + } + }, + { tx } + ); + + const userKeysSet = new Set(keys.map((k) => `${k.projectId}-${k.receiverId}`)); + + for await (const projectId of projectIds) { + const usersToAddProjectKeyFor = users.filter((u) => !userKeysSet.has(`${projectId}-${u.userId}`)); + + if (usersToAddProjectKeyFor.length) { + // there are users who need to be shared keys + // process adding bulk users to projects for each project individually + const ghostUser = await projectDAL.findProjectGhostUser(projectId, tx); + + if (!ghostUser) { + throw new BadRequestError({ + message: "Failed to find sudo user" + }); + } + + const ghostUserLatestKey = await projectKeyDAL.findLatestProjectKey(ghostUser.id, projectId, tx); + + if (!ghostUserLatestKey) { + throw new BadRequestError({ + message: "Failed to find sudo user latest key" + }); + } + + const bot = await projectBotDAL.findOne({ projectId }, tx); + + if (!bot) { + throw new BadRequestError({ + message: "Failed to find bot" + }); + } + + const botPrivateKey = infisicalSymmetricDecrypt({ + keyEncoding: bot.keyEncoding as SecretKeyEncoding, + iv: bot.iv, + tag: bot.tag, + ciphertext: bot.encryptedPrivateKey + }); + + const plaintextProjectKey = decryptAsymmetric({ + ciphertext: ghostUserLatestKey.encryptedKey, + nonce: ghostUserLatestKey.nonce, + publicKey: ghostUserLatestKey.sender.publicKey, + privateKey: botPrivateKey + }); + + const projectKeysToAdd = usersToAddProjectKeyFor.map((user) => { + const { ciphertext: encryptedKey, nonce } = encryptAsymmetric( + plaintextProjectKey, + user.publicKey, + botPrivateKey + ); + return { + encryptedKey, + nonce, + senderId: ghostUser.id, + receiverId: user.userId, + projectId + }; + }); + + await projectKeyDAL.insertMany(projectKeysToAdd, tx); + } + } + + return users; + }; + + if (outerTx) { + return processAddition(outerTx); + } + return userDAL.transaction(async (tx) => { + return processAddition(tx); + }); +}; + +export const addUsersToPendingGroupAdditions = async ({ + group, + userIds, + pendingGroupAdditionDAL, + userDAL, + orgDAL, + tx: outerTx +}: TAddUsersToPendingGroupAdditions) => { + const processAddition = async (tx: Knex) => { + const users = await userDAL.find( + { + $in: { + id: userIds + } + }, + { tx } + ); + + const usersUserIdsSet = new Set(users.map((u) => u.id)); + userIds.forEach((userId) => { + if (!usersUserIdsSet.has(userId)) { + throw new BadRequestError({ + message: `Failed to find user with id ${userId}` + }); + } + }); + + users.map((u) => { + if (u.isAccepted) { + throw new BadRequestError({ + message: `User ${u.username} cannot be added to a pending group addition because they have confirmed their account` + }); + } + + return u.id; + }); + + // check if user(s) pending group addition(s) already exist + const existingPendingGroupAdditions = await pendingGroupAdditionDAL.find( + { + groupId: group.id, + $in: { + userId: userIds + } + }, + { tx } + ); + + if (existingPendingGroupAdditions.length) { + throw new BadRequestError({ + message: `User(s) are already part of the group ${group.slug}` + }); + } + + // check if all user(s) are part of the organization + const existingUserOrgMemberships = await orgDAL.findMembership( + { + orgId: group.orgId, + $in: { + userId: userIds + } + }, + { tx } + ); + + const existingUserOrgMembershipsUserIdsSet = new Set(existingUserOrgMemberships.map((u) => u.userId)); + + userIds.forEach((userId) => { + if (!existingUserOrgMembershipsUserIdsSet.has(userId)) + throw new BadRequestError({ + message: `User with id ${userId} is not part of the organization` + }); + }); + + await pendingGroupAdditionDAL.insertMany( + users.map((user) => ({ + userId: user.id, + groupId: group.id + })), + tx + ); + + return users; + }; + + if (outerTx) { + return processAddition(outerTx); + } + return userDAL.transaction(async (tx) => { + return processAddition(tx); + }); +}; + +export const addUsersToGroupByUserIds = async ({ + group, + userIds, + userDAL, + userGroupMembershipDAL, + orgDAL, + groupProjectDAL, + pendingGroupAdditionDAL, + projectKeyDAL, + projectDAL, + projectBotDAL, + tx: outerTx +}: TAddUsersToGroupByUserIds) => { + const processAddition = async (tx: Knex) => { + const foundMembers = await userDAL.find({ + $in: { + id: userIds + } + }); + + const foundMembersIdsSet = new Set(foundMembers.map((member) => member.id)); + + const isCompleteMatch = userIds.every((userId) => foundMembersIdsSet.has(userId)); + + if (!isCompleteMatch) { + throw new ScimRequestError({ + detail: "Members not found", + status: 404 + }); + } + + const membersToAddToGroupDirectly: TUsers[] = []; + const membersToAddToGroupPending: TUsers[] = []; + + foundMembers.forEach((member) => { + if (member.isAccepted) { + // add accepted member to group + membersToAddToGroupDirectly.push(member); + } else { + // add incomplete member to pending group addition + membersToAddToGroupPending.push(member); + } + }); + + let addedUsers: TUsers[] = []; + + if (membersToAddToGroupDirectly.length) { + addedUsers = addedUsers.concat( + await addUsersToGroupDirectly({ + group, + usernames: membersToAddToGroupDirectly.map((member) => member.username), + userDAL, + userGroupMembershipDAL, + orgDAL, + groupProjectDAL, + projectKeyDAL, + projectDAL, + projectBotDAL, + tx + }) + ); + } + + if (membersToAddToGroupPending.length) { + addedUsers = addedUsers.concat( + await addUsersToPendingGroupAdditions({ + group, + userIds: membersToAddToGroupPending.map((member) => member.id), + pendingGroupAdditionDAL, + userDAL, + orgDAL, + tx + }) + ); + } + + return addedUsers; + }; + + if (outerTx) { + return processAddition(outerTx); + } + return userDAL.transaction(async (tx) => { + return processAddition(tx); + }); +}; + +export const removeUsersFromGroupDirectly = async ({ + group, + userIds, + userDAL, + userGroupMembershipDAL, + groupProjectDAL, + projectKeyDAL, + tx: outerTx +}: TRemoveUsersFromGroupDirectly) => { + const processRemoval = async (tx: Knex) => { + const users = await userDAL.find( + { + $in: { + id: userIds + } + }, + { tx } + ); + + const usersUserIdsSet = new Set(users.map((u) => u.id)); + userIds.forEach((userId) => { + if (!usersUserIdsSet.has(userId)) { + throw new BadRequestError({ + message: `Failed to find user with id ${userId}` + }); + } + }); + + // check if user group membership already exists + const existingUserGroupMemberships = await userGroupMembershipDAL.find( + { + groupId: group.id, + $in: { + userId: userIds + } + }, + { tx } + ); + + const existingUserGroupMembershipsUserIdsSet = new Set(existingUserGroupMemberships.map((u) => u.userId)); + + userIds.forEach((userId) => { + if (!existingUserGroupMembershipsUserIdsSet.has(userId)) + throw new BadRequestError({ + message: `User(s) are not part of the group ${group.slug}` + }); + }); + + // check which projects the group is part of + const projectIds = Array.from( + new Set( + ( + await groupProjectDAL.find( + { + groupId: group.id + }, + { tx } + ) + ).map((gp) => gp.projectId) + ) + ); + + // TODO: this part can be optimized + for await (const userId of userIds) { + const t = await userGroupMembershipDAL.filterProjectsByUserMembership(userId, group.id, projectIds, tx); + const projectsToDeleteKeyFor = projectIds.filter((p) => !t.has(p)); + + if (projectsToDeleteKeyFor.length) { + await projectKeyDAL.delete( + { + receiverId: userId, + $in: { + projectId: projectsToDeleteKeyFor + } + }, + tx + ); + } + + await userGroupMembershipDAL.delete( + { + groupId: group.id, + userId + }, + tx + ); + } + + return users; + }; + + if (outerTx) { + return processRemoval(outerTx); + } + return userDAL.transaction(async (tx) => { + return processRemoval(tx); + }); +}; + +export const removeUsersFromPendingGroupAdditions = async ({ + group, + userIds, + userDAL, + pendingGroupAdditionDAL, + tx: outerTx +}: TRemoveUsersFromPendingGroupAdditions) => { + const processRemoval = async (tx: Knex) => { + const users = await userDAL.find( + { + $in: { + id: userIds + } + }, + { tx } + ); + + const usersUserIdsSet = new Set(users.map((u) => u.id)); + userIds.forEach((userId) => { + if (!usersUserIdsSet.has(userId)) { + throw new BadRequestError({ + message: `Failed to find user with id ${userId}` + }); + } + }); + + // check if user pending group addition already exists + const existingPendingGroupAdditions = await pendingGroupAdditionDAL.find( + { + groupId: group.id, + $in: { + userId: userIds + } + }, + { tx } + ); + + const existingPendingGroupAdditionsUserIdsSet = new Set(existingPendingGroupAdditions.map((u) => u.userId)); + + userIds.forEach((userId) => { + if (!existingPendingGroupAdditionsUserIdsSet.has(userId)) + throw new BadRequestError({ + message: `User(s) are not part of the group ${group.slug}` + }); + }); + + await pendingGroupAdditionDAL.delete( + { + groupId: group.id, + $in: { + userId: userIds + } + }, + tx + ); + + return users; + }; + + if (outerTx) { + return processRemoval(outerTx); + } + return userDAL.transaction(async (tx) => { + return processRemoval(tx); + }); +}; + +export const convertPendingGroupAdditionsToGroupMemberships = async ({ + userIds, + userDAL, + pendingGroupAdditionDAL, + userGroupMembershipDAL, + orgDAL, + groupProjectDAL, + projectKeyDAL, + projectDAL, + projectBotDAL, + tx: outerTx +}: TConvertPendingGroupAdditionsToGroupMemberships) => { + const processConversion = async (tx: Knex) => { + const users = await userDAL.find( + { + $in: { + id: userIds + } + }, + { tx } + ); + + const usersUserIdsSet = new Set(users.map((u) => u.id)); + userIds.forEach((userId) => { + if (!usersUserIdsSet.has(userId)) { + throw new BadRequestError({ + message: `Failed to find user with id ${userId}` + }); + } + }); + + users.forEach((user) => { + if (!user.isAccepted) { + throw new BadRequestError({ + message: `Failed to convert pending group additions to group memberships for user ${user.username} because they have not confirmed their account` + }); + } + }); + + const pendingGroupAdditions = await pendingGroupAdditionDAL.deletePendingGroupAdditionsByUserIds(userIds, tx); + + for await (const pendingGroupAddition of pendingGroupAdditions) { + await addUsersToGroupDirectly({ + group: pendingGroupAddition.group, + usernames: [pendingGroupAddition.user.username], + userDAL, + userGroupMembershipDAL, + orgDAL, + groupProjectDAL, + projectKeyDAL, + projectDAL, + projectBotDAL, + tx + }); + } + }; + + if (outerTx) { + return processConversion(outerTx); + } + return userDAL.transaction(async (tx) => { + await processConversion(tx); + }); +}; + +export const removeUsersFromGroupByUserIds = async ({ + group, + userIds, + userDAL, + userGroupMembershipDAL, + groupProjectDAL, + pendingGroupAdditionDAL, + projectKeyDAL, + tx: outerTx +}: TRemoveUsersFromGroupByUserIds) => { + const processRemoval = async (tx: Knex) => { + const foundMembers = await userDAL.find({ + $in: { + id: userIds + } + }); + + const foundMembersIdsSet = new Set(foundMembers.map((member) => member.id)); + + const isCompleteMatch = userIds.every((userId) => foundMembersIdsSet.has(userId)); + + if (!isCompleteMatch) { + throw new ScimRequestError({ + detail: "Members not found", + status: 404 + }); + } + + const membersToRemoveFromGroupDirectly: TUsers[] = []; + const membersToRemoveFromGroupPending: TUsers[] = []; + + foundMembers.forEach((member) => { + if (member.isAccepted) { + // remove accepted member from group + membersToRemoveFromGroupDirectly.push(member); + } else { + // remove incomplete member from pending group addition + membersToRemoveFromGroupPending.push(member); + } + }); + + console.log("removeUsersFromGroupByUserIds membersToRemoveFromGroupDirectly: ", membersToRemoveFromGroupDirectly); + console.log("removeUsersFromGroupByUserIds membersToRemoveFromGroupPending: ", membersToRemoveFromGroupPending); + + let removedUsers: TUsers[] = []; + + if (membersToRemoveFromGroupDirectly.length) { + removedUsers = removedUsers.concat( + await removeUsersFromGroupDirectly({ + group, + userIds: membersToRemoveFromGroupDirectly.map((member) => member.id), + userDAL, + userGroupMembershipDAL, + groupProjectDAL, + projectKeyDAL, + tx + }) + ); + } + + if (membersToRemoveFromGroupPending.length) { + removedUsers = removedUsers.concat( + await removeUsersFromPendingGroupAdditions({ + group, + userIds: membersToRemoveFromGroupPending.map((member) => member.id), + pendingGroupAdditionDAL, + userDAL, + tx + }) + ); + } + + return removedUsers; + }; + + if (outerTx) { + return processRemoval(outerTx); + } + return userDAL.transaction(async (tx) => { + return processRemoval(tx); + }); +}; diff --git a/backend/src/ee/services/group/group-service.ts b/backend/src/ee/services/group/group-service.ts index 285403bcd..5bb6aa9d6 100644 --- a/backend/src/ee/services/group/group-service.ts +++ b/backend/src/ee/services/group/group-service.ts @@ -1,22 +1,23 @@ import { ForbiddenError } from "@casl/ability"; import slugify from "@sindresorhus/slugify"; -import { OrgMembershipRole, SecretKeyEncoding, TOrgRoles } from "@app/db/schemas"; +import { OrgMembershipRole, TOrgRoles } from "@app/db/schemas"; +import { TPendingGroupAdditionDALFactory } from "@app/ee/services/group/pending-group-addition-dal"; import { isAtLeastAsPrivileged } from "@app/lib/casl"; -import { decryptAsymmetric, encryptAsymmetric, infisicalSymmetricDecrypt } from "@app/lib/crypto/encryption"; import { BadRequestError, ForbiddenRequestError } from "@app/lib/errors"; import { alphaNumericNanoId } from "@app/lib/nanoid"; +import { TGroupProjectDALFactory } from "@app/services/group-project/group-project-dal"; +import { TOrgDALFactory } from "@app/services/org/org-dal"; +import { TProjectDALFactory } from "@app/services/project/project-dal"; +import { TProjectBotDALFactory } from "@app/services/project-bot/project-bot-dal"; +import { TProjectKeyDALFactory } from "@app/services/project-key/project-key-dal"; +import { TUserDALFactory } from "@app/services/user/user-dal"; -import { TGroupProjectDALFactory } from "../../../services/group-project/group-project-dal"; -import { TOrgDALFactory } from "../../../services/org/org-dal"; -import { TProjectDALFactory } from "../../../services/project/project-dal"; -import { TProjectBotDALFactory } from "../../../services/project-bot/project-bot-dal"; -import { TProjectKeyDALFactory } from "../../../services/project-key/project-key-dal"; -import { TUserDALFactory } from "../../../services/user/user-dal"; import { TLicenseServiceFactory } from "../license/license-service"; import { OrgPermissionActions, OrgPermissionSubjects } from "../permission/org-permission"; import { TPermissionServiceFactory } from "../permission/permission-service"; import { TGroupDALFactory } from "./group-dal"; +import { addUsersToGroupByUserIds, removeUsersFromGroupByUserIds } from "./group-fns"; import { TAddUserToGroupDTO, TCreateGroupDTO, @@ -28,20 +29,21 @@ import { import { TUserGroupMembershipDALFactory } from "./user-group-membership-dal"; type TGroupServiceFactoryDep = { - userDAL: Pick; + userDAL: Pick; groupDAL: Pick< TGroupDALFactory, - "create" | "findOne" | "update" | "delete" | "findAllGroupMembers" | "countAllGroupMembers" + "create" | "findOne" | "update" | "delete" | "findAllGroupMembers" | "countGroupMembers" >; groupProjectDAL: Pick; orgDAL: Pick; userGroupMembershipDAL: Pick< TUserGroupMembershipDALFactory, - "findOne" | "create" | "delete" | "filterProjectsByUserMembership" + "findOne" | "delete" | "filterProjectsByUserMembership" | "transaction" | "insertMany" | "find" >; projectDAL: Pick; projectBotDAL: Pick; - projectKeyDAL: Pick; + projectKeyDAL: Pick; + pendingGroupAdditionDAL: TPendingGroupAdditionDALFactory; // remove? permissionService: Pick; licenseService: Pick; }; @@ -57,6 +59,7 @@ export const groupServiceFactory = ({ projectDAL, projectBotDAL, projectKeyDAL, + pendingGroupAdditionDAL, permissionService, licenseService }: TGroupServiceFactoryDep) => { @@ -227,7 +230,7 @@ export const groupServiceFactory = ({ username }); - const totalCount = await groupDAL.countAllGroupMembers({ + const totalCount = await groupDAL.countGroupMembers({ orgId: group.orgId, groupId: group.id }); @@ -272,111 +275,23 @@ export const groupServiceFactory = ({ if (!hasRequiredPriviledges) throw new ForbiddenRequestError({ message: "Failed to add user to more privileged group" }); - // get user with username - const user = await userDAL.findUserEncKeyByUsername({ - username + const user = await userDAL.findOne({ username }); + if (!user) throw new BadRequestError({ message: `Failed to find user with username ${username}` }); + + const users = await addUsersToGroupByUserIds({ + group, + userIds: [user.id], + userDAL, + userGroupMembershipDAL, + orgDAL, + groupProjectDAL, + pendingGroupAdditionDAL, + projectKeyDAL, + projectDAL, + projectBotDAL }); - if (!user) - throw new BadRequestError({ - message: `Failed to find user with username ${username}` - }); - - // check if user group membership already exists - const existingUserGroupMembership = await userGroupMembershipDAL.findOne({ - groupId: group.id, - userId: user.userId - }); - - if (existingUserGroupMembership) - throw new BadRequestError({ - message: `User ${username} is already part of the group ${groupSlug}` - }); - - // check if user is even part of the organization - const existingUserOrgMembership = await orgDAL.findMembership({ - userId: user.userId, - orgId: actorOrgId - }); - - if (!existingUserOrgMembership) - throw new BadRequestError({ - message: `User ${username} is not part of the organization` - }); - - await userGroupMembershipDAL.create({ - userId: user.userId, - groupId: group.id - }); - - // check which projects the group is part of - const projectIds = ( - await groupProjectDAL.find({ - groupId: group.id - }) - ).map((gp) => gp.projectId); - - const keys = await projectKeyDAL.find({ - receiverId: user.userId, - $in: { - projectId: projectIds - } - }); - - const keysSet = new Set(keys.map((k) => k.projectId)); - const projectsToAddKeyFor = projectIds.filter((p) => !keysSet.has(p)); - - for await (const projectId of projectsToAddKeyFor) { - const ghostUser = await projectDAL.findProjectGhostUser(projectId); - - if (!ghostUser) { - throw new BadRequestError({ - message: "Failed to find sudo user" - }); - } - - const ghostUserLatestKey = await projectKeyDAL.findLatestProjectKey(ghostUser.id, projectId); - - if (!ghostUserLatestKey) { - throw new BadRequestError({ - message: "Failed to find sudo user latest key" - }); - } - - const bot = await projectBotDAL.findOne({ projectId }); - - if (!bot) { - throw new BadRequestError({ - message: "Failed to find bot" - }); - } - - const botPrivateKey = infisicalSymmetricDecrypt({ - keyEncoding: bot.keyEncoding as SecretKeyEncoding, - iv: bot.iv, - tag: bot.tag, - ciphertext: bot.encryptedPrivateKey - }); - - const plaintextProjectKey = decryptAsymmetric({ - ciphertext: ghostUserLatestKey.encryptedKey, - nonce: ghostUserLatestKey.nonce, - publicKey: ghostUserLatestKey.sender.publicKey, - privateKey: botPrivateKey - }); - - const { ciphertext: encryptedKey, nonce } = encryptAsymmetric(plaintextProjectKey, user.publicKey, botPrivateKey); - - await projectKeyDAL.create({ - encryptedKey, - nonce, - senderId: ghostUser.id, - receiverId: user.userId, - projectId - }); - } - - return user; + return users[0]; }; const removeUserFromGroup = async ({ @@ -416,51 +331,20 @@ export const groupServiceFactory = ({ if (!hasRequiredPriviledges) throw new ForbiddenRequestError({ message: "Failed to delete user from more privileged group" }); - const user = await userDAL.findOne({ - username + const user = await userDAL.findOne({ username }); + if (!user) throw new BadRequestError({ message: `Failed to find user with username ${username}` }); + + const users = await removeUsersFromGroupByUserIds({ + group, + userIds: [user.id], + userDAL, + userGroupMembershipDAL, + pendingGroupAdditionDAL, + groupProjectDAL, + projectKeyDAL }); - if (!user) - throw new BadRequestError({ - message: `Failed to find user with username ${username}` - }); - - // check if user group membership already exists - const existingUserGroupMembership = await userGroupMembershipDAL.findOne({ - groupId: group.id, - userId: user.id - }); - - if (!existingUserGroupMembership) - throw new BadRequestError({ - message: `User ${username} is not part of the group ${groupSlug}` - }); - - const projectIds = ( - await groupProjectDAL.find({ - groupId: group.id - }) - ).map((gp) => gp.projectId); - - const t = await userGroupMembershipDAL.filterProjectsByUserMembership(user.id, group.id, projectIds); - - const projectsToDeleteKeyFor = projectIds.filter((p) => !t.has(p)); - - if (projectsToDeleteKeyFor.length) { - await projectKeyDAL.delete({ - receiverId: user.id, - $in: { - projectId: projectsToDeleteKeyFor - } - }); - } - - await userGroupMembershipDAL.delete({ - groupId: group.id, - userId: user.id - }); - - return user; + return users[0]; }; return { diff --git a/backend/src/ee/services/group/group-types.ts b/backend/src/ee/services/group/group-types.ts index e2fbbe63e..301e12cdc 100644 --- a/backend/src/ee/services/group/group-types.ts +++ b/backend/src/ee/services/group/group-types.ts @@ -1,4 +1,15 @@ +import { Knex } from "knex"; + +import { TGroups } from "@app/db/schemas"; +import { TPendingGroupAdditionDALFactory } from "@app/ee/services/group/pending-group-addition-dal"; +import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal"; import { TGenericPermission } from "@app/lib/types"; +import { TGroupProjectDALFactory } from "@app/services/group-project/group-project-dal"; +import { TOrgDALFactory } from "@app/services/org/org-dal"; +import { TProjectDALFactory } from "@app/services/project/project-dal"; +import { TProjectBotDALFactory } from "@app/services/project-bot/project-bot-dal"; +import { TProjectKeyDALFactory } from "@app/services/project-key/project-key-dal"; +import { TUserDALFactory } from "@app/services/user/user-dal"; export type TCreateGroupDTO = { name: string; @@ -35,3 +46,83 @@ export type TRemoveUserFromGroupDTO = { groupSlug: string; username: string; } & TGenericPermission; + +// group fns types + +export type TAddUsersToGroupByUserIds = { + group: TGroups; + userIds: string[]; + userDAL: Pick; + userGroupMembershipDAL: Pick; + orgDAL: Pick; + groupProjectDAL: Pick; + pendingGroupAdditionDAL: Pick; + projectKeyDAL: Pick; + projectDAL: Pick; + projectBotDAL: Pick; + tx?: Knex; +}; + +export type TAddUsersToGroupDirectly = { + group: TGroups; + usernames: string[]; + userDAL: Pick; + userGroupMembershipDAL: Pick; + orgDAL: Pick; + groupProjectDAL: Pick; + projectKeyDAL: Pick; + projectDAL: Pick; + projectBotDAL: Pick; + tx?: Knex; +}; + +export type TAddUsersToPendingGroupAdditions = { + userIds: string[]; + group: TGroups; + pendingGroupAdditionDAL: Pick; + userDAL: Pick; + orgDAL: Pick; + tx?: Knex; +}; + +export type TRemoveUsersFromGroupByUserIds = { + group: TGroups; + userIds: string[]; + userDAL: Pick; + userGroupMembershipDAL: Pick; + pendingGroupAdditionDAL: Pick; + groupProjectDAL: Pick; + projectKeyDAL: Pick; + tx?: Knex; +}; + +export type TRemoveUsersFromGroupDirectly = { + group: TGroups; + userIds: string[]; + userDAL: Pick; + userGroupMembershipDAL: Pick; + groupProjectDAL: Pick; + projectKeyDAL: Pick; + tx?: Knex; +}; + +export type TRemoveUsersFromPendingGroupAdditions = { + group: TGroups; + userIds: string[]; + pendingGroupAdditionDAL: Pick; + userDAL: Pick; + tx?: Knex; +}; + +export type TConvertPendingGroupAdditionsToGroupMemberships = { + userIds: string[]; + pendingGroupAdditionDAL: Pick; + userDAL: Pick; + userGroupMembershipDAL: Pick; + orgDAL: Pick; + groupProjectDAL: Pick; + projectKeyDAL: Pick; + projectDAL: Pick; + projectBotDAL: Pick; + tx?: Knex; +}; diff --git a/backend/src/ee/services/group/pending-group-addition-dal.ts b/backend/src/ee/services/group/pending-group-addition-dal.ts new file mode 100644 index 000000000..579cbb6e5 --- /dev/null +++ b/backend/src/ee/services/group/pending-group-addition-dal.ts @@ -0,0 +1,55 @@ +import { Knex } from "knex"; + +import { TDbClient } from "@app/db"; +import { TableName } from "@app/db/schemas"; +import { DatabaseError } from "@app/lib/errors"; +import { ormify } from "@app/lib/knex"; + +export type TPendingGroupAdditionDALFactory = ReturnType; + +export const pendingGroupAdditionDALFactory = (db: TDbClient) => { + const pendingGroupAdditionOrm = ormify(db, TableName.PendingGroupAddition); + + // special query + const deletePendingGroupAdditionsByUserIds = async (userIds: string[], tx?: Knex) => { + try { + const pendingGroupAdditions = await (tx || db)(TableName.PendingGroupAddition) + .whereIn(`${TableName.PendingGroupAddition}.userId`, userIds) + .join(TableName.Groups, `${TableName.PendingGroupAddition}.groupId`, `${TableName.Groups}.id`) + .join(TableName.Users, `${TableName.PendingGroupAddition}.userId`, `${TableName.Users}.id`); + + await pendingGroupAdditionOrm.delete( + { + $in: { + userId: userIds + } + }, + tx + ); + + return pendingGroupAdditions.map(({ userId, username, groupId, orgId, name, slug, role, roleId }) => ({ + user: { + id: userId, + username + }, + group: { + id: groupId, + orgId, + name, + slug, + role, + roleId, + createdAt: new Date(), + updatedAt: new Date() + } + })); + } catch (error) { + throw new DatabaseError({ error, name: "Filter projects by user membership" }); + } + }; + + return { + ...pendingGroupAdditionOrm, + deletePendingGroupAdditionsByUserIds + }; +}; diff --git a/backend/src/ee/services/group/user-group-membership-dal.ts b/backend/src/ee/services/group/user-group-membership-dal.ts index e8a262c3e..d4f8fecd7 100644 --- a/backend/src/ee/services/group/user-group-membership-dal.ts +++ b/backend/src/ee/services/group/user-group-membership-dal.ts @@ -1,3 +1,5 @@ +import { Knex } from "knex"; + import { TDbClient } from "@app/db"; import { TableName, TUserEncryptionKeys } from "@app/db/schemas"; import { DatabaseError } from "@app/lib/errors"; @@ -14,24 +16,28 @@ export const userGroupMembershipDALFactory = (db: TDbClient) => { * - The user is a member of a group that is a member of the project, excluding projects that they are part of * through the group with id [groupId]. */ - const filterProjectsByUserMembership = async (userId: string, groupId: string, projectIds: string[]) => { - const userProjectMemberships: string[] = await db(TableName.ProjectMembership) - .where(`${TableName.ProjectMembership}.userId`, userId) - .whereIn(`${TableName.ProjectMembership}.projectId`, projectIds) - .pluck(`${TableName.ProjectMembership}.projectId`); + const filterProjectsByUserMembership = async (userId: string, groupId: string, projectIds: string[], tx?: Knex) => { + try { + const userProjectMemberships: string[] = await (tx || db)(TableName.ProjectMembership) + .where(`${TableName.ProjectMembership}.userId`, userId) + .whereIn(`${TableName.ProjectMembership}.projectId`, projectIds) + .pluck(`${TableName.ProjectMembership}.projectId`); - const userGroupMemberships: string[] = await db(TableName.UserGroupMembership) - .where(`${TableName.UserGroupMembership}.userId`, userId) - .whereNot(`${TableName.UserGroupMembership}.groupId`, groupId) - .join( - TableName.GroupProjectMembership, - `${TableName.UserGroupMembership}.groupId`, - `${TableName.GroupProjectMembership}.groupId` - ) - .whereIn(`${TableName.GroupProjectMembership}.projectId`, projectIds) - .pluck(`${TableName.GroupProjectMembership}.projectId`); + const userGroupMemberships: string[] = await (tx || db)(TableName.UserGroupMembership) + .where(`${TableName.UserGroupMembership}.userId`, userId) + .whereNot(`${TableName.UserGroupMembership}.groupId`, groupId) + .join( + TableName.GroupProjectMembership, + `${TableName.UserGroupMembership}.groupId`, + `${TableName.GroupProjectMembership}.groupId` + ) + .whereIn(`${TableName.GroupProjectMembership}.projectId`, projectIds) + .pluck(`${TableName.GroupProjectMembership}.projectId`); - return new Set(userProjectMemberships.concat(userGroupMemberships)); + return new Set(userProjectMemberships.concat(userGroupMemberships)); + } catch (error) { + throw new DatabaseError({ error, name: "Filter projects by user membership" }); + } }; // special query @@ -45,7 +51,7 @@ export const userGroupMembershipDALFactory = (db: TDbClient) => { ) .join(TableName.Users, `${TableName.UserGroupMembership}.userId`, `${TableName.Users}.id`) .where(`${TableName.GroupProjectMembership}.projectId`, projectId) - .whereIn(`${TableName.Users}.username`, usernames) // TODO: pluck usernames + .whereIn(`${TableName.Users}.username`, usernames) .pluck(`${TableName.Users}.id`); return usernameDocs; diff --git a/backend/src/ee/services/license/licence-fns.ts b/backend/src/ee/services/license/licence-fns.ts index 8a4de57f1..17a538881 100644 --- a/backend/src/ee/services/license/licence-fns.ts +++ b/backend/src/ee/services/license/licence-fns.ts @@ -24,10 +24,10 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({ customAlerts: false, auditLogs: false, auditLogsRetentionDays: 0, - samlSSO: false, - scim: false, + samlSSO: true, + scim: true, ldap: false, - groups: false, + groups: true, status: null, trial_end: null, has_used_trial: true, diff --git a/backend/src/ee/services/license/license-types.ts b/backend/src/ee/services/license/license-types.ts index 1cea39a83..efc1c18dd 100644 --- a/backend/src/ee/services/license/license-types.ts +++ b/backend/src/ee/services/license/license-types.ts @@ -40,10 +40,10 @@ export type TFeatureSet = { customAlerts: false; auditLogs: false; auditLogsRetentionDays: 0; - samlSSO: false; - scim: false; + samlSSO: true; + scim: true; ldap: false; - groups: false; + groups: true; status: null; trial_end: null; has_used_trial: true; diff --git a/backend/src/ee/services/scim/scim-service.ts b/backend/src/ee/services/scim/scim-service.ts index 15ca67a10..588159acf 100644 --- a/backend/src/ee/services/scim/scim-service.ts +++ b/backend/src/ee/services/scim/scim-service.ts @@ -4,15 +4,21 @@ import jwt from "jsonwebtoken"; import { OrgMembershipRole, OrgMembershipStatus, TableName, TGroups } from "@app/db/schemas"; import { TGroupDALFactory } from "@app/ee/services/group/group-dal"; +import { addUsersToGroupByUserIds, removeUsersFromGroupByUserIds } from "@app/ee/services/group/group-fns"; +import { TPendingGroupAdditionDALFactory } from "@app/ee/services/group/pending-group-addition-dal"; +import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal"; import { TScimDALFactory } from "@app/ee/services/scim/scim-dal"; import { getConfig } from "@app/lib/config/env"; import { BadRequestError, ScimRequestError, UnauthorizedError } from "@app/lib/errors"; import { alphaNumericNanoId } from "@app/lib/nanoid"; import { TOrgPermission } from "@app/lib/types"; import { AuthMethod, AuthTokenType } from "@app/services/auth/auth-type"; +import { TGroupProjectDALFactory } from "@app/services/group-project/group-project-dal"; import { TOrgDALFactory } from "@app/services/org/org-dal"; import { deleteOrgMembership } from "@app/services/org/org-fns"; import { TProjectDALFactory } from "@app/services/project/project-dal"; +import { TProjectBotDALFactory } from "@app/services/project-bot/project-bot-dal"; +import { TProjectKeyDALFactory } from "@app/services/project-key/project-key-dal"; import { TProjectMembershipDALFactory } from "@app/services/project-membership/project-membership-dal"; import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service"; import { TUserDALFactory } from "@app/services/user/user-dal"; @@ -42,14 +48,22 @@ import { type TScimServiceFactoryDep = { scimDAL: Pick; - userDAL: Pick; + userDAL: Pick; orgDAL: Pick< TOrgDALFactory, "createMembership" | "findById" | "findMembership" | "deleteMembershipById" | "transaction" >; - projectDAL: Pick; + projectDAL: Pick; projectMembershipDAL: Pick; - groupDAL: Pick; + groupDAL: Pick< + TGroupDALFactory, + "create" | "findOne" | "findAllGroupMembers" | "update" | "delete" | "findGroups" | "transaction" + >; + groupProjectDAL: Pick; + userGroupMembershipDAL: TUserGroupMembershipDALFactory; // TODO: Pick + projectKeyDAL: Pick; + projectBotDAL: Pick; + pendingGroupAdditionDAL: TPendingGroupAdditionDALFactory; // TODO: Pick licenseService: Pick; permissionService: Pick; smtpService: TSmtpService; @@ -65,6 +79,11 @@ export const scimServiceFactory = ({ projectDAL, projectMembershipDAL, groupDAL, + groupProjectDAL, + userGroupMembershipDAL, + projectKeyDAL, + projectBotDAL, + pendingGroupAdditionDAL, permissionService, smtpService }: TScimServiceFactoryDep) => { @@ -473,7 +492,19 @@ export const scimServiceFactory = ({ }; const listScimGroups = async ({ orgId, offset, limit }: TListScimGroupsDTO) => { + const plan = await licenseService.getPlan(orgId); + if (!plan.groups) + throw new BadRequestError({ + message: "Failed to list SCIM groups due to plan restriction. Upgrade plan to list SCIM groups." + }); + const org = await orgDAL.findById(orgId); + if (!org) { + throw new ScimRequestError({ + detail: "Organization Not Found", + status: 404 + }); + } if (!org.scimEnabled) throw new ScimRequestError({ @@ -500,30 +531,77 @@ export const scimServiceFactory = ({ }); }; - const createScimGroup = async ({ displayName, orgId }: TCreateScimGroupDTO) => { + const createScimGroup = async ({ displayName, orgId, members }: TCreateScimGroupDTO) => { + const plan = await licenseService.getPlan(orgId); + if (!plan.groups) + throw new BadRequestError({ + message: "Failed to create a SCIM group due to plan restriction. Upgrade plan to create a SCIM group." + }); + const org = await orgDAL.findById(orgId); + if (!org) { + throw new ScimRequestError({ + detail: "Organization Not Found", + status: 404 + }); + } + if (!org.scimEnabled) throw new ScimRequestError({ detail: "SCIM is disabled for the organization", status: 403 }); - const group = await groupDAL.create({ - name: displayName, - slug: slugify(`${displayName}-${alphaNumericNanoId(4)}`), - orgId, - role: OrgMembershipRole.NoAccess + const newGroup = await groupDAL.transaction(async (tx) => { + const group = await groupDAL.create( + { + name: displayName, + slug: slugify(`${displayName}-${alphaNumericNanoId(4)}`), + orgId, + role: OrgMembershipRole.NoAccess + }, + tx + ); + + if (members && members.length) { + const newMembers = await addUsersToGroupByUserIds({ + group, + userIds: members.map((member) => member.value), + userDAL, + userGroupMembershipDAL, + orgDAL, + groupProjectDAL, + pendingGroupAdditionDAL, + projectKeyDAL, + projectDAL, + projectBotDAL, + tx + }); + + return { group, newMembers }; + } + + return { group, newMembers: [] }; }); return buildScimGroup({ - groupId: group.id, - name: group.name, - members: [] + groupId: newGroup.group.id, + name: newGroup.group.name, + members: newGroup.newMembers.map((member) => ({ + value: member.id, + display: `${member.firstName} ${member.lastName}` + })) }); }; const getScimGroup = async ({ groupId, orgId }: TGetScimGroupDTO) => { + const plan = await licenseService.getPlan(orgId); + if (!plan.groups) + throw new BadRequestError({ + message: "Failed to get SCIM group due to plan restriction. Upgrade plan to get SCIM group." + }); + const group = await groupDAL.findOne({ id: groupId, orgId @@ -536,6 +614,7 @@ export const scimServiceFactory = ({ }); } + // TODO: update to include pending group additions const users = await groupDAL.findAllGroupMembers({ orgId: group.orgId, groupId: group.id @@ -553,35 +632,130 @@ export const scimServiceFactory = ({ }); }; - const updateScimGroupNamePut = async ({ groupId, orgId, displayName }: TUpdateScimGroupNamePutDTO) => { - const [group] = await groupDAL.update( - { - id: groupId, - orgId - }, - { - name: displayName - } - ); + const updateScimGroupNamePut = async ({ groupId, orgId, displayName, members }: TUpdateScimGroupNamePutDTO) => { + console.log("updateScimGroupNamePut args: ", { + groupId, + orgId, + displayName, + members + }); - if (!group) { + const plan = await licenseService.getPlan(orgId); + if (!plan.groups) + throw new BadRequestError({ + message: "Failed to update SCIM group due to plan restriction. Upgrade plan to update SCIM group." + }); + + const org = await orgDAL.findById(orgId); + if (!org) { throw new ScimRequestError({ - detail: "Group Not Found", + detail: "Organization Not Found", status: 404 }); } + if (!org.scimEnabled) + throw new ScimRequestError({ + detail: "SCIM is disabled for the organization", + status: 403 + }); + + const updatedGroup = await groupDAL.transaction(async (tx) => { + const [group] = await groupDAL.update( + { + id: groupId, + orgId + }, + { + name: displayName + } + ); + + if (!group) { + throw new ScimRequestError({ + detail: "Group Not Found", + status: 404 + }); + } + + if (members) { + const membersIdsSet = new Set(members.map((member) => member.value)); + + const directMemberUserIds = ( + await userGroupMembershipDAL.find({ + groupId: group.id + }) + ).map((membership) => membership.userId); + + const pendingGroupAdditionsUserIds = ( + await pendingGroupAdditionDAL.find({ + groupId: group.id + }) + ).map((pendingGroupAddition) => pendingGroupAddition.userId); + + const allMembersUserIds = directMemberUserIds.concat(pendingGroupAdditionsUserIds); + const allMembersUserIdsSet = new Set(allMembersUserIds); + + const toAddUserIds = members.filter((member) => !allMembersUserIdsSet.has(member.value)); + const toRemoveUserIds = allMembersUserIds.filter((userId) => !membersIdsSet.has(userId)); + + if (toAddUserIds.length) { + await addUsersToGroupByUserIds({ + group, + userIds: toAddUserIds.map((member) => member.value), + userDAL, + userGroupMembershipDAL, + orgDAL, + groupProjectDAL, + pendingGroupAdditionDAL, + projectKeyDAL, + projectDAL, + projectBotDAL, + tx + }); + } + + if (toRemoveUserIds.length) { + await removeUsersFromGroupByUserIds({ + group, + userIds: toRemoveUserIds, + userDAL, + userGroupMembershipDAL, + groupProjectDAL, + pendingGroupAdditionDAL, + projectKeyDAL, + tx + }); + } + } + + return group; + }); + return buildScimGroup({ - groupId: group.id, - name: group.name, - members: [] + groupId: updatedGroup.id, + name: updatedGroup.name, + members }); }; // TODO: add support for add/remove op const updateScimGroupNamePatch = async ({ groupId, orgId, operations }: TUpdateScimGroupNamePatchDTO) => { + const plan = await licenseService.getPlan(orgId); + if (!plan.groups) + throw new BadRequestError({ + message: "Failed to update SCIM group due to plan restriction. Upgrade plan to update SCIM group." + }); + const org = await orgDAL.findById(orgId); + if (!org) { + throw new ScimRequestError({ + detail: "Organization Not Found", + status: 404 + }); + } + if (!org.scimEnabled) throw new ScimRequestError({ detail: "SCIM is disabled for the organization", @@ -635,6 +809,26 @@ export const scimServiceFactory = ({ }; const deleteScimGroup = async ({ groupId, orgId }: TDeleteScimGroupDTO) => { + const plan = await licenseService.getPlan(orgId); + if (!plan.groups) + throw new BadRequestError({ + message: "Failed to delete SCIM group due to plan restriction. Upgrade plan to delete SCIM group." + }); + + const org = await orgDAL.findById(orgId); + if (!org) { + throw new ScimRequestError({ + detail: "Organization Not Found", + status: 404 + }); + } + + if (!org.scimEnabled) + throw new ScimRequestError({ + detail: "SCIM is disabled for the organization", + status: 403 + }); + const [group] = await groupDAL.delete({ id: groupId, orgId diff --git a/backend/src/ee/services/scim/scim-types.ts b/backend/src/ee/services/scim/scim-types.ts index fc5df0b2e..73d0ebe78 100644 --- a/backend/src/ee/services/scim/scim-types.ts +++ b/backend/src/ee/services/scim/scim-types.ts @@ -81,6 +81,11 @@ export type TListScimGroups = { export type TCreateScimGroupDTO = { displayName: string; orgId: string; + members?: { + // TODO: account for members with value and display (is this optional?) + value: string; + display: string; + }[]; }; export type TGetScimGroupDTO = { @@ -92,6 +97,10 @@ export type TUpdateScimGroupNamePutDTO = { groupId: string; orgId: string; displayName: string; + members: { + value: string; + display: string; + }[]; }; export type TUpdateScimGroupNamePatchDTO = { diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts index 5d77c340b..7d2a8fd93 100644 --- a/backend/src/server/routes/index.ts +++ b/backend/src/server/routes/index.ts @@ -13,6 +13,7 @@ import { dynamicSecretLeaseQueueServiceFactory } from "@app/ee/services/dynamic- import { dynamicSecretLeaseServiceFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-service"; import { groupDALFactory } from "@app/ee/services/group/group-dal"; import { groupServiceFactory } from "@app/ee/services/group/group-service"; +import { pendingGroupAdditionDALFactory } from "@app/ee/services/group/pending-group-addition-dal"; import { userGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal"; import { identityProjectAdditionalPrivilegeDALFactory } from "@app/ee/services/identity-project-additional-privilege/identity-project-additional-privilege-dal"; import { identityProjectAdditionalPrivilegeServiceFactory } from "@app/ee/services/identity-project-additional-privilege/identity-project-additional-privilege-service"; @@ -217,6 +218,7 @@ export const registerRoutes = async ( const groupProjectDAL = groupProjectDALFactory(db); const groupProjectMembershipRoleDAL = groupProjectMembershipRoleDALFactory(db); const userGroupMembershipDAL = userGroupMembershipDALFactory(db); + const pendingGroupAdditionDAL = pendingGroupAdditionDALFactory(db); const secretScanningDAL = secretScanningDALFactory(db); const licenseDAL = licenseDALFactory(db); const dynamicSecretDAL = dynamicSecretDALFactory(db); @@ -268,6 +270,7 @@ export const registerRoutes = async ( projectDAL, projectBotDAL, projectKeyDAL, + pendingGroupAdditionDAL, permissionService, licenseService }); @@ -290,6 +293,11 @@ export const registerRoutes = async ( projectDAL, projectMembershipDAL, groupDAL, + groupProjectDAL, + userGroupMembershipDAL, + projectKeyDAL, + projectBotDAL, + pendingGroupAdditionDAL, permissionService, smtpService }); @@ -344,6 +352,12 @@ export const registerRoutes = async ( smtpService, authDAL, userDAL, + pendingGroupAdditionDAL, + userGroupMembershipDAL, + projectKeyDAL, + projectDAL, + projectBotDAL, + groupProjectDAL, orgDAL, orgService, licenseService diff --git a/backend/src/services/auth/auth-signup-service.ts b/backend/src/services/auth/auth-signup-service.ts index 3db935769..c2f024290 100644 --- a/backend/src/services/auth/auth-signup-service.ts +++ b/backend/src/services/auth/auth-signup-service.ts @@ -1,10 +1,17 @@ import jwt from "jsonwebtoken"; import { OrgMembershipStatus } from "@app/db/schemas"; +import { convertPendingGroupAdditionsToGroupMemberships } from "@app/ee/services/group/group-fns"; +import { TPendingGroupAdditionDALFactory } from "@app/ee/services/group/pending-group-addition-dal"; +import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal"; import { TLicenseServiceFactory } from "@app/ee/services/license/license-service"; import { getConfig } from "@app/lib/config/env"; import { BadRequestError } from "@app/lib/errors"; import { isDisposableEmail } from "@app/lib/validator"; +import { TGroupProjectDALFactory } from "@app/services/group-project/group-project-dal"; +import { TProjectDALFactory } from "@app/services/project/project-dal"; +import { TProjectBotDALFactory } from "@app/services/project-bot/project-bot-dal"; +import { TProjectKeyDALFactory } from "@app/services/project-key/project-key-dal"; import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service"; import { TokenType } from "../auth-token/auth-token-types"; @@ -20,6 +27,12 @@ import { AuthMethod, AuthTokenType } from "./auth-type"; type TAuthSignupDep = { authDAL: TAuthDALFactory; userDAL: TUserDALFactory; + pendingGroupAdditionDAL: Pick; + userGroupMembershipDAL: Pick; + projectKeyDAL: Pick; + projectDAL: Pick; + projectBotDAL: Pick; + groupProjectDAL: Pick; orgService: Pick; orgDAL: TOrgDALFactory; tokenService: TAuthTokenServiceFactory; @@ -31,6 +44,12 @@ export type TAuthSignupFactory = ReturnType; export const authSignupServiceFactory = ({ authDAL, userDAL, + pendingGroupAdditionDAL, + userGroupMembershipDAL, + projectKeyDAL, + projectDAL, + projectBotDAL, + groupProjectDAL, tokenService, smtpService, orgService, @@ -168,6 +187,20 @@ export const authSignupServiceFactory = ({ const uniqueOrgId = [...new Set(updatedMembersips.map(({ orgId }) => orgId))]; await Promise.allSettled(uniqueOrgId.map((orgId) => licenseService.updateSubscriptionOrgMemberCount(orgId))); + console.log("conv A"); + await convertPendingGroupAdditionsToGroupMemberships({ + userIds: [user.id], + userDAL, + pendingGroupAdditionDAL, + userGroupMembershipDAL, + orgDAL, + groupProjectDAL, + projectKeyDAL, + projectDAL, + projectBotDAL + }); + console.log("conv B"); + const tokenSession = await tokenService.getUserTokenSession({ userAgent, ip, @@ -225,13 +258,16 @@ export const authSignupServiceFactory = ({ encryptedPrivateKeyTag, authorization }: TCompleteAccountInviteDTO) => { + console.log("conv 0"); const user = await userDAL.findUserByUsername(email); if (!user || (user && user.isAccepted)) { throw new Error("Failed to complete account for complete user"); } + console.log("conv 1"); validateSignUpAuthorization(authorization, user.id); + console.log("conv 2"); const [orgMembership] = await orgDAL.findMembership({ inviteEmail: email, status: OrgMembershipStatus.Invited @@ -242,9 +278,12 @@ export const authSignupServiceFactory = ({ name: "complete account invite" }); + console.log("conv 3"); const updateduser = await authDAL.transaction(async (tx) => { + console.log("conv 4"); const us = await userDAL.updateById(user.id, { firstName, lastName, isAccepted: true }, tx); if (!us) throw new Error("User not found"); + console.log("conv 5"); const userEncKey = await userDAL.upsertUserEncryptionKey( us.id, { @@ -261,15 +300,33 @@ export const authSignupServiceFactory = ({ }, tx ); + console.log("conv 6"); const updatedMembersips = await orgDAL.updateMembership( { inviteEmail: email, status: OrgMembershipStatus.Invited }, { userId: us.id, status: OrgMembershipStatus.Accepted }, tx ); + console.log("conv 7"); const uniqueOrgId = [...new Set(updatedMembersips.map(({ orgId }) => orgId))]; + console.log("conv 8"); await Promise.allSettled(uniqueOrgId.map((orgId) => licenseService.updateSubscriptionOrgMemberCount(orgId))); + console.log("conv AA"); + await convertPendingGroupAdditionsToGroupMemberships({ + userIds: [user.id], + userDAL, + pendingGroupAdditionDAL, + userGroupMembershipDAL, + orgDAL, + groupProjectDAL, + projectKeyDAL, + projectDAL, + projectBotDAL, + tx + }); + console.log("conv BB"); + return { info: us, key: userEncKey }; }); diff --git a/backend/src/services/project/project-dal.ts b/backend/src/services/project/project-dal.ts index 42cc54393..a4ec99157 100644 --- a/backend/src/services/project/project-dal.ts +++ b/backend/src/services/project/project-dal.ts @@ -81,9 +81,9 @@ export const projectDALFactory = (db: TDbClient) => { } }; - const findProjectGhostUser = async (projectId: string) => { + const findProjectGhostUser = async (projectId: string, tx?: Knex) => { try { - const ghostUser = await db(TableName.ProjectMembership) + const ghostUser = await (tx || db)(TableName.ProjectMembership) .where({ projectId }) .join(TableName.Users, `${TableName.ProjectMembership}.userId`, `${TableName.Users}.id`) .select(selectAllTableCols(TableName.Users)) diff --git a/backend/src/services/user/user-dal.ts b/backend/src/services/user/user-dal.ts index 425e8215c..4c61c3174 100644 --- a/backend/src/services/user/user-dal.ts +++ b/backend/src/services/user/user-dal.ts @@ -34,6 +34,19 @@ export const userDALFactory = (db: TDbClient) => { } }; + const findUserEncKeyByUsernameBatch = async ({ usernames }: { usernames: string[] }, tx?: Knex) => { + try { + return await (tx || db)(TableName.Users) + .where({ + isGhost: false + }) + .whereIn("username", usernames) + .join(TableName.UserEncryptionKey, `${TableName.Users}.id`, `${TableName.UserEncryptionKey}.userId`); + } catch (error) { + throw new DatabaseError({ error, name: "Find user enc by email batch" }); + } + }; + const findUserEncKeyByUserId = async (userId: string) => { try { const user = await db(TableName.Users) @@ -123,6 +136,7 @@ export const userDALFactory = (db: TDbClient) => { ...userOrm, findUserByUsername, findUserEncKeyByUsername, + findUserEncKeyByUsernameBatch, // TODO: if successful, replace findUserEncKeyByUsername with this findUserEncKeyByUserId, updateUserEncryptionByUserId, findUserByProjectMembershipId, diff --git a/frontend/src/views/Org/MembersPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupMembersModal.tsx b/frontend/src/views/Org/MembersPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupMembersModal.tsx index 8c15643b7..d9aa4c3e0 100644 --- a/frontend/src/views/Org/MembersPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupMembersModal.tsx +++ b/frontend/src/views/Org/MembersPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupMembersModal.tsx @@ -1,32 +1,27 @@ import { useState } from "react"; -import { faMagnifyingGlass,faUsers } from "@fortawesome/free-solid-svg-icons"; +import { faMagnifyingGlass, faUsers } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { createNotification } from "@app/components/notifications"; import { OrgPermissionCan } from "@app/components/permissions"; import { - Button, - EmptyState, - Input, - Modal, - ModalContent, - Pagination, - Table, - TableContainer, - TableSkeleton, - TBody, - Td, - Th, - THead, - Tr} from "@app/components/v2"; -import { - OrgPermissionActions, - OrgPermissionSubjects -} from "@app/context"; -import { - useAddUserToGroup, - useListGroupUsers, - useRemoveUserFromGroup} from "@app/hooks/api"; + Button, + EmptyState, + Input, + Modal, + ModalContent, + Pagination, + Table, + TableContainer, + TableSkeleton, + TBody, + Td, + Th, + THead, + Tr +} from "@app/components/v2"; +import { OrgPermissionActions, OrgPermissionSubjects } from "@app/context"; +import { useAddUserToGroup, useListGroupUsers, useRemoveUserFromGroup } from "@app/hooks/api"; import { UsePopUpState } from "@app/hooks/usePopUp"; type Props = { @@ -34,136 +29,127 @@ type Props = { handlePopUpToggle: (popUpName: keyof UsePopUpState<["groupMembers"]>, state?: boolean) => void; }; -export const OrgGroupMembersModal = ({ - popUp, - handlePopUpToggle -}: Props) => { - const [page, setPage] = useState(1); - const [perPage, setPerPage] = useState(10); - const [searchMemberFilter, setSearchMemberFilter] = useState(""); - - const popUpData = popUp?.groupMembers?.data as { - slug: string; - }; - - const { data, isLoading } = useListGroupUsers({ - groupSlug: popUpData?.slug, - offset: (page - 1) * perPage, - limit: perPage, - username: searchMemberFilter - }); - - const { mutateAsync: assignMutateAsync } = useAddUserToGroup(); - const { mutateAsync: unassignMutateAsync } = useRemoveUserFromGroup(); - - const handleAssignment = async (username: string, assign: boolean) => { - try { - if (!popUpData?.slug) return; - - if (assign) { - await assignMutateAsync({ - username, - slug: popUpData.slug - }); - } else { - await unassignMutateAsync({ - username, - slug: popUpData.slug - }); - } +export const OrgGroupMembersModal = ({ popUp, handlePopUpToggle }: Props) => { + const [page, setPage] = useState(1); + const [perPage, setPerPage] = useState(10); + const [searchMemberFilter, setSearchMemberFilter] = useState(""); - createNotification({ - text: `Successfully ${assign ? "assigned" : "removed "} user ${assign ? "to" : "from"} group`, - type: "success" - }); - } catch (err) { - createNotification({ - text: `Failed to ${assign ? "assigned" : "remove"} user ${assign ? "to" : "from"} group`, - type: "error" - }); - } + const popUpData = popUp?.groupMembers?.data as { + slug: string; + }; + + const { data, isLoading } = useListGroupUsers({ + groupSlug: popUpData?.slug, + offset: (page - 1) * perPage, + limit: perPage, + username: searchMemberFilter + }); + + const { mutateAsync: assignMutateAsync } = useAddUserToGroup(); + const { mutateAsync: unassignMutateAsync } = useRemoveUserFromGroup(); + + const handleAssignment = async (username: string, assign: boolean) => { + try { + if (!popUpData?.slug) return; + + if (assign) { + await assignMutateAsync({ + username, + slug: popUpData.slug + }); + } else { + await unassignMutateAsync({ + username, + slug: popUpData.slug + }); + } + + createNotification({ + text: `Successfully ${assign ? "assigned" : "removed "} user ${ + assign ? "to" : "from" + } group`, + type: "success" + }); + } catch (err) { + createNotification({ + text: `Failed to ${assign ? "assigned" : "remove"} user ${assign ? "to" : "from"} group`, + type: "error" + }); } - - return ( - { - handlePopUpToggle("groupMembers", isOpen); - }} - > - - setSearchMemberFilter(e.target.value)} - leftIcon={} - placeholder="Search members..." - /> - - - - - - - - - {isLoading && } - {!isLoading && data?.users?.map(({ - id, - firstName, - lastName, - username, - isPartOfGroup - }) => { - return ( - - - - - ); - })} - -
User -
-

{`${firstName} ${lastName}`}

-

{username}

-
- - {(isAllowed) => { - return ( - - ); - }} - -
- {!isLoading && data?.totalCount !== undefined && ( - setPage(newPage)} - onChangePerPage={(newPerPage) => setPerPage(newPerPage)} - /> - )} - {!isLoading && !data?.users?.length && ( - - )} -
-
-
- ); -} \ No newline at end of file + }; + + return ( + { + handlePopUpToggle("groupMembers", isOpen); + }} + > + + setSearchMemberFilter(e.target.value)} + leftIcon={} + placeholder="Search members..." + /> + + + + + + + + + {isLoading && } + {!isLoading && + data?.users?.map(({ id, firstName, lastName, username, isPartOfGroup }) => { + return ( + + + + + ); + })} + +
User +
+

{`${firstName ?? "-"} ${lastName ?? ""}`}

+

{username}

+
+ + {(isAllowed) => { + return ( + + ); + }} + +
+ {!isLoading && data?.totalCount !== undefined && ( + setPage(newPage)} + onChangePerPage={(newPerPage) => setPerPage(newPerPage)} + /> + )} + {!isLoading && !data?.users?.length && ( + + )} +
+
+
+ ); +}; From 6e3d5a8c7cb05883c9f6ea9fc21d649d8e89203e Mon Sep 17 00:00:00 2001 From: Tuan Dang Date: Thu, 18 Apr 2024 13:51:47 -0700 Subject: [PATCH 20/99] Remove print statements, cleanup --- backend/src/ee/routes/v1/scim-router.ts | 10 ---------- backend/src/ee/services/group/group-fns.ts | 3 --- backend/src/ee/services/license/licence-fns.ts | 6 +++--- backend/src/ee/services/license/license-types.ts | 6 +++--- backend/src/ee/services/scim/scim-service.ts | 7 ------- backend/src/services/auth/auth-signup-service.ts | 13 ------------- backend/src/services/org/org-service.ts | 2 +- 7 files changed, 7 insertions(+), 40 deletions(-) diff --git a/backend/src/ee/routes/v1/scim-router.ts b/backend/src/ee/routes/v1/scim-router.ts index 67209e774..dea0e3d70 100644 --- a/backend/src/ee/routes/v1/scim-router.ts +++ b/backend/src/ee/routes/v1/scim-router.ts @@ -192,7 +192,6 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { }, onRequest: verifyAuth([AuthMode.SCIM_TOKEN]), handler: async (req) => { - console.log(`GET /Users/${req.params.userId}`); const user = await req.server.services.scim.getScimUser({ userId: req.params.userId, orgId: req.permission.orgId @@ -247,7 +246,6 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { }, onRequest: verifyAuth([AuthMode.SCIM_TOKEN]), handler: async (req) => { - console.log(`POST /Users req.body: `, req.body); const primaryEmail = req.body.emails?.find((email) => email.primary)?.value; const user = await req.server.services.scim.createScimUser({ @@ -275,7 +273,6 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { }, onRequest: verifyAuth([AuthMode.SCIM_TOKEN]), handler: async (req) => { - console.log(`DELETE /Users/${req.params.userId}`); const user = await req.server.services.scim.deleteScimUser({ userId: req.params.userId, orgId: req.permission.orgId @@ -322,7 +319,6 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { }, onRequest: verifyAuth([AuthMode.SCIM_TOKEN]), handler: async (req) => { - console.log(`POST /Groups req.body: `, req.body); const group = await req.server.services.scim.createScimGroup({ orgId: req.permission.orgId, ...req.body @@ -363,7 +359,6 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { }, onRequest: verifyAuth([AuthMode.SCIM_TOKEN]), handler: async (req) => { - console.log(`GET /Groups req.query: `, req.query); const groups = await req.server.services.scim.listScimGroups({ orgId: req.permission.orgId, offset: req.query.startIndex, @@ -400,7 +395,6 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { }, onRequest: verifyAuth([AuthMode.SCIM_TOKEN]), handler: async (req) => { - console.log(`GET /Groups/${req.params.groupId}`); const group = await req.server.services.scim.getScimGroup({ groupId: req.params.groupId, orgId: req.permission.orgId @@ -446,7 +440,6 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { }, onRequest: verifyAuth([AuthMode.SCIM_TOKEN]), handler: async (req) => { - console.log(`PUT /Groups/${req.params.groupId} req.body: `, req.body); const group = await req.server.services.scim.updateScimGroupNamePut({ groupId: req.params.groupId, orgId: req.permission.orgId, @@ -508,7 +501,6 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { }, onRequest: verifyAuth([AuthMode.SCIM_TOKEN]), handler: async (req) => { - console.log(`PATCH /Groups/:${req.params.groupId} req.body: `, req.body); const group = await req.server.services.scim.updateScimGroupNamePatch({ groupId: req.params.groupId, orgId: req.permission.orgId, @@ -532,7 +524,6 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { }, onRequest: verifyAuth([AuthMode.SCIM_TOKEN]), handler: async (req) => { - console.log(`DELETE /Groups/:${req.params.groupId}`); const group = await req.server.services.scim.deleteScimGroup({ groupId: req.params.groupId, orgId: req.permission.orgId @@ -583,7 +574,6 @@ export const registerScimRouter = async (server: FastifyZodProvider) => { }, onRequest: verifyAuth([AuthMode.SCIM_TOKEN]), handler: async (req) => { - console.log(`PUT /Users/:${req.params.userId} req.body: `, req.body); const user = await req.server.services.scim.replaceScimUser({ userId: req.params.userId, orgId: req.permission.orgId, diff --git a/backend/src/ee/services/group/group-fns.ts b/backend/src/ee/services/group/group-fns.ts index ae488edcf..07152fe36 100644 --- a/backend/src/ee/services/group/group-fns.ts +++ b/backend/src/ee/services/group/group-fns.ts @@ -658,9 +658,6 @@ export const removeUsersFromGroupByUserIds = async ({ } }); - console.log("removeUsersFromGroupByUserIds membersToRemoveFromGroupDirectly: ", membersToRemoveFromGroupDirectly); - console.log("removeUsersFromGroupByUserIds membersToRemoveFromGroupPending: ", membersToRemoveFromGroupPending); - let removedUsers: TUsers[] = []; if (membersToRemoveFromGroupDirectly.length) { diff --git a/backend/src/ee/services/license/licence-fns.ts b/backend/src/ee/services/license/licence-fns.ts index 17a538881..8a4de57f1 100644 --- a/backend/src/ee/services/license/licence-fns.ts +++ b/backend/src/ee/services/license/licence-fns.ts @@ -24,10 +24,10 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({ customAlerts: false, auditLogs: false, auditLogsRetentionDays: 0, - samlSSO: true, - scim: true, + samlSSO: false, + scim: false, ldap: false, - groups: true, + groups: false, status: null, trial_end: null, has_used_trial: true, diff --git a/backend/src/ee/services/license/license-types.ts b/backend/src/ee/services/license/license-types.ts index efc1c18dd..1cea39a83 100644 --- a/backend/src/ee/services/license/license-types.ts +++ b/backend/src/ee/services/license/license-types.ts @@ -40,10 +40,10 @@ export type TFeatureSet = { customAlerts: false; auditLogs: false; auditLogsRetentionDays: 0; - samlSSO: true; - scim: true; + samlSSO: false; + scim: false; ldap: false; - groups: true; + groups: false; status: null; trial_end: null; has_used_trial: true; diff --git a/backend/src/ee/services/scim/scim-service.ts b/backend/src/ee/services/scim/scim-service.ts index 588159acf..bc7fd2528 100644 --- a/backend/src/ee/services/scim/scim-service.ts +++ b/backend/src/ee/services/scim/scim-service.ts @@ -633,13 +633,6 @@ export const scimServiceFactory = ({ }; const updateScimGroupNamePut = async ({ groupId, orgId, displayName, members }: TUpdateScimGroupNamePutDTO) => { - console.log("updateScimGroupNamePut args: ", { - groupId, - orgId, - displayName, - members - }); - const plan = await licenseService.getPlan(orgId); if (!plan.groups) throw new BadRequestError({ diff --git a/backend/src/services/auth/auth-signup-service.ts b/backend/src/services/auth/auth-signup-service.ts index c2f024290..be80c4c40 100644 --- a/backend/src/services/auth/auth-signup-service.ts +++ b/backend/src/services/auth/auth-signup-service.ts @@ -187,7 +187,6 @@ export const authSignupServiceFactory = ({ const uniqueOrgId = [...new Set(updatedMembersips.map(({ orgId }) => orgId))]; await Promise.allSettled(uniqueOrgId.map((orgId) => licenseService.updateSubscriptionOrgMemberCount(orgId))); - console.log("conv A"); await convertPendingGroupAdditionsToGroupMemberships({ userIds: [user.id], userDAL, @@ -199,7 +198,6 @@ export const authSignupServiceFactory = ({ projectDAL, projectBotDAL }); - console.log("conv B"); const tokenSession = await tokenService.getUserTokenSession({ userAgent, @@ -258,16 +256,13 @@ export const authSignupServiceFactory = ({ encryptedPrivateKeyTag, authorization }: TCompleteAccountInviteDTO) => { - console.log("conv 0"); const user = await userDAL.findUserByUsername(email); if (!user || (user && user.isAccepted)) { throw new Error("Failed to complete account for complete user"); } - console.log("conv 1"); validateSignUpAuthorization(authorization, user.id); - console.log("conv 2"); const [orgMembership] = await orgDAL.findMembership({ inviteEmail: email, status: OrgMembershipStatus.Invited @@ -278,12 +273,9 @@ export const authSignupServiceFactory = ({ name: "complete account invite" }); - console.log("conv 3"); const updateduser = await authDAL.transaction(async (tx) => { - console.log("conv 4"); const us = await userDAL.updateById(user.id, { firstName, lastName, isAccepted: true }, tx); if (!us) throw new Error("User not found"); - console.log("conv 5"); const userEncKey = await userDAL.upsertUserEncryptionKey( us.id, { @@ -300,19 +292,15 @@ export const authSignupServiceFactory = ({ }, tx ); - console.log("conv 6"); const updatedMembersips = await orgDAL.updateMembership( { inviteEmail: email, status: OrgMembershipStatus.Invited }, { userId: us.id, status: OrgMembershipStatus.Accepted }, tx ); - console.log("conv 7"); const uniqueOrgId = [...new Set(updatedMembersips.map(({ orgId }) => orgId))]; - console.log("conv 8"); await Promise.allSettled(uniqueOrgId.map((orgId) => licenseService.updateSubscriptionOrgMemberCount(orgId))); - console.log("conv AA"); await convertPendingGroupAdditionsToGroupMemberships({ userIds: [user.id], userDAL, @@ -325,7 +313,6 @@ export const authSignupServiceFactory = ({ projectBotDAL, tx }); - console.log("conv BB"); return { info: us, key: userEncKey }; }); diff --git a/backend/src/services/org/org-service.ts b/backend/src/services/org/org-service.ts index c03fe1748..996a08c4d 100644 --- a/backend/src/services/org/org-service.ts +++ b/backend/src/services/org/org-service.ts @@ -248,7 +248,7 @@ export const orgServiceFactory = ({ ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Scim); } - if (authEnforced || scimEnabled) { + if (authEnforced) { const samlCfg = await samlConfigDAL.findEnforceableSamlCfg(orgId); if (!samlCfg) throw new BadRequestError({ From e1407cc09317251bcabec1936a8ad1042ef573f6 Mon Sep 17 00:00:00 2001 From: Tuan Dang Date: Thu, 18 Apr 2024 14:14:08 -0700 Subject: [PATCH 21/99] Add comments for group-fns --- backend/src/ee/services/group/group-fns.ts | 174 ++++++++++++--------- 1 file changed, 104 insertions(+), 70 deletions(-) diff --git a/backend/src/ee/services/group/group-fns.ts b/backend/src/ee/services/group/group-fns.ts index 07152fe36..383b44a6e 100644 --- a/backend/src/ee/services/group/group-fns.ts +++ b/backend/src/ee/services/group/group-fns.ts @@ -14,13 +14,11 @@ import { TRemoveUsersFromPendingGroupAdditions } from "./group-types"; -// TODO: write docstrings - /** - * Add users with usernames [usernames] to group [group] - * @param {group} group - group to add user to + * Add users with usernames [usernames] to group [group] directly. + * - Users must have finished completing their account and have private key(s). + * @param {group} group - group to add user(s) to * @param {string[]} usernames - username(s) of user(s) to add to group - * @returns {Promise} - user that was added to group */ export const addUsersToGroupDirectly = async ({ group, @@ -206,6 +204,12 @@ export const addUsersToGroupDirectly = async ({ }); }; +/** + * Add users with user ids [userIds] to group [group] via pending group additions. + * - Users must have not finished completing their accounts (i.e. they don't have private key(s) yet). + * @param {group} group - group to add user(s) to + * @param {string[]} userIds - id(s) of user(s) to add to group + */ export const addUsersToPendingGroupAdditions = async ({ group, userIds, @@ -299,6 +303,13 @@ export const addUsersToPendingGroupAdditions = async ({ }); }; +/** + * Add users with user ids [userIds] to group [group]. + * - Users may or may not have finished completing their accounts; this function will + * handle both adding users to groups directly and via pending group additions. + * @param {group} group - group to add user(s) to + * @param {string[]} userIds - id(s) of user(s) to add to group + */ export const addUsersToGroupByUserIds = async ({ group, userIds, @@ -386,6 +397,12 @@ export const addUsersToGroupByUserIds = async ({ }); }; +/** + * Remove users with user ids [userIds] from group [group]. + * - Users must be directly added to the group. + * @param {group} group - group to remove user(s) from + * @param {string[]} userIds - id(s) of user(s) to remove from group + */ export const removeUsersFromGroupDirectly = async ({ group, userIds, @@ -485,6 +502,12 @@ export const removeUsersFromGroupDirectly = async ({ }); }; +/** + * Remove users with user ids [userIds] from group [group] via pending group additions. + * - Users must have pending group additions to the group. + * @param {group} group - group to remove user(s) from + * @param {string[]} userIds - id(s) of user(s) to remove from group + */ export const removeUsersFromPendingGroupAdditions = async ({ group, userIds, @@ -552,71 +575,13 @@ export const removeUsersFromPendingGroupAdditions = async ({ }); }; -export const convertPendingGroupAdditionsToGroupMemberships = async ({ - userIds, - userDAL, - pendingGroupAdditionDAL, - userGroupMembershipDAL, - orgDAL, - groupProjectDAL, - projectKeyDAL, - projectDAL, - projectBotDAL, - tx: outerTx -}: TConvertPendingGroupAdditionsToGroupMemberships) => { - const processConversion = async (tx: Knex) => { - const users = await userDAL.find( - { - $in: { - id: userIds - } - }, - { tx } - ); - - const usersUserIdsSet = new Set(users.map((u) => u.id)); - userIds.forEach((userId) => { - if (!usersUserIdsSet.has(userId)) { - throw new BadRequestError({ - message: `Failed to find user with id ${userId}` - }); - } - }); - - users.forEach((user) => { - if (!user.isAccepted) { - throw new BadRequestError({ - message: `Failed to convert pending group additions to group memberships for user ${user.username} because they have not confirmed their account` - }); - } - }); - - const pendingGroupAdditions = await pendingGroupAdditionDAL.deletePendingGroupAdditionsByUserIds(userIds, tx); - - for await (const pendingGroupAddition of pendingGroupAdditions) { - await addUsersToGroupDirectly({ - group: pendingGroupAddition.group, - usernames: [pendingGroupAddition.user.username], - userDAL, - userGroupMembershipDAL, - orgDAL, - groupProjectDAL, - projectKeyDAL, - projectDAL, - projectBotDAL, - tx - }); - } - }; - - if (outerTx) { - return processConversion(outerTx); - } - return userDAL.transaction(async (tx) => { - await processConversion(tx); - }); -}; - +/** + * Remove users with user ids [userIds] from group [group]. + * - Users may be part of the group directly or via pending group additions; + * this function will handle both cases. + * @param {group} group - group to remove user(s) from + * @param {string[]} userIds - id(s) of user(s) to remove from group + */ export const removeUsersFromGroupByUserIds = async ({ group, userIds, @@ -696,3 +661,72 @@ export const removeUsersFromGroupByUserIds = async ({ return processRemoval(tx); }); }; + +/** + * Convert pending group additions for users with ids [userIds] to group memberships. + * @param {string[]} userIds - id(s) of user(s) to try to convert pending group additions to group memberships + */ +export const convertPendingGroupAdditionsToGroupMemberships = async ({ + userIds, + userDAL, + pendingGroupAdditionDAL, + userGroupMembershipDAL, + orgDAL, + groupProjectDAL, + projectKeyDAL, + projectDAL, + projectBotDAL, + tx: outerTx +}: TConvertPendingGroupAdditionsToGroupMemberships) => { + const processConversion = async (tx: Knex) => { + const users = await userDAL.find( + { + $in: { + id: userIds + } + }, + { tx } + ); + + const usersUserIdsSet = new Set(users.map((u) => u.id)); + userIds.forEach((userId) => { + if (!usersUserIdsSet.has(userId)) { + throw new BadRequestError({ + message: `Failed to find user with id ${userId}` + }); + } + }); + + users.forEach((user) => { + if (!user.isAccepted) { + throw new BadRequestError({ + message: `Failed to convert pending group additions to group memberships for user ${user.username} because they have not confirmed their account` + }); + } + }); + + const pendingGroupAdditions = await pendingGroupAdditionDAL.deletePendingGroupAdditionsByUserIds(userIds, tx); + + for await (const pendingGroupAddition of pendingGroupAdditions) { + await addUsersToGroupDirectly({ + group: pendingGroupAddition.group, + usernames: [pendingGroupAddition.user.username], + userDAL, + userGroupMembershipDAL, + orgDAL, + groupProjectDAL, + projectKeyDAL, + projectDAL, + projectBotDAL, + tx + }); + } + }; + + if (outerTx) { + return processConversion(outerTx); + } + return userDAL.transaction(async (tx) => { + await processConversion(tx); + }); +}; From 4050e56e60da308a0a09ca0c2f8535c1e6e0e8f2 Mon Sep 17 00:00:00 2001 From: Daniel Hougaard <62331820+DanielHougaard@users.noreply.github.com> Date: Thu, 18 Apr 2024 23:29:11 +0200 Subject: [PATCH 22/99] Feat: CLI Integration tests --- .../workflows/release_build_infisical_cli.yml | 112 +++++++++--------- .github/workflows/run-cli-tests.yml | 9 +- 2 files changed, 66 insertions(+), 55 deletions(-) diff --git a/.github/workflows/release_build_infisical_cli.yml b/.github/workflows/release_build_infisical_cli.yml index d01d56198..40137a455 100644 --- a/.github/workflows/release_build_infisical_cli.yml +++ b/.github/workflows/release_build_infisical_cli.yml @@ -1,60 +1,64 @@ name: Build and release CLI on: - push: - # run only against tags - tags: - - "infisical-cli/v*.*.*" + push: + # run only against tags + tags: + - "infisical-cli/v*.*.*" permissions: - contents: write - # packages: write - # issues: write - + contents: write + # packages: write + # issues: write jobs: - goreleaser: - runs-on: ubuntu-20.04 - steps: - - uses: actions/checkout@v3 - with: - fetch-depth: 0 - - name: 🐋 Login to Docker Hub - uses: docker/login-action@v2 - with: - username: ${{ secrets.DOCKERHUB_USERNAME }} - password: ${{ secrets.DOCKERHUB_TOKEN }} - - name: 🔧 Set up Docker Buildx - uses: docker/setup-buildx-action@v2 - - run: git fetch --force --tags - - run: echo "Ref name ${{github.ref_name}}" - - uses: actions/setup-go@v3 - with: - go-version: ">=1.19.3" - cache: true - cache-dependency-path: cli/go.sum - - name: libssl1.1 => libssl1.0-dev for OSXCross - run: | - echo 'deb http://security.ubuntu.com/ubuntu bionic-security main' | sudo tee -a /etc/apt/sources.list - sudo apt update && apt-cache policy libssl1.0-dev - sudo apt-get install libssl1.0-dev - - name: OSXCross for CGO Support - run: | - mkdir ../../osxcross - git clone https://github.com/plentico/osxcross-target.git ../../osxcross/target - - uses: goreleaser/goreleaser-action@v4 - with: - distribution: goreleaser-pro - version: latest - args: release --clean - env: - GITHUB_TOKEN: ${{ secrets.GO_RELEASER_GITHUB_TOKEN }} - POSTHOG_API_KEY_FOR_CLI: ${{ secrets.POSTHOG_API_KEY_FOR_CLI }} - FURY_TOKEN: ${{ secrets.FURYPUSHTOKEN }} - AUR_KEY: ${{ secrets.AUR_KEY }} - GORELEASER_KEY: ${{ secrets.GORELEASER_KEY }} - - uses: actions/setup-python@v4 - - run: pip install --upgrade cloudsmith-cli - - name: Publish to CloudSmith - run: sh cli/upload_to_cloudsmith.sh - env: - CLOUDSMITH_API_KEY: ${{ secrets.CLOUDSMITH_API_KEY }} + cli-integration-tests: + name: Run tests before deployment + uses: ./.github/workflows/run-cli-tests.yml + + goreleaser: + runs-on: ubuntu-20.04 + needs: [cli-integration-tests] + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + - name: 🐋 Login to Docker Hub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + - name: 🔧 Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - run: git fetch --force --tags + - run: echo "Ref name ${{github.ref_name}}" + - uses: actions/setup-go@v3 + with: + go-version: ">=1.19.3" + cache: true + cache-dependency-path: cli/go.sum + - name: libssl1.1 => libssl1.0-dev for OSXCross + run: | + echo 'deb http://security.ubuntu.com/ubuntu bionic-security main' | sudo tee -a /etc/apt/sources.list + sudo apt update && apt-cache policy libssl1.0-dev + sudo apt-get install libssl1.0-dev + - name: OSXCross for CGO Support + run: | + mkdir ../../osxcross + git clone https://github.com/plentico/osxcross-target.git ../../osxcross/target + - uses: goreleaser/goreleaser-action@v4 + with: + distribution: goreleaser-pro + version: latest + args: release --clean + env: + GITHUB_TOKEN: ${{ secrets.GO_RELEASER_GITHUB_TOKEN }} + POSTHOG_API_KEY_FOR_CLI: ${{ secrets.POSTHOG_API_KEY_FOR_CLI }} + FURY_TOKEN: ${{ secrets.FURYPUSHTOKEN }} + AUR_KEY: ${{ secrets.AUR_KEY }} + GORELEASER_KEY: ${{ secrets.GORELEASER_KEY }} + - uses: actions/setup-python@v4 + - run: pip install --upgrade cloudsmith-cli + - name: Publish to CloudSmith + run: sh cli/upload_to_cloudsmith.sh + env: + CLOUDSMITH_API_KEY: ${{ secrets.CLOUDSMITH_API_KEY }} diff --git a/.github/workflows/run-cli-tests.yml b/.github/workflows/run-cli-tests.yml index 1076228cc..9cd5d1519 100644 --- a/.github/workflows/run-cli-tests.yml +++ b/.github/workflows/run-cli-tests.yml @@ -1,5 +1,12 @@ name: Go CLI Tests -on: [push] # Test + +on: + pull_request: + types: [opened, synchronize] + paths: + - "cli/**" + + workflow_call: jobs: test: From 1dd451f2215845713eb25a7c4a6a2a45bfbc3fda Mon Sep 17 00:00:00 2001 From: Tuan Dang Date: Thu, 18 Apr 2024 14:54:02 -0700 Subject: [PATCH 23/99] Update groups count fn, type check --- backend/src/ee/services/group/group-dal.ts | 33 ------------------- .../src/ee/services/group/group-service.ts | 14 +++----- .../server/routes/v2/organization-router.ts | 1 - backend/src/services/org/org-dal.ts | 20 +++++++++++ .../OrgGroupsSection/OrgGroupModal.tsx | 5 ++- 5 files changed, 28 insertions(+), 45 deletions(-) diff --git a/backend/src/ee/services/group/group-dal.ts b/backend/src/ee/services/group/group-dal.ts index 3392bad32..26a5d688e 100644 --- a/backend/src/ee/services/group/group-dal.ts +++ b/backend/src/ee/services/group/group-dal.ts @@ -59,37 +59,6 @@ export const groupDALFactory = (db: TDbClient) => { } }; - const countGroupMembers = async ({ orgId, groupId }: { orgId: string; groupId: string }) => { - try { - interface CountResult { - count: string; - } - - const directCount = await db(TableName.OrgMembership) - .where(`${TableName.OrgMembership}.orgId`, orgId) - .join(TableName.Users, `${TableName.OrgMembership}.userId`, `${TableName.Users}.id`) - .leftJoin(TableName.UserGroupMembership, function () { - this.on(`${TableName.UserGroupMembership}.userId`, "=", `${TableName.Users}.id`).andOn( - `${TableName.UserGroupMembership}.groupId`, - "=", - db.raw("?", [groupId]) - ); - }) - .where({ isGhost: false, isAccepted: true }) - .count(`${TableName.Users}.id`) - .first(); - - const pendingCount = await db(TableName.PendingGroupAddition) - .where(`${TableName.PendingGroupAddition}.groupId`, groupId) - .count("*") - .first(); - - return parseInt((directCount?.count as string) || "0", 10) + parseInt((pendingCount?.count as string) || "0", 10); - } catch (err) { - throw new DatabaseError({ error: err, name: "Count all direct group members" }); - } - }; - // special query const findAllGroupMembers = async ({ orgId, @@ -160,7 +129,6 @@ export const groupDALFactory = (db: TDbClient) => { const members = await query; return members.map(({ email, username: memberUsername, firstName, lastName, userId, isPartOfGroup }) => ({ - // TODO: fix type id: userId, email, username: memberUsername, @@ -176,7 +144,6 @@ export const groupDALFactory = (db: TDbClient) => { return { findGroups, findByOrgId, - countGroupMembers, findAllGroupMembers, ...groupOrm }; diff --git a/backend/src/ee/services/group/group-service.ts b/backend/src/ee/services/group/group-service.ts index 5bb6aa9d6..b9ec68013 100644 --- a/backend/src/ee/services/group/group-service.ts +++ b/backend/src/ee/services/group/group-service.ts @@ -30,12 +30,9 @@ import { TUserGroupMembershipDALFactory } from "./user-group-membership-dal"; type TGroupServiceFactoryDep = { userDAL: Pick; - groupDAL: Pick< - TGroupDALFactory, - "create" | "findOne" | "update" | "delete" | "findAllGroupMembers" | "countGroupMembers" - >; + groupDAL: Pick; groupProjectDAL: Pick; - orgDAL: Pick; + orgDAL: Pick; userGroupMembershipDAL: Pick< TUserGroupMembershipDALFactory, "findOne" | "delete" | "filterProjectsByUserMembership" | "transaction" | "insertMany" | "find" @@ -230,12 +227,9 @@ export const groupServiceFactory = ({ username }); - const totalCount = await groupDAL.countGroupMembers({ - orgId: group.orgId, - groupId: group.id - }); + const count = await orgDAL.countAllOrgMembers(group.orgId); - return { users, totalCount }; + return { users, totalCount: count }; }; const addUserToGroup = async ({ diff --git a/backend/src/server/routes/v2/organization-router.ts b/backend/src/server/routes/v2/organization-router.ts index a4a66e992..ae132316a 100644 --- a/backend/src/server/routes/v2/organization-router.ts +++ b/backend/src/server/routes/v2/organization-router.ts @@ -45,7 +45,6 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => { onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]), handler: async (req) => { if (req.auth.actor !== ActorType.USER) return; - const users = await server.services.org.findAllOrgMembers( req.permission.id, req.params.organizationId, diff --git a/backend/src/services/org/org-dal.ts b/backend/src/services/org/org-dal.ts index 3b1daa827..4dc76b612 100644 --- a/backend/src/services/org/org-dal.ts +++ b/backend/src/services/org/org-dal.ts @@ -89,6 +89,25 @@ export const orgDALFactory = (db: TDbClient) => { } }; + const countAllOrgMembers = async (orgId: string) => { + try { + interface CountResult { + count: string; + } + + const count = await db(TableName.OrgMembership) + .where(`${TableName.OrgMembership}.orgId`, orgId) + .count("*") + .join(TableName.Users, `${TableName.OrgMembership}.userId`, `${TableName.Users}.id`) + .where({ isGhost: false }) + .first(); + + return parseInt((count as unknown as CountResult).count || "0", 10); + } catch (error) { + throw new DatabaseError({ error, name: "Count all org members" }); + } + }; + const findOrgMembersByUsername = async (orgId: string, usernames: string[]) => { try { const members = await db(TableName.OrgMembership) @@ -269,6 +288,7 @@ export const orgDALFactory = (db: TDbClient) => { ...orgOrm, findOrgByProjectId, findAllOrgMembers, + countAllOrgMembers, findOrgById, findAllOrgsByUserId, ghostUserExists, diff --git a/frontend/src/views/Org/MembersPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupModal.tsx b/frontend/src/views/Org/MembersPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupModal.tsx index 7791eaa06..85a5c0c23 100644 --- a/frontend/src/views/Org/MembersPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupModal.tsx +++ b/frontend/src/views/Org/MembersPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupModal.tsx @@ -19,7 +19,10 @@ import { UsePopUpState } from "@app/hooks/usePopUp"; const GroupFormSchema = z.object({ name: z.string().min(1, "Name cannot be empty").max(50, "Name must be 50 characters or fewer"), - slug: z.string().min(5, "Slug cannot be empty").max(36, "Slug must be 36 characters or fewer"), + slug: z + .string() + .min(5, "Slug must be at least 5 characters long") + .max(36, "Slug must be 36 characters or fewer"), role: z.string() }); From 718cabe49b83bf04942dea8a64513ccae4ed7169 Mon Sep 17 00:00:00 2001 From: Akhil Mohan Date: Fri, 19 Apr 2024 20:53:54 +0530 Subject: [PATCH 24/99] feat(server): added batch raw bulk secret ops api --- backend/e2e-test/routes/v3/secrets.spec.ts | 107 ++++++++ backend/src/lib/api-docs/constants.ts | 1 + backend/src/server/routes/v3/secret-router.ts | 259 ++++++++++++++++++ backend/src/services/secret/secret-service.ts | 131 +++++++++ backend/src/services/secret/secret-types.ts | 30 ++ 5 files changed, 528 insertions(+) diff --git a/backend/e2e-test/routes/v3/secrets.spec.ts b/backend/e2e-test/routes/v3/secrets.spec.ts index 03e1c2f50..ab73a7f1f 100644 --- a/backend/e2e-test/routes/v3/secrets.spec.ts +++ b/backend/e2e-test/routes/v3/secrets.spec.ts @@ -942,6 +942,113 @@ describe.each([{ auth: AuthMode.JWT }, { auth: AuthMode.IDENTITY_ACCESS_TOKEN }] const secrets = await getSecrets(seedData1.environment.slug, path); expect(secrets).toEqual([]); }); + + test.each(testRawSecrets)("Bulk create secret raw in path $path", async ({ path, secret }) => { + const createSecretReqBody = { + workspaceId: seedData1.project.id, + environment: seedData1.environment.slug, + secretPath: path, + secrets: [ + { + secretKey: secret.key, + secretValue: secret.value, + secretComment: secret.comment + } + ] + }; + const createSecRes = await testServer.inject({ + method: "POST", + url: `/api/v3/secrets/batch/raw`, + headers: { + authorization: `Bearer ${authToken}` + }, + body: createSecretReqBody + }); + expect(createSecRes.statusCode).toBe(200); + const createdSecretPayload = JSON.parse(createSecRes.payload); + expect(createdSecretPayload).toHaveProperty("secrets"); + + // fetch secrets + const secrets = await getSecrets(seedData1.environment.slug, path); + expect(secrets).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + key: secret.key, + value: secret.value, + type: SecretType.Shared + }) + ]) + ); + + await deleteRawSecret({ path, key: secret.key }); + }); + + test.each(testRawSecrets)("Bulk update secret raw in path $path", async ({ secret, path }) => { + await createRawSecret({ path, ...secret }); + const updateSecretReqBody = { + workspaceId: seedData1.project.id, + environment: seedData1.environment.slug, + secretPath: path, + secrets: [ + { + secretValue: "new-value", + secretKey: secret.key + } + ] + }; + const updateSecRes = await testServer.inject({ + method: "PATCH", + url: `/api/v3/secrets/batch/raw`, + headers: { + authorization: `Bearer ${authToken}` + }, + body: updateSecretReqBody + }); + expect(updateSecRes.statusCode).toBe(200); + const updatedSecretPayload = JSON.parse(updateSecRes.payload); + expect(updatedSecretPayload).toHaveProperty("secrets"); + + // fetch secrets + const secrets = await getSecrets(seedData1.environment.slug, path); + expect(secrets).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + key: secret.key, + value: "new-value", + version: 2, + type: SecretType.Shared + }) + ]) + ); + + await deleteRawSecret({ path, key: secret.key }); + }); + + test.each(testRawSecrets)("Bulk delete secret raw in path $path", async ({ path, secret }) => { + await createRawSecret({ path, ...secret }); + + const deletedSecretReqBody = { + workspaceId: seedData1.project.id, + environment: seedData1.environment.slug, + secretPath: path, + secrets: [{ secretKey: secret.key }] + }; + const deletedSecRes = await testServer.inject({ + method: "DELETE", + url: `/api/v3/secrets/batch/raw`, + headers: { + authorization: `Bearer ${authToken}` + }, + body: deletedSecretReqBody + }); + expect(deletedSecRes.statusCode).toBe(200); + const deletedSecretPayload = JSON.parse(deletedSecRes.payload); + expect(deletedSecretPayload).toHaveProperty("secrets"); + + // fetch secrets + const secrets = await getSecrets(seedData1.environment.slug, path); + expect(secrets).toEqual([]); + }); } ); diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts index c83234c1f..4a98f73c8 100644 --- a/backend/src/lib/api-docs/constants.ts +++ b/backend/src/lib/api-docs/constants.ts @@ -301,6 +301,7 @@ export const RAW_SECRETS = { }, UPDATE: { secretName: "The name of the secret to update.", + secretComment: "Update comment to the secret.", environment: "The slug of the environment where the secret is located.", secretPath: "The path of the secret to update", secretValue: "The new value of the secret.", diff --git a/backend/src/server/routes/v3/secret-router.ts b/backend/src/server/routes/v3/secret-router.ts index b1d852a88..ceecc0805 100644 --- a/backend/src/server/routes/v3/secret-router.ts +++ b/backend/src/server/routes/v3/secret-router.ts @@ -1656,4 +1656,263 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => { return { secrets }; } }); + + server.route({ + method: "POST", + url: "/batch/raw", + config: { + rateLimit: secretsLimit + }, + schema: { + description: "Create many secrets", + security: [ + { + bearerAuth: [] + } + ], + body: z.object({ + workspaceId: z.string().trim().describe(RAW_SECRETS.CREATE.workspaceId), + environment: z.string().trim().describe(RAW_SECRETS.CREATE.environment), + secretPath: z + .string() + .trim() + .default("/") + .transform(removeTrailingSlash) + .describe(RAW_SECRETS.CREATE.secretPath), + secrets: z + .object({ + secretKey: z.string().trim().describe(RAW_SECRETS.CREATE.secretName), + secretValue: z + .string() + .transform((val) => (val.at(-1) === "\n" ? `${val.trim()}\n` : val.trim())) + .describe(RAW_SECRETS.CREATE.secretValue), + secretComment: z.string().trim().optional().default("").describe(RAW_SECRETS.CREATE.secretComment), + skipMultilineEncoding: z.boolean().optional().describe(RAW_SECRETS.CREATE.skipMultilineEncoding) + }) + .array() + .min(1) + }), + response: { + 200: z.object({ + secrets: secretRawSchema.array() + }) + } + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]), + handler: async (req) => { + const { environment, workspaceId: projectId, secretPath, secrets: inputSecrets } = req.body; + + const secrets = await server.services.secret.createManySecretsRaw({ + actorId: req.permission.id, + actor: req.permission.type, + actorAuthMethod: req.permission.authMethod, + actorOrgId: req.permission.orgId, + secretPath, + environment, + projectId, + secrets: inputSecrets + }); + + await server.services.auditLog.createAuditLog({ + projectId: req.body.workspaceId, + ...req.auditLogInfo, + event: { + type: EventType.CREATE_SECRETS, + metadata: { + environment: req.body.environment, + secretPath: req.body.secretPath, + secrets: secrets.map((secret, i) => ({ + secretId: secret.id, + secretKey: inputSecrets[i].secretKey, + secretVersion: secret.version + })) + } + } + }); + + await server.services.telemetry.sendPostHogEvents({ + event: PostHogEventTypes.SecretCreated, + distinctId: getTelemetryDistinctId(req), + properties: { + numberOfSecrets: secrets.length, + workspaceId: req.body.workspaceId, + environment: req.body.environment, + secretPath: req.body.secretPath, + channel: getUserAgentType(req.headers["user-agent"]), + ...req.auditLogInfo + } + }); + return { secrets }; + } + }); + + server.route({ + method: "PATCH", + url: "/batch/raw", + config: { + rateLimit: secretsLimit + }, + schema: { + description: "Update many secrets", + security: [ + { + bearerAuth: [] + } + ], + body: z.object({ + workspaceId: z.string().trim().describe(RAW_SECRETS.UPDATE.workspaceId), + environment: z.string().trim().describe(RAW_SECRETS.UPDATE.environment), + secretPath: z + .string() + .trim() + .default("/") + .transform(removeTrailingSlash) + .describe(RAW_SECRETS.UPDATE.secretPath), + secrets: z + .object({ + secretKey: z.string().trim().describe(RAW_SECRETS.UPDATE.secretName), + secretValue: z + .string() + .transform((val) => (val.at(-1) === "\n" ? `${val.trim()}\n` : val.trim())) + .describe(RAW_SECRETS.UPDATE.secretValue), + secretComment: z.string().trim().optional().describe(RAW_SECRETS.UPDATE.secretComment), + skipMultilineEncoding: z.boolean().optional().describe(RAW_SECRETS.UPDATE.skipMultilineEncoding) + }) + .array() + .min(1) + }), + response: { + 200: z.object({ + secrets: secretRawSchema.array() + }) + } + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]), + handler: async (req) => { + const { environment, workspaceId: projectId, secretPath, secrets: inputSecrets } = req.body; + const secrets = await server.services.secret.updateManySecretsRaw({ + actorId: req.permission.id, + actor: req.permission.type, + actorAuthMethod: req.permission.authMethod, + actorOrgId: req.permission.orgId, + secretPath, + environment, + projectId, + secrets: inputSecrets + }); + + await server.services.auditLog.createAuditLog({ + projectId: req.body.workspaceId, + ...req.auditLogInfo, + event: { + type: EventType.UPDATE_SECRETS, + metadata: { + environment: req.body.environment, + secretPath: req.body.secretPath, + secrets: secrets.map((secret, i) => ({ + secretId: secret.id, + secretKey: inputSecrets[i].secretKey, + secretVersion: secret.version + })) + } + } + }); + + await server.services.telemetry.sendPostHogEvents({ + event: PostHogEventTypes.SecretUpdated, + distinctId: getTelemetryDistinctId(req), + properties: { + numberOfSecrets: secrets.length, + workspaceId: req.body.workspaceId, + environment: req.body.environment, + secretPath: req.body.secretPath, + channel: getUserAgentType(req.headers["user-agent"]), + ...req.auditLogInfo + } + }); + return { secrets }; + } + }); + + server.route({ + method: "DELETE", + url: "/batch/raw", + config: { + rateLimit: secretsLimit + }, + schema: { + description: "Delete many secrets", + security: [ + { + bearerAuth: [] + } + ], + body: z.object({ + workspaceId: z.string().trim().describe(RAW_SECRETS.DELETE.workspaceId), + environment: z.string().trim().describe(RAW_SECRETS.DELETE.environment), + secretPath: z + .string() + .trim() + .default("/") + .transform(removeTrailingSlash) + .describe(RAW_SECRETS.DELETE.secretPath), + secrets: z + .object({ + secretKey: z.string().trim().describe(RAW_SECRETS.DELETE.secretName) + }) + .array() + .min(1) + }), + response: { + 200: z.object({ + secrets: secretRawSchema.array() + }) + } + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]), + handler: async (req) => { + const { environment, workspaceId: projectId, secretPath, secrets: inputSecrets } = req.body; + const secrets = await server.services.secret.deleteManySecretsRaw({ + actorId: req.permission.id, + actor: req.permission.type, + actorAuthMethod: req.permission.authMethod, + actorOrgId: req.permission.orgId, + environment, + projectId, + secretPath, + secrets: inputSecrets + }); + + await server.services.auditLog.createAuditLog({ + projectId: req.body.workspaceId, + ...req.auditLogInfo, + event: { + type: EventType.DELETE_SECRETS, + metadata: { + environment: req.body.environment, + secretPath: req.body.secretPath, + secrets: secrets.map((secret, i) => ({ + secretId: secret.id, + secretKey: inputSecrets[i].secretKey, + secretVersion: secret.version + })) + } + } + }); + + await server.services.telemetry.sendPostHogEvents({ + event: PostHogEventTypes.SecretDeleted, + distinctId: getTelemetryDistinctId(req), + properties: { + numberOfSecrets: secrets.length, + workspaceId: req.body.workspaceId, + environment: req.body.environment, + secretPath: req.body.secretPath, + channel: getUserAgentType(req.headers["user-agent"]), + ...req.auditLogInfo + } + }); + return { secrets }; + } + }); }; diff --git a/backend/src/services/secret/secret-service.ts b/backend/src/services/secret/secret-service.ts index 3b504fbf4..9c7c0cbd6 100644 --- a/backend/src/services/secret/secret-service.ts +++ b/backend/src/services/secret/secret-service.ts @@ -33,9 +33,11 @@ import { TSecretQueueFactory } from "./secret-queue"; import { TAttachSecretTagsDTO, TCreateBulkSecretDTO, + TCreateManySecretRawDTO, TCreateSecretDTO, TCreateSecretRawDTO, TDeleteBulkSecretDTO, + TDeleteManySecretRawDTO, TDeleteSecretDTO, TDeleteSecretRawDTO, TFnSecretBlindIndexCheckV2, @@ -46,6 +48,7 @@ import { TGetSecretsRawDTO, TGetSecretVersionsDTO, TUpdateBulkSecretDTO, + TUpdateManySecretRawDTO, TUpdateSecretDTO, TUpdateSecretRawDTO } from "./secret-types"; @@ -1036,6 +1039,131 @@ export const secretServiceFactory = ({ return decryptSecretRaw(secret, botKey); }; + const createManySecretsRaw = async ({ + actorId, + projectId, + environment, + actor, + actorOrgId, + actorAuthMethod, + secretPath, + secrets: inputSecrets = [] + }: TCreateManySecretRawDTO) => { + const botKey = await projectBotService.getBotKey(projectId); + if (!botKey) throw new BadRequestError({ message: "Project bot not found", name: "bot_not_found_error" }); + + const secrets = await createManySecret({ + projectId, + environment, + path: secretPath, + actor, + actorId, + actorOrgId, + actorAuthMethod, + secrets: inputSecrets.map(({ secretComment, secretKey, secretValue, skipMultilineEncoding }) => { + const secretKeyEncrypted = encryptSymmetric128BitHexKeyUTF8(secretKey, botKey); + const secretValueEncrypted = encryptSymmetric128BitHexKeyUTF8(secretValue || "", botKey); + const secretCommentEncrypted = encryptSymmetric128BitHexKeyUTF8(secretComment || "", botKey); + return { + secretName: secretKey, + skipMultilineEncoding, + secretKeyCiphertext: secretKeyEncrypted.ciphertext, + secretKeyIV: secretKeyEncrypted.iv, + secretKeyTag: secretKeyEncrypted.tag, + secretValueCiphertext: secretValueEncrypted.ciphertext, + secretValueIV: secretValueEncrypted.iv, + secretValueTag: secretValueEncrypted.tag, + secretCommentCiphertext: secretCommentEncrypted.ciphertext, + secretCommentIV: secretCommentEncrypted.iv, + secretCommentTag: secretCommentEncrypted.tag + }; + }) + }); + + await snapshotService.performSnapshot(secrets[0].folderId); + await secretQueueService.syncSecrets({ secretPath, projectId, environment }); + + return secrets.map((secret) => decryptSecretRaw({ ...secret, workspace: projectId, environment }, botKey)); + }; + + const updateManySecretsRaw = async ({ + actorId, + projectId, + environment, + actor, + actorOrgId, + actorAuthMethod, + secretPath, + secrets: inputSecrets = [] + }: TUpdateManySecretRawDTO) => { + const botKey = await projectBotService.getBotKey(projectId); + if (!botKey) throw new BadRequestError({ message: "Project bot not found", name: "bot_not_found_error" }); + + const secrets = await updateManySecret({ + projectId, + environment, + path: secretPath, + actor, + actorId, + actorOrgId, + actorAuthMethod, + secrets: inputSecrets.map(({ secretComment, secretKey, secretValue, skipMultilineEncoding }) => { + const secretKeyEncrypted = encryptSymmetric128BitHexKeyUTF8(secretKey, botKey); + const secretValueEncrypted = encryptSymmetric128BitHexKeyUTF8(secretValue || "", botKey); + const secretCommentEncrypted = encryptSymmetric128BitHexKeyUTF8(secretComment || "", botKey); + return { + secretName: secretKey, + type: SecretType.Shared, + skipMultilineEncoding, + secretKeyCiphertext: secretKeyEncrypted.ciphertext, + secretKeyIV: secretKeyEncrypted.iv, + secretKeyTag: secretKeyEncrypted.tag, + secretValueCiphertext: secretValueEncrypted.ciphertext, + secretValueIV: secretValueEncrypted.iv, + secretValueTag: secretValueEncrypted.tag, + secretCommentCiphertext: secretCommentEncrypted.ciphertext, + secretCommentIV: secretCommentEncrypted.iv, + secretCommentTag: secretCommentEncrypted.tag + }; + }) + }); + + await snapshotService.performSnapshot(secrets[0].folderId); + await secretQueueService.syncSecrets({ secretPath, projectId, environment }); + + return secrets.map((secret) => decryptSecretRaw({ ...secret, workspace: projectId, environment }, botKey)); + }; + + const deleteManySecretsRaw = async ({ + actorId, + projectId, + environment, + actor, + actorOrgId, + actorAuthMethod, + secretPath, + secrets: inputSecrets = [] + }: TDeleteManySecretRawDTO) => { + const botKey = await projectBotService.getBotKey(projectId); + if (!botKey) throw new BadRequestError({ message: "Project bot not found", name: "bot_not_found_error" }); + + const secrets = await deleteManySecret({ + projectId, + environment, + path: secretPath, + actor, + actorId, + actorOrgId, + actorAuthMethod, + secrets: inputSecrets.map(({ secretKey }) => ({ secretName: secretKey, type: SecretType.Shared })) + }); + + await snapshotService.performSnapshot(secrets[0].folderId); + await secretQueueService.syncSecrets({ secretPath, projectId, environment }); + + return secrets.map((secret) => decryptSecretRaw({ ...secret, workspace: projectId, environment }, botKey)); + }; + const getSecretVersions = async ({ actorId, actor, @@ -1280,6 +1408,9 @@ export const secretServiceFactory = ({ createSecretRaw, updateSecretRaw, deleteSecretRaw, + createManySecretsRaw, + updateManySecretsRaw, + deleteManySecretsRaw, getSecretVersions, // external services function fnSecretBulkDelete, diff --git a/backend/src/services/secret/secret-types.ts b/backend/src/services/secret/secret-types.ts index 22347de4e..34b8bc822 100644 --- a/backend/src/services/secret/secret-types.ts +++ b/backend/src/services/secret/secret-types.ts @@ -181,6 +181,36 @@ export type TDeleteSecretRawDTO = TProjectPermission & { type: SecretType; }; +export type TCreateManySecretRawDTO = TProjectPermission & { + secretPath: string; + environment: string; + secrets: { + secretKey: string; + secretValue: string; + secretComment?: string; + skipMultilineEncoding?: boolean; + }[]; +}; + +export type TUpdateManySecretRawDTO = TProjectPermission & { + secretPath: string; + environment: string; + secrets: { + secretKey: string; + secretValue: string; + secretComment?: string; + skipMultilineEncoding?: boolean; + }[]; +}; + +export type TDeleteManySecretRawDTO = TProjectPermission & { + secretPath: string; + environment: string; + secrets: { + secretKey: string; + }[]; +}; + export type TGetSecretVersionsDTO = Omit & { limit?: number; offset?: number; From a339c473d5dd1730fa1a2343ac6b0922f7d20488 Mon Sep 17 00:00:00 2001 From: Akhil Mohan Date: Fri, 19 Apr 2024 20:54:41 +0530 Subject: [PATCH 25/99] docs: updated api doc with bulk raw secret ops --- docs/api-reference/endpoints/secrets/create-many.mdx | 8 ++++++++ docs/api-reference/endpoints/secrets/delete-many.mdx | 8 ++++++++ docs/api-reference/endpoints/secrets/update-many.mdx | 8 ++++++++ 3 files changed, 24 insertions(+) create mode 100644 docs/api-reference/endpoints/secrets/create-many.mdx create mode 100644 docs/api-reference/endpoints/secrets/delete-many.mdx create mode 100644 docs/api-reference/endpoints/secrets/update-many.mdx diff --git a/docs/api-reference/endpoints/secrets/create-many.mdx b/docs/api-reference/endpoints/secrets/create-many.mdx new file mode 100644 index 000000000..9b0609c0a --- /dev/null +++ b/docs/api-reference/endpoints/secrets/create-many.mdx @@ -0,0 +1,8 @@ +--- +title: "Bulk Create" +openapi: "POST /api/v3/secrets/batch/raw" +--- + + + This endpoint requires you to disable end-to-end encryption. For more information, you should consult this [note](https://infisical.com/docs/api-reference/overview/examples/note). + diff --git a/docs/api-reference/endpoints/secrets/delete-many.mdx b/docs/api-reference/endpoints/secrets/delete-many.mdx new file mode 100644 index 000000000..6477b2a98 --- /dev/null +++ b/docs/api-reference/endpoints/secrets/delete-many.mdx @@ -0,0 +1,8 @@ +--- +title: "Bulk Delete" +openapi: "DELETE /api/v3/secrets/batch/raw" +--- + + + This endpoint requires you to disable end-to-end encryption. For more information, you should consult this [note](https://infisical.com/docs/api-reference/overview/examples/note). + diff --git a/docs/api-reference/endpoints/secrets/update-many.mdx b/docs/api-reference/endpoints/secrets/update-many.mdx new file mode 100644 index 000000000..9feaf2ca2 --- /dev/null +++ b/docs/api-reference/endpoints/secrets/update-many.mdx @@ -0,0 +1,8 @@ +--- +title: "Bulk Update" +openapi: "PATCH /api/v3/secrets/batch/raw" +--- + + + This endpoint requires you to disable end-to-end encryption. For more information, you should consult this [note](https://infisical.com/docs/api-reference/overview/examples/note). + From ea6e739b4646967772fa7a28cab351fb1cc9ae6f Mon Sep 17 00:00:00 2001 From: Akhil Mohan Date: Mon, 22 Apr 2024 16:14:26 +0530 Subject: [PATCH 26/99] chore: added a docker setup to run a cassandra instance for dynamic secret --- sink/cassandra.yaml | 1820 +++++++++++++++++++++++++++++ sink/docker-compose.cassandra.yml | 10 + 2 files changed, 1830 insertions(+) create mode 100644 sink/cassandra.yaml create mode 100644 sink/docker-compose.cassandra.yml diff --git a/sink/cassandra.yaml b/sink/cassandra.yaml new file mode 100644 index 000000000..059fb7e3e --- /dev/null +++ b/sink/cassandra.yaml @@ -0,0 +1,1820 @@ + +# Cassandra storage config YAML + +# NOTE: +# See https://cassandra.apache.org/doc/latest/configuration/ for +# full explanations of configuration directives +# /NOTE + +# The name of the cluster. This is mainly used to prevent machines in +# one logical cluster from joining another. +cluster_name: 'Test Cluster' + +# This defines the number of tokens randomly assigned to this node on the ring +# The more tokens, relative to other nodes, the larger the proportion of data +# that this node will store. You probably want all nodes to have the same number +# of tokens assuming they have equal hardware capability. +# +# If you leave this unspecified, Cassandra will use the default of 1 token for legacy compatibility, +# and will use the initial_token as described below. +# +# Specifying initial_token will override this setting on the node's initial start, +# on subsequent starts, this setting will apply even if initial token is set. +# +# See https://cassandra.apache.org/doc/latest/getting_started/production.html#tokens for +# best practice information about num_tokens. +# +num_tokens: 16 + +# Triggers automatic allocation of num_tokens tokens for this node. The allocation +# algorithm attempts to choose tokens in a way that optimizes replicated load over +# the nodes in the datacenter for the replica factor. +# +# The load assigned to each node will be close to proportional to its number of +# vnodes. +# +# Only supported with the Murmur3Partitioner. + +# Replica factor is determined via the replication strategy used by the specified +# keyspace. +# allocate_tokens_for_keyspace: KEYSPACE + +# Replica factor is explicitly set, regardless of keyspace or datacenter. +# This is the replica factor within the datacenter, like NTS. +allocate_tokens_for_local_replication_factor: 3 + +# initial_token allows you to specify tokens manually. While you can use it with +# vnodes (num_tokens > 1, above) -- in which case you should provide a +# comma-separated list -- it's primarily used when adding nodes to legacy clusters +# that do not have vnodes enabled. +# initial_token: + +# May either be "true" or "false" to enable globally +hinted_handoff_enabled: true + +# When hinted_handoff_enabled is true, a black list of data centers that will not +# perform hinted handoff +# hinted_handoff_disabled_datacenters: +# - DC1 +# - DC2 + +# this defines the maximum amount of time a dead host will have hints +# generated. After it has been dead this long, new hints for it will not be +# created until it has been seen alive and gone down again. +# Min unit: ms +max_hint_window: 3h + +# Maximum throttle in KiBs per second, per delivery thread. This will be +# reduced proportionally to the number of nodes in the cluster. (If there +# are two nodes in the cluster, each delivery thread will use the maximum +# rate; if there are three, each will throttle to half of the maximum, +# since we expect two nodes to be delivering hints simultaneously.) +# Min unit: KiB +hinted_handoff_throttle: 1024KiB + +# Number of threads with which to deliver hints; +# Consider increasing this number when you have multi-dc deployments, since +# cross-dc handoff tends to be slower +max_hints_delivery_threads: 2 + +# Directory where Cassandra should store hints. +# If not set, the default directory is $CASSANDRA_HOME/data/hints. +# hints_directory: /var/lib/cassandra/hints + +# How often hints should be flushed from the internal buffers to disk. +# Will *not* trigger fsync. +# Min unit: ms +hints_flush_period: 10000ms + +# Maximum size for a single hints file, in mebibytes. +# Min unit: MiB +max_hints_file_size: 128MiB + +# The file size limit to store hints for an unreachable host, in mebibytes. +# Once the local hints files have reached the limit, no more new hints will be created. +# Set a non-positive value will disable the size limit. +# max_hints_size_per_host: 0MiB + +# Enable / disable automatic cleanup for the expired and orphaned hints file. +# Disable the option in order to preserve those hints on the disk. +auto_hints_cleanup_enabled: false + +# Compression to apply to the hint files. If omitted, hints files +# will be written uncompressed. LZ4, Snappy, and Deflate compressors +# are supported. +#hints_compression: +# - class_name: LZ4Compressor +# parameters: +# - + +# Enable / disable persistent hint windows. +# +# If set to false, a hint will be stored only in case a respective node +# that hint is for is down less than or equal to max_hint_window. +# +# If set to true, a hint will be stored in case there is not any +# hint which was stored earlier than max_hint_window. This is for cases +# when a node keeps to restart and hints are not delivered yet, we would be saving +# hints for that node indefinitely. +# +# Defaults to true. +# +# hint_window_persistent_enabled: true + +# Maximum throttle in KiBs per second, total. This will be +# reduced proportionally to the number of nodes in the cluster. +# Min unit: KiB +batchlog_replay_throttle: 1024KiB + +# Authentication backend, implementing IAuthenticator; used to identify users +# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllAuthenticator, +# PasswordAuthenticator}. +# +# - AllowAllAuthenticator performs no checks - set it to disable authentication. +# - PasswordAuthenticator relies on username/password pairs to authenticate +# users. It keeps usernames and hashed passwords in system_auth.roles table. +# Please increase system_auth keyspace replication factor if you use this authenticator. +# If using PasswordAuthenticator, CassandraRoleManager must also be used (see below) +authenticator: PasswordAuthenticator + +# Authorization backend, implementing IAuthorizer; used to limit access/provide permissions +# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllAuthorizer, +# CassandraAuthorizer}. +# +# - AllowAllAuthorizer allows any action to any user - set it to disable authorization. +# - CassandraAuthorizer stores permissions in system_auth.role_permissions table. Please +# increase system_auth keyspace replication factor if you use this authorizer. +authorizer: CassandraAuthorizer + +# Part of the Authentication & Authorization backend, implementing IRoleManager; used +# to maintain grants and memberships between roles. +# Out of the box, Cassandra provides org.apache.cassandra.auth.CassandraRoleManager, +# which stores role information in the system_auth keyspace. Most functions of the +# IRoleManager require an authenticated login, so unless the configured IAuthenticator +# actually implements authentication, most of this functionality will be unavailable. +# +# - CassandraRoleManager stores role data in the system_auth keyspace. Please +# increase system_auth keyspace replication factor if you use this role manager. +role_manager: CassandraRoleManager + +# Network authorization backend, implementing INetworkAuthorizer; used to restrict user +# access to certain DCs +# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllNetworkAuthorizer, +# CassandraNetworkAuthorizer}. +# +# - AllowAllNetworkAuthorizer allows access to any DC to any user - set it to disable authorization. +# - CassandraNetworkAuthorizer stores permissions in system_auth.network_permissions table. Please +# increase system_auth keyspace replication factor if you use this authorizer. +network_authorizer: AllowAllNetworkAuthorizer + +# Depending on the auth strategy of the cluster, it can be beneficial to iterate +# from root to table (root -> ks -> table) instead of table to root (table -> ks -> root). +# As the auth entries are whitelisting, once a permission is found you know it to be +# valid. We default to false as the legacy behavior is to query at the table level then +# move back up to the root. See CASSANDRA-17016 for details. +# traverse_auth_from_root: false + +# Validity period for roles cache (fetching granted roles can be an expensive +# operation depending on the role manager, CassandraRoleManager is one example) +# Granted roles are cached for authenticated sessions in AuthenticatedUser and +# after the period specified here, become eligible for (async) reload. +# Defaults to 2000, set to 0 to disable caching entirely. +# Will be disabled automatically for AllowAllAuthenticator. +# For a long-running cache using roles_cache_active_update, consider +# setting to something longer such as a daily validation: 86400000 +# Min unit: ms +roles_validity: 2000ms + +# Refresh interval for roles cache (if enabled). +# After this interval, cache entries become eligible for refresh. Upon next +# access, an async reload is scheduled and the old value returned until it +# completes. If roles_validity is non-zero, then this must be +# also. +# This setting is also used to inform the interval of auto-updating if +# using roles_cache_active_update. +# Defaults to the same value as roles_validity. +# For a long-running cache, consider setting this to 60000 (1 hour) etc. +# Min unit: ms +# roles_update_interval: 2000ms + +# If true, cache contents are actively updated by a background task at the +# interval set by roles_update_interval. If false, cache entries +# become eligible for refresh after their update interval. Upon next access, +# an async reload is scheduled and the old value returned until it completes. +# roles_cache_active_update: false + +# Validity period for permissions cache (fetching permissions can be an +# expensive operation depending on the authorizer, CassandraAuthorizer is +# one example). Defaults to 2000, set to 0 to disable. +# Will be disabled automatically for AllowAllAuthorizer. +# For a long-running cache using permissions_cache_active_update, consider +# setting to something longer such as a daily validation: 86400000ms +# Min unit: ms +permissions_validity: 2000ms + +# Refresh interval for permissions cache (if enabled). +# After this interval, cache entries become eligible for refresh. Upon next +# access, an async reload is scheduled and the old value returned until it +# completes. If permissions_validity is non-zero, then this must be +# also. +# This setting is also used to inform the interval of auto-updating if +# using permissions_cache_active_update. +# Defaults to the same value as permissions_validity. +# For a longer-running permissions cache, consider setting to update hourly (60000) +# Min unit: ms +# permissions_update_interval: 2000ms + +# If true, cache contents are actively updated by a background task at the +# interval set by permissions_update_interval. If false, cache entries +# become eligible for refresh after their update interval. Upon next access, +# an async reload is scheduled and the old value returned until it completes. +# permissions_cache_active_update: false + +# Validity period for credentials cache. This cache is tightly coupled to +# the provided PasswordAuthenticator implementation of IAuthenticator. If +# another IAuthenticator implementation is configured, this cache will not +# be automatically used and so the following settings will have no effect. +# Please note, credentials are cached in their encrypted form, so while +# activating this cache may reduce the number of queries made to the +# underlying table, it may not bring a significant reduction in the +# latency of individual authentication attempts. +# Defaults to 2000, set to 0 to disable credentials caching. +# For a long-running cache using credentials_cache_active_update, consider +# setting to something longer such as a daily validation: 86400000 +# Min unit: ms +credentials_validity: 2000ms + +# Refresh interval for credentials cache (if enabled). +# After this interval, cache entries become eligible for refresh. Upon next +# access, an async reload is scheduled and the old value returned until it +# completes. If credentials_validity is non-zero, then this must be +# also. +# This setting is also used to inform the interval of auto-updating if +# using credentials_cache_active_update. +# Defaults to the same value as credentials_validity. +# For a longer-running permissions cache, consider setting to update hourly (60000) +# Min unit: ms +# credentials_update_interval: 2000ms + +# If true, cache contents are actively updated by a background task at the +# interval set by credentials_update_interval. If false (default), cache entries +# become eligible for refresh after their update interval. Upon next access, +# an async reload is scheduled and the old value returned until it completes. +# credentials_cache_active_update: false + +# The partitioner is responsible for distributing groups of rows (by +# partition key) across nodes in the cluster. The partitioner can NOT be +# changed without reloading all data. If you are adding nodes or upgrading, +# you should set this to the same partitioner that you are currently using. +# +# The default partitioner is the Murmur3Partitioner. Older partitioners +# such as the RandomPartitioner, ByteOrderedPartitioner, and +# OrderPreservingPartitioner have been included for backward compatibility only. +# For new clusters, you should NOT change this value. +# +partitioner: org.apache.cassandra.dht.Murmur3Partitioner + +# Directories where Cassandra should store data on disk. If multiple +# directories are specified, Cassandra will spread data evenly across +# them by partitioning the token ranges. +# If not set, the default directory is $CASSANDRA_HOME/data/data. +# data_file_directories: +# - /var/lib/cassandra/data + +# Directory were Cassandra should store the data of the local system keyspaces. +# By default Cassandra will store the data of the local system keyspaces in the first of the data directories specified +# by data_file_directories. +# This approach ensures that if one of the other disks is lost Cassandra can continue to operate. For extra security +# this setting allows to store those data on a different directory that provides redundancy. +# local_system_data_file_directory: + +# commit log. when running on magnetic HDD, this should be a +# separate spindle than the data directories. +# If not set, the default directory is $CASSANDRA_HOME/data/commitlog. +# commitlog_directory: /var/lib/cassandra/commitlog + +# Enable / disable CDC functionality on a per-node basis. This modifies the logic used +# for write path allocation rejection (standard: never reject. cdc: reject Mutation +# containing a CDC-enabled table if at space limit in cdc_raw_directory). +cdc_enabled: false + +# CommitLogSegments are moved to this directory on flush if cdc_enabled: true and the +# segment contains mutations for a CDC-enabled table. This should be placed on a +# separate spindle than the data directories. If not set, the default directory is +# $CASSANDRA_HOME/data/cdc_raw. +# cdc_raw_directory: /var/lib/cassandra/cdc_raw + +# Policy for data disk failures: +# +# die +# shut down gossip and client transports and kill the JVM for any fs errors or +# single-sstable errors, so the node can be replaced. +# +# stop_paranoid +# shut down gossip and client transports even for single-sstable errors, +# kill the JVM for errors during startup. +# +# stop +# shut down gossip and client transports, leaving the node effectively dead, but +# can still be inspected via JMX, kill the JVM for errors during startup. +# +# best_effort +# stop using the failed disk and respond to requests based on +# remaining available sstables. This means you WILL see obsolete +# data at CL.ONE! +# +# ignore +# ignore fatal errors and let requests fail, as in pre-1.2 Cassandra +disk_failure_policy: stop + +# Policy for commit disk failures: +# +# die +# shut down the node and kill the JVM, so the node can be replaced. +# +# stop +# shut down the node, leaving the node effectively dead, but +# can still be inspected via JMX. +# +# stop_commit +# shutdown the commit log, letting writes collect but +# continuing to service reads, as in pre-2.0.5 Cassandra +# +# ignore +# ignore fatal errors and let the batches fail +commit_failure_policy: stop + +# Maximum size of the native protocol prepared statement cache +# +# Valid values are either "auto" (omitting the value) or a value greater 0. +# +# Note that specifying a too large value will result in long running GCs and possbily +# out-of-memory errors. Keep the value at a small fraction of the heap. +# +# If you constantly see "prepared statements discarded in the last minute because +# cache limit reached" messages, the first step is to investigate the root cause +# of these messages and check whether prepared statements are used correctly - +# i.e. use bind markers for variable parts. +# +# Do only change the default value, if you really have more prepared statements than +# fit in the cache. In most cases it is not neccessary to change this value. +# Constantly re-preparing statements is a performance penalty. +# +# Default value ("auto") is 1/256th of the heap or 10MiB, whichever is greater +# Min unit: MiB +prepared_statements_cache_size: + +# Maximum size of the key cache in memory. +# +# Each key cache hit saves 1 seek and each row cache hit saves 2 seeks at the +# minimum, sometimes more. The key cache is fairly tiny for the amount of +# time it saves, so it's worthwhile to use it at large numbers. +# The row cache saves even more time, but must contain the entire row, +# so it is extremely space-intensive. It's best to only use the +# row cache if you have hot rows or static rows. +# +# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup. +# +# Default value is empty to make it "auto" (min(5% of Heap (in MiB), 100MiB)). Set to 0 to disable key cache. +# Min unit: MiB +key_cache_size: + +# Duration in seconds after which Cassandra should +# save the key cache. Caches are saved to saved_caches_directory as +# specified in this configuration file. +# +# Saved caches greatly improve cold-start speeds, and is relatively cheap in +# terms of I/O for the key cache. Row cache saving is much more expensive and +# has limited use. +# +# Default is 14400 or 4 hours. +# Min unit: s +key_cache_save_period: 4h + +# Number of keys from the key cache to save +# Disabled by default, meaning all keys are going to be saved +# key_cache_keys_to_save: 100 + +# Row cache implementation class name. Available implementations: +# +# org.apache.cassandra.cache.OHCProvider +# Fully off-heap row cache implementation (default). +# +# org.apache.cassandra.cache.SerializingCacheProvider +# This is the row cache implementation availabile +# in previous releases of Cassandra. +# row_cache_class_name: org.apache.cassandra.cache.OHCProvider + +# Maximum size of the row cache in memory. +# Please note that OHC cache implementation requires some additional off-heap memory to manage +# the map structures and some in-flight memory during operations before/after cache entries can be +# accounted against the cache capacity. This overhead is usually small compared to the whole capacity. +# Do not specify more memory that the system can afford in the worst usual situation and leave some +# headroom for OS block level cache. Do never allow your system to swap. +# +# Default value is 0, to disable row caching. +# Min unit: MiB +row_cache_size: 0MiB + +# Duration in seconds after which Cassandra should save the row cache. +# Caches are saved to saved_caches_directory as specified in this configuration file. +# +# Saved caches greatly improve cold-start speeds, and is relatively cheap in +# terms of I/O for the key cache. Row cache saving is much more expensive and +# has limited use. +# +# Default is 0 to disable saving the row cache. +# Min unit: s +row_cache_save_period: 0s + +# Number of keys from the row cache to save. +# Specify 0 (which is the default), meaning all keys are going to be saved +# row_cache_keys_to_save: 100 + +# Maximum size of the counter cache in memory. +# +# Counter cache helps to reduce counter locks' contention for hot counter cells. +# In case of RF = 1 a counter cache hit will cause Cassandra to skip the read before +# write entirely. With RF > 1 a counter cache hit will still help to reduce the duration +# of the lock hold, helping with hot counter cell updates, but will not allow skipping +# the read entirely. Only the local (clock, count) tuple of a counter cell is kept +# in memory, not the whole counter, so it's relatively cheap. +# +# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup. +# +# Default value is empty to make it "auto" (min(2.5% of Heap (in MiB), 50MiB)). Set to 0 to disable counter cache. +# NOTE: if you perform counter deletes and rely on low gcgs, you should disable the counter cache. +# Min unit: MiB +counter_cache_size: + +# Duration in seconds after which Cassandra should +# save the counter cache (keys only). Caches are saved to saved_caches_directory as +# specified in this configuration file. +# +# Default is 7200 or 2 hours. +# Min unit: s +counter_cache_save_period: 7200s + +# Number of keys from the counter cache to save +# Disabled by default, meaning all keys are going to be saved +# counter_cache_keys_to_save: 100 + +# saved caches +# If not set, the default directory is $CASSANDRA_HOME/data/saved_caches. +# saved_caches_directory: /var/lib/cassandra/saved_caches + +# Number of seconds the server will wait for each cache (row, key, etc ...) to load while starting +# the Cassandra process. Setting this to zero is equivalent to disabling all cache loading on startup +# while still having the cache during runtime. +# Min unit: s +# cache_load_timeout: 30s + +# commitlog_sync may be either "periodic", "group", or "batch." +# +# When in batch mode, Cassandra won't ack writes until the commit log +# has been flushed to disk. Each incoming write will trigger the flush task. +# commitlog_sync_batch_window_in_ms is a deprecated value. Previously it had +# almost no value, and is being removed. +# +# commitlog_sync_batch_window_in_ms: 2 +# +# group mode is similar to batch mode, where Cassandra will not ack writes +# until the commit log has been flushed to disk. The difference is group +# mode will wait up to commitlog_sync_group_window between flushes. +# +# Min unit: ms +# commitlog_sync_group_window: 1000ms +# +# the default option is "periodic" where writes may be acked immediately +# and the CommitLog is simply synced every commitlog_sync_period +# milliseconds. +commitlog_sync: periodic +# Min unit: ms +commitlog_sync_period: 10000ms + +# When in periodic commitlog mode, the number of milliseconds to block writes +# while waiting for a slow disk flush to complete. +# Min unit: ms +# periodic_commitlog_sync_lag_block: + +# The size of the individual commitlog file segments. A commitlog +# segment may be archived, deleted, or recycled once all the data +# in it (potentially from each columnfamily in the system) has been +# flushed to sstables. +# +# The default size is 32, which is almost always fine, but if you are +# archiving commitlog segments (see commitlog_archiving.properties), +# then you probably want a finer granularity of archiving; 8 or 16 MB +# is reasonable. +# Max mutation size is also configurable via max_mutation_size setting in +# cassandra.yaml. The default is half the size commitlog_segment_size in bytes. +# This should be positive and less than 2048. +# +# NOTE: If max_mutation_size is set explicitly then commitlog_segment_size must +# be set to at least twice the size of max_mutation_size +# +# Min unit: MiB +commitlog_segment_size: 32MiB + +# Compression to apply to the commit log. If omitted, the commit log +# will be written uncompressed. LZ4, Snappy, and Deflate compressors +# are supported. +# commitlog_compression: +# - class_name: LZ4Compressor +# parameters: +# - + +# Compression to apply to SSTables as they flush for compressed tables. +# Note that tables without compression enabled do not respect this flag. +# +# As high ratio compressors like LZ4HC, Zstd, and Deflate can potentially +# block flushes for too long, the default is to flush with a known fast +# compressor in those cases. Options are: +# +# none : Flush without compressing blocks but while still doing checksums. +# fast : Flush with a fast compressor. If the table is already using a +# fast compressor that compressor is used. +# table: Always flush with the same compressor that the table uses. This +# was the pre 4.0 behavior. +# +# flush_compression: fast + +# any class that implements the SeedProvider interface and has a +# constructor that takes a Map of parameters will do. +seed_provider: + # Addresses of hosts that are deemed contact points. + # Cassandra nodes use this list of hosts to find each other and learn + # the topology of the ring. You must change this if you are running + # multiple nodes! + - class_name: org.apache.cassandra.locator.SimpleSeedProvider + parameters: + # seeds is actually a comma-delimited list of addresses. + # Ex: ",," + - seeds: "172.30.0.10" + +# For workloads with more data than can fit in memory, Cassandra's +# bottleneck will be reads that need to fetch data from +# disk. "concurrent_reads" should be set to (16 * number_of_drives) in +# order to allow the operations to enqueue low enough in the stack +# that the OS and drives can reorder them. Same applies to +# "concurrent_counter_writes", since counter writes read the current +# values before incrementing and writing them back. +# +# On the other hand, since writes are almost never IO bound, the ideal +# number of "concurrent_writes" is dependent on the number of cores in +# your system; (8 * number_of_cores) is a good rule of thumb. +concurrent_reads: 32 +concurrent_writes: 32 +concurrent_counter_writes: 32 + +# For materialized view writes, as there is a read involved, so this should +# be limited by the less of concurrent reads or concurrent writes. +concurrent_materialized_view_writes: 32 + +# Maximum memory to use for inter-node and client-server networking buffers. +# +# Defaults to the smaller of 1/16 of heap or 128MB. This pool is allocated off-heap, +# so is in addition to the memory allocated for heap. The cache also has on-heap +# overhead which is roughly 128 bytes per chunk (i.e. 0.2% of the reserved size +# if the default 64k chunk size is used). +# Memory is only allocated when needed. +# Min unit: MiB +# networking_cache_size: 128MiB + +# Enable the sstable chunk cache. The chunk cache will store recently accessed +# sections of the sstable in-memory as uncompressed buffers. +# file_cache_enabled: false + +# Maximum memory to use for sstable chunk cache and buffer pooling. +# 32MB of this are reserved for pooling buffers, the rest is used for chunk cache +# that holds uncompressed sstable chunks. +# Defaults to the smaller of 1/4 of heap or 512MB. This pool is allocated off-heap, +# so is in addition to the memory allocated for heap. The cache also has on-heap +# overhead which is roughly 128 bytes per chunk (i.e. 0.2% of the reserved size +# if the default 64k chunk size is used). +# Memory is only allocated when needed. +# Min unit: MiB +# file_cache_size: 512MiB + +# Flag indicating whether to allocate on or off heap when the sstable buffer +# pool is exhausted, that is when it has exceeded the maximum memory +# file_cache_size, beyond which it will not cache buffers but allocate on request. + +# buffer_pool_use_heap_if_exhausted: true + +# The strategy for optimizing disk read +# Possible values are: +# ssd (for solid state disks, the default) +# spinning (for spinning disks) +# disk_optimization_strategy: ssd + +# Total permitted memory to use for memtables. Cassandra will stop +# accepting writes when the limit is exceeded until a flush completes, +# and will trigger a flush based on memtable_cleanup_threshold +# If omitted, Cassandra will set both to 1/4 the size of the heap. +# Min unit: MiB +# memtable_heap_space: 2048MiB +# Min unit: MiB +# memtable_offheap_space: 2048MiB + +# memtable_cleanup_threshold is deprecated. The default calculation +# is the only reasonable choice. See the comments on memtable_flush_writers +# for more information. +# +# Ratio of occupied non-flushing memtable size to total permitted size +# that will trigger a flush of the largest memtable. Larger mct will +# mean larger flushes and hence less compaction, but also less concurrent +# flush activity which can make it difficult to keep your disks fed +# under heavy write load. +# +# memtable_cleanup_threshold defaults to 1 / (memtable_flush_writers + 1) +# memtable_cleanup_threshold: 0.11 + +# Specify the way Cassandra allocates and manages memtable memory. +# Options are: +# +# heap_buffers +# on heap nio buffers +# +# offheap_buffers +# off heap (direct) nio buffers +# +# offheap_objects +# off heap objects +memtable_allocation_type: heap_buffers + +# Limit memory usage for Merkle tree calculations during repairs. The default +# is 1/16th of the available heap. The main tradeoff is that smaller trees +# have less resolution, which can lead to over-streaming data. If you see heap +# pressure during repairs, consider lowering this, but you cannot go below +# one mebibyte. If you see lots of over-streaming, consider raising +# this or using subrange repair. +# +# For more details see https://issues.apache.org/jira/browse/CASSANDRA-14096. +# +# Min unit: MiB +# repair_session_space: + +# Total space to use for commit logs on disk. +# +# If space gets above this value, Cassandra will flush every dirty CF +# in the oldest segment and remove it. So a small total commitlog space +# will tend to cause more flush activity on less-active columnfamilies. +# +# The default value is the smaller of 8192, and 1/4 of the total space +# of the commitlog volume. +# +# commitlog_total_space: 8192MiB + +# This sets the number of memtable flush writer threads per disk +# as well as the total number of memtables that can be flushed concurrently. +# These are generally a combination of compute and IO bound. +# +# Memtable flushing is more CPU efficient than memtable ingest and a single thread +# can keep up with the ingest rate of a whole server on a single fast disk +# until it temporarily becomes IO bound under contention typically with compaction. +# At that point you need multiple flush threads. At some point in the future +# it may become CPU bound all the time. +# +# You can tell if flushing is falling behind using the MemtablePool.BlockedOnAllocation +# metric which should be 0, but will be non-zero if threads are blocked waiting on flushing +# to free memory. +# +# memtable_flush_writers defaults to two for a single data directory. +# This means that two memtables can be flushed concurrently to the single data directory. +# If you have multiple data directories the default is one memtable flushing at a time +# but the flush will use a thread per data directory so you will get two or more writers. +# +# Two is generally enough to flush on a fast disk [array] mounted as a single data directory. +# Adding more flush writers will result in smaller more frequent flushes that introduce more +# compaction overhead. +# +# There is a direct tradeoff between number of memtables that can be flushed concurrently +# and flush size and frequency. More is not better you just need enough flush writers +# to never stall waiting for flushing to free memory. +# +# memtable_flush_writers: 2 + +# Total space to use for change-data-capture logs on disk. +# +# If space gets above this value, Cassandra will throw WriteTimeoutException +# on Mutations including tables with CDC enabled. A CDCCompactor is responsible +# for parsing the raw CDC logs and deleting them when parsing is completed. +# +# The default value is the min of 4096 MiB and 1/8th of the total space +# of the drive where cdc_raw_directory resides. +# Min unit: MiB +# cdc_total_space: 4096MiB + +# When we hit our cdc_raw limit and the CDCCompactor is either running behind +# or experiencing backpressure, we check at the following interval to see if any +# new space for cdc-tracked tables has been made available. Default to 250ms +# Min unit: ms +# cdc_free_space_check_interval: 250ms + +# A fixed memory pool size in MB for for SSTable index summaries. If left +# empty, this will default to 5% of the heap size. If the memory usage of +# all index summaries exceeds this limit, SSTables with low read rates will +# shrink their index summaries in order to meet this limit. However, this +# is a best-effort process. In extreme conditions Cassandra may need to use +# more than this amount of memory. +# Min unit: KiB +index_summary_capacity: + +# How frequently index summaries should be resampled. This is done +# periodically to redistribute memory from the fixed-size pool to sstables +# proportional their recent read rates. Setting to null value will disable this +# process, leaving existing index summaries at their current sampling level. +# Min unit: m +index_summary_resize_interval: 60m + +# Whether to, when doing sequential writing, fsync() at intervals in +# order to force the operating system to flush the dirty +# buffers. Enable this to avoid sudden dirty buffer flushing from +# impacting read latencies. Almost always a good idea on SSDs; not +# necessarily on platters. +trickle_fsync: false +# Min unit: KiB +trickle_fsync_interval: 10240KiB + +# TCP port, for commands and data +# For security reasons, you should not expose this port to the internet. Firewall it if needed. +storage_port: 7000 + +# SSL port, for legacy encrypted communication. This property is unused unless enabled in +# server_encryption_options (see below). As of cassandra 4.0, this property is deprecated +# as a single port can be used for either/both secure and insecure connections. +# For security reasons, you should not expose this port to the internet. Firewall it if needed. +ssl_storage_port: 7001 + +# Address or interface to bind to and tell other Cassandra nodes to connect to. +# You _must_ change this if you want multiple nodes to be able to communicate! +# +# Set listen_address OR listen_interface, not both. +# +# Leaving it blank leaves it up to InetAddress.getLocalHost(). This +# will always do the Right Thing _if_ the node is properly configured +# (hostname, name resolution, etc), and the Right Thing is to use the +# address associated with the hostname (it might not be). If unresolvable +# it will fall back to InetAddress.getLoopbackAddress(), which is wrong for production systems. +# +# Setting listen_address to 0.0.0.0 is always wrong. +# +listen_address: 172.30.0.10 + +# Set listen_address OR listen_interface, not both. Interfaces must correspond +# to a single address, IP aliasing is not supported. +# listen_interface: eth0 + +# If you choose to specify the interface by name and the interface has an ipv4 and an ipv6 address +# you can specify which should be chosen using listen_interface_prefer_ipv6. If false the first ipv4 +# address will be used. If true the first ipv6 address will be used. Defaults to false preferring +# ipv4. If there is only one address it will be selected regardless of ipv4/ipv6. +# listen_interface_prefer_ipv6: false + +# Address to broadcast to other Cassandra nodes +# Leaving this blank will set it to the same value as listen_address +broadcast_address: 172.30.0.10 + +# When using multiple physical network interfaces, set this +# to true to listen on broadcast_address in addition to +# the listen_address, allowing nodes to communicate in both +# interfaces. +# Ignore this property if the network configuration automatically +# routes between the public and private networks such as EC2. +# listen_on_broadcast_address: false + +# Internode authentication backend, implementing IInternodeAuthenticator; +# used to allow/disallow connections from peer nodes. +# internode_authenticator: org.apache.cassandra.auth.AllowAllInternodeAuthenticator + +# Whether to start the native transport server. +# The address on which the native transport is bound is defined by rpc_address. +start_native_transport: true +# port for the CQL native transport to listen for clients on +# For security reasons, you should not expose this port to the internet. Firewall it if needed. +native_transport_port: 9042 +# Enabling native transport encryption in client_encryption_options allows you to either use +# encryption for the standard port or to use a dedicated, additional port along with the unencrypted +# standard native_transport_port. +# Enabling client encryption and keeping native_transport_port_ssl disabled will use encryption +# for native_transport_port. Setting native_transport_port_ssl to a different value +# from native_transport_port will use encryption for native_transport_port_ssl while +# keeping native_transport_port unencrypted. +# native_transport_port_ssl: 9142 +# The maximum threads for handling requests (note that idle threads are stopped +# after 30 seconds so there is not corresponding minimum setting). +# native_transport_max_threads: 128 +# +# The maximum size of allowed frame. Frame (requests) larger than this will +# be rejected as invalid. The default is 16MiB. If you're changing this parameter, +# you may want to adjust max_value_size accordingly. This should be positive and less than 2048. +# Min unit: MiB +# native_transport_max_frame_size: 16MiB + +# The maximum number of concurrent client connections. +# The default is -1, which means unlimited. +# native_transport_max_concurrent_connections: -1 + +# The maximum number of concurrent client connections per source ip. +# The default is -1, which means unlimited. +# native_transport_max_concurrent_connections_per_ip: -1 + +# Controls whether Cassandra honors older, yet currently supported, protocol versions. +# The default is true, which means all supported protocols will be honored. +native_transport_allow_older_protocols: true + +# Controls when idle client connections are closed. Idle connections are ones that had neither reads +# nor writes for a time period. +# +# Clients may implement heartbeats by sending OPTIONS native protocol message after a timeout, which +# will reset idle timeout timer on the server side. To close idle client connections, corresponding +# values for heartbeat intervals have to be set on the client side. +# +# Idle connection timeouts are disabled by default. +# Min unit: ms +# native_transport_idle_timeout: 60000ms + +# When enabled, limits the number of native transport requests dispatched for processing per second. +# Behavior once the limit has been breached depends on the value of THROW_ON_OVERLOAD specified in +# the STARTUP message sent by the client during connection establishment. (See section "4.1.1. STARTUP" +# in "CQL BINARY PROTOCOL v5".) With the THROW_ON_OVERLOAD flag enabled, messages that breach the limit +# are dropped, and an OverloadedException is thrown for the client to handle. When the flag is not +# enabled, the server will stop consuming messages from the channel/socket, putting backpressure on +# the client while already dispatched messages are processed. +# native_transport_rate_limiting_enabled: false +# native_transport_max_requests_per_second: 1000000 + +# The address or interface to bind the native transport server to. +# +# Set rpc_address OR rpc_interface, not both. +# +# Leaving rpc_address blank has the same effect as on listen_address +# (i.e. it will be based on the configured hostname of the node). +# +# Note that unlike listen_address, you can specify 0.0.0.0, but you must also +# set broadcast_rpc_address to a value other than 0.0.0.0. +# +# For security reasons, you should not expose this port to the internet. Firewall it if needed. +rpc_address: 0.0.0.0 + +# Set rpc_address OR rpc_interface, not both. Interfaces must correspond +# to a single address, IP aliasing is not supported. +# rpc_interface: eth1 + +# If you choose to specify the interface by name and the interface has an ipv4 and an ipv6 address +# you can specify which should be chosen using rpc_interface_prefer_ipv6. If false the first ipv4 +# address will be used. If true the first ipv6 address will be used. Defaults to false preferring +# ipv4. If there is only one address it will be selected regardless of ipv4/ipv6. +# rpc_interface_prefer_ipv6: false + +# RPC address to broadcast to drivers and other Cassandra nodes. This cannot +# be set to 0.0.0.0. If left blank, this will be set to the value of +# rpc_address. If rpc_address is set to 0.0.0.0, broadcast_rpc_address must +# be set. +broadcast_rpc_address: 172.30.0.10 + +# enable or disable keepalive on rpc/native connections +rpc_keepalive: true + +# Uncomment to set socket buffer size for internode communication +# Note that when setting this, the buffer size is limited by net.core.wmem_max +# and when not setting it it is defined by net.ipv4.tcp_wmem +# See also: +# /proc/sys/net/core/wmem_max +# /proc/sys/net/core/rmem_max +# /proc/sys/net/ipv4/tcp_wmem +# /proc/sys/net/ipv4/tcp_wmem +# and 'man tcp' +# Min unit: B +# internode_socket_send_buffer_size: + +# Uncomment to set socket buffer size for internode communication +# Note that when setting this, the buffer size is limited by net.core.wmem_max +# and when not setting it it is defined by net.ipv4.tcp_wmem +# Min unit: B +# internode_socket_receive_buffer_size: + +# Set to true to have Cassandra create a hard link to each sstable +# flushed or streamed locally in a backups/ subdirectory of the +# keyspace data. Removing these links is the operator's +# responsibility. +incremental_backups: false + +# Whether or not to take a snapshot before each compaction. Be +# careful using this option, since Cassandra won't clean up the +# snapshots for you. Mostly useful if you're paranoid when there +# is a data format change. +snapshot_before_compaction: false + +# Whether or not a snapshot is taken of the data before keyspace truncation +# or dropping of column families. The STRONGLY advised default of true +# should be used to provide data safety. If you set this flag to false, you will +# lose data on truncation or drop. +auto_snapshot: true + +# Adds a time-to-live (TTL) to auto snapshots generated by table +# truncation or drop (when enabled). +# After the TTL is elapsed, the snapshot is automatically cleared. +# By default, auto snapshots *do not* have TTL, uncomment the property below +# to enable TTL on auto snapshots. +# Accepted units: d (days), h (hours) or m (minutes) +# auto_snapshot_ttl: 30d + +# The act of creating or clearing a snapshot involves creating or removing +# potentially tens of thousands of links, which can cause significant performance +# impact, especially on consumer grade SSDs. A non-zero value here can +# be used to throttle these links to avoid negative performance impact of +# taking and clearing snapshots +snapshot_links_per_second: 0 + +# Granularity of the collation index of rows within a partition. +# Increase if your rows are large, or if you have a very large +# number of rows per partition. The competing goals are these: +# +# - a smaller granularity means more index entries are generated +# and looking up rows withing the partition by collation column +# is faster +# - but, Cassandra will keep the collation index in memory for hot +# rows (as part of the key cache), so a larger granularity means +# you can cache more hot rows +# Min unit: KiB +column_index_size: 64KiB + +# Per sstable indexed key cache entries (the collation index in memory +# mentioned above) exceeding this size will not be held on heap. +# This means that only partition information is held on heap and the +# index entries are read from disk. +# +# Note that this size refers to the size of the +# serialized index information and not the size of the partition. +# Min unit: KiB +column_index_cache_size: 2KiB + +# Number of simultaneous compactions to allow, NOT including +# validation "compactions" for anti-entropy repair. Simultaneous +# compactions can help preserve read performance in a mixed read/write +# workload, by mitigating the tendency of small sstables to accumulate +# during a single long running compactions. The default is usually +# fine and if you experience problems with compaction running too +# slowly or too fast, you should look at +# compaction_throughput first. +# +# concurrent_compactors defaults to the smaller of (number of disks, +# number of cores), with a minimum of 2 and a maximum of 8. +# +# If your data directories are backed by SSD, you should increase this +# to the number of cores. +# concurrent_compactors: 1 + +# Number of simultaneous repair validations to allow. If not set or set to +# a value less than 1, it defaults to the value of concurrent_compactors. +# To set a value greeater than concurrent_compactors at startup, the system +# property cassandra.allow_unlimited_concurrent_validations must be set to +# true. To dynamically resize to a value > concurrent_compactors on a running +# node, first call the bypassConcurrentValidatorsLimit method on the +# org.apache.cassandra.db:type=StorageService mbean +# concurrent_validations: 0 + +# Number of simultaneous materialized view builder tasks to allow. +concurrent_materialized_view_builders: 1 + +# Throttles compaction to the given total throughput across the entire +# system. The faster you insert data, the faster you need to compact in +# order to keep the sstable count down, but in general, setting this to +# 16 to 32 times the rate you are inserting data is more than sufficient. +# Setting this to 0 disables throttling. Note that this accounts for all types +# of compaction, including validation compaction (building Merkle trees +# for repairs). +compaction_throughput: 64MiB/s + +# When compacting, the replacement sstable(s) can be opened before they +# are completely written, and used in place of the prior sstables for +# any range that has been written. This helps to smoothly transfer reads +# between the sstables, reducing page cache churn and keeping hot rows hot +# Set sstable_preemptive_open_interval to null for disabled which is equivalent to +# sstable_preemptive_open_interval_in_mb being negative +# Min unit: MiB +sstable_preemptive_open_interval: 50MiB + +# Starting from 4.1 sstables support UUID based generation identifiers. They are disabled by default +# because once enabled, there is no easy way to downgrade. When the node is restarted with this option +# set to true, each newly created sstable will have a UUID based generation identifier and such files are +# not readable by previous Cassandra versions. At some point, this option will become true by default +# and eventually get removed from the configuration. +uuid_sstable_identifiers_enabled: false + +# When enabled, permits Cassandra to zero-copy stream entire eligible +# SSTables between nodes, including every component. +# This speeds up the network transfer significantly subject to +# throttling specified by entire_sstable_stream_throughput_outbound, +# and entire_sstable_inter_dc_stream_throughput_outbound +# for inter-DC transfers. +# Enabling this will reduce the GC pressure on sending and receiving node. +# When unset, the default is enabled. While this feature tries to keep the +# disks balanced, it cannot guarantee it. This feature will be automatically +# disabled if internode encryption is enabled. +# stream_entire_sstables: true + +# Throttles entire SSTable outbound streaming file transfers on +# this node to the given total throughput in Mbps. +# Setting this value to 0 it disables throttling. +# When unset, the default is 200 Mbps or 24 MiB/s. +# entire_sstable_stream_throughput_outbound: 24MiB/s + +# Throttles entire SSTable file streaming between datacenters. +# Setting this value to 0 disables throttling for entire SSTable inter-DC file streaming. +# When unset, the default is 200 Mbps or 24 MiB/s. +# entire_sstable_inter_dc_stream_throughput_outbound: 24MiB/s + +# Throttles all outbound streaming file transfers on this node to the +# given total throughput in Mbps. This is necessary because Cassandra does +# mostly sequential IO when streaming data during bootstrap or repair, which +# can lead to saturating the network connection and degrading rpc performance. +# When unset, the default is 200 Mbps or 24 MiB/s. +# stream_throughput_outbound: 24MiB/s + +# Throttles all streaming file transfer between the datacenters, +# this setting allows users to throttle inter dc stream throughput in addition +# to throttling all network stream traffic as configured with +# stream_throughput_outbound_megabits_per_sec +# When unset, the default is 200 Mbps or 24 MiB/s. +# inter_dc_stream_throughput_outbound: 24MiB/s + +# Server side timeouts for requests. The server will return a timeout exception +# to the client if it can't complete an operation within the corresponding +# timeout. Those settings are a protection against: +# 1) having client wait on an operation that might never terminate due to some +# failures. +# 2) operations that use too much CPU/read too much data (leading to memory build +# up) by putting a limit to how long an operation will execute. +# For this reason, you should avoid putting these settings too high. In other words, +# if you are timing out requests because of underlying resource constraints then +# increasing the timeout will just cause more problems. Of course putting them too +# low is equally ill-advised since clients could get timeouts even for successful +# operations just because the timeout setting is too tight. + +# How long the coordinator should wait for read operations to complete. +# Lowest acceptable value is 10 ms. +# Min unit: ms +read_request_timeout: 5000ms +# How long the coordinator should wait for seq or index scans to complete. +# Lowest acceptable value is 10 ms. +# Min unit: ms +range_request_timeout: 10000ms +# How long the coordinator should wait for writes to complete. +# Lowest acceptable value is 10 ms. +# Min unit: ms +write_request_timeout: 2000ms +# How long the coordinator should wait for counter writes to complete. +# Lowest acceptable value is 10 ms. +# Min unit: ms +counter_write_request_timeout: 5000ms +# How long a coordinator should continue to retry a CAS operation +# that contends with other proposals for the same row. +# Lowest acceptable value is 10 ms. +# Min unit: ms +cas_contention_timeout: 1000ms +# How long the coordinator should wait for truncates to complete +# (This can be much longer, because unless auto_snapshot is disabled +# we need to flush first so we can snapshot before removing the data.) +# Lowest acceptable value is 10 ms. +# Min unit: ms +truncate_request_timeout: 60000ms +# The default timeout for other, miscellaneous operations. +# Lowest acceptable value is 10 ms. +# Min unit: ms +request_timeout: 10000ms + +# Defensive settings for protecting Cassandra from true network partitions. +# See (CASSANDRA-14358) for details. +# +# The amount of time to wait for internode tcp connections to establish. +# Min unit: ms +# internode_tcp_connect_timeout: 2000ms +# +# The amount of time unacknowledged data is allowed on a connection before we throw out the connection +# Note this is only supported on Linux + epoll, and it appears to behave oddly above a setting of 30000 +# (it takes much longer than 30s) as of Linux 4.12. If you want something that high set this to 0 +# which picks up the OS default and configure the net.ipv4.tcp_retries2 sysctl to be ~8. +# Min unit: ms +# internode_tcp_user_timeout: 30000ms + +# The amount of time unacknowledged data is allowed on a streaming connection. +# The default is 5 minutes. Increase it or set it to 0 in order to increase the timeout. +# Min unit: ms +# internode_streaming_tcp_user_timeout: 300000ms + +# Global, per-endpoint and per-connection limits imposed on messages queued for delivery to other nodes +# and waiting to be processed on arrival from other nodes in the cluster. These limits are applied to the on-wire +# size of the message being sent or received. +# +# The basic per-link limit is consumed in isolation before any endpoint or global limit is imposed. +# Each node-pair has three links: urgent, small and large. So any given node may have a maximum of +# N*3*(internode_application_send_queue_capacity+internode_application_receive_queue_capacity) +# messages queued without any coordination between them although in practice, with token-aware routing, only RF*tokens +# nodes should need to communicate with significant bandwidth. +# +# The per-endpoint limit is imposed on all messages exceeding the per-link limit, simultaneously with the global limit, +# on all links to or from a single node in the cluster. +# The global limit is imposed on all messages exceeding the per-link limit, simultaneously with the per-endpoint limit, +# on all links to or from any node in the cluster. +# +# Min unit: B +# internode_application_send_queue_capacity: 4MiB +# internode_application_send_queue_reserve_endpoint_capacity: 128MiB +# internode_application_send_queue_reserve_global_capacity: 512MiB +# internode_application_receive_queue_capacity: 4MiB +# internode_application_receive_queue_reserve_endpoint_capacity: 128MiB +# internode_application_receive_queue_reserve_global_capacity: 512MiB + + +# How long before a node logs slow queries. Select queries that take longer than +# this timeout to execute, will generate an aggregated log message, so that slow queries +# can be identified. Set this value to zero to disable slow query logging. +# Min unit: ms +slow_query_log_timeout: 500ms + +# Enable operation timeout information exchange between nodes to accurately +# measure request timeouts. If disabled, replicas will assume that requests +# were forwarded to them instantly by the coordinator, which means that +# under overload conditions we will waste that much extra time processing +# already-timed-out requests. +# +# Warning: It is generally assumed that users have setup NTP on their clusters, and that clocks are modestly in sync, +# since this is a requirement for general correctness of last write wins. +# internode_timeout: true + +# Set period for idle state control messages for earlier detection of failed streams +# This node will send a keep-alive message periodically on the streaming's control channel. +# This ensures that any eventual SocketTimeoutException will occur within 2 keep-alive cycles +# If the node cannot send, or timeouts sending, the keep-alive message on the netty control channel +# the stream session is closed. +# Default value is 300s (5 minutes), which means stalled streams +# are detected within 10 minutes +# Specify 0 to disable. +# Min unit: s +# streaming_keep_alive_period: 300s + +# Limit number of connections per host for streaming +# Increase this when you notice that joins are CPU-bound rather that network +# bound (for example a few nodes with big files). +# streaming_connections_per_host: 1 + +# Settings for stream stats tracking; used by system_views.streaming table +# How long before a stream is evicted from tracking; this impacts both historic and currently running +# streams. +# streaming_state_expires: 3d +# How much memory may be used for tracking before evicting session from tracking; once crossed +# historic and currently running streams maybe impacted. +# streaming_state_size: 40MiB +# Enable/Disable tracking of streaming stats +# streaming_stats_enabled: true + +# Allows denying configurable access (rw/rr) to operations on configured ks, table, and partitions, intended for use by +# operators to manage cluster health vs application access. See CASSANDRA-12106 and CEP-13 for more details. +# partition_denylist_enabled: false + +# denylist_writes_enabled: true +# denylist_reads_enabled: true +# denylist_range_reads_enabled: true + +# The interval at which keys in the cache for denylisting will "expire" and async refresh from the backing DB. +# Note: this serves only as a fail-safe, as the usage pattern is expected to be "mutate state, refresh cache" on any +# changes to the underlying denylist entries. See documentation for details. +# Min unit: s +# denylist_refresh: 600s + +# In the event of errors on attempting to load the denylist cache, retry on this interval. +# Min unit: s +# denylist_initial_load_retry: 5s + +# We cap the number of denylisted keys allowed per table to keep things from growing unbounded. Nodes will warn above +# this limit while allowing new denylisted keys to be inserted. Denied keys are loaded in natural query / clustering +# ordering by partition key in case of overflow. +# denylist_max_keys_per_table: 1000 + +# We cap the total number of denylisted keys allowed in the cluster to keep things from growing unbounded. +# Nodes will warn on initial cache load that there are too many keys and be direct the operator to trim down excess +# entries to within the configured limits. +# denylist_max_keys_total: 10000 + +# Since the denylist in many ways serves to protect the health of the cluster from partitions operators have identified +# as being in a bad state, we usually want more robustness than just CL.ONE on operations to/from these tables to +# ensure that these safeguards are in place. That said, we allow users to configure this if they're so inclined. +# denylist_consistency_level: QUORUM + +# phi value that must be reached for a host to be marked down. +# most users should never need to adjust this. +# phi_convict_threshold: 8 + +# endpoint_snitch -- Set this to a class that implements +# IEndpointSnitch. The snitch has two functions: +# +# - it teaches Cassandra enough about your network topology to route +# requests efficiently +# - it allows Cassandra to spread replicas around your cluster to avoid +# correlated failures. It does this by grouping machines into +# "datacenters" and "racks." Cassandra will do its best not to have +# more than one replica on the same "rack" (which may not actually +# be a physical location) +# +# CASSANDRA WILL NOT ALLOW YOU TO SWITCH TO AN INCOMPATIBLE SNITCH +# ONCE DATA IS INSERTED INTO THE CLUSTER. This would cause data loss. +# This means that if you start with the default SimpleSnitch, which +# locates every node on "rack1" in "datacenter1", your only options +# if you need to add another datacenter are GossipingPropertyFileSnitch +# (and the older PFS). From there, if you want to migrate to an +# incompatible snitch like Ec2Snitch you can do it by adding new nodes +# under Ec2Snitch (which will locate them in a new "datacenter") and +# decommissioning the old ones. +# +# Out of the box, Cassandra provides: +# +# SimpleSnitch: +# Treats Strategy order as proximity. This can improve cache +# locality when disabling read repair. Only appropriate for +# single-datacenter deployments. +# +# GossipingPropertyFileSnitch +# This should be your go-to snitch for production use. The rack +# and datacenter for the local node are defined in +# cassandra-rackdc.properties and propagated to other nodes via +# gossip. If cassandra-topology.properties exists, it is used as a +# fallback, allowing migration from the PropertyFileSnitch. +# +# PropertyFileSnitch: +# Proximity is determined by rack and data center, which are +# explicitly configured in cassandra-topology.properties. +# +# Ec2Snitch: +# Appropriate for EC2 deployments in a single Region. Loads Region +# and Availability Zone information from the EC2 API. The Region is +# treated as the datacenter, and the Availability Zone as the rack. +# Only private IPs are used, so this will not work across multiple +# Regions. +# +# Ec2MultiRegionSnitch: +# Uses public IPs as broadcast_address to allow cross-region +# connectivity. (Thus, you should set seed addresses to the public +# IP as well.) You will need to open the storage_port or +# ssl_storage_port on the public IP firewall. (For intra-Region +# traffic, Cassandra will switch to the private IP after +# establishing a connection.) +# +# RackInferringSnitch: +# Proximity is determined by rack and data center, which are +# assumed to correspond to the 3rd and 2nd octet of each node's IP +# address, respectively. Unless this happens to match your +# deployment conventions, this is best used as an example of +# writing a custom Snitch class and is provided in that spirit. +# +# You can use a custom Snitch by setting this to the full class name +# of the snitch, which will be assumed to be on your classpath. +endpoint_snitch: SimpleSnitch + +# controls how often to perform the more expensive part of host score +# calculation +# Min unit: ms +dynamic_snitch_update_interval: 100ms +# controls how often to reset all host scores, allowing a bad host to +# possibly recover +# Min unit: ms +dynamic_snitch_reset_interval: 600000ms +# if set greater than zero, this will allow +# 'pinning' of replicas to hosts in order to increase cache capacity. +# The badness threshold will control how much worse the pinned host has to be +# before the dynamic snitch will prefer other replicas over it. This is +# expressed as a double which represents a percentage. Thus, a value of +# 0.2 means Cassandra would continue to prefer the static snitch values +# until the pinned host was 20% worse than the fastest. +dynamic_snitch_badness_threshold: 1.0 + +# Configure server-to-server internode encryption +# +# JVM and netty defaults for supported SSL socket protocols and cipher suites can +# be replaced using custom encryption options. This is not recommended +# unless you have policies in place that dictate certain settings, or +# need to disable vulnerable ciphers or protocols in case the JVM cannot +# be updated. +# +# FIPS compliant settings can be configured at JVM level and should not +# involve changing encryption settings here: +# https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/FIPS.html +# +# **NOTE** this default configuration is an insecure configuration. If you need to +# enable server-to-server encryption generate server keystores (and truststores for mutual +# authentication) per: +# http://download.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#CreateKeystore +# Then perform the following configuration changes: +# +# Step 1: Set internode_encryption= and explicitly set optional=true. Restart all nodes +# +# Step 2: Set optional=false (or remove it) and if you generated truststores and want to use mutual +# auth set require_client_auth=true. Restart all nodes +server_encryption_options: + # On outbound connections, determine which type of peers to securely connect to. + # The available options are : + # none : Do not encrypt outgoing connections + # dc : Encrypt connections to peers in other datacenters but not within datacenters + # rack : Encrypt connections to peers in other racks but not within racks + # all : Always use encrypted connections + internode_encryption: none + # When set to true, encrypted and unencrypted connections are allowed on the storage_port + # This should _only be true_ while in unencrypted or transitional operation + # optional defaults to true if internode_encryption is none + # optional: true + # If enabled, will open up an encrypted listening socket on ssl_storage_port. Should only be used + # during upgrade to 4.0; otherwise, set to false. + legacy_ssl_storage_port_enabled: false + # Set to a valid keystore if internode_encryption is dc, rack or all + keystore: conf/.keystore + keystore_password: cassandra + # Configure the way Cassandra creates SSL contexts. + # To use PEM-based key material, see org.apache.cassandra.security.PEMBasedSslContextFactory + # ssl_context_factory: + # # Must be an instance of org.apache.cassandra.security.ISslContextFactory + # class_name: org.apache.cassandra.security.DefaultSslContextFactory + # Verify peer server certificates + require_client_auth: false + # Set to a valid trustore if require_client_auth is true + truststore: conf/.truststore + truststore_password: cassandra + # Verify that the host name in the certificate matches the connected host + require_endpoint_verification: false + # More advanced defaults: + # protocol: TLS + # store_type: JKS + # cipher_suites: [ + # TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, + # TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, + # TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA, + # TLS_RSA_WITH_AES_256_CBC_SHA + # ] + +# Configure client-to-server encryption. +# +# **NOTE** this default configuration is an insecure configuration. If you need to +# enable client-to-server encryption generate server keystores (and truststores for mutual +# authentication) per: +# http://download.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#CreateKeystore +# Then perform the following configuration changes: +# +# Step 1: Set enabled=true and explicitly set optional=true. Restart all nodes +# +# Step 2: Set optional=false (or remove it) and if you generated truststores and want to use mutual +# auth set require_client_auth=true. Restart all nodes +client_encryption_options: + # Enable client-to-server encryption + enabled: false + # When set to true, encrypted and unencrypted connections are allowed on the native_transport_port + # This should _only be true_ while in unencrypted or transitional operation + # optional defaults to true when enabled is false, and false when enabled is true. + # optional: true + # Set keystore and keystore_password to valid keystores if enabled is true + keystore: conf/.keystore + keystore_password: cassandra + # Configure the way Cassandra creates SSL contexts. + # To use PEM-based key material, see org.apache.cassandra.security.PEMBasedSslContextFactory + # ssl_context_factory: + # # Must be an instance of org.apache.cassandra.security.ISslContextFactory + # class_name: org.apache.cassandra.security.DefaultSslContextFactory + # Verify client certificates + require_client_auth: false + # Set trustore and truststore_password if require_client_auth is true + # truststore: conf/.truststore + # truststore_password: cassandra + # More advanced defaults: + # protocol: TLS + # store_type: JKS + # cipher_suites: [ + # TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, + # TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, + # TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA, + # TLS_RSA_WITH_AES_256_CBC_SHA + # ] + +# internode_compression controls whether traffic between nodes is +# compressed. +# Can be: +# +# all +# all traffic is compressed +# +# dc +# traffic between different datacenters is compressed +# +# none +# nothing is compressed. +internode_compression: dc + +# Enable or disable tcp_nodelay for inter-dc communication. +# Disabling it will result in larger (but fewer) network packets being sent, +# reducing overhead from the TCP protocol itself, at the cost of increasing +# latency if you block for cross-datacenter responses. +inter_dc_tcp_nodelay: false + +# TTL for different trace types used during logging of the repair process. +# Min unit: s +trace_type_query_ttl: 1d +# Min unit: s +trace_type_repair_ttl: 7d + +# If unset, all GC Pauses greater than gc_log_threshold will log at +# INFO level +# UDFs (user defined functions) are disabled by default. +# As of Cassandra 3.0 there is a sandbox in place that should prevent execution of evil code. +user_defined_functions_enabled: false + +# Enables scripted UDFs (JavaScript UDFs). +# Java UDFs are always enabled, if user_defined_functions_enabled is true. +# Enable this option to be able to use UDFs with "language javascript" or any custom JSR-223 provider. +# This option has no effect, if user_defined_functions_enabled is false. +scripted_user_defined_functions_enabled: false + +# Enables encrypting data at-rest (on disk). Different key providers can be plugged in, but the default reads from +# a JCE-style keystore. A single keystore can hold multiple keys, but the one referenced by +# the "key_alias" is the only key that will be used for encrypt opertaions; previously used keys +# can still (and should!) be in the keystore and will be used on decrypt operations +# (to handle the case of key rotation). +# +# It is strongly recommended to download and install Java Cryptography Extension (JCE) +# Unlimited Strength Jurisdiction Policy Files for your version of the JDK. +# (current link: http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html) +# +# Currently, only the following file types are supported for transparent data encryption, although +# more are coming in future cassandra releases: commitlog, hints +transparent_data_encryption_options: + enabled: false + chunk_length_kb: 64 + cipher: AES/CBC/PKCS5Padding + key_alias: testing:1 + # CBC IV length for AES needs to be 16 bytes (which is also the default size) + # iv_length: 16 + key_provider: + - class_name: org.apache.cassandra.security.JKSKeyProvider + parameters: + - keystore: conf/.keystore + keystore_password: cassandra + store_type: JCEKS + key_password: cassandra + + +##################### +# SAFETY THRESHOLDS # +##################### + +# When executing a scan, within or across a partition, we need to keep the +# tombstones seen in memory so we can return them to the coordinator, which +# will use them to make sure other replicas also know about the deleted rows. +# With workloads that generate a lot of tombstones, this can cause performance +# problems and even exaust the server heap. +# (http://www.datastax.com/dev/blog/cassandra-anti-patterns-queues-and-queue-like-datasets) +# Adjust the thresholds here if you understand the dangers and want to +# scan more tombstones anyway. These thresholds may also be adjusted at runtime +# using the StorageService mbean. +tombstone_warn_threshold: 1000 +tombstone_failure_threshold: 100000 + +# Filtering and secondary index queries at read consistency levels above ONE/LOCAL_ONE use a +# mechanism called replica filtering protection to ensure that results from stale replicas do +# not violate consistency. (See CASSANDRA-8272 and CASSANDRA-15907 for more details.) This +# mechanism materializes replica results by partition on-heap at the coordinator. The more possibly +# stale results returned by the replicas, the more rows materialized during the query. +replica_filtering_protection: + # These thresholds exist to limit the damage severely out-of-date replicas can cause during these + # queries. They limit the number of rows from all replicas individual index and filtering queries + # can materialize on-heap to return correct results at the desired read consistency level. + # + # "cached_replica_rows_warn_threshold" is the per-query threshold at which a warning will be logged. + # "cached_replica_rows_fail_threshold" is the per-query threshold at which the query will fail. + # + # These thresholds may also be adjusted at runtime using the StorageService mbean. + # + # If the failure threshold is breached, it is likely that either the current page/fetch size + # is too large or one or more replicas is severely out-of-sync and in need of repair. + cached_rows_warn_threshold: 2000 + cached_rows_fail_threshold: 32000 + +# Log WARN on any multiple-partition batch size exceeding this value. 5KiB per batch by default. +# Caution should be taken on increasing the size of this threshold as it can lead to node instability. +# Min unit: KiB +batch_size_warn_threshold: 5KiB + +# Fail any multiple-partition batch exceeding this value. 50KiB (10x warn threshold) by default. +# Min unit: KiB +batch_size_fail_threshold: 50KiB + +# Log WARN on any batches not of type LOGGED than span across more partitions than this limit +unlogged_batch_across_partitions_warn_threshold: 10 + +# Log a warning when compacting partitions larger than this value +compaction_large_partition_warning_threshold: 100MiB + +# Log a warning when writing more tombstones than this value to a partition +compaction_tombstone_warning_threshold: 100000 + +# GC Pauses greater than 200 ms will be logged at INFO level +# This threshold can be adjusted to minimize logging if necessary +# Min unit: ms +# gc_log_threshold: 200ms + +# GC Pauses greater than gc_warn_threshold will be logged at WARN level +# Adjust the threshold based on your application throughput requirement. Setting to 0 +# will deactivate the feature. +# Min unit: ms +# gc_warn_threshold: 1000ms + +# Maximum size of any value in SSTables. Safety measure to detect SSTable corruption +# early. Any value size larger than this threshold will result into marking an SSTable +# as corrupted. This should be positive and less than 2GiB. +# Min unit: MiB +# max_value_size: 256MiB + +# ** Impact on keyspace creation ** +# If replication factor is not mentioned as part of keyspace creation, default_keyspace_rf would apply. +# Changing this configuration would only take effect for keyspaces created after the change, but does not impact +# existing keyspaces created prior to the change. +# ** Impact on keyspace alter ** +# When altering a keyspace from NetworkTopologyStrategy to SimpleStrategy, default_keyspace_rf is applied if rf is not +# explicitly mentioned. +# ** Impact on system keyspaces ** +# This would also apply for any system keyspaces that need replication factor. +# A further note about system keyspaces - system_traces and system_distributed keyspaces take RF of 2 or default, +# whichever is higher, and system_auth keyspace takes RF of 1 or default, whichever is higher. +# Suggested value for use in production: 3 +# default_keyspace_rf: 1 + +# Track a metric per keyspace indicating whether replication achieved the ideal consistency +# level for writes without timing out. This is different from the consistency level requested by +# each write which may be lower in order to facilitate availability. +# ideal_consistency_level: EACH_QUORUM + +# Automatically upgrade sstables after upgrade - if there is no ordinary compaction to do, the +# oldest non-upgraded sstable will get upgraded to the latest version +# automatic_sstable_upgrade: false +# Limit the number of concurrent sstable upgrades +# max_concurrent_automatic_sstable_upgrades: 1 + +# Audit logging - Logs every incoming CQL command request, authentication to a node. See the docs +# on audit_logging for full details about the various configuration options. +audit_logging_options: + enabled: false + logger: + - class_name: BinAuditLogger + # audit_logs_dir: + # included_keyspaces: + # excluded_keyspaces: system, system_schema, system_virtual_schema + # included_categories: + # excluded_categories: + # included_users: + # excluded_users: + # roll_cycle: HOURLY + # block: true + # max_queue_weight: 268435456 # 256 MiB + # max_log_size: 17179869184 # 16 GiB + ## archive command is "/path/to/script.sh %path" where %path is replaced with the file being rolled: + # archive_command: + # max_archive_retries: 10 + + +# default options for full query logging - these can be overridden from command line when executing +# nodetool enablefullquerylog +# full_query_logging_options: + # log_dir: + # roll_cycle: HOURLY + # block: true + # max_queue_weight: 268435456 # 256 MiB + # max_log_size: 17179869184 # 16 GiB + ## archive command is "/path/to/script.sh %path" where %path is replaced with the file being rolled: + # archive_command: + ## note that enabling this allows anyone with JMX/nodetool access to run local shell commands as the user running cassandra + # allow_nodetool_archive_command: false + # max_archive_retries: 10 + +# validate tombstones on reads and compaction +# can be either "disabled", "warn" or "exception" +# corrupted_tombstone_strategy: disabled + +# Diagnostic Events # +# If enabled, diagnostic events can be helpful for troubleshooting operational issues. Emitted events contain details +# on internal state and temporal relationships across events, accessible by clients via JMX. +diagnostic_events_enabled: false + +# Use native transport TCP message coalescing. If on upgrade to 4.0 you found your throughput decreasing, and in +# particular you run an old kernel or have very fewer client connections, this option might be worth evaluating. +#native_transport_flush_in_batches_legacy: false + +# Enable tracking of repaired state of data during reads and comparison between replicas +# Mismatches between the repaired sets of replicas can be characterized as either confirmed +# or unconfirmed. In this context, unconfirmed indicates that the presence of pending repair +# sessions, unrepaired partition tombstones, or some other condition means that the disparity +# cannot be considered conclusive. Confirmed mismatches should be a trigger for investigation +# as they may be indicative of corruption or data loss. +# There are separate flags for range vs partition reads as single partition reads are only tracked +# when CL > 1 and a digest mismatch occurs. Currently, range queries don't use digests so if +# enabled for range reads, all range reads will include repaired data tracking. As this adds +# some overhead, operators may wish to disable it whilst still enabling it for partition reads +repaired_data_tracking_for_range_reads_enabled: false +repaired_data_tracking_for_partition_reads_enabled: false +# If false, only confirmed mismatches will be reported. If true, a separate metric for unconfirmed +# mismatches will also be recorded. This is to avoid potential signal:noise issues are unconfirmed +# mismatches are less actionable than confirmed ones. +report_unconfirmed_repaired_data_mismatches: false + +# Having many tables and/or keyspaces negatively affects performance of many operations in the +# cluster. When the number of tables/keyspaces in the cluster exceeds the following thresholds +# a client warning will be sent back to the user when creating a table or keyspace. +# As of cassandra 4.1, these properties are deprecated in favor of keyspaces_warn_threshold and tables_warn_threshold +# table_count_warn_threshold: 150 +# keyspace_count_warn_threshold: 40 + +# configure the read and write consistency levels for modifications to auth tables +# auth_read_consistency_level: LOCAL_QUORUM +# auth_write_consistency_level: EACH_QUORUM + +# Delays on auth resolution can lead to a thundering herd problem on reconnects; this option will enable +# warming of auth caches prior to node completing startup. See CASSANDRA-16958 +# auth_cache_warming_enabled: false + +######################### +# EXPERIMENTAL FEATURES # +######################### + +# Enables materialized view creation on this node. +# Materialized views are considered experimental and are not recommended for production use. +materialized_views_enabled: false + +# Enables SASI index creation on this node. +# SASI indexes are considered experimental and are not recommended for production use. +sasi_indexes_enabled: false + +# Enables creation of transiently replicated keyspaces on this node. +# Transient replication is experimental and is not recommended for production use. +transient_replication_enabled: false + +# Enables the used of 'ALTER ... DROP COMPACT STORAGE' statements on this node. +# 'ALTER ... DROP COMPACT STORAGE' is considered experimental and is not recommended for production use. +drop_compact_storage_enabled: false + +# Whether or not USE is allowed. This is enabled by default to avoid failure on upgrade. +#use_statements_enabled: true + +# When the client triggers a protocol exception or unknown issue (Cassandra bug) we increment +# a client metric showing this; this logic will exclude specific subnets from updating these +# metrics +#client_error_reporting_exclusions: +# subnets: +# - 127.0.0.1 +# - 127.0.0.0/31 + +# Enables read thresholds (warn/fail) across all replicas for reporting back to the client. +# See: CASSANDRA-16850 +# read_thresholds_enabled: false # scheduled to be set true in 4.2 +# When read_thresholds_enabled: true, this tracks the materialized size of a query on the +# coordinator. If coordinator_read_size_warn_threshold is defined, this will emit a warning +# to clients with details on what query triggered this as well as the size of the result set; if +# coordinator_read_size_fail_threshold is defined, this will fail the query after it +# has exceeded this threshold, returning a read error to the user. +# coordinator_read_size_warn_threshold: +# coordinator_read_size_fail_threshold: +# When read_thresholds_enabled: true, this tracks the size of the local read (as defined by +# heap size), and will warn/fail based off these thresholds; undefined disables these checks. +# local_read_size_warn_threshold: +# local_read_size_fail_threshold: +# When read_thresholds_enabled: true, this tracks the expected memory size of the RowIndexEntry +# and will warn/fail based off these thresholds; undefined disables these checks +# row_index_read_size_warn_threshold: +# row_index_read_size_fail_threshold: + +# Guardrail to warn or fail when creating more user keyspaces than threshold. +# The two thresholds default to -1 to disable. +# keyspaces_warn_threshold: -1 +# keyspaces_fail_threshold: -1 +# Guardrail to warn or fail when creating more user tables than threshold. +# The two thresholds default to -1 to disable. +# tables_warn_threshold: -1 +# tables_fail_threshold: -1 +# Guardrail to enable or disable the ability to create uncompressed tables +# uncompressed_tables_enabled: true +# Guardrail to warn or fail when creating/altering a table with more columns per table than threshold. +# The two thresholds default to -1 to disable. +# columns_per_table_warn_threshold: -1 +# columns_per_table_fail_threshold: -1 +# Guardrail to warn or fail when creating more secondary indexes per table than threshold. +# The two thresholds default to -1 to disable. +# secondary_indexes_per_table_warn_threshold: -1 +# secondary_indexes_per_table_fail_threshold: -1 +# Guardrail to enable or disable the creation of secondary indexes +# secondary_indexes_enabled: true +# Guardrail to warn or fail when creating more materialized views per table than threshold. +# The two thresholds default to -1 to disable. +# materialized_views_per_table_warn_threshold: -1 +# materialized_views_per_table_fail_threshold: -1 +# Guardrail to warn about, ignore or reject properties when creating tables. By default all properties are allowed. +# table_properties_warned: [] +# table_properties_ignored: [] +# table_properties_disallowed: [] +# Guardrail to allow/disallow user-provided timestamps. Defaults to true. +# user_timestamps_enabled: true +# Guardrail to allow/disallow GROUP BY functionality. +# group_by_enabled: true +# Guardrail to allow/disallow TRUNCATE and DROP TABLE statements +# drop_truncate_table_enabled: true +# Guardrail to warn or fail when using a page size greater than threshold. +# The two thresholds default to -1 to disable. +# page_size_warn_threshold: -1 +# page_size_fail_threshold: -1 +# Guardrail to allow/disallow list operations that require read before write, i.e. setting list element by index and +# removing list elements by either index or value. Defaults to true. +# read_before_write_list_operations_enabled: true +# Guardrail to warn or fail when querying with an IN restriction selecting more partition keys than threshold. +# The two thresholds default to -1 to disable. +# partition_keys_in_select_warn_threshold: -1 +# partition_keys_in_select_fail_threshold: -1 +# Guardrail to warn or fail when an IN query creates a cartesian product with a size exceeding threshold, +# eg. "a in (1,2,...10) and b in (1,2...10)" results in cartesian product of 100. +# The two thresholds default to -1 to disable. +# in_select_cartesian_product_warn_threshold: -1 +# in_select_cartesian_product_fail_threshold: -1 +# Guardrail to warn about or reject read consistency levels. By default, all consistency levels are allowed. +# read_consistency_levels_warned: [] +# read_consistency_levels_disallowed: [] +# Guardrail to warn about or reject write consistency levels. By default, all consistency levels are allowed. +# write_consistency_levels_warned: [] +# write_consistency_levels_disallowed: [] +# Guardrail to warn or fail when encountering larger size of collection data than threshold. +# At query time this guardrail is applied only to the collection fragment that is being writen, even though in the case +# of non-frozen collections there could be unaccounted parts of the collection on the sstables. This is done this way to +# prevent read-before-write. The guardrail is also checked at sstable write time to detect large non-frozen collections, +# although in that case exceeding the fail threshold will only log an error message, without interrupting the operation. +# The two thresholds default to null to disable. +# Min unit: B +# collection_size_warn_threshold: +# Min unit: B +# collection_size_fail_threshold: +# Guardrail to warn or fail when encountering more elements in collection than threshold. +# At query time this guardrail is applied only to the collection fragment that is being writen, even though in the case +# of non-frozen collections there could be unaccounted parts of the collection on the sstables. This is done this way to +# prevent read-before-write. The guardrail is also checked at sstable write time to detect large non-frozen collections, +# although in that case exceeding the fail threshold will only log an error message, without interrupting the operation. +# The two thresholds default to -1 to disable. +# items_per_collection_warn_threshold: -1 +# items_per_collection_fail_threshold: -1 +# Guardrail to allow/disallow querying with ALLOW FILTERING. Defaults to true. +# allow_filtering_enabled: true +# Guardrail to warn or fail when creating a user-defined-type with more fields in than threshold. +# Default -1 to disable. +# fields_per_udt_warn_threshold: -1 +# fields_per_udt_fail_threshold: -1 +# Guardrail to warn or fail when local data disk usage percentage exceeds threshold. Valid values are in [1, 100]. +# This is only used for the disks storing data directories, so it won't count any separate disks used for storing +# the commitlog, hints nor saved caches. The disk usage is the ratio between the amount of space used by the data +# directories and the addition of that same space and the remaining free space on disk. The main purpose of this +# guardrail is rejecting user writes when the disks are over the defined usage percentage, so the writes done by +# background processes such as compaction and streaming don't fail due to a full disk. The limits should be defined +# accordingly to the expected data growth due to those background processes, so for example a compaction strategy +# doubling the size of the data would require to keep the disk usage under 50%. +# The two thresholds default to -1 to disable. +# data_disk_usage_percentage_warn_threshold: -1 +# data_disk_usage_percentage_fail_threshold: -1 +# Allows defining the max disk size of the data directories when calculating thresholds for +# disk_usage_percentage_warn_threshold and disk_usage_percentage_fail_threshold, so if this is greater than zero they +# become percentages of a fixed size on disk instead of percentages of the physically available disk size. This should +# be useful when we have a large disk and we only want to use a part of it for Cassandra's data directories. +# Valid values are in [1, max available disk size of all data directories]. +# Defaults to null to disable and use the physically available disk size of data directories during calculations. +# Min unit: B +# data_disk_usage_max_disk_size: +# Guardrail to warn or fail when the minimum replication factor is lesser than threshold. +# This would also apply to system keyspaces. +# Suggested value for use in production: 2 or higher +# minimum_replication_factor_warn_threshold: -1 +# minimum_replication_factor_fail_threshold: -1 + +# Startup Checks are executed as part of Cassandra startup process, not all of them +# are configurable (so you can disable them) but these which are enumerated bellow. +# Uncomment the startup checks and configure them appropriately to cover your needs. +# +#startup_checks: +# Verifies correct ownership of attached locations on disk at startup. See CASSANDRA-16879 for more details. +# check_filesystem_ownership: +# enabled: false +# ownership_token: "sometoken" # (overriden by "CassandraOwnershipToken" system property) +# ownership_filename: ".cassandra_fs_ownership" # (overriden by "cassandra.fs_ownership_filename") +# Prevents a node from starting if snitch's data center differs from previous data center. +# check_dc: +# enabled: true # (overriden by cassandra.ignore_dc system property) +# Prevents a node from starting if snitch's rack differs from previous rack. +# check_rack: +# enabled: true # (overriden by cassandra.ignore_rack system property) +# Enable this property to fail startup if the node is down for longer than gc_grace_seconds, to potentially +# prevent data resurrection on tables with deletes. By default, this will run against all keyspaces and tables +# except the ones specified on excluded_keyspaces and excluded_tables. +# check_data_resurrection: +# enabled: false +# file where Cassandra periodically writes the last time it was known to run +# heartbeat_file: /var/lib/cassandra/data/cassandra-heartbeat +# excluded_keyspaces: # comma separated list of keyspaces to exclude from the check +# excluded_tables: # comma separated list of keyspace.table pairs to exclude from the check + diff --git a/sink/docker-compose.cassandra.yml b/sink/docker-compose.cassandra.yml new file mode 100644 index 000000000..42519ff9c --- /dev/null +++ b/sink/docker-compose.cassandra.yml @@ -0,0 +1,10 @@ +version: '3' + +services: + cassandra: + image: cassandra + volumes: + - ./cassandra.yaml:/etc/cassandra/cassandra.yaml + ports: + - "9042:9042" + From a0f0593e2d4e9ac66d2fbb8d162c0590b7a6278d Mon Sep 17 00:00:00 2001 From: Akhil Mohan Date: Mon, 22 Apr 2024 16:14:55 +0530 Subject: [PATCH 27/99] feat(server): added dynamic secret cassandra --- backend/package-lock.json | 32 +++++ backend/package.json | 1 + .../dynamic-secret/providers/cassandra.ts | 125 ++++++++++++++++++ .../dynamic-secret/providers/index.ts | 4 +- .../dynamic-secret/providers/models.ts | 19 ++- .../dynamic-secret/providers/sql-database.ts | 66 ++++----- 6 files changed, 211 insertions(+), 36 deletions(-) create mode 100644 backend/src/ee/services/dynamic-secret/providers/cassandra.ts diff --git a/backend/package-lock.json b/backend/package-lock.json index 1ef6c19e2..98b15e5f5 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -35,6 +35,7 @@ "axios-retry": "^4.0.0", "bcrypt": "^5.1.1", "bullmq": "^5.3.3", + "cassandra-driver": "^4.7.2", "dotenv": "^16.4.1", "fastify": "^4.26.0", "fastify-plugin": "^4.5.1", @@ -4565,6 +4566,15 @@ "@types/lodash": "*" } }, + "node_modules/@types/long": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@types/long/-/long-5.0.0.tgz", + "integrity": "sha512-eQs9RsucA/LNjnMoJvWG/nXa7Pot/RbBzilF/QRIU/xRl+0ApxrSUFsV5lmf01SvSlqMzJ7Zwxe440wmz2SJGA==", + "deprecated": "This is a stub types definition. long provides its own type definitions, so you do not need this installed.", + "dependencies": { + "long": "*" + } + }, "node_modules/@types/mime": { "version": "1.3.5", "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", @@ -5313,6 +5323,14 @@ "node": ">=0.4.0" } }, + "node_modules/adm-zip": { + "version": "0.5.12", + "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.12.tgz", + "integrity": "sha512-6TVU49mK6KZb4qG6xWaaM4C7sA/sgUMLy/JYMOzkcp3BvVLpW0fXDFQiIzAuxFCt/2+xD7fNIiPFAoLZPhVNLQ==", + "engines": { + "node": ">=6.0" + } + }, "node_modules/agent-base": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", @@ -6190,6 +6208,20 @@ "node": ">=6" } }, + "node_modules/cassandra-driver": { + "version": "4.7.2", + "resolved": "https://registry.npmjs.org/cassandra-driver/-/cassandra-driver-4.7.2.tgz", + "integrity": "sha512-gwl1DeYvL8Wy3i1GDMzFtpUg5G473fU7EnHFZj7BUtdLB7loAfgZgB3zBhROc9fbaDSUDs6YwOPPojS5E1kbSA==", + "dependencies": { + "@types/long": "~5.0.0", + "@types/node": ">=8", + "adm-zip": "~0.5.10", + "long": "~5.2.3" + }, + "engines": { + "node": ">=16" + } + }, "node_modules/chai": { "version": "4.4.1", "resolved": "https://registry.npmjs.org/chai/-/chai-4.4.1.tgz", diff --git a/backend/package.json b/backend/package.json index f53ec9329..0f7b5a590 100644 --- a/backend/package.json +++ b/backend/package.json @@ -96,6 +96,7 @@ "axios-retry": "^4.0.0", "bcrypt": "^5.1.1", "bullmq": "^5.3.3", + "cassandra-driver": "^4.7.2", "dotenv": "^16.4.1", "fastify": "^4.26.0", "fastify-plugin": "^4.5.1", diff --git a/backend/src/ee/services/dynamic-secret/providers/cassandra.ts b/backend/src/ee/services/dynamic-secret/providers/cassandra.ts new file mode 100644 index 000000000..aea0b9c99 --- /dev/null +++ b/backend/src/ee/services/dynamic-secret/providers/cassandra.ts @@ -0,0 +1,125 @@ +import cassandra from "cassandra-driver"; +import handlebars from "handlebars"; +import { customAlphabet } from "nanoid"; +import { z } from "zod"; + +import { BadRequestError } from "@app/lib/errors"; +import { alphaNumericNanoId } from "@app/lib/nanoid"; + +import { DynamicSecretCassandraSchema, TDynamicProviderFns } from "./models"; + +const generatePassword = (size = 48) => { + const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~!*$#"; + return customAlphabet(charset, 48)(size); +}; + +const generateUsername = () => { + return alphaNumericNanoId(32); +}; + +export const CassandraProvider = (): TDynamicProviderFns => { + const validateProviderInputs = async (inputs: unknown) => { + const providerInputs = await DynamicSecretCassandraSchema.parseAsync(inputs); + if (providerInputs.host === "localhost" || providerInputs.host === "127.0.0.1") { + throw new BadRequestError({ message: "Invalid db host" }); + } + + return providerInputs; + }; + + const getClient = async (providerInputs: z.infer) => { + const sslOptions = providerInputs.ca ? { rejectUnauthorized: false, ca: providerInputs.ca } : undefined; + const client = new cassandra.Client({ + sslOptions, + protocolOptions: { + port: providerInputs.port + }, + credentials: { + username: providerInputs.username, + password: providerInputs.password + }, + keyspace: providerInputs.keyspace, + localDataCenter: providerInputs?.localDataCenter, + contactPoints: providerInputs.host.split(",").filter(Boolean) + }); + return client; + }; + + const validateConnection = async (inputs: unknown) => { + const providerInputs = await validateProviderInputs(inputs); + const client = await getClient(providerInputs); + + const isConnected = await client.execute("SELECT * FROM system_schema.keyspaces").then(() => true); + await client.shutdown(); + return isConnected; + }; + + const create = async (inputs: unknown, expireAt: number) => { + const providerInputs = await validateProviderInputs(inputs); + const client = await getClient(providerInputs); + + const username = generateUsername(); + const password = generatePassword(); + const { keyspace } = providerInputs; + const expiration = new Date(expireAt).toISOString(); + + const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({ + username, + password, + expiration, + keyspace + }); + + const queries = creationStatement.toString().split(";").filter(Boolean); + for (const query of queries) { + // eslint-disable-next-line + await client.execute(query); + } + await client.shutdown(); + + return { entityId: username, data: { DB_USERNAME: username, DB_PASSWORD: password } }; + }; + + const revoke = async (inputs: unknown, entityId: string) => { + const providerInputs = await validateProviderInputs(inputs); + const client = await getClient(providerInputs); + + const username = entityId; + const { keyspace } = providerInputs; + + const revokeStatement = handlebars.compile(providerInputs.revocationStatement)({ username, keyspace }); + const queries = revokeStatement.toString().split(";").filter(Boolean); + for (const query of queries) { + // eslint-disable-next-line + await client.execute(query); + } + await client.shutdown(); + return { entityId: username }; + }; + + const renew = async (inputs: unknown, entityId: string, expireAt: number) => { + const providerInputs = await validateProviderInputs(inputs); + const client = await getClient(providerInputs); + + const username = entityId; + const expiration = new Date(expireAt).toISOString(); + const { keyspace } = providerInputs; + + const renewStatement = handlebars.compile(providerInputs.revocationStatement)({ username, keyspace, expiration }); + const queries = renewStatement.toString().split(";").filter(Boolean); + for (const query of queries) { + // eslint-disable-next-line + await client.execute(query); + } + await client.shutdown(); + return { entityId: username }; + }; + + return { + validateProviderInputs, + validateConnection, + create, + revoke, + renew + }; +}; diff --git a/backend/src/ee/services/dynamic-secret/providers/index.ts b/backend/src/ee/services/dynamic-secret/providers/index.ts index d66e60802..34c049553 100644 --- a/backend/src/ee/services/dynamic-secret/providers/index.ts +++ b/backend/src/ee/services/dynamic-secret/providers/index.ts @@ -1,6 +1,8 @@ +import { CassandraProvider } from "./cassandra"; import { DynamicSecretProviders } from "./models"; import { SqlDatabaseProvider } from "./sql-database"; export const buildDynamicSecretProviders = () => ({ - [DynamicSecretProviders.SqlDatabase]: SqlDatabaseProvider() + [DynamicSecretProviders.SqlDatabase]: SqlDatabaseProvider(), + [DynamicSecretProviders.Cassandra]: CassandraProvider() }); diff --git a/backend/src/ee/services/dynamic-secret/providers/models.ts b/backend/src/ee/services/dynamic-secret/providers/models.ts index d3510d583..edb60d4b2 100644 --- a/backend/src/ee/services/dynamic-secret/providers/models.ts +++ b/backend/src/ee/services/dynamic-secret/providers/models.ts @@ -19,12 +19,27 @@ export const DynamicSecretSqlDBSchema = z.object({ ca: z.string().optional() }); +export const DynamicSecretCassandraSchema = z.object({ + host: z.string().toLowerCase(), + port: z.number(), + localDataCenter: z.string().min(1), + keyspace: z.string().optional(), + username: z.string(), + password: z.string(), + creationStatement: z.string(), + revocationStatement: z.string(), + renewStatement: z.string().optional(), + ca: z.string().optional() +}); + export enum DynamicSecretProviders { - SqlDatabase = "sql-database" + SqlDatabase = "sql-database", + Cassandra = "cassandra" } export const DynamicSecretProviderSchema = z.discriminatedUnion("type", [ - z.object({ type: z.literal(DynamicSecretProviders.SqlDatabase), inputs: DynamicSecretSqlDBSchema }) + z.object({ type: z.literal(DynamicSecretProviders.SqlDatabase), inputs: DynamicSecretSqlDBSchema }), + z.object({ type: z.literal(DynamicSecretProviders.Cassandra), inputs: DynamicSecretCassandraSchema }) ]); export type TDynamicProviderFns = { diff --git a/backend/src/ee/services/dynamic-secret/providers/sql-database.ts b/backend/src/ee/services/dynamic-secret/providers/sql-database.ts index 4c1d5438b..6745f573b 100644 --- a/backend/src/ee/services/dynamic-secret/providers/sql-database.ts +++ b/backend/src/ee/services/dynamic-secret/providers/sql-database.ts @@ -30,19 +30,24 @@ const generateUsername = (provider: SqlProviders) => { export const SqlDatabaseProvider = (): TDynamicProviderFns => { const validateProviderInputs = async (inputs: unknown) => { const appCfg = getConfig(); + const isCloud = Boolean(appCfg.LICENSE_SERVER_KEY); // quick and dirty way to check if its cloud or not const dbHost = appCfg.DB_HOST || getDbConnectionHost(appCfg.DB_CONNECTION_URI); const providerInputs = await DynamicSecretSqlDBSchema.parseAsync(inputs); if ( + isCloud && // localhost + // internal ips + (providerInputs.host === "host.docker.internal" || + providerInputs.host.match(/^10\.\d+\.\d+\.\d+/) || + providerInputs.host.match(/^192\.168\.\d+\.\d+/)) + ) + throw new BadRequestError({ message: "Invalid db host" }); + if ( providerInputs.host === "localhost" || providerInputs.host === "127.0.0.1" || // database infisical uses - dbHost === providerInputs.host || - // internal ips - providerInputs.host === "host.docker.internal" || - providerInputs.host.match(/^10\.\d+\.\d+\.\d+/) || - providerInputs.host.match(/^192\.168\.\d+\.\d+/) + dbHost === providerInputs.host ) throw new BadRequestError({ message: "Invalid db host" }); return providerInputs; @@ -93,15 +98,13 @@ export const SqlDatabaseProvider = (): TDynamicProviderFns => { database }); - await db.transaction(async (tx) => - Promise.all( - creationStatement - .toString() - .split(";") - .filter(Boolean) - .map((query) => tx.raw(query)) - ) - ); + const queries = creationStatement.toString().split(";").filter(Boolean); + await db.transaction(async (tx) => { + for (const query of queries) { + // eslint-disable-next-line + await tx.raw(query); + } + }); await db.destroy(); return { entityId: username, data: { DB_USERNAME: username, DB_PASSWORD: password } }; }; @@ -114,15 +117,13 @@ export const SqlDatabaseProvider = (): TDynamicProviderFns => { const { database } = providerInputs; const revokeStatement = handlebars.compile(providerInputs.revocationStatement)({ username, database }); - await db.transaction(async (tx) => - Promise.all( - revokeStatement - .toString() - .split(";") - .filter(Boolean) - .map((query) => tx.raw(query)) - ) - ); + const queries = revokeStatement.toString().split(";").filter(Boolean); + await db.transaction(async (tx) => { + for (const query of queries) { + // eslint-disable-next-line + await tx.raw(query); + } + }); await db.destroy(); return { entityId: username }; @@ -137,16 +138,15 @@ export const SqlDatabaseProvider = (): TDynamicProviderFns => { const { database } = providerInputs; const renewStatement = handlebars.compile(providerInputs.renewStatement)({ username, expiration, database }); - if (renewStatement) - await db.transaction(async (tx) => - Promise.all( - renewStatement - .toString() - .split(";") - .filter(Boolean) - .map((query) => tx.raw(query)) - ) - ); + if (renewStatement) { + const queries = renewStatement.toString().split(";").filter(Boolean); + await db.transaction(async (tx) => { + for (const query of queries) { + // eslint-disable-next-line + await tx.raw(query); + } + }); + } await db.destroy(); return { entityId: username }; From 3745b65148566fa0e00133242f5a359a6f0d572a Mon Sep 17 00:00:00 2001 From: Akhil Mohan Date: Mon, 22 Apr 2024 16:15:17 +0530 Subject: [PATCH 28/99] feat(ui): added dynamic secret ui for cassandra --- frontend/src/hooks/api/dynamicSecret/types.ts | 47 ++- .../CassandraInputForm.tsx | 363 +++++++++++++++++ .../CreateDynamicSecretForm.tsx | 73 +++- .../SqlDatabaseInputForm.tsx | 6 +- .../CreateDynamicSecretLease.tsx | 6 +- .../EditDynamicSecretCassandraForm.tsx | 374 ++++++++++++++++++ .../EditDynamicSecretForm.tsx | 18 + .../EditDynamicSecretSqlProviderForm.tsx | 6 +- 8 files changed, 849 insertions(+), 44 deletions(-) create mode 100644 frontend/src/views/SecretMainPage/components/ActionBar/CreateDynamicSecretForm/CassandraInputForm.tsx create mode 100644 frontend/src/views/SecretMainPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretCassandraForm.tsx diff --git a/frontend/src/hooks/api/dynamicSecret/types.ts b/frontend/src/hooks/api/dynamicSecret/types.ts index 4b2a736d3..27c4c5ddf 100644 --- a/frontend/src/hooks/api/dynamicSecret/types.ts +++ b/frontend/src/hooks/api/dynamicSecret/types.ts @@ -16,7 +16,8 @@ export type TDynamicSecret = { }; export enum DynamicSecretProviders { - SqlDatabase = "sql-database" + SqlDatabase = "sql-database", + Cassandra = "cassandra" } export enum SqlProviders { @@ -25,21 +26,37 @@ export enum SqlProviders { Oracle = "oracledb" } -export type TDynamicSecretProvider = { - type: DynamicSecretProviders; - inputs: { - client: SqlProviders; - host: string; - port: number; - database: string; - username: string; - password: string; - creationStatement: string; - revocationStatement: string; - renewStatement?: string; - ca?: string | undefined; +export type TDynamicSecretProvider = + | { + type: DynamicSecretProviders.SqlDatabase; + inputs: { + client: SqlProviders; + host: string; + port: number; + database: string; + username: string; + password: string; + creationStatement: string; + revocationStatement: string; + renewStatement?: string; + ca?: string | undefined; + }; + } + | { + type: DynamicSecretProviders.Cassandra; + inputs: { + host: string; + port: number; + keyspace?: string; + localDataCenter: string; + username: string; + password: string; + creationStatement: string; + revocationStatement: string; + renewStatement?: string; + ca?: string | undefined; + }; }; -}; export type TCreateDynamicSecretDTO = { projectSlug: string; diff --git a/frontend/src/views/SecretMainPage/components/ActionBar/CreateDynamicSecretForm/CassandraInputForm.tsx b/frontend/src/views/SecretMainPage/components/ActionBar/CreateDynamicSecretForm/CassandraInputForm.tsx new file mode 100644 index 000000000..950e7b2aa --- /dev/null +++ b/frontend/src/views/SecretMainPage/components/ActionBar/CreateDynamicSecretForm/CassandraInputForm.tsx @@ -0,0 +1,363 @@ +import { Controller, useForm } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod"; +import ms from "ms"; +import { z } from "zod"; + +import { TtlFormLabel } from "@app/components/features"; +import { createNotification } from "@app/components/notifications"; +import { + Accordion, + AccordionContent, + AccordionItem, + AccordionTrigger, + Button, + FormControl, + Input, + SecretInput, + TextArea +} from "@app/components/v2"; +import { useCreateDynamicSecret } from "@app/hooks/api"; +import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types"; + +const formSchema = z.object({ + provider: z.object({ + host: z.string().toLowerCase().min(1), + port: z.coerce.number(), + keyspace: z.string().optional(), + localDataCenter: z.string().min(1), + username: z.string().min(1), + password: z.string().min(1), + creationStatement: z.string().min(1), + revocationStatement: z.string().min(1), + renewStatement: z.string().optional(), + ca: z.string().optional() + }), + defaultTTL: z.string().superRefine((val, ctx) => { + const valMs = ms(val); + if (valMs < 60 * 1000) + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be a greater than 1min" }); + // a day + if (valMs > 24 * 60 * 60 * 1000) + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than a day" }); + }), + maxTTL: z + .string() + .optional() + .superRefine((val, ctx) => { + if (!val) return; + const valMs = ms(val); + if (valMs < 60 * 1000) + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be a greater than 1min" }); + // a day + if (valMs > 24 * 60 * 60 * 1000) + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than a day" }); + }), + name: z.string().refine((val) => val.toLowerCase() === val, "Must be lowercase") +}); +type TForm = z.infer; + +type Props = { + onCompleted: () => void; + onCancel: () => void; + secretPath: string; + projectSlug: string; + environment: string; +}; + +const getSqlStatements = () => { + return { + creationStatement: + "CREATE ROLE '{{username}}' WITH PASSWORD = '{{password}}' AND LOGIN=true;\nGRANT ALL PERMISSIONS ON ALL KEYSPACES TO '{{username}}';", + renewStatement: "", + revocationStatement: 'DROP ROLE "{{username}}";' + }; +}; + +export const CassandraInputForm = ({ + onCompleted, + onCancel, + environment, + secretPath, + projectSlug +}: Props) => { + const { + control, + formState: { isSubmitting }, + handleSubmit + } = useForm({ + resolver: zodResolver(formSchema), + defaultValues: { + provider: getSqlStatements() + } + }); + + const createDynamicSecret = useCreateDynamicSecret(); + + const handleCreateDynamicSecret = async ({ name, maxTTL, provider, defaultTTL }: TForm) => { + // wait till previous request is finished + if (createDynamicSecret.isLoading) return; + try { + await createDynamicSecret.mutateAsync({ + provider: { type: DynamicSecretProviders.Cassandra, inputs: provider }, + maxTTL, + name, + path: secretPath, + defaultTTL, + projectSlug, + environmentSlug: environment + }); + onCompleted(); + } catch (err) { + createNotification({ + type: "error", + text: "Failed to create dynamic secret" + }); + } + }; + + return ( +
+
+
+
+
+ ( + + + + )} + /> +
+
+ ( + } + isError={Boolean(error?.message)} + errorText={error?.message} + > + + + )} + /> +
+
+ ( + } + isError={Boolean(error?.message)} + errorText={error?.message} + > + + + )} + /> +
+
+
+
+ Configuration +
+
+
+ ( + + + + )} + /> + ( + + + + )} + /> +
+ ( + + + + )} + /> +
+ ( + + + + )} + /> + ( + + + + )} + /> + ( + + + + )} + /> +
+
+ ( + + + + )} + /> + + + Modify CQL Statements + + ( + +