Subir proyecto
This commit is contained in:
Vendored
+164
@@ -0,0 +1,164 @@
|
||||
<?php
|
||||
/**
|
||||
* Post-login Authorization Callback — Consent Screen.
|
||||
*
|
||||
* Handles GET /oauth/authorize-callback — called by WordPress after the user
|
||||
* authenticates. Looks up the state transient (which already carries the
|
||||
* validated client display data captured at authorize time), refreshes the
|
||||
* transient TTL to give the user time to read the screen, then renders a
|
||||
* standalone HTML consent page.
|
||||
*
|
||||
* The user's Allow/Deny choice is handled by ConsentEndpoint (POST /oauth/consent).
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
use WPMedia\MCP\OAuth\Logging\McpLogger;
|
||||
use WPMedia\MCP\OAuth\Views\Render;
|
||||
|
||||
/**
|
||||
* Authorize Callback — renders the consent screen.
|
||||
*/
|
||||
class AuthorizeCallback {
|
||||
/**
|
||||
* How long (seconds) the state transient lives once the consent screen is shown.
|
||||
* Replaces the original 60 s authorize-window TTL so the user has time to decide.
|
||||
*/
|
||||
const CONSENT_TTL = 300;
|
||||
|
||||
/**
|
||||
* View renderer.
|
||||
*
|
||||
* @var Render
|
||||
*/
|
||||
private Render $render;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param Render $render View renderer.
|
||||
*/
|
||||
public function __construct( Render $render ) {
|
||||
$this->render = $render;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the post-login callback — show the consent screen.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle_request(): void {
|
||||
$state = sanitize_text_field( wp_unslash( $_GET['state'] ?? '' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- OAuth state token echoed back by the login redirect, not a WP nonce-protected form.
|
||||
|
||||
McpLogger::log(
|
||||
'CALLBACK',
|
||||
'authorize-callback received',
|
||||
[
|
||||
'is_logged_in' => is_user_logged_in() ? 'yes' : 'no',
|
||||
'user_id' => is_user_logged_in() ? get_current_user_id() : 0,
|
||||
'has_state' => '' !== $state ? 'yes' : 'no',
|
||||
'remote_addr' => isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '',
|
||||
]
|
||||
);
|
||||
|
||||
if ( ! is_user_logged_in() ) {
|
||||
McpLogger::log( 'CALLBACK', 'rejected: user not logged in' );
|
||||
wp_die( esc_html__( 'You must be logged in to authorise an MCP session.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 401 ] );
|
||||
}
|
||||
|
||||
if ( '' === $state ) {
|
||||
McpLogger::log( 'CALLBACK', 'rejected: missing state' );
|
||||
wp_die( esc_html__( 'Missing state parameter.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
|
||||
$state_key = 'mcp_oauth_state_' . $state;
|
||||
$state_data = get_transient( $state_key );
|
||||
|
||||
if ( false === $state_data || ! is_array( $state_data ) ) {
|
||||
McpLogger::log( 'CALLBACK', 'rejected: state transient not found or expired', [ 'state' => $state ] );
|
||||
wp_die( esc_html__( 'Invalid or expired state. Please restart the authorization flow.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
|
||||
// Client display data was captured and validated by AuthorizeEndpoint and
|
||||
// stored in the state transient. Reusing it avoids a second CIMD lookup —
|
||||
// no network round-trip, and no spurious failure if the publisher is
|
||||
// briefly unreachable between login and consent.
|
||||
$client_id = (string) ( $state_data['client_id'] ?? '' );
|
||||
$client = [
|
||||
'client_id' => $client_id,
|
||||
'client_name' => (string) ( $state_data['client_name'] ?? '' ),
|
||||
'client_uri' => (string) ( $state_data['client_uri'] ?? '' ),
|
||||
'verified' => ! empty( $state_data['verified'] ),
|
||||
'publisher' => (string) ( $state_data['publisher'] ?? '' ),
|
||||
];
|
||||
|
||||
// Refresh state TTL — the user now has CONSENT_TTL seconds to decide.
|
||||
set_transient( $state_key, $state_data, self::CONSENT_TTL );
|
||||
|
||||
McpLogger::log(
|
||||
'CALLBACK',
|
||||
'showing consent screen',
|
||||
[
|
||||
'user_id' => get_current_user_id(),
|
||||
'client_id' => $client_id,
|
||||
'client_name' => $client['client_name'],
|
||||
'verified' => $client['verified'] ? 'yes' : 'no',
|
||||
]
|
||||
);
|
||||
|
||||
$this->render_consent_screen( $state, $client );
|
||||
}
|
||||
|
||||
/**
|
||||
* Assemble the consent-screen view model and render it.
|
||||
*
|
||||
* @param string $state OAuth state token.
|
||||
* @param array<string, mixed> $client Resolved CIMD client record.
|
||||
* @return void
|
||||
*/
|
||||
private function output_consent_screen( string $state, array $client ): void {
|
||||
nocache_headers();
|
||||
|
||||
// Escaped at each output site inside the template. URLs are esc_url'd
|
||||
// here since they're only ever emitted into href/action attributes.
|
||||
$client_name = (string) ( $client['client_name'] ?? '' );
|
||||
$client_id = esc_url( (string) ( $client['client_id'] ?? '' ) );
|
||||
$client_uri = esc_url( (string) ( $client['client_uri'] ?? '' ) );
|
||||
$verified = ! empty( $client['verified'] );
|
||||
$publisher = (string) ( $client['publisher'] ?? '' );
|
||||
$site_name = (string) get_bloginfo( 'name' );
|
||||
$consent_url = esc_url( home_url( '/oauth/consent' ) ); // Rewrite endpoint: home_url(), not get_site_url().
|
||||
|
||||
// The display name links to client_uri if available, otherwise client_id.
|
||||
$display_href = '' !== $client_uri ? $client_uri : $client_id;
|
||||
|
||||
$this->render->view(
|
||||
'consent-screen',
|
||||
[
|
||||
'state' => $state,
|
||||
'client_name' => $client_name,
|
||||
'client_id' => $client_id,
|
||||
'client_uri' => $client_uri,
|
||||
'verified' => $verified,
|
||||
'publisher' => $publisher,
|
||||
'site_name' => $site_name,
|
||||
'consent_url' => $consent_url,
|
||||
'display_href' => $display_href,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the consent screen, then terminate the request.
|
||||
*
|
||||
* @param string $state OAuth state token.
|
||||
* @param array<string, mixed> $client Resolved CIMD client record.
|
||||
* @return void
|
||||
*/
|
||||
private function render_consent_screen( string $state, array $client ): void {
|
||||
$this->output_consent_screen( $state, $client );
|
||||
exit;
|
||||
}
|
||||
}
|
||||
Vendored
+275
@@ -0,0 +1,275 @@
|
||||
<?php
|
||||
/**
|
||||
* Authorization Endpoint.
|
||||
*
|
||||
* Handles GET /oauth/authorize — validates the PKCE parameters, stores the
|
||||
* challenge in a 60-second transient, then routes the browser onward: a
|
||||
* user with an existing WordPress session is redirected straight to
|
||||
* /oauth/authorize-callback; otherwise the browser goes to the WordPress
|
||||
* login form first, and WordPress delivers the user back to
|
||||
* /oauth/authorize-callback after a successful login, where the auth code
|
||||
* is issued.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
use WPMedia\MCP\OAuth\Logging\McpLogger;
|
||||
|
||||
/**
|
||||
* Authorize Endpoint.
|
||||
*/
|
||||
class AuthorizeEndpoint {
|
||||
/**
|
||||
* Transient TTL for the state parameter (seconds).
|
||||
*/
|
||||
const STATE_TTL = 60;
|
||||
|
||||
/**
|
||||
* CIMD resolver used to dereference and validate the client_id URL.
|
||||
*
|
||||
* @var CimdResolver
|
||||
*/
|
||||
private CimdResolver $resolver;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param CimdResolver $resolver CIMD resolver.
|
||||
*/
|
||||
public function __construct( CimdResolver $resolver ) {
|
||||
$this->resolver = $resolver;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an authorization request.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle_request(): void {
|
||||
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- OAuth 2.1 authorization request from an external client; CSRF protection is provided by the state parameter and PKCE, not a WP nonce.
|
||||
$client_id = esc_url_raw( wp_unslash( $_GET['client_id'] ?? '' ) );
|
||||
$redirect_uri = esc_url_raw( wp_unslash( $_GET['redirect_uri'] ?? '' ) );
|
||||
$response_type = sanitize_text_field( wp_unslash( $_GET['response_type'] ?? '' ) );
|
||||
$code_challenge = sanitize_text_field( wp_unslash( $_GET['code_challenge'] ?? '' ) );
|
||||
$code_challenge_method = sanitize_text_field( wp_unslash( $_GET['code_challenge_method'] ?? '' ) );
|
||||
$state = sanitize_text_field( wp_unslash( $_GET['state'] ?? '' ) );
|
||||
// phpcs:enable WordPress.Security.NonceVerification.Recommended
|
||||
|
||||
McpLogger::log(
|
||||
'AUTHORIZE',
|
||||
'authorization request received',
|
||||
[
|
||||
'response_type' => $response_type,
|
||||
'client_id' => $client_id,
|
||||
'redirect_uri' => $redirect_uri,
|
||||
'code_challenge_method' => $code_challenge_method,
|
||||
'has_code_challenge' => '' !== $code_challenge ? 'yes' : 'no',
|
||||
'has_state' => '' !== $state ? 'yes' : 'no',
|
||||
'remote_addr' => isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '',
|
||||
]
|
||||
);
|
||||
|
||||
// Validate the client and redirect_uri BEFORE using redirect_uri in any redirect.
|
||||
// Per OAuth 2.1 §7.5.2 and RFC 6749 §10.15, the AS MUST NOT redirect to a URI
|
||||
// that has not been positively validated against a registered client.
|
||||
|
||||
if ( '' === $client_id ) {
|
||||
McpLogger::log( 'AUTHORIZE', 'rejected: missing client_id' );
|
||||
wp_die( esc_html__( 'client_id is required.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
|
||||
$client = $this->resolver->resolve( $client_id );
|
||||
if ( null === $client ) {
|
||||
McpLogger::log( 'AUTHORIZE', 'rejected: client_id could not be resolved via CIMD', [ 'client_id' => $client_id ] );
|
||||
wp_die( esc_html__( 'Unknown OAuth client.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
|
||||
if ( empty( $client['verified'] ) ) {
|
||||
McpLogger::log( 'AUTHORIZE', 'rejected: client not a verified publisher', [ 'client_id' => $client_id ] );
|
||||
wp_die( esc_html__( 'This OAuth client is not a verified publisher.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
|
||||
if ( '' === $redirect_uri ) {
|
||||
McpLogger::log( 'AUTHORIZE', 'rejected: missing redirect_uri' );
|
||||
wp_die( esc_html__( 'redirect_uri is required.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
|
||||
if ( ! $this->redirect_uri_matches( $redirect_uri, $client['redirect_uris'] ) ) {
|
||||
McpLogger::log(
|
||||
'AUTHORIZE',
|
||||
'rejected: redirect_uri mismatch',
|
||||
[
|
||||
'provided' => $redirect_uri,
|
||||
'registered' => $client['redirect_uris'],
|
||||
]
|
||||
);
|
||||
wp_die( esc_html__( 'redirect_uri does not match registered value.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
|
||||
// redirect_uri is now validated — remaining errors may safely redirect to it.
|
||||
|
||||
if ( 'code' !== $response_type ) {
|
||||
McpLogger::log( 'AUTHORIZE', 'rejected: unsupported response_type', [ 'response_type' => $response_type ] );
|
||||
$this->send_error( $redirect_uri, 'unsupported_response_type', $state );
|
||||
return;
|
||||
}
|
||||
|
||||
if ( '' === $code_challenge || 'S256' !== $code_challenge_method ) {
|
||||
McpLogger::log(
|
||||
'AUTHORIZE',
|
||||
'rejected: missing or invalid PKCE params',
|
||||
[
|
||||
'has_code_challenge' => '' !== $code_challenge ? 'yes' : 'no',
|
||||
'code_challenge_method' => $code_challenge_method,
|
||||
]
|
||||
);
|
||||
$this->send_error( $redirect_uri, 'invalid_request', $state );
|
||||
return;
|
||||
}
|
||||
|
||||
// OAuth 2.1 §4.1.1 requires state; reject rather than generate silently.
|
||||
// A server-generated state never reaches the client before the redirect,
|
||||
// so the client cannot validate it on return — providing no CSRF protection.
|
||||
if ( '' === $state ) {
|
||||
McpLogger::log( 'AUTHORIZE', 'rejected: state parameter is required' );
|
||||
$this->send_error( $redirect_uri, 'invalid_request', '' );
|
||||
return;
|
||||
}
|
||||
|
||||
// Persist the validated client display data alongside the PKCE state so the
|
||||
// consent screen can be rendered after login without a second CIMD fetch.
|
||||
set_transient(
|
||||
'mcp_oauth_state_' . $state,
|
||||
[
|
||||
'client_id' => $client_id,
|
||||
'client_name' => (string) ( $client['client_name'] ?? '' ),
|
||||
'client_uri' => (string) ( $client['client_uri'] ?? '' ),
|
||||
// Already guaranteed truthy - the 'client not a verified publisher' guard above exits otherwise.
|
||||
'verified' => true,
|
||||
'publisher' => (string) ( $client['publisher'] ?? '' ),
|
||||
'redirect_uri' => $redirect_uri,
|
||||
'code_challenge' => $code_challenge,
|
||||
'code_challenge_method' => $code_challenge_method,
|
||||
'state' => $state,
|
||||
],
|
||||
self::STATE_TTL
|
||||
);
|
||||
|
||||
// home_url(): the callback is a rewrite endpoint served from the Site Address,
|
||||
// so it must match home_url() and not get_site_url() on split-directory installs.
|
||||
$callback_url = add_query_arg( 'state', rawurlencode( $state ), home_url( '/oauth/authorize-callback' ) );
|
||||
|
||||
if ( is_user_logged_in() ) {
|
||||
McpLogger::log(
|
||||
'AUTHORIZE',
|
||||
'existing session, skipping login',
|
||||
[
|
||||
'state' => $state,
|
||||
'callback_url' => $callback_url,
|
||||
]
|
||||
);
|
||||
wp_redirect( $callback_url ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- server-constructed home_url() target.
|
||||
exit;
|
||||
}
|
||||
|
||||
$login_url = wp_login_url( $callback_url );
|
||||
|
||||
McpLogger::log(
|
||||
'AUTHORIZE',
|
||||
'redirecting to login',
|
||||
[
|
||||
'state' => $state,
|
||||
'callback_url' => $callback_url,
|
||||
]
|
||||
);
|
||||
|
||||
wp_redirect( $login_url ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether a provided redirect_uri matches a registered one.
|
||||
*
|
||||
* Non-loopback clients require an exact match. Loopback clients (native
|
||||
* apps per RFC 8252) are matched port-agnostically: the ephemeral port
|
||||
* varies per session, so scheme, host, and path must match but the port is
|
||||
* ignored. The exemption is constrained to the literal loopback hosts over
|
||||
* http so it cannot widen open-redirect exposure for normal clients.
|
||||
*
|
||||
* @param string $provided The redirect_uri supplied in the request.
|
||||
* @param string[] $registered The redirect URIs from the client metadata.
|
||||
* @return bool
|
||||
*/
|
||||
private function redirect_uri_matches( string $provided, array $registered ): bool {
|
||||
if ( in_array( $provided, $registered, true ) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$provided_parts = wp_parse_url( $provided );
|
||||
if ( ! is_array( $provided_parts ) || ! $this->is_loopback( $provided_parts ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ( $registered as $candidate ) {
|
||||
$candidate_parts = wp_parse_url( (string) $candidate );
|
||||
if ( ! is_array( $candidate_parts ) || ! $this->is_loopback( $candidate_parts ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
( $provided_parts['scheme'] ?? '' ) === ( $candidate_parts['scheme'] ?? '' )
|
||||
&& ( $provided_parts['host'] ?? '' ) === ( $candidate_parts['host'] ?? '' )
|
||||
&& ( $provided_parts['path'] ?? '' ) === ( $candidate_parts['path'] ?? '' )
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a parsed URL points at a loopback address over http.
|
||||
*
|
||||
* Covers IPv4 (127.0.0.1), hostname (localhost), and IPv6 (::1) loopback
|
||||
* addresses per RFC 8252 §8.3. Only plain HTTP is permitted — HTTPS
|
||||
* loopback is not exempted to avoid widening open-redirect exposure for
|
||||
* normal (non-native-app) clients. wp_parse_url() strips the brackets
|
||||
* from IPv6 literals, so the host value is '::1', not '[::1]'.
|
||||
*
|
||||
* @param array<string, mixed> $parts Parsed URL components from wp_parse_url().
|
||||
* @return bool
|
||||
*/
|
||||
private function is_loopback( array $parts ): bool {
|
||||
$scheme = (string) ( $parts['scheme'] ?? '' );
|
||||
$host = (string) ( $parts['host'] ?? '' );
|
||||
|
||||
return 'http' === $scheme && in_array( $host, [ '127.0.0.1', 'localhost', '::1' ], true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirect the client to redirect_uri with an error parameter.
|
||||
*
|
||||
* @param string $redirect_uri Destination URI (may be empty on early failure).
|
||||
* @param string $error OAuth error code.
|
||||
* @param string $state State token echoed back to the client.
|
||||
* @return void
|
||||
*/
|
||||
private function send_error( string $redirect_uri, string $error, string $state ): void {
|
||||
if ( '' !== $redirect_uri ) {
|
||||
$params = [
|
||||
'error' => $error,
|
||||
'iss' => home_url(),
|
||||
];
|
||||
if ( '' !== $state ) {
|
||||
$params['state'] = $state;
|
||||
}
|
||||
wp_redirect( add_query_arg( $params, $redirect_uri ) ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- redirecting to the client's own registered redirect_uri, already validated against the CIMD allowlist; not a same-site redirect.
|
||||
exit;
|
||||
}
|
||||
|
||||
wp_die( esc_html( $error ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
}
|
||||
+363
@@ -0,0 +1,363 @@
|
||||
<?php
|
||||
/**
|
||||
* Client ID Metadata Document (CIMD) resolver.
|
||||
*
|
||||
* Replaces Dynamic Client Registration (RFC 7591). Instead of pre-registering
|
||||
* a client and minting a client_id/secret, the client presents an HTTPS URL as
|
||||
* its client_id; this resolver dereferences that URL, validates the returned
|
||||
* metadata document, and produces a normalised client record compatible with
|
||||
* the one AuthorizeEndpoint previously read from ClientRegistration::get_client().
|
||||
*
|
||||
* CIMD is the default client-registration model in the 2025-11-25 MCP
|
||||
* specification (IETF OAuth WG, adopted October 2025).
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
use WPMedia\MCP\OAuth\Logging\McpLogger;
|
||||
|
||||
class CimdResolver {
|
||||
/**
|
||||
* Maximum size (bytes) of a metadata document we will read.
|
||||
*/
|
||||
const MAX_DOCUMENT_BYTES = 5120;
|
||||
|
||||
/**
|
||||
* HTTP request timeout (seconds) for fetching a document.
|
||||
*/
|
||||
const FETCH_TIMEOUT = 5;
|
||||
|
||||
/**
|
||||
* Transient key prefix for cached, validated documents.
|
||||
*/
|
||||
const CACHE_PREFIX = 'mcp_cimd_';
|
||||
|
||||
/**
|
||||
* Grant types this server supports.
|
||||
*/
|
||||
const SUPPORTED_GRANT_TYPES = [ 'authorization_code', 'refresh_token' ];
|
||||
|
||||
/**
|
||||
* Trusted-publisher verifier.
|
||||
*
|
||||
* @var ClaudeClientVerifier
|
||||
*/
|
||||
private ClaudeClientVerifier $verifier;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param ClaudeClientVerifier $verifier Trusted-publisher verifier.
|
||||
*/
|
||||
public function __construct( ClaudeClientVerifier $verifier ) {
|
||||
$this->verifier = $verifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a client_id URL into a normalised client record.
|
||||
*
|
||||
* @param string $client_id The client_id URL presented by the client.
|
||||
* @return array<string, mixed>|null Normalised client record, or null on any failure.
|
||||
*/
|
||||
public function resolve( string $client_id ): ?array {
|
||||
if ( ! $this->is_valid_client_id_url( $client_id ) ) {
|
||||
McpLogger::log( 'CIMD', 'rejected: invalid client_id url', [ 'client_id' => $client_id ] );
|
||||
return null;
|
||||
}
|
||||
|
||||
// Gate the network fetch on the trusted-publisher host allowlist. The
|
||||
// authorize endpoint is unauthenticated, so dereferencing an arbitrary
|
||||
// client_id URL would let any caller use this server as an outbound
|
||||
// fetch proxy and pollute the transient cache. Only allowlisted hosts
|
||||
// are ever fetched; exact client_id verification still happens later.
|
||||
if ( ! $this->verifier->is_trusted_host( $client_id ) ) {
|
||||
McpLogger::log( 'CIMD', 'rejected: client_id host not in trusted-publisher allowlist', [ 'client_id' => $client_id ] );
|
||||
return null;
|
||||
}
|
||||
|
||||
$cached = $this->cache_get( $client_id );
|
||||
if ( null !== $cached ) {
|
||||
return $cached;
|
||||
}
|
||||
|
||||
$fetched = $this->fetch_document( $client_id );
|
||||
if ( null === $fetched ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$record = $this->validate_document( $fetched['doc'], $client_id );
|
||||
if ( null === $record ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$verification = $this->verifier->verify( $client_id, $fetched['doc'] );
|
||||
$record['verified'] = (bool) $verification['verified'];
|
||||
$record['publisher'] = (string) $verification['publisher'];
|
||||
|
||||
$this->cache_set( $client_id, $record, $fetched['ttl'] );
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the shape of a client_id URL per the CIMD spec.
|
||||
*
|
||||
* Requires an HTTPS URL with a path and no fragment or userinfo.
|
||||
*
|
||||
* @param string $client_id The client_id URL.
|
||||
* @return bool
|
||||
*/
|
||||
private function is_valid_client_id_url( string $client_id ): bool {
|
||||
if ( '' === $client_id ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$parts = wp_parse_url( $client_id );
|
||||
|
||||
if ( ! is_array( $parts ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( 'https' !== ( $parts['scheme'] ?? '' ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( empty( $parts['host'] ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$path = (string) ( $parts['path'] ?? '' );
|
||||
if ( '' === $path || '/' === $path ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( isset( $parts['fragment'] ) || isset( $parts['user'] ) || isset( $parts['pass'] ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a metadata document with SSRF guards and a size cap.
|
||||
*
|
||||
* @param string $url The client_id URL.
|
||||
* @return array{doc: array<string, mixed>, ttl: int}|null Decoded document and cache TTL, or null on failure.
|
||||
*/
|
||||
private function fetch_document( string $url ) {
|
||||
$response = wp_safe_remote_get(
|
||||
$url,
|
||||
[
|
||||
'timeout' => self::FETCH_TIMEOUT,
|
||||
'redirection' => 0,
|
||||
'limit_response_size' => self::MAX_DOCUMENT_BYTES,
|
||||
'headers' => [ 'Accept' => 'application/json' ],
|
||||
]
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
McpLogger::log(
|
||||
'CIMD',
|
||||
'rejected: fetch failed',
|
||||
[
|
||||
'client_id' => $url,
|
||||
'error' => $response->get_error_message(),
|
||||
]
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
$status = (int) wp_remote_retrieve_response_code( $response );
|
||||
if ( 200 !== $status ) {
|
||||
McpLogger::log(
|
||||
'CIMD',
|
||||
'rejected: non-200 status',
|
||||
[
|
||||
'client_id' => $url,
|
||||
'status' => $status,
|
||||
]
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
$body = (string) wp_remote_retrieve_body( $response );
|
||||
if ( strlen( $body ) > self::MAX_DOCUMENT_BYTES ) {
|
||||
McpLogger::log(
|
||||
'CIMD',
|
||||
'rejected: document too large',
|
||||
[
|
||||
'client_id' => $url,
|
||||
'bytes' => strlen( $body ),
|
||||
]
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
$content_type = (string) wp_remote_retrieve_header( $response, 'content-type' );
|
||||
if ( '' !== $content_type && false === strpos( $content_type, 'application/json' ) ) {
|
||||
McpLogger::log(
|
||||
'CIMD',
|
||||
'warning: unexpected content-type',
|
||||
[
|
||||
'client_id' => $url,
|
||||
'content_type' => $content_type,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
$doc = json_decode( $body, true );
|
||||
if ( ! is_array( $doc ) || empty( $doc ) ) {
|
||||
McpLogger::log( 'CIMD', 'rejected: body is not a JSON object', [ 'client_id' => $url ] );
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
'doc' => $doc,
|
||||
'ttl' => $this->parse_ttl( (string) wp_remote_retrieve_header( $response, 'cache-control' ) ),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a metadata document and build a normalized client record.
|
||||
*
|
||||
* @param array<string, mixed> $doc The decoded metadata document.
|
||||
* @param string $url The client_id URL it was fetched from.
|
||||
* @return array<string, mixed>|null Normalized record, or null on validation failure.
|
||||
*/
|
||||
private function validate_document( array $doc, string $url ): ?array {
|
||||
// The document's client_id MUST exactly equal the document URL.
|
||||
$doc_client_id = isset( $doc['client_id'] ) && is_string( $doc['client_id'] ) ? $doc['client_id'] : '';
|
||||
if ( '' === $doc_client_id || $url !== $doc_client_id ) {
|
||||
McpLogger::log(
|
||||
'CIMD',
|
||||
'rejected: client_id mismatch',
|
||||
[
|
||||
'client_id' => $url,
|
||||
'document_client_id' => $doc_client_id,
|
||||
]
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Only public clients are supported (no shared secret to authenticate).
|
||||
$auth_method = isset( $doc['token_endpoint_auth_method'] ) ? (string) $doc['token_endpoint_auth_method'] : 'none';
|
||||
if ( 'none' !== $auth_method ) {
|
||||
McpLogger::log(
|
||||
'CIMD',
|
||||
'rejected: unsupported token_endpoint_auth_method',
|
||||
[
|
||||
'client_id' => $url,
|
||||
'method' => $auth_method,
|
||||
]
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
// redirect_uris is required.
|
||||
$redirect_uris = $doc['redirect_uris'] ?? [];
|
||||
if ( ! is_array( $redirect_uris ) || empty( $redirect_uris ) ) {
|
||||
McpLogger::log( 'CIMD', 'rejected: missing redirect_uris', [ 'client_id' => $url ] );
|
||||
return null;
|
||||
}
|
||||
|
||||
$redirect_uris = array_values(
|
||||
array_filter(
|
||||
array_map( 'esc_url_raw', array_map( 'strval', $redirect_uris ) )
|
||||
)
|
||||
);
|
||||
|
||||
if ( empty( $redirect_uris ) ) {
|
||||
McpLogger::log( 'CIMD', 'rejected: no valid redirect_uris after sanitisation', [ 'client_id' => $url ] );
|
||||
return null;
|
||||
}
|
||||
|
||||
// grant_types: intersect with what we support; must include authorization_code.
|
||||
$requested_grants = isset( $doc['grant_types'] ) && is_array( $doc['grant_types'] )
|
||||
? array_map( 'strval', $doc['grant_types'] )
|
||||
: self::SUPPORTED_GRANT_TYPES;
|
||||
|
||||
$grant_types = array_values( array_intersect( self::SUPPORTED_GRANT_TYPES, $requested_grants ) );
|
||||
if ( ! in_array( 'authorization_code', $grant_types, true ) ) {
|
||||
McpLogger::log(
|
||||
'CIMD',
|
||||
'rejected: authorization_code grant not offered',
|
||||
[
|
||||
'client_id' => $url,
|
||||
'grant_types' => $requested_grants,
|
||||
]
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
$client_name = isset( $doc['client_name'] ) ? sanitize_text_field( (string) $doc['client_name'] ) : '';
|
||||
if ( '' === $client_name ) {
|
||||
$client_name = (string) wp_parse_url( $url, PHP_URL_HOST );
|
||||
}
|
||||
|
||||
$client_uri = isset( $doc['client_uri'] ) && is_string( $doc['client_uri'] ) ? esc_url_raw( $doc['client_uri'] ) : '';
|
||||
|
||||
return [
|
||||
'client_id' => $url,
|
||||
'client_name' => $client_name,
|
||||
'client_uri' => $client_uri,
|
||||
'redirect_uris' => $redirect_uris,
|
||||
'grant_types' => $grant_types,
|
||||
'token_endpoint_auth_method' => 'none',
|
||||
'source' => 'cimd',
|
||||
'verified' => false,
|
||||
'publisher' => '',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a max-age TTL from a Cache-Control header, clamped to a sane range.
|
||||
*
|
||||
* @param string $cache_control The Cache-Control header value.
|
||||
* @return int TTL in seconds.
|
||||
*/
|
||||
private function parse_ttl( string $cache_control ): int {
|
||||
$default = HOUR_IN_SECONDS;
|
||||
|
||||
if ( '' !== $cache_control && preg_match( '/max-age\s*=\s*(\d+)/i', $cache_control, $matches ) ) {
|
||||
$default = (int) $matches[1];
|
||||
}
|
||||
|
||||
return (int) max( 300, min( $default, DAY_IN_SECONDS ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the transient cache key for a client_id URL.
|
||||
*
|
||||
* @param string $url The client_id URL.
|
||||
* @return string
|
||||
*/
|
||||
private function cache_key( string $url ): string {
|
||||
return self::CACHE_PREFIX . md5( $url );
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a cached, validated client record.
|
||||
*
|
||||
* @param string $url The client_id URL.
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
private function cache_get( string $url ): ?array {
|
||||
$cached = get_transient( $this->cache_key( $url ) );
|
||||
|
||||
return is_array( $cached ) ? $cached : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cache a validated client record. Only successful documents are ever cached.
|
||||
*
|
||||
* @param string $url The client_id URL.
|
||||
* @param array<string, mixed> $record The normalised record.
|
||||
* @param int $ttl Cache TTL in seconds.
|
||||
* @return void
|
||||
*/
|
||||
private function cache_set( string $url, array $record, int $ttl ): void {
|
||||
set_transient( $this->cache_key( $url ), $record, $ttl );
|
||||
}
|
||||
}
|
||||
Vendored
+147
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
/**
|
||||
* Built-in verification for trusted CIMD publishers.
|
||||
*
|
||||
* Client ID Metadata Documents (CIMD) let any client identify itself with an
|
||||
* HTTPS URL, but this proof of concept only authorizes clients whose metadata
|
||||
* matches a known, trusted publisher. Claude is the bundled publisher: its
|
||||
* official client_id URL, host, and loopback redirect shape are pinned here so
|
||||
* that a fetched document can be cryptographically bound to Claude rather than
|
||||
* trusted on its own say-so.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
use WPMedia\MCP\OAuth\Logging\McpLogger;
|
||||
|
||||
class ClaudeClientVerifier {
|
||||
/**
|
||||
* Verify a fetched CIMD document against the trusted-publisher allowlist.
|
||||
*
|
||||
* @param string $client_id The client_id URL the document was fetched from.
|
||||
* @param array<string, mixed> $doc The decoded, already URL-validated metadata document.
|
||||
* @return array{verified: bool, publisher: string} Verification result.
|
||||
*/
|
||||
public function verify( string $client_id, array $doc ): array {
|
||||
$unverified = [
|
||||
'verified' => false,
|
||||
'publisher' => '',
|
||||
];
|
||||
|
||||
foreach ( $this->get_trusted_publishers() as $publisher => $config ) {
|
||||
if ( $this->matches_publisher( $client_id, $doc, (array) $config ) ) {
|
||||
McpLogger::log(
|
||||
'CIMD',
|
||||
'client verified against trusted publisher',
|
||||
[
|
||||
'client_id' => $client_id,
|
||||
'publisher' => $publisher,
|
||||
]
|
||||
);
|
||||
|
||||
return [
|
||||
'verified' => true,
|
||||
'publisher' => (string) $publisher,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $unverified;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a client_id URL's host belongs to a trusted publisher.
|
||||
*
|
||||
* Used to gate the (unauthenticated) CIMD network fetch: only client_ids
|
||||
* whose host is allowlisted are ever dereferenced, so an arbitrary URL
|
||||
* cannot turn the public authorize endpoint into an outbound-request proxy
|
||||
* or fill the transient cache with junk records.
|
||||
*
|
||||
* @param string $client_id The client_id URL.
|
||||
* @return bool
|
||||
*/
|
||||
public function is_trusted_host( string $client_id ): bool {
|
||||
$host = (string) wp_parse_url( $client_id, PHP_URL_HOST );
|
||||
if ( '' === $host ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ( $this->get_trusted_publishers() as $config ) {
|
||||
if ( (string) ( ( (array) $config )['host'] ?? '' ) === $host ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the trusted-publisher allowlist.
|
||||
*
|
||||
* @return array<string, array<string, mixed>>
|
||||
*/
|
||||
private function get_trusted_publishers(): array {
|
||||
$publishers = [
|
||||
'claude' => [
|
||||
'client_ids' => [
|
||||
'https://claude.ai/oauth/claude-code-client-metadata',
|
||||
'https://claude.ai/oauth/mcp-oauth-client-metadata',
|
||||
],
|
||||
'host' => 'claude.ai',
|
||||
],
|
||||
];
|
||||
|
||||
$publishers = apply_filters_deprecated( 'rocket_mcp_trusted_publishers', [ $publishers ], '1.0.1', 'wpmedia_mcp_oauth_trusted_publishers' );
|
||||
|
||||
/**
|
||||
* Filters the trusted-publisher allowlist for MCP OAuth client verification.
|
||||
*
|
||||
* Each entry is keyed by an arbitrary publisher slug and must provide:
|
||||
* - client_ids (string[]): exact client_id URLs that are trusted for this publisher.
|
||||
* - host (string): the hostname client_id URLs must resolve to (defense in depth,
|
||||
* also used as the SSRF allowlist gate before any network fetch is made).
|
||||
*
|
||||
* This filter only ever runs server-side, with no request-derived input passed into it
|
||||
* or influencing its evaluation — it does not accept or process untrusted input. It can
|
||||
* only ADD trusted publishers; it does not bypass the exact client_id match in
|
||||
* matches_publisher() or the "verified" hard-reject in AuthorizeEndpoint::handle_request().
|
||||
*
|
||||
* @param array<string, array{client_ids: string[], host: string}> $publishers Trusted-publisher allowlist.
|
||||
* @return array<string, array{client_ids: string[], host: string}>
|
||||
*/
|
||||
return wpm_apply_filters_typed( 'array', 'wpmedia_mcp_oauth_trusted_publishers', $publishers );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a document matches a single trusted publisher.
|
||||
*
|
||||
* @param string $client_id The client_id URL.
|
||||
* @param array<string, mixed> $doc The metadata document.
|
||||
* @param array<string, mixed> $config The publisher configuration.
|
||||
* @return bool
|
||||
*/
|
||||
private function matches_publisher( string $client_id, array $doc, array $config ): bool {
|
||||
$client_ids = (array) ( $config['client_ids'] ?? [] );
|
||||
|
||||
// 1. Exact, known-good client_id URL (primary trust anchor).
|
||||
if ( ! in_array( $client_id, $client_ids, true ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 2. URL host must match the publisher host (defense in depth).
|
||||
$host = (string) wp_parse_url( $client_id, PHP_URL_HOST );
|
||||
if ( '' === $host || (string) ( $config['host'] ?? '' ) !== $host ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 3. Public-client flow only.
|
||||
// Redirect URI validation at authorize time is AuthorizeEndpoint::redirect_uri_matches()'s
|
||||
// responsibility. Checking the redirect_uri shape here would break verification when
|
||||
// the publisher's CIMD document includes additional redirect URIs for other products.
|
||||
$auth_method = (string) ( $doc['token_endpoint_auth_method'] ?? 'none' );
|
||||
|
||||
return 'none' === $auth_method;
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
/**
|
||||
* Consent Endpoint.
|
||||
*
|
||||
* Handles POST /oauth/consent — the form submission from the consent screen
|
||||
* rendered by AuthorizeCallback. Verifies the WordPress nonce, looks up and
|
||||
* consumes the state transient, then either issues an auth code (Allow) or
|
||||
* redirects back to the client with error=access_denied (Deny).
|
||||
*
|
||||
* redirect_uri is always read from the server-side state transient, never from
|
||||
* $_POST, so it cannot be manipulated by the user or a third party.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
use WPMedia\MCP\OAuth\Logging\McpLogger;
|
||||
|
||||
class ConsentEndpoint {
|
||||
/**
|
||||
* Auth-code transient TTL (seconds). Codes are single-use; the transient
|
||||
* is deleted immediately on redemption at the token endpoint.
|
||||
*/
|
||||
const CODE_TTL = 60;
|
||||
|
||||
/**
|
||||
* Handle the consent form POST.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle_request(): void {
|
||||
$request_method = isset( $_SERVER['REQUEST_METHOD'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) : '';
|
||||
|
||||
if ( 'POST' !== $request_method ) {
|
||||
McpLogger::log( 'CONSENT', 'rejected: wrong method', [ 'method' => $request_method ] );
|
||||
wp_die( esc_html__( 'Method not allowed.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 405 ] );
|
||||
}
|
||||
|
||||
if ( ! is_user_logged_in() ) {
|
||||
McpLogger::log( 'CONSENT', 'rejected: user not logged in' );
|
||||
wp_die( esc_html__( 'You must be logged in to authorise an MCP session.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 401 ] );
|
||||
}
|
||||
|
||||
$state = sanitize_text_field( wp_unslash( $_POST['state'] ?? '' ) );
|
||||
$action = sanitize_text_field( wp_unslash( $_POST['mcp_action'] ?? '' ) );
|
||||
|
||||
if ( '' === $state ) {
|
||||
McpLogger::log( 'CONSENT', 'rejected: missing state' );
|
||||
wp_die( esc_html__( 'Missing state parameter.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
|
||||
// Nonce verification (CSRF protection) — must happen before consuming the transient.
|
||||
check_admin_referer( 'mcp_consent_' . $state, 'mcp_consent_nonce' );
|
||||
|
||||
$state_key = 'mcp_oauth_state_' . $state;
|
||||
$state_data = get_transient( $state_key );
|
||||
|
||||
if ( false === $state_data || ! is_array( $state_data ) ) {
|
||||
McpLogger::log( 'CONSENT', 'rejected: state transient not found or expired', [ 'state' => $state ] );
|
||||
wp_die( esc_html__( 'Your session has expired. Please restart the authorization flow.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
|
||||
// Atomically consume the state — one-time use only. delete_transient()
|
||||
// returns true for a single caller when requests race, so a double
|
||||
// submission cannot mint two auth codes from one consent.
|
||||
if ( ! delete_transient( $state_key ) ) {
|
||||
McpLogger::log( 'CONSENT', 'rejected: state already consumed (concurrent submission)', [ 'state' => $state ] );
|
||||
wp_die( esc_html__( 'Your session has expired. Please restart the authorization flow.', 'mcp-oauth' ), esc_html__( 'OAuth Error', 'mcp-oauth' ), [ 'response' => 400 ] );
|
||||
}
|
||||
|
||||
$redirect_uri = (string) ( $state_data['redirect_uri'] ?? '' );
|
||||
$user_id = get_current_user_id();
|
||||
|
||||
if ( 'allow' !== $action ) {
|
||||
McpLogger::log(
|
||||
'CONSENT',
|
||||
'user denied access',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'client_id' => $state_data['client_id'] ?? '',
|
||||
'mcp_action' => $action,
|
||||
'redirect_uri' => $redirect_uri,
|
||||
]
|
||||
);
|
||||
|
||||
wp_redirect( // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- redirecting to the client's registered redirect_uri sourced from the server-side state transient, not user input.
|
||||
add_query_arg(
|
||||
[
|
||||
'error' => 'access_denied',
|
||||
'state' => $state,
|
||||
'iss' => home_url(),
|
||||
],
|
||||
$redirect_uri
|
||||
)
|
||||
);
|
||||
exit;
|
||||
}
|
||||
|
||||
// User allowed — issue a single-use auth code.
|
||||
$auth_code = bin2hex( random_bytes( 32 ) );
|
||||
|
||||
set_transient(
|
||||
'mcp_oauth_code_' . $auth_code,
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'client_id' => $state_data['client_id'] ?? '',
|
||||
'client_name' => $state_data['client_name'] ?? '',
|
||||
'code_challenge' => $state_data['code_challenge'] ?? '',
|
||||
'redirect_uri' => $redirect_uri,
|
||||
],
|
||||
self::CODE_TTL
|
||||
);
|
||||
|
||||
McpLogger::log(
|
||||
'CONSENT',
|
||||
'user granted access, auth code issued',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'client_id' => $state_data['client_id'] ?? '',
|
||||
'redirect_uri' => $redirect_uri,
|
||||
'code_ttl_s' => self::CODE_TTL,
|
||||
]
|
||||
);
|
||||
|
||||
wp_redirect( // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- redirecting to the client's registered redirect_uri sourced from the server-side state transient, not user input.
|
||||
add_query_arg(
|
||||
[
|
||||
'code' => $auth_code,
|
||||
'state' => $state,
|
||||
'iss' => home_url(),
|
||||
],
|
||||
$redirect_uri
|
||||
)
|
||||
);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
Vendored
+144
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
/**
|
||||
* OAuth 2.0 Discovery Endpoints.
|
||||
*
|
||||
* Registers the two RFC-mandated well-known documents so MCP clients can
|
||||
* auto-discover the authorization server metadata without hard-coding URLs.
|
||||
*
|
||||
* Paths served:
|
||||
* GET /.well-known/oauth-protected-resource (RFC 9728)
|
||||
* GET /.well-known/oauth-authorization-server (RFC 8414)
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth\Discovery;
|
||||
|
||||
use WPMedia\MCP\OAuth\Auth\Http404Trait;
|
||||
use WPMedia\MCP\OAuth\Context;
|
||||
use WPMedia\MCP\OAuth\Logging\McpLogger;
|
||||
|
||||
class Endpoints {
|
||||
|
||||
use Http404Trait;
|
||||
|
||||
/**
|
||||
* Query var name used to route discovery requests.
|
||||
*/
|
||||
const QUERY_VAR = 'mcp_oauth_discovery';
|
||||
|
||||
/**
|
||||
* OAuth server context.
|
||||
*
|
||||
* @var Context
|
||||
*/
|
||||
private Context $context;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param Context $context OAuth server context.
|
||||
*/
|
||||
public function __construct( Context $context ) {
|
||||
$this->context = $context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register rewrite rules for the .well-known paths.
|
||||
*
|
||||
* Called on the 'init' action.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function add_rewrite_rules(): void {
|
||||
if ( ! $this->context->is_enabled() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
add_rewrite_rule(
|
||||
'^\\.well-known/oauth-protected-resource$',
|
||||
'index.php?' . self::QUERY_VAR . '=protected-resource',
|
||||
'top'
|
||||
);
|
||||
add_rewrite_rule(
|
||||
'^\\.well-known/oauth-authorization-server$',
|
||||
'index.php?' . self::QUERY_VAR . '=authorization-server',
|
||||
'top'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the OAuth query var to WordPress's list of recognised vars.
|
||||
*
|
||||
* @param string[] $vars Existing query vars.
|
||||
* @return string[] Modified list.
|
||||
*/
|
||||
public function add_query_vars( array $vars ): array {
|
||||
$vars[] = self::QUERY_VAR;
|
||||
|
||||
return $vars;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serve the discovery document if the request matches.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle_request(): void {
|
||||
$discovery = (string) get_query_var( self::QUERY_VAR, '' );
|
||||
|
||||
if ( '' === $discovery ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! $this->context->is_enabled() ) {
|
||||
$this->force_404();
|
||||
return;
|
||||
}
|
||||
|
||||
// Every OAuth endpoint and both .well-known documents are served through
|
||||
// rewrite rules, which resolve against home_url() (the Site Address) — the
|
||||
// same base get_rest_url() uses for the resource/audience below. Advertising
|
||||
// them under get_site_url() (the WordPress Address) would point clients at
|
||||
// the wrong location on installs where WordPress lives in its own directory
|
||||
// (siteurl !== home).
|
||||
$base_url = home_url();
|
||||
|
||||
McpLogger::log(
|
||||
'DISCOVERY',
|
||||
'request received',
|
||||
[
|
||||
'document' => $discovery,
|
||||
'remote_addr' => isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '',
|
||||
'user_agent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '',
|
||||
]
|
||||
);
|
||||
|
||||
if ( 'protected-resource' === $discovery ) {
|
||||
$body = [
|
||||
'resource' => get_rest_url( null, 'mcp/mcp-oauth-server' ),
|
||||
'authorization_servers' => [ $base_url ],
|
||||
'bearer_methods_supported' => [ 'header' ],
|
||||
'scopes_supported' => [ 'mcp' ],
|
||||
];
|
||||
McpLogger::log( 'DISCOVERY', 'serving protected-resource document', $body );
|
||||
wp_send_json( $body );
|
||||
} elseif ( 'authorization-server' === $discovery ) {
|
||||
$body = [
|
||||
'issuer' => $base_url,
|
||||
'authorization_endpoint' => $base_url . '/oauth/authorize',
|
||||
'token_endpoint' => $base_url . '/oauth/token',
|
||||
'revocation_endpoint' => $base_url . '/oauth/revoke',
|
||||
'response_types_supported' => [ 'code' ],
|
||||
'grant_types_supported' => [ 'authorization_code', 'refresh_token' ],
|
||||
'code_challenge_methods_supported' => [ 'S256' ],
|
||||
'scopes_supported' => [ 'mcp' ],
|
||||
'token_endpoint_auth_methods_supported' => [ 'none' ],
|
||||
'client_id_metadata_document_supported' => true,
|
||||
'authorization_response_iss_parameter_supported' => true,
|
||||
];
|
||||
McpLogger::log( 'DISCOVERY', 'serving authorization-server document', $body );
|
||||
wp_send_json( $body );
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+272
@@ -0,0 +1,272 @@
|
||||
<?php
|
||||
/**
|
||||
* Site Health self-check for the .well-known OAuth discovery documents.
|
||||
*
|
||||
* On hosts that provision a physical `.well-known/acme-challenge/` directory
|
||||
* for Let's Encrypt auto-SSL (OVH, cPanel/AutoSSL, Plesk, and most managed-WP
|
||||
* hosts), the web server can 404 sibling `.well-known/oauth-*` paths before
|
||||
* WordPress ever runs — see the README "Hosting: .well-known conflicts"
|
||||
* section. No WordPress-level code change can influence that; this class is
|
||||
* a passive diagnostic only, registered as a single `direct` WordPress Site
|
||||
* Health test (the `site_status_tests` filter) that issues a loopback request
|
||||
* to both RFC discovery documents (`Endpoints`) and reports one combined
|
||||
* status.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth\Discovery;
|
||||
|
||||
use WP_Error;
|
||||
use WPMedia\MCP\OAuth\Context;
|
||||
|
||||
class HealthCheck {
|
||||
|
||||
/**
|
||||
* Site Health test key registered under the `direct` bucket.
|
||||
*/
|
||||
const TEST_KEY = 'wpmedia_mcp_oauth_wellknown_discovery';
|
||||
|
||||
/**
|
||||
* Transient key caching the combined self-check result.
|
||||
*/
|
||||
const TRANSIENT_KEY = 'wpmedia_mcp_oauth_wellknown_health_check';
|
||||
|
||||
/**
|
||||
* Cache TTL, in seconds, for the combined self-check result.
|
||||
*/
|
||||
const TRANSIENT_TTL = 5 * MINUTE_IN_SECONDS;
|
||||
|
||||
/**
|
||||
* Per-request timeout, in seconds, for each loopback discovery request.
|
||||
*/
|
||||
const FETCH_TIMEOUT = 5;
|
||||
|
||||
/**
|
||||
* Relative discovery document paths, keyed by a short display name.
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
private const DOCUMENTS = [
|
||||
'oauth-protected-resource' => '/.well-known/oauth-protected-resource',
|
||||
'oauth-authorization-server' => '/.well-known/oauth-authorization-server',
|
||||
];
|
||||
|
||||
/**
|
||||
* Status severity used to pick the combined result.
|
||||
*
|
||||
* @var array<string, int>
|
||||
*/
|
||||
private const STATUS_RANK = [
|
||||
'good' => 0,
|
||||
'recommended' => 1,
|
||||
'critical' => 2,
|
||||
];
|
||||
|
||||
/**
|
||||
* OAuth server context.
|
||||
*
|
||||
* @var Context
|
||||
*/
|
||||
private Context $context;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param Context $context OAuth server context.
|
||||
*/
|
||||
public function __construct( Context $context ) {
|
||||
$this->context = $context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the combined discovery-document self-check as a `direct` Site Health test.
|
||||
*
|
||||
* @param array<string, array<string, array<string, mixed>>> $tests Existing Site Health tests, keyed by bucket ('direct'|'async').
|
||||
* @return array<string, array<string, array<string, mixed>>> Modified tests.
|
||||
*/
|
||||
public function add_test( array $tests ): array {
|
||||
$tests['direct'][ self::TEST_KEY ] = [
|
||||
'label' => __( 'MCP OAuth discovery documents', 'mcp-oauth' ),
|
||||
'test' => [ $this, 'run_self_check' ],
|
||||
];
|
||||
|
||||
return $tests;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the combined discovery-document self-check.
|
||||
*
|
||||
* @return array<string, mixed> Site Health test result (label, status, badge, description, actions, test).
|
||||
*/
|
||||
public function run_self_check(): array {
|
||||
if ( ! $this->context->is_enabled() ) {
|
||||
return $this->build_result(
|
||||
'good',
|
||||
[],
|
||||
__( 'The MCP OAuth server is intentionally disabled (the <code>wpmedia_mcp_oauth_server_enabled</code> filter returns false), so the .well-known discovery documents are not expected to be reachable.', 'mcp-oauth' )
|
||||
);
|
||||
}
|
||||
|
||||
if ( '' === (string) get_option( 'permalink_structure' ) ) {
|
||||
return $this->build_result(
|
||||
'recommended',
|
||||
[],
|
||||
__( 'The .well-known OAuth discovery documents are served through a rewrite rule, which requires a pretty permalink structure. Enable one under Settings → Permalinks, then re-check this test.', 'mcp-oauth' )
|
||||
);
|
||||
}
|
||||
|
||||
$cached = get_transient( self::TRANSIENT_KEY );
|
||||
if ( is_array( $cached ) ) {
|
||||
return $cached;
|
||||
}
|
||||
|
||||
$worst_status = 'good';
|
||||
$failing = [];
|
||||
|
||||
foreach ( self::DOCUMENTS as $name => $path ) {
|
||||
$response = wp_safe_remote_get(
|
||||
home_url( $path ),
|
||||
[
|
||||
'timeout' => self::FETCH_TIMEOUT,
|
||||
]
|
||||
);
|
||||
|
||||
$status = $this->classify( $response );
|
||||
|
||||
if ( self::STATUS_RANK[ $status ] > self::STATUS_RANK[ $worst_status ] ) {
|
||||
$worst_status = $status;
|
||||
}
|
||||
|
||||
if ( 'good' !== $status ) {
|
||||
$failing[] = $name;
|
||||
}
|
||||
}
|
||||
|
||||
$result = $this->build_result( $worst_status, $failing );
|
||||
|
||||
set_transient( self::TRANSIENT_KEY, $result, self::TRANSIENT_TTL );
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify a single document's fetch result into a Site Health status.
|
||||
*
|
||||
* @param array<string, mixed>|WP_Error $response The wp_remote_get() response array, or a WP_Error.
|
||||
* @return string One of 'good', 'recommended', 'critical'.
|
||||
*/
|
||||
private function classify( $response ): string {
|
||||
if ( is_wp_error( $response ) ) {
|
||||
return 'recommended';
|
||||
}
|
||||
|
||||
$status_code = (int) wp_remote_retrieve_response_code( $response );
|
||||
|
||||
if ( in_array( $status_code, [ 401, 403, 407 ], true ) ) {
|
||||
return 'recommended';
|
||||
}
|
||||
|
||||
if ( 404 === $status_code ) {
|
||||
$powered_by = (string) wp_remote_retrieve_header( $response, 'x-powered-by' );
|
||||
$redirect_by = (string) wp_remote_retrieve_header( $response, 'x-redirect-by' );
|
||||
|
||||
if ( '' === $powered_by && false === stripos( $redirect_by, 'WordPress' ) ) {
|
||||
return 'critical';
|
||||
}
|
||||
|
||||
return 'recommended';
|
||||
}
|
||||
|
||||
if ( 200 === $status_code ) {
|
||||
$body = (string) wp_remote_retrieve_body( $response );
|
||||
$decoded = json_decode( $body, true );
|
||||
|
||||
if ( is_array( $decoded ) ) {
|
||||
return 'good';
|
||||
}
|
||||
}
|
||||
|
||||
return 'recommended';
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the Site Health result array for a given combined status.
|
||||
*
|
||||
* @param string $status One of 'good', 'recommended', 'critical'.
|
||||
* @param string[] $failing Display names of the documents that did not report 'good'.
|
||||
* @param string $summary Optional override for the description's leading sentence
|
||||
* (used by the disabled/plain-permalinks short-circuits).
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function build_result( string $status, array $failing, string $summary = '' ): array {
|
||||
$loopback_caveat = __( 'This check runs from the server to itself. A "Good" result here does not guarantee external clients can reach these documents: a CDN, WAF, or reverse proxy in front of the site can still 404 these paths for external traffic while the server\'s own loopback request bypasses it. Verify with an external <code>curl</code> request after applying any server-config change.', 'mcp-oauth' );
|
||||
|
||||
/*
|
||||
* The acme-challenge fingerprint is classified 'critical' internally so
|
||||
* the detailed guidance below is selected, but it is reported to Site
|
||||
* Health as 'recommended': the .well-known discovery documents are an
|
||||
* optional MCP feature, and a "critical" badge generates support tickets
|
||||
* for what is a non-blocking misconfiguration.
|
||||
*/
|
||||
$reported_status = 'critical' === $status ? 'recommended' : $status;
|
||||
|
||||
if ( '' !== $summary ) {
|
||||
$description = sprintf( '<p>%s</p>', $summary );
|
||||
$actions = sprintf( '<p>%s</p>', $loopback_caveat );
|
||||
} elseif ( 'good' === $status ) {
|
||||
$description = sprintf(
|
||||
'<p>%s</p>',
|
||||
__( 'Both .well-known OAuth discovery documents (oauth-protected-resource and oauth-authorization-server) responded with HTTP 200 and valid JSON.', 'mcp-oauth' )
|
||||
);
|
||||
$actions = sprintf( '<p>%s</p>', $loopback_caveat );
|
||||
} else {
|
||||
$document_list = implode( ', ', $failing );
|
||||
|
||||
if ( 'critical' === $status ) {
|
||||
$description = sprintf(
|
||||
'<p>%s</p>',
|
||||
sprintf(
|
||||
/* translators: %s: comma-separated list of failing discovery document names. */
|
||||
__( 'The following .well-known discovery document(s) returned a bare 404 with no WordPress-originated response header: %s. This matches the fingerprint of a physical .well-known/acme-challenge/ directory (provisioned by the host for Let\'s Encrypt auto-SSL) intercepting the request before WordPress runs — likely the cause here, though this should be confirmed against the actual .well-known/acme-challenge/ directory on the server before concluding root cause.', 'mcp-oauth' ),
|
||||
esc_html( $document_list )
|
||||
)
|
||||
);
|
||||
|
||||
$actions = sprintf(
|
||||
'<p>%s</p><p>%s</p><p>%s</p>',
|
||||
__( 'Apply the Apache or Nginx snippet from this library\'s README ("Hosting: .well-known conflicts") to re-enable routing for these two paths without touching acme-challenge/.', 'mcp-oauth' ),
|
||||
__( 'If a CDN or page cache is in front of the site, purge it after applying the fix — a stale cached 404 for these paths can otherwise persist even once the server config is corrected.', 'mcp-oauth' ),
|
||||
$loopback_caveat
|
||||
);
|
||||
} else {
|
||||
$description = sprintf(
|
||||
'<p>%s</p>',
|
||||
sprintf(
|
||||
/* translators: %s: comma-separated list of failing discovery document names. */
|
||||
__( 'The following .well-known discovery document(s) did not respond as expected: %s. This does not match the confirmed .well-known/acme-challenge/ interception fingerprint, so the cause is inconclusive from this check alone (it may be a timeout, an access wall such as HTTP Basic Auth or a WAF, or a WordPress-served error).', 'mcp-oauth' ),
|
||||
esc_html( $document_list )
|
||||
)
|
||||
);
|
||||
|
||||
$actions = sprintf(
|
||||
'<p>%s</p><p>%s</p>',
|
||||
__( 'Check your error/access logs for the requests to these paths, and rule out an authentication wall (staging HTTP Basic Auth, a WAF, or bot mitigation) before assuming a routing problem.', 'mcp-oauth' ),
|
||||
$loopback_caveat
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'label' => __( 'MCP OAuth discovery documents', 'mcp-oauth' ),
|
||||
'status' => $reported_status,
|
||||
'badge' => [
|
||||
'label' => __( 'Configuration', 'mcp-oauth' ),
|
||||
'color' => 'blue',
|
||||
],
|
||||
'description' => $description,
|
||||
'actions' => $actions,
|
||||
'test' => self::TEST_KEY,
|
||||
];
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
/**
|
||||
* Shared 404 helper for OAuth request handlers.
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
/**
|
||||
* Provides a clean 404 response for stale OAuth/discovery rewrite rules.
|
||||
*/
|
||||
trait Http404Trait {
|
||||
|
||||
/**
|
||||
* Force a clean 404 response.
|
||||
*
|
||||
* Used when a stale rewrite rule still routes a request to an OAuth or
|
||||
* discovery endpoint after the OAuth server has been disabled, before
|
||||
* rewrite rules have been flushed. Without this, WordPress's main query
|
||||
* would fall through to the homepage instead of returning a 404.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function force_404(): void {
|
||||
global $wp_query;
|
||||
$wp_query->set_404();
|
||||
status_header( 404 );
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
/**
|
||||
* JWT Helper — pure HS256 implementation with no external dependencies.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
/**
|
||||
* JWT encoder / decoder.
|
||||
*
|
||||
* Implements HS256 (HMAC-SHA256) signing. All methods are static so callers
|
||||
* never need to instantiate the class.
|
||||
*/
|
||||
class JWT {
|
||||
|
||||
/**
|
||||
* Encode a payload as a signed JWT.
|
||||
*
|
||||
* @param array<string, mixed> $payload Claims to include in the token.
|
||||
* @param string $secret HMAC signing secret.
|
||||
* @return string Signed JWT string.
|
||||
*/
|
||||
public static function encode( array $payload, string $secret ): string {
|
||||
$header = self::base64url_encode(
|
||||
(string) wp_json_encode(
|
||||
[
|
||||
'typ' => 'JWT',
|
||||
'alg' => 'HS256',
|
||||
]
|
||||
)
|
||||
);
|
||||
$body = self::base64url_encode( (string) wp_json_encode( $payload ) );
|
||||
$sig = self::base64url_encode( hash_hmac( 'sha256', $header . '.' . $body, $secret, true ) );
|
||||
|
||||
return $header . '.' . $body . '.' . $sig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode and verify a JWT.
|
||||
*
|
||||
* Returns null if the signature is invalid or (when $verify_expiry is true)
|
||||
* the token has expired. Pass false for $verify_expiry when the caller
|
||||
* needs to act on an expired token — e.g. the revocation endpoint, which
|
||||
* must accept expired tokens per RFC 7009.
|
||||
*
|
||||
* @param string $token JWT string.
|
||||
* @param string $secret HMAC signing secret.
|
||||
* @param bool $verify_expiry Whether to reject tokens whose exp has passed.
|
||||
* @return array<string, mixed>|null Decoded payload, or null on failure.
|
||||
*/
|
||||
public static function decode( string $token, string $secret, bool $verify_expiry = true ): ?array {
|
||||
$parts = explode( '.', $token );
|
||||
if ( 3 !== count( $parts ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
list( $header, $body, $signature ) = $parts;
|
||||
|
||||
// Pin the algorithm. We only ever issue and verify HS256; rejecting any
|
||||
// other alg (notably 'none') defends against algorithm-substitution
|
||||
// attacks explicitly rather than relying on the HMAC comparison alone.
|
||||
$header_data = json_decode( self::base64url_decode( $header ), true );
|
||||
if ( ! is_array( $header_data ) || 'HS256' !== ( $header_data['alg'] ?? '' ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$expected_sig = self::base64url_encode( hash_hmac( 'sha256', $header . '.' . $body, $secret, true ) );
|
||||
if ( ! hash_equals( $expected_sig, $signature ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$payload = json_decode( self::base64url_decode( $body ), true );
|
||||
if ( ! is_array( $payload ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ( $verify_expiry && isset( $payload['exp'] ) && (int) $payload['exp'] < time() ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base64URL-encode a binary string.
|
||||
*
|
||||
* @param string $data Raw bytes to encode.
|
||||
* @return string URL-safe base64 without padding.
|
||||
*/
|
||||
public static function base64url_encode( string $data ): string {
|
||||
return rtrim( strtr( base64_encode( $data ), '+/', '-_' ), '=' ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
|
||||
}
|
||||
|
||||
/**
|
||||
* Base64URL-decode a string.
|
||||
*
|
||||
* @param string $data URL-safe base64 string.
|
||||
* @return string Decoded binary string.
|
||||
*/
|
||||
private static function base64url_decode( string $data ): string {
|
||||
return (string) base64_decode( strtr( $data, '-_', '+/' ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
/**
|
||||
* OAuth Request Body Parser.
|
||||
*
|
||||
* Shared logic for parsing application/json or application/x-www-form-urlencoded
|
||||
* request bodies in OAuth endpoints (TokenEndpoint, RevokeEndpoint).
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
/**
|
||||
* Provides parse_body() to OAuth endpoint classes.
|
||||
*/
|
||||
trait ParseBodyTrait {
|
||||
|
||||
/**
|
||||
* Parse the request body from either JSON or form-encoded content.
|
||||
*
|
||||
* JSON bodies are capped at 32 KB to prevent memory exhaustion from
|
||||
* oversized payloads; form-encoded bodies are read from $_POST which
|
||||
* PHP already limits via the post_max_size ini setting.
|
||||
*
|
||||
* @return array<string, mixed> Associative array of body parameters.
|
||||
*/
|
||||
private function parse_body(): array {
|
||||
$content_type = isset( $_SERVER['CONTENT_TYPE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['CONTENT_TYPE'] ) ) : '';
|
||||
|
||||
if ( false !== strpos( $content_type, 'application/json' ) ) {
|
||||
$raw = substr( (string) file_get_contents( 'php://input' ), 0, 32768 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
|
||||
$body = json_decode( '' !== $raw ? $raw : '{}', true );
|
||||
return is_array( $body ) ? $body : [];
|
||||
}
|
||||
|
||||
// Form-encoded (application/x-www-form-urlencoded).
|
||||
// phpcs:ignore WordPress.Security.NonceVerification.Missing
|
||||
return array_map( 'sanitize_text_field', wp_unslash( $_POST ) );
|
||||
}
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
/**
|
||||
* Token Revocation Endpoint (RFC 7009).
|
||||
*
|
||||
* Handles POST /oauth/revoke. Accepts an access or refresh JWT, verifies its
|
||||
* signature (ignoring expiry per spec), then deletes the WordPress Application
|
||||
* Password that anchors the session. Because OAuthHttpTransport checks the
|
||||
* Application Password on every request, deletion immediately invalidates all
|
||||
* outstanding tokens for that session — no token store is needed.
|
||||
*
|
||||
* RFC 7009 §2.2 requires HTTP 200 even for unrecognisable or already-revoked
|
||||
* tokens; the response body is an empty JSON object `{}`.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
use WPMedia\MCP\OAuth\Logging\McpLogger;
|
||||
|
||||
/**
|
||||
* Revoke Endpoint.
|
||||
*/
|
||||
class RevokeEndpoint {
|
||||
use ParseBodyTrait;
|
||||
|
||||
/**
|
||||
* Handle the revocation request.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle_request(): void {
|
||||
$request_method = isset( $_SERVER['REQUEST_METHOD'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) : '';
|
||||
|
||||
McpLogger::log(
|
||||
'REVOKE',
|
||||
'revocation request received',
|
||||
[
|
||||
'method' => $request_method,
|
||||
'remote_addr' => isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '',
|
||||
'user_agent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '',
|
||||
]
|
||||
);
|
||||
|
||||
if ( 'POST' !== $request_method ) {
|
||||
McpLogger::log( 'REVOKE', 'rejected: wrong method', [ 'method' => $request_method ] );
|
||||
$this->send_error( 405, 'invalid_request', 'Method not allowed.' );
|
||||
return;
|
||||
}
|
||||
|
||||
$body = $this->parse_body();
|
||||
$token = sanitize_text_field( $body['token'] ?? '' );
|
||||
$client_id_param = esc_url_raw( $body['client_id'] ?? '' );
|
||||
|
||||
if ( '' === $token ) {
|
||||
McpLogger::log( 'REVOKE', 'rejected: missing token parameter' );
|
||||
$this->send_error( 400, 'invalid_request', 'token is required.' );
|
||||
return;
|
||||
}
|
||||
|
||||
$secret = SecretManager::get_secret();
|
||||
|
||||
// Decode without expiry check — RFC 7009 requires revoking even expired tokens.
|
||||
$claims = JWT::decode( $token, $secret, false );
|
||||
|
||||
if ( null === $claims ) {
|
||||
// Invalid signature or malformed token — return success per RFC 7009 §2.2.
|
||||
McpLogger::log( 'REVOKE', 'no-op: token not recognised (invalid signature or format)' );
|
||||
$this->send_success();
|
||||
return;
|
||||
}
|
||||
|
||||
$user_id = (int) ( $claims['sub'] ?? 0 );
|
||||
$app_pass_uuid = (string) ( $claims['app_pass_id'] ?? '' );
|
||||
|
||||
if ( 0 === $user_id || '' === $app_pass_uuid ) {
|
||||
McpLogger::log( 'REVOKE', 'no-op: token missing sub or app_pass_id claims' );
|
||||
$this->send_success();
|
||||
return;
|
||||
}
|
||||
|
||||
// Client binding check (RFC 7009 §2.1): if the caller supplied a client_id and
|
||||
// the token carries one, they must match. A mismatch silently succeeds — no
|
||||
// Application Password is deleted and no information about token ownership is
|
||||
// leaked to the caller.
|
||||
$token_client_id = (string) ( $claims['client_id'] ?? '' );
|
||||
if ( '' !== $client_id_param && '' !== $token_client_id && $client_id_param !== $token_client_id ) {
|
||||
McpLogger::log(
|
||||
'REVOKE',
|
||||
'no-op: client_id mismatch',
|
||||
[
|
||||
'param_client_id' => $client_id_param,
|
||||
'token_client_id' => $token_client_id,
|
||||
'user_id' => $user_id,
|
||||
]
|
||||
);
|
||||
$this->send_success();
|
||||
return;
|
||||
}
|
||||
|
||||
\WP_Application_Passwords::delete_application_password( $user_id, $app_pass_uuid );
|
||||
|
||||
McpLogger::log(
|
||||
'REVOKE',
|
||||
'session revoked',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'app_pass_uuid' => $app_pass_uuid,
|
||||
'client_id' => $token_client_id,
|
||||
'token_type' => isset( $claims['type'] ) && 'refresh' === $claims['type'] ? 'refresh' : 'access',
|
||||
]
|
||||
);
|
||||
|
||||
$this->send_success();
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a successful revocation response (HTTP 200, empty JSON object).
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function send_success(): void {
|
||||
nocache_headers();
|
||||
wp_send_json( new \stdClass() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a JSON error response and exit.
|
||||
*
|
||||
* @param int $status HTTP status code.
|
||||
* @param string $error OAuth error code.
|
||||
* @param string $description Optional human-readable description.
|
||||
* @return void
|
||||
*/
|
||||
private function send_error( int $status, string $error, string $description = '' ): void {
|
||||
status_header( $status );
|
||||
nocache_headers();
|
||||
$body = [ 'error' => $error ];
|
||||
if ( '' !== $description ) {
|
||||
$body['error_description'] = $description;
|
||||
}
|
||||
wp_send_json( $body );
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
/**
|
||||
* OAuth 2.1 Rewrite Rules.
|
||||
*
|
||||
* Registers the WordPress rewrite rules and query var used to route the
|
||||
* five OAuth endpoints (authorize, authorize-callback, token, consent,
|
||||
* revoke).
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
/**
|
||||
* Registers OAuth endpoint rewrite rules and the query var used to route them.
|
||||
*/
|
||||
class Rewrite {
|
||||
|
||||
/**
|
||||
* WordPress query var used to route OAuth endpoint requests.
|
||||
*/
|
||||
const OAUTH_QUERY_VAR = 'mcp_oauth_endpoint';
|
||||
|
||||
/**
|
||||
* Canary rule key used to detect whether the OAuth rules are persisted.
|
||||
*/
|
||||
const AUTHORIZE_RULE = '^oauth/authorize$';
|
||||
|
||||
/**
|
||||
* Register WordPress rewrite rules for all five OAuth endpoints.
|
||||
*
|
||||
* Called on the 'init' action (normal page load).
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_oauth_rewrite_rules(): void {
|
||||
add_rewrite_rule( self::AUTHORIZE_RULE, 'index.php?' . self::OAUTH_QUERY_VAR . '=authorize', 'top' );
|
||||
add_rewrite_rule( '^oauth/authorize-callback$', 'index.php?' . self::OAUTH_QUERY_VAR . '=authorize-callback', 'top' );
|
||||
add_rewrite_rule( '^oauth/token$', 'index.php?' . self::OAUTH_QUERY_VAR . '=token', 'top' );
|
||||
add_rewrite_rule( '^oauth/consent$', 'index.php?' . self::OAUTH_QUERY_VAR . '=consent', 'top' );
|
||||
add_rewrite_rule( '^oauth/revoke$', 'index.php?' . self::OAUTH_QUERY_VAR . '=revoke', 'top' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the OAuth query var to WordPress's list of recognised vars.
|
||||
*
|
||||
* @param string[] $vars Existing query vars.
|
||||
* @return string[] Modified list.
|
||||
*/
|
||||
public function add_oauth_query_vars( array $vars ): array {
|
||||
$vars[] = self::OAUTH_QUERY_VAR;
|
||||
|
||||
return $vars;
|
||||
}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
<?php
|
||||
/**
|
||||
* MCP Auth Router.
|
||||
*
|
||||
* Wires the OAuth 2.1 endpoint routing. Registered directly by Bootstrap via
|
||||
* add_action()/add_filter() calls. Plugin lifecycle (activation) is handled
|
||||
* separately by Rewrite and SecretManager.
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
use WPMedia\MCP\OAuth\Context;
|
||||
|
||||
/**
|
||||
* Registers OAuth endpoint routing callbacks.
|
||||
*/
|
||||
class Router {
|
||||
|
||||
use Http404Trait;
|
||||
|
||||
/**
|
||||
* OAuth rewrite rules and query var registration.
|
||||
*
|
||||
* @var Rewrite
|
||||
*/
|
||||
private Rewrite $rewrite;
|
||||
|
||||
/**
|
||||
* Authorize endpoint handler.
|
||||
*
|
||||
* @var AuthorizeEndpoint
|
||||
*/
|
||||
private AuthorizeEndpoint $authorize_endpoint;
|
||||
|
||||
/**
|
||||
* Authorize callback handler.
|
||||
*
|
||||
* @var AuthorizeCallback
|
||||
*/
|
||||
private AuthorizeCallback $authorize_callback;
|
||||
|
||||
/**
|
||||
* Token endpoint handler.
|
||||
*
|
||||
* @var TokenEndpoint
|
||||
*/
|
||||
private TokenEndpoint $token_endpoint;
|
||||
|
||||
/**
|
||||
* Consent endpoint handler.
|
||||
*
|
||||
* @var ConsentEndpoint
|
||||
*/
|
||||
private ConsentEndpoint $consent_endpoint;
|
||||
|
||||
/**
|
||||
* Revoke endpoint handler.
|
||||
*
|
||||
* @var RevokeEndpoint
|
||||
*/
|
||||
private RevokeEndpoint $revoke_endpoint;
|
||||
|
||||
/**
|
||||
* OAuth server context.
|
||||
*
|
||||
* @var Context
|
||||
*/
|
||||
private Context $context;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param Rewrite $rewrite OAuth rewrite rules and query var registration.
|
||||
* @param AuthorizeEndpoint $authorize_endpoint Authorization endpoint.
|
||||
* @param AuthorizeCallback $authorize_callback Authorization callback.
|
||||
* @param TokenEndpoint $token_endpoint Token endpoint.
|
||||
* @param ConsentEndpoint $consent_endpoint Consent endpoint.
|
||||
* @param RevokeEndpoint $revoke_endpoint Revocation endpoint.
|
||||
* @param Context $context OAuth server context.
|
||||
*/
|
||||
public function __construct(
|
||||
Rewrite $rewrite,
|
||||
AuthorizeEndpoint $authorize_endpoint,
|
||||
AuthorizeCallback $authorize_callback,
|
||||
TokenEndpoint $token_endpoint,
|
||||
ConsentEndpoint $consent_endpoint,
|
||||
RevokeEndpoint $revoke_endpoint,
|
||||
Context $context
|
||||
) {
|
||||
$this->rewrite = $rewrite;
|
||||
$this->authorize_endpoint = $authorize_endpoint;
|
||||
$this->authorize_callback = $authorize_callback;
|
||||
$this->token_endpoint = $token_endpoint;
|
||||
$this->consent_endpoint = $consent_endpoint;
|
||||
$this->revoke_endpoint = $revoke_endpoint;
|
||||
$this->context = $context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register WordPress rewrite rules for all five OAuth endpoints.
|
||||
*
|
||||
* Called on the 'init' action (normal page load).
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_rewrite_rules(): void {
|
||||
if ( ! $this->context->is_enabled() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->rewrite->register_oauth_rewrite_rules();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the OAuth query var to WordPress's list of recognised vars.
|
||||
*
|
||||
* @param string[] $vars Existing query vars.
|
||||
* @return string[] Modified list.
|
||||
*/
|
||||
public function add_query_vars( array $vars ): array {
|
||||
return $this->rewrite->add_oauth_query_vars( $vars );
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch an incoming OAuth endpoint request to the appropriate handler.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle_request(): void {
|
||||
$endpoint = (string) get_query_var( Rewrite::OAUTH_QUERY_VAR, '' );
|
||||
|
||||
if ( '' === $endpoint ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! $this->context->is_enabled() ) {
|
||||
$this->force_404();
|
||||
return;
|
||||
}
|
||||
|
||||
switch ( $endpoint ) {
|
||||
case 'authorize':
|
||||
$this->authorize_endpoint->handle_request();
|
||||
break;
|
||||
case 'authorize-callback':
|
||||
$this->authorize_callback->handle_request();
|
||||
break;
|
||||
case 'consent':
|
||||
$this->consent_endpoint->handle_request();
|
||||
break;
|
||||
case 'revoke':
|
||||
$this->revoke_endpoint->handle_request();
|
||||
break;
|
||||
case 'token':
|
||||
$this->token_endpoint->handle_request();
|
||||
break;
|
||||
default:
|
||||
status_header( 404 );
|
||||
wp_die( esc_html__( 'Unknown OAuth endpoint.', 'mcp-oauth' ), '', [ 'response' => 404 ] );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the refresh-token rotation marker when a session's Application
|
||||
* Password is deleted.
|
||||
*
|
||||
* @param int $user_id WordPress user ID.
|
||||
* @param array<string, mixed> $item The Application Password record being deleted.
|
||||
* @return void
|
||||
*/
|
||||
public function purge_refresh_jti_meta( $user_id, $item ): void {
|
||||
$this->token_endpoint->purge_refresh_jti_meta( (int) $user_id, (array) $item );
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
/**
|
||||
* Site Secret Manager.
|
||||
*
|
||||
* Generates, stores, and rotates the 256-bit HMAC secret used to sign all
|
||||
* MCP JWTs. Regenerating the secret immediately invalidates every outstanding
|
||||
* access and refresh token site-wide.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
/**
|
||||
* Secret Manager.
|
||||
*/
|
||||
class SecretManager {
|
||||
|
||||
/**
|
||||
* WordPress option key where the JWT signing secret is stored.
|
||||
*/
|
||||
const OPTION_KEY = 'mcp_jwt_secret';
|
||||
|
||||
/**
|
||||
* Return the current site JWT signing secret, generating one if absent.
|
||||
*
|
||||
* Uses add_option() for the initial write so that two concurrent requests
|
||||
* racing on first activation cannot both store different secrets — only one
|
||||
* caller's add_option() succeeds; the other reads back the winner's value.
|
||||
*
|
||||
* @return string Hex-encoded 256-bit secret.
|
||||
*/
|
||||
public static function get_secret(): string {
|
||||
$secret = (string) get_option( self::OPTION_KEY, '' );
|
||||
if ( '' !== $secret ) {
|
||||
return $secret;
|
||||
}
|
||||
|
||||
$candidate = self::generate();
|
||||
if ( ! add_option( self::OPTION_KEY, $candidate, '', false ) ) {
|
||||
// Another request won the race; read back whatever was stored.
|
||||
$candidate = (string) get_option( self::OPTION_KEY );
|
||||
}
|
||||
|
||||
return $candidate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure a secret exists; create one on first activation.
|
||||
*
|
||||
* Idempotent — safe to call on every activation.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function ensure_secret(): void {
|
||||
self::get_secret();
|
||||
}
|
||||
|
||||
/**
|
||||
* Regenerate the site secret, invalidating all current MCP sessions.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function regenerate(): void {
|
||||
update_option( self::OPTION_KEY, self::generate(), false );
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a fresh 256-bit random secret as a hex string.
|
||||
*
|
||||
* @return string 64-character hex string.
|
||||
*/
|
||||
private static function generate(): string {
|
||||
return bin2hex( random_bytes( 32 ) );
|
||||
}
|
||||
}
|
||||
+517
@@ -0,0 +1,517 @@
|
||||
<?php
|
||||
/**
|
||||
* Token Endpoint.
|
||||
*
|
||||
* Handles POST /oauth/token for two grant types:
|
||||
* - authorization_code: PKCE verification → create Application Password → issue JWT pair.
|
||||
* - refresh_token: verify refresh JWT → revocation check → issue new access JWT.
|
||||
*
|
||||
* Raw Application Passwords are never stored and are discarded immediately
|
||||
* after creation. Only the UUID is retained inside the JWT claims for
|
||||
* revocation checking.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WPMedia\MCP\OAuth\Auth;
|
||||
|
||||
use WPMedia\MCP\OAuth\Logging\McpLogger;
|
||||
|
||||
class TokenEndpoint {
|
||||
use ParseBodyTrait;
|
||||
|
||||
/**
|
||||
* User-meta key prefix storing the currently valid refresh-token id (jti)
|
||||
* for a session. The session is identified by its Application Password UUID,
|
||||
* so the full key is REFRESH_JTI_META_PREFIX . $app_pass_uuid.
|
||||
*/
|
||||
const REFRESH_JTI_META_PREFIX = 'mcp_refresh_jti_';
|
||||
|
||||
/**
|
||||
* Maximum number of concurrent MCP sessions (Application Passwords) retained
|
||||
* per user per client. Every successful code exchange mints a new Application
|
||||
* Password, so a client that re-runs the authorize→token flow repeatedly would
|
||||
* otherwise accumulate unbounded rows — bloating the user's Application
|
||||
* Passwords screen and slowing the per-request revocation lookup in
|
||||
* OAuthHttpTransport, which scans all of the user's Application Passwords. When
|
||||
* a new session would exceed this cap, the oldest sessions for that client are
|
||||
* evicted first.
|
||||
*/
|
||||
const MAX_SESSIONS_PER_CLIENT = 5;
|
||||
|
||||
/**
|
||||
* Handle the token request.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle_request(): void {
|
||||
$request_method = isset( $_SERVER['REQUEST_METHOD'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) : '';
|
||||
$content_type = isset( $_SERVER['CONTENT_TYPE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['CONTENT_TYPE'] ) ) : '';
|
||||
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'token request received',
|
||||
[
|
||||
'method' => $request_method,
|
||||
'content_type' => $content_type,
|
||||
'remote_addr' => isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '',
|
||||
'user_agent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '',
|
||||
'headers' => McpLogger::safe_request_headers(),
|
||||
'body' => McpLogger::safe_request_body(),
|
||||
]
|
||||
);
|
||||
|
||||
if ( 'POST' !== $request_method ) {
|
||||
McpLogger::log( 'TOKEN', 'rejected: wrong method', [ 'method' => $request_method ] );
|
||||
$this->send_error( 405, 'invalid_request', 'Method not allowed.' );
|
||||
return;
|
||||
}
|
||||
|
||||
$body = $this->parse_body();
|
||||
|
||||
$grant_type = sanitize_text_field( $body['grant_type'] ?? '' );
|
||||
|
||||
McpLogger::log( 'TOKEN', 'grant_type received', [ 'grant_type' => $grant_type ] );
|
||||
|
||||
if ( 'authorization_code' === $grant_type ) {
|
||||
$this->handle_authorization_code( $body );
|
||||
} elseif ( 'refresh_token' === $grant_type ) {
|
||||
$this->handle_refresh_token( $body );
|
||||
} else {
|
||||
McpLogger::log( 'TOKEN', 'rejected: unsupported grant_type', [ 'grant_type' => $grant_type ] );
|
||||
$this->send_error( 400, 'unsupported_grant_type' );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Exchange an auth code for a JWT pair.
|
||||
*
|
||||
* @param array<string, mixed> $body Parsed request body.
|
||||
* @return void
|
||||
*/
|
||||
private function handle_authorization_code( array $body ): void {
|
||||
$code = sanitize_text_field( $body['code'] ?? '' );
|
||||
$code_verifier = sanitize_text_field( $body['code_verifier'] ?? '' );
|
||||
$redirect_uri = esc_url_raw( $body['redirect_uri'] ?? '' );
|
||||
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'authorization_code exchange: params',
|
||||
[
|
||||
'has_code' => '' !== $code ? 'yes' : 'no',
|
||||
'has_code_verifier' => '' !== $code_verifier ? 'yes' : 'no',
|
||||
'redirect_uri' => $redirect_uri,
|
||||
]
|
||||
);
|
||||
|
||||
if ( '' === $code || '' === $code_verifier ) {
|
||||
McpLogger::log( 'TOKEN', 'rejected: missing code or code_verifier' );
|
||||
$this->send_error( 400, 'invalid_request', 'code and code_verifier are required.' );
|
||||
return;
|
||||
}
|
||||
|
||||
// Look up the single-use code, then atomically consume it. delete_transient()
|
||||
// returns true for only one caller when two requests race for the same code
|
||||
// (delete_option / wp_cache_delete report the row/key they actually removed),
|
||||
// so a double-submitted or replayed code is rejected here rather than minting
|
||||
// a second session.
|
||||
$code_key = 'mcp_oauth_code_' . $code;
|
||||
$code_data = get_transient( $code_key );
|
||||
|
||||
if ( false === $code_data || ! is_array( $code_data ) ) {
|
||||
McpLogger::log( 'TOKEN', 'rejected: auth code transient missing or expired (60 s window)' );
|
||||
$this->send_error( 400, 'invalid_grant', 'Code is invalid or has expired.' );
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! delete_transient( $code_key ) ) {
|
||||
McpLogger::log( 'TOKEN', 'rejected: auth code already consumed (concurrent redemption)' );
|
||||
$this->send_error( 400, 'invalid_grant', 'Code is invalid or has expired.' );
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify PKCE S256: BASE64URL(SHA256(verifier)) must equal stored challenge.
|
||||
$expected = JWT::base64url_encode( hash( 'sha256', $code_verifier, true ) );
|
||||
|
||||
if ( ! hash_equals( (string) $code_data['code_challenge'], $expected ) ) {
|
||||
McpLogger::log( 'TOKEN', 'rejected: PKCE code_verifier does not match challenge' );
|
||||
$this->send_error( 400, 'invalid_grant', 'PKCE code_verifier does not match challenge.' );
|
||||
return;
|
||||
}
|
||||
|
||||
// redirect_uri is required whenever it was included in the authorization request
|
||||
// (OAuth 2.1 §4.1.3). AuthorizeEndpoint always requires it, so code_data always
|
||||
// contains a non-empty value. Exact match is enforced; the client must send the
|
||||
// same runtime URI (including ephemeral port for loopback) it used at authorize time.
|
||||
if ( $redirect_uri !== (string) $code_data['redirect_uri'] ) {
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'rejected: redirect_uri missing or does not match authorization request',
|
||||
[
|
||||
'provided' => $redirect_uri,
|
||||
'stored' => $code_data['redirect_uri'],
|
||||
]
|
||||
);
|
||||
$this->send_error( 400, 'invalid_grant', 'redirect_uri is required and must match the authorization request.' );
|
||||
return;
|
||||
}
|
||||
|
||||
$user_id = (int) $code_data['user_id'];
|
||||
$client_id = (string) ( $code_data['client_id'] ?? '' );
|
||||
|
||||
// The Application Password name is required by WordPress core and must be
|
||||
// non-empty. Fall back to the client host when the CIMD document omitted a
|
||||
// client_name so a sparse-but-valid client cannot break the token exchange.
|
||||
$client_name = (string) ( $code_data['client_name'] ?? '' );
|
||||
if ( '' === $client_name ) {
|
||||
$client_name = (string) wp_parse_url( $client_id, PHP_URL_HOST );
|
||||
}
|
||||
if ( '' === $client_name ) {
|
||||
$client_name = 'MCP Client';
|
||||
}
|
||||
|
||||
McpLogger::log( 'TOKEN', 'PKCE verified — creating Application Password', [ 'user_id' => $user_id ] );
|
||||
|
||||
// Bound the number of sessions this client can stockpile before adding one more.
|
||||
$this->prune_sessions( $user_id, $client_id );
|
||||
|
||||
// Create a WordPress Application Password (raw password is discarded).
|
||||
$result = \WP_Application_Passwords::create_new_application_password(
|
||||
$user_id,
|
||||
[
|
||||
'name' => $client_name,
|
||||
'app_id' => $client_id,
|
||||
],
|
||||
);
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'server_error: Application Password creation failed',
|
||||
[
|
||||
'wp_error_code' => $result->get_error_code(),
|
||||
'wp_error_message' => $result->get_error_message(),
|
||||
'user_id' => $user_id,
|
||||
]
|
||||
);
|
||||
$this->send_error( 500, 'server_error', 'Could not create MCP session.' );
|
||||
return;
|
||||
}
|
||||
|
||||
// create_new_application_password() returns [raw_password, metadata]. Raw password is discarded.
|
||||
$app_pass_uuid = (string) $result[1]['uuid'];
|
||||
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'Application Password created — issuing token pair',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'app_pass_uuid' => $app_pass_uuid,
|
||||
]
|
||||
);
|
||||
|
||||
$this->issue_token_pair( $user_id, $app_pass_uuid, $client_id );
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh an access token using a valid refresh JWT.
|
||||
*
|
||||
* @param array<string, mixed> $body Parsed request body.
|
||||
* @return void
|
||||
*/
|
||||
private function handle_refresh_token( array $body ): void {
|
||||
$refresh_token = sanitize_text_field( $body['refresh_token'] ?? '' );
|
||||
|
||||
McpLogger::log( 'TOKEN', 'refresh_token grant: validating', [ 'has_refresh_token' => '' !== $refresh_token ? 'yes' : 'no' ] );
|
||||
|
||||
if ( '' === $refresh_token ) {
|
||||
McpLogger::log( 'TOKEN', 'rejected: refresh_token missing' );
|
||||
$this->send_error( 400, 'invalid_request', 'refresh_token is required.' );
|
||||
return;
|
||||
}
|
||||
|
||||
$secret = SecretManager::get_secret();
|
||||
$claims = JWT::decode( $refresh_token, $secret );
|
||||
|
||||
if ( null === $claims || 'refresh' !== ( $claims['type'] ?? '' ) ) {
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'rejected: refresh token decode failed or wrong type',
|
||||
[
|
||||
'claims_null' => null === $claims ? 'yes' : 'no',
|
||||
'type' => null !== $claims ? ( $claims['type'] ?? '(missing)' ) : 'n/a',
|
||||
]
|
||||
);
|
||||
$this->send_error( 401, 'invalid_token', 'Refresh token is invalid or expired.' );
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify the token was issued by this site. A staging clone sharing the same
|
||||
// JWT secret would otherwise allow cross-site token replay.
|
||||
$token_iss = (string) ( $claims['iss'] ?? '' );
|
||||
if ( home_url() !== $token_iss ) {
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'rejected: refresh token issuer mismatch',
|
||||
[
|
||||
'token_iss' => $token_iss,
|
||||
'expected_iss' => home_url(),
|
||||
]
|
||||
);
|
||||
$this->send_error( 401, 'invalid_token', 'Refresh token was not issued by this server.' );
|
||||
return;
|
||||
}
|
||||
|
||||
$user_id = (int) $claims['sub'];
|
||||
$app_pass_uuid = (string) ( $claims['app_pass_id'] ?? '' );
|
||||
$client_id = (string) ( $claims['client_id'] ?? '' );
|
||||
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'refresh token decoded — checking revocation',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'app_pass_uuid' => $app_pass_uuid,
|
||||
]
|
||||
);
|
||||
|
||||
// Revocation check: if the Application Password was deleted the session is gone.
|
||||
$app_pass = \WP_Application_Passwords::get_user_application_password( $user_id, $app_pass_uuid );
|
||||
|
||||
if ( ! is_array( $app_pass ) ) {
|
||||
// Session is gone; drop the now-orphaned rotation marker too.
|
||||
delete_user_meta( $user_id, self::REFRESH_JTI_META_PREFIX . $app_pass_uuid );
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'rejected: Application Password revoked or not found',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'app_pass_uuid' => $app_pass_uuid,
|
||||
]
|
||||
);
|
||||
$this->send_error( 401, 'invalid_token', 'MCP session has been revoked.' );
|
||||
return;
|
||||
}
|
||||
|
||||
// Refresh-token rotation / reuse detection (OAuth 2.1 §4.3.1, RFC 6819 §5.2.2.3).
|
||||
// Each issued refresh token carries a unique jti; only the most recently
|
||||
// issued jti for this session is accepted. Presenting any other (i.e. an
|
||||
// already-rotated, previously-consumed) refresh token means the token has
|
||||
// leaked and is being replayed — revoke the whole session so the attacker
|
||||
// and the legitimate client are both forced to re-authenticate.
|
||||
$presented_jti = (string) ( $claims['jti'] ?? '' );
|
||||
$current_jti = (string) get_user_meta( $user_id, self::REFRESH_JTI_META_PREFIX . $app_pass_uuid, true );
|
||||
|
||||
if ( '' === $presented_jti || '' === $current_jti || ! hash_equals( $current_jti, $presented_jti ) ) {
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'SECURITY: refresh token reuse detected — revoking session',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'app_pass_uuid' => $app_pass_uuid,
|
||||
'has_presented' => '' !== $presented_jti ? 'yes' : 'no',
|
||||
'has_current' => '' !== $current_jti ? 'yes' : 'no',
|
||||
]
|
||||
);
|
||||
// Deleting the Application Password fires wp_delete_application_password,
|
||||
// which purges the rotation marker via purge_refresh_jti_meta().
|
||||
\WP_Application_Passwords::delete_application_password( $user_id, $app_pass_uuid );
|
||||
$this->send_error( 401, 'invalid_grant', 'Refresh token has been revoked.' );
|
||||
return;
|
||||
}
|
||||
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'refresh token valid — issuing new token pair',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'app_pass_uuid' => $app_pass_uuid,
|
||||
]
|
||||
);
|
||||
|
||||
// Issue a new access token and rotate the refresh token: issue_token_pair()
|
||||
// mints a fresh jti and overwrites the stored marker, invalidating the
|
||||
// refresh token just presented.
|
||||
$this->issue_token_pair( $user_id, $app_pass_uuid, $client_id );
|
||||
}
|
||||
|
||||
/**
|
||||
* Build and return an access + refresh JWT pair.
|
||||
*
|
||||
* @param int $user_id WordPress user ID.
|
||||
* @param string $app_pass_uuid UUID of the Application Password.
|
||||
* @param string $client_id Client ID URL from the CIMD record.
|
||||
* @return void
|
||||
*/
|
||||
private function issue_token_pair( int $user_id, string $app_pass_uuid, string $client_id = '' ): void {
|
||||
$secret = SecretManager::get_secret();
|
||||
// iss is home_url() (the Site Address), matching the base get_rest_url()
|
||||
// uses for aud and where the OAuth/.well-known routes are actually served.
|
||||
$issuer = home_url();
|
||||
$now = time();
|
||||
$aud = get_rest_url( null, 'mcp/mcp-oauth-server' );
|
||||
|
||||
// Mint a fresh refresh-token id and persist it as the only one accepted
|
||||
// for this session. This overwrites any prior marker, so the previously
|
||||
// issued refresh token (if any) is invalidated the instant this returns.
|
||||
$refresh_jti = bin2hex( random_bytes( 16 ) );
|
||||
update_user_meta( $user_id, self::REFRESH_JTI_META_PREFIX . $app_pass_uuid, $refresh_jti );
|
||||
|
||||
$access_payload = [
|
||||
'iss' => $issuer,
|
||||
'aud' => $aud,
|
||||
'sub' => (string) $user_id,
|
||||
'app_pass_id' => $app_pass_uuid,
|
||||
'client_id' => $client_id,
|
||||
'scope' => 'mcp',
|
||||
'iat' => $now,
|
||||
'exp' => $now + HOUR_IN_SECONDS,
|
||||
];
|
||||
|
||||
$refresh_payload = [
|
||||
'iss' => $issuer,
|
||||
'sub' => (string) $user_id,
|
||||
'app_pass_id' => $app_pass_uuid,
|
||||
'client_id' => $client_id,
|
||||
'type' => 'refresh',
|
||||
'jti' => $refresh_jti,
|
||||
'iat' => $now,
|
||||
'exp' => $now + ( 30 * DAY_IN_SECONDS ),
|
||||
];
|
||||
|
||||
$access_token = JWT::encode( $access_payload, $secret );
|
||||
$refresh_token = JWT::encode( $refresh_payload, $secret );
|
||||
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'token pair issued',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'app_pass_uuid' => $app_pass_uuid,
|
||||
'access_exp' => $access_payload['exp'],
|
||||
'refresh_exp' => $refresh_payload['exp'],
|
||||
'access_token_len' => strlen( $access_token ),
|
||||
]
|
||||
);
|
||||
|
||||
nocache_headers();
|
||||
wp_send_json(
|
||||
[
|
||||
'access_token' => $access_token,
|
||||
'token_type' => 'Bearer',
|
||||
'expires_in' => HOUR_IN_SECONDS,
|
||||
'refresh_token' => $refresh_token,
|
||||
'scope' => 'mcp',
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Evict the oldest MCP sessions for a user+client so that creating one more
|
||||
* stays within MAX_SESSIONS_PER_CLIENT.
|
||||
*
|
||||
* Only Application Passwords this feature created are considered — they are
|
||||
* matched by the `app_id` we set to the client_id at creation time, so
|
||||
* Application Passwords the user created for other integrations are never
|
||||
* touched. Deleting one fires `wp_delete_application_password`, which removes
|
||||
* its `mcp_refresh_jti_*` meta via purge_refresh_jti_meta(), so no orphaned
|
||||
* rows are left behind.
|
||||
*
|
||||
* @param int $user_id WordPress user ID.
|
||||
* @param string $client_id Client ID URL the sessions belong to.
|
||||
* @return void
|
||||
*/
|
||||
private function prune_sessions( int $user_id, string $client_id ): void {
|
||||
if ( '' === $client_id ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$passwords = \WP_Application_Passwords::get_user_application_passwords( $user_id );
|
||||
|
||||
// Keep only this feature's Application Passwords for this client.
|
||||
$ours = array_values(
|
||||
array_filter(
|
||||
$passwords,
|
||||
static function ( $item ) use ( $client_id ) {
|
||||
return $item['app_id'] === $client_id;
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
// Below the cap: the new session about to be created still fits.
|
||||
if ( count( $ours ) < self::MAX_SESSIONS_PER_CLIENT ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Oldest first.
|
||||
usort(
|
||||
$ours,
|
||||
static function ( $a, $b ) {
|
||||
return $a['created'] <=> $b['created'];
|
||||
}
|
||||
);
|
||||
|
||||
// Evict enough of the oldest so that, after the new one is created, the
|
||||
// total sits at exactly MAX_SESSIONS_PER_CLIENT.
|
||||
$evict_count = ( count( $ours ) - self::MAX_SESSIONS_PER_CLIENT ) + 1;
|
||||
|
||||
for ( $i = 0; $i < $evict_count; $i++ ) {
|
||||
$uuid = (string) ( $ours[ $i ]['uuid'] ?? '' );
|
||||
if ( '' === $uuid ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
\WP_Application_Passwords::delete_application_password( $user_id, $uuid );
|
||||
|
||||
McpLogger::log(
|
||||
'TOKEN',
|
||||
'evicted oldest MCP session to enforce per-client cap',
|
||||
[
|
||||
'user_id' => $user_id,
|
||||
'client_id' => $client_id,
|
||||
'app_pass_uuid' => $uuid,
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purge the stored refresh-token rotation marker for a deleted session.
|
||||
*
|
||||
* Hooked on WordPress's `wp_delete_application_password` action so the
|
||||
* per-session user meta is removed wherever the Application Password that
|
||||
* anchors the session is deleted — the revoke endpoint, the admin page, or
|
||||
* WordPress core — leaving no orphaned rows behind.
|
||||
*
|
||||
* @param int $user_id WordPress user ID.
|
||||
* @param array<string, mixed> $item The Application Password record being deleted.
|
||||
* @return void
|
||||
*/
|
||||
public function purge_refresh_jti_meta( int $user_id, array $item ): void {
|
||||
$uuid = (string) ( $item['uuid'] ?? '' );
|
||||
|
||||
if ( '' === $uuid ) {
|
||||
return;
|
||||
}
|
||||
|
||||
delete_user_meta( $user_id, self::REFRESH_JTI_META_PREFIX . $uuid );
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a JSON error response and exit.
|
||||
*
|
||||
* @param int $status HTTP status code.
|
||||
* @param string $error OAuth error code.
|
||||
* @param string $description Optional human-readable description.
|
||||
* @return void
|
||||
*/
|
||||
private function send_error( int $status, string $error, string $description = '' ): void {
|
||||
status_header( $status );
|
||||
nocache_headers();
|
||||
$body = [ 'error' => $error ];
|
||||
if ( '' !== $description ) {
|
||||
$body['error_description'] = $description;
|
||||
}
|
||||
wp_send_json( $body );
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user