From 3a87be635a588bb93d3460d948f6d0b0f97176a1 Mon Sep 17 00:00:00 2001 From: romanetar Date: Mon, 23 Nov 2026 15:58:34 +0100 Subject: [PATCH 1/5] feat(oauth2): per-client refresh token lifetime override Add a nullable oauth2_client.refresh_token_lifetime column that overrides the global OAuth2.RefreshToken.Lifetime for a single client. NULL inherits the global value, 0 means the refresh token never expires, N > 0 is N seconds. - TokenService::createRefreshToken resolves the lifetime per client, so both initial issuance and rotation honor it - ClientFactory uses array_key_exists so null/empty clears the override - expose the field in the admin serializer, API validation and the console client edit UI (shown when refresh tokens are enabled) - tests: issuance with/without override, 0 as explicit infinite, factory semantics and admin API round trip --- .../Controllers/Api/ClientApiController.php | 1 + .../OAuth2/ClientAdminSerializer.php | 1 + app/Models/OAuth2/Client.php | 26 ++++ app/Models/OAuth2/Factories/ClientFactory.php | 8 ++ app/Services/OAuth2/TokenService.php | 18 ++- database/migrations/Version20261123142702.php | 56 ++++++++ .../js/oauth2/profile/edit_client/actions.js | 5 + .../edit_client/components/oauth_panel.js | 20 ++- tests/ClientApiTest.php | 61 +++++++++ tests/OAuth2RefreshTokenLifetimeTest.php | 126 ++++++++++++++++++ tests/StubServerConfigurationService.php | 4 + tests/unit/ClientFactoryTest.php | 51 +++++++ 12 files changed, 375 insertions(+), 2 deletions(-) create mode 100644 database/migrations/Version20261123142702.php create mode 100644 tests/OAuth2RefreshTokenLifetimeTest.php diff --git a/app/Http/Controllers/Api/ClientApiController.php b/app/Http/Controllers/Api/ClientApiController.php index a507143a7..5c5f9f087 100644 --- a/app/Http/Controllers/Api/ClientApiController.php +++ b/app/Http/Controllers/Api/ClientApiController.php @@ -721,6 +721,7 @@ protected function getUpdatePayloadValidationRules(): array 'otp_enabled' => 'sometimes|boolean', 'otp_length' => 'sometimes|integer|min:4|max:8', 'otp_lifetime' => 'sometimes|integer|min:60|max:600', + 'refresh_token_lifetime' => 'sometimes|nullable|integer|min:0', 'max_allowed_user_sessions' => 'sometimes|integer|min:0', ]; } diff --git a/app/ModelSerializers/OAuth2/ClientAdminSerializer.php b/app/ModelSerializers/OAuth2/ClientAdminSerializer.php index 86e6a8989..1d6a7cbfe 100644 --- a/app/ModelSerializers/OAuth2/ClientAdminSerializer.php +++ b/app/ModelSerializers/OAuth2/ClientAdminSerializer.php @@ -96,6 +96,7 @@ public function serialize($expand = null, array $fields = [], array $relations = $values['owner_name'] = $client->getOwnerNice(); $values['post_logout_redirect_uris'] = $client->getPostLogoutUris(); $values['redirect_uris'] = $client->getRedirectUris(); + $values['refresh_token_lifetime'] = $client->getRefreshTokenLifetime(); $values['rotate_refresh_token'] = $client->useRotateRefreshTokenPolicy(); $values['token_endpoint_auth_method'] = $tokenEndpointAuthInfo->getAuthenticationMethod() ?? 'none'; diff --git a/app/Models/OAuth2/Client.php b/app/Models/OAuth2/Client.php index a2b2f6c66..56b00d630 100644 --- a/app/Models/OAuth2/Client.php +++ b/app/Models/OAuth2/Client.php @@ -116,6 +116,14 @@ class Client extends BaseEntity implements IClient #[ORM\Column(name: 'otp_lifetime', type: 'integer')] private $otp_lifetime; + /** + * Per-client refresh token lifetime override (seconds). + * NULL = inherit global OAuth2.RefreshToken.Lifetime, 0 = never expires, N > 0 = N seconds + * @var int|null + */ + #[ORM\Column(name: 'refresh_token_lifetime', type: 'integer', nullable: true)] + private $refresh_token_lifetime; + /** * @var bool */ @@ -1829,6 +1837,24 @@ public function setOtpLifetime(int $otp_lifetime): void $this->otp_lifetime = $otp_lifetime; } + /** + * @return int|null null means "inherit the global OAuth2.RefreshToken.Lifetime" + */ + public function getRefreshTokenLifetime(): ?int + { + return is_null($this->refresh_token_lifetime) ? null : intval($this->refresh_token_lifetime); + } + + /** + * @param int|null $refresh_token_lifetime null = inherit global, 0 = never expires, N > 0 = N seconds + */ + public function setRefreshTokenLifetime(?int $refresh_token_lifetime): void + { + if (!is_null($refresh_token_lifetime) && $refresh_token_lifetime < 0) + throw new ValidationException("refresh_token_lifetime must be null or greater or equal than 0."); + $this->refresh_token_lifetime = $refresh_token_lifetime; + } + public function getOTPGrantsByEmailNotRedeemed(string $email){ $criteria = Criteria::create(); $criteria->where(Criteria::expr()->eq('email', trim($email))); diff --git a/app/Models/OAuth2/Factories/ClientFactory.php b/app/Models/OAuth2/Factories/ClientFactory.php index 79e1b13f1..89002632d 100644 --- a/app/Models/OAuth2/Factories/ClientFactory.php +++ b/app/Models/OAuth2/Factories/ClientFactory.php @@ -219,6 +219,14 @@ public static function populate(Client $client, array $payload):Client $client->setOtpLifetime(intval($payload['otp_lifetime'])); } + // array_key_exists (not isset): an explicit null / empty value clears the override (inherit global) + if(array_key_exists('refresh_token_lifetime', $payload)){ + $value = $payload['refresh_token_lifetime']; + $client->setRefreshTokenLifetime( + (is_null($value) || $value === '') ? null : intval($value) + ); + } + if(isset($payload['max_allowed_user_sessions'])){ $client->setMaxAllowedUserSessions(intval($payload['max_allowed_user_sessions'])); } diff --git a/app/Services/OAuth2/TokenService.php b/app/Services/OAuth2/TokenService.php index cbdd79233..1caa2fcf5 100644 --- a/app/Services/OAuth2/TokenService.php +++ b/app/Services/OAuth2/TokenService.php @@ -959,6 +959,22 @@ public function checkAccessTokenAudience(AccessToken $access_token, $current_ip) } + /** + * Refresh token lifetime (seconds) to apply for a given client. + * The per-client override wins when set (0 = never expires); a null override inherits + * the global OAuth2.RefreshToken.Lifetime. + * @param string $client_id + * @return int + */ + private function resolveRefreshTokenLifetime($client_id): int + { + $client = $this->client_repository->getClientById($client_id); + $client_lifetime = $client instanceof Client ? $client->getRefreshTokenLifetime() : null; + if (!is_null($client_lifetime)) + return $client_lifetime; + return intval($this->configuration_service->getConfigValue('OAuth2.RefreshToken.Lifetime')); + } + /** * Creates a new refresh token and associate it with given access token * @param AccessToken $access_token @@ -970,7 +986,7 @@ public function createRefreshToken(AccessToken &$access_token, $refresh_cache = $refresh_token = $this->identifier_generator->generate( RefreshToken::create( $access_token, - $this->configuration_service->getConfigValue('OAuth2.RefreshToken.Lifetime') + $this->resolveRefreshTokenLifetime($access_token->getClientId()) ) ); diff --git a/database/migrations/Version20261123142702.php b/database/migrations/Version20261123142702.php new file mode 100644 index 000000000..933524389 --- /dev/null +++ b/database/migrations/Version20261123142702.php @@ -0,0 +1,56 @@ + 0 = N seconds. + * @package Database\Migrations + */ +final class Version20261123142702 extends AbstractMigration +{ + /** + * @param Schema $schema + * @throws SchemaException + */ + public function up(Schema $schema): void + { + $builder = new Builder($schema); + if ($schema->hasTable("oauth2_client") && !$builder->hasColumn("oauth2_client", "refresh_token_lifetime")) { + $builder->table('oauth2_client', function (Table $table) { + $table->unsignedInteger('refresh_token_lifetime')->setNotnull(false)->setDefault(null); + }); + } + } + + /** + * @param Schema $schema + * @throws SchemaException + */ + public function down(Schema $schema): void + { + $builder = new Builder($schema); + if ($schema->hasTable("oauth2_client") && $builder->hasColumn("oauth2_client", "refresh_token_lifetime")) { + $builder->table('oauth2_client', function (Table $table) { + $table->dropColumn('refresh_token_lifetime'); + }); + } + } +} diff --git a/resources/js/oauth2/profile/edit_client/actions.js b/resources/js/oauth2/profile/edit_client/actions.js index 94de1dbef..0d01eec84 100644 --- a/resources/js/oauth2/profile/edit_client/actions.js +++ b/resources/js/oauth2/profile/edit_client/actions.js @@ -119,6 +119,11 @@ const normalizeEntity = (entity, entitySection) => { normEntity.contacts = Array.isArray(entity.contacts) ? entity.contacts.filter(c => c).join(',') : entity.contacts; normEntity.use_refresh_token = entity.use_refresh_token ? 1 : 0; normEntity.rotate_refresh_token = entity.rotate_refresh_token ? 1 : 0; + // empty / null = inherit the server default, 0 = never expires + normEntity.refresh_token_lifetime = + entity.refresh_token_lifetime === '' || entity.refresh_token_lifetime == null + ? null + : Number(entity.refresh_token_lifetime); normEntity.app_name = entity.app_name; normEntity.app_description = entity.app_description; if (entity.admin_users) { diff --git a/resources/js/oauth2/profile/edit_client/components/oauth_panel.js b/resources/js/oauth2/profile/edit_client/components/oauth_panel.js index 4d206af3b..a54bba130 100644 --- a/resources/js/oauth2/profile/edit_client/components/oauth_panel.js +++ b/resources/js/oauth2/profile/edit_client/components/oauth_panel.js @@ -5,7 +5,7 @@ import TagsInput, {getTags} from "../../../../components/tags_input"; import {handleErrorResponse} from "../../../../utils"; import {CheckboxFormControl, SimpleTextFormControl} from "./form_controls"; import {useFormik} from 'formik'; -import {object, ref, string} from 'yup'; +import {number, object, ref, string} from 'yup'; import AssignmentIcon from "@material-ui/icons/Assignment"; import CheckCircleIcon from '@material-ui/icons/CheckCircle'; import InfoOutlinedIcon from "@material-ui/icons/InfoOutlined"; @@ -96,6 +96,11 @@ const OauthPanel = ({ logo_uri: string().max(SIMPLE_INPUT_MAX_LENGTH, '').nullable(), tos_uri: string().max(SIMPLE_INPUT_MAX_LENGTH, '').nullable(), policy_uri: string().max(SIMPLE_INPUT_MAX_LENGTH, '').nullable(), + refresh_token_lifetime: number() + .transform((value, originalValue) => (originalValue === '' ? null : value)) + .nullable() + .integer('The refresh token lifetime must be an integer.') + .min(0, 'The refresh token lifetime must be greater or equal than 0.'), }); } @@ -230,6 +235,19 @@ const OauthPanel = ({ value={formik.values.rotate_refresh_token} onChange={formik.handleChange} /> + { + formik.values.use_refresh_token && + + } } diff --git a/tests/ClientApiTest.php b/tests/ClientApiTest.php index 7f552af1e..c71dcecd7 100644 --- a/tests/ClientApiTest.php +++ b/tests/ClientApiTest.php @@ -18,6 +18,7 @@ use Illuminate\Support\Facades\Session; use Illuminate\Support\Facades\Config; use LaravelDoctrine\ORM\Facades\EntityManager; +use App\ModelSerializers\SerializerRegistry; use Services\OAuth2\ClientService; use Utils\Services\ILockManagerService; /** @@ -99,6 +100,66 @@ public function testCreate(){ $this->assertTrue(isset($json_response->client_id) && !empty($json_response->client_id)); } + private function putRefreshTokenLifetime(Client $client, $value): void + { + $this->action("PUT", "Api\\ClientApiController@update", + [ + 'id' => $client->id, + 'application_type' => $client->getApplicationType(), + 'refresh_token_lifetime' => $value, + ], + [], + [], + []); + } + + /** + * Reads the value the way the console edit page does: the admin (private) client serializer, + * over a refreshed entity. + */ + private function getRefreshTokenLifetimeFromAdminSerializer(Client $client) + { + // refresh (not clear): clear() would detach the authenticated user and break the next PUT + $fresh = EntityManager::getRepository(Client::class)->find($client->id); + EntityManager::refresh($fresh); + $values = SerializerRegistry::getInstance() + ->getSerializer($fresh, SerializerRegistry::SerializerType_Private) + ->serialize(); + $this->assertArrayHasKey('refresh_token_lifetime', $values); + return $values['refresh_token_lifetime']; + } + + public function testRefreshTokenLifetimeIsWritableAndReadableThroughAdminApi(){ + + $client = EntityManager::getRepository(Client::class)->findOneBy(['app_name' => 'oauth2_native_app']); + + // unset by default => inherit global + $this->assertNull($this->getRefreshTokenLifetimeFromAdminSerializer($client)); + + $this->putRefreshTokenLifetime($client, 3600); + $this->assertResponseStatus(201); + $this->assertSame(3600, $this->getRefreshTokenLifetimeFromAdminSerializer($client)); + + // 0 is a real value (never expires), distinct from unset + $this->putRefreshTokenLifetime($client, 0); + $this->assertResponseStatus(201); + $this->assertSame(0, $this->getRefreshTokenLifetimeFromAdminSerializer($client)); + + // an empty value clears the override (inherit global). The test harness form-encodes the + // request, which drops null; JSON null (what the console UI sends) is covered in ClientFactoryTest. + $this->putRefreshTokenLifetime($client, ''); + $this->assertResponseStatus(201); + $this->assertNull($this->getRefreshTokenLifetimeFromAdminSerializer($client)); + } + + public function testRefreshTokenLifetimeRejectsNegativeValue(){ + + $client = EntityManager::getRepository(Client::class)->findOneBy(['app_name' => 'oauth2_native_app']); + + $this->putRefreshTokenLifetime($client, -1); + $this->assertResponseStatus(412); + } + public function testUpdateNativeClientAcceptsCustomSchemePostLogoutUrisAndAllowedOrigins(){ $client = EntityManager::getRepository(Client::class)->findOneBy(['app_name' => 'oauth2_native_app']); diff --git a/tests/OAuth2RefreshTokenLifetimeTest.php b/tests/OAuth2RefreshTokenLifetimeTest.php new file mode 100644 index 000000000..2b509ad42 --- /dev/null +++ b/tests/OAuth2RefreshTokenLifetimeTest.php @@ -0,0 +1,126 @@ +singleton(UtilsServiceCatalog::ServerConfigurationService, StubServerConfigurationService::class); + return $app; + } + + protected function prepareForTests(): void + { + parent::prepareForTests(); + $_ENV['refresh.token.lifetime'] = self::GLOBAL_LIFETIME; + $this->user = EntityManager::getRepository(User::class)->findOneBy(['email' => 'sebastian@tipit.net']); + $repo = EntityManager::getRepository(Client::class); + $this->client_a = $repo->findOneBy(['client_id' => '.-_~87D8/Vcvr6fvQbH4HyNgwTlfSyQ3x.openstack.client']); + $this->client_b = $repo->findOneBy(['client_id' => '1234/Vcvr6fvQbH4HyNgwKlfSpkce.openstack.client']); + } + + protected function tearDown(): void + { + unset($_ENV['refresh.token.lifetime']); + parent::tearDown(); + } + + /** + * Issues a refresh token for the given client and returns [token lifetime, persisted row lifetime] + */ + private function issueRefreshToken(Client $client): array + { + $token_service = app()->make(ITokenService::class); + $access_token = $token_service->createAccessTokenFromParams( + $client->getClientId(), + 'openid', + Config::get('app.url'), + $this->user->getId() + ); + $refresh_token = $token_service->createRefreshToken($access_token); + $row = DB::table('oauth2_refresh_token') + ->where('value', Hash::compute('sha256', $refresh_token->getValue())) + ->first(); + $this->assertNotNull($row); + return [$refresh_token->getLifetime(), intval($row->lifetime)]; + } + + private function setClientLifetime(Client $client, ?int $lifetime): void + { + $client->setRefreshTokenLifetime($lifetime); + EntityManager::persist($client); + EntityManager::flush(); + } + + public function testClientWithoutOverrideUsesGlobalLifetime(): void + { + $this->setClientLifetime($this->client_a, null); + [$lifetime, $persisted] = $this->issueRefreshToken($this->client_a); + $this->assertSame(self::GLOBAL_LIFETIME, $lifetime); + $this->assertSame(self::GLOBAL_LIFETIME, $persisted); + } + + public function testClientOverrideTakesPrecedenceOverGlobalAndOnlyForThatClient(): void + { + $this->setClientLifetime($this->client_a, 600); + $this->setClientLifetime($this->client_b, null); + + [$lifetime_a, $persisted_a] = $this->issueRefreshToken($this->client_a); + [$lifetime_b, $persisted_b] = $this->issueRefreshToken($this->client_b); + + $this->assertSame(600, $lifetime_a); + $this->assertSame(600, $persisted_a); + $this->assertSame(self::GLOBAL_LIFETIME, $lifetime_b); + $this->assertSame(self::GLOBAL_LIFETIME, $persisted_b); + } + + public function testClientOverrideZeroMeansNeverExpiresEvenWithFiniteGlobal(): void + { + $this->setClientLifetime($this->client_a, 0); + [$lifetime, $persisted] = $this->issueRefreshToken($this->client_a); + $this->assertSame(0, $lifetime); + $this->assertSame(0, $persisted); + } + + public function testGlobalZeroIsInheritedWhenNoOverride(): void + { + $_ENV['refresh.token.lifetime'] = 0; + $this->setClientLifetime($this->client_a, null); + [$lifetime] = $this->issueRefreshToken($this->client_a); + $this->assertSame(0, $lifetime); + } +} diff --git a/tests/StubServerConfigurationService.php b/tests/StubServerConfigurationService.php index ce10af156..7c41ce51f 100644 --- a/tests/StubServerConfigurationService.php +++ b/tests/StubServerConfigurationService.php @@ -28,6 +28,10 @@ public function getConfigValue($value) return intval($_ENV['access.token.refresh.jitter']); } + if ($value === 'OAuth2.RefreshToken.Lifetime' && isset($_ENV['refresh.token.lifetime'])) { + return intval($_ENV['refresh.token.lifetime']); + } + if ($value === 'OAuth2.IdToken.Lifetime' && isset($_ENV['id.token.lifetime'])) { return intval($_ENV['id.token.lifetime']); } diff --git a/tests/unit/ClientFactoryTest.php b/tests/unit/ClientFactoryTest.php index eaf1ea960..4e7ac9521 100644 --- a/tests/unit/ClientFactoryTest.php +++ b/tests/unit/ClientFactoryTest.php @@ -40,4 +40,55 @@ public function testPopulateTrimsEachUriListItem() $this->assertStringNotContainsString(', ', implode(',', $client->getPostLogoutUris())); $this->assertStringNotContainsString(', ', $client->getRawRedirectUris()); } + + public function testRefreshTokenLifetimeDefaultsToInheritGlobal() + { + $this->assertNull((new Client)->getRefreshTokenLifetime()); + } + + public function testPopulateSetsRefreshTokenLifetime() + { + $client = ClientFactory::populate(new Client, [ + 'application_type' => IClient::ApplicationType_Native, + 'refresh_token_lifetime' => '3600', + ]); + $this->assertSame(3600, $client->getRefreshTokenLifetime()); + } + + public function testPopulateKeepsZeroAsNeverExpires() + { + // 0 is a real value (infinite) and must not be confused with the unset sentinel (null) + $client = ClientFactory::populate(new Client, [ + 'application_type' => IClient::ApplicationType_Native, + 'refresh_token_lifetime' => 0, + ]); + $this->assertSame(0, $client->getRefreshTokenLifetime()); + } + + public function testPopulateClearsRefreshTokenLifetimeOnNullOrEmpty() + { + foreach ([null, ''] as $unset_value) { + $client = new Client; + $client->setRefreshTokenLifetime(600); + ClientFactory::populate($client, [ + 'application_type' => IClient::ApplicationType_Native, + 'refresh_token_lifetime' => $unset_value, + ]); + $this->assertNull($client->getRefreshTokenLifetime()); + } + } + + public function testPopulateWithoutKeyKeepsRefreshTokenLifetime() + { + $client = new Client; + $client->setRefreshTokenLifetime(600); + ClientFactory::populate($client, ['application_type' => IClient::ApplicationType_Native]); + $this->assertSame(600, $client->getRefreshTokenLifetime()); + } + + public function testNegativeRefreshTokenLifetimeIsRejected() + { + $this->expectException(\models\exceptions\ValidationException::class); + (new Client)->setRefreshTokenLifetime(-1); + } } From 9d257b8c57d6de4a8154ecf6fadbc82fa4110e41 Mon Sep 17 00:00:00 2001 From: romanetar Date: Mon, 23 Nov 2026 16:01:03 +0100 Subject: [PATCH 2/5] fix(migrations): add refresh_token_lifetime to the base oauth2_client schema On a fresh database an old data migration (Version20190729150610) loads ResourceServer through the ORM, which joins oauth2_client and selects every mapped column, so the new entity column must already exist when it runs. Follow the max_allowed_user_sessions precedent: define the column in the base schema; the dedicated migration stays guarded by hasColumn and still upgrades existing databases. --- database/migrations/Version20190604015804.php | 1 + 1 file changed, 1 insertion(+) diff --git a/database/migrations/Version20190604015804.php b/database/migrations/Version20190604015804.php index 90fec5784..989f7c2c9 100644 --- a/database/migrations/Version20190604015804.php +++ b/database/migrations/Version20190604015804.php @@ -297,6 +297,7 @@ public function up(Schema $schema):void otp_enabled tinyint(1) default '0' not null, otp_length int default '6' not null, otp_lifetime int default '120' not null, + refresh_token_lifetime int unsigned null, resource_server_id bigint unsigned null, website text null, application_type enum('WEB_APPLICATION', 'JS_CLIENT', 'SERVICE', 'NATIVE') default 'WEB_APPLICATION' null, From 431bb1639e1ed4e4821e8ba88ad956bb56233261 Mon Sep 17 00:00:00 2001 From: romanetar Date: Mon, 23 Nov 2026 16:28:50 +0100 Subject: [PATCH 3/5] fix(oauth2): validate refresh_token_lifetime on client create The create endpoint did not validate refresh_token_lifetime, so a non-numeric value went through intval() and became 0, which means the refresh token never expires. - add the same rule used by update to the create validation rules - make ClientFactory::populate reject non-integer values instead of coercing them, so write paths that bypass the controller (e.g. seeders calling build() directly) cannot produce an accidental infinite lifetime - tests for both layers --- .../Controllers/Api/ClientApiController.php | 1 + app/Models/OAuth2/Factories/ClientFactory.php | 12 +++++++++--- tests/ClientApiTest.php | 19 +++++++++++++++++++ tests/unit/ClientFactoryTest.php | 15 +++++++++++++++ 4 files changed, 44 insertions(+), 3 deletions(-) diff --git a/app/Http/Controllers/Api/ClientApiController.php b/app/Http/Controllers/Api/ClientApiController.php index 5c5f9f087..2df95be05 100644 --- a/app/Http/Controllers/Api/ClientApiController.php +++ b/app/Http/Controllers/Api/ClientApiController.php @@ -740,6 +740,7 @@ protected function getCreatePayloadValidationRules(): array 'redirect_uris' => 'nullable|string|custom_url_set:application_type', 'post_logout_redirect_uris' => 'nullable|string|custom_url_set:application_type', 'allowed_origins' => 'nullable|string|custom_url_set:application_type', + 'refresh_token_lifetime' => 'sometimes|nullable|integer|min:0', ]; } diff --git a/app/Models/OAuth2/Factories/ClientFactory.php b/app/Models/OAuth2/Factories/ClientFactory.php index 89002632d..df2336cfe 100644 --- a/app/Models/OAuth2/Factories/ClientFactory.php +++ b/app/Models/OAuth2/Factories/ClientFactory.php @@ -15,6 +15,7 @@ use App\libs\Utils\URLUtils; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Log; +use models\exceptions\ValidationException; use Models\OAuth2\Client; use Models\OAuth2\ResourceServer; use OAuth2\Models\IClient; @@ -222,9 +223,14 @@ public static function populate(Client $client, array $payload):Client // array_key_exists (not isset): an explicit null / empty value clears the override (inherit global) if(array_key_exists('refresh_token_lifetime', $payload)){ $value = $payload['refresh_token_lifetime']; - $client->setRefreshTokenLifetime( - (is_null($value) || $value === '') ? null : intval($value) - ); + if (is_null($value) || $value === '') { + $client->setRefreshTokenLifetime(null); + } else { + // never let intval() turn garbage into 0, which means "refresh token never expires" + if (filter_var($value, FILTER_VALIDATE_INT) === false) + throw new ValidationException("refresh_token_lifetime must be an integer."); + $client->setRefreshTokenLifetime(intval($value)); + } } if(isset($payload['max_allowed_user_sessions'])){ diff --git a/tests/ClientApiTest.php b/tests/ClientApiTest.php index c71dcecd7..9eed815db 100644 --- a/tests/ClientApiTest.php +++ b/tests/ClientApiTest.php @@ -152,6 +152,25 @@ public function testRefreshTokenLifetimeIsWritableAndReadableThroughAdminApi(){ $this->assertNull($this->getRefreshTokenLifetimeFromAdminSerializer($client)); } + public function testCreateRejectsNonNumericRefreshTokenLifetime(){ + + $response = $this->action("POST", "Api\\ClientApiController@create", + [ + 'app_name' => 'refresh_lifetime_invalid_app', + 'app_description' => 'refresh lifetime invalid app', + 'application_type' => IClient::ApplicationType_Native, + 'refresh_token_lifetime' => 'abc', + ], + [], + [], + []); + + $this->assertResponseStatus(412); + $this->assertNull( + EntityManager::getRepository(Client::class)->findOneBy(['app_name' => 'refresh_lifetime_invalid_app']) + ); + } + public function testRefreshTokenLifetimeRejectsNegativeValue(){ $client = EntityManager::getRepository(Client::class)->findOneBy(['app_name' => 'oauth2_native_app']); diff --git a/tests/unit/ClientFactoryTest.php b/tests/unit/ClientFactoryTest.php index 4e7ac9521..5ea819772 100644 --- a/tests/unit/ClientFactoryTest.php +++ b/tests/unit/ClientFactoryTest.php @@ -86,6 +86,21 @@ public function testPopulateWithoutKeyKeepsRefreshTokenLifetime() $this->assertSame(600, $client->getRefreshTokenLifetime()); } + public function testNonNumericRefreshTokenLifetimeIsRejectedInsteadOfBecomingZero() + { + foreach (['abc', '1e3x', '12.5', [1]] as $bad_value) { + try { + ClientFactory::populate(new Client, [ + 'application_type' => IClient::ApplicationType_Native, + 'refresh_token_lifetime' => $bad_value, + ]); + $this->fail('A non numeric refresh_token_lifetime must be rejected'); + } catch (\models\exceptions\ValidationException $ex) { + $this->addToAssertionCount(1); + } + } + } + public function testNegativeRefreshTokenLifetimeIsRejected() { $this->expectException(\models\exceptions\ValidationException::class); From ccc927420f1c5c7094eb2b0e93c169766cf87a99 Mon Sep 17 00:00:00 2001 From: romanetar Date: Mon, 23 Nov 2026 16:30:27 +0100 Subject: [PATCH 4/5] fix(oauth2-ui): do not let a hidden refresh token lifetime block Save The lifetime input is only rendered while "Use Refresh Tokens" is on, but its yup rule applied unconditionally, so an invalid value left in the form state after disabling refresh tokens silently blocked the submit. - validate refresh_token_lifetime only when use_refresh_token is enabled - omit the field from the payload while refresh tokens are disabled, so the stored override (including 0) is left untouched --- resources/js/oauth2/profile/edit_client/actions.js | 14 +++++++++----- .../profile/edit_client/components/oauth_panel.js | 10 ++++++++-- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/resources/js/oauth2/profile/edit_client/actions.js b/resources/js/oauth2/profile/edit_client/actions.js index 0d01eec84..18ef71e2e 100644 --- a/resources/js/oauth2/profile/edit_client/actions.js +++ b/resources/js/oauth2/profile/edit_client/actions.js @@ -119,11 +119,15 @@ const normalizeEntity = (entity, entitySection) => { normEntity.contacts = Array.isArray(entity.contacts) ? entity.contacts.filter(c => c).join(',') : entity.contacts; normEntity.use_refresh_token = entity.use_refresh_token ? 1 : 0; normEntity.rotate_refresh_token = entity.rotate_refresh_token ? 1 : 0; - // empty / null = inherit the server default, 0 = never expires - normEntity.refresh_token_lifetime = - entity.refresh_token_lifetime === '' || entity.refresh_token_lifetime == null - ? null - : Number(entity.refresh_token_lifetime); + // empty / null = inherit the server default, 0 = never expires. + // Only sent while refresh tokens are enabled (the input is hidden otherwise); an absent + // key leaves the stored override untouched. + if (entity.use_refresh_token) { + normEntity.refresh_token_lifetime = + entity.refresh_token_lifetime === '' || entity.refresh_token_lifetime == null + ? null + : Number(entity.refresh_token_lifetime); + } normEntity.app_name = entity.app_name; normEntity.app_description = entity.app_description; if (entity.admin_users) { diff --git a/resources/js/oauth2/profile/edit_client/components/oauth_panel.js b/resources/js/oauth2/profile/edit_client/components/oauth_panel.js index a54bba130..6a8c71db4 100644 --- a/resources/js/oauth2/profile/edit_client/components/oauth_panel.js +++ b/resources/js/oauth2/profile/edit_client/components/oauth_panel.js @@ -99,8 +99,14 @@ const OauthPanel = ({ refresh_token_lifetime: number() .transform((value, originalValue) => (originalValue === '' ? null : value)) .nullable() - .integer('The refresh token lifetime must be an integer.') - .min(0, 'The refresh token lifetime must be greater or equal than 0.'), + // the input is only shown when refresh tokens are enabled: do not let a hidden + // invalid value block the save + .when('use_refresh_token', { + is: (value) => !!value, + then: (schema) => schema + .integer('The refresh token lifetime must be an integer.') + .min(0, 'The refresh token lifetime must be greater or equal than 0.'), + }), }); } From 8ea3904f01628c8e1f6f283f28251519e712a9e8 Mon Sep 17 00:00:00 2001 From: romanetar Date: Mon, 23 Nov 2026 16:36:51 +0100 Subject: [PATCH 5/5] fix(oauth2): cap refresh_token_lifetime at the signed 32 bit maximum oauth2_client.refresh_token_lifetime is unsigned but the issued refresh token is stored in oauth2_refresh_token.lifetime, a signed int. An override above 2147483647 was accepted and saved, then failed with an out of range error when the first refresh token was inserted, returning a 500 on the token endpoint. - add max:2147483647 to the create and update validation rules - enforce the same upper bound in Client::setRefreshTokenLifetime - tests for the boundary value and the first value above it --- app/Http/Controllers/Api/ClientApiController.php | 4 ++-- app/Models/OAuth2/Client.php | 6 ++++-- tests/ClientApiTest.php | 12 ++++++++++++ tests/unit/ClientFactoryTest.php | 10 ++++++++++ 4 files changed, 28 insertions(+), 4 deletions(-) diff --git a/app/Http/Controllers/Api/ClientApiController.php b/app/Http/Controllers/Api/ClientApiController.php index 2df95be05..06035ed1a 100644 --- a/app/Http/Controllers/Api/ClientApiController.php +++ b/app/Http/Controllers/Api/ClientApiController.php @@ -721,7 +721,7 @@ protected function getUpdatePayloadValidationRules(): array 'otp_enabled' => 'sometimes|boolean', 'otp_length' => 'sometimes|integer|min:4|max:8', 'otp_lifetime' => 'sometimes|integer|min:60|max:600', - 'refresh_token_lifetime' => 'sometimes|nullable|integer|min:0', + 'refresh_token_lifetime' => 'sometimes|nullable|integer|min:0|max:2147483647', 'max_allowed_user_sessions' => 'sometimes|integer|min:0', ]; } @@ -740,7 +740,7 @@ protected function getCreatePayloadValidationRules(): array 'redirect_uris' => 'nullable|string|custom_url_set:application_type', 'post_logout_redirect_uris' => 'nullable|string|custom_url_set:application_type', 'allowed_origins' => 'nullable|string|custom_url_set:application_type', - 'refresh_token_lifetime' => 'sometimes|nullable|integer|min:0', + 'refresh_token_lifetime' => 'sometimes|nullable|integer|min:0|max:2147483647', ]; } diff --git a/app/Models/OAuth2/Client.php b/app/Models/OAuth2/Client.php index 56b00d630..7b829ebcc 100644 --- a/app/Models/OAuth2/Client.php +++ b/app/Models/OAuth2/Client.php @@ -1850,8 +1850,10 @@ public function getRefreshTokenLifetime(): ?int */ public function setRefreshTokenLifetime(?int $refresh_token_lifetime): void { - if (!is_null($refresh_token_lifetime) && $refresh_token_lifetime < 0) - throw new ValidationException("refresh_token_lifetime must be null or greater or equal than 0."); + // upper bound: oauth2_refresh_token.lifetime is a signed 32 bit int, a larger override would + // pass here but fail when the refresh token row is inserted + if (!is_null($refresh_token_lifetime) && ($refresh_token_lifetime < 0 || $refresh_token_lifetime > 2147483647)) + throw new ValidationException("refresh_token_lifetime must be null or between 0 and 2147483647."); $this->refresh_token_lifetime = $refresh_token_lifetime; } diff --git a/tests/ClientApiTest.php b/tests/ClientApiTest.php index 9eed815db..dc93a0c37 100644 --- a/tests/ClientApiTest.php +++ b/tests/ClientApiTest.php @@ -171,6 +171,18 @@ public function testCreateRejectsNonNumericRefreshTokenLifetime(){ ); } + public function testRefreshTokenLifetimeRejectsValueAboveSigned32BitMax(){ + + $client = EntityManager::getRepository(Client::class)->findOneBy(['app_name' => 'oauth2_native_app']); + + $this->putRefreshTokenLifetime($client, 2147483648); + $this->assertResponseStatus(412); + + $this->putRefreshTokenLifetime($client, 2147483647); + $this->assertResponseStatus(201); + $this->assertSame(2147483647, $this->getRefreshTokenLifetimeFromAdminSerializer($client)); + } + public function testRefreshTokenLifetimeRejectsNegativeValue(){ $client = EntityManager::getRepository(Client::class)->findOneBy(['app_name' => 'oauth2_native_app']); diff --git a/tests/unit/ClientFactoryTest.php b/tests/unit/ClientFactoryTest.php index 5ea819772..bdd3df28a 100644 --- a/tests/unit/ClientFactoryTest.php +++ b/tests/unit/ClientFactoryTest.php @@ -101,6 +101,16 @@ public function testNonNumericRefreshTokenLifetimeIsRejectedInsteadOfBecomingZer } } + public function testRefreshTokenLifetimeUpperBound() + { + $client = new Client; + $client->setRefreshTokenLifetime(2147483647); + $this->assertSame(2147483647, $client->getRefreshTokenLifetime()); + + $this->expectException(\models\exceptions\ValidationException::class); + $client->setRefreshTokenLifetime(2147483648); + } + public function testNegativeRefreshTokenLifetimeIsRejected() { $this->expectException(\models\exceptions\ValidationException::class);