Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions plugins/data-machine/docs/core-system/oauth-handlers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion plugins/data-machine/docs/development/1-0-baseline.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}

Expand Down
201 changes: 104 additions & 97 deletions plugins/data-machine/inc/Core/OAuth/BaseAuthProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
*/
Expand Down Expand Up @@ -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.
Expand All @@ -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 ) ) {
Expand All @@ -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;
Expand Down Expand Up @@ -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<string>
*/
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<string, true> $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;
}
}
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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.
Expand All @@ -1430,42 +1439,40 @@ 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' )
);
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.
Expand Down
Loading
Loading