redirect_url = $redirectUrl; } /** * Return the webapp Keycloak singleton configured by keycloak.json. */ public static function getInstance(): ?WebAppKeyCloak { if (!defined('GROMOX_CONFIG_PATH')) { define('GROMOX_CONFIG_PATH', '/etc/gromox/'); } $configFile = GROMOX_CONFIG_PATH . 'keycloak.json'; if (self::$instance === null && is_file($configFile)) { $config = json_decode((string) @file_get_contents($configFile), true); if (!is_array($config)) { error_log('Unable to load webapp Keycloak configuration'); return null; } try { self::$instance = new self($config); } catch (InvalidArgumentException|UnexpectedValueException) { error_log('Unable to load webapp Keycloak configuration'); return null; } } return self::$instance; } /** * Build an authorization URL and remember its one-time state value. * * The argument remains for compatibility with KeyCloak::login_url(); the * validated callback established by the constructor is always used. * * @param string $redirectUrl ignored caller-supplied redirect URL * @param bool $usePkce ignored parent-client compatibility option * * @return string authorization URL */ public function login_url($redirectUrl, $usePkce = false): string { $state = bin2hex(random_bytes(32)); $this->storeState($state); $params = [ 'scope' => 'openid', 'client_id' => $this->client_id, 'state' => $state, 'redirect_uri' => $this->redirect_url, 'response_type' => 'code', ]; return $this->realm_url . '/protocol/openid-connect/auth?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986); } /** * Consume a current state value exactly once. * * @param mixed $state callback state parameter * * @return bool true when the state was generated by this session */ public function consumeState($state) { $states = $this->pendingStates(); if (!is_string($state) || preg_match('/\A[a-f0-9]{64}\z/D', $state) !== 1) { $this->saveStates($states); return false; } $key = hash('sha256', $state); if (!isset($states[$key])) { $this->saveStates($states); return false; } unset($states[$key]); $this->saveStates($states); return true; } /** * Require the introspection endpoint to return the JSON boolean true. * * @param mixed $token access token */ protected function validate_token(mixed $token): bool { if (!isset($token)) { return false; } $headers = ['Content-Type: application/x-www-form-urlencoded']; $params = ['token' => $token->get_payload()]; if ($this->is_public) { $params['client_id'] = $this->client_id; } else { $headers[] = 'Authorization: Basic ' . base64_encode($this->client_id . ':' . $this->secret); } $response = $this->http_curl_request( 'POST', '/protocol/openid-connect/token/introspect', $headers, http_build_query($params) ); if ($response['code'] < 200 || $response['code'] > 299) { return false; } try { $data = json_decode((string) $response['body'], true, 512, JSON_THROW_ON_ERROR); } catch (JsonException) { return false; } return is_array($data) && !array_key_exists('error', $data) && ($data['active'] ?? null) === true; } /** * Choose and normalize the OAuth callback URL. * * The callback is the deployment directory (https://host/web), which is the * redirect URI the grommunio-auth client template registers; nginx sends the * browser on to index.php. A fixed SERVER_NAME is preferred. The stock nginx * configuration serves grommunio Web from a catch-all server block * (server_name _;), so the Host header is used when SERVER_NAME is not a * usable host name. Set redirect-url in keycloak.json to pin the callback. * * @param array $config keycloak.json configuration * * @return null|string */ private static function callbackUrl($config) { if (isset($config['redirect-url'])) { return self::normalizeCallbackUrl($config['redirect-url']); } $scriptName = (string) ($_SERVER['SCRIPT_NAME'] ?? '/index.php'); $scriptName = preg_replace('/[\x00-\x1f\x7f]/', '', str_replace('\\', '/', $scriptName)); $directory = rtrim(dirname('/' . ltrim($scriptName, '/')), '/'); $serverName = (string) ($_SERVER['SERVER_NAME'] ?? ''); $host = (string) ($_SERVER['HTTP_HOST'] ?? ''); // SERVER_NAME never carries the port the browser used if ($serverName !== '' && preg_match('~\A' . preg_quote($serverName, '~') . '(:\d{1,5})\z~i', $host, $match) === 1) { $serverName .= $match[1]; } foreach ([$serverName, $host] as $authority) { // a host with an optional port, nothing that could smuggle in a path if ($authority === '' || preg_match('~[^A-Za-z0-9.:\[\]-]~', $authority) === 1) { continue; } $url = self::normalizeCallbackUrl('https://' . $authority . $directory); if ($url !== null) { return $url; } } return null; } /** * Normalize an absolute HTTPS callback URL. * * @param mixed $url * * @return null|string */ private static function normalizeCallbackUrl($url) { if (!is_string($url) || $url === '' || strlen($url) > 4096 || preg_match('/[\x00-\x20\x5c\x7f]/', $url) === 1) { return null; } $parts = @parse_url($url); if ($parts === false || strtolower($parts['scheme'] ?? '') !== 'https' || empty($parts['host']) || isset($parts['user']) || isset($parts['pass']) || isset($parts['fragment'])) { return null; } $host = trim(strtolower((string) $parts['host']), '[]'); if (filter_var($host, FILTER_VALIDATE_IP) === false) { $host = rtrim($host, '.'); if ($host === '' || strlen($host) > 253 || preg_match('/\A[0-9.]+\z/D', $host) === 1 || preg_match('/\A(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?))*\z/D', $host) !== 1) { return null; } } $port = $parts['port'] ?? 443; if (!is_int($port) || $port < 1 || $port > 65535) { return null; } $authority = str_contains($host, ':') ? '[' . $host . ']' : $host; if ($port !== 443) { $authority .= ':' . $port; } // Keycloak matches the string exactly, so keep the path as given $path = $parts['path'] ?? ''; $query = isset($parts['query']) ? '?' . $parts['query'] : ''; return 'https://' . $authority . $path . $query; } /** * Store a state value and retain a small set for concurrent login tabs. * * @param string $state */ private function storeState($state) { $states = $this->pendingStates(); $states[hash('sha256', $state)] = time() + self::STATE_LIFETIME; asort($states, SORT_NUMERIC); if (count($states) > self::MAX_PENDING_STATES) { $states = array_slice($states, -self::MAX_PENDING_STATES, null, true); } $this->saveStates($states); } /** * Return pending, unexpired state hashes from the session. * * @return array */ private function pendingStates() { $stored = $_SESSION[self::STATE_SESSION_KEY] ?? []; if (!is_array($stored)) { return []; } $states = []; $now = time(); foreach ($stored as $hash => $expires) { if (is_string($hash) && preg_match('/\A[a-f0-9]{64}\z/D', $hash) === 1 && is_int($expires) && $expires >= $now) { $states[$hash] = $expires; } } return $states; } /** * Save pending states, removing the session key when none remain. * * @param array $states */ private function saveStates($states) { if (empty($states)) { unset($_SESSION[self::STATE_SESSION_KEY]); } else { $_SESSION[self::STATE_SESSION_KEY] = $states; } } }