diff --git a/docs/docs.json b/docs/docs.json index 4b8e62adf2..6eadf70b8f 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -343,10 +343,7 @@ }, { "group": "Architecture", - "pages": [ - "internals/architecture/components", - "internals/architecture/cloud" - ] + "pages": ["internals/architecture/components", "internals/architecture/cloud"] }, "internals/security", "internals/service-tokens" @@ -565,10 +562,7 @@ "integrations/cloud/gcp-secret-manager", { "group": "Cloudflare", - "pages": [ - "integrations/cloud/cloudflare-pages", - "integrations/cloud/cloudflare-workers" - ] + "pages": ["integrations/cloud/cloudflare-pages", "integrations/cloud/cloudflare-workers"] }, "integrations/cloud/terraform-cloud", "integrations/cloud/databricks", @@ -662,9 +656,7 @@ "documentation/platform/secret-scanning/overview", { "group": "Concepts", - "pages": [ - "documentation/platform/secret-scanning/concepts/secret-scanning" - ] + "pages": ["documentation/platform/secret-scanning/concepts/secret-scanning"] } ] }, @@ -714,18 +706,13 @@ "documentation/platform/ssh/overview", { "group": "Concepts", - "pages": [ - "documentation/platform/ssh/concepts/ssh-certificates" - ] + "pages": ["documentation/platform/ssh/concepts/ssh-certificates"] } ] }, { "group": "Platform Reference", - "pages": [ - "documentation/platform/ssh/usage", - "documentation/platform/ssh/host-groups" - ] + "pages": ["documentation/platform/ssh/usage", "documentation/platform/ssh/host-groups"] } ] }, @@ -772,11 +759,7 @@ "cli/commands/reset", { "group": "infisical scan", - "pages": [ - "cli/commands/scan", - "cli/commands/scan-git-changes", - "cli/commands/scan-install" - ] + "pages": ["cli/commands/scan", "cli/commands/scan-git-changes", "cli/commands/scan-install"] } ] }, @@ -1110,9 +1093,7 @@ "pages": [ { "group": "Kubernetes", - "pages": [ - "api-reference/endpoints/dynamic-secrets/kubernetes/create-lease" - ] + "pages": ["api-reference/endpoints/dynamic-secrets/kubernetes/create-lease"] }, "api-reference/endpoints/dynamic-secrets/create", "api-reference/endpoints/dynamic-secrets/update", @@ -2467,7 +2448,7 @@ "sdks/languages/node", "sdks/languages/python", "sdks/languages/java", - "sdks/languages/csharp", + "sdks/languages/dotnet", "sdks/languages/cpp", "sdks/languages/rust", "sdks/languages/go", @@ -2695,5 +2676,11 @@ "koala": { "publicApiKey": "pk_b50d7184e0e39ddd5cdb43cf6abeadd9b97d" } - } + }, + "redirects": [ + { + "source": "/sdks/languages/csharp", + "destination": "/sdks/languages/dotnet" + } + ] } diff --git a/docs/sdks/languages/cpp.mdx b/docs/sdks/languages/cpp.mdx index 2e22def9c4..27f1aad3e9 100644 --- a/docs/sdks/languages/cpp.mdx +++ b/docs/sdks/languages/cpp.mdx @@ -1,6 +1,315 @@ --- title: "Infisical C++ SDK" sidebarTitle: "C++" -url: "https://github.com/Infisical/infisical-cpp-sdk/?tab=readme-ov-file#infisical-c-sdk" icon: "/images/sdks/languages/cpp.svg" ---- \ No newline at end of file +--- + +If you're working with C++, the official Infisical C++ SDK package is the easiest way to fetch and work with secrets for your application. + +## Compatible with C++ 17 and later +The Infisical C++ SDK is compatible with C++ 17 capable compilers. This implies GCC 8 or newer, and clang 3.8 or newer. Earlier versions of C++ are unsupported. + +## Dependencies +- `cURL`: Used internally for crafting HTTP requests. + +## CMake Installation + +```bash +cmake_minimum_required(VERSION 3.14) +project(InfisicalTest) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_PREFIX_PATH ${CMAKE_BINARY_DIR}) + +find_package(OpenSSL REQUIRED) + + +include(FetchContent) + + +FetchContent_Declare( + infisical + GIT_REPOSITORY https://github.com/Infisical/infisical-cpp-sdk.git + GIT_TAG 1.0.0 # Replace with the desired version +) + +FetchContent_MakeAvailable(infisical) +FetchContent_GetProperties(infisical) + + +# Example usage. This will differ based on your project structure. +add_executable(my_app src/main.cpp) +target_link_libraries(my_app PRIVATE infisical OpenSSL::SSL OpenSSL::Crypto) +target_include_directories(my_app PRIVATE ${infisical_SOURCE_DIR}/include) +``` + +## Manual Installation +If you're unable to use the recommended CMake installation approach, you can choose to manually build the library and use it in your project. + +```bash +mkdir build +cd build +cmake .. +make +``` + +## Quick-Start Example + +Below you'll find an example that uses the Infisical SDK to fetch a secret with the key `API_KEY` using [Machine Identity Universal Auth](https://infisical.com/docs/documentation/platform/identities/universal-auth) + +More examples can be found in the [/examples](https://github.com/Infisical/infisical-cpp-sdk/tree/main/examples) folder. + +```cpp +#include +#include + +int main() { + + try { + Infisical::InfisicalClient client( + Infisical::ConfigBuilder() + .withHostUrl("https://app.infisical.com") // Optionally change this to your custom Infisical instance URL. + .withAuthentication( + Infisical::AuthenticationBuilder() + .withUniversalAuth("", "") + .build()) + .build()); + + const auto getSecretOptions = Infisical::Input::GetSecretOptionsBuilder() + .withEnvironment("") // dev, staging, prod, etc + .withProjectId("") + .withSecretKey("API_KEY") + .build(); + + const auto apiKeySecret = client.secrets().getSecret(getSecretOptions); + + printf("Secret retrieved, [key=%s] [value=%s]\n", apiKeySecret.getSecretKey().c_str(), apiKeySecret.getSecretValue().c_str()); + } catch (const Infisical::InfisicalError &e) { + std::cerr << "Error: " << e.what() << std::endl; + return 1; + } + + return 0; +} +``` + +## JSON Serialization +The SDK uses [nlohmann/json](https://github.com/nlohmann/json) internally to serialize/deserialize JSON data. This SDK makes no assumptions about which JSON library you use in your project, and you aren't constrained to `nlohmann/json` in any way. Data returned by the SDK is returned as a class, which exposes Getter methods for getting fields such as the secret value or secret key. + + +## Documentation +The Infisical C++ SDK follows a builder pattern for all types of input. Below is a detailed documentation of our currently support methods. + +Everything related to the Infisical SDK lives inside the `Infisical` namespace. + +### InfisicalClient Class +`InfisicalClient(Config &config)` + +```cpp + Infisical::InfisicalClient client( + Infisical::ConfigBuilder() + .withHostUrl("https://app.infisical.com") + .withAuthentication( + Infisical::AuthenticationBuilder() + .withUniversalAuth(clientId, clientSecret) + .build()) + .build()); +``` + +Config is created through the `ConfigBuilder` class. See below for more details + +### Config Class + +`Config` defines the configuration of the Infisical Client itself, such as authentication. + +```cpp +Infisical::Config config = Infisical::ConfigBuilder() + .withHostUrl("https://app.infisical.com") + .withAuthentication( + Infisical::AuthenticationBuilder() + .withUniversalAuth(clientId, clientSecret) + .build()) + .build(); + +Infisical::InfisicalClient client(config); +``` + +- `withHostUrl(string)` _(optional)_: Specify a custom Infisical host URL, pointing to your Infisical instance. Defaults to `https://app.infisical.com` +- `withAuthentication(Infisical::Authentication)`: Configure the authentication that will be used by the SDK. See [Authentication Class](#authentication-class) for more details. +- `build()`: Returns the `Config` object with the options you configured. + +### Authentication Class +```cpp +Infisical::Authentication auth = Infisical::AuthenticationBuilder() + .withUniversalAuth(clientId, clientSecret) + .build(); + +Infisical::Config config = Infisical::ConfigBuilder() + .withAuthentication(std::move(auth)) // Or use inline declaration + .build(); +``` + +- `withUniversalAuth(string, string)`: Specify the Universal Auth Client ID and Client Secret that will be used for authentication. +- `build()`: Returns the `Authentication` object with the options you specified. + +### TSecret Class +The `TSecret` class is the class that's returned by all secret methods (get/list/delete/update/create). It can come in the form of a `std::vector` or a single instance. + +**Available getter methods:** +- `getId(): std::string`: Returns the ID of the secret. +- `getWorkspace(): std::string`: Returns the project ID of the secret. +- `getEnvironment(): std::string`: Returns the environment slug of the secret. +- `getVersion(): unsigned int`: Gets the version of the secret. By default this will always be the latest version unless specified otherwise with `withVersion()` +- `getType(): std::string`: Returns the type of the secret. Can only be `shared` or `personal`. Shared secrets are available to everyone with access to the secret. Personal secrets are personal overwrites of the secret, mainly intended for local development purposes. +- `getSecretKey(): std::string`: Returns the secret key. +- `getSecretValue(): std::string` Returns the secret value. +- `getRotationId(): std::string`: If the secret is a rotation secret, this will return the rotation ID of the secret. If it's a regular secret, this will return an empty string. +- `getSecretPath(): std::string`: Returns the secret path of the secret. +- `getSkipMultilineEncoding(): bool`: Returns whether or not skip multiline encoding is enabled for the secret or not. +`getIsRotatedSecret(): bool`: Returns wether or not the secret is a rotated secret. If `true`, then `getRotationId()` returns the ID of the rotation. + + + +### Secrets + +#### Create Secret +```cpp +const auto createSecretOptions = Infisical::Input::CreateSecretOptionsBuilder() + .withEnvironment("") + .withProjectId("") + .withSecretKey("SECRET_KEY_TO_CREATE") + .withSecretValue("VALUE_TO_CREATE") + .withSecretComment("Secret comment to attach") // Optional + .withSecretPath("/path/where/to/create/secret") // Optional, defaults to / + .withTagIds({"tag-id-1", "tag-id-2"}) // Optional + .build(); + +const auto secret = client.secrets().createSecret(createSecretOptions); +``` + +**Parameters**: +- `withEnvironment(string)`: Specify the slug of the environment to create the secret in. +- `withProjectId(string)`: Specify the ID of the project to create the secret in. +- `withSecretPath(string)`: Specify the secret path to create the secret in. Defaults to `/` +- `withSecretKey(string)`: The secret key to be created. +- `withSecretValue(string)`: The value of the secret to create. +- `withSecretComment(string)` _(optional)_: Optionally add a comment to the secret. +- `withTagIds(std::vector>)` _(optional)_: A list of ID's of tags to attach to the secret. +- `build()`: Returns the `CreateSecretOptions` class that can be passed into the `createSecret()` method. + +**Returns**: +- Returns the created secret as a `TSecret` class. Read more in the [TSecret Class](#tsecret-class) documentation. + +#### Update Secret + +```cpp + const auto updateSecretOptions = Infisical::Input::UpdateSecretOptionsBuilder() + .withEnvironment("") + .withProjectId("") + .withSecretKey("") + .withNewSecretKey("") // Optional + .withSecretValue("") // Optional + .withSecretComment("Updated comment") // Optional + .withSecretReminderNote("Updated reminder note") // Optional + .withSecretReminderRepeatDays(1) // Optional + .withType("shared") // Optional + .withTagIds({"tag-id-3", "tag-id-4"}) // Optional + .build(); + +const auto updatedSecret = client.secrets().updateSecret(updateSecretOptions); +``` + +**Parameters**: +- `withEnvironment(string)`: Specify the slug of the environment where the secret lives in. +- `withProjectId(string)`: Specify the ID of the project where the secret to update lives in. +- `withSecretPath(string)`: Specify the secret path of the secret to update. Defaults to `/`. +- `withType("shared" | "personal")`: _(optional)_: The type of secret to update. Defaults to `shared`. +- `withSecretKey(string)`: The key of the secret you wish to update. +- `withNewSecretKey(string)` _(optional)_: The new key of the secret you wish to update. +- `withSecretValue(string)` _(optional)_: The new value of the secret. +- `withSecretReminderNote(string)` _(optional)_: Update the secret reminder note attached to the secret. +- `withSecretReminderRepeatDays(unsigned int)` _(optional)_: Update the secret reminder repeat days attached to the secret. +- `withTagIds(std::vector>)` _(optional)_: A list of ID's of tags to attach to the secret. +- `build()`: Returns the `UpdateSecretOptions` class that can be passed into the `updateSecret()` method. + +**Returns**: +- Returns the updated secret as a `TSecret` class. Read more in the [TSecret Class](#tsecret-class) documentation. + +#### Get Secret +```cpp +const auto getSecretOptions = Infisical::Input::GetSecretOptionsBuilder() + .withEnvironment("") + .withProjectId("") + .withSecretKey("") + .withType("shared") + .withVersion(2) + .withExpandSecretReferences(true) + .build(); + +const auto secret = client.secrets().getSecret(getSecretOptions); +``` +**Parameters**: +- `withEnvironment(string)`: Specify the slug of the environment where the secret lives in. +- `withProjectId(string)`: Specify the ID of the project where the secret lives in. +- `withSecretPath(string)`: Specify the secret path of the secret to get. Defaults to `/` +- `withType("shared" | "personal")`: _(optional)_: The type of secret to get. Defaults to `shared`. +- `withSecretKey(string)`: The key of the secret to get. +- `withExpandSecretReferences(bool)` _(optional)_: Whether or not to expand secret references automatically. Defaults to `true`. +- `withVersion(unsigned int)` _(optional)_: Optionally fetch a specific version of the secret. If not defined, the latest version of the secret is returned. +- `build()`: Returns the `GetSecretOptions` class that can be passed into the `getSecret()` method. + +**Returns**: +- Returns the secret as a `TSecret` class. Read more in the [TSecret Class](#tsecret-class) documentation. + +#### Delete Secret + +```cpp +const auto deleteSecretOptions = Infisical::Input::DeleteSecretOptionsBuilder() + .withEnvironment("") + .withProjectId("") + .withSecretKey("") + .withType("shared") + .withSecretPath("") + .build(); + +const auto deletedSecret = client.secrets().deleteSecret(deleteSecretOptions); +``` + +**Parameters**: +- `withEnvironment(string)`: Specify the slug of the environment where the secret to delete lives in. +- `withProjectId(string)`: Specify the ID of the project where the secret to delete lives in. +- `withSecretPath(string)`: Specify the secret path of the secret to delete. Defaults to `/` +- `withType("shared" | "personal")`: _(optional)_: The type of secret to delete. Defaults to `shared`. +- `withSecretKey(string)`: The key of the secret to delete. +- `build()` Returns the `DeleteSecretOptions` class that can be passed into the `deleteSecret()` method. + +**Returns**: +- Returns the deleted secret as a `TSecret` class. Read more in the [TSecret Class](#tsecret-class) documentation. + + +#### List Secrets +```cpp +const auto listSecretsOptions = Infisical::Input::ListSecretOptionsBuilder() + .withProjectId(projectId) + .withEnvironment(environment) + .withSecretPath("/") + .withRecursive(false) + .withAddSecretsToEnvironmentVariables(false) + .build(); + +const auto secrets = client.secrets().listSecrets(listSecretsOptions); + +``` + +**Parameters**: +- `withEnvironment(string)`: Specify the slug of the environment to list secrets from. +- `withProjectId(string)`: Specify the ID of the project to fetch secrets from. +- `withSecretPath(string)`: Specify the secret path to fetch secrets from. Defaults to `/` +- `withExpandSecretReferences(bool)` _(optional)_: Whether or not to expand secret references automatically. Defaults to `true`. +- `withRecursive(bool)` _(optional)_: Wether or not to recursively fetch secrets from sub-folders. If set to true, all secrets from the secret path specified with `withSecretPath()` and downwards will be fetched. +- `withAddSecretsToEnvironmentVariables(bool)` _(optional)_: If set to true, the fetched secrets will be automatically set as environment variables, making them accessible with `std::getenv` or equivalent by secret key. +- `build()`: Returns the `ListSecretsOptions` class that can be passed into the `listSecrets()` method. + +**Returns**: +- Returns the listed secrets as `std::vector`. Read more in the [TSecret Class](#tsecret-class) documentation. diff --git a/docs/sdks/languages/csharp.mdx b/docs/sdks/languages/csharp.mdx deleted file mode 100644 index 524778a4ae..0000000000 --- a/docs/sdks/languages/csharp.mdx +++ /dev/null @@ -1,594 +0,0 @@ ---- -title: "Infisical .NET SDK" -sidebarTitle: ".NET" -url: "https://github.com/Infisical/infisical-dotnet-sdk?tab=readme-ov-file#infisical-net-sdk" -icon: "/images/sdks/languages/dotnet.svg" ---- -{/* -If you're working with C#, the official [Infisical C# SDK](https://github.com/Infisical/sdk/tree/main/languages/csharp) package is the easiest way to fetch and work with secrets for your application. - -- [Nuget Package](https://www.nuget.org/packages/Infisical.Sdk) -- [Github Repository](https://github.com/Infisical/sdk/tree/main/languages/csharp) - - - **Deprecation Notice** - - All versions prior to **2.3.9** should be considered deprecated and are no longer supported by Infisical. Please update to version **2.3.9** or newer. All changes are fully backwards compatible with older versions. - - -## Basic Usage - -```cs -using Infisical.Sdk; - -namespace Example -{ - class Program - { - static void Main(string[] args) - { - - ClientSettings settings = new ClientSettings - { - Auth = new AuthenticationOptions - { - UniversalAuth = new UniversalAuthMethod - { - ClientId = "your-client-id", - ClientSecret = "your-client-secret" - } - } - }; - - - var infisicalClient = new InfisicalClient(settings); - - var getSecretOptions = new GetSecretOptions - { - SecretName = "TEST", - ProjectId = "PROJECT_ID", - Environment = "dev", - }; - var secret = infisicalClient.GetSecret(getSecretOptions); - - - Console.WriteLine($"The value of secret '{secret.SecretKey}', is: {secret.SecretValue}"); - } - } -} -``` - -This example demonstrates how to use the Infisical C# SDK in a C# application. The application retrieves a secret named `TEST` from the `dev` environment of the `PROJECT_ID` project. - - - We do not recommend hardcoding your [Machine Identity Tokens](/platform/identities/overview). Setting it as an environment variable would be best. - - -# Installation - -```console -$ dotnet add package Infisical.Sdk -``` -# Configuration - -Import the SDK and create a client instance with your [Machine Identity](/platform/identities/universal-auth). - -```cs -using Infisical.Sdk; - -namespace Example -{ - class Program - { - static void Main(string[] args) - { - ClientSettings settings = new ClientSettings - { - Auth = new AuthenticationOptions - { - UniversalAuth = new UniversalAuthMethod - { - ClientId = "your-client-id", - ClientSecret = "your-client-secret" - } - } - }; - - - var infisicalClient = new InfisicalClient(settings); // <-- Your SDK client is now ready to use - } - } -} -``` - -### ClientSettings methods - - - - - Your machine identity client ID. - - - Your machine identity client secret. - - - - An access token obtained from the machine identity login endpoint. - - - - Time-to-live (in seconds) for refreshing cached secrets. - If manually set to 0, caching will be disabled, this is not recommended. - - - - Your self-hosted absolute site URL including the protocol (e.g. `https://app.infisical.com`) - - - - Optionally provide a path to a custom SSL certificate file. This can be substituted by setting the `INFISICAL_SSL_CERTIFICATE` environment variable to the contents of the certificate. - - - - The authentication object to use for the client. This is required unless you're using environment variables. - - - - - -### Authentication - -The SDK supports a variety of authentication methods. The most common authentication method is Universal Auth, which uses a client ID and client secret to authenticate. - -#### Universal Auth - -**Using environment variables** -- `INFISICAL_UNIVERSAL_AUTH_CLIENT_ID` - Your machine identity client ID. -- `INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET` - Your machine identity client secret. - -**Using the SDK directly** -```csharp - ClientSettings settings = new ClientSettings - { - Auth = new AuthenticationOptions - { - UniversalAuth = new UniversalAuthMethod - { - ClientId = "your-client-id", - ClientSecret = "your-client-secret" - } - } - }; - - var infisicalClient = new InfisicalClient(settings); -``` - -#### GCP ID Token Auth - - Please note that this authentication method will only work if you're running your application on Google Cloud Platform. - Please [read more](/documentation/platform/identities/gcp-auth) about this authentication method. - - -**Using environment variables** -- `INFISICAL_GCP_AUTH_IDENTITY_ID` - Your Infisical Machine Identity ID. - -**Using the SDK directly** -```csharp - ClientSettings settings = new ClientSettings - { - Auth = new AuthenticationOptions - { - GcpIdToken = new GcpIdTokenAuthMethod - { - IdentityId = "your-machine-identity-id", - } - } - }; - - - var infisicalClient = new InfisicalClient(settings); -``` - -#### GCP IAM Auth - -**Using environment variables** -- `INFISICAL_GCP_IAM_AUTH_IDENTITY_ID` - Your Infisical Machine Identity ID. -- `INFISICAL_GCP_IAM_SERVICE_ACCOUNT_KEY_FILE_PATH` - The path to your GCP service account key file. - -**Using the SDK directly** -```csharp - ClientSettings settings = new ClientSettings - { - Auth = new AuthenticationOptions - { - GcpIam = new GcpIamAuthMethod - { - IdentityId = "your-machine-identity-id", - ServiceAccountKeyFilePath = "./path/to/your/service-account-key.json" - } - } - }; - - - var infisicalClient = new InfisicalClient(settings); -``` - -#### AWS IAM Auth - - Please note that this authentication method will only work if you're running your application on AWS. - Please [read more](/documentation/platform/identities/aws-auth) about this authentication method. - - -**Using environment variables** -- `INFISICAL_AWS_IAM_AUTH_IDENTITY_ID` - Your Infisical Machine Identity ID. - -**Using the SDK directly** -```csharp - ClientSettings settings = new ClientSettings - { - Auth = new AuthenticationOptions - { - AwsIam = new AwsIamAuthMethod - { - IdentityId = "your-machine-identity-id", - } - } - }; - - - var infisicalClient = new InfisicalClient(settings); -``` - - -#### Azure Auth - - Please note that this authentication method will only work if you're running your application on Azure. - Please [read more](/documentation/platform/identities/azure-auth) about this authentication method. - - -**Using environment variables** -- `INFISICAL_AZURE_AUTH_IDENTITY_ID` - Your Infisical Machine Identity ID. - -**Using the SDK directly** -```csharp - ClientSettings settings = new ClientSettings - { - Auth = new AuthenticationOptions - { - Azure = new AzureAuthMethod - { - IdentityId = "YOUR_IDENTITY_ID", - } - } - }; - - var infisicalClient = new InfisicalClient(settings); -``` - -#### Kubernetes Auth - - Please note that this authentication method will only work if you're running your application on Kubernetes. - Please [read more](/documentation/platform/identities/kubernetes-auth) about this authentication method. - - -**Using environment variables** -- `INFISICAL_KUBERNETES_IDENTITY_ID` - Your Infisical Machine Identity ID. -- `INFISICAL_KUBERNETES_SERVICE_ACCOUNT_TOKEN_PATH_ENV_NAME` - The environment variable name that contains the path to the service account token. This is optional and will default to `/var/run/secrets/kubernetes.io/serviceaccount/token`. - -**Using the SDK directly** -```csharp - ClientSettings settings = new ClientSettings - { - Auth = new AuthenticationOptions - { - Kubernetes = new KubernetesAuthMethod - { - ServiceAccountTokenPath = "/var/run/secrets/kubernetes.io/serviceaccount/token", // Optional - IdentityId = "YOUR_IDENTITY_ID", - } - } - }; - - var infisicalClient = new InfisicalClient(settings); -``` - - - -### Caching - -To reduce the number of API requests, the SDK temporarily stores secrets it retrieves. By default, a secret remains cached for 5 minutes after it's first fetched. Each time it's fetched again, this 5-minute timer resets. You can adjust this caching duration by setting the "cacheTTL" option when creating the client. - -## Working with Secrets - -### client.ListSecrets(options) - -```cs -var options = new ListSecretsOptions -{ - ProjectId = "PROJECT_ID", - Environment = "dev", - Path = "/foo/bar", - AttachToProcessEnv = false, -}; - -var secrets = infisical.ListSecrets(options); -``` - -Retrieve all secrets within the Infisical project and environment that client is connected to - -#### Parameters - - - - - The slug name (dev, prod, etc) of the environment from where secrets should be fetched from. - - - - The project ID where the secret lives in. - - - - The path from where secrets should be fetched from. - - - - Whether or not to set the fetched secrets to the process environment. If true, you can access the secrets like so `System.getenv("SECRET_NAME")`. - - - - Whether or not to include imported secrets from the current path. Read about [secret import](/documentation/platform/secret-reference) - - - - Whether or not to fetch secrets recursively from the specified path. Please note that there's a 20-depth limit for recursive fetching. - - - - Whether or not to expand secret references in the fetched secrets. Read about [secret reference](/documentation/platform/secret-reference) - - - - - -### client.GetSecret(options) - -```cs -var options = new GetSecretOptions - { - SecretName = "AAAA", - ProjectId = "659c781eb2d4fe3e307b77bd", - Environment = "dev", - }; -var secret = infisical.GetSecret(options); -``` - -Retrieve a secret from Infisical. - -By default, `GetSecret()` fetches and returns a shared secret. - -#### Parameters - - - - - The key of the secret to retrieve. - - - The project ID where the secret lives in. - - - The slug name (dev, prod, etc) of the environment from where secrets should be fetched from. - - - The path from where secret should be fetched from. - - - The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared". - - - Whether or not to include imported secrets from the current path. Read about [secret import](/documentation/platform/secret-reference) - - - Whether or not to expand secret references in the fetched secrets. Read about [secret reference](/documentation/platform/secret-reference) - - - - - -### client.CreateSecret(options) - -```cs -var options = new CreateSecretOptions { - Environment = "dev", - ProjectId = "PROJECT_ID", - - SecretName = "NEW_SECRET", - SecretValue = "NEW_SECRET_VALUE", - SecretComment = "This is a new secret", -}; - -var newSecret = infisical.CreateSecret(options); -``` - -Create a new secret in Infisical. - -#### Parameters - - - - - The key of the secret to create. - - - The value of the secret. - - - The project ID where the secret lives in. - - - The slug name (dev, prod, etc) of the environment from where secrets should be fetched from. - - - The path from where secret should be created. - - - The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared". - - - - -### client.UpdateSecret(options) - -```cs -var options = new UpdateSecretOptions { - Environment = "dev", - ProjectId = "PROJECT_ID", - - SecretName = "SECRET_TO_UPDATE", - SecretValue = "NEW VALUE" -}; - -var updatedSecret = infisical.UpdateSecret(options); -``` - -Update an existing secret in Infisical. - -#### Parameters - - - - - The key of the secret to update. - - - The new value of the secret. - - - The project ID where the secret lives in. - - - The slug name (dev, prod, etc) of the environment from where secrets should be fetched from. - - - The path from where secret should be updated. - - - The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared". - - - - -### client.DeleteSecret(options) - -```cs -var options = new DeleteSecretOptions -{ - Environment = "dev", - ProjectId = "PROJECT_ID", - SecretName = "NEW_SECRET", -}; - -var deletedSecret = infisical.DeleteSecret(options); -``` - -Delete a secret in Infisical. - -#### Parameters - - - - - The key of the secret to update. - - - The project ID where the secret lives in. - - - The slug name (dev, prod, etc) of the environment from where secrets should be fetched from. - - - The path from where secret should be deleted. - - - The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared". - - - - -## Cryptography - -### Create a symmetric key - -Create a base64-encoded, 256-bit symmetric key to be used for encryption/decryption. - -```cs -var key = infisical.CreateSymmetricKey(); -``` - -#### Returns (string) -`key` (string): A base64-encoded, 256-bit symmetric key, that can be used for encryption/decryption purposes. - -### Encrypt symmetric -```cs -var options = new EncryptSymmetricOptions -{ - Plaintext = "Infisical is awesome!", - Key = key, -}; - -var encryptedData = infisical.EncryptSymmetric(options); -``` - -#### Parameters - - - - - The plaintext you want to encrypt. - - - The symmetric key to use for encryption. - - - - -#### Returns (object) -`Tag` (string): A base64-encoded, 128-bit authentication tag. -`Iv` (string): A base64-encoded, 96-bit initialization vector. -`CipherText` (string): A base64-encoded, encrypted ciphertext. - -### Decrypt symmetric -```cs -var decryptOptions = new DecryptSymmetricOptions -{ - Key = key, - Ciphertext = encryptedData.Ciphertext, - Iv = encryptedData.Iv, - Tag = encryptedData.Tag, -}; - -var decryptedPlaintext = infisical.DecryptSymmetric(decryptOptions); -``` - -#### Parameters - - - - The ciphertext you want to decrypt. - - - The symmetric key to use for encryption. - - - The initialization vector to use for decryption. - - - The authentication tag to use for decryption. - - - - -#### Returns (string) -`Plaintext` (string): The decrypted plaintext. - */} diff --git a/docs/sdks/languages/dotnet.mdx b/docs/sdks/languages/dotnet.mdx new file mode 100644 index 0000000000..7b3d128853 --- /dev/null +++ b/docs/sdks/languages/dotnet.mdx @@ -0,0 +1,358 @@ +--- +title: "Infisical .NET SDK" +sidebarTitle: ".NET" +icon: "/images/sdks/languages/dotnet.svg" +--- + +If you're working with .NET, the official Infisical .NET SDK package is the easiest way to fetch and work with secrets for your application. + +## Installation + +```bash +dotnet add package Infisical.Sdk +``` + +## Getting Started (.NET) + +```csharp +namespace Example; + +using Infisical.Sdk; +using Infisical.Sdk.Model; + +public class Program { + public static void Main(string[] args) { + + var settings = new InfisicalSdkSettingsBuilder() + .WithHostUri("http://localhost:8080") // Optional. Will default to https://app.infisical.com + .Build(); + + var infisicalClient = new InfisicalClient(settings); + + var _ = infisicalClient.Auth().UniversalAuth().LoginAsync("", "").Result; + + var options = new ListSecretsOptions + { + SetSecretsAsEnvironmentVariables = true, + EnvironmentSlug = "", + SecretPath = "/", + ProjectId = "", + }; + + var secrets = infisicalClient.Secrets().ListAsync(options).Result; + + if (secrets == null) + { + throw new Exception("Failed to fetch secrets, returned null response"); + } + + foreach (var secret in secrets) + { + Console.WriteLine($"{secret.SecretKey}: {secret.SecretValue}"); + } + } +} +``` + +## Getting Started (Visual Basic) +```vb +Imports Infisical.Sdk +Imports Infisical.Sdk.Model + +Module Program + Sub Main(args As String()) + Dim settings = New InfisicalSdkSettingsBuilder() _ + .WithHostUri("https://app.infisical.com") _ + .Build() + + Dim infisicalClient As New InfisicalClient(settings) + + Dim authResult = infisicalClient.Auth().UniversalAuth() _ + .LoginAsync("", "machine-identity-universal-auth-client-secret").Result + + Dim options As New ListSecretsOptions With { + .SetSecretsAsEnvironmentVariables = True, + .EnvironmentSlug = "", + .SecretPath = "/", + .ProjectId = "" + } + + Dim secrets = infisicalClient.Secrets().ListAsync(options).Result + + For Each secret In secrets + Console.WriteLine(secret.SecretKey) + if Environment.GetEnvironmentVariable(secret.SecretKey) IsNot Nothing Then + Console.WriteLine("{0} found on environment variables", secret.SecretKey) + End If + Next + + End Sub +End Module +``` + +## Core Methods + +The SDK methods are organized into the following high-level categories: + +1. `Auth()`: Handles authentication methods. +2. `Secrets()`: Manages CRUD operations for secrets. +3. `Pki()`: Programmatically interact with the Infisical PKI. + * `Subscribers()`: Manage PKI Subscribers. + +### `Auth()` + +The `Auth()` component provides methods for authentication: + +### Universal Auth + +#### Authenticating +```cs +var _ = await sdk.Auth().UniversalAuth().LoginAsync( + "CLIENT_ID", + "CLIENT_SECRET" +); +``` + + +**Parameters:** +- `clientId` (string): The client ID of your Machine Identity. +- `clientSecret` (string): The client secret of your Machine Identity. + +### `Secrets()` + +The `Secrets()` sub-class handles operations related to the Infisical secrets management product. + +#### List Secrets + +```cs +Task ListAsync(ListSecretsOptions options); + +throws InfisicalException +``` + +```csharp +var options = new ListSecretsOptions + { + SetSecretsAsEnvironmentVariables = true, + EnvironmentSlug = "dev", + SecretPath = "/test", + Recursive = true, + ExpandSecretReferences = true, + ProjectId = projectId, + ViewSecretValue = true, + }; + +Secret[] secrets = await sdk.Secrets().ListAsync(options); +``` + +**ListSecretsOptions:** +- `ProjectId` (string): The ID of your project. +- `EnvironmentSlug` (string): The environment in which to list secrets (e.g., "dev"). +- `SecretPath` (string): The path to the secrets. +- `ExpandSecretReferences` (boolean): Whether to expand secret references. +- `Recursive` (boolean): Whether to list secrets recursively. +- `SetSecretsAsEnvironmentVariables` (boolean): Set the retrieved secrets as environment variables. + +**Returns:** +- `Task`: The response containing the list of secrets. + +#### Create Secret + +```cs +public Task CreateAsync(CreateSecretOptions options); + +throws InfisicalException +``` + +```cs + +var options = new CreateSecretOptions +{ + SecretName = "SECRET_NAME", + SecretValue = "SECRET_VALUE", + EnvironmentSlug = "", + SecretPath = "/", + ProjectId = "", + Metadata = new SecretMetadata[] { + new SecretMetadata { + Key = "metadata-key", + Value = "metadata-value" + } + } +}; + +Task newSecret = await sdk.Secrets().CreateAsync(options); +``` + +**Parameters:** +- `SecretName` (string): The name of the secret to create +- `SecretValue` (string): The value of the secret. +- `ProjectId` (string): The ID of your project. +- `EnvironmentSlug` (string): The environment in which to create the secret. +- `SecretPath` (string, optional): The path to the secret. +- `Metadata` (object, optional): Attach metadata to the secret. +- `SecretComment` (string, optional): Attach a secret comment to the secret. +- `SecretReminderNote` (string, optional): Attach a secret reminder note to the secret. +- `SecretReminderRepeatDays` (int, optional): Set the reminder repeat days on the secret. +- `SkipMultilineEncoding` (bool, optional): Whether or not to skip multiline encoding for the secret's value. Defaults to `false`. + +**Returns:** +- `Task`: The created secret. + +#### Update Secret + +```cs +public Task UpdateAsync(UpdateSecretOptions options); + +throws InfisicalException +``` + + +```cs + +var updateSecretOptions = new UpdateSecretOptions +{ + SecretName = "EXISTING_SECRET_NAME", + EnvironmentSlug = "", + SecretPath = "/", + NewSecretName = "NEW_SECRET_NAME", + NewSecretValue = "new-secret-value", + ProjectId = "", +}; + + +Task updatedSecret = await sdk.Secrets().UpdateAsync(updateSecretOptions); +``` + +**Parameters:** +- `SecretName` (string): The name of the secret to update.` +- `ProjectId` (string): The ID of your project. +- `EnvironmentSlug` (string): The environment in which to update the secret. +- `SecretPath` (string): The path to the secret. +- `NewSecretValue` (string, optional): The new value of the secret. +- `NewSecretName` (string, optional): A new name for the secret. +- `NewMetadata` (object, optional): New metadata to attach to the secret. + +**Returns:** +- `Task`: The updated secret. + +#### Get Secret by Name + +```cs +public Task GetAsync(GetSecretOptions options); + +throws InfisicalException +``` + +```cs + +var getSecretOptions = new GetSecretOptions +{ + SecretName = "SECRET_NAME", + EnvironmentSlug = "", + SecretPath = "/", + ProjectId = "", +}; + +Secret secret = await sdk.Secrets().GetAsync(getSecretOptions); +``` + +**Parameters:** +- `SecretName` (string): The name of the secret to get` +- `ProjectId` (string): The ID of your project. +- `EnvironmentSlug` (string): The environment in which to retrieve the secret. +- `SecretPath` (string): The path to the secret. +- `ExpandSecretReferences` (boolean, optional): Whether to expand secret references. +- `Type` (SecretType, optional): The type of secret to fetch. Defaults to `Shared`. + + +**Returns:** +- `Task`: The fetched secret. + +#### Delete Secret by Name + +```cs +public Secret DeleteAsync(DeleteSecretOptions options); + +throws InfisicalException +``` + +```cs + +var options = new DeleteSecretOptions +{ + SecretName = "SECRET_TO_DELETE", + EnvironmentSlug = "", + SecretPath = "/", + ProjectId = "", +}; + + +Secret deletedSecret = await sdk.Secrets().DeleteAsync(options); +``` + +**Parameters:** +- `SecretName` (string): The name of the secret to delete. +- `ProjectId` (string): The ID of your project. +- `EnvironmentSlug` (string): The environment in which to delete the secret. +- `SecretPath` (string, optional): The path to the secret. + +**Returns:** +- `Task`: The deleted secret. + + +### `Pki().Subscribers()` + +The `Pki().Subscribers()` sub-class is used to programmatically interact with the Infisical PKI product line. Currently only issuing new certificates and retrieving the latest certificate bundle from a subscriber is supported. More widespread support for the PKI product is coming to the .NET SDK in the near future. + + +#### Issue a new certificate + +```cs +public async Task IssueCertificateAsync(IssueCertificateOptions options); + +throws InfisicalException +``` + +```cs + +var options = new IssueCertificateOptions +{ + SubscriberName = "", + ProjectId = "", +}; + +SubscriberIssuedCertificate newCertificate = await sdk.Pki().Subscribers().IssueCertificateAsync(options); +``` + +**Parameters:** +- `SubscriberName` (string): The name of the subscriber to create a certificate for. +- `ProjectId` (string): The ID of PKI project. + +**Returns:** +- `Task`: The newly issued certificate along with it's credentials for the specified subscriber. + +#### Retrieve latest certificate bundle + +```cs +public async Task RetrieveLatestCertificateBundleAsync(RetrieveLatestCertificateBundleOptions options) + +throws InfisicalException +``` + +```cs +var options = new RetrieveLatestCertificateBundleOptions +{ + SubscriberName = "", + ProjectId = "", +}; + +CertificateBundle latestCertificate = await sdk.Pki().Subscribers().RetrieveLatestCertificateBundleAsync(options); +``` + +**Parameters:** +- `SubscriberName` (string): The name of the subscriber to retrieve the latest certificate bundle for +- `ProjectId` (string): The ID of PKI project. + +**Returns:** +- `Task`: The latest certificate bundle for the specified subscriber. \ No newline at end of file diff --git a/docs/sdks/languages/go.mdx b/docs/sdks/languages/go.mdx index 312f7e3075..01250c452c 100644 --- a/docs/sdks/languages/go.mdx +++ b/docs/sdks/languages/go.mdx @@ -4,7 +4,7 @@ sidebarTitle: "Go" icon: "/images/sdks/languages/go.svg" --- -If you're working with Go Lang, the official [Infisical Go SDK](https://github.com/infisical/go-sdk) package is the easiest way to fetch and work with secrets for your application. +If you're working with Go, the official Infisical Go SDK package is the easiest way to fetch and work with secrets for your application. - [Package](https://pkg.go.dev/github.com/infisical/go-sdk) - [Github Repository](https://github.com/infisical/go-sdk) diff --git a/docs/sdks/languages/java.mdx b/docs/sdks/languages/java.mdx index 359afb987d..7ead4d3ddd 100644 --- a/docs/sdks/languages/java.mdx +++ b/docs/sdks/languages/java.mdx @@ -1,575 +1,487 @@ --- title: "Infisical Java SDK" sidebarTitle: "Java" -url: "https://github.com/Infisical/java-sdk?tab=readme-ov-file#infisical-java-sdk" icon: "/images/sdks/languages/java.svg" --- -{ -/* -If you're working with Java, the official [Infisical Java SDK](https://github.com/Infisical/sdk/tree/main/languages/java) package is the easiest way to fetch and work with secrets for your application. +If you're working with Java, the official Infisical Java SDK package is the easiest way to fetch and work with secrets for your application. -- [Maven Package](https://github.com/Infisical/sdk/packages/2019741) -- [Github Repository](https://github.com/Infisical/sdk/tree/main/languages/java) +## Installation -## Basic Usage +Replace `{version}` with the version of the SDK you wish to use. This documentation covers version >=3.0.0. + +### Maven + +```xml + + com.infisical + sdk + {version} + +``` + +### Gradle +```gradle + implementation group: 'com.infisical', name: 'sdk', version: '{version}' +``` + + +### Others +For other build tools, please check our [package snippets](https://central.sonatype.com/artifact/com.infisical/sdk), and select the build tool you're using for your project. + + + +## Getting Started ```java -package com.example.app; +package com.example.example; -import com.infisical.sdk.InfisicalClient; -import com.infisical.sdk.schema.*; +import com.infisical.sdk.InfisicalSdk; +import com.infisical.sdk.SdkConfig; public class Example { - public static void main(String[] args) { - - // Create the authentication settings for the client - ClientSettings settings = new ClientSettings(); - AuthenticationOptions authOptions = new AuthenticationOptions(); - UniversalAuthMethod authMethod = new UniversalAuthMethod(); - authMethod.setClientID("YOUR_IDENTITY_ID"); - authMethod.setClientSecret("YOUR_CLIENT_SECRET"); + public static void main(String[] args) { + var sdk = new InfisicalSdk( + new SdkConfig.Builder() + // Optional, will default to https://app.infisical.com + .withSiteUrl("https://your-infisical-instance.com") + .build() + ); - authOptions.setUniversalAuth(authMethod); - settings.setAuth(authOptions); + sdk.Auth().UniversalAuthLogin( + "CLIENT_ID", + "CLIENT_SECRET" + ); - // Create a new Infisical Client - InfisicalClient client = new InfisicalClient(settings); + var secret = sdk.Secrets().GetSecret( + "", + "", + "", + "", + null, // Expand Secret References (boolean, optional) + null, // Include Imports (boolean, optional) + null // Secret Type (shared/personal, defaults to shared, optional) + ); - // Create the options for fetching the secret - GetSecretOptions options = new GetSecretOptions(); - options.setSecretName("TEST"); - options.setEnvironment("dev"); - options.setProjectID("PROJECT_ID"); - // Fetch the sercret with the provided options - GetSecretResponseSecret secret = client.getSecret(options); - - // Print the value - System.out.println(secret.getSecretValue()); - - // Important to avoid memory leaks! - // If you intend to use the client throughout your entire application, you can omit this line. - client.close(); - } + System.out.println(secret); + } } ``` -This example demonstrates how to use the Infisical Java SDK in a Java application. The application retrieves a secret named `TEST` from the `dev` environment of the `PROJECT_ID` project. +## Core Methods - - We do not recommend hardcoding your [Machine Identity Tokens](/platform/identities/overview). Setting it as an environment variable would be best. - +The SDK methods are organized into the following high-level categories: -# Installation +1. `Auth()`: Handles authentication methods. +2. `Secrets()`: Manages CRUD operations for secrets. -The Infisical Java SDK is hosted on the GitHub Packages Apache Maven registry. Because of this you need to configure your environment properly so it's able to pull dependencies from the GitHub registry. Please check [this guide from GitHub](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-apache-maven-registry) on how to achieve this. +### `Auth` -Our package is [located here](https://github.com/Infisical/sdk/packages/2019741). Please follow the installation guide on the page. +The `Auth` component provides methods for authentication: -# Configuration +### Universal Auth -Import the SDK and create a client instance with your [Machine Identity](/platform/identities/universal-auth). +#### Authenticating ```java -import com.infisical.sdk.InfisicalClient; -import com.infisical.sdk.schema.*; - -public class App { - public static void main(String[] args) { - // Create the authentication settings for the client - ClientSettings settings = new ClientSettings(); - AuthenticationOptions authOptions = new AuthenticationOptions(); - UniversalAuthMethod authMethod = new UniversalAuthMethod(); - - authMethod.setClientID("YOUR_IDENTITY_ID"); - authMethod.setClientSecret("YOUR_CLIENT_SECRET"); - - authOptions.setUniversalAuth(authMethod); - settings.setAuth(authOptions); - - // Create a new Infisical Client - InfisicalClient client = new InfisicalClient(settings); // Your client! - } -} +public void UniversalAuthLogin( + String clientId, + String clientSecret +) +throws InfisicalException ``` -### ClientSettings methods - - - - - Your machine identity client ID. - - **This field is deprecated and will be removed in future versions.** Please use the `setAuth()` method on the client settings instead. - - - Your machine identity client secret. - - **This field is deprecated and will be removed in future versions.** Please use the `setAuth()` method on the client settings instead. - - - - An access token obtained from the machine identity login endpoint. - - **This field is deprecated and will be removed in future versions.** Please use the `setAuth()` method on the client settings instead. - - - - Time-to-live (in seconds) for refreshing cached secrets. - If manually set to 0, caching will be disabled, this is not recommended. - - - - Your self-hosted absolute site URL including the protocol (e.g. `https://app.infisical.com`) - - - - Optionally provide a path to a custom SSL certificate file. This can be substituted by setting the `INFISICAL_SSL_CERTIFICATE` environment variable to the contents of the certificate. - - - - The authentication object to use for the client. This is required unless you're using environment variables. - - - - - -### Authentication - -The SDK supports a variety of authentication methods. The most common authentication method is Universal Auth, which uses a client ID and client secret to authenticate. - -#### Universal Auth - -**Using environment variables** -- `INFISICAL_UNIVERSAL_AUTH_CLIENT_ID` - Your machine identity client ID. -- `INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET` - Your machine identity client secret. - -**Using the SDK directly** ```java - ClientSettings settings = new ClientSettings(); - AuthenticationOptions authOptions = new AuthenticationOptions(); - UniversalAuthMethod authMethod = new UniversalAuthMethod(); - - authMethod.setClientID("YOUR_IDENTITY_ID"); - authMethod.setClientSecret("YOUR_CLIENT_SECRET"); - - authOptions.setUniversalAuth(authMethod); - settings.setAuth(authOptions); - - InfisicalClient client = new InfisicalClient(settings); -``` - -#### GCP ID Token Auth - - Please note that this authentication method will only work if you're running your application on Google Cloud Platform. - Please [read more](/documentation/platform/identities/gcp-auth) about this authentication method. - - -**Using environment variables** -- `INFISICAL_GCP_AUTH_IDENTITY_ID` - Your Infisical Machine Identity ID. - -**Using the SDK directly** -```java - ClientSettings settings = new ClientSettings(); - AuthenticationOptions authOptions = new AuthenticationOptions(); - GCPIDTokenAuthMethod authMethod = new GCPIDTokenAuthMethod(); - - authMethod.setIdentityID("YOUR_MACHINE_IDENTITY_ID"); - - authOptions.setGcpIDToken(authMethod); - settings.setAuth(authOptions); - - InfisicalClient client = new InfisicalClient(settings); -``` - -#### GCP IAM Auth - -**Using environment variables** -- `INFISICAL_GCP_IAM_AUTH_IDENTITY_ID` - Your Infisical Machine Identity ID. -- `INFISICAL_GCP_IAM_SERVICE_ACCOUNT_KEY_FILE_PATH` - The path to your GCP service account key file. - -**Using the SDK directly** -```java - ClientSettings settings = new ClientSettings(); - AuthenticationOptions authOptions = new AuthenticationOptions(); - GCPIamAuthMethod authMethod = new GCPIamAuthMethod(); - - authMethod.setIdentityID("YOUR_MACHINE_IDENTITY_ID"); - authMethod.setServiceAccountKeyFilePath("./path/to/your/service-account-key.json"); - - authOptions.setGcpIam(authMethod); - settings.setAuth(authOptions); - - InfisicalClient client = new InfisicalClient(settings); -``` - -#### AWS IAM Auth - - Please note that this authentication method will only work if you're running your application on AWS. - Please [read more](/documentation/platform/identities/aws-auth) about this authentication method. - - -**Using environment variables** -- `INFISICAL_AWS_IAM_AUTH_IDENTITY_ID` - Your Infisical Machine Identity ID. - -**Using the SDK directly** -```java - ClientSettings settings = new ClientSettings(); - AuthenticationOptions authOptions = new AuthenticationOptions(); - AWSIamAuthMethod authMethod = new AWSIamAuthMethod(); - - authMethod.setIdentityID("YOUR_MACHINE_IDENTITY_ID"); - - authOptions.setAwsIam(authMethod); - settings.setAuth(authOptions); - - InfisicalClient client = new InfisicalClient(settings); -``` - -#### Azure Auth - - Please note that this authentication method will only work if you're running your application on Azure. - Please [read more](/documentation/platform/identities/azure-auth) about this authentication method. - - -**Using environment variables** -- `INFISICAL_AZURE_AUTH_IDENTITY_ID` - Your Infisical Machine Identity ID. - -**Using the SDK directly** -```java - ClientSettings settings = new ClientSettings(); - AuthenticationOptions authOptions = new AuthenticationOptions(); - AzureAuthMethod authMethod = new AzureAuthMethod(); - - authMethod.setIdentityID("YOUR_IDENTITY_ID"); - - authOptions.setAzure(authMethod); - settings.setAuth(authOptions); - - InfisicalClient client = new InfisicalClient(settings); -``` - -#### Kubernetes Auth - - Please note that this authentication method will only work if you're running your application on Kubernetes. - Please [read more](/documentation/platform/identities/kubernetes-auth) about this authentication method. - - -**Using environment variables** -- `INFISICAL_KUBERNETES_IDENTITY_ID` - Your Infisical Machine Identity ID. -- `INFISICAL_KUBERNETES_SERVICE_ACCOUNT_TOKEN_PATH_ENV_NAME` - The environment variable name that contains the path to the service account token. This is optional and will default to `/var/run/secrets/kubernetes.io/serviceaccount/token`. - -**Using the SDK directly** -```java - ClientSettings settings = new ClientSettings(); - AuthenticationOptions authOptions = new AuthenticationOptions(); - KubernetesAuthMethod authMethod = new KubernetesAuthMethod(); - - authMethod.setIdentityID("YOUR_IDENTITY_ID"); - authMethod.setServiceAccountTokenPath("/var/run/secrets/kubernetes.io/serviceaccount/token"); // Optional - - authOptions.setKubernetes(authMethod); - settings.setAuth(authOptions); - - InfisicalClient client = new InfisicalClient(settings); +sdk.Auth().UniversalAuthLogin( + "CLIENT_ID", + "CLIENT_SECRET" +); ``` -### Caching +**Parameters:** +- `clientId` (string): The client ID of your Machine Identity. +- `clientSecret` (string): The client secret of your Machine Identity. -To reduce the number of API requests, the SDK temporarily stores secrets it retrieves. By default, a secret remains cached for 5 minutes after it's first fetched. Each time it's fetched again, this 5-minute timer resets. You can adjust this caching duration by setting the "cacheTTL" option when creating the client. - -## Working with Secrets - -### client.listSecrets(options) +### LDAP Auth ```java -ListSecretsOptions options = new ListSecretsOptions(); -options.setEnvironment("dev"); -options.setProjectID("PROJECT_ID"); -options.setPath("/foo/bar"); -options.setIncludeImports(false); -options.setRecursive(false); -options.setExpandSecretReferences(true); - -SecretElement[] secrets = client.listSecrets(options); +public void LdapAuthLogin( + LdapAuthLoginInput input +) +throws InfisicalException ``` -Retrieve all secrets within the Infisical project and environment that client is connected to - -#### Methods - - - - - The slug name (dev, prod, etc) of the environment from where secrets should be fetched from. - - - - The project ID where the secret lives in. - - - - The path from where secrets should be fetched from. - - - - Whether or not to set the fetched secrets to the process environment. If true, you can access the secrets like so `System.getenv("SECRET_NAME")`. - - - - Whether or not to include imported secrets from the current path. Read about [secret import](/documentation/platform/secret-reference) - - - - Whether or not to fetch secrets recursively from the specified path. Please note that there's a 20-depth limit for recursive fetching. - - - - Whether or not to expand secret references in the fetched secrets. Read about [secret reference](/documentation/platform/secret-reference) - - - - - -### client.getSecret(options) - ```java -GetSecretOptions options = new GetSecretOptions(); -options.setSecretName("TEST"); -options.setEnvironment("dev"); -options.setProjectID("PROJECT_ID"); +var input = LdapAuthLoginInput + .builder() + .identityId("") + .username("") + .password("") + .build(); -GetSecretResponseSecret secret = client.getSecret(options); - -String secretValue = secret.getSecretValue(); +sdk.Auth().LdapAuthLogin(input); ``` -Retrieve a secret from Infisical. +**Parameters:** +- `input` (LdapAuthLoginInput): The input for authenticating with LDAP. + - `identityId` (String): The ID of the machine identity to authenticate with. + - `username` (String): The LDAP username. + - `password` (String): The LDAP password. -By default, `getSecret()` fetches and returns a shared secret. +### Access Token Auth -#### Methods - - - - - The key of the secret to retrieve. - - - The project ID where the secret lives in. - - - The slug name (dev, prod, etc) of the environment from where secrets should be fetched from. - - - The path from where secret should be fetched from. - - - The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared". - - - Whether or not to include imported secrets from the current path. Read about [secret import](/documentation/platform/secret-reference) - - - Whether or not to expand secret references in the fetched secrets. Read about [secret reference](/documentation/platform/secret-reference) - - - - -### client.createSecret(options) +#### Authenticating ```java -CreateSecretOptions createOptions = new CreateSecretOptions(); -createOptions.setSecretName("NEW_SECRET"); -createOptions.setEnvironment("dev"); -createOptions.setProjectID("PROJECT_ID"); -createOptions.setSecretValue("SOME SECRET VALUE"); -createOptions.setPath("/"); // Default -createOptions.setType("shared"); // Default - -CreateSecretResponseSecret newSecret = client.createSecret(createOptions); +public void SetAccessToken( + String accessToken +) +throws InfisicalException ``` -Create a new secret in Infisical. - -#### Methods - - - - - The key of the secret to create. - - - The value of the secret. - - - The project ID where the secret lives in. - - - The slug name (dev, prod, etc) of the environment from where secrets should be fetched from. - - - The path from where secret should be created. - - - The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared". - - - - -### client.updateSecret(options) - ```java -UpdateSecretOptions options = new UpdateSecretOptions(); - -options.setSecretName("SECRET_TO_UPDATE"); -options.setSecretValue("NEW SECRET VALUE"); -options.setEnvironment("dev"); -options.setProjectID("PROJECT_ID"); -options.setPath("/"); // Default -options.setType("shared"); // Default - -UpdateSecretResponseSecret updatedSecret = client.updateSecret(options); +sdk.Auth().SetAccessToken("ACCESS_TOKEN"); ``` -Update an existing secret in Infisical. +**Parameters:** +- `accessToken` (string): The access token you want to use for authentication. -#### Methods +### `Secrets` - - - - The key of the secret to update. - - - The new value of the secret. - - - The project ID where the secret lives in. - - - The slug name (dev, prod, etc) of the environment from where secrets should be fetched from. - - - The path from where secret should be updated. - - - The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared". - - - +This sub-class handles operations related to secrets: -### client.deleteSecret(options) +#### List Secrets ```java -DeleteSecretOptions options = new DeleteSecretOptions(); +public List ListSecrets( + String projectId, + String environmentSlug, + String secretPath, + Boolean expandSecretReferences, + Boolean recursive, + Boolean includeImports, + Boolean setSecretsOnSystemProperties +) -options.setSecretName("SECRET_TO_DELETE"); -options.setEnvironment("dev"); -options.setProjectID("PROJECT_ID"); -options.setPath("/"); // Default -options.setType("shared"); // Default - -DeleteSecretResponseSecret deletedSecret = client.deleteSecret(options); +throws InfisicalException ``` -Delete a secret in Infisical. - -#### Methods - - - - - The key of the secret to update. - - - The project ID where the secret lives in. - - - The slug name (dev, prod, etc) of the environment from where secrets should be fetched from. - - - The path from where secret should be deleted. - - - The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared". - - - - -## Cryptography - -### Create a symmetric key - -Create a base64-encoded, 256-bit symmetric key to be used for encryption/decryption. - ```java -String key = client.createSymmetricKey(); +List secrets = sdk.Secrets().ListSecrets( + "", + "", // dev, prod, staging, etc. + "/secret/path", // `/` is the root folder + false, // Should expand secret references + false, // Should get secrets recursively from sub folders + false, // Should include imports + false // Should set the fetched secrets as key/value pairs on the system properties. Makes the secrets accessible as System.getProperty("") +); ``` -#### Returns (string) -`key` (string): A base64-encoded, 256-bit symmetric key, that can be used for encryption/decryption purposes. +**Parameters:** +- `projectId` (string): The ID of your project. +- `environmentSlug` (string): The environment in which to list secrets (e.g., "dev"). +- `secretPath` (string): The path to the secrets. +- `expandSecretReferences` (boolean): Whether to expand secret references. +- `recursive` (boolean): Whether to list secrets recursively. +- `includeImports` (boolean): Whether to include imported secrets. +- `setSecretsOnSystemProperties` (boolean): Set the retrieved secrets as key/value pairs on the system properties, making them accessible through `System.getProperty("")` + +**Returns:** +- `List`: The response containing the list of secrets. + +#### Create Secret + -### Encrypt symmetric ```java -EncryptSymmetricOptions options = new EncryptSymmetricOptions(); -options.setKey(key); -options.setPlaintext("Infisical is awesome!"); - -EncryptSymmetricResponse encryptedData = client.encryptSymmetric(options); +public Secret CreateSecret( + String secretName, + String secretValue, + String projectId, + String environmentSlug, + String secretPath +) +throws InfisicalException ``` -#### Methods - - - - - The plaintext you want to encrypt. - - - The symmetric key to use for encryption. - - - - -#### Returns (object) -`tag (getTag())` (string): A base64-encoded, 128-bit authentication tag. -`iv (getIv())` (string): A base64-encoded, 96-bit initialization vector. -`ciphertext (getCipherText())` (string): A base64-encoded, encrypted ciphertext. - - -### Decrypt symmetric ```java -DecryptSymmetricOptions decryptOptions = new DecryptSymmetricOptions(); -decryptOptions.setKey(key); -decryptOptions.setCiphertext(encryptedData.getCiphertext()); -decryptOptions.setIv(encryptedData.getIv()); -decryptOptions.setTag(encryptedData.getTag()); - -String decryptedString = client.decryptSymmetric(decryptOptions); +Secret newSecret = sdk.Secrets().CreateSecret( + "NEW_SECRET_NAME", + "secret-value", + "", + "", // dev, prod, staging, etc. + "/secret/path", // `/` is the root folder +); ``` -#### Methods - - - - The ciphertext you want to decrypt. - - - The symmetric key to use for encryption. - - - The initialization vector to use for decryption. - - - The authentication tag to use for decryption. - - - +**Parameters:** +- `secretName` (string): The name of the secret to create +- `secretValue` (string): The value of the secret. +- `projectId` (string): The ID of your project. +- `environmentSlug` (string): The environment in which to create the secret. +- `secretPath` (string, optional): The path to the secret. -#### Returns (string) -`Plaintext` (string): The decrypted plaintext. -*/} \ No newline at end of file +**Returns:** +- `Secret`: The created secret. + +#### Update Secret + +```java +public Secret UpdateSecret( + String secretName, + String projectId, + String environmentSlug, + String secretPath, + String newSecretValue, + String newSecretName + ) + +throws InfisicalException +``` + + +```java +Secret updatedSecret = sdk.Secrets().UpdateSecret( + "SECRET_NAME", + "", + "", // dev, prod, staging, etc. + "/secret/path", // `/` is the root folder + "NEW_SECRET_VALUE", // nullable + "NEW_SECRET_NAME" // nullable +); +``` + +**Parameters:** +- `secretName` (string): The name of the secret to update. +- `projectId` (string): The ID of your project. +- `environmentSlug` (string): The environment in which to update the secret. +- `secretPath` (string): The path to the secret. +- `newSecretValue` (string, nullable): The new value of the secret. +- `newSecretName` (string, nullable): A new name for the secret. + +**Returns:** +- `Secret`: The updated secret. + +#### Get Secret by Name + +```java +public Secret GetSecret( + String secretName, + String projectId, + String environmentSlug, + String secretPath, + Boolean expandSecretReferences, + Boolean includeImports, + String secretType + ) +throws InfisicalException +``` + +```java +Secret secret = sdk.Secrets().GetSecret( + "SECRET_NAME", + "", + "", // dev, prod, staging, etc. + "/secret/path", // `/` is the root folder + false, // Should expand secret references + false, // Should get secrets recursively from sub folders + false, // Should include imports + "shared" // Optional Secret Type (defaults to "shared") +); +``` + +**Parameters:** +- `secretName` (string): The name of the secret to get` +- `projectId` (string): The ID of your project. +- `environmentSlug` (string): The environment in which to retrieve the secret. +- `secretPath` (string): The path to the secret. +- `expandSecretReferences` (boolean, optional): Whether to expand secret references. +- `includeImports` (boolean, optional): Whether to include imported secrets. +- `secretType` (personal | shared, optional): The type of secret to fetch. + + +**Returns:** +- `Secret`: The fetched secret. + +#### Delete Secret by Name + +```java +public Secret DeleteSecret( + String secretName, + String projectId, + String environmentSlug, + String secretPath + ) +throws InfisicalException +``` + +```java +Secret deletedSecret = sdk.Secrets().DeleteSecret( + "SECRET_NAME", + "", + "", // dev, prod, staging, etc. + "/secret/path", // `/` is the root folder +); +``` + +**Parameters:** +- `secretName` (string): The name of the secret to delete. +- `projectId` (string): The ID of your project. +- `environmentSlug` (string): The environment in which to delete the secret. +- `secretPath` (string, optional): The path to the secret. + +**Returns:** +- `Secret`: The deleted secret. + + +### `Folders` + +#### Get Folder By Name + +```java +public Folder Get( + String folderId +); +throws InfisicalException +``` + +```java +Folder folder = sdk.Folders().Get(""); +``` + +**Parameters:** +- `folderId` (String): The ID of the folder to retrieve. + +**Returns:** +- `Folder`: The retrieved folder. + +#### List Folders + +```java +public List List( + ListFoldersInput input +) +throws InfisicalException +``` + +```java +ListFoldersInput input = ListFoldersInput + .builder() + .projectId("") + .environmentSlug("") + .folderPath("/") + .recursive(false) + .build(); + +List folders = sdk.Folders().List(input); +``` + + +**Parameters:** +- `input` (ListFoldersInput): The input for listing folders. + - `projectId` (String): The ID of the project to list folders from. + - `environmentSlug` (String): The slug of the environment to list folders from. + - `folderPath` (String): The path to list folders from. Defaults to `/`. + - `recursive` (Boolean): Whether or not to list sub-folders recursively from the specified folder path and downwards. Defaults to `false`. + +**Returns:** +- `List`: The retrieved folders. + +#### Create Folder + +```java +public Folder Create( + CreateFolderInput input +) +throws InfisicalException +``` + +```java +var input = CreateFolderInput + .builder() + .projectId("") + .environmentSlug("") + .folderName("") + .folderPath("/") + .description("Optional folder description") + .build(); + +Folder createdFolder = sdk.Folders().Create(input); +``` + +**Parameters:** +- `input` (CreateFolderInput): The input for creating a folder. + - `projectId` (String): The ID of the project to create the folder in. + - `environmentSlug` (String): The slug of the environment to create the folder in. + - `folderPath` (String): The path to create the folder in. Defaults to `/`. + - `folderName` (String): The name of the folder to create. + - `description` (String): The description of the folder to create. This is optional. + +**Returns:** +- `Folder`: The created folder. + +#### Update Folder + +```java +public Folder Update( + UpdateFolderInput input +) +throws InfisicalException +``` + +```java +var input = UpdateFolderInput + .builder() + .projectId("") + .environmentSlug("") + .folderId("") + .newFolderName("") + .folderPath("/") + .build(); + +Folder updatedFolder = sdk.Folders().Update(input); +``` + +**Parameters:** +- `input` (UpdateFolderInput): The input for updating a folder. + - `projectId` (String): The ID of the project where the folder exists. + - `environmentSlug` (String): The slug of the environment where the folder exists. + - `folderPath` (String): The path of the folder to update. + - `folderId` (String): The ID of the folder to update. + - `newFolderName` (String): The new folder name. + +**Returns:** +- `Folder`: The updated folder. + +#### Delete Folder + +```java +public Folder Delete( + DeleteFolderInput input +) +throws InfisicalException +``` + +```java +var input = DeleteFolderInput + .builder() + .folderId("") + .environmentSlug("") + .projectId("") + .build(); + +Folder deletedFolder = sdk.Folders().Delete(input); +``` + + +**Parameters:** +- `input` (DeleteFolderInput): The input for deleting a folder. + - `projectId` (String): The ID of the project where the folder exists. + - `environmentSlug` (String): The slug of the environment where the folder exists. + - `folderId` (String): The ID of the folder to delete. + +**Returns:** +- `Folder`: The deleted folder. \ No newline at end of file diff --git a/docs/sdks/languages/node.mdx b/docs/sdks/languages/node.mdx index 69bb36e974..e28e9c9f28 100644 --- a/docs/sdks/languages/node.mdx +++ b/docs/sdks/languages/node.mdx @@ -1,558 +1,559 @@ --- title: "Infisical Node.js SDK" sidebarTitle: "Node.js" -url: "https://github.com/Infisical/node-sdk-v2?tab=readme-ov-file#infisical-nodejs-sdk" icon: "/images/sdks/languages/node.svg" --- -{/* -If you're working with Node.js, the official [Infisical Node SDK](https://github.com/Infisical/sdk/tree/main/languages/node) package is the easiest way to fetch and work with secrets for your application. +If you're working with Node.js, the official Infisical Node.js SDK package is the easiest way to fetch and work with secrets for your application. -- [NPM Package](https://www.npmjs.com/package/@infisical/sdk) -- [Github Repository](https://github.com/Infisical/sdk/tree/main/languages/node) +## Deprecation Notice -## Basic Usage - -```js -import express from "express"; - -import { InfisicalClient } from "@infisical/sdk"; - -const app = express(); - -const PORT = 3000; - -const client = new InfisicalClient({ - siteUrl: "https://app.infisical.com", // Optional, defaults to https://app.infisical.com - auth: { - universalAuth: { - clientId: "YOUR_CLIENT_ID", - clientSecret: "YOUR_CLIENT_SECRET" - } - } -}); - -app.get("/", async (req, res) => { - // Access the secret - - const name = await client.getSecret({ - environment: "dev", - projectId: "PROJECT_ID", - path: "/", - type: "shared", - secretName: "NAME" - }); - - res.send(`Hello! My name is: ${name.secretValue}`); -}); - -app.listen(PORT, async () => { - // initialize client - - console.log(`App listening on port ${PORT}`); -}); -``` - -This example demonstrates how to use the Infisical Node SDK with an Express application. The application retrieves a secret named "NAME" and responds to requests with a greeting that includes the secret value. - - - We do not recommend hardcoding your [Machine Identity Tokens](/documentation/platform/identities/overview). Setting it as an environment variable - would be best. - +Please be aware that all versions prior to `4.0.0` are officially fully unsupported. +Please upgrade to version 4.0.0 or newer in order to receive the latest updates. ## Installation -Run `npm` to add `@infisical/sdk` to your project. - -```console -$ npm install @infisical/sdk +```bash +npm install @infisical/sdk ``` -## Configuration +## Getting Started -Import the SDK and create a client instance with your [Machine Identity](/documentation/platform/identities/overview). +```typescript +import { InfisicalSDK } from '@infisical/sdk' - - - ```js - import { InfisicalClient, LogLevel } from "@infisical/sdk"; +const client = new InfisicalSDK({ + siteUrl: "your-infisical-instance.com" // Optional, defaults to https://app.infisical.com +}); - const client = new InfisicalClient({ - auth: { - universalAuth: { - clientId: "YOUR_CLIENT_ID", - clientSecret: "YOUR_CLIENT_SECRET" - } - }, - logLevel: LogLevel.Error - }); - ``` +// Authenticate with Infisical +await client.auth().universalAuth.login({ + clientId: "", + clientSecret: "" +}); - - - ```js - const { InfisicalClient } = require("@infisical/sdk"); +const allSecrets = await client.secrets().listSecrets({ + environment: "dev", // stg, dev, prod, or custom environment slugs + projectId: "" +}); - const client = new InfisicalClient({ - auth: { - universalAuth: { - clientId: "YOUR_CLIENT_ID", - clientSecret: "YOUR_CLIENT_SECRET" - } - }, - }); - ``` +console.log("Fetched secrets", allSecrets) +``` - - +## Core Methods -### Parameters +The SDK methods are organized into the following high-level categories: - - - - Your machine identity client ID. - - **This field is deprecated and will be removed in future versions.** Please use the `auth.universalAuth.clientId` field instead. - - - Your machine identity client secret. - - **This field is deprecated and will be removed in future versions.** Please use the `auth.universalAuth.clientSecret` field instead. - +1. `auth`: Handles authentication methods. +2. `secrets`: Manages CRUD operations for secrets. +3. `dynamicSecrets`: Manages dynamic secrets and leases. +4. `projects`: Creates and manages projects. +5. `environments`: Creates and manages environments. +6. `folders`: Creates and manages folders. - - An access token obtained from the machine identity login endpoint. - - **This field is deprecated and will be removed in future versions.** Please use the `auth.accessToken` field instead. - +### `auth` - - Time-to-live (in seconds) for refreshing cached secrets. - If manually set to 0, caching will be disabled, this is not recommended. - - - - Your self-hosted absolute site URL including the protocol (e.g. `https://app.infisical.com`) - - - The level of logs you wish to log The logs are derived from Rust, as we have written our base SDK in Rust. - - - - Optionally provide a path to a custom SSL certificate file. This can be substituted by setting the `INFISICAL_SSL_CERTIFICATE` environment variable to the contents of the certificate. - - - - The authentication object to use for the client. This is required unless you're using environment variables. - - - - - - -### Authentication - -The SDK supports a variety of authentication methods. The most common authentication method is Universal Auth, which uses a client ID and client secret to authenticate. +The `Auth` component provides methods for authentication: #### Universal Auth -**Using environment variables** -- `INFISICAL_UNIVERSAL_AUTH_CLIENT_ID` - Your machine identity client ID. -- `INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET` - Your machine identity client secret. - -**Using the SDK directly** -```js -const client = new InfisicalClient({ - auth: { - universalAuth: { - clientId: "YOUR_CLIENT_ID", - clientSecret: "YOUR_CLIENT_SECRET" - } - } +#### Authenticating +```typescript +await client.auth().universalAuth.login({ + clientId: "", + clientSecret: "" }); ``` -#### GCP ID Token Auth - - Please note that this authentication method will only work if you're running your application on Google Cloud Platform. - Please [read more](/documentation/platform/identities/gcp-auth) about this authentication method. - +**Parameters:** +- `options` (object): + - `clientId` (string): The client ID of your Machine Identity. + - `clientSecret` (string): The client secret of your Machine Identity. -**Using environment variables** -- `INFISICAL_GCP_AUTH_IDENTITY_ID` - Your Infisical Machine Identity ID. - -**Using the SDK directly** -```js -const client = new InfisicalClient({ - auth: { - gcpIdToken: { - identityId: "YOUR_IDENTITY_ID" - } - } -}); +#### Renewing +You can renew the authentication token that is currently set by using the `renew()` method. +```typescript +await client.auth().universalAuth.renew(); ``` -#### GCP IAM Auth +#### Manually set access token +By default, when you run a successful `.login()` method call, the access token returned will be auto set for the client instance. However, if you wish to set the access token manually, you may use this method. -**Using environment variables** -- `INFISICAL_GCP_IAM_AUTH_IDENTITY_ID` - Your Infisical Machine Identity ID. -- `INFISICAL_GCP_IAM_SERVICE_ACCOUNT_KEY_FILE_PATH` - The path to your GCP service account key file. - -**Using the SDK directly** -```js -const client = new InfisicalClient({ - auth: { - gcpIam: { - identityId: "YOUR_IDENTITY_ID", - serviceAccountKeyFilePath: "./path/to/your/service-account-key.json" - } - } -}); +```typescript +client.auth().accessToken("") ``` -#### AWS IAM Auth - - Please note that this authentication method will only work if you're running your application on AWS. - Please [read more](/documentation/platform/identities/aws-auth) about this authentication method. - - -**Using environment variables** -- `INFISICAL_AWS_IAM_AUTH_IDENTITY_ID` - Your Infisical Machine Identity ID. - -**Using the SDK directly** -```js -const client = new InfisicalClient({ - auth: { - awsIam: { - identityId: "YOUR_IDENTITY_ID" - } - } -}); -``` - -#### Azure Auth - - Please note that this authentication method will only work if you're running your application on Azure. - Please [read more](/documentation/platform/identities/azure-auth) about this authentication method. - - -**Using environment variables** -- `INFISICAL_AZURE_AUTH_IDENTITY_ID` - Your Infisical Machine Identity ID. - -**Using the SDK directly** -```js -const client = new InfisicalClient({ - auth: { - azure: { - identityId: "YOUR_IDENTITY_ID" - } - } -}); -``` +**Parameters:** +- `accessToken` (string): The access token to be used for authentication. _This should not include "Bearer"._ -#### Kubernetes Auth - - Please note that this authentication method will only work if you're running your application on Kubernetes. - Please [read more](/documentation/platform/identities/kubernetes-auth) about this authentication method. - +#### AWS IAM -**Using environment variables** -- `INFISICAL_KUBERNETES_IDENTITY_ID` - Your Infisical Machine Identity ID. -- `INFISICAL_KUBERNETES_SERVICE_ACCOUNT_TOKEN_PATH_ENV_NAME` - The environment variable name that contains the path to the service account token. This is optional and will default to `/var/run/secrets/kubernetes.io/serviceaccount/token`. + + AWS IAM auth only works when the SDK is being used from within an AWS service, such as Lambda, EC2, etc. + -**Using the SDK directly** -```js -const client = new InfisicalClient({ - auth: { - kubernetes: { - identityId: "YOUR_IDENTITY_ID", - serviceAccountTokenPathEnvName: "/var/run/secrets/kubernetes.io/serviceaccount/token" // Optional - } - } -}); -``` - -### Caching - -To reduce the number of API requests, the SDK temporarily stores secrets it retrieves. By default, a secret remains cached for 5 minutes after it's first fetched. Each time it's fetched again, this 5-minute timer resets. You can adjust this caching duration by setting the "cacheTtl" option when creating the client. - -## Working with Secrets - -### client.listSecrets(options) - -```js -const secrets = await client.listSecrets({ - environment: "dev", - projectId: "PROJECT_ID", - path: "/foo/bar/", - includeImports: false -}); -``` - -Retrieve all secrets within the Infisical project and environment that client is connected to - -#### Parameters - - - - - The slug name (dev, prod, etc) of the environment from where secrets should be fetched from. - - - The project ID where the secret lives in. - - - - The path from where secrets should be fetched from. - - - - Whether or not to set the fetched secrets to the process environment. If true, you can access the secrets like so `process.env["SECRET_NAME"]`. - - - - Whether or not to fetch secrets recursively from the specified path. Please note that there's a 20-depth limit for recursive fetching. - - - - Whether or not to expand secret references in the fetched secrets. Read about [secret reference](/documentation/platform/secret-reference) - - - - Whether or not to include imported secrets from the current path. Read about [secret import](/documentation/platform/secret-reference) - - - - - -### client.getSecret(options) - -```js -const secret = await client.getSecret({ - environment: "dev", - projectId: "PROJECT_ID", - secretName: "API_KEY", - path: "/", - type: "shared" -}); -``` - -Retrieve a secret from Infisical. - -By default, `getSecret()` fetches and returns a shared secret. - -#### Parameters - - - - - The key of the secret to retrieve. - - - The project ID where the secret lives in. - - - The slug name (dev, prod, etc) of the environment from where secrets should be fetched from. - - - The path from where secret should be fetched from. - - - The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared". - - - Whether or not to include imported secrets from the current path. Read about [secret import](/documentation/platform/secret-reference) - - - Whether or not to expand secret references in the fetched secrets. Read about [secret reference](/documentation/platform/secret-reference) - - - - -### client.createSecret(options) - -```js -const newApiKey = await client.createSecret({ - projectId: "PROJECT_ID", - environment: "dev", - secretName: "API_KEY", - secretValue: "SECRET VALUE", - path: "/", - type: "shared" -}); -``` - -Create a new secret in Infisical. - - - - - The key of the secret to create. - - - The value of the secret. - - - The project ID where the secret lives in. - - - The slug name (dev, prod, etc) of the environment from where secrets should be fetched from. - - - The path from where secret should be created. - - - The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared". - - - - -### client.updateSecret(options) - -```js -const updatedApiKey = await client.updateSecret({ - secretName: "API_KEY", - secretValue: "NEW SECRET VALUE", - projectId: "PROJECT_ID", - environment: "dev", - path: "/", - type: "shared" -}); -``` - -Update an existing secret in Infisical. - -#### Parameters - - - - - The key of the secret to update. - - - The new value of the secret. - - - The project ID where the secret lives in. - - - The slug name (dev, prod, etc) of the environment from where secrets should be fetched from. - - - The path from where secret should be updated. - - - The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared". - - - - -### client.deleteSecret(options) - -```js -const deletedSecret = await client.deleteSecret({ - secretName: "API_KEY", - - environment: "dev", - projectId: "PROJECT_ID", - path: "/", - - type: "shared" -}); -``` - -Delete a secret in Infisical. - - - - - The key of the secret to update. - - - The project ID where the secret lives in. - - - The slug name (dev, prod, etc) of the environment from where secrets should be fetched from. - - - The path from where secret should be deleted. - - - The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared". - - - - -## Cryptography - -### Create a symmetric key - -Create a base64-encoded, 256-bit symmetric key to be used for encryption/decryption. - -```js -const key = client.createSymmetricKey(); -``` - -#### Returns (string) -`key` (string): A base64-encoded, 256-bit symmetric key, that can be used for encryption/decryption purposes. - -### Encrypt symmetric -```js -const { iv, tag, ciphertext } = await client.encryptSymmetric({ - key: key, - plaintext: "Infisical is awesome!", +#### Authenticating +```typescript +await client.auth().awsIamAuth.login({ + identityId: "" }) ``` -#### Parameters +**Parameters:** +- `options` (object): + - `identityId` (string): The ID of your identity - - - - The plaintext you want to encrypt. - - - The symmetric key to use for encryption. - - - +#### Renewing +You can renew the authentication token that is currently set by using the `renew()` method. +```typescript +await client.auth().awsIamAuth.renew(); +``` -#### Returns (object) -`tag` (string): A base64-encoded, 128-bit authentication tag. -`iv` (string): A base64-encoded, 96-bit initialization vector. -`ciphertext` (string): A base64-encoded, encrypted ciphertext. -### Decrypt symmetric -```js -const decryptedString = await client.decryptSymmetric({ - key: key, - iv: iv, - tag: tag, - ciphertext: ciphertext, +### `secrets` + +This sub-class handles operations related to secrets: + +#### List Secrets + +```typescript +const allSecrets = await client.secrets().listSecrets({ + environment: "dev", + projectId: "", + expandSecretReferences: true, + viewSecretValue: true, + includeImports: false, + recursive: false, + secretPath: "/foo/bar", }); ``` -#### Parameters - - - - The ciphertext you want to decrypt. - - - The symmetric key to use for encryption. - - - The initialization vector to use for decryption. - - - The authentication tag to use for decryption. - - - +**Parameters:** +- `projectId` (string): The ID of your project. +- `environment` (string): The environment in which to list secrets (e.g., "dev"). +- `secretPath` (str): The path to the secrets. +- `expandSecretReferences` (bool, optional): Whether to expand secret references. +- `viewSecretValue` (bool, optional): Whether or not to reveal the secret value of the secrets. If set to `false`, the `secretValue` is masked with ``. Defaults to `true`. +- `recursive` (bool, optional): Whether to list secrets recursively. +- `includeImports` (bool, optional): Whether to include imported secrets. +- `tagFilters` (string[], optional): Tags to filter secrets. -#### Returns (string) -`plaintext` (string): The decrypted plaintext. +**Returns:** +- `ListSecretsResponse`: The response containing the list of secrets. -*/} \ No newline at end of file +#### List secrets with imports + +The `listSecretsWithImports` method makes it easier to get all your secrets at once. The imported secrets will automatically be added to the secrets returned. The secrets in the selected environment will take precedence over the imported secrets. This means if you have secrets with conflicting names, the secret from the environment the import was imported into, will take precedence. + +```typescript +const allSecrets = await client.secrets().listSecretsWithImports({ + environment: "dev", + projectId: "", + expandSecretReferences: true, + viewSecretValue: true, + recursive: false, + secretPath: "/foo/bar" +}); +``` + +**Parameters:** +- `projectId` (string): The ID of your project. +- `environment` (string): The environment in which to list secrets (e.g., "dev"). +- `secretPath` (str): The path to the secrets. +- `expandSecretReferences` (bool, optional): Whether to expand secret references. +- `viewSecretValue` (bool, optional): Whether or not to reveal the secret value of the secrets. If set to `false`, the `secretValue` is masked with ``. Defaults to `true`. +- `recursive` (bool, optional): Whether to list secrets recursively. +- `tagFilters` (string[], optional): Tags to filter secrets. + +**Returns:** +- `Secret[]`: Returns the list of secrets objects, with imports. + + + +#### Create Secret + +```typescript + const newSecret = await client.secrets().createSecret("SECRET_NAME", { + environment: "dev", + projectId: "", + secretValue: "SECRET_VALUE", + secretComment: "This is a new secret", // Optional + secretPath: "/foo/bar", // Optional + secretReminderNote: "This is a reminder note", // Optional + secretReminderRepeatDays: 7, // Optional + skipMultilineEncoding: false, // Optional + tagIds: ["tagId1", "tagId2"], // Optional + type: "personal" // Optional + }); +``` + +**Parameters:** +- `secretName` (string): The name of the secret to create +- `options` (object): + - `projectId` (string): The ID of your project. + - `environment` (str): The environment in which to create the secret. + - `secretValue` (str): The value of the secret. + - `secretPath` (string, optional): The path to the secret. + - `secretComment` (str, optional): A comment associated with the secret. + - `skipMultilineEncoding` (bool, optional): Whether to skip encoding for multiline secrets. + - `secretReminderNote` (string, optional): A note for the secret reminder. + - `secretReminderRepeatDays` (number, optional): Number of days after which to repeat secret reminders. + - `tagIds` (string[], optional): Array of tags to assign to the new secret. + - `type` (personal | shared, optional): Which type of secret to create. + +**Returns:** +- `CreateSecretResponse`: The response after creating the secret. + +#### Update Secret + +```typescript +const updatedSecret = await client.secrets().updateSecret("SECRET_TO_UPDATE", { + environment: "dev", + projectId: "", + secretValue: "UPDATED_SECRET_VALUE", + newSecretName: "NEW_SECRET_NAME2", // Optional + secretComment: "This is an updated secret", // Optional + secretPath: "/foo/bar", // Optional + secretReminderNote: "This is an updated reminder note", // Optional + secretReminderRepeatDays: 14, // Optional + skipMultilineEncoding: false, // Optional + tagIds: ["tagId1", "tagId2"], // Optional + type: "personal", // Optional + metadata: { // Optional + extra: "metadata" + } +}); +``` + +**Parameters:** +- `secretName` (string): The name of the secret to update.` +- `options` (object): + - `environment` (str): The environment in which to update the secret. + - `projectId` (str): The ID of your project. + - `secretValue` (str, optional): The new value of the secret. + - `newSecretName` (str, optional): A new name for the secret. + - `secretComment` (str, optional): An updated comment associated with the secret. + - `secretPath` (str): The path to the secret. + - `secretReminderNote` (str, optional): An updated note for the secret reminder. + - `secretReminderRepeatDays` (number, optional): Updated number of days after which to repeat secret reminders. + - `skipMultilineEncoding` (bool, optional): Whether to skip encoding for multiline secrets. + - `tagIds` (string[], optional): Array of tags to assign to the secret. + - `type` (personal | shared, optional): Which type of secret to create. + - `metadata` (object, optional): Assign additional details to the secret, accessible through the API. + +**Returns:** +- `UpdateSecretResponse`: The response after updating the secret. + +#### Get Secret by Name + +```typescript + const singleSecret = await client.secrets().getSecret({ + environment: "dev", + projectId: "", + secretName: "DATABASE_URL", + expandSecretReferences: true, // Optional + viewSecretValue: true, // Optional + includeImports: true, // Optional + secretPath: "/foo/bar", // Optional + type: "shared", // Optional + version: 1 // Optional + }); +``` + +**Parameters:** +- `environment` (str): The environment in which to retrieve the secret. +- `projectId` (str): The ID of your project. +- `secretName` (str): The name of the secret. +- `secretPath` (str, optional): The path to the secret. +- `expandSecretReferences` (bool, optional): Whether to expand secret references. +- `viewSecretValue` (bool, optional): Whether or not to reveal the secret value of the secret. If set to `false`, the `secretValue` is masked with ``. Defaults to `true`. +- `includeImports` (bool): Whether to include imported secrets. +- `version` (str, optional): The version of the secret to retrieve. Fetches the latest by default. +- `type` (personal | shared, optional): The type of secret to fetch. + + +**Returns:** +- `Secret`: Returns the secret object. + +#### Delete Secret by Name + +```typescript +const deletedSecret = await client.secrets().deleteSecret("SECRET_TO_DELETE", { + environment: "dev", + projectId: "", + secretPath: "/foo/bar", // Optional + type: "personal" // Optional +}); +``` + +**Parameters:** +- `secretName` (string): The name of the secret to delete. +- `options` (object): + - `projectId` (str): The ID of your project. + - `environment` (str): The environment in which to delete the secret. + - `secret_path` (str, optional): The path to the secret. + - `type` (personal | shared, optional): The type of secret to delete. + +**Returns:** +- `DeleteSecretResponse`: The response after deleting the secret. + + + + +### `dynamicSecrets` + + +#### Create a new dynamic secret + +Creating a new dynamic secret can be done by using the `.dynamicSecrets().create({})` function. More details below. + + +The input for creating new dynamic secret varies greatly between secret types. +For a more in-depth description of each input type for each dynamic secret type, please refer to [our API documentation](https://infisical.com/docs/api-reference/endpoints/dynamic-secrets/create) + + +##### Example for creating a new Redis dynamic secret + +```typescript +import { InfisicalSDK, DynamicSecretProviders } from "@infisical/sdk"; + const client = new InfisicalSDK(); + + await client.auth().universalAuth.login({ + // For localhost + clientId: "CLIENT_ID", + clientSecret: "CLIENT_SECRET" + }); +const dynamicSecret = await client.dynamicSecrets().create({ + provider: { + type: DynamicSecretProviders.Redis, + inputs: { + host: "", + port: 6479, + username: "", + password: "", // Only required if your Redis instance uses authentication (recommended) + creationStatement: "ACL SETUSER {{username}} on >{{password}} ~* &* +@all", + revocationStatement: "ACL DELUSER {{username}}" + } + }, + defaultTTL: "1h", + maxTTL: "24h", + name: "dynamic-secret-name", + projectSlug: "project-slug", + environmentSlug: "dev" +}); +console.log(dynamicSecret); +``` + +**Returns:** +- `DynamicSecret`: The created dynamic secret. + + +#### Delete a dynamic secret + +Note: Deleting a dynamic secret will also delete it's associated leases. + +```typescript +const deletedDynamicSecret = await client.dynamicSecrets().delete("dynamic-secret-name", { + environmentSlug: "dev", + projectSlug: "project-slug" +}); +``` + +**Parameters:** +- `secretName` (string): The ID of the dynamic secret to delete +- `options` (object): + - `projectSlug` (str): The ID of your project. + - `environment` (str): The environment in which to delete the secret. + +**Returns:** +- `DynamicSecret`: The deleted dynamic secret. + +### `dynamicSecrets.leases` +In this section you'll learn how to work with dynamic secret leases + + +#### Create a new lease + +```typescript +const lease = await client.dynamicSecrets().leases.create({ + dynamicSecretName: "dynamic-secret-name", + environmentSlug: "dev", + projectSlug: "your-project-slug", + path: "/foo/bar", + ttl: "5m" // Optional +}); + +console.log(lease); +``` + +**Your dynamic secret credentials will be contained user `lease.data` in this example.** + +**Parameters:** +- `dynamicSecretName` (string): The name of the dynamic secret you wish to create a lease for. +- `projectSlug` (string): The slug of the project where the secret is located. +- `environmentSlug` (string): The environment where the dynamic secret is located. +- `path` (string, optional): The path of where the dynamic secret is located. +- `ttl` (string, optional): A [vercel/ms](https://github.com/vercel/ms) encoded string representation of how long the lease credentials should be valid for. This will default to the dynamic secret's default TTL if not specified. + +**Returns:** +- `CreateLeaseResponse`: The dynamic secret lease result. + + +#### Delete a lease +```typescript +const deletedLease = await client.dynamicSecrets().leases.delete(newLease.lease.id, { + environmentSlug: "dev", + projectSlug: "test-zb-3a", + path: "/foo/bar", + isForced: false // Whether or not to forcefully delete the lease. This can't guarantee that the lease will be deleted from the external provider. +}); +``` + +**Parameters:** +- `leaseId` (string): The ID of the lease you want to delete. +- options: + - `projectSlug` (string): The slug of the project where the secret is located. + - `environmentSlug` (string): The environment where the dynamic secret is located. + - `path` (string, optional): The path of where the dynamic secret is located. + - `isForced` (bool, optional): Whether or not to forcefully delete the lease. This can't guarantee that the lease will be deleted from the external provider, and is potentially unsafe for sensitive dynamic secrets. + +**Returns:** +- `DeleteLeaseResponse`: The deleted lease result. + +#### Renew a lease + +Please note that renewals must happen **before** the lease has fully expired. After renewing the lease, you won't be given new credentials. Instead the existing credentials will continue to live for the specified TTL + +```typescript +const renewedLease = await client.dynamicSecrets().leases.renew(newLease.lease.id, { + environmentSlug: "dev", + projectSlug: "project-slug", + path: "/foo/bar", // Optional + ttl: "10m" // Optional + }); +``` + +**Parameters:** +- `leaseId` (string): The ID of the lease you want to delete. +- `options` (object): + - `projectSlug` (string): The slug of the project where the secret is located. + - `environmentSlug` (string): The environment where the dynamic secret is located. + - `path` (string, optional): The path of where the dynamic secret is located. + - `ttl` (string, optional): A [vercel/ms](https://github.com/vercel/ms) encoded string representation of how long the lease credentials should be valid for. This will default to the dynamic secret's default TTL if not specified. + +**Returns:** +- `RenewLeaseResponse`: The renewed lease response _(doesn't contain new credentials)_. + +### `projects` + +#### Create a new project + +```typescript +const project = await client.projects().create({ + projectName: "", + type: "secret-manager", // cert-manager, secret-manager, kms, ssh + projectDescription: "", // Optional + slug: "", // Optional + template: "", // Optional + kmsKeyId: "kms-key-id" // Optional +}); +``` + +**Parameters:** +- `projectName` (string): The name of the project to create. +- `type` (string): The type of project to create. Valid options are `secret-manager`, `cert-manager`, `kms`, `ssh` +- `projectDescription` (string): An optional description of the project to create. +- `slug` (string): An optional slug for the project to create. If not provided, one will be generated automatically. +- `template` (string): Optionally provide a project template name to use for creating this project. +- `kmsKeyId` (string): The ID of the KMS key to use for the project. Will use the Infisical KMS by default. + +**Returns:** +- `Project`: The project that was created. + + +#### Invite members to a project + +When inviting members to projects, you must either specify the `emails` or `usernames`. If neither are specified, the SDK will throw an error. + +```typescript +const memberships = await client.projects().inviteMembers({ + projectId: project.id, + emails: ["test1@example.com", "test2@example.com"], // Optional + usernames: ["example-user3", "example-user4"] // Optional + roleSlugs: ["member"] // Optional +}); +``` + +**Parameters:** +- `projectId`: (string): The ID of the project to invite members to +- `emails`: (string[]): An array of emails of the users to invite to the project. +- `usernames`: (string[]) An array of usernames of the users to invite to the project. +- `roleSlugs`: (string[]): An array of role slugs to assign to the members. If not specified, this will default to `member`. + +**Returns:** +- `Membership[]`: An array of the created project memberships. + +### `environments` + +#### Create a new environment + +```typescript +const environment = await client.environments().create({ + name: "", + projectId: "", + slug: "", + position: 1 // Optional +}); +``` + +**Parameters:** +- `name` (string): The name of the environment to be created. +- `projectId` (string): The ID of the project to create the environment within. +- `slug`: (string): The slug of the environment to be created. +- `position` (number): An optional position of the environment to be created. The position is used in the Infisical UI to display environments in order. Environments with the lowest position come first. + +**Returns:** +- `Environment`: The environment that was created. + +#### Create a new folder + +```typescript +const folder = await client.folders().create({ + name: "", + path: "", + projectId: "", + environment: "", + description: "" // Optional +}); +``` + +**Parameters:** +- `name` (string): The name of the folder to create. +- `path` (string): The path where of where to create the folder. Defaults to `/`, which is the root folder. +- `projectId` (string): The ID of the project to create the folder within. +- `environment` (string): The slug of the environment to create the folder within. +- `description` (string): An optional folder description. + +**Returns:** +- `Folder`: The folder that was created. + +#### List folders + +```typescript +const folders = await client.folders().listFolders({ + environment: "dev", + projectId: "", + path: "/foo/bar", // Optional + recursive: false // Optional +}); +``` + +**Parameters:** +- `environment` (string): The slug of the environment to list folders within. +- `projectId` (string): The ID of the project to list folders within. +- `path` (string): The path to list folders within. Defaults to `/`, which is the root folder. +- `recursive` (boolean): An optional flag to list folders recursively. Defaults to `false`. + +**Returns:** +- `Folder[]`: An array of folders. \ No newline at end of file diff --git a/docs/sdks/languages/python.mdx b/docs/sdks/languages/python.mdx index f888c08192..066ecc060f 100644 --- a/docs/sdks/languages/python.mdx +++ b/docs/sdks/languages/python.mdx @@ -1,533 +1,418 @@ --- title: "Infisical Python SDK" sidebarTitle: "Python" -url: "https://github.com/Infisical/python-sdk-official?tab=readme-ov-file#infisical-python-sdk" icon: "/images/sdks/languages/python.svg" --- -{/* If you're working with Python, the official [infisical-python](https://github.com/Infisical/sdk/edit/main/crates/infisical-py) package is the easiest way to fetch and work with secrets for your application. +If you're working with Python, the official Infisical Python SDK package is the easiest way to fetch and work with secrets for your application. -- [PyPi Package](https://pypi.org/project/infisical-python/) -- [Github Repository](https://github.com/Infisical/sdk/edit/main/crates/infisical-py) +### Migrating to version 1.0.3 or above -## Basic Usage +We have recently rolled out our first stable version of the SDK, version `1.0.3` and above. -```py -from flask import Flask -from infisical_client import ClientSettings, InfisicalClient, GetSecretOptions, AuthenticationOptions, UniversalAuthMethod +The 1.0.3 version comes with a few key changes that may change how you're using the SDK. +1. **Removal of `rest`**: The SDK no longer exposes the entire Infisical API. This was nessecary as we have moved away from using an OpenAPI generator approach. We aim to add support for more API resources in the near future. If you have any specific requests, please [open an issue](https://github.com/Infisical/python-sdk-official/issues). -app = Flask(__name__) +2. **New response types**: The 1.0.3 release uses return types that differ from the older versions. The new return types such as `BaseSecret`, are all exported from the Infisical SDK. -client = InfisicalClient(ClientSettings( - auth=AuthenticationOptions( - universal_auth=UniversalAuthMethod( - client_id="CLIENT_ID", - client_secret="CLIENT_SECRET", - ) - ) -)) +3. **Property renaming**: Some properties on the responses have been slightly renamed. An example of this would be that the `secret_key` property on the `get_secret_by_name()` method, that has been renamed to `secretKey`. -@app.route("/") -def hello_world(): - # access value +With this in mind, you're ready to upgrade your SDK version to `1.0.3` or above. - name = client.getSecret(options=GetSecretOptions( - environment="dev", - project_id="PROJECT_ID", - secret_name="NAME" - )) +You can refer to our [legacy documentation](https://github.com/Infisical/python-sdk-official/tree/9b0403938ee5ae599d42c5f1fdf9158671a15606?tab=readme-ov-file#infisical-python-sdk) if need be. - return f"Hello! My name is: {name.secret_value}" -``` +## Requirements -This example demonstrates how to use the Infisical Python SDK with a Flask application. The application retrieves a secret named "NAME" and responds to requests with a greeting that includes the secret value. - - - We do not recommend hardcoding your [Machine Identity Tokens](/platform/identities/overview). Setting it as an environment variable would be best. - +Python 3.7+ ## Installation -Run `pip` to add `infisical-python` to your project - -```console -$ pip install infisical-python +```bash +pip install infisicalsdk ``` -Note: You need Python 3.7+. +## Getting Started -## Configuration +```python +from infisical_sdk import InfisicalSDKClient -Import the SDK and create a client instance with your [Machine Identity](/api-reference/overview/authentication). +# Initialize the client +client = InfisicalSDKClient(host="https://app.infisical.com") -```py -from infisical_client import ClientSettings, InfisicalClient, AuthenticationOptions, UniversalAuthMethod +# Authenticate (example using Universal Auth) +client.auth.universal_auth.login( + client_id="", + client_secret="" +) -client = InfisicalClient(ClientSettings( - auth=AuthenticationOptions( - universal_auth=UniversalAuthMethod( - client_id="CLIENT_ID", - client_secret="CLIENT_SECRET", - ) - ) -)) +# Use the SDK to interact with Infisical +secrets = client.secrets.list_secrets(project_id="", environment_slug="dev", secret_path="/") ``` -#### Parameters +## InfisicalSDKClient Parameters - - - - Your Infisical Client ID. +The `InfisicalSDKClient` takes the following parameters, which are used as a global configuration for the lifetime of the SDK instance. - **This field is deprecated and will be removed in future versions.** Please use the `auth` field instead. - - - Your Infisical Client Secret. +- **host** (`str`, _Optional_): The host URL for your Infisical instance. Defaults to `https://app.infisical.com`. +- **token** (`str`, _Optional_): Specify an authentication token to use for all requests. If provided, you will not need to call any of the `auth` methods. Defaults to `None` +- **cache_ttl** (`int`, _Optional_): The SDK has built-in client-side caching for secrets, greatly improving response times. By default, secrets are cached for 1 minute (60 seconds). You can disable caching by setting `cache_ttl` to `None`, or adjust the duration in seconds as needed. - **This field is deprecated and will be removed in future versions.** Please use the `auth` field instead. - - - If you want to directly pass an access token obtained from the authentication endpoints, you can do so. +```python +client = InfisicalSDKClient( + host="https://app.infisical.com", # Defaults to https://app.infisical.com + token="", # If not set, use the client.auth() methods. + cache_ttl = 300 # `None` to disable caching +) +``` - **This field is deprecated and will be removed in future versions.** Please use the `auth` field instead. - +## Core Methods - - Time-to-live (in seconds) for refreshing cached secrets. - If manually set to 0, caching will be disabled, this is not recommended. - +The SDK methods are organized into the following high-level categories: - - Your self-hosted absolute site URL including the protocol (e.g. `https://app.infisical.com`) - +1. `auth`: Handles authentication methods. +2. `secrets`: Manages CRUD operations for secrets. +3. `kms`: Perform cryptographic operations with Infisical KMS. - - Optionally provide a path to a custom SSL certificate file. This can be substituted by setting the `INFISICAL_SSL_CERTIFICATE` environment variable to the contents of the certificate. - +### `auth` - - The authentication object to use for the client. This is required unless you're using environment variables. - - - - - -### Authentication - -The SDK supports a variety of authentication methods. The most common authentication method is Universal Auth, which uses a client ID and client secret to authenticate. +The `Auth` component provides methods for authentication: #### Universal Auth -**Using environment variables** -- `INFISICAL_UNIVERSAL_AUTH_CLIENT_ID` - Your machine identity client ID. -- `INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET` - Your machine identity client secret. - -**Using the SDK directly** -```python3 -from infisical_client import ClientSettings, InfisicalClient, AuthenticationOptions, UniversalAuthMethod - -client = InfisicalClient(ClientSettings( - auth=AuthenticationOptions( - universal_auth=UniversalAuthMethod( - client_id="CLIENT_ID", - client_secret="CLIENT_SECRET", - ) - ) -)) -``` - -#### GCP ID Token Auth - - Please note that this authentication method will only work if you're running your application on Google Cloud Platform. - Please [read more](/documentation/platform/identities/gcp-auth) about this authentication method. - - -**Using environment variables** -- `INFISICAL_GCP_AUTH_IDENTITY_ID` - Your Infisical Machine Identity ID. - -**Using the SDK directly** -```py -from infisical_client import ClientSettings, InfisicalClient, AuthenticationOptions, GCPIDTokenAuthMethod - -client = InfisicalClient(ClientSettings( - auth=AuthenticationOptions( - gcp_id_token=GCPIDTokenAuthMethod( - identity_id="MACHINE_IDENTITY_ID", - ) - ) -)) -``` - -#### GCP IAM Auth - -**Using environment variables** -- `INFISICAL_GCP_IAM_AUTH_IDENTITY_ID` - Your Infisical Machine Identity ID. -- `INFISICAL_GCP_IAM_SERVICE_ACCOUNT_KEY_FILE_PATH` - The path to your GCP service account key file. - -**Using the SDK directly** -```py -from infisical_client import ClientSettings, InfisicalClient, AuthenticationOptions, GCPIamAuthMethod - - -client = InfisicalClient(ClientSettings( - auth=AuthenticationOptions( - gcp_iam=GCPIamAuthMethod( - identity_id="MACHINE_IDENTITY_ID", - service_account_key_file_path="./path/to/service_account_key.json" - ) - ) -)) -``` - -#### AWS IAM Auth - - Please note that this authentication method will only work if you're running your application on AWS. - Please [read more](/documentation/platform/identities/aws-auth) about this authentication method. - - -**Using environment variables** -- `INFISICAL_AWS_IAM_AUTH_IDENTITY_ID` - Your Infisical Machine Identity ID. - -**Using the SDK directly** -```py -from infisical_client import ClientSettings, InfisicalClient, AuthenticationOptions, AWSIamAuthMethod - -client = InfisicalClient(ClientSettings( - auth=AuthenticationOptions( - aws_iam=AWSIamAuthMethod(identity_id="MACHINE_IDENTITY_ID") - ) -)) -``` - -#### Azure Auth - - Please note that this authentication method will only work if you're running your application on Azure. - Please [read more](/documentation/platform/identities/azure-auth) about this authentication method. - - -**Using environment variables** -- `INFISICAL_AZURE_AUTH_IDENTITY_ID` - Your Infisical Machine Identity ID. - -**Using the SDK directly** ```python -from infisical_client import InfisicalClient, ClientSettings, AuthenticationOptions, AzureAuthMethod - -kubernetes_client = InfisicalClient(ClientSettings( - auth=AuthenticationOptions( - azure=AzureAuthMethod( - identity_id="YOUR_IDENTITY_ID", - ) - ) -)) +response = client.auth.universal_auth.login( + client_id="", + client_secret="" +) ``` +#### AWS Auth -#### Kubernetes Auth - - Please note that this authentication method will only work if you're running your application on Kubernetes. - Please [read more](/documentation/platform/identities/kubernetes-auth) about this authentication method. - - -**Using environment variables** -- `INFISICAL_KUBERNETES_IDENTITY_ID` - Your Infisical Machine Identity ID. -- `INFISICAL_KUBERNETES_SERVICE_ACCOUNT_TOKEN_PATH_ENV_NAME` - The environment variable name that contains the path to the service account token. This is optional and will default to `/var/run/secrets/kubernetes.io/serviceaccount/token`. - -**Using the SDK directly** ```python -from infisical_client import InfisicalClient, ClientSettings, AuthenticationOptions, KubernetesAuthMethod - -kubernetes_client = InfisicalClient(ClientSettings( - auth=AuthenticationOptions( - kubernetes=KubernetesAuthMethod( - identity_id="YOUR_IDENTITY_ID", - service_account_token_path="/var/run/secrets/kubernetes.io/serviceaccount/token" # Optional - ) - ) -)) +response = client.auth.aws_auth.login(identity_id="") ``` -### Caching +#### OIDC Auth -To reduce the number of API requests, the SDK temporarily stores secrets it retrieves. By default, a secret remains cached for 5 minutes after it's first fetched. Each time it's fetched again, this 5-minute timer resets. You can adjust this caching duration by setting the "cache_ttl" option when creating the client. - -## Working with Secrets - -### client.listSecrets(options) - -```py -client.listSecrets(options=ListSecretsOptions( - environment="dev", - project_id="PROJECT_ID" -)) -``` - -Retrieve all secrets within the Infisical project and environment that client is connected to - -#### Parameters - - - - - The slug name (dev, prod, etc) of the environment from where secrets should be fetched from. - - - The project ID where the secret lives in. - - - - The path from where secrets should be fetched from. - - - - Whether or not to set the fetched secrets to the process environment. If true, you can access the secrets like so `process.env["SECRET_NAME"]`. - - - - Whether or not to fetch secrets recursively from the specified path. Please note that there's a 20-depth limit for recursive fetching. - - - - Whether or not to expand secret references in the fetched secrets. Read about [secret reference](/documentation/platform/secret-reference) - - - - Whether or not to include imported secrets from the current path. Read about [secret import](/documentation/platform/secret-reference) - - - - - -### client.getSecret(options) - -```py -secret = client.getSecret(options=GetSecretOptions( - environment="dev", - project_id="PROJECT_ID", - secret_name="API_KEY" -)) -value = secret.secret_value # get its value -``` - -By default, `getSecret()` fetches and returns a shared secret. If not found, it returns a personal secret. - -#### Parameters - - - - - The key of the secret to retrieve - - - Whether or not to include imported secrets from the current path. Read about [secret import](/documentation/platform/secret-reference) - - - The slug name (dev, prod, etc) of the environment from where secrets should be fetched from. - - - The project ID where the secret lives in. - - - The path from where secret should be fetched from. - - - The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "personal". - - - Whether or not to include imported secrets from the current path. Read about [secret import](/documentation/platform/secret-reference) - - - Whether or not to expand secret references in the fetched secrets. Read about [secret reference](/documentation/platform/secret-reference) - - - - -### client.createSecret(options) - -```py -api_key = client.createSecret(options=CreateSecretOptions( - secret_name="API_KEY", - secret_value="Some API Key", - environment="dev", - project_id="PROJECT_ID" -)) -``` - -Create a new secret in Infisical. - -#### Parameters - - - - - The key of the secret to create. - - - The value of the secret. - - - The project ID where the secret lives in. - - - The slug name (dev, prod, etc) of the environment from where secrets should be fetched from. - - - The path from where secret should be created. - - - The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared". - - - - -### client.updateSecret(options) - -```py -client.updateSecret(options=UpdateSecretOptions( - secret_name="API_KEY", - secret_value="NEW_VALUE", - environment="dev", - project_id="PROJECT_ID" -)) -``` - -Update an existing secret in Infisical. - -#### Parameters - - - - - The key of the secret to update. - - - The new value of the secret. - - - The project ID where the secret lives in. - - - The slug name (dev, prod, etc) of the environment from where secrets should be fetched from. - - - The path from where secret should be updated. - - - The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared". - - - - -### client.deleteSecret(options) - -```py -client.deleteSecret(options=DeleteSecretOptions( - environment="dev", - project_id="PROJECT_ID", - secret_name="API_KEY" -)) -``` - -Delete a secret in Infisical. - -#### Parameters - - - - - The key of the secret to update. - - - The project ID where the secret lives in. - - - The slug name (dev, prod, etc) of the environment from where secrets should be fetched from. - - - The path from where secret should be deleted. - - - The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared". - - - - -## Cryptography - -### Create a symmetric key - -Create a base64-encoded, 256-bit symmetric key to be used for encryption/decryption. - -```py -key = client.createSymmetricKey() -``` - -#### Returns (string) - -`key` (string): A base64-encoded, 256-bit symmetric key, that can be used for encryption/decryption purposes. - -### Encrypt symmetric - -```py -encryptOptions = EncryptSymmetricOptions( - key=key, - plaintext="Infisical is awesome!" +```python +response = client.auth.oidc_auth.login( + identity_id="", + jwt="" ) - -encryptedData = client.encryptSymmetric(encryptOptions) ``` -#### Parameters +**Parameters:** +- `identity_id` (str): The ID of the OIDC identity configuration in Infisical. +- `jwt` (str): The OIDC JWT token obtained from your identity provider. - - - - The plaintext you want to encrypt. - - - The symmetric key to use for encryption. - - - +This authentication method is useful when integrating with OIDC-compliant identity providers like Okta, Auth0, or any service that issues OIDC tokens. -#### Returns (object) +### `secrets` -`tag` (string): A base64-encoded, 128-bit authentication tag. `iv` (string): A base64-encoded, 96-bit initialization vector. `ciphertext` (string): A base64-encoded, encrypted ciphertext. +This sub-class handles operations related to secrets: -### Decrypt symmetric +#### List Secrets -```py -decryptOptions = DecryptSymmetricOptions( - ciphertext=encryptedData.ciphertext, - iv=encryptedData.iv, - tag=encryptedData.tag, - key=key +```python +secrets = client.secrets.list_secrets( + project_id="", + environment_slug="dev", + secret_path="/", + expand_secret_references=True, # Optional + view_secret_value=True, # Optional + recursive=False, # Optional + include_imports=True, # Optional + tag_filters=[] # Optional ) - -decryptedString = client.decryptSymmetric(decryptOptions) - - ``` -#### Parameters +**Parameters:** +- `project_id` (str): The ID of your project. +- `project_slug` (str): The slug of your project. +- `environment_slug` (str): The environment in which to list secrets (e.g., "dev"). +- `secret_path` (str): The path to the secrets. +- `expand_secret_references` (bool): Whether to expand secret references. +- `view_secret_value` (bool): Whether or not to include the secret value in the response. If set to false, the `secretValue` will be masked with ``. Defaults to true. +- `recursive` (bool): Whether to list secrets recursively. +- `include_imports` (bool): Whether to include imported secrets. +- `tag_filters` (List[str]): Tags to filter secrets. - - - - The ciphertext you want to decrypt. - - - The symmetric key to use for encryption. - - - The initialization vector to use for decryption. - - - The authentication tag to use for decryption. - - - +**Note:** Exactly one of `project_id` or `project_slug` is required. If both are provided, `project_id` takes precedence. -#### Returns (string) +**Returns:** +- `ListSecretsResponse`: The response containing the list of secrets. -`plaintext` (string): The decrypted plaintext. */} +#### Create Secret + +```python +new_secret = client.secrets.create_secret_by_name( + secret_name="NEW_SECRET", + project_id="", + secret_path="/", + environment_slug="dev", + secret_value="secret_value", + secret_comment="Optional comment", + skip_multiline_encoding=False, + secret_reminder_repeat_days=30, # Optional + secret_reminder_note="Remember to update this secret", # Optional + secret_metadata=[{"key": "metadata_key", "value": "metadata_value"}], # Optional + tags_ids=["tag_id_1", "tag_id_2"] # Optional +) +``` + +**Parameters:** +- `secret_name` (str): The name of the secret. +- `project_id` (str): The ID of your project. +- `project_slug` (str): The slug of your project. +- `secret_path` (str): The path to the secret. +- `environment_slug` (str): The environment in which to create the secret. +- `secret_value` (str): The value of the secret. +- `secret_comment` (str, optional): A comment associated with the secret. +- `skip_multiline_encoding` (bool, optional): Whether to skip encoding for multiline secrets. +- `secret_reminder_repeat_days` (Union[float, int], optional): Number of days after which to repeat secret reminders. +- `secret_reminder_note` (str, optional): A note for the secret reminder. +- `secret_metadata` (List[Dict[str, Any]], optional): Metadata associated with the secret. +- `tags_ids` (List[str], optional): IDs of tags to associate with the secret. + +**Note:** Exactly one of `project_id` or `project_slug` is required. If both are provided, `project_id` takes precedence. + +**Returns:** +- `BaseSecret`: The response after creating the secret. + +#### Update Secret + +```python +updated_secret = client.secrets.update_secret_by_name( + current_secret_name="EXISTING_SECRET", + project_id="", + project_slug="", + secret_path="/", + environment_slug="dev", + secret_value="new_secret_value", + secret_comment="Updated comment", # Optional + skip_multiline_encoding=False, + secret_reminder_repeat_days=30, # Optional + secret_reminder_note="Updated reminder note", # Optional + new_secret_name="NEW_NAME", # Optional + secret_metadata=[{"key": "metadata_key", "value": "metadata_value"}], # Optional + tags_ids=["tag_id_1", "tag_id_2"] # Optional +) +``` + +**Parameters:** +- `current_secret_name` (str): The current name of the secret. +- `project_id` (str): The ID of your project. +- `project_slug` (str): The slug of your project. +- `secret_path` (str): The path to the secret. +- `environment_slug` (str): The environment in which to update the secret. +- `secret_value` (str, optional): The new value of the secret. +- `secret_comment` (str, optional): An updated comment associated with the secret. +- `skip_multiline_encoding` (bool, optional): Whether to skip encoding for multiline secrets. +- `secret_reminder_repeat_days` (Union[float, int], optional): Updated number of days after which to repeat secret reminders. +- `secret_reminder_note` (str, optional): An updated note for the secret reminder. +- `new_secret_name` (str, optional): A new name for the secret. +- `secret_metadata` (List[Dict[str, Any]], optional): Metadata associated with the secret. +- `tags_ids` (List[str], optional): IDs of tags to associate with the secret. + +**Note:** Exactly one of `project_id` or `project_slug` is required. If both are provided, `project_id` takes precedence. + +**Returns:** +- `BaseSecret`: The response after updating the secret. + +#### Get Secret by Name + +```python +secret = client.secrets.get_secret_by_name( + secret_name="EXISTING_SECRET", + project_id="", + environment_slug="dev", + secret_path="/", + expand_secret_references=True, # Optional + view_secret_value=True, # Optional + include_imports=True, # Optional + version=None # Optional +) +``` + +**Parameters:** +- `secret_name` (str): The name of the secret. +- `project_id` (str): The ID of your project. +- `project_slug` (str): The slug of your project. +- `environment_slug` (str): The environment in which to retrieve the secret. +- `secret_path` (str): The path to the secret. +- `expand_secret_references` (bool): Whether to expand secret references. +- `view_secret_value` (bool): Whether or not to include the secret value in the response. If set to false, the `secretValue` will be masked with ``. Defaults to true. +- `include_imports` (bool): Whether to include imported secrets. +- `version` (str, optional): The version of the secret to retrieve. Fetches the latest by default. + +**Note:** Exactly one of `project_id` or `project_slug` is required. If both are provided, `project_id` takes precedence. + +**Returns:** +- `BaseSecret`: The response containing the secret. + +#### Delete Secret by Name + +```python +deleted_secret = client.secrets.delete_secret_by_name( + secret_name="EXISTING_SECRET", + project_id="", + environment_slug="dev", + secret_path="/" +) +``` + +**Parameters:** +- `secret_name` (str): The name of the secret to delete. +- `project_id` (str): The ID of your project. +- `project_slug` (str): The slug of your project. +- `environment_slug` (str): The environment in which to delete the secret. +- `secret_path` (str): The path to the secret. + +**Note:** Exactly one of `project_id` or `project_slug` is required. If both are provided, `project_id` takes precedence. + +**Returns:** +- `BaseSecret`: The response after deleting the secret. + +### `kms` + +This sub-class handles KMS related operations: + +#### List KMS Keys + +```python +kms_keys = client.kms.list_keys( + project_id="", + offset=0, # Optional + limit=100, # Optional + order_by=KmsKeysOrderBy.NAME, # Optional + order_direction=OrderDirection.ASC, # Optional + search=None # Optional +) +``` + +**Parameters:** +- `project_id` (str): The ID of your project. +- `offset` (int, optional): The offset to paginate from. +- `limit` (int, optional): The page size for paginating. +- `order_by` (KmsKeysOrderBy, optional): The key property to order the list response by. +- `order_direction` (OrderDirection, optional): The direction to order the list response in. +- `search` (str, optional): The text value to filter key names by. + +**Returns:** +- `ListKmsKeysResponse`: The response containing the list of KMS keys. + +#### Get KMS Key by ID + +```python +kms_key = client.kms.get_key_by_id( + key_id="" +) +``` + +**Parameters:** +- `key_id` (str): The ID of the key to retrieve. + +**Returns:** +- `KmsKey`: The specified key. + +#### Get KMS Key by Name + +```python +kms_key = client.kms.get_key_by_name( + key_name="my-key", + project_id="" +) +``` + +**Parameters:** +- `key_name` (str): The name of the key to retrieve. +- `project_id` (str): The ID of your project. + +**Returns:** +- `KmsKey`: The specified key. + +#### Create KMS Key + +```python +kms_key = client.kms.create_key( + name="my-key", + project_id="", + encryption_algorithm=SymmetricEncryption.AES_GCM_256, + description=None # Optional +) +``` + +**Parameters:** +- `name` (str): The name of the key (must be slug-friendly). +- `project_id` (str): The ID of your project. +- `encryption_algorithm` (SymmetricEncryption): The encryption algorithm this key should use. +- `description` (str, optional): A description of your key. + +**Returns:** +- `KmsKey`: The newly created key. + +#### Update KMS Key + +```python +updated_key = client.kms.update_key( + key_id="", + name="my-updated-key", # Optional + description="Updated description", # Optional + is_disabled=True # Optional +) +``` + +**Parameters:** +- `key_id` (str): The ID of the key to be updated. +- `name` (str, optional): The updated name of the key (must be slug-friendly). +- `description` (str): The updated description of the key. +- `is_disabled` (str): The flag to disable operations with this key. + +**Returns:** +- `KmsKey`: The updated key. + +#### Delete KMS Key + +```python +deleted_key = client.kms.delete_key( + key_id="" +) +``` + +**Parameters:** +- `key_id` (str): The ID of the key to be deleted. + +**Returns:** +- `KmsKey`: The deleted key. + +#### Encrypt Data with KMS Key + +```python +encrypted_data = client.kms.encrypt_data( + key_id="", + base64EncodedPlaintext="TXkgc2VjcmV0IG1lc3NhZ2U=" # must be base64 encoded +) +``` + +**Parameters:** +- `key_id` (str): The ID of the key to encrypt the data with. +- `base64EncodedPlaintext` (str): The plaintext data to encrypt (must be base64 encoded). + +**Returns:** +- `str`: The encrypted ciphertext. + +#### Decrypt Data with KMS Key + +```python +decrypted_data = client.kms.decrypt_data( + key_id="", + ciphertext="Aq96Ry7sMH3k/ogaIB5MiSfH+LblQRBu69lcJe0GfIvI48ZvbWY+9JulyoQYdjAx" +) +``` + +**Parameters:** +- `key_id` (str): The ID of the key to decrypt the data with. +- `ciphertext` (str): The ciphertext returned from the encrypt operation. + +**Returns:** +- `str`: The base64 encoded plaintext. \ No newline at end of file diff --git a/docs/sdks/languages/ruby.mdx b/docs/sdks/languages/ruby.mdx index 5780c48ece..3fb9cb3e12 100644 --- a/docs/sdks/languages/ruby.mdx +++ b/docs/sdks/languages/ruby.mdx @@ -4,9 +4,7 @@ sidebarTitle: "Ruby" icon: "/images/sdks/languages/ruby.svg" --- - - -If you're working with Ruby, the official [Infisical Ruby SDK](https://github.com/infisical/sdk) package is the easiest way to fetch and work with secrets for your application. +If you're working with Ruby, the official Infisical Ruby SDK package is the easiest way to fetch and work with secrets for your application. - [Ruby Package](https://rubygems.org/gems/infisical-sdk) - [Github Repository](https://github.com/infisical/sdk) diff --git a/docs/sdks/languages/rust.mdx b/docs/sdks/languages/rust.mdx index 3d2f16175f..40ad78bfb1 100644 --- a/docs/sdks/languages/rust.mdx +++ b/docs/sdks/languages/rust.mdx @@ -2,5 +2,494 @@ title: "Infisical Rust SDK" sidebarTitle: "Rust" icon: "/images/sdks/languages/rust.svg" -url: "https://github.com/Infisical/rust-sdk?tab=readme-ov-file#infisical--the-official-infisical-rust-sdk" ---- \ No newline at end of file +--- + +If you're working with Rust, the official Infisical Rust SDK package is the easiest way to fetch and work with secrets for your application. + +### Installation + +```bash +cargo add infisical +``` + +### Getting Started + +The easiest way to get started is to use the builder pattern for both the client and your requests. + +```rust +use infisical::{AuthMethod, Client, InfisicalError, encode_base64, decode_base64}; +use infisical::secrets::GetSecretRequest; + +async fn fetch_secret() -> Result<(), InfisicalError> { + // 1. Build the client. You can chain methods to configure it. + let mut client = Client::builder() + .base_url("https://app.infisical.com") // Optional: defaults to https://app.infisical.com + .build() + .await?; + + // 2. Set up your authentication method and log in. + let auth_method = AuthMethod::new_universal_auth("", ""); + client.login(auth_method).await?; + + // 3. Build a request to get a secret. + // Required parameters (name, project_id, environment) are passed to `builder()`. + let request = GetSecretRequest::builder("API_KEY", "", "dev") + .path("/") // Optional parameters are set with builder methods. + .build(); + + // 4. Make the API call. + let secret = client.secrets().get(request).await?; + + println!("Fetched secret key: {}", secret.secret_key); + // For security, avoid printing the secret value in production code! + // println!("Secret value: {}", secret.secret_value); + + Ok(()) +} +``` + +### Client Configuration + +The `Client::builder()` provides several configuration options: + +```rust +let mut client = Client::builder() + .base_url("https://app.infisical.com") // Optional: set custom Infisical instance URL + .build() + .await?; +``` + +**Parameters** +- `.base_url(url)`: Optional method to set the Infisical instance URL. Defaults to `https://app.infisical.com` for Infisical Cloud. Use `https://eu.infisical.com` for EU and `http://localhost:8080` for local development. + +### Core Methods + +The SDK methods are organized into the following high-level categories: + +- `Client::builder()`: The main entry point for creating a client. +- `client.login()`: Allows client to make authenticated requests to the API. +- `client.secrets()`: Provides access to all CRUD operations for secrets. +- `client.kms()`: Provides access to all KMS (Key Management Service) operations. + +### Helper Functions + +The SDK provides utility functions for common operations: + +```rust +use infisical::{encode_base64, decode_base64}; + +// Base64 encode a string +let encoded = encode_base64("sensitive data"); +println!("Encoded: {}", encoded); + +// Base64 decode a string +let decoded = decode_base64(&encoded)?; +println!("Decoded: {}", decoded); +``` + +**Available Functions** +- `encode_base64(data: &str) -> String`: Encodes a string as base64 +- `decode_base64(data: &str) -> Result`: Decodes a base64 string + +### `secrets` + +All secret operations are accessed via `client.secrets()`. Each operation has a dedicated request builder. + +#### Create Secret + +Create a new secret in your project. + +**Example** + +```rust +use infisical::secrets::CreateSecretRequest; + +let request = CreateSecretRequest::builder( + "API_KEY", + "your-secret-value", + "", + "dev" +) +.path("/") +.secret_comment("A comment for the new secret") +.build(); + +let created_secret = client.secrets().create(request).await?; +``` + +**Parameters** + +- `secret_name`, `secret_value`, `project_id`, `environment`: Required parameters passed to the `builder()` function. +- `.path(path)`: Optional method to set the secret's path (defaults to `/`). +- `.secret_comment(comment)`: Optional method to add a comment. +- `.skip_multiline_encoding(bool)`: Optional method to control multiline encoding (defaults to `false`). +- `.r#type(type)`: Optional method to set the secret type (`shared` or `personal`), defaults to `shared`. + +#### Get Secret + +Retrieve a specific secret by name. + +**Example** + +```rust +use infisical::secrets::GetSecretRequest; + +let request = GetSecretRequest::builder("API_KEY", "", "dev") + .path("/") + .build(); + +let secret = client.secrets().get(request).await?; +``` + +**Parameters** + +- `secret_name`, `project_id`, `environment`: Required parameters passed to the `builder()` function. +- `.path(path)`: Optional method to set the secret's path (defaults to `/`). +- `.expand_secret_references(bool)`: Optional method to control secret reference expansion (defaults to `true`). +- `.r#type(type)`: Optional method to set the secret type (`shared` or `personal`), defaults to `shared`. + +#### List Secrets + +List all secrets in a project and environment. + +**Example** + +```rust +use infisical::secrets::ListSecretsRequest; + +let request = ListSecretsRequest::builder("", "dev") + .path("/") + .recursive(true) + .build(); + +let secrets = client.secrets().list(request).await?; +``` + +**Parameters** + +- `project_id`, `environment`: Required parameters passed to the `builder()` function. +- `.path(path)`: Optional method to set the path from which to list secrets (defaults to `/`). +- `.expand_secret_references(bool)`: Optional method to control secret reference expansion (defaults to `true`). +- `.recursive(bool)`: Optional method to recursively list secrets from sub-folders (defaults to `false`). +- `.attach_to_process_env(bool)`: Optional method to attach fetched secrets to the current process's environment variables (defaults to `false`). + +#### Update Secret + +Update an existing secret. + +**Example** + +```rust +use infisical::secrets::UpdateSecretRequest; + +let request = UpdateSecretRequest::builder("API_KEY", "", "dev") + .secret_value("new-secret-value") // Set the new value + .build(); + +let updated_secret = client.secrets().update(request).await?; +``` + +**Parameters** + +- `secret_name`, `project_id`, `environment`: Required parameters passed to the `builder()` function. +- `.new_secret_name(name)`: Optional method to rename the secret. +- `.secret_value(value)`: Optional method to set a new value for the secret. +- `.path(path)`: Optional method to set the secret's path. +- `.secret_comment(comment)`: Optional method to add or change the comment. +- `.skip_multiline_encoding(bool)`: Optional method to control multiline encoding. +- `.r#type(type)`: Optional method to set the secret type (`shared` or `personal`). + +#### Delete Secret + +Delete a secret from your project. + +**Example** + +```rust +use infisical::secrets::DeleteSecretRequest; + +let request = DeleteSecretRequest::builder("API_KEY", "", "dev") + .path("/") + .build(); + +let deleted_secret = client.secrets().delete(request).await?; +``` + +**Parameters** + +- `secret_name`, `project_id`, `environment`: Required parameters passed to the `builder()` function. +- `.path(path)`: Optional method to set the secret's path (defaults to `/`). +- `.r#type(type)`: Optional method to set the secret type (`shared` or `personal`), defaults to `shared`. + +### `kms` + +All KMS (Key Management Service) operations are accessed via `client.kms()`. Each operation has a dedicated request builder. + +#### List KMS Keys + +List all KMS keys in a project. + +**Example** + +```rust +use infisical::kms::ListKmsKeysRequest; + +let request = ListKmsKeysRequest::builder("").build(); + +let keys = client.kms().list(request).await?; +``` + +**Parameters** + +- `project_id`: Required parameter passed to the `builder()` function. + +#### Get KMS Key + +Retrieve a specific KMS key by ID. + +**Example** + +```rust +use infisical::kms::GetKmsKeyRequest; + +let request = GetKmsKeyRequest::builder("").build(); + +let key = client.kms().get(request).await?; +``` + +**Parameters** + +- `key_id`: Required parameter passed to the `builder()` function. + +#### Get KMS Key by Name + +Retrieve a specific KMS key by name. + +**Example** + +```rust +use infisical::kms::GetKmsKeyByNameRequest; + +let request = GetKmsKeyByNameRequest::builder("").build(); + +let key = client.kms().get_by_name(request).await?; +``` + +**Parameters** + +- `key_name`: Required parameter passed to the `builder()` function. + +#### Create KMS Key + +Create a new KMS key in your project. + +**Example** + +```rust +use infisical::kms::{CreateKmsKeyRequest, EncryptionAlgorithm, KeyUsage}; + +let request = CreateKmsKeyRequest::builder("", "my-key") + .description("A key for encryption operations") + .key_usage(KeyUsage::EncryptDecrypt) + .encryption_algorithm(EncryptionAlgorithm::Aes256Gcm) + .build(); + +let created_key = client.kms().create(request).await?; +``` + +**Parameters** + +- `project_id`, `name`: Required parameters passed to the `builder()` function. +- `.description(description)`: Optional method to set the key description. +- `.key_usage(usage)`: Optional method to set the key usage using the `KeyUsage` enum (defaults to `KeyUsage::EncryptDecrypt`). +- `.encryption_algorithm(algorithm)`: Optional method to set the encryption algorithm using the `EncryptionAlgorithm` enum (defaults to `EncryptionAlgorithm::Aes256Gcm`). + +#### Update KMS Key + +Update an existing KMS key. + +**Example** + +```rust +use infisical::kms::UpdateKmsKeyRequest; + +let request = UpdateKmsKeyRequest::builder("") + .name("updated-key-name") + .description("Updated description") + .is_disabled(false) + .build(); + +let updated_key = client.kms().update(request).await?; +``` + +**Parameters** + +- `key_id`: Required parameter passed to the `builder()` function. +- `.name(name)`: Optional method to rename the key. +- `.description(description)`: Optional method to update the key description. +- `.is_disabled(disabled)`: Optional method to enable or disable the key. + +#### Delete KMS Key + +Delete a KMS key from your project. + +**Example** + +```rust +use infisical::kms::DeleteKmsKeyRequest; + +let request = DeleteKmsKeyRequest::builder("").build(); + +let deleted_key = client.kms().delete(request).await?; +``` + +**Parameters** + +- `key_id`: Required parameter passed to the `builder()` function. + +#### Encrypt Data + +Encrypt data using a KMS key. + +**Example** + +```rust +use infisical::kms::EncryptRequest; + +let request = EncryptRequest::builder("", "sensitive data").build(); + +let ciphertext = client.kms().encrypt(request).await?; +``` + +**Parameters** + +- `key_id`, `plaintext`: Required parameters passed to the `builder()` function. + +#### Decrypt Data + +Decrypt data using a KMS key. + +**Example** + +```rust +use infisical::kms::DecryptRequest; + +let request = DecryptRequest::builder("", "encrypted-data").build(); + +let plaintext = client.kms().decrypt(request).await?; +``` + +**Parameters** + +- `key_id`, `ciphertext`: Required parameters passed to the `builder()` function. + +#### Sign Data + +Sign data using a KMS key. + +**Example** + +```rust +use infisical::kms::{SigningAlgorithm, SignRequest}; + +let request = SignRequest::builder("", "data to sign") + .signing_algorithm(SigningAlgorithm::RsassaPkcs1V15Sha256) + .is_digest(false) + .build(); + +let signature = client.kms().sign(request).await?; +``` + +**Parameters** + +- `key_id`, `data`: Required parameters passed to the `builder()` function. +- `.signing_algorithm(algorithm)`: Optional method to set the signing algorithm using the `SigningAlgorithm` enum (defaults to `SigningAlgorithm::RsassaPkcs1V15Sha256`). +- `.is_digest(is_digest)`: Optional method to indicate if the data is a digest (defaults to `false`). + +#### Verify Signature + +Verify a signature using a KMS key. + +**Example** + +```rust +use infisical::kms::{SigningAlgorithm, VerifyRequest}; + +let request = VerifyRequest::builder("", "data to sign", "signature") + .signing_algorithm(SigningAlgorithm::RsassaPkcs1V15Sha256) + .is_digest(false) + .build(); + +let verification = client.kms().verify(request).await?; +``` + +**Parameters** + +- `key_id`, `data`, `signature`: Required parameters passed to the `builder()` function. +- `.signing_algorithm(algorithm)`: Optional method to set the signing algorithm using the `SigningAlgorithm` enum (defaults to `SigningAlgorithm::RsassaPkcs1V15Sha256`). +- `.is_digest(is_digest)`: Optional method to indicate if the data is a digest (defaults to `false`). + +#### Get Public Key + +Get the public key for a KMS key. + +**Example** + +```rust +let public_key = client.kms().get_public_key("").await?; +``` + +**Parameters** + +- `key_id`: The ID of the key to get the public key for. + +#### Get Signing Algorithms + +Get the available signing algorithms for a KMS key. + +**Example** + +```rust +let algorithms = client.kms().get_signing_algorithms("").await?; +``` + +**Parameters** + +- `key_id`: The ID of the key to get signing algorithms for. + +## Development and Testing + +### Environment Setup + +For development and testing, you'll need to set up environment variables. Create a `.env` file in your project root: + +```env +INFISICAL_CLIENT_ID=your_client_id_here +INFISICAL_CLIENT_SECRET=your_client_secret_here +INFISICAL_BASE_URL=http://localhost:8080 # Optional: for local development + +# Project IDs for different resources +INFISICAL_SECRETS_PROJECT_ID=your_project_id_here +INFISICAL_KMS_PROJECT_ID=your_project_id_here +``` + +### Getting Credentials + +To obtain the required credentials: + +1. **Client ID and Secret**: Create a Universal Auth machine identity in your Infisical project settings +2. **Project ID**: Found in your project settings or URL when viewing a project in the Infisical dashboard + +### Running Tests + +Tests that require authentication are marked with `#[ignore]` and need valid credentials: + +```bash +# Run ignored tests (requires .env file with valid credentials) +cargo test -- --ignored --nocapture + +# Run a specific test +cargo test test_kms_resource -- --ignored --nocapture +``` + +**Note**: Integration tests require a running Infisical instance and valid authentication credentials. \ No newline at end of file diff --git a/docs/sdks/overview.mdx b/docs/sdks/overview.mdx index 32192805da..0b69491087 100644 --- a/docs/sdks/overview.mdx +++ b/docs/sdks/overview.mdx @@ -12,22 +12,22 @@ From local development to production, Infisical SDKs provide the easiest way for - Fetch secrets on demand - + Manage secrets for your Node application on demand - + Manage secrets for your Python application on demand - + Manage secrets for your Java application on demand - + Manage secrets for your .NET application on demand - + Manage secrets for your C++ application on demand - + Manage secrets for your Rust application on demand