Compare commits

...

5 Commits

Author SHA1 Message Date
sidwebworks
080bc3162f docs: add python oidc section 2025-08-29 02:36:50 +05:30
sidwebworks
bcad333234 fix: doc updates 2025-08-28 22:32:08 +05:30
Sid
25fc1ac06e Apply suggestions from code review
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2025-08-23 23:02:07 +05:30
Sid
de39548d6b Apply suggestions from code review
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2025-08-23 22:57:33 +05:30
sidwebworks
81756bb37a feat: merge sdk docs 2025-08-23 14:30:59 +05:30
11 changed files with 2466 additions and 2121 deletions

View File

@@ -342,10 +342,7 @@
},
{
"group": "Architecture",
"pages": [
"internals/architecture/components",
"internals/architecture/cloud"
]
"pages": ["internals/architecture/components", "internals/architecture/cloud"]
},
"internals/security",
"internals/service-tokens"
@@ -564,10 +561,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",
@@ -661,9 +655,7 @@
"documentation/platform/secret-scanning/overview",
{
"group": "Concepts",
"pages": [
"documentation/platform/secret-scanning/concepts/secret-scanning"
]
"pages": ["documentation/platform/secret-scanning/concepts/secret-scanning"]
}
]
},
@@ -712,18 +704,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"]
}
]
},
@@ -770,11 +757,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"]
}
]
},
@@ -1108,9 +1091,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",
@@ -2453,7 +2434,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",
@@ -2681,5 +2662,11 @@
"koala": {
"publicApiKey": "pk_b50d7184e0e39ddd5cdb43cf6abeadd9b97d"
}
}
},
"redirects": [
{
"source": "/sdks/languages/csharp",
"destination": "/sdks/languages/dotnet"
}
]
}

View File

