diff --git a/.env b/.env index e1032c8a8d..d6a78fc36b 100644 --- a/.env +++ b/.env @@ -170,5 +170,7 @@ _APP_VCS_GITLAB_WEBHOOK_SECRET= _APP_VCS_BITBUCKET_CLIENT_ID= _APP_VCS_BITBUCKET_CLIENT_SECRET= _APP_VCS_BITBUCKET_WEBHOOK_SECRET= +_APP_VCS_ORIGIN_CLIENT_ID= +_APP_VCS_ORIGIN_PRIVATE_KEY= _APP_VCS_WEBHOOK_URL=http://appwrite/v1 _APP_WEBHOOK_MAX_FAILED_ATTEMPTS=10 diff --git a/app/config/variables.php b/app/config/variables.php index 7e32f6ea16..443dc19f66 100644 --- a/app/config/variables.php +++ b/app/config/variables.php @@ -1392,6 +1392,24 @@ return [ 'question' => '', 'filter' => '' ], + [ + 'name' => '_APP_VCS_ORIGIN_CLIENT_ID', + 'description' => 'Origin app client ID. You can find it in your Origin app details on Cursor.', + 'introduction' => '2.0.0', + 'default' => '', + 'required' => false, + 'question' => '', + 'filter' => '' + ], + [ + 'name' => '_APP_VCS_ORIGIN_PRIVATE_KEY', + 'description' => 'Origin app private key. You can generate private keys from your Origin app settings on Cursor.', + 'introduction' => '2.0.0', + 'default' => '', + 'required' => false, + 'question' => '', + 'filter' => '' + ], [ 'name' => '_APP_VCS_WEBHOOK_URL', 'description' => 'Base URL Appwrite advertises to self-hosted VCS providers when registering repository webhooks, if different from the public domain (e.g. a Docker-internal address). Falls back to the public domain when unset.', diff --git a/app/config/vcs.php b/app/config/vcs.php index d3a5dc8279..f21d54c803 100644 --- a/app/config/vcs.php +++ b/app/config/vcs.php @@ -12,6 +12,7 @@ use Utopia\VCS\Adapter\Git\Bitbucket; use Utopia\VCS\Adapter\Git\Gitea; use Utopia\VCS\Adapter\Git\GitHub; use Utopia\VCS\Adapter\Git\GitLab; +use Utopia\VCS\Adapter\Git\Origin; return [ 'github' => [ @@ -62,6 +63,20 @@ return [ 'webhookSecret' => ['required' => true, 'envVariable' => '_APP_VCS_GITLAB_WEBHOOK_SECRET'], ], ], + 'origin' => [ + 'adapter' => Origin::class, + // No 'oauth2': Origin has no OAuth2 user flow. Installs are approved + // on Cursor and confirmed by a signed receipt, a handshake the + // adapter itself owns (getInstallUrl / verifyReceipt). + 'variables' => [ + // Factory::fromInstallation() reads appId + privateKey; Origin's + // app id doubles as its client id. + 'appId' => ['required' => true, 'envVariable' => '_APP_VCS_ORIGIN_CLIENT_ID'], + 'privateKey' => ['required' => true, 'envVariable' => '_APP_VCS_ORIGIN_PRIVATE_KEY'], + // No webhookSecret: Origin signs deliveries with its own Ed25519 + // key, verified against its published JWKS instead of a shared secret. + ], + ], 'bitbucket' => [ 'adapter' => Bitbucket::class, 'oauth2' => fn (string $clientId, string $clientSecret, string $endpoint) => new OAuth2Bitbucket($clientId, $clientSecret, ''), diff --git a/app/init/constants.php b/app/init/constants.php index 61d861936b..96ded3139b 100644 --- a/app/init/constants.php +++ b/app/init/constants.php @@ -114,6 +114,7 @@ const APP_VCS_GITHUB_URL = 'https://github.com/TeamAppwrite'; const APP_VCS_GITEA_EMAIL = 'team@appwrite.io'; // Used to detect Appwrite's own commits const APP_VCS_GITLAB_EMAIL = 'team@appwrite.io'; // Used to detect Appwrite's own commits const APP_VCS_BITBUCKET_EMAIL = 'team@appwrite.io'; // Used to detect Appwrite's own commits +const APP_VCS_ORIGIN_EMAIL = 'vcs@utopia.dev'; // Used to detect commits the VCS adapter pushes over Git HTTPS const APP_BRANDED_EMAIL_BASE_TEMPLATE = 'email-base-styled'; // Embeddings diff --git a/composer.json b/composer.json index 1aaadf5dd6..f5de650609 100644 --- a/composer.json +++ b/composer.json @@ -94,6 +94,7 @@ "utopia-php/agents": "2.*", "utopia-php/audit": "3.0.*", "utopia-php/auth": "^0.10", + "utopia-php/balancer": "0.4.*", "utopia-php/cache": "^4.0.0", "utopia-php/cli": "^0.24", "utopia-php/compression": "0.1.*", @@ -135,7 +136,7 @@ "league/csv": "9.14.*", "enshrined/svg-sanitize": "0.22.*", "utopia-php/client": "^0.3.0", - "open-runtimes/sdk-for-php": "0.10.*", + "open-runtimes/sdk-for-php": "0.11.*", "utopia-php/schedule": "^0.2.0" }, "require-dev": { diff --git a/composer.lock b/composer.lock index 7264779afb..7c3415dc4c 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "40231755d4dc80d8a23901402b42df4a", + "content-hash": "4fd078c5f4c652e6b07c639e275b520c", "packages": [ { "name": "adhocore/jwt", @@ -1079,16 +1079,16 @@ }, { "name": "open-runtimes/sdk-for-php", - "version": "0.10.1", + "version": "0.11.1", "source": { "type": "git", "url": "https://github.com/open-runtimes/sdk-for-php.git", - "reference": "2a83df23a377d846a6a57e2146c485c4be706512" + "reference": "2db10da2fa7163d096bfd8343a44ae99a2852527" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/open-runtimes/sdk-for-php/zipball/2a83df23a377d846a6a57e2146c485c4be706512", - "reference": "2a83df23a377d846a6a57e2146c485c4be706512", + "url": "https://api.github.com/repos/open-runtimes/sdk-for-php/zipball/2db10da2fa7163d096bfd8343a44ae99a2852527", + "reference": "2db10da2fa7163d096bfd8343a44ae99a2852527", "shasum": "" }, "require": { @@ -1113,12 +1113,12 @@ "license": [ "MIT" ], - "description": "PHP SDK for the Open Runtimes orchestrator Jobs API.", + "description": "PHP SDK for the Open Runtimes orchestrator: jobs, deployments, sandboxes, and pools.", "support": { "issues": "https://github.com/open-runtimes/sdk-for-php/issues", - "source": "https://github.com/open-runtimes/sdk-for-php/tree/0.10.1" + "source": "https://github.com/open-runtimes/sdk-for-php/tree/0.11.1" }, - "time": "2026-07-31T13:09:22+00:00" + "time": "2026-08-19T12:49:14+00:00" }, { "name": "open-telemetry/api", @@ -3144,6 +3144,54 @@ }, "time": "2026-07-23T07:34:27+00:00" }, + { + "name": "utopia-php/balancer", + "version": "0.4.1", + "source": { + "type": "git", + "url": "https://github.com/utopia-php/balancer.git", + "reference": "7fc8922da3e381c227cd88435cb12b17040c6ee1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/utopia-php/balancer/zipball/7fc8922da3e381c227cd88435cb12b17040c6ee1", + "reference": "7fc8922da3e381c227cd88435cb12b17040c6ee1", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "utopia-php/telemetry": "^0.4.0" + }, + "require-dev": { + "laravel/pint": "1.2.*", + "phpstan/phpstan": "^1.8", + "phpunit/phpunit": "^9.3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Utopia\\Balancer\\": "src/Balancer" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "A simple library to balance choices between multiple options.", + "keywords": [ + "balancer", + "balancing", + "framework", + "php", + "upf", + "utopia" + ], + "support": { + "issues": "https://github.com/utopia-php/balancer/issues", + "source": "https://github.com/utopia-php/balancer/tree/0.4.1" + }, + "time": "2026-08-13T19:36:49+00:00" + }, { "name": "utopia-php/cache", "version": "4.0.2", @@ -5068,16 +5116,16 @@ }, { "name": "utopia-php/vcs", - "version": "5.1.2", + "version": "5.2.2", "source": { "type": "git", - "url": "git@github.com:utopia-php/vcs.git", - "reference": "abdb5763221d7e4900174c280244f83638e3133e" + "url": "https://github.com/utopia-php/vcs.git", + "reference": "758eb3ab3c32a607b5aca78b1c9bae4ab1ba9b6e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/vcs/zipball/abdb5763221d7e4900174c280244f83638e3133e", - "reference": "abdb5763221d7e4900174c280244f83638e3133e", + "url": "https://api.github.com/repos/utopia-php/vcs/zipball/758eb3ab3c32a607b5aca78b1c9bae4ab1ba9b6e", + "reference": "758eb3ab3c32a607b5aca78b1c9bae4ab1ba9b6e", "shasum": "" }, "require": { @@ -5128,10 +5176,10 @@ "vcs" ], "support": { - "source": "https://github.com/utopia-php/vcs/tree/5.1.2", + "source": "https://github.com/utopia-php/vcs/tree/5.2.2", "issues": "https://github.com/utopia-php/vcs/issues" }, - "time": "2026-08-07T12:32:15+00:00" + "time": "2026-08-19T14:01:44+00:00" }, { "name": "utopia-php/websocket", diff --git a/docker-compose.yml b/docker-compose.yml index 09d477eb44..abb56e3c21 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -210,6 +210,8 @@ services: - _APP_VCS_BITBUCKET_CLIENT_ID - _APP_VCS_BITBUCKET_CLIENT_SECRET - _APP_VCS_BITBUCKET_WEBHOOK_SECRET + - _APP_VCS_ORIGIN_CLIENT_ID + - _APP_VCS_ORIGIN_PRIVATE_KEY - _APP_VCS_WEBHOOK_URL - _APP_MIGRATIONS_FIREBASE_CLIENT_ID - _APP_MIGRATIONS_FIREBASE_CLIENT_SECRET @@ -428,6 +430,8 @@ services: - _APP_VCS_BITBUCKET_CLIENT_ID - _APP_VCS_BITBUCKET_CLIENT_SECRET - _APP_VCS_BITBUCKET_WEBHOOK_SECRET + - _APP_VCS_ORIGIN_CLIENT_ID + - _APP_VCS_ORIGIN_PRIVATE_KEY - _APP_VCS_WEBHOOK_URL - _APP_BUILDS_VOLUME - _APP_JOBS_HOST @@ -708,6 +712,8 @@ services: - _APP_VCS_BITBUCKET_CLIENT_ID - _APP_VCS_BITBUCKET_CLIENT_SECRET - _APP_VCS_BITBUCKET_WEBHOOK_SECRET + - _APP_VCS_ORIGIN_CLIENT_ID + - _APP_VCS_ORIGIN_PRIVATE_KEY - _APP_VCS_WEBHOOK_URL - _APP_FUNCTIONS_TIMEOUT - _APP_SITES_TIMEOUT @@ -1500,7 +1506,7 @@ services: options: max-file: "5" max-size: 10m - image: ghcr.io/open-runtimes/orchestrator/jobs-service:0.18.0 + image: ghcr.io/open-runtimes/orchestrator/jobs-service:1.3.0 restart: unless-stopped user: root networks: diff --git a/src/Appwrite/AvatarPhotos/Photo.php b/src/Appwrite/AvatarPhotos/Photo.php new file mode 100644 index 0000000000..e46067bc68 --- /dev/null +++ b/src/Appwrite/AvatarPhotos/Photo.php @@ -0,0 +1,90 @@ +setAllowRedirects(true) + ->setConnectTimeout(static::CONNECT_TIMEOUT) + ->setTimeout(static::REQUEST_TIMEOUT) + ->fetch($url); + } catch (\Throwable) { + return null; + } + + if ($response->getStatusCode() !== 200) { + return null; + } + + $body = $response->getBody(); + + return empty($body) ? null : $body; + } +} diff --git a/src/Appwrite/AvatarPhotos/Providers/Fallback.php b/src/Appwrite/AvatarPhotos/Providers/Fallback.php new file mode 100644 index 0000000000..cc2bcbe030 --- /dev/null +++ b/src/Appwrite/AvatarPhotos/Providers/Fallback.php @@ -0,0 +1,78 @@ + 0 ? $width : 256; + $height = $height > 0 ? $height : 256; + + // Generate an SVG silhouette and rasterise it with Imagick so the + // caller always receives a PNG regardless of whether SVG support is + // available in the client. + $svg = $this->buildSvg($width, $height); + + if (\extension_loaded('imagick')) { + try { + $imagick = new \Imagick(); + $imagick->setBackgroundColor(new \ImagickPixel('transparent')); + $imagick->readImageBlob($svg); + $imagick->setImageFormat('png'); + $imagick->resizeImage($width, $height, \Imagick::FILTER_LANCZOS, 1); + return $imagick->getImageBlob(); + } catch (\Throwable) { + // Fall through to raw SVG on Imagick failure. + } + } + + // Last resort: return the SVG bytes directly. The HTTP action sets + // the content-type header to image/png, so this branch should be + // considered a degraded path. + return $svg; + } + + /** + * Build the SVG source for the fallback silhouette. + */ + private function buildSvg(int $width, int $height): string + { + return << + + + + + + +SVG; + } +} diff --git a/src/Appwrite/AvatarPhotos/Providers/Gravatar.php b/src/Appwrite/AvatarPhotos/Providers/Gravatar.php new file mode 100644 index 0000000000..a4985fdf60 --- /dev/null +++ b/src/Appwrite/AvatarPhotos/Providers/Gravatar.php @@ -0,0 +1,45 @@ +getAttribute('email', '')); + } + + public function get(Document $user, int $width, int $height, string $rating): ?string + { + $email = $user->getAttribute('email', ''); + $hash = \hash('sha256', \strtolower(\trim($email))); + + // Use 'd=404' so Gravatar returns HTTP 404 instead of a generic image + // when the user has no custom avatar — letting us fall through to the + // next provider. + $url = self::BASE_URL . $hash . '?' . \http_build_query([ + 's' => \max($width, $height) > 0 ? \max($width, $height) : 256, + 'd' => '404', + 'r' => $rating, + ]); + + return $this->fetch($url); + } +} diff --git a/src/Appwrite/AvatarPhotos/Providers/Initials.php b/src/Appwrite/AvatarPhotos/Providers/Initials.php new file mode 100644 index 0000000000..3bbfdd2462 --- /dev/null +++ b/src/Appwrite/AvatarPhotos/Providers/Initials.php @@ -0,0 +1,172 @@ + '#FD366E'], // Pink + ['background' => '#FE9567'], // Orange + ['background' => '#7C67FE'], // Purple + ['background' => '#68A3FE'], // Blue + ['background' => '#85DBD8'], // Mint + ]; + + public function __construct( + private readonly string $background = '', + ) { + } + + public function getName(): string + { + return 'initials'; + } + + public function supports(Document $user): bool + { + return !empty(\trim($this->getLabel($user))); + } + + public function get(Document $user, int $width, int $height, string $rating): ?string + { + if (!\extension_loaded('imagick')) { + return null; + } + + $name = $this->getLabel($user); + + // Nothing printable to draw — bail out so the static fallback can be + // used instead. The standalone endpoint has no such fallback and keeps + // rendering a plain coloured square, which is why this check lives + // here and not in render(). + if (empty($this->getInitials($name))) { + return null; + } + + return $this->render($name, $width, $height); + } + + /** + * Render the initials of an arbitrary label as a PNG. + * + * @param string $name Label to derive the initials from. + * @param int $width Output width in pixels; defaults when not positive. + * @param int $height Output height in pixels; defaults when not positive. + * @return string Raw PNG bytes. + */ + public function render(string $name, int $width, int $height): string + { + $initials = $this->getInitials($name); + + $width = $width > 0 ? $width : self::DEFAULT_SIZE; + $height = $height > 0 ? $height : self::DEFAULT_SIZE; + + $bg = !empty($this->background) + ? '#' . \ltrim($this->background, '#') + : $this->getTheme($initials); + + $image = new Imagick(); + $punch = new Imagick(); + $draw = new ImagickDraw(); + + $fontSize = \min($width, $height) / 2; + + $punch->newImage($width, $height, 'transparent'); + + // Providers live at src/Appwrite/AvatarPhotos/Providers, four levels + // below the project root — same walk-up as Avatars\Http\Action. + $fontPath = \dirname(__DIR__, 4) . self::FONT_PATH; + $draw->setFont($fontPath); + $image->setFont($fontPath); + + $draw->setFillColor(new ImagickPixel('black')); + $draw->setFontSize($fontSize); + $draw->setTextAlignment(Imagick::ALIGN_CENTER); + $draw->annotation($width / 1.97, ($height / 2) + ($fontSize / 3), $initials); + + $punch->drawImage($draw); + $punch->negateImage(true, Imagick::CHANNEL_ALPHA); + + $image->newImage($width, $height, $bg); + $image->setImageFormat('png'); + $image->compositeImage($punch, Imagick::COMPOSITE_COPYOPACITY, 0, 0); + + return $image->getImageBlob(); + } + + /** + * First letter of the first two words, skipping words that do not start + * with an alphanumeric character. Underscores stand in for spaces when the + * label has none. + */ + private function getInitials(string $name): string + { + $words = \explode(' ', \strtoupper($name)); + // Fallback: split on underscores when there is no space + $words = (\count($words) === 1) ? \explode('_', \strtoupper($name)) : $words; + + $initials = ''; + + foreach ($words as $key => $w) { + if (\ctype_alnum($w[0] ?? '')) { + $initials .= $w[0]; + + if ($key === 1) { + break; + } + } + } + + return $initials; + } + + /** + * Background colour for a set of initials. Derived from the initials so the + * same label always gets the same colour. + */ + private function getTheme(string $initials): string + { + $code = 0; + + foreach (\str_split($initials) as $char) { + $code += \ord($char); + } + + $rand = (int) \substr((string) $code, -1); + $rand = ($rand > \count($this->themes) - 1) ? $rand % \count($this->themes) : $rand; + + return $this->themes[$rand]['background']; + } + + /** + * Text the initials are derived from — the display name, falling back to + * the email address when the user has not set one. + */ + private function getLabel(Document $user): string + { + $name = $user->getAttribute('name', ''); + + return !empty($name) ? $name : $user->getAttribute('email', ''); + } +} diff --git a/src/Appwrite/AvatarPhotos/Providers/Libavatar.php b/src/Appwrite/AvatarPhotos/Providers/Libavatar.php new file mode 100644 index 0000000000..e5100c809e --- /dev/null +++ b/src/Appwrite/AvatarPhotos/Providers/Libavatar.php @@ -0,0 +1,49 @@ +getAttribute('email', '')); + } + + public function get(Document $user, int $width, int $height, string $rating): ?string + { + $email = $user->getAttribute('email', ''); + + // Libravatar supports both SHA-256 and MD5; use MD5 for widest + // compatibility with older instances. + $hash = \md5(\strtolower(\trim($email))); + + $url = self::BASE_URL . $hash . '?' . \http_build_query([ + 's' => \max($width, $height) > 0 ? \max($width, $height) : 256, + 'd' => '404', + 'r' => $rating, + ]); + + return $this->fetch($url); + } +} diff --git a/src/Appwrite/Deployment/Deployments.php b/src/Appwrite/Deployment/Deployments.php index 92d3c56150..79c6e3ddb9 100644 --- a/src/Appwrite/Deployment/Deployments.php +++ b/src/Appwrite/Deployment/Deployments.php @@ -7,6 +7,7 @@ use Appwrite\Extend\Exception; use OpenRuntimes\Orchestrator\Enum\CallbackEvent; use OpenRuntimes\Orchestrator\Enum\ReadFormat; use OpenRuntimes\Orchestrator\Jobs; +use OpenRuntimes\Orchestrator\Model\Artifact\CloneArtifact; use OpenRuntimes\Orchestrator\Model\Artifact\DownloadArtifact; use OpenRuntimes\Orchestrator\Model\Artifact\ReadArtifact; use OpenRuntimes\Orchestrator\Model\Artifact\StatArtifact; @@ -21,6 +22,7 @@ use Utopia\Database\Helpers\Permission; use Utopia\Database\Helpers\Role; use Utopia\Database\Query; use Utopia\System\System; +use Utopia\VCS\Adapter\Git; /** * Owns a deployment's lifecycle: upload bookkeeping, creating it and @@ -133,6 +135,41 @@ readonly class Deployments return $this->submit($resource, $deployment, ['url' => $url, 'subdir' => $rootDirectory, 'headers' => $headers]); } + /** + * Same as createFromUpload(), but builds from a repository on a VCS + * provider: a presigned archive URL when the provider hands those out, or + * a git clone through the jobs-service's clone artifact when the provider + * serves content over the git protocol only (Origin). + * + * @param string $ref Branch, tag, or commit the deployment builds from + */ + public function createFromVcs( + Document $resource, + Document $deployment, + Git $vcs, + string $owner, + string $repository, + string $ref, + string $rootDirectory = '', + ): Document { + if ($vcs->supportsRepositoryArchives()) { + return $this->createFromUrl( + $resource, + $deployment, + $vcs->getRepositoryPresignedUrl($owner, $repository, $ref), + $rootDirectory, + $vcs->getRepositoryPresignedUrlHeaders(), + ); + } + + return $this->submit($resource, $deployment, [ + 'clone' => $vcs->getRepositoryCloneUrl($owner, $repository), + 'ref' => $ref, + 'subdir' => $rootDirectory, + 'headers' => $vcs->getRepositoryCloneHeaders(), + ]); + } + private function submit(Document $resource, Document $deployment, ?array $source): Document { // The caller may have been holding this deployment for a while (the @@ -317,15 +354,25 @@ readonly class Deployments $protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS') === 'disabled' ? 'http' : 'https'; $endpoint = System::getEnv('_APP_JOBS_ENDPOINT', "$protocol://{$platform['apiHostname']}"); - // Source artifacts, both ending in /mnt/code/source: - // - remote tarball ($source): templates (public codeload URL) and VCS - // (a short-lived presigned URL). Git-forge archives wrap the tree in - // a "{repo}-{ref}/" root the caller can't predict, so strip drops it - // and subdir then extracts just the rootDirectory from the unwrapped - // tree. Uploaded tarballs (the else branch) are flat — no strip. + // Source artifacts, all ending in /mnt/code/source: + // - remote tarball ($source with url): templates (public codeload URL) + // and VCS (a short-lived presigned URL). Git-forge archives wrap the + // tree in a "{repo}-{ref}/" root the caller can't predict, so strip + // drops it and subdir then extracts just the rootDirectory from the + // unwrapped tree. Uploaded tarballs (the else branch) are flat — no + // strip. + // - git clone ($source with clone): a provider without archive + // downloads; the sidecar clones over Git HTTPS and checks the tree + // out directly, so there is no archive to unarchive — or to stat, + // which is why this path reports no sourceSize. // - otherwise: the deployment's uploaded tarball, fetched from Appwrite // over a presigned GET (manual upload / duplicate). - if ($source !== null) { + if (isset($source['clone'])) { + $subdir = \trim($source['subdir'] ?? '', '/'); + $sourceArtifacts = [ + new CloneArtifact(id: 'source', in: $source['clone'], out: 'source', ref: $source['ref'] ?? '', subdir: $subdir, headers: $source['headers'] ?? []), + ]; + } elseif ($source !== null) { $subdir = \trim($source['subdir'] ?? '', '/'); $sourceArtifacts = [ new DownloadArtifact(id: 'source', in: $source['url'], out: 'source.tar.gz', headers: $source['headers'] ?? []), diff --git a/src/Appwrite/Deployment/GitAction.php b/src/Appwrite/Deployment/GitAction.php index 03d679b2ba..8d709a0a2e 100644 --- a/src/Appwrite/Deployment/GitAction.php +++ b/src/Appwrite/Deployment/GitAction.php @@ -86,7 +86,7 @@ final class GitAction ]); $previewUrl = $isSite && !$rule->isEmpty() ? "{$protocol}://" . $rule->getAttribute('domain', '') : ''; - $comment = new Comment($platform); + $comment = new Comment($platform, $vcs->supportsCommentImages()); $comment->parseComment($vcs->getComment($owner, $repositoryName, $commentId)); $comment->addBuild($project, $resource, $isSite ? 'site' : 'function', $status, $deployment->getId(), ['type' => 'logs'], $previewUrl); $vcs->updateComment($owner, $repositoryName, $commentId, $comment->generateComment()); diff --git a/src/Appwrite/Platform/Modules/Avatars/Http/Initials/Get.php b/src/Appwrite/Platform/Modules/Avatars/Http/Initials/Get.php index 4808cb7267..d5f100e96f 100644 --- a/src/Appwrite/Platform/Modules/Avatars/Http/Initials/Get.php +++ b/src/Appwrite/Platform/Modules/Avatars/Http/Initials/Get.php @@ -2,6 +2,7 @@ namespace Appwrite\Platform\Modules\Avatars\Http\Initials; +use Appwrite\AvatarPhotos\Providers\Initials; use Appwrite\Platform\Modules\Avatars\Http\Action; use Appwrite\SDK\AuthType; use Appwrite\SDK\ContentType; @@ -9,9 +10,6 @@ use Appwrite\SDK\Method; use Appwrite\SDK\MethodType; use Appwrite\SDK\Response as SDKResponse; use Appwrite\Utopia\Response; -use Imagick; -use ImagickDraw; -use ImagickPixel; use Utopia\Database\Document; use Utopia\Platform\Action as UtopiaAction; use Utopia\Platform\Scope\HTTP; @@ -64,65 +62,13 @@ class Get extends Action public function action(string $name, int $width, int $height, string $background, Response $response, Document $user) { - $themes = [ - ['background' => '#FD366E'], // Default (Pink) - ['background' => '#FE9567'], // Orange - ['background' => '#7C67FE'], // Purple - ['background' => '#68A3FE'], // Blue - ['background' => '#85DBD8'], // Mint - ]; - $name = (!empty($name)) ? $name : $user->getAttribute('name', $user->getAttribute('email', '')); - $words = \explode(' ', \strtoupper($name)); - // if there is no space, try to split by `_` underscore - $words = (count($words) == 1) ? \explode('_', \strtoupper($name)) : $words; - $initials = ''; - $code = 0; - - foreach ($words as $key => $w) { - if (ctype_alnum($w[0] ?? '')) { - $initials .= $w[0]; - $code += ord($w[0]); - - if ($key == 1) { - break; - } - } - } - - $rand = (int) \substr((string) $code, -1); - - $rand = ($rand > \count($themes) - 1) ? $rand % \count($themes) : $rand; - - $background = (!empty($background)) ? '#' . $background : $themes[$rand]['background']; - - $image = new Imagick(); - $punch = new Imagick(); - $draw = new ImagickDraw(); - $fontSize = \min($width, $height) / 2; - - $punch->newImage($width, $height, 'transparent'); - - $draw->setFont($this->getAppRoot() . '/app/assets/fonts/inter-v8-latin-regular.woff2'); - $image->setFont($this->getAppRoot() . '/app/assets/fonts/inter-v8-latin-regular.woff2'); - - $draw->setFillColor(new ImagickPixel('black')); - $draw->setFontSize($fontSize); - - $draw->setTextAlignment(Imagick::ALIGN_CENTER); - $draw->annotation($width / 1.97, ($height / 2) + ($fontSize / 3), $initials); - - $punch->drawImage($draw); - $punch->negateImage(true, Imagick::CHANNEL_ALPHA); - - $image->newImage($width, $height, $background); - $image->setImageFormat("png"); - $image->compositeImage($punch, Imagick::COMPOSITE_COPYOPACITY, 0, 0); + $image = (new Initials($background))->render($name, $width, $height); $response ->addHeader('Cache-Control', 'private, max-age=3888000') // 45 days ->setContentType('image/png') - ->file($image->getImageBlob()); + ->file($image); } } diff --git a/src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php b/src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php new file mode 100644 index 0000000000..7428deb54b --- /dev/null +++ b/src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php @@ -0,0 +1,170 @@ +setHttpMethod(UtopiaAction::HTTP_REQUEST_METHOD_GET) + ->setHttpPath('/v1/avatars/photo') + ->desc('Get user photo') + ->groups(['api', 'avatars']) + ->label('scope', 'avatars.read') + ->label('sdk', new Method( + namespace: 'avatars', + group: null, + name: 'getPhoto', + description: <<param('width', 256, new Range(0, 2000), 'Output image width in pixels. Pass an integer between 0 and 2000. Defaults to 256.', true) + ->param('height', 256, new Range(0, 2000), 'Output image height in pixels. Pass an integer between 0 and 2000. Defaults to 256.', true) + ->param('quality', 100, new Range(0, 100), 'Output image quality between 0 and 100. Defaults to 100.', true) + ->param('output', 'png', new WhiteList(['png', 'jpg', 'webp'], true), 'Output image format. Defaults to \'png\'.', true) + ->param('rating', 'g', new WhiteList(['g', 'pg', 'r', 'x'], true), 'Maximum image rating to fetch from Gravatar/Libravatar. Defaults to \'g\'.', true) + ->inject('response') + ->inject('user') + ->callback($this->action(...)); + } + + public function action( + int $width, + int $height, + int $quality, + string $output, + string $rating, + Response $response, + Document $user, + ): void { + // ------------------------------------------------------------------- + // Priority 1: OAuth2 session photo + // TODO: Resolve profile photo from the user's active OAuth2 token. + // Each OAuth2 provider (Google, GitHub, …) exposes a profile- + // picture URL. Add it as a provider at the front of the list. + // Track in: https://github.com/appwrite/appwrite/issues/TODO + // ------------------------------------------------------------------- + $providers = [ + new Gravatar(), + new Libavatar(), + new Initials(), + new Fallback(), + ]; + + $balancer = new Balancer(new First()); + + foreach ($providers as $provider) { + $balancer->addOption(new Option(['provider' => $provider])); + } + + // Skip providers that lack the data they need — no email means no + // Gravatar lookup — so we never pay for a doomed network round-trip. + $balancer->addFilter(function (Option $option) use ($user) { + /** @var Photo $provider */ + $provider = $option->getState('provider'); + + return $provider->supports($user); + }); + + // A provider that came up empty is out of the running; without this the + // First algorithm would hand back the same option forever. + $balancer->addFilter(fn (Option $option) => !$option->getState('attempted', false)); + + $data = null; + + while (($option = $balancer->run()) !== null) { + $option->setState('attempted', true); + + /** @var Photo $provider */ + $provider = $option->getState('provider'); + + $data = $provider->get($user, $width, $height, $rating); + + if ($data !== null) { + break; + } + } + + if ($data === null) { + throw new Exception(Exception::AVATAR_NOT_FOUND); + } + + $contentType = match ($output) { + 'jpg' => 'image/jpeg', + 'webp' => 'image/webp', + default => 'image/png', + }; + + $response + ->addHeader('Cache-Control', 'private, no-store') // photo can change at any time + ->setContentType($contentType) + ->file($this->process($data, $width, $height, $quality, $output)); + } + + /** + * Resize and re-encode raw image bytes. + */ + private function process(string $raw, int $width, int $height, int $quality, string $output): string + { + if (!\extension_loaded('imagick') || empty($raw)) { + return $raw; + } + + try { + $image = new Image($raw); + + if ($width > 0 || $height > 0) { + $image->crop( + $width > 0 ? $width : 256, + $height > 0 ? $height : 256, + ); + } + + return $image->output($output, $quality); + } catch (\Throwable) { + return $raw; + } + } +} diff --git a/src/Appwrite/Platform/Modules/Avatars/Services/Http.php b/src/Appwrite/Platform/Modules/Avatars/Services/Http.php index c462b25ca9..e6348fc5ad 100644 --- a/src/Appwrite/Platform/Modules/Avatars/Services/Http.php +++ b/src/Appwrite/Platform/Modules/Avatars/Services/Http.php @@ -8,6 +8,7 @@ use Appwrite\Platform\Modules\Avatars\Http\Favicon\Get as GetFavicon; use Appwrite\Platform\Modules\Avatars\Http\Flags\Get as GetFlag; use Appwrite\Platform\Modules\Avatars\Http\Image\Get as GetImage; use Appwrite\Platform\Modules\Avatars\Http\Initials\Get as GetInitials; +use Appwrite\Platform\Modules\Avatars\Http\Photo\Get as GetPhoto; use Appwrite\Platform\Modules\Avatars\Http\QR\Get as GetQR; use Appwrite\Platform\Modules\Avatars\Http\Screenshots\Get as GetScreenshot; use Utopia\Platform\Service; @@ -26,5 +27,6 @@ class Http extends Service $this->addAction(GetQR::getName(), new GetQR()); $this->addAction(GetInitials::getName(), new GetInitials()); $this->addAction(GetScreenshot::getName(), new GetScreenshot()); + $this->addAction(GetPhoto::getName(), new GetPhoto()); } } diff --git a/src/Appwrite/Platform/Modules/Compute/Base.php b/src/Appwrite/Platform/Modules/Compute/Base.php index fb3e5bd8a1..b9cf1948d5 100644 --- a/src/Appwrite/Platform/Modules/Compute/Base.php +++ b/src/Appwrite/Platform/Modules/Compute/Base.php @@ -175,12 +175,14 @@ class Base extends Action // git write and then hands the build to the jobs-service itself. if ($template->isEmpty()) { $ref = $deployment->getAttribute('providerCommitHash') ?: $deployment->getAttribute('providerBranch'); - $deployment = $deployments->createFromUrl( + $deployment = $deployments->createFromVcs( $function, $deployment, - $vcs->getRepositoryPresignedUrl($owner, $repositoryName, $ref), + $vcs, + $owner, + $repositoryName, + $ref, $function->getAttribute('providerRootDirectory', ''), - $vcs->getRepositoryPresignedUrlHeaders(), ); } else { $deployment = $dbForProject->createDocument('deployments', new Document([ @@ -400,12 +402,14 @@ class Base extends Action // pushes go through the Builds worker (same split as redeployVcsFunction). if ($template->isEmpty()) { $ref = $deployment->getAttribute('providerCommitHash') ?: $deployment->getAttribute('providerBranch'); - $deployment = $deployments->createFromUrl( + $deployment = $deployments->createFromVcs( $site, $deployment, - $vcs->getRepositoryPresignedUrl($owner, $repositoryName, $ref), + $vcs, + $owner, + $repositoryName, + $ref, $site->getAttribute('providerRootDirectory', ''), - $vcs->getRepositoryPresignedUrlHeaders(), ); } else { $publisherForBuilds->enqueue(new BuildMessage( diff --git a/src/Appwrite/Platform/Modules/Console/Http/Variables/Get.php b/src/Appwrite/Platform/Modules/Console/Http/Variables/Get.php index 9adf5ebf9a..7474866438 100644 --- a/src/Appwrite/Platform/Modules/Console/Http/Variables/Get.php +++ b/src/Appwrite/Platform/Modules/Console/Http/Variables/Get.php @@ -7,6 +7,7 @@ use Appwrite\SDK\ContentType; use Appwrite\SDK\Method; use Appwrite\SDK\Response as SDKResponse; use Appwrite\Utopia\Response; +use Appwrite\Vcs\Factory as VcsFactory; use Utopia\Database\Database; use Utopia\Database\Document; use Utopia\Domains\Domain; @@ -47,6 +48,7 @@ class Get extends Action contentType: ContentType::JSON )) ->inject('vcsProviders') + ->inject('vcsFactory') ->inject('response') ->inject('platform') ->inject('dbForProject') @@ -55,6 +57,7 @@ class Get extends Action public function action( callable $vcsProviders, + VcsFactory $vcsFactory, Response $response, array $platform, Database $dbForProject @@ -71,7 +74,20 @@ class Get extends Action $isDomainEnabled = $isAAAAValid || $isAValid || $isCNAMEValid; - $isVcsEnabled = !empty($vcsProviders()); + $providers = $vcsProviders(); + $isVcsEnabled = !empty($providers); + + $providersWithRepositoryCreation = []; + $providersWithPublicRepositories = []; + foreach ($providers as $provider) { + $adapter = $vcsFactory->fromProvider($provider); + if ($adapter->supportsRepositoryCreation()) { + $providersWithRepositoryCreation[] = $provider; + } + if ($adapter->supportsPublicRepositories()) { + $providersWithPublicRepositories[] = $provider; + } + } $isAssistantEnabled = !empty(System::getEnv('_APP_ASSISTANT_OPENAI_API_KEY', '')); @@ -87,7 +103,9 @@ class Get extends Action '_APP_COMPUTE_SIZE_LIMIT' => +System::getEnv('_APP_COMPUTE_SIZE_LIMIT'), '_APP_USAGE_STATS' => System::getEnv('_APP_USAGE_STATS'), '_APP_VCS_ENABLED' => $isVcsEnabled, - '_APP_VCS_PROVIDERS' => $vcsProviders(), + '_APP_VCS_PROVIDERS' => $providers, + '_APP_VCS_PROVIDERS_WITH_REPOSITORY_CREATION' => $providersWithRepositoryCreation, + '_APP_VCS_PROVIDERS_WITH_PUBLIC_REPOSITORIES' => $providersWithPublicRepositories, '_APP_DOMAIN_ENABLED' => $isDomainEnabled, '_APP_ASSISTANT_ENABLED' => $isAssistantEnabled, '_APP_DOMAIN_SITES' => $platform['sitesDomain'], diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php index 55616a18b7..5f98bbf24a 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php @@ -157,12 +157,14 @@ class Create extends Action $github = $vcsFactory->fromInstallation($installation); $ref = $deployment->getAttribute('providerCommitHash') ?: $deployment->getAttribute('providerBranch'); - $deployment = $deployments->createFromUrl( + $deployment = $deployments->createFromVcs( $function, $deployment, - $github->getRepositoryPresignedUrl($owner, $repository, $ref), + $github, + $owner, + $repository, + $ref, $deployment->getAttribute('providerRootDirectory', ''), - $github->getRepositoryPresignedUrlHeaders(), ); } else { // Public template repo: providerBranch holds the resolved ref, diff --git a/src/Appwrite/Platform/Modules/Functions/Workers/Builds.php b/src/Appwrite/Platform/Modules/Functions/Workers/Builds.php index 776f0adae6..16fe9f66be 100644 --- a/src/Appwrite/Platform/Modules/Functions/Workers/Builds.php +++ b/src/Appwrite/Platform/Modules/Functions/Workers/Builds.php @@ -401,12 +401,14 @@ class Builds extends Action // jobs-service like any other VCS commit, via the same Deployments // service the HTTP endpoints use. $ref = $deployment->getAttribute('providerCommitHash') ?: $branchName; - $deployments->createFromUrl( + $deployments->createFromVcs( $resource, $deployment, - $providerAdapter->getRepositoryPresignedUrl($cloneOwner, $cloneRepository, $ref), + $providerAdapter, + $cloneOwner, + $cloneRepository, + $ref, $resource->getAttribute('providerRootDirectory', ''), - $providerAdapter->getRepositoryPresignedUrlHeaders(), ); Console::execute('rm -rf ' . \escapeshellarg('/tmp/builds/' . $deploymentId), '', $stdout, $stderr); diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php index 9dc11db43e..f9a81f494e 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php @@ -182,12 +182,14 @@ class Create extends Action $vcs = $vcsFactory->fromInstallation($installation); $ref = $deployment->getAttribute('providerCommitHash') ?: $deployment->getAttribute('providerBranch'); - $deployment = $deployments->createFromUrl( + $deployment = $deployments->createFromVcs( $site, $deployment, - $vcs->getRepositoryPresignedUrl($owner, $repository, $ref), + $vcs, + $owner, + $repository, + $ref, $deployment->getAttribute('providerRootDirectory', ''), - $vcs->getRepositoryPresignedUrlHeaders(), ); } else { // Public template repo: providerBranch holds the resolved ref, diff --git a/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php b/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php index 892f666cad..b89364fb45 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php @@ -395,12 +395,14 @@ trait Deployment // The Deployments service is built per repository: a webhook fans out to // many tenant projects, each with its own database. $deployment = $authorization->skip(fn () => $deploymentsFactory($dbForProject, $project) - ->createFromUrl( + ->createFromVcs( $resource, $deployment, - $vcs->getRepositoryPresignedUrl($providerRepositoryOwner, $providerRepositoryName, $providerCommitHash), + $vcs, + $providerRepositoryOwner, + $providerRepositoryName, + $providerCommitHash, $resource->getAttribute('providerRootDirectory', ''), - $vcs->getRepositoryPresignedUrlHeaders(), )); if ($resource->getCollection() === 'sites') { diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Installations/Repositories/Create.php b/src/Appwrite/Platform/Modules/VCS/Http/Installations/Repositories/Create.php index d8dae58f3b..7f29f0b005 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Installations/Repositories/Create.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Installations/Repositories/Create.php @@ -112,6 +112,11 @@ class Create extends Action } else { $providerInstallationId = $installation->getAttribute('providerInstallationId'); $vcs = $vcsFactory->fromInstallation($installation); + + if (!$vcs->supportsRepositoryCreation()) { + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'VCS provider does not support repository creation: ' . $provider); + } + $owner = !empty($providerNamespace) ? $providerNamespace : $vcs->getOwnerName($providerInstallationId); try { diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Origin/Authorize/Get.php b/src/Appwrite/Platform/Modules/VCS/Http/Origin/Authorize/Get.php new file mode 100644 index 0000000000..58c12103ac --- /dev/null +++ b/src/Appwrite/Platform/Modules/VCS/Http/Origin/Authorize/Get.php @@ -0,0 +1,123 @@ +setHttpMethod(Action::HTTP_REQUEST_METHOD_GET) + ->setHttpPath('/v1/vcs/origin/authorize') + ->desc('Create Origin app installation') + ->groups(['api', 'vcs']) + ->label('scope', 'vcs.read') + ->label('error', APP_VIEWS_DIR . '/general/error.phtml') + ->label('sdk', new Method( + namespace: 'vcs', + group: 'installations', + name: 'createOriginInstallation', + description: <<param('success', '', fn ($redirectValidator) => $redirectValidator, 'URL to redirect back to console after a successful installation attempt.', true, ['redirectValidator']) + ->param('failure', '', fn ($redirectValidator) => $redirectValidator, 'URL to redirect back to console after a failed installation attempt.', true, ['redirectValidator']) + ->inject('response') + ->inject('project') + ->inject('platform') + ->inject('vcsConfigured') + ->inject('vcsFactory') + ->callback($this->action(...)); + } + + public function action( + string $success, + string $failure, + Response $response, + Document $project, + array $platform, + callable $vcsConfigured, + VcsFactory $vcsFactory, + ) { + if (!$vcsConfigured('origin')) { + throw new Exception(Exception::GENERAL_SERVER_ERROR, 'This endpoint is not implemented on this server. Please configure VCS (Version Control System) variables in .env file.'); + } + + $projectId = $project->getId(); + + // The callback is public and Origin performs no token exchange, so the + // state carries an HMAC binding the redirect targets to this project. + $state = [ + 'projectId' => $projectId, + 'success' => $success, + 'failure' => $failure, + 'signature' => \hash_hmac('sha256', \json_encode([$projectId, $success, $failure]), System::getEnv('_APP_OPENSSL_KEY_V1', '')), + ]; + + $protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS') === 'disabled' ? 'http' : 'https'; + $callback = $protocol . '://' . ($platform['consoleHostname'] ?? '') . '/v1/vcs/origin/callback'; + + /** @var \Utopia\VCS\Adapter\Git\Origin $vcs */ + $vcs = $vcsFactory->fromProvider('origin'); + $installUrl = $vcs->getInstallUrl( + System::getEnv('_APP_VCS_ORIGIN_CLIENT_ID', ''), + self::SCOPES, + $callback, + \json_encode($state) ?: '' + ); + + $response + ->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0') + ->addHeader('Pragma', 'no-cache') + ->redirect($installUrl); + } +} diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Origin/Callback/Get.php b/src/Appwrite/Platform/Modules/VCS/Http/Origin/Callback/Get.php new file mode 100644 index 0000000000..6c51fa124e --- /dev/null +++ b/src/Appwrite/Platform/Modules/VCS/Http/Origin/Callback/Get.php @@ -0,0 +1,186 @@ +setHttpMethod(Action::HTTP_REQUEST_METHOD_GET) + ->setHttpPath('/v1/vcs/origin/callback') + ->desc('Get installation from Origin app') + ->groups(['api', 'vcs']) + ->label('scope', 'public') + ->label('error', APP_VIEWS_DIR . '/general/error.phtml') + ->param('installation_id', '', new Text(256, 0), 'Origin installation ID', true) + ->param('installation_receipt', '', new Text(8192, 0), 'Origin installation receipt JWT, signed by Cursor.', true) + ->param('state', '', new Text(2048, 0), 'Origin state. Contains info sent when starting the installation flow.', true) + ->inject('response') + ->inject('dbForPlatform') + ->inject('platform') + ->inject('vcsFactory') + ->callback($this->action(...)); + } + + public function action( + string $providerInstallationId, + string $installationReceipt, + string $state, + Response $response, + Database $dbForPlatform, + array $platform, + VcsFactory $vcsFactory, + ) { + if (empty($installationReceipt)) { + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Missing installation receipt. Please restart the installation from the Appwrite Console.'); + } + + // Authenticate the callback before trusting anything else on it: the + // endpoint is public and Origin performs no token exchange, so the + // EdDSA-signed receipt is the only proof the request came from Cursor. + /** @var \Utopia\VCS\Adapter\Git\Origin $vcs */ + $vcs = $vcsFactory->fromProvider('origin'); + + try { + $receiptClaims = $vcs->verifyReceipt($installationReceipt, System::getEnv('_APP_VCS_ORIGIN_CLIENT_ID', '')); + } catch (\Throwable $e) { + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Could not verify the Origin installation receipt. Please restart the installation from the Appwrite Console.'); + } + + // The receipt's subject is the authoritative installation id; a + // separately passed installation_id may only confirm it. + $receiptInstallationId = \strval($receiptClaims['sub'] ?? ''); + if (!empty($providerInstallationId) && $providerInstallationId !== $receiptInstallationId) { + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Receipt subject does not match the installation ID.'); + } + $providerInstallationId = $receiptInstallationId; + + // Cursor echoes the state given to the install URL as a receipt claim; + // accept a query parameter carrying the same value as a fallback. + $state = !empty($state) ? $state : \strval($receiptClaims['state'] ?? ''); + if (empty($state)) { + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Missing state parameter. Please restart the installation from the Appwrite Console.'); + } + + $state = \json_decode($state, true) ?? []; + $projectId = $state['projectId'] ?? ''; + $redirectFailure = $state['failure'] ?? ''; + + // The receipt authenticates Cursor, and this HMAC authenticates the + // Appwrite Console that started the flow -- without it anyone could + // attach an installation to an arbitrary projectId. + $signature = \hash_hmac('sha256', \json_encode([$projectId, $state['success'] ?? '', $redirectFailure]), System::getEnv('_APP_OPENSSL_KEY_V1', '')); + if (!\hash_equals($signature, $state['signature'] ?? '')) { + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Invalid state parameter. Please restart the installation from the Appwrite Console.'); + } + + $project = $dbForPlatform->getDocument('projects', $projectId); + + if ($project->isEmpty()) { + $this->failure($response, $redirectFailure, 'Project with the ID from state could not be found.', Exception::PROJECT_NOT_FOUND); + return; + } + + $region = $project->getAttribute('region', 'default'); + $protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS') === 'disabled' ? 'http' : 'https'; + $hostname = $platform['consoleHostname'] ?? ''; + + $defaultState = [ + 'success' => $protocol . '://' . $hostname . "/console/project-$region-$projectId/settings/git-installations", + 'failure' => $protocol . '://' . $hostname . "/console/project-$region-$projectId/settings/git-installations", + ]; + + $state = \array_merge($defaultState, \array_filter($state)); + $redirectSuccess = $state['success'] ?? ''; + $redirectFailure = $state['failure'] ?? ''; + + if (empty($providerInstallationId)) { + $this->failure($response, $redirectFailure, 'Origin installation ID is missing.'); + return; + } + + // The receipt names the workspace by its stable id; the owner slug the + // rest of the integration works with comes from the installation itself. + $organization = \strval($receiptClaims['namespace_id'] ?? ''); + try { + $adapter = $vcsFactory->fromInstallation(new Document([ + 'provider' => 'origin', + 'providerInstallationId' => $providerInstallationId, + ])); + $organization = $adapter->getOwnerName($providerInstallationId); + } catch (\Throwable $e) { + Console::warning('Failed to resolve Origin installation owner: ' . $e->getMessage()); + } + + $projectInternalId = $project->getSequence(); + + $installation = $dbForPlatform->findOne('installations', [ + Query::equal('providerInstallationId', [$providerInstallationId]), + Query::equal('projectInternalId', [$projectInternalId]), + Query::equal('provider', ['origin']), + ]); + + if ($installation->isEmpty()) { + $teamId = $project->getAttribute('teamId', ''); + + $installation = $dbForPlatform->createDocument('installations', new Document([ + '$id' => ID::unique(), + '$permissions' => $this->getPermissions($teamId, $projectId), + 'providerInstallationId' => $providerInstallationId, + 'projectId' => $projectId, + 'projectInternalId' => $projectInternalId, + 'provider' => 'origin', + 'organization' => $organization, + 'personal' => false, + ])); + } else { + $installation = $dbForPlatform->updateDocument('installations', $installation->getId(), new Document([ + 'organization' => $organization, + ])); + } + + $response + ->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0') + ->addHeader('Pragma', 'no-cache') + ->redirect($redirectSuccess); + } + + /** + * Redirect back to the console with an error, or throw when no redirect is available. + */ + private function failure(Response $response, string $redirect, string $error, string $type = Exception::GENERAL_ARGUMENT_INVALID): void + { + if (empty($redirect)) { + throw new Exception($type, $error); + } + + $separator = \str_contains($redirect, '?') ? '&' : '?'; + $response + ->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0') + ->addHeader('Pragma', 'no-cache') + ->redirect($redirect . $separator . \http_build_query(['error' => $error])); + } +} diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Origin/Events/Create.php b/src/Appwrite/Platform/Modules/VCS/Http/Origin/Events/Create.php new file mode 100644 index 0000000000..0c9b096e99 --- /dev/null +++ b/src/Appwrite/Platform/Modules/VCS/Http/Origin/Events/Create.php @@ -0,0 +1,395 @@ +|null + */ + protected static ?array $signingKeys = null; + + public static function getName() + { + return 'createVCSOriginEvent'; + } + + public function __construct() + { + $this + ->setHttpMethod(Action::HTTP_REQUEST_METHOD_POST) + ->setHttpPath('/v1/vcs/origin/events') + ->desc('Create event') + ->groups(['api', 'vcs']) + ->label('scope', 'public') + ->inject('vcsFactory') + ->inject('request') + ->inject('response') + ->inject('dbForPlatform') + ->inject('authorization') + ->inject('bus') + ->inject('getProjectDB') + ->inject('deploymentsFactory') + ->inject('platform') + ->callback($this->action(...)); + } + + public function action( + VcsFactory $vcsFactory, + Request $request, + Response $response, + Database $dbForPlatform, + Authorization $authorization, + Bus $bus, + callable $getProjectDB, + callable $deploymentsFactory, + array $platform + ) { + /** @var Origin $vcs */ + $vcs = $vcsFactory->fromProvider('origin'); + + $event = $request->getHeaderLine($vcs->getEventHeaderName(), ''); + Span::add('vcs.origin.event.name', $event); + + $payload = $request->getRawPayload(); + $signature = $request->getHeaderLine($vcs->getSignatureHeaderName(), ''); + $deliveryId = $request->getHeaderLine('webhook-id', ''); + $timestamp = $request->getHeaderLine('webhook-timestamp', ''); + + // Origin signs the SHA-256 of ".." + // with its own Ed25519 key, verified against its published JWKS rather + // than a shared secret. Stale timestamps are replays. + $valid = false; + if (!empty($deliveryId) && \ctype_digit($timestamp) && \abs(\time() - (int) $timestamp) <= 300) { + $signedContent = $deliveryId . '.' . $timestamp . '.' . $payload; + + foreach ($this->signingKeys($vcs) as $publicKey) { + if ($vcs->validateWebhookEvent($signedContent, $signature, $publicKey)) { + $valid = true; + break; + } + } + + // The key set may have rotated since it was cached. + if (!$valid) { + foreach ($this->signingKeys($vcs, refresh: true) as $publicKey) { + if ($vcs->validateWebhookEvent($signedContent, $signature, $publicKey)) { + $valid = true; + break; + } + } + } + } + + Span::add('vcs.origin.event.signature.valid', $valid); + + if (!$valid) { + throw new Exception(Exception::GENERAL_ACCESS_FORBIDDEN, 'Invalid webhook payload signature. The delivery could not be verified against Origin\'s published signing keys.'); + } + + // Origin delivers at least once and retries anything not acknowledged + // with a 2xx in time. Processing here is synchronous and can outlast + // that window, so claim the delivery id before doing the work - a + // retry of a delivery already being processed must not deploy again. + // TODO: acknowledge first and process asynchronously instead. + try { + $authorization->skip(fn () => $dbForPlatform->createDocument('vcsCommentLocks', new Document([ + '$id' => 'origin-delivery-' . $deliveryId, + ]))); + } catch (Duplicate) { + $response->json(['events' => [], 'duplicate' => true]); + return; + } + + $parsedPayloads = $vcs->getEvents($event, $payload); + + foreach ($parsedPayloads as $parsedPayload) { + match (true) { + $event === Origin::EVENT_PUSH => $this->handlePushEvent($parsedPayload, $vcsFactory, $dbForPlatform, $authorization, $bus, $getProjectDB, $platform, $deploymentsFactory), + \str_starts_with($event, Origin::EVENT_PULL_REQUEST . '.') => $this->handlePullRequestEvent($parsedPayload, $vcsFactory, $dbForPlatform, $authorization, $bus, $getProjectDB, $platform, $deploymentsFactory), + \str_starts_with($event, Origin::EVENT_INSTALLATION . '.') => $this->handleInstallationEvent($parsedPayload, $dbForPlatform, $authorization, $getProjectDB), + default => null, + }; + } + + $response->json(['events' => $parsedPayloads]); + } + + /** + * Origin's active signing keys, from the adapter, cached for the worker's + * lifetime - the adapter memoizes only per instance, and a new adapter is + * built for every delivery. + * + * @return array + */ + protected function signingKeys(Origin $vcs, bool $refresh = false): array + { + if (!$refresh && self::$signingKeys !== null) { + return self::$signingKeys; + } + + $keys = []; + + try { + $keys = $vcs->getSigningKeys($refresh); + } catch (\Throwable $e) { + Console::warning('Failed to fetch Origin signing keys: ' . $e->getMessage()); + } + + // Never cache an empty set - a fetch hiccup would reject deliveries + // until the worker restarts. + if (!empty($keys)) { + self::$signingKeys = $keys; + } + + return self::$signingKeys ?? []; + } + + protected function handleInstallationEvent( + array $parsedPayload, + Database $dbForPlatform, + Authorization $authorization, + callable $getProjectDB, + ) { + if ($parsedPayload['action'] !== 'deleted') { + return; + } + + $providerInstallationId = $parsedPayload['installationId']; + + $installationCursor = null; + do { + $installationQueries = [ + Query::equal('providerInstallationId', [$providerInstallationId]), + Query::equal('provider', ['origin']), + Query::limit(1000), + ]; + if ($installationCursor !== null) { + $installationQueries[] = Query::cursorAfter($installationCursor); + } + $installations = $authorization->skip(fn () => $dbForPlatform->find('installations', $installationQueries)); + + foreach ($installations as $installation) { + $projectId = $installation->getAttribute('projectId', ''); + $project = $authorization->skip(fn () => $dbForPlatform->getDocument('projects', $projectId)); + + if (!$project->isEmpty() && $this->isProjectInCurrentRegion($project)) { + $dbForProject = $getProjectDB($project); + + foreach (['functions', 'sites'] as $collection) { + $cursor = null; + do { + $queries = [ + Query::equal('installationInternalId', [$installation->getSequence()]), + Query::limit(1000), + ]; + if ($cursor !== null) { + $queries[] = Query::cursorAfter($cursor); + } + $resources = $authorization->skip(fn () => $dbForProject->find($collection, $queries)); + + foreach ($resources as $resource) { + $authorization->skip(fn () => $dbForProject->updateDocument($collection, $resource->getId(), new Document([ + 'installationId' => '', + 'installationInternalId' => '', + 'providerRepositoryId' => '', + 'providerBranch' => '', + 'providerSilentMode' => false, + 'providerRootDirectory' => '', + 'repositoryId' => '', + 'repositoryInternalId' => '', + ]))); + } + + $cursor = count($resources) === 1000 ? $resources[array_key_last($resources)] : null; + } while ($cursor !== null); + } + } + + $cursor = null; + do { + $queries = [ + Query::equal('installationInternalId', [$installation->getSequence()]), + Query::limit(1000), + ]; + if ($cursor !== null) { + $queries[] = Query::cursorAfter($cursor); + } + $repositories = $authorization->skip(fn () => $dbForPlatform->find('repositories', $queries)); + + foreach ($repositories as $repository) { + $authorization->skip(fn () => $dbForPlatform->deleteDocument('repositories', $repository->getId())); + } + + $cursor = count($repositories) === 1000 ? $repositories[array_key_last($repositories)] : null; + } while ($cursor !== null); + + $authorization->skip(fn () => $dbForPlatform->deleteDocument('installations', $installation->getId())); + } + + $installationCursor = count($installations) === 1000 ? $installations[array_key_last($installations)] : null; + } while ($installationCursor !== null); + } + + private function isProjectInCurrentRegion(Document $project): bool + { + try { + $dsn = new DSN($project->getAttribute('database')); + $databaseName = $dsn->getHost(); + } catch (\InvalidArgumentException) { + $databaseName = $project->getAttribute('database'); + } + + $databases = Config::getParam('pools-database', []); + if (!\in_array($databaseName, $databases)) { + Console::warning("Skipping project {$project->getId()}: database '{$databaseName}' is not part of region " . System::getEnv('_APP_REGION')); + return false; + } + + return true; + } + + private function handlePushEvent( + array $parsedPayload, + VcsFactory $vcsFactory, + Database $dbForPlatform, + Authorization $authorization, + Bus $bus, + callable $getProjectDB, + array $platform, + callable $deploymentsFactory, + ) { + $providerBranchDeleted = $parsedPayload['branchDeleted'] ?? false; + $providerBranch = $parsedPayload['branch'] ?? ''; + $providerBranchUrl = $parsedPayload['branchUrl'] ?? ''; + $providerRepositoryId = $parsedPayload['repositoryId'] ?? ''; + $providerRepositoryName = $parsedPayload['repositoryName'] ?? ''; + $providerInstallationId = $parsedPayload['installationId'] ?? ''; + $providerRepositoryUrl = $parsedPayload['repositoryUrl'] ?? ''; + $providerCommitHash = $parsedPayload['commitHash'] ?? ''; + $providerRepositoryOwner = $parsedPayload['owner'] ?? ''; + $providerCommitAuthorName = $parsedPayload['headCommitAuthorName'] ?? ''; + $providerCommitAuthorEmail = $parsedPayload['headCommitAuthorEmail'] ?? ''; + $providerCommitAuthorUrl = $parsedPayload['authorUrl'] ?? ''; + $providerCommitMessage = $parsedPayload['headCommitMessage'] ?? ''; + $providerCommitUrl = $parsedPayload['headCommitUrl'] ?? ''; + + Span::add('vcs.origin.event.repo.id', $providerRepositoryId); + Span::add('vcs.origin.event.repo.name', $providerRepositoryName); + Span::add('vcs.origin.event.branch', $providerBranch); + Span::add('vcs.origin.event.installation.id', $providerInstallationId); + + $vcs = $vcsFactory->fromInstallation(new Document([ + 'provider' => 'origin', + 'providerInstallationId' => $providerInstallationId, + ])); + + // Find associated repositories + $repositories = $authorization->skip(fn () => $dbForPlatform->find('repositories', [ + Query::equal('providerRepositoryId', [$providerRepositoryId]), + Query::limit(100), + ])); + + // Create new deployment only on push (not committed by us) and not when branch is deleted + if (!\in_array($providerCommitAuthorEmail, [APP_VCS_GITHUB_EMAIL, APP_VCS_ORIGIN_EMAIL], true) && !$providerBranchDeleted) { + $providerAffectedFiles = $parsedPayload['affectedFiles'] ?? []; + $this->createGitDeployments($vcs, $providerInstallationId, $repositories, $providerBranch, $providerBranchUrl, $providerRepositoryName, $providerRepositoryUrl, $providerRepositoryOwner, $providerCommitHash, $providerCommitAuthorName, $providerCommitAuthorUrl, $providerCommitMessage, $providerCommitUrl, '', $providerAffectedFiles, false, $dbForPlatform, $authorization, $bus, $getProjectDB, $platform, $deploymentsFactory); + } + } + + private function handlePullRequestEvent( + array $parsedPayload, + VcsFactory $vcsFactory, + Database $dbForPlatform, + Authorization $authorization, + Bus $bus, + callable $getProjectDB, + array $platform, + callable $deploymentsFactory, + ) { + $action = $parsedPayload['action'] ?? ''; + + if ($action == 'opened' || $action == 'reopened' || $action == 'synchronize') { + $providerBranch = $parsedPayload['branch'] ?? ''; + $providerBranchUrl = $parsedPayload['branchUrl'] ?? ''; + $providerRepositoryId = $parsedPayload['repositoryId'] ?? ''; + $providerRepositoryName = $parsedPayload['repositoryName'] ?? ''; + $providerInstallationId = $parsedPayload['installationId'] ?? ''; + $providerRepositoryUrl = $parsedPayload['repositoryUrl'] ?? ''; + $providerPullRequestId = $parsedPayload['pullRequestNumber'] ?? ''; + $providerCommitHash = $parsedPayload['commitHash'] ?? ''; + $providerRepositoryOwner = $parsedPayload['owner'] ?? ''; + $external = $parsedPayload['external'] ?? false; + $providerCommitUrl = $parsedPayload['headCommitUrl'] ?? ''; + $providerCommitAuthorUrl = $parsedPayload['authorUrl'] ?? ''; + + Span::add('vcs.origin.event.repo.id', $providerRepositoryId); + Span::add('vcs.origin.event.repo.name', $providerRepositoryName); + Span::add('vcs.origin.event.branch', $providerBranch); + Span::add('vcs.origin.event.installation.id', $providerInstallationId); + + // Ignore sync for non-external. We handle it in push webhook. + // Origin has no fork model, so every pull request is non-external. + if (!$external && $action == 'synchronize') { + return; + } + + $vcs = $vcsFactory->fromInstallation(new Document([ + 'provider' => 'origin', + 'providerInstallationId' => $providerInstallationId, + ])); + + try { + $commitDetails = $vcs->getCommit($providerRepositoryOwner, $providerRepositoryName, $providerCommitHash); + } catch (\Throwable $e) { + Console::warning("Failed to fetch commit '{$providerCommitHash}': " . $e->getMessage()); + $commitDetails = []; + } + $providerCommitAuthor = $commitDetails['commitAuthor'] ?? ''; + $providerCommitMessage = $commitDetails['commitMessage'] ?? ''; + + $prFiles = $vcs->getPullRequestFiles($providerRepositoryOwner, $providerRepositoryName, (int) $providerPullRequestId); + $providerAffectedFiles = [ + ...array_column($prFiles, 'filename'), + // Only renamed files carry a previous filename; skip missing values from other file changes. + ...array_filter(array_column($prFiles, 'previousFilename')) + ]; + + $repositories = $authorization->skip(fn () => $dbForPlatform->find('repositories', [ + Query::equal('providerRepositoryId', [$providerRepositoryId]), + Query::orderDesc('$createdAt') + ])); + + $this->createGitDeployments($vcs, $providerInstallationId, $repositories, $providerBranch, $providerBranchUrl, $providerRepositoryName, $providerRepositoryUrl, $providerRepositoryOwner, $providerCommitHash, $providerCommitAuthor, $providerCommitAuthorUrl, $providerCommitMessage, $providerCommitUrl, \strval($providerPullRequestId), $providerAffectedFiles, $external, $dbForPlatform, $authorization, $bus, $getProjectDB, $platform, $deploymentsFactory); + } + + // No cleanup on close: Origin pull requests are never external, so no + // authorized-contributor entries accumulate on the repository. + } +} diff --git a/src/Appwrite/Platform/Modules/VCS/Services/Http.php b/src/Appwrite/Platform/Modules/VCS/Services/Http.php index e078c8fca0..71498db484 100644 --- a/src/Appwrite/Platform/Modules/VCS/Services/Http.php +++ b/src/Appwrite/Platform/Modules/VCS/Services/Http.php @@ -25,6 +25,9 @@ use Appwrite\Platform\Modules\VCS\Http\Installations\Repositories\Detections\Cre use Appwrite\Platform\Modules\VCS\Http\Installations\Repositories\Get as GetRepository; use Appwrite\Platform\Modules\VCS\Http\Installations\Repositories\XList as ListRepositories; use Appwrite\Platform\Modules\VCS\Http\Installations\XList as ListInstallations; +use Appwrite\Platform\Modules\VCS\Http\Origin\Authorize\Get as GetOriginAuthorize; +use Appwrite\Platform\Modules\VCS\Http\Origin\Callback\Get as GetOriginCallback; +use Appwrite\Platform\Modules\VCS\Http\Origin\Events\Create as CreateOriginEvent; use Utopia\Platform\Service; class Http extends Service @@ -50,6 +53,10 @@ class Http extends Service $this->addAction(GetBitbucketAuthorize::getName(), new GetBitbucketAuthorize()); $this->addAction(GetBitbucketCallback::getName(), new GetBitbucketCallback()); + // Origin Authorization & Callback + $this->addAction(GetOriginAuthorize::getName(), new GetOriginAuthorize()); + $this->addAction(GetOriginCallback::getName(), new GetOriginCallback()); + // Installations $this->addAction(GetInstallation::getName(), new GetInstallation()); $this->addAction(ListInstallations::getName(), new ListInstallations()); @@ -69,5 +76,6 @@ class Http extends Service $this->addAction(CreateGiteaEvent::getName(), new CreateGiteaEvent()); $this->addAction(CreateGitlabEvent::getName(), new CreateGitlabEvent()); $this->addAction(CreateBitbucketEvent::getName(), new CreateBitbucketEvent()); + $this->addAction(CreateOriginEvent::getName(), new CreateOriginEvent()); } } diff --git a/src/Appwrite/Utopia/Response/Model/ConsoleVariables.php b/src/Appwrite/Utopia/Response/Model/ConsoleVariables.php index ab179d04ee..2a32be686e 100644 --- a/src/Appwrite/Utopia/Response/Model/ConsoleVariables.php +++ b/src/Appwrite/Utopia/Response/Model/ConsoleVariables.php @@ -71,6 +71,20 @@ class ConsoleVariables extends Model 'example' => ['github'], 'array' => true, ]) + ->addRule('_APP_VCS_PROVIDERS_WITH_REPOSITORY_CREATION', [ + 'type' => self::TYPE_STRING, + 'description' => 'List of configured VCS providers that support repository creation.', + 'default' => [], + 'example' => ['github'], + 'array' => true, + ]) + ->addRule('_APP_VCS_PROVIDERS_WITH_PUBLIC_REPOSITORIES', [ + 'type' => self::TYPE_STRING, + 'description' => 'List of configured VCS providers that can host public repositories.', + 'default' => [], + 'example' => ['github'], + 'array' => true, + ]) ->addRule('_APP_DOMAIN_ENABLED', [ 'type' => self::TYPE_BOOLEAN, 'description' => 'Defines if main domain is configured. If so, custom domains can be created.', diff --git a/src/Appwrite/Vcs/Comment.php b/src/Appwrite/Vcs/Comment.php index ac0f6e1dae..328dcaa19a 100644 --- a/src/Appwrite/Vcs/Comment.php +++ b/src/Appwrite/Vcs/Comment.php @@ -10,7 +10,8 @@ use Utopia\System\System; class Comment { public function __construct( - private array $platform + private array $platform, + private bool $withImages = true, ) { } @@ -173,7 +174,9 @@ class Comment $qrImagePathDark = '/images/vcs/qr-dark.svg'; $consoleUrl = $protocol . '://' . $hostname . '/v1/avatars/qr?text=' . \urlencode($site['previewUrl']); - $qr = '[' . $this->generatImage($qrImagePathLight, $qrImagePathDark, 'QR Code', 28) . '](' . $consoleUrl . ')'; + $qr = $this->withImages + ? '[' . $this->generatImage($qrImagePathLight, $qrImagePathDark, 'QR Code', 28) . '](' . $consoleUrl . ')' + : '[QR Code](' . $consoleUrl . ')'; $preview = '[Preview URL](' . $site['previewUrl'] . ')'; @@ -248,6 +251,11 @@ class Comment public function generatImage(string $pathLight, string $pathDark, string $alt, int $width): string { + // Providers without comment image support get the textual cells only. + if (!$this->withImages) { + return ''; + } + $protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS') === 'disabled' ? 'http' : 'https'; $hostname = $this->platform['consoleHostname'] ?? ''; diff --git a/src/Appwrite/Vcs/InstallationTokens.php b/src/Appwrite/Vcs/InstallationTokens.php index c192f6c07b..043ebdbb37 100644 --- a/src/Appwrite/Vcs/InstallationTokens.php +++ b/src/Appwrite/Vcs/InstallationTokens.php @@ -17,6 +17,13 @@ class InstallationTokens */ public function refreshForInstallation(Document $installation, Database $dbForPlatform, Factory $vcsFactory): Document { + // Only personal installations carry OAuth tokens to refresh. An app + // installation (a GitHub App, an Origin app) authenticates per request + // with an app-signed JWT and may have no OAuth2 client to resolve at all. + if (!$installation->getAttribute('personal', false)) { + return $installation; + } + $provider = $installation->getAttribute('provider', 'github'); return $this->refresh($installation, $dbForPlatform, $vcsFactory->oauth2FromProvider($provider)); diff --git a/tests/e2e/Services/Avatars/AvatarsBase.php b/tests/e2e/Services/Avatars/AvatarsBase.php index 9a65b8070f..027b8fd516 100644 --- a/tests/e2e/Services/Avatars/AvatarsBase.php +++ b/tests/e2e/Services/Avatars/AvatarsBase.php @@ -1342,4 +1342,154 @@ trait AvatarsBase return []; } + + + + public function testGetPhoto(): array + { + /** + * Test for SUCCESS — authenticated user (client side) + * + * The endpoint always returns an image: even when no Gravatar/Libravatar + * avatar exists it falls back to initials or the static placeholder, so + * we always expect HTTP 200. + */ + + // Default call — uses session user; falls through priority chain and + // returns some image (initials or static fallback at minimum). + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), []); + + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertEquals('image/png', $response['headers']['content-type']); + $this->assertNotEmpty($response['body']); + + // Width + height + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'width' => 128, + 'height' => 128, + ]); + + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertEquals('image/png', $response['headers']['content-type']); + $this->assertNotEmpty($response['body']); + + // Quality param + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'width' => 200, + 'height' => 200, + 'quality' => 50, + ]); + + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertNotEmpty($response['body']); + + // Output format: webp + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'output' => 'webp', + ]); + + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertEquals('image/webp', $response['headers']['content-type']); + $this->assertNotEmpty($response['body']); + + // Output format: jpg + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'output' => 'jpg', + ]); + + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertEquals('image/jpeg', $response['headers']['content-type']); + $this->assertNotEmpty($response['body']); + + // Rating param + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'rating' => 'pg', + ]); + + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertNotEmpty($response['body']); + + /** + * Test for SUCCESS — Gravatar flow + * + * Use a well-known email that has a real Gravatar so we can verify the + * provider is actually being reached. Wrapped in assertEventually to + * tolerate transient network hiccups. + * + * TODO: Once the OAuth2 session photo is implemented, add a test that + * verifies priority 1 takes precedence over Gravatar. + */ + $this->assertEventually(function () { + // When we have a Gravatar for the user's email the chain resolves at + // priority 2; result must be a non-trivial PNG. + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'width' => 256, + 'height' => 256, + ]); + + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertEquals('image/png', $response['headers']['content-type']); + $this->assertNotEmpty($response['body']); + }, 30_000, 2_000); + + /** + * Test for FAILURE — invalid params + */ + + // Width out of range + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'width' => 2001, + ]); + $this->assertEquals(400, $response['headers']['status-code']); + + // Height out of range + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'height' => 2001, + ]); + $this->assertEquals(400, $response['headers']['status-code']); + + // Quality out of range + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'quality' => 101, + ]); + $this->assertEquals(400, $response['headers']['status-code']); + + // Invalid output format + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'output' => 'bmp', + ]); + $this->assertEquals(400, $response['headers']['status-code']); + + // Invalid rating + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'rating' => 'xx', + ]); + $this->assertEquals(400, $response['headers']['status-code']); + + return []; + } } diff --git a/tests/unit/Vcs/FactoryTest.php b/tests/unit/Vcs/FactoryTest.php index 9c758593bd..671aec8ff9 100644 --- a/tests/unit/Vcs/FactoryTest.php +++ b/tests/unit/Vcs/FactoryTest.php @@ -31,7 +31,11 @@ final class FactoryTest extends TestCase foreach ($registry as $key => $entry) { $this->assertTrue(\is_subclass_of($entry['adapter'], Git::class), "Adapter for '{$key}' must extend Git"); - $this->assertIsCallable($entry['oauth2'], "OAuth2 builder for '{$key}' must be callable"); + // A provider with an OAuth2 user flow registers a builder; an + // app-only provider (Origin) deliberately registers none. + if (isset($entry['oauth2'])) { + $this->assertIsCallable($entry['oauth2'], "OAuth2 builder for '{$key}' must be callable"); + } $this->assertNotEmpty($entry['variables'], "Variables missing for '{$key}'"); foreach ($entry['variables'] as $name => $variable) { $this->assertStringStartsWith('_APP_VCS_', $variable['envVariable'] ?? '', "Env variable for '{$name}' missing or invalid for '{$key}'"); @@ -39,6 +43,21 @@ final class FactoryTest extends TestCase } } + public function testOriginRegistersNoOAuth2(): void + { + // Origin has no OAuth2 user flow: installs are approved on Cursor and + // confirmed by a signed receipt the adapter verifies itself, so the + // registry deliberately carries no builder and oauth2FromProvider() + // fails loudly instead of handing out a half-configured client. + $registry = Config::getParam('vcs', []); + $this->assertArrayHasKey('origin', $registry); + $this->assertArrayNotHasKey('oauth2', $registry['origin']); + + $factory = new Factory($this->cache(), $registry); + $this->expectException(Exception::class); + $factory->oauth2FromProvider('origin'); + } + public function testOauth2FromProviderUnknownThrows(): void { $factory = new Factory($this->cache(), ['github' => $this->githubEntry()]);