mirror of
https://github.com/appwrite/appwrite.git
synced 2026-11-18 20:36:03 +00:00
Merge branch 'main' into fix/webhook-utopia-client
This commit is contained in:
33 files changed
+1740
-105
No files matched your search
@@ -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
|
||||
@@ -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.',
|
||||
|
||||
@@ -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, ''),
|
||||
|
||||
@@ -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
|
||||
|
||||
+2
-1
@@ -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": {
|
||||
|
||||
Generated
+63
-15
@@ -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",
|
||||
|
||||
+7
-1
@@ -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:
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\AvatarPhotos;
|
||||
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Fetch\Client;
|
||||
|
||||
/**
|
||||
* Base class every avatar photo provider extends.
|
||||
*
|
||||
* A provider knows how to turn a user into raw image bytes from one source —
|
||||
* Gravatar, Libravatar, generated initials, a built-in placeholder — and
|
||||
* nothing more. Picking which provider actually answers a request is the
|
||||
* caller's job; providers never chain into one another.
|
||||
*/
|
||||
abstract class Photo
|
||||
{
|
||||
/**
|
||||
* How long a provider may wait to open a connection to a remote service.
|
||||
*/
|
||||
protected const CONNECT_TIMEOUT = 2 * 1000; // 2 seconds
|
||||
|
||||
/**
|
||||
* How long a provider may wait for a complete remote response.
|
||||
*
|
||||
* Providers are tried one after another, so these budgets stack: a single
|
||||
* unreachable service must not be able to hold the request open while we
|
||||
* still have other providers — and a local fallback — left to try.
|
||||
*/
|
||||
protected const REQUEST_TIMEOUT = 5 * 1000; // 5 seconds
|
||||
|
||||
/**
|
||||
* Machine-readable name of the provider, e.g. 'gravatar'.
|
||||
*/
|
||||
abstract public function getName(): string;
|
||||
|
||||
/**
|
||||
* Whether this provider has everything it needs to attempt a lookup.
|
||||
*
|
||||
* Providers that key off an email address return false for users without
|
||||
* one, so the caller can skip them without paying for a network round-trip.
|
||||
*/
|
||||
abstract public function supports(Document $user): bool;
|
||||
|
||||
/**
|
||||
* Fetch the raw image bytes for $user.
|
||||
*
|
||||
* Returning null means "I have no photo for this user" and is an expected
|
||||
* outcome, not an error — the caller moves on to the next provider. Network
|
||||
* or rendering failures must be swallowed and reported the same way.
|
||||
*
|
||||
* @param Document $user User to resolve a photo for.
|
||||
* @param int $width Desired width in pixels.
|
||||
* @param int $height Desired height in pixels.
|
||||
* @param string $rating Maximum image rating: 'g' | 'pg' | 'r' | 'x'.
|
||||
* @return string|null Raw image bytes, or null when unavailable.
|
||||
*/
|
||||
abstract public function get(Document $user, int $width, int $height, string $rating): ?string;
|
||||
|
||||
/**
|
||||
* GET $url with the provider timeout budget applied.
|
||||
*
|
||||
* Anything other than a 200 with a non-empty body — including a timeout or
|
||||
* a transport error — is reported as null so the caller can move on.
|
||||
*
|
||||
* @return string|null Raw response body, or null when unavailable.
|
||||
*/
|
||||
protected function fetch(string $url): ?string
|
||||
{
|
||||
$client = new Client();
|
||||
|
||||
try {
|
||||
$response = $client
|
||||
->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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\AvatarPhotos\Providers;
|
||||
|
||||
use Appwrite\AvatarPhotos\Photo;
|
||||
use Utopia\Database\Document;
|
||||
|
||||
/**
|
||||
* Static fallback provider.
|
||||
*
|
||||
* Returns a minimal built-in avatar image when all other providers have
|
||||
* failed. The image is a simple SVG rendered to a PNG-compatible byte
|
||||
* string; designers can swap it out later for a brand-aligned asset
|
||||
* without changing any surrounding logic.
|
||||
*
|
||||
* The SVG depicts a neutral silhouette on an Appwrite-pink background —
|
||||
* similar to what "mystery man" (mp) looks like on Gravatar, but ours.
|
||||
*
|
||||
* This provider needs nothing from the user and never returns null, so it is
|
||||
* always safe to place last in the chain.
|
||||
*/
|
||||
class Fallback extends Photo
|
||||
{
|
||||
public function getName(): string
|
||||
{
|
||||
return 'fallback';
|
||||
}
|
||||
|
||||
public function supports(Document $user): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function get(Document $user, int $width, int $height, string $rating): ?string
|
||||
{
|
||||
$width = $width > 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
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="{$width}" height="{$height}" viewBox="0 0 {$width} {$height}">
|
||||
<rect width="{$width}" height="{$height}" fill="#FD366E"/>
|
||||
<!-- Head -->
|
||||
<circle cx="50%" cy="38%" r="22%" fill="rgba(255,255,255,0.85)"/>
|
||||
<!-- Body / shoulder shape -->
|
||||
<ellipse cx="50%" cy="90%" rx="35%" ry="30%" fill="rgba(255,255,255,0.85)"/>
|
||||
</svg>
|
||||
SVG;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\AvatarPhotos\Providers;
|
||||
|
||||
use Appwrite\AvatarPhotos\Photo;
|
||||
use Utopia\Database\Document;
|
||||
|
||||
/**
|
||||
* Gravatar provider.
|
||||
*
|
||||
* Resolves a photo for a user's email address via the Gravatar service.
|
||||
* Uses the '404' fallback so we get a clear signal when the user has no
|
||||
* custom Gravatar; the caller can then move on to the next provider.
|
||||
*/
|
||||
class Gravatar extends Photo
|
||||
{
|
||||
private const BASE_URL = 'https://www.gravatar.com/avatar/';
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return 'gravatar';
|
||||
}
|
||||
|
||||
public function supports(Document $user): bool
|
||||
{
|
||||
return !empty($user->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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\AvatarPhotos\Providers;
|
||||
|
||||
use Appwrite\AvatarPhotos\Photo;
|
||||
use Imagick;
|
||||
use ImagickDraw;
|
||||
use ImagickPixel;
|
||||
use Utopia\Database\Document;
|
||||
|
||||
/**
|
||||
* Initials provider.
|
||||
*
|
||||
* Generates a coloured square with the user's initials. This is the single
|
||||
* implementation behind both the photo-resolution chain and the standalone
|
||||
* GET /v1/avatars/initials endpoint — the endpoint renders an arbitrary label
|
||||
* through render(), the chain resolves the label off the user first.
|
||||
*/
|
||||
class Initials extends Photo
|
||||
{
|
||||
/** Font used to render the initials, relative to the project root. */
|
||||
private const FONT_PATH = '/app/assets/fonts/inter-v8-latin-regular.woff2';
|
||||
|
||||
/** Edge length used when the caller does not ask for a size. */
|
||||
private const DEFAULT_SIZE = 500;
|
||||
|
||||
/** Colour palette — a theme is picked from the initials themselves. */
|
||||
private array $themes = [
|
||||
['background' => '#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', '');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\AvatarPhotos\Providers;
|
||||
|
||||
use Appwrite\AvatarPhotos\Photo;
|
||||
use Utopia\Database\Document;
|
||||
|
||||
/**
|
||||
* Libravatar provider.
|
||||
*
|
||||
* Libravatar is a federated, self-hosted alternative to Gravatar.
|
||||
* Resolution order: the domain's SRV record is consulted first
|
||||
* (federation); when that is absent we fall back to the central
|
||||
* seccdn.libravatar.org service.
|
||||
*
|
||||
* Libravatar supports d=404 just like Gravatar — we use that for a clean
|
||||
* "no photo here" signal.
|
||||
*/
|
||||
class Libavatar extends Photo
|
||||
{
|
||||
private const BASE_URL = 'https://seccdn.libravatar.org/avatar/';
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return 'libavatar';
|
||||
}
|
||||
|
||||
public function supports(Document $user): bool
|
||||
{
|
||||
return !empty($user->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);
|
||||
}
|
||||
}
|
||||
@@ -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'] ?? []),
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Platform\Modules\Avatars\Http\Photo;
|
||||
|
||||
use Appwrite\AvatarPhotos\Photo;
|
||||
use Appwrite\AvatarPhotos\Providers\Fallback;
|
||||
use Appwrite\AvatarPhotos\Providers\Gravatar;
|
||||
use Appwrite\AvatarPhotos\Providers\Initials;
|
||||
use Appwrite\AvatarPhotos\Providers\Libavatar;
|
||||
use Appwrite\Extend\Exception;
|
||||
use Appwrite\Platform\Modules\Avatars\Http\Action;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\ContentType;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\MethodType;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Response;
|
||||
use Utopia\Balancer\Algorithm\First;
|
||||
use Utopia\Balancer\Balancer;
|
||||
use Utopia\Balancer\Option;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Image\Image;
|
||||
use Utopia\Platform\Action as UtopiaAction;
|
||||
use Utopia\Platform\Scope\HTTP;
|
||||
use Utopia\Validator\Range;
|
||||
use Utopia\Validator\WhiteList;
|
||||
|
||||
class Get extends Action
|
||||
{
|
||||
use HTTP;
|
||||
|
||||
public static function getName(): string
|
||||
{
|
||||
return 'getPhoto';
|
||||
}
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this
|
||||
->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: <<<EOT
|
||||
Returns the best available profile photo for the currently authenticated user. The endpoint tries each source in priority order and returns the first successful result: Gravatar, Libavatar, Appwrite Initials, built-in static fallback file.
|
||||
EOT,
|
||||
auth: [AuthType::ADMIN, AuthType::SESSION, AuthType::KEY, AuthType::JWT],
|
||||
type: MethodType::LOCATION,
|
||||
locationAuth: ['Project', 'ImpersonateUserId'],
|
||||
responses: [
|
||||
new SDKResponse(
|
||||
code: Response::STATUS_CODE_OK,
|
||||
model: Response::MODEL_NONE,
|
||||
)
|
||||
],
|
||||
contentType: ContentType::IMAGE
|
||||
))
|
||||
->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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
@@ -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'],
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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') {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Platform\Modules\VCS\Http\Origin\Authorize;
|
||||
|
||||
use Appwrite\Extend\Exception;
|
||||
use Appwrite\Platform\Action;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\ContentType;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\MethodType;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Response;
|
||||
use Appwrite\Vcs\Factory as VcsFactory;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Platform\Scope\HTTP;
|
||||
use Utopia\System\System;
|
||||
|
||||
class Get extends Action
|
||||
{
|
||||
use HTTP;
|
||||
|
||||
/**
|
||||
* Everything the integration touches: reading repository metadata,
|
||||
* cloning sources, pushing templates, deploying from pull requests,
|
||||
* commenting on them, and reporting build checks.
|
||||
*/
|
||||
public const SCOPES = [
|
||||
'repository:contents:read',
|
||||
'repository:metadata:read',
|
||||
'repository:contents:write',
|
||||
'repository:pull_requests:read',
|
||||
'repository:pull_requests:write',
|
||||
'repository:pull_requests:reviews:read',
|
||||
'repository:pull_requests:reviews:write',
|
||||
'repository:checks:read',
|
||||
'repository:checks:write',
|
||||
];
|
||||
|
||||
public static function getName()
|
||||
{
|
||||
return 'getVCSOriginAuthorize';
|
||||
}
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this
|
||||
->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: <<<EOT
|
||||
Begin Appwrite's Origin app installation to set up version control integration. This endpoint responds with a redirect URL to the Origin app's installation page on Cursor. The Origin app must be configured in your environment for this endpoint to work.
|
||||
EOT,
|
||||
auth: [AuthType::ADMIN],
|
||||
responses: [
|
||||
new SDKResponse(
|
||||
code: Response::STATUS_CODE_MOVED_PERMANENTLY,
|
||||
model: Response::MODEL_NONE,
|
||||
)
|
||||
],
|
||||
contentType: ContentType::HTML,
|
||||
type: MethodType::WEBAUTH,
|
||||
// Preview SDK builds show the whole surface, so they do not hide.
|
||||
hide: System::getEnv('_APP_SDK_PREVIEW', 'disabled') !== 'enabled',
|
||||
))
|
||||
->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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Platform\Modules\VCS\Http\Origin\Callback;
|
||||
|
||||
use Appwrite\Extend\Exception;
|
||||
use Appwrite\Platform\Permission as AppwritePermission;
|
||||
use Appwrite\Utopia\Response;
|
||||
use Appwrite\Vcs\Factory as VcsFactory;
|
||||
use Utopia\Console;
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Database\Helpers\ID;
|
||||
use Utopia\Database\Query;
|
||||
use Utopia\Platform\Action;
|
||||
use Utopia\Platform\Scope\HTTP;
|
||||
use Utopia\System\System;
|
||||
use Utopia\Validator\Text;
|
||||
|
||||
class Get extends Action
|
||||
{
|
||||
use HTTP;
|
||||
use AppwritePermission;
|
||||
|
||||
public static function getName()
|
||||
{
|
||||
return 'getVCSOriginCallback';
|
||||
}
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this
|
||||
->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]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Platform\Modules\VCS\Http\Origin\Events;
|
||||
|
||||
use Appwrite\Extend\Exception;
|
||||
use Appwrite\Platform\Action;
|
||||
use Appwrite\Platform\Modules\VCS\Http\GitHub\Deployment;
|
||||
use Appwrite\Utopia\Request;
|
||||
use Appwrite\Utopia\Response;
|
||||
use Appwrite\Vcs\Factory as VcsFactory;
|
||||
use Utopia\Bus\Bus;
|
||||
use Utopia\Config\Config;
|
||||
use Utopia\Console;
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Database\Exception\Duplicate;
|
||||
use Utopia\Database\Query;
|
||||
use Utopia\Database\Validator\Authorization;
|
||||
use Utopia\DSN\DSN;
|
||||
use Utopia\Platform\Scope\HTTP;
|
||||
use Utopia\Span\Span;
|
||||
use Utopia\System\System;
|
||||
use Utopia\VCS\Adapter\Git\Origin;
|
||||
|
||||
class Create extends Action
|
||||
{
|
||||
use HTTP;
|
||||
use Deployment;
|
||||
|
||||
/**
|
||||
* Origin's active signing keys, cached for the worker's lifetime. The set
|
||||
* rotates rarely and a delivery that fails on a stale set refetches once.
|
||||
*
|
||||
* @var array<string>|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 "<webhook-id>.<webhook-timestamp>.<raw body>"
|
||||
// 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<string>
|
||||
*/
|
||||
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.
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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.',
|
||||
|
||||
@@ -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'] ?? '';
|
||||
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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 [];
|
||||
}
|
||||
}
|
||||
@@ -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()]);
|
||||
|
||||
Reference in new issue
Block a user