← Back
Editing: class-sso.php
<?php namespace WPaaS; if ( ! defined( 'ABSPATH' ) ) { exit; } final class SSO { /** * Query arg to identify sso problems */ const INVALID_SSO_QARG = 'wpaas_invalid_sso'; /** * Instance of the API. * * @var API_Interface */ private $api; /** * Excluded classes hooked into 'login_form' or 'login_enqueue_scripts'. * * @var array */ private $excluded_classes; /** * The app variant this site serves, as read at mu-plugin load. * * @var string|null */ private static $entry_url_variant; /** * Class constructor. * * @param API_Interface $api */ public function __construct( API_Interface $api ) { $this->api = $api; // Read the variant now, before active plugins load; see entry_url_variant(). self::entry_url_variant(); /** * Excluded plugin classes. * * @var array */ $this->excluded_classes = (array) apply_filters( 'wpaas_gd_login_enqueue_scripts_plugin_classes', array( 'Limit_Login_Attempts', 'Wpsec\twofa\Core\TwoFactorAuthCore', 'Wpsec\captcha\handlers\LoginFormEventHandler', ) ); /** * We must + 1 the minimum integer when hooking into SSO to ensure * that the Log class captures these events properly. * * Note: In WordPress 4.7 the SORT_NUMERIC flag was added to ksort() * for sorting filter priorities. There is also a bug in PHP 5 that * treats ~PHP_INT_MAX as greater than -PHP_INT_MAX. For this reason, * ~PHP_INT_MAX should never be used as a filter priority in WP. * * Note: Must hook into setup_theme for customize.php to work. * * @link https://gist.github.com/fjarrett/d2d1d60930d2ca4e67d35cf672ac9b13 */ add_action( 'setup_theme', [ $this, 'init' ], -PHP_INT_MAX + 1 ); add_action( 'login_init', [ $this, 'login_init' ], PHP_INT_MAX ); add_action( 'shake_error_codes', [ $this, 'shake_error_codes' ] ); add_filter( 'wp_login_errors', [ $this, 'wp_login_errors' ] ); add_filter( 'login_redirect', [ $this, 'login_redirect' ], 10, 3 ); } /** * Initialize script. * * @action setup_theme */ public function init() { // @codingStandardsIgnoreStart $action = ( ! empty( $_REQUEST['GD_COMMAND'] ) && is_string( $_REQUEST['GD_COMMAND'] ) ) ? strtolower( $_REQUEST['GD_COMMAND'] ) : filter_input( INPUT_GET, 'wpaas_action' ); // Backward compat. $hash = ! empty( $_REQUEST['SSO_HASH'] ) ? $_REQUEST['SSO_HASH'] : filter_input( INPUT_GET, 'wpaas_sso_hash' ); // Backward compat. // @codingStandardsIgnoreEnd if ( 'sso_login' !== $action || ! $hash ) { return; } $uri = sanitize_url( filter_input( INPUT_SERVER, 'REQUEST_URI' ) ); if ( is_user_logged_in() ) { wp_safe_redirect( esc_url_raw( $this->resolve_redirect( $uri, wp_get_current_user() ) ) ); exit; } $user_id = $this->user_id(); if ( is_int( $user_id ) ) { if ( $hash && $this->api->is_valid_sso_hash( $hash ) ) { @wp_set_auth_cookie( $user_id ); // @codingStandardsIgnoreLine /** Logg user action */ $GLOBALS['wpaas_activity_logger']->log_sp_action($user_id, 'SSO login success' ); // Resolved with the SSO user, who is not the current user yet on this request. wp_safe_redirect( esc_url_raw( $this->resolve_redirect( $uri, get_userdata( $user_id ) ) ) ); exit; } $GLOBALS['wpaas_activity_logger']->log_sp_action($user_id, sprintf('SSO invalid hash user_id: %d', $user_id) ); } /** Logg user action */ $GLOBALS['wpaas_activity_logger']->log_sp_action($user_id, 'SSO login fail' ); wp_safe_redirect( add_query_arg( static::INVALID_SSO_QARG, '', wp_login_url( admin_url() ) ) ); exit; } /** * Resolve the redirect target for a successful SSO login. * * @param string $uri The request URI the SSO login was initiated from. * @param \WP_User|null $user The user the SSO login resolves to. * * @return string */ private function resolve_redirect( $uri, $user = null ) { $redirect = remove_query_arg( [ 'GD_COMMAND', 'SSO_HASH', 'wpaas_action', 'wpaas_sso_hash', 'nocache' ], home_url( $uri ) ); /** * An SSO callback that lands on the login screen can't redirect back to it. * Honor an explicit redirect_to deep link when one is present, falling back * to wp-admin otherwise. wp_validate_redirect() confines the destination to * this host, so an off-site redirect_to degrades to the fallback. */ if ( preg_match( '~^/wp-login\.php~', $uri ) ) { $args = []; parse_str( (string) wp_parse_url( $redirect, PHP_URL_QUERY ), $args ); $redirect = empty( $args['redirect_to'] ) ? admin_url() : wp_validate_redirect( $args['redirect_to'], admin_url() ); } // Go theme users should go straight to the Colors panel. if ( urldecode( $redirect ) === admin_url( 'customize.php' ) && 'go' === get_option( 'stylesheet' ) ) { $redirect = admin_url( 'customize.php?autofocus[section]=colors' ); } return $this->maybe_redirect_to_dashboard( $redirect, $user ); } /** * Redirect standard (non-SSO) logins to the GoDaddy WordPress dashboard, * unless the resolved destination is a specific admin page. * * Note: $requested_redirect_to is intentionally not treated as "a path was * specified". WordPress's own auth_redirect() sets it to the bare wp-admin * URL whenever a logged-out visitor is bounced from /wp-admin/ to the login * screen, which is the common case this feature is meant to cover, not an * explicit deep link. maybe_redirect_to_dashboard() only rewrites when the * resolved $redirect_to is itself the bare dashboard, so a genuine deep * link (e.g. back to a specific settings page) is left untouched either way. * * SSO logins bypass this filter entirely; they're handled by init(), which * calls wp_safe_redirect() and exit()s before WordPress's normal login flow * (and this filter) ever runs. * * Users who cannot load the dashboard page are left where WordPress sent them, * which also preserves its own low-privilege profile.php redirect. See * dashboard_page_available(). * * @filter login_redirect * * @param string $redirect_to The redirect destination URL. * @param string $requested_redirect_to The requested redirect destination URL passed as a parameter. * @param \WP_User|\WP_Error $user WP_User object if login was successful, WP_Error object otherwise. * * @return string */ public function login_redirect( $redirect_to, $requested_redirect_to, $user ) { return $this->maybe_redirect_to_dashboard( $redirect_to, $user ); } /** * Determine whether the GoDaddy WordPress dashboard page is actually loadable * by a given user. * * The page is registered by the bundled wptool/wp-admin-dash plugin, which only * calls add_menu_page() when the current user has the administrator role — see * AdminDashCore::is_admin(), which checks the role rather than a capability. If * the page was never registered, admin.php has nothing to load and responds with * a "Cannot load wp-dashboard." wp_die() screen, so the conditions here must * mirror that plugin's rather than approximate them with a capability check. * * @param \WP_User|\WP_Error|null $user The user being redirected. * * @return bool */ private function dashboard_page_available( $user ) { // A failed login hands a WP_Error to the login_redirect filter. $available = ( $user instanceof \WP_User ) && in_array( 'administrator', (array) $user->roles, true ) // Mirrors the Bundled_Plugins gate that loads the page's plugin at all. && 'enabled' === get_option( 'admin_dash_enabled', 'enabled' ); /** * Filter whether the GoDaddy WordPress dashboard is available as a login * redirect target for this user. * * @var bool */ return (bool) apply_filters( 'wpaas_dashboard_redirect_available', $available, $user ); } /** * Rewrite a redirect target of the bare wp-admin dashboard to the GoDaddy * WordPress dashboard. * * @param string $redirect The redirect destination URL. * @param \WP_User|\WP_Error|null $user The user being redirected. * * @return string */ private function maybe_redirect_to_dashboard( $redirect, $user = null ) { // Never send a user to a dashboard page that will not load for them. if ( ! $this->dashboard_page_available( $user ) ) { return $redirect; } /** * Filter to send users to the GoDaddy WordPress dashboard after login. * * Only applies when the resolved redirect is the default wp-admin dashboard; * an explicit path to another admin page is left untouched. * * @var bool */ $enabled = (bool) apply_filters( 'wpaas_dashboard_redirect_enabled', true ); // Compare paths only; a stray/incidental query string (e.g. left over from // stripping SSO-specific args) shouldn't stop this from being treated as // the bare dashboard. $redirect_path = untrailingslashit( (string) wp_parse_url( urldecode( $redirect ), PHP_URL_PATH ) ); $admin_path = untrailingslashit( (string) wp_parse_url( admin_url(), PHP_URL_PATH ) ); if ( $enabled && $redirect_path === $admin_path ) { /** * Query args whose presence marks the redirect as a genuine deep link * (e.g. the AIRO onboarding trigger, or a pre-SSO OAuth handoff) rather * than a bare dashboard landing. When any is present the destination * and its full query string are preserved instead of being rewritten * to the dashboard. * * @var string[] */ $preserved_args = (array) apply_filters( 'wpaas_dashboard_redirect_preserved_args', [ 'ai-action', 'airo_onboard', 'handoff_code', 'oauth_status', 'sdui-post-sync' ] ); // Parse the raw query string; parse_str() decodes each value once on // its own. Decoding the whole URL first would turn an encoded // ampersand inside a value (e.g. redirect_to=...%26airo_onboard%3D1) // into a real separator and falsely surface a preserved trigger arg. $query = []; parse_str( (string) wp_parse_url( $redirect, PHP_URL_QUERY ), $query ); if ( empty( array_intersect_key( array_flip( $preserved_args ), $query ) ) ) { return admin_url( 'admin.php?page=wp-dashboard' ); } } return $redirect; } /** * Initialize the GD SSO login button. * * @action login_init */ public function login_init() { /** * Filter to forcefully disable the SSO login functionality. * * @var bool */ $enabled = (bool) apply_filters( 'wpaas_gd_sso_button_enabled', true ); // Only show if all conditions are met. Bail if any other plugin is customizing the login form. if ( ! $enabled || ! Plugin::is_gd() || ! defined( 'GD_ACCOUNT_UID' ) || ! GD_ACCOUNT_UID || ( isset( $_GET['wpaas-standard-login'] ) && (bool) $_GET['wpaas-standard-login'] ) || $this->is_plugin_hooked( 'login_form' ) || $this->is_plugin_hooked( 'login_enqueue_scripts' ) ) { return; } // Add a body class for our SSO login form styles. add_filter( 'login_body_class', function ( $classes ) { $classes[] = 'wpaas-show-sso-login'; return $classes; } ); add_action( 'login_head', [ $this, 'login_head' ] ); add_action( 'login_form', [ $this, 'login_form' ] ); add_action( 'login_footer', [ $this, 'login_footer' ] ); add_action( 'login_enqueue_scripts', [ $this, 'login_enqueue_scripts' ] ); } /** * Determine if a plugin is hooked into 'login_enqueue_scripts' and customizing the login screen. * * @param string $action The action to check against. * * @return boolean True when a plugin is hooked into $action, else false. */ private function is_plugin_hooked( $action ) { global $wp_filter; if ( empty( $action ) || ! array_key_exists( $action, $wp_filter ) ) { return false; } $hooked_actions = array(); $data = $wp_filter[ $action ]->callbacks[ key( $wp_filter[ $action ]->callbacks ) ]; foreach ( $data as $info ) { // Standard function. if ( is_string( $info['function'] ) ) { $hooked_actions[] = $info['function']; continue; } // Closure. if ( is_object( $info['function'] ) ) { $hooked_actions[] = get_class( $info['function'] ); continue; } // Class method. if ( is_array( $info['function'] ) ) { foreach ( $info['function'] as $hook ) { if ( is_object( $hook ) ) { $hooked_actions[] = get_class( $hook ); } } } } if ( ! empty( $hooked_actions ) ) { $hooked_actions = array_diff( $hooked_actions, $this->excluded_classes ); } return ! empty( array_filter( $hooked_actions ) ); } /** * Load fonts for SSO login button. * * @action login_head */ public function login_head() { ?> <link rel="preload" href="//img1.wsimg.com/ux/fonts/sherpa/1.1/gdsherpa-bold.woff2" as="font" type="font/woff2" crossorigin=""/> <style> @font-face { font-family: gdsherpa; src: url(//img1.wsimg.com/ux/fonts/sherpa/1.1/gdsherpa-bold.woff2) format("woff2"), url(//img1.wsimg.com/ux/fonts/sherpa/1.1/gdsherpa-bold.woff) format("woff"); font-weight: 500; font-display: swap; } </style> <?php } /** * Display the SSO login button. * * @action login_form */ public function login_form() { $sso_url = $this->sso_login_url(); ?> <div class="wpaas-sso-login-wrapper"> <div class="wpaas-sso-login-button"> <a href="<?php echo esc_url( $sso_url ); ?>" rel="nofollow" class="button button-primary"> <svg width="42" height="37" viewBox="0 0 42 37" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><path d="M37.633 18.13c-.562 2.115-1.472 4.177-2.705 6.13a22.93 22.93 0 0 1-2.649 3.435c1.112-4.482.36-9.973-2.367-15.122a.69.69 0 0 0-.985-.265l-8.49 5.25a.683.683 0 0 0-.221.946l1.245 1.97c.203.322.631.42.956.22l5.503-3.403c.184.523.35 1.05.49 1.58.53 1.991.727 3.936.587 5.778-.262 3.429-1.673 6.101-3.974 7.524-1.149.71-2.484 1.086-3.934 1.127h-.177c-1.451-.04-2.786-.417-3.936-1.128-2.3-1.422-3.711-4.094-3.973-7.523-.14-1.842.057-3.787.586-5.779.562-2.114 1.472-4.177 2.706-6.13a22.321 22.321 0 0 1 4.382-5.093c1.578-1.344 3.258-2.372 4.993-3.054 3.23-1.271 6.275-1.187 8.576.235 2.3 1.422 3.712 4.094 3.973 7.524.141 1.842-.056 3.786-.586 5.778m-30.56 6.13c-1.234-1.953-2.144-4.015-2.706-6.13-.53-1.992-.727-3.936-.586-5.778.261-3.43 1.672-6.102 3.973-7.524 2.3-1.422 5.347-1.506 8.576-.235.487.191.968.413 1.444.66a26.242 26.242 0 0 0-4.649 5.528C9.562 16.422 8.48 22.689 9.721 27.696a22.939 22.939 0 0 1-2.649-3.436M36.227 1.692C31.86-1.007 26.115-.365 20.999 2.822 15.883-.363 10.138-1.005 5.773 1.693-1.122 5.955-1.96 16.937 3.903 26.22 8.226 33.064 14.983 37.074 21 36.999c6.017.074 12.774-3.935 17.097-10.78 5.863-9.282 5.025-20.264-1.87-24.527" id="a"/></defs><use fill="#FFF" xlink:href="#a" fill-rule="evenodd"/></svg> <?php esc_html_e( 'Log in with GoDaddy', 'gd-system-plugin' ); ?> </a> </div> <div class="wpaas-sso-login-divider"> <span><?php esc_html_e( 'Or', 'gd-system-plugin' ); ?></span> </div> <a href="<?php echo esc_url( add_query_arg( 'wpaas-standard-login', 1 ) ); ?>" rel="nofollow" class="wpaas-sso-login-toggle"> <?php esc_html_e( 'Log in with username and password', 'gd-system-plugin' ); ?> </a> </div> <?php } /** * Resolve where the "Log in with GoDaddy" button sends the browser. * * This is the *entry* hop of SSO — a shopper-authenticated page that proves * who is asking, mints a single-use login token for this site and redirects * back into WordPress carrying it. It is not the same call as * API::is_valid_sso_hash(), which is this site redeeming that token * server-to-server (see API::sso_api_url()). The two hops are addressed * separately and must never be conflated. * * Two branches, selected by API::delivered_sso_api_url() — the same value that * decides where hop 2 redeems, called rather than re-derived so that the two * cannot drift into minting in one control plane and redeeming in the other: * * 1. A base delivered — this site's tokens belong to the hosting control * plane, so the button goes to the Airo app builder route on a host this * plugin hardcodes. * 2. Otherwise the legacy `host.{env}-godaddy.com` URL — every site that * exists today, byte for byte unchanged, and reached without consulting * any entry-URL config at all. * * Neither branch is filterable, and branch 1's host comes off the hardcoded * airo_builder_hosts() allow-list. This value decides where a GoDaddy-branded * button sends a shopper who is already signed in to GoDaddy, so it is * resolved from delivered config and nothing else. * * @return string */ private function sso_login_url() { $env = Plugin::get_env(); if ( '' === API::delivered_sso_api_url() ) { return $this->legacy_login_url( GD_ACCOUNT_UID, $env ); } return $this->airo_builder_login_url( GD_ACCOUNT_UID, $env ); } /** * Build the Airo app builder SSO entry URL. * * `GD_ACCOUNT_UID` is the addressable app id: on the hosting control plane it * carries the app nanoid, and that is what both the Airo route and hosting's * mint expect. No `path`/`type`/`origin` args, unlike the legacy URL — the * minted link always lands at site root because hosting's mint takes no * destination, so sending them would only look as though they worked. * * `variant` is the one argument that is sent, and only from a staging site. * Every variant of a site shares one app id, so an id on its own does not say * which of the site's hosts the shopper should be handed to: hosting mints for * the live site when nothing asks otherwise, which is why the button on a * staging site landed a shopper on the live one. Publish sends no argument at * all, leaving that URL byte for byte the one it emits today. * * The route and the argument are both built here from this site's own config, * and `GD_SSO_LOGIN_URL` contributes a host and nothing else — so what the * platform delivers cannot aim the button at another app, another route, or * another variant. * * @param string $app_id * @param string $env * * @return string */ private function airo_builder_login_url( $app_id, $env ) { $url = sprintf( 'https://%s/api/apps/%s/wp-sso', self::airo_builder_host( $env ), rawurlencode( $app_id ) ); $variant = self::entry_url_variant(); return ( '' === $variant ) ? $url : add_query_arg( 'variant', $variant, $url ); } /** * The app variant this site's login button mints for, or an empty string to * leave the choice at hosting's default. * * Read from `GD_STAGING_SITE` rather than through Plugin::is_staging_site(), * which passes the value through `wpaas_is_staging_site`. Which variant is * being served is a fact the control plane renders into gd-config.php, and the * variant decides which host a signed-in shopper is handed to — the same * reason airo_builder_hosts() is hardcoded keeps this off a filter. The * constant is only rendered on a staging site, so its absence is publish. * * Resolved once, from the constructor, and remembered: the login button renders * long after active plugins have loaded, and a plugin defining this otherwise * absent constant must not be able to point a live site's button at staging. * * Only `staging` is ever emitted. Hosting mints for the variants that have a * login of their own and refuses the rest, so a value it does not recognise * would turn a working button into an error rather than into a fallback. * * @return string */ private static function entry_url_variant() { if ( null === self::$entry_url_variant ) { self::$entry_url_variant = ( defined( 'GD_STAGING_SITE' ) && GD_STAGING_SITE ) ? 'staging' : ''; } return self::$entry_url_variant; } /** * The app builder host this site's login button may address. * * Defaults to the first entry of airo_builder_hosts(); `GD_SSO_LOGIN_URL` may * select any other host on that list, which is how a lower-environment site is * pointed at a pre-test deployment. Only the host is taken from it — the route * is the plugin's, not the platform's. * * @param string $env * * @return string */ private static function airo_builder_host( $env ) { $allowed = self::airo_builder_hosts( $env ); $requested = defined( 'GD_SSO_LOGIN_URL' ) ? self::url_host( (string) GD_SSO_LOGIN_URL ) : ''; return in_array( $requested, $allowed, true ) ? $requested : $allowed[0]; } /** * Hosts allowed to serve the Airo app builder entry hop, per environment. * * Hardcoded rather than synthesized from `SERVER_ENV`, because this value * decides where a GoDaddy-branded button sends a shopper who is already signed * in to GoDaddy. `GD_SSO_LOGIN_URL` is absent on a site the control plane has * not opted in, and an absent constant is definable by site code, so an * allow-list is what keeps that decision in the plugin rather than in the site. * * `pre-test-airo-builder` is a test-environment deployment of the same app * (`APP_HOSTNAME`), which is why it is selectable there and nowhere near * production. There is no deployed `dev` app builder, so dev sites address the * test one; that is also why an unmapped environment lands on the test list * rather than passing through to a hostname that does not resolve. * * @param string $env * * @return array */ private static function airo_builder_hosts( $env ) { if ( 'prod' === Plugin::short_env( $env ) ) { return [ 'airo-builder.godaddy.com' ]; } return [ 'airo-builder.test-godaddy.com', 'pre-test-airo-builder.test-godaddy.com' ]; } /** * Lower-cased host of an absolute https URL, or an empty string. * * Anything that is not https resolves to no host at all: the entry hop carries * a shopper session, and a scheme-less or http value must fail the allow-list * rather than match a host on it. * * @param string $url * * @return string */ private static function url_host( $url ) { $url = trim( (string) $url ); if ( 0 !== stripos( $url, 'https://' ) ) { return ''; } return strtolower( (string) parse_url( $url, PHP_URL_HOST ) ); } /** * Build the legacy Managed WordPress SSO entry URL. * * Unchanged behaviour, including the un-encoded uid and the `path`/`type`/ * `origin` args the legacy endpoint honours. Every site in the existing * estate takes this branch, so it is deliberately left byte-identical rather * than tidied while passing through. * * @param string $app_id * @param string $env * * @return string */ private function legacy_login_url( $app_id, $env ) { return sprintf( 'https://%s/mwp/site/%s/sso?path=/wp-admin&type=wp&origin=wp-login', ( 'prod' === $env ) ? 'host.godaddy.com' : "host.{$env}-godaddy.com", $app_id ); } /** * Remove target="_blank" from the login links * * @action login_footer */ public function login_footer() { if ( ! isset( $_REQUEST['interim-login'] ) ) { return; } ?> <script type="text/javascript"> ( function() { try { var i, links = document.getElementsByTagName( 'a' ); for ( i in links ) { if ( links[i].href && 'wpaas-sso-login-toggle' === links[i].className ) { links[i].target = ''; links[i].rel = ''; } } } catch( er ) {} }()); </script> <?php } /** * Enqueue scripts and styles for SSO login button. * * @action login_enqueue_scripts */ public function login_enqueue_scripts() { $rtl = is_rtl() ? '-rtl' : ''; $suffix = SCRIPT_DEBUG ? '' : '.min'; wp_enqueue_style( 'wpaas-sso-login', Plugin::assets_url( "css/sso-login{$rtl}{$suffix}.css" ), [], Plugin::version() ); } /** * Return the SSO user ID. * * @return int|false */ private function user_id() { $user_id = ! empty( $_REQUEST['SSO_USER_ID'] ) ? $_REQUEST['SSO_USER_ID'] : filter_input( INPUT_GET, 'wpaas_sso_user_id', FILTER_VALIDATE_INT ); // Backwards compat - @codingStandardsIgnoreLine if ( $user_id ) { return absint( $user_id ); } $user = Plugin::get_first_admin_user(); return ( ! $user || ! isset( $user->ID ) ) ? false : $user->ID; } /** * Add our custom error message to the shaking messages * * @action shake_error_codes * @param $shake_error_codes * * @return array */ public function shake_error_codes( $shake_error_codes ) { $shake_error_codes[] = static::INVALID_SSO_QARG; return $shake_error_codes; } /** * Check if there were any SSO problems. * * @filter wp_login_errors * @param $errors * * @return mixed */ public function wp_login_errors( $errors ) { if ( ! isset( $_GET[ static::INVALID_SSO_QARG ] ) ) { // @codingStandardsIgnoreLine return $errors; } $errors->add( static::INVALID_SSO_QARG, __( 'We were unable to log you in automatically. Please enter your WordPress username and password.', 'gd-system-plugin' ), 'error' ); return $errors; } }
Save File
Cancel