Cross Container (ECS) WordPress Session Management

Since containers are ephemeral and each instance handles requests independently, sharing session data requires using a centralized session storage such as AWS ElastiCache.

ElastiCache can be configured for Valkey (open source Reddis) or Memcache. Valkey is lower cost.

Set up ElastiCache

  • Create a Valkey server.
  • Configure a publicly accessible or VPC-limited endpoint, depending on your ECS networking setup.
  • Choose 3 subnets on same network as ECS containers
  • Choose the ECS security group

Configure The Docker Image

Add the Redis extension to PHP and enable it in the php.ini configuration. This configuration uses environment variables so the Redis server can be configured with environment variables for each container instance.

Create The Host Image Builder PHP Ini File

Review the PHP Runtime Configuration page on session settings.

Create ./Docker/Images/Files/php/docker-php-ext-redis.ini

extension=redis.so
session.save_handler = ${PHP_SESSION_SAVE_HANDLER}
session.save_path = ${PHP_SESSION_SAVE_PATH}

Update The Host Dockerfile

Update the host Dockerfile to install Redis and the libs needed to support it. Copy the php ini file into conf.d so it is loaded when PHP starts. This example is from a WordPress 6 image running PHP 8 on Apache.

Create ./Docker/Images/Dockerfile

# -- base image

FROM public.ecr.aws/docker/library/wordpress:6.4.2-php8.3-apache
LABEL authors="lancecleveland" \
      image="WordPress Multisite on Apache"

# -- ports

EXPOSE 443

# -- os utilities

RUN set -eux; \
	apt-get update; \
	apt-get install -y --no-install-recommends \
		dnsutils \
        inetutils-traceroute \
        iputils-ping \
        libz-dev \
        libssl-dev \
        libmagickwand-dev \
	; \
	rm -rf \
        /var/lib/apt/lists/* \
	    /usr/src/wordpress/wp-content/themes/* \
	    /usr/src/wordpress/wp-content/plugins/* \
	    /usr/src/wordpress/wp-config-example.php \
    ;

# -- install Redis PHP extension
RUN pecl channel-update pecl.php.net \
    && pecl install redis \
    && docker-php-ext-enable redis

# -- PHP redis
COPY ./Files/php/docker-php-ext-redis.ini /usr/local/etc/php/conf.d/docker-php-ext-redis.ini

# -- apache rewrite

RUN a2enmod ssl && a2enmod rewrite; \
    mkdir -p /etc/apache2/ssl

# -- apache SSL

COPY ./Files/ssl/*.pem /etc/apache2/ssl/
COPY ./Files/apache/sites-available/*.conf /etc/apache2/sites-available/

# -- WordPress , gets copies to apache root /var/www/html
COPY ./Files/wordpress/ /usr/src/wordpress/

# -- php xdebug

RUN pecl channel-update pecl.php.net
RUN pecl install xdebug \
    && docker-php-ext-enable xdebug

# -- Standard WordPress Env Vars

ENV WORDPRESS_DB_USER="blah_blah_user"
ENV WORDPRESS_DB_NAME="blah_blah_database"
ENV WORDPRESS_TABLE_PREFIX="wp_"
ENV WORDPRESS_DB_CHARSET="utf8"
ENV WORDPRESS_DB_COLLATE=""

Configure The Docker Container

Update Docker Composer and ECS Task Definitions

Docker Composer is for local development container setup. ECS Task definitions are for AWS Cloud Elastic Container Services.

For our local Docker Composer configuration we use a docker-compose secrets file that is not committed to our repository for setting sensitive environment variables.

In this example the PHP_SESSION_* environment variables are read by the PHP startup and substituted in the session.* variables.

./Docker/Composers/Secrets/docker-compose-secrets.yml

This configuration uses local file based session storage. This is what you’d use on a typical single-server development file.

services:
wp:
environment:
PHP_SESSION_SAVE_HANDLER: 'files'
PHP_SESSION_SAVE_PATH: ''

For a PHP connection to a cluster, like we have on our AWS fault-tolerant container clusters you and fault-tolerant ElastiCache clusters you need to set something similar in the Task Definition environment variables using the same names as above.

      PHP_SESSION_SAVE_HANDLER: 'redis'
PHP_SESSION_SAVE_PATH: 'tcp://blah-saas-staging.blah.blah.blah.amazonaws.com:6379?persistent=1&failover=1&timeout=2&read_timeout=2&serialize=php&cluster=redis'

Load Balancer Sticky Sessions Option

Configure your Application Load Balancer (or Elastic Load Balancer) to enable sticky sessions to reduce the need to share session data across containers. Sticky sessions ensure that a user is always directed to the same container instance during their session.

– Application Load Balancer: Enable Session Stickiness.
– Set a **duration-based stickiness** cookie to control how long the user remains connected to the same task/container.

**Note**: Sticky sessions are not ideal for auto-scaling environments or when maintaining container independence is critical, so this should complement, not replace, shared session storage.

Additional Considerations

1. **Security**:
– Encrypt session data in transit using TLS (especially when connecting to Redis or RDS).
– Ensure that only trusted ECS tasks and resources can access session storage by restricting permissions through IAM roles and security groups.

2. **Performance Tuning**:
– Cache session data effectively using low TTLs for Redis or Memcached.
– Monitor ElastiCache or RDS instance performance to prevent bottlenecks caused by session sharing.

3. **Scaling and Resilience**:
– Use multi-AZ configurations for Redis or RDS.
– Consider Redis Cluster for read/write scaling and high availability.

By offloading session management to centralized storage and using ECS best practices, your WordPress instances can efficiently share session information while scaling seamlessly.

Tweaking The Configuration

The cluster is not working exactly as expected.

One container will connect and appears to work properly, but the user experience will swap form a logged in page to a not logged in page mid-session. The assumption is that this is due to the user connection jumping to a different server in the container cluster.

Attempted Resolution: Set PHP session.save_handler to rediscluster

On the staging server the initial php session_save handler (set via environment variable) was set to redis.

Changing this to rediscluster did not change the session switching behavior.

Attempted Resolution: Revise the PHP session_start() call

In WordPress the session_start() was moved from the prior invocation in the WordPress init() hook to the muplugins_loaded hook which loads earlier in the process. This did not seem to have an impact on the issue. Some minor updates to deal with configurations using a Redis Cluster and not were made as well as ensuring we check if a session was already started.

Our Redis Cluster code, invoked during muplugins_loaded with a MySLP_RedisCluster::get_instance() call.

<?php
defined( 'MYSLP_VERSION' ) || exit;


/**
 *
 */
