Bd security

From Lonsdale201/wp-agent-skills · View interactive version

Bd security is an AI agent skill from the GitHub repository Lonsdale201/wp-agent-skills. Apply better-data's security discipline when touching Secret, EncryptionEngine, #[Sensitive], #[Encrypted], MetaKeyRegistry::register, RequestSource guards, or user_pass handling. Loud-over-silent — missing key throws, tampered ciphertext throws, unknown strict-whitelist field throws, colliding rout

How to use this skill

Skill file

better-data: Security-sensitive changes

For library maintainers touching anything in better-data's security perimeter — Secret, EncryptionEngine, #[Sensitive], #[Encrypted], RequestSource guards, password handling. Mistakes in this perimeter aren't bugs that show up in tests; they're regressions that ship plaintext to disk or leak credentials in logs.

Misconception this skill corrects

"I'll add a debug-mode that logs the encrypted value's plaintext when developer mode is on — it's only for development."

Don't. The security-feature-with-bypass is the worst outcome — caller assumes redaction is universal, log infrastructure picks up the "debug" path in production by accident, plaintext lands in CloudWatch / Sentry / wp-debug.log forever. The discipline is no-bypass: Secret's __toString returns '***' (src/Secret.php:84-87), jsonSerialize returns '***' (src/Secret.php:89-92), __debugInfo (controls var_dump / print_r) returns ['value' => '***'] (src/Secret.php:99-103), __serialize THROWS SecretSerializationException (src/Secret.php:105-109).

The throwing __serialize is deliberate — a caller serialized a Secret has already made a security-relevant mistake. Relaxing it to redact instead would silently let the bug ship. The exception forces them to either ->reveal() explicitly (audit point) or rethink the flow.

Other AI-prone misconceptions:

When to use this skill

Trigger when ANY of the following is true:

Workflow

1. Threat model first (in the PR description or a code comment)

Write down explicitly:

The goal: a future contributor reads the comment and knows whether their proposed change preserves or breaks the model.

2. Loud over silent

Every degradation must throw. The catalog:

| Condition | Throws |

|---|---|

| Encryption key constant not defined | RuntimeException |

| decrypt called on garbage | DecryptionFailedException |

| decrypt called with tampered ciphertext (GCM auth tag mismatch) | DecryptionFailedException |

| Secret __serialize invoked | SecretSerializationException |

| MetaKeyRegistry::register collision (one key, two DTOs) | RuntimeException |

| RequestSource::noCollision finds an unexpected route-owned field in the body | RequestParamCollisionException |

| strict mode + unknown DTO field in incoming data | UnknownFieldException |

If you add a security feature, add a corresponding throw. Don't ship a flag that converts the throw into a warning.

3. Symmetric end-to-end

Every encrypt has a matching decrypt, every redact has a matching reveal. Lookup table:

| Write side | Read side |

|---|---|

| SinkProjection::prepareValue encrypts when #[Encrypted] | AttributeDrivenHydrator decrypts when #[Encrypted] |

| Presenter::toArray redacts Secret / #[Sensitive] | Explicit $secret->reveal() inside compute() closure |

| OptionSink::projectForStorage encrypts | OptionSource decrypts |

| __serialize throws | __unserialize throws — symmetric blockage |

If you add an encrypt path, you MUST add the matching decrypt path in the same PR. The reverse is also true. Asymmetry is a security regression because it preserves DATA but loses CONFIDENTIALITY.

4. Never cache the raw key

The pattern at src/Encryption/EncryptionEngine.php:53-54 is:

private const CONST_PRIMARY = 'BETTER_DATA_ENCRYPTION_KEY';
private const CONST_PREVIOUS = 'BETTER_DATA_ENCRYPTION_KEY_PREVIOUS';

Each encrypt / decrypt call reads the constant fresh. NO static property holds the resolved key. Reason: rotation. The runbook is:

  1. Define BETTER_DATA_ENCRYPTION_KEY with the new key.
  2. Define BETTER_DATA_ENCRYPTION_KEY_PREVIOUS with the old key.
  3. Wait for the rotation period (lazy migration: every read decrypts under the old key, every write re-encrypts under the new).
  4. Eventually undefine BETTER_DATA_ENCRYPTION_KEY_PREVIOUS.

If you cached the key in a static, step 1 doesn't take effect until the PHP process restarts — which can be hours after the constant changes. Don't cache.

5. Constant-time comparison

