Files
wordpress-sso/tests/wordpress-test.php
Polyedre 6b54fd524b OpenFlyers SSO WordPress plugin 1.2.0
Read the member name and email from a custom report (profile_report_id).
2026-11-18 20:30:16 +01:00

476 lines
22 KiB
PHP

<?php
/**
* Functional test of the plugin inside a real WordPress installation.
*
* Run it from the command line, from the root of a WordPress site where this plugin is installed:
* php wp-content/plugins/openflyers-sso/tests/wordpress-test.php
*
* The site can also be named explicitly, which is needed when the plugin folder is a symbolic
* link or a junction pointing outside the site:
* php wordpress-test.php C:\wamp64\www\my-site
*
* It activates the plugin, then exercises the login start, the callback error paths,
* the account resolution modes, the shortcodes, the settings screen and the member
* linking field. It creates and removes its own test accounts and contacts no server.
*/
define('WP_USE_THEMES', false);
$_SERVER['HTTP_HOST'] = 'localhost';
$_SERVER['REQUEST_URI'] = '/';
$_SERVER['SERVER_NAME'] = 'localhost';
$_SERVER['REQUEST_METHOD'] = 'GET';
$fail = 0;
function check($label, $ok, $detail = '')
{
global $fail;
echo ($ok ? ' OK ' : ' FAIL ') . $label . ($detail !== '' ? " [$detail]" : '') . "\n";
if (!$ok) {
$fail++;
}
}
/**
* Locate the WordPress bootstrap.
*
* The plugin folder is often a symbolic link or a junction to a working copy kept outside the
* site, in which case walking up from this file lands somewhere else entirely. So an explicit
* path wins, then the working directory, then this file's own location.
*
* @return string|null
*/
function ofSsoFindWordPress()
{
global $argv;
$candidates = array();
if (!empty($argv[1])) {
$candidates[] = rtrim($argv[1], '/\\') . '/wp-load.php';
}
foreach (array(getcwd(), __DIR__) as $start) {
$directory = $start;
for ($depth = 0; $depth < 8 and $directory; $depth++) {
$candidates[] = $directory . '/wp-load.php';
$parent = dirname($directory);
if ($parent === $directory) {
break;
}
$directory = $parent;
}
}
foreach ($candidates as $candidate) {
if (is_readable($candidate)) {
return $candidate;
}
}
return null;
}
$wpLoad = ofSsoFindWordPress();
if ($wpLoad === null) {
echo "WordPress introuvable.\n"
. "Lancez ce test depuis la racine du site, ou indiquez le chemin du site :\n"
. " php wordpress-test.php C:\\chemin\\vers\\le\\site\n";
exit(1);
}
require $wpLoad;
// Align the fake request with the site's own address so home_url() stays consistent.
$_SERVER['HTTP_HOST'] = (string) parse_url(get_option('home'), PHP_URL_HOST);
require_once ABSPATH . 'wp-admin/includes/plugin.php';
require_once ABSPATH . 'wp-admin/includes/user.php';
// The settings screen only ever runs inside wp-admin, which loads these helpers.
require_once ABSPATH . 'wp-admin/includes/template.php';
require_once ABSPATH . 'wp-admin/includes/screen.php';
// Remove anything left by a previous run so the script is repeatable.
foreach (array('pilote.test', 'of-7777', 'of-8888', 'of-9191', 'of-9292', 'of-9393') as $login) {
$stale = get_user_by('login', $login);
if ($stale) {
wp_delete_user($stale->ID);
}
}
delete_option('of_sso_settings');
// --- activation -------------------------------------------------------------
$activation = activate_plugin('openflyers-sso/openflyers-sso.php');
check('plugin activates without error', !is_wp_error($activation), is_wp_error($activation) ? $activation->get_error_message() : '');
check('plugin is listed as active', is_plugin_active('openflyers-sso/openflyers-sso.php'));
check('protocol client class is loaded', class_exists('OF_SSO_Client'));
check('admin class is loaded', class_exists('OF_SSO_Admin'));
check('helper functions are available', function_exists('of_sso_login_url') && function_exists('of_sso_is_member'));
// The plugin file is loaded by wp-load only on the next request, so load it now.
if (!class_exists('OF_SSO_Auth')) {
require_once ABSPATH . 'wp-content/plugins/openflyers-sso/openflyers-sso.php';
OF_SSO_Auth::init();
OF_SSO_Admin::init();
}
// --- settings ---------------------------------------------------------------
$certDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'of-sso-test-certs';
$settings = array(
'base_url' => 'https://openflyers.com',
'platform' => 'acat-lfcl',
'client_id' => 'testclient',
'client_secret' => 'secret',
'cert_dir' => $certDir,
'auto_create' => 0,
'default_role' => 'subscriber',
'debug' => 0,
);
update_option('of_sso_settings', OF_SSO_Admin::sanitize($settings));
$stored = of_sso_get_settings();
check('settings are stored and read back', $stored['platform'] === 'acat-lfcl' && $stored['client_id'] === 'testclient');
check('secret is kept when resubmitted empty', OF_SSO_Admin::sanitize(array('client_secret' => ''))['client_secret'] === 'secret');
check('secret is replaced when resubmitted', OF_SSO_Admin::sanitize(array('client_secret' => 'new'))['client_secret'] === 'new');
// --- certificate folder -----------------------------------------------------
// One folder is enough: the files are found by their standard names.
$paths = of_sso_resolve_cert_paths();
$required = array('auth_cert', 'auth_key', 'sign_cert', 'sign_key', 'server_sign_cert');
check(
'the folder resolves every required certificate path',
count(array_filter(array_intersect_key($paths, array_flip($required)))) === count($required)
);
check('the TLS certificate keeps its standard name', basename($paths['auth_cert']) === 'auth_cert.crt', basename($paths['auth_cert']));
check('the signing key keeps its standard name', basename($paths['sign_key']) === 'sign.key', basename($paths['sign_key']));
check('every required path sits in the configured folder', dirname($paths['auth_cert']) === $certDir, dirname($paths['auth_cert']));
// ca.crt is the exception: it only overrides the bundle used to validate the OpenFlyers server,
// so its absence must fall back to the system store instead of blocking every call.
$caFolder = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'of-sso-ca-test';
if (!is_dir($caFolder)) {
mkdir($caFolder, 0777, true);
}
$caSettings = $settings;
$caSettings['cert_dir'] = $caFolder;
update_option('of_sso_settings', OF_SSO_Admin::sanitize($caSettings));
check('an absent ca.crt falls back to the system store', of_sso_resolve_cert_paths()['ca_cert'] === '');
file_put_contents($caFolder . DIRECTORY_SEPARATOR . 'ca.crt', 'placeholder');
check(
'a ca.crt sitting in the folder is used',
of_sso_resolve_cert_paths()['ca_cert'] === $caFolder . DIRECTORY_SEPARATOR . 'ca.crt'
);
unlink($caFolder . DIRECTORY_SEPARATOR . 'ca.crt');
rmdir($caFolder);
update_option('of_sso_settings', OF_SSO_Admin::sanitize($settings));
// A file stored elsewhere, or under another name, can still be pointed at individually.
$override = $settings;
$override['sign_key'] = $certDir . DIRECTORY_SEPARATOR . 'autre-nom.key';
update_option('of_sso_settings', OF_SSO_Admin::sanitize($override));
$paths = of_sso_resolve_cert_paths();
check('an explicit path overrides the folder', basename($paths['sign_key']) === 'autre-nom.key');
check('the other paths still come from the folder', basename($paths['auth_key']) === 'auth.key');
// The connection test must never announce success when nothing could be sent.
$missing = $settings;
$missing['cert_dir'] = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'of-sso-absent';
update_option('of_sso_settings', OF_SSO_Admin::sanitize($missing));
$verdict = of_sso_get_client()->testConnection(of_sso_get_redirect_uri());
check('the connection test reports a problem when certificates are missing', $verdict['status'] !== 'ok', $verdict['status']);
update_option('of_sso_settings', OF_SSO_Admin::sanitize($settings));
$client = of_sso_get_client();
check('client is built from the settings', $client instanceof OF_SSO_Client);
check(
'the platform code becomes a path segment',
strpos($client->getAuthorizeUrl('http://x/', 's', 'c'), 'https://openflyers.com/acat-lfcl/oauth/authorize.php') === 0
);
// A dedicated or local install answers at the domain root, with no platform code.
$rootSettings = $settings;
$rootSettings['platform'] = '';
$rootSettings['base_url'] = 'https://openflyers.exemple.fr';
update_option('of_sso_settings', OF_SSO_Admin::sanitize($rootSettings));
$rootClient = of_sso_get_client();
check('a platform served at the root still builds a client', $rootClient instanceof OF_SSO_Client);
check(
'no empty segment is inserted in the endpoint URL',
strpos($rootClient->getAuthorizeUrl('http://x/', 's', 'c'), 'https://openflyers.exemple.fr/oauth/authorize.php') === 0,
substr($rootClient->getAuthorizeUrl('http://x/', 's', 'c'), 0, 60)
);
// Without a client identifier there is nothing to build, whatever the rest holds.
$noClient = $settings;
$noClient['client_id'] = '';
update_option('of_sso_settings', OF_SSO_Admin::sanitize($noClient));
check('no client is built without a client_id', of_sso_get_client() === false);
update_option('of_sso_settings', OF_SSO_Admin::sanitize($settings));
$client = of_sso_get_client();
check('callback URL is derived from the site URL', of_sso_get_redirect_uri() === home_url('/?of_sso=callback'), of_sso_get_redirect_uri());
// --- login start ------------------------------------------------------------
// wp_redirect() is intercepted so the flow can be observed without leaving the script.
$redirects = array();
add_filter(
'wp_redirect',
function ($location) use (&$redirects) {
$redirects[] = $location;
throw new Exception('redirect');
},
10,
1
);
function capture($callable)
{
try {
ob_start();
$callable();
ob_end_clean();
} catch (Exception $e) {
ob_end_clean();
}
}
$_GET = array('of_sso' => 'login', 'redirect_to' => rawurlencode(home_url('/espace-membres/')));
capture(array('OF_SSO_Auth', 'route'));
check('starting a login triggers a redirect', count($redirects) === 1);
$authorizeUrl = end($redirects);
check(
'the member is sent to the platform authorize endpoint',
strpos($authorizeUrl, 'https://openflyers.com/acat-lfcl/oauth/authorize.php?') === 0,
substr($authorizeUrl, 0, 70)
);
parse_str((string) parse_url($authorizeUrl, PHP_URL_QUERY), $query);
check('client_id is sent', $query['client_id'] === 'testclient');
check('PKCE challenge is sent', !empty($query['code_challenge']) && $query['code_challenge_method'] === 'S256');
check('redirect_uri matches the registered callback', $query['redirect_uri'] === of_sso_get_redirect_uri());
check('scope is default.login', $query['scope'] === 'default.login');
$state = $query['state'];
$pending = get_transient('of_sso_state_' . $state);
check('the pending request is stored under its state', is_array($pending) && !empty($pending['code_verifier']));
check('the requested destination is kept', $pending['redirect_to'] === home_url('/espace-membres/'));
check(
'the stored verifier matches the sent challenge',
OF_SSO_Client::computeCodeChallenge($pending['code_verifier']) === $query['code_challenge']
);
// --- callback error paths ---------------------------------------------------
$redirects = array();
$_GET = array('of_sso' => 'callback', 'code' => 'abc', 'state' => 'unknown-state');
capture(array('OF_SSO_Auth', 'route'));
check('an unknown state is refused', count($redirects) === 1 && strpos(end($redirects), 'of_sso_error=1') !== false);
$redirects = array();
$_GET = array('of_sso' => 'callback', 'error' => 'access_denied');
capture(array('OF_SSO_Auth', 'route'));
check('a refused authorization is handled', count($redirects) === 1 && strpos(end($redirects), 'of_sso_error=1') !== false);
$redirects = array();
$_GET = array('of_sso' => 'callback', 'state' => $state);
capture(array('OF_SSO_Auth', 'route'));
check('a callback without code is refused', count($redirects) === 1);
// A used state must not be replayable.
$redirects = array();
$_GET = array('of_sso' => 'callback', 'code' => 'abc', 'state' => $state);
capture(array('OF_SSO_Auth', 'route'));
check('a consumed state cannot be replayed', get_transient('of_sso_state_' . $state) === false);
$_GET = array();
// --- account resolution -----------------------------------------------------
$resolve = new ReflectionMethod('OF_SSO_Auth', 'resolveUser');
$resolve->setAccessible(true);
$result = $resolve->invoke(null, 4242, array(), $client);
check(
'an unlinked member is refused when auto-creation is off',
is_wp_error($result) && $result->get_error_code() === 'of_sso_no_account'
);
$linkedId = wp_insert_user(array('user_login' => 'pilote.test', 'user_pass' => 'x', 'user_email' => 'pilote@example.test'));
update_user_meta($linkedId, OF_SSO_USER_META, '4242');
$result = $resolve->invoke(null, 4242, array(), $client);
check('a linked member is recognized', $result instanceof WP_User && (int) $result->ID === (int) $linkedId);
$settings['auto_create'] = 1;
update_option('of_sso_settings', OF_SSO_Admin::sanitize($settings));
$result = $resolve->invoke(null, 7777, array(), $client);
check('an unknown member is created when auto-creation is on', $result instanceof WP_User, is_wp_error($result) ? $result->get_error_message() : '');
check('the created account carries the OpenFlyers identifier', get_user_meta($result->ID, OF_SSO_USER_META, true) === '7777');
check('the created account has the configured role', in_array('subscriber', $result->roles, true));
// The profile filter is the documented way to feed name and e-mail from a report.
add_filter(
'of_sso_user_profile',
function ($profile) {
return array('user_email' => 'nouveau@example.test', 'display_name' => 'Nouveau Membre');
}
);
$result = $resolve->invoke(null, 8888, array(), $client);
$created = get_user_by('id', $result->ID);
check('the profile filter fills the e-mail', $created->user_email === 'nouveau@example.test', $created->user_email);
check('the profile filter fills the display name', $created->display_name === 'Nouveau Membre', $created->display_name);
remove_all_filters('of_sso_user_profile');
// --- member report (name and e-mail) ------------------------------------------
/**
* Client whose report call is answered locally, the way the OpenFlyers resource server answers: the
* row is the one of the token's user ($connectedPersonId), here carried by the test token.
*/
class OF_SSO_Report_Test_Client extends OF_SSO_Client
{
public $answers = array();
public $replacementLists = array();
public function getReport(array $token, $reportId, $resourceType = 'report', array $replacementList = array())
{
$this->replacementLists[] = $replacementList;
$memberId = isset($token['test_user_id']) ? $token['test_user_id'] : 0;
return isset($this->answers[$memberId]) ? $this->answers[$memberId] : false;
}
}
$settings['profile_report_id'] = '12';
update_option('of_sso_settings', OF_SSO_Admin::sanitize($settings));
check('the report number is stored as an integer', of_sso_get_settings()['profile_report_id'] === 12);
$redirects = array();
$_GET = array('of_sso' => 'login');
capture(array('OF_SSO_Auth', 'route'));
parse_str((string) parse_url((string) end($redirects), PHP_URL_QUERY), $query);
check('the custom reports scope is requested once a report is set', $query['scope'] === 'default.login reports.readonly', $query['scope']);
$_GET = array();
$reportClient = new OF_SSO_Report_Test_Client(array());
$reportClient->answers = array(
9191 => "first_name;last_name;email\nÉlodie;D'Artagnan;elodie@example.test\n",
4242 => "first_name;last_name;email\nPaul;PILOTE;paul.pilote@example.test\n",
9292 => "first_name;last_name;email\nJean;MARTIN;paul.pilote@example.test\n",
);
$result = $resolve->invoke(null, 9191, array('test_user_id' => 9191), $reportClient);
$created = get_user_by('id', $result->ID);
check('a new member gets the name from the report', $created->first_name === 'Élodie' && $created->last_name === "D'Artagnan");
check('a new member is displayed under that name', $created->display_name === "Élodie D'Artagnan", $created->display_name);
check('a new member gets the e-mail from the report', $created->user_email === 'elodie@example.test', $created->user_email);
check('the login name stays technical', $created->user_login === 'of-9191');
$result = $resolve->invoke(null, 4242, array('test_user_id' => 4242), $reportClient);
$updated = get_user_by('id', $linkedId);
check('a linked member is updated at the next login', $updated->display_name === 'Paul PILOTE' && $updated->user_email === 'paul.pilote@example.test', $updated->display_name . ' ' . $updated->user_email);
$result = $resolve->invoke(null, 9292, array('test_user_id' => 9292), $reportClient);
check('an e-mail used by another account does not block the login', $result instanceof WP_User, is_wp_error($result) ? $result->get_error_message() : '');
$created = get_user_by('id', $result->ID);
check('that e-mail is not copied to the new account', $created->user_email === '', $created->user_email);
check('the name is still filled', $created->display_name === 'Jean MARTIN', $created->display_name);
$result = $resolve->invoke(null, 9393, array('test_user_id' => 9393), $reportClient);
check('an unreadable report does not block the login', $result instanceof WP_User, is_wp_error($result) ? $result->get_error_message() : '');
check('the member then keeps the technical name', get_user_by('id', $result->ID)->display_name === 'of-9393');
check('no member identifier is ever sent to the report', $reportClient->replacementLists === array(array(), array(), array(), array()), wp_json_encode($reportClient->replacementLists));
$settings['profile_report_id'] = '';
update_option('of_sso_settings', OF_SSO_Admin::sanitize($settings));
check('an empty report number disables the report', of_sso_get_settings()['profile_report_id'] === 0);
// --- shortcodes -------------------------------------------------------------
check('the login shortcode is registered', shortcode_exists('openflyers_login'));
check('the member shortcode is registered', shortcode_exists('openflyers_membre'));
$html = do_shortcode('[openflyers_login]');
check('the login shortcode renders a link to the login route', strpos($html, 'of_sso=login') !== false);
$html = do_shortcode('[openflyers_membre]Contenu reserve[/openflyers_membre]');
check('reserved content is hidden from visitors', strpos($html, 'Contenu reserve') === false);
check('visitors are offered the login button', strpos($html, 'of_sso=login') !== false);
wp_set_current_user($linkedId);
$html = do_shortcode('[openflyers_membre]Contenu reserve[/openflyers_membre]');
check('reserved content is shown to a linked member', strpos($html, 'Contenu reserve') !== false);
check('of_sso_is_member() recognizes a linked member', of_sso_is_member() === true);
wp_set_current_user(0);
check('of_sso_is_member() is false for a visitor', of_sso_is_member() === false);
// --- settings screen --------------------------------------------------------
wp_set_current_user(1);
ob_start();
OF_SSO_Admin::renderPage();
$page = ob_get_clean();
check('the settings page renders', strlen($page) > 1000, strlen($page) . ' bytes');
check('it shows the callback URL to declare', strpos($page, esc_html(of_sso_get_redirect_uri())) !== false);
check('it exposes every certificate field', substr_count($page, 'of_sso_settings[') >= 15);
check('it offers the certificate folder field', strpos($page, 'name="of_sso_settings[cert_dir]"') !== false);
check('it offers the member report field', strpos($page, 'name="of_sso_settings[profile_report_id]"') !== false);
check('it offers the connection test button', strpos($page, 'name="of_sso_test_connection"') !== false);
check('the stored secret is never printed back', strpos($page, 'value="secret"') === false);
// The diagnostics must flag what is missing, whatever the machine running the test holds.
$absent = $settings;
$absent['cert_dir'] = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'of-sso-absent';
update_option('of_sso_settings', OF_SSO_Admin::sanitize($absent));
ob_start();
OF_SSO_Admin::renderPage();
$brokenPage = ob_get_clean();
check('the diagnostics block flags unreadable certificates', strpos($brokenPage, '&#10007;') !== false);
check('it names the file it could not read', strpos($brokenPage, 'of-sso-absent') !== false);
update_option('of_sso_settings', OF_SSO_Admin::sanitize($settings));
// --- user profile field -----------------------------------------------------
$_POST = array(
'of_sso_user_nonce' => wp_create_nonce('of_sso_user_field'),
'of_sso_user_id' => '9999',
);
OF_SSO_Admin::saveUserField($linkedId);
check('an administrator can link a member from the user profile', get_user_meta($linkedId, OF_SSO_USER_META, true) === '9999');
$_POST['of_sso_user_nonce'] = 'forged';
$_POST['of_sso_user_id'] = '1';
OF_SSO_Admin::saveUserField($linkedId);
check('a forged nonce is rejected', get_user_meta($linkedId, OF_SSO_USER_META, true) === '9999');
$_POST = array();
// --- PHP notices ------------------------------------------------------------
$log = WP_CONTENT_DIR . '/debug.log';
if (file_exists($log)) {
$lines = array_filter(
file($log),
function ($line) {
// Header warnings are expected: the flow is exercised from the command line.
return strpos($line, 'openflyers-sso') !== false && strpos($line, 'Cannot modify header information') === false;
}
);
check('no PHP notice from the plugin', count($lines) === 0, implode(' | ', array_slice($lines, 0, 3)));
} else {
check('no PHP notice from the plugin', true, 'no debug.log');
}
echo $fail === 0 ? "\nAll checks passed.\n" : "\n$fail check(s) failed.\n";
exit($fail === 0 ? 0 : 1);