class RedisClusterSessionHandler implements SessionHandlerInterface {
	private $redis;

	public function __construct() {
		$redisClusterEndpoint = get_cfg_var( 'session.save_path' );
		if ( empty( $redisClusterEndpoint ) ) {
			throw new RuntimeException( 'No Redis Cluster endpoint configured' );
		}


		// Parse and extract host/port (handle both single node and cluster)
		$parsedUrl = parse_url( $redisClusterEndpoint );
		$redisHost = $parsedUrl['host'] ?? 'localhost';
		$redisPort = $parsedUrl['port'] ?? 6379;

		// Use an array format required by RedisCluster
		$redisClusterNodes = [ "$redisHost:$redisPort" ];

		try {
			// Initialize RedisCluster
			$this->redis = new RedisCluster( null, $redisClusterNodes, 5, 5, true );
		} catch ( RedisClusterException $e ) {
			throw new RuntimeException( 'Failed to connect to Redis Cluster: ' . $e->getMessage() );
		}

	}

	/**
	 * Initialize session
	 * @link https://php.net/manual/en/sessionhandlerinterface.open.php
	 *
	 * @param $savePath
	 * @param $sessionName
	 *
	 * @return bool <p>
	 * The return value (usually TRUE on success, FALSE on failure).
	 * Note this value is returned internally to PHP for processing.
	 * </p>
	 * @since 5.4
	 */
	public function open( $savePath, $sessionName ): bool {
		return true; // No need to do anything here
	}

	/**
	 * Close the session
	 * @link https://php.net/manual/en/sessionhandlerinterface.close.php
	 * @return bool <p>
	 * The return value (usually TRUE on success, FALSE on failure).
	 * Note this value is returned internally to PHP for processing.
	 * </p>
	 * @since 5.4
	 */
	public function close(): bool {
		return true; // No need to close anything explicitly
	}

	/**
	 * Read session data
	 * @link https://php.net/manual/en/sessionhandlerinterface.read.php
	 *
	 * @param $sessionId
	 *
	 * @return string <p>
	 * Returns an encoded string of the read data.
	 * If nothing was read, it must return false.
	 * Note this value is returned internally to PHP for processing.
	 * </p>
	 * @since 5.4
	 */
	public function read( $sessionId ): string {
		$sessionData = $this->redis->get( "PHPREDIS_SESSION:$sessionId" );

		return $sessionData ?: ''; // Return session data or empty string if not found
	}