Any string comparison involving secret material:

// WRONG — timing oracle
if ($candidate === $stored) { /* ... */ }

// RIGHT
if (\hash_equals($stored, $candidate)) { /* ... */ }

Secret::equals is the canonical example (src/Secret.php:78-82). For password verification, use password_verify (which is constant-time by design).

6. Unit-test contract for security changes

Three probes minimum:

public function test_tampering_throws(): void
{
    $ciphertext = EncryptionEngine::encrypt('hello');
    // Flip one byte after the bd:v1: prefix
    $tampered = substr($ciphertext, 0, 8) . 'X' . substr($ciphertext, 9);

    $this->expectException(DecryptionFailedException::class);
    EncryptionEngine::decrypt($tampered, 'field');
}

public function test_missing_key_throws(): void
{
    // ensure the constant is undefined for this test
    $this->expectException(RuntimeException::class);
    EncryptionEngine::encrypt('hello');
}

public function test_secret_does_not_leak_via_dump_or_json_or_serialize(): void
{
    $secret = new Secret('sk_live_supersecret');

    $this->assertSame('***', (string) $secret);
    $this->assertSame('"***"', \json_encode($secret));
    $this->assertStringNotContainsString('sk_live', \print_r($secret, true));
    $this->assertStringNotContainsString('sk_live', \var_export($secret, true));

    $this->expectException(SecretSerializationException::class);
    \serialize($secret);
}

Add a leak probe for any new property / class that wraps secret material. The probe should print_r / var_dump / json_encode / serialize and assert the raw value isn't present.

7. Stress scenario for the WP boundary

The companion plugin's stress suite covers live-WP behavior:

wp better-data stress --filter Secret

A FAIL finding here blocks the change. A NOTE is acceptable but documented.

8. Run the full check

vendor/bin/phpunit
vendor/bin/phpstan analyse --memory-limit=1G
vendor/bin/php-cs-fixer fix
wp better-data stress

Critical rules

Common mistakes

// WRONG — debug-mode plaintext logging
public function decrypt(string $ciphertext, string $field): string
{
    $plaintext = self::actualDecrypt($ciphertext);
    if (\defined('BETTER_DATA_DEBUG') && BETTER_DATA_DEBUG) {
        \error_log("Decrypted {$field}: {$plaintext}");  // INSECURE — plaintext to log
    }
    return $plaintext;
}

// RIGHT — no plaintext-leaking branches at all

// WRONG — silent failure on decrypt
public function decrypt(string $ciphertext, string $field): ?string
{
    try {
        return self::actualDecrypt($ciphertext);
    } catch (\Throwable) {
        return null;  // BUG — caller can't tell garbage data from missing data
    }
}

// RIGHT — let it throw
public function decrypt(string $ciphertext, string $field): string
{
    return self::actualDecrypt($ciphertext);
    // throws DecryptionFailedException on tampered / wrong-key / garbage
}

// WRONG — caching the key
class EncryptionEngine
{
    private static ?string $cachedKey = null;

    private static function getKey(): string
    {
        return self::$cachedKey ??= \constant(self::CONST_PRIMARY);  // BUG — rotation broken
    }
}

// RIGHT — fresh read every call
private static function getKey(): string
{
    return \constant(self::CONST_PRIMARY);  // O(1) constant lookup; not worth caching
}

// WRONG — equality with ===
if ($candidate === $secret->reveal()) {  // INSECURE — timing oracle
    grant_access();
}

// RIGHT
if ($secret->equals($candidate)) {  // hash_equals under the hood
    grant_access();
}

// WRONG — relaxing __serialize to redact
public function __serialize(): array
{
    return ['value' => '***'];  // BUG — silent: caller's serialized blob looks "fine"
}

// RIGHT — throw, force explicit reveal at the call site
public function __serialize(): array
{
    throw SecretSerializationException::forSerialize();
}

// WRONG — encrypt-only
class SinkProjection {
    static function prepareValue(...): mixed {
        if ($encrypted) return EncryptionEngine::encrypt($value);
        return $value;
    }
}
class AttributeDrivenHydrator {
    static function hydrate(...): DataObject {
        // forgot to call EncryptionEngine::decrypt
        return $dto;
    }
}
// Result: stored ciphertext, hydrated ciphertext-as-string. Looks like garbage on read.

// RIGHT — symmetric pair lands in the same PR

Cross-references

What this skill does NOT cover

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.