Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
91.58% covered (success)
91.58%
87 / 95
55.56% covered (warning)
55.56%
5 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
Settings
93.55% covered (success)
93.55%
87 / 93
55.56% covered (warning)
55.56%
5 / 9
41.45
0.00% covered (danger)
0.00%
0 / 1
 init
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 register_routes
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
1
 get_settings
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
6
 update_settings
96.43% covered (success)
96.43%
27 / 28
0.00% covered (danger)
0.00%
0 / 1
15
 sanitize_ip_lists
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
6
 get_monitor_notifications
76.92% covered (warning)
76.92%
10 / 13
0.00% covered (danger)
0.00%
0 / 1
5.31
 get_waf_keys
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 wpcom_fault_message
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 error
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2/**
3 * Protect dashboard: the settings its toggles read and save.
4 *
5 * @package automattic/jetpack-protect
6 */
7
8namespace Automattic\Jetpack\Protect;
9
10use Automattic\Jetpack\Connection\Manager as Connection_Manager;
11use Automattic\Jetpack\Connection\SSO\Helpers as SSO_Helpers;
12use Automattic\Jetpack\Modules;
13use Automattic\Jetpack\Monitor\Monitor;
14use Automattic\Jetpack\Protect\Sections\Firewall;
15use Automattic\Jetpack\Waf\REST_Controller as Waf_REST_Controller;
16use Automattic\Jetpack\Waf\Waf_Runner;
17use WP_Error;
18use WP_REST_Request;
19use WP_REST_Server;
20
21if ( ! defined( 'ABSPATH' ) ) {
22    exit( 0 );
23}
24
25/**
26 * A flat settings route covering only the dashboard's keys, so the page works without the Jetpack plugin's `jetpack/v4/settings`.
27 *
28 * @since 0.7.0
29 */
30class Settings {
31
32    /**
33     * Modules the dashboard can switch on and off.
34     *
35     * @var string[]
36     */
37    const MODULES = array( 'waf', 'protect', 'account-protection', 'monitor', 'sso' );
38
39    /**
40     * Monitor's per-user email setting, which lives on WordPress.com.
41     *
42     * @var string
43     */
44    const MONITOR_NOTIFICATIONS = 'monitor_receive_notifications';
45
46    /**
47     * Prefix of the per-user transient set while WordPress.com can't answer for that setting.
48     *
49     * @var string
50     */
51    const MONITOR_NOTIFICATIONS_FAILED = 'jetpack_protect_monitor_notifications_failed_';
52
53    /**
54     * IXR error codes the client sets itself, for transport and parse failures, rather than WordPress.com.
55     *
56     * @var int[]
57     */
58    const IXR_CLIENT_ERRORS = array( -10520, -32300, -32700 );
59
60    /**
61     * SSO's options, saved locally as 0 or 1, each with the SSO helper that reads its value in effect.
62     *
63     * @var string[]
64     */
65    const SSO_OPTIONS = array(
66        'jetpack_sso_match_by_email'   => 'match_by_email',
67        'jetpack_sso_require_two_step' => 'is_two_step_required',
68    );
69
70    /**
71     * Firewall options, saved through the WAF package's own handler.
72     *
73     * @var string[]
74     */
75    const WAF_OPTIONS = array(
76        'jetpack_waf_automatic_rules',
77        'jetpack_waf_ip_allow_list',
78        'jetpack_waf_ip_allow_list_enabled',
79        'jetpack_waf_ip_block_list',
80        'jetpack_waf_ip_block_list_enabled',
81        'jetpack_waf_share_data',
82        'jetpack_waf_share_debug_data',
83    );
84
85    /**
86     * Wire the hooks.
87     *
88     * @return void
89     */
90    public static function init() {
91        add_action( 'rest_api_init', array( __CLASS__, 'register_routes' ) );
92    }
93
94    /**
95     * Register the settings route.
96     *
97     * @return void
98     */
99    public static function register_routes() {
100        register_rest_route(
101            'jetpack/v4',
102            '/protect-dashboard/settings',
103            array(
104                array(
105                    'methods'             => WP_REST_Server::READABLE,
106                    'callback'            => array( __CLASS__, 'get_settings' ),
107                    'permission_callback' => array( Dashboard::class, 'can_manage' ),
108                ),
109                array(
110                    'methods'             => WP_REST_Server::EDITABLE,
111                    'callback'            => array( __CLASS__, 'update_settings' ),
112                    'permission_callback' => array( Dashboard::class, 'can_manage' ),
113                ),
114            )
115        );
116    }
117
118    /**
119     * Every supported key and its current value; keys for features this site can't run are left out.
120     *
121     * @return array
122     */
123    public static function get_settings() {
124        $modules  = new Modules();
125        $settings = array();
126
127        foreach ( self::MODULES as $module ) {
128            if ( $modules->is_module( $module ) ) {
129                $settings[ $module ] = $modules->is_active( $module );
130            }
131        }
132
133        if ( ! empty( $settings['monitor'] ) ) {
134            $settings[ self::MONITOR_NOTIFICATIONS ] = self::get_monitor_notifications();
135        }
136
137        if ( isset( $settings['sso'] ) ) {
138            // The helpers apply the constant and filters that can force a value, which the dashboard then shows as locked.
139            foreach ( self::SSO_OPTIONS as $option => $helper ) {
140                $settings[ $option ] = (bool) call_user_func( array( SSO_Helpers::class, $helper ) );
141            }
142        }
143
144        $settings = array_merge( $settings, self::get_waf_keys() );
145
146        return $settings;
147    }
148
149    /**
150     * Save the given keys, then return every setting.
151     *
152     * @param WP_REST_Request $request The request; its JSON body is the patch.
153     * @return array|WP_Error
154     */
155    public static function update_settings( $request ) {
156        $patch = self::sanitize_ip_lists( (array) $request->get_json_params() );
157        if ( $patch instanceof WP_Error ) {
158            return $patch;
159        }
160        $modules = new Modules();
161
162        foreach ( array_intersect( self::MODULES, array_keys( $patch ) ) as $module ) {
163            if ( ! $modules->is_module( $module ) ) {
164                return self::error( 'module_unavailable', $module );
165            }
166        }
167
168        foreach ( $patch as $key => $value ) {
169            if ( in_array( $key, self::MODULES, true ) ) {
170                if ( $value ) {
171                    $modules->activate( $key, false, false );
172                } else {
173                    $modules->deactivate( $key );
174                }
175                // deactivate() returns false when nothing changed, and a filter can force a module on, so check the outcome.
176                if ( $modules->is_active( $key ) !== (bool) $value ) {
177                    return self::error( 'module_update_failed', $key );
178                }
179            } elseif ( isset( self::SSO_OPTIONS[ $key ] ) && $modules->is_module( 'sso' ) ) {
180                // An integer, because update_option() won't create an option whose value is `false`.
181                update_option( $key, (int) (bool) $value );
182            } elseif ( self::MONITOR_NOTIFICATIONS === $key ) {
183                $result = Monitor::set_notifications( (bool) $value );
184                if ( true !== $result ) {
185                    return self::error( 'monitor_notifications_failed', $key, self::wpcom_fault_message( $result ) );
186                }
187            }
188        }
189
190        $waf_patch = array_intersect_key( $patch, self::get_waf_keys() );
191        if ( $waf_patch && class_exists( Waf_REST_Controller::class ) ) {
192            $waf_request = new WP_REST_Request( 'POST' );
193            $waf_request->set_body_params( $waf_patch );
194            $result = Waf_REST_Controller::update_waf( $waf_request );
195            if ( is_wp_error( $result ) ) {
196                return $result;
197            }
198        }
199
200        return self::get_settings();
201    }
202
203    /**
204     * Check the IP lists as `jetpack/v4/settings` did, before anything is saved, and return the patch with them escaped.
205     *
206     * @param array $patch The requested changes.
207     * @return array|WP_Error
208     */
209    private static function sanitize_ip_lists( $patch ) {
210        foreach ( array( 'jetpack_waf_ip_allow_list', 'jetpack_waf_ip_block_list' ) as $key ) {
211            if ( ! array_key_exists( $key, $patch ) ) {
212                continue;
213            }
214            if ( ! is_string( $patch[ $key ] ) ) {
215                /* translators: %s is a setting name. */
216                return self::error( 'rest_invalid_param', $key, sprintf( __( '%s must be a string.', 'jetpack-protect-pkg' ), $key ) );
217            }
218            // The firewall reads the stored copy, so check the list as it will be stored.
219            $patch[ $key ] = esc_textarea( $patch[ $key ] );
220            if ( 'jetpack_waf_ip_block_list' === $key ) {
221                $valid = Firewall::validate_ip_block_list( $patch[ $key ] );
222                if ( is_wp_error( $valid ) ) {
223                    return self::error( 'rest_invalid_param', $key, $valid->get_error_message() );
224                }
225            }
226        }
227        return $patch;
228    }
229
230    /**
231     * Whether the current user gets downtime emails: the local copy, or else WordPress.com's answer, which is then saved.
232     *
233     * @return bool
234     */
235    private static function get_monitor_notifications() {
236        $user_id = get_current_user_id();
237        $value   = get_option( Monitor::notifications_copy_option_name( $user_id ), 'does_not_exist' );
238        if ( 'does_not_exist' !== $value ) {
239            return (bool) $value;
240        }
241
242        $failed_key = self::MONITOR_NOTIFICATIONS_FAILED . $user_id;
243        if ( ! ( new Connection_Manager() )->is_user_connected() || get_transient( $failed_key ) ) {
244            return false;
245        }
246
247        $value = Monitor::user_receives_notifications();
248        // Not saved, since the user may not be connected yet; the transient only stops a remote call on every load.
249        if ( is_wp_error( $value ) ) {
250            set_transient( $failed_key, 1, 5 * MINUTE_IN_SECONDS );
251            return false;
252        }
253
254        Monitor::save_notifications_copy( $value );
255        return (bool) $value;
256    }
257
258    /**
259     * The firewall settings the dashboard edits, with their values; get_config() also returns server paths.
260     *
261     * @return array
262     */
263    private static function get_waf_keys() {
264        if ( ! class_exists( Waf_Runner::class ) ) {
265            return array();
266        }
267        return array_intersect_key( Waf_Runner::get_config(), array_flip( self::WAF_OPTIONS ) );
268    }
269
270    /**
271     * WordPress.com's own reason for refusing a call, or '' for a transport or parse failure, whose text is untranslated client detail.
272     *
273     * @param mixed $result What the IXR call returned.
274     * @return string
275     */
276    private static function wpcom_fault_message( $result ) {
277        if ( ! is_wp_error( $result ) || in_array( $result->get_error_code(), self::IXR_CLIENT_ERRORS, true ) ) {
278            return '';
279        }
280        return $result->get_error_message();
281    }
282
283    /**
284     * A 400 error naming the key that could not be saved, with any reason also under `params`, where core's `rest_invalid_param` puts it.
285     *
286     * @param string $code   Error code.
287     * @param string $key    The setting.
288     * @param string $reason Why it was refused, if known.
289     * @return WP_Error
290     */
291    private static function error( $code, $key, $reason = '' ) {
292        /* translators: %s is a setting name. */
293        $message = sprintf( __( 'The "%s" setting couldn’t be saved.', 'jetpack-protect-pkg' ), $key );
294        $data    = array( 'status' => 400 );
295        if ( '' !== $reason ) {
296            $message       .= ' ' . $reason;
297            $data['params'] = array( $key => $reason );
298        }
299        return new WP_Error( $code, $message, $data );
300    }
301}