	/**
	 * Write session data
	 * @link https://php.net/manual/en/sessionhandlerinterface.write.php
	 *
	 * @param $sessionId
	 * @param string $data <p>
	 * The encoded session data. This data is the
	 * result of the PHP internally encoding
	 * the $_SESSION superglobal to a serialized
	 * string and passing it as this parameter.
	 * Please note sessions use an alternative serialization method.
	 * </p>
	 *
	 * @return bool <p>
	 * The return value (usually TRUE on success, FALSE on failure).
	 * Note this value is returned internally to PHP for processing.
	 * </p>
	 * @since 5.4
	 */
	public function write( $sessionId, $data ): bool {
		return $this->redis->setex( "PHPREDIS_SESSION:$sessionId", 3600, $data ); // 1-hour TTL
	}

	/**
	 * Destroy a session
	 * @link https://php.net/manual/en/sessionhandlerinterface.destroy.php
	 *
	 * @param $sessionId
	 *
	 * @return bool <p>
	 * The return value (usually TRUE on success, FALSE on failure).
	 * Note this value is returned internally to PHP for processing.
	 * </p>
	 * @since 5.4
	 */
	public function destroy( $sessionId ): bool {
		return $this->redis->del( [ "PHPREDIS_SESSION:$sessionId" ] ) > 0;
	}

	/**
	 * Cleanup old sessions
	 * @link https://php.net/manual/en/sessionhandlerinterface.gc.php
	 *
	 * @param $maxLifetime
	 *
	 * @return int|false <p>
	 * Returns the number of deleted sessions on success, or false on failure. Prior to PHP version 7.1, the function returned true on success.
	 * Note this value is returned internally to PHP for processing.
	 * </p>
	 * @since 5.4
	 */
	public function gc( $maxLifetime ): int|false {
		return true; // Redis handles expiration via TTL, so no need to do anything
	}
}

/**
 *
 */
class MySLP_RedisCluster extends MySLP_Base {
	private $redis;

	/**
	 * Catch cluster redirects (MOVED) using the built-in PHP RedisCluster lib
	 * @return void
	 * @throws RedisClusterException
	 */
	final function initialize() {
		$redisClusterEndpoint = get_cfg_var( 'session.save_path' );
		if ( class_exists( 'RedisCluster' ) && ! empty( $redisClusterEndpoint ) ) {
			try {
				$handler = new RedisClusterSessionHandler();
				session_set_save_handler( $handler, true );

			} catch ( RuntimeException $e ) {
				error_log( 'Error initializing RedisClusterSessionHandler: ' . $e->getMessage() );
			}
		}
		if ( ! session_id() && ! headers_sent() ) {
			session_start();
		}
	}
}