@@ -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"
---
---
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 <iostream>
#include <libinfisical/InfisicalClient.h>
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("<machine-identity-universal-auth-client-id>", "<machine-identity-universal-auth-client-secret>")
.build())
.build());
const auto getSecretOptions = Infisical::Input::GetSecretOptionsBuilder()
.withEnvironment("<env-slug>") // dev, staging, prod, etc
.withProjectId("<your-project-id>")
.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("<env-slug>")
.withProjectId("<project-id>")
.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<std::string>>)` _(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("<env-slug>")
.withProjectId("<project-id>")
.withSecretKey("<secret-key>")
.withNewSecretKey("<new-secret-key>") // Optional
.withSecretValue("<new-secret-value>") // 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<std::string>>)` _(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("<env-slug>")
.withProjectId("<project-id>")
.withSecretKey("<secret-key>")
.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("<env-slug>")
.withProjectId("<project-id>")
.withSecretKey("<secret-key>")
.withType("shared")
.withSecretPath("<secret-path>")
.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<TSecret>`. Read more in the [TSecret Class](#tsecret-class) documentation.

View File

@@ -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)
<Warning>
**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.
</Warning>
## 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.
<Warning>
We do not recommend hardcoding your [Machine Identity Tokens](/platform/identities/overview). Setting it as an environment variable would be best.
</Warning>
# 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
<ParamField query="options" type="object">
<Expandable title="properties">
<ParamField query="ClientId" deprecated type="string" optional>
Your machine identity client ID.
</ParamField>
<ParamField query="ClientSecret" deprecated type="string" optional>
Your machine identity client secret.
</ParamField>
<ParamField query="AccessToken" deprecated type="string" optional>
An access token obtained from the machine identity login endpoint.
</ParamField>
<ParamField query="CacheTtl" type="number" default="300" optional>
Time-to-live (in seconds) for refreshing cached secrets.
If manually set to 0, caching will be disabled, this is not recommended.
</ParamField>
<ParamField query="SiteUrl" type="string" default="https://app.infisical.com" optional>
Your self-hosted absolute site URL including the protocol (e.g. `https://app.infisical.com`)
</ParamField>
<ParamField query="SslCertificatePath" optional>
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.
</ParamField>
<ParamField query="Auth" type="AuthenticationOptions">
The authentication object to use for the client. This is required unless you're using environment variables.
</ParamField>
</Expandable>
</ParamField>
### 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
<Info>
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.
</Info>
**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
<Info>
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.
</Info>
**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
<Info>
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.
</Info>
**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
<Info>
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.
</Info>
**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
<ParamField query="Parameters" type="object">
<Expandable title="properties">
<ParamField query="Environment" type="string" required>
The slug name (dev, prod, etc) of the environment from where secrets should be fetched from.
</ParamField>
<ParamField query="ProjectId" type="string">
The project ID where the secret lives in.
</ParamField>
<ParamField query="Path" type="string" optional>
The path from where secrets should be fetched from.
</ParamField>
<ParamField query="AttachToProcessEnv" type="boolean" default="false" optional>
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")`.
</ParamField>
<ParamField query="IncludeImports" type="boolean" default="false" optional>
Whether or not to include imported secrets from the current path. Read about [secret import](/documentation/platform/secret-reference)
</ParamField>
<ParamField query="Recursive" type="boolean" default="false" optional>
Whether or not to fetch secrets recursively from the specified path. Please note that there's a 20-depth limit for recursive fetching.
</ParamField>
<ParamField query="ExpandSecretReferences" type="boolean" default="true" optional>
Whether or not to expand secret references in the fetched secrets. Read about [secret reference](/documentation/platform/secret-reference)
</ParamField>
</Expandable>
</ParamField>
### 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
<ParamField query="Parameters" type="object" optional>
<Expandable title="properties">
<ParamField query="SecretName" type="string" required>
The key of the secret to retrieve.
</ParamField>
<ParamField query="ProjectId" type="string" required>
The project ID where the secret lives in.
</ParamField>
<ParamField query="Environment" type="string" required>
The slug name (dev, prod, etc) of the environment from where secrets should be fetched from.
</ParamField>
<ParamField query="Path" type="string" optional>
The path from where secret should be fetched from.
</ParamField>
<ParamField query="Type" type="string" optional>
The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared".
</ParamField>
<ParamField query="IncludeImports" type="boolean" optional>
Whether or not to include imported secrets from the current path. Read about [secret import](/documentation/platform/secret-reference)
</ParamField>
<ParamField query="ExpandSecretReferences" type="boolean" optional>
Whether or not to expand secret references in the fetched secrets. Read about [secret reference](/documentation/platform/secret-reference)
</ParamField>
</Expandable>
</ParamField>
### 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
<ParamField query="Parameters" type="object" optional>
<Expandable title="properties">
<ParamField query="SecretName" type="string" required>
The key of the secret to create.
</ParamField>
<ParamField query="SecretValue" type="string" required>
The value of the secret.
</ParamField>
<ParamField query="ProjectId" type="string" required>
The project ID where the secret lives in.
</ParamField>
<ParamField query="Environment" type="string" required>
The slug name (dev, prod, etc) of the environment from where secrets should be fetched from.
</ParamField>
<ParamField query="Path" type="string" optional>
The path from where secret should be created.
</ParamField>
<ParamField query="Type" type="string" optional>
The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared".
</ParamField>
</Expandable>
</ParamField>
### 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
<ParamField query="Parameters" type="object" optional>
<Expandable title="properties">
<ParamField query="SecretName" type="string" required>
The key of the secret to update.
</ParamField>
<ParamField query="SecretValue" type="string" required>
The new value of the secret.
</ParamField>
<ParamField query="ProjectId" type="string" required>
The project ID where the secret lives in.
</ParamField>
<ParamField query="Environment" type="string" required>
The slug name (dev, prod, etc) of the environment from where secrets should be fetched from.
</ParamField>
<ParamField query="Path" type="string" optional>
The path from where secret should be updated.
</ParamField>
<ParamField query="Type" type="string" optional>
The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared".
</ParamField>
</Expandable>
</ParamField>
### 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
<ParamField query="Parameters" type="object" optional>
<Expandable title="properties">
<ParamField query="SecretName" type="string">
The key of the secret to update.
</ParamField>
<ParamField query="ProjectId" type="string" required>
The project ID where the secret lives in.
</ParamField>
<ParamField query="Environment" type="string" required>
The slug name (dev, prod, etc) of the environment from where secrets should be fetched from.
</ParamField>
<ParamField query="Path" type="string" optional>
The path from where secret should be deleted.
</ParamField>
<ParamField query="Type" type="string" optional>
The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared".
</ParamField>
</Expandable>
</ParamField>
## 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
<ParamField query="Parameters" type="object" required>
<Expandable title="properties">
<ParamField query="Plaintext" type="string">
The plaintext you want to encrypt.
</ParamField>
<ParamField query="Key" type="string" required>
The symmetric key to use for encryption.
</ParamField>
</Expandable>
</ParamField>
#### 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
<ParamField query="Parameters" type="object" required>
<Expandable title="properties">
<ParamField query="Ciphertext" type="string">
The ciphertext you want to decrypt.
</ParamField>
<ParamField query="Key" type="string" required>
The symmetric key to use for encryption.
</ParamField>
<ParamField query="Iv" type="string" required>
The initialization vector to use for decryption.
</ParamField>
<ParamField query="Tag" type="string" required>
The authentication tag to use for decryption.
</ParamField>
</Expandable>
</ParamField>
#### Returns (string)
`Plaintext` (string): The decrypted plaintext.
*/}

