OpenFlyers SSO WordPress plugin 1.1.1
Import of the 1.1.0 archive plus a CLI guard on the two test scripts: served over HTTP from wp-content/plugins they would delete the plugin settings and create test accounts on the site.
This commit is contained in:
2
.distignore
Normal file
2
.distignore
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
tests/
|
||||||
|
.git/
|
||||||
332
README.md
Normal file
332
README.md
Normal file
@@ -0,0 +1,332 @@
|
|||||||
|
# OpenFlyers SSO pour WordPress
|
||||||
|
|
||||||
|
Plugin d'authentification permettant aux membres d'un club de se connecter a un espace prive
|
||||||
|
WordPress avec leurs identifiants OpenFlyers. Le mot de passe est saisi sur OpenFlyers et n'est
|
||||||
|
jamais transmis ni stocke sur le site WordPress.
|
||||||
|
|
||||||
|
Le plugin implemente le flux `authorization_code` avec PKCE, l'authentification TLS mutuelle et la
|
||||||
|
signature HTTP exigees par le serveur d'autorisation OpenFlyers, ainsi que la verification de la
|
||||||
|
signature des reponses du serveur.
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
- Documentation publique, cote plateforme OpenFlyers :
|
||||||
|
<https://doc4-fr.openflyers.com/Plugin-WordPress>
|
||||||
|
- API OpenFlyers, procedures de declaration d'un client et d'emission des certificats :
|
||||||
|
<https://doc4-fr.openflyers.com/API-OpenFlyers>
|
||||||
|
|
||||||
|
Le present fichier decrit l'installation et l'exploitation du plugin cote WordPress. La
|
||||||
|
documentation publique decrit ce qui se passe cote OpenFlyers. Les deux se completent et se
|
||||||
|
referencent mutuellement.
|
||||||
|
|
||||||
|
## En bref
|
||||||
|
|
||||||
|
| Qui | Fait quoi |
|
||||||
|
| --- | --- |
|
||||||
|
| Le prestataire du site | Genere deux bi-cles et deux demandes de certificat sur le serveur (section 2), installe et configure le plugin (sections 4 et 5) |
|
||||||
|
| Le club (ou OpenFlyers) | Declare le client depuis l'administration de la plateforme, ce qui signe les deux demandes et delivre les certificats, le `client_id` et la passphrase (section 3) |
|
||||||
|
| Le club | Coche **Connexion depuis l'exterieur (OAuth2)** pour les profils concernes, puis associe chaque membre a son compte WordPress ou active la creation automatique (section 7) |
|
||||||
|
| Le membre | Clique sur "Se connecter avec OpenFlyers", saisit ses identifiants sur OpenFlyers, revient connecte sur le site |
|
||||||
|
|
||||||
|
Comptez une demi-journee pour une premiere mise en place, l'essentiel du temps etant l'echange des
|
||||||
|
certificats.
|
||||||
|
|
||||||
|
## 1. Prerequis
|
||||||
|
|
||||||
|
Sur l'hebergement WordPress :
|
||||||
|
|
||||||
|
- PHP 7.4 ou superieur, avec les extensions `curl` et `openssl` ;
|
||||||
|
- la possibilite d'utiliser un certificat client sortant (`CURLOPT_SSLCERT`). Certains hebergements
|
||||||
|
mutualises le bloquent : c'est le point a verifier en premier ;
|
||||||
|
- un emplacement de stockage hors de la racine web pour les cles privees ;
|
||||||
|
- le site accessible en HTTPS, avec une URL stable.
|
||||||
|
|
||||||
|
Cote OpenFlyers :
|
||||||
|
|
||||||
|
- un compte disposant des droits d'administration sur la plateforme du club ;
|
||||||
|
- le code plateforme (par exemple `acat-lfcl`) ;
|
||||||
|
- la case **Connexion depuis l'exterieur (OAuth2)** cochee pour les profils des membres concernes.
|
||||||
|
Sans elle, OpenFlyers refuse l'autorisation apres la saisie des identifiants, avec le message
|
||||||
|
*Connected user is not allowed to login*. Voir la section 7.
|
||||||
|
|
||||||
|
La procedure officielle de declaration d'un client est documentee sur le wiki OpenFlyers, chapitre
|
||||||
|
*Enregistrer un client* : <https://doc4-fr.openflyers.com/API-OpenFlyers>. Les sections 2 et 3
|
||||||
|
ci-dessous en donnent la version courte, limitee a ce dont ce plugin a besoin.
|
||||||
|
|
||||||
|
## 2. Generer les cles et les demandes de certificat
|
||||||
|
|
||||||
|
Deux bi-cles distinctes sont necessaires : une pour le TLS mutuel, une pour la signature HTTP.
|
||||||
|
Sur le serveur, dans un dossier hors de la racine web (ici `/home/site/of-certs`) :
|
||||||
|
|
||||||
|
```
|
||||||
|
openssl req -new -newkey rsa:2048 -nodes \
|
||||||
|
-keyout auth.key -out auth.csr \
|
||||||
|
-subj "/C=FR/O=Nom du club/CN=www.exemple.fr"
|
||||||
|
|
||||||
|
openssl req -new -newkey rsa:2048 -nodes \
|
||||||
|
-keyout sign.key -out sign.csr \
|
||||||
|
-subj "/C=FR/O=Nom du club/CN=www.exemple.fr"
|
||||||
|
|
||||||
|
chmod 600 auth.key sign.key
|
||||||
|
```
|
||||||
|
|
||||||
|
Conserver les deux fichiers `.key` a l'abri : ils ne doivent jamais quitter le serveur ni etre
|
||||||
|
accessibles depuis le web.
|
||||||
|
|
||||||
|
La procedure officielle (chapitre *Generer des certificats* du wiki) passe par des fichiers de
|
||||||
|
configuration `.conf` et produit des cles chiffrees, sans `-nodes`. Les deux approches conviennent :
|
||||||
|
si vous suivez celle du wiki, renseignez la passphrase des cles dans les reglages du plugin.
|
||||||
|
|
||||||
|
## 3. Declarer le client dans OpenFlyers
|
||||||
|
|
||||||
|
Dans OpenFlyers, **Admin > Transferts > Exports > API OAuth2**, bouton **Ajouter un client** :
|
||||||
|
|
||||||
|
- **Nom du client** : le nom du site WordPress ;
|
||||||
|
- **Type d'autorisation** : `authorization_code` (ajouter `refresh_token` pour des sessions longues) ;
|
||||||
|
- **URL de redirection** : l'URL affichee en haut de la page de reglages du plugin, typiquement
|
||||||
|
`https://www.exemple.fr/?of_sso=callback`. Elle doit correspondre au caractere pres ;
|
||||||
|
- **CSR TLS mutuel** : contenu de `auth.csr` ;
|
||||||
|
- **CSR signature HTTP** : contenu de `sign.csr`.
|
||||||
|
|
||||||
|
Apres validation, OpenFlyers renvoie les deux certificats signes (valables 3 ans), a enregistrer
|
||||||
|
sous `auth_cert.crt` et `sign_cert.crt` dans le meme dossier. Relever egalement le `client_id` et la
|
||||||
|
passphrase : **ils ne sont affiches qu'une seule fois**, et les regenerer invalide les precedents.
|
||||||
|
|
||||||
|
Cette declaration se fait entierement depuis l'administration de la plateforme : le club, ou son
|
||||||
|
prestataire s'il en a les droits, peut la realiser sans intervention d'OpenFlyers.
|
||||||
|
|
||||||
|
Deux fichiers supplementaires sont a demander a OpenFlyers et a deposer dans ce dossier :
|
||||||
|
|
||||||
|
- `ca.crt` : autorite de certification OpenFlyers ;
|
||||||
|
- `sign_cert_server.crt` : certificat avec lequel le serveur signe ses reponses.
|
||||||
|
|
||||||
|
Le dossier contient alors :
|
||||||
|
|
||||||
|
```
|
||||||
|
/home/site/of-certs/
|
||||||
|
├── auth.key
|
||||||
|
├── auth_cert.crt
|
||||||
|
├── sign.key
|
||||||
|
├── sign_cert.crt
|
||||||
|
├── ca.crt
|
||||||
|
└── sign_cert_server.crt
|
||||||
|
```
|
||||||
|
|
||||||
|
## 4. Installer le plugin
|
||||||
|
|
||||||
|
Copier le dossier `openflyers-sso` dans `wp-content/plugins/`, ou televerser l'archive
|
||||||
|
`openflyers-sso-1.1.1.zip` depuis Extensions > Ajouter > Televerser une extension. Activer ensuite
|
||||||
|
le plugin depuis l'administration WordPress.
|
||||||
|
|
||||||
|
## 5. Configurer
|
||||||
|
|
||||||
|
Reglages > OpenFlyers SSO. Trois choses a renseigner, pas davantage :
|
||||||
|
|
||||||
|
1. le code plateforme, le `client_id` et la passphrase ;
|
||||||
|
2. le **dossier des certificats**, un seul chemin absolu. Les six fichiers y sont retrouves par
|
||||||
|
leurs noms standard, ceux de la section 3. Si l'un d'eux porte un autre nom ou se trouve
|
||||||
|
ailleurs, depliez *Chemins personnalises (avance)* et indiquez-le individuellement ;
|
||||||
|
3. le mode de gestion des comptes.
|
||||||
|
|
||||||
|
### Verifier que tout fonctionne
|
||||||
|
|
||||||
|
Le bouton **Tester la connexion a OpenFlyers**, en haut de la page, envoie une vraie requete au
|
||||||
|
serveur avec un code d'autorisation volontairement invalide. Tout ce qui protege le point de
|
||||||
|
terminaison est donc traverse : certificat TLS, signature HTTP et identifiants du client. Seul le
|
||||||
|
code ne peut pas etre valide. Si la reponse ne reproche que le code, c'est que toute la chaine
|
||||||
|
d'authentification est acceptee, et le plugin l'annonce en clair.
|
||||||
|
|
||||||
|
C'est la verification decisive, et elle ne demande ni membre, ni navigateur, ni rendez-vous : elle
|
||||||
|
peut se faire des que les certificats sont en place. En cas d'echec, le message designe le maillon
|
||||||
|
en cause (certificat, signature, identifiants, ou type d'autorisation du client) plutot qu'un code
|
||||||
|
d'erreur brut.
|
||||||
|
|
||||||
|
Le bloc **Diagnostic** en bas de page complete cela hors ligne : extensions PHP, lisibilite des
|
||||||
|
fichiers, dates d'expiration, correspondance entre chaque certificat et sa cle, et permissions des
|
||||||
|
cles privees sur les serveurs qui les gerent.
|
||||||
|
|
||||||
|
### Gestion des comptes
|
||||||
|
|
||||||
|
Deux modes, selon ce que souhaite le club :
|
||||||
|
|
||||||
|
- **Comptes existants uniquement** (par defaut) : le membre doit deja avoir un compte WordPress
|
||||||
|
portant son identifiant OpenFlyers. Cet identifiant se saisit dans la fiche de l'utilisateur
|
||||||
|
WordPress, section OpenFlyers. Mode recommande quand l'espace membres compte peu d'utilisateurs
|
||||||
|
ou quand les comptes existent deja.
|
||||||
|
- **Creation automatique** : tout membre qui se connecte via OpenFlyers obtient un compte WordPress
|
||||||
|
avec le role choisi. Le compte cree porte l'identifiant `of-<identifiant OpenFlyers>` et n'a pas
|
||||||
|
d'adresse e-mail tant que celle-ci n'est pas fournie (voir section 8).
|
||||||
|
|
||||||
|
## 6. Utiliser dans les pages
|
||||||
|
|
||||||
|
Bouton de connexion :
|
||||||
|
|
||||||
|
```
|
||||||
|
[openflyers_login]
|
||||||
|
[openflyers_login label="Acceder a l'espace membres" redirect="https://www.exemple.fr/espace-membres/"]
|
||||||
|
```
|
||||||
|
|
||||||
|
Contenu reserve aux membres :
|
||||||
|
|
||||||
|
```
|
||||||
|
[openflyers_membre]
|
||||||
|
Contenu visible uniquement par les membres connectes via OpenFlyers.
|
||||||
|
[/openflyers_membre]
|
||||||
|
```
|
||||||
|
|
||||||
|
Dans un theme :
|
||||||
|
|
||||||
|
```php
|
||||||
|
if (function_exists('of_sso_is_member') && of_sso_is_member()) {
|
||||||
|
// Contenu reserve.
|
||||||
|
}
|
||||||
|
|
||||||
|
echo '<a href="' . esc_url(of_sso_login_url()) . '">Se connecter</a>';
|
||||||
|
```
|
||||||
|
|
||||||
|
## 7. Au quotidien : gerer les acces
|
||||||
|
|
||||||
|
### Autoriser les membres cote OpenFlyers
|
||||||
|
|
||||||
|
Prealable indispensable, a faire une fois. Dans OpenFlyers, **Admin > Utilisateurs > Profils**,
|
||||||
|
onglet **Generalites** : cocher la case **Connexion depuis l'exterieur (OAuth2)** pour les profils
|
||||||
|
dont les membres doivent pouvoir se connecter au site (pilotes, eleves, instructeurs, selon le
|
||||||
|
club).
|
||||||
|
|
||||||
|
OpenFlyers verifie cette autorisation apres la saisie des identifiants. Un membre dont aucun profil
|
||||||
|
ne la porte voit sa connexion refusee avec *Connected user is not allowed to login*, meme si tout le
|
||||||
|
reste est correctement configure. C'est aussi le levier qui permet de restreindre l'espace membres a
|
||||||
|
une categorie d'adherents : seuls les profils coches ici accedent au site.
|
||||||
|
|
||||||
|
### Ce que vit le membre
|
||||||
|
|
||||||
|
Il clique sur le bouton de connexion, arrive sur la page de connexion OpenFlyers de la plateforme
|
||||||
|
du club, saisit ses identifiants habituels, et revient sur le site deja connecte. Il ne cree pas de
|
||||||
|
compte, ne choisit pas de mot de passe, et n'a rien a retenir de plus. La deconnexion se fait
|
||||||
|
normalement depuis WordPress ; elle ne le deconnecte pas d'OpenFlyers.
|
||||||
|
|
||||||
|
### Associer un membre a un compte WordPress
|
||||||
|
|
||||||
|
Necessaire uniquement si la creation automatique est desactivee.
|
||||||
|
|
||||||
|
1. Dans OpenFlyers, ouvrir la fiche du membre (administration des utilisateurs). Son identifiant
|
||||||
|
apparait dans l'URL de la fiche, dans le parametre `menuParameter`.
|
||||||
|
2. Dans WordPress, Utilisateurs > modifier l'utilisateur concerne, section **OpenFlyers**, saisir cet
|
||||||
|
identifiant et enregistrer.
|
||||||
|
|
||||||
|
Un identifiant ne peut etre associe qu'a un seul compte WordPress.
|
||||||
|
|
||||||
|
### Retirer un acces
|
||||||
|
|
||||||
|
Videz le champ **Identifiant du membre** dans la fiche WordPress de la personne : elle ne pourra
|
||||||
|
plus se connecter via OpenFlyers, sans que son compte WordPress soit supprime. Un membre radie du
|
||||||
|
club perd de toute facon l'acces des que son compte OpenFlyers est desactive, puisque
|
||||||
|
l'authentification se fait chez nous.
|
||||||
|
|
||||||
|
### Un membre n'arrive pas a se connecter
|
||||||
|
|
||||||
|
- **"Connected user is not allowed to login"**, affiche par OpenFlyers juste apres la saisie des
|
||||||
|
identifiants : le membre n'appartient a aucun profil ou la case **Connexion depuis l'exterieur
|
||||||
|
(OAuth2)** est cochee. Voir le
|
||||||
|
debut de cette section. C'est de loin la cause la plus frequente lors d'une premiere mise en
|
||||||
|
service.
|
||||||
|
- **"Aucun compte de ce site n'est associe a votre compte OpenFlyers"** : la liaison decrite
|
||||||
|
ci-dessus n'a pas ete faite, ou l'identifiant saisi n'est pas le bon.
|
||||||
|
- **"Session de connexion expiree ou invalide"** : le membre a mis plus de dix minutes a se
|
||||||
|
connecter, ou a utilise un vieil onglet. Il suffit de recommencer.
|
||||||
|
- **La page de connexion OpenFlyers refuse ses identifiants** : le probleme est cote OpenFlyers, pas
|
||||||
|
cote site. Verifier son compte dans la plateforme.
|
||||||
|
|
||||||
|
Pour tout le reste, activer la journalisation dans les reglages et consulter la section 9.
|
||||||
|
|
||||||
|
## 8. Recuperer le nom et l'e-mail du membre
|
||||||
|
|
||||||
|
Le scope `default.login` retourne uniquement l'identifiant interne OpenFlyers du membre. Pour
|
||||||
|
alimenter le nom ou l'e-mail du compte WordPress, il faut creer un rapport dans OpenFlyers exposant
|
||||||
|
ces donnees, autoriser le scope de lecture correspondant sur le client, puis brancher le filtre
|
||||||
|
`of_sso_user_profile` :
|
||||||
|
|
||||||
|
```php
|
||||||
|
add_filter('of_sso_scope', function () {
|
||||||
|
return 'default.login reports.readonly';
|
||||||
|
});
|
||||||
|
|
||||||
|
add_filter('of_sso_user_profile', function ($profile, $ofUserId, $token, $client) {
|
||||||
|
// 42 : identifiant du rapport OpenFlyers renvoyant les coordonnees des membres.
|
||||||
|
$report = $client->getReport($token, 42, 'report', array('userId' => $ofUserId));
|
||||||
|
|
||||||
|
// Adapter l'extraction aux colonnes du rapport.
|
||||||
|
// $profile['user_email'] = ...;
|
||||||
|
// $profile['first_name'] = ...;
|
||||||
|
// $profile['last_name'] = ...;
|
||||||
|
// $profile['display_name'] = ...;
|
||||||
|
|
||||||
|
return $profile;
|
||||||
|
}, 10, 4);
|
||||||
|
```
|
||||||
|
|
||||||
|
Autres points d'extension :
|
||||||
|
|
||||||
|
- `of_sso_client_config` : modifier la configuration du client avant chaque appel ;
|
||||||
|
- `of_sso_after_login` : action declenchee apres la connexion, avec l'utilisateur WordPress,
|
||||||
|
l'identifiant OpenFlyers et le jeton.
|
||||||
|
|
||||||
|
## 9. Depannage
|
||||||
|
|
||||||
|
Commencez par le bouton **Tester la connexion a OpenFlyers** (section 5) : il nomme le maillon en
|
||||||
|
cause. Pour aller plus loin, activez la journalisation dans les reglages et consultez le journal
|
||||||
|
PHP du site, ou vous retrouverez le message exact renvoye par le serveur.
|
||||||
|
|
||||||
|
| Message renvoye par OpenFlyers | Cause probable |
|
||||||
|
| --- | --- |
|
||||||
|
| `invalid_client` | `client_id` errone, ou client non declare sur cette plateforme. |
|
||||||
|
| `invalid_certificate` | Le certificat TLS envoye ne correspond pas a celui enregistre. Si les certificats sont corrects, l'hebergeur termine probablement le TLS sur un proxy : activer l'option `X-SSL-CERT`. |
|
||||||
|
| `invalid_request` / `Invalid signature` | Signature HTTP invalide : mauvaise cle de signature, ou horloge du serveur desynchronisee. Verifier la synchronisation NTP. |
|
||||||
|
| `invalid_grant` | Code d'autorisation expire (10 minutes) ou `redirect_uri` different de celui declare dans OpenFlyers. |
|
||||||
|
| Erreur cURL 58 / 35 | Cle privee illisible par PHP, ou certificat client refuse lors de la negociation TLS. |
|
||||||
|
|
||||||
|
## 10. Securite
|
||||||
|
|
||||||
|
- Les cles privees restent hors de la racine web, en permissions `600`.
|
||||||
|
- La passphrase du client est stockee dans les options WordPress : la base de donnees du site doit
|
||||||
|
etre protegee au meme titre qu'un secret applicatif.
|
||||||
|
- Le parametre `state` et le PKCE sont verifies a chaque connexion ; une demande non aboutie expire
|
||||||
|
au bout de 10 minutes.
|
||||||
|
- La signature et l'empreinte des reponses du serveur sont verifiees avant exploitation du jeton.
|
||||||
|
- En cas de compromission, revoquer le client dans l'administration OpenFlyers : les certificats
|
||||||
|
emis pour ce client cessent immediatement d'etre acceptes.
|
||||||
|
|
||||||
|
## 11. Tests
|
||||||
|
|
||||||
|
Deux tests sont fournis, aucun ne contacte de serveur.
|
||||||
|
|
||||||
|
Le premier verifie le protocole : generation PKCE, URL d'autorisation, signature HTTP, et rejet des
|
||||||
|
reponses alterees (empreinte ou signature invalide, statut HTTP en erreur). Il genere son propre
|
||||||
|
certificat et fonctionne sans WordPress, ce qui permet de valider l'installation PHP de
|
||||||
|
l'hebergement avant meme de configurer le client :
|
||||||
|
|
||||||
|
```
|
||||||
|
php tests/smoke-test.php
|
||||||
|
```
|
||||||
|
|
||||||
|
Le second verifie l'integration WordPress : activation du plugin, enregistrement des reglages,
|
||||||
|
resolution du dossier de certificats, demarrage de la connexion, rejet d'un retour invalide,
|
||||||
|
association des comptes, shortcodes, page de reglages et champ de liaison dans la fiche
|
||||||
|
utilisateur. Il se lance depuis la racine du site :
|
||||||
|
|
||||||
|
```
|
||||||
|
php wp-content/plugins/openflyers-sso/tests/wordpress-test.php
|
||||||
|
```
|
||||||
|
|
||||||
|
Si le dossier du plugin est un lien symbolique vers une copie de travail situee ailleurs, indiquez
|
||||||
|
le site explicitement :
|
||||||
|
|
||||||
|
```
|
||||||
|
php wordpress-test.php /chemin/vers/le/site
|
||||||
|
```
|
||||||
|
|
||||||
|
Il cree ses propres comptes de test (`pilote.test`, `of-7777`, `of-8888`) et les supprime a chaque
|
||||||
|
execution. A ne pas lancer sur le site de production.
|
||||||
|
|
||||||
|
Ces deux tests portent sur le plugin lui-meme. Pour verifier la configuration reelle d'un site,
|
||||||
|
c'est le bouton **Tester la connexion a OpenFlyers** de la page de reglages qu'il faut utiliser.
|
||||||
596
includes/class-of-sso-admin.php
Normal file
596
includes/class-of-sso-admin.php
Normal file
@@ -0,0 +1,596 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* class-of-sso-admin.php
|
||||||
|
*
|
||||||
|
* Settings screen, member linking field and configuration diagnostics.
|
||||||
|
*
|
||||||
|
* @package OpenFlyers_SSO
|
||||||
|
*
|
||||||
|
* @link https://doc4-fr.openflyers.com/Plugin-WordPress Documentation publique
|
||||||
|
* @link https://work.openflyers.com/OF4-WordPress-SSO-plugin Fiche interne
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Prevent direct access.
|
||||||
|
if (!defined('ABSPATH')) {
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class OF_SSO_Admin
|
||||||
|
*/
|
||||||
|
class OF_SSO_Admin
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Register the admin hooks.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public static function init()
|
||||||
|
{
|
||||||
|
add_action('admin_menu', array(__CLASS__, 'addMenu'));
|
||||||
|
add_action('admin_init', array(__CLASS__, 'registerSettings'));
|
||||||
|
add_action('show_user_profile', array(__CLASS__, 'renderUserField'));
|
||||||
|
add_action('edit_user_profile', array(__CLASS__, 'renderUserField'));
|
||||||
|
add_action('personal_options_update', array(__CLASS__, 'saveUserField'));
|
||||||
|
add_action('edit_user_profile_update', array(__CLASS__, 'saveUserField'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add the settings page under the Settings menu.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public static function addMenu()
|
||||||
|
{
|
||||||
|
add_options_page(
|
||||||
|
__('OpenFlyers SSO', 'openflyers-sso'),
|
||||||
|
__('OpenFlyers SSO', 'openflyers-sso'),
|
||||||
|
'manage_options',
|
||||||
|
'openflyers-sso',
|
||||||
|
array(__CLASS__, 'renderPage')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Declare the option and its sanitize callback.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public static function registerSettings()
|
||||||
|
{
|
||||||
|
register_setting(
|
||||||
|
'of_sso_settings_group',
|
||||||
|
OF_SSO_OPTION,
|
||||||
|
array('sanitize_callback' => array(__CLASS__, 'sanitize'))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sanitize the submitted settings.
|
||||||
|
*
|
||||||
|
* @param array $input Raw submitted values.
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public static function sanitize($input)
|
||||||
|
{
|
||||||
|
$input = is_array($input) ? $input : array();
|
||||||
|
$current = of_sso_get_settings();
|
||||||
|
$output = array();
|
||||||
|
|
||||||
|
$textKeys = array('platform', 'client_id', 'default_role');
|
||||||
|
foreach ($textKeys as $key) {
|
||||||
|
$output[$key] = isset($input[$key]) ? sanitize_text_field($input[$key]) : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
$urlKeys = array('base_url', 'redirect_uri', 'redirect_after_login');
|
||||||
|
foreach ($urlKeys as $key) {
|
||||||
|
$output[$key] = isset($input[$key]) ? esc_url_raw(trim($input[$key])) : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Paths are kept as-is apart from trimming: they point outside the web root on purpose.
|
||||||
|
$pathKeys = array('cert_dir', 'auth_cert', 'auth_key', 'sign_cert', 'sign_key', 'ca_cert', 'server_sign_cert');
|
||||||
|
foreach ($pathKeys as $key) {
|
||||||
|
$output[$key] = isset($input[$key]) ? trim(wp_strip_all_tags($input[$key])) : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
$boolKeys = array('send_x_ssl_cert', 'auto_create', 'show_login_button', 'debug');
|
||||||
|
foreach ($boolKeys as $key) {
|
||||||
|
$output[$key] = empty($input[$key]) ? 0 : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// An empty secret field means "keep the stored value", so a secret is never wiped by accident.
|
||||||
|
foreach (array('client_secret', 'key_passphrase') as $key) {
|
||||||
|
$submitted = isset($input[$key]) ? trim($input[$key]) : '';
|
||||||
|
$output[$key] = ($submitted === '') ? $current[$key] : $submitted;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($output['base_url'])) {
|
||||||
|
$output['base_url'] = 'https://openflyers.com';
|
||||||
|
}
|
||||||
|
|
||||||
|
return $output;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render the settings page.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public static function renderPage()
|
||||||
|
{
|
||||||
|
if (!current_user_can('manage_options')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$settings = of_sso_get_settings();
|
||||||
|
$verdict = self::handleConnectionTest();
|
||||||
|
?>
|
||||||
|
<div class="wrap">
|
||||||
|
<h1><?php esc_html_e('OpenFlyers SSO', 'openflyers-sso'); ?></h1>
|
||||||
|
|
||||||
|
<p><?php esc_html_e('URL de redirection a declarer dans OpenFlyers (Administration > Configuration de l\'API) :', 'openflyers-sso'); ?></p>
|
||||||
|
<p><code><?php echo esc_html(of_sso_get_redirect_uri()); ?></code></p>
|
||||||
|
|
||||||
|
<?php self::renderConnectionTest($verdict); ?>
|
||||||
|
|
||||||
|
<form method="post" action="options.php">
|
||||||
|
<?php settings_fields('of_sso_settings_group'); ?>
|
||||||
|
|
||||||
|
<h2><?php esc_html_e('Plateforme et client', 'openflyers-sso'); ?></h2>
|
||||||
|
<table class="form-table" role="presentation">
|
||||||
|
<?php
|
||||||
|
self::textRow('platform', __('Code plateforme', 'openflyers-sso'), $settings['platform'], 'acat-lfcl');
|
||||||
|
self::descriptionRow(__('A laisser vide si la plateforme repond directement a la racine du domaine, ce qui est le cas des installations dediees.', 'openflyers-sso'));
|
||||||
|
self::textRow('base_url', __('URL de base OpenFlyers', 'openflyers-sso'), $settings['base_url'], 'https://openflyers.com');
|
||||||
|
self::textRow('client_id', __('client_id', 'openflyers-sso'), $settings['client_id'], '');
|
||||||
|
self::secretRow('client_secret', __('Passphrase (client_secret)', 'openflyers-sso'), $settings['client_secret']);
|
||||||
|
self::textRow('redirect_uri', __('URL de redirection (facultatif)', 'openflyers-sso'), $settings['redirect_uri'], of_sso_get_redirect_uri());
|
||||||
|
?>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h2><?php esc_html_e('Certificats', 'openflyers-sso'); ?></h2>
|
||||||
|
<p class="description">
|
||||||
|
<?php esc_html_e('Indiquez le dossier ou vous avez depose les six fichiers fournis par OpenFlyers. Ce dossier doit etre hors de la racine web et lisible par PHP uniquement.', 'openflyers-sso'); ?>
|
||||||
|
</p>
|
||||||
|
<table class="form-table" role="presentation">
|
||||||
|
<?php
|
||||||
|
self::textRow('cert_dir', __('Dossier des certificats', 'openflyers-sso'), $settings['cert_dir'], '/home/site/of-certs');
|
||||||
|
self::secretRow('key_passphrase', __('Passphrase des cles privees (si protegees)', 'openflyers-sso'), $settings['key_passphrase']);
|
||||||
|
self::checkboxRow('send_x_ssl_cert', __('Envoyer l\'en-tete X-SSL-CERT', 'openflyers-sso'), $settings['send_x_ssl_cert'], __('A activer uniquement si OpenFlyers repond invalid_certificate alors que les certificats sont corrects.', 'openflyers-sso'));
|
||||||
|
?>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<p class="description">
|
||||||
|
<?php esc_html_e('Noms de fichiers attendus dans ce dossier :', 'openflyers-sso'); ?>
|
||||||
|
<code><?php echo implode('</code>, <code>', array_map('esc_html', of_sso_cert_file_names())); ?></code>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary style="cursor:pointer;margin:12px 0">
|
||||||
|
<?php esc_html_e('Chemins personnalises (avance)', 'openflyers-sso'); ?>
|
||||||
|
</summary>
|
||||||
|
<p class="description">
|
||||||
|
<?php esc_html_e('A remplir uniquement si un fichier porte un autre nom ou se trouve ailleurs. Un champ vide utilise le dossier ci-dessus.', 'openflyers-sso'); ?>
|
||||||
|
</p>
|
||||||
|
<table class="form-table" role="presentation">
|
||||||
|
<?php
|
||||||
|
$resolved = of_sso_resolve_cert_paths($settings);
|
||||||
|
|
||||||
|
self::textRow('auth_cert', __('Certificat TLS mutuel', 'openflyers-sso'), $settings['auth_cert'], $resolved['auth_cert']);
|
||||||
|
self::textRow('auth_key', __('Cle privee TLS mutuel', 'openflyers-sso'), $settings['auth_key'], $resolved['auth_key']);
|
||||||
|
self::textRow('sign_cert', __('Certificat de signature HTTP', 'openflyers-sso'), $settings['sign_cert'], $resolved['sign_cert']);
|
||||||
|
self::textRow('sign_key', __('Cle privee de signature HTTP', 'openflyers-sso'), $settings['sign_key'], $resolved['sign_key']);
|
||||||
|
self::textRow('ca_cert', __('Autorite de certification OpenFlyers', 'openflyers-sso'), $settings['ca_cert'], $resolved['ca_cert']);
|
||||||
|
self::textRow('server_sign_cert', __('Certificat de signature du serveur', 'openflyers-sso'), $settings['server_sign_cert'], $resolved['server_sign_cert']);
|
||||||
|
?>
|
||||||
|
</table>
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<h2><?php esc_html_e('Comptes WordPress', 'openflyers-sso'); ?></h2>
|
||||||
|
<table class="form-table" role="presentation">
|
||||||
|
<?php
|
||||||
|
self::checkboxRow('auto_create', __('Creer automatiquement les comptes', 'openflyers-sso'), $settings['auto_create'], __('Si decoche, seuls les membres deja associes a un compte WordPress peuvent se connecter.', 'openflyers-sso'));
|
||||||
|
self::roleRow('default_role', __('Role des comptes crees', 'openflyers-sso'), $settings['default_role']);
|
||||||
|
self::textRow('redirect_after_login', __('Page apres connexion', 'openflyers-sso'), $settings['redirect_after_login'], home_url('/espace-membres/'));
|
||||||
|
self::checkboxRow('show_login_button', __('Bouton sur la page de connexion WordPress', 'openflyers-sso'), $settings['show_login_button'], '');
|
||||||
|
self::checkboxRow('debug', __('Journalisation', 'openflyers-sso'), $settings['debug'], __('Ecrit les erreurs dans le journal PHP (error_log).', 'openflyers-sso'));
|
||||||
|
?>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<?php submit_button(); ?>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<h2><?php esc_html_e('Diagnostic', 'openflyers-sso'); ?></h2>
|
||||||
|
<?php self::renderDiagnostics($settings); ?>
|
||||||
|
</div>
|
||||||
|
<?php
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run the connection test when its button was pressed.
|
||||||
|
*
|
||||||
|
* @return array|null Verdict returned by the client, or null when no test was requested.
|
||||||
|
*/
|
||||||
|
private static function handleConnectionTest()
|
||||||
|
{
|
||||||
|
if (empty($_POST['of_sso_test_connection']) or !current_user_can('manage_options')) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isset($_POST['of_sso_test_nonce'])
|
||||||
|
or !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['of_sso_test_nonce'])), 'of_sso_test_connection')
|
||||||
|
) {
|
||||||
|
return array('status' => 'unknown', 'detail' => __('Jeton de securite invalide, merci de recharger la page.', 'openflyers-sso'));
|
||||||
|
}
|
||||||
|
|
||||||
|
$client = of_sso_get_client();
|
||||||
|
|
||||||
|
if (!$client) {
|
||||||
|
return array('status' => 'unknown', 'detail' => __('Renseignez au moins le code plateforme et le client_id.', 'openflyers-sso'));
|
||||||
|
}
|
||||||
|
|
||||||
|
return $client->testConnection(of_sso_get_redirect_uri());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render the connection test button and the verdict of the last run.
|
||||||
|
*
|
||||||
|
* @param array|null $verdict Verdict returned by handleConnectionTest().
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
private static function renderConnectionTest($verdict)
|
||||||
|
{
|
||||||
|
if (is_array($verdict)) {
|
||||||
|
// Every status but 'ok' names the exact link in the chain that refused the call.
|
||||||
|
$messages = array(
|
||||||
|
'ok' => array('success', __('Connexion a OpenFlyers reussie. Le certificat TLS, la signature et les identifiants du client sont acceptes : un membre peut se connecter.', 'openflyers-sso')),
|
||||||
|
'network' => array('error', __('Le serveur OpenFlyers n\'a pas pu etre contacte. Verifiez que l\'hebergeur autorise les connexions sortantes avec un certificat client, et que la cle privee est lisible par PHP.', 'openflyers-sso')),
|
||||||
|
'server_ca' => array('error', __('Le certificat du serveur OpenFlyers n\'a pas pu etre verifie avec le fichier ca.crt fourni. Ce fichier sert a valider le serveur, pas votre client : s\'il ne convient pas, retirez ca.crt du dossier des certificats pour utiliser le magasin d\'autorites du systeme.', 'openflyers-sso')),
|
||||||
|
'tls' => array('error', __('Le certificat TLS a ete refuse. Il ne correspond pas a celui enregistre dans OpenFlyers. Si les fichiers sont les bons, votre hebergeur termine sans doute le TLS sur un proxy : activez l\'option X-SSL-CERT.', 'openflyers-sso')),
|
||||||
|
'signature' => array('error', __('La signature HTTP a ete refusee. Verifiez la cle de signature, et surtout que l\'horloge du serveur est a l\'heure (NTP).', 'openflyers-sso')),
|
||||||
|
'client' => array('error', __('Le client_id ou la passphrase sont incorrects.', 'openflyers-sso')),
|
||||||
|
'grant_type' => array('error', __('Ce client n\'est pas declare avec le type d\'autorisation authorization_code dans OpenFlyers.', 'openflyers-sso')),
|
||||||
|
'unknown' => array('warning', __('Reponse inattendue d\'OpenFlyers.', 'openflyers-sso')),
|
||||||
|
);
|
||||||
|
|
||||||
|
$status = isset($messages[$verdict['status']]) ? $verdict['status'] : 'unknown';
|
||||||
|
list($noticeType, $text) = $messages[$status];
|
||||||
|
|
||||||
|
printf(
|
||||||
|
'<div class="notice notice-%s"><p><strong>%s</strong></p>%s</div>',
|
||||||
|
esc_attr($noticeType),
|
||||||
|
esc_html($text),
|
||||||
|
empty($verdict['detail'])
|
||||||
|
? ''
|
||||||
|
: '<p><code>' . esc_html($verdict['detail']) . '</code></p>'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
<form method="post">
|
||||||
|
<?php wp_nonce_field('of_sso_test_connection', 'of_sso_test_nonce'); ?>
|
||||||
|
<p>
|
||||||
|
<button type="submit" name="of_sso_test_connection" value="1" class="button button-secondary">
|
||||||
|
<?php esc_html_e('Tester la connexion a OpenFlyers', 'openflyers-sso'); ?>
|
||||||
|
</button>
|
||||||
|
<span class="description">
|
||||||
|
<?php esc_html_e('Verifie le certificat, la signature et les identifiants du client sans qu\'un membre ait a se connecter.', 'openflyers-sso'); ?>
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
</form>
|
||||||
|
<?php
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render the configuration checks.
|
||||||
|
*
|
||||||
|
* @param array $settings Current settings.
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
private static function renderDiagnostics(array $settings)
|
||||||
|
{
|
||||||
|
$checks = array();
|
||||||
|
|
||||||
|
$checks[] = array(
|
||||||
|
__('Extension cURL', 'openflyers-sso'),
|
||||||
|
function_exists('curl_init'),
|
||||||
|
__('Requise pour le TLS mutuel.', 'openflyers-sso'),
|
||||||
|
);
|
||||||
|
|
||||||
|
$checks[] = array(
|
||||||
|
__('Extension OpenSSL', 'openflyers-sso'),
|
||||||
|
function_exists('openssl_sign'),
|
||||||
|
__('Requise pour la signature HTTP.', 'openflyers-sso'),
|
||||||
|
);
|
||||||
|
|
||||||
|
$files = array(
|
||||||
|
'auth_cert' => __('Certificat TLS mutuel', 'openflyers-sso'),
|
||||||
|
'auth_key' => __('Cle privee TLS mutuel', 'openflyers-sso'),
|
||||||
|
'sign_cert' => __('Certificat de signature HTTP', 'openflyers-sso'),
|
||||||
|
'sign_key' => __('Cle privee de signature HTTP', 'openflyers-sso'),
|
||||||
|
'ca_cert' => __('Autorite de certification', 'openflyers-sso'),
|
||||||
|
'server_sign_cert' => __('Certificat de signature du serveur', 'openflyers-sso'),
|
||||||
|
);
|
||||||
|
|
||||||
|
// The folder setting and the per-file overrides both land here.
|
||||||
|
$paths = of_sso_resolve_cert_paths($settings);
|
||||||
|
|
||||||
|
foreach ($files as $key => $label) {
|
||||||
|
$path = $paths[$key];
|
||||||
|
$comment = '';
|
||||||
|
|
||||||
|
if (!empty($path) and is_readable($path) and substr($key, -4) === 'cert') {
|
||||||
|
$parsed = openssl_x509_parse((string) file_get_contents($path));
|
||||||
|
|
||||||
|
if (!empty($parsed['validTo_time_t'])) {
|
||||||
|
$comment = sprintf(
|
||||||
|
/* translators: %s: certificate expiry date. */
|
||||||
|
__('Expire le %s', 'openflyers-sso'),
|
||||||
|
date_i18n(get_option('date_format'), $parsed['validTo_time_t'])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ca.crt only overrides the bundle used to validate the OpenFlyers server; without it
|
||||||
|
// the system store applies, which is what most hosts want.
|
||||||
|
if ($key === 'ca_cert' and empty($path)) {
|
||||||
|
$checks[] = array(
|
||||||
|
$label,
|
||||||
|
true,
|
||||||
|
__('Absent : le magasin d\'autorites du systeme sera utilise.', 'openflyers-sso'),
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($path)) {
|
||||||
|
$comment = __('Aucun chemin : renseignez le dossier des certificats.', 'openflyers-sso');
|
||||||
|
} elseif (!is_readable($path)) {
|
||||||
|
$comment = sprintf(
|
||||||
|
/* translators: %s: expected file path. */
|
||||||
|
__('Introuvable ou illisible : %s', 'openflyers-sso'),
|
||||||
|
$path
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$checks[] = array($label, !empty($path) && is_readable($path), $comment);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A certificate paired with the wrong key fails at handshake time with an obscure error.
|
||||||
|
$pairs = array(
|
||||||
|
'auth' => array('auth_cert', 'auth_key', __('Le certificat TLS et sa cle correspondent', 'openflyers-sso')),
|
||||||
|
'sign' => array('sign_cert', 'sign_key', __('Le certificat de signature et sa cle correspondent', 'openflyers-sso')),
|
||||||
|
);
|
||||||
|
|
||||||
|
foreach ($pairs as $pair) {
|
||||||
|
list($certKey, $keyKey, $label) = $pair;
|
||||||
|
|
||||||
|
if (empty($paths[$certKey]) or empty($paths[$keyKey])
|
||||||
|
or !is_readable($paths[$certKey]) or !is_readable($paths[$keyKey])
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$privateKey = empty($settings['key_passphrase'])
|
||||||
|
? openssl_get_privatekey((string) file_get_contents($paths[$keyKey]))
|
||||||
|
: openssl_get_privatekey((string) file_get_contents($paths[$keyKey]), $settings['key_passphrase']);
|
||||||
|
|
||||||
|
$matches = $privateKey
|
||||||
|
? openssl_x509_check_private_key((string) file_get_contents($paths[$certKey]), $privateKey)
|
||||||
|
: false;
|
||||||
|
|
||||||
|
$checks[] = array(
|
||||||
|
$label,
|
||||||
|
$matches,
|
||||||
|
$matches ? '' : __('La cle ne correspond pas au certificat, ou la passphrase est incorrecte.', 'openflyers-sso'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A private key readable by anyone on a shared host is the main risk of this setup.
|
||||||
|
// Skipped on Windows, where fileperms() says nothing about the actual ACL.
|
||||||
|
foreach (array('auth_key', 'sign_key') as $key) {
|
||||||
|
if (DIRECTORY_SEPARATOR === '\\') {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($paths[$key]) and is_readable($paths[$key])) {
|
||||||
|
$perms = substr(sprintf('%o', fileperms($paths[$key])), -3);
|
||||||
|
|
||||||
|
$checks[] = array(
|
||||||
|
sprintf(
|
||||||
|
/* translators: %s: setting label. */
|
||||||
|
__('Permissions de %s', 'openflyers-sso'),
|
||||||
|
$key
|
||||||
|
),
|
||||||
|
in_array($perms, array('600', '400'), true),
|
||||||
|
sprintf(
|
||||||
|
/* translators: %s: octal file permissions. */
|
||||||
|
__('Actuellement %s, attendu 600.', 'openflyers-sso'),
|
||||||
|
$perms
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
echo '<table class="widefat striped" style="max-width:900px">';
|
||||||
|
foreach ($checks as $check) {
|
||||||
|
list($label, $ok, $comment) = $check;
|
||||||
|
|
||||||
|
printf(
|
||||||
|
'<tr><td style="width:320px">%s</td><td style="width:60px">%s</td><td>%s</td></tr>',
|
||||||
|
esc_html($label),
|
||||||
|
$ok ? '<span style="color:#00a32a">✓</span>' : '<span style="color:#d63638">✗</span>',
|
||||||
|
esc_html($comment)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
echo '</table>';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render a text input row.
|
||||||
|
*
|
||||||
|
* @param string $key Setting key.
|
||||||
|
* @param string $label Field label.
|
||||||
|
* @param string $value Current value.
|
||||||
|
* @param string $placeholder Placeholder text.
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
private static function textRow($key, $label, $value, $placeholder)
|
||||||
|
{
|
||||||
|
printf(
|
||||||
|
'<tr><th scope="row"><label for="of_sso_%1$s">%2$s</label></th>'
|
||||||
|
. '<td><input type="text" class="regular-text" id="of_sso_%1$s" name="%3$s[%1$s]" value="%4$s" placeholder="%5$s" /></td></tr>',
|
||||||
|
esc_attr($key),
|
||||||
|
esc_html($label),
|
||||||
|
esc_attr(OF_SSO_OPTION),
|
||||||
|
esc_attr($value),
|
||||||
|
esc_attr($placeholder)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render a full-width note under the previous field.
|
||||||
|
*
|
||||||
|
* @param string $text Help text.
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
private static function descriptionRow($text)
|
||||||
|
{
|
||||||
|
printf('<tr><th scope="row"></th><td><p class="description">%s</p></td></tr>', esc_html($text));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render a write-only secret row.
|
||||||
|
*
|
||||||
|
* @param string $key Setting key.
|
||||||
|
* @param string $label Field label.
|
||||||
|
* @param string $value Current value.
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
private static function secretRow($key, $label, $value)
|
||||||
|
{
|
||||||
|
printf(
|
||||||
|
'<tr><th scope="row"><label for="of_sso_%1$s">%2$s</label></th>'
|
||||||
|
. '<td><input type="password" class="regular-text" id="of_sso_%1$s" name="%3$s[%1$s]" value="" autocomplete="new-password" />'
|
||||||
|
. '<p class="description">%4$s</p></td></tr>',
|
||||||
|
esc_attr($key),
|
||||||
|
esc_html($label),
|
||||||
|
esc_attr(OF_SSO_OPTION),
|
||||||
|
empty($value)
|
||||||
|
? esc_html__('Non renseigne.', 'openflyers-sso')
|
||||||
|
: esc_html__('Deja enregistre. Laisser vide pour conserver la valeur actuelle.', 'openflyers-sso')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render a checkbox row.
|
||||||
|
*
|
||||||
|
* @param string $key Setting key.
|
||||||
|
* @param string $label Field label.
|
||||||
|
* @param int $value Current value.
|
||||||
|
* @param string $description Help text.
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
private static function checkboxRow($key, $label, $value, $description)
|
||||||
|
{
|
||||||
|
printf(
|
||||||
|
'<tr><th scope="row">%2$s</th><td><label><input type="checkbox" id="of_sso_%1$s" name="%3$s[%1$s]" value="1" %4$s /> %2$s</label>'
|
||||||
|
. '<p class="description">%5$s</p></td></tr>',
|
||||||
|
esc_attr($key),
|
||||||
|
esc_html($label),
|
||||||
|
esc_attr(OF_SSO_OPTION),
|
||||||
|
checked(1, (int) $value, false),
|
||||||
|
esc_html($description)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render the role selector.
|
||||||
|
*
|
||||||
|
* @param string $key Setting key.
|
||||||
|
* @param string $label Field label.
|
||||||
|
* @param string $value Current value.
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
private static function roleRow($key, $label, $value)
|
||||||
|
{
|
||||||
|
printf(
|
||||||
|
'<tr><th scope="row"><label for="of_sso_%1$s">%2$s</label></th><td><select id="of_sso_%1$s" name="%3$s[%1$s]">',
|
||||||
|
esc_attr($key),
|
||||||
|
esc_html($label),
|
||||||
|
esc_attr(OF_SSO_OPTION)
|
||||||
|
);
|
||||||
|
|
||||||
|
// wp_roles() is always available, unlike wp_dropdown_roles() which needs the admin includes.
|
||||||
|
foreach (wp_roles()->get_names() as $role => $name) {
|
||||||
|
printf(
|
||||||
|
'<option value="%s" %s>%s</option>',
|
||||||
|
esc_attr($role),
|
||||||
|
selected($role, $value, false),
|
||||||
|
esc_html(translate_user_role($name))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
echo '</select></td></tr>';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Display the OpenFlyers identifier on the user profile screen.
|
||||||
|
*
|
||||||
|
* @param WP_User $user User being edited.
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public static function renderUserField($user)
|
||||||
|
{
|
||||||
|
if (!current_user_can('edit_users') and get_current_user_id() !== $user->ID) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$value = get_user_meta($user->ID, OF_SSO_USER_META, true);
|
||||||
|
$editable = current_user_can('edit_users');
|
||||||
|
?>
|
||||||
|
<h2><?php esc_html_e('OpenFlyers', 'openflyers-sso'); ?></h2>
|
||||||
|
<table class="form-table" role="presentation">
|
||||||
|
<tr>
|
||||||
|
<th><label for="of_sso_user_id"><?php esc_html_e('Identifiant du membre', 'openflyers-sso'); ?></label></th>
|
||||||
|
<td>
|
||||||
|
<?php if ($editable) : ?>
|
||||||
|
<?php wp_nonce_field('of_sso_user_field', 'of_sso_user_nonce'); ?>
|
||||||
|
<input type="text" id="of_sso_user_id" name="of_sso_user_id" value="<?php echo esc_attr($value); ?>" class="regular-text" />
|
||||||
|
<p class="description"><?php esc_html_e('Identifiant OpenFlyers du membre. Necessaire pour associer ce compte WordPress a un compte OpenFlyers.', 'openflyers-sso'); ?></p>
|
||||||
|
<?php else : ?>
|
||||||
|
<code><?php echo esc_html($value ? $value : '-'); ?></code>
|
||||||
|
<?php endif; ?>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
<?php
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save the OpenFlyers identifier from the user profile screen.
|
||||||
|
*
|
||||||
|
* @param int $userId Edited user identifier.
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public static function saveUserField($userId)
|
||||||
|
{
|
||||||
|
if (!current_user_can('edit_users')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isset($_POST['of_sso_user_nonce'])
|
||||||
|
or !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['of_sso_user_nonce'])), 'of_sso_user_field')
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$value = isset($_POST['of_sso_user_id']) ? sanitize_text_field(wp_unslash($_POST['of_sso_user_id'])) : '';
|
||||||
|
|
||||||
|
if ($value === '') {
|
||||||
|
delete_user_meta($userId, OF_SSO_USER_META);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
update_user_meta($userId, OF_SSO_USER_META, (string) absint($value));
|
||||||
|
}
|
||||||
|
}
|
||||||
670
includes/class-of-sso-client.php
Normal file
670
includes/class-of-sso-client.php
Normal file
@@ -0,0 +1,670 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* class-of-sso-client.php
|
||||||
|
*
|
||||||
|
* OpenFlyers OAuth 2.0 protocol client.
|
||||||
|
*
|
||||||
|
* Ported from the official OpenFlyers demonstration client (oauth2-demo/ClientDemo.php).
|
||||||
|
* The OpenFlyers authorization server is stricter than a plain OAuth2/OIDC provider: every call to
|
||||||
|
* the token and resource endpoints must be sent over mutual TLS AND carry a Cavage HTTP Signature
|
||||||
|
* header, and the server signs its own responses (Digest + Signature) which the client must verify.
|
||||||
|
*
|
||||||
|
* @package OpenFlyers_SSO
|
||||||
|
*
|
||||||
|
* @link https://doc4-fr.openflyers.com/Plugin-WordPress Documentation publique
|
||||||
|
* @link https://work.openflyers.com/OF4-WordPress-SSO-plugin Fiche interne
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Prevent direct access.
|
||||||
|
if (!defined('ABSPATH')) {
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class OF_SSO_Client
|
||||||
|
*/
|
||||||
|
class OF_SSO_Client
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Configuration keys: client_id, client_secret, authorize_uri, token_uri, resource_uri,
|
||||||
|
* revoke_uri, auth_cert, auth_key, sign_cert, sign_key, ca_cert, server_sign_cert,
|
||||||
|
* key_passphrase, send_x_ssl_cert.
|
||||||
|
*
|
||||||
|
* @var array
|
||||||
|
*/
|
||||||
|
private $config;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Last error message, for display and logging.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
private $lastError = '';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* OAuth2 error code returned by the last failed call ('invalid_client', 'invalid_grant', ...).
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
private $lastErrorCode = '';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* cURL error number of the last failed call, 0 when the failure happened above the transport.
|
||||||
|
*
|
||||||
|
* @var int
|
||||||
|
*/
|
||||||
|
private $lastCurlErrno = 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* OF_SSO_Client constructor.
|
||||||
|
*
|
||||||
|
* @param array $config Client configuration.
|
||||||
|
*/
|
||||||
|
public function __construct(array $config)
|
||||||
|
{
|
||||||
|
$this->config = $config;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the last error raised by a request.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function getLastError()
|
||||||
|
{
|
||||||
|
return $this->lastError;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the OAuth2 error code of the last failed call.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function getLastErrorCode()
|
||||||
|
{
|
||||||
|
return $this->lastErrorCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the cURL error number of the last failed call.
|
||||||
|
*
|
||||||
|
* @return int
|
||||||
|
*/
|
||||||
|
public function getLastCurlErrno()
|
||||||
|
{
|
||||||
|
return $this->lastCurlErrno;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate a PKCE code_verifier.
|
||||||
|
*
|
||||||
|
* @param int $length Length of the generated string.
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public static function generateCodeVerifier($length = 128)
|
||||||
|
{
|
||||||
|
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-._~';
|
||||||
|
$output = '';
|
||||||
|
|
||||||
|
for ($i = 0; $i < $length; $i++) {
|
||||||
|
$output .= $characters[random_int(0, strlen($characters) - 1)];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $output;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compute the PKCE code_challenge (S256) matching a code_verifier.
|
||||||
|
*
|
||||||
|
* @param string $codeVerifier The code_verifier.
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public static function computeCodeChallenge($codeVerifier)
|
||||||
|
{
|
||||||
|
return strtr(rtrim(base64_encode(hash('sha256', $codeVerifier, true)), '='), '+/', '-_');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the URL the member's browser must be redirected to in order to log in on OpenFlyers.
|
||||||
|
*
|
||||||
|
* @param string $redirectUri Callback URL, must match the one registered in OpenFlyers.
|
||||||
|
* @param string $state Anti-CSRF opaque value.
|
||||||
|
* @param string $codeChallenge PKCE challenge.
|
||||||
|
* @param string $scope Requested scope, 'default.login' for authentication.
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function getAuthorizeUrl($redirectUri, $state, $codeChallenge, $scope = 'default.login')
|
||||||
|
{
|
||||||
|
$params = array(
|
||||||
|
'response_type' => 'code',
|
||||||
|
'client_id' => $this->config['client_id'],
|
||||||
|
'redirect_uri' => $redirectUri,
|
||||||
|
'scope' => $scope,
|
||||||
|
'state' => $state,
|
||||||
|
'code_challenge' => $codeChallenge,
|
||||||
|
'code_challenge_method' => 'S256',
|
||||||
|
);
|
||||||
|
|
||||||
|
return $this->config['authorize_uri'] . '?' . http_build_query($params);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exchange an authorization code for an access token.
|
||||||
|
*
|
||||||
|
* @param string $code Authorization code returned by the authorization endpoint.
|
||||||
|
* @param string $codeVerifier PKCE verifier matching the challenge sent at authorize time.
|
||||||
|
* @param string $redirectUri Same callback URL as the one used to obtain the code.
|
||||||
|
* @return array|false Token array on success, false on failure.
|
||||||
|
*/
|
||||||
|
public function exchangeCode($code, $codeVerifier, $redirectUri)
|
||||||
|
{
|
||||||
|
return $this->apiRequest(
|
||||||
|
$this->config['token_uri'],
|
||||||
|
array(
|
||||||
|
'grant_type' => 'authorization_code',
|
||||||
|
'client_id' => $this->config['client_id'],
|
||||||
|
'client_secret' => empty($this->config['client_secret']) ? null : $this->config['client_secret'],
|
||||||
|
'redirect_uri' => $redirectUri,
|
||||||
|
'code' => $code,
|
||||||
|
'code_verifier' => $codeVerifier,
|
||||||
|
),
|
||||||
|
null,
|
||||||
|
true
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renew an access token from a refresh token.
|
||||||
|
*
|
||||||
|
* @param string $refreshToken The refresh token.
|
||||||
|
* @param string $scope Requested scope.
|
||||||
|
* @return array|false
|
||||||
|
*/
|
||||||
|
public function refreshToken($refreshToken, $scope = 'default.login')
|
||||||
|
{
|
||||||
|
return $this->apiRequest(
|
||||||
|
$this->config['token_uri'],
|
||||||
|
array(
|
||||||
|
'grant_type' => 'refresh_token',
|
||||||
|
'client_id' => $this->config['client_id'],
|
||||||
|
'client_secret' => empty($this->config['client_secret']) ? null : $this->config['client_secret'],
|
||||||
|
'refresh_token' => $refreshToken,
|
||||||
|
'scope' => $scope,
|
||||||
|
),
|
||||||
|
null,
|
||||||
|
true
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve the OpenFlyers identifier of the member who authorized the token.
|
||||||
|
*
|
||||||
|
* The 'default.login' scope exposes the user identifier and nothing else.
|
||||||
|
*
|
||||||
|
* @param array $token Token array returned by exchangeCode().
|
||||||
|
* @return int|false OpenFlyers user id, or false on failure.
|
||||||
|
*/
|
||||||
|
public function getUserId(array $token)
|
||||||
|
{
|
||||||
|
$body = $this->apiRequest(
|
||||||
|
$this->config['resource_uri'],
|
||||||
|
array(
|
||||||
|
'resource_type' => 'user_information',
|
||||||
|
'client_id' => $this->config['client_id'],
|
||||||
|
),
|
||||||
|
$token,
|
||||||
|
false
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!is_array($body) or !isset($body['user_id'])) {
|
||||||
|
$this->lastError = $this->lastError ? $this->lastError : 'No user_id in the resource server response';
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (int) $body['user_id'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve a report from the resource server.
|
||||||
|
*
|
||||||
|
* Requires the 'reports.readonly' (custom report) or 'genericreports.readonly' (generic report)
|
||||||
|
* scope to have been granted to the token. Used when the member space needs more than the bare
|
||||||
|
* user identifier (name, e-mail, membership status, ...).
|
||||||
|
*
|
||||||
|
* @param array $token Token array returned by exchangeCode().
|
||||||
|
* @param int $reportId Identifier of the report in OpenFlyers.
|
||||||
|
* @param string $resourceType 'report' for a custom report, 'generic_report' otherwise.
|
||||||
|
* @param array $replacementList Report variables, as name => value.
|
||||||
|
* @return array|string|false Decoded JSON, raw CSV body, or false on failure.
|
||||||
|
*/
|
||||||
|
public function getReport(array $token, $reportId, $resourceType = 'report', array $replacementList = array())
|
||||||
|
{
|
||||||
|
$post = array(
|
||||||
|
'resource_type' => $resourceType,
|
||||||
|
'report_id' => (int) $reportId,
|
||||||
|
'client_id' => $this->config['client_id'],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!empty($replacementList)) {
|
||||||
|
$post['replacementList'] = $replacementList;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->apiRequest($this->config['resource_uri'], $post, $token, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Revoke a token on the authorization server.
|
||||||
|
*
|
||||||
|
* @param array $token Token array holding the refresh token to revoke.
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function revoke(array $token)
|
||||||
|
{
|
||||||
|
if (empty($this->config['revoke_uri']) or empty($token['refresh_token'])) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$response = $this->apiRequest(
|
||||||
|
$this->config['revoke_uri'],
|
||||||
|
array(
|
||||||
|
'client_id' => $this->config['client_id'],
|
||||||
|
'token' => $token['refresh_token'],
|
||||||
|
'token_type_hint' => 'refresh_token',
|
||||||
|
),
|
||||||
|
$token,
|
||||||
|
false
|
||||||
|
);
|
||||||
|
|
||||||
|
return $response !== false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Probe the token endpoint with a deliberately invalid authorization code.
|
||||||
|
*
|
||||||
|
* Everything guarding that endpoint is exercised on the way in: mutual TLS, HTTP signature and
|
||||||
|
* client credentials. Only the code itself cannot be valid. So a refusal that complains about
|
||||||
|
* the code, and nothing else, means the whole authentication chain is accepted. That is what
|
||||||
|
* has to be confirmed before a member ever tries to log in, and it needs no member and no
|
||||||
|
* browser.
|
||||||
|
*
|
||||||
|
* @param string $redirectUri The callback URL registered in OpenFlyers.
|
||||||
|
* @return array Verdict as array('status' => string, 'detail' => string), where status is one
|
||||||
|
* of 'ok', 'network', 'tls', 'signature', 'client', 'grant_type', 'unknown'.
|
||||||
|
*/
|
||||||
|
public function testConnection($redirectUri)
|
||||||
|
{
|
||||||
|
$this->exchangeCode('of-sso-connection-probe', self::generateCodeVerifier(), $redirectUri);
|
||||||
|
|
||||||
|
$code = $this->lastErrorCode;
|
||||||
|
$message = $this->lastError;
|
||||||
|
|
||||||
|
// CAINFO verifies the *server* certificate. A ca.crt that does not chain up to the one
|
||||||
|
// OpenFlyers serves stops the call here, which looks like a network failure but is not.
|
||||||
|
if (in_array($this->lastCurlErrno, array(60, 77), true)) {
|
||||||
|
return array('status' => 'server_ca', 'detail' => $message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nothing reached the server: the failure is in the transport or in the key material.
|
||||||
|
if ($this->lastCurlErrno !== 0) {
|
||||||
|
return array('status' => 'network', 'detail' => $message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 'invalid_certificate' comes from the application, 'ssl_certificate_error' from the web
|
||||||
|
// server in front of it. Both mean the same thing to whoever has to fix it.
|
||||||
|
if ($code === 'invalid_certificate' or $code === 'ssl_certificate_error') {
|
||||||
|
return array('status' => 'tls', 'detail' => $message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A signature refusal also comes back as invalid_request, so the wording decides.
|
||||||
|
if (stripos($message, 'signature') !== false) {
|
||||||
|
return array('status' => 'signature', 'detail' => $message);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($code === 'invalid_client') {
|
||||||
|
return array('status' => 'client', 'detail' => $message);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($code === 'unsupported_grant_type') {
|
||||||
|
return array('status' => 'grant_type', 'detail' => $message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Anything else means the request was authenticated and only the fake code was rejected.
|
||||||
|
if ($code !== '') {
|
||||||
|
return array('status' => 'ok', 'detail' => $message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return array('status' => 'unknown', 'detail' => $message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Private methods */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a signed request over mutual TLS to the authorization or resource server.
|
||||||
|
*
|
||||||
|
* @param string $url Endpoint URL.
|
||||||
|
* @param array $post POST parameters.
|
||||||
|
* @param array|null $token Access token to send as a bearer, if any.
|
||||||
|
* @param bool $verifySignature Whether the response signature must be verified.
|
||||||
|
* @return array|string|false
|
||||||
|
*/
|
||||||
|
private function apiRequest($url, array $post, $token = null, $verifySignature = true)
|
||||||
|
{
|
||||||
|
$this->lastError = '';
|
||||||
|
$this->lastErrorCode = '';
|
||||||
|
$this->lastCurlErrno = 0;
|
||||||
|
|
||||||
|
// Every certificate and key must be readable before anything is sent over the wire.
|
||||||
|
if (!$this->checkFiles()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Null values would be sent as empty strings and break client authentication.
|
||||||
|
$post = array_filter(
|
||||||
|
$post,
|
||||||
|
function ($value) {
|
||||||
|
return !is_null($value);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
$postData = http_build_query($post);
|
||||||
|
|
||||||
|
// Headers covered by the HTTP signature. The order defines the signing string.
|
||||||
|
$headersToSign = array(
|
||||||
|
'Content-Type' => 'application/x-www-form-urlencoded',
|
||||||
|
'digest' => 'SHA-256=' . base64_encode(hash('sha256', $postData, true)),
|
||||||
|
'(request-target)' => 'post ' . parse_url($url, PHP_URL_PATH),
|
||||||
|
'Host' => parse_url($url, PHP_URL_HOST),
|
||||||
|
'Date' => gmdate('D, j M Y H:i:s T'),
|
||||||
|
);
|
||||||
|
|
||||||
|
$signKey = $this->readFile($this->config['sign_key']);
|
||||||
|
$keyId = openssl_x509_fingerprint($this->readFile($this->config['sign_cert']));
|
||||||
|
|
||||||
|
$headers = array();
|
||||||
|
$headers['Signature'] = $this->generateSignatureHeader($headersToSign, $keyId, $signKey);
|
||||||
|
$headers['Accept'] = 'application/json';
|
||||||
|
$headers['User-Agent'] = 'OpenFlyers-SSO-WordPress/' . OF_SSO_VERSION;
|
||||||
|
|
||||||
|
// Some hosting setups terminate TLS on a proxy that does not forward the client certificate
|
||||||
|
// to PHP. In that case OpenFlyers accepts the certificate fingerprint in X-SSL-CERT instead.
|
||||||
|
if (!empty($this->config['send_x_ssl_cert'])) {
|
||||||
|
$headers['X-SSL-CERT'] = openssl_x509_fingerprint($this->readFile($this->config['auth_cert']));
|
||||||
|
}
|
||||||
|
|
||||||
|
// '(request-target)' is a signing pseudo-header and must not be sent as a real header.
|
||||||
|
unset($headersToSign['(request-target)']);
|
||||||
|
$headers += $headersToSign;
|
||||||
|
|
||||||
|
if ($token and isset($token['access_token'])) {
|
||||||
|
$tokenType = isset($token['token_type']) ? $token['token_type'] : 'Bearer';
|
||||||
|
$headers['Authorization'] = $tokenType . ' ' . $token['access_token'];
|
||||||
|
}
|
||||||
|
|
||||||
|
$httpHeaders = array();
|
||||||
|
foreach ($headers as $key => $value) {
|
||||||
|
$httpHeaders[] = trim($key) . ': ' . trim($value);
|
||||||
|
}
|
||||||
|
|
||||||
|
$curl = curl_init($url);
|
||||||
|
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
|
||||||
|
curl_setopt($curl, CURLOPT_HEADER, true);
|
||||||
|
curl_setopt($curl, CURLOPT_POST, true);
|
||||||
|
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
|
||||||
|
curl_setopt($curl, CURLOPT_HTTPHEADER, $httpHeaders);
|
||||||
|
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
|
||||||
|
curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
|
||||||
|
|
||||||
|
// Mutual TLS: client certificate and private key issued by the OpenFlyers PKI.
|
||||||
|
curl_setopt($curl, CURLOPT_SSLCERT, $this->config['auth_cert']);
|
||||||
|
curl_setopt($curl, CURLOPT_SSLKEY, $this->config['auth_key']);
|
||||||
|
if (!empty($this->config['key_passphrase'])) {
|
||||||
|
curl_setopt($curl, CURLOPT_KEYPASSWD, $this->config['key_passphrase']);
|
||||||
|
}
|
||||||
|
if (!empty($this->config['ca_cert'])) {
|
||||||
|
curl_setopt($curl, CURLOPT_CAINFO, $this->config['ca_cert']);
|
||||||
|
}
|
||||||
|
|
||||||
|
$response = curl_exec($curl);
|
||||||
|
$errno = curl_errno($curl);
|
||||||
|
$error = curl_error($curl);
|
||||||
|
curl_close($curl);
|
||||||
|
|
||||||
|
if ($response === false) {
|
||||||
|
$this->lastCurlErrno = $errno;
|
||||||
|
$this->lastError = sprintf('cURL error %d: %s', $errno, $error);
|
||||||
|
OF_SSO_Logger::log($this->lastError . ' (' . $url . ')');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->parseResponse($response, $url, $verifySignature);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check that every configured certificate and key can be read.
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
private function checkFiles()
|
||||||
|
{
|
||||||
|
$required = array('auth_cert', 'auth_key', 'sign_cert', 'sign_key');
|
||||||
|
|
||||||
|
if (!empty($this->config['ca_cert'])) {
|
||||||
|
$required[] = 'ca_cert';
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($required as $key) {
|
||||||
|
if (empty($this->config[$key]) or !is_readable($this->config[$key])) {
|
||||||
|
$this->lastError = sprintf('Unreadable or missing file for "%s"', $key);
|
||||||
|
OF_SSO_Logger::log($this->lastError);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the Cavage HTTP Signature header line.
|
||||||
|
*
|
||||||
|
* @param array $headersToSign Headers to cover, as name => value.
|
||||||
|
* @param string $keyId Fingerprint of the signing certificate.
|
||||||
|
* @param string $privateKey PEM encoded private key.
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
private function generateSignatureHeader(array $headersToSign, $keyId, $privateKey)
|
||||||
|
{
|
||||||
|
$headerList = '';
|
||||||
|
$signatureString = '';
|
||||||
|
|
||||||
|
foreach ($headersToSign as $key => $value) {
|
||||||
|
$normalizedKey = trim(strtolower($key));
|
||||||
|
$headerList .= $normalizedKey . ' ';
|
||||||
|
$signatureString .= $normalizedKey . ': ' . trim($value) . "\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
$headerList = trim($headerList);
|
||||||
|
$signatureString = trim($signatureString);
|
||||||
|
|
||||||
|
$key = empty($this->config['key_passphrase'])
|
||||||
|
? openssl_get_privatekey($privateKey)
|
||||||
|
: openssl_get_privatekey($privateKey, $this->config['key_passphrase']);
|
||||||
|
|
||||||
|
$signature = '';
|
||||||
|
openssl_sign($signatureString, $signature, $key, 'RSA-SHA256');
|
||||||
|
|
||||||
|
return sprintf(
|
||||||
|
'keyId="%s",algorithm="rsa-sha256",headers="%s",signature="%s"',
|
||||||
|
$keyId,
|
||||||
|
$headerList,
|
||||||
|
base64_encode($signature)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Split the raw cURL response, check its status, verify Digest and Signature, decode the body.
|
||||||
|
*
|
||||||
|
* @param string $response Raw response including headers.
|
||||||
|
* @param string $url Endpoint that was called, for logging.
|
||||||
|
* @param bool $verifySignature Whether a valid response signature is mandatory.
|
||||||
|
* @return array|string|false
|
||||||
|
*/
|
||||||
|
private function parseResponse($response, $url, $verifySignature)
|
||||||
|
{
|
||||||
|
$parts = explode("\r\n\r\n", $response, 2);
|
||||||
|
|
||||||
|
if (count($parts) < 2) {
|
||||||
|
$this->lastError = 'Malformed response from the OpenFlyers server';
|
||||||
|
OF_SSO_Logger::log($this->lastError . ' (' . $url . ')');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
list($rawHeaders, $body) = $parts;
|
||||||
|
|
||||||
|
// An informational block ('100 Continue') may precede the real response. Match it on the
|
||||||
|
// status line only: any "100" elsewhere in the headers, in a cookie or a content length,
|
||||||
|
// would otherwise split the body at the wrong place and lose the payload.
|
||||||
|
while (preg_match('#^HTTP/[0-9.]+\s+1\d\d#', $rawHeaders)) {
|
||||||
|
$split = explode("\r\n\r\n", $body, 2);
|
||||||
|
|
||||||
|
if (count($split) !== 2) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
list($rawHeaders, $body) = $split;
|
||||||
|
}
|
||||||
|
|
||||||
|
$headerLines = explode("\r\n", $rawHeaders);
|
||||||
|
$statusLine = array_shift($headerLines);
|
||||||
|
|
||||||
|
$headers = array();
|
||||||
|
foreach ($headerLines as $line) {
|
||||||
|
if (strpos($line, ': ') === false) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
list($key, $value) = explode(': ', $line, 2);
|
||||||
|
$headers[strtolower(trim($key))] = trim($value);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!preg_match('#^HTTP/[0-9.]+ 200#', trim($statusLine))) {
|
||||||
|
// The interesting part of a refusal is in the body, not in the status line.
|
||||||
|
$error = json_decode($body, true);
|
||||||
|
$details = array();
|
||||||
|
|
||||||
|
if (is_array($error)) {
|
||||||
|
$this->lastErrorCode = isset($error['error']) ? (string) $error['error'] : '';
|
||||||
|
|
||||||
|
foreach (array('error', 'error_description', 'message', 'hint') as $field) {
|
||||||
|
if (!empty($error[$field]) and is_string($error[$field])) {
|
||||||
|
$details[] = $error[$field];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} elseif (preg_match('#<title>(.*?)</title>#is', $body, $title)) {
|
||||||
|
// A client certificate the server does not accept is rejected by the web server
|
||||||
|
// itself, which answers an HTML page long before PHP and its JSON errors run.
|
||||||
|
$details[] = trim($title[1]);
|
||||||
|
|
||||||
|
if (stripos($title[1], 'certificate') !== false) {
|
||||||
|
$this->lastErrorCode = 'ssl_certificate_error';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->lastError = 'OpenFlyers returned "' . trim($statusLine) . '"'
|
||||||
|
. (empty($details) ? '' : ' : ' . implode(' - ', array_unique($details)));
|
||||||
|
|
||||||
|
OF_SSO_Logger::log($this->lastError . ' (' . $url . ') body=' . substr($body, 0, 500));
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response integrity: the server sends a Digest of the body and signs its own headers.
|
||||||
|
if (isset($headers['digest'])) {
|
||||||
|
list($algo, $expected) = array_pad(explode('=', $headers['digest'], 2), 2, '');
|
||||||
|
$computed = base64_encode(hash(strtolower(str_replace('-', '', $algo)), $body, true));
|
||||||
|
|
||||||
|
if (!hash_equals($expected, $computed)) {
|
||||||
|
$this->lastError = 'Digest mismatch, the response may have been tampered with';
|
||||||
|
OF_SSO_Logger::log($this->lastError . ' (' . $url . ')');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($verifySignature and !$this->verifyResponseSignature($headers, $url)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$decoded = json_decode($body, true);
|
||||||
|
|
||||||
|
return is_null($decoded) ? $body : $decoded;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify the Signature header sent back by the OpenFlyers server.
|
||||||
|
*
|
||||||
|
* @param array $headers Response headers, lowercased keys.
|
||||||
|
* @param string $url Endpoint that was called, for logging.
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
private function verifyResponseSignature(array $headers, $url)
|
||||||
|
{
|
||||||
|
if (empty($this->config['server_sign_cert']) or !is_readable($this->config['server_sign_cert'])) {
|
||||||
|
$this->lastError = 'The OpenFlyers response signing certificate is missing';
|
||||||
|
OF_SSO_Logger::log($this->lastError);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($headers['signature'])) {
|
||||||
|
$this->lastError = 'No signature in the OpenFlyers response';
|
||||||
|
OF_SSO_Logger::log($this->lastError . ' (' . $url . ')');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$signature = array();
|
||||||
|
foreach (explode(',', $headers['signature']) as $chunk) {
|
||||||
|
if (strpos($chunk, '=') === false) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
list($key, $value) = explode('=', $chunk, 2);
|
||||||
|
$signature[trim($key)] = trim($value, '"');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($signature['headers']) or empty($signature['signature'])) {
|
||||||
|
$this->lastError = 'Unreadable signature in the OpenFlyers response';
|
||||||
|
OF_SSO_Logger::log($this->lastError . ' (' . $url . ')');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rebuild the signing string from the headers the server declared it had signed.
|
||||||
|
$signingString = '';
|
||||||
|
foreach (explode(' ', $signature['headers']) as $name) {
|
||||||
|
$name = trim($name);
|
||||||
|
if (!isset($headers[$name])) {
|
||||||
|
$this->lastError = 'Signed header "' . $name . '" missing from the response';
|
||||||
|
OF_SSO_Logger::log($this->lastError . ' (' . $url . ')');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
$signingString .= $name . ': ' . trim($headers[$name]) . "\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
$publicKey = openssl_get_publickey($this->readFile($this->config['server_sign_cert']));
|
||||||
|
$valid = openssl_verify(trim($signingString), base64_decode($signature['signature']), $publicKey, 'RSA-SHA256');
|
||||||
|
|
||||||
|
if ($valid !== 1) {
|
||||||
|
$this->lastError = 'Invalid signature on the OpenFlyers response';
|
||||||
|
OF_SSO_Logger::log($this->lastError . ' (' . $url . ')');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read a local certificate or key file.
|
||||||
|
*
|
||||||
|
* @param string $path Absolute path.
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
private function readFile($path)
|
||||||
|
{
|
||||||
|
return is_readable($path) ? (string) file_get_contents($path) : '';
|
||||||
|
}
|
||||||
|
}
|
||||||
607
openflyers-sso.php
Normal file
607
openflyers-sso.php
Normal file
@@ -0,0 +1,607 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* Plugin Name: OpenFlyers SSO
|
||||||
|
* Plugin URI: https://openflyers.com
|
||||||
|
* Description: Authentification des membres d'un espace prive WordPress avec leurs identifiants OpenFlyers (OAuth 2.0, mTLS et signature HTTP). Aucun mot de passe OpenFlyers n'est stocke sur le site.
|
||||||
|
* Version: 1.1.1
|
||||||
|
* Author: OpenFlyers
|
||||||
|
* License: GPL-2.0-or-later
|
||||||
|
* Text Domain: openflyers-sso
|
||||||
|
*
|
||||||
|
* @package OpenFlyers_SSO
|
||||||
|
*
|
||||||
|
* @link https://doc4-fr.openflyers.com/Plugin-WordPress Documentation publique
|
||||||
|
* @link https://work.openflyers.com/OF4-WordPress-SSO-plugin Fiche interne
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Prevent direct access.
|
||||||
|
if (!defined('ABSPATH')) {
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
define('OF_SSO_VERSION', '1.1.1');
|
||||||
|
define('OF_SSO_FILE', __FILE__);
|
||||||
|
define('OF_SSO_PATH', plugin_dir_path(__FILE__));
|
||||||
|
define('OF_SSO_OPTION', 'of_sso_settings');
|
||||||
|
define('OF_SSO_USER_META', 'of_sso_user_id');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class OF_SSO_Logger
|
||||||
|
*
|
||||||
|
* Minimal logger. Writes through error_log() so nothing lands in a publicly readable file.
|
||||||
|
*/
|
||||||
|
class OF_SSO_Logger
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Log a message when debug mode is enabled in the plugin settings.
|
||||||
|
*
|
||||||
|
* @param string $message Message to log.
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public static function log($message)
|
||||||
|
{
|
||||||
|
$settings = of_sso_get_settings();
|
||||||
|
|
||||||
|
if (empty($settings['debug'])) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
error_log('[OpenFlyers SSO] ' . $message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the plugin settings, merged with their defaults.
|
||||||
|
*
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
function of_sso_get_settings()
|
||||||
|
{
|
||||||
|
$defaults = array(
|
||||||
|
'base_url' => 'https://openflyers.com',
|
||||||
|
'platform' => '',
|
||||||
|
'client_id' => '',
|
||||||
|
'client_secret' => '',
|
||||||
|
'cert_dir' => '',
|
||||||
|
'auth_cert' => '',
|
||||||
|
'auth_key' => '',
|
||||||
|
'sign_cert' => '',
|
||||||
|
'sign_key' => '',
|
||||||
|
'ca_cert' => '',
|
||||||
|
'server_sign_cert' => '',
|
||||||
|
'key_passphrase' => '',
|
||||||
|
'redirect_uri' => '',
|
||||||
|
'send_x_ssl_cert' => 0,
|
||||||
|
'auto_create' => 0,
|
||||||
|
'default_role' => 'subscriber',
|
||||||
|
'redirect_after_login' => '',
|
||||||
|
'show_login_button' => 1,
|
||||||
|
'debug' => 0,
|
||||||
|
);
|
||||||
|
|
||||||
|
$settings = get_option(OF_SSO_OPTION, array());
|
||||||
|
|
||||||
|
return wp_parse_args(is_array($settings) ? $settings : array(), $defaults);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the callback URL that must be registered as the redirect URL in OpenFlyers.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
function of_sso_get_redirect_uri()
|
||||||
|
{
|
||||||
|
$settings = of_sso_get_settings();
|
||||||
|
|
||||||
|
if (!empty($settings['redirect_uri'])) {
|
||||||
|
return $settings['redirect_uri'];
|
||||||
|
}
|
||||||
|
|
||||||
|
return home_url('/?of_sso=callback');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Conventional file names inside the certificate folder, as delivered by OpenFlyers.
|
||||||
|
*
|
||||||
|
* @return array Setting key => expected file name.
|
||||||
|
*/
|
||||||
|
function of_sso_cert_file_names()
|
||||||
|
{
|
||||||
|
return array(
|
||||||
|
'auth_cert' => 'auth_cert.crt',
|
||||||
|
'auth_key' => 'auth.key',
|
||||||
|
'sign_cert' => 'sign_cert.crt',
|
||||||
|
'sign_key' => 'sign.key',
|
||||||
|
'ca_cert' => 'ca.crt',
|
||||||
|
'server_sign_cert' => 'sign_cert_server.crt',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve the six certificate paths.
|
||||||
|
*
|
||||||
|
* A single folder is enough when the files carry their standard names; any file stored elsewhere,
|
||||||
|
* or under another name, can still be pointed at individually in the advanced settings.
|
||||||
|
*
|
||||||
|
* @param array|null $settings Settings to resolve, current ones when omitted.
|
||||||
|
* @return array Setting key => absolute path (empty string when neither source provides one).
|
||||||
|
*/
|
||||||
|
function of_sso_resolve_cert_paths($settings = null)
|
||||||
|
{
|
||||||
|
$settings = is_array($settings) ? $settings : of_sso_get_settings();
|
||||||
|
$folder = isset($settings['cert_dir']) ? rtrim(trim($settings['cert_dir']), '/\\') : '';
|
||||||
|
$paths = array();
|
||||||
|
|
||||||
|
foreach (of_sso_cert_file_names() as $key => $fileName) {
|
||||||
|
$explicit = isset($settings[$key]) ? trim($settings[$key]) : '';
|
||||||
|
|
||||||
|
if ($explicit !== '') {
|
||||||
|
$paths[$key] = $explicit;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$derived = ($folder === '') ? '' : $folder . DIRECTORY_SEPARATOR . $fileName;
|
||||||
|
|
||||||
|
// ca.crt is optional: it overrides the CA bundle used to verify the OpenFlyers server.
|
||||||
|
// When the folder does not hold one, fall back to the system bundle rather than failing.
|
||||||
|
if ($key === 'ca_cert' and $derived !== '' and !is_readable($derived)) {
|
||||||
|
$derived = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
$paths[$key] = $derived;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $paths;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a configured protocol client, or false when the plugin is not fully configured.
|
||||||
|
*
|
||||||
|
* @return OF_SSO_Client|false
|
||||||
|
*/
|
||||||
|
function of_sso_get_client()
|
||||||
|
{
|
||||||
|
$settings = of_sso_get_settings();
|
||||||
|
|
||||||
|
if (empty($settings['client_id']) or empty($settings['base_url'])) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hosted platforms live under a code (openflyers.com/mon-club/oauth). A dedicated or local
|
||||||
|
// install answers at the domain root instead, and then the code is simply left empty.
|
||||||
|
$root = untrailingslashit($settings['base_url']);
|
||||||
|
|
||||||
|
if (!empty($settings['platform'])) {
|
||||||
|
$root .= '/' . trim($settings['platform'], '/');
|
||||||
|
}
|
||||||
|
|
||||||
|
$root .= '/oauth';
|
||||||
|
|
||||||
|
$config = array(
|
||||||
|
'client_id' => $settings['client_id'],
|
||||||
|
'client_secret' => $settings['client_secret'],
|
||||||
|
'authorize_uri' => $root . '/authorize.php',
|
||||||
|
'token_uri' => $root . '/access_token.php',
|
||||||
|
'resource_uri' => $root . '/resources.php',
|
||||||
|
'revoke_uri' => $root . '/revoke.php',
|
||||||
|
'key_passphrase' => $settings['key_passphrase'],
|
||||||
|
'send_x_ssl_cert' => $settings['send_x_ssl_cert'],
|
||||||
|
);
|
||||||
|
|
||||||
|
$config += of_sso_resolve_cert_paths($settings);
|
||||||
|
|
||||||
|
return new OF_SSO_Client(apply_filters('of_sso_client_config', $config));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the URL that starts an OpenFlyers login.
|
||||||
|
*
|
||||||
|
* @param string $redirectTo Where the member should land once logged in.
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
function of_sso_login_url($redirectTo = '')
|
||||||
|
{
|
||||||
|
$args = array('of_sso' => 'login');
|
||||||
|
|
||||||
|
if (!empty($redirectTo)) {
|
||||||
|
$args['redirect_to'] = rawurlencode($redirectTo);
|
||||||
|
}
|
||||||
|
|
||||||
|
return add_query_arg($args, home_url('/'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tell whether the current user is logged in through OpenFlyers.
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
function of_sso_is_member()
|
||||||
|
{
|
||||||
|
if (!is_user_logged_in()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (bool) get_user_meta(get_current_user_id(), OF_SSO_USER_META, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
require_once OF_SSO_PATH . 'includes/class-of-sso-client.php';
|
||||||
|
require_once OF_SSO_PATH . 'includes/class-of-sso-admin.php';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class OF_SSO_Auth
|
||||||
|
*
|
||||||
|
* Drives the authorization code flow and maps OpenFlyers members onto WordPress users.
|
||||||
|
*/
|
||||||
|
class OF_SSO_Auth
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Lifetime, in seconds, of a pending authorization request.
|
||||||
|
*/
|
||||||
|
const STATE_TTL = 600;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register the hooks.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public static function init()
|
||||||
|
{
|
||||||
|
add_action('init', array(__CLASS__, 'route'));
|
||||||
|
add_action('login_form', array(__CLASS__, 'renderLoginButton'));
|
||||||
|
add_filter('login_message', array(__CLASS__, 'renderLoginError'));
|
||||||
|
add_shortcode('openflyers_login', array(__CLASS__, 'shortcodeLoginButton'));
|
||||||
|
add_shortcode('openflyers_membre', array(__CLASS__, 'shortcodeMemberOnly'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dispatch the plugin's own front-end URLs.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public static function route()
|
||||||
|
{
|
||||||
|
$action = isset($_GET['of_sso']) ? sanitize_key(wp_unslash($_GET['of_sso'])) : '';
|
||||||
|
|
||||||
|
if ($action === 'login') {
|
||||||
|
self::startLogin();
|
||||||
|
} elseif ($action === 'callback') {
|
||||||
|
self::handleCallback();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start the authorization code flow: store the PKCE material, then redirect to OpenFlyers.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public static function startLogin()
|
||||||
|
{
|
||||||
|
$client = of_sso_get_client();
|
||||||
|
|
||||||
|
if (!$client) {
|
||||||
|
self::fail(__('Le module OpenFlyers SSO n\'est pas configure.', 'openflyers-sso'));
|
||||||
|
}
|
||||||
|
|
||||||
|
$state = bin2hex(random_bytes(16));
|
||||||
|
$codeVerifier = OF_SSO_Client::generateCodeVerifier();
|
||||||
|
|
||||||
|
$redirectTo = isset($_GET['redirect_to']) ? esc_url_raw(rawurldecode(wp_unslash($_GET['redirect_to']))) : '';
|
||||||
|
|
||||||
|
// The state is the key: it links the callback back to this pending request.
|
||||||
|
set_transient(
|
||||||
|
'of_sso_state_' . $state,
|
||||||
|
array(
|
||||||
|
'code_verifier' => $codeVerifier,
|
||||||
|
'redirect_to' => $redirectTo,
|
||||||
|
),
|
||||||
|
self::STATE_TTL
|
||||||
|
);
|
||||||
|
|
||||||
|
$url = $client->getAuthorizeUrl(
|
||||||
|
of_sso_get_redirect_uri(),
|
||||||
|
$state,
|
||||||
|
OF_SSO_Client::computeCodeChallenge($codeVerifier),
|
||||||
|
apply_filters('of_sso_scope', 'default.login')
|
||||||
|
);
|
||||||
|
|
||||||
|
wp_redirect($url);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the return from OpenFlyers: validate the state, exchange the code, log the member in.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public static function handleCallback()
|
||||||
|
{
|
||||||
|
$client = of_sso_get_client();
|
||||||
|
|
||||||
|
if (!$client) {
|
||||||
|
self::fail(__('Le module OpenFlyers SSO n\'est pas configure.', 'openflyers-sso'));
|
||||||
|
}
|
||||||
|
|
||||||
|
// OpenFlyers reports a refused authorization with an error parameter.
|
||||||
|
if (isset($_GET['error'])) {
|
||||||
|
OF_SSO_Logger::log('Authorization refused: ' . sanitize_text_field(wp_unslash($_GET['error'])));
|
||||||
|
self::fail(__('La connexion a ete refusee par OpenFlyers.', 'openflyers-sso'));
|
||||||
|
}
|
||||||
|
|
||||||
|
$state = isset($_GET['state']) ? sanitize_text_field(wp_unslash($_GET['state'])) : '';
|
||||||
|
$code = isset($_GET['code']) ? sanitize_text_field(wp_unslash($_GET['code'])) : '';
|
||||||
|
|
||||||
|
if (empty($state) or empty($code)) {
|
||||||
|
self::fail(__('Reponse incomplete d\'OpenFlyers.', 'openflyers-sso'));
|
||||||
|
}
|
||||||
|
|
||||||
|
$pending = get_transient('of_sso_state_' . $state);
|
||||||
|
delete_transient('of_sso_state_' . $state);
|
||||||
|
|
||||||
|
// An unknown or expired state means the flow was tampered with, or simply took too long.
|
||||||
|
if (!is_array($pending) or empty($pending['code_verifier'])) {
|
||||||
|
self::fail(__('Session de connexion expiree ou invalide. Merci de reessayer.', 'openflyers-sso'));
|
||||||
|
}
|
||||||
|
|
||||||
|
$token = $client->exchangeCode($code, $pending['code_verifier'], of_sso_get_redirect_uri());
|
||||||
|
|
||||||
|
if (!is_array($token) or empty($token['access_token'])) {
|
||||||
|
OF_SSO_Logger::log('Token exchange failed: ' . $client->getLastError());
|
||||||
|
self::fail(__('Impossible d\'obtenir le jeton d\'acces aupres d\'OpenFlyers.', 'openflyers-sso'));
|
||||||
|
}
|
||||||
|
|
||||||
|
$ofUserId = $client->getUserId($token);
|
||||||
|
|
||||||
|
if (!$ofUserId) {
|
||||||
|
OF_SSO_Logger::log('User identifier retrieval failed: ' . $client->getLastError());
|
||||||
|
self::fail(__('Impossible de recuperer l\'identifiant du membre aupres d\'OpenFlyers.', 'openflyers-sso'));
|
||||||
|
}
|
||||||
|
|
||||||
|
$user = self::resolveUser($ofUserId, $token, $client);
|
||||||
|
|
||||||
|
if (is_wp_error($user)) {
|
||||||
|
self::fail($user->get_error_message());
|
||||||
|
}
|
||||||
|
|
||||||
|
wp_set_current_user($user->ID);
|
||||||
|
wp_set_auth_cookie($user->ID, false);
|
||||||
|
do_action('wp_login', $user->user_login, $user);
|
||||||
|
|
||||||
|
update_user_meta($user->ID, 'of_sso_last_login', time());
|
||||||
|
|
||||||
|
do_action('of_sso_after_login', $user, $ofUserId, $token);
|
||||||
|
|
||||||
|
$settings = of_sso_get_settings();
|
||||||
|
$redirectTo = !empty($pending['redirect_to'])
|
||||||
|
? $pending['redirect_to']
|
||||||
|
: (!empty($settings['redirect_after_login']) ? $settings['redirect_after_login'] : home_url('/'));
|
||||||
|
|
||||||
|
wp_safe_redirect($redirectTo);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find, or optionally create, the WordPress user matching an OpenFlyers member.
|
||||||
|
*
|
||||||
|
* @param int $ofUserId OpenFlyers user identifier.
|
||||||
|
* @param array $token Token array, passed to the profile filter.
|
||||||
|
* @param OF_SSO_Client $client Configured client, passed to the profile filter.
|
||||||
|
* @return WP_User|WP_Error
|
||||||
|
*/
|
||||||
|
private static function resolveUser($ofUserId, array $token, OF_SSO_Client $client)
|
||||||
|
{
|
||||||
|
$settings = of_sso_get_settings();
|
||||||
|
|
||||||
|
$existing = get_users(
|
||||||
|
array(
|
||||||
|
'meta_key' => OF_SSO_USER_META,
|
||||||
|
'meta_value' => (string) $ofUserId,
|
||||||
|
'number' => 1,
|
||||||
|
'fields' => 'all',
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Extra data (name, e-mail, membership status) is not exposed by the 'default.login' scope.
|
||||||
|
// Sites needing it hook this filter and feed it from an OpenFlyers report.
|
||||||
|
$profile = apply_filters('of_sso_user_profile', array(), $ofUserId, $token, $client);
|
||||||
|
|
||||||
|
if (!empty($existing)) {
|
||||||
|
$user = $existing[0];
|
||||||
|
self::applyProfile($user->ID, $profile);
|
||||||
|
|
||||||
|
return $user;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($settings['auto_create'])) {
|
||||||
|
OF_SSO_Logger::log('No WordPress user linked to OpenFlyers id ' . $ofUserId);
|
||||||
|
|
||||||
|
return new WP_Error(
|
||||||
|
'of_sso_no_account',
|
||||||
|
__('Aucun compte de ce site n\'est associe a votre compte OpenFlyers. Merci de contacter le club.', 'openflyers-sso')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$login = 'of-' . $ofUserId;
|
||||||
|
$email = !empty($profile['user_email']) ? $profile['user_email'] : '';
|
||||||
|
|
||||||
|
$userId = wp_insert_user(
|
||||||
|
array(
|
||||||
|
'user_login' => $login,
|
||||||
|
'user_pass' => wp_generate_password(32, true, true),
|
||||||
|
'user_email' => $email,
|
||||||
|
'display_name' => !empty($profile['display_name']) ? $profile['display_name'] : $login,
|
||||||
|
'role' => $settings['default_role'],
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
if (is_wp_error($userId)) {
|
||||||
|
OF_SSO_Logger::log('User creation failed: ' . $userId->get_error_message());
|
||||||
|
|
||||||
|
return $userId;
|
||||||
|
}
|
||||||
|
|
||||||
|
update_user_meta($userId, OF_SSO_USER_META, (string) $ofUserId);
|
||||||
|
self::applyProfile($userId, $profile);
|
||||||
|
|
||||||
|
return get_user_by('id', $userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Copy the optional profile fields onto the WordPress user.
|
||||||
|
*
|
||||||
|
* @param int $userId WordPress user identifier.
|
||||||
|
* @param array $profile Profile data returned by the 'of_sso_user_profile' filter.
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
private static function applyProfile($userId, array $profile)
|
||||||
|
{
|
||||||
|
$fields = array_intersect_key(
|
||||||
|
$profile,
|
||||||
|
array_flip(array('user_email', 'display_name', 'first_name', 'last_name'))
|
||||||
|
);
|
||||||
|
|
||||||
|
if (empty($fields)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$fields['ID'] = $userId;
|
||||||
|
wp_update_user($fields);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stop the flow and send the member back to the login page with a message.
|
||||||
|
*
|
||||||
|
* @param string $message Message to display.
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
private static function fail($message)
|
||||||
|
{
|
||||||
|
set_transient('of_sso_error_' . self::visitorKey(), $message, 120);
|
||||||
|
|
||||||
|
wp_safe_redirect(add_query_arg('of_sso_error', '1', wp_login_url()));
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a key identifying the current visitor, to store a one-shot error message.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
private static function visitorKey()
|
||||||
|
{
|
||||||
|
$ip = isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : '';
|
||||||
|
$agent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '';
|
||||||
|
|
||||||
|
return md5($ip . $agent);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Display the pending error message on the WordPress login page.
|
||||||
|
*
|
||||||
|
* @param string $message Existing login page message.
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public static function renderLoginError($message)
|
||||||
|
{
|
||||||
|
if (!isset($_GET['of_sso_error'])) {
|
||||||
|
return $message;
|
||||||
|
}
|
||||||
|
|
||||||
|
$error = get_transient('of_sso_error_' . self::visitorKey());
|
||||||
|
delete_transient('of_sso_error_' . self::visitorKey());
|
||||||
|
|
||||||
|
if (empty($error)) {
|
||||||
|
$error = __('La connexion via OpenFlyers a echoue.', 'openflyers-sso');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $message . '<div id="login_error">' . esc_html($error) . '</div>';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add an OpenFlyers button to the standard WordPress login form.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public static function renderLoginButton()
|
||||||
|
{
|
||||||
|
$settings = of_sso_get_settings();
|
||||||
|
|
||||||
|
if (empty($settings['show_login_button'])) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
echo '<p style="margin-bottom:16px">' . self::buttonHtml(__('Se connecter avec OpenFlyers', 'openflyers-sso'), '') . '</p>';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shortcode [openflyers_login] : login button, or a short message once logged in.
|
||||||
|
*
|
||||||
|
* @param array $atts Shortcode attributes.
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public static function shortcodeLoginButton($atts)
|
||||||
|
{
|
||||||
|
$atts = shortcode_atts(
|
||||||
|
array(
|
||||||
|
'label' => __('Se connecter avec OpenFlyers', 'openflyers-sso'),
|
||||||
|
'redirect' => '',
|
||||||
|
),
|
||||||
|
$atts,
|
||||||
|
'openflyers_login'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (is_user_logged_in()) {
|
||||||
|
$user = wp_get_current_user();
|
||||||
|
|
||||||
|
return '<p>' . sprintf(
|
||||||
|
/* translators: %s: display name of the logged in member. */
|
||||||
|
esc_html__('Connecte en tant que %s.', 'openflyers-sso'),
|
||||||
|
esc_html($user->display_name)
|
||||||
|
) . ' <a href="' . esc_url(wp_logout_url(home_url('/'))) . '">' . esc_html__('Se deconnecter', 'openflyers-sso') . '</a></p>';
|
||||||
|
}
|
||||||
|
|
||||||
|
return self::buttonHtml($atts['label'], $atts['redirect']);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shortcode [openflyers_membre] : content reserved to members logged in through OpenFlyers.
|
||||||
|
*
|
||||||
|
* @param array $atts Shortcode attributes.
|
||||||
|
* @param string $content Enclosed content.
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public static function shortcodeMemberOnly($atts, $content = '')
|
||||||
|
{
|
||||||
|
$atts = shortcode_atts(
|
||||||
|
array(
|
||||||
|
'message' => __('Cet espace est reserve aux membres du club.', 'openflyers-sso'),
|
||||||
|
),
|
||||||
|
$atts,
|
||||||
|
'openflyers_membre'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (of_sso_is_member()) {
|
||||||
|
return do_shortcode($content);
|
||||||
|
}
|
||||||
|
|
||||||
|
return '<div class="of-sso-restricted"><p>' . esc_html($atts['message']) . '</p>'
|
||||||
|
. self::buttonHtml(__('Se connecter avec OpenFlyers', 'openflyers-sso'), '') . '</div>';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render the login button markup.
|
||||||
|
*
|
||||||
|
* @param string $label Button label.
|
||||||
|
* @param string $redirect Where to land after login.
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
private static function buttonHtml($label, $redirect)
|
||||||
|
{
|
||||||
|
$target = !empty($redirect) ? $redirect : (is_singular() ? get_permalink() : '');
|
||||||
|
|
||||||
|
return '<a class="button button-primary of-sso-button" href="' . esc_url(of_sso_login_url($target)) . '">'
|
||||||
|
. esc_html($label) . '</a>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
OF_SSO_Auth::init();
|
||||||
|
OF_SSO_Admin::init();
|
||||||
184
tests/smoke-test.php
Normal file
184
tests/smoke-test.php
Normal file
@@ -0,0 +1,184 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
// Command-line only: this script rewrites settings and accounts, it must never run from a web request.
|
||||||
|
if (PHP_SAPI !== 'cli') {
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Smoke test for the WordPress plugin protocol client, run outside WordPress.
|
||||||
|
* Checks the HTTP signature generation and the response verification (Digest + Signature)
|
||||||
|
* against a locally generated certificate, the same way the OpenFlyers server does it.
|
||||||
|
*/
|
||||||
|
|
||||||
|
define('ABSPATH', __DIR__);
|
||||||
|
define('OF_SSO_VERSION', 'test');
|
||||||
|
|
||||||
|
class OF_SSO_Logger
|
||||||
|
{
|
||||||
|
public static function log($message)
|
||||||
|
{
|
||||||
|
echo " [log] $message\n";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
require __DIR__ . '/../includes/class-of-sso-client.php';
|
||||||
|
|
||||||
|
$dir = sys_get_temp_dir() . '/of-sso-test-certs';
|
||||||
|
@mkdir($dir);
|
||||||
|
|
||||||
|
// Generate a throwaway key pair and self-signed certificate.
|
||||||
|
$key = openssl_pkey_new(array('private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA));
|
||||||
|
$csr = openssl_csr_new(array('commonName' => 'test.local'), $key);
|
||||||
|
$crt = openssl_csr_sign($csr, null, $key, 3650);
|
||||||
|
openssl_pkey_export($key, $keyPem);
|
||||||
|
openssl_x509_export($crt, $crtPem);
|
||||||
|
file_put_contents("$dir/sign.key", $keyPem);
|
||||||
|
file_put_contents("$dir/sign_cert.crt", $crtPem);
|
||||||
|
file_put_contents("$dir/auth.key", $keyPem);
|
||||||
|
file_put_contents("$dir/auth_cert.crt", $crtPem);
|
||||||
|
file_put_contents("$dir/server_sign.crt", $crtPem);
|
||||||
|
|
||||||
|
$config = array(
|
||||||
|
'client_id' => 'testclient',
|
||||||
|
'client_secret' => 'secret',
|
||||||
|
'authorize_uri' => 'https://openflyers.com/demo/oauth/authorize.php',
|
||||||
|
'token_uri' => 'https://openflyers.com/demo/oauth/access_token.php',
|
||||||
|
'resource_uri' => 'https://openflyers.com/demo/oauth/resources.php',
|
||||||
|
'revoke_uri' => 'https://openflyers.com/demo/oauth/revoke.php',
|
||||||
|
'auth_cert' => "$dir/auth_cert.crt",
|
||||||
|
'auth_key' => "$dir/auth.key",
|
||||||
|
'sign_cert' => "$dir/sign_cert.crt",
|
||||||
|
'sign_key' => "$dir/sign.key",
|
||||||
|
'ca_cert' => '',
|
||||||
|
'server_sign_cert' => "$dir/server_sign.crt",
|
||||||
|
'key_passphrase' => '',
|
||||||
|
'send_x_ssl_cert' => 0,
|
||||||
|
);
|
||||||
|
|
||||||
|
$client = new OF_SSO_Client($config);
|
||||||
|
$reflection = new ReflectionClass($client);
|
||||||
|
$fail = 0;
|
||||||
|
|
||||||
|
function check($label, $ok)
|
||||||
|
{
|
||||||
|
global $fail;
|
||||||
|
echo ($ok ? ' OK ' : ' FAIL ') . $label . "\n";
|
||||||
|
if (!$ok) {
|
||||||
|
$fail++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- PKCE -------------------------------------------------------------------
|
||||||
|
$verifier = OF_SSO_Client::generateCodeVerifier();
|
||||||
|
$challenge = OF_SSO_Client::computeCodeChallenge($verifier);
|
||||||
|
check('code_verifier length is 128', strlen($verifier) === 128);
|
||||||
|
check(
|
||||||
|
'code_challenge is base64url of sha256(verifier)',
|
||||||
|
$challenge === rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=')
|
||||||
|
);
|
||||||
|
check('code_challenge has no padding or unsafe chars', preg_match('#^[A-Za-z0-9_-]+$#', $challenge) === 1);
|
||||||
|
|
||||||
|
// --- authorize URL ----------------------------------------------------------
|
||||||
|
$url = $client->getAuthorizeUrl('https://www.exemple.fr/?of_sso=callback', 'abc123', $challenge);
|
||||||
|
parse_str(parse_url($url, PHP_URL_QUERY), $query);
|
||||||
|
check('authorize URL targets the platform endpoint', strpos($url, 'https://openflyers.com/demo/oauth/authorize.php?') === 0);
|
||||||
|
check('response_type=code', $query['response_type'] === 'code');
|
||||||
|
check('code_challenge_method=S256', $query['code_challenge_method'] === 'S256');
|
||||||
|
check('scope defaults to default.login', $query['scope'] === 'default.login');
|
||||||
|
check('redirect_uri is preserved exactly', $query['redirect_uri'] === 'https://www.exemple.fr/?of_sso=callback');
|
||||||
|
|
||||||
|
// --- HTTP signature ---------------------------------------------------------
|
||||||
|
$method = $reflection->getMethod('generateSignatureHeader');
|
||||||
|
$method->setAccessible(true);
|
||||||
|
|
||||||
|
$postData = http_build_query(array('grant_type' => 'authorization_code', 'client_id' => 'testclient'));
|
||||||
|
$headersToSign = array(
|
||||||
|
'Content-Type' => 'application/x-www-form-urlencoded',
|
||||||
|
'digest' => 'SHA-256=' . base64_encode(hash('sha256', $postData, true)),
|
||||||
|
'(request-target)' => 'post /demo/oauth/access_token.php',
|
||||||
|
'Host' => 'openflyers.com',
|
||||||
|
'Date' => gmdate('D, j M Y H:i:s T'),
|
||||||
|
);
|
||||||
|
|
||||||
|
$keyId = openssl_x509_fingerprint($crtPem);
|
||||||
|
$header = $method->invoke($client, $headersToSign, $keyId, $keyPem);
|
||||||
|
|
||||||
|
preg_match('/keyId="([^"]+)"/', $header, $m);
|
||||||
|
check('keyId is the signing certificate fingerprint', $m[1] === $keyId);
|
||||||
|
preg_match('/headers="([^"]+)"/', $header, $m);
|
||||||
|
check(
|
||||||
|
'signed header list matches the server expectation',
|
||||||
|
$m[1] === 'content-type digest (request-target) host date'
|
||||||
|
);
|
||||||
|
|
||||||
|
// Verify exactly the way the server does: rebuild the signing string, verify with the certificate.
|
||||||
|
preg_match('/signature="([^"]+)"/', $header, $m);
|
||||||
|
$signingString = '';
|
||||||
|
foreach ($headersToSign as $name => $value) {
|
||||||
|
$signingString .= strtolower($name) . ': ' . $value . "\n";
|
||||||
|
}
|
||||||
|
$verified = openssl_verify(trim($signingString), base64_decode($m[1]), openssl_get_publickey($crtPem), 'RSA-SHA256');
|
||||||
|
check('signature verifies against the certificate', $verified === 1);
|
||||||
|
|
||||||
|
// --- response parsing, digest and signature ---------------------------------
|
||||||
|
$parse = $reflection->getMethod('parseResponse');
|
||||||
|
$parse->setAccessible(true);
|
||||||
|
|
||||||
|
$body = json_encode(array('token_type' => 'Bearer', 'access_token' => 'abc', 'expires_in' => 3600));
|
||||||
|
$digest = 'SHA-256=' . base64_encode(hash('sha256', $body, true));
|
||||||
|
$date = gmdate('D, j M Y H:i:s T');
|
||||||
|
|
||||||
|
$serverSigningString = "date: $date\ndigest: $digest";
|
||||||
|
openssl_sign($serverSigningString, $serverSignature, openssl_get_privatekey($keyPem), 'RSA-SHA256');
|
||||||
|
$serverSignatureHeader = 'keyId="' . $keyId . '",algorithm="rsa-sha256",headers="date digest",signature="'
|
||||||
|
. base64_encode($serverSignature) . '"';
|
||||||
|
|
||||||
|
$response = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nDate: $date\r\nDigest: $digest\r\n"
|
||||||
|
. "Signature: $serverSignatureHeader\r\n\r\n" . $body;
|
||||||
|
|
||||||
|
$result = $parse->invoke($client, $response, $config['token_uri'], true);
|
||||||
|
check('valid signed response is accepted and decoded', is_array($result) && $result['access_token'] === 'abc');
|
||||||
|
|
||||||
|
// A '100 Continue' preamble must not break the parsing.
|
||||||
|
$withContinue = "HTTP/1.1 100 Continue\r\n\r\n" . $response;
|
||||||
|
$result = $parse->invoke($client, $withContinue, $config['token_uri'], true);
|
||||||
|
check('100 Continue preamble is handled', is_array($result) && $result['access_token'] === 'abc');
|
||||||
|
|
||||||
|
// Tampered body must be rejected by the digest check.
|
||||||
|
$tampered = str_replace($body, json_encode(array('access_token' => 'stolen')), $response);
|
||||||
|
$result = $parse->invoke($client, $tampered, $config['token_uri'], true);
|
||||||
|
check('tampered body is rejected (digest)', $result === false);
|
||||||
|
|
||||||
|
// Tampered signature must be rejected.
|
||||||
|
$badSignature = str_replace(base64_encode($serverSignature), base64_encode(strrev($serverSignature)), $response);
|
||||||
|
$result = $parse->invoke($client, $badSignature, $config['token_uri'], true);
|
||||||
|
check('forged signature is rejected', $result === false);
|
||||||
|
|
||||||
|
// A non 200 status must be reported as an error, not decoded.
|
||||||
|
$error = "HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\n\r\n{\"error\":\"invalid_client\"}";
|
||||||
|
$result = $parse->invoke($client, $error, $config['token_uri'], true);
|
||||||
|
check('HTTP 400 is reported as a failure', $result === false);
|
||||||
|
check('error message mentions the status', strpos($client->getLastError(), '400') !== false);
|
||||||
|
|
||||||
|
// A 200 whose status line merely contains "200" elsewhere must still be accepted only on the status code.
|
||||||
|
$weird = "HTTP/1.1 500 Internal Server Error 200\r\nContent-Type: application/json\r\n\r\n{}";
|
||||||
|
$result = $parse->invoke($client, $weird, $config['token_uri'], true);
|
||||||
|
check('a 500 containing "200" in its reason phrase is rejected', $result === false);
|
||||||
|
|
||||||
|
// A "100" inside a cookie or a length must not be mistaken for a '100 Continue' preamble:
|
||||||
|
// the body would then be split at the wrong place and the payload lost.
|
||||||
|
$decoy = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nSet-Cookie: s=a100b; path=/\r\nDate: $date\r\n"
|
||||||
|
. "Digest: $digest\r\nSignature: $serverSignatureHeader\r\n\r\n" . $body;
|
||||||
|
$result = $parse->invoke($client, $decoy, $config['token_uri'], true);
|
||||||
|
check('a "100" inside a header value is not read as a preamble', is_array($result) && $result['access_token'] === 'abc');
|
||||||
|
|
||||||
|
// The web server refuses an unaccepted client certificate itself, with an HTML page and no JSON.
|
||||||
|
$nginx = "HTTP/1.1 400 Bad Request\r\nContent-Type: text/html\r\n\r\n"
|
||||||
|
. "<html><head><title>400 The SSL certificate error</title></head><body></body></html>";
|
||||||
|
$result = $parse->invoke($client, $nginx, $config['token_uri'], true);
|
||||||
|
check('an HTML certificate refusal is reported as a failure', $result === false);
|
||||||
|
check('it is recognized as a certificate problem', $client->getLastErrorCode() === 'ssl_certificate_error');
|
||||||
|
check('the reason reaches the error message', strpos($client->getLastError(), 'SSL certificate error') !== false);
|
||||||
|
|
||||||
|
echo $fail === 0 ? "\nAll checks passed.\n" : "\n$fail check(s) failed.\n";
|
||||||
|
exit($fail === 0 ? 0 : 1);
|
||||||
417
tests/wordpress-test.php
Normal file
417
tests/wordpress-test.php
Normal file
@@ -0,0 +1,417 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
// Command-line only: this script rewrites settings and accounts, it must never run from a web request.
|
||||||
|
if (PHP_SAPI !== 'cli') {
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 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') 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');
|
||||||
|
|
||||||
|
// --- 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 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, '✗') !== 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);
|
||||||
18
uninstall.php
Normal file
18
uninstall.php
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* uninstall.php
|
||||||
|
*
|
||||||
|
* Removes the plugin settings when it is deleted from WordPress.
|
||||||
|
* The user links (of_sso_user_id) are kept so a reinstall does not lose them.
|
||||||
|
*
|
||||||
|
* @package OpenFlyers_SSO
|
||||||
|
*
|
||||||
|
* @link https://doc4-fr.openflyers.com/Plugin-WordPress Documentation publique
|
||||||
|
* @link https://work.openflyers.com/OF4-WordPress-SSO-plugin Fiche interne
|
||||||
|
*/
|
||||||
|
|
||||||
|
if (!defined('WP_UNINSTALL_PLUGIN')) {
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
delete_option('of_sso_settings');
|
||||||
Reference in New Issue
Block a user