SaaS WP Login Processing

  • wp-login.php
    • $reauth = empty( $_REQUEST[‘reauth’] ) ? false : true; is set to false.
    • $user = wp_signon( array() , $secure_cookie “” )
      • do_action( ‘wp_login’ , $user->user_login “lcleveland” , $user “WP_User” is set)
    • if ( empty( $_COOKIE[ LOGGED_IN_COOKIE ] )) is NOT empty
      • LOGGED_IN_COOKIE is something like “wordpress_logged_in_e2ec4afff4940eebb6cd200cc8206825”
        which IS set on this session
    • $requested_redirect_to ==> ‘https://staging.storelocatorplus.com/wp-admin/”
      as set in $_REQUEST[‘redirect_to’]
    • if ( ! is_wp_error( $user ) && ! $reauth ) { // This is executing because user is set and reauth is not set.

Need to set the WP Secrets the same (keys and salts) on ALL nodes in the cluster that share login. The auth (login) cookies have salt and keys in them and with each server generating their own they will not be validated.

Docker has a method to pass these in via an ENV setting.

Image by Robert from Pixabay

WordPress / SaaS Menu Ordering

WordPress

add_menu_page()


add_menu_page( 
string $page_title, 
string $menu_title, 
string $capability, 
string $menu_slug, 
callable $callback = ”, 
string $icon_url = ”, 
int|float $position = null 
): string
WordPress Default Admin Menu Positions
StandardNetwork Admin
2 – Dashboard2 – Dashboard
4 – Separator4 – Separator
5 – Posts5 – Sites
10 – Media10 – Users
15 – Links15 – Themes
20 – Pages20 – Plugins
25 – Comments25 – Settings
30 – Updates
59 – Separator
60 – Appearance
65 – Plugins
70 – Users
75 – Tools
80 – Settings
99 – Separator99 – Separator

add_submenu_page()

SaaS Menu Positions

Standard / UserNetwork Admin
1.10 – MySLP
myslp-dashboard
1.10 – Manage
MYSLP_MANAGE_MENU_SLUG
‘myslp-manage-menu’

10 – Customers
30 – History Log
50 – Cron : System
51 – Cron : User
80 – Database
70 – Addressess
1.20 – Store Locator Plus®
csl-slplus
1.30 – Config
MYSLP_CONFIG_MENU_SLUG
‘myslp-config-menu’

10 – Plans
15 – Plan Limits
20 – Plugins
25 – Email Settings
30 – Payments
70 – System Settings
80- Cache
2 – Dashboard2 – Dashboard
4 – Separator4 – Separator
5 – Posts5 – Sites
10 – Media10 – Users
15 – Links15 – Themes
20 – Pages20 – Plugins
25 – Comments25 – Settings
30 – Updates
59 – Separator
60 – Appearance
65 – Plugins
70 – Users
75 – Tools
80 – Settings
99 – Separator99 – Separator

0 comments on “Debugging: Location Category Not Filtering”

Debugging: Location Category Not Filtering

The User Action : Filtering Locations With Category on the Testing : Location Categories article is not limiting output to only the specified category.

Tech Overview

The front end sends a request back to WordPress via AJAX to request a list of locations. Part of that request encodes all of the form field entries, including the category drop down selection, into a query-encoded (key/value pairs with an & delimiter) string that is send in the formData property to the backend.

The category ID is not being parsed and filtered properly.

Looking At The Data Request

Via browser developer tools and the network I/O inspector, XHR filter…

HTTP Method: POST
URL: /wp-admin/admin-ajax.php
Request Payload…

You can see the formdata property in the POST body along with the encoded form data including the cat=5 entry. This is where the requests tells the back end to limit results to those that have WordPress category ID #5 attached to the location.

Diving Into The Code

On the back end the AJAX is routed through the Store Locator Plus® base plugin via the standard WordPress hooks and filters. These are setup in the SLP_AJAX class via this add_ajax_hooks method:

    /**
     * Add our AJAX hooks.
     *
     * @uses \SLP_AJAX::slp_delete_location for the AJAX 'slp_delete_location' action
     */
    public function add_ajax_hooks() {

    	// -- priv (WP logged in) and no priv (guest) AJAX calls
        add_action( 'wp_ajax_csl_ajax_search', array( $this, 'csl_ajax_search' ) );
        add_action( 'wp_ajax_nopriv_csl_ajax_search', array( $this, 'csl_ajax_search' ) );

        add_action( 'wp_ajax_csl_ajax_onload', array( $this, 'csl_ajax_onload' ) );
        add_action( 'wp_ajax_nopriv_csl_ajax_onload', array( $this, 'csl_ajax_onload' ) );

	    // -- priv only AJAX calls (WP logged in)
	    add_action( 'wp_ajax_slp_delete_location', array( $this, 'slp_delete_location' ) );
        add_action( 'wp_ajax_slp_change_option', array( $this, 'slp_change_option' ) );
    }

Where the csl_ajax_search eventually finds its way to the find_locations method.

Debugging the find_locations method it looks like the formdata variable coming in via the superglobal $_REQUEST variable is not being set properly.

Digging Into The Malformed Variables

Looking at the call stack the form data is mishandled causing the & in the query string to be encoded as &amp, this causes wp_parse_args() to set the property name incorrect as you can see in the debugging screenshot below.

Turns out the wp_kses_post() is too aggressive with the data munging and converts & to &amp; which then throws wp_parse_args() for a loop.

Instead we need to use esc_url_raw() to leave most URL entities intact.

0 comments on “WordPress Escaping and Sanitizing”

WordPress Escaping and Sanitizing

Escaping or Sanitizing General Rules

Arrays

Instead of manually detecting arrays then using array_map(), as noted below, instead use map_deep( $arrayOrScalarVar, ‘<method>’.

For example:

$cleanVar = map_deep( $_REQUEST['id'], 'santize_key');

For wp_kses_post use wp_kses_post_deep(). See below for more info.

When processing an array of values use array_map( ‘<method>’ , $arrayVar).

For example array_map( ‘sanitize_key’ , (array) $_REQUEST[‘id’] ).

Unslash Warnings

There is no need to call wp_unslash() before sanitizing inputs.

Related Resources


Securing Input (sanitizing)

sanitize_email()

Strips out all characters that are not allowable in an email.

sanitize_file_name()

sanitize_hex_color()

sanitize_hex_color_no_hash()

sanitize_html_class()

sanitize_key()

Lowercase alphanumeric characters, dashes, and underscores are allowed.

sanitize_meta()

This function applies filters that can be hooked to perform specific sanitization procedures for the particular metadata type and key. Does not sanitize anything on its own. Custom filters must be hooked in to do the work. The filter hook tag has the form “sanitize_{$meta_type}_meta_{$meta_key}“.

sanitize_mime_type()

sanitize_option()

Only sanitizes specific options known to WordPress (primarily for internal use).
After the value has been handled by the functions in the switch statement, it will be passed through a sanitize_option_$option filter.

sanitize_sql_orderby()

💙 sanitize_text_field()

From the WordPress docs…

  • Checks for invalid UTF-8,
  • Converts single < characters to entities
  • Strips all tags
  • Removes line breaks, tabs, and extra whitespace
  • Strips octets

Strips All Tags…

That means this CANNOT be used for anything that processes HTML elements.

The Code

/**
 * Sanitizes a string from user input or from the database.
 *
 * - Checks for invalid UTF-8,
 * - Converts single `<` characters to entities
 * - Strips all tags
 * - Removes line breaks, tabs, and extra whitespace
 * - Strips octets
 *
 * @param string $str String to sanitize.
 * @return string Sanitized string.
 */
function sanitize_text_field( $str ) {
	$filtered = _sanitize_text_fields( $str, false );

	/**
	 * Filters a sanitized text field string.
	 *
	 * @since 2.9.0
	 *
	 * @param string $filtered The sanitized string.
	 * @param string $str      The string prior to being sanitized.
	 */
	return apply_filters( 'sanitize_text_field', $filtered, $str );
}

💙 sanitize_textarea_field()

Like sanitize_text_field, but keeps newlines.

sanitize_title()

sanitize_title_for_query()

sanitize_title_with_dashes()

sanitize_user()

sanitize_url()

use esc_url_raw() – see below

wp_kses()

💙 wp_kses_post()

Calls wp_kses() with the ‘post’ context that automatically allows all HTML that is permitted in post content.

ℹ️ Processing an array or object? Use wp_kses_post_deep().

SLP Modifications

In SLP it allows HTML tags like Vue, etc. that are on the allowed HTML tags filter.

Converts & to &amp;

The wp_kses methods call wp_normalize_entities which bastardizes nearly all (but not ALL) occurrences of & in a string to &amp;.

That means wp_kses functions are basically useless for sanitizing query parameter strings.

The Code

 function wp_kses_post( $data ) {
    return wp_kses( $data, 'post' );
}

💙 wp_kses_post_deep()

Navigates through an array, object, or scalar, and sanitizes content for allowed HTML tags for post content.


function wp_kses_post_deep( $data ) {
    return map_deep( $data, 'wp_kses_post' );
}

Securing Output (escaping)

esc_attr()
Use on everything else that’s printed into an HTML element’s attribute.

esc_html()
Use anytime an HTML element encloses a section of data being displayed. This WILL NOT display HTML content, it is meant for being used inside HTML and will remove your HTML.

esc_js()
Use for inline Javascript.

esc_textarea() – Use this to encode text for use inside a textarea element.

esc_url()

Use on all URLs, including those in the src and href attributes of an HTML element.

Does encode things like & to wonky-ass WordPress HTML coded entities.

esc_url_raw()

Use when storing a URL in the database or in other cases where non-encoded URLs are needed.

Does NOT encode things like & to wonky-ass WordPress HTML coded entities.

esc_xml() – Use to escape XML block.

wp_kses() – See Santize above for more details.

💙 wp_kses_post() – See Sanitize above for more details.

💙 wp_kses_post_deep() – See Sanitize above for more details.


Nonces

wp_kses_data() – Alternative version of wp_kses() that allows only the HTML permitted in post comments.

wp_nonce_field( <action> , [ name = ‘_wpnonce’ ], [ referer = true ] , [ echo = true ])

– Add nonce input to a form.

check_admin_referer( <action> , [ name = ‘_wpnonce’ ])

– Check a received nonce is valid AND from an admin page.