settings = Plugin::get_settings( 'security' );
add_filter( 'adminease_settings_fields', [ $this, 'adminease_settings_fields' ] );
add_filter( 'adminease_settings_fields', [ $this, 'remove_duplicate_routes_field' ], 99 );
add_filter( 'adminease_validate_settings', [ $this, 'validate_settings' ], 20, 1 );
if( !empty( $this->settings['disable_rest_api'] ) ) {
remove_action( 'xmlrpc_rsd_apis', 'rest_output_rsd' );
remove_action( 'wp_head', 'rest_output_link_wp_head', 10 );
remove_action( 'template_redirect', 'rest_output_link_header', 11 );
add_filter( 'rest_authentication_errors', [ $this, 'check_rest_access' ], 110 );
}
if( !empty( $this->settings['hide_rest_index'] ) ) {
add_filter( 'rest_authentication_errors', [ $this, 'hide_rest_index' ], 110 );
}
}
/**
* Modifies or appends custom settings fields to the existing settings array.
*
* @param array $fields The existing array of settings fields.
*
* @return array The updated array of settings fields with modifications or additions.
*/
public function adminease_settings_fields( array $fields ): array {
$fields['security']['fields'][] = [
'type' => 'switch',
'id' => 'disable-rest-api',
'name' => 'adminease[security][disable_rest_api]',
'value' => $this->settings['disable_rest_api'] ?? false,
'label_class' => 'pwp-switch',
'input_class' => 'pwp-field-input toggle-field',
'label' => __( 'Disable REST API', 'adminease' ),
'risk' => 'careful',
'breaks' => __( 'Plugins, themes and apps that use the REST API can stop working.', 'adminease' ),
'description' => __( "The WordPress REST API allows external applications and services to interact with your website’s data, such as posts, users, and settings. While it’s useful for developers building custom features or apps, it can also expose sensitive information(!) especially on sites that don’t need it. Disabling the REST API helps reduce potential security risks and protect user privacy. You can disable it completely or restrict access to logged-in users using code or a security plugin.", 'adminease' ),
'conflicts' => [
'contact-form-7/wp-contact-form-7.php' => __( 'Contact Form 7 sends its forms through the REST API. Turning this on can stop the forms from sending.', 'adminease' ),
'woocommerce/woocommerce.php' => __( 'WooCommerce uses the REST API for parts of the admin. Turning this on can break them. The routes the block Cart and Checkout use stay open for visitors.', 'adminease' ),
'jetpack/jetpack.php' => __( 'Jetpack uses the REST API to connect to WordPress.com. Turning this on can disconnect it.', 'adminease' ),
],
'child_fields' => [
[
'type' => 'switch',
'id' => 'enable-rest-api-loggedin',
'name' => 'adminease[security][enable_rest_api_loggedin]',
'value' => $this->settings['enable_rest_api_loggedin'] ?? false,
'label_class' => 'pwp-switch',
'input_class' => 'pwp-field-input',
'label' => __( 'Also allow other logged-in users (customers, members)', 'adminease' ),
'description' => __( 'Allows logged-in users to keep using the REST API while all anonymous requests remain blocked. Outgoing communication with wordpress.org — plugin and theme updates, version checks — is unaffected by this setting either way.', 'adminease' ),
'field_description' => __( "Note: Users who can edit posts always keep REST API access, so Gutenberg, Elementor and the media library keep working in wp-admin. Enable this option to let every other logged-in user, such as customers or members, keep using it too.", 'adminease' ),
'attributes' => [
'data-parent' => 'disable-rest-api',
],
],
[
'type' => 'select',
'id' => 'disable-rest-api-allowed-roles',
'name' => 'adminease[security][disable_rest_api_allowed_roles][]',
'value' => $this->get_saved_allowed_roles(),
'options' => Utils::get_user_roles_options(),
'label_class' => 'pwp-field-label',
'input_class' => 'pwp-field-input adminease-choices',
'wrapper_class' => 'form-group-child',
'label' => __( 'Roles that keep REST API access (optional)', 'adminease' ),
'field_description' => __( 'Logged-in users with one of these roles keep using the REST API, for example Customer. Every other role is blocked, except on the always-allowed routes below. Users who can edit posts always keep access. Not needed when the switch above lets every logged-in user in.', 'adminease' ),
'attributes' => [
'multiple' => 'multiple',
'data-allow_clear' => true,
'data-parent' => 'disable-rest-api',
],
],
[
'type' => 'textarea',
'id' => 'disable-rest-api-excluded-routes',
'name' => 'adminease[security][disable_rest_api_excluded_routes]',
'value' => str_replace( ' ', PHP_EOL, (string) ( $this->settings['disable_rest_api_excluded_routes'] ?? '' ) ),
'label_class' => 'pwp-field-label',
'input_class' => 'pwp-field-input',
'wrapper_class' => 'form-group-child',
'label' => __( 'Always-allowed REST routes (optional)', 'adminease' ),
'field_description' => __( 'REST routes that stay reachable even while the API is disabled, one per line. Both /wp/v2/posts and the full /wp-json/wp/v2/posts are accepted. A route is matched as a prefix, so /wc/v3/ allows everything in that namespace. The batch route and the whole REST API cannot be listed, and the list can hold at most 50 routes. Useful for webhooks and form plugins. Comments are not supported - list routes only.', 'adminease' ),
'attributes' => [
'data-parent' => 'disable-rest-api',
'rows' => '5',
'placeholder' => esc_html__( 'Examples:', 'adminease' ) . "\n/contact-form-7/v1/\n/wp-json/wp/v2/posts\n/wp-json/wc",
],
],
],
];
$fields['security']['fields'][] = [
'type' => 'switch',
'id' => 'hide-rest-index',
'name' => 'adminease[security][hide_rest_index]',
'value' => $this->settings['hide_rest_index'] ?? false,
'label_class' => 'pwp-switch',
'input_class' => 'pwp-field-input',
'label' => __( 'Hide the REST API route list', 'adminease' ),
'description' => __( "Hides the list of all API addresses at /wp-json/ from visitors who are not logged in, so they can't see which plugins you use. Each plugin's own API keeps working. Not needed when Disable REST API is on.", 'adminease' ),
];
return $fields;
}
/**
* Drops a second always-allowed routes box when an older AdminEase Pro has added its own.
*
* @param array $fields The settings fields array.
*
* @return array The settings fields array with one routes box.
*/
public function remove_duplicate_routes_field( array $fields ): array {
foreach( $fields['security']['fields'] ?? [] as $key => $field ) {
if( empty( $field['child_fields'] ) || !is_array( $field['child_fields'] ) ) {
continue;
}
$seen = false;
foreach( $field['child_fields'] as $child_key => $child ) {
if( 'disable-rest-api-excluded-routes' !== ( $child['id'] ?? '' ) ) {
continue;
}
if( $seen ) {
unset( $fields['security']['fields'][ $key ]['child_fields'][ $child_key ] );
}
$seen = true;
}
}
return $fields;
}
/**
* Checks and manages access to the WordPress REST API based on plugin settings and user authentication.
*
* @param mixed $result The current REST API access result. Default null or pre-existing authentication error.
*
* @return mixed The modified access result, which may be a WP_Error if access is disabled, or the original result if no restrictions apply.
*/
public function check_rest_access( $result ) {
if( is_wp_error( $result ) ) {
return $result;
}
if( apply_filters( 'adminease_disable_rest_api_bypass', false ) ) {
return $result;
}
if( $this->is_route_excluded() ) {
return $result;
}
if( current_user_can( 'edit_posts' ) ) {
return $result;
}
if( !empty( $this->settings['enable_rest_api_loggedin'] ) && is_user_logged_in() ) {
return $result;
}
if( class_exists( 'WooCommerce' ) && Utils::rest_route_is_under( Utils::current_rest_route(), 'wc/store' ) ) {
return $result;
}
if( $this->user_has_allowed_role() ) {
return $result;
}
if( !empty( $this->settings['disable_rest_api'] ) ) {
return new WP_Error(
'rest_api_disabled',
esc_html__( 'REST API is disabled.', 'adminease' ),
[ 'status' => 403 ]
);
}
return $result;
}
/**
* Reads the roles chosen to keep REST API access, as a clean list of role names.
*
* @return string[] Role names. Empty when none are chosen, which is also what a site saved before this field existed has.
*/
private function get_saved_allowed_roles(): array {
$saved = $this->settings['disable_rest_api_allowed_roles'] ?? [];
if( !is_array( $saved ) ) {
return [];
}
return array_values( array_filter( array_map( 'strval', array_filter( $saved, 'is_scalar' ) ) ) );
}
/**
* Whether the current user holds at least one of the roles chosen to keep REST API access.
*
* @return bool False for a visitor, and when no role is chosen.
*/
private function user_has_allowed_role(): bool {
$allowed = $this->get_saved_allowed_roles();
$user = wp_get_current_user();
if( empty( $allowed ) || !$user->exists() ) {
return false;
}
return [] !== array_intersect( $allowed, (array) $user->roles );
}
/**
* Answers the REST API index, the list of every route, with a 401 for visitors who are not logged in.
*
* @param mixed $result The current REST API access result. Default null or pre-existing authentication error.
*
* @return mixed A WP_Error for a visitor asking for the index, otherwise the result unchanged.
*/
public function hide_rest_index( $result ) {
if( is_wp_error( $result ) || is_user_logged_in() ) {
return $result;
}
if( '/' !== Utils::current_rest_route() ) {
return $result;
}
return new WP_Error(
'adminease_rest_index_disabled',
esc_html__( 'The REST API route list is not available.', 'adminease' ),
[ 'status' => 401 ]
);
}
/**
* Checks the REST route being served against the configured route allowlist.
*
* Reads the route through Utils::current_rest_route(), which holds the same lowercase,
* slash-trimmed route ('/wp/v2/posts') whether the request arrived as /wp-json/wp/v2/posts
* or as ?rest_route=/wp/v2/posts, and folds away the spellings WordPress also serves (capital
* letters, trailing slashes and line breaks). Matching is on a path boundary, so listing
* '/wc' allows '/wc/v3/orders' but not '/wcfoo'. The REST index is never allowed through.
*
* @return bool True when the requested route must bypass the REST API block.
*/
private function is_route_excluded(): bool {
$excluded_routes = self::parse_excluded_routes( str_replace( ' ', PHP_EOL, (string) ( $this->settings['disable_rest_api_excluded_routes'] ?? '' ) ) )['routes'];
if( empty( $excluded_routes ) ) {
return false;
}
$current_route = Utils::current_rest_route();
if( '' === $current_route || '/' === $current_route ) {
return false;
}
foreach( $excluded_routes as $route ) {
if( Utils::rest_route_is_under( $current_route, $route ) ) {
return true;
}
}
return false;
}
/**
* Refuses unusable entries in the excluded-routes box when settings are saved, and names them.
*
* Runs at priority 20. The parameter is untyped because other
* callbacks on this filter may return an error.
*
* @param mixed $sanitized_settings The settings about to be saved.
*
* @return mixed The settings, or a WP_Error naming the entries that cannot be used.
*/
public function validate_settings( $sanitized_settings ) {
if( !is_array( $sanitized_settings ) || ! isset( $sanitized_settings['security']['disable_rest_api_excluded_routes'] ) ) {
return $sanitized_settings;
}
$parsed = self::parse_excluded_routes( (string) $sanitized_settings['security']['disable_rest_api_excluded_routes'] );
if( empty( $parsed['rejected'] ) ) {
return $sanitized_settings;
}
$url_prefix = strtolower( trim( function_exists( 'rest_get_url_prefix' ) ? rest_get_url_prefix() : 'wp-json', '/' ) );
$index = [];
$others = [];
foreach( $parsed['rejected'] as $entry ) {
$bare = strtolower( trim( $entry, '/' ) );
if( '' === $bare || $bare === $url_prefix ) {
$index[] = $entry;
}
else {
$others[] = $entry;
}
}
$show = function( array $entries ): array {
return array_map(
function( $entry ) {
return esc_html( mb_substr( $entry, 0, 60 ) );
},
array_slice( $entries, 0, 5 )
);
};
$messages = [];
if( !empty( $index ) ) {
$messages[] = sprintf(
/* translators: %s: the entries that stand for the whole REST API, separated by commas. */
esc_html__( '%s is the REST index (the list of all routes), so it cannot be listed. List routes under it instead, such as /wp/v2/types or /wc/v3.', 'adminease' ),
implode( ', ', $show( $index ) )
);
}
if( !empty( $others ) ) {
$messages[] = sprintf(
/* translators: %s: the entries that cannot be used, separated by commas. */
esc_html__( 'These always-allowed REST routes cannot be used: %s. Routes must be plain paths such as /wc/v3, the batch route cannot be listed, and the list can hold at most 50 routes.', 'adminease' ),
implode( ', ', $show( $others ) )
);
}
return new WP_Error( 'disable_rest_api_excluded_routes', implode( ' ', $messages ) );
}
/**
* Parses the excluded-routes textarea value into a clean list of route prefixes.
* - Splits on any whitespace, lowercases, and skips empty entries and repeats.
* - Strips the REST URL prefix ('/wp-json') when present, and the slashes around the route.
* - Rejects the whole API ('/' or '/wp-json'), the batch route, entries with characters a
* route cannot hold, and anything past the 50th entry.
*
* The prefix strip is what makes the field behave the way people actually use it. Matching
* happens against a route that has no '/wp-json' on the front, but the obvious thing to
* paste into this box is the URL being tested, '/wp-json/wp/v2/posts'. Both forms are accepted.
*
* The batch route is refused because WordPress runs its sub-requests without any
* authentication check, so allowing it would open every batch-enabled route to visitors.
* Entries are checked again every time they are read, because the stored value can come
* from an import or a hand-edited option as well as from the settings screen.
*
* Comment lines are not supported, and this is why: the setting is not registered in
* Plugin::should_sanitize_textarea(), so sanitize_text_field()
* collapses its newlines into spaces. That round trip is lossless for routes, which cannot
* contain a space, but a comment would be split on its own spaces and each word would
* become a live allowlist entry.
*
* @param string $raw The raw textarea value (one route per line, or space-separated).
*
* @return array{routes: string[], rejected: string[]} The usable route prefixes without slashes, and the entries that were refused.
*/
public static function parse_excluded_routes( string $raw ): array {
$routes = [];
$rejected = [];
$url_prefix = function_exists( 'rest_get_url_prefix' ) ? rest_get_url_prefix() : 'wp-json';
$url_prefix = strtolower( trim( $url_prefix, '/' ) );
$entries = preg_split( '/\s+/', trim( $raw ), -1, PREG_SPLIT_NO_EMPTY );
foreach( $entries as $entry ) {
$route = strtolower( trim( $entry, '/' ) );
if( $route === $url_prefix ) {
$rejected[] = $entry;
continue;
}
if( 0 === strpos( $route, $url_prefix . '/' ) ) {
$route = trim( substr( $route, strlen( $url_prefix ) ), '/' );
}
if( '' === $route
|| 1 !== preg_match( self::ROUTE_PATTERN, $route )
|| false !== strpos( $route, '..' )
|| 1 === preg_match( '#^batch(/|$)#', $route )
|| ( !in_array( $route, $routes, true ) && count( $routes ) >= self::MAX_EXCLUDED_ROUTES )
) {
$rejected[] = $entry;
continue;
}
if( !in_array( $route, $routes, true ) ) {
$routes[] = $route;
}
}
return [
'routes' => $routes,
'rejected' => $rejected,
];
}
}