Skip to content

Secrets Management ​

The secrets module provides a unified interface for retrieving sensitive values (credentials, API keys, tokens) from external backends and injecting them into the framework configuration at runtime. This keeps secrets out of source control and .env files in shared environments.


What It Does ​

  • Resolves secrets from multiple provider backends (AWS, Vault, OpenBao, GitLab, Azure, env-file)
  • Injects fetched secrets into FrameworkConfig via dot-notation key mappings
  • Caches all fetched secrets for the entire test runner invocation
  • Enforces configurable fetch timeouts per provider
  • Falls back to local .env file provider when no external backend is configured

Architecture ​

SecretsManager (orchestrator)
├── Registers one or more SecretsProvider implementations
├── Resolves which provider to use from config
├── Fetches secrets with timeout enforcement
├── Caches results (singleton per test run)
└── Injects values into FrameworkConfig via keyMappings

Providers:
├── aws          — AWS Secrets Manager
├── vault        — HashiCorp Vault (KV v1/v2)
├── openbao      — OpenBao (KV v1/v2), shares the Vault implementation
├── gitlab       — GitLab CI/CD Variables API
├── azure        — Azure Key Vault
└── env-file     — Local .env file fallback

Configuration ​

environments.json ​

json
{
  "environments": {
    "dev": {
      "database": {
        "type": "postgresql",
        "host": "db.example.com",
        "port": 5432,
        "database": "myapp",
        "username": "",
        "password": ""
      },
      "secrets": {
        "provider": "aws",
        "options": {
          "region": "us-east-1",
          "secretPrefix": "myapp/dev/"
        },
        "keyMappings": {
          "db-username": "database.username",
          "db-password": "database.password",
          "api-key": "openapi.baseUrl"
        },
        "timeout": 10000
      }
    }
  }
}

playwright.config.ts ​

typescript
import { defineConfig } from '@playwright/test';

export default defineConfig({
  projects: [
    {
      name: 'integration',
      testMatch: '**/integration/**/*.spec.ts',
      use: {
        secrets: {
          provider: 'vault',
          options: {
            url: 'https://vault.example.com',
            mountPath: 'secret/data/playwright',
          },
          keyMappings: {
            'db-password': 'database.password',
            'redis-password': 'redis.password',
          },
          timeout: 15000,
        },
      },
    },
  ],
});

Configuration Options ​

OptionTypeDefaultDescription
providerstring—Provider backend name: aws, vault, openbao, gitlab, azure, env-file
optionsobject—Provider-specific options (see each provider below)
keyMappingsRecord<string, string>—Maps secret key → config field path (dot-notation)
timeoutnumber10000Fetch timeout in ms for all secret operations

Key Mappings ​

Key mappings define which secrets to fetch and where to inject them in the framework config. The key is the secret identifier in the backend, and the value is the dot-notation path in FrameworkConfig.

json
{
  "keyMappings": {
    "db-password": "database.password",
    "db-username": "database.username",
    "kafka-sasl-password": "kafka.sasl.password",
    "redis-auth": "redis.password",
    "api-token": "graphql.authToken"
  }
}

The target field must exist in the config object. If the path is invalid, a SecretsError with operation mapping is thrown.


Providers ​

AWS Secrets Manager ​

Retrieves secrets from AWS Secrets Manager using the AWS SDK.

Prerequisites ​

bash
npm install @aws-sdk/client-secrets-manager

Authentication ​

Uses the standard AWS credential chain (environment variables, shared credentials file, IAM role, etc.):

MethodVariables
EnvironmentAWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN
Shared credentials~/.aws/credentials with profile
IAM RoleAutomatic on EC2/ECS/Lambda
SSOaws sso login then use profile

Options ​

OptionTypeRequiredDescription
regionstringYesAWS region (e.g., us-east-1, eu-west-1)
secretPrefixstringNoPrefix prepended to all secret keys when fetching

Configuration Example ​

json
{
  "secrets": {
    "provider": "aws",
    "options": {
      "region": "us-east-1",
      "secretPrefix": "myapp/prod/"
    },
    "keyMappings": {
      "db-credentials": "database.password"
    }
  }
}

