Skip to content

Commit

Permalink
Merge pull request #8191 from kenjis/fix-force_https
Browse files Browse the repository at this point in the history
fix: force_https() redirects to wrong URL when baseURL has subfolder
  • Loading branch information
kenjis authored Nov 16, 2023
2 parents 2021c36 + d59fdaa commit 6a7fd1e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 18 deletions.
20 changes: 2 additions & 18 deletions system/Common.php
Original file line number Diff line number Diff line change
Expand Up @@ -502,27 +502,11 @@ function force_https(
Services::session()->regenerate(); // @codeCoverageIgnore
}

$baseURL = config(App::class)->baseURL;

if (strpos($baseURL, 'https://') === 0) {
$authority = substr($baseURL, strlen('https://'));
} elseif (strpos($baseURL, 'http://') === 0) {
$authority = substr($baseURL, strlen('http://'));
} else {
$authority = $baseURL;
}

$uri = URI::createURIString(
'https',
$authority,
$request->getUri()->getPath(), // Absolute URIs should use a "/" for an empty path
$request->getUri()->getQuery(),
$request->getUri()->getFragment()
);
$uri = $request->getUri()->withScheme('https');

// Set an HSTS header
$response->setHeader('Strict-Transport-Security', 'max-age=' . $duration)
->redirect($uri)
->redirect((string) $uri)
->setStatusCode(307)
->setBody('')
->getCookieStore()
Expand Down
20 changes: 20 additions & 0 deletions tests/system/CommonFunctionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -612,6 +612,7 @@ public function testViewNotSaveData(): void
public function testForceHttpsNullRequestAndResponse(): void
{
$this->assertNull(Services::response()->header('Location'));

Services::response()->setCookie('force', 'cookie');
Services::response()->setHeader('Force', 'header');
Services::response()->setBody('default body');
Expand All @@ -634,6 +635,25 @@ public function testForceHttpsNullRequestAndResponse(): void
force_https();
}

public function testForceHttpsWithBaseUrlSubFolder(): void
{
$config = config(App::class);
$config->baseURL = 'https://example.jp/codeIgniter/';
$uri = new SiteURI($config, 'en/home?foo=bar');
$request = new IncomingRequest($config, $uri, '', new UserAgent());
Services::injectMock('request', $request);

try {
force_https();
} catch (Exception $e) {
$this->assertInstanceOf(RedirectException::class, $e);
$this->assertSame(
'https://example.jp/codeIgniter/index.php/en/home?foo=bar',
$e->getResponse()->header('Location')->getValue()
);
}
}

/**
* @dataProvider provideCleanPathActuallyCleaningThePaths
*
Expand Down

0 comments on commit 6a7fd1e

Please sign in to comment.