1
0
Fork 0
mirror of synced 2024-06-30 12:10:51 +12:00

Merge branch '0.7.x' of github.com:appwrite/appwrite into feat-730-new-webhook-events

This commit is contained in:
Eldad Fux 2020-11-20 08:54:58 +02:00
commit a4ea9e78a8
12 changed files with 216 additions and 29 deletions

View file

@ -33,14 +33,16 @@ App::post('/v1/teams')
->label('sdk.response.model', Response::MODEL_TEAM) ->label('sdk.response.model', Response::MODEL_TEAM)
->param('name', null, new Text(128), 'Team name. Max length: 128 chars.') ->param('name', null, new Text(128), 'Team name. Max length: 128 chars.')
->param('roles', ['owner'], new ArrayList(new Key()), 'Array of strings. Use this param to set the roles in the team for the user who created it. The default role is **owner**. A role can be any string. Learn more about [roles and permissions](/docs/permissions). Max length for each role is 32 chars.', true) ->param('roles', ['owner'], new ArrayList(new Key()), 'Array of strings. Use this param to set the roles in the team for the user who created it. The default role is **owner**. A role can be any string. Learn more about [roles and permissions](/docs/permissions). Max length for each role is 32 chars.', true)
->action(function ($name, $roles, $response, $user, $projectDB, $mode) { ->action(function ($name, $roles, $response, $user, $projectDB) {
/** @var Appwrite\Utopia\Response $response */ /** @var Appwrite\Utopia\Response $response */
/** @var Appwrite\Database\Document $user */ /** @var Appwrite\Database\Document $user */
/** @var Appwrite\Database\Database $projectDB */ /** @var Appwrite\Database\Database $projectDB */
/** @var bool $mode */
Authorization::disable(); Authorization::disable();
$isPreviliggedUser = Auth::isPreviliggedUser(Authorization::$roles);
$isAppUser = Auth::isAppUser(Authorization::$roles);
$team = $projectDB->createDocument([ $team = $projectDB->createDocument([
'$collection' => Database::SYSTEM_COLLECTION_TEAMS, '$collection' => Database::SYSTEM_COLLECTION_TEAMS,
'$permissions' => [ '$permissions' => [
@ -48,7 +50,7 @@ App::post('/v1/teams')
'write' => ['team:{self}/owner'], 'write' => ['team:{self}/owner'],
], ],
'name' => $name, 'name' => $name,
'sum' => ($mode !== APP_MODE_ADMIN && $user->getId()) ? 1 : 0, 'sum' => ($isPreviliggedUser || $isAppUser) ? 0 : 1,
'dateCreated' => \time(), 'dateCreated' => \time(),
]); ]);
@ -58,7 +60,7 @@ App::post('/v1/teams')
throw new Exception('Failed saving team to DB', 500); throw new Exception('Failed saving team to DB', 500);
} }
if ($mode !== APP_MODE_ADMIN && $user->getId()) { // Don't add user on server mode if (!$isPreviliggedUser && !$isAppUser) { // Don't add user on server mode
$membership = new Document([ $membership = new Document([
'$collection' => Database::SYSTEM_COLLECTION_MEMBERSHIPS, '$collection' => Database::SYSTEM_COLLECTION_MEMBERSHIPS,
'$permissions' => [ '$permissions' => [
@ -88,7 +90,7 @@ App::post('/v1/teams')
->setStatusCode(Response::STATUS_CODE_CREATED) ->setStatusCode(Response::STATUS_CODE_CREATED)
->dynamic($team, Response::MODEL_TEAM) ->dynamic($team, Response::MODEL_TEAM)
; ;
}, ['response', 'user', 'projectDB', 'mode']); }, ['response', 'user', 'projectDB']);
App::get('/v1/teams') App::get('/v1/teams')
->desc('List Teams') ->desc('List Teams')
@ -246,14 +248,16 @@ App::post('/v1/teams/:teamId/memberships')
->param('name', '', new Text(128), 'New team member name. Max length: 128 chars.', true) ->param('name', '', new Text(128), 'New team member name. Max length: 128 chars.', true)
->param('roles', [], new ArrayList(new Key()), 'Array of strings. Use this param to set the user roles in the team. A role can be any string. Learn more about [roles and permissions](/docs/permissions). Max length for each role is 32 chars.') ->param('roles', [], new ArrayList(new Key()), 'Array of strings. Use this param to set the user roles in the team. A role can be any string. Learn more about [roles and permissions](/docs/permissions). Max length for each role is 32 chars.')
->param('url', '', function ($clients) { return new Host($clients); }, 'URL to redirect the user back to your app from the invitation email. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API.', false, ['clients']) // TODO add our own built-in confirm page ->param('url', '', function ($clients) { return new Host($clients); }, 'URL to redirect the user back to your app from the invitation email. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API.', false, ['clients']) // TODO add our own built-in confirm page
->action(function ($teamId, $email, $name, $roles, $url, $response, $project, $user, $projectDB, $locale, $audits, $mails, $mode) { ->action(function ($teamId, $email, $name, $roles, $url, $response, $project, $user, $projectDB, $locale, $audits, $mails) {
/** @var Appwrite\Utopia\Response $response */ /** @var Appwrite\Utopia\Response $response */
/** @var Appwrite\Database\Document $project */ /** @var Appwrite\Database\Document $project */
/** @var Appwrite\Database\Document $user */ /** @var Appwrite\Database\Document $user */
/** @var Appwrite\Database\Database $projectDB */ /** @var Appwrite\Database\Database $projectDB */
/** @var Appwrite\Event\Event $audits */ /** @var Appwrite\Event\Event $audits */
/** @var Appwrite\Event\Event $mails */ /** @var Appwrite\Event\Event $mails */
/** @var bool $mode */
$isPreviliggedUser = Auth::isPreviliggedUser(Authorization::$roles);
$isAppUser = Auth::isAppUser(Authorization::$roles);
$name = (empty($name)) ? $email : $name; $name = (empty($name)) ? $email : $name;
$team = $projectDB->getDocument($teamId); $team = $projectDB->getDocument($teamId);
@ -323,7 +327,7 @@ App::post('/v1/teams/:teamId/memberships')
} }
} }
if (!$isOwner && APP_MODE_ADMIN !== $mode && $user->getId()) { // Not owner, not admin, not app (server) if (!$isOwner && !$isPreviliggedUser && !$isAppUser) { // Not owner, not admin, not app (server)
throw new Exception('User is not allowed to send invitations for this team', 401); throw new Exception('User is not allowed to send invitations for this team', 401);
} }
@ -339,12 +343,12 @@ App::post('/v1/teams/:teamId/memberships')
'teamId' => $team->getId(), 'teamId' => $team->getId(),
'roles' => $roles, 'roles' => $roles,
'invited' => \time(), 'invited' => \time(),
'joined' => (APP_MODE_ADMIN === $mode || !$user->getId()) ? \time() : 0, 'joined' => ($isPreviliggedUser || $isAppUser) ? \time() : 0,
'confirm' => (APP_MODE_ADMIN === $mode || !$user->getId()), 'confirm' => ($isPreviliggedUser || $isAppUser),
'secret' => Auth::hash($secret), 'secret' => Auth::hash($secret),
]); ]);
if (APP_MODE_ADMIN === $mode || !$user->getId()) { // Allow admin to create membership if ($isPreviliggedUser || $isAppUser) { // Allow admin to create membership
Authorization::disable(); Authorization::disable();
$membership = $projectDB->createDocument($membership->getArrayCopy()); $membership = $projectDB->createDocument($membership->getArrayCopy());
@ -395,7 +399,7 @@ App::post('/v1/teams/:teamId/memberships')
->setParam('{{text-cta}}', '#ffffff') ->setParam('{{text-cta}}', '#ffffff')
; ;
if (APP_MODE_ADMIN !== $mode && $user->getId()) { // No need in comfirmation when in admin or app mode if (!$isPreviliggedUser && !$isAppUser) { // No need in comfirmation when in admin or app mode
$mails $mails
->setParam('event', 'teams.membership.create') ->setParam('event', 'teams.membership.create')
->setParam('from', ($project->getId() === 'console') ? '' : \sprintf($locale->getText('account.emails.team'), $project->getAttribute('name'))) ->setParam('from', ($project->getId() === 'console') ? '' : \sprintf($locale->getText('account.emails.team'), $project->getAttribute('name')))
@ -420,7 +424,7 @@ App::post('/v1/teams/:teamId/memberships')
'name' => $name, 'name' => $name,
])), Response::MODEL_MEMBERSHIP) ])), Response::MODEL_MEMBERSHIP)
; ;
}, ['response', 'project', 'user', 'projectDB', 'locale', 'audits', 'mails', 'mode']); }, ['response', 'project', 'user', 'projectDB', 'locale', 'audits', 'mails']);
App::get('/v1/teams/:teamId/memberships') App::get('/v1/teams/:teamId/memberships')
->desc('Get Team Memberships') ->desc('Get Team Memberships')

