rejected = false; $token = $this->bearer_token(); if ( null === $token ) { return $user_id; } $agent = $this->tokens->verify( $token ); // An administrator-run agent is never issued a token (AF-25.15); one // that reached the row anyway does not authenticate it. if ( null === $agent || $agent->runs_as_admin() ) { $this->rejected = true; return $user_id; } if ( ! AgentContext::is_agent_request() ) { AgentContext::establish( $agent ); } return $agent->wp_user_id; } /** * Reject requests that presented an invalid agent token. * * @param \WP_Error|true|null $result Result from earlier handlers. * @return \WP_Error|true|null */ public function rest_authentication_errors( $result ) { if ( null !== $result ) { return $result; } if ( $this->rejected ) { return new \WP_Error( 'adaf_invalid_token', __( 'The agent token presented is unknown, revoked, or belongs to a disabled agent. Retrying will not help; request a new token from a site administrator.', 'agentic-daisy-ai-agent-firewall' ), array( 'status' => 401, 'reason' => 'invalid_token', 'retryable' => false, ) ); } return $result; } /** * Extract an agent bearer token from the Authorization header. * * Only `Bearer ag_live_*` credentials are claimed; Basic auth and other * bearer tokens (application passwords, OAuth) are left to their handlers. * * @return string|null The token, or null when this request presents none. */ private function bearer_token(): ?string { $header = ''; if ( isset( $_SERVER['HTTP_AUTHORIZATION'] ) ) { $header = sanitize_text_field( wp_unslash( (string) $_SERVER['HTTP_AUTHORIZATION'] ) ); } elseif ( isset( $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ) ) { $header = sanitize_text_field( wp_unslash( (string) $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ) ); } if ( '' === $header ) { return null; } if ( 1 !== preg_match( '/^Bearer\s+(ag_live_[A-Za-z0-9_\-]+)$/i', $header, $matches ) ) { return null; } return $matches[1]; } }