diff --git a/plugins/data-machine/docs/core-system/oauth-handlers.md b/plugins/data-machine/docs/core-system/oauth-handlers.md index 313a3ad562..eb60fc879b 100644 --- a/plugins/data-machine/docs/core-system/oauth-handlers.md +++ b/plugins/data-machine/docs/core-system/oauth-handlers.md @@ -307,8 +307,10 @@ not someone "calling" the agent right now). Existing installs need no action. The legacy site-wide flow (`get_account()` / `save_account()` without a context arg) continues to -work unchanged. Tokens stored before the encryption-at-rest feature landed -in v0.88.0 are lazy-migrated on next save. Per-user storage activates only +work unchanged. Secret fields must be stored as fingerprinted +`dm:enc:v1:` envelopes; a plaintext or fingerprint-less value reads as null +with a decryption error, and the wake briefing credential audit reports it. +Re-authenticate the connection to store it encrypted. Per-user storage activates only when callers opt in via `get_account_for_user( $user_id )` or by setting `calling_user_id > 0` in the payload. diff --git a/plugins/data-machine/docs/development/1-0-baseline.md b/plugins/data-machine/docs/development/1-0-baseline.md index 66b9998a18..4b937a6214 100644 --- a/plugins/data-machine/docs/development/1-0-baseline.md +++ b/plugins/data-machine/docs/development/1-0-baseline.md @@ -24,7 +24,7 @@ Compatibility is retained only for a named current external or persisted contrac The following grep-visible paths are intentionally retained and are not pre-1.0 API compatibility promises: - **Current schema/bootstrap:** repository `create_table()` methods create missing tables via `dbDelta`. They must not `ALTER` existing tables, `SELECT`/`UPDATE` existing rows, or run chat-network convergence on web `init`. Operator repairs live in named CLI commands. -- **Concrete persisted production data:** compound job statuses, generation-less recurring actions, descriptor-less in-flight claims, pending-action numeric owner columns, installed bundle artifact config mirrors (including the concrete singular `handler_config` runtime overlay consumed by `AgentBundleRuntimeDrift` and `AgentBundleArtifactPayloads`), plaintext OAuth secrets awaiting opportunistic encryption, and existing memory directories remain readable so current queued work and operator data survive the production upgrade. +- **Concrete persisted production data:** compound job statuses, generation-less recurring actions, descriptor-less in-flight claims, pending-action numeric owner columns, installed bundle artifact config mirrors (including the concrete singular `handler_config` runtime overlay consumed by `AgentBundleRuntimeDrift` and `AgentBundleArtifactPayloads`), and existing memory directories remain readable so current queued work and operator data survive the production upgrade. - **Shipped external edges:** stable `datamachine/v1` REST error codes, the `datamachine_tools` and pending-action handler extension filters, OAuth implicit-flow support, and both possible PSR-16 namespaces are presentation, extension, or dependency boundaries rather than alternate internal models. - **Current pipeline delegation edge:** `ToolPolicyResolver` accepts top-level `runtime_tool_declarations` because the current pipeline policy consumer supplies run-scoped client declarations there. The namespaced client-context envelope remains supported for interactive runtime adapters. - **External/dependency edges:** Action Scheduler owns its schema compatibility hooks; WordPress owns the Abilities REST runner; Agents API owns the canonical pending-action ability and approval vocabulary. Data Machine keeps only the required adapters and verified dependency seams. diff --git a/plugins/data-machine/inc/Core/Bootstrap/HostIntegrationServiceProvider.php b/plugins/data-machine/inc/Core/Bootstrap/HostIntegrationServiceProvider.php index 78536bc693..7e69322086 100644 --- a/plugins/data-machine/inc/Core/Bootstrap/HostIntegrationServiceProvider.php +++ b/plugins/data-machine/inc/Core/Bootstrap/HostIntegrationServiceProvider.php @@ -19,6 +19,7 @@ use DataMachine\Core\Identity\AgentIdentityStoreAdapter; use DataMachine\Core\OAuth\HttpBasicAuthProvider; use DataMachine\Core\PluginSettings; +use DataMachine\Core\Steps\Fetch\Handlers\Email\EmailAuth; use DataMachine\Engine\AI\Actions\PendingActionStore; use DataMachine\Engine\AI\Actions\ResolvePendingActionAbility; use DataMachine\Engine\AI\AgentModeRegistry; @@ -114,6 +115,9 @@ public static function register_auth_encrypted_fields( array $fields, string $pr if ( HttpBasicAuthProvider::PROVIDER_SLUG === $provider_slug ) { $fields[] = 'password'; } + if ( EmailAuth::PROVIDER_SLUG === $provider_slug ) { + $fields = array_merge( $fields, EmailAuth::SECRET_FIELDS ); + } return $fields; } diff --git a/plugins/data-machine/inc/Core/OAuth/BaseAuthProvider.php b/plugins/data-machine/inc/Core/OAuth/BaseAuthProvider.php index 8b97e8d41f..8fc05f61b4 100644 --- a/plugins/data-machine/inc/Core/OAuth/BaseAuthProvider.php +++ b/plugins/data-machine/inc/Core/OAuth/BaseAuthProvider.php @@ -17,16 +17,15 @@ * The trailing key fingerprint (first 8 bytes of sha256(key), hex) records which * key generation encrypted the value. On read it is compared before decryption, * so a rotated auth salt is reported as a key mismatch instead of surfacing as a - * remote HTTP 401. Envelopes written before the fingerprint existed decrypt the - * same way they always did. + * remote HTTP 401. An envelope without the fingerprint is malformed. * * Decryption failure fails closed: the field is returned as null and the error * is exposed via get_last_decryption_error(). The encrypted envelope itself is * never returned to consumers, because emitting it has transmitted ciphertext * to remote services as if it were the secret. * - * Plaintext values without the envelope prefix are read as-is for backward - * compatibility. Values get encrypted opportunistically on next save. + * A non-empty encrypted field that does not carry the envelope prefix is not + * encrypted and fails closed the same way. * * @package DataMachine * @subpackage Core\OAuth @@ -520,8 +519,8 @@ public function get_account_for_policy_context( array $context = array() ): ?arr /** * Get OAuth configuration keys directly from options. * - * Automatically decrypts any encrypted fields. Plaintext legacy values - * pass through unchanged. + * Automatically decrypts any encrypted fields; unencrypted or undecryptable + * secret fields are withheld as null. * * @return array Configuration data or empty array */ @@ -1149,12 +1148,10 @@ public function get_last_decryption_error(): ?\WP_Error { * than asking an instance: key derivation is provider-independent — the * same wp_salt('auth') for all of them. * - * Envelopes written since the key fingerprint landed are settled by - * comparing that fingerprint, with no decryption attempted at all. Legacy - * envelopes carry no fingerprint, so those — and only those — are decided - * by a trial decryption. That keeps a diagnostic which runs on every wake - * from doing crypto work it does not need to do, while still reporting - * accurately on credentials stored before the fingerprint existed. + * Every envelope is settled by comparing its key fingerprint, with no + * decryption attempted. A secret field holding a value that is not an + * envelope, or an envelope without a valid fingerprint, is counted as + * undecryptable because reads fail closed on it. * * Reports counts and provider slugs only. No secret material, and no * envelope, is returned. @@ -1177,8 +1174,7 @@ public static function audit_stored_credentials(): array { return $result; } - $key = hash( 'sha256', wp_salt( 'auth' ) . 'datamachine-oauth', true ); - $fingerprint = self::fingerprint_for_key( $key ); + $fingerprint = self::fingerprint_for_key( hash( 'sha256', wp_salt( 'auth' ) . 'datamachine-oauth', true ) ); foreach ( $all_auth_data as $provider_slug => $provider_data ) { if ( ! is_array( $provider_data ) ) { @@ -1190,7 +1186,8 @@ public static function audit_stored_credentials(): array { } $undecryptable = 0; - self::count_undecryptable_values( $provider_data, $key, $fingerprint, $undecryptable ); + $secret_fields = array_fill_keys( self::audited_secret_fields( (string) $provider_slug ), true ); + self::count_undecryptable_values( $provider_data, '', $secret_fields, $fingerprint, $undecryptable ); if ( $undecryptable > 0 ) { $result['undecryptable_counts'][ (string) $provider_slug ] = $undecryptable; @@ -1224,50 +1221,55 @@ private static function provider_slot_holds_credentials( array $provider_data ): } /** - * Count envelopes the current key cannot open, walking nested auth data. + * Secret field names audited for a provider slot. * * @since 0.177.0 - * @param mixed $value Node in the stored auth structure. - * @param string $key Binary encryption key for the current salt. - * @param string $fingerprint Fingerprint of that key. - * @param int $count Running total, by reference. + * @param string $provider_slug Provider slug. + * @return array */ - private static function count_undecryptable_values( mixed $value, string $key, string $fingerprint, int &$count ): void { + private static function audited_secret_fields( string $provider_slug ): array { + $fields = self::ENCRYPTED_FIELDS; + if ( function_exists( 'apply_filters' ) ) { + $fields = apply_filters( 'datamachine_auth_encrypted_fields', $fields, $provider_slug ); + } + return array_map( 'strval', (array) $fields ); + } + + /** + * Count stored secrets the current key cannot open, walking nested auth data. + * + * An envelope counts when its fingerprint is missing, malformed, or belongs + * to another key. A non-empty secret field without the envelope prefix + * counts too: it is not encrypted, so reads withhold it. + * + * @since 0.177.0 + * @param mixed $value Node in the stored auth structure. + * @param string $field Key under which the node is stored. + * @param array $secret_fields Secret field names, as keys. + * @param string $fingerprint Fingerprint of the current key. + * @param int $count Running total, by reference. + */ + private static function count_undecryptable_values( mixed $value, string $field, array $secret_fields, string $fingerprint, int &$count ): void { if ( is_array( $value ) ) { - foreach ( $value as $child ) { - self::count_undecryptable_values( $child, $key, $fingerprint, $count ); + foreach ( $value as $child_field => $child ) { + self::count_undecryptable_values( $child, (string) $child_field, $secret_fields, $fingerprint, $count ); } return; } - if ( ! is_string( $value ) || ! str_starts_with( $value, self::ENCRYPTION_PREFIX ) ) { + if ( ! is_string( $value ) ) { return; } - $parts = explode( ':', substr( $value, strlen( self::ENCRYPTION_PREFIX ) ), 4 ); - - // Fingerprinted envelope: the fingerprint settles it without crypto. - if ( 4 === count( $parts ) ) { - if ( ! hash_equals( $fingerprint, strtolower( $parts[3] ) ) ) { + if ( ! str_starts_with( $value, self::ENCRYPTION_PREFIX ) ) { + if ( '' !== $value && isset( $secret_fields[ $field ] ) ) { ++$count; } return; } - // Legacy envelope with no fingerprint: a trial decryption is the only - // way to know, so it is confined to this branch. - if ( 3 !== count( $parts ) ) { - ++$count; - return; - } - - $iv = base64_decode( $parts[0], true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- Decoding a binary crypto envelope field. - $tag = base64_decode( $parts[1], true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- Decoding a binary crypto envelope field. - $ct = base64_decode( $parts[2], true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- Decoding a binary crypto envelope field. - - if ( false === $iv || false === $tag || false === $ct - || strlen( $tag ) !== self::AUTH_TAG_LENGTH - || false === openssl_decrypt( $ct, self::CIPHER_ALGO, $key, OPENSSL_RAW_DATA, $iv, $tag ) ) { + $parts = explode( ':', substr( $value, strlen( self::ENCRYPTION_PREFIX ) ), 4 ); + if ( 4 !== count( $parts ) || ! hash_equals( $fingerprint, strtolower( $parts[3] ) ) ) { ++$count; } } @@ -1331,41 +1333,48 @@ protected function encrypt_fields( array $data ): array { /** * Decrypt sensitive fields in a data array after retrieval. * - * Only attempts decryption on fields that carry the encryption envelope - * prefix. Plaintext values are returned unchanged for backward compatibility. - * - * Decryption failure fails closed: the field becomes null and the error is - * recorded for get_last_decryption_error(). The stored envelope is never - * returned as the field value. + * Every non-empty string in an encrypted field must carry the encryption + * envelope. A value without it is not encrypted and fails closed exactly + * like an envelope that cannot be decrypted: the field becomes null and the + * error is recorded for get_last_decryption_error(). The stored value is + * never returned as the field value. * * @since 0.88.0 - * @param array $data Stored data array (may contain encrypted or plaintext values). + * @param array $data Stored data array. * @return array Data with sensitive fields decrypted, or null where decryption failed. */ protected function decrypt_fields( array $data ): array { $this->last_decryption_error = null; foreach ( $this->get_encrypted_fields() as $field ) { - if ( isset( $data[ $field ] ) && is_string( $data[ $field ] ) ) { - if ( str_starts_with( $data[ $field ], self::ENCRYPTION_PREFIX ) ) { - $decrypted = $this->decrypt_value( $data[ $field ] ); - if ( null !== $decrypted ) { - $data[ $field ] = $decrypted; - } else { - /* - * Fail closed. Returning the envelope here has leaked - * ciphertext to remote services that read it as the - * secret itself. Null the field; the stored envelope - * stays in storage untouched for recovery. - */ - $data[ $field ] = null; - $this->record_decryption_error( - 'datamachine_auth_decrypt_failed', - __( 'A stored credential could not be decrypted and was withheld. Re-authenticate the affected connection to restore access.', 'data-machine' ) - ); - } - } - // else: plaintext legacy value — pass through unchanged. + if ( ! isset( $data[ $field ] ) || ! is_string( $data[ $field ] ) || '' === $data[ $field ] ) { + continue; + } + + if ( ! str_starts_with( $data[ $field ], self::ENCRYPTION_PREFIX ) ) { + $data[ $field ] = null; + $this->record_decryption_error( + 'datamachine_auth_decrypt_failed', + __( 'A stored credential is not encrypted and was withheld. Re-authenticate the affected connection to store it encrypted.', 'data-machine' ) + ); + continue; + } + + $decrypted = $this->decrypt_value( $data[ $field ] ); + if ( null !== $decrypted ) { + $data[ $field ] = $decrypted; + continue; } + + /* + * Fail closed. Returning the envelope here has leaked ciphertext + * to remote services that read it as the secret itself. Null the + * field; the stored envelope stays in storage untouched for recovery. + */ + $data[ $field ] = null; + $this->record_decryption_error( + 'datamachine_auth_decrypt_failed', + __( 'A stored credential could not be decrypted and was withheld. Re-authenticate the affected connection to restore access.', 'data-machine' ) + ); } return $data; } @@ -1409,9 +1418,9 @@ private function encrypt_value( string $plaintext ): ?string { /** * Decrypt a single value from the encryption envelope format. * - * Expects input in format: dm:enc:v1:{base64(iv)}:{base64(tag)}:{base64(ciphertext)}[:{key_fingerprint}] + * Expects input in format: dm:enc:v1:{base64(iv)}:{base64(tag)}:{base64(ciphertext)}:{key_fingerprint} * - * When the trailing key fingerprint is present it is compared before any + * Any other shape is malformed. The key fingerprint is compared before any * decryption is attempted, so a credential encrypted under a different key * generation fails fast with `datamachine_auth_key_mismatch` instead of a * wrong-key GCM failure that reads as remote authentication rejection. @@ -1430,35 +1439,22 @@ private function decrypt_value( string $envelope ): ?string { return null; } - // Strip prefix and split into iv:tag:ciphertext[:fingerprint]. + // Strip prefix and split into iv:tag:ciphertext:fingerprint. $payload = substr( $envelope, strlen( self::ENCRYPTION_PREFIX ) ); $parts = explode( ':', $payload, 4 ); - if ( 4 === count( $parts ) ) { - $fingerprint = strtolower( $parts[3] ); - if ( ! ctype_xdigit( $fingerprint ) || strlen( $fingerprint ) !== 2 * self::KEY_FINGERPRINT_LENGTH ) { - $this->log_encryption_error( 'Malformed encryption envelope: invalid key fingerprint' ); - $this->record_decryption_error( - 'datamachine_auth_decrypt_failed', - __( 'A stored credential envelope is malformed and cannot be decrypted.', 'data-machine' ) - ); - return null; - } - - if ( ! hash_equals( $this->key_fingerprint( $key ), $fingerprint ) ) { - $this->log_encryption_error( 'Key fingerprint mismatch: credential was encrypted under a different key generation' ); - $this->record_decryption_error( - 'datamachine_auth_key_mismatch', - __( 'A stored credential was encrypted under a different key — the site auth salt may have changed. Re-authenticate the affected connection to restore access.', 'data-machine' ) - ); - // Refuse before attempting decryption: no key under this - // generation can open the envelope, and trying leaks nothing. - return null; - } + if ( 4 !== count( $parts ) ) { + $this->log_encryption_error( 'Malformed encryption envelope: missing key fingerprint' ); + $this->record_decryption_error( + 'datamachine_auth_decrypt_failed', + __( 'A stored credential envelope is malformed and cannot be decrypted.', 'data-machine' ) + ); + return null; + } - array_pop( $parts ); - } elseif ( 3 !== count( $parts ) ) { - $this->log_encryption_error( 'Malformed encryption envelope: missing separator' ); + $fingerprint = strtolower( $parts[3] ); + if ( ! ctype_xdigit( $fingerprint ) || strlen( $fingerprint ) !== 2 * self::KEY_FINGERPRINT_LENGTH ) { + $this->log_encryption_error( 'Malformed encryption envelope: invalid key fingerprint' ); $this->record_decryption_error( 'datamachine_auth_decrypt_failed', __( 'A stored credential envelope is malformed and cannot be decrypted.', 'data-machine' ) @@ -1466,6 +1462,17 @@ private function decrypt_value( string $envelope ): ?string { return null; } + if ( ! hash_equals( $this->key_fingerprint( $key ), $fingerprint ) ) { + $this->log_encryption_error( 'Key fingerprint mismatch: credential was encrypted under a different key generation' ); + $this->record_decryption_error( + 'datamachine_auth_key_mismatch', + __( 'A stored credential was encrypted under a different key — the site auth salt may have changed. Re-authenticate the affected connection to restore access.', 'data-machine' ) + ); + // Refuse before attempting decryption: no key under this + // generation can open the envelope, and trying leaks nothing. + return null; + } + // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- Decoding binary crypto envelope fields, not obfuscation. $iv = base64_decode( $parts[0], true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- Decoding binary crypto envelope fields, not obfuscation. diff --git a/plugins/data-machine/inc/Core/OAuth/HttpBasicAuthProvider.php b/plugins/data-machine/inc/Core/OAuth/HttpBasicAuthProvider.php index 900c086f74..46229a0566 100644 --- a/plugins/data-machine/inc/Core/OAuth/HttpBasicAuthProvider.php +++ b/plugins/data-machine/inc/Core/OAuth/HttpBasicAuthProvider.php @@ -186,51 +186,26 @@ public function delete_account( string $account, array $context = array() ): boo } /** - * The stored account map, reading the pre-multi-account shape when that is what is there. - * - * Installs configured before this change hold a single flat credential alongside the account - * name it was given. Presenting it as a one-entry map means those installs keep resolving - * without a migration step, and the next save rewrites them into the map. + * The stored account map. * * @param array $context Optional principal context. * @param bool $decrypt Whether to decrypt secrets; false when reading for a re-save. * @return array> */ private function stored_accounts( array $context = array(), bool $decrypt = true ): array { + if ( $decrypt ) { + $this->undecryptable_accounts = array(); + $this->undecryptable_error = null; + } + $config = $this->get_config( $context ); $stored = $config['accounts'] ?? null; if ( ! is_array( $stored ) ) { - $legacy_account = trim( (string) ( $config['account'] ?? '' ) ); - if ( '' === $legacy_account || empty( $config['username'] ) ) { - return array(); - } - - // get_config() already decrypted the legacy top-level password. - $legacy = array( - 'username' => (string) $config['username'], - 'password' => (string) ( $config['password'] ?? '' ), - 'proxy_url' => trim( (string) ( $config['proxy_url'] ?? '' ) ), - ); - - if ( $decrypt ) { - $this->undecryptable_accounts = array(); - $this->undecryptable_error = null; - // decrypt_fields() nulls a password it cannot decrypt; the - // fail-closed sentinel distinguishes that from an empty one. - if ( array_key_exists( 'password', $config ) && null === $config['password'] ) { - $this->mark_undecryptable( $legacy_account ); - } - } - - return array( $legacy_account => $decrypt ? $legacy : $this->map_account_secrets( $legacy, true ) ); + return array(); } $accounts = array(); - if ( $decrypt ) { - $this->undecryptable_accounts = array(); - $this->undecryptable_error = null; - } foreach ( $stored as $name => $credential ) { if ( ! is_array( $credential ) ) { continue; @@ -241,7 +216,7 @@ private function stored_accounts( array $context = array(), bool $decrypt = true } $raw_secret = $credential['password'] ?? null; $mapped = $this->map_account_secrets( $credential, false ); - if ( is_string( $raw_secret ) && str_starts_with( $raw_secret, BaseAuthProvider::ENCRYPTION_PREFIX ) && array_key_exists( 'password', $mapped ) && null === $mapped['password'] ) { + if ( is_string( $raw_secret ) && '' !== $raw_secret && array_key_exists( 'password', $mapped ) && null === $mapped['password'] ) { $this->mark_undecryptable( (string) $name ); } $accounts[ (string) $name ] = $mapped; @@ -251,7 +226,7 @@ private function stored_accounts( array $context = array(), bool $decrypt = true } /** - * Record an account whose stored envelope failed to decrypt, keeping the + * Record an account whose stored secret failed to decrypt, keeping the * first specific error for surfacing through resolve_auth_ref(). */ private function mark_undecryptable( string $account ): void { diff --git a/plugins/data-machine/inc/Core/Steps/Fetch/Handlers/Email/EmailAuth.php b/plugins/data-machine/inc/Core/Steps/Fetch/Handlers/Email/EmailAuth.php index 302874ec3c..87c6e56897 100644 --- a/plugins/data-machine/inc/Core/Steps/Fetch/Handlers/Email/EmailAuth.php +++ b/plugins/data-machine/inc/Core/Steps/Fetch/Handlers/Email/EmailAuth.php @@ -22,8 +22,13 @@ class EmailAuth extends BaseAuthProvider { public const OPERATIONS = array( 'read', 'search', 'draft', 'send', 'reply', 'organize', 'delete', 'unsubscribe' ); + public const PROVIDER_SLUG = 'email_imap'; + + /** Mailbox secrets encrypted at rest, beyond the base list. */ + public const SECRET_FIELDS = array( 'imap_password', 'smtp_password' ); + public function __construct() { - parent::__construct( 'email_imap' ); + parent::__construct( self::PROVIDER_SLUG ); } /** @@ -86,7 +91,7 @@ public function is_authenticated(): bool { } protected function get_encrypted_fields(): array { - return array_values( array_unique( array_merge( parent::get_encrypted_fields(), array( 'imap_password', 'smtp_password' ) ) ) ); + return array_values( array_unique( array_merge( parent::get_encrypted_fields(), self::SECRET_FIELDS ) ) ); } public function strip_auth_config_secrets( array $handler_config ): array { diff --git a/plugins/data-machine/inc/Engine/AI/System/Tasks/WakeBriefingTask.php b/plugins/data-machine/inc/Engine/AI/System/Tasks/WakeBriefingTask.php index 58ce19f0a8..fb6543b00f 100644 --- a/plugins/data-machine/inc/Engine/AI/System/Tasks/WakeBriefingTask.php +++ b/plugins/data-machine/inc/Engine/AI/System/Tasks/WakeBriefingTask.php @@ -862,9 +862,9 @@ private function getActionSchedulerBloat(): string { * * Two distinct conditions, each at most one terse line: * - * 1. Undecryptable stored credentials: values carrying the encryption - * envelope that fail to decrypt under the current key — i.e. the key - * protecting them changed and they are unrecoverable as stored. One + * 1. Undecryptable stored credentials: envelopes encrypted under another + * key or missing the key fingerprint, and secret fields stored without + * encryption. Reads withhold all of them. One * grouped line naming providers and counts ONLY; no secret material, * ciphertext, or credential value ever appears in the output. * 2. AUTH_KEY/AUTH_SALT not defined in wp-config.php: core then keys @@ -873,7 +873,7 @@ private function getActionSchedulerBloat(): string { * shortly after first detection so a permanent condition does not * become permanent noise. * - * Cheap — one option read plus one bounded decrypt probe per stored + * Cheap — one option read and a fingerprint comparison per stored * envelope — and makes no outbound requests. Fail-soft: no lines when the * audit cannot run. * @@ -896,7 +896,7 @@ private function getCredentialSignals(): array { } $signals[] = sprintf( - '⚠ **Credentials** — %d stored credential(s) cannot be decrypted (%s); encryption key changed. Re-authenticate.', + '⚠ **Credentials** — %d stored credential(s) cannot be decrypted (%s); encryption key changed or value not encrypted. Re-authenticate.', array_sum( $failures ), implode( ', ', $parts ) ); diff --git a/plugins/data-machine/tests/Unit/Core/OAuth/BaseAuthProviderEncryptionTest.php b/plugins/data-machine/tests/Unit/Core/OAuth/BaseAuthProviderEncryptionTest.php index 36296eb1dd..97d2b4b492 100644 --- a/plugins/data-machine/tests/Unit/Core/OAuth/BaseAuthProviderEncryptionTest.php +++ b/plugins/data-machine/tests/Unit/Core/OAuth/BaseAuthProviderEncryptionTest.php @@ -206,21 +206,44 @@ public function test_encrypt_decrypt_roundtrip_with_unicode(): void { } // ------------------------------------------------------------------------- - // Plaintext passthrough (backward compatibility) + // Unencrypted and fingerprint-less values fail closed // ------------------------------------------------------------------------- - public function test_plaintext_values_pass_through_on_decrypt(): void { - // Simulate legacy data stored before encryption was added. - $data = array( - 'access_token' => 'plaintext-legacy-token', - 'username' => 'olduser', + /** + * @return array + */ + public static function unreadable_secret_provider(): array { + return array( + 'plaintext value' => array( 'plaintext', 'not encrypted' ), + 'three-part envelope' => array( 'three_part', 'malformed' ), ); + } - $decrypted = $this->provider->test_decrypt_fields( $data ); + /** + * @dataProvider unreadable_secret_provider + */ + public function test_unreadable_secret_fails_closed( string $shape, string $message_fragment ): void { + $stored = 'secret-value'; + if ( 'three_part' === $shape ) { + $encrypted = $this->provider->test_encrypt_fields( array( 'access_token' => $stored ) ); + $parts = explode( ':', $encrypted['access_token'] ); + array_pop( $parts ); + $stored = implode( ':', $parts ); + } + + $decrypted = $this->provider->test_decrypt_fields( + array( + 'access_token' => $stored, + 'username' => 'user', + ) + ); - // Should return data unchanged. - $this->assertSame( 'plaintext-legacy-token', $decrypted['access_token'] ); - $this->assertSame( 'olduser', $decrypted['username'] ); + $this->assertNull( $decrypted['access_token'] ); + $this->assertSame( 'user', $decrypted['username'] ); + $error = $this->provider->get_last_decryption_error(); + $this->assertNotNull( $error ); + $this->assertSame( 'datamachine_auth_decrypt_failed', $error->get_error_code() ); + $this->assertStringContainsString( $message_fragment, $error->get_error_message() ); } public function test_empty_string_not_encrypted(): void { @@ -315,7 +338,9 @@ public function test_malformed_envelope_wrong_iv_length_fails_closed(): void { $short_iv = base64_encode( 'short' ); $tag = base64_encode( str_repeat( 't', BaseAuthProvider::AUTH_TAG_LENGTH ) ); $ciphertext = base64_encode( 'fakeciphertext' ); - $envelope = "dm:enc:v1:{$short_iv}:{$tag}:{$ciphertext}"; + $encrypted = $this->provider->test_encrypt_fields( array( 'access_token' => 'x' ) ); + $parts = explode( ':', $encrypted['access_token'] ); + $envelope = "dm:enc:v1:{$short_iv}:{$tag}:{$ciphertext}:" . end( $parts ); $data = array( 'access_token' => $envelope ); $decrypted = $this->provider->test_decrypt_fields( $data ); @@ -415,15 +440,6 @@ public function test_key_derivation_is_deterministic(): void { // Key rotation / fail-closed reads // ------------------------------------------------------------------------- - /** - * Strip the fingerprint segment to reproduce a pre-fingerprint envelope. - */ - private function legacy_envelope( string $envelope ): string { - $parts = explode( ':', $envelope ); - array_pop( $parts ); - return implode( ':', $parts ); - } - public function test_salt_rotation_never_returns_envelope_and_surfaces_error(): void { $data = array( 'access_token' => 'rotated-secret', 'username' => 'user' ); $encrypted = $this->provider->test_encrypt_fields( $data ); @@ -464,32 +480,6 @@ public function test_key_fingerprint_mismatch_reported_without_decryption(): voi $this->assertSame( 'datamachine_auth_key_mismatch', $this->provider->get_last_decryption_error()->get_error_code() ); } - public function test_legacy_envelope_salt_rotation_fails_closed_with_decrypt_failed(): void { - $encrypted = $this->provider->test_encrypt_fields( array( 'access_token' => 'legacy-secret' ) ); - $legacy = array( 'access_token' => $this->legacy_envelope( $encrypted['access_token'] ) ); - - // Legacy envelopes carry no fingerprint, so decryption is attempted and - // fails on GCM authentication — still fail closed, never the envelope. - self::$current_salt = 'another-new-salt'; - $this->provider->set_test_salt( self::$current_salt ); - - $decrypted = $this->provider->test_decrypt_fields( $legacy ); - $this->assertNull( $decrypted['access_token'] ); - $this->assertNotSame( $legacy['access_token'], $decrypted['access_token'] ); - $this->assertSame( 'datamachine_auth_decrypt_failed', $this->provider->get_last_decryption_error()->get_error_code() ); - } - - public function test_legacy_envelope_without_rotation_still_decrypts(): void { - // Pre-fingerprint envelopes written by older versions must keep - // decrypting under the same key. - $encrypted = $this->provider->test_encrypt_fields( array( 'access_token' => 'old-format-secret' ) ); - $legacy = array( 'access_token' => $this->legacy_envelope( $encrypted['access_token'] ) ); - - $decrypted = $this->provider->test_decrypt_fields( $legacy ); - $this->assertSame( 'old-format-secret', $decrypted['access_token'] ); - $this->assertNull( $this->provider->get_last_decryption_error() ); - } - public function test_successful_decrypt_leaves_no_error(): void { $encrypted = $this->provider->test_encrypt_fields( array( 'access_token' => 'fine' ) ); diff --git a/plugins/data-machine/tests/auth-per-user-api-smoke.php b/plugins/data-machine/tests/auth-per-user-api-smoke.php index e9c605dd2c..63aca4c273 100644 --- a/plugins/data-machine/tests/auth-per-user-api-smoke.php +++ b/plugins/data-machine/tests/auth-per-user-api-smoke.php @@ -163,9 +163,7 @@ function smoke_assert( string $label, bool $condition, string $detail = '' ): vo smoke_assert( 'plaintext fields preserved', is_array( $account ) && 'alice' === $account['username'] ); echo "\n[2] missing per-user account returns null (no site fallback)\n"; -$GLOBALS['datamachine_auth_per_user_options']['datamachine_auth_data']['sample']['account'] = array( - 'access_token' => 'site-token', -); +$provider->save_site_account( array( 'access_token' => 'site-token' ) ); $missing = $provider->get_account_for_user( 999 ); smoke_assert( 'unknown user returns null', null === $missing ); smoke_assert( 'site account remains readable through the canonical site API', 'site-token' === $provider->get_account()['access_token'] ); diff --git a/plugins/data-machine/tests/auth-principal-scoped-smoke.php b/plugins/data-machine/tests/auth-principal-scoped-smoke.php index 953aab342e..738966e34b 100644 --- a/plugins/data-machine/tests/auth-principal-scoped-smoke.php +++ b/plugins/data-machine/tests/auth-principal-scoped-smoke.php @@ -179,12 +179,12 @@ function smoke_assert( string $label, bool $condition, string $detail = '' ): vo smoke_assert( 'agent account stored under agent principal', isset( $raw['example']['principals']['agent:303']['account'] ) ); echo "\n[3] policy context explicitly opts into site fallback\n"; -$GLOBALS['datamachine_auth_scope_options']['datamachine_auth_data']['legacy']['account'] = array( 'access_token' => 'legacy-token' ); $legacy = new class() extends DataMachine\Core\OAuth\BaseAuthProvider { public function __construct() { parent::__construct( 'legacy' ); } public function get_config_fields(): array { return array(); } public function is_authenticated(): bool { return ! empty( $this->get_account()['access_token'] ); } }; +$legacy->save_site_account( array( 'access_token' => 'legacy-token' ) ); smoke_assert( 'named user lookup does not fall back to legacy account', null === $legacy->get_account_for_user( 404 ) ); smoke_assert( 'policy context lookup falls back to legacy account', 'legacy-token' === $legacy->get_account_for_policy_context( array( 'user_id' => 404 ) )['access_token'] ); diff --git a/plugins/data-machine/tests/auth-ref-handler-config-smoke.php b/plugins/data-machine/tests/auth-ref-handler-config-smoke.php index 72b0afbd95..cd1c5f38d2 100644 --- a/plugins/data-machine/tests/auth-ref-handler-config-smoke.php +++ b/plugins/data-machine/tests/auth-ref-handler-config-smoke.php @@ -97,6 +97,12 @@ function update_site_option( string $option, $value ): bool { } } +if ( ! function_exists( 'wp_salt' ) ) { + function wp_salt( string $scheme = 'auth' ): string { + return 'auth-ref-smoke-' . $scheme; + } +} + require_once __DIR__ . '/smoke-bootstrap.php'; use DataMachine\Abilities\AuthAbilities; @@ -146,16 +152,15 @@ static function ( array $providers ): array { AuthAbilities::clearCache(); AuthRefHandlerConfig::register(); -$GLOBALS['auth_ref_smoke_options']['datamachine_auth_data'] = array( - 'email_imap' => array( - 'config' => array( - 'imap_host' => 'imap.example.test', - 'imap_port' => 993, - 'imap_encryption' => 'ssl', - 'imap_user' => 'reader@example.test', - 'imap_password' => 'super-secret-app-password', - ), - ), +$GLOBALS['auth_ref_smoke_options']['datamachine_auth_data'] = array(); +( new EmailAuth() )->save_config( + array( + 'imap_host' => 'imap.example.test', + 'imap_port' => 993, + 'imap_encryption' => 'ssl', + 'imap_user' => 'reader@example.test', + 'imap_password' => 'super-secret-app-password', + ) ); echo "\n[1] Export rewrite strips secrets and inserts auth_ref\n"; diff --git a/plugins/data-machine/tests/http-basic-auth-provider-smoke.php b/plugins/data-machine/tests/http-basic-auth-provider-smoke.php index db2ab59118..a9a9078f59 100644 --- a/plugins/data-machine/tests/http-basic-auth-provider-smoke.php +++ b/plugins/data-machine/tests/http-basic-auth-provider-smoke.php @@ -168,36 +168,24 @@ public function get_error_message(): string { $fail( 'deleting one account removed another' ); } -// An install configured before multi-account support stores a flat credential. It must keep -// resolving without a migration step, otherwise upgrading silently breaks live auth refs. -$legacy_provider = new HttpBasicAuthProvider(); +// Only the `accounts` map is read; a flat top-level credential is not an account. +$flat_provider = new HttpBasicAuthProvider(); $GLOBALS['datamachine_http_basic_options']['datamachine_auth_data']['http_basic']['config'] = array( - 'account' => 'legacy', - 'username' => 'olduser', - 'password' => 'legacy-password', - 'proxy_url' => 'socks5://127.0.0.1:9999', + 'account' => 'flat', + 'username' => 'olduser', + 'password' => 'flat-password', ); -$legacy = $legacy_provider->resolve_auth_ref( 'legacy' ); -if ( is_wp_error( $legacy ) || 'olduser' !== ( $legacy['auth']['username'] ?? '' ) || 'legacy-password' !== ( $legacy['auth']['password'] ?? '' ) ) { - $fail( 'pre-multi-account credential stopped resolving' ); -} -if ( 'socks5://127.0.0.1:9999' !== ( $legacy['proxy_url'] ?? '' ) ) { - $fail( 'pre-multi-account proxy stopped resolving' ); -} -if ( array( 'legacy' ) !== $legacy_provider->get_account_names() ) { - $fail( 'pre-multi-account credential was not listed' ); -} -if ( ! $legacy_provider->is_authenticated() ) { - $fail( 'pre-multi-account credential did not read as authenticated' ); +if ( ! is_wp_error( $flat_provider->resolve_auth_ref( 'flat' ) ) || array() !== $flat_provider->get_account_names() ) { + $fail( 'a flat top-level credential resolved as an account' ); } -// Adding an account alongside a legacy credential must carry the legacy one forward. -$legacy_provider->save_config( array( 'account' => 'added', 'username' => 'u2', 'password' => 'p2' ) ); -if ( is_wp_error( $legacy_provider->resolve_auth_ref( 'legacy' ) ) ) { - $fail( 'adding an account dropped the migrated legacy credential' ); -} -if ( 'legacy-password' !== ( $legacy_provider->resolve_auth_ref( 'legacy' )['auth']['password'] ?? '' ) ) { - $fail( 'migrated legacy credential lost its password' ); +// A plaintext password inside the account map fails closed instead of passing through. +$GLOBALS['datamachine_http_basic_options']['datamachine_auth_data']['http_basic']['config'] = array( + 'accounts' => array( 'plain' => array( 'username' => 'u', 'password' => 'not-encrypted' ) ), +); +$plain = $flat_provider->resolve_auth_ref( 'plain' ); +if ( ! is_wp_error( $plain ) || 'datamachine_auth_decrypt_failed' !== $plain->get_error_code() ) { + $fail( 'a plaintext stored password did not fail closed' ); } $empty = new HttpBasicAuthProvider(); diff --git a/plugins/data-machine/tests/wake-briefing-credential-integrity-smoke.php b/plugins/data-machine/tests/wake-briefing-credential-integrity-smoke.php index 9cbc1b39ed..ed4a839ee6 100644 --- a/plugins/data-machine/tests/wake-briefing-credential-integrity-smoke.php +++ b/plugins/data-machine/tests/wake-briefing-credential-integrity-smoke.php @@ -275,7 +275,7 @@ public function test_encrypt_fields( array $data ): array { ); wake_assert( 'signal: carries the re-authenticate call to action', - str_contains( $line, 'encryption key changed. Re-authenticate.' ), + str_contains( $line, 'encryption key changed or value not encrypted. Re-authenticate.' ), "got: {$line}" ); wake_assert( @@ -457,13 +457,11 @@ public function get_row( $prepared, $output = ARRAY_A ) { ); // ----------------------------------------------------------------------- - // Legacy envelopes: written before the key fingerprint existed, so they - // carry three parts and can only be settled by a trial decryption. Any - // install holding credentials stored before that change has these, which - // is exactly the shape the original incident left behind. + // Values that reads refuse: a secret field that is not an envelope, and an + // envelope without the key fingerprint, are both undecryptable. // ----------------------------------------------------------------------- - $legacy_envelope = static function ( string $plaintext, string $salt ): string { + $three_part = static function ( string $plaintext, string $salt ): string { $key = hash( 'sha256', $salt . 'datamachine-oauth', true ); $iv = random_bytes( (int) openssl_cipher_iv_length( BaseAuthProvider::CIPHER_ALGO ) ); $tag = ''; @@ -471,42 +469,62 @@ public function get_row( $prepared, $output = ARRAY_A ) { return 'dm:enc:v1:' . base64_encode( $iv ) . ':' . base64_encode( $tag ) . ':' . base64_encode( $ct ); }; - $current_salt = wp_salt( 'auth' ); + wake_set_filter( + 'datamachine_auth_encrypted_fields', + array_merge( BaseAuthProvider::ENCRYPTED_FIELDS, array( 'password' ) ) + ); update_site_option( 'datamachine_auth_data', array( - 'legacy_ok' => array( - 'config' => array( 'access_token' => $legacy_envelope( 'still-readable', $current_salt ) ), + 'three_part' => array( + 'config' => array( 'access_token' => $three_part( 'current-key', wp_salt( 'auth' ) ) ), + ), + 'plaintext' => array( + 'config' => array( + 'access_token' => 'stored-in-the-clear', + 'username' => 'not-a-secret', + ), + ), + 'nested_plain' => array( + 'accounts' => array( 'logs' => array( 'username' => 'u', 'password' => 'clear-password' ) ), ), - 'legacy_orphan' => array( - 'config' => array( 'access_token' => $legacy_envelope( 'lost-to-rotation', 'a-different-salt-entirely' ) ), + 'malformed' => array( + 'config' => array( 'access_token' => 'dm:enc:v1:only-two:parts' ), + ), + 'non_secret_only' => array( + 'config' => array( 'username' => 'just-a-name' ), ), ) ); - $legacy_audit = BaseAuthProvider::audit_stored_credentials(); + $strict_audit = BaseAuthProvider::audit_stored_credentials(); + $counts = $strict_audit['undecryptable_counts']; wake_assert( - 'legacy: a three-part envelope under the current key is not reported', - ! isset( $legacy_audit['undecryptable_counts']['legacy_ok'] ), - 'got: ' . json_encode( $legacy_audit['undecryptable_counts'] ) + 'strict: a three-part envelope is reported even under the current key', + 1 === ( $counts['three_part'] ?? 0 ), + 'got: ' . json_encode( $counts ) ); wake_assert( - 'legacy: a three-part envelope under a rotated key is reported', - 1 === ( $legacy_audit['undecryptable_counts']['legacy_orphan'] ?? 0 ), - 'got: ' . json_encode( $legacy_audit['undecryptable_counts'] ) + 'strict: a plaintext secret field is reported; non-secret fields are not', + 1 === ( $counts['plaintext'] ?? 0 ), + 'got: ' . json_encode( $counts ) ); wake_assert( - 'legacy: a malformed envelope counts as undecryptable rather than passing', - ( static function () { - update_site_option( - 'datamachine_auth_data', - array( 'legacy_broken' => array( 'config' => array( 'access_token' => 'dm:enc:v1:only-two:parts' ) ) ) - ); - $audit = BaseAuthProvider::audit_stored_credentials(); - return 1 === ( $audit['undecryptable_counts']['legacy_broken'] ?? 0 ); - } )() + 'strict: a plaintext secret nested in an account map is reported', + 1 === ( $counts['nested_plain'] ?? 0 ), + 'got: ' . json_encode( $counts ) + ); + wake_assert( + 'strict: a malformed envelope is reported', + 1 === ( $counts['malformed'] ?? 0 ), + 'got: ' . json_encode( $counts ) + ); + wake_assert( + 'strict: a slot with only non-secret fields is not reported', + ! isset( $counts['non_secret_only'] ), + 'got: ' . json_encode( $counts ) ); // -----------------------------------------------------------------------