View File

@@ -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("<machine-identity-universal-auth-client-id>", "<machine-identity-universal-auth-client-secret>").Result;
var options = new ListSecretsOptions
{
SetSecretsAsEnvironmentVariables = true,
EnvironmentSlug = "<your-env-slug>",
SecretPath = "/",
ProjectId = "<your-project-id>",
};
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-id>", "machine-identity-universal-auth-client-secret").Result
Dim options As New ListSecretsOptions With {
.SetSecretsAsEnvironmentVariables = True,
.EnvironmentSlug = "<your-env-slug>",
.SecretPath = "/",
.ProjectId = "<your-project-id>"
}
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<Secret[]> 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<Secret[]>`: The response containing the list of secrets.
#### Create Secret
```cs
public Task<Secret> CreateAsync(CreateSecretOptions options);
throws InfisicalException
```
```cs
var options = new CreateSecretOptions
{
SecretName = "SECRET_NAME",
SecretValue = "SECRET_VALUE",
EnvironmentSlug = "<environment-slug>",
SecretPath = "/",
ProjectId = "<your-project-id>",
Metadata = new SecretMetadata[] {
new SecretMetadata {
Key = "metadata-key",
Value = "metadata-value"
}
}
};
Task<Secret> 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<Secret>`: The created secret.
#### Update Secret
```cs
public Task<Secret> UpdateAsync(UpdateSecretOptions options);
throws InfisicalException
```
```cs
var updateSecretOptions = new UpdateSecretOptions
{
SecretName = "EXISTING_SECRET_NAME",
EnvironmentSlug = "<environment-slug>",
SecretPath = "/",
NewSecretName = "NEW_SECRET_NAME",
NewSecretValue = "new-secret-value",
ProjectId = "<project-id>",
};
Task<Secret> 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<Secret>`: The updated secret.
#### Get Secret by Name
```cs
public Task<Secret> GetAsync(GetSecretOptions options);
throws InfisicalException
```
```cs
var getSecretOptions = new GetSecretOptions
{
SecretName = "SECRET_NAME",
EnvironmentSlug = "<environment-slug>",
SecretPath = "/",
ProjectId = "<project-id>",
};
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<Secret>`: 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 = "<environment-slug>",
SecretPath = "/",
ProjectId = "<project-id>",
};
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<Secret>`: 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<SubscriberIssuedCertificate> IssueCertificateAsync(IssueCertificateOptions options);
throws InfisicalException
```
```cs
var options = new IssueCertificateOptions
{
SubscriberName = "<subscriber-name>",
ProjectId = "<your-project-id>",
};
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<SubscriberIssuedCertificate>`: The newly issued certificate along with it's credentials for the specified subscriber.
#### Retrieve latest certificate bundle
```cs
public async Task<CertificateBundle> RetrieveLatestCertificateBundleAsync(RetrieveLatestCertificateBundleOptions options)
throws InfisicalException
```
```cs
var options = new RetrieveLatestCertificateBundleOptions
{
SubscriberName = "<subscriber-name>",
ProjectId = "<your-project-id>",
};
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<CertificateBundle>`: The latest certificate bundle for the specified subscriber.

View File

@@ -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)

View File

@@ -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
<dependency>
<groupId>com.infisical</groupId>
<artifactId>sdk</artifactId>
<version>{version}</version>
</dependency>
```
### 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(
"<secret-name>",
"<project-id>",
"<env-slug>",
"<secret-path>",
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
<Warning>
We do not recommend hardcoding your [Machine Identity Tokens](/platform/identities/overview). Setting it as an environment variable would be best.
</Warning>
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
<ParamField query="options" type="object">
<Expandable title="properties">
<ParamField query="setClientID()" type="string" deprecated optional>
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.
</ParamField>
<ParamField query="setClientSecret()" deprecated type="string" optional>
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.
</ParamField>
<ParamField query="setAccessToken()" deprecatedtype="string" optional>
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.
</ParamField>
<ParamField query="setCacheTTL()" type="number" default="300" optional>
Time-to-live (in seconds) for refreshing cached secrets.
If manually set to 0, caching will be disabled, this is not recommended.
</ParamField>
<ParamField query="setSiteURL()" type="string" default="https://app.infisical.com" optional>
Your self-hosted absolute site URL including the protocol (e.g. `https://app.infisical.com`)
</ParamField>
<ParamField query="setSSLCertificatePath()">
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.
</ParamField>
<ParamField query="setAuth()" type="AuthenticationOptions">
The authentication object to use for the client. This is required unless you're using environment variables.
</ParamField>
</Expandable>
</ParamField>
### 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
<Info>
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.
</Info>
**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
<Info>
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.
</Info>
**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
<Info>
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.
</Info>
**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
<Info>
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.
</Info>
**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
<ParamField query="Parameters" type="object">
<Expandable title="properties">
<ParamField query="setEnvironment()" type="string" required>
The slug name (dev, prod, etc) of the environment from where secrets should be fetched from.
</ParamField>
<ParamField query="setProjectID()" type="string">
The project ID where the secret lives in.
</ParamField>
<ParamField query="setPath()" type="string" optional>
The path from where secrets should be fetched from.
</ParamField>
<ParamField query="setAttachToProcessEnv()" type="boolean" default="false" optional>
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")`.
</ParamField>
<ParamField query="setIncludeImports()" type="boolean" default="false" optional>
Whether or not to include imported secrets from the current path. Read about [secret import](/documentation/platform/secret-reference)
</ParamField>
<ParamField query="setRecursive()" type="boolean" default="false" optional>
Whether or not to fetch secrets recursively from the specified path. Please note that there's a 20-depth limit for recursive fetching.
</ParamField>
<ParamField query="setExpandSecretReferences()" type="boolean" default="true" optional>
Whether or not to expand secret references in the fetched secrets. Read about [secret reference](/documentation/platform/secret-reference)
</ParamField>
</Expandable>
</ParamField>
### client.getSecret(options)
```java
GetSecretOptions options = new GetSecretOptions();
options.setSecretName("TEST");
options.setEnvironment("dev");
options.setProjectID("PROJECT_ID");
var input = LdapAuthLoginInput
.builder()
.identityId("<machine-identity-id>")
.username("<ldap-username>")
.password("<ldap-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
<ParamField query="Parameters" type="object" optional>
<Expandable title="properties">
<ParamField query="setSecretName()" type="string" required>
The key of the secret to retrieve.
</ParamField>
<ParamField query="setProjectID()" type="string" required>
The project ID where the secret lives in.
</ParamField>
<ParamField query="setEnvironment()" type="string" required>
The slug name (dev, prod, etc) of the environment from where secrets should be fetched from.
</ParamField>
<ParamField query="setPath()" type="string" optional>
The path from where secret should be fetched from.
</ParamField>
<ParamField query="setType()" type="string" optional>
The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared".
</ParamField>
<ParamField query="setIncludeImports()" type="boolean" optional>
Whether or not to include imported secrets from the current path. Read about [secret import](/documentation/platform/secret-reference)
</ParamField>
<ParamField query="setExpandSecretReferences()" type="boolean" default="true" optional>
Whether or not to expand secret references in the fetched secrets. Read about [secret reference](/documentation/platform/secret-reference)
</ParamField>
</Expandable>
</ParamField>
### 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
<ParamField query="Parameters" type="object" optional>
<Expandable title="properties">
<ParamField query="setSecretName()" type="string" required>
The key of the secret to create.
</ParamField>
<ParamField query="setSecretValue()" type="string" required>
The value of the secret.
</ParamField>
<ParamField query="setProjectID()" type="string" required>
The project ID where the secret lives in.
</ParamField>
<ParamField query="setEnvironment()" type="string" required>
The slug name (dev, prod, etc) of the environment from where secrets should be fetched from.
</ParamField>
<ParamField query="setPath()" type="string" optional>
The path from where secret should be created.
</ParamField>
<ParamField query="setType()" type="string" optional>
The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared".
</ParamField>
</Expandable>
</ParamField>
### 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`
<ParamField query="Parameters" type="object" optional>
<Expandable title="properties">
<ParamField query="setSecretName()" type="string" required>
The key of the secret to update.
</ParamField>
<ParamField query="setSecretValue()" type="string" required>
The new value of the secret.
</ParamField>
<ParamField query="setProjectID()" type="string" required>
The project ID where the secret lives in.
</ParamField>
<ParamField query="setEnvironment()" type="string" required>
The slug name (dev, prod, etc) of the environment from where secrets should be fetched from.
</ParamField>
<ParamField query="setPath()" type="string" optional>
The path from where secret should be updated.
</ParamField>
<ParamField query="setType()" type="string" optional>
The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared".
</ParamField>
</Expandable>
</ParamField>
This sub-class handles operations related to secrets:
### client.deleteSecret(options)
#### List Secrets
```java
DeleteSecretOptions options = new DeleteSecretOptions();
public List<Secret> 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
<ParamField query="Parameters" type="object" optional>
<Expandable title="properties">
<ParamField query="setSecretName()" type="string">
The key of the secret to update.
</ParamField>
<ParamField query="setProjectID()" type="string" required>
The project ID where the secret lives in.
</ParamField>
<ParamField query="setEnvironment()" type="string" required>
The slug name (dev, prod, etc) of the environment from where secrets should be fetched from.
</ParamField>
<ParamField query="setPath()" type="string" optional>
The path from where secret should be deleted.
</ParamField>
<ParamField query="setType()" type="string" optional>
The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared".
</ParamField>
</Expandable>
</ParamField>
## 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<Secret> secrets = sdk.Secrets().ListSecrets(
"<project-id>",
"<env-slug>", // 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("<secret-key>")
);
```
#### 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("<secret-key>")`
**Returns:**
- `List<Secret>`: 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
<ParamField query="Parameters" type="object" required>
<Expandable title="properties">
<ParamField query="setPlaintext()" type="string">
The plaintext you want to encrypt.
</ParamField>
<ParamField query="setKey()" type="string" required>
The symmetric key to use for encryption.
</ParamField>
</Expandable>
</ParamField>
#### 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",
"<project-id>",
"<env-slug>", // dev, prod, staging, etc.
"/secret/path", // `/` is the root folder
);
```
#### Methods
<ParamField query="Parameters" type="object" required>
<Expandable title="properties">
<ParamField query="setCiphertext()" type="string">
The ciphertext you want to decrypt.
</ParamField>
<ParamField query="setKey()" type="string" required>
The symmetric key to use for encryption.
</ParamField>
<ParamField query="setIv()" type="string" required>
The initialization vector to use for decryption.
</ParamField>
<ParamField query="setTag()" type="string" required>
The authentication tag to use for decryption.
</ParamField>
</Expandable>
</ParamField>
**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.
*/}
**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",
"<project-id>",
"<env-slug>", // 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",
"<project-id>",
"<env-slug>", // 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",
"<project-id>",
"<env-slug>", // 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("<folder-id>");
```
**Parameters:**
- `folderId` (String): The ID of the folder to retrieve.
**Returns:**
- `Folder`: The retrieved folder.
#### List Folders
```java
public List<Folder> List(
ListFoldersInput input
)
throws InfisicalException
```
```java
ListFoldersInput input = ListFoldersInput
.builder()
.projectId("<your-project-id>")
.environmentSlug("<env-slug>")
.folderPath("/")
.recursive(false)
.build();
List<Folder> 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<Folder>`: The retrieved folders.
#### Create Folder
```java
public Folder Create(
CreateFolderInput input
)
throws InfisicalException
```
```java
var input = CreateFolderInput
.builder()
.projectId("<your-project-id>")
.environmentSlug("<env-slug>")
.folderName("<folder-name>")
.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("<your-project-id>")
.environmentSlug("<env-slug>")
.folderId("<id-of-folder-to-update>")
.newFolderName("<the-new-folder-name>")
.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("<the-folder-id>")
.environmentSlug("<env-slug>")
.projectId("<your-project-id>")
.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.

File diff suppressed because it is too large Load Diff

View File

@@ -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.
<Warning>
We do not recommend hardcoding your [Machine Identity Tokens](/platform/identities/overview). Setting it as an environment variable would be best.
</Warning>
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="<machine-identity-client-id>",
client_secret="<machine-identity-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="<project-id>", environment_slug="dev", secret_path="/")
```
#### Parameters
## InfisicalSDKClient Parameters
<ParamField query="options" type="object">
<Expandable title="properties">
<ParamField query="client_id" type="string" deprecated optional>
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.
</ParamField>
<ParamField query="client_secret" type="string" deprecated optional>
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.
</ParamField>
<ParamField query="access_token" type="string" deprecated optional>
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="<optional-auth-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.
</ParamField>
## Core Methods
<ParamField query="cache_ttl" type="number" default="300" optional>
Time-to-live (in seconds) for refreshing cached secrets.
If manually set to 0, caching will be disabled, this is not recommended.
</ParamField>
The SDK methods are organized into the following high-level categories:
<ParamField query="site_url" type="string" default="https://app.infisical.com" optional>
Your self-hosted absolute site URL including the protocol (e.g. `https://app.infisical.com`)
</ParamField>
1. `auth`: Handles authentication methods.
2. `secrets`: Manages CRUD operations for secrets.
3. `kms`: Perform cryptographic operations with Infisical KMS.
<ParamField query="ssl_certificate_path" optional>
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.
</ParamField>
### `auth`
<ParamField query="auth" type="AuthenticationOptions">
The authentication object to use for the client. This is required unless you're using environment variables.
</ParamField>
</Expandable>
</ParamField>
### 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
<Info>
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.
</Info>
**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
<Info>
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.
</Info>
**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
<Info>
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.
</Info>
**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="<machine-identity-client-id>",
client_secret="<machine-identity-client-secret>"
)
```
#### AWS Auth
#### Kubernetes Auth
<Info>
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.
</Info>
**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="<machine-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
<ParamField query="Parameters" type="object">
<Expandable title="properties">
<ParamField query="environment" type="string" required>
The slug name (dev, prod, etc) of the environment from where secrets should be fetched from.
</ParamField>
<ParamField query="project_id" type="string" required>
The project ID where the secret lives in.
</ParamField>
<ParamField query="path" type="string" optional>
The path from where secrets should be fetched from.
</ParamField>
<ParamField query="attach_to_process_env" type="boolean" default="false" optional>
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"]`.
</ParamField>
<ParamField query="recursive" type="boolean" default="false" optional>
Whether or not to fetch secrets recursively from the specified path. Please note that there's a 20-depth limit for recursive fetching.
</ParamField>
<ParamField query="expand_secret_references" type="boolean" default="true" optional>
Whether or not to expand secret references in the fetched secrets. Read about [secret reference](/documentation/platform/secret-reference)
</ParamField>
<ParamField query="include_imports" type="boolean" default="false" optional>
Whether or not to include imported secrets from the current path. Read about [secret import](/documentation/platform/secret-reference)
</ParamField>
</Expandable>
</ParamField>
### 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
<ParamField query="Parameters" type="object" optional>
<Expandable title="properties">
<ParamField query="secret_name" type="string" required>
The key of the secret to retrieve
</ParamField>
<ParamField query="include_imports" type="boolean">
Whether or not to include imported secrets from the current path. Read about [secret import](/documentation/platform/secret-reference)
</ParamField>
<ParamField query="environment" type="string" required>
The slug name (dev, prod, etc) of the environment from where secrets should be fetched from.
</ParamField>
<ParamField query="project_id" type="string" required>
The project ID where the secret lives in.
</ParamField>
<ParamField query="path" type="string" optional>
The path from where secret should be fetched from.
</ParamField>
<ParamField query="type" type="string" optional>
The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "personal".
</ParamField>
<ParamField query="include_imports" type="boolean" default="false" optional>
Whether or not to include imported secrets from the current path. Read about [secret import](/documentation/platform/secret-reference)
</ParamField>
<ParamField query="expand_secret_references" type="boolean" default="true" optional>
Whether or not to expand secret references in the fetched secrets. Read about [secret reference](/documentation/platform/secret-reference)
</ParamField>
</Expandable>
</ParamField>
### 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
<ParamField query="Parameters" type="object" optional>
<Expandable title="properties">
<ParamField query="secret_name" type="string" required>
The key of the secret to create.
</ParamField>
<ParamField query="secret_value" type="string" required>
The value of the secret.
</ParamField>
<ParamField query="project_id" type="string" required>
The project ID where the secret lives in.
</ParamField>
<ParamField query="environment" type="string" required>
The slug name (dev, prod, etc) of the environment from where secrets should be fetched from.
</ParamField>
<ParamField query="path" type="string" optional>
The path from where secret should be created.
</ParamField>
<ParamField query="type" type="string" optional>
The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared".
</ParamField>
</Expandable>
</ParamField>
### 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
<ParamField query="Parameters" type="object" optional>
<Expandable title="properties">
<ParamField query="secret_name" type="string" required>
The key of the secret to update.
</ParamField>
<ParamField query="secret_value" type="string" required>
The new value of the secret.
</ParamField>
<ParamField query="project_id" type="string" required>
The project ID where the secret lives in.
</ParamField>
<ParamField query="environment" type="string" required>
The slug name (dev, prod, etc) of the environment from where secrets should be fetched from.
</ParamField>
<ParamField query="path" type="string" optional>
The path from where secret should be updated.
</ParamField>
<ParamField query="type" type="string" optional>
The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared".
</ParamField>
</Expandable>
</ParamField>
### client.deleteSecret(options)
```py
client.deleteSecret(options=DeleteSecretOptions(
environment="dev",
project_id="PROJECT_ID",
secret_name="API_KEY"
))
```
Delete a secret in Infisical.
#### Parameters
<ParamField query="Parameters" type="object" optional>
<Expandable title="properties">
<ParamField query="secret_name" type="string">
The key of the secret to update.
</ParamField>
<ParamField query="project_id" type="string" required>
The project ID where the secret lives in.
</ParamField>
<ParamField query="environment" type="string" required>
The slug name (dev, prod, etc) of the environment from where secrets should be fetched from.
</ParamField>
<ParamField query="path" type="string" optional>
The path from where secret should be deleted.
</ParamField>
<ParamField query="type" type="string" optional>
The type of the secret. Valid options are "shared" or "personal". If not specified, the default value is "shared".
</ParamField>
</Expandable>
</ParamField>
## 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="<oidc-identity-id>",
jwt="<your-oidc-jwt-token>"
)
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.
<ParamField query="Parameters" type="object" required>
<Expandable title="properties">
<ParamField query="plaintext" type="string">
The plaintext you want to encrypt.
</ParamField>
<ParamField query="key" type="string" required>
The symmetric key to use for encryption.
</ParamField>
</Expandable>
</ParamField>
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="<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 `<hidden-by-infisical>`. 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.
<ParamField query="Parameters" type="object" required>
<Expandable title="properties">
<ParamField query="ciphertext" type="string">
The ciphertext you want to decrypt.
</ParamField>
<ParamField query="key" type="string" required>
The symmetric key to use for encryption.
</ParamField>
<ParamField query="iv" type="string" required>
The initialization vector to use for decryption.
</ParamField>
<ParamField query="tag" type="string" required>
The authentication tag to use for decryption.
</ParamField>
</Expandable>
</ParamField>
**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="<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-id>",
project_slug="<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="<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 `<hidden-by-infisical>`. 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="<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="<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="<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="<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="<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="<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="<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="<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="<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.

