Skip to content

Commit

Permalink
Posts, Post Types: Add no-cache headers to password protected posts.
Browse files Browse the repository at this point in the history
This instructs an intermediate cache, for example a proxy server, to not cache a password protected post both before and after a visitor has entered a password.

Props brevilo, haozi, ironprogrammer, narenin

Fixes #61711

git-svn-id: https://develop.svn.wordpress.org/trunk@59728 602fd350-edb4-49c9-b593-d223f7449a82
  • Loading branch information
johnbillion committed Jan 29, 2025
1 parent 382211a commit 4863a92
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/wp-includes/class-wp.php
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,11 @@ public function send_headers() {
if ( $post && pings_open( $post ) ) {
$headers['X-Pingback'] = get_bloginfo( 'pingback_url', 'display' );
}

// Send nocache headers for password protected posts to avoid unwanted caching.
if ( ! empty( $post->post_password ) ) {
$headers = array_merge( $headers, wp_get_nocache_headers() );
}
}

/**
Expand Down
43 changes: 43 additions & 0 deletions tests/phpunit/tests/wp/sendHeaders.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* @covers WP::send_headers
*/
class Tests_WP_SendHeaders extends WP_UnitTestCase {
protected $headers_sent = array();

/**
* @ticket 56068
Expand Down Expand Up @@ -35,4 +36,46 @@ function ( $headers ) {
$post_id = self::factory()->post->create();
$this->go_to( get_permalink( $post_id ) );
}

/**
* @ticket 61711
*/
public function test_send_headers_sets_cache_control_header_for_password_protected_posts() {
$password = 'password';

add_filter(
'wp_headers',
function ( $headers ) {
$this->headers_sent = $headers;
return $headers;
}
);

$post_id = self::factory()->post->create(
array(
'post_password' => $password,
)
);
$this->go_to( get_permalink( $post_id ) );

$headers_without_password = $this->headers_sent;
$password_status_without_password = post_password_required( $post_id );

require_once ABSPATH . WPINC . '/class-phpass.php';

$hash = ( new PasswordHash( 8, true ) )->HashPassword( $password );

$_COOKIE[ 'wp-postpass_' . COOKIEHASH ] = $hash;

$this->go_to( get_permalink( $post_id ) );

$headers_with_password = $this->headers_sent;
$password_status_with_password = post_password_required( $post_id );

$this->assertTrue( $password_status_without_password );
$this->assertArrayHasKey( 'Cache-Control', $headers_without_password );

$this->assertFalse( $password_status_with_password );
$this->assertArrayHasKey( 'Cache-Control', $headers_with_password );
}
}

0 comments on commit 4863a92

Please sign in to comment.