diff --git a/class-gf-paystack-api.php b/class-gf-paystack-api.php index 42d1f1b..63588f0 100644 --- a/class-gf-paystack-api.php +++ b/class-gf-paystack-api.php @@ -3,19 +3,29 @@ die('You are not allowed to call this page directly.'); } +require_once __DIR__ . '/includes/class-gf-paystack-keys.php'; +require_once __DIR__ . '/includes/class-gf-paystack-restricted-key.php'; + class GFPaystackApi { public $plugin_name; - protected $public_key; protected $secret_key; + protected $webhook_secret; + + protected $stored_secret_key; + + /** @var array|null Path (`whsec`|`legacy`|`none`) and outcome of the last validate_webhook() call. */ + public $last_webhook_check = null; + public function __construct($config) { $this->plugin_name = 'Paystack Addon for Gravity Forms'; $this->secret_key = $config->secret_key ?? ''; - $this->public_key = $config->public_key ?? ''; + $this->webhook_secret = $config->webhook_secret ?? ''; + $this->stored_secret_key = $config->stored_secret_key ?? ''; } /** @@ -26,16 +36,8 @@ public function __construct($config) */ public function log_transaction_success($reference) { - // Send reference to logger along with plugin name and public key - // $params = [ - // 'plugin_name' => $this->plugin_name, - // 'public_key' => $this->public_key, - // 'transaction_reference' => $reference - // ]; - $params = [ 'plugin_name' => 'pstk-gravityforms', - 'public_key' => $this->public_key, 'transaction_reference' => $reference ]; @@ -48,7 +50,7 @@ public function log_transaction_success($reference) 'https://plugin-tracker.paystackintegrations.com/' ); } catch (\Throwable $e) { - error_log(__METHOD__ . '(): plugin tracker request failed: ' . $e->getMessage()); + error_log(GF_Paystack_Keys::redact(__METHOD__ . '(): plugin tracker request failed: ' . $e->getMessage())); } } @@ -86,7 +88,12 @@ public function send_request( $body = json_decode($res['body'], true); if (is_array($body)) { - error_log(__METHOD__ . '(): ' . strtoupper($method) . ' ' . $uri . ' status: ' . (isset($body['status']) ? var_export($body['status'], true) : 'unknown')); + error_log(GF_Paystack_Keys::redact(__METHOD__ . '(): ' . strtoupper($method) . ' ' . $uri . ' status: ' . (isset($body['status']) ? var_export($body['status'], true) : 'unknown'))); + + $code = isset($res['response']['code']) ? (int) $res['response']['code'] : 0; + if ($code === 403 && isset($body['message']) && $body['message'] === GF_Paystack_Restricted_Key::SCOPE_DENIED_MESSAGE) { + error_log(GF_Paystack_Keys::redact('rk scope denied method=' . strtoupper($method) . ' path=' . parse_url($uri, PHP_URL_PATH))); + } if (isset($body['error']) || $body['status'] == false) { throw new Exception("{$body['message']}"); @@ -113,21 +120,99 @@ public function verify_transaction($reference) /** * Validate Webhook Signature * - * @param $input - * @param string|null $signature Defaults to the request's signature header. + * A configured signing secret decides alone; the legacy sk HMAC is only used when none is set. + * + * @param string $input The raw body that will be decoded. + * @param string|null $signature Legacy X-Paystack-Signature; defaults to the request's header. + * @param string|null $signing_header Paystack-Signature; defaults to the request's header. * @return boolean */ - public function validate_webhook($input, $signature = null) + public function validate_webhook($input, $signature = null, $signing_header = null) + { + if (is_string($this->webhook_secret) && trim($this->webhook_secret) !== '') { + if ($signing_header === null) { + $signing_header = isset($_SERVER['HTTP_PAYSTACK_SIGNATURE']) ? $_SERVER['HTTP_PAYSTACK_SIGNATURE'] : ''; + } + + $outcome = $this->check_signing_secret_header($input, $signing_header); + $this->last_webhook_check = array('sig' => 'whsec', 'result' => $outcome); + + return $outcome === 'valid'; + } + + if (GF_Paystack_Keys::type($this->stored_secret_key) === 'sk') { + if ($signature === null) { + $signature = isset($_SERVER['HTTP_X_PAYSTACK_SIGNATURE']) ? $_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] : ''; + } + + $is_valid = is_string($signature) && $signature !== '' + && hash_equals(hash_hmac('sha512', (string) $input, $this->stored_secret_key), $signature); + $this->last_webhook_check = array('sig' => 'legacy', 'result' => $is_valid ? 'valid' : 'invalid'); + + return $is_valid; + } + + $this->last_webhook_check = array('sig' => 'none', 'result' => 'invalid'); + + return false; + } + + /** + * Verify a `Paystack-Signature: t=,v1=:[,v1=...]` header. + * + * @param string $input The raw body. + * @param mixed $header The header value. + * @param int|null $now Current unix time; defaults to time(). + * @return string valid|stale|invalid|malformed + */ + public function check_signing_secret_header($input, $header, $now = null) { - if ($signature === null) { - $signature = isset($_SERVER['HTTP_X_PAYSTACK_SIGNATURE']) ? $_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] : ''; + if (!is_string($this->webhook_secret) || trim($this->webhook_secret) === '' || !is_string($header)) { + return 'malformed'; } - if (!is_string($signature) || $signature === '' || !is_string($this->secret_key) || trim($this->secret_key) === '') { - return false; + $timestamps = array(); + $signatures = array(); + foreach (explode(',', $header) as $part) { + $pair = explode('=', $part, 2); + if (count($pair) !== 2) { + continue; + } + + $name = trim($pair[0]); + $value = trim($pair[1]); + if ($name === 't') { + $timestamps[] = $value; + } elseif ($name === 'v1' && count($signatures) < 10) { + $colon = strrpos($value, ':'); + $hex = $colon === false ? '' : substr($value, $colon + 1); + if ($colon > 0 && preg_match('/^[0-9a-fA-F]{128}$/', $hex)) { + $signatures[] = strtolower($hex); + } + } } - return hash_equals(hash_hmac('sha512', (string) $input, $this->secret_key), $signature); + if (count($timestamps) !== 1 || !ctype_digit($timestamps[0]) || empty($signatures)) { + return 'malformed'; + } + + $timestamp = $timestamps[0]; + $expected = hash_hmac('sha512', $timestamp . '.' . (string) $input, $this->webhook_secret); + + $matched = false; + foreach ($signatures as $candidate) { + if (hash_equals($expected, $candidate)) { + $matched = true; + } + } + + if (!$matched) { + return 'invalid'; + } + + $now = $now === null ? time() : (int) $now; + + return abs($now - (int) $timestamp) <= 300 ? 'valid' : 'stale'; } /** diff --git a/class-gf-paystack.php b/class-gf-paystack.php index 9a74d63..26d0914 100644 --- a/class-gf-paystack.php +++ b/class-gf-paystack.php @@ -2,6 +2,9 @@ defined('ABSPATH') || die(); +require_once __DIR__ . '/includes/class-gf-paystack-keys.php'; +require_once __DIR__ . '/includes/class-gf-paystack-restricted-key.php'; + // Include the payment add-on framework. GFForms::include_payment_addon_framework(); @@ -31,6 +34,8 @@ class GFPaystack extends GFPaymentAddOn /** @var string|null */ protected $webhook_mode = null; + protected $transaction_type_callback = null; + /** * Defines the version of the Paystack Add-On. * @@ -51,7 +56,7 @@ class GFPaystack extends GFPaymentAddOn * * @var string $_min_gravityforms_version The minimum version required. */ - protected $_min_gravityforms_version = '2.0'; + protected $_min_gravityforms_version = '2.5'; /** * Defines the plugin slug. @@ -227,6 +232,16 @@ public static function get_instance() return self::$_instance; } + public function log_debug($message) + { + parent::log_debug(GF_Paystack_Keys::redact($message)); + } + + public function log_error($message) + { + parent::log_error(GF_Paystack_Keys::redact($message)); + } + /** * Load the Paystack credit card field. * @@ -286,10 +301,11 @@ public function plugin_settings_fields() */ public function api_settings_fields() { - $api_mode = ''; + // Each mode's fields only show while that mode is selected, so a first-time setup starts in Test. + $api_mode = 'test'; - if ($this->is_detail_page() && empty($api_mode)) { - $api_mode = $this->get_plugin_setting('api_mode'); + if ($this->is_detail_page()) { + $api_mode = $this->get_plugin_setting('api_mode') ?: 'test'; } $fields = array( @@ -298,6 +314,7 @@ public function api_settings_fields() 'label' => esc_html__('Mode', 'gravityformspaystack'), 'type' => 'radio', 'default_value' => $api_mode, + 'validation_callback' => array($this, 'validate_credentials'), 'choices' => array( array( 'label' => esc_html__('Live', 'gravityformspaystack'), @@ -312,30 +329,45 @@ public function api_settings_fields() ) ); + $key_help = '
' . esc_html__('Restricted Key', 'gravityformspaystack') . '
' . esc_html__('Create a restricted key in your Paystack Dashboard with Transactions: read and write, plus Plans: write if you sell subscriptions.', 'gravityformspaystack'); + $whsec_help = '
' . esc_html__('Webhook Signing Secret', 'gravityformspaystack') . '
' . esc_html__('Copy it from Settings → API Keys & Webhooks in your Paystack Dashboard.', 'gravityformspaystack'); + $credentials_fields = array( array( - 'name' => 'test_public_key', - 'label' => esc_html__('Test Public Key', 'gravityformspaystack'), + 'name' => 'test_secret_key', + 'label' => esc_html__('Test Restricted Key', 'gravityformspaystack'), 'type' => 'text', + 'input_type' => 'password', 'class' => 'medium', + 'tooltip' => $key_help, + 'dependency' => $this->mode_dependency('test'), ), array( - 'name' => 'test_secret_key', - 'label' => esc_html__('Test Secret Key', 'gravityformspaystack'), + 'name' => 'test_webhook_secret', + 'label' => esc_html__('Test Webhook Signing Secret', 'gravityformspaystack'), 'type' => 'text', + 'input_type' => 'password', 'class' => 'medium', + 'tooltip' => $whsec_help, + 'dependency' => $this->mode_dependency('test'), ), array( - 'name' => 'live_public_key', - 'label' => esc_html__('Live Public Key', 'gravityformspaystack'), + 'name' => 'live_secret_key', + 'label' => esc_html__('Live Restricted Key', 'gravityformspaystack'), 'type' => 'text', + 'input_type' => 'password', 'class' => 'medium', + 'tooltip' => $key_help, + 'dependency' => $this->mode_dependency('live'), ), array( - 'name' => 'live_secret_key', - 'label' => esc_html__('Live Secret Key', 'gravityformspaystack'), + 'name' => 'live_webhook_secret', + 'label' => esc_html__('Live Webhook Signing Secret', 'gravityformspaystack'), 'type' => 'text', + 'input_type' => 'password', 'class' => 'medium', + 'tooltip' => $whsec_help, + 'dependency' => $this->mode_dependency('live'), ), ); @@ -365,6 +397,15 @@ public function api_settings_fields() return $fields; } + // Gravity Forms 2.5+ live dependency: the field shows and hides as the Mode radio changes. + protected function mode_dependency($mode) + { + return array( + 'live' => true, + 'fields' => array(array('field' => 'api_mode', 'values' => array($mode))), + ); + } + /** * Define the markup to be displayed for the webhooks section description. * @@ -398,7 +439,9 @@ public function get_webhooks_section_description() get_webhook_url($this->get_current_feed_id()); ?>

+
  • +
  • @@ -444,6 +487,13 @@ public function feed_settings_fields() $default_settings = parent::add_field_after('feedName', $fields, $default_settings); + $transaction_type = $this->get_field('transactionType', $default_settings); + if (is_array($transaction_type)) { + $this->transaction_type_callback = rgar($transaction_type, 'validation_callback', null); + $transaction_type['validation_callback'] = array($this, 'validate_subscription_plans'); + $default_settings = $this->replace_field('transactionType', $transaction_type, $default_settings); + } + // Add donation to transaction type drop down // $transaction_type = parent::get_field('transactionType', $default_settings); // $choices = $transaction_type['choices']; @@ -810,17 +860,17 @@ public function validate_custom_meta($field) // If there are more than 20 metadata keys, set field error. if ($meta_count > 20) { - $this->set_field_error(array(esc_html__('You may only have 20 custom keys.'), 'gravityformspaystack')); + $this->set_setting_error('metaData', esc_html__('You may only have 20 custom keys.', 'gravityformspaystack'), $field); return; } // Loop through metadata and check the key name length (custom_key). foreach ($meta_data as $meta) { if (empty($meta['custom_key']) && !empty($meta['value'])) { - $this->set_field_error(array('name' => 'metaData'), esc_html__("A field has been mapped to a custom key without a name. Please enter a name for the custom key, remove the metadata item, or return the corresponding drop down to 'Select a Field'.", 'gravityformspaystack')); + $this->set_setting_error('metaData', esc_html__("A field has been mapped to a custom key without a name. Please enter a name for the custom key, remove the metadata item, or return the corresponding drop down to 'Select a Field'.", 'gravityformspaystack'), $field); break; } else if (strlen($meta['custom_key']) > 40) { - $this->set_field_error(array('name' => 'metaData'), sprintf(esc_html__('The name of custom key %s is too long. Please shorten this to 40 characters or less.', 'gravityformspaystack'), $meta['custom_key'])); + $this->set_setting_error('metaData', sprintf(esc_html__('The name of custom key %s is too long. Please shorten this to 40 characters or less.', 'gravityformspaystack'), esc_html($meta['custom_key'])), $field); break; } } @@ -1301,19 +1351,41 @@ public function callback() return false; } + try { + $response = $this->paystack_api->verify_transaction($reference); + } catch (\Exception $e) { + $this->log_error(__METHOD__ . '(): Transaction could not be verified. Reason: ' . $e->getMessage()); + + return new WP_Error('transaction_verification', __('Transaction could not be verified.', 'gravityformspaystack'), array('status_header' => 500)); + } + + $charge = rgar($response, 'data'); + + if (!is_array($charge) || rgar($charge, 'status') !== 'success') { + $this->log_error(__METHOD__ . '(): Transaction verification failed. Aborting.'); + + return false; + } + + if (rgar($charge, 'id') === null || rgar($charge, 'id') === '' || (string) rgar($charge, 'id') !== (string) rgars($event, 'data/id') || rgar($charge, 'reference') !== $reference) { + $this->log_error(__METHOD__ . '(): Verified transaction does not match the webhook event. Aborting.'); + + return false; + } + if ($feed['meta']['transactionType'] == 'subscription') { - gform_update_meta($entry_id, 'paystack_tx_auth_code', rgars($event, 'data/authorization/authorization_code')); + gform_update_meta($entry_id, 'paystack_tx_auth_code', rgars($charge, 'authorization/authorization_code')); } else { - if (!self::charge_matches_stored(rgars($event, 'data/amount'), rgars($event, 'data/currency'), gform_get_meta($entry_id, 'paystack_tx_amount'), gform_get_meta($entry_id, 'paystack_tx_currency'))) { + if (!self::charge_matches_stored(rgar($charge, 'amount'), rgar($charge, 'currency'), gform_get_meta($entry_id, 'paystack_tx_amount'), gform_get_meta($entry_id, 'paystack_tx_currency'))) { $this->log_error(__METHOD__ . '(): Webhook could not be matched to entry. Aborting.'); return false; } - $action['id'] = rgars($event, 'data/id') . '_' . $type; + $action['id'] = rgar($charge, 'id') . '_' . $type; $action['entry_id'] = $entry_id; - $action['transaction_id'] = rgars($event, 'data/id'); - $action['amount'] = $this->get_amount_import(rgars($event, 'data/amount'), rgars($event, 'data/currency')); + $action['transaction_id'] = rgar($charge, 'id'); + $action['amount'] = $this->get_amount_import(rgar($charge, 'amount'), rgar($charge, 'currency')); $action['type'] = 'complete_payment'; $action['ready_to_fulfill'] = !$entry['is_fulfilled'] ? true : false; $action['payment_date'] = rgars($event, 'data/paidAt'); @@ -1689,33 +1761,73 @@ public function get_webhook_event($body = null) $settings = $this->get_plugin_settings(); - // Get api mode from data - $mode = self::resolve_webhook_mode(rgars($response, 'data/domain')) ?: $this->get_api_mode($settings); + $candidates = $this->webhook_candidate_modes($response, $settings); - $this->paystack_api($mode, $settings); + $check = null; + $mode = null; + $attempts = array(); + foreach ($candidates as $candidate_mode) { + $this->paystack_api($candidate_mode, $settings); - $this->webhook_mode = $mode; + try { + $is_verified = $this->paystack_api->validate_webhook($body); + } catch (\Exception $e) { + $this->log_error(__METHOD__ . "(): Error: " . $e->getMessage()); - // Validate Webhook Request Payload - try { - $is_verified = $this->paystack_api->validate_webhook($body); - } catch (\Exception $e) { - $this->log_error(__METHOD__ . "(): Error: " . $e->getMessage()); + return new WP_Error('Webhook Validation Failed', $e->getMessage()); + } - return new WP_Error('Webhook Validation Failed', $e->getMessage()); + $check = $this->paystack_api->last_webhook_check; + $mode = $candidate_mode; + $attempts[] = $candidate_mode . ':' . rgar($check, 'sig') . ':' . rgar($check, 'result'); + + if ($is_verified) { + break; + } } + $this->webhook_mode = $mode; + if (!$is_verified) { - $this->log_error(__METHOD__ . '(): Wehhook request is invalid. Aborting.'); + $this->log_error(sprintf( + '%s(): Webhook request is invalid. Aborting. checks=%s', + __METHOD__, + implode(',', $attempts) + )); return false; } - $this->log_debug(__METHOD__ . "(): Processing {$this->webhook_mode} mode event."); + $this->log_debug(sprintf('%s(): Webhook verified. Processing %s mode event. sig=%s result=%s', __METHOD__, $this->webhook_mode, rgar($check, 'sig'), rgar($check, 'result'))); return $response; } + /** + * A payload's own domain decides the mode; otherwise try each mode with a signing secret, then the global mode. + */ + private function webhook_candidate_modes($response, $settings) + { + $domain_mode = self::resolve_webhook_mode(rgars($response, 'data/domain')); + if ($domain_mode) { + return array($domain_mode); + } + + $candidates = array(); + foreach (array('live', 'test') as $candidate_mode) { + if ($this->get_webhook_secret($candidate_mode, $settings) !== '') { + $candidates[] = $candidate_mode; + } + } + + $api_mode = $this->get_api_mode($settings); + if (!in_array($api_mode, $candidates, true)) { + $candidates[] = $api_mode; + } + + return $candidates; + } + /** * Generate the url Paystack webhooks should be sent to. * @@ -1924,7 +2036,6 @@ public function get_paystack_meta_data($feed, $entry, $form) * @used-by GFPaystack::subscribe() * @uses GFAddOn::get_base_path() * @uses GFPaystack::get_secret_api_key() - * @uses GFPaystack::get_public_api_key() * * @param null|string $mode The API mode; live or test. * @param null|array $settings The settings. @@ -1943,7 +2054,8 @@ public function paystack_api($mode = null, $settings = null) $config = (object) array( 'secret_key' => $this->get_secret_api_key($mode, $settings), - 'public_key' => $this->get_public_api_key($mode, $settings) + 'webhook_secret' => $this->get_webhook_secret($mode, $settings), + 'stored_secret_key' => $this->get_stored_secret_key($mode, $settings) ); $this->log_debug(sprintf('%s(): Initializing Paystack API for %s mode.', __METHOD__, $mode)); @@ -1951,6 +2063,325 @@ public function paystack_api($mode = null, $settings = null) return $this->paystack_api = new GFPaystackApi($config); } + public function get_webhook_secret($mode, $settings = null) + { + return $this->stored_setting("{$mode}_webhook_secret", $settings); + } + + public function get_stored_secret_key($mode, $settings = null) + { + return $this->stored_setting("{$mode}_secret_key", $settings); + } + + // Reads straight from stored settings. + private function stored_setting($name, $settings) + { + return trim((string) rgar(empty($settings) ? $this->get_plugin_settings() : $settings, $name)); + } + + // # KEY VALIDATION ------------------------------------------------------------------------------------------------ + + /** + * Validation compares trimmed values, so store them trimmed too: a pasted key with a trailing space would + * otherwise pass validation but break the Authorization header. + */ + public function update_plugin_settings($settings) + { + if (is_array($settings)) { + foreach (array('test_secret_key', 'live_secret_key', 'test_webhook_secret', 'live_webhook_secret') as $name) { + if (isset($settings[$name]) && is_string($settings[$name])) { + $settings[$name] = trim($settings[$name]); + } + } + unset($settings['test_public_key'], $settings['live_public_key']); + } + + parent::update_plugin_settings($settings); + } + + /** + * Runs from the always-visible Mode field: Gravity Forms skips validation of fields hidden by a dependency but + * still saves their posted values, so both modes' credentials are checked on every save. + */ + public function validate_credentials($field = null) + { + $this->validating_field = $field; + try { + $this->validate_both_modes($field); + } finally { + $this->validating_field = null; + } + } + + private function validate_both_modes($field) + { + $selected = rgar($this->get_posted_settings(), 'api_mode'); + if ($selected !== 'test' && $selected !== 'live') { + $this->set_setting_error('api_mode', esc_html__('Choose Test or Live.', 'gravityformspaystack'), $field); + } + + foreach (array('test', 'live') as $mode) { + $failed = $this->validate_secret_key_for_mode($mode); + $failed = $this->validate_webhook_secret_for_mode($mode) || $failed; + + if ($failed && $mode !== $selected && ($selected === 'test' || $selected === 'live')) { + $this->set_setting_error('api_mode', sprintf(esc_html__('Your %1$s settings have a problem. Select %2$s to see it. No settings were saved.', 'gravityformspaystack'), $mode, $mode === 'test' ? esc_html__('Test', 'gravityformspaystack') : esc_html__('Live', 'gravityformspaystack')), $field); + } + } + } + + protected function resolve_posted_key($mode) + { + $settings = $this->get_posted_settings(); + + return GF_Paystack_Keys::resolve_save( + $mode, + trim((string) rgar($settings, "{$mode}_secret_key")), + $this->get_plugin_setting("{$mode}_secret_key"), + rgar($settings, "{$mode}_webhook_secret"), + rgar($settings, $this->other_mode($mode) . '_webhook_secret') + ); + } + + protected function validate_webhook_secret_for_mode($mode) + { + $result = $this->resolve_posted_key($mode); + + if ($result['error'] !== null && strpos($result['error'], 'whsec_') === 0) { + $this->set_save_error("{$mode}_webhook_secret", $this->key_error_message($result['error'], $mode)); + + return true; + } + + return false; + } + + protected function validate_secret_key_for_mode($mode) + { + $key = trim((string) rgar($this->get_posted_settings(), "{$mode}_secret_key")); + $result = $this->resolve_posted_key($mode); + + if ($result['error'] !== null) { + if (strpos($result['error'], 'whsec_') !== 0) { + $this->set_save_error("{$mode}_secret_key", $this->key_error_message($result['error'], $mode)); + + return true; + } + + return false; + } + + if (!$result['probe']) { + return false; + } + + $verdict = $this->validate_restricted_key($key); + $this->log_debug("rk validate mode={$mode} code={$verdict['code']} probes={$verdict['probes']}"); + + // A key that was already accepted stays usable when Paystack can't be reached, so an outage never blocks + // saving unrelated settings. A definite refusal still blocks. + $kept = $key === trim((string) $this->get_plugin_setting("{$mode}_secret_key")); + if ($kept && $verdict['code'] === 'unverifiable') { + return false; + } + + if ($verdict['code'] !== 'ok') { + $this->set_save_error("{$mode}_secret_key", $this->probe_error_message($verdict)); + + return true; + } + + if ($this->has_subscription_feed($mode)) { + $plans = $this->probe_restricted_key_plans($key); + if ($plans !== 'ok' && !($kept && $plans === 'unverifiable')) { + $this->set_save_error("{$mode}_secret_key", $this->plans_error_message($plans, $mode, 'settings')); + + return true; + } + } + + return false; + } + + protected function has_subscription_feed($mode) + { + foreach ((array) $this->get_feeds() as $feed) { + if (rgars($feed, 'meta/transactionType') === 'subscription' && $this->feed_mode($feed) === $mode) { + return true; + } + } + + return false; + } + + // A feed without a mode follows the global API mode. + protected function feed_mode($feed) + { + $mode = self::resolve_webhook_mode(rgars($feed, 'meta/mode')); + if ($mode) { + return $mode; + } + + return $this->get_api_mode($this->get_plugin_settings()) === 'test' ? 'test' : 'live'; + } + + protected function validate_restricted_key($key) + { + return GF_Paystack_Restricted_Key::validate($key); + } + + protected function probe_restricted_key_plans($key) + { + return GF_Paystack_Restricted_Key::probe_plans($key); + } + + /** + * Subscription feeds need Plans: write, which the settings probe doesn't check. + */ + public function validate_subscription_plans($field, $value = null) + { + if (is_callable($this->transaction_type_callback)) { + call_user_func_array($this->transaction_type_callback, func_get_args()); + } + + $settings = $this->get_posted_settings(); + $type = rgar($settings, 'transactionType'); + + $allowed = array('product', 'subscription'); + $choices = is_array($field) ? rgar($field, 'choices') : (is_object($field) && isset($field->choices) ? $field->choices : null); + if (is_array($choices)) { + $allowed = array(); + foreach ($choices as $choice) { + $allowed[] = isset($choice['value']) ? $choice['value'] : rgar($choice, 'name'); + } + } + + if (!is_string($type) || $type === '' || !in_array($type, $allowed, true)) { + $this->set_setting_error('transactionType', esc_html__('This field is required.', 'gravityformspaystack'), $field); + return; + } + + if ($type !== 'subscription') { + return; + } + + $mode = $this->feed_mode(array('meta' => $settings)); + $current = $this->get_current_feed(); + if (is_array($current) && rgars($current, 'meta/transactionType') === $type && $this->feed_mode($current) === $mode) { + return; + } + + $key = $this->get_stored_secret_key($mode); + if (GF_Paystack_Keys::type($key) !== 'rk') { + return; + } + + $result = $this->probe_restricted_key_plans($key); + if ($result !== 'ok') { + $this->set_setting_error('transactionType', $this->plans_error_message($result, $mode), $field); + } + } + + protected function plans_error_message($result, $mode, $context = 'feed') + { + if ($result === 'plans_missing') { + $again = $context === 'settings' ? __('these settings', 'gravityformspaystack') : __('this feed', 'gravityformspaystack'); + + return sprintf(esc_html__('Subscriptions need Plans: write on your %1$s restricted key. Add it in your Paystack Dashboard, then save %2$s again.', 'gravityformspaystack'), $mode, esc_html($again)); + } + + if ($result === 'plans_mor') { + return esc_html__('Paystack subscriptions aren\'t available for merchant-of-record accounts.', 'gravityformspaystack'); + } + + return esc_html__('We couldn\'t reach Paystack to check this key. Please try again.', 'gravityformspaystack'); + } + + /** The Mode field while validate_credentials() runs: where an error goes if its own field can't be found. */ + private $validating_field = null; + + protected function set_save_error($field_name, $message) + { + $this->set_setting_error($field_name, $message . ' ' . esc_html__('No settings were saved.', 'gravityformspaystack')); + } + + /** + * Gravity Forms 2.5+ only records an error on the settings field object, passed by reference, so the field is + * looked up by name. If the lookup fails, the error goes on the field being validated, so the save stays blocked. + */ + protected function set_setting_error($name, $message, $fallback = null) + { + $renderer = $this->get_settings_renderer(); + $field = $renderer ? $renderer->get_field($name) : false; + if (!is_object($field)) { + $field = is_object($fallback) ? $fallback : $this->validating_field; + } + if (is_object($field)) { + $this->set_field_error($field, $message); + return; + } + $this->log_error(__METHOD__ . "(): no settings field to attach an error to ({$name})."); + } + + private function other_mode($mode) + { + return $mode === 'test' ? 'live' : 'test'; + } + + protected function key_error_message($code, $mode) + { + switch ($code) { + case 'secret_key': + return sprintf(esc_html__('Use a %s restricted key instead. Create one in your Paystack Dashboard with Transactions: read and write.', 'gravityformspaystack'), $mode); + case 'wrong_field': + return sprintf(esc_html__('This is a %1$s key. Paste it in the %1$s restricted key field.', 'gravityformspaystack'), $this->other_mode($mode)); + case 'invalid_format': + return sprintf(esc_html__('Restricted keys start with rk_%s_. Check you copied the whole key.', 'gravityformspaystack'), $mode); + case 'whsec_required': + return sprintf(esc_html__('Add your %s webhook signing secret from Settings → API Keys & Webhooks in your Paystack Dashboard.', 'gravityformspaystack'), $mode); + case 'whsec_format': + return esc_html__('Webhook signing secrets start with whsec_. Copy it from Settings → API Keys & Webhooks in your Paystack Dashboard.', 'gravityformspaystack'); + case 'whsec_same': + return esc_html__('Your test and live webhook signing secrets are the same. Each mode has its own secret.', 'gravityformspaystack'); + } + + return esc_html__('Paystack didn\'t accept this key.', 'gravityformspaystack'); + } + + protected function probe_error_message($verdict) + { + switch ($verdict['code']) { + case 'invalid_key': + return esc_html__('Paystack didn\'t accept this key. It may be invalid, revoked, or restricted keys may not be enabled on your Paystack account yet.', 'gravityformspaystack'); + case 'missing_scope': + case 'sensitive_scope': + $parts = array(); + if (!empty($verdict['scopes'])) { + $parts[] = sprintf(esc_html__('enable %s', 'gravityformspaystack'), $this->scope_labels($verdict['scopes'])); + } + if (!empty($verdict['sensitive_scopes'])) { + $parts[] = sprintf(esc_html__('remove %s', 'gravityformspaystack'), $this->scope_labels($verdict['sensitive_scopes'])); + } + return sprintf(esc_html__('This restricted key can\'t be used: %s. It needs Transactions: read and write. Permissions such as transfers, refunds, settlements and payouts aren\'t allowed.', 'gravityformspaystack'), implode('; ', $parts)); + } + + if ($verdict['reason'] === 'blocked') { + return esc_html__('Paystack refused our check of this key. Try again, or contact Paystack Support if it keeps happening.', 'gravityformspaystack'); + } + + return esc_html__('We couldn\'t reach Paystack to check this key. Please try again.', 'gravityformspaystack'); + } + + protected function scope_labels($scopes) + { + $out = array(); + foreach ($scopes as $scope) { + $out[] = esc_html(GF_Paystack_Restricted_Key::scope_label($scope)); + } + + return implode(', ', $out); + } + // # OTHER HELPER FUNCTIONS ---------------------------------------------------------------------------------------------- /** @@ -1958,9 +2389,7 @@ public function paystack_api($mode = null, $settings = null) * * @access public * - * @used-by GFPaystack::get_public_api_key() * @used-by GFPaystack::get_secret_api_key() - * @uses GFPaystack::get_query_string_api_key() * @uses GFAddOn::get_plugin_settings() * @uses GFPaystack::get_api_mode() * @uses GFAddOn::get_setting() @@ -1973,12 +2402,6 @@ public function paystack_api($mode = null, $settings = null) */ public function get_api_key($type = 'secret', $mode = null, $settings = null) { - // Check for api key in query first; user must be an administrator to use this feature. - $api_key = $this->get_query_string_api_key($type); - if ($api_key && current_user_can('update_core')) { - return $api_key; - } - if (!isset($settings)) { $settings = $this->get_plugin_settings(); @@ -2024,44 +2447,13 @@ public function get_api_mode($settings, $feed_id = null) } /** - * Retrieve the specified api key from the query string. - * - * @access public - * - * @used-by GFPaystack::get_api_key() - * - * @param string $type The type of key to retrieve. Defaults to 'secret'. - * - * @return string The result of the query string. - */ - public function get_query_string_api_key($type) - { - return rgget($type); - } - - /** - * Retrieve the public api key. - * - * @access public - * - * @uses GFPaystack::get_api_key() - * - * @param null|string $mode The API mode; live or test. - * @param array|null $settings The current settings. - * - * @return string The public API key. + * @deprecated 2.0.10 Public keys are no longer used. */ public function get_public_api_key($mode = null, $settings = null) { - if (empty($settings)) { - $settings = $this->get_plugin_settings(); - } - - if (empty($mode)) { - $mode = $this->get_api_mode($settings); - } + _deprecated_function(__METHOD__, '2.0.10'); - return $this->get_api_key('public', $mode, $settings); + return ''; } /** diff --git a/includes/class-gf-paystack-keys.php b/includes/class-gf-paystack-keys.php new file mode 100644 index 0000000..542f663 --- /dev/null +++ b/includes/class-gf-paystack-keys.php @@ -0,0 +1,104 @@ +]+/'; + + public static function type($key) + { + return self::parse($key)[0]; + } + + public static function mode($key) + { + return self::parse($key)[1]; + } + + private static function parse($key) + { + if (is_string($key) && preg_match('/^(sk|rk)_(live|test)_/', $key, $m)) { + return array($m[1], $m[2]); + } + + return array(null, null); + } + + public static function is_whsec_shaped($value) + { + return is_string($value) && preg_match(self::WHSEC_SHAPE, $value) === 1; + } + + // Only a new or changed key must be restricted: an sk_ key saved by an earlier version keeps working until replaced. + // A restricted key, new or kept, is always probed. + public static function resolve_save($mode, $posted_key, $stored_key, $posted_whsec, $other_mode_whsec) + { + $key = trim((string) $posted_key); + $stored = trim((string) $stored_key); + $whsec = trim((string) $posted_whsec); + $other_whsec = trim((string) $other_mode_whsec); + + $probe = false; + if ($key !== '' && $key !== $stored) { + if (self::type($key) === 'sk') { + return self::result(false, 'secret_key'); + } + + $key_mode = self::mode($key); + if ($key_mode !== null && $key_mode !== $mode) { + return self::result(false, 'wrong_field'); + } + + if (!preg_match(self::RK_SHAPE, $key)) { + return self::result(false, 'invalid_format'); + } + + $probe = true; + } elseif ($key !== '' && self::type($key) === 'rk') { + // Permissions can change in the Dashboard without the key changing, so a kept key is checked again. + $probe = true; + } + + // A blank key is a cleared field, so it never needs a signing secret. + if ($whsec !== '' && !self::is_whsec_shaped($whsec)) { + return self::result($probe, 'whsec_format'); + } + if ($key !== '' && self::type($key) === 'rk' && $whsec === '') { + return self::result($probe, 'whsec_required'); + } + if ($whsec !== '' && $whsec === $other_whsec) { + return self::result($probe, 'whsec_same'); + } + + return self::result($probe, null); + } + + public static function redact($string) + { + if (!is_string($string)) { + return $string; + } + + if (strpos($string, '_live_') === false && strpos($string, '_test_') === false && strpos($string, 'whsec_') === false) { + return $string; + } + + return preg_replace_callback(self::REDACT_PATTERN, array(__CLASS__, 'redact_match'), $string); + } + + private static function redact_match($match) + { + return $match[1] . '[redacted]'; + } + + private static function result($probe, $error) + { + return array('probe' => $error === null ? $probe : false, 'error' => $error); + } + } +} diff --git a/includes/class-gf-paystack-restricted-key.php b/includes/class-gf-paystack-restricted-key.php new file mode 100644 index 0000000..db133eb --- /dev/null +++ b/includes/class-gf-paystack-restricted-key.php @@ -0,0 +1,275 @@ + 'transactions:read', 'label' => 'Transactions: read', 'type' => 'required', 'method' => 'GET', 'path' => 'transaction?perPage=1', 'body' => null, 'present' => '2xx'), + array('scope' => 'transactions:write', 'label' => 'Transactions: write', 'type' => 'required', 'method' => 'POST', 'path' => 'transaction/check_authorization', 'body' => array(), 'present' => '404_write'), + array('scope' => 'disputes_refunds', 'label' => 'Disputes and refunds', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'refund?perPage=1', 'body' => null, 'present' => '2xx_or_400'), + array('scope' => 'bulk_charges', 'label' => 'Bulk charges', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'bulkcharge', 'body' => null, 'present' => '2xx_or_400'), + array('scope' => 'direct_debit', 'label' => 'Direct debit', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'directdebit/account', 'body' => null, 'present' => '2xx_or_400'), + array('scope' => 'preauthorizations', 'label' => 'Preauthorizations', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'preauthorization', 'body' => null, 'present' => '2xx_or_400'), + array('scope' => 'settlements', 'label' => 'Settlements', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'settlement?perPage=1', 'body' => null, 'present' => '2xx_or_400'), + array('scope' => 'subaccounts', 'label' => 'Subaccounts', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'subaccount', 'body' => null, 'present' => '2xx_or_400'), + array('scope' => 'transfers', 'label' => 'Transfers', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'transfer/config', 'body' => null, 'present' => '2xx_or_400'), + array('scope' => 'virtual_accounts', 'label' => 'Virtual accounts', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'pay-with-transfer/custom-accounts/status', 'body' => null, 'present' => '2xx_or_400'), + array('scope' => 'webhooks', 'label' => 'Webhooks', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'integration/webhooks/events', 'body' => null, 'present' => '2xx_or_400'), + array('scope' => 'connect', 'label' => 'Connect', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'connect/platforms', 'body' => null, 'present' => '2xx_or_400'), + array('scope' => 'payouts', 'label' => 'Payouts', 'type' => 'sensitive', 'method' => 'GET', 'path' => 'settlement/instant/profile', 'body' => null, 'present' => '2xx_or_400'), + ); + + // Total across every validate()/probe_plans() call in a request; overridable so tests can exhaust it without sleeping. + protected static $budget_seconds = 15.0; + protected static $deadline = null; + + protected static function now() + { + return microtime(true); + } + + public static function reset_budget() + { + self::$deadline = null; + } + + public static function scope_label($scope) + { + foreach (self::PROBES as $probe) { + if ($probe['scope'] === $scope) { + return $probe['label']; + } + } + + return $scope; + } + + private static function budget_left() + { + $now = static::now(); + // A long-lived process must not stay out of budget forever after one slow request. + if (self::$deadline === null || $now > self::$deadline + 60) { + self::$deadline = $now + static::$budget_seconds; + } + + return $now < self::$deadline; + } + + public static function validate($key, $request = null) + { + try { + $results = array(); + $baseline = null; + + foreach (self::PROBES as $index => $probe) { + if (!self::budget_left()) { + $results[] = array('probe' => $probe, 'outcome' => 'indeterminate', 'status' => 0, 'ran' => false); + break; + } + + $response = self::send($request, $key, $probe['method'], $probe['path'], $probe['body']); + $outcome = self::classify($probe, $response, $baseline); + $results[] = array('probe' => $probe, 'outcome' => $outcome, 'status' => $response['status'], 'ran' => true); + + if ($index === 0) { + $baseline = $outcome; + } + if ($outcome === 'invalid' || $outcome === 'indeterminate') { + break; + } + } + + return self::decide($results); + } catch (\Throwable $e) { + return self::verdict('unverifiable', array(), array('reason' => 'transient')); + } + } + + public static function probe_plans($key, $request = null) + { + try { + if (!self::budget_left()) { + return 'unverifiable'; + } + + $response = self::send($request, $key, 'POST', 'plan', array()); + if ($response['status'] === 400) { + return 'ok'; + } + if ($response['status'] === 403) { + if ($response['message'] === self::SCOPE_DENIED_MESSAGE) { + return 'plans_missing'; + } + if ($response['message'] === self::MOR_MESSAGE) { + return 'plans_mor'; + } + } + + return 'unverifiable'; + } catch (\Throwable $e) { + return 'unverifiable'; + } + } + + public static function default_request($method, $url, $headers, $body) + { + $res = wp_remote_request($url, array( + 'method' => $method, + 'timeout' => self::REQUEST_TIMEOUT, + 'redirection' => 0, + 'headers' => $headers, + 'body' => $body === null ? null : json_encode($body, JSON_FORCE_OBJECT), + )); + + if (is_wp_error($res) || !is_array($res)) { + return array('status' => 0, 'body' => null); + } + + $status = isset($res['response']['code']) ? (int) $res['response']['code'] : 0; + $raw = isset($res['body']) ? $res['body'] : null; + + return array('status' => $status, 'body' => $raw); + } + + private static function send($request, $key, $method, $path, $body) + { + if (!is_callable($request)) { + $request = array(__CLASS__, 'default_request'); + } + + $headers = apply_filters('gf_paystack_request_headers', array('Authorization' => 'Bearer ' . $key, 'Content-Type' => 'application/json')); + if (!is_array($headers)) { + $headers = array(); + } + // Header names are case-insensitive, so a filter's differently-cased Authorization must not survive alongside ours. + foreach (array_keys($headers) as $name) { + if (strcasecmp(trim((string) $name), 'authorization') === 0) { + unset($headers[$name]); + } + } + $headers['Authorization'] = 'Bearer ' . $key; + + try { + $response = call_user_func($request, $method, self::BASE_URL . $path, $headers, $body); + } catch (\Throwable $e) { + $response = null; + } + + if (!is_array($response) || !isset($response['status'])) { + return array('status' => 0, 'message' => null); + } + + return array('status' => (int) $response['status'], 'message' => self::message_of(isset($response['body']) ? $response['body'] : null)); + } + + private static function message_of($body) + { + if (is_string($body)) { + $decoded = json_decode($body, true); + $body = is_array($decoded) ? $decoded : $body; + } + if (is_array($body)) { + return isset($body['message']) && is_string($body['message']) ? $body['message'] : null; + } + + return is_string($body) ? $body : null; + } + + private static function is_present($probe, $response) + { + $status = $response['status']; + if ($probe['present'] === '404_write') { + return $status === 404 && $response['message'] === self::WRITE_PRESENT_MESSAGE; + } + if ($status >= 200 && $status <= 299) { + return true; + } + + return $probe['present'] === '2xx_or_400' && $status === 400; + } + + // Any 403 that isn't the exact scope message may be another gate (IP, feature), so it fails closed. + private static function classify($probe, $response, $baseline) + { + if ($response['status'] === 401) { + if ($baseline === null) { + return 'invalid'; + } + + return $baseline === 'present' && $probe['type'] === 'sensitive' ? 'present' : 'indeterminate'; + } + if ($response['status'] === 403 && $response['message'] === self::SCOPE_DENIED_MESSAGE) { + return 'absent'; + } + + return self::is_present($probe, $response) ? 'present' : 'indeterminate'; + } + + private static function decide($results) + { + if ($results[0]['outcome'] === 'invalid') { + return self::verdict('invalid_key', $results); + } + + $missing = array(); + $sensitive = array(); + $indeterminate = array(); + foreach ($results as $r) { + $type = $r['probe']['type']; + if ($type === 'required' && $r['outcome'] === 'absent') { + $missing[] = $r['probe']['scope']; + } elseif ($type === 'sensitive' && $r['outcome'] === 'present') { + $sensitive[] = $r['probe']['scope']; + } elseif ($r['outcome'] === 'indeterminate') { + $indeterminate[] = $r; + } + } + + if ($missing) { + return self::verdict('missing_scope', $results, array('scopes' => $missing, 'sensitive_scopes' => $sensitive)); + } + if ($sensitive) { + return self::verdict('sensitive_scope', $results, array('sensitive_scopes' => $sensitive)); + } + if ($indeterminate) { + $reason = 'transient'; + foreach ($indeterminate as $r) { + if ($r['status'] === 403) { + $reason = 'blocked'; + } + } + + return self::verdict('unverifiable', $results, array('reason' => $reason)); + } + + return self::verdict('ok', $results); + } + + private static function verdict($code, $results = array(), $extra = array()) + { + $parts = array(); + foreach ($results as $r) { + if ($r['ran']) { + $parts[] = $r['probe']['scope'] . ':' . $r['status']; + } + } + + $defaults = array('scopes' => array(), 'sensitive_scopes' => array(), 'reason' => null); + + return array('code' => $code) + array_merge($defaults, $extra) + array('probes' => $parts ? implode(',', $parts) : '-'); + } + } +} diff --git a/paystack.php b/paystack.php index 7f0d5ad..fbf8417 100644 --- a/paystack.php +++ b/paystack.php @@ -4,7 +4,7 @@ Plugin URI: https://paystack.com/docs/libraries-and-plugins/plugins#wordpress 0 Description: Integrates Gravity Forms with Paystack, enabling customers to pay for goods and services through Gravity Forms. -Version: 2.0.9 +Version: 2.0.10 Author: Paystack Author URI: https://developers.paystack.com License: GPL-2.0+ @@ -31,7 +31,7 @@ defined('ABSPATH') || die(); -define('GF_PAYSTACK_VERSION', '2.0.9'); +define('GF_PAYSTACK_VERSION', '2.0.10'); require_once __DIR__ . '/includes/php-advisory.php'; add_action('admin_notices', 'gf_paystack_php_advisory_notice'); diff --git a/readme.txt b/readme.txt index fbec328..ee50bfa 100644 --- a/readme.txt +++ b/readme.txt @@ -5,18 +5,35 @@ Tags: payments, subscriptions, gravityforms Requires at least: 5.1 Tested up to: 7.1 Requires PHP: 7.2 -Stable tag: 2.0.9 +Stable tag: 2.0.10 License: GPLv2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html == Description == The Paystack Addon for Gravity Forms allows you to quickly and easily implement credit card payments with WordPress. With the Paystack Add-On you can capture one time credit card payments or setup recurring payment subscriptions. += Restricted keys = +The add-on connects to Paystack with a restricted key. Choose Test or Live under Mode, then paste an `rk_test_...` or `rk_live_...` key into that mode's Restricted Key field. Only the selected mode's fields are shown. + +* The key needs Transactions: read and write permissions, plus Plans: write if you sell subscriptions. +* Keys with permissions that can move money (transfers, refunds, settlements, payouts and similar) are rejected. +* The key is checked with Paystack every time you save the settings, so after changing its permissions in the Paystack Dashboard, click Save to check them. If Paystack can't be reached, a key that was already saved stays in use. +* A restricted key needs the Webhook signing secret for the same mode (see below). +* Sites set up before version 2.0.10 keep working with the key they already saved. When you replace it, the new key must be a restricted key. + += Webhook signing secret = +The Test and Live settings have a "Webhook signing secret" field. Copy the `whsec_...` value from Settings > API Keys & Webhooks in your Paystack Dashboard. + +* It is required with a restricted key. +* Once it is set, webhooks are only accepted with a valid Paystack-Signature header that was signed within the last 5 minutes. +* Successful-payment webhooks are confirmed with Paystack before an entry is marked as paid. +* The webhook URL must listen to charge.success. Forms that sell subscriptions also need subscription.create, subscription.disable, invoice.create, invoice.update and invoice.payment_failed. Selecting all events is fine: the others are ignored. + == Installation == = Minimum Requirements = -* Gravity Forms v2.4+ +* Gravity Forms v2.5+ * WordPress v5.1+ * SSL Certificate Installed and - Configured * Download and install the add-on @@ -54,6 +71,18 @@ Yes you can! Join in on our [GitHub repository](https://github.com/PaystackHQ/pl == Changelog == += 2.0.10 - November 19, 2026 = +* The add-on now uses Paystack restricted keys (`rk_test_...` / `rk_live_...`). A key saved by an earlier version keeps working until you replace it; a new key must be a restricted key. +* Removed the public key fields. Payments never used them. +* The settings page shows only the selected mode's fields. +* Requires Gravity Forms 2.5 or later. +* A restricted key's permissions are checked with Paystack every time the settings are saved. +* Added Test and Live webhook signing secret fields, and webhook signature verification when one is set. +* Successful-payment (charge.success) webhooks are now confirmed with Paystack before an entry is marked as paid. +* Keys and signing secrets are hidden in logs. +* The key fields are now password inputs. +* Removed the admin-only ?secret= / ?public= URL override for API keys. + = 2.0.9 - October 28, 2026 = * Fixed a fatal error on the confirmation page after a successful payment when the usage tracking service is unreachable. @@ -95,6 +124,9 @@ Yes you can! Join in on our [GitHub repository](https://github.com/PaystackHQ/pl == Upgrade Notice == += 2.0.10 = +* Adds Paystack restricted keys and webhook signing secrets. Your saved key keeps working with no changes needed; a new key must be a restricted key. Requires Gravity Forms 2.5 or later. The ?secret= / ?public= URL override has been removed. + = 2.0.9 = * Fixes a fatal error customers could see after paying. Please update. diff --git a/tests/fixtures.php b/tests/fixtures.php index 7cae16e..3f8bc34 100644 --- a/tests/fixtures.php +++ b/tests/fixtures.php @@ -125,12 +125,18 @@ public function get_amount_export($amount, $currency) class GFPaystackEventFixture extends GFPaystack { public $settings = array(); + public $errors = array(); public function get_plugin_settings() { return $this->settings; } + public function log_error($message) + { + $this->errors[] = $message; + } + public function webhook_mode_value() { return $this->webhook_mode; @@ -177,3 +183,141 @@ function gf_paystack_exception_message($callback) return ''; } + +// Stands in for Gravity Forms' Settings renderer and its field objects; errors land in the fixture's field_errors. +class GFPaystackTestSettingField +{ + public $name; + private $fixture; + + public function __construct($name, $fixture) + { + $this->name = $name; + $this->fixture = $fixture; + } + + public function set_error($message = '') + { + $this->fixture->field_errors[$this->name] = $message; + $this->fixture->error_log[] = $this->name; + } +} + +class GFPaystackTestSettingsRenderer +{ + private $fixture; + + public function __construct($fixture) + { + $this->fixture = $fixture; + } + + // Like Gravity Forms, only fields the add-on defines are found; renderer_fields overrides the list. + public function get_field($name) + { + $known = $this->fixture->renderer_fields; + if (!is_array($known)) { + $known = self::defined_field_names($this->fixture); + } + if (!in_array($name, $known, true)) { + return false; + } + + return new GFPaystackTestSettingField($name, $this->fixture); + } + + public static function defined_field_names($addon) + { + $names = array(); + $collect = function ($items) use (&$collect, &$names) { + foreach ((array) $items as $item) { + if (!is_array($item)) { + continue; + } + if (isset($item['name'])) { + $names[] = $item['name']; + } + if (isset($item['fields'])) { + $collect($item['fields']); + } + } + }; + $collect($addon->plugin_settings_fields()); + $collect($addon->feed_settings_fields()); + + return $names; + } +} + +class GFPaystackSettingsFixture extends GFPaystack +{ + public $posted = array(); + public $stored = array(); + public $field_errors = array(); + public $verdict = array('code' => 'ok', 'scopes' => array(), 'sensitive_scopes' => array(), 'reason' => null, 'probes' => 'transactions:read:200'); + public $plans_result = 'ok'; + public $validate_calls = array(); + public $plans_calls = array(); + public $feeds = array(); + public $current_feed = false; + public $error_log = array(); + + public function get_feeds($form_id = null) + { + return $this->feeds; + } + + public function get_current_feed() + { + return $this->current_feed; + } + + public function get_posted_settings() + { + return $this->posted; + } + + public function get_plugin_setting($name) + { + return rgar($this->stored, $name); + } + + public function get_plugin_settings() + { + return $this->stored; + } + + public $renderer_fields = null; + + public function get_settings_renderer() + { + return new GFPaystackTestSettingsRenderer($this); + } + + public function is_detail_page() + { + return false; + } + + public function get_current_feed_id() + { + return 0; + } + + public function get_webhook_url($feed_id = null) + { + return 'https://example.test/?callback=gravityformspaystack'; + } + + protected function validate_restricted_key($key) + { + $this->validate_calls[] = $key; + return $this->verdict; + } + + protected function probe_restricted_key_plans($key) + { + $this->plans_calls[] = $key; + return $this->plans_result; + } +} diff --git a/tests/run.php b/tests/run.php index aa3a5ec..2b62826 100644 --- a/tests/run.php +++ b/tests/run.php @@ -25,6 +25,14 @@ function gf_paystack_test_check($condition, $label) $test_files = glob(__DIR__ . '/test-*.php'); sort($test_files); foreach ($test_files as $test_file) { + $GLOBALS['gf_paystack_test_filters'] = array(); + if (class_exists('GF_Paystack_Restricted_Key')) { + GF_Paystack_Restricted_Key::reset_budget(); + } + $GLOBALS['gf_paystack_test_gf_logs'] = array(); + $GLOBALS['gf_paystack_test_saved_settings'] = null; + $_GET = array(); + unset($_SERVER['HTTP_PAYSTACK_SIGNATURE'], $_SERVER['HTTP_X_PAYSTACK_SIGNATURE']); require $test_file; } diff --git a/tests/stubs.php b/tests/stubs.php index f65b052..fe7fc2a 100644 --- a/tests/stubs.php +++ b/tests/stubs.php @@ -15,7 +15,12 @@ function add_filter() if (!function_exists('apply_filters')) { function apply_filters($tag, $value) { - return $value; + $overrides = isset($GLOBALS['gf_paystack_test_filters']) ? $GLOBALS['gf_paystack_test_filters'] : array(); + if (array_key_exists($tag, $overrides) && $overrides[$tag] instanceof Closure) { + return call_user_func($overrides[$tag], $value); + } + + return array_key_exists($tag, $overrides) ? $overrides[$tag] : $value; } } @@ -33,6 +38,13 @@ function esc_html__($text, $domain = '') } } +if (!function_exists('esc_html_e')) { + function esc_html_e($text, $domain = '') + { + echo $text; + } +} + if (!function_exists('esc_html')) { function esc_html($text) { @@ -144,6 +156,20 @@ public static function include_payment_addon_framework() if (!class_exists('GFAddOn')) { class GFAddOn { + // Gravity Forms 2.5+ takes the settings field object by reference and silently ignores anything else; + // the stub throws instead, so a dropped error fails the test. + public function set_field_error(&$field, $error_message = '') + { + if (!$field instanceof GFPaystackTestSettingField) { + throw new LogicException('set_field_error() needs a settings field object'); + } + $field->set_error($error_message ? $error_message : 'This field is required.'); + } + + public function get_settings_renderer() + { + return false; + } } } @@ -157,10 +183,17 @@ public static function get_entry_meta_table_name() public function log_debug($message) { + $GLOBALS['gf_paystack_test_gf_logs'][] = array('debug', $message); } public function log_error($message) { + $GLOBALS['gf_paystack_test_gf_logs'][] = array('error', $message); + } + + public function update_plugin_settings($settings) + { + $GLOBALS['gf_paystack_test_saved_settings'] = $settings; } public function get_plugin_settings() @@ -172,6 +205,99 @@ public function get_setting($setting_name, $default_value = '', $settings = null { return rgar($settings, $setting_name, $default_value); } + + public function get_feeds($form_id = null) + { + return array(); + } + + public function get_current_feed() + { + return false; + } + + public function feed_settings_fields() + { + return array( + array( + 'title' => 'Feed Settings', + 'fields' => array( + array('name' => 'feedName', 'type' => 'text'), + array( + 'name' => 'transactionType', + 'type' => 'select', + 'choices' => array( + array('label' => 'Products and Services', 'value' => 'product'), + array('label' => 'Subscription', 'value' => 'subscription'), + ), + ), + ), + ), + ); + } + + public function get_field($name, $fields) + { + foreach ($fields as $section) { + foreach (rgar($section, 'fields', array()) as $field) { + if (rgar($field, 'name') === $name) { + return $field; + } + } + } + + return false; + } + + public function replace_field($name, $new_field, $fields) + { + foreach ($fields as $i => $section) { + foreach (rgar($section, 'fields', array()) as $j => $field) { + if (rgar($field, 'name') === $name) { + $fields[$i]['fields'][$j] = $new_field; + } + } + } + + return $fields; + } + + public function add_field_after($name, $new_fields, $fields) + { + return $this->insert_fields($name, $new_fields, $fields, 1); + } + + public function add_field_before($name, $new_fields, $fields) + { + return $this->insert_fields($name, $new_fields, $fields, 0); + } + + public function remove_field($name, $fields) + { + foreach ($fields as $i => $section) { + foreach (rgar($section, 'fields', array()) as $j => $field) { + if (rgar($field, 'name') === $name) { + array_splice($fields[$i]['fields'], $j, 1); + } + } + } + + return $fields; + } + + private function insert_fields($name, $new_fields, $fields, $offset) + { + foreach ($fields as $i => $section) { + foreach (rgar($section, 'fields', array()) as $j => $field) { + if (rgar($field, 'name') === $name) { + array_splice($fields[$i]['fields'], $j + $offset, 0, isset($new_fields['name']) ? array($new_fields) : $new_fields); + return $fields; + } + } + } + + return $fields; + } } } @@ -180,11 +306,18 @@ class WP_Error { public $code; public $message; + public $data; - public function __construct($code = '', $message = '') + public function __construct($code = '', $message = '', $data = '') { $this->code = $code; $this->message = $message; + $this->data = $data; + } + + public function get_error_data() + { + return $this->data; } public function get_error_message() diff --git a/tests/test-gateway.php b/tests/test-gateway.php index 1e91272..d83b449 100644 --- a/tests/test-gateway.php +++ b/tests/test-gateway.php @@ -50,9 +50,43 @@ }); gf_paystack_test_check(strpos($log_thrown, 'Paystack Addon for Gravity Forms') !== false, 'send_request logging case 5'); +file_put_contents($log_file, ''); +$GLOBALS['gf_paystack_test_remote_response'] = array('body' => json_encode(array('status' => false, 'message' => 'bad rk_live_abc123XYZ and whsec_def456 given'))); +$log_thrown = gf_paystack_exception_message(function () use ($log_api) { + $log_api->send_request('transaction/verify/abc', array(), 'get'); +}); +$log_contents = (string) file_get_contents($log_file); +gf_paystack_test_check(strpos($log_contents, 'abc123XYZ') === false && strpos($log_contents, 'def456') === false, 'send_request logging case 6'); + +$rk_api = new GFPaystackApi((object) array('secret_key' => 'rk_live_scopedsecret99', 'public_key' => 'pk_live_public')); +file_put_contents($log_file, ''); +$GLOBALS['gf_paystack_test_remote_response'] = array('response' => array('code' => 403), 'body' => json_encode(array('status' => false, 'message' => 'This restricted key is not permitted to perform this action'))); +$log_thrown = gf_paystack_exception_message(function () use ($rk_api) { + $rk_api->send_request('transaction/verify/abc?x=1', array(), 'get'); +}); +$log_contents = (string) file_get_contents($log_file); +gf_paystack_test_check($log_thrown === 'This restricted key is not permitted to perform this action', 'rk scope denied case 1'); +gf_paystack_test_check(strpos($log_contents, 'rk scope denied method=GET path=/transaction/verify/abc') !== false && strpos($log_contents, 'x=1', strpos($log_contents, 'rk scope denied')) === false, 'rk scope denied case 2'); +gf_paystack_test_check(strpos($log_contents, 'rk_live_scopedsecret99') === false, 'rk scope denied case 3'); + +file_put_contents($log_file, ''); +$GLOBALS['gf_paystack_test_remote_response'] = array('response' => array('code' => 403), 'body' => json_encode(array('status' => false, 'message' => 'Something else'))); +gf_paystack_exception_message(function () use ($rk_api) { + $rk_api->send_request('transaction/verify/abc', array(), 'get'); +}); +gf_paystack_test_check(strpos((string) file_get_contents($log_file), 'rk scope denied') === false, 'rk scope denied case 4'); + ini_set('error_log', $previous_log === false ? '' : $previous_log); unlink($log_file); +$GLOBALS['gf_paystack_test_gf_logs'] = array(); +$gf_log_addon = new GFPaystackGatewayFixture(); +$gf_log_addon->log_error('bad rk_live_abc123XYZ here'); +$gf_log_addon->log_debug('got whsec_def456 and sk_test_ghi789'); +$gf_logged = json_encode($GLOBALS['gf_paystack_test_gf_logs']); +gf_paystack_test_check(count($GLOBALS['gf_paystack_test_gf_logs']) === 2 && strpos($gf_logged, 'abc123XYZ') === false && strpos($gf_logged, 'def456') === false && strpos($gf_logged, 'ghi789') === false, 'addon log redaction case 1'); +gf_paystack_test_check(strpos($gf_logged, 'rk_live_[redacted]') !== false && strpos($gf_logged, 'whsec_[redacted]') !== false, 'addon log redaction case 2'); + $event_settings = array('api_mode' => 'test', 'live_secret_key' => 'sk_live_a', 'test_secret_key' => 'sk_test_b'); $event_addon = new GFPaystackEventFixture(); $event_addon->settings = $event_settings; @@ -141,3 +175,45 @@ }); gf_paystack_test_check(strpos($scalar_thrown, 'issue connecting') !== false, 'send_request case: JSON scalar response throws the generic Exception'); $GLOBALS['gf_paystack_test_remote_response'] = array('body' => json_encode(array('status' => true))); + +// # Coverage additions (dedicated test pass): every GFPaystackApi error_log line is redacted. +$redact_log = tempnam(sys_get_temp_dir(), 'gfpstk'); +$redact_prev = ini_get('error_log'); +ini_set('error_log', $redact_log); +$redact_api = new GFPaystackApi((object) array('secret_key' => 'sk_live_callkey', 'public_key' => 'pk_live_public')); +$GLOBALS['gf_paystack_test_remote_response'] = array('response' => array('code' => 200), 'body' => json_encode(array('status' => true, 'message' => 'ok', 'data' => array()))); +$redact_api->send_request('transaction/verify/sk_live_leakinguri99', array(), 'get'); +$redact_contents = (string) file_get_contents($redact_log); +gf_paystack_test_check(strpos($redact_contents, 'transaction/verify/sk_live_[redacted]') !== false && strpos($redact_contents, 'leakinguri99') === false, 'send_request status log line is redacted'); + +file_put_contents($redact_log, ''); +$GLOBALS['gf_paystack_test_remote_response'] = array('response' => array('code' => 403), 'body' => json_encode(array('status' => false, 'message' => 'This restricted key is not permitted to perform this action'))); +gf_paystack_exception_message(function () use ($redact_api) { + $redact_api->send_request('transaction/verify/rk_live_leakingscope77', array(), 'get'); +}); +$redact_contents = (string) file_get_contents($redact_log); +gf_paystack_test_check(strpos($redact_contents, 'rk scope denied') !== false && strpos($redact_contents, 'leakingscope77') === false && strpos($redact_contents, 'rk_live_[redacted]') !== false, 'rk scope denied log line is redacted'); + +class GFPaystackLeakyTrackerApi extends GFPaystackApi +{ + public function send_request($endpoint, $args = array(), $method = 'post', $domain = 'https://api.paystack.co/') + { + throw new Exception('tracker said Bearer sk_live_leakingtracker55'); + } +} +file_put_contents($redact_log, ''); +$leaky = new GFPaystackLeakyTrackerApi((object) array('secret_key' => 'sk', 'public_key' => 'pk')); +$leaky->log_transaction_success('ref'); +$redact_contents = (string) file_get_contents($redact_log); +gf_paystack_test_check(strpos($redact_contents, 'plugin tracker request failed') !== false && strpos($redact_contents, 'leakingtracker55') === false, 'plugin tracker failure log line is redacted'); + +ini_set('error_log', $redact_prev === false ? '' : $redact_prev); +unlink($redact_log); + +// GFPaystack log helpers redact too (including debug lines). +$GLOBALS['gf_paystack_test_gf_logs'] = array(); +$log_addon = new GFPaystackSettingsFixture(); +$log_addon->log_debug('d rk_live_leakdebug11 whsec_leakdebug22'); +$log_addon->log_error('e sk_test_leakerror33'); +$logged_all = json_encode($GLOBALS['gf_paystack_test_gf_logs']); +gf_paystack_test_check(count($GLOBALS['gf_paystack_test_gf_logs']) === 2 && strpos($logged_all, 'leakdebug') === false && strpos($logged_all, 'leakerror') === false && strpos($logged_all, 'rk_live_[redacted]') !== false, 'GFPaystack log_debug and log_error redact secrets'); diff --git a/tests/test-keys.php b/tests/test-keys.php new file mode 100644 index 0000000..928e3a6 --- /dev/null +++ b/tests/test-keys.php @@ -0,0 +1,87 @@ + array(array('live', '', $sk_live, '', ''), false, null), + 'blank key, stored rk, no whsec' => array(array('live', '', $rk_live, '', ''), false, null), + 'unchanged odd shape' => array(array('live', 'weird-key', 'weird-key', '', ''), false, null), + 'unchanged wrong field' => array(array('live', $sk_test, $sk_test, '', ''), false, null), + 'unchanged with whitespace' => array(array('live', " $sk_live ", $sk_live, '', ''), false, null), + 'new sk refused' => array(array('live', $sk_live, '', '', ''), false, 'secret_key'), + 'new sk other mode refused' => array(array('live', $sk_test, '', '', ''), false, 'secret_key'), + 'changed sk refused' => array(array('live', 'sk_live_rotated999', $sk_live, '', ''), false, 'secret_key'), + 'kept rk with whsec is probed again' => array(array('live', $rk_live, $rk_live, $whsec_a, ''), true, null), + 'stored sk replaced by rk' => array(array('live', $rk_live, $sk_live, $whsec_a, ''), true, null), + 'new rk other mode' => array(array('test', $rk_live, '', $whsec_a, ''), false, 'wrong_field'), + 'new key bad shape' => array(array('live', 'rk_live_', '', $whsec_a, ''), false, 'invalid_format'), + 'new key unknown prefix' => array(array('live', 'pk_live_abc', '', '', ''), false, 'invalid_format'), + 'new rk too short' => array(array('live', 'rk_live_short', '', $whsec_a, ''), false, 'invalid_format'), + 'new rk with whsec' => array(array('live', $rk_live, '', $whsec_a, $whsec_b), true, null), + 'new rk without whsec' => array(array('live', $rk_live, '', '', ''), false, 'whsec_required'), + 'kept rk without whsec' => array(array('live', $rk_live, $rk_live, '', ''), false, 'whsec_required'), + 'kept sk without whsec' => array(array('live', $sk_live, $sk_live, '', ''), false, null), + 'sk with whsec' => array(array('live', $sk_live, $sk_live, $whsec_a, ''), false, null), + 'whsec same as other mode' => array(array('live', $sk_live, $sk_live, $whsec_a, $whsec_a), false, 'whsec_same'), + 'whsec bad shape' => array(array('live', $sk_live, $sk_live, 'whsec_x', ''), false, 'whsec_format'), + 'whsec bad shape with blank key' => array(array('live', '', '', 'nope', ''), false, 'whsec_format'), + 'key error before whsec error' => array(array('live', $rk_test, '', 'nope', ''), false, 'wrong_field'), +); +foreach ($keys_cases as $label => $case) { + $result = call_user_func_array(array('GF_Paystack_Keys', 'resolve_save'), $case[0]); + gf_paystack_test_check($result === array('probe' => $case[1], 'error' => $case[2]), 'keys resolve_save ' . $label); +} + +$keys_redact_cases = array( + 'punctuation rk' => array('key rk_live_ab-c.d~e!f_g tail', 'key rk_live_[redacted] tail'), + 'base64 whsec' => array('whsec_ab+/cd==ef rest', 'whsec_[redacted] rest'), + 'query string' => array('x=1&secret=sk_live_abc&y=2', 'x=1&secret=sk_live_[redacted]'), + 'rk with &,; chars' => array('k=rk_live_ab&cd,ef;gh_ijklmnop tail', 'k=rk_live_[redacted] tail'), + 'json escaped' => array('{"key":"rk_live_abc123"}', '{"key":"rk_live_[redacted]"}'), + 'json escaped slash tail' => array('{"k":"rk_live_abcdefghij\\/klmnopTAIL"}', '{"k":"rk_live_[redacted]"}'), + 'url encoded' => array('secret%3Dsk_live_abc%26y', 'secret%3Dsk_live_[redacted]'), + 'pk' => array('pk_test_abc123', 'pk_test_[redacted]'), + 'no secrets' => array('Payment verified for ref gf-9 task_live_x', 'Payment verified for ref gf-9 task_live_x'), +); +foreach ($keys_redact_cases as $label => $case) { + gf_paystack_test_check(GF_Paystack_Keys::redact($case[0]) === $case[1], 'keys redact ' . $label); +} +gf_paystack_test_check(GF_Paystack_Keys::redact(array('sk_live_abc')) === array('sk_live_abc') && GF_Paystack_Keys::redact(null) === null, 'keys redact non-strings'); + +// # Coverage additions (dedicated test pass) +gf_paystack_test_check(GF_Paystack_Keys::mode('sk_livefoo') === null && GF_Paystack_Keys::type('sk_livefoo') === null, 'keys prefix needs the trailing underscore'); +$keys_extra = array( + 'prefix without trailing underscore' => array(array('test', 'sk_livefoo', '', '', ''), false, 'invalid_format'), + 'rk body at 256 chars' => array(array('live', 'rk_live_' . str_repeat('a', 256), '', $whsec_a, ''), true, null), + 'rk body over 256 chars' => array(array('live', 'rk_live_' . str_repeat('a', 257), '', $whsec_a, ''), false, 'invalid_format'), + 'rk at 16 chars' => array(array('live', 'rk_live_' . str_repeat('a', 16), '', $whsec_a, ''), true, null), + 'rk at 15 chars' => array(array('live', 'rk_live_' . str_repeat('a', 15), '', $whsec_a, ''), false, 'invalid_format'), + 'blank whsec on both sides is not a duplicate' => array(array('live', $sk_live, $sk_live, '', ''), false, null), + 'whsec at 16 chars' => array(array('live', $sk_live, $sk_live, 'whsec_' . str_repeat('a', 16), ''), false, null), + 'whsec at 15 chars' => array(array('live', $sk_live, $sk_live, 'whsec_' . str_repeat('a', 15), ''), false, 'whsec_format'), + 'whitespace-only other whsec is blank' => array(array('live', $sk_live, $sk_live, $whsec_a, ' '), false, null), + 'rk containing a double quote' => array(array('live', 'rk_live_abcdefgh"ijklmnopqr', '', $whsec_a, ''), false, 'invalid_format'), + 'rk containing a backslash' => array(array('live', 'rk_live_abcdefgh\\ijklmnopqr', '', $whsec_a, ''), false, 'invalid_format'), + 'rk containing a less-than' => array(array('live', 'rk_live_abcdefgh array(array('live', "rk_live_abcdefgh'ijklmnopqr", '', $whsec_a, ''), false, 'invalid_format'), + 'rk error reports no probe' => array(array('live', $rk_live, '', '', ''), false, 'whsec_required'), +); +foreach ($keys_extra as $label => $case) { + $result = call_user_func_array(array('GF_Paystack_Keys', 'resolve_save'), $case[0]); + gf_paystack_test_check($result === array('probe' => $case[1], 'error' => $case[2]), 'keys resolve_save ' . $label); +} + +gf_paystack_test_check(GF_Paystack_Keys::redact('a sk_live_abc and rk_test_def and whsec_ghi') === 'a sk_live_[redacted] and rk_test_[redacted] and whsec_[redacted]', 'keys redact several secrets in one string'); +gf_paystack_test_check(GF_Paystack_Keys::redact('sk_live_abc"') === 'sk_live_[redacted]"', 'keys redact stops at a closing quote'); diff --git a/tests/test-restricted-key.php b/tests/test-restricted-key.php new file mode 100644 index 0000000..d5f4691 --- /dev/null +++ b/tests/test-restricted-key.php @@ -0,0 +1,347 @@ + status | array(status, message); unlisted scopes get $default. +$rk_make = function ($map, $default = array(403, 'This restricted key is not permitted to perform this action'), &$log = null) { + $log = array(); + + return function ($method, $url, $headers, $body) use ($map, $default, &$log) { + $path = substr($url, strlen('https://api.paystack.co/')); + $scope = null; + foreach (GF_Paystack_Restricted_Key::PROBES as $p) { + if ($p['path'] === $path && $p['method'] === $method) { + $scope = $p['scope']; + } + } + $log[] = $scope; + $r = array_key_exists($scope, $map) ? $map[$scope] : $default; + if ($r instanceof Exception) { + throw $r; + } + $r = (array) $r; + + return array('status' => $r[0], 'body' => isset($r[1]) ? array('status' => false, 'message' => $r[1]) : null); + }; +}; + +$rk_ok_map = array('transactions:read' => 200, 'transactions:write' => array(404, $write_msg)); +$rk_expected_scopes = array('transactions:read', 'transactions:write', 'disputes_refunds', 'bulk_charges', 'direct_debit', 'preauthorizations', 'settlements', 'subaccounts', 'transfers', 'virtual_accounts', 'webhooks', 'connect', 'payouts'); + +$scope_list = array(); +foreach (GF_Paystack_Restricted_Key::PROBES as $p) { + $scope_list[] = $p['scope']; +} +gf_paystack_test_check($scope_list === $rk_expected_scopes, 'rk probe table scope list and order pinned'); +$labels_ok = true; +foreach (GF_Paystack_Restricted_Key::PROBES as $p) { + $labels_ok = $labels_ok && isset($p['label']) && is_string($p['label']) && $p['label'] !== '' && GF_Paystack_Restricted_Key::scope_label($p['scope']) === $p['label']; +} +gf_paystack_test_check($labels_ok && GF_Paystack_Restricted_Key::scope_label('payouts') === 'Payouts' && GF_Paystack_Restricted_Key::scope_label('unknown') === 'unknown', 'rk every probe has a label and scope_label falls back to the raw scope'); +gf_paystack_test_check(GF_Paystack_Restricted_Key::PROBES[1]['path'] === 'transaction/check_authorization' && GF_Paystack_Restricted_Key::PROBES[1]['method'] === 'POST', 'rk write probe route pinned'); + +$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map, array(403, $scope_msg), $log)); +gf_paystack_test_check($v['code'] === 'ok' && $v['reason'] === null && $v['scopes'] === array() && $v['sensitive_scopes'] === array() && count($log) === 13, 'rk ok when baseline and write present and sensitive absent'); +gf_paystack_test_check(strpos($v['probes'], 'transactions:read:200,transactions:write:404,disputes_refunds:403') === 0 && strpos($v['probes'], $rk_key) === false, 'rk probes string has scope:status and no key'); + +$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make(array('transactions:read' => array(401, 'Invalid key')), array(401), $log)); +gf_paystack_test_check($v['code'] === 'invalid_key' && $log === array('transactions:read'), 'rk baseline 401 is invalid_key and stops'); + +$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make(array(), array(403, $scope_msg), $log)); +gf_paystack_test_check($v['code'] === 'missing_scope' && $v['scopes'] === array('transactions:read', 'transactions:write') && count($log) === 13, 'rk missing read and write when all absent'); + +$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make(array('transactions:write' => array(404, $write_msg)) + array('transactions:read' => array(403, $scope_msg)), array(403, $scope_msg), $log)); +gf_paystack_test_check($v['code'] === 'missing_scope' && $v['scopes'] === array('transactions:read'), 'rk missing read only'); + +$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make(array('transactions:read' => 200, 'transactions:write' => 404), array(403, $scope_msg), $log)); +gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient' && $log === array('transactions:read', 'transactions:write'), 'rk write 404 without exact message is unverifiable and stops'); + +$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make(array('transactions:read' => 200, 'transactions:write' => array(404, 'Not found')), array(403, $scope_msg))); +gf_paystack_test_check($v['code'] === 'unverifiable', 'rk write 404 with other message is unverifiable'); + +foreach (array(200, 400) as $status) { + $v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map + array('settlements' => $status, 'payouts' => $status), array(403, $scope_msg), $log)); + gf_paystack_test_check($v['code'] === 'sensitive_scope' && $v['sensitive_scopes'] === array('settlements', 'payouts') && $v['scopes'] === array(), "rk sensitive present on $status"); +} + +$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map + array('transfers' => 401), array(403, $scope_msg))); +gf_paystack_test_check($v['code'] === 'sensitive_scope' && $v['sensitive_scopes'] === array('transfers'), 'rk 401 on sensitive after 2xx baseline is present'); + +$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make(array('transactions:read' => array(403, $scope_msg), 'transactions:write' => array(404, $write_msg), 'disputes_refunds' => 401), array(403, $scope_msg), $log)); +gf_paystack_test_check($v['code'] === 'missing_scope' && end($log) === 'disputes_refunds', 'rk 401 on sensitive after absent baseline is not present and stops'); + +$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map + array('direct_debit' => array(403, 'IP not allowed')), array(403, $scope_msg), $log)); +gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'blocked' && end($log) === 'direct_debit', 'rk other 403 is blocked and probing stops'); + +$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map + array('bulk_charges' => 429), array(403, $scope_msg), $log)); +gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient' && end($log) === 'bulk_charges', 'rk 429 is transient'); + +$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map + array('subaccounts' => 503), array(403, $scope_msg))); +gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient', 'rk 5xx is transient'); + +$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map + array('connect' => 302), array(403, $scope_msg))); +gf_paystack_test_check($v['code'] === 'unverifiable', 'rk 3xx is unverifiable'); + +$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map + array('webhooks' => 0), array(403, $scope_msg), $log)); +gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient' && end($log) === 'webhooks', 'rk status 0 on sensitive probe is unverifiable'); + +$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map + array('settlements' => 200, 'transfers' => 429), array(403, $scope_msg))); +gf_paystack_test_check($v['code'] === 'sensitive_scope', 'rk proven sensitive scope wins over a later indeterminate'); + +$v = GF_Paystack_Restricted_Key::validate($rk_key, function () { + throw new RuntimeException('boom'); +}); +gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient', 'rk throwing request is unverifiable transient'); + +$v = GF_Paystack_Restricted_Key::validate($rk_key, function () { + return 'garbage'; +}); +gf_paystack_test_check($v['code'] === 'unverifiable', 'rk malformed response is unverifiable'); + +GF_Paystack_Restricted_Key::reset_budget(); +$calls = 0; +$v = GF_Paystack_Restricted_Key_Zero::validate($rk_key, function () use (&$calls) { + $calls++; + + return array('status' => 200, 'body' => null); +}); +gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient' && $calls === 0 && $v['probes'] === '-', 'rk exhausted budget stops before any probe'); + +GF_Paystack_Restricted_Key::reset_budget(); +gf_paystack_test_check(GF_Paystack_Restricted_Key_Zero::probe_plans($rk_key, function () use (&$calls) { + $calls++; + + return array('status' => 400, 'body' => null); +}) === 'unverifiable' && $calls === 0, 'rk probe_plans after exhausted budget is unverifiable without a request'); + +GF_Paystack_Restricted_Key::reset_budget(); +$slow = $rk_make($rk_ok_map, array(403, $scope_msg), $log); +$v = GF_Paystack_Restricted_Key_Spent::validate($rk_key, function ($m, $u, $h, $b) use ($slow) { + usleep(30000); + + return $slow($m, $u, $h, $b); +}); +gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient' && strpos($v['probes'], 'transactions:read:200') === 0, 'rk budget exhausted mid-run is unverifiable transient'); + +// A new window starts once the old one has been over for more than 60s. +if (!class_exists('GF_Paystack_Restricted_Key_Clocked')) { + class GF_Paystack_Restricted_Key_Clocked extends GF_Paystack_Restricted_Key + { + public static $time = 1000.0; + protected static $budget_seconds = 5.0; + + protected static function now() + { + return static::$time; + } + } +} +GF_Paystack_Restricted_Key::reset_budget(); +$clock_calls = 0; +$clock_request = function () use (&$clock_calls) { + $clock_calls++; + + return array('status' => 200, 'body' => null); +}; +GF_Paystack_Restricted_Key_Clocked::$time = 1000.0; +GF_Paystack_Restricted_Key_Clocked::validate($rk_key, $clock_request); +$first_calls = $clock_calls; +GF_Paystack_Restricted_Key_Clocked::$time = 1010.0; +$clock_calls = 0; +$v = GF_Paystack_Restricted_Key_Clocked::validate($rk_key, $clock_request); +gf_paystack_test_check($first_calls > 0 && $clock_calls === 0 && $v['code'] === 'unverifiable', 'rk budget stays spent shortly after the window ends'); +GF_Paystack_Restricted_Key_Clocked::$time = 1066.0; +$v = GF_Paystack_Restricted_Key_Clocked::validate($rk_key, $clock_request); +gf_paystack_test_check($clock_calls > 0, 'rk budget opens a new window once the old one is over by more than 60s'); +GF_Paystack_Restricted_Key::reset_budget(); + +// Budget is shared across calls: a second validate() in the same request gets what the first left. +GF_Paystack_Restricted_Key::reset_budget(); +$slow_ok = function ($m, $u, $h, $b) use ($rk_make, $rk_ok_map, $scope_msg) { + usleep(30000); + $f = $rk_make($rk_ok_map, array(403, $scope_msg)); + + return $f($m, $u, $h, $b); +}; +GF_Paystack_Restricted_Key_Spent::validate($rk_key, $slow_ok); +$calls = 0; +$v = GF_Paystack_Restricted_Key_Spent::validate($rk_key, function () use (&$calls) { + $calls++; + + return array('status' => 200, 'body' => null); +}); +gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient' && $calls === 0, 'rk second validate shares the exhausted budget'); +GF_Paystack_Restricted_Key::reset_budget(); + +// probe_plans +$plan = function ($status, $message = null) { + return function ($method, $url, $headers, $body) use ($status, $message) { + return array('status' => $status, 'body' => $message === null ? null : json_encode(array('message' => $message))); + }; +}; +gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, $plan(400, 'Plan name is required')) === 'ok', 'rk plans 400 ok'); +gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, $plan(403, $scope_msg)) === 'plans_missing', 'rk plans scope 403 missing'); +gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, $plan(403, $mor_msg)) === 'plans_mor', 'rk plans MoR 403'); +gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, $plan(403, 'other')) === 'unverifiable', 'rk plans other 403 unverifiable'); +gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, $plan(500)) === 'unverifiable', 'rk plans 500 unverifiable'); +gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, function () { + throw new Exception('x'); +}) === 'unverifiable', 'rk plans throwing request unverifiable'); +$seen = array(); +GF_Paystack_Restricted_Key::probe_plans($rk_key, function ($m, $u, $h, $b) use (&$seen) { + $seen = array($m, $u, $b); + + return array('status' => 400, 'body' => null); +}); +gf_paystack_test_check($seen === array('POST', 'https://api.paystack.co/plan', array()), 'rk plans probe is POST plan with empty body'); + +// default transport +$GLOBALS['gf_paystack_test_remote_calls'] = array(); +$GLOBALS['gf_paystack_test_remote_response'] = array('response' => array('code' => 403), 'body' => json_encode(array('message' => $scope_msg))); +$v = GF_Paystack_Restricted_Key::validate($rk_key); +$call = $GLOBALS['gf_paystack_test_remote_calls'][0]; +gf_paystack_test_check($call[0] === 'https://api.paystack.co/transaction?perPage=1' && $call[1]['method'] === 'GET' && $call[1]['timeout'] === 4 && $call[1]['redirection'] === 0 && $call[1]['body'] === null, 'rk default transport request args'); +gf_paystack_test_check($call[1]['headers']['Authorization'] === 'Bearer ' . $rk_key && $call[1]['headers']['Content-Type'] === 'application/json', 'rk default transport headers'); +gf_paystack_test_check($v['code'] === 'missing_scope' && count($GLOBALS['gf_paystack_test_remote_calls']) === 13, 'rk default transport parses json message'); + +$GLOBALS['gf_paystack_test_remote_calls'] = array(); +$GLOBALS['gf_paystack_test_remote_response'] = array('response' => array('code' => 200), 'body' => '{}'); +GF_Paystack_Restricted_Key::validate($rk_key); +$write_call = $GLOBALS['gf_paystack_test_remote_calls'][1]; +gf_paystack_test_check($write_call[1]['method'] === 'POST' && $write_call[1]['body'] === '{}', 'rk default transport encodes empty write body'); + +$GLOBALS['gf_paystack_test_remote_calls'] = array(); +$GLOBALS['gf_paystack_test_remote_response'] = new WP_Error('http', 'down'); +$v = GF_Paystack_Restricted_Key::validate($rk_key); +gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient' && count($GLOBALS['gf_paystack_test_remote_calls']) === 1 && strpos($v['probes'], $rk_key) === false, 'rk wp_error maps to status 0'); + +$GLOBALS['gf_paystack_test_remote_calls'] = array(); +$GLOBALS['gf_paystack_test_remote_response'] = array('response' => array('code' => 403), 'body' => json_encode(array('message' => $scope_msg))); +$GLOBALS['gf_paystack_test_filters']['gf_paystack_request_headers'] = array('Authorization' => 'Bearer other', 'authorization' => 'Bearer other', 'X-Extra' => '1'); +GF_Paystack_Restricted_Key::validate($rk_key); +$sent_headers = $GLOBALS['gf_paystack_test_remote_calls'][0][1]['headers']; +unset($GLOBALS['gf_paystack_test_filters']['gf_paystack_request_headers']); +$auth_keys = array_filter(array_keys($sent_headers), function ($k) { + return strtolower($k) === 'authorization'; +}); +gf_paystack_test_check(count($auth_keys) === 1 && $sent_headers['Authorization'] === 'Bearer ' . $rk_key && $sent_headers['X-Extra'] === '1', 'rk probe headers keep a single Authorization with the saved key'); + +foreach (array(' Authorization', 'authorization ') as $odd_name) { + $GLOBALS['gf_paystack_test_remote_calls'] = array(); + $GLOBALS['gf_paystack_test_filters']['gf_paystack_request_headers'] = array($odd_name => 'Bearer other', 'X-Extra' => '1'); + GF_Paystack_Restricted_Key::validate($rk_key); + $sent_headers = $GLOBALS['gf_paystack_test_remote_calls'][0][1]['headers']; + unset($GLOBALS['gf_paystack_test_filters']['gf_paystack_request_headers']); + gf_paystack_test_check(array_keys($sent_headers) === array('X-Extra', 'Authorization') && $sent_headers['Authorization'] === 'Bearer ' . $rk_key, 'rk probe strips a padded Authorization header name: ' . json_encode($odd_name)); +} + +// # Coverage additions (dedicated test pass) + +$rk_pinned = array( + 'transactions:read|required|GET|transaction?perPage=1|2xx', + 'transactions:write|required|POST|transaction/check_authorization|404_write', + 'disputes_refunds|sensitive|GET|refund?perPage=1|2xx_or_400', + 'bulk_charges|sensitive|GET|bulkcharge|2xx_or_400', + 'direct_debit|sensitive|GET|directdebit/account|2xx_or_400', + 'preauthorizations|sensitive|GET|preauthorization|2xx_or_400', + 'settlements|sensitive|GET|settlement?perPage=1|2xx_or_400', + 'subaccounts|sensitive|GET|subaccount|2xx_or_400', + 'transfers|sensitive|GET|transfer/config|2xx_or_400', + 'virtual_accounts|sensitive|GET|pay-with-transfer/custom-accounts/status|2xx_or_400', + 'webhooks|sensitive|GET|integration/webhooks/events|2xx_or_400', + 'connect|sensitive|GET|connect/platforms|2xx_or_400', + 'payouts|sensitive|GET|settlement/instant/profile|2xx_or_400', +); +$rk_actual = array(); +$rk_only_safe = true; +foreach (GF_Paystack_Restricted_Key::PROBES as $p) { + $rk_actual[] = $p['scope'] . '|' . $p['type'] . '|' . $p['method'] . '|' . $p['path'] . '|' . $p['present']; + $rk_only_safe = $rk_only_safe && ($p['method'] === 'GET' || $p['scope'] === 'transactions:write'); +} +gf_paystack_test_check($rk_actual === $rk_pinned, 'rk full probe table (scope, type, method, path, presence rule) pinned'); +gf_paystack_test_check($rk_only_safe, 'rk only the transactions:write probe is a non-GET'); + +$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make(array('transactions:read' => 201, 'transactions:write' => array(404, $write_msg)), array(403, $scope_msg))); +gf_paystack_test_check($v['code'] === 'ok', 'rk baseline 201 counts as present'); + +$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map + array('settlements' => 204), array(403, $scope_msg))); +gf_paystack_test_check($v['code'] === 'sensitive_scope' && $v['sensitive_scopes'] === array('settlements'), 'rk sensitive probe 204 is present'); + +$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make(array('transactions:read' => 400), array(403, $scope_msg), $log)); +gf_paystack_test_check($v['code'] === 'unverifiable' && $log === array('transactions:read'), 'rk 400 on the required baseline is not presence'); + +$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make(array('transactions:read' => 200, 'transactions:write' => 401), array(403, $scope_msg), $log)); +gf_paystack_test_check($v['code'] === 'unverifiable' && end($log) === 'transactions:write', 'rk 401 on the required write probe after a 2xx baseline is not proof'); + +$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make(array('transactions:read' => array(403, $scope_msg), 'transactions:write' => array(404, $write_msg), 'disputes_refunds' => 401), array(403, $scope_msg))); +gf_paystack_test_check($v['sensitive_scopes'] === array(), 'rk 401 on sensitive after absent baseline reports no sensitive scope'); + +// A failing transport still records the probe that ran. +$notices = array(); +set_error_handler(function ($no, $str) use (&$notices) { + $notices[] = $str; + + return true; +}); +$v_throw = GF_Paystack_Restricted_Key::validate($rk_key, function () { + throw new RuntimeException('boom'); +}); +$v_nostatus = GF_Paystack_Restricted_Key::validate($rk_key, function () { + return array('body' => null); +}); +restore_error_handler(); +gf_paystack_test_check($v_throw['probes'] === 'transactions:read:0' && $v_nostatus['probes'] === 'transactions:read:0' && $v_nostatus['code'] === 'unverifiable' && $notices === array(), 'rk throwing or status-less transport maps to status 0 without notices'); + +// Anything thrown outside the transport is still contained. +$GLOBALS['gf_paystack_test_filters']['gf_paystack_request_headers'] = function () { + throw new RuntimeException('filter exploded'); +}; +$v = GF_Paystack_Restricted_Key::validate($rk_key, $rk_make($rk_ok_map)); +gf_paystack_test_check($v['code'] === 'unverifiable' && $v['reason'] === 'transient' && $v['probes'] === '-', 'rk validate contains a Throwable raised outside the transport'); +gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, $plan(400)) === 'unverifiable', 'rk probe_plans contains a Throwable raised outside the transport'); +unset($GLOBALS['gf_paystack_test_filters']['gf_paystack_request_headers']); + +// A filter returning a non-array must not break the probe. +$GLOBALS['gf_paystack_test_filters']['gf_paystack_request_headers'] = 'junk'; +$seen_headers = null; +$v = GF_Paystack_Restricted_Key::validate($rk_key, function ($m, $u, $h, $b) use (&$seen_headers, $rk_make, $rk_ok_map, $scope_msg) { + $seen_headers = $h; + $f = $rk_make($rk_ok_map, array(403, $scope_msg)); + + return $f($m, $u, $h, $b); +}); +unset($GLOBALS['gf_paystack_test_filters']['gf_paystack_request_headers']); +gf_paystack_test_check($v['code'] === 'ok' && $seen_headers === array('Authorization' => 'Bearer ' . $rk_key), 'rk non-array header filter falls back to the forced Authorization header'); + +// probe_plans: only 400 is a pass +gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, $plan(422, 'x')) === 'unverifiable', 'rk plans 422 unverifiable'); +gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, $plan(200)) === 'unverifiable', 'rk plans 200 unverifiable'); +gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, $plan(401, $scope_msg)) === 'unverifiable', 'rk plans 401 unverifiable'); +gf_paystack_test_check(GF_Paystack_Restricted_Key::probe_plans($rk_key, $plan(403)) === 'unverifiable', 'rk plans 403 without a message unverifiable'); +$plan_headers = null; +GF_Paystack_Restricted_Key::probe_plans($rk_key, function ($m, $u, $h, $b) use (&$plan_headers) { + $plan_headers = $h; + + return array('status' => 400, 'body' => null); +}); +gf_paystack_test_check($plan_headers['Authorization'] === 'Bearer ' . $rk_key, 'rk plans probe sends the key as Bearer'); diff --git a/tests/test-settings.php b/tests/test-settings.php new file mode 100644 index 0000000..4c909c9 --- /dev/null +++ b/tests/test-settings.php @@ -0,0 +1,487 @@ +posted = $posted; + $addon->stored = $stored; + if ($configure) { + $configure($addon); + } + $call = function ($method) use ($addon, $mode) { + return (function () use ($method, $mode) { + return $this->$method($mode); + })->call($addon); + }; + if ($which !== 'whsec') { + $call('validate_secret_key_for_mode'); + } + if ($which !== 'key') { + $call('validate_webhook_secret_for_mode'); + } + + return $addon; +}; + +// The Mode field's callback checks both modes, so a key hidden by the mode switch can't skip validation. +$cred = function ($posted, $stored = array(), $configure = null) { + $GLOBALS['gf_paystack_test_gf_logs'] = array(); + $addon = new GFPaystackSettingsFixture(); + $addon->posted = $posted; + $addon->stored = $stored; + if ($configure) { + $configure($addon); + } + $addon->validate_credentials(array()); + + return $addon; +}; +$a = $cred(array('api_mode' => 'live', 'test_secret_key' => $st_sk_test)); +gf_paystack_test_check(isset($a->field_errors['test_secret_key']) && strpos($a->field_errors['api_mode'] ?? '', 'Your test settings have a problem. Select Test to see it.') === 0, 'credentials: new sk in the hidden test fields is refused and flagged on Mode'); +$a = $cred(array('api_mode' => 'live', 'test_secret_key' => $st_rk_test, 'test_webhook_secret' => '')); +gf_paystack_test_check(isset($a->field_errors['test_webhook_secret']) && isset($a->field_errors['api_mode']), 'credentials: hidden rk without whsec is refused'); +$a = $cred(array('api_mode' => 'test', 'live_secret_key' => $st_rk_live, 'live_webhook_secret' => 'nope')); +gf_paystack_test_check(isset($a->field_errors['live_webhook_secret']) && strpos($a->field_errors['api_mode'] ?? '', 'Your live settings') === 0, 'credentials: hidden bad whsec is refused'); +$a = $cred(array('api_mode' => 'test', 'live_secret_key' => $st_rk_live, 'live_webhook_secret' => $st_ws_live)); +gf_paystack_test_check($a->validate_calls === array($st_rk_live), 'credentials: hidden new rk is still probed'); +$a = $cred(array('api_mode' => 'test', 'test_secret_key' => $st_sk_test)); +gf_paystack_test_check(isset($a->field_errors['test_secret_key']) && !isset($a->field_errors['api_mode']), 'credentials: an error in the selected mode is not repeated on Mode'); +$a = $cred(array('api_mode' => 'test', 'test_secret_key' => $st_sk_test, 'live_secret_key' => $st_sk_live), array('test_secret_key' => $st_sk_test, 'live_secret_key' => $st_sk_live)); +gf_paystack_test_check($a->field_errors === array() && $a->validate_calls === array(), 'credentials: grandfathered sk keys in both modes save'); +$a = $cred(array('api_mode' => '')); +gf_paystack_test_check(($a->field_errors['api_mode'] ?? '') === 'Choose Test or Live.', 'credentials: a missing mode is refused'); + +$a = $st_run('test', array('test_secret_key' => $st_sk_test), array('test_secret_key' => $st_sk_test)); +gf_paystack_test_check($a->field_errors === array() && $a->validate_calls === array(), 'settings unchanged sk saves'); + +$a = $st_run('live', array('live_secret_key' => $st_sk_live), array()); +gf_paystack_test_check(strpos($a->field_errors['live_secret_key'] ?? '', 'Use a live restricted key instead.') === 0 && $a->validate_calls === array(), 'settings new sk refused without probe'); + +$a = $st_run('test', array('test_secret_key' => ' ' . $st_rk_test . ' ', 'test_webhook_secret' => $st_ws_test)); +gf_paystack_test_check($a->field_errors === array() && $a->validate_calls === array($st_rk_test), 'settings new rk with whsec probes trimmed key and saves'); +$logged = json_encode($GLOBALS['gf_paystack_test_gf_logs']); +gf_paystack_test_check(strpos($logged, 'rk validate mode=test code=ok probes=transactions:read:200') !== false && strpos($logged, $st_rk_test) === false, 'settings probe log line never contains the key'); + +$rk_posted = array('live_secret_key' => $st_rk_live, 'live_webhook_secret' => $st_ws_live); +$verdict = function ($v) { + return function ($addon) use ($v) { + $addon->verdict = array_merge($addon->verdict, $v); + }; +}; + +$a = $st_run('live', $rk_posted, array(), $verdict(array('code' => 'invalid_key'))); +gf_paystack_test_check(isset($a->field_errors['live_secret_key']) && strpos($a->field_errors['live_secret_key'], 'Paystack didn\'t accept this key.') === 0 && substr($a->field_errors['live_secret_key'], -strlen($st_suffix)) === $st_suffix, 'settings probe invalid_key error'); + +$a = $st_run('live', $rk_posted, array(), $verdict(array('code' => 'missing_scope', 'scopes' => array('transactions:write')))); +gf_paystack_test_check($a->field_errors['live_secret_key'] === 'This restricted key can\'t be used: enable Transactions: write. It needs Transactions: read and write. Permissions such as transfers, refunds, settlements and payouts aren\'t allowed.' . $st_suffix, 'settings probe missing_scope copy'); + +$a = $st_run('live', $rk_posted, array(), $verdict(array('code' => 'sensitive_scope', 'sensitive_scopes' => array('transfers', 'disputes_refunds')))); +gf_paystack_test_check(strpos($a->field_errors['live_secret_key'], 'remove Transfers, Disputes and refunds.') !== false && strpos($a->field_errors['live_secret_key'], 'enable') === false, 'settings probe sensitive_scope copy'); + +$a = $st_run('live', $rk_posted, array(), $verdict(array('code' => 'missing_scope', 'scopes' => array('transactions:read'), 'sensitive_scopes' => array('payouts')))); +gf_paystack_test_check(strpos($a->field_errors['live_secret_key'], 'enable Transactions: read; remove Payouts.') !== false, 'settings probe missing and sensitive scope copy'); + +$a = $st_run('live', $rk_posted, array(), $verdict(array('code' => 'unverifiable', 'reason' => 'blocked'))); +gf_paystack_test_check(strpos($a->field_errors['live_secret_key'], 'Paystack refused our check of this key.') === 0 && substr($a->field_errors['live_secret_key'], -strlen($st_suffix)) === $st_suffix, 'settings probe unverifiable blocked copy'); + +$a = $st_run('live', $rk_posted, array(), $verdict(array('code' => 'unverifiable', 'reason' => 'transient'))); +gf_paystack_test_check(strpos($a->field_errors['live_secret_key'], 'We couldn\'t reach Paystack to check this key.') === 0 && substr($a->field_errors['live_secret_key'], -strlen($st_suffix)) === $st_suffix, 'settings probe unverifiable transient copy'); + +$a = $st_run('test', array('test_secret_key' => $st_rk_test, 'test_webhook_secret' => '')); +gf_paystack_test_check(isset($a->field_errors['test_webhook_secret']) && !isset($a->field_errors['test_secret_key']) && strpos($a->field_errors['test_webhook_secret'], 'Add your test webhook signing secret') !== false && substr($a->field_errors['test_webhook_secret'], -strlen($st_suffix)) === $st_suffix && $a->validate_calls === array(), 'settings rk without whsec errors on whsec field without probing'); + +$a = $st_run('test', array('test_secret_key' => $st_rk_test, 'test_webhook_secret' => ''), array('test_secret_key' => $st_rk_test)); +gf_paystack_test_check(isset($a->field_errors['test_webhook_secret']), 'settings whsec cleared with unchanged rk errors'); + +$a = $st_run('test', array('test_secret_key' => $st_rk_test, 'test_webhook_secret' => 'nope'), array('test_secret_key' => $st_rk_test)); +gf_paystack_test_check(strpos($a->field_errors['test_webhook_secret'], 'Webhook signing secrets start with whsec_.') === 0, 'settings bad whsec shape errors'); + +$a = $st_run('live', array('live_secret_key' => $st_sk_live, 'live_webhook_secret' => $st_ws_live, 'test_webhook_secret' => $st_ws_live), array('live_secret_key' => $st_sk_live)); +gf_paystack_test_check(isset($a->field_errors['live_webhook_secret']) && strpos($a->field_errors['live_webhook_secret'], 'are the same') !== false, 'settings test==live whsec errors'); + +$a = $st_run('live', array('live_secret_key' => $st_rk_test, 'live_webhook_secret' => $st_ws_live)); +gf_paystack_test_check($a->field_errors['live_secret_key'] === 'This is a test key. Paste it in the test restricted key field.' . $st_suffix, 'settings wrong_field copy'); + +$a = $st_run('live', array('live_secret_key' => 'sk_live_rotated123'), array('live_secret_key' => $st_sk_live)); +gf_paystack_test_check($a->field_errors['live_secret_key'] === 'Use a live restricted key instead. Create one in your Paystack Dashboard with Transactions: read and write.' . $st_suffix, 'settings changed sk refused copy'); + +$a = $st_run('test', array('test_secret_key' => 'garbage')); +gf_paystack_test_check($a->field_errors['test_secret_key'] === 'Restricted keys start with rk_test_. Check you copied the whole key.' . $st_suffix, 'settings invalid_format copy'); + +// Each callback reports only its own codes. +$a = $st_run('test', array('test_secret_key' => $st_rk_test, 'test_webhook_secret' => ''), array(), null, 'key'); +gf_paystack_test_check($a->error_log === array() && $a->validate_calls === array(), 'settings key callback ignores whsec codes'); +$a = $st_run('test', array('test_secret_key' => $st_rk_test, 'test_webhook_secret' => ''), array(), null, 'whsec'); +gf_paystack_test_check($a->error_log === array('test_webhook_secret'), 'settings whsec callback reports whsec codes once'); +$a = $st_run('live', array('live_secret_key' => $st_sk_test), array(), null, 'whsec'); +gf_paystack_test_check($a->error_log === array(), 'settings whsec callback ignores key codes'); +$a = $st_run('live', array('live_secret_key' => $st_sk_test)); +gf_paystack_test_check($a->error_log === array('live_secret_key'), 'settings key code is reported once across both callbacks'); +$a = $st_run('live', $rk_posted, array(), $verdict(array('code' => 'invalid_key'))); +gf_paystack_test_check($a->error_log === array('live_secret_key'), 'settings probe result is reported once across both callbacks'); +$a = $st_run('live', array('live_secret_key' => $st_sk_live, 'live_webhook_secret' => 'nope'), array('live_secret_key' => $st_sk_live), null, 'key'); +gf_paystack_test_check($a->error_log === array(), 'settings key callback silent on bad whsec shape'); + +// Plans check on save. +$sub_feed = function ($mode, $active = '1', $type = 'subscription') { + return array('is_active' => $active, 'meta' => array('transactionType' => $type) + ($mode === null ? array() : array('mode' => $mode))); +}; +$with_feeds = function ($feeds, $plans = 'ok') use ($verdict) { + return function ($addon) use ($feeds, $plans) { + $addon->feeds = $feeds; + $addon->plans_result = $plans; + }; +}; + +$a = $st_run('live', $rk_posted, array(), $with_feeds(array($sub_feed('live'))), 'key'); +gf_paystack_test_check($a->field_errors === array() && $a->plans_calls === array($st_rk_live), 'settings save probes plans for an active subscription feed in that mode'); + +$a = $st_run('live', $rk_posted, array(), $with_feeds(array($sub_feed(null))), 'key'); +gf_paystack_test_check($a->plans_calls === array($st_rk_live), 'settings save treats a feed without a mode as live'); + +$a = $st_run('live', $rk_posted, array(), $with_feeds(array($sub_feed('live')), 'plans_missing'), 'key'); +gf_paystack_test_check($a->field_errors['live_secret_key'] === 'Subscriptions need Plans: write on your live restricted key. Add it in your Paystack Dashboard, then save these settings again.' . $st_suffix, 'settings save plans_missing error on the key field'); + +$a = $st_run('live', $rk_posted, array(), $with_feeds(array($sub_feed('live')), 'plans_mor'), 'key'); +gf_paystack_test_check($a->field_errors['live_secret_key'] === 'Paystack subscriptions aren\'t available for merchant-of-record accounts.' . $st_suffix, 'settings save plans_mor error on the key field'); + +$a = $st_run('live', $rk_posted, array(), $with_feeds(array($sub_feed('live')), 'unverifiable'), 'key'); +gf_paystack_test_check(strpos($a->field_errors['live_secret_key'], 'We couldn\'t reach Paystack') === 0, 'settings save plans unverifiable error on the key field'); + +$a = $st_run('live', $rk_posted, array(), $with_feeds(array($sub_feed('test'), $sub_feed('live', '1', 'product')), 'plans_missing'), 'key'); +gf_paystack_test_check($a->field_errors === array() && $a->plans_calls === array(), 'settings save skips plans when no subscription feed uses that mode'); + +$a = $st_run('live', $rk_posted, array(), $with_feeds(array($sub_feed('live', '0'))), 'key'); +gf_paystack_test_check($a->plans_calls === array($st_rk_live), 'settings save probes plans for an inactive subscription feed too'); + +$a = $st_run('test', array('test_secret_key' => $st_rk_test, 'test_webhook_secret' => $st_ws_test), array('api_mode' => 'test'), $with_feeds(array($sub_feed(null))), 'key'); +gf_paystack_test_check($a->plans_calls === array($st_rk_test), 'settings save treats a feed without a mode as the global api mode'); + +$a2 = $st_run('live', $rk_posted, array(), function ($addon) use ($sub_feed, $verdict) { + $addon->feeds = array($sub_feed('live')); + $addon->verdict = array_merge($addon->verdict, array('code' => 'invalid_key')); + $addon->plans_result = 'plans_missing'; +}, 'key'); +gf_paystack_test_check($a2->plans_calls === array() && strpos($a2->field_errors['live_secret_key'], 'Paystack didn\'t accept this key.') === 0, 'settings save skips plans when the settings probe fails'); + +$a = $st_run('live', array('live_secret_key' => $st_rk_live, 'live_webhook_secret' => $st_ws_live), array('live_secret_key' => $st_rk_live), $with_feeds(array($sub_feed('live')), 'plans_missing'), 'key'); +gf_paystack_test_check($a->plans_calls === array($st_rk_live) && strpos($a->field_errors['live_secret_key'] ?? '', 'Subscriptions need Plans: write') === 0, 'settings save re-checks plans for a kept key'); + +// A kept restricted key is checked again on every save; only an unreachable Paystack is let through. +$kept = array('live_secret_key' => $st_rk_live, 'live_webhook_secret' => $st_ws_live); +$a = $st_run('live', $kept, array('live_secret_key' => $st_rk_live), $verdict(array('code' => 'sensitive_scope', 'sensitive_scopes' => array('transfers'))), 'key'); +gf_paystack_test_check($a->validate_calls === array($st_rk_live) && strpos($a->field_errors['live_secret_key'] ?? '', 'remove Transfers') !== false, 'settings kept key that gained transfers is refused'); +$a = $st_run('live', $kept, array('live_secret_key' => $st_rk_live), $verdict(array('code' => 'unverifiable', 'reason' => 'transient')), 'key'); +gf_paystack_test_check($a->field_errors === array(), 'settings kept key saves when Paystack is unreachable'); +$a = $st_run('live', $kept, array('live_secret_key' => $st_rk_live), $verdict(array('code' => 'unverifiable', 'reason' => 'blocked')), 'key'); +gf_paystack_test_check($a->field_errors === array(), 'settings kept key saves when the check is blocked'); +$a = $st_run('live', $kept, array(), $verdict(array('code' => 'unverifiable', 'reason' => 'transient')), 'key'); +gf_paystack_test_check(isset($a->field_errors['live_secret_key']), 'settings new key is refused when Paystack is unreachable'); +$a = $st_run('live', $kept, array('live_secret_key' => $st_rk_live), $with_feeds(array($sub_feed('live')), 'unverifiable'), 'key'); +gf_paystack_test_check($a->field_errors === array(), 'settings kept key saves when the plans check cannot reach Paystack'); +$a = $st_run('live', $kept, array('live_secret_key' => $st_rk_live), $verdict(array('code' => 'invalid_key')), 'key'); +gf_paystack_test_check(strpos($a->field_errors['live_secret_key'] ?? '', 'Paystack didn\'t accept this key.') === 0, 'settings kept key that was revoked is refused'); + +$a = $st_run('live', array('live_secret_key' => $st_rk_live, 'live_webhook_secret' => $st_ws_live), array('live_secret_key' => $st_sk_live)); +gf_paystack_test_check($a->field_errors === array() && $a->validate_calls === array($st_rk_live), 'settings stored sk replaced by rk is probed'); + +// Fields. +$fa = new GFPaystackSettingsFixture(); +$by_name = array(); +foreach ($fa->api_settings_fields() as $f) { + $by_name[$f['name']] = $f; +} +$pw_ok = true; +foreach (array('test_secret_key', 'live_secret_key', 'test_webhook_secret', 'live_webhook_secret') as $n) { + $pw_ok = $pw_ok && isset($by_name[$n]) && $by_name[$n]['input_type'] === 'password'; +} +gf_paystack_test_check($pw_ok, 'settings secret and whsec fields are password inputs'); +$order = array_keys($by_name); +gf_paystack_test_check(array_search('test_webhook_secret', $order) === array_search('test_secret_key', $order) + 1 && array_search('live_webhook_secret', $order) === array_search('live_secret_key', $order) + 1, 'settings whsec fields follow their secret key'); +gf_paystack_test_check($by_name['test_secret_key']['label'] === 'Test Restricted Key' && $by_name['live_webhook_secret']['label'] === 'Live Webhook Signing Secret' && strpos($by_name['live_secret_key']['tooltip'], 'Create a restricted key in your Paystack Dashboard') !== false, 'settings labels and help text'); +gf_paystack_test_check(!isset($by_name['test_public_key']) && !isset($by_name['live_public_key']), 'settings have no public key fields'); +$labels = ''; +foreach ($by_name as $f) { + $labels .= ' ' . rgar($f, 'label') . ' ' . rgar($f, 'tooltip'); +} +gf_paystack_test_check(stripos($labels, 'secret key') === false, 'settings never mention secret keys'); +$dep_ok = true; +foreach (array('test' => array('test_secret_key', 'test_webhook_secret'), 'live' => array('live_secret_key', 'live_webhook_secret')) as $dep_mode => $names) { + foreach ($names as $n) { + $dep_ok = $dep_ok && rgar($by_name[$n], 'dependency') === array('live' => true, 'fields' => array(array('field' => 'api_mode', 'values' => array($dep_mode)))); + } +} +gf_paystack_test_check($dep_ok, 'settings key fields show only for their own mode'); +gf_paystack_test_check($by_name['api_mode']['default_value'] === 'test' && !isset($by_name['webhooks_enabled']['dependency']['live']), 'settings mode defaults to test and webhook checkbox shows in both modes'); + +// Feed. +$feed = function ($posted, $stored, $plans = 'ok') { + $addon = new GFPaystackSettingsFixture(); + $addon->posted = $posted; + $addon->stored = $stored; + $addon->plans_result = $plans; + $addon->validate_subscription_plans(array()); + + return $addon; +}; + +$sub_test = array('transactionType' => 'subscription', 'mode' => 'test'); +$a = $feed($sub_test, array('test_secret_key' => $st_rk_test)); +gf_paystack_test_check($a->field_errors === array() && $a->plans_calls === array($st_rk_test), 'feed subscription rk plans ok'); + +$a = $feed($sub_test, array('test_secret_key' => $st_rk_test), 'plans_missing'); +gf_paystack_test_check($a->field_errors['transactionType'] === 'Subscriptions need Plans: write on your test restricted key. Add it in your Paystack Dashboard, then save this feed again.', 'feed plans_missing copy'); + +$a = $feed(array('transactionType' => 'subscription', 'mode' => 'live'), array('live_secret_key' => $st_rk_live), 'plans_mor'); +gf_paystack_test_check($a->field_errors['transactionType'] === 'Paystack subscriptions aren\'t available for merchant-of-record accounts.', 'feed plans_mor copy'); + +$a = $feed($sub_test, array('test_secret_key' => $st_rk_test), 'unverifiable'); +gf_paystack_test_check(strpos($a->field_errors['transactionType'], 'We couldn\'t reach Paystack') === 0, 'feed plans unverifiable copy'); + +$a = $feed($sub_test, array('test_secret_key' => $st_sk_test, 'live_secret_key' => $st_rk_live), 'plans_missing'); +gf_paystack_test_check($a->field_errors === array() && $a->plans_calls === array(), 'feed subscription sk no probe, other mode rk ignored'); + +$a = $feed(array('transactionType' => 'product', 'mode' => 'test'), array('test_secret_key' => $st_rk_test), 'plans_missing'); +gf_paystack_test_check($a->field_errors === array() && $a->plans_calls === array(), 'feed product rk no probe'); + + +// Feed: own validity of the transactionType field. +$feed_field = array('name' => 'transactionType', 'choices' => array(array('label' => 'Products', 'value' => 'product'), array('label' => 'Subscription', 'value' => 'subscription'))); +$feed_run = function ($posted, $stored, $plans = 'ok', $configure = null, $field = null) use ($feed_field) { + $addon = new GFPaystackSettingsFixture(); + $addon->posted = $posted; + $addon->stored = $stored; + $addon->plans_result = $plans; + if ($configure) { + $configure($addon); + } + $addon->validate_subscription_plans($field === null ? $feed_field : $field); + + return $addon; +}; + +foreach (array('empty' => '', 'missing' => null, 'unknown' => 'donation', 'array' => array('subscription')) as $label => $bad) { + $posted = $bad === null ? array('mode' => 'test') : array('transactionType' => $bad, 'mode' => 'test'); + $a = $feed_run($posted, array('test_secret_key' => $st_rk_test)); + gf_paystack_test_check($a->field_errors === array('transactionType' => 'This field is required.') && $a->plans_calls === array(), "feed $label transactionType is a required error"); +} + +$a = $feed_run(array('transactionType' => 'donation'), array(), 'ok', null, array('name' => 'transactionType')); +gf_paystack_test_check($a->field_errors === array('transactionType' => 'This field is required.'), 'feed without choices accepts only product or subscription'); +$a = $feed_run(array('transactionType' => 'product'), array(), 'ok', null, array('name' => 'transactionType')); +gf_paystack_test_check($a->field_errors === array(), 'feed without choices accepts product'); + +// Feed: probe only when something changed. +$stored_feed = function ($type, $mode) { + return array('id' => 4, 'meta' => array('transactionType' => $type, 'mode' => $mode)); +}; +$with_current = function ($current) { + return function ($addon) use ($current) { + $addon->current_feed = $current; + }; +}; + +$a = $feed_run($sub_test, array('test_secret_key' => $st_rk_test), 'plans_missing', $with_current($stored_feed('subscription', 'test'))); +gf_paystack_test_check($a->field_errors === array() && $a->plans_calls === array(), 'feed unchanged subscription feed is not probed'); + +$a = $feed_run($sub_test, array('test_secret_key' => $st_rk_test, 'live_secret_key' => $st_rk_live), 'plans_missing', $with_current($stored_feed('subscription', 'live'))); +gf_paystack_test_check(isset($a->field_errors['transactionType']) && $a->plans_calls === array($st_rk_test), 'feed changed mode is probed'); + +$a = $feed_run($sub_test, array('test_secret_key' => $st_rk_test), 'ok', $with_current($stored_feed('product', 'test'))); +gf_paystack_test_check($a->plans_calls === array($st_rk_test), 'feed changed to subscription is probed'); + +$a = $feed_run(array('transactionType' => 'subscription'), array('live_secret_key' => $st_rk_live), 'ok', $with_current($stored_feed('subscription', 'test'))); +gf_paystack_test_check($a->plans_calls === array($st_rk_live), 'feed posted without mode compares as live'); + +$a = $feed_run(array('transactionType' => 'subscription'), array('live_secret_key' => $st_rk_live), 'plans_missing', $with_current($stored_feed('subscription', 'live'))); +gf_paystack_test_check($a->plans_calls === array(), 'feed unchanged live default is not probed'); + +// Feed: wiring and chaining. +class GFPaystackFeedWiringFixture extends GFPaystackSettingsFixture +{ + public $parent_calls = 0; + + public function parent_callback($field) + { + $this->parent_calls++; + } + + public function feed_settings_fields() + { + return parent::feed_settings_fields(); + } +} + +$wired = new GFPaystackFeedWiringFixture(); +$wired_fields = $wired->feed_settings_fields(); +$wired_type = $wired->get_field('transactionType', $wired_fields); +gf_paystack_test_check(is_array($wired_type) && $wired_type['validation_callback'] === array($wired, 'validate_subscription_plans'), 'feed_settings_fields wires validate_subscription_plans onto transactionType'); + +class GFPaystackFeedChainFixture extends GFPaystackFeedWiringFixture +{ + public function get_field($name, $fields) + { + $field = parent::get_field($name, $fields); + if ($name === 'transactionType' && is_array($field) && !isset($field['validation_callback'])) { + $field['validation_callback'] = array($this, 'parent_callback'); + } + + return $field; + } +} + +$chained = new GFPaystackFeedChainFixture(); +$chained->posted = array('transactionType' => 'product'); +$chained_fields = $chained->feed_settings_fields(); +$chained_type = $chained->get_field('transactionType', $chained_fields); +$chained->validate_subscription_plans($chained_type); +gf_paystack_test_check($chained->parent_calls === 1 && $chained->field_errors === array(), 'feed existing transactionType callback is still called'); + +$GLOBALS['gf_paystack_test_saved_settings'] = null; +$st_saver = new GFPaystackSettingsFixture(); +$st_saver->update_plugin_settings(array('test_secret_key' => " $st_rk_test\n", 'live_webhook_secret' => " $st_ws_live ", 'api_mode' => ' test ')); +$st_saved = $GLOBALS['gf_paystack_test_saved_settings']; +gf_paystack_test_check($st_saved['test_secret_key'] === $st_rk_test && $st_saved['live_webhook_secret'] === $st_ws_live && $st_saved['api_mode'] === ' test ', 'settings save trims only credential fields'); + +// # Coverage additions (dedicated test pass) + +// Credentials are validated from the always-visible Mode field, never from fields a dependency can hide. +$wiring_ok = $by_name['api_mode']['validation_callback'] === array($fa, 'validate_credentials'); +foreach (array('test_secret_key', 'live_secret_key', 'test_webhook_secret', 'live_webhook_secret') as $field_name) { + $wiring_ok = $wiring_ok && !isset($by_name[$field_name]['validation_callback']); +} +gf_paystack_test_check($wiring_ok, 'settings credentials are validated from the Mode field'); + +// Each callback validates its own mode. +$a = $st_run('test', array('test_secret_key' => $st_sk_live, 'live_secret_key' => $st_sk_test)); +gf_paystack_test_check($a->error_log === array('test_secret_key'), 'settings test key callback only reports the test field'); +$a = $st_run('live', array('test_secret_key' => $st_sk_live, 'live_secret_key' => $st_sk_test)); +gf_paystack_test_check($a->error_log === array('live_secret_key'), 'settings live key callback only reports the live field'); +$a = $st_run('test', array('test_webhook_secret' => 'nope', 'live_webhook_secret' => 'nope'), array(), null, 'whsec'); +gf_paystack_test_check($a->error_log === array('test_webhook_secret'), 'settings test whsec callback only reports the test field'); +$a = $st_run('live', array('test_webhook_secret' => 'nope', 'live_webhook_secret' => 'nope'), array(), null, 'whsec'); +gf_paystack_test_check($a->error_log === array('live_webhook_secret'), 'settings live whsec callback only reports the live field'); + +// The mirror image: each mode's rk probe uses its own mode's whsec and stored key. +$a = $st_run('live', array('live_secret_key' => $st_rk_live, 'live_webhook_secret' => $st_ws_live, 'test_webhook_secret' => $st_ws_live)); +gf_paystack_test_check(isset($a->field_errors['live_webhook_secret']) && $a->validate_calls === array(), 'settings whsec_same is judged against the other mode and blocks the probe'); +$a = $st_run('live', array('live_secret_key' => $st_rk_live, 'live_webhook_secret' => $st_ws_live, 'test_webhook_secret' => $st_ws_test), array('live_secret_key' => $st_rk_test)); +gf_paystack_test_check($a->validate_calls === array($st_rk_live), 'settings a changed key is compared against this mode stored key'); +$a = $st_run('live', array('live_secret_key' => $st_rk_live, 'live_webhook_secret' => $st_ws_live), array('test_secret_key' => $st_rk_live)); +gf_paystack_test_check($a->validate_calls === array($st_rk_live), 'settings stored key of the other mode does not make this key unchanged'); + +// Feed choices drive the allowed transaction types. +$custom_field = array('name' => 'transactionType', 'choices' => array(array('label' => 'Donation', 'value' => 'donation'), array('label' => 'Sub', 'value' => 'subscription'))); +$a = $feed_run(array('transactionType' => 'donation'), array(), 'ok', null, $custom_field); +gf_paystack_test_check($a->field_errors === array(), 'feed accepts a type that is only in the field choices'); +$a = $feed_run(array('transactionType' => 'product'), array(), 'ok', null, $custom_field); +gf_paystack_test_check($a->field_errors === array('transactionType' => 'This field is required.'), 'feed rejects product when the field choices do not offer it'); +$name_field = array('name' => 'transactionType', 'choices' => array(array('label' => 'Donation', 'name' => 'donation'))); +$a = $feed_run(array('transactionType' => 'donation'), array(), 'ok', null, $name_field); +gf_paystack_test_check($a->field_errors === array(), 'feed choice without a value falls back to its name'); + +// Non-array settings pass through untouched. +$GLOBALS['gf_paystack_test_saved_settings'] = 'unset'; +$st_saver->update_plugin_settings(null); +gf_paystack_test_check($GLOBALS['gf_paystack_test_saved_settings'] === null, 'settings save passes non-array settings through'); + +// get_webhook_secret / get_stored_secret_key read per-mode settings and trim. +$st_reader = new GFPaystackSettingsFixture(); +$st_reader->stored = array('test_webhook_secret' => " $st_ws_test ", 'live_webhook_secret' => $st_ws_live, 'test_secret_key' => " $st_sk_test\n", 'live_secret_key' => $st_rk_live); +gf_paystack_test_check($st_reader->get_webhook_secret('test') === $st_ws_test && $st_reader->get_webhook_secret('live') === $st_ws_live && $st_reader->get_webhook_secret('live', array()) === $st_ws_live, 'settings get_webhook_secret is per mode, trimmed, and falls back to plugin settings'); +gf_paystack_test_check($st_reader->get_stored_secret_key('test') === $st_sk_test && $st_reader->get_stored_secret_key('live', array('live_secret_key' => 'x')) === 'x', 'settings get_stored_secret_key is per mode, trimmed, and prefers passed settings'); +gf_paystack_test_check($st_reader->get_webhook_secret('test', array('test_webhook_secret' => $st_ws_live)) === $st_ws_live && (new GFPaystackSettingsFixture())->get_webhook_secret('test') === '', 'settings get_webhook_secret prefers passed settings and defaults to blank'); + +// Feed: callback arguments, object fields and the global-mode default. +class GFPaystackFeedArgsFixture extends GFPaystackFeedWiringFixture +{ + public $parent_args = array(); + + public function set_transaction_type_callback($callback) + { + $this->transaction_type_callback = $callback; + } + + public function parent_callback($field, $value = null) + { + $this->parent_args = func_get_args(); + } +} + +$args_addon = new GFPaystackFeedArgsFixture(); +$args_addon->posted = array('transactionType' => 'product'); +$args_fields = $args_addon->feed_settings_fields(); +$args_addon->set_transaction_type_callback(array($args_addon, 'parent_callback')); +$args_addon->validate_subscription_plans($feed_field, 'product'); +gf_paystack_test_check(count($args_addon->parent_args) === 2 && $args_addon->parent_args[1] === 'product', 'feed existing transactionType callback receives both arguments'); + +$obj_field = (object) array('name' => 'transactionType', 'choices' => array(array('label' => 'Subscription', 'value' => 'subscription'))); +$a = $feed_run(array('transactionType' => 'product'), array(), 'ok', null, $obj_field); +gf_paystack_test_check($a->field_errors === array('transactionType' => 'This field is required.'), 'feed object field choices are enforced'); +$a = $feed_run(array('transactionType' => 'subscription', 'mode' => 'test'), array('test_secret_key' => $st_rk_test), 'ok', null, $obj_field); +gf_paystack_test_check($a->field_errors === array() && $a->plans_calls === array($st_rk_test), 'feed object field accepts a listed choice'); + +$a = $feed_run(array('transactionType' => 'subscription'), array('api_mode' => 'test', 'test_secret_key' => $st_rk_test, 'live_secret_key' => $st_rk_live)); +gf_paystack_test_check($a->plans_calls === array($st_rk_test), 'feed without a mode follows the global api mode'); + +// Gravity Forms 2.5+ only records errors on field objects, so every error goes through set_setting_error(). +$plugin_src = file_get_contents(dirname(__DIR__) . '/class-gf-paystack.php'); +gf_paystack_test_check(substr_count($plugin_src, '->set_field_error(') === 1, 'set_field_error is only called from set_setting_error'); +$names = GFPaystackTestSettingsRenderer::defined_field_names(new GFPaystackSettingsFixture()); +$wanted = array('api_mode', 'test_secret_key', 'test_webhook_secret', 'live_secret_key', 'live_webhook_secret', 'transactionType'); +gf_paystack_test_check(!array_diff($wanted, $names), 'every field an error is raised on is a defined settings field: missing ' . implode(',', array_diff($wanted, $names))); +// metaData is added after Gravity Forms' own billingInformation field, which the stubs don't build. +gf_paystack_test_check(preg_match("/'name'\\s*=>\\s*'metaData'/", $plugin_src) === 1, 'metaData is a defined feed field'); + +// If a field can't be found, the credential error lands on the Mode field instead of being dropped. +$cred_lookup_fails = function ($posted, $stored = array()) { + $addon = new GFPaystackSettingsFixture(); + $addon->posted = $posted; + $addon->stored = $stored; + $addon->renderer_fields = array(); + $addon->validate_credentials(new GFPaystackTestSettingField('api_mode', $addon)); + + return $addon; +}; +$a = $cred_lookup_fails(array('api_mode' => 'test', 'test_secret_key' => $st_sk_test . 'x')); +gf_paystack_test_check(strpos($a->field_errors['api_mode'] ?? '', 'Use a test restricted key instead.') === 0, 'credentials: selected-mode key error falls back to Mode when its field is missing'); +$a = $cred_lookup_fails(array('api_mode' => 'test', 'live_secret_key' => $st_sk_live . 'x')); +gf_paystack_test_check(isset($a->field_errors['api_mode']), 'credentials: other-mode error falls back to Mode when fields are missing'); +$a = $cred_lookup_fails(array('api_mode' => 'test', 'test_secret_key' => $st_rk_test)); +gf_paystack_test_check(isset($a->field_errors['api_mode']), 'credentials: missing signing secret falls back to Mode'); + +$GLOBALS['gf_paystack_test_gf_logs'] = array(); +$a = new GFPaystackSettingsFixture(); +$a->renderer_fields = array(); +(function () { $this->set_setting_error('nope', 'x'); })->call($a); +gf_paystack_test_check($a->field_errors === array() && strpos(json_encode($GLOBALS['gf_paystack_test_gf_logs']), 'no settings field to attach an error to (nope)') !== false, 'an error with nowhere to go is logged, not silently dropped'); + +$a = $st_run('live', array('api_mode' => 'live', 'live_secret_key' => $st_rk_live, 'live_webhook_secret' => $st_ws_live), array(), function ($addon) { + $addon->verdict = array('code' => 'sensitive_scope', 'scopes' => array(), 'sensitive_scopes' => array(''), 'reason' => null, 'probes' => ''); +}); +gf_paystack_test_check(strpos($a->field_errors['live_secret_key'] ?? '', '<img') !== false && strpos($a->field_errors['live_secret_key'], 'posted = array('metaData' => $meta); + $addon->renderer_fields = $renderer_fields; + $addon->validate_custom_meta(new GFPaystackTestSettingField('metaData', $addon)); + + return $addon; +}; +$a = $meta_run(array_fill(0, 21, array('custom_key' => 'k', 'value' => '1'))); +gf_paystack_test_check(($a->field_errors['metaData'] ?? '') === 'You may only have 20 custom keys.', 'feed metadata over 20 keys is flagged on metaData'); +$a = $meta_run(array(array('custom_key' => '', 'value' => '3'))); +gf_paystack_test_check(strpos($a->field_errors['metaData'] ?? '', 'A field has been mapped to a custom key without a name.') === 0, 'feed metadata without a key name is flagged'); +$a = $meta_run(array(array('custom_key' => str_repeat('', 14), 'value' => '3'))); +gf_paystack_test_check(strpos($a->field_errors['metaData'] ?? '', '<b>') !== false && strpos($a->field_errors['metaData'], '') === false, 'feed metadata long key name is flagged and escaped'); +$a = $meta_run(array(array('custom_key' => '', 'value' => '3')), array()); +gf_paystack_test_check(isset($a->field_errors['metaData']), 'an error falls back to the validated field when the renderer cannot find it'); diff --git a/tests/test-webhook.php b/tests/test-webhook.php index 13df754..0569887 100644 --- a/tests/test-webhook.php +++ b/tests/test-webhook.php @@ -1,7 +1,7 @@ 'sk_test_secret', 'public_key' => 'pk')); +$webhook_api = new GFPaystackApi((object) array('secret_key' => 'sk_test_secret', 'public_key' => 'pk', 'stored_secret_key' => 'sk_test_secret')); $webhook_sig = hash_hmac('sha512', $webhook_body, 'sk_test_secret'); unset($_SERVER['HTTP_X_PAYSTACK_SIGNATURE']); @@ -44,8 +44,15 @@ $stored = array('paystack_mode' => 'live', 'paystack_tx_amount' => '5000', 'paystack_tx_currency' => 'NGN'); -$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored); -gf_paystack_test_check(is_array($result) && $result['type'] === 'complete_payment' && $result['entry_id'] === '7', 'callback case 1'); +$charge_api = function ($overrides = array()) { + $api = new GFPaystackRecordingApi(); + $api->response = array('status' => true, 'message' => 'ok', 'data' => array_merge(array('id' => 99, 'reference' => 'gf-7-abc', 'status' => 'success', 'amount' => 5000, 'currency' => 'NGN'), $overrides)); + return $api; +}; + +$verified_api = $charge_api(); +$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored, null, null, $verified_api); +gf_paystack_test_check(is_array($result) && $result['type'] === 'complete_payment' && $result['entry_id'] === '7' && $result['amount'] == 50 && $verified_api->calls === array('transaction/verify/gf-7-abc'), 'callback case 1'); $result = gf_paystack_callback_run(gf_paystack_charge_event(array('metadata' => array('entry_id' => '8'))), 'live', $stored); gf_paystack_test_check($result === false, 'callback case 2'); @@ -53,21 +60,65 @@ $result = gf_paystack_callback_run(gf_paystack_charge_event(), 'test', $stored); gf_paystack_test_check($result === false, 'callback case 3'); -$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', array('paystack_tx_amount' => '5000')); +$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', array('paystack_tx_amount' => '5000'), null, null, $charge_api()); gf_paystack_test_check(is_array($result) && $result['type'] === 'complete_payment', 'callback case 4'); $result = gf_paystack_callback_run(gf_paystack_charge_event(), 'test', array('paystack_tx_amount' => '5000')); gf_paystack_test_check($result === false, 'callback case 5'); -$result = gf_paystack_callback_run(gf_paystack_charge_event(array('amount' => 100)), 'live', $stored); +$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored, null, null, $charge_api(array('amount' => 100))); gf_paystack_test_check($result === false, 'callback case 6'); -$result = gf_paystack_callback_run(gf_paystack_charge_event(array('currency' => 'USD')), 'live', $stored); +$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored, null, null, $charge_api(array('currency' => 'USD'))); gf_paystack_test_check($result === false, 'callback case 7'); -$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', array()); +$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', array(), null, null, $charge_api()); gf_paystack_test_check(is_array($result) && $result['type'] === 'complete_payment', 'callback case 8'); +$result = gf_paystack_callback_run(gf_paystack_charge_event(array('amount' => 100, 'currency' => 'USD')), 'live', $stored, null, null, $charge_api()); +gf_paystack_test_check(is_array($result) && $result['type'] === 'complete_payment' && $result['amount'] == 50, 'callback case 29'); + +$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored, null, null, $charge_api(array('status' => 'failed'))); +gf_paystack_test_check($result === false, 'callback case 30'); + +$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored, null, null, $charge_api(array('id' => 100))); +gf_paystack_test_check($result === false, 'callback case 31'); + +$throwing_charge_api = $charge_api(); +$throwing_charge_api->throw = true; +$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored, null, null, $throwing_charge_api); +gf_paystack_test_check(is_wp_error($result) && $result->code === 'transaction_verification' && rgar($result->get_error_data(), 'status_header') === 500, 'callback case 32: verify throws asks Paystack to retry'); + +gf_paystack_test_check(is_wp_error($result) && $result->get_error_message() === 'Transaction could not be verified.' && strpos($result->get_error_message(), 'request failed') === false, 'callback case 32b: verify failure message is fixed'); + +$result = gf_paystack_callback_run(gf_paystack_charge_event(array('id' => '')), 'live', $stored, null, null, $charge_api(array('id' => ''))); +gf_paystack_test_check($result === false, 'callback case 33b: verified charge with an empty id is not completed'); + +$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored, null, null, $charge_api(array('id' => null))); +gf_paystack_test_check($result === false, 'callback case 33: verified charge without an id is not completed'); + +$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored, null, null, $charge_api(array('reference' => 'gf-7-other'))); +gf_paystack_test_check($result === false, 'callback case 34: verified reference mismatch is not completed'); + +$result = gf_paystack_callback_run(gf_paystack_charge_event(), 'live', $stored, null, null, $charge_api(array('reference' => null))); +gf_paystack_test_check($result === false, 'callback case 35: verified charge without a reference is not completed'); + +$sub_feed = array('is_active' => '1', 'meta' => array('mode' => 'live', 'transactionType' => 'subscription')); +$sub_charge = $charge_api(array('authorization' => array('authorization_code' => 'AUTH_verified'))); +$sub_event = gf_paystack_charge_event(); +$sub_event['data']['authorization'] = array('authorization_code' => 'AUTH_forged'); +$result = gf_paystack_callback_run($sub_event, 'live', $stored, $sub_feed, null, $sub_charge); +gf_paystack_test_check($sub_charge->calls === array('transaction/verify/gf-7-abc') && gform_get_meta('7', 'paystack_tx_auth_code') === 'AUTH_verified', 'callback case 36: subscription branch stores the verified authorization code'); + +$sub_forged = $charge_api(array('id' => 100, 'authorization' => array('authorization_code' => 'AUTH_verified'))); +gf_paystack_callback_run($sub_event, 'live', $stored, $sub_feed, null, $sub_forged); +gf_paystack_test_check(gform_get_meta('7', 'paystack_tx_auth_code') === false, 'callback case 37: subscription branch stores nothing when the verified id differs'); + +$sub_throwing = $charge_api(); +$sub_throwing->throw = true; +$result = gf_paystack_callback_run($sub_event, 'live', $stored, $sub_feed, null, $sub_throwing); +gf_paystack_test_check(is_wp_error($result) && rgar($result->get_error_data(), 'status_header') === 500 && gform_get_meta('7', 'paystack_tx_auth_code') === false, 'callback case 38: subscription verify throws asks Paystack to retry'); + $result = gf_paystack_callback_run(gf_paystack_charge_event(array('reference' => 'gf-7-unknown')), 'live', $stored); gf_paystack_test_check(is_wp_error($result) && $result->code === 'entry_not_found', 'callback case 9'); @@ -206,3 +257,265 @@ public function send_request($endpoint, $args = array(), $method = 'post', $doma $path_api = new GFPaystackPathRecordingApi((object) array('secret_key' => 'sk', 'public_key' => 'pk')); $path_api->verify_transaction('a/b?c#d'); gf_paystack_test_check($path_api->paths === array('transaction/verify/a%2Fb%3Fc%23d'), 'verify_transaction case 1'); + +// # Signing-secret (Paystack-Signature) verification +$whsec = 'whsec_' . str_repeat('ab12', 8); +$whsec_other = 'whsec_' . str_repeat('cd34', 8); +$sk_live = 'sk_live_abc123'; +$rk_live = 'rk_live_' . str_repeat('x', 20); +$reset_sig_headers = function () { + unset($_SERVER['HTTP_PAYSTACK_SIGNATURE'], $_SERVER['HTTP_X_PAYSTACK_SIGNATURE']); +}; +$reset_sig_headers(); +$sign = function ($t, $body, $secret, $kid = 'k1') { + return "v1={$kid}:" . hash_hmac('sha512', $t . '.' . $body, $secret); +}; +$whsec_api = function ($secret, $stored = '') { + return new GFPaystackApi((object) array('secret_key' => $stored, 'public_key' => 'pk', 'webhook_secret' => $secret, 'stored_secret_key' => $stored)); +}; +$now = 1800000000; +$bad_v1 = 'v1=k0:' . str_repeat('0', 128); + +$api = $whsec_api($whsec); +$t = (string) $now; +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t," . $sign($t, $webhook_body, $whsec), $now) === 'valid', 'whsec valid header'); +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, " t = $t , " . $sign($t, $webhook_body, $whsec), $now) === 'valid', 'whsec header whitespace trimmed'); +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t,$bad_v1," . $sign($t, $webhook_body, $whsec, 'k2'), $now) === 'valid', 'whsec rotated multi-v1, right one second'); +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t," . $sign($t, $webhook_body, $whsec) . ",$bad_v1", $now) === 'valid', 'whsec rotated multi-v1, right one first'); +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t,$bad_v1,$bad_v1", $now) === 'invalid', 'whsec all v1 wrong'); + +$t_old = (string) ($now - 301); +$t_edge = (string) ($now - 300); +$t_future = (string) ($now + 301); +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t_old," . $sign($t_old, $webhook_body, $whsec), $now) === 'stale', 'whsec stale t-301'); +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t_future," . $sign($t_future, $webhook_body, $whsec), $now) === 'stale', 'whsec future t+301'); +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t_edge," . $sign($t_edge, $webhook_body, $whsec), $now) === 'valid', 'whsec t-300 accepted'); +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t_old," . $bad_v1, $now) === 'invalid', 'whsec HMAC checked before window'); + +$good_v1 = $sign($t, $webhook_body, $whsec); +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t,t=$t,$good_v1", $now) === 'malformed', 'whsec two t values'); +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, $good_v1, $now) === 'malformed', 'whsec no t'); +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=12ab,$good_v1", $now) === 'malformed', 'whsec non-digit t'); +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=-5,$good_v1", $now) === 'malformed', 'whsec negative t'); +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t", $now) === 'malformed', 'whsec no v1'); +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t,v1=" . hash_hmac('sha512', $t . '.' . $webhook_body, $whsec), $now) === 'malformed', 'whsec v1 without kid'); +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t,v1=k1:abc", $now) === 'malformed', 'whsec v1 short hex'); +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, '', $now) === 'malformed', 'whsec empty header'); +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, array($good_v1), $now) === 'malformed', 'whsec non-string header'); + +$many = "t=$t," . str_repeat("$bad_v1,", 10) . $good_v1; +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, $many, $now) === 'invalid', 'whsec v1 entries beyond 10 ignored'); +$nine = "t=$t," . str_repeat("$bad_v1,", 9) . $good_v1; +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, $nine, $now) === 'valid', 'whsec 10th v1 entry counted'); + +gf_paystack_test_check($api->check_signing_secret_header('{"event":"charge.success","x":1}', "t=$t,$good_v1", $now) === 'invalid', 'whsec tampered body'); +gf_paystack_test_check($whsec_api($whsec_other)->check_signing_secret_header($webhook_body, "t=$t,$good_v1", $now) === 'invalid', 'whsec wrong secret'); +gf_paystack_test_check($whsec_api('')->check_signing_secret_header($webhook_body, "t=$t,$good_v1", $now) === 'malformed', 'whsec blank secret never verifies'); + +// validate_webhook(): header from $_SERVER, HMAC over the injected $input +$live_t = (string) time(); +$live_header = "t=$live_t," . $sign($live_t, $webhook_body, $whsec); +$_SERVER['HTTP_PAYSTACK_SIGNATURE'] = $live_header; +gf_paystack_test_check($whsec_api($whsec)->validate_webhook($webhook_body) === true, 'validate_webhook whsec via server header'); +$checked = $whsec_api($whsec); +$checked->validate_webhook($webhook_body); +gf_paystack_test_check($checked->last_webhook_check === array('sig' => 'whsec', 'result' => 'valid'), 'validate_webhook records whsec/valid'); +gf_paystack_test_check($whsec_api($whsec)->validate_webhook('{"event":"charge.success","amount":1}') === false, 'validate_webhook HMAC uses injected input, not signed body'); +$reset_sig_headers(); +gf_paystack_test_check($whsec_api($whsec)->validate_webhook($webhook_body) === false, 'validate_webhook whsec set, no header'); + +// whsec set: legacy header must not rescue a bad or missing Paystack-Signature +$legacy = hash_hmac('sha512', $webhook_body, $sk_live); +$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = $legacy; +gf_paystack_test_check($whsec_api($whsec, $sk_live)->validate_webhook($webhook_body) === false, 'whsec set + only valid legacy header rejected'); +$_SERVER['HTTP_PAYSTACK_SIGNATURE'] = "t=$live_t,$bad_v1"; +gf_paystack_test_check($whsec_api($whsec, $sk_live)->validate_webhook($webhook_body) === false, 'whsec set + bad header + valid legacy rejected'); +gf_paystack_test_check($whsec_api($whsec, $sk_live)->validate_webhook($webhook_body, $legacy) === false, 'whsec set + legacy passed explicitly rejected'); +$reset_sig_headers(); + +// rk stored without whsec is never an HMAC key +$rk_sig = hash_hmac('sha512', $webhook_body, $rk_live); +$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = $rk_sig; +gf_paystack_test_check($whsec_api('', $rk_live)->validate_webhook($webhook_body) === false, 'rk without whsec rejected despite rk-signed header'); +$rk_api = new GFPaystackApi((object) array('secret_key' => $rk_live, 'public_key' => 'pk', 'webhook_secret' => '', 'stored_secret_key' => $rk_live)); +gf_paystack_test_check($rk_api->validate_webhook($webhook_body, $rk_sig) === false, 'rk without whsec rejected with explicit signature'); +$reset_sig_headers(); + +// sk legacy path unchanged +$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = $legacy; +$sk_api = $whsec_api('', $sk_live); +gf_paystack_test_check($sk_api->validate_webhook($webhook_body) === true && $sk_api->last_webhook_check === array('sig' => 'legacy', 'result' => 'valid'), 'sk legacy path valid'); +gf_paystack_test_check($sk_api->validate_webhook('{"tampered":1}') === false, 'sk legacy path tampered body'); +$reset_sig_headers(); + +// get_webhook_event(): mode selection +$event_addon = function ($settings) { + $addon = new GFPaystackEventFixture(); + $addon->settings = $settings; + return $addon; +}; +$header_for = function ($body, $secret) use ($sign) { + $ts = (string) time(); + return "t=$ts," . $sign($ts, $body, $secret); +}; +$live_whsec = $whsec; +$test_whsec = $whsec_other; +$both = array('api_mode' => 'live', 'live_secret_key' => $rk_live, 'live_webhook_secret' => $live_whsec, 'test_secret_key' => 'rk_test_' . str_repeat('y', 20), 'test_webhook_secret' => $test_whsec); + +$event_body = json_encode(array('event' => 'charge.success', 'data' => array('reference' => 'gf-7-abc'))); +$_SERVER['HTTP_PAYSTACK_SIGNATURE'] = $header_for($event_body, $test_whsec); +$addon = $event_addon($both); +$event = $addon->get_webhook_event($event_body); +gf_paystack_test_check(is_array($event) && $addon->webhook_mode_value() === 'test', 'domain missing: verifies under the mode whose whsec matches (test)'); + +$_SERVER['HTTP_PAYSTACK_SIGNATURE'] = $header_for($event_body, $live_whsec); +$addon = $event_addon($both); +$event = $addon->get_webhook_event($event_body); +gf_paystack_test_check(is_array($event) && $addon->webhook_mode_value() === 'live', 'domain missing: verifies under the mode whose whsec matches (live)'); + +$_SERVER['HTTP_PAYSTACK_SIGNATURE'] = $header_for($event_body, 'whsec_' . str_repeat('ef56', 8)); +$addon = $event_addon($both); +gf_paystack_test_check($addon->get_webhook_event($event_body) === false, 'domain missing: no mode verifies'); +gf_paystack_test_check(count($addon->errors) === 1 && strpos($addon->errors[0], 'checks=live:whsec:invalid,test:whsec:invalid') !== false && strpos($addon->errors[0], $live_whsec) === false, 'failure logged at error level listing every attempt, no secret'); + +$domain_body = json_encode(array('event' => 'charge.success', 'data' => array('domain' => 'live', 'reference' => 'gf-7-abc'))); +$_SERVER['HTTP_PAYSTACK_SIGNATURE'] = $header_for($domain_body, $test_whsec); +$addon = $event_addon($both); +gf_paystack_test_check($addon->get_webhook_event($domain_body) === false, 'domain=live with a test-secret signature rejected (no cross-mode retry)'); + +$_SERVER['HTTP_PAYSTACK_SIGNATURE'] = $header_for($domain_body, $live_whsec); +$addon = $event_addon($both); +gf_paystack_test_check(is_array($addon->get_webhook_event($domain_body)) && $addon->webhook_mode_value() === 'live', 'domain=live verifies with live whsec'); + +$test_event_body = json_encode(array('event' => 'charge.success', 'data' => array('reference' => 'gf-7-abc'))); +$_SERVER['HTTP_PAYSTACK_SIGNATURE'] = $header_for($test_event_body, $test_whsec); +$addon = $event_addon($both); +$addon->get_webhook_event($test_event_body); +$GLOBALS['gf_paystack_test_entries'] = array('7' => array('id' => '7', 'form_id' => '1')); +$GLOBALS['gf_paystack_test_meta'] = array('7' => array('paystack_mode' => 'live')); +$matcher = new class extends GFPaystackEventFixture { + public function matches($entry) + { + return $this->webhook_mode_matches_entry($entry, array('meta' => array('mode' => 'live'))); + } + public function set_mode($mode) + { + $this->webhook_mode = $mode; + } +}; +$matcher->set_mode($addon->webhook_mode_value()); +gf_paystack_test_check($matcher->matches(array('id' => '7')) === false, 'test-signed event cannot match a live entry'); + +// sk merchant without whsec: legacy path through get_webhook_event, mode from domain or sk presence +$sk_settings = array('api_mode' => 'live', 'live_secret_key' => $sk_live); +$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', $event_body, $sk_live); +$addon = $event_addon($sk_settings); +gf_paystack_test_check(is_array($addon->get_webhook_event($event_body)) && $addon->webhook_mode_value() === 'live', 'sk legacy via get_webhook_event, domain missing'); +$reset_sig_headers(); + +// domain missing, no whsec: the configured api mode decides, as before +$both_sk = array('api_mode' => 'test', 'live_secret_key' => $sk_live, 'test_secret_key' => 'sk_test_abc123'); +$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', $event_body, $sk_live); +$addon = $event_addon($both_sk); +gf_paystack_test_check($addon->get_webhook_event($event_body) === false && $addon->webhook_mode_value() === 'test' && strpos($addon->errors[0], 'checks=test:legacy:invalid') !== false, 'domain missing, no whsec: api mode only, no sk try-both'); +$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', $event_body, 'sk_test_abc123'); +gf_paystack_test_check(is_array($event_addon($both_sk)->get_webhook_event($event_body)), 'domain missing, no whsec: api mode key verifies'); + +$one_whsec = array('api_mode' => 'live', 'live_secret_key' => $sk_live, 'test_secret_key' => 'sk_test_abc123', 'test_webhook_secret' => $test_whsec); +$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', $event_body, 'sk_other'); +$addon = $event_addon($one_whsec); +gf_paystack_test_check($addon->get_webhook_event($event_body) === false && $addon->webhook_mode_value() === 'live' && strpos($addon->errors[0], 'checks=test:whsec:malformed') !== false && strpos($addon->errors[0], 'live:legacy:invalid') !== false, 'domain missing: whsec modes first, then the api mode'); + +$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', $event_body, $sk_live); +$addon = $event_addon($one_whsec); +gf_paystack_test_check(is_array($addon->get_webhook_event($event_body)) && $addon->webhook_mode_value() === 'live', 'domain missing: whsec in test, api mode live still verifies a legacy-signed event'); +$reset_sig_headers(); + +// ?secret= must not change the verifying key +$_GET['secret'] = 'sk_live_attacker'; +$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', $event_body, 'sk_live_attacker'); +$addon = $event_addon($sk_settings); +gf_paystack_test_check($addon->get_webhook_event($event_body) === false, '?secret= does not reach webhook verification'); +$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', $event_body, $sk_live); +gf_paystack_test_check(is_array($event_addon($sk_settings)->get_webhook_event($event_body)), '?secret= present, stored sk still verifies'); +unset($_GET['secret']); + +// no whsec, no sk: rejected +$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', $event_body, $rk_live); +gf_paystack_test_check($event_addon(array('api_mode' => 'live', 'live_secret_key' => $rk_live))->get_webhook_event($event_body) === false, 'rk only, no whsec: get_webhook_event rejects'); +$reset_sig_headers(); + +// ?secret= must not reach Paystack calls +$_GET['secret'] = 'sk_live_attacker'; +$_GET['public'] = 'pk_live_attacker'; +$GLOBALS['gf_paystack_test_caps'] = array('update_core'); +$read_prop = function ($api, $prop) { + return (function () use ($prop) { + return $this->$prop; + })->call($api); +}; +$qs_addon = $event_addon(array('api_mode' => 'live', 'live_secret_key' => $sk_live)); +$qs_api = $qs_addon->paystack_api(); +gf_paystack_test_check($read_prop($qs_api, 'secret_key') === $sk_live, '?secret= ignored when building the API client'); +unset($_GET['secret'], $_GET['public'], $GLOBALS['gf_paystack_test_caps']); + +// # Coverage additions (dedicated test pass) + +// Legacy HMAC key is the stored sk, never the (possibly overridden) API-call key. +$legacy_cfg = new GFPaystackApi((object) array('secret_key' => 'sk_live_callkey', 'public_key' => 'pk', 'stored_secret_key' => $sk_live)); +gf_paystack_test_check($legacy_cfg->validate_webhook($webhook_body, hash_hmac('sha512', $webhook_body, $sk_live)) === true, 'legacy HMAC verifies with the stored sk'); +gf_paystack_test_check($legacy_cfg->validate_webhook($webhook_body, hash_hmac('sha512', $webhook_body, 'sk_live_callkey')) === false, 'legacy HMAC does not verify with the API-call key'); + +// The fallthrough path records why it rejected. +$none_api = $whsec_api('', $rk_live); +$none_api->validate_webhook($webhook_body, 'x'); +gf_paystack_test_check($none_api->last_webhook_check === array('sig' => 'none', 'result' => 'invalid'), 'validate_webhook records none/invalid when neither whsec nor sk is configured'); +$legacy_bad = $whsec_api('', $sk_live); +$legacy_bad->validate_webhook($webhook_body, 'deadbeef'); +gf_paystack_test_check($legacy_bad->last_webhook_check === array('sig' => 'legacy', 'result' => 'invalid'), 'validate_webhook records legacy/invalid'); +$whsec_bad = $whsec_api($whsec); +$whsec_bad->validate_webhook($webhook_body, null, "t=$t,$bad_v1"); +gf_paystack_test_check($whsec_bad->last_webhook_check['sig'] === 'whsec' && $whsec_bad->last_webhook_check['result'] === 'invalid', 'validate_webhook records whsec result for an explicit signing header'); + +// Header parsing details +$hdr_notices = array(); +set_error_handler(function ($no, $str) use (&$hdr_notices) { + $hdr_notices[] = $str; + + return true; +}); +$junk_result = $api->check_signing_secret_header($webhook_body, "junk,t=$t,$good_v1", $now); +restore_error_handler(); +gf_paystack_test_check($junk_result === 'valid' && $hdr_notices === array(), 'whsec header part without = is ignored silently'); +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t,v1=:" . hash_hmac('sha512', $t . '.' . $webhook_body, $whsec), $now) === 'malformed', 'whsec v1 with empty kid is malformed'); +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t,v1=k1:" . str_repeat('a', 64), $now) === 'malformed', 'whsec v1 with 64 hex chars is malformed'); +gf_paystack_test_check($api->check_signing_secret_header($webhook_body, "t=$t,v1=k1:" . strtoupper(hash_hmac('sha512', $t . '.' . $webhook_body, $whsec)), $now) === 'valid', 'whsec uppercase hex signature is accepted'); + +// Settings values are trimmed before they become secrets +$ws_padded = array('api_mode' => 'live', 'live_secret_key' => $rk_live, 'live_webhook_secret' => " $whsec \n"); +$_SERVER['HTTP_PAYSTACK_SIGNATURE'] = $header_for($event_body, $whsec); +gf_paystack_test_check(is_array($event_addon($ws_padded)->get_webhook_event($event_body)), 'whsec read from settings is trimmed'); +$reset_sig_headers(); +$_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] = hash_hmac('sha512', $event_body, $sk_live); +gf_paystack_test_check(is_array($event_addon(array('api_mode' => 'live', 'live_secret_key' => "$sk_live \n"))->get_webhook_event($event_body)), 'stored sk read from settings is trimmed for the legacy HMAC'); +$reset_sig_headers(); + +// A validator that throws becomes a WP_Error +class GFPaystackThrowingValidatorApi extends GFPaystackApi +{ + public function validate_webhook($input, $signature = null, $signing_header = null) + { + throw new Exception('validator down'); + } +} +class GFPaystackThrowingValidatorAddon extends GFPaystackEventFixture +{ + public function paystack_api($mode = null, $settings = null) + { + return $this->paystack_api = new GFPaystackThrowingValidatorApi((object) array()); + } +} +$throwing_addon = new GFPaystackThrowingValidatorAddon(); +$throwing_addon->settings = array('api_mode' => 'live', 'live_secret_key' => $sk_live); +$throw_result = $throwing_addon->get_webhook_event($event_body); +gf_paystack_test_check(is_wp_error($throw_result) && $throw_result->code === 'Webhook Validation Failed' && $throw_result->message === 'validator down' && count($throwing_addon->errors) === 1, 'webhook validator exception returns a WP_Error and is logged');