Skip to content

Commit 80150c1

Browse files
committed
Add a proper permission callback to the endpoint that get the JWT
1 parent 2829b7a commit 80150c1

File tree

1 file changed

+52
-1
lines changed

1 file changed

+52
-1
lines changed

includes/rest-routes.php

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,63 @@ function add_endpoints() {
2626
[
2727
'methods' => 'GET',
2828
'callback' => __NAMESPACE__ . '\get_jwt',
29-
'permission_callback' => '__return_true',
29+
'permission_callback' => __NAMESPACE__ . '\check_jwt_permission',
3030
]
3131
);
3232
}
3333

34+
/**
35+
* Check if the current user has permission to access the JWT endpoint.
36+
*
37+
* This endpoint requires authentication to prevent unauthorized access
38+
* to sensitive JWT tokens containing Apple Maps credentials.
39+
*
40+
* SECURITY NOTE: While same-origin checking is implemented as a fallback
41+
* for public frontend maps, requiring authentication is the most secure approach.
42+
* Consider implementing nonce-based authentication for public pages if needed.
43+
*
44+
* @return bool|WP_Error True if user has permission, WP_Error otherwise.
45+
*/
46+
function check_jwt_permission() {
47+
// Primary security: Require authentication.
48+
if ( is_user_logged_in() ) {
49+
return true;
50+
}
51+
52+
// Fallback for public frontend maps: Verify same-origin request
53+
// Note: This is less secure than authentication but allows public maps to function.
54+
$site_url = get_fqdn_from_url( get_site_url() );
55+
$site_host = wp_parse_url( $site_url, PHP_URL_HOST );
56+
57+
// Check Referer header (more reliable for same-origin requests).
58+
if ( isset( $_SERVER['HTTP_REFERER'] ) ) {
59+
$referer = esc_url_raw( wp_unslash( $_SERVER['HTTP_REFERER'] ) );
60+
$referer_host = wp_parse_url( $referer, PHP_URL_HOST );
3461

62+
// Allow if referer host matches site host.
63+
if ( $referer_host === $site_host ) {
64+
return true;
65+
}
66+
}
67+
68+
// Check Origin header (for CORS requests, but should be blocked for security).
69+
if ( isset( $_SERVER['HTTP_ORIGIN'] ) ) {
70+
$origin = esc_url_raw( wp_unslash( $_SERVER['HTTP_ORIGIN'] ) );
71+
$origin_host = wp_parse_url( $origin, PHP_URL_HOST );
72+
73+
// Only allow if origin matches site host.
74+
if ( $origin_host === $site_host ) {
75+
return true;
76+
}
77+
}
78+
79+
// Block all unauthenticated requests without valid same-origin verification.
80+
return new WP_Error(
81+
'rest_forbidden',
82+
__( 'You must be logged in to access this endpoint.', 'maps-block-apple' ),
83+
[ 'status' => rest_authorization_required_code() ]
84+
);
85+
}
3586

3687
/**
3788
* Encode String.

0 commit comments

Comments
 (0)