View file

@ -35,8 +35,6 @@ App::init(function ($utopia, $request, $response, $console, $project, $user, $lo
/** @var Appwrite\Event\Event $deletes */ /** @var Appwrite\Event\Event $deletes */
/** @var bool $mode */ /** @var bool $mode */
/** @var array $clients */ /** @var array $clients */
Authorization::$roles = ['*'];
$localeParam = (string)$request->getParam('locale', $request->getHeader('x-appwrite-locale', '')); $localeParam = (string)$request->getParam('locale', $request->getHeader('x-appwrite-locale', ''));

View file

@ -2,6 +2,7 @@
require_once __DIR__.'/../vendor/autoload.php'; require_once __DIR__.'/../vendor/autoload.php';
use Appwrite\Database\Validator\Authorization;
use Utopia\Swoole\Files; use Utopia\Swoole\Files;
use Utopia\Swoole\Request; use Utopia\Swoole\Request;
use Appwrite\Utopia\Response; use Appwrite\Utopia\Response;
@ -94,6 +95,9 @@ $http->on('request', function (SwooleRequest $swooleRequest, SwooleResponse $swo
$app = new App('America/New_York'); $app = new App('America/New_York');
try { try {
Authorization::cleanRoles();
Authorization::setRole('*');
$app->run($request, $response); $app->run($request, $response);
} catch (\Throwable $th) { } catch (\Throwable $th) {
Console::error('[Error] Type: '.get_class($th)); Console::error('[Error] Type: '.get_class($th));

View file

@ -34,6 +34,7 @@ const APP_DOMAIN = 'appwrite.io';
const APP_EMAIL_TEAM = 'team@localhost.test'; // Default email address const APP_EMAIL_TEAM = 'team@localhost.test'; // Default email address
const APP_EMAIL_SECURITY = 'security@localhost.test'; // Default security email address const APP_EMAIL_SECURITY = 'security@localhost.test'; // Default security email address
const APP_USERAGENT = APP_NAME.'-Server v%s. Please report abuse at %s'; const APP_USERAGENT = APP_NAME.'-Server v%s. Please report abuse at %s';
const APP_MODE_DEFAULT = 'default';
const APP_MODE_ADMIN = 'admin'; const APP_MODE_ADMIN = 'admin';
const APP_PAGING_LIMIT = 12; const APP_PAGING_LIMIT = 12;
const APP_CACHE_BUSTER = 140; const APP_CACHE_BUSTER = 140;
@ -381,8 +382,7 @@ App::setResource('user', function($mode, $project, $console, $request, $response
$session = Auth::decodeSession( $session = Auth::decodeSession(
$request->getCookie(Auth::$cookieName, // Get sessions $request->getCookie(Auth::$cookieName, // Get sessions
$request->getCookie(Auth::$cookieName.'_legacy', // Get fallback session from old clients (no SameSite support) $request->getCookie(Auth::$cookieName.'_legacy', '')));// Get fallback session from old clients (no SameSite support)
$request->getHeader('x-appwrite-key', '')))); // Get API Key
// Get fallback session from clients who block 3rd-party cookies // Get fallback session from clients who block 3rd-party cookies
$response->addHeader('X-Debug-Fallback', 'false'); $response->addHeader('X-Debug-Fallback', 'false');
@ -463,7 +463,7 @@ App::setResource('projectDB', function($register, $project) {
App::setResource('mode', function($request) { App::setResource('mode', function($request) {
/** @var Utopia\Swoole\Request $request */ /** @var Utopia\Swoole\Request $request */
return $request->getParam('mode', $request->getHeader('x-appwrite-mode', 'default')); return $request->getParam('mode', $request->getHeader('x-appwrite-mode', APP_MODE_DEFAULT));
}, ['request']); }, ['request']);
App::setResource('geodb', function($register) { App::setResource('geodb', function($register) {

View file

@ -138,6 +138,7 @@ $cli
Console::success('SMTP................connected 👍'); Console::success('SMTP................connected 👍');
} catch (\Throwable $th) { } catch (\Throwable $th) {
Console::error('SMTP.............disconnected 👎'); Console::error('SMTP.............disconnected 👎');
var_dump($th);
} }
$host = App::getEnv('_APP_STATSD_HOST', 'telegraf'); $host = App::getEnv('_APP_STATSD_HOST', 'telegraf');

View file

@ -67,6 +67,11 @@ services:
- _APP_DB_SCHEMA - _APP_DB_SCHEMA
- _APP_DB_USER - _APP_DB_USER
- _APP_DB_PASS - _APP_DB_PASS
- _APP_SMTP_HOST
- _APP_SMTP_PORT
- _APP_SMTP_SECURE
- _APP_SMTP_USERNAME
- _APP_SMTP_PASSWORD
- _APP_INFLUXDB_HOST - _APP_INFLUXDB_HOST
- _APP_INFLUXDB_PORT - _APP_INFLUXDB_PORT
- _APP_STORAGE_LIMIT - _APP_STORAGE_LIMIT

View file

@ -82,6 +82,11 @@ services:
- _APP_DB_SCHEMA - _APP_DB_SCHEMA
- _APP_DB_USER - _APP_DB_USER
- _APP_DB_PASS - _APP_DB_PASS
- _APP_SMTP_HOST
- _APP_SMTP_PORT
- _APP_SMTP_SECURE
- _APP_SMTP_USERNAME
- _APP_SMTP_PASSWORD
- _APP_INFLUXDB_HOST - _APP_INFLUXDB_HOST
- _APP_INFLUXDB_PORT - _APP_INFLUXDB_PORT
- _APP_STORAGE_LIMIT - _APP_STORAGE_LIMIT

View file

@ -23,7 +23,6 @@ class Auth
const USER_ROLE_OWNER = 4; const USER_ROLE_OWNER = 4;
const USER_ROLE_APP = 5; const USER_ROLE_APP = 5;
const USER_ROLE_SYSTEM = 6; const USER_ROLE_SYSTEM = 6;
const USER_ROLE_ALL = '*';
/** /**
* Token Types. * Token Types.
@ -49,9 +48,9 @@ class Auth
/** /**
* User Unique ID. * User Unique ID.
* *
* @var int * @var string
*/ */
public static $unique = 0; public static $unique = '';
/** /**
* User Secret Key. * User Secret Key.
@ -75,7 +74,7 @@ class Auth
/** /**
* Encode Session. * Encode Session.
* *
* @param int $id * @param string $id
* @param string $secret * @param string $secret
* *
* @return string * @return string
@ -206,4 +205,40 @@ class Auth
return false; return false;
} }
/**
* Is Previligged User?
*
* @param array $roles
*
* @return bool
*/
public static function isPreviliggedUser(array $roles): bool
{
if(
array_key_exists('role:'.self::USER_ROLE_OWNER, $roles) ||
array_key_exists('role:'.self::USER_ROLE_DEVELOPER, $roles) ||
array_key_exists('role:'.self::USER_ROLE_ADMIN, $roles)
) {
return true;
}
return false;
}
/**
* Is App User?
*
* @param array $roles
*
* @return bool
*/
public static function isAppUser(array $roles): bool
{
if(array_key_exists('role:'.self::USER_ROLE_APP, $roles)) {
return true;
}
return false;
}
} }

View file

@ -10,7 +10,7 @@ class Authorization extends Validator
/** /**
* @var array * @var array
*/ */
static $roles = ['*']; static $roles = ['*' => true];
/** /**
* @var Document * @var Document
@ -77,7 +77,7 @@ class Authorization extends Validator
foreach ($permissions[$this->action] as $permission) { foreach ($permissions[$this->action] as $permission) {
$permission = \str_replace(':{self}', ':'.$this->document->getId(), $permission); $permission = \str_replace(':{self}', ':'.$this->document->getId(), $permission);
if (\in_array($permission, self::getRoles())) { if (\array_key_exists($permission, self::$roles)) {
return true; return true;
} }
} }
@ -92,17 +92,35 @@ class Authorization extends Validator
* *
* @return void * @return void
*/ */
public static function setRole($role): void public static function setRole(string $role): void
{ {
self::$roles[] = $role; self::$roles[$role] = true;
} }
/** /**
* @return array * @return array
*/ */
public static function getRoles() public static function getRoles(): array
{ {
return self::$roles; return \array_keys(self::$roles);
}
/**
* @return void
*/
public static function cleanRoles(): void
{
self::$roles = [];
}
/**
* @param string $role
*
* @return bool
*/
public static function isRole(string $role): bool
{
return (\array_key_exists($role, self::$roles));
} }
/** /**

View file

@ -280,7 +280,7 @@ class OpenAPI3 extends Format
'x-example' => $node['x-example'] ?? null, 'x-example' => $node['x-example'] ?? null,
]; ];
if(!\is_null($node['default'])) { if(isset($node['default'])) {
$body['content'][$consumes[0]]['schema']['properties'][$name]['default'] = $node['default']; $body['content'][$consumes[0]]['schema']['properties'][$name]['default'] = $node['default'];
} }

View file

@ -118,4 +118,38 @@ class AuthTest extends TestCase
$this->assertEquals(Auth::tokenVerify($tokens3, Auth::TOKEN_TYPE_LOGIN, $secret), false); $this->assertEquals(Auth::tokenVerify($tokens3, Auth::TOKEN_TYPE_LOGIN, $secret), false);
$this->assertEquals(Auth::tokenVerify($tokens3, Auth::TOKEN_TYPE_LOGIN, 'false-secret'), false); $this->assertEquals(Auth::tokenVerify($tokens3, Auth::TOKEN_TYPE_LOGIN, 'false-secret'), false);
} }
public function testIsPreviliggedUser()
{
$this->assertEquals(false, Auth::isPreviliggedUser([]));
$this->assertEquals(false, Auth::isPreviliggedUser(['role:'.Auth::USER_ROLE_GUEST => true]));
$this->assertEquals(false, Auth::isPreviliggedUser(['role:'.Auth::USER_ROLE_MEMBER => true]));
$this->assertEquals(true, Auth::isPreviliggedUser(['role:'.Auth::USER_ROLE_ADMIN => true]));
$this->assertEquals(true, Auth::isPreviliggedUser(['role:'.Auth::USER_ROLE_DEVELOPER => true]));
$this->assertEquals(true, Auth::isPreviliggedUser(['role:'.Auth::USER_ROLE_OWNER => true]));
$this->assertEquals(false, Auth::isPreviliggedUser(['role:'.Auth::USER_ROLE_APP => true]));
$this->assertEquals(false, Auth::isPreviliggedUser(['role:'.Auth::USER_ROLE_SYSTEM => true]));
$this->assertEquals(false, Auth::isPreviliggedUser(['role:'.Auth::USER_ROLE_APP => true, 'role:'.Auth::USER_ROLE_APP => true]));
$this->assertEquals(false, Auth::isPreviliggedUser(['role:'.Auth::USER_ROLE_APP => true, 'role:'.Auth::USER_ROLE_GUEST => true]));
$this->assertEquals(true, Auth::isPreviliggedUser(['role:'.Auth::USER_ROLE_OWNER => true, 'role:'.Auth::USER_ROLE_GUEST => true]));
$this->assertEquals(true, Auth::isPreviliggedUser(['role:'.Auth::USER_ROLE_OWNER => true, 'role:'.Auth::USER_ROLE_ADMIN => true, 'role:'.Auth::USER_ROLE_DEVELOPER => true]));
}
public function testIsAppUser()
{
$this->assertEquals(false, Auth::isAppUser([]));
$this->assertEquals(false, Auth::isAppUser(['role:'.Auth::USER_ROLE_GUEST => true]));
$this->assertEquals(false, Auth::isAppUser(['role:'.Auth::USER_ROLE_MEMBER => true]));
$this->assertEquals(false, Auth::isAppUser(['role:'.Auth::USER_ROLE_ADMIN => true]));
$this->assertEquals(false, Auth::isAppUser(['role:'.Auth::USER_ROLE_DEVELOPER => true]));
$this->assertEquals(false, Auth::isAppUser(['role:'.Auth::USER_ROLE_OWNER => true]));
$this->assertEquals(true, Auth::isAppUser(['role:'.Auth::USER_ROLE_APP => true]));
$this->assertEquals(false, Auth::isAppUser(['role:'.Auth::USER_ROLE_SYSTEM => true]));
$this->assertEquals(true, Auth::isAppUser(['role:'.Auth::USER_ROLE_APP => true, 'role:'.Auth::USER_ROLE_APP => true]));
$this->assertEquals(true, Auth::isAppUser(['role:'.Auth::USER_ROLE_APP => true, 'role:'.Auth::USER_ROLE_GUEST => true]));
$this->assertEquals(false, Auth::isAppUser(['role:'.Auth::USER_ROLE_OWNER => true, 'role:'.Auth::USER_ROLE_GUEST => true]));
$this->assertEquals(false, Auth::isAppUser(['role:'.Auth::USER_ROLE_OWNER => true, 'role:'.Auth::USER_ROLE_ADMIN => true, 'role:'.Auth::USER_ROLE_DEVELOPER => true]));
}
} }

View file

@ -0,0 +1,83 @@
<?php
namespace Appwrite\Tests;
use Appwrite\Database\Document;
use Appwrite\Database\Validator\Authorization;
use PHPUnit\Framework\TestCase;
class AuthorizationTest extends TestCase
{
/**
* @var Authorization
*/
protected $object = null;
/**
* @var Document
*/
protected $document = null;
public function setUp(): void
{
$this->document = new Document([
'$id' => uniqid(),
'$collection' => uniqid(),
'$permissions' => [
'read' => ['user:123', 'team:123'],
'write' => ['*'],
],
]);
$this->object = new Authorization($this->document, 'read');
}
public function tearDown(): void
{
}
public function testValues()
{
$this->assertEquals($this->object->isValid($this->document->getPermissions()), false);
Authorization::setRole('user:456');
Authorization::setRole('user:123');
$this->assertEquals(Authorization::isRole('user:456'), true);
$this->assertEquals(Authorization::isRole('user:457'), false);
$this->assertEquals(Authorization::isRole(''), false);
$this->assertEquals(Authorization::isRole('*'), true);
$this->assertEquals($this->object->isValid($this->document->getPermissions()), true);
Authorization::cleanRoles();
$this->assertEquals($this->object->isValid($this->document->getPermissions()), false);
Authorization::setRole('team:123');
$this->assertEquals($this->object->isValid($this->document->getPermissions()), true);
Authorization::cleanRoles();
Authorization::disable();
$this->assertEquals($this->object->isValid($this->document->getPermissions()), true);
Authorization::reset();
$this->assertEquals($this->object->isValid($this->document->getPermissions()), false);
Authorization::setDefaultStatus(false);
Authorization::disable();
$this->assertEquals($this->object->isValid($this->document->getPermissions()), true);
Authorization::reset();
$this->assertEquals($this->object->isValid($this->document->getPermissions()), true);
Authorization::enable();
$this->assertEquals($this->object->isValid($this->document->getPermissions()), false);
}
}