定制 polokij/laravel-vault-env 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

polokij/laravel-vault-env

Composer 安装命令:

composer require polokij/laravel-vault-env

包简介

Hashicorp Vault client for Laravel with possibility set the env variables from Vault secret dynamically

README 文档

README

This package provide the base features for Hashicorp Vault API.

Motivation

Developing my multi-tenant application using Laravel I've faced with lacking of the package which could fetch the env variables from vault and apply it on bootstrapping the application. Here it bref implementation of the required features:

- Vault API Client + Service + Facade   
- artisan command to unseal the vault
- artisan command for create the secret engine 
- Laravel bootstraper which apply the env variables fetched from Vault  

Requirements

- Laravel 9+
- PHP 8+

Installation

Adding composer package

 composer require polokij/laravel-vault-env

Setting up the .env variables

VAULT_ADDR=http://vault:8200 
# Required is no VAULT_ADDR specified
VAULT_HOST=vault
VAULT_PORT=8200
VAULT_SCHEME=https
# The storage engine thich will be used by default kv2 or secrets, or whatewhere
VAULT_DEFAULT_ENGINE=kv2
# The prefix will be added to each key on put/get requests
VAULT_KEY_PREFIX=TenantRootPath

VAULT_TOKEN=

Publishing the config

php artisan vendor:publish --provider="LaravelVault\VaultServiceProvider"

Usage

  • Unseal Vault using json php artisan vault:unseal -f secret/file.json
  • Unseal Vault using key as command arguments php artisan vault:unseal $key
  • Check the seal status php artisan vault:unseal -s
  • Create new secret storage php artisan vault:storage create new_storage_name
  • Access to Secrets
Vault::secret('my-secret', ['foo' => 'bar']); // push the secret to Vault 
Vault::secret('my-secret'); // pull the secret from Vault - return ['foo' => 'bar']
Vault::instance()->sys->get('some/not/implemented/endpoints'); // call the other endpoints on sys group 
Vault::instance()->auth->get('some/not/implemented/endpoints'); // call the other endpoints on auth group 

Bootstrap the application with dynamic env variables

Example for Multi-tenant application:

bootstrap/app.php

$app = new Illuminate\Foundation\Application(
    $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);

$app->afterLoadingEnvironment(function () use ($app) {
    // checking is the feature enabled
    if (env('VAULT_LOAD_ENV', false)) {
        try {
            $tenantId = env('TENANT_ID');

            // resolving tenant_id by headers - make sure proxy override this header for security reason
            if (!$tenantId) {
                $headers = collect(getallheaders());
                $tenantIdHeader = env('TENANT_ID_HEADER', 'tenant-id');
                $tenantId = $headers
                    ->first(fn($value, $key) => $key === $tenantIdHeader
                        || strtolower($key) === $tenantIdHeader);
            }

            if (!$tenantId) {
                throw new Exception('Missed Tenant_id ');
            }

            $envRepository = Env::getRepository();
            $vaultDefaultPrefix = $envRepository->get('VAULT_KEY_PREFIX');
            $envRepository->set('VAULT_KEY_PREFIX', $vaultDefaultPrefix.'/'.$tenantId);

            (new LoadEnvironmentVariablesVault)->bootstrap($app);
        } catch (Throwable $e) {
            // preparing the logs for exception
            $app->instance('config', $config = new Repository([]));

            throw $e;
        }
    }
});

Alternative way

To enable this feature override the array of bootstrappers on app/Console/Kernel.php and app/Http/Kernel.php files app/Console/Kernel.php

use LaravelVault\LoadEnvironmentVariablesVault;

class Kernel extends ConsoleKernel
{
    /**
     * The bootstrap classes for the application.
     *
     * @var string[]
     */
    protected $bootstrappers = [
        LoadEnvironmentVariables::class,
        LoadEnvironmentVariablesVault::class, // <-- added custom bootstrapper 
        LoadConfiguration::class,
        HandleExceptions::class,
        RegisterFacades::class,
        SetRequestForConsole::class,
        RegisterProviders::class,
        BootProviders::class,
    ];

app/Http/Kernel.php

use LaravelVault\LoadEnvironmentVariablesVault;

class Kernel extends HttpKernel
{
    /**
     * The bootstrap classes for the application.
     *
     * @var string[]
     */
    protected $bootstrappers = [
        LoadEnvironmentVariables::class,
        LoadEnvironmentVariablesVault::class,
        LoadConfiguration::class,
        HandleExceptions::class,
        RegisterFacades::class,
        RegisterProviders::class,
        BootProviders::class,
    ];

HasSecret Eloquent Trait Usage

Add use trait to module

<?php

namespace App\Models;

use LaravelVault\Models\Traits\HasSecret;

class User extends Authenticatable
{
    use HasSecret;
    
    public function getSecretKeyAttribute(): string
    {
        return "{$this->id}";
    }


    /**
     * @return string
     */
    public function getSecretPrefix(): string
    {
        return "users/user_{$this->id}";
    }
}

Store the secret to User's model

use App\Models\User;


$user = User::find(1);

$user->secret = ['token' => 'secret_token_to_store']; // Stored on vault /secrets/users/user_1/1 

\Log::info('User\'s secret', $user->secret); // Will log : User\'s secret: ['token' => 'secret_token_to_store']   

Performance

Under investigation ))

TODO

  • Tests implementation
  • Refactor the VaultClient to separate the methods by entrypoints to simplify the project development

License

The MIT License (MIT). Please see License File for more information.

polokij/laravel-vault-env 适用场景与选型建议

polokij/laravel-vault-env 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 4.74k 次下载、GitHub Stars 达 4, 最近一次更新时间为 2023 年 10 月 19 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「dynamic」 「laravel」 「multi-tenant」 「env」 「bootstrapper」 「api client」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 polokij/laravel-vault-env 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 polokij/laravel-vault-env 我们能提供哪些服务?
定制开发 / 二次开发

基于 polokij/laravel-vault-env 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 4.74k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 4
  • 点击次数: 21
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 4
  • Watchers: 1
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-10-19