diff --git a/src/js/_enqueues/admin/application-passwords.js b/src/js/_enqueues/admin/application-passwords.js index 21fbeb65820af..5e35aff299f8f 100644 --- a/src/js/_enqueues/admin/application-passwords.js +++ b/src/js/_enqueues/admin/application-passwords.js @@ -10,7 +10,10 @@ ( function( $ ) { var $appPassSection = $( '#application-passwords-section' ), $newAppPassForm = $appPassSection.find( '.create-application-password' ), - $newAppPassField = $newAppPassForm.find( '.input' ), + $newAppPassField = $newAppPassForm.find( '#new_application_password_name' ), + $newAppPassPresetField = $newAppPassForm.find( '#new_application_password_expiration_preset' ), + $newAppPassCustomWrap = $newAppPassForm.find( '#new_application_password_custom_expires_wrap' ), + $newAppPassExpiresField = $newAppPassForm.find( '#new_application_password_expires' ), $newAppPassButton = $newAppPassForm.find( '.button' ), $appPassTwrapper = $appPassSection.find( '.application-passwords-list-table-wrapper' ), $appPassTbody = $appPassSection.find( 'tbody' ), @@ -18,7 +21,82 @@ $removeAllBtn = $( '#revoke-all-application-passwords' ), tmplNewAppPass = wp.template( 'new-application-password' ), tmplAppPassRow = wp.template( 'application-password-row' ), - userId = $( '#user_id' ).val(); + userId = $( '#user_id' ).val(), + settings = window.wpApplicationPasswordsSettings || {}; + + $newAppPassPresetField.on( 'change', function() { + if ( 'custom' === $( this ).val() ) { + $newAppPassCustomWrap.removeClass( 'hidden' ); + $newAppPassExpiresField.trigger( 'focus' ); + } else { + $newAppPassCustomWrap.addClass( 'hidden' ); + $newAppPassExpiresField.val( '' ); + } + } ); + + /** + * Calculates the ISO string for expiration based on selected preset or custom date. + * + * Expiration is set to 23:59:59 of the target day in the site's local timezone. + * + * @since 7.2.0 + * @return {string|null} The ISO 8601 date string, or null if no expiration or invalid. + */ + function calculateExpiresIso() { + var preset = $newAppPassPresetField.val(), + days = 0, + baseDateIso = settings.todayEndIso, + baseDate; + + if ( 'no_expiry' === preset ) { + return null; + } + + if ( 'custom' === preset ) { + var customVal = $newAppPassExpiresField.val(); + if ( ! customVal ) { + return null; + } + + // Format custom date string into ISO for end of day in site timezone. + var siteTimezone = wp.date.getSettings().timezone; + var offsetString = '+00:00'; + if ( siteTimezone && siteTimezone.offsetFormatted ) { + offsetString = siteTimezone.offsetFormatted; + // Format to standard ISO offset like +06:00 or -05:00. + if ( ! /^[-+]\d{2}:\d{2}$/.test( offsetString ) ) { + var numOffset = parseFloat( siteTimezone.offset || 0 ); + var sign = numOffset >= 0 ? '+' : '-'; + var absH = Math.floor( Math.abs( numOffset ) ); + var absM = Math.round( ( Math.abs( numOffset ) - absH ) * 60 ); + offsetString = sign + ( '0' + absH ).slice( -2 ) + ':' + ( '0' + absM ).slice( -2 ); + } + } + + var customIsoDate = new Date( customVal + 'T23:59:59' + offsetString ); + if ( ! isNaN( customIsoDate.getTime() ) ) { + return customIsoDate.toISOString(); + } + + return null; + } + + if ( '7_days' === preset ) { + days = 7; + } else if ( '30_days' === preset ) { + days = 30; + } else if ( '90_days' === preset ) { + days = 90; + } + + if ( days > 0 ) { + baseDate = baseDateIso ? new Date( baseDateIso ) : new Date(); + baseDate.setUTCDate( baseDate.getUTCDate() + days ); + return baseDate.toISOString(); + } + + return null; + } $newAppPassButton.on( 'click', function( e ) { e.preventDefault(); @@ -41,6 +119,11 @@ name: name }; + var expiresIso = calculateExpiresIso(); + if ( expiresIso ) { + request.expires = expiresIso; + } + /** * Filters the request data used to create a new Application Password. * @@ -59,6 +142,9 @@ $newAppPassButton.removeProp( 'aria-disabled' ).removeClass( 'disabled' ); } ).done( function( response ) { $newAppPassField.val( '' ); + $newAppPassPresetField.val( '30_days' ); + $newAppPassCustomWrap.addClass( 'hidden' ); + $newAppPassExpiresField.val( '' ); $newAppPassButton.prop( 'disabled', false ); $newAppPassForm.after( tmplNewAppPass( { @@ -82,7 +168,7 @@ */ wp.hooks.doAction( 'wp_application_passwords_created_password', response, request ); } ).fail( handleErrorResponse ); - } ); + }); $appPassTbody.on( 'click', '.delete', function( e ) { e.preventDefault(); diff --git a/src/wp-admin/css/forms.css b/src/wp-admin/css/forms.css index 0475984e19105..92101bde6ccd0 100644 --- a/src/wp-admin/css/forms.css +++ b/src/wp-admin/css/forms.css @@ -1075,6 +1075,10 @@ table.form-table td .updated p { max-width: 20em; } +.column-expires { + vertical-align: top; +} + .auth-app-card.card { max-width: 768px; } diff --git a/src/wp-admin/includes/class-wp-application-passwords-list-table.php b/src/wp-admin/includes/class-wp-application-passwords-list-table.php index b3dccaf478a83..050d37713b49f 100644 --- a/src/wp-admin/includes/class-wp-application-passwords-list-table.php +++ b/src/wp-admin/includes/class-wp-application-passwords-list-table.php @@ -29,6 +29,7 @@ public function get_columns() { 'created' => __( 'Created' ), 'last_used' => __( 'Last Used' ), 'last_ip' => __( 'Last IP' ), + 'expires' => __( 'Expires' ), 'revoke' => __( 'Revoke' ), ); } @@ -101,6 +102,30 @@ public function column_last_ip( $item ) { } } + /** + * Handles the expires column output. + * + * @since 7.2.0 + * + * @param array $item The current application password item. + */ + public function column_expires( $item ) { + if ( empty( $item['expires'] ) ) { + echo '—'; + } else { + $date = date_i18n( __( 'F j, Y' ), $item['expires'] ); + if ( time() > $item['expires'] ) { + printf( + '%s', + /* translators: %s: Expiration date for the Application Password. */ + sprintf( esc_html__( 'Expired on %s' ), esc_html( $date ) ) + ); + } else { + echo esc_html( $date ); + } + } + } + /** * Handles the revoke column output. * @@ -235,6 +260,24 @@ public function print_js_template_row() { case 'last_ip': echo "{{ data.last_ip || '—' }}"; break; + case 'expires': + ?> + <# if ( data.expires ) { #> + <# var isExpired = new Date().getTime() > new Date( data.expires ).getTime(); #> + <# var formattedDate = wp.date.dateI18n( , data.expires ); #> + <# if ( isExpired ) { #> + + <# } else { #> + {{ formattedDate }} + <# } #> + <# } else { #> + — + <# } #> + %2$s', diff --git a/src/wp-admin/user-edit.php b/src/wp-admin/user-edit.php index 8055de6b36385..683103d75b951 100644 --- a/src/wp-admin/user-edit.php +++ b/src/wp-admin/user-edit.php @@ -34,6 +34,14 @@ if ( wp_is_application_passwords_available_for_user( $user_id ) ) { wp_enqueue_script( 'application-passwords' ); + wp_localize_script( + 'application-passwords', + 'wpApplicationPasswordsSettings', + array( + 'currentDate' => wp_date( 'Y-m-d' ), + 'todayEndIso' => wp_date( 'c', strtotime( 'today 23:59:59', current_datetime()->getTimestamp() ) ), + ) + ); } if ( IS_PROFILE_PAGE ) { @@ -848,6 +856,28 @@

+ +
+ + +
+ + + Array of preset keys and translatable labels. + */ + public static function get_expiry_presets() { + return array( + self::EXPIRY_7_DAYS => __( '7 days' ), + self::EXPIRY_30_DAYS => __( '30 days' ), + self::EXPIRY_90_DAYS => __( '90 days' ), + self::EXPIRY_NO_EXPIRY => __( 'No expiry' ), + self::EXPIRY_CUSTOM => __( 'Custom date' ), + ); + } + /** * Checks if application passwords are being used by the site. * @@ -61,6 +89,7 @@ public static function is_in_use() { * @since 5.6.0 * @since 5.7.0 Returns WP_Error if application name already exists. * @since 6.8.0 The hashed password value now uses wp_fast_hash() instead of phpass. + * @since 7.2.0 The application password expiration functionality added. * * @param int $user_id User ID. * @param array $args { @@ -98,6 +127,18 @@ public static function create_new_application_password( $user_id, $args = array( $new_password = wp_generate_password( static::PW_LENGTH, false ); $hashed_password = self::hash_password( $new_password ); + $expires = null; + if ( ! empty( $args['expires'] ) ) { + $expires = (int) $args['expires']; + if ( $expires <= time() ) { + return new WP_Error( + 'application_password_past_expiration', + __( 'Application password expiration date must be in the future.' ), + array( 'status' => 400 ) + ); + } + } + $new_item = array( 'uuid' => wp_generate_uuid4(), 'app_id' => empty( $args['app_id'] ) ? '' : $args['app_id'], @@ -106,6 +147,7 @@ public static function create_new_application_password( $user_id, $args = array( 'created' => time(), 'last_used' => null, 'last_ip' => null, + 'expires' => $expires, ); $passwords = static::get_user_application_passwords( $user_id ); @@ -282,6 +324,14 @@ public static function update_application_password( $user_id, $uuid, $update = a $save = false; + if ( array_key_exists( 'expires', $update ) ) { + $expires = null === $update['expires'] ? null : (int) $update['expires']; + if ( ! array_key_exists( 'expires', $item ) || $item['expires'] !== $expires ) { + $item['expires'] = $expires; + $save = true; + } + } + if ( ! empty( $update['name'] ) && $item['name'] !== $update['name'] ) { $item['name'] = $update['name']; $save = true; diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php index 767917d6f6fd0..bf08d4aa52a29 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php @@ -583,6 +583,11 @@ protected function prepare_item_for_database( $request ) { $prepared->app_id = $request['app_id']; } + $prepared->expires = null; + if ( isset( $request['expires'] ) && null !== $request['expires'] ) { + $prepared->expires = rest_parse_date( $request['expires'] ); + } + /** * Filters an application password before it is inserted via the REST API. * @@ -619,6 +624,7 @@ public function prepare_item_for_response( $item, $request ) { 'created' => gmdate( 'Y-m-d\TH:i:s', $item['created'] ), 'last_used' => $item['last_used'] ? gmdate( 'Y-m-d\TH:i:s', $item['last_used'] ) : null, 'last_ip' => $item['last_ip'] ? $item['last_ip'] : null, + 'expires' => ! empty( $item['expires'] ) ? gmdate( 'Y-m-d\TH:i:s', $item['expires'] ) : null, ); if ( isset( $item['new_password'] ) ) { @@ -849,6 +855,12 @@ public function get_item_schema() { 'context' => array( 'view', 'edit' ), 'readonly' => true, ), + 'expires' => array( + 'description' => __( 'The GMT date the application password expires.' ), + 'type' => array( 'string', 'null' ), + 'format' => 'date-time', + 'context' => array( 'view', 'edit' ), + ), ), ); diff --git a/src/wp-includes/user.php b/src/wp-includes/user.php index 92d091165525b..a8c199ca6850d 100644 --- a/src/wp-includes/user.php +++ b/src/wp-includes/user.php @@ -463,6 +463,13 @@ function wp_authenticate_application_password( $error = new WP_Error(); + if ( ! empty( $item['expires'] ) && time() > $item['expires'] ) { + $error->add( + 'application_password_expired', + __( 'The provided application password has expired.' ) + ); + } + /** * Fires when an application password has been successfully checked as valid. * diff --git a/tests/e2e/playwright.config.js b/tests/e2e/playwright.config.js index 0de694e324c24..38a3bfea402b8 100644 --- a/tests/e2e/playwright.config.js +++ b/tests/e2e/playwright.config.js @@ -3,6 +3,7 @@ */ import path from 'node:path'; import { defineConfig } from '@playwright/test'; +import 'dotenv/config'; /** * WordPress dependencies diff --git a/tests/e2e/specs/profile/applications-passwords.test.js b/tests/e2e/specs/profile/applications-passwords.test.js index aa7d2938d2c4f..770a376305b0f 100644 --- a/tests/e2e/specs/profile/applications-passwords.test.js +++ b/tests/e2e/specs/profile/applications-passwords.test.js @@ -40,6 +40,40 @@ test.describe( 'Manage applications passwords', () => { ); } ); + test( 'should correctly create a new application password with preset expiration', async ( { + page, + applicationPasswords, + } ) => { + await applicationPasswords.create( TEST_APPLICATION_NAME, '7_days' ); + + const [ app ] = await applicationPasswords.get(); + expect( app.name ).toBe( TEST_APPLICATION_NAME ); + expect( app.expires ).not.toBeNull(); + + const successMessage = page.getByRole( 'alert' ); + await expect( successMessage ).toHaveClass( /notice-success/ ); + } ); + + test( 'should correctly create a new application password with custom expiration date', async ( { + page, + applicationPasswords, + } ) => { + const expiresDate = new Date(); + expiresDate.setDate( expiresDate.getDate() + 7 ); + const expiresString = expiresDate.toISOString().split( 'T' )[ 0 ]; + + await applicationPasswords.create( `${ TEST_APPLICATION_NAME } Custom`, 'custom', expiresString ); + + const apps = await applicationPasswords.get(); + const app = apps.find( ( item ) => item.name === `${ TEST_APPLICATION_NAME } Custom` ); + expect( app ).toBeDefined(); + expect( app.expires ).not.toBeNull(); + expect( app.expires.startsWith( expiresString ) ).toBe( true ); + + const successMessage = page.getByRole( 'alert' ); + await expect( successMessage ).toHaveClass( /notice-success/ ); + } ); + test( 'should correctly revoke a single application password', async ( { page, applicationPasswords @@ -94,13 +128,25 @@ class ApplicationPasswords { this.admin = admin; } - async create(applicationName = TEST_APPLICATION_NAME) { + async create(applicationName = TEST_APPLICATION_NAME, preset = null, customDate = null) { await this.admin.visitAdminPage( '/profile.php' ); const newPasswordField = this.page.getByRole( 'textbox', { name: 'New Application Password Name' } ); await expect( newPasswordField ).toBeVisible(); await newPasswordField.fill( applicationName ); + if ( preset ) { + const presetSelect = this.page.getByLabel( 'Expiration', { exact: true } ); + await expect( presetSelect ).toBeVisible(); + await presetSelect.selectOption( preset ); + + if ( 'custom' === preset && customDate ) { + const customDateField = this.page.getByLabel( 'Custom expiration date' ); + await expect( customDateField ).toBeVisible(); + await customDateField.fill( customDate ); + } + } + await this.page.getByRole( 'button', { name: 'Add Application Password' } ).click(); await expect( this.page.getByRole( 'alert' ) ).toBeVisible(); } diff --git a/tests/phpunit/tests/auth.php b/tests/phpunit/tests/auth.php index a290d11e118e6..3480620e91b16 100644 --- a/tests/phpunit/tests/auth.php +++ b/tests/phpunit/tests/auth.php @@ -1767,6 +1767,55 @@ public function test_authenticate_application_password_chunked() { $this->assertSame( self::$user_id, $user->ID ); } + /** + * @ticket 53995 + */ + public function test_authenticate_application_password_expired() { + add_filter( 'application_password_is_api_request', '__return_true' ); + add_filter( 'wp_is_application_passwords_available', '__return_true' ); + + // Create with valid future expiry first. + list( $password, $item ) = WP_Application_Passwords::create_new_application_password( + self::$user_id, + array( + 'name' => 'phpunit', + 'expires' => time() + DAY_IN_SECONDS, + ) + ); + + // Simulate passage of time by updating the stored expiry to a past timestamp. + WP_Application_Passwords::update_application_password( + self::$user_id, + $item['uuid'], + array( 'expires' => time() - DAY_IN_SECONDS ) + ); + + $error = wp_authenticate_application_password( null, self::$_user->user_login, $password ); + $this->assertWPError( $error ); + $this->assertSame( 'application_password_expired', $error->get_error_code() ); + } + + /** + * @ticket 53995 + */ + public function test_authenticate_application_password_with_valid_future_expiry() { + add_filter( 'application_password_is_api_request', '__return_true' ); + add_filter( 'wp_is_application_passwords_available', '__return_true' ); + + list( $password ) = WP_Application_Passwords::create_new_application_password( + self::$user_id, + array( + 'name' => 'phpunit_future', + 'expires' => time() + 7 * DAY_IN_SECONDS, + ) + ); + + $user = wp_authenticate_application_password( null, self::$_user->user_login, $password ); + $this->assertNotWPError( $user ); + $this->assertInstanceOf( WP_User::class, $user ); + $this->assertSame( self::$user_id, $user->ID ); + } + /** * @ticket 51939 */ diff --git a/tests/phpunit/tests/rest-api/application-passwords.php b/tests/phpunit/tests/rest-api/application-passwords.php index 65e3bf222d85f..57b9d4a26626d 100644 --- a/tests/phpunit/tests/rest-api/application-passwords.php +++ b/tests/phpunit/tests/rest-api/application-passwords.php @@ -95,7 +95,7 @@ public function test_create_new_application_password( array $args, array $names $this->assertNotEmpty( $new_password ); $this->assertSame( - array( 'uuid', 'app_id', 'name', 'password', 'created', 'last_used', 'last_ip' ), + array( 'uuid', 'app_id', 'name', 'password', 'created', 'last_used', 'last_ip', 'expires' ), array_keys( $new_item ) ); $this->assertSame( $args['name'], $new_item['name'] ); @@ -106,10 +106,16 @@ public function data_create_new_application_password() { 'should create new password when no passwords exists' => array( 'args' => array( 'name' => 'test3' ), ), - 'should create new password when name is unique' => array( + 'should create new password when name is unique' => array( 'args' => array( 'name' => 'test3' ), 'names' => array( 'test1', 'test2' ), ), + 'should create new password with expiration' => array( + 'args' => array( + 'name' => 'test_expire', + 'expires' => time() + DAY_IN_SECONDS, + ), + ), ); } @@ -154,7 +160,7 @@ public function test_update_application_password( array $update, array $existing // Check updated only given values. $updated_item = WP_Application_Passwords::get_user_application_password( self::$user_id, $uuid ); foreach ( $updated_item as $key => $update_value ) { - $expected_value = $update[ $key ] ?? $original_item[ $key ]; + $expected_value = array_key_exists( $key, $update ) ? $update[ $key ] : $original_item[ $key ]; $this->assertSame( $expected_value, $update_value ); } } @@ -186,6 +192,17 @@ public function data_update_application_password() { 'update' => array( 'name' => 'Test Updated' ), 'existing' => array( 'name' => 'Test' ), ), + 'should update expires' => array( + 'update' => array( 'expires' => time() + DAY_IN_SECONDS ), + 'existing' => array( 'name' => 'Test' ), + ), + 'should clear expires' => array( + 'update' => array( 'expires' => null ), + 'existing' => array( + 'name' => 'Test', + 'expires' => time() + DAY_IN_SECONDS, + ), + ), ); } @@ -198,4 +215,34 @@ public function test_can_create_duplicate_app_password_names() { $created = WP_Application_Passwords::create_new_application_password( self::$user_id, array( 'name' => 'My App' ) ); $this->assertNotWPError( $created, 'Second attempt to create an application password should not return an error' ); } + + /** + * @ticket 53995 + */ + public function test_create_application_password_rejects_past_expiration() { + $result = WP_Application_Passwords::create_new_application_password( + self::$user_id, + array( + 'name' => 'Past Expire App', + 'expires' => time() - DAY_IN_SECONDS, + ) + ); + + $this->assertWPError( $result ); + $this->assertSame( 'application_password_past_expiration', $result->get_error_code() ); + } + + /** + * @ticket 53995 + */ + public function test_get_expiry_presets() { + $presets = WP_Application_Passwords::get_expiry_presets(); + + $this->assertIsArray( $presets ); + $this->assertArrayHasKey( WP_Application_Passwords::EXPIRY_7_DAYS, $presets ); + $this->assertArrayHasKey( WP_Application_Passwords::EXPIRY_30_DAYS, $presets ); + $this->assertArrayHasKey( WP_Application_Passwords::EXPIRY_90_DAYS, $presets ); + $this->assertArrayHasKey( WP_Application_Passwords::EXPIRY_NO_EXPIRY, $presets ); + $this->assertArrayHasKey( WP_Application_Passwords::EXPIRY_CUSTOM, $presets ); + } } diff --git a/tests/phpunit/tests/rest-api/rest-application-passwords-controller.php b/tests/phpunit/tests/rest-api/rest-application-passwords-controller.php index 060a5c0912a94..287d649e2ba19 100644 --- a/tests/phpunit/tests/rest-api/rest-application-passwords-controller.php +++ b/tests/phpunit/tests/rest-api/rest-application-passwords-controller.php @@ -906,6 +906,7 @@ protected function check_response( $response, $item, $password = false ) { $this->assertArrayHasKey( 'created', $response ); $this->assertArrayHasKey( 'last_used', $response ); $this->assertArrayHasKey( 'last_ip', $response ); + $this->assertArrayHasKey( 'expires', $response ); $this->assertSame( $item['uuid'], $response['uuid'] ); $this->assertSame( $item['app_id'], $response['app_id'] ); @@ -924,6 +925,12 @@ protected function check_response( $response, $item, $password = false ) { $this->assertNull( $response['last_ip'] ); } + if ( ! empty( $item['expires'] ) ) { + $this->assertSame( gmdate( 'Y-m-d\TH:i:s', $item['expires'] ), $response['expires'] ); + } else { + $this->assertNull( $response['expires'] ); + } + if ( $password ) { $this->assertArrayHasKey( 'password', $response ); } else { @@ -947,7 +954,8 @@ public function test_get_item_schema() { $this->assertArrayHasKey( 'created', $properties ); $this->assertArrayHasKey( 'last_used', $properties ); $this->assertArrayHasKey( 'last_ip', $properties ); - $this->assertCount( 7, $properties ); + $this->assertArrayHasKey( 'expires', $properties ); + $this->assertCount( 8, $properties ); } /** diff --git a/tests/qunit/fixtures/wp-api-generated.js b/tests/qunit/fixtures/wp-api-generated.js index 5d209f1c79820..b592620a36456 100644 --- a/tests/qunit/fixtures/wp-api-generated.js +++ b/tests/qunit/fixtures/wp-api-generated.js @@ -10328,6 +10328,15 @@ mockedApiResponse.Schema = { "minLength": 1, "pattern": ".*\\S.*", "required": true + }, + "expires": { + "description": "The GMT date the application password expires.", + "type": [ + "string", + "null" + ], + "format": "date-time", + "required": false } } }, @@ -10423,6 +10432,15 @@ mockedApiResponse.Schema = { "minLength": 1, "pattern": ".*\\S.*", "required": false + }, + "expires": { + "description": "The GMT date the application password expires.", + "type": [ + "string", + "null" + ], + "format": "date-time", + "required": false } } },