With secretPrefix: "myapp/prod/", a key mapping of "db-credentials" fetches the secret named myapp/prod/db-credentials from AWS.

Notes ​

  • Only string secrets are supported (binary secrets throw an error)
  • Secrets are fetched individually (no native batch API for arbitrary names)
  • The SDK is loaded dynamically — the provider throws a clear error if the package is missing

HashiCorp Vault ​

Retrieves secrets from HashiCorp Vault via the HTTP API. Supports KV v1 and KV v2 secrets engines.

Prerequisites ​

A running Vault instance accessible over HTTPS. No additional npm packages required (uses native fetch, or node:https when TLS options are set).

Authentication ​

MethodConfigurationEnvironment Variables
Tokenoptions.tokenVAULT_TOKEN
AppRoleoptions.roleId + options.secretIdVAULT_ROLE_ID + VAULT_SECRET_ID
KubernetesauthMethod: "kubernetes" + role (JWT read from the pod's service-account token)VAULT_AUTH_METHOD, VAULT_AUTH_ROLE, VAULT_JWT_PATH
JWT / OIDCrole + jwt or jwtPathVAULT_AUTH_ROLE, VAULT_JWT / VAULT_JWT_PATH

When authMethod is omitted it is inferred: a token wins, then AppRole (role_id + secret_id), then JWT (if a JWT or JWT path is set). Kubernetes must be selected explicitly. Auth methods mounted somewhere other than their default path (approle, kubernetes, jwt) need authMount.

AppRole, Kubernetes or JWT are recommended for CI/CD pipelines. Token-based auth is suitable for local development.

Options ​

Every option except kvVersion's default can also come from an environment variable; explicit options always win.

OptionTypeRequiredEnv fallbackDescription
urlstringYesVAULT_ADDRServer URL (e.g., https://vault.example.com)
mountPathstringYesVAULT_MOUNT_PATHPath prefix after /v1/. For KV v2 include data (e.g., secret/data/playwright)
kvVersion1 | 2NoVAULT_KV_VERSIONKV secrets engine version (default: 2)
namespacestringNoVAULT_NAMESPACENamespace, sent as X-Vault-Namespace
authMethodtoken | approle | kubernetes | jwtNoVAULT_AUTH_METHODAuth method (inferred when omitted)
authMountstringNoVAULT_AUTH_MOUNTAuth mount path, if not the default
tokenstringNoVAULT_TOKENClient token
roleIdstringNoVAULT_ROLE_IDAppRole role_id
secretIdstringNoVAULT_SECRET_IDAppRole secret_id
rolestringNoVAULT_AUTH_ROLERole for Kubernetes / JWT login
jwtstringNoVAULT_JWTJWT for Kubernetes / JWT login
jwtPathstringNoVAULT_JWT_PATHFile holding the JWT (Kubernetes default: /var/run/secrets/kubernetes.io/serviceaccount/token)
caCertstringNoVAULT_CACERTPEM CA bundle file used to verify the server
caPathstringNoVAULT_CAPATHDirectory of PEM CA certificates (ignored if caCert is set)
clientCertstringNoVAULT_CLIENT_CERTPEM client certificate for mutual TLS
clientKeystringNoVAULT_CLIENT_KEYUnencrypted PEM client key for mutual TLS
tlsServerNamestringNoVAULT_TLS_SERVER_NAMESNI server name
skipVerifybooleanNoVAULT_SKIP_VERIFYDisable certificate verification (local only, never in shared environments)

Configuration Example ​

json
{
  "secrets": {
    "provider": "vault",
    "options": {
      "url": "https://vault.example.com",
      "mountPath": "secret/data/playwright",
      "namespace": "admin/team-qa",
      "kvVersion": 2
    },
    "keyMappings": {
      "db-password": "database.password",
      "redis-password": "redis.password"
    }
  }
}

Secret Resolution Logic ​

Each key is appended to mountPath (nested keys such as team/db-password keep their slashes). The provider then looks for the value in this order:

  1. A value field in the secret data
  2. A field matching the key name
  3. The first value in the data object

Notes ​

  • Supports namespaces via the X-Vault-Namespace header
  • Login (AppRole, Kubernetes, JWT) is performed lazily on first secret fetch, once per provider instance; concurrent fetches share the same login
  • The token is cached for the lifetime of the provider instance (it is not renewed)
  • Tokens, secret_ids, JWTs and client keys are never included in SecretsError details, and are replaced with [REDACTED] if the server echoes them back

OpenBao ​

Retrieves secrets from OpenBao, the Linux Foundation's open-source fork of HashiCorp Vault.

OpenBao's HTTP API is wire-compatible with Vault's for everything this provider uses: /v1 KV v1/v2 reads, the X-Vault-Token and X-Vault-Namespace headers, and the AppRole, Kubernetes and JWT login endpoints. The openbao provider therefore shares the Vault implementation, and every option, auth method, TLS setting and note in the HashiCorp Vault section applies unchanged. Only the provider name and the environment variables differ.

Environment Variables ​

Each option falls back to environment variables in this order, highest precedence first:

PW_OPENBAO_<NAME>  →  BAO_<NAME>  →  VAULT_<NAME>

The framework's own PW_OPENBAO_* variables win over the bao CLI's BAO_* variables, which win over the VAULT_* names that OpenBao also accepts. Explicit options in environments.json or playwright.config.ts always win over all of them.

OptionEnvironment variables
urlPW_OPENBAO_ADDR, BAO_ADDR, VAULT_ADDR
tokenPW_OPENBAO_TOKEN, BAO_TOKEN, VAULT_TOKEN
namespacePW_OPENBAO_NAMESPACE, BAO_NAMESPACE, VAULT_NAMESPACE
mountPathPW_OPENBAO_MOUNT_PATH, BAO_MOUNT_PATH, VAULT_MOUNT_PATH
kvVersionPW_OPENBAO_KV_VERSION, BAO_KV_VERSION, VAULT_KV_VERSION
authMethod / authMountPW_OPENBAO_AUTH_METHOD, PW_OPENBAO_AUTH_MOUNT (+ BAO_* / VAULT_*)
roleId / secretIdPW_OPENBAO_ROLE_ID, PW_OPENBAO_SECRET_ID (+ BAO_* / VAULT_*)
role / jwt / jwtPathPW_OPENBAO_AUTH_ROLE, PW_OPENBAO_JWT, PW_OPENBAO_JWT_PATH (+ BAO_* / VAULT_*)
caCert / caPathPW_OPENBAO_CACERT, PW_OPENBAO_CAPATH, BAO_CACERT, BAO_CAPATH (+ VAULT_*)
clientCert / clientKeyPW_OPENBAO_CLIENT_CERT, PW_OPENBAO_CLIENT_KEY, BAO_CLIENT_CERT, BAO_CLIENT_KEY (+ VAULT_*)
tlsServerNamePW_OPENBAO_TLS_SERVER_NAME, BAO_TLS_SERVER_NAME, VAULT_TLS_SERVER_NAME
skipVerifyPW_OPENBAO_SKIP_VERIFY, BAO_SKIP_VERIFY, VAULT_SKIP_VERIFY

Because the server URL can come from BAO_ADDR, url is optional for openbao; the provider raises a SecretsError naming the variables above if no URL or mount path is found.

Configuration Example ​

json
{
  "secrets": {
    "provider": "openbao",
    "options": {
      "url": "https://bao.example.com",
      "mountPath": "secret/data/playwright",
      "namespace": "team-qa"
    },
    "keyMappings": {
      "db-password": "database.password",
      "redis-password": "redis.password"
    }
  }
}

With BAO_ADDR and BAO_TOKEN already exported (as for the bao CLI), only mountPath needs to be in options.

Kubernetes Example ​

json
{
  "secrets": {
    "provider": "openbao",
    "options": {
      "url": "https://bao.internal:8200",
      "mountPath": "secret/data/playwright",
      "authMethod": "kubernetes",
      "role": "playwright-ci",
      "caCert": "/etc/openbao/ca.pem"
    },
    "keyMappings": { "db-password": "database.password" }
  }
}

Notes ​

  • mountPath is the full path prefix after /v1/, so KV v2 needs the data segment (secret/data/...), as the bao kv CLI adds for you. A KV v2 response without data.data raises a SecretsError that points at mountPath
  • Namespaces are sent with the X-Vault-Namespace header, which OpenBao uses unchanged
  • OpenBao does not guarantee backwards compatibility of its API yet, even under /v1; pin the server version in shared test environments

GitLab CI/CD Variables ​

Retrieves secrets from GitLab project CI/CD variables via the GitLab REST API.

Prerequisites ​

  • A GitLab project with CI/CD variables configured
  • A private token or CI_JOB_TOKEN (automatically available in GitLab CI pipelines)

Authentication ​

MethodConfigurationEnvironment Variables
Private Tokenoptions.token—
Job Token—CI_JOB_TOKEN (auto-set in GitLab CI)

In GitLab CI pipelines, CI_JOB_TOKEN is automatically available and used as the fallback.

Options ​

OptionTypeRequiredDescription
projectIdstringYesGitLab project ID (numeric) or URL-encoded path
apiUrlstringYesGitLab API base URL (e.g., https://gitlab.com/api/v4)
tokenstringNoPrivate token. Falls back to CI_JOB_TOKEN env var

Configuration Example ​

json
{
  "secrets": {
    "provider": "gitlab",
    "options": {
      "projectId": "12345678",
      "apiUrl": "https://gitlab.com/api/v4",
      "token": ""
    },
    "keyMappings": {
      "DB_PASSWORD": "database.password",
      "REDIS_PASSWORD": "redis.password"
    }
  }
}

Notes ​

  • Secret keys must match the exact CI/CD variable key name in GitLab
  • Variables are fetched individually via the GitLab API
  • Protected and masked variables are supported
  • For self-hosted GitLab, update apiUrl to your instance URL

Azure Key Vault ​

Retrieves secrets from Azure Key Vault using the Azure SDK with DefaultAzureCredential.

Prerequisites ​

bash
npm install @azure/keyvault-secrets @azure/identity

Authentication ​

Uses DefaultAzureCredential from @azure/identity, which tries these methods in order:

MethodEnvironment Variables
EnvironmentAZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET
Managed IdentityAutomatic on Azure VMs, App Service, Functions
Azure CLIaz login (local development)
Visual Studio CodeAzure Account extension

Options ​

OptionTypeRequiredDescription
vaultUrlstringYesKey Vault URL (e.g., https://my-vault.vault.azure.net)

Configuration Example ​

json
{
  "secrets": {
    "provider": "azure",
    "options": {
      "vaultUrl": "https://my-vault.vault.azure.net"
    },
    "keyMappings": {
      "db-password": "database.password",
      "api-key": "openapi.baseUrl"
    }
  }
}

Notes ​

  • Only string secrets are supported (empty values throw an error)
  • The SDK is loaded dynamically — the provider throws a clear error if packages are missing
  • Secret names in Azure Key Vault use hyphens (not underscores): my-secret-name

Env File (Local Fallback) ​

Reads secrets from local .env.{environment} files. This is the default provider when no external backend is configured. Intended for local development only.

Prerequisites ​

None — uses the built-in EnvLoader.

Options ​

OptionTypeRequiredDescription
projectRootstringNoDirectory containing .env files (default: process.cwd())
environmentstringNoEnvironment name to load (default: local)

Configuration Example ​

json
{
  "secrets": {
    "provider": "env-file",
    "options": {
      "environment": "dev"
    },
    "keyMappings": {
      "PW_DB_PASSWORD": "database.password",
      "PW_REDIS_PASSWORD": "redis.password"
    }
  }
}

This reads from .env.dev and maps the specified keys into the framework config.

.env.dev Example ​

dotenv
PW_DB_PASSWORD=my-local-password
PW_REDIS_PASSWORD=redis-secret
PW_API_KEY=sk-test-12345

Notes ​

  • The env file is loaded once and cached for the test run
  • Keys must exist in the file — missing keys throw a SecretsError
  • This provider is automatically used when no other provider is configured

Programmatic Usage ​

You can use the SecretsManager directly in custom fixtures or setup scripts:

typescript
import { SecretsManager, AwsSecretsProvider } from '@inluxc/propmaster';

const manager = new SecretsManager();

// Register a provider
manager.registerProvider(new AwsSecretsProvider({ region: 'us-east-1' }));

// Fetch a single secret
const password = await manager.getSecret('db-password', 'aws');

// Fetch multiple secrets
const secrets = await manager.getSecrets(
  ['db-password', 'api-key', 'redis-auth'],
  'aws',
  15000 // timeout in ms
);

// Resolve and inject into config
const resolvedConfig = await manager.resolve(frameworkConfig);

Error Handling ​

All secrets errors use the SecretsError class with structured context:

OperationWhen
resolveProvider not registered or not found
fetchSecret retrieval failed (network, auth, missing key)
timeoutFetch exceeded the configured timeout
mappingKey mapping path is invalid (field doesn't exist in config)
typescript
// Provider not found:
// SecretsError: aws/resolve — reason: Provider "aws" is not registered

// Fetch failure:
// SecretsError: vault/fetch [db-password] — reason: API returned 403: permission denied

// Timeout:
// SecretsError: aws/timeout [db-password] — timeoutMs: 10000

// Invalid mapping:
// SecretsError: aws/mapping [db-password] — invalidField: database.nonexistent, reason: Field "nonexistent" does not exist

Provider Comparison ​

ProviderAuth MethodBest ForDependencies
awsIAM / env credentialsAWS-hosted infrastructure@aws-sdk/client-secrets-manager
vaultToken / AppRole / Kubernetes / JWTMulti-cloud, on-premNone (native fetch)
openbaoToken / AppRole / Kubernetes / JWTOpen-source Vault alternative, on-premNone (native fetch)
gitlabPrivate token / Job tokenGitLab CI/CD pipelinesNone (native fetch)
azureDefaultAzureCredentialAzure-hosted infrastructure@azure/keyvault-secrets, @azure/identity
env-fileFile systemLocal developmentNone (built-in)

EnvironmentProviderNotes
Localenv-fileUse .env.local with dummy/dev credentials
CI/CD (GitLab)gitlabLeverages CI_JOB_TOKEN automatically
CI/CD (GitHub)env-file, vault or openbaoMap GitHub secrets to env vars, or use Vault/OpenBao JWT auth with the GitHub OIDC token
Staging/Prod (AWS)awsUse IAM roles for zero-config auth
Staging/Prod (Azure)azureUse Managed Identity for zero-config auth
Multi-cloudvault or openbaoCentral secrets management across providers

Security Best Practices ​

  1. Never commit secrets — Use .gitignore to exclude .env.* files (already configured in this template)
  2. Use key mappings — Let the framework inject secrets rather than reading them in test code
  3. Prefer IAM/Managed Identity — Avoid long-lived tokens when running in cloud environments
  4. Set timeouts — Prevent test hangs if a secrets backend is unreachable
  5. Use secret prefixes — Namespace secrets per application/environment (e.g., myapp/prod/db-password)
  6. Rotate regularly — The caching layer means secrets are fetched once per test run, so rotations take effect on next run
  7. Limit scope — Use protected/masked variables in GitLab, or scoped policies in Vault/OpenBao

Custom Provider ​

You can implement the SecretsProvider interface to add support for any backend:

typescript
import { SecretsProvider } from '@inluxc/propmaster';

export class MyCustomProvider implements SecretsProvider {
  readonly name = 'my-provider';

  async getSecret(key: string): Promise<string> {
    // Fetch from your backend
    const value = await myBackend.fetch(key);
    return value;
  }

  async getSecrets(keys: string[]): Promise<Map<string, string>> {
    const results = new Map<string, string>();
    for (const key of keys) {
      results.set(key, await this.getSecret(key));
    }
    return results;
  }
}

Register it with the SecretsManager:

typescript
import { SecretsManager } from '@inluxc/propmaster';
import { MyCustomProvider } from './my-custom-provider';

const manager = new SecretsManager();
manager.registerProvider(new MyCustomProvider());

Released under the MIT License.