diff --git a/src/js/_enqueues/admin/application-passwords.js b/src/js/_enqueues/admin/application-passwords.js
index 21fbeb65820af..eb0303edec8e3 100644
--- a/src/js/_enqueues/admin/application-passwords.js
+++ b/src/js/_enqueues/admin/application-passwords.js
@@ -10,7 +10,8 @@
( function( $ ) {
var $appPassSection = $( '#application-passwords-section' ),
$newAppPassForm = $appPassSection.find( '.create-application-password' ),
- $newAppPassField = $newAppPassForm.find( '.input' ),
+ $newAppPassField = $newAppPassForm.find( '#new_application_password_name' ),
+ $newAppPassExpiresField = $newAppPassForm.find( '#new_application_password_expires' ),
$newAppPassButton = $newAppPassForm.find( '.button' ),
$appPassTwrapper = $appPassSection.find( '.application-passwords-list-table-wrapper' ),
$appPassTbody = $appPassSection.find( 'tbody' ),
@@ -20,6 +21,11 @@
tmplAppPassRow = wp.template( 'application-password-row' ),
userId = $( '#user_id' ).val();
+ updateApplicationPasswordExpirationMinimum( $newAppPassExpiresField );
+ $newAppPassExpiresField.on( 'focus', function() {
+ updateApplicationPasswordExpirationMinimum( $newAppPassExpiresField );
+ } );
+
$newAppPassButton.on( 'click', function( e ) {
e.preventDefault();
@@ -34,6 +40,11 @@
return;
}
+ updateApplicationPasswordExpirationMinimum( $newAppPassExpiresField );
+ if ( ! $newAppPassExpiresField[0].reportValidity() ) {
+ return;
+ }
+
clearNotices();
$newAppPassButton.prop( 'aria-disabled', true ).addClass( 'disabled' );
@@ -41,6 +52,15 @@
name: name
};
+ var expires = $newAppPassExpiresField.val();
+ if ( expires ) {
+ var expiresDate = wp.date.getDate( expires );
+
+ if ( ! isNaN( expiresDate.getTime() ) ) {
+ request.expires = expiresDate.toISOString();
+ }
+ }
+
/**
* Filters the request data used to create a new Application Password.
*
@@ -59,6 +79,7 @@
$newAppPassButton.removeProp( 'aria-disabled' ).removeClass( 'disabled' );
} ).done( function( response ) {
$newAppPassField.val( '' );
+ $newAppPassExpiresField.val( '' );
$newAppPassButton.prop( 'disabled', false );
$newAppPassForm.after( tmplNewAppPass( {
@@ -82,6 +103,127 @@
*/
wp.hooks.doAction( 'wp_application_passwords_created_password', response, request );
} ).fail( handleErrorResponse );
+ });
+
+ /**
+ * Handles the inline editing of an application password expiration date.
+ * * @since 7.1.0
+ */
+ $appPassTbody.on( 'click', '.edit-expires', function( e ) {
+ e.preventDefault();
+
+ var $button = $( this ),
+ $tr = $button.closest( 'tr' ),
+ uuid = $tr.data( 'uuid' ),
+ currentExpires = $tr.data( 'expires' ),
+ $td = $button.closest( 'td' );
+
+ if ( $td.find( '.edit-expires-form' ).length ) {
+ return;
+ }
+
+ var $form = $( '
' );
+ var timezoneDescriptionId = 'application-password-timezone-' + uuid;
+ var $input = $( '' )
+ .attr( 'aria-label', wp.i18n.__( 'Expiration date and time' ) )
+ .attr( 'aria-describedby', timezoneDescriptionId );
+
+ if ( currentExpires ) {
+ $input.val( wp.date.date( 'Y-m-d\\TH:i:s', currentExpires + 'Z' ) );
+ }
+ var initialExpires = $input.val();
+ $input.on( 'focus', function() {
+ updateApplicationPasswordExpirationMinimum( $input );
+ } );
+
+ var $buttonContainer = $( '' );
+ var $saveBtn = $( '' );
+ var $cancelBtn = $( '' );
+ var $removeBtn = $( '' ).text( wp.i18n.__( 'Remove expiry' ) );
+
+ $buttonContainer.append( $saveBtn ).append( $cancelBtn );
+ if ( currentExpires ) {
+ $buttonContainer.append( $removeBtn );
+ }
+ $form.append( $input )
+ .append( $( '' ).attr( 'id', timezoneDescriptionId ).text(
+ /* translators: %s: Site timezone. */
+ wp.i18n.sprintf( wp.i18n.__( 'Timezone: %s' ), $appPassSection.data( 'timezone' ) )
+ ) )
+ .append( $buttonContainer );
+
+ $td.append( $form );
+ $button.hide();
+ $input.trigger( 'focus' );
+
+ // Close form on Escape key.
+ $input.on( 'keydown', function( e ) {
+ if ( 27 === e.which ) {
+ $cancelBtn.trigger( 'click' );
+ }
+ if ( 13 === e.which ) {
+ e.preventDefault();
+ $saveBtn.trigger( 'click' );
+ }
+ });
+
+ $cancelBtn.on( 'click', function() {
+ if ( $cancelBtn.prop( 'disabled' ) ) {
+ return;
+ }
+
+ $form.remove();
+ $button.show().trigger( 'focus' );
+ } );
+
+ $removeBtn.on( 'click', function() {
+ $input.val( '' ).trigger( 'focus' );
+ $saveBtn.trigger( 'click' );
+ } );
+
+ $saveBtn.on( 'click', function() {
+ if ( $saveBtn.prop( 'disabled' ) ) {
+ return;
+ }
+
+ updateApplicationPasswordExpirationMinimum( $input );
+ var newExpires = $input.val();
+
+ // An existing expired value may be retained, but a newly selected time must be in the future.
+ if ( ! ( currentExpires && newExpires === initialExpires ) && ! $input[0].reportValidity() ) {
+ return;
+ }
+
+ var expiresDate = newExpires ? wp.date.getDate( newExpires ) : null;
+ var requestData = {
+ expires: ( expiresDate && ! isNaN( expiresDate.getTime() ) ) ? expiresDate.toISOString() : null
+ };
+
+ if ( currentExpires && newExpires === initialExpires ) {
+ requestData.expires = currentExpires + 'Z';
+ }
+
+ clearNotices();
+ $saveBtn.prop( 'disabled', true );
+ $cancelBtn.prop( 'disabled', true );
+ $removeBtn.prop( 'disabled', true );
+
+ wp.apiRequest( {
+ path: '/wp/v2/users/' + userId + '/application-passwords/' + uuid + '?_locale=user',
+ method: 'PUT',
+ data: JSON.stringify( requestData ),
+ contentType: 'application/json'
+ } ).always( function() {
+ $saveBtn.prop( 'disabled', false );
+ $cancelBtn.prop( 'disabled', false );
+ $removeBtn.prop( 'disabled', false );
+ } ).done( function( response ) {
+ var $newRow = $( tmplAppPassRow( response ) );
+ $tr.replaceWith( $newRow );
+ $newRow.find( '.edit-expires' ).trigger( 'focus' );
+ addNotice( wp.i18n.__( 'Application password expiration updated.' ), 'success' );
+ } ).fail( handleErrorResponse );
+ } );
} );
$appPassTbody.on( 'click', '.delete', function( e ) {
@@ -186,6 +328,17 @@
addNotice( errorMessage, 'error' );
}
+ /**
+ * Updates the earliest expiration allowed in an application password input.
+ *
+ * @since 7.2.0
+ *
+ * @param {jQuery} $input The expiration input.
+ */
+ function updateApplicationPasswordExpirationMinimum( $input ) {
+ $input.attr( 'min', wp.date.date( 'Y-m-d\\TH:i:s', new Date( Date.now() + 1000 ) ) );
+ }
+
/**
* Displays a message in the Application Passwords section.
*
diff --git a/src/wp-admin/css/forms.css b/src/wp-admin/css/forms.css
index 2ace16f733004..47a6a506d8fb4 100644
--- a/src/wp-admin/css/forms.css
+++ b/src/wp-admin/css/forms.css
@@ -1064,6 +1064,29 @@ table.form-table td .updated p {
max-width: 20em;
}
+.edit-expires-form {
+ margin-top: 8px;
+ width: 100%;
+}
+
+.edit-expires-input {
+ display: block;
+ width: 100%;
+ max-width: 20em;
+ margin-bottom: 5px;
+}
+
+.edit-expires-button-group {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ justify-content: flex-start;
+}
+
+.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 a5e143e30eccb..54f99923a92b6 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,35 @@ public function column_last_ip( $item ) {
}
}
+ /**
+ * Handles the expires column output.
+ *
+ * @since 7.1.0
+ *
+ * @param array $item The current application password item.
+ */
+ public function column_expires( $item ) {
+ if ( empty( $item['expires'] ) ) {
+ echo '—';
+ } else {
+ $date = wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $item['expires'] );
+ if ( time() > $item['expires'] ) {
+ printf(
+ '%s',
+ /* translators: %s: Expiration date and time for the Application Password. */
+ sprintf( esc_html__( 'Expired on %s' ), esc_html( $date ) )
+ );
+ } else {
+ echo esc_html( $date );
+ }
+ }
+ printf(
+ '
',
+ esc_attr__( 'Edit Expiration Date and Time' ),
+ esc_html__( 'Edit Expiry' )
+ );
+ }
+
/**
* Handles the revoke column output.
*
@@ -178,7 +208,8 @@ protected function display_tablenav( $which ) {
* @param array $item The current item.
*/
public function single_row( $item ) {
- echo '';
+ $expires = ! empty( $item['expires'] ) ? gmdate( 'Y-m-d\TH:i:s', $item['expires'] ) : '';
+ echo '
';
$this->single_row_columns( $item );
echo '
';
}
@@ -202,7 +233,7 @@ protected function get_default_primary_column_name() {
public function print_js_template_row() {
list( $columns, $hidden, , $primary ) = $this->get_column_info();
- echo '';
+ echo '
';
foreach ( $columns as $column_name => $display_name ) {
$is_primary = $primary === $column_name;
@@ -237,6 +268,26 @@ public function print_js_template_row() {
case 'last_ip':
echo "{{ data.last_ip || '—' }}";
break;
+ case 'expires':
+ ?>
+ <# if ( data.expires ) { #>
+ <# var expiresDate = new Date( data.expires + 'Z' ); #>
+ <# var isExpired = new Date().getTime() > expiresDate.getTime(); #>
+ <# var formattedDate = wp.date.dateI18n( , expiresDate ); #>
+ <# if ( isExpired ) { #>
+
+ <# } else { #>
+ {{ formattedDate }}
+ <# } #>
+ <# } else { #>
+ —
+ <# } #>
+
+ %2$s',
diff --git a/src/wp-admin/user-edit.php b/src/wp-admin/user-edit.php
index cdd442fe98395..b6ee5c6239e11 100644
--- a/src/wp-admin/user-edit.php
+++ b/src/wp-admin/user-edit.php
@@ -811,7 +811,7 @@
-
400 ) );
}
+ $created = time();
+ $expires = isset( $args['expires'] ) ? (int) $args['expires'] : null;
+
+ if ( null !== $expires && $expires <= $created ) {
+ return new WP_Error(
+ 'application_password_invalid_expiration',
+ __( 'The expiration date and time must be in the future.' ),
+ array( 'status' => 400 )
+ );
+ }
+
$new_password = wp_generate_password( static::PW_LENGTH, false );
$hashed_password = self::hash_password( $new_password );
@@ -103,9 +116,10 @@ public static function create_new_application_password( $user_id, $args = array(
'app_id' => empty( $args['app_id'] ) ? '' : $args['app_id'],
'name' => $args['name'],
'password' => $hashed_password,
- 'created' => time(),
+ 'created' => $created,
'last_used' => null,
'last_ip' => null,
+ 'expires' => $expires,
);
$passwords = static::get_user_application_passwords( $user_id );
@@ -282,6 +296,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 30c418ee264cc..ad65d70b692c7 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/specs/profile/applications-passwords.test.js b/tests/e2e/specs/profile/applications-passwords.test.js
index aa7d2938d2c4f..8c344db1c68ba 100644
--- a/tests/e2e/specs/profile/applications-passwords.test.js
+++ b/tests/e2e/specs/profile/applications-passwords.test.js
@@ -8,100 +8,741 @@ const TEST_APPLICATION_NAME = 'Test Application';
test.describe( 'Manage applications passwords', () => {
test.use( {
applicationPasswords: async ( { requestUtils, admin, page }, use ) => {
- await use( new ApplicationPasswords( { requestUtils, admin, page } ) );
+ await use(
+ new ApplicationPasswords( { requestUtils, admin, page } )
+ );
},
} );
- test.beforeEach(async ( { applicationPasswords } ) => {
+ test.beforeEach( async ( { applicationPasswords } ) => {
await applicationPasswords.delete();
} );
- test('should correctly create a new application password', async ( {
+ test( 'should correctly create a new application password', async ( {
page,
- applicationPasswords
+ applicationPasswords,
} ) => {
await applicationPasswords.create();
const [ app ] = await applicationPasswords.get();
- expect( app['name']).toBe( TEST_APPLICATION_NAME );
+ expect( app[ 'name' ] ).toBe( TEST_APPLICATION_NAME );
const successMessage = page.getByRole( 'alert' );
await expect( successMessage ).toHaveClass( /notice-success/ );
- await expect(
- successMessage
- ).toContainText(
- `Your new password for ${TEST_APPLICATION_NAME} is:`
+ await expect( successMessage ).toContainText(
+ `Your new password for ${ TEST_APPLICATION_NAME } is:`
);
- await expect(
- successMessage
- ).toContainText(
+ await expect( successMessage ).toContainText(
`Be sure to save this in a safe location. You will not be able to retrieve it.`
);
} );
+ test( 'should correctly create a new application password with expiration', 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,
+ expiresString + 'T09:30'
+ );
+ await expect(
+ page.locator(
+ '.create-application-password #application-passwords-timezone'
+ )
+ ).toBeVisible();
+
+ const [ app ] = await applicationPasswords.get();
+ expect( app[ 'name' ] ).toBe( TEST_APPLICATION_NAME );
+ 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 update an application password expiration date', async ( {
+ page,
+ applicationPasswords,
+ } ) => {
+ await applicationPasswords.create();
+
+ const [ app ] = await applicationPasswords.get();
+ expect( app[ 'expires' ] ).toBeNull();
+
+ const editButton = page.getByRole( 'button', {
+ name: 'Edit Expiration Date and Time',
+ } );
+ await expect( editButton ).toBeVisible();
+ await editButton.click();
+
+ const expiresInput = page.locator( '.edit-expires-input' );
+ await expect( expiresInput ).toBeVisible();
+
+ const expiresDate = new Date();
+ expiresDate.setDate( expiresDate.getDate() + 10 );
+ const expiresString = expiresDate.toISOString().split( 'T' )[ 0 ];
+ await expiresInput.fill( expiresString + 'T16:45' );
+
+ const saveButton = page.getByRole( 'button', { name: 'Save' } );
+ await saveButton.click();
+
+ await expect( page.getByRole( 'alert' ) ).toContainText(
+ 'Application password expiration updated.'
+ );
+
+ const [ updatedApp ] = await applicationPasswords.get();
+ expect( updatedApp[ 'expires' ] ).not.toBeNull();
+ expect( updatedApp[ 'expires' ].startsWith( expiresString ) ).toBe(
+ true
+ );
+ } );
+
+ test.describe( 'Expiration timezone handling', () => {
+ test.use( { timezoneId: 'Australia/Melbourne' } );
+
+ for ( const { timezone, created, updated } of [
+ {
+ timezone: 'UTC',
+ created: '2028-07-15T00:30:00',
+ updated: '2029-01-15T16:45:00',
+ },
+ {
+ timezone: 'Australia/Melbourne',
+ created: '2028-07-14T14:30:00',
+ updated: '2029-01-15T05:45:00',
+ },
+ {
+ timezone: 'America/New_York',
+ created: '2028-07-15T04:30:00',
+ updated: '2029-01-15T21:45:00',
+ },
+ {
+ timezone: 'UTC+5.5',
+ created: '2028-07-14T19:00:00',
+ updated: '2029-01-15T11:15:00',
+ },
+ ] ) {
+ test( `should preserve site-local expiry dates in ${ timezone }`, async ( {
+ page,
+ admin,
+ applicationPasswords,
+ } ) => {
+ await admin.visitAdminPage( '/options-general.php' );
+ const originalTimezone = await page
+ .locator( '#timezone_string' )
+ .inputValue();
+ try {
+ await page
+ .locator( '#timezone_string' )
+ .selectOption( timezone );
+ await page
+ .getByRole( 'button', {
+ name: 'Save Changes',
+ exact: true,
+ } )
+ .click();
+ await page.clock.setFixedTime(
+ new Date(
+ new Date( created + 'Z' ).getTime() - 15 * 60 * 1000
+ )
+ );
+ await applicationPasswords.create(
+ TEST_APPLICATION_NAME,
+ '2028-07-15T00:30'
+ );
+
+ const [ app ] = await applicationPasswords.get();
+ expect( app.expires ).toBe( created );
+ const expiresCell = page
+ .locator( '.column-expires' )
+ .filter( { has: page.locator( '.edit-expires' ) } );
+ await expect( expiresCell ).toContainText(
+ 'July 15, 2028 12:30 am'
+ );
+ await expect( expiresCell ).not.toContainText(
+ 'Expired on'
+ );
+
+ // Both AJAX-rendered and server-rendered rows must reopen with the site date.
+ await page.locator( '.edit-expires' ).click();
+ await expect(
+ page.locator( '.edit-expires-input' )
+ ).toHaveValue( '2028-07-15T00:30' );
+ await page
+ .getByRole( 'button', { name: 'Cancel', exact: true } )
+ .click();
+ await page.reload();
+ await expect( expiresCell ).toContainText(
+ 'July 15, 2028 12:30 am'
+ );
+ await page.locator( '.edit-expires' ).click();
+ await expect(
+ page.locator( '.edit-expires-input' )
+ ).toHaveValue( '2028-07-15T00:30' );
+ await page
+ .locator( '.edit-expires-input' )
+ .fill( '2029-01-15T16:45' );
+ await page
+ .getByRole( 'button', { name: 'Save', exact: true } )
+ .click();
+ await expect( page.getByRole( 'alert' ) ).toContainText(
+ 'Application password expiration updated.'
+ );
+
+ const [ updatedApp ] = await applicationPasswords.get();
+ expect( updatedApp.expires ).toBe( updated );
+ await expect( expiresCell ).toContainText(
+ 'January 15, 2029 4:45 pm'
+ );
+ await page.locator( '.edit-expires' ).click();
+ await expect(
+ page.locator( '.edit-expires-input' )
+ ).toHaveValue( '2029-01-15T16:45' );
+ await page.reload();
+ await expect( expiresCell ).toContainText(
+ 'January 15, 2029 4:45 pm'
+ );
+ } finally {
+ await admin.visitAdminPage( '/options-general.php' );
+ await page
+ .locator( '#timezone_string' )
+ .selectOption( originalTimezone );
+ await page
+ .getByRole( 'button', {
+ name: 'Save Changes',
+ exact: true,
+ } )
+ .click();
+ }
+ } );
+ }
+
+ test( 'should preserve an unchanged expiry during the repeated DST hour', async ( {
+ page,
+ admin,
+ requestUtils,
+ applicationPasswords,
+ } ) => {
+ await admin.visitAdminPage( '/options-general.php' );
+ const originalTimezone = await page
+ .locator( '#timezone_string' )
+ .inputValue();
+ try {
+ await page
+ .locator( '#timezone_string' )
+ .selectOption( 'America/New_York' );
+ await page
+ .getByRole( 'button', {
+ name: 'Save Changes',
+ exact: true,
+ } )
+ .click();
+ await applicationPasswords.create(
+ TEST_APPLICATION_NAME,
+ '2028-07-15T00:30:37'
+ );
+ const [ app ] = await applicationPasswords.get();
+ expect( app.expires ).toBe( '2028-07-15T04:30:37' );
+ await requestUtils.rest( {
+ method: 'PUT',
+ path: `/wp/v2/users/me/application-passwords/${ app.uuid }`,
+ data: { expires: '2028-11-05T06:30:37Z' },
+ } );
+ await page.reload();
+ // The later 01:30 during the fallback must not become the earlier 01:30.
+ for ( let i = 0; i < 2; i++ ) {
+ await page.locator( '.edit-expires' ).click();
+ await expect(
+ page.locator( '.edit-expires-input' )
+ ).toHaveValue( '2028-11-05T01:30:37' );
+ await page
+ .getByRole( 'button', { name: 'Save', exact: true } )
+ .click();
+ await expect( page.getByRole( 'alert' ) ).toContainText(
+ 'Application password expiration updated.'
+ );
+ const [ saved ] = await applicationPasswords.get();
+ expect( saved.expires ).toBe( '2028-11-05T06:30:37' );
+ }
+ } finally {
+ await admin.visitAdminPage( '/options-general.php' );
+ await page
+ .locator( '#timezone_string' )
+ .selectOption( originalTimezone );
+ await page
+ .getByRole( 'button', {
+ name: 'Save Changes',
+ exact: true,
+ } )
+ .click();
+ }
+ } );
+ } );
+
test( 'should correctly revoke a single application password', async ( {
page,
- applicationPasswords
+ applicationPasswords,
} ) => {
await applicationPasswords.create();
- const revokeButton = page.getByRole( 'button', { name: `Revoke "${ TEST_APPLICATION_NAME }"` } );
+ const revokeButton = page.getByRole( 'button', {
+ name: `Revoke "${ TEST_APPLICATION_NAME }"`,
+ } );
await expect( revokeButton ).toBeVisible();
// Revoke password.
page.once( 'dialog', ( dialog ) => dialog.accept() );
await revokeButton.click();
- await expect(
- page.getByRole( 'alert' )
- ).toContainText(
+ await expect( page.getByRole( 'alert' ) ).toContainText(
'Application password revoked.'
);
const response = await applicationPasswords.get();
- expect( response ).toEqual([]);
+ expect( response ).toEqual( [] );
} );
test( 'should correctly revoke all the application passwords', async ( {
page,
- applicationPasswords
+ applicationPasswords,
} ) => {
await applicationPasswords.create();
- const revokeAllButton = page.getByRole( 'button', { name: 'Revoke all application passwords' } );
+ const revokeAllButton = page.getByRole( 'button', {
+ name: 'Revoke all application passwords',
+ } );
await expect( revokeAllButton ).toBeVisible();
// Confirms revoking action.
page.once( 'dialog', ( dialog ) => dialog.accept() );
await revokeAllButton.click();
- await expect(
- page.getByRole( 'alert' )
- ).toContainText(
+ await expect( page.getByRole( 'alert' ) ).toContainText(
'All application passwords revoked.'
);
const response = await applicationPasswords.get();
- expect( response ).toEqual([]);
+ expect( response ).toEqual( [] );
+ } );
+} );
+
+test.describe( 'Application password creation expiry validation', () => {
+ test.use( { timezoneId: 'Australia/Melbourne' } );
+
+ test( 'should restrict new expiry times in the site timezone and refresh the minimum', async ( {
+ page,
+ admin,
+ } ) => {
+ await page.clock.setFixedTime( new Date( '2028-07-15T10:00:00Z' ) );
+ await admin.visitAdminPage( '/profile.php' );
+ await page.evaluate( () => {
+ const settings = window.wp.date.getSettings();
+ window.wp.date.setSettings( {
+ ...settings,
+ timezone: { ...settings.timezone, string: '', offset: 5.5 },
+ } );
+ } );
+
+ const input = page.getByLabel( 'Expires on' );
+ await input.focus();
+ await expect( input ).toHaveAttribute( 'min', '2028-07-15T15:30:01' );
+ await input.fill( '2028-07-15T15:29:59' );
+ expect(
+ await input.evaluate(
+ ( element ) => element.validity.rangeUnderflow
+ )
+ ).toBe( true );
+ await input.fill( '2028-07-15T15:30:01' );
+ expect(
+ await input.evaluate( ( element ) => element.checkValidity() )
+ ).toBe( true );
+
+ await page.clock.setFixedTime( new Date( '2028-07-15T10:00:30Z' ) );
+ await input.blur();
+ await input.focus();
+ await expect( input ).toHaveAttribute( 'min', '2028-07-15T15:30:31' );
+
+ // A time that was valid when the picker opened may have passed before submission.
+ await page.clock.setFixedTime( new Date( '2028-07-15T10:01:00Z' ) );
+ await page
+ .getByLabel( 'New Application Password Name' )
+ .fill( 'Not created' );
+ let submitted = false;
+ await page.route( '**/application-passwords?*', async ( route ) => {
+ submitted = true;
+ await route.abort();
+ } );
+ await page
+ .getByRole( 'button', {
+ name: 'Add Application Password',
+ exact: true,
+ } )
+ .click();
+ await expect( input ).toHaveAttribute( 'min', '2028-07-15T15:31:01' );
+ expect(
+ await input.evaluate(
+ ( element ) => element.validity.rangeUnderflow
+ )
+ ).toBe( true );
+ expect( submitted ).toBe( false );
+ await expect(
+ page.getByRole( 'button', {
+ name: 'Add Application Password',
+ exact: true,
+ } )
+ ).not.toHaveClass( /disabled/ );
+ await input.fill( '' );
+ expect(
+ await input.evaluate( ( element ) => element.checkValidity() )
+ ).toBe( true );
+ } );
+} );
+
+test.describe( 'Application password table expiry validation', () => {
+ test.use( { timezoneId: 'Australia/Melbourne' } );
+
+ test( 'should block past selections in the inline editor while allowing expiry removal', async ( {
+ page,
+ admin,
+ } ) => {
+ await page.clock.setFixedTime( new Date( '2028-07-15T10:00:00Z' ) );
+ await admin.visitAdminPage( '/profile.php' );
+ const uuid = '11111111-1111-4111-8111-111111111111';
+ await page.evaluate( ( fixtureUuid ) => {
+ const settings = window.wp.date.getSettings();
+ window.wp.date.setSettings( {
+ ...settings,
+ timezone: { ...settings.timezone, string: '', offset: 5.5 },
+ } );
+ window.jQuery( '#application-passwords-section tbody' ).append(
+ window.wp.template( 'application-password-row' )( {
+ uuid: fixtureUuid,
+ app_id: '',
+ name: 'Browser-only expiry fixture',
+ created: '2028-07-15T09:00:00',
+ last_used: null,
+ last_ip: null,
+ expires: '2028-07-16T10:00:00',
+ } )
+ );
+ window.jQuery( '.application-passwords-list-table-wrapper' ).show();
+ }, uuid );
+
+ const submitted = [];
+ await page.route(
+ `**/application-passwords/${ uuid }?*`,
+ async ( route ) => {
+ submitted.push( route.request().postDataJSON() );
+ await route.fulfill( {
+ status: 400,
+ contentType: 'application/json',
+ body: JSON.stringify( {
+ message: 'Save intercepted for testing.',
+ } ),
+ } );
+ }
+ );
+ const row = page.locator( `tr[data-uuid="${ uuid }"]` );
+ await row.locator( '.edit-expires' ).click();
+ const input = row.getByLabel( 'Expiration date and time', {
+ exact: true,
+ } );
+ const save = row.getByRole( 'button', { name: 'Save', exact: true } );
+
+ await expect( input ).toHaveAttribute( 'min', '2028-07-15T15:30:01' );
+ await input.fill( '2028-07-14T15:30' );
+ expect(
+ await input.evaluate(
+ ( element ) => element.validity.rangeUnderflow
+ )
+ ).toBe( true );
+ await save.click();
+ expect( submitted ).toHaveLength( 0 );
+ await expect( save ).toBeEnabled();
+
+ await input.fill( '2028-07-15T15:30:01' );
+ await page.clock.setFixedTime( new Date( '2028-07-15T10:01:00Z' ) );
+ await save.click();
+ await expect( input ).toHaveAttribute( 'min', '2028-07-15T15:31:01' );
+ expect( submitted ).toHaveLength( 0 );
+ await page.clock.setFixedTime( new Date( '2028-07-15T10:01:30Z' ) );
+ await input.blur();
+ await input.focus();
+ await expect( input ).toHaveAttribute( 'min', '2028-07-15T15:31:31' );
+
+ await input.fill( '2028-07-15T15:32' );
+ await save.click();
+ await expect( page.getByRole( 'alert' ) ).toContainText(
+ 'Save intercepted for testing.'
+ );
+ expect( submitted ).toEqual( [
+ { expires: '2028-07-15T10:02:00.000Z' },
+ ] );
+ await input.fill( '' );
+ await save.click();
+ await expect.poll( () => submitted.length ).toBe( 2 );
+ expect( submitted[ 1 ] ).toEqual( { expires: null } );
+
+ // Opening an already expired password must not silently change its stored expiry.
+ await row
+ .getByRole( 'button', { name: 'Cancel', exact: true } )
+ .click();
+ await row.evaluate( ( element ) => {
+ window.jQuery( element ).data( 'expires', '2028-07-14T10:00:00' );
+ } );
+ await row.locator( '.edit-expires' ).click();
+ await expect( input ).toHaveValue( '2028-07-14T15:30' );
+ await save.click();
+ await expect.poll( () => submitted.length ).toBe( 3 );
+ expect( submitted[ 2 ] ).toEqual( { expires: '2028-07-14T10:00:00Z' } );
+ } );
+} );
+
+test.describe( 'Application password expiry removal', () => {
+ test( 'should remove and restore expiry and add expiry to a password without one', async ( {
+ page,
+ admin,
+ requestUtils,
+ } ) => {
+ const currentUser = await requestUtils.rest( {
+ path: '/wp/v2/users/me',
+ } );
+ const username = 'expiry-removal-' + Date.now();
+ const user = await requestUtils.createUser( {
+ username,
+ email: username + '@example.org',
+ password: 'test-password',
+ roles: [ 'subscriber' ],
+ } );
+ try {
+ const app = await requestUtils.rest( {
+ method: 'POST',
+ path: `/wp/v2/users/${ user.id }/application-passwords`,
+ data: {
+ name: TEST_APPLICATION_NAME,
+ expires: new Date(
+ Date.now() + 24 * 60 * 60 * 1000
+ ).toISOString(),
+ },
+ } );
+ const path = `/wp/v2/users/${ user.id }/application-passwords/${ app.uuid }`;
+ await admin.visitAdminPage(
+ '/user-edit.php',
+ `user_id=${ user.id }`
+ );
+ const row = page.locator( `tr[data-uuid="${ app.uuid }"]` );
+ const input = row.getByLabel( 'Expiration date and time', {
+ exact: true,
+ } );
+ const remove = row.getByRole( 'button', {
+ name: 'Remove expiry',
+ exact: true,
+ } );
+
+ await row.locator( '.edit-expires' ).click();
+ await expect( remove ).toBeVisible();
+ await expect
+ .poll( async () =>
+ remove.evaluate( ( element ) => {
+ const [ red, green, blue ] = getComputedStyle( element )
+ .color.match( /\d+/g )
+ .map( Number );
+ return red > green * 2 && red > blue * 2;
+ } )
+ )
+ .toBe( true );
+ const originalExpires = await input.inputValue();
+
+ // Cancel still discards manual edits; Remove expiry is an immediate action.
+ await input.fill( '' );
+ await row
+ .getByRole( 'button', { name: 'Cancel', exact: true } )
+ .click();
+ const unchanged = await requestUtils.rest( { path } );
+ expect( unchanged.expires ).toBe( app.expires );
+
+ await row.locator( '.edit-expires' ).click();
+ await expect( input ).not.toHaveValue( '' );
+
+ // Hold a failed removal response to check pending controls and retry behavior.
+ let releaseResponse;
+ const responseGate = new Promise( ( resolve ) => {
+ releaseResponse = resolve;
+ } );
+ const routePattern = `**/application-passwords/${ app.uuid }?*`;
+ let removalRequests = 0;
+ await page.route( routePattern, async ( route ) => {
+ removalRequests++;
+ expect( route.request().postDataJSON() ).toEqual( {
+ expires: null,
+ } );
+ await responseGate;
+ await route.fulfill( {
+ status: 500,
+ contentType: 'application/json',
+ body: JSON.stringify( {
+ message: 'Removal failed for testing.',
+ } ),
+ } );
+ } );
+
+ try {
+ await remove.click();
+ await expect( remove ).toBeDisabled();
+ await expect(
+ row.getByRole( 'button', { name: 'Save', exact: true } )
+ ).toBeDisabled();
+ await expect(
+ row.getByRole( 'button', { name: 'Cancel', exact: true } )
+ ).toBeDisabled();
+ await expect.poll( () => removalRequests ).toBe( 1 );
+ await input.press( 'Enter' );
+ await input.press( 'Escape' );
+ await expect( input ).toBeVisible();
+ } finally {
+ releaseResponse();
+ }
+
+ await expect( page.getByRole( 'alert' ) ).toContainText(
+ 'Removal failed for testing.'
+ );
+ expect( removalRequests ).toBe( 1 );
+ await expect( input ).toBeVisible();
+ await expect( remove ).toBeEnabled();
+ await expect(
+ row.getByRole( 'button', { name: 'Save', exact: true } )
+ ).toBeEnabled();
+ await expect(
+ row.getByRole( 'button', { name: 'Cancel', exact: true } )
+ ).toBeEnabled();
+
+ const failedRemoval = await requestUtils.rest( { path } );
+ expect( failedRemoval.expires ).toBe( app.expires );
+ await page.unroute( routePattern );
+ await remove.click();
+ await expect( page.getByRole( 'alert' ) ).toContainText(
+ 'Application password expiration updated.'
+ );
+
+ const cleared = await requestUtils.rest( { path } );
+ expect( cleared.expires ).toBeNull();
+ await expect( row.locator( '.edit-expires' ) ).toBeFocused();
+ await expect( row.locator( '.column-expires' ) ).toContainText(
+ '—'
+ );
+ await row.locator( '.edit-expires' ).click();
+ await expect( input ).toHaveValue( '' );
+ await expect( remove ).toHaveCount( 0 );
+ await row
+ .getByRole( 'button', { name: 'Cancel', exact: true } )
+ .click();
+ await page.reload();
+ await expect( row.locator( '.column-expires' ) ).toContainText(
+ '—'
+ );
+ await row.locator( '.edit-expires' ).click();
+ await expect( input ).toHaveValue( '' );
+ await expect( remove ).toHaveCount( 0 );
+
+ // Add the original expiry back after removing it, then verify it survives reload.
+ await input.fill( originalExpires );
+ await row
+ .getByRole( 'button', { name: 'Save', exact: true } )
+ .click();
+ await expect( page.getByRole( 'alert' ) ).toContainText(
+ 'Application password expiration updated.'
+ );
+ const restored = await requestUtils.rest( { path } );
+ expect( restored.expires ).toBe( app.expires );
+ await page.reload();
+ await row.locator( '.edit-expires' ).click();
+ await expect( input ).toHaveValue( originalExpires );
+ await expect( remove ).toBeVisible();
+
+ // A password created without any expiry must support adding and then removing one.
+ const noExpiry = await requestUtils.rest( {
+ method: 'POST',
+ path: `/wp/v2/users/${ user.id }/application-passwords`,
+ data: { name: 'Initially without expiry' },
+ } );
+ expect( noExpiry.expires ).toBeNull();
+ await page.reload();
+ const noExpiryRow = page.locator(
+ `tr[data-uuid="${ noExpiry.uuid }"]`
+ );
+ const noExpiryInput = noExpiryRow.getByLabel(
+ 'Expiration date and time',
+ { exact: true }
+ );
+ const noExpiryRemove = noExpiryRow.getByRole( 'button', {
+ name: 'Remove expiry',
+ exact: true,
+ } );
+ await noExpiryRow.locator( '.edit-expires' ).click();
+ await expect( noExpiryInput ).toHaveValue( '' );
+ await expect( noExpiryRemove ).toHaveCount( 0 );
+ await noExpiryInput.fill( originalExpires );
+ await noExpiryRow
+ .getByRole( 'button', { name: 'Save', exact: true } )
+ .click();
+ await expect( page.getByRole( 'alert' ) ).toContainText(
+ 'Application password expiration updated.'
+ );
+ const noExpiryPath = `/wp/v2/users/${ user.id }/application-passwords/${ noExpiry.uuid }`;
+ const added = await requestUtils.rest( { path: noExpiryPath } );
+ expect( added.expires ).toBe( app.expires );
+ await page.reload();
+ await noExpiryRow.locator( '.edit-expires' ).click();
+ await expect( noExpiryInput ).toHaveValue( originalExpires );
+ await noExpiryRemove.click();
+ await expect( page.getByRole( 'alert' ) ).toContainText(
+ 'Application password expiration updated.'
+ );
+ const removedAgain = await requestUtils.rest( {
+ path: noExpiryPath,
+ } );
+ expect( removedAgain.expires ).toBeNull();
+ } finally {
+ await requestUtils.rest( {
+ method: 'DELETE',
+ path: `/wp/v2/users/${ user.id }`,
+ params: { force: true, reassign: currentUser.id },
+ } );
+ }
} );
} );
class ApplicationPasswords {
- constructor( { requestUtils, page, admin }) {
+ constructor( { requestUtils, page, admin } ) {
this.requestUtils = requestUtils;
this.page = page;
this.admin = admin;
}
- async create(applicationName = TEST_APPLICATION_NAME) {
+ async create( applicationName = TEST_APPLICATION_NAME, expires = null ) {
await this.admin.visitAdminPage( '/profile.php' );
- const newPasswordField = this.page.getByRole( 'textbox', { name: 'New Application Password Name' } );
+ const newPasswordField = this.page.getByRole( 'textbox', {
+ name: 'New Application Password Name',
+ } );
await expect( newPasswordField ).toBeVisible();
await newPasswordField.fill( applicationName );
- await this.page.getByRole( 'button', { name: 'Add Application Password' } ).click();
+ if ( expires ) {
+ const newPasswordExpiresField =
+ this.page.getByLabel( 'Expires on' );
+ await expect( newPasswordExpiresField ).toBeVisible();
+ await newPasswordExpiresField.fill( expires );
+ }
+
+ 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..f41bf8edd1306 100644
--- a/tests/phpunit/tests/auth.php
+++ b/tests/phpunit/tests/auth.php
@@ -1767,6 +1767,28 @@ 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' );
+
+ list( $password, $item ) = WP_Application_Passwords::create_new_application_password(
+ self::$user_id,
+ array( 'name' => 'phpunit' )
+ );
+ 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 51939
*/
diff --git a/tests/phpunit/tests/rest-api/application-passwords.php b/tests/phpunit/tests/rest-api/application-passwords.php
index 65e3bf222d85f..781fc22c408fb 100644
--- a/tests/phpunit/tests/rest-api/application-passwords.php
+++ b/tests/phpunit/tests/rest-api/application-passwords.php
@@ -95,10 +95,11 @@ 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'] );
+ $this->assertSame( $args['expires'] ?? null, $new_item['expires'] );
}
public function data_create_new_application_password() {
@@ -106,10 +107,61 @@ 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,
+ ),
+ ),
+ 'should create new password with null expiration' => array(
+ 'args' => array(
+ 'name' => 'test_null_expire',
+ 'expires' => null,
+ ),
+ ),
+ );
+ }
+
+ /**
+ * @ticket 53995
+ * @dataProvider data_create_new_application_password_with_non_future_expiration
+ *
+ * @param int $offset Expiration offset from the current time, in seconds.
+ */
+ public function test_create_new_application_password_with_non_future_expiration( $offset ) {
+ WP_Application_Passwords::create_new_application_password( self::$user_id, array( 'name' => 'Existing' ) );
+ $passwords = WP_Application_Passwords::get_user_application_passwords( self::$user_id );
+ $created_count = did_action( 'wp_create_application_password' );
+
+ $result = WP_Application_Passwords::create_new_application_password(
+ self::$user_id,
+ array(
+ 'name' => 'Expired',
+ 'expires' => time() + $offset,
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'application_password_invalid_expiration', $result->get_error_code() );
+ $this->assertSame( array( 'status' => 400 ), $result->get_error_data() );
+ $this->assertSame( $passwords, WP_Application_Passwords::get_user_application_passwords( self::$user_id ) );
+ $this->assertSame( $created_count, did_action( 'wp_create_application_password' ) );
+ }
+
+ /**
+ * Data provider for rejecting an expiration that is not in the future.
+ *
+ * @return array[]
+ */
+ public function data_create_new_application_password_with_non_future_expiration() {
+ return array(
+ 'past day' => array( -DAY_IN_SECONDS ),
+ 'past second' => array( -1 ),
+ 'current second' => array( 0 ),
);
}
@@ -154,7 +206,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 +238,21 @@ 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 update expires to the past' => 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,
+ ),
+ ),
);
}
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..75d254632b245 100644
--- a/tests/phpunit/tests/rest-api/rest-application-passwords-controller.php
+++ b/tests/phpunit/tests/rest-api/rest-application-passwords-controller.php
@@ -349,6 +349,76 @@ public function test_create_item_self_user_id_admin() {
$this->check_response( $response->get_data(), $passwords[0], true );
}
+ /**
+ * @ticket 53995
+ * @dataProvider data_create_item_with_non_future_expiration
+ *
+ * @param int $offset Expiration offset from the current time, in seconds.
+ */
+ public function test_create_item_with_non_future_expiration( $offset ) {
+ wp_set_current_user( self::$admin );
+ $request = new WP_REST_Request( 'POST', '/wp/v2/users/me/application-passwords' );
+ $request->set_body_params(
+ array(
+ 'name' => 'Expired',
+ 'expires' => gmdate( 'Y-m-d\TH:i:s\Z', time() + $offset ),
+ )
+ );
+
+ $response = rest_do_request( $request );
+
+ $this->assertErrorResponse( 'application_password_invalid_expiration', $response, 400 );
+ $this->assertSame( array(), WP_Application_Passwords::get_user_application_passwords( self::$admin ) );
+ }
+
+ /**
+ * Data provider for rejecting an expiration that is not in the future.
+ *
+ * @return array[]
+ */
+ public function data_create_item_with_non_future_expiration() {
+ return array(
+ 'past day' => array( -DAY_IN_SECONDS ),
+ 'current second' => array( 0 ),
+ );
+ }
+
+ /**
+ * @ticket 53995
+ */
+ public function test_create_item_with_future_expiration() {
+ wp_set_current_user( self::$admin );
+ $expires = time() + DAY_IN_SECONDS;
+ $request = new WP_REST_Request( 'POST', '/wp/v2/users/me/application-passwords' );
+ $request->set_body_params(
+ array(
+ 'name' => 'Future',
+ 'expires' => gmdate( 'Y-m-d\TH:i:s\Z', $expires ),
+ )
+ );
+
+ $response = rest_do_request( $request );
+
+ $this->assertSame( 201, $response->get_status() );
+ $this->assertSame( gmdate( 'Y-m-d\TH:i:s', $expires ), $response->get_data()['expires'] );
+ }
+
+ /**
+ * @ticket 53995
+ */
+ public function test_update_item_with_past_expiration() {
+ wp_set_current_user( self::$admin );
+ list( , $item ) = WP_Application_Passwords::create_new_application_password( self::$admin, array( 'name' => 'App' ) );
+ $expires = time() - DAY_IN_SECONDS;
+ $request = new WP_REST_Request( 'PUT', '/wp/v2/users/me/application-passwords/' . $item['uuid'] );
+ $request->set_body_params( array( 'expires' => gmdate( 'Y-m-d\TH:i:s\Z', $expires ) ) );
+
+ $response = rest_do_request( $request );
+
+ $this->assertSame( 200, $response->get_status() );
+ $this->assertSame( gmdate( 'Y-m-d\TH:i:s', $expires ), $response->get_data()['expires'] );
+ }
+
/**
* @ticket 42790
*/
@@ -366,6 +436,37 @@ public function test_create_item_self_user_id_subscriber() {
$this->check_response( $response->get_data(), $passwords[0], true );
}
+ /**
+ * @ticket 53995
+ */
+ public function test_update_item_clears_expiration_with_json_null() {
+ wp_set_current_user( self::$admin );
+ list( , $item ) = WP_Application_Passwords::create_new_application_password(
+ self::$admin,
+ array(
+ 'name' => 'App',
+ 'expires' => time() + DAY_IN_SECONDS,
+ )
+ );
+ $path = '/wp/v2/users/me/application-passwords/' . $item['uuid'];
+ $request = new WP_REST_Request( 'PUT', $path );
+ $request->set_header( 'Content-Type', 'application/json' );
+ $request->set_body( wp_json_encode( array( 'expires' => null ) ) );
+
+ $response = rest_do_request( $request );
+
+ $this->assertSame( 200, $response->get_status() );
+ $this->assertNull( $response->get_data()['expires'] );
+ $stored = WP_Application_Passwords::get_user_application_password( self::$admin, $item['uuid'] );
+ $this->assertNull( $stored['expires'] );
+ $this->assertSame( $item['password'], $stored['password'] );
+ $this->assertSame( $item['name'], $stored['name'] );
+
+ $response = rest_do_request( new WP_REST_Request( 'GET', $path ) );
+ $this->assertSame( 200, $response->get_status() );
+ $this->assertNull( $response->get_data()['expires'] );
+ }
+
/**
* @ticket 42790
*/
@@ -906,6 +1007,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 +1026,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 +1055,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
}
}
},