Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions app/Http/Controllers/Api/ClientApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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:2147483647',
'max_allowed_user_sessions' => 'sometimes|integer|min:0',
];
}
Expand All @@ -739,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|max:2147483647',
];
}

Expand Down
1 change: 1 addition & 0 deletions app/ModelSerializers/OAuth2/ClientAdminSerializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
28 changes: 28 additions & 0 deletions app/Models/OAuth2/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down Expand Up @@ -1829,6 +1837,26 @@ 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
{
// 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;
}

public function getOTPGrantsByEmailNotRedeemed(string $email){
$criteria = Criteria::create();
$criteria->where(Criteria::expr()->eq('email', trim($email)));
Expand Down
14 changes: 14 additions & 0 deletions app/Models/OAuth2/Factories/ClientFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -219,6 +220,19 @@ 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'];
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'])){
$client->setMaxAllowedUserSessions(intval($payload['max_allowed_user_sessions']));
}
Expand Down
18 changes: 17 additions & 1 deletion app/Services/OAuth2/TokenService.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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())
)
);

Expand Down
1 change: 1 addition & 0 deletions database/migrations/Version20190604015804.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
56 changes: 56 additions & 0 deletions database/migrations/Version20261123142702.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php namespace Database\Migrations;
/**
* Copyright 2026 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/

use Doctrine\DBAL\Schema\SchemaException;
use Doctrine\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema as Schema;
use LaravelDoctrine\Migrations\Schema\Builder;
use LaravelDoctrine\Migrations\Schema\Table;

/**
* Class Version20261123142702
* Adds the per-client refresh token lifetime override.
* NULL = inherit the global OAuth2.RefreshToken.Lifetime, 0 = never expires, N > 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');
});
}
}
}
9 changes: 9 additions & 0 deletions resources/js/oauth2/profile/edit_client/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +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.
// 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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -96,6 +96,17 @@ 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()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
.transform((value, originalValue) => (originalValue === '' ? null : value))
.nullable()
// 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.'),
}),
});
}

Expand Down Expand Up @@ -230,6 +241,19 @@ const OauthPanel = ({
value={formik.values.rotate_refresh_token}
onChange={formik.handleChange}
/>
{
formik.values.use_refresh_token &&
<SimpleTextFormControl
id="refresh_token_lifetime"
title="Refresh Token Lifetime (Seconds, optional)"
tooltip="Overrides the server default refresh token lifetime for this client. Leave empty to use the server default. 0 means the refresh token never expires."
type="number"
value={formik.values.refresh_token_lifetime ?? ''}
touched={formik.touched.refresh_token_lifetime}
errors={formik.errors.refresh_token_lifetime}
onChange={formik.handleChange}
/>
}
</>
}
</FormGroup>
Expand Down
92 changes: 92 additions & 0 deletions tests/ClientApiTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
/**
Expand Down Expand Up @@ -99,6 +100,97 @@ 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 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 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']);

$this->putRefreshTokenLifetime($client, -1);
$this->assertResponseStatus(412);
}

public function testUpdateNativeClientAcceptsCustomSchemePostLogoutUrisAndAllowedOrigins(){

$client = EntityManager::getRepository(Client::class)->findOneBy(['app_name' => 'oauth2_native_app']);
Expand Down
Loading
Loading