An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.
PHP coolifydatabasesdeploymentdockerdocker-composeinertiajslaravelmariadbmysqlnextjsnodejsphppostgresredisself-hostedself-hostingserverstatic-sitesveltesvelte5
Merge remote-tracking branch 'origin/next' into ghe-support-helpers
Andras Bacsaia7dddccd2e6e
diff --cc app/Livewire/Source/Github/Change.phpindex a5479e0fd7,682333aa6b..9c9f87469c--- a/app/Livewire/Source/Github/Change.php+++ b/app/Livewire/Source/Github/Change.php@@@ -8,11 -8,7 +8,8 @@@ use App\Models\PrivateKeyuse App\Rules\SafeExternalUrl;use Illuminate\Foundation\Auth\Access\AuthorizesRequests;use Illuminate\Support\Facades\Cache;- use Illuminate\Support\Facades\Http;use Illuminate\Support\Str;- use Lcobucci\JWT\Configuration;- use Lcobucci\JWT\Signer\Key\InMemory;- use Lcobucci\JWT\Signer\Rsa\Sha256;++use Illuminate\Validation\ValidationException;use Livewire\Component;class Change extends Component@@@ -304,36 -294,13 +303,16 @@@public function getGithubAppNameUpdatePath(){- if (str($this->github_app->organization)->isNotEmpty()) {- return "{$this->github_app->html_url}/organizations/{$this->github_app->organization}/settings/apps/{$this->github_app->name}";+ $name = encodeGithubPathSegment($this->github_app->name);+ $organization = normalizeGithubOrganization($this->github_app->organization);++ if (filled($organization)) {+ return rtrim($this->github_app->html_url, '/').'/organizations/'.encodeGithubPathSegment($organization)."/settings/apps/{$name}";}- return "{$this->github_app->html_url}/settings/apps/{$this->github_app->name}";+ return rtrim($this->github_app->html_url, '/')."/settings/apps/{$name}";}- private function generateGithubJwt($private_key, $app_id): string- {- $configuration = Configuration::forAsymmetricSigner(- new Sha256,- InMemory::plainText($private_key),- InMemory::plainText($private_key)- );-- $now = time();-- return $configuration->builder()- ->issuedBy((string) $app_id)- ->permittedFor($this->github_app->api_url)- ->identifiedBy((string) $now)- ->issuedAt(new \DateTimeImmutable("@{$now}"))- ->expiresAt(new \DateTimeImmutable('@'.($now + 600)))- ->getToken($configuration->signer(), $configuration->signingKey())- ->toString();- }-public function updateGithubAppName(){try {@@@ -391,6 -346,6 +360,8 @@@$this->syncData(true);$this->github_app->save();$this->dispatch('success', 'Github App updated.');++ } catch (ValidationException $e) {++ throw $e;} catch (\Throwable $e) {return handleError($e, $this);}diff --cc bootstrap/helpers/github.phpindex f1e131a1de,978e9ddaeb..69991f52ec--- a/bootstrap/helpers/github.php+++ b/bootstrap/helpers/github.php@@@ -13,143 -14,9 +14,143 @@@ use Lcobucci\JWT\Signer\Key\InMemoryuse Lcobucci\JWT\Signer\Rsa\Sha256;use Lcobucci\JWT\Token\Builder;+/**+ * Extract and normalize the hostname from a GitHub URL.+ *+ * @param string|null $url The URL to parse+ * @return string|null The lowercase hostname, or null if the URL is blank or has no parseable host+ */+function githubUrlHost(?string $url): ?string+{+ if (blank($url)) {+ return null;+ }++ $host = parse_url($url, PHP_URL_HOST);++ if (! is_string($host) || blank($host)) {+ return null;+ }++ return strtolower($host);+}++/**+ * Build the scheme://host[:port] origin for a GitHub URL.+ *+ * When the host cannot be parsed (e.g. a scheme-less or malformed URL such as+ * "not-a-url"), the input is returned verbatim with any trailing slashes+ * trimmed. Callers should pass already-validated URLs (see SafeExternalUrl),+ * so this fallback only guards against unexpected input.+ *+ * @param string $url The URL to derive the origin from+ * @return string The normalized origin, or the trimmed input when the host is unparseable+ */+function githubUrlOrigin(string $url): string+{+ $scheme = parse_url($url, PHP_URL_SCHEME) ?: 'https';+ $host = githubUrlHost($url);+ $port = parse_url($url, PHP_URL_PORT);++ if (! $host) {+ return rtrim($url, '/');+ }++ return $scheme.'://'.$host.($port ? ":{$port}" : '');+}++/**+ * Determine whether the URL points at github.com.+ *+ * @param string|null $htmlUrl The GitHub HTML URL to check+ */+function isGithubDotComHost(?string $htmlUrl): bool+{+ return githubUrlHost($htmlUrl) === 'github.com';+}++/**+ * Determine whether the URL points at a *.ghe.com GitHub Enterprise Cloud host.+ *+ * @param string|null $htmlUrl The GitHub HTML URL to check+ */+function isGheDotComHost(?string $htmlUrl): bool+{+ $host = githubUrlHost($htmlUrl);++ return is_string($host)+ && Str::endsWith($host, '.ghe.com')+ && ! Str::startsWith($host, 'api.');+}++/**+ * Determine whether the URL belongs to GitHub's cloud family (github.com or *.ghe.com).+ *+ * @param string|null $htmlUrl The GitHub HTML URL to check+ */+function isGithubCloudFamilyHost(?string $htmlUrl): bool+{+ return isGithubDotComHost($htmlUrl) || isGheDotComHost($htmlUrl);+}++/**+ * Determine whether the URL belongs to a self-hosted GitHub Enterprise Server.+ *+ * @param string|null $htmlUrl The GitHub HTML URL to check+ */+function isGithubEnterpriseServerHost(?string $htmlUrl): bool+{+ return filled($htmlUrl) && ! isGithubCloudFamilyHost($htmlUrl);+}++/**+ * Derive the GitHub REST API base URL from a GitHub HTML URL.+ *+ * @param string $htmlUrl The GitHub HTML URL+ * @return string The API base URL (api.github.com, api.<host> for *.ghe.com, or <origin>/api/v3 for GHES)+ */+function githubApiUrlFromHtmlUrl(string $htmlUrl): string+{+ if (isGithubDotComHost($htmlUrl)) {+ return 'https://api.github.com';+ }++ if (isGheDotComHost($htmlUrl)) {+ return 'https://api.'.githubUrlHost($htmlUrl);+ }++ return githubUrlOrigin($htmlUrl).'/api/v3';+}++/**+ * Normalize a GitHub organization slug by trimming surrounding slashes and whitespace.+ *+ * @param string|null $organization The raw organization value+ * @return string|null The trimmed organization, or null when blank+ */+function normalizeGithubOrganization(?string $organization): ?string+{+ if (blank($organization)) {+ return null;+ }++ return trim((string) $organization, "/ \t\n\r\0\x0B");+}++/**+ * URL-encode a single GitHub path segment.+ *+ * @param string $segment The raw path segment+ * @return string The raw-URL-encoded segment+ */+function encodeGithubPathSegment(string $segment): string+{+ return rawurlencode($segment);+}+- function generateGithubToken(GithubApp $source, string $type)+ function assertGithubClockInSync(string $apiUrl): void{- $response = Http::get("{$source->api_url}/zen");+ $response = Http::get("{$apiUrl}/zen");$serverTime = CarbonImmutable::now()->setTimezone('UTC');$githubTime = Carbon::parse($response->header('date'));$timeDiff = abs($serverTime->diffInSeconds($githubTime));@@@ -251,19 -123,82 +257,86 @@@ function githubApi(GithubApp|GitlabApp|];}+ function generateGithubAppJwt(string $privateKey, string|int $appId): string+ {+ $algorithm = new Sha256;+ $tokenBuilder = (new Builder(new JoseEncoder, ChainedFormatter::default()));+ $now = CarbonImmutable::now()->setTimezone('UTC');+ $now = $now->setTime($now->format('H'), $now->format('i'), $now->format('s'));++ return $tokenBuilder+ ->issuedBy((string) $appId)+ ->issuedAt($now->modify('-1 minute'))+ ->expiresAt($now->modify('+8 minutes'))+ ->getToken($algorithm, InMemory::plainText($privateKey))+ ->toString();+ }++ function syncGithubAppName(GithubApp $source, bool $throw = false): ?string+ {+ try {+ if (blank($source->app_id) || blank($source->private_key_id)) {+ return null;+ }++ $privateKey = $source->privateKey ?: PrivateKey::find($source->private_key_id);++ if (! $privateKey) {+ return null;+ }++ assertGithubClockInSync($source->api_url);++ $jwt = generateGithubAppJwt($privateKey->private_key, $source->app_id);++ $response = Http::withHeaders([+ 'Accept' => 'application/vnd.github+json',+ 'X-GitHub-Api-Version' => '2022-11-28',+ 'Authorization' => "Bearer {$jwt}",+ ])->get("{$source->api_url}/app");++ if (! $response->successful()) {+ throw new RuntimeException(data_get($response->json(), 'message', 'Failed to fetch GitHub App information.'));+ }++ $appSlug = data_get($response->json(), 'slug');++ if (blank($appSlug)) {+ return null;+ }++ $source->name = $appSlug;++ if ($source->exists) {+ $source->save();+ }++ $privateKey->name = "github-app-{$appSlug}";+ $privateKey->save();++ return $appSlug;+ } catch (Throwable $e) {+ if ($throw) {+ throw $e;+ }++ return null;+ }+ }+function getInstallationPath(GithubApp $source): string{- $name = str(Str::kebab($source->name));- $baseUrl = rtrim($source->html_url, '/');- $host = parse_url($source->html_url, PHP_URL_HOST);- $host = blank($host) ? null : Str::lower($host);- $usesDataResidencyPath = filled($host) && Str::endsWith($host, '.ghe.com');- $installation_path = $host === 'github.com' || $usesDataResidencyPath ? 'apps' : 'github-apps';+ $name = encodeGithubPathSegment(Str::kebab($source->name));$state = Str::random(64);+ $organization = normalizeGithubOrganization($source->organization);++ if (isGithubEnterpriseServerHost($source->html_url)) {+ $path = "github-apps/{$name}";+ } elseif (isGheDotComHost($source->html_url) && filled($organization)) {+ $path = 'apps/'.encodeGithubPathSegment($organization)."/{$name}";+ } else {+ $path = "apps/{$name}";+ }Cache::put('github-app-setup-state:'.hash('sha256', $state), ['action' => 'install',diff --cc tests/Feature/Application/GithubSourceChangeTest.phpindex a66aea8b19,70d4e101d3..f3ee7bedf4--- a/tests/Feature/Application/GithubSourceChangeTest.php+++ b/tests/Feature/Application/GithubSourceChangeTest.php@@@ -147,18 -147,123 +147,138 @@@ describe('GitHub Source Change Componen]);});- test('ghe dot com installation path includes encoded organization segment', function () {+ test('ghe.com installation path uses github cloud owner scoped route', function () {+ $githubApp = new GithubApp;+ $githubApp->forceFill([+ 'id' => 123,+ 'name' => 'provided-github-app',+ 'organization' => 'acme-enterprise',+ 'html_url' => 'https://octocorp.ghe.com',+ 'team_id' => 456,+ ]);++ $installationUrl = getInstallationPath($githubApp);+ parse_str(parse_url($installationUrl, PHP_URL_QUERY), $query);+ $installState = $query['state'] ?? null;++ expect($installationUrl)->toStartWith('https://octocorp.ghe.com/apps/acme-enterprise/provided-github-app/installations/new?')+ ->and($installState)->not->toBeEmpty()+ ->and(Cache::get('github-app-setup-state:'.hash('sha256', $installState)))+ ->toMatchArray([+ 'action' => 'install',+ 'github_app_id' => 123,+ 'team_id' => 456,+ ]);+ });++ test('installation path is pure and never calls github or mutates the app', function () {+ Http::fake();++ $privateKey = PrivateKey::create([+ 'name' => 'github-app-local-name',+ 'private_key' => validPrivateKey(),+ 'team_id' => $this->team->id,+ 'is_git_related' => true,+ ]);++ $githubApp = GithubApp::create([+ 'name' => 'Local Display Name',+ 'organization' => 'acme-enterprise',+ 'api_url' => 'https://api.github.com',+ 'html_url' => 'https://octocorp.ghe.com',+ 'custom_user' => 'git',+ 'custom_port' => 22,+ 'app_id' => 12345,+ 'private_key_id' => $privateKey->id,+ 'team_id' => $this->team->id,+ 'is_system_wide' => false,+ ]);++ $installationUrl = getInstallationPath($githubApp);++ Http::assertNothingSent();++ expect($installationUrl)->toStartWith('https://octocorp.ghe.com/apps/acme-enterprise/local-display-name/installations/new?')+ ->and($githubApp->refresh()->name)->toBe('Local Display Name')+ ->and($privateKey->refresh()->name)->toBe('github-app-local-name');+ });++ test('syncGithubAppName persists the github slug and renames the private key', function () {+ Http::fake([+ '*/app' => Http::response(['slug' => 'actual-github-slug']),+ '*/zen' => Http::response('Keep it logically awesome.'),+ ]);++ $privateKey = PrivateKey::create([+ 'name' => 'github-app-local-name',+ 'private_key' => validPrivateKey(),+ 'team_id' => $this->team->id,+ 'is_git_related' => true,+ ]);++ $githubApp = GithubApp::create([+ 'name' => 'Local Display Name',+ 'organization' => 'acme-enterprise',+ 'api_url' => 'https://api.github.com',+ 'html_url' => 'https://octocorp.ghe.com',+ 'custom_user' => 'git',+ 'custom_port' => 22,+ 'app_id' => 12345,+ 'private_key_id' => $privateKey->id,+ 'team_id' => $this->team->id,+ 'is_system_wide' => false,+ ]);++ $appSlug = syncGithubAppName($githubApp, true);++ expect($appSlug)->toBe('actual-github-slug')+ ->and($githubApp->refresh()->name)->toBe('actual-github-slug')+ ->and($privateKey->refresh()->name)->toBe('github-app-actual-github-slug');+ });++ test('ghe.com installation path encodes the organization segment', function () {+ $githubApp = new GithubApp;+ $githubApp->forceFill([+ 'id' => 123,+ 'name' => 'provided-github-app',+ 'organization' => '/acme enterprise/',+ 'html_url' => 'https://octocorp.ghe.com',+ 'team_id' => 456,+ ]);++ $installationUrl = getInstallationPath($githubApp);++ expect($installationUrl)->toStartWith('https://octocorp.ghe.com/apps/acme%20enterprise/provided-github-app/installations/new?');+ });+++ test('ghe.com installation path encodes plus signs in the organization segment', function () {+ $githubApp = new GithubApp;+ $githubApp->forceFill([+ 'id' => 123,+ 'name' => 'Provided GitHub App',+ 'organization' => 'octo+corp',+ 'html_url' => 'https://octocorp.ghe.com',+ 'team_id' => 456,+ ]);+- expect(getInstallationPath($githubApp))- ->toStartWith('https://octocorp.ghe.com/apps/octo%2Bcorp/provided-git-hub-app/installations/new?');++ $installationUrl = getInstallationPath($githubApp);++++ expect($installationUrl)->toStartWith('https://octocorp.ghe.com/apps/octo%2Bcorp/provided-git-hub-app/installations/new?');++ });+++ test('ghe.com installation path keeps app scoped fallback when organization is blank', function () {+ $githubApp = new GithubApp;+ $githubApp->forceFill([+ 'id' => 123,+ 'name' => 'provided-github-app',+ 'organization' => null,+ 'html_url' => 'https://octocorp.ghe.com',+ 'team_id' => 456,+ ]);++ $installationUrl = getInstallationPath($githubApp);++ expect($installationUrl)->toStartWith('https://octocorp.ghe.com/apps/provided-github-app/installations/new?');});test('defaults webhook endpoint to app url when it is the first available endpoint', function () {@@@ -291,49 -404,6 +419,49 @@@expect($githubApp->private_key_id)->toBe($privateKey->id);});- test('normalizes ghe dot com api url when saving github app settings', function () {++ test('normalizes resolvable ghe dot com api url when saving github app settings', function () {+ $githubApp = GithubApp::create([+ 'name' => 'Test GitHub App',- 'api_url' => 'https://octocorp.ghe.com/api/v3',++ 'api_url' => 'https://github.ghe.com/api/v3',+ 'html_url' => 'https://github.com',+ 'custom_user' => 'git',+ 'custom_port' => 22,+ 'team_id' => $this->team->id,+ 'is_system_wide' => false,+ ]);++ Livewire::withQueryParams(['github_app_uuid' => $githubApp->uuid])+ ->test(Change::class)+ ->assertSuccessful()- ->set('htmlUrl', 'https://octocorp.ghe.com')- ->set('apiUrl', 'https://octocorp.ghe.com/api/v3')++ ->set('htmlUrl', 'https://github.ghe.com')++ ->set('apiUrl', 'https://github.ghe.com/api/v3')+ ->call('submit')+ ->assertDispatched('success')- ->assertSet('apiUrl', 'https://api.octocorp.ghe.com');++ ->assertSet('apiUrl', 'https://api.github.ghe.com');++ $githubApp->refresh();- expect($githubApp->api_url)->toBe('https://api.octocorp.ghe.com');++ expect($githubApp->api_url)->toBe('https://api.github.ghe.com');+ });++ test('rejects invalid github organization values', function () {+ $githubApp = GithubApp::create([+ 'name' => 'Test GitHub App',+ 'api_url' => 'https://api.github.com',+ 'html_url' => 'https://github.com',+ 'custom_user' => 'git',+ 'custom_port' => 22,+ 'team_id' => $this->team->id,+ 'is_system_wide' => false,+ ]);++ Livewire::withQueryParams(['github_app_uuid' => $githubApp->uuid])+ ->test(Change::class)+ ->assertSuccessful()+ ->set('organization', 'octo/corp')+ ->call('submit')+ ->assertHasErrors(['organization']);+ });+test('validation allows nullable values for app configuration', function () {$githubApp = GithubApp::create(['name' => 'Test GitHub App',@@@ -486,40 -556,4 +614,43 @@@->and($githubApp->metadata)->toBe('read')->and($githubApp->pull_requests)->toBe('write');});+- test('sync name uses normalized ghe dot com api url', function () {++ test('sync name uses normalized resolvable ghe dot com api url', function () {+ $privateKey = PrivateKey::create([+ 'name' => 'Test Key',+ 'private_key' => validPrivateKey(),+ 'team_id' => $this->team->id,+ ]);++ $githubApp = GithubApp::create([+ 'name' => 'Test GitHub App',- 'api_url' => 'https://api.octocorp.ghe.com',- 'html_url' => 'https://octocorp.ghe.com',++ 'api_url' => 'https://api.github.ghe.com',++ 'html_url' => 'https://github.ghe.com',+ 'custom_user' => 'git',+ 'custom_port' => 22,+ 'app_id' => 12345,+ 'installation_id' => 67890,+ 'private_key_id' => $privateKey->id,+ 'team_id' => $this->team->id,+ 'is_system_wide' => false,+ ]);++ Http::preventStrayRequests();+ Http::fake([- 'https://api.octocorp.ghe.com/app' => Http::response([++ 'https://api.github.ghe.com/zen' => Http::response('Keep it logically awesome.', 200, [++ 'date' => now()->toRfc7231String(),++ ]),++ 'https://api.github.ghe.com/app' => Http::response([+ 'slug' => 'octocorp-app',+ ]),+ ]);++ Livewire::withQueryParams(['github_app_uuid' => $githubApp->uuid])+ ->test(Change::class)+ ->assertSuccessful()+ ->call('updateGithubAppName')+ ->assertDispatched('success');+- Http::assertSent(fn ($request) => $request->url() === 'https://api.octocorp.ghe.com/app');++ Http::assertSent(fn ($request) => $request->url() === 'https://api.github.ghe.com/app');+ });});