security
Secrets Management
Secrets include database passwords, API tokens, encryption keys, signing keys, and private repository credentials. They should be injected at runtime, scoped narrowly, rotated, and kept out of source control and logs.
Core Controls
- Read secrets from environment variables or an approved secret manager.
- Fail clearly when a required secret is missing without printing the secret value.
- Use separate credentials for development, testing, staging, and production.
- Rotate compromised or long-lived credentials and document ownership.
- Prevent secrets entering logs, exception traces, analytics, and support screenshots.
Load Required Secrets Deliberately
<?php
declare(strict_types=1);
function requiredSecret(string $name, array $environment): string
{
$value = $environment[$name] ?? null;
if (!is_string($value) || trim($value) === '') {
throw new RuntimeException("Required secret {$name} is missing.");
}
return $value;
}
echo strlen(requiredSecret('PAYMENT_API_KEY', ['PAYMENT_API_KEY' => 'local-test-key'])) . PHP_EOL;
// Prints:
// 14
The error names the missing configuration key, not its value.
Separate Environments And Privileges
Development, CI, staging, and production should use different credentials. Scope each credential to the minimum service access it needs. A compromised reporting token should not also administer the payment account.
Rotate And Redact
Know who owns each secret, where it is stored, how it is rotated, and which systems must reload after rotation.
Redact secrets from logs, traces, debug pages, analytics, and support screenshots. Review HTTP-client logging carefully because authorization headers and request bodies often contain credentials.
In Application Work
A .env file can be useful locally but is not a reason to commit production secrets. Review deployment configuration and CI variables as part of the application boundary.
What To Check
Before moving on, make sure you can load required secrets without leaking values, separate environments, apply least privilege, rotate credentials, and identify common log-leak paths.
Practice
Practice: Load A Required Secret
Requirements
- Read a named runtime secret.
- Reject missing or empty values.
- Avoid including the secret in errors.
- Describe environment-specific credentials and rotation.
Show solution
Review Points
- Read secrets from environment variables or an approved secret manager.
- Fail clearly when a required secret is missing without printing the secret value.
- Use separate credentials for development, testing, staging, and production.
- Rotate compromised or long-lived credentials and document ownership.
- Prevent secrets entering logs, exception traces, analytics, and support screenshots.