PHP code example of tigusigalpa / yandex-lockbox-php
1. Go to this page and download the library: Download tigusigalpa/yandex-lockbox-php library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
tigusigalpa / yandex-lockbox-php example snippets
use Tigusigalpa\YandexLockbox\Token\OAuthTokenProvider;
$tokenProvider = new OAuthTokenProvider('y0_your-oauth-token');
$tokenProvider = new OAuthTokenProvider('y0_your-oauth-token');
// Get IAM token (cached for 12 hours)
$iamToken = $tokenProvider->getToken();
$tokenProvider = new OAuthTokenProvider('y0_your-oauth-token');
// Get cloud client for infrastructure management
$cloudClient = $tokenProvider->getCloudClient();
// Get all clouds
$clouds = $cloudClient->clouds()->list();
foreach ($clouds['clouds'] as $cloud) {
echo "Cloud: {$cloud['name']} (ID: {$cloud['id']})\n";
}
// Use first cloud
$cloudId = $clouds['clouds'][0]['id'];
// Get first cloud ID (convenience method)
$cloudId = $tokenProvider->getFirstCloudId();
// Get all folders in cloud
$cloudClient = $tokenProvider->getCloudClient();
$folders = $cloudClient->folders()->list($cloudId);
foreach ($folders['folders'] as $folder) {
echo "Folder: {$folder['name']} (ID: {$folder['id']})\n";
}
// Use first folder
$folderId = $folders['folders'][0]['id'];
// Get first folder ID (convenience method)
$folderId = $tokenProvider->getFirstFolderId($cloudId);
// Or get first folder from first cloud in one call
$folderId = $tokenProvider->getFirstFolderIdFromFirstCloud();
$subjectId = $manager->getUserIdByLogin('your-yandex-login'); // [email protected]
$manager->assignRoleToFolder(
$iamToken,
$folderId,
$subjectId,
'lockbox.editor',
'userAccount',
true // waitForCompletion - waits until operation is done
);
use Tigusigalpa\YandexLockbox\Client;
use Tigusigalpa\YandexLockbox\Token\OAuthTokenProvider;
// Create client with OAuth token
$tokenProvider = new OAuthTokenProvider('y0_your-oauth-token');
$client = new Client($tokenProvider);
// List all secrets in a folder
$secrets = $client->listSecrets($folderId);
foreach ($secrets['secrets'] as $secret) {
echo "{$secret['name']} (ID: {$secret['id']})\n";
echo "Description: {$secret['description']}\n";
echo "Labels: " . json_encode($secret['labels']) . "\n";
echo "Status: {$secret['status']}\n";
echo "Created at: {$secret['createdAt']}\n";
echo "Updated at: {$secret['updatedAt']}\n";
echo "Current version: {$secret['currentVersion']}\n";
}
// Get secret metadata
// @see https://yandex.cloud/en/docs/lockbox/api-ref/Secret/get
$secret = $client->getSecret('your-secret-id');
// Get secret payload (actual values)
$payload = $client->getPayload('your-secret-id');
foreach ($payload['entries'] as $entry) {
echo "{$entry['key']}: {$entry['textValue']}\n"; // or {$entry['binaryValue']}
}
echo $payload['versionId'];
// Optional: get specific version
$payload = $client->getPayload('your-secret-id', 'version-id');
// Create a new secret
// @see https://yandex.cloud/en/docs/lockbox/api-ref/Secret/create
$created = $client->createSecret([
'folderId' => $folderId,
'name' => 'my-api-keys',
'description' => 'Production API keys',
'labels' => ['env' => 'production'],
]);
$secretId = $created['id'];
// Add a new version with secret values
// Uses POST /secrets/{id}:addVersion endpoint
// @see https://yandex.cloud/en/docs/lockbox/api-ref/Secret/addVersion
$version = $client->addVersion($secretId, [
'description' => 'Version with API keys', // Optional
'payloadEntries' => [
['key' => 'API_KEY', 'textValue' => 'super-secret-key'],
['key' => 'API_SECRET', 'textValue' => 'super-secret-value'],
],
]);
// Update secret metadata
$updated = $client->updateSecret($secretId, [
'name' => 'updated-name',
'description' => 'Updated description',
]);
// List all versions
$versions = $client->listVersions($secretId);
// Activate/Deactivate secret
$client->activateSecret($secretId);
$client->deactivateSecret($secretId);
// Schedule version destruction (7 days by default)
$client->scheduleVersionDestruction($secretId, 'version-id', '604800s');
// Cancel scheduled destruction
$client->cancelVersionDestruction($secretId, 'version-id');
// Delete secret
$client->deleteSecret($secretId);
// List operations
$operations = $client->listOperations($secretId);
// Access control
$bindings = $client->listAccessBindings($secretId);
$client->setAccessBindings($secretId, [
['roleId' => 'viewer', 'subject' => ['type' => 'userAccount', 'id' => 'user-id']],
]);
$manager = new OAuthTokenManager('y0_your-oauth-token');
$iamToken = $manager->getIamToken();
// Set waitForCompletion to true (6th parameter)
$result = $manager->assignRoleToFolder(
$iamToken,
'folder-id',
'user-id',
'lockbox.editor',
'userAccount',
true, // waitForCompletion
60 // maxWaitSeconds (optional, default: 60)
);
// $result['done'] will be true
// Start operation
$operation = $manager->assignRoleToFolder($iamToken, 'folder-id', 'user-id', 'lockbox.editor');
// Check if done
if (!$operation['done']) {
// Wait for operation to complete
$completed = $manager->waitForOperation(
$iamToken,
$operation['id'],
60 // maxWaitSeconds (optional)
);
if ($completed['done']) {
echo "Operation completed successfully!\n";
}
}
// Or check status without waiting
$status = $manager->getOperation($iamToken, $operation['id']);
echo "Operation status: " . ($status['done'] ? 'completed' : 'in progress') . "\n";
use Tigusigalpa\YandexLockbox\Auth\OAuthTokenManager;
$manager = new OAuthTokenManager('y0_your-oauth-token');
$iamToken = $manager->getIamToken();
// List access bindings with pagination
$result = $manager->listFolderAccessBindings($iamToken, 'folder-id', 100);
foreach ($result['accessBindings'] as $binding) {
echo "Role: {$binding['roleId']}\n";
echo "Subject: {$binding['subject']['id']} ({$binding['subject']['type']})\n";
}
// Handle pagination if needed
if (isset($result['nextPageToken'])) {
$nextPage = $manager->listFolderAccessBindings(
$iamToken,
'folder-id',
100,
$result['nextPageToken']
);
}
// Get all bindings at once (automatic pagination)
$allBindings = $manager->getAllFolderAccessBindings($iamToken, 'folder-id');
echo "Total permissions: " . count($allBindings) . "\n";
// Group by role
$byRole = [];
foreach ($allBindings as $binding) {
$byRole[$binding['roleId']][] = $binding['subject'];
}
[
'accessBindings' => [
[
'roleId' => 'lockbox.editor', // Role identifier
'subject' => [
'id' => 'ajef55nu903fiklhapf9', // User/SA ID
'type' => 'userAccount' // 'userAccount' or 'serviceAccount'
]
],
// ... more bindings
],
'nextPageToken' => 'token...' // Present if more pages available
]
use Tigusigalpa\YandexLockbox\Laravel\Facades\Lockbox;
// List secrets using default folder from config
$secrets = Lockbox::listSecrets(config('lockbox.default_folder_id'));
// Get secret metadata
$secret = Lockbox::getSecret('secret-id');
// Get actual secret values
$payload = Lockbox::getPayload('secret-id');
foreach ($payload['entries'] as $entry) {
echo $entry['key'] . ': ' . $entry['textValue'] . PHP_EOL;
}
// Create secret
$created = Lockbox::createSecret([
'folderId' => config('lockbox.default_folder_id'),
'name' => 'laravel-secrets',
'description' => 'Laravel application secrets',
]);
// Add version
$version = Lockbox::addVersion('secret-id', [
'payloadEntries' => [
['key' => 'DB_PASSWORD', 'textValue' => env('DB_PASSWORD')],
['key' => 'APP_KEY', 'textValue' => env('APP_KEY')],
],
]);
use Tigusigalpa\YandexLockbox\Exceptions\AuthenticationException;
use Tigusigalpa\YandexLockbox\Exceptions\NotFoundException;
use Tigusigalpa\YandexLockbox\Exceptions\RateLimitException;
use Tigusigalpa\YandexLockbox\Exceptions\ValidationException;
use Tigusigalpa\YandexLockbox\Exceptions\LockboxException;
try {
$payload = $client->getPayload('secret-id');
} catch (AuthenticationException $e) {
// Handle 401/403 errors
echo "Authentication failed: " . $e->getMessage();
} catch (NotFoundException $e) {
// Handle 404 errors
echo "Secret not found: " . $e->getMessage();
} catch (RateLimitException $e) {
// Handle 429 errors
echo "Rate limit exceeded: " . $e->getMessage();
} catch (ValidationException $e) {
// Handle 400 errors
echo "Validation error: " . $e->getMessage();
} catch (LockboxException $e) {
// Handle other errors
echo "API error: " . $e->getMessage();
print_r($e->getContext());
}
bash
composer json
{
"repositories": [
{
"type": "path",
"url": "public_html/packages/yandex-lockbox-php"
}
],
"bash
composer update tigusigalpa/yandex-lockbox-php
bash
php artisan vendor:publish --tag=yandex-lockbox-config
bash
# Basic run
php artisan lockbox:test
# With specific folder
php artisan lockbox:test --folder=b1g8dn6s4f5h6j7k8l9m
# With automatic cleanup
php artisan lockbox:test --cleanup
bash
# Interactive mode
php artisan lockbox:add-version e6q7r8s9t0u1v2w3x4y5
# With parameters
php artisan lockbox:add-version e6q7r8s9t0u1v2w3x4y5 \
--entry=DB_HOST=localhost \
--entry=DB_USER=admin \
--entry=DB_PASSWORD=secret
# From JSON file
php artisan lockbox:add-version e6q7r8s9t0u1v2w3x4y5 --file=secrets.json
bash
# With confirmation
php artisan lockbox:delete e6q7r8s9t0u1v2w3x4y5
# Without confirmation
php artisan lockbox:delete e6q7r8s9t0u1v2w3x4y5 --force
bash
# 1. Check connection
php artisan lockbox:test
# 2. View existing secrets
php artisan lockbox:list
# 3. View specific secret
php artisan lockbox:show <secret-id> --payload
bash
# 1. Create secret
php artisan lockbox:create production-db \
--description="Production database credentials" \
--label=env=production
# 2. Add values
php artisan lockbox:add-version <secret-id> \
--entry=DB_HOST=prod-db.example.com \
--entry=DB_USER=prod_user \
--entry=DB_PASSWORD=secure_password
# 3. Verify
php artisan lockbox:show <secret-id> --payload
bash
# 1. View current version
php artisan lockbox:show <secret-id> --payload
# 2. Add new version
php artisan lockbox:add-version <secret-id> \
--entry=DB_PASSWORD=new_password
# 3. Verify new version
php artisan lockbox:show <secret-id> --payload