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

745 lines
28 KiB
PHP

<?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);
}
/**
* Read the member's name and e-mail from an OpenFlyers custom report.
*
* The report filters on the reserved $connectedPersonId variable, which OpenFlyers replaces by the
* user of the access token: no member identifier is sent, so a member can only read their own row.
* It returns one row with the 'first_name', 'last_name' and 'email' columns. Requires the
* 'reports.readonly' scope.
*
* @param array $token Token array returned by exchangeCode().
* @param int $reportId Identifier of the custom report in OpenFlyers.
* @param int $ofUserId OpenFlyers identifier of the member, used in the error message only.
* @return array|false Profile with the first_name, last_name, user_email and display_name keys
* that the report provides, or false on failure.
*/
public function getMemberProfile(array $token, $reportId, $ofUserId)
{
$csv = $this->getReport($token, $reportId, 'report');
if (!is_string($csv)) {
$this->lastError = $this->lastError ? $this->lastError : 'Unexpected report response';
return false;
}
$row = self::parseReportCsv($csv);
if (empty($row)) {
$this->lastError = 'The report returned no row for member ' . (int) $ofUserId;
return false;
}
$profile = array();
foreach (array('first_name' => 'first_name', 'last_name' => 'last_name', 'email' => 'user_email') as $column => $field) {
if (isset($row[$column]) and trim($row[$column]) !== '') {
$profile[$field] = trim($row[$column]);
}
}
$displayName = trim((isset($profile['first_name']) ? $profile['first_name'] : '') . ' ' . (isset($profile['last_name']) ? $profile['last_name'] : ''));
if ($displayName !== '') {
$profile['display_name'] = $displayName;
}
return $profile;
}
/**
* Return the first data row of a report exported by OpenFlyers, keyed by column name.
*
* OpenFlyers writes one header line, ';' as separator, '\n' as end of line, and replaces any ';'
* found in the data by ',' : a plain split is therefore exact.
*
* @param string $csv CSV text returned by the resource server.
* @return array Column name => value, empty when the report has no data row.
*/
public static function parseReportCsv($csv)
{
$lines = preg_split('/\r\n|\n/', trim((string) $csv, "\r\n"));
if (count($lines) < 2 or trim($lines[1]) === '') {
return array();
}
$header = array_map('trim', explode(';', $lines[0]));
$values = explode(';', $lines[1]);
if (count($header) !== count($values)) {
return array();
}
return array_combine($header, $values);
}
/**
* 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) : '';
}
}