View File

@@ -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)

View File

@@ -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"
---
---
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("<your-client-id>", "<your-client-secret>");
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", "<your-project-id>", "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<String, InfisicalError>`: 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",
"<your-project-id>",
"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", "<your-project-id>", "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("<your-project-id>", "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", "<your-project-id>", "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", "<your-project-id>", "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("<your-project-id>").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("<key-id>").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("<key-name>").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("<your-project-id>", "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("<key-id>")
.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("<key-id>").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("<key-id>", "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("<key-id>", "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("<key-id>", "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("<key-id>", "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("<key-id>").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("<key-id>").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.

View File

@@ -12,22 +12,22 @@ From local development to production, Infisical SDKs provide the easiest way for
- Fetch secrets on demand
<CardGroup cols={2}>
<Card title="Node.js" href="https://github.com/Infisical/node-sdk-v2?tab=readme-ov-file#infisical-nodejs-sdk" icon="/images/sdks/languages/node.svg">
<Card title="Node.js" href="/sdks/languages/node" icon="/images/sdks/languages/node.svg">
Manage secrets for your Node application on demand
</Card>
<Card href="https://github.com/Infisical/python-sdk-official?tab=readme-ov-file#infisical-python-sdk" title="Python" icon="/images/sdks/languages/python.svg">
<Card href="/sdks/languages/python" title="Python" icon="/images/sdks/languages/python.svg">
Manage secrets for your Python application on demand
</Card>
<Card href="https://github.com/Infisical/java-sdk?tab=readme-ov-file#infisical-java-sdk" title="Java" icon="/images/sdks/languages/java.svg">
<Card href="/sdks/languages/java" title="Java" icon="/images/sdks/languages/java.svg">
Manage secrets for your Java application on demand
</Card>
<Card href="https://github.com/Infisical/infisical-dotnet-sdk?tab=readme-ov-file#infisical-net-sdk" title=".NET" icon="/images/sdks/languages/dotnet.svg">
<Card href="/sdks/languages/dotnet" title=".NET" icon="/images/sdks/languages/dotnet.svg">
Manage secrets for your .NET application on demand
</Card>
<Card href="https://github.com/Infisical/infisical-cpp-sdk/?tab=readme-ov-file#infisical-c-sdk" title="C++" icon="/images/sdks/languages/cpp.svg">
<Card href="/sdks/languages/cpp" title="C++" icon="/images/sdks/languages/cpp.svg">
Manage secrets for your C++ application on demand
</Card>
<Card href="https://github.com/Infisical/rust-sdk?tab=readme-ov-file#infisical--the-official-infisical-rust-sdk" title="Rust" icon="/images/sdks/languages/rust.svg">
<Card href="/sdks/languages/rust" title="Rust" icon="/images/sdks/languages/rust.svg">
Manage secrets for your Rust application on demand
</Card>
<Card href="/sdks/languages/go" title="Go" icon="/images/sdks/languages/go.svg">