From 839bec841d6ae911d4a0e89fc6785006f900f8f2 Mon Sep 17 00:00:00 2001 From: Roman Date: Fri, 15 Jul 2016 13:43:19 +0400 Subject: [PATCH 1/4] added MongoDB (new php driver mongodb) storage --- .gitignore | 11 +- src/OAuth2/Storage/MongoDB.php | 366 +++++ test/OAuth2/Storage/MongoDBTest.php | 120 ++ test/lib/OAuth2/Storage/BaseTest.php | 70 +- test/lib/OAuth2/Storage/Bootstrap.php | 1884 +++++++++++++------------ 5 files changed, 1524 insertions(+), 927 deletions(-) create mode 100644 src/OAuth2/Storage/MongoDB.php create mode 100644 test/OAuth2/Storage/MongoDBTest.php diff --git a/.gitignore b/.gitignore index c43a667d4..8a0c06d6c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ -# Test Files # -test/config/test.sqlite -vendor -composer.lock -.idea +# Test Files # +test/config/test.sqlite +vendor +composer.lock +.idea +nbproject \ No newline at end of file diff --git a/src/OAuth2/Storage/MongoDB.php b/src/OAuth2/Storage/MongoDB.php new file mode 100644 index 000000000..2d1f2cb3a --- /dev/null +++ b/src/OAuth2/Storage/MongoDB.php @@ -0,0 +1,366 @@ + + */ +class MongoDB implements AuthorizationCodeInterface, + AccessTokenInterface, + ClientCredentialsInterface, + UserCredentialsInterface, + RefreshTokenInterface, + JwtBearerInterface, + OpenIDAuthorizationCodeInterface +{ + protected $db; + protected $database; + protected $config; + + public function __construct($connection, $config = array()) + { + if (is_string ($connection)) { + $this->db = new Manager($connection); + if (preg_match('/^mongodb:\\/\\/.+\\/([^?&]+)/s', $connection, $matches)) { + $this->database = $matches[1]; + } else { + throw new \InvalidArgumentException("Unable to determine Database Name from dsn."); + } + } elseif (is_array($connection)) { + $a = ['mongodb://']; + if (!empty($connection['username'])) { + $a[] = $connection['username'] . ':'; + } + if (!empty($connection['password'])) { + $a[] = rawurlencode($connection['password']) . '@'; + } + if (!empty($connection['host'])) { + $a[] = $connection['host']; + } + if (!empty($connection['port'])) { + $a[] = ':' . $connection['port']; + } + if (!empty($connection['database'])) { + $a[] = '/' . $connection['database']; + $this->database = $connection['database']; + } + $dsn = implode('', $a); + + $o = !empty($connection['options']) ? $connection['options'] : []; + $options = array_merge([ + 'w' => \MongoDB\Driver\WriteConcern::MAJORITY, + 'j' => true, + 'readPreference' => \MongoDB\Driver\ReadPreference::RP_NEAREST + ], $o); + $driverOptions = !empty($connection['driverOptions']) ? $connection['driverOptions'] : []; + + $this->db = new Manager($dsn, $options, $driverOptions); + } else { + throw new \InvalidArgumentException('First argument to OAuth2\Storage\MongoDB must be a string or a configuration array'); + } + + $this->db->selectServer($this->db->getReadPreference()); + + $this->config = array_merge(array( + 'client_table' => 'oauth_clients', + 'access_token_table' => 'oauth_access_tokens', + 'refresh_token_table' => 'oauth_refresh_tokens', + 'code_table' => 'oauth_authorization_codes', + 'user_table' => 'oauth_users', + 'jwt_table' => 'oauth_jwt', + ), $config); + } + + /* ClientCredentialsInterface */ + public function checkClientCredentials($client_id, $client_secret = null) + { + if ($result = $this->findOne('client_table', ['client_id' => $client_id])) { + return $result['client_secret'] == $client_secret; + } + return false; + } + + /** + * @param string $client_id + * @return boolean + */ + public function isPublicClient($client_id) + { + if (!$result = $this->findOne('client_table', ['client_id' => $client_id])) { + return false; + } + return empty($result['client_secret']); + } + + /* ClientInterface */ + public function getClientDetails($client_id) + { + return $this->findOne('client_table', ['client_id' => $client_id]); + } + + public function setClientDetails($client_id, $client_secret = null, $redirect_uri = null, $grant_types = null, $scope = null, $user_id = null) + { + $bulk = new BulkWrite(); + $bulk->update( + ['client_id' => $client_id], + ['$set' => [ + 'client_id' => $client_id, + 'client_secret' => $client_secret, + 'redirect_uri' => $redirect_uri, + 'grant_types' => $grant_types, + 'scope' => $scope, + 'user_id' => $user_id, + ]], + ['upsert' => true] + ); + $this->db->executeBulkWrite($this->collection('client_table'), $bulk); + return true; + } + + public function unsetClientDetails($client_id) + { + $this->delete('client_table', ['client_id' => $client_id]); + return true; + } + + public function checkRestrictedGrantType($client_id, $grant_type) + { + if ($details = $this->getClientDetails($client_id)) { + if (isset($details['grant_types'])) { + $grant_types = explode(' ', $details['grant_types']); + return in_array($grant_type, $grant_types); + } + } + + // if grant_types are not defined, then none are restricted + return true; + } + + /* AccessTokenInterface */ + public function getAccessToken($access_token) + { + return $this->findOne('access_token_table', ['access_token' => $access_token]); + } + + public function setAccessToken($access_token, $client_id, $user_id, $expires, $scope = null) + { + $bulk = new BulkWrite(); + $bulk->update( + ['access_token' => $access_token], + ['$set' => [ + 'access_token' => $access_token, + 'client_id' => $client_id, + 'expires' => $expires, + 'user_id' => $user_id, + 'scope' => $scope + ]], + ['upsert' => true] + ); + $this->db->executeBulkWrite($this->collection('access_token_table'), $bulk); + return true; + } + + public function unsetAccessToken($access_token) + { + $this->delete('access_token_table', ['access_token' => $access_token]); + return true; + } + + + /* AuthorizationCodeInterface */ + public function getAuthorizationCode($code) + { + return $this->findOne('code_table', ['authorization_code' => $code]); + } + + public function setAuthorizationCode($code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null) + { + $bulk = new BulkWrite(); + $bulk->update( + ['authorization_code' => $code], + ['$set' => [ + 'authorization_code' => $code, + 'client_id' => $client_id, + 'user_id' => $user_id, + 'redirect_uri' => $redirect_uri, + 'expires' => $expires, + 'scope' => $scope, + 'id_token' => $id_token, + ]], + ['upsert' => true] + ); + $this->db->executeBulkWrite($this->collection('code_table'), $bulk); + return true; + } + + public function expireAuthorizationCode($code) + { + $this->delete('code_table', ['authorization_code' => $code]); + return true; + } + + /* UserCredentialsInterface */ + public function checkUserCredentials($username, $password) + { + if ($user = $this->getUser($username)) { + return $this->checkPassword($user, $password); + } + + return false; + } + + public function getUserDetails($username) + { + if ($user = $this->getUser($username)) { + $user['user_id'] = $user['username']; + } + + return $user; + } + + /* RefreshTokenInterface */ + public function getRefreshToken($refresh_token) + { + return $this->findOne('refresh_token_table', ['refresh_token' => $refresh_token]); + } + + public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null) + { + $bulk = new BulkWrite(); + $bulk->update( + ['refresh_token' => $refresh_token], + ['$set' => [ + 'refresh_token' => $refresh_token, + 'client_id' => $client_id, + 'user_id' => $user_id, + 'expires' => $expires, + 'scope' => $scope + ]], + ['upsert' => true] + ); + $this->db->executeBulkWrite($this->collection('refresh_token_table'), $bulk); + return true; + } + + public function unsetRefreshToken($refresh_token) + { + $this->delete('refresh_token_table', ['refresh_token' => $refresh_token]); + return true; + } + + // plaintext passwords are bad! Override this for your application + protected function checkPassword($user, $password) + { + return $user['password'] == $password; + } + + public function getUser($username) + { + return $this->findOne('user_table', ['username' => $username]); + } + + public function setUser($username, $password, $firstName = null, $lastName = null) + { + $bulk = new BulkWrite(); + $bulk->update( + ['username' => $username], + ['$set' => [ + 'username' => $username, + 'password' => $password, + 'first_name' => $firstName, + 'last_name' => $lastName + ]], + ['upsert' => true] + ); + $this->db->executeBulkWrite($this->collection('user_table'), $bulk); + return true; + } + + public function getClientKey($client_id, $subject) + { + $result = $this->findOne('jwt_table', [ + 'client_id' => $client_id, + 'subject' => $subject + ]); + return $result ? $result['key'] : false; + } + + public function getClientScope($client_id) + { + if (!$clientDetails = $this->getClientDetails($client_id)) { + return false; + } + + if (isset($clientDetails['scope'])) { + return $clientDetails['scope']; + } + + return null; + } + + public function getJti($client_id, $subject, $audience, $expiration, $jti) + { + //TODO: Needs mongodb implementation. + throw new \Exception('getJti() for the MongoDB driver is currently unimplemented.'); + } + + public function setJti($client_id, $subject, $audience, $expiration, $jti) + { + //TODO: Needs mongodb implementation. + throw new \Exception('setJti() for the MongoDB driver is currently unimplemented.'); + } + + + protected function collection($name) + { + return $this->database . '.' . $this->config[$name]; + } + + /** + * + * @param string $collection + * @param array $filter + * @return array | false + */ + protected function findOne($collection, $filter) + { + $query = new Query($filter, ['limit' => 1, ['sort' => ['_id' => -1]]]); + $cursor = $this->db + ->executeQuery($this->collection($collection), $query); + $cursor->setTypeMap([ + 'root' => 'array', + 'document' => 'array' + ]); + $result = $cursor->toArray(); + return current($result); + } + + /** + * + * @param string $collection + * @param array $filter + * @return boolean + */ + protected function delete($collection, $filter) + { + $bulk = new BulkWrite(); + $bulk->delete($filter); + $this->db->executeBulkWrite($this->collection($collection), $bulk); + return true; + } +} diff --git a/test/OAuth2/Storage/MongoDBTest.php b/test/OAuth2/Storage/MongoDBTest.php new file mode 100644 index 000000000..715750186 --- /dev/null +++ b/test/OAuth2/Storage/MongoDBTest.php @@ -0,0 +1,120 @@ + + */ +class MongoDBTest extends BaseTest +{ + + public function __construct() { + $mongodb = Bootstrap::getInstance()->getMongoDB(); + } + + public function testSetClientDetails() { + $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + +// comment with Bootstrap::getInstance()->getMongoDB(); +// $db->setClientDetails('oauth_test_client', 'testpass', 'redirect_uri', [], 'map green', 'oauth_test_user_id'); + + $this->assertFalse($db->checkClientCredentials('oauth_test_client')); + $this->assertTrue($db->checkClientCredentials('oauth_test_client', 'testpass')); + $this->assertFalse($db->checkClientCredentials('oauth_test_client', 'testpass!!!!')); + + $db->setClientDetails('oauth_test_client', 'testpass!!!', 'redirect_uri', [], 'map green', 'oauth_test_user_id'); + $this->assertFalse($db->checkClientCredentials('oauth_test_client', 'testpass')); + + $db->unsetClientDetails('oauth_test_client'); + $this->assertFalse($db->checkClientCredentials('oauth_test_client', 'testpass')); + + $db->setClientDetails('oauth_test_client', 'testpass', 'redirect_uri', [], 'map green', 'oauth_test_user_id'); + $this->assertTrue($db->checkClientCredentials('oauth_test_client', 'testpass')); + } + + public function testConnection() { + $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + $this->assertNotFalse($db->getClientDetails('oauth_test_client')); + $db = new MongoDB(['host' => 'localhost', 'port' => '27017', 'database' => 'oauth2_server_php']); + $this->assertNotFalse($db->getClientDetails('oauth_test_client')); + } + + public function testIsPublicClient() { + $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + + $res = $db->isPublicClient('oauth_test_client'); + $this->assertFalse($res); + } + + public function testAccessToken() { + $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + + $this->assertNotFalse($db->getAccessToken('testtoken')); + $db->setAccessToken('testtoken', 'Some Client!!!', 'oauth_test_user_id', 1); + $this->assertEquals($db->getAccessToken('testtoken')['client_id'], 'Some Client!!!'); + $db->unsetAccessToken('testtoken'); + $this->assertFalse($db->getAccessToken('testtoken')); + $db->setAccessToken('testtoken', 'Some Client', 'oauth_test_user_id', 2); + $this->assertNotFalse($db->getAccessToken('testtoken')); + + } + + public function testAuthorizationCode() { + $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + + $this->assertNotFalse($db->getAuthorizationCode('testcode')); + $db->setAuthorizationCode('testcode', 'Some Client!!!', 'oauth_test_user_id', 'http://example.com', 0); + $this->assertEquals($db->getAuthorizationCode('testcode')['client_id'], 'Some Client!!!'); + $db->expireAuthorizationCode('testcode'); + $this->assertFalse($db->getAuthorizationCode('testcode')); + $db->setAuthorizationCode('testcode', 'Some Client', 'oauth_test_user_id', 'http://example.com', 23442); + $this->assertNotFalse($db->getAuthorizationCode('testcode')); + } + + public function testRefreshToken() { + $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + + $this->assertNotFalse($db->getRefreshToken('testrefreshtoken')); + $db->setRefreshToken('testrefreshtoken', 'Some Client!!!', 'oauth_test_user_id', 0); + $this->assertEquals($db->getRefreshToken('testrefreshtoken')['client_id'], 'Some Client!!!'); + $db->unsetRefreshToken('testrefreshtoken'); + $this->assertFalse($db->getRefreshToken('testrefreshtoken')); + $db->setRefreshToken('testrefreshtoken', 'Some Client', 'oauth_test_user_id', 232342); + $this->assertNotFalse($db->getRefreshToken('testrefreshtoken')); + } + + public function testCheckUserCredentials() { + $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + + $this->assertTrue($db->checkUserCredentials('testuser', 'password')); + } + + public function testGetUserDetails() { + $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + $this->assertNotFalse($db->getUserDetails('testuser')); + } + + public function testUser() { + $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + + $this->assertNotFalse($db->getUser('testuser')); + $db->setUser('testuser', 'password123123', 'First Name', 'Last Name'); + $this->assertTrue($db->checkUserCredentials('testuser', 'password123123')); + } + + public function testGetClientKey() { + $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + + $this->assertNotFalse($db->getClientKey('oauth_test_client', 'test_subject')); + } + + public function testGetClientScope() { + $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + + $this->assertStringMatchesFormat('%S', $db->getClientScope('oauth_test_client')); + + } + +} diff --git a/test/lib/OAuth2/Storage/BaseTest.php b/test/lib/OAuth2/Storage/BaseTest.php index 921d52500..34eacfc55 100755 --- a/test/lib/OAuth2/Storage/BaseTest.php +++ b/test/lib/OAuth2/Storage/BaseTest.php @@ -1,34 +1,36 @@ -getMemoryStorage(); - $sqlite = Bootstrap::getInstance()->getSqlitePdo(); - $mysql = Bootstrap::getInstance()->getMysqlPdo(); - $postgres = Bootstrap::getInstance()->getPostgresPdo(); - $mongo = Bootstrap::getInstance()->getMongo(); - $redis = Bootstrap::getInstance()->getRedisStorage(); - $cassandra = Bootstrap::getInstance()->getCassandraStorage(); - $dynamodb = Bootstrap::getInstance()->getDynamoDbStorage(); - $couchbase = Bootstrap::getInstance()->getCouchbase(); - - /* hack until we can fix "default_scope" dependencies in other tests */ - $memory->defaultScope = 'defaultscope1 defaultscope2'; - - return array( - array($memory), - array($sqlite), - array($mysql), - array($postgres), - array($mongo), - array($redis), - array($cassandra), - array($dynamodb), - array($couchbase), - ); - } -} +getMemoryStorage(); + $sqlite = Bootstrap::getInstance()->getSqlitePdo(); + $mysql = Bootstrap::getInstance()->getMysqlPdo(); + $postgres = Bootstrap::getInstance()->getPostgresPdo(); + $mongo = Bootstrap::getInstance()->getMongo(); + $mongodb = Bootstrap::getInstance()->getMongoDB(); + $redis = Bootstrap::getInstance()->getRedisStorage(); + $cassandra = Bootstrap::getInstance()->getCassandraStorage(); + $dynamodb = Bootstrap::getInstance()->getDynamoDbStorage(); + $couchbase = Bootstrap::getInstance()->getCouchbase(); + + /* hack until we can fix "default_scope" dependencies in other tests */ + $memory->defaultScope = 'defaultscope1 defaultscope2'; + + return array( + array($memory), + array($sqlite), + array($mysql), + array($postgres), + array($mongo), + array($mongodb), + array($redis), + array($cassandra), + array($dynamodb), + array($couchbase), + ); + } +} diff --git a/test/lib/OAuth2/Storage/Bootstrap.php b/test/lib/OAuth2/Storage/Bootstrap.php index 4ac9022b1..d926a7343 100755 --- a/test/lib/OAuth2/Storage/Bootstrap.php +++ b/test/lib/OAuth2/Storage/Bootstrap.php @@ -1,888 +1,996 @@ -configDir = __DIR__.'/../../../config'; - } - - public static function getInstance() - { - if (!self::$instance) { - self::$instance = new self(); - } - - return self::$instance; - } - - public function getSqlitePdo() - { - if (!$this->sqlite) { - $this->removeSqliteDb(); - $pdo = new \PDO(sprintf('sqlite://%s', $this->getSqliteDir())); - $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); - $this->createSqliteDb($pdo); - - $this->sqlite = new Pdo($pdo); - } - - return $this->sqlite; - } - - public function getPostgresPdo() - { - if (!$this->postgres) { - if (in_array('pgsql', \PDO::getAvailableDrivers())) { - $this->removePostgresDb(); - $this->createPostgresDb(); - if ($pdo = $this->getPostgresDriver()) { - $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); - $this->populatePostgresDb($pdo); - $this->postgres = new Pdo($pdo); - } - } else { - $this->postgres = new NullStorage('Postgres', 'Missing postgres PDO extension.'); - } - } - - return $this->postgres; - } - - public function getPostgresDriver() - { - try { - $pdo = new \PDO('pgsql:host=localhost;dbname=oauth2_server_php', 'postgres'); - - return $pdo; - } catch (\PDOException $e) { - $this->postgres = new NullStorage('Postgres', $e->getMessage()); - } - } - - public function getMemoryStorage() - { - return new Memory(json_decode(file_get_contents($this->configDir. '/storage.json'), true)); - } - - public function getRedisStorage() - { - if (!$this->redis) { - if (class_exists('Predis\Client')) { - $redis = new \Predis\Client(); - if ($this->testRedisConnection($redis)) { - $redis->flushdb(); - $this->redis = new Redis($redis); - $this->createRedisDb($this->redis); - } else { - $this->redis = new NullStorage('Redis', 'Unable to connect to redis server on port 6379'); - } - } else { - $this->redis = new NullStorage('Redis', 'Missing redis library. Please run "composer.phar require predis/predis:dev-master"'); - } - } - - return $this->redis; - } - - private function testRedisConnection(\Predis\Client $redis) - { - try { - $redis->connect(); - } catch (\Predis\CommunicationException $exception) { - // we were unable to connect to the redis server - return false; - } - - return true; - } - - public function getMysqlPdo() - { - if (!$this->mysql) { - $pdo = null; - try { - $pdo = new \PDO('mysql:host=localhost;', 'root'); - } catch (\PDOException $e) { - $this->mysql = new NullStorage('MySQL', 'Unable to connect to MySQL on root@localhost'); - } - - if ($pdo) { - $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); - $this->removeMysqlDb($pdo); - $this->createMysqlDb($pdo); - - $this->mysql = new Pdo($pdo); - } - } - - return $this->mysql; - } - - public function getMongo() - { - if (!$this->mongo) { - $skipMongo = $this->getEnvVar('SKIP_MONGO_TESTS'); - if (!$skipMongo && class_exists('MongoClient')) { - $mongo = new \MongoClient('mongodb://localhost:27017', array('connect' => false)); - if ($this->testMongoConnection($mongo)) { - $db = $mongo->oauth2_server_php; - $this->removeMongoDb($db); - $this->createMongoDb($db); - - $this->mongo = new Mongo($db); - } else { - $this->mongo = new NullStorage('Mongo', 'Unable to connect to mongo server on "localhost:27017"'); - } - } else { - $this->mongo = new NullStorage('Mongo', 'Missing mongo php extension. Please install mongo.so'); - } - } - - return $this->mongo; - } - - private function testMongoConnection(\MongoClient $mongo) - { - try { - $mongo->connect(); - } catch (\MongoConnectionException $e) { - return false; - } - - return true; - } - - public function getCouchbase() - { - if (!$this->couchbase) { - if ($this->getEnvVar('SKIP_COUCHBASE_TESTS')) { - $this->couchbase = new NullStorage('Couchbase', 'Skipping Couchbase tests'); - } elseif (!class_exists('Couchbase')) { - $this->couchbase = new NullStorage('Couchbase', 'Missing Couchbase php extension. Please install couchbase.so'); - } else { - // round-about way to make sure couchbase is working - // this is required because it throws a "floating point exception" otherwise - $code = "new \Couchbase(array('localhost:8091'), '', '', 'auth', false);"; - $exec = sprintf('php -r "%s"', $code); - $ret = exec($exec, $test, $var); - if ($ret != 0) { - $couchbase = new \Couchbase(array('localhost:8091'), '', '', 'auth', false); - if ($this->testCouchbaseConnection($couchbase)) { - $this->clearCouchbase($couchbase); - $this->createCouchbaseDB($couchbase); - - $this->couchbase = new CouchbaseDB($couchbase); - } else { - $this->couchbase = new NullStorage('Couchbase', 'Unable to connect to Couchbase server on "localhost:8091"'); - } - } else { - $this->couchbase = new NullStorage('Couchbase', 'Error while trying to connect to Couchbase'); - } - } - } - - return $this->couchbase; - } - - private function testCouchbaseConnection(\Couchbase $couchbase) - { - try { - if (count($couchbase->getServers()) > 0) { - return true; - } - } catch (\CouchbaseException $e) { - return false; - } - - return true; - } - - public function getCassandraStorage() - { - if (!$this->cassandra) { - if (class_exists('phpcassa\ColumnFamily')) { - $cassandra = new \phpcassa\Connection\ConnectionPool('oauth2_test', array('127.0.0.1:9160')); - if ($this->testCassandraConnection($cassandra)) { - $this->removeCassandraDb(); - $this->cassandra = new Cassandra($cassandra); - $this->createCassandraDb($this->cassandra); - } else { - $this->cassandra = new NullStorage('Cassandra', 'Unable to connect to cassandra server on "127.0.0.1:9160"'); - } - } else { - $this->cassandra = new NullStorage('Cassandra', 'Missing cassandra library. Please run "composer.phar require thobbs/phpcassa:dev-master"'); - } - } - - return $this->cassandra; - } - - private function testCassandraConnection(\phpcassa\Connection\ConnectionPool $cassandra) - { - try { - new \phpcassa\SystemManager('localhost:9160'); - } catch (\Exception $e) { - return false; - } - - return true; - } - - private function removeCassandraDb() - { - $sys = new \phpcassa\SystemManager('localhost:9160'); - - try { - $sys->drop_keyspace('oauth2_test'); - } catch (\cassandra\InvalidRequestException $e) { - - } - } - - private function createCassandraDb(Cassandra $storage) - { - // create the cassandra keyspace and column family - $sys = new \phpcassa\SystemManager('localhost:9160'); - - $sys->create_keyspace('oauth2_test', array( - "strategy_class" => \phpcassa\Schema\StrategyClass::SIMPLE_STRATEGY, - "strategy_options" => array('replication_factor' => '1') - )); - - $sys->create_column_family('oauth2_test', 'auth'); - $cassandra = new \phpcassa\Connection\ConnectionPool('oauth2_test', array('127.0.0.1:9160')); - $cf = new \phpcassa\ColumnFamily($cassandra, 'auth'); - - // populate the data - $storage->setClientDetails("oauth_test_client", "testpass", "http://example.com", 'implicit password'); - $storage->setAccessToken("testtoken", "Some Client", '', time() + 1000); - $storage->setAuthorizationCode("testcode", "Some Client", '', '', time() + 1000); - - $storage->setScope('supportedscope1 supportedscope2 supportedscope3 supportedscope4'); - $storage->setScope('defaultscope1 defaultscope2', null, 'default'); - - $storage->setScope('clientscope1 clientscope2', 'Test Client ID'); - $storage->setScope('clientscope1 clientscope2', 'Test Client ID', 'default'); - - $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Client ID 2'); - $storage->setScope('clientscope1 clientscope2', 'Test Client ID 2', 'default'); - - $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID'); - $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID', 'default'); - - $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Default Scope Client ID 2'); - $storage->setScope('clientscope3', 'Test Default Scope Client ID 2', 'default'); - - $storage->setClientKey('oauth_test_client', $this->getTestPublicKey(), 'test_subject'); - - $cf->insert("oauth_public_keys:ClientID_One", array('__data' => json_encode(array("public_key" => "client_1_public", "private_key" => "client_1_private", "encryption_algorithm" => "RS256")))); - $cf->insert("oauth_public_keys:ClientID_Two", array('__data' => json_encode(array("public_key" => "client_2_public", "private_key" => "client_2_private", "encryption_algorithm" => "RS256")))); - $cf->insert("oauth_public_keys:", array('__data' => json_encode(array("public_key" => $this->getTestPublicKey(), "private_key" => $this->getTestPrivateKey(), "encryption_algorithm" => "RS256")))); - - $cf->insert("oauth_users:testuser", array('__data' =>json_encode(array("password" => "password", "email" => "testuser@test.com", "email_verified" => true)))); - - } - - private function createSqliteDb(\PDO $pdo) - { - $this->runPdoSql($pdo); - } - - private function removeSqliteDb() - { - if (file_exists($this->getSqliteDir())) { - unlink($this->getSqliteDir()); - } - } - - private function createMysqlDb(\PDO $pdo) - { - $pdo->exec('CREATE DATABASE oauth2_server_php'); - $pdo->exec('USE oauth2_server_php'); - $this->runPdoSql($pdo); - } - - private function removeMysqlDb(\PDO $pdo) - { - $pdo->exec('DROP DATABASE IF EXISTS oauth2_server_php'); - } - - private function createPostgresDb() - { - if (!`psql postgres -tAc "SELECT 1 FROM pg_roles WHERE rolname='postgres'"`) { - `createuser -s -r postgres`; - } - - `createdb -O postgres oauth2_server_php`; - } - - private function populatePostgresDb(\PDO $pdo) - { - $this->runPdoSql($pdo); - } - - private function removePostgresDb() - { - if (trim(`psql -l | grep oauth2_server_php | wc -l`)) { - `dropdb oauth2_server_php`; - } - } - - public function runPdoSql(\PDO $pdo) - { - $storage = new Pdo($pdo); - foreach (explode(';', $storage->getBuildSql()) as $statement) { - $result = $pdo->exec($statement); - } - - // set up scopes - $sql = 'INSERT INTO oauth_scopes (scope) VALUES (?)'; - foreach (explode(' ', 'supportedscope1 supportedscope2 supportedscope3 supportedscope4 clientscope1 clientscope2 clientscope3') as $supportedScope) { - $pdo->prepare($sql)->execute(array($supportedScope)); - } - - $sql = 'INSERT INTO oauth_scopes (scope, is_default) VALUES (?, ?)'; - foreach (array('defaultscope1', 'defaultscope2') as $defaultScope) { - $pdo->prepare($sql)->execute(array($defaultScope, true)); - } - - // set up clients - $sql = 'INSERT INTO oauth_clients (client_id, client_secret, scope, grant_types) VALUES (?, ?, ?, ?)'; - $pdo->prepare($sql)->execute(array('Test Client ID', 'TestSecret', 'clientscope1 clientscope2', null)); - $pdo->prepare($sql)->execute(array('Test Client ID 2', 'TestSecret', 'clientscope1 clientscope2 clientscope3', null)); - $pdo->prepare($sql)->execute(array('Test Default Scope Client ID', 'TestSecret', 'clientscope1 clientscope2', null)); - $pdo->prepare($sql)->execute(array('oauth_test_client', 'testpass', null, 'implicit password')); - - // set up misc - $sql = 'INSERT INTO oauth_access_tokens (access_token, client_id, expires, user_id) VALUES (?, ?, ?, ?)'; - $pdo->prepare($sql)->execute(array('testtoken', 'Some Client', date('Y-m-d H:i:s', strtotime('+1 hour')), null)); - $pdo->prepare($sql)->execute(array('accesstoken-openid-connect', 'Some Client', date('Y-m-d H:i:s', strtotime('+1 hour')), 'testuser')); - - $sql = 'INSERT INTO oauth_authorization_codes (authorization_code, client_id, expires) VALUES (?, ?, ?)'; - $pdo->prepare($sql)->execute(array('testcode', 'Some Client', date('Y-m-d H:i:s', strtotime('+1 hour')))); - - $sql = 'INSERT INTO oauth_users (username, password, email, email_verified) VALUES (?, ?, ?, ?)'; - $pdo->prepare($sql)->execute(array('testuser', 'password', 'testuser@test.com', true)); - - $sql = 'INSERT INTO oauth_public_keys (client_id, public_key, private_key, encryption_algorithm) VALUES (?, ?, ?, ?)'; - $pdo->prepare($sql)->execute(array('ClientID_One', 'client_1_public', 'client_1_private', 'RS256')); - $pdo->prepare($sql)->execute(array('ClientID_Two', 'client_2_public', 'client_2_private', 'RS256')); - - $sql = 'INSERT INTO oauth_public_keys (client_id, public_key, private_key, encryption_algorithm) VALUES (?, ?, ?, ?)'; - $pdo->prepare($sql)->execute(array(null, $this->getTestPublicKey(), $this->getTestPrivateKey(), 'RS256')); - - $sql = 'INSERT INTO oauth_jwt (client_id, subject, public_key) VALUES (?, ?, ?)'; - $pdo->prepare($sql)->execute(array('oauth_test_client', 'test_subject', $this->getTestPublicKey())); - } - - public function getSqliteDir() - { - return $this->configDir. '/test.sqlite'; - } - - public function getConfigDir() - { - return $this->configDir; - } - - private function createCouchbaseDB(\Couchbase $db) - { - $db->set('oauth_clients-oauth_test_client',json_encode(array( - 'client_id' => "oauth_test_client", - 'client_secret' => "testpass", - 'redirect_uri' => "http://example.com", - 'grant_types' => 'implicit password' - ))); - - $db->set('oauth_access_tokens-testtoken',json_encode(array( - 'access_token' => "testtoken", - 'client_id' => "Some Client" - ))); - - $db->set('oauth_authorization_codes-testcode',json_encode(array( - 'access_token' => "testcode", - 'client_id' => "Some Client" - ))); - - $db->set('oauth_users-testuser',json_encode(array( - 'username' => 'testuser', - 'password' => 'password', - 'email' => 'testuser@test.com', - 'email_verified' => true, - ))); - - $db->set('oauth_jwt-oauth_test_client',json_encode(array( - 'client_id' => 'oauth_test_client', - 'key' => $this->getTestPublicKey(), - 'subject' => 'test_subject', - ))); - } - - private function clearCouchbase(\Couchbase $cb) - { - $cb->delete('oauth_authorization_codes-new-openid-code'); - $cb->delete('oauth_access_tokens-newtoken'); - $cb->delete('oauth_authorization_codes-newcode'); - $cb->delete('oauth_refresh_tokens-refreshtoken'); - } - - private function createMongoDb(\MongoDB $db) - { - $db->oauth_clients->insert(array( - 'client_id' => "oauth_test_client", - 'client_secret' => "testpass", - 'redirect_uri' => "http://example.com", - 'grant_types' => 'implicit password' - )); - - $db->oauth_access_tokens->insert(array( - 'access_token' => "testtoken", - 'client_id' => "Some Client" - )); - - $db->oauth_authorization_codes->insert(array( - 'authorization_code' => "testcode", - 'client_id' => "Some Client" - )); - - $db->oauth_users->insert(array( - 'username' => 'testuser', - 'password' => 'password', - 'email' => 'testuser@test.com', - 'email_verified' => true, - )); - - $db->oauth_jwt->insert(array( - 'client_id' => 'oauth_test_client', - 'key' => $this->getTestPublicKey(), - 'subject' => 'test_subject', - )); - } - - private function createRedisDb(Redis $storage) - { - $storage->setClientDetails("oauth_test_client", "testpass", "http://example.com", 'implicit password'); - $storage->setAccessToken("testtoken", "Some Client", '', time() + 1000); - $storage->setAuthorizationCode("testcode", "Some Client", '', '', time() + 1000); - $storage->setUser("testuser", "password"); - - $storage->setScope('supportedscope1 supportedscope2 supportedscope3 supportedscope4'); - $storage->setScope('defaultscope1 defaultscope2', null, 'default'); - - $storage->setScope('clientscope1 clientscope2', 'Test Client ID'); - $storage->setScope('clientscope1 clientscope2', 'Test Client ID', 'default'); - - $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Client ID 2'); - $storage->setScope('clientscope1 clientscope2', 'Test Client ID 2', 'default'); - - $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID'); - $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID', 'default'); - - $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Default Scope Client ID 2'); - $storage->setScope('clientscope3', 'Test Default Scope Client ID 2', 'default'); - - $storage->setClientKey('oauth_test_client', $this->getTestPublicKey(), 'test_subject'); - } - - public function removeMongoDb(\MongoDB $db) - { - $db->drop(); - } - - public function getTestPublicKey() - { - return file_get_contents(__DIR__.'/../../../config/keys/id_rsa.pub'); - } - - private function getTestPrivateKey() - { - return file_get_contents(__DIR__.'/../../../config/keys/id_rsa'); - } - - public function getDynamoDbStorage() - { - if (!$this->dynamodb) { - // only run once per travis build - if (true == $this->getEnvVar('TRAVIS')) { - if (self::DYNAMODB_PHP_VERSION != $this->getEnvVar('TRAVIS_PHP_VERSION')) { - $this->dynamodb = new NullStorage('DynamoDb', 'Skipping for travis.ci - only run once per build'); - - return; - } - } - if (class_exists('\Aws\DynamoDb\DynamoDbClient')) { - if ($client = $this->getDynamoDbClient()) { - // travis runs a unique set of tables per build, to avoid conflict - $prefix = ''; - if ($build_id = $this->getEnvVar('TRAVIS_JOB_NUMBER')) { - $prefix = sprintf('build_%s_', $build_id); - } else { - if (!$this->deleteDynamoDb($client, $prefix, true)) { - return $this->dynamodb = new NullStorage('DynamoDb', 'Timed out while waiting for DynamoDB deletion (30 seconds)'); - } - } - $this->createDynamoDb($client, $prefix); - $this->populateDynamoDb($client, $prefix); - $config = array( - 'client_table' => $prefix.'oauth_clients', - 'access_token_table' => $prefix.'oauth_access_tokens', - 'refresh_token_table' => $prefix.'oauth_refresh_tokens', - 'code_table' => $prefix.'oauth_authorization_codes', - 'user_table' => $prefix.'oauth_users', - 'jwt_table' => $prefix.'oauth_jwt', - 'scope_table' => $prefix.'oauth_scopes', - 'public_key_table' => $prefix.'oauth_public_keys', - ); - $this->dynamodb = new DynamoDB($client, $config); - } elseif (!$this->dynamodb) { - $this->dynamodb = new NullStorage('DynamoDb', 'unable to connect to DynamoDB'); - } - } else { - $this->dynamodb = new NullStorage('DynamoDb', 'Missing DynamoDB library. Please run "composer.phar require aws/aws-sdk-php:dev-master'); - } - } - - return $this->dynamodb; - } - - private function getDynamoDbClient() - { - $config = array(); - // check for environment variables - if (($key = $this->getEnvVar('AWS_ACCESS_KEY_ID')) && ($secret = $this->getEnvVar('AWS_SECRET_KEY'))) { - $config['key'] = $key; - $config['secret'] = $secret; - } else { - // fall back on ~/.aws/credentials file - // @see http://docs.aws.amazon.com/aws-sdk-php/guide/latest/credentials.html#credential-profiles - if (!file_exists($this->getEnvVar('HOME') . '/.aws/credentials')) { - $this->dynamodb = new NullStorage('DynamoDb', 'No aws credentials file found, and no AWS_ACCESS_KEY_ID or AWS_SECRET_KEY environment variable set'); - - return; - } - - // set profile in AWS_PROFILE environment variable, defaults to "default" - $config['profile'] = $this->getEnvVar('AWS_PROFILE', 'default'); - } - - // set region in AWS_REGION environment variable, defaults to "us-east-1" - $config['region'] = $this->getEnvVar('AWS_REGION', \Aws\Common\Enum\Region::US_EAST_1); - - return \Aws\DynamoDb\DynamoDbClient::factory($config); - } - - private function deleteDynamoDb(\Aws\DynamoDb\DynamoDbClient $client, $prefix = null, $waitForDeletion = false) - { - $tablesList = explode(' ', 'oauth_access_tokens oauth_authorization_codes oauth_clients oauth_jwt oauth_public_keys oauth_refresh_tokens oauth_scopes oauth_users'); - $nbTables = count($tablesList); - - // Delete all table. - foreach ($tablesList as $key => $table) { - try { - $client->deleteTable(array('TableName' => $prefix.$table)); - } catch (\Aws\DynamoDb\Exception\DynamoDbException $e) { - // Table does not exist : nothing to do - } - } - - // Wait for deleting - if ($waitForDeletion) { - $retries = 5; - $nbTableDeleted = 0; - while ($nbTableDeleted != $nbTables) { - $nbTableDeleted = 0; - foreach ($tablesList as $key => $table) { - try { - $result = $client->describeTable(array('TableName' => $prefix.$table)); - } catch (\Aws\DynamoDb\Exception\DynamoDbException $e) { - // Table does not exist : nothing to do - $nbTableDeleted++; - } - } - if ($nbTableDeleted != $nbTables) { - if ($retries < 0) { - // we are tired of waiting - return false; - } - sleep(5); - echo "Sleeping 5 seconds for DynamoDB ($retries more retries)...\n"; - $retries--; - } - } - } - - return true; - } - - private function createDynamoDb(\Aws\DynamoDb\DynamoDbClient $client, $prefix = null) - { - $tablesList = explode(' ', 'oauth_access_tokens oauth_authorization_codes oauth_clients oauth_jwt oauth_public_keys oauth_refresh_tokens oauth_scopes oauth_users'); - $nbTables = count($tablesList); - $client->createTable(array( - 'TableName' => $prefix.'oauth_access_tokens', - 'AttributeDefinitions' => array( - array('AttributeName' => 'access_token','AttributeType' => 'S') - ), - 'KeySchema' => array(array('AttributeName' => 'access_token','KeyType' => 'HASH')), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - $client->createTable(array( - 'TableName' => $prefix.'oauth_authorization_codes', - 'AttributeDefinitions' => array( - array('AttributeName' => 'authorization_code','AttributeType' => 'S') - ), - 'KeySchema' => array(array('AttributeName' => 'authorization_code','KeyType' => 'HASH')), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - $client->createTable(array( - 'TableName' => $prefix.'oauth_clients', - 'AttributeDefinitions' => array( - array('AttributeName' => 'client_id','AttributeType' => 'S') - ), - 'KeySchema' => array(array('AttributeName' => 'client_id','KeyType' => 'HASH')), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - $client->createTable(array( - 'TableName' => $prefix.'oauth_jwt', - 'AttributeDefinitions' => array( - array('AttributeName' => 'client_id','AttributeType' => 'S'), - array('AttributeName' => 'subject','AttributeType' => 'S') - ), - 'KeySchema' => array( - array('AttributeName' => 'client_id','KeyType' => 'HASH'), - array('AttributeName' => 'subject','KeyType' => 'RANGE') - ), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - $client->createTable(array( - 'TableName' => $prefix.'oauth_public_keys', - 'AttributeDefinitions' => array( - array('AttributeName' => 'client_id','AttributeType' => 'S') - ), - 'KeySchema' => array(array('AttributeName' => 'client_id','KeyType' => 'HASH')), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - $client->createTable(array( - 'TableName' => $prefix.'oauth_refresh_tokens', - 'AttributeDefinitions' => array( - array('AttributeName' => 'refresh_token','AttributeType' => 'S') - ), - 'KeySchema' => array(array('AttributeName' => 'refresh_token','KeyType' => 'HASH')), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - $client->createTable(array( - 'TableName' => $prefix.'oauth_scopes', - 'AttributeDefinitions' => array( - array('AttributeName' => 'scope','AttributeType' => 'S'), - array('AttributeName' => 'is_default','AttributeType' => 'S') - ), - 'KeySchema' => array(array('AttributeName' => 'scope','KeyType' => 'HASH')), - 'GlobalSecondaryIndexes' => array( - array( - 'IndexName' => 'is_default-index', - 'KeySchema' => array(array('AttributeName' => 'is_default', 'KeyType' => 'HASH')), - 'Projection' => array('ProjectionType' => 'ALL'), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - ), - ), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - $client->createTable(array( - 'TableName' => $prefix.'oauth_users', - 'AttributeDefinitions' => array(array('AttributeName' => 'username','AttributeType' => 'S')), - 'KeySchema' => array(array('AttributeName' => 'username','KeyType' => 'HASH')), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - // Wait for creation - $nbTableCreated = 0; - while ($nbTableCreated != $nbTables) { - $nbTableCreated = 0; - foreach ($tablesList as $key => $table) { - try { - $result = $client->describeTable(array('TableName' => $prefix.$table)); - if ($result['Table']['TableStatus'] == 'ACTIVE') { - $nbTableCreated++; - } - } catch (\Aws\DynamoDb\Exception\DynamoDbException $e) { - // Table does not exist : nothing to do - $nbTableCreated++; - } - } - if ($nbTableCreated != $nbTables) { - sleep(1); - } - } - } - - private function populateDynamoDb($client, $prefix = null) - { - // set up scopes - foreach (explode(' ', 'supportedscope1 supportedscope2 supportedscope3 supportedscope4 clientscope1 clientscope2 clientscope3') as $supportedScope) { - $client->putItem(array( - 'TableName' => $prefix.'oauth_scopes', - 'Item' => array('scope' => array('S' => $supportedScope)) - )); - } - - foreach (array('defaultscope1', 'defaultscope2') as $defaultScope) { - $client->putItem(array( - 'TableName' => $prefix.'oauth_scopes', - 'Item' => array('scope' => array('S' => $defaultScope), 'is_default' => array('S' => "true")) - )); - } - - $client->putItem(array( - 'TableName' => $prefix.'oauth_clients', - 'Item' => array( - 'client_id' => array('S' => 'Test Client ID'), - 'client_secret' => array('S' => 'TestSecret'), - 'scope' => array('S' => 'clientscope1 clientscope2') - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_clients', - 'Item' => array( - 'client_id' => array('S' => 'Test Client ID 2'), - 'client_secret' => array('S' => 'TestSecret'), - 'scope' => array('S' => 'clientscope1 clientscope2 clientscope3') - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_clients', - 'Item' => array( - 'client_id' => array('S' => 'Test Default Scope Client ID'), - 'client_secret' => array('S' => 'TestSecret'), - 'scope' => array('S' => 'clientscope1 clientscope2') - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_clients', - 'Item' => array( - 'client_id' => array('S' => 'oauth_test_client'), - 'client_secret' => array('S' => 'testpass'), - 'grant_types' => array('S' => 'implicit password') - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_access_tokens', - 'Item' => array( - 'access_token' => array('S' => 'testtoken'), - 'client_id' => array('S' => 'Some Client'), - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_access_tokens', - 'Item' => array( - 'access_token' => array('S' => 'accesstoken-openid-connect'), - 'client_id' => array('S' => 'Some Client'), - 'user_id' => array('S' => 'testuser'), - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_authorization_codes', - 'Item' => array( - 'authorization_code' => array('S' => 'testcode'), - 'client_id' => array('S' => 'Some Client'), - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_users', - 'Item' => array( - 'username' => array('S' => 'testuser'), - 'password' => array('S' => 'password'), - 'email' => array('S' => 'testuser@test.com'), - 'email_verified' => array('S' => 'true'), - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_public_keys', - 'Item' => array( - 'client_id' => array('S' => 'ClientID_One'), - 'public_key' => array('S' => 'client_1_public'), - 'private_key' => array('S' => 'client_1_private'), - 'encryption_algorithm' => array('S' => 'RS256'), - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_public_keys', - 'Item' => array( - 'client_id' => array('S' => 'ClientID_Two'), - 'public_key' => array('S' => 'client_2_public'), - 'private_key' => array('S' => 'client_2_private'), - 'encryption_algorithm' => array('S' => 'RS256'), - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_public_keys', - 'Item' => array( - 'client_id' => array('S' => '0'), - 'public_key' => array('S' => $this->getTestPublicKey()), - 'private_key' => array('S' => $this->getTestPrivateKey()), - 'encryption_algorithm' => array('S' => 'RS256'), - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_jwt', - 'Item' => array( - 'client_id' => array('S' => 'oauth_test_client'), - 'subject' => array('S' => 'test_subject'), - 'public_key' => array('S' => $this->getTestPublicKey()), - ) - )); - } - - public function cleanupTravisDynamoDb($prefix = null) - { - if (is_null($prefix)) { - // skip this when not applicable - if (!$this->getEnvVar('TRAVIS') || self::DYNAMODB_PHP_VERSION != $this->getEnvVar('TRAVIS_PHP_VERSION')) { - return; - } - - $prefix = sprintf('build_%s_', $this->getEnvVar('TRAVIS_JOB_NUMBER')); - } - - $client = $this->getDynamoDbClient(); - $this->deleteDynamoDb($client, $prefix); - } - - private function getEnvVar($var, $default = null) - { - return isset($_SERVER[$var]) ? $_SERVER[$var] : (getenv($var) ?: $default); - } -} +configDir = __DIR__.'/../../../config'; + } + + public static function getInstance() + { + if (!self::$instance) { + self::$instance = new self(); + } + + return self::$instance; + } + + public function getSqlitePdo() + { + if (!$this->sqlite) { + $this->removeSqliteDb(); + $pdo = new \PDO(sprintf('sqlite://%s', $this->getSqliteDir())); + $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); + $this->createSqliteDb($pdo); + + $this->sqlite = new Pdo($pdo); + } + + return $this->sqlite; + } + + public function getPostgresPdo() + { + if (!$this->postgres) { + if (in_array('pgsql', \PDO::getAvailableDrivers())) { + $this->removePostgresDb(); + $this->createPostgresDb(); + if ($pdo = $this->getPostgresDriver()) { + $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); + $this->populatePostgresDb($pdo); + $this->postgres = new Pdo($pdo); + } + } else { + $this->postgres = new NullStorage('Postgres', 'Missing postgres PDO extension.'); + } + } + + return $this->postgres; + } + + public function getPostgresDriver() + { + try { + $pdo = new \PDO('pgsql:host=localhost;dbname=oauth2_server_php', 'postgres'); + + return $pdo; + } catch (\PDOException $e) { + $this->postgres = new NullStorage('Postgres', $e->getMessage()); + } + } + + public function getMemoryStorage() + { + return new Memory(json_decode(file_get_contents($this->configDir. '/storage.json'), true)); + } + + public function getRedisStorage() + { + if (!$this->redis) { + if (class_exists('Predis\Client')) { + $redis = new \Predis\Client(); + if ($this->testRedisConnection($redis)) { + $redis->flushdb(); + $this->redis = new Redis($redis); + $this->createRedisDb($this->redis); + } else { + $this->redis = new NullStorage('Redis', 'Unable to connect to redis server on port 6379'); + } + } else { + $this->redis = new NullStorage('Redis', 'Missing redis library. Please run "composer.phar require predis/predis:dev-master"'); + } + } + + return $this->redis; + } + + private function testRedisConnection(\Predis\Client $redis) + { + try { + $redis->connect(); + } catch (\Predis\CommunicationException $exception) { + // we were unable to connect to the redis server + return false; + } + + return true; + } + + public function getMysqlPdo() + { + if (!$this->mysql) { + $pdo = null; + try { + $pdo = new \PDO('mysql:host=localhost;', 'root'); + } catch (\PDOException $e) { + $this->mysql = new NullStorage('MySQL', 'Unable to connect to MySQL on root@localhost'); + } + + if ($pdo) { + $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); + $this->removeMysqlDb($pdo); + $this->createMysqlDb($pdo); + + $this->mysql = new Pdo($pdo); + } + } + + return $this->mysql; + } + + public function getMongo() + { + if (!$this->mongo) { + $skipMongo = $this->getEnvVar('SKIP_MONGO_TESTS'); + if (!$skipMongo && class_exists('MongoClient')) { + $mongo = new \MongoClient('mongodb://localhost:27017', array('connect' => false)); + if ($this->testMongoConnection($mongo)) { + $db = $mongo->oauth2_server_php; + $this->removeMongo($db); + $this->createMongo($db); + $this->mongo = new Mongo($db); + } else { + $this->mongo = new NullStorage('Mongo', 'Unable to connect to mongo server on "localhost:27017"'); + } + } else { + $this->mongo = new NullStorage('Mongo', 'Missing mongo php extension. Please install mongo.so'); + } + } + + return $this->mongo; + } + + private function testMongoConnection(\MongoClient $mongo) + { + try { + $mongo->connect(); + } catch (\MongoConnectionException $e) { + return false; + } + + return true; + } + + public function getMongoDB() + { + if (!$this->mongodb) { + $skipMongo = $this->getEnvVar('SKIP_MONGODB_TESTS'); + if (!$skipMongo && class_exists('\MongoDB\Driver\Manager')) { + try { + $this->mongodb = new \MongoDB\Driver\Manager('mongodb://localhost:27017'); + $this->mongodb->selectServer($this->mongodb->getReadPreference()); + } catch (\Exception $e) { + $this->mongodb = new NullStorage('MongoDB', 'Unable to connect to mongoDB server on "localhost:27017"'); + } + $this->removeMongoDB(); + $this->createMongoDB(); + } else { + $this->mongodb = new NullStorage('MongoDB', 'Missing mongoDB php extension. Please install mongodb.so'); + } + } + + return $this->mongodb; + } + + public function getCouchbase() + { + if (!$this->couchbase) { + if ($this->getEnvVar('SKIP_COUCHBASE_TESTS')) { + $this->couchbase = new NullStorage('Couchbase', 'Skipping Couchbase tests'); + } elseif (!class_exists('Couchbase')) { + $this->couchbase = new NullStorage('Couchbase', 'Missing Couchbase php extension. Please install couchbase.so'); + } else { + // round-about way to make sure couchbase is working + // this is required because it throws a "floating point exception" otherwise + $code = "new \Couchbase(array('localhost:8091'), '', '', 'auth', false);"; + $exec = sprintf('php -r "%s"', $code); + $ret = exec($exec, $test, $var); + if ($ret != 0) { + $couchbase = new \Couchbase(array('localhost:8091'), '', '', 'auth', false); + if ($this->testCouchbaseConnection($couchbase)) { + $this->clearCouchbase($couchbase); + $this->createCouchbaseDB($couchbase); + + $this->couchbase = new CouchbaseDB($couchbase); + } else { + $this->couchbase = new NullStorage('Couchbase', 'Unable to connect to Couchbase server on "localhost:8091"'); + } + } else { + $this->couchbase = new NullStorage('Couchbase', 'Error while trying to connect to Couchbase'); + } + } + } + + return $this->couchbase; + } + + private function testCouchbaseConnection(\Couchbase $couchbase) + { + try { + if (count($couchbase->getServers()) > 0) { + return true; + } + } catch (\CouchbaseException $e) { + return false; + } + + return true; + } + + public function getCassandraStorage() + { + if (!$this->cassandra) { + if (class_exists('phpcassa\ColumnFamily')) { + $cassandra = new \phpcassa\Connection\ConnectionPool('oauth2_test', array('127.0.0.1:9160')); + if ($this->testCassandraConnection($cassandra)) { + $this->removeCassandraDb(); + $this->cassandra = new Cassandra($cassandra); + $this->createCassandraDb($this->cassandra); + } else { + $this->cassandra = new NullStorage('Cassandra', 'Unable to connect to cassandra server on "127.0.0.1:9160"'); + } + } else { + $this->cassandra = new NullStorage('Cassandra', 'Missing cassandra library. Please run "composer.phar require thobbs/phpcassa:dev-master"'); + } + } + + return $this->cassandra; + } + + private function testCassandraConnection(\phpcassa\Connection\ConnectionPool $cassandra) + { + try { + new \phpcassa\SystemManager('localhost:9160'); + } catch (\Exception $e) { + return false; + } + + return true; + } + + private function removeCassandraDb() + { + $sys = new \phpcassa\SystemManager('localhost:9160'); + + try { + $sys->drop_keyspace('oauth2_test'); + } catch (\cassandra\InvalidRequestException $e) { + + } + } + + private function createCassandraDb(Cassandra $storage) + { + // create the cassandra keyspace and column family + $sys = new \phpcassa\SystemManager('localhost:9160'); + + $sys->create_keyspace('oauth2_test', array( + "strategy_class" => \phpcassa\Schema\StrategyClass::SIMPLE_STRATEGY, + "strategy_options" => array('replication_factor' => '1') + )); + + $sys->create_column_family('oauth2_test', 'auth'); + $cassandra = new \phpcassa\Connection\ConnectionPool('oauth2_test', array('127.0.0.1:9160')); + $cf = new \phpcassa\ColumnFamily($cassandra, 'auth'); + + // populate the data + $storage->setClientDetails("oauth_test_client", "testpass", "http://example.com", 'implicit password'); + $storage->setAccessToken("testtoken", "Some Client", '', time() + 1000); + $storage->setAuthorizationCode("testcode", "Some Client", '', '', time() + 1000); + + $storage->setScope('supportedscope1 supportedscope2 supportedscope3 supportedscope4'); + $storage->setScope('defaultscope1 defaultscope2', null, 'default'); + + $storage->setScope('clientscope1 clientscope2', 'Test Client ID'); + $storage->setScope('clientscope1 clientscope2', 'Test Client ID', 'default'); + + $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Client ID 2'); + $storage->setScope('clientscope1 clientscope2', 'Test Client ID 2', 'default'); + + $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID'); + $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID', 'default'); + + $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Default Scope Client ID 2'); + $storage->setScope('clientscope3', 'Test Default Scope Client ID 2', 'default'); + + $storage->setClientKey('oauth_test_client', $this->getTestPublicKey(), 'test_subject'); + + $cf->insert("oauth_public_keys:ClientID_One", array('__data' => json_encode(array("public_key" => "client_1_public", "private_key" => "client_1_private", "encryption_algorithm" => "RS256")))); + $cf->insert("oauth_public_keys:ClientID_Two", array('__data' => json_encode(array("public_key" => "client_2_public", "private_key" => "client_2_private", "encryption_algorithm" => "RS256")))); + $cf->insert("oauth_public_keys:", array('__data' => json_encode(array("public_key" => $this->getTestPublicKey(), "private_key" => $this->getTestPrivateKey(), "encryption_algorithm" => "RS256")))); + + $cf->insert("oauth_users:testuser", array('__data' =>json_encode(array("password" => "password", "email" => "testuser@test.com", "email_verified" => true)))); + + } + + private function createSqliteDb(\PDO $pdo) + { + $this->runPdoSql($pdo); + } + + private function removeSqliteDb() + { + if (file_exists($this->getSqliteDir())) { + unlink($this->getSqliteDir()); + } + } + + private function createMysqlDb(\PDO $pdo) + { + $pdo->exec('CREATE DATABASE oauth2_server_php'); + $pdo->exec('USE oauth2_server_php'); + $this->runPdoSql($pdo); + } + + private function removeMysqlDb(\PDO $pdo) + { + $pdo->exec('DROP DATABASE IF EXISTS oauth2_server_php'); + } + + private function createPostgresDb() + { + if (!`psql postgres -tAc "SELECT 1 FROM pg_roles WHERE rolname='postgres'"`) { + `createuser -s -r postgres`; + } + + `createdb -O postgres oauth2_server_php`; + } + + private function populatePostgresDb(\PDO $pdo) + { + $this->runPdoSql($pdo); + } + + private function removePostgresDb() + { + if (trim(`psql -l | grep oauth2_server_php | wc -l`)) { + `dropdb oauth2_server_php`; + } + } + + public function runPdoSql(\PDO $pdo) + { + $storage = new Pdo($pdo); + foreach (explode(';', $storage->getBuildSql()) as $statement) { + $result = $pdo->exec($statement); + } + + // set up scopes + $sql = 'INSERT INTO oauth_scopes (scope) VALUES (?)'; + foreach (explode(' ', 'supportedscope1 supportedscope2 supportedscope3 supportedscope4 clientscope1 clientscope2 clientscope3') as $supportedScope) { + $pdo->prepare($sql)->execute(array($supportedScope)); + } + + $sql = 'INSERT INTO oauth_scopes (scope, is_default) VALUES (?, ?)'; + foreach (array('defaultscope1', 'defaultscope2') as $defaultScope) { + $pdo->prepare($sql)->execute(array($defaultScope, true)); + } + + // set up clients + $sql = 'INSERT INTO oauth_clients (client_id, client_secret, scope, grant_types) VALUES (?, ?, ?, ?)'; + $pdo->prepare($sql)->execute(array('Test Client ID', 'TestSecret', 'clientscope1 clientscope2', null)); + $pdo->prepare($sql)->execute(array('Test Client ID 2', 'TestSecret', 'clientscope1 clientscope2 clientscope3', null)); + $pdo->prepare($sql)->execute(array('Test Default Scope Client ID', 'TestSecret', 'clientscope1 clientscope2', null)); + $pdo->prepare($sql)->execute(array('oauth_test_client', 'testpass', null, 'implicit password')); + + // set up misc + $sql = 'INSERT INTO oauth_access_tokens (access_token, client_id, expires, user_id) VALUES (?, ?, ?, ?)'; + $pdo->prepare($sql)->execute(array('testtoken', 'Some Client', date('Y-m-d H:i:s', strtotime('+1 hour')), null)); + $pdo->prepare($sql)->execute(array('accesstoken-openid-connect', 'Some Client', date('Y-m-d H:i:s', strtotime('+1 hour')), 'testuser')); + + $sql = 'INSERT INTO oauth_authorization_codes (authorization_code, client_id, expires) VALUES (?, ?, ?)'; + $pdo->prepare($sql)->execute(array('testcode', 'Some Client', date('Y-m-d H:i:s', strtotime('+1 hour')))); + + $sql = 'INSERT INTO oauth_users (username, password, email, email_verified) VALUES (?, ?, ?, ?)'; + $pdo->prepare($sql)->execute(array('testuser', 'password', 'testuser@test.com', true)); + + $sql = 'INSERT INTO oauth_public_keys (client_id, public_key, private_key, encryption_algorithm) VALUES (?, ?, ?, ?)'; + $pdo->prepare($sql)->execute(array('ClientID_One', 'client_1_public', 'client_1_private', 'RS256')); + $pdo->prepare($sql)->execute(array('ClientID_Two', 'client_2_public', 'client_2_private', 'RS256')); + + $sql = 'INSERT INTO oauth_public_keys (client_id, public_key, private_key, encryption_algorithm) VALUES (?, ?, ?, ?)'; + $pdo->prepare($sql)->execute(array(null, $this->getTestPublicKey(), $this->getTestPrivateKey(), 'RS256')); + + $sql = 'INSERT INTO oauth_jwt (client_id, subject, public_key) VALUES (?, ?, ?)'; + $pdo->prepare($sql)->execute(array('oauth_test_client', 'test_subject', $this->getTestPublicKey())); + } + + public function getSqliteDir() + { + return $this->configDir. '/test.sqlite'; + } + + public function getConfigDir() + { + return $this->configDir; + } + + private function createCouchbaseDB(\Couchbase $db) + { + $db->set('oauth_clients-oauth_test_client',json_encode(array( + 'client_id' => "oauth_test_client", + 'client_secret' => "testpass", + 'redirect_uri' => "http://example.com", + 'grant_types' => 'implicit password' + ))); + + $db->set('oauth_access_tokens-testtoken',json_encode(array( + 'access_token' => "testtoken", + 'client_id' => "Some Client" + ))); + + $db->set('oauth_authorization_codes-testcode',json_encode(array( + 'access_token' => "testcode", + 'client_id' => "Some Client" + ))); + + $db->set('oauth_users-testuser',json_encode(array( + 'username' => 'testuser', + 'password' => 'password', + 'email' => 'testuser@test.com', + 'email_verified' => true, + ))); + + $db->set('oauth_jwt-oauth_test_client',json_encode(array( + 'client_id' => 'oauth_test_client', + 'key' => $this->getTestPublicKey(), + 'subject' => 'test_subject', + ))); + } + + private function clearCouchbase(\Couchbase $cb) + { + $cb->delete('oauth_authorization_codes-new-openid-code'); + $cb->delete('oauth_access_tokens-newtoken'); + $cb->delete('oauth_authorization_codes-newcode'); + $cb->delete('oauth_refresh_tokens-refreshtoken'); + } + + private function createMongo(\MongoDB $db) + { + $db->oauth_clients->insert(array( + 'client_id' => "oauth_test_client", + 'client_secret' => "testpass", + 'redirect_uri' => "http://example.com", + 'grant_types' => 'implicit password' + )); + + $db->oauth_access_tokens->insert(array( + 'access_token' => "testtoken", + 'client_id' => "Some Client" + )); + + $db->oauth_authorization_codes->insert(array( + 'authorization_code' => "testcode", + 'client_id' => "Some Client" + )); + + $db->oauth_users->insert(array( + 'username' => 'testuser', + 'password' => 'password', + 'email' => 'testuser@test.com', + 'email_verified' => true, + )); + + $db->oauth_jwt->insert(array( + 'client_id' => 'oauth_test_client', + 'key' => $this->getTestPublicKey(), + 'subject' => 'test_subject', + )); + } + + private function createMongoDB() + { + $bulk = new \MongoDB\Driver\BulkWrite(); + $bulk->insert([ + 'client_id' => "oauth_test_client", + 'client_secret' => "testpass", + 'redirect_uri' => "http://example.com", + 'grant_types' => 'implicit password', + 'scope' => 'clientscope1 clientscope2' + ]); + $bulk->insert([ + 'client_id' => "oauth_test_client2", + 'client_secret' => "testpass2", + 'redirect_uri' => "http://example.com", + 'grant_types' => 'implicit password', + 'scope' => 'clientscope3 clientscope4' + ]); + $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_clients', $bulk); + + $bulk = new \MongoDB\Driver\BulkWrite(); + $bulk->insert([ + 'access_token' => "testtoken", + 'client_id' => "Some Client" + ]); + $bulk->insert([ + 'access_token' => "testtoken2", + 'client_id' => "Some Client2" + ]); + $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_access_tokens', $bulk); + + $bulk = new \MongoDB\Driver\BulkWrite(); + $bulk->insert([ + 'authorization_code' => "testcode", + 'client_id' => "Some Client" + ]); + $bulk->insert([ + 'authorization_code' => "testcode2", + 'client_id' => "Some Client2" + ]); + $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_authorization_codes', $bulk); + + $bulk = new \MongoDB\Driver\BulkWrite(); + $bulk->insert([ + 'refresh_token' => 'testrefreshtoken', + 'client_id' => 'Some Client', + ]); + $bulk->insert([ + 'refresh_token' => 'testrefreshtoken2', + 'client_id' => 'Some Client2', + ]); + $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_refresh_tokens', $bulk); + + $bulk = new \MongoDB\Driver\BulkWrite(); + $bulk->insert([ + 'username' => 'testuser', + 'password' => 'password', + 'email' => 'testuser@test.com', + 'email_verified' => true, + ]); + $bulk->insert([ + 'username' => 'testuser2', + 'password' => 'password2', + 'email' => 'testuser@test.com', + 'email_verified' => true, + ]); + $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_users', $bulk); + + $bulk = new \MongoDB\Driver\BulkWrite(); + $bulk->insert([ + 'client_id' => 'oauth_test_client', + 'key' => $this->getTestPublicKey(), + 'subject' => 'test_subject', + ]); + $bulk->insert([ + 'client_id' => 'oauth_test_client2', + 'key' => $this->getTestPublicKey(), + 'subject' => 'test_subject2', + ]); + $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_jwt', $bulk); + } + + private function createRedisDb(Redis $storage) + { + $storage->setClientDetails("oauth_test_client", "testpass", "http://example.com", 'implicit password'); + $storage->setAccessToken("testtoken", "Some Client", '', time() + 1000); + $storage->setAuthorizationCode("testcode", "Some Client", '', '', time() + 1000); + $storage->setUser("testuser", "password"); + + $storage->setScope('supportedscope1 supportedscope2 supportedscope3 supportedscope4'); + $storage->setScope('defaultscope1 defaultscope2', null, 'default'); + + $storage->setScope('clientscope1 clientscope2', 'Test Client ID'); + $storage->setScope('clientscope1 clientscope2', 'Test Client ID', 'default'); + + $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Client ID 2'); + $storage->setScope('clientscope1 clientscope2', 'Test Client ID 2', 'default'); + + $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID'); + $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID', 'default'); + + $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Default Scope Client ID 2'); + $storage->setScope('clientscope3', 'Test Default Scope Client ID 2', 'default'); + + $storage->setClientKey('oauth_test_client', $this->getTestPublicKey(), 'test_subject'); + } + + public function removeMongo(\MongoDB $db) + { + $db->drop(); + } + + public function removeMongoDB() + { + $command = new \MongoDB\Driver\Command(['dropDatabase' => 1]); + $this->mongodb->executeCommand('oauth2_server_php', $command); + } + + public function getTestPublicKey() + { + return file_get_contents(__DIR__.'/../../../config/keys/id_rsa.pub'); + } + + private function getTestPrivateKey() + { + return file_get_contents(__DIR__.'/../../../config/keys/id_rsa'); + } + + public function getDynamoDbStorage() + { + if (!$this->dynamodb) { + // only run once per travis build + if (true == $this->getEnvVar('TRAVIS')) { + if (self::DYNAMODB_PHP_VERSION != $this->getEnvVar('TRAVIS_PHP_VERSION')) { + $this->dynamodb = new NullStorage('DynamoDb', 'Skipping for travis.ci - only run once per build'); + + return; + } + } + if (class_exists('\Aws\DynamoDb\DynamoDbClient')) { + if ($client = $this->getDynamoDbClient()) { + // travis runs a unique set of tables per build, to avoid conflict + $prefix = ''; + if ($build_id = $this->getEnvVar('TRAVIS_JOB_NUMBER')) { + $prefix = sprintf('build_%s_', $build_id); + } else { + if (!$this->deleteDynamoDb($client, $prefix, true)) { + return $this->dynamodb = new NullStorage('DynamoDb', 'Timed out while waiting for DynamoDB deletion (30 seconds)'); + } + } + $this->createDynamoDb($client, $prefix); + $this->populateDynamoDb($client, $prefix); + $config = array( + 'client_table' => $prefix.'oauth_clients', + 'access_token_table' => $prefix.'oauth_access_tokens', + 'refresh_token_table' => $prefix.'oauth_refresh_tokens', + 'code_table' => $prefix.'oauth_authorization_codes', + 'user_table' => $prefix.'oauth_users', + 'jwt_table' => $prefix.'oauth_jwt', + 'scope_table' => $prefix.'oauth_scopes', + 'public_key_table' => $prefix.'oauth_public_keys', + ); + $this->dynamodb = new DynamoDB($client, $config); + } elseif (!$this->dynamodb) { + $this->dynamodb = new NullStorage('DynamoDb', 'unable to connect to DynamoDB'); + } + } else { + $this->dynamodb = new NullStorage('DynamoDb', 'Missing DynamoDB library. Please run "composer.phar require aws/aws-sdk-php:dev-master'); + } + } + + return $this->dynamodb; + } + + private function getDynamoDbClient() + { + $config = array(); + // check for environment variables + if (($key = $this->getEnvVar('AWS_ACCESS_KEY_ID')) && ($secret = $this->getEnvVar('AWS_SECRET_KEY'))) { + $config['key'] = $key; + $config['secret'] = $secret; + } else { + // fall back on ~/.aws/credentials file + // @see http://docs.aws.amazon.com/aws-sdk-php/guide/latest/credentials.html#credential-profiles + if (!file_exists($this->getEnvVar('HOME') . '/.aws/credentials')) { + $this->dynamodb = new NullStorage('DynamoDb', 'No aws credentials file found, and no AWS_ACCESS_KEY_ID or AWS_SECRET_KEY environment variable set'); + + return; + } + + // set profile in AWS_PROFILE environment variable, defaults to "default" + $config['profile'] = $this->getEnvVar('AWS_PROFILE', 'default'); + } + + // set region in AWS_REGION environment variable, defaults to "us-east-1" + $config['region'] = $this->getEnvVar('AWS_REGION', \Aws\Common\Enum\Region::US_EAST_1); + + return \Aws\DynamoDb\DynamoDbClient::factory($config); + } + + private function deleteDynamoDb(\Aws\DynamoDb\DynamoDbClient $client, $prefix = null, $waitForDeletion = false) + { + $tablesList = explode(' ', 'oauth_access_tokens oauth_authorization_codes oauth_clients oauth_jwt oauth_public_keys oauth_refresh_tokens oauth_scopes oauth_users'); + $nbTables = count($tablesList); + + // Delete all table. + foreach ($tablesList as $key => $table) { + try { + $client->deleteTable(array('TableName' => $prefix.$table)); + } catch (\Aws\DynamoDb\Exception\DynamoDbException $e) { + // Table does not exist : nothing to do + } + } + + // Wait for deleting + if ($waitForDeletion) { + $retries = 5; + $nbTableDeleted = 0; + while ($nbTableDeleted != $nbTables) { + $nbTableDeleted = 0; + foreach ($tablesList as $key => $table) { + try { + $result = $client->describeTable(array('TableName' => $prefix.$table)); + } catch (\Aws\DynamoDb\Exception\DynamoDbException $e) { + // Table does not exist : nothing to do + $nbTableDeleted++; + } + } + if ($nbTableDeleted != $nbTables) { + if ($retries < 0) { + // we are tired of waiting + return false; + } + sleep(5); + echo "Sleeping 5 seconds for DynamoDB ($retries more retries)...\n"; + $retries--; + } + } + } + + return true; + } + + private function createDynamoDb(\Aws\DynamoDb\DynamoDbClient $client, $prefix = null) + { + $tablesList = explode(' ', 'oauth_access_tokens oauth_authorization_codes oauth_clients oauth_jwt oauth_public_keys oauth_refresh_tokens oauth_scopes oauth_users'); + $nbTables = count($tablesList); + $client->createTable(array( + 'TableName' => $prefix.'oauth_access_tokens', + 'AttributeDefinitions' => array( + array('AttributeName' => 'access_token','AttributeType' => 'S') + ), + 'KeySchema' => array(array('AttributeName' => 'access_token','KeyType' => 'HASH')), + 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) + )); + + $client->createTable(array( + 'TableName' => $prefix.'oauth_authorization_codes', + 'AttributeDefinitions' => array( + array('AttributeName' => 'authorization_code','AttributeType' => 'S') + ), + 'KeySchema' => array(array('AttributeName' => 'authorization_code','KeyType' => 'HASH')), + 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) + )); + + $client->createTable(array( + 'TableName' => $prefix.'oauth_clients', + 'AttributeDefinitions' => array( + array('AttributeName' => 'client_id','AttributeType' => 'S') + ), + 'KeySchema' => array(array('AttributeName' => 'client_id','KeyType' => 'HASH')), + 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) + )); + + $client->createTable(array( + 'TableName' => $prefix.'oauth_jwt', + 'AttributeDefinitions' => array( + array('AttributeName' => 'client_id','AttributeType' => 'S'), + array('AttributeName' => 'subject','AttributeType' => 'S') + ), + 'KeySchema' => array( + array('AttributeName' => 'client_id','KeyType' => 'HASH'), + array('AttributeName' => 'subject','KeyType' => 'RANGE') + ), + 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) + )); + + $client->createTable(array( + 'TableName' => $prefix.'oauth_public_keys', + 'AttributeDefinitions' => array( + array('AttributeName' => 'client_id','AttributeType' => 'S') + ), + 'KeySchema' => array(array('AttributeName' => 'client_id','KeyType' => 'HASH')), + 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) + )); + + $client->createTable(array( + 'TableName' => $prefix.'oauth_refresh_tokens', + 'AttributeDefinitions' => array( + array('AttributeName' => 'refresh_token','AttributeType' => 'S') + ), + 'KeySchema' => array(array('AttributeName' => 'refresh_token','KeyType' => 'HASH')), + 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) + )); + + $client->createTable(array( + 'TableName' => $prefix.'oauth_scopes', + 'AttributeDefinitions' => array( + array('AttributeName' => 'scope','AttributeType' => 'S'), + array('AttributeName' => 'is_default','AttributeType' => 'S') + ), + 'KeySchema' => array(array('AttributeName' => 'scope','KeyType' => 'HASH')), + 'GlobalSecondaryIndexes' => array( + array( + 'IndexName' => 'is_default-index', + 'KeySchema' => array(array('AttributeName' => 'is_default', 'KeyType' => 'HASH')), + 'Projection' => array('ProjectionType' => 'ALL'), + 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) + ), + ), + 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) + )); + + $client->createTable(array( + 'TableName' => $prefix.'oauth_users', + 'AttributeDefinitions' => array(array('AttributeName' => 'username','AttributeType' => 'S')), + 'KeySchema' => array(array('AttributeName' => 'username','KeyType' => 'HASH')), + 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) + )); + + // Wait for creation + $nbTableCreated = 0; + while ($nbTableCreated != $nbTables) { + $nbTableCreated = 0; + foreach ($tablesList as $key => $table) { + try { + $result = $client->describeTable(array('TableName' => $prefix.$table)); + if ($result['Table']['TableStatus'] == 'ACTIVE') { + $nbTableCreated++; + } + } catch (\Aws\DynamoDb\Exception\DynamoDbException $e) { + // Table does not exist : nothing to do + $nbTableCreated++; + } + } + if ($nbTableCreated != $nbTables) { + sleep(1); + } + } + } + + private function populateDynamoDb($client, $prefix = null) + { + // set up scopes + foreach (explode(' ', 'supportedscope1 supportedscope2 supportedscope3 supportedscope4 clientscope1 clientscope2 clientscope3') as $supportedScope) { + $client->putItem(array( + 'TableName' => $prefix.'oauth_scopes', + 'Item' => array('scope' => array('S' => $supportedScope)) + )); + } + + foreach (array('defaultscope1', 'defaultscope2') as $defaultScope) { + $client->putItem(array( + 'TableName' => $prefix.'oauth_scopes', + 'Item' => array('scope' => array('S' => $defaultScope), 'is_default' => array('S' => "true")) + )); + } + + $client->putItem(array( + 'TableName' => $prefix.'oauth_clients', + 'Item' => array( + 'client_id' => array('S' => 'Test Client ID'), + 'client_secret' => array('S' => 'TestSecret'), + 'scope' => array('S' => 'clientscope1 clientscope2') + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_clients', + 'Item' => array( + 'client_id' => array('S' => 'Test Client ID 2'), + 'client_secret' => array('S' => 'TestSecret'), + 'scope' => array('S' => 'clientscope1 clientscope2 clientscope3') + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_clients', + 'Item' => array( + 'client_id' => array('S' => 'Test Default Scope Client ID'), + 'client_secret' => array('S' => 'TestSecret'), + 'scope' => array('S' => 'clientscope1 clientscope2') + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_clients', + 'Item' => array( + 'client_id' => array('S' => 'oauth_test_client'), + 'client_secret' => array('S' => 'testpass'), + 'grant_types' => array('S' => 'implicit password') + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_access_tokens', + 'Item' => array( + 'access_token' => array('S' => 'testtoken'), + 'client_id' => array('S' => 'Some Client'), + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_access_tokens', + 'Item' => array( + 'access_token' => array('S' => 'accesstoken-openid-connect'), + 'client_id' => array('S' => 'Some Client'), + 'user_id' => array('S' => 'testuser'), + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_authorization_codes', + 'Item' => array( + 'authorization_code' => array('S' => 'testcode'), + 'client_id' => array('S' => 'Some Client'), + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_users', + 'Item' => array( + 'username' => array('S' => 'testuser'), + 'password' => array('S' => 'password'), + 'email' => array('S' => 'testuser@test.com'), + 'email_verified' => array('S' => 'true'), + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_public_keys', + 'Item' => array( + 'client_id' => array('S' => 'ClientID_One'), + 'public_key' => array('S' => 'client_1_public'), + 'private_key' => array('S' => 'client_1_private'), + 'encryption_algorithm' => array('S' => 'RS256'), + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_public_keys', + 'Item' => array( + 'client_id' => array('S' => 'ClientID_Two'), + 'public_key' => array('S' => 'client_2_public'), + 'private_key' => array('S' => 'client_2_private'), + 'encryption_algorithm' => array('S' => 'RS256'), + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_public_keys', + 'Item' => array( + 'client_id' => array('S' => '0'), + 'public_key' => array('S' => $this->getTestPublicKey()), + 'private_key' => array('S' => $this->getTestPrivateKey()), + 'encryption_algorithm' => array('S' => 'RS256'), + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_jwt', + 'Item' => array( + 'client_id' => array('S' => 'oauth_test_client'), + 'subject' => array('S' => 'test_subject'), + 'public_key' => array('S' => $this->getTestPublicKey()), + ) + )); + } + + public function cleanupTravisDynamoDb($prefix = null) + { + if (is_null($prefix)) { + // skip this when not applicable + if (!$this->getEnvVar('TRAVIS') || self::DYNAMODB_PHP_VERSION != $this->getEnvVar('TRAVIS_PHP_VERSION')) { + return; + } + + $prefix = sprintf('build_%s_', $this->getEnvVar('TRAVIS_JOB_NUMBER')); + } + + $client = $this->getDynamoDbClient(); + $this->deleteDynamoDb($client, $prefix); + } + + private function getEnvVar($var, $default = null) + { + return isset($_SERVER[$var]) ? $_SERVER[$var] : (getenv($var) ?: $default); + } +} From 78e3a14dcb0d41b25f0d2d7dfb117ec29aefc4f0 Mon Sep 17 00:00:00 2001 From: Roman Shuplov Date: Mon, 29 Aug 2016 19:07:55 +0400 Subject: [PATCH 2/4] made changes to the code for compatibility to php v.5.3 and common code base --- .travis.yml | 5 + src/OAuth2/Storage/MongoDB.php | 732 ++++----- test/OAuth2/Storage/MongoDBTest.php | 38 +- test/lib/OAuth2/Storage/BaseTest.php | 72 +- test/lib/OAuth2/Storage/Bootstrap.php | 1995 +++++++++++++------------ 5 files changed, 1431 insertions(+), 1411 deletions(-) diff --git a/.travis.yml b/.travis.yml index dd4aae4a6..4f634b00c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,6 +22,11 @@ services: - cassandra before_install: - phpenv config-rm xdebug.ini || return 0 +- if [[ ${TRAVIS_PHP_VERSION:0:3} == "7.0" ]]; then + phpenv config-add testing/mongodb.ini; + elif [[ ${TRAVIS_PHP_VERSION:0:3} != "5.3" ]]; then + pecl install mongodb || /bin/true; + fi install: - composer install --no-interaction before_script: diff --git a/src/OAuth2/Storage/MongoDB.php b/src/OAuth2/Storage/MongoDB.php index 2d1f2cb3a..d203d6eb6 100644 --- a/src/OAuth2/Storage/MongoDB.php +++ b/src/OAuth2/Storage/MongoDB.php @@ -1,366 +1,366 @@ - - */ -class MongoDB implements AuthorizationCodeInterface, - AccessTokenInterface, - ClientCredentialsInterface, - UserCredentialsInterface, - RefreshTokenInterface, - JwtBearerInterface, - OpenIDAuthorizationCodeInterface -{ - protected $db; - protected $database; - protected $config; - - public function __construct($connection, $config = array()) - { - if (is_string ($connection)) { - $this->db = new Manager($connection); - if (preg_match('/^mongodb:\\/\\/.+\\/([^?&]+)/s', $connection, $matches)) { - $this->database = $matches[1]; - } else { - throw new \InvalidArgumentException("Unable to determine Database Name from dsn."); - } - } elseif (is_array($connection)) { - $a = ['mongodb://']; - if (!empty($connection['username'])) { - $a[] = $connection['username'] . ':'; - } - if (!empty($connection['password'])) { - $a[] = rawurlencode($connection['password']) . '@'; - } - if (!empty($connection['host'])) { - $a[] = $connection['host']; - } - if (!empty($connection['port'])) { - $a[] = ':' . $connection['port']; - } - if (!empty($connection['database'])) { - $a[] = '/' . $connection['database']; - $this->database = $connection['database']; - } - $dsn = implode('', $a); - - $o = !empty($connection['options']) ? $connection['options'] : []; - $options = array_merge([ - 'w' => \MongoDB\Driver\WriteConcern::MAJORITY, - 'j' => true, - 'readPreference' => \MongoDB\Driver\ReadPreference::RP_NEAREST - ], $o); - $driverOptions = !empty($connection['driverOptions']) ? $connection['driverOptions'] : []; - - $this->db = new Manager($dsn, $options, $driverOptions); - } else { - throw new \InvalidArgumentException('First argument to OAuth2\Storage\MongoDB must be a string or a configuration array'); - } - - $this->db->selectServer($this->db->getReadPreference()); - - $this->config = array_merge(array( - 'client_table' => 'oauth_clients', - 'access_token_table' => 'oauth_access_tokens', - 'refresh_token_table' => 'oauth_refresh_tokens', - 'code_table' => 'oauth_authorization_codes', - 'user_table' => 'oauth_users', - 'jwt_table' => 'oauth_jwt', - ), $config); - } - - /* ClientCredentialsInterface */ - public function checkClientCredentials($client_id, $client_secret = null) - { - if ($result = $this->findOne('client_table', ['client_id' => $client_id])) { - return $result['client_secret'] == $client_secret; - } - return false; - } - - /** - * @param string $client_id - * @return boolean - */ - public function isPublicClient($client_id) - { - if (!$result = $this->findOne('client_table', ['client_id' => $client_id])) { - return false; - } - return empty($result['client_secret']); - } - - /* ClientInterface */ - public function getClientDetails($client_id) - { - return $this->findOne('client_table', ['client_id' => $client_id]); - } - - public function setClientDetails($client_id, $client_secret = null, $redirect_uri = null, $grant_types = null, $scope = null, $user_id = null) - { - $bulk = new BulkWrite(); - $bulk->update( - ['client_id' => $client_id], - ['$set' => [ - 'client_id' => $client_id, - 'client_secret' => $client_secret, - 'redirect_uri' => $redirect_uri, - 'grant_types' => $grant_types, - 'scope' => $scope, - 'user_id' => $user_id, - ]], - ['upsert' => true] - ); - $this->db->executeBulkWrite($this->collection('client_table'), $bulk); - return true; - } - - public function unsetClientDetails($client_id) - { - $this->delete('client_table', ['client_id' => $client_id]); - return true; - } - - public function checkRestrictedGrantType($client_id, $grant_type) - { - if ($details = $this->getClientDetails($client_id)) { - if (isset($details['grant_types'])) { - $grant_types = explode(' ', $details['grant_types']); - return in_array($grant_type, $grant_types); - } - } - - // if grant_types are not defined, then none are restricted - return true; - } - - /* AccessTokenInterface */ - public function getAccessToken($access_token) - { - return $this->findOne('access_token_table', ['access_token' => $access_token]); - } - - public function setAccessToken($access_token, $client_id, $user_id, $expires, $scope = null) - { - $bulk = new BulkWrite(); - $bulk->update( - ['access_token' => $access_token], - ['$set' => [ - 'access_token' => $access_token, - 'client_id' => $client_id, - 'expires' => $expires, - 'user_id' => $user_id, - 'scope' => $scope - ]], - ['upsert' => true] - ); - $this->db->executeBulkWrite($this->collection('access_token_table'), $bulk); - return true; - } - - public function unsetAccessToken($access_token) - { - $this->delete('access_token_table', ['access_token' => $access_token]); - return true; - } - - - /* AuthorizationCodeInterface */ - public function getAuthorizationCode($code) - { - return $this->findOne('code_table', ['authorization_code' => $code]); - } - - public function setAuthorizationCode($code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null) - { - $bulk = new BulkWrite(); - $bulk->update( - ['authorization_code' => $code], - ['$set' => [ - 'authorization_code' => $code, - 'client_id' => $client_id, - 'user_id' => $user_id, - 'redirect_uri' => $redirect_uri, - 'expires' => $expires, - 'scope' => $scope, - 'id_token' => $id_token, - ]], - ['upsert' => true] - ); - $this->db->executeBulkWrite($this->collection('code_table'), $bulk); - return true; - } - - public function expireAuthorizationCode($code) - { - $this->delete('code_table', ['authorization_code' => $code]); - return true; - } - - /* UserCredentialsInterface */ - public function checkUserCredentials($username, $password) - { - if ($user = $this->getUser($username)) { - return $this->checkPassword($user, $password); - } - - return false; - } - - public function getUserDetails($username) - { - if ($user = $this->getUser($username)) { - $user['user_id'] = $user['username']; - } - - return $user; - } - - /* RefreshTokenInterface */ - public function getRefreshToken($refresh_token) - { - return $this->findOne('refresh_token_table', ['refresh_token' => $refresh_token]); - } - - public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null) - { - $bulk = new BulkWrite(); - $bulk->update( - ['refresh_token' => $refresh_token], - ['$set' => [ - 'refresh_token' => $refresh_token, - 'client_id' => $client_id, - 'user_id' => $user_id, - 'expires' => $expires, - 'scope' => $scope - ]], - ['upsert' => true] - ); - $this->db->executeBulkWrite($this->collection('refresh_token_table'), $bulk); - return true; - } - - public function unsetRefreshToken($refresh_token) - { - $this->delete('refresh_token_table', ['refresh_token' => $refresh_token]); - return true; - } - - // plaintext passwords are bad! Override this for your application - protected function checkPassword($user, $password) - { - return $user['password'] == $password; - } - - public function getUser($username) - { - return $this->findOne('user_table', ['username' => $username]); - } - - public function setUser($username, $password, $firstName = null, $lastName = null) - { - $bulk = new BulkWrite(); - $bulk->update( - ['username' => $username], - ['$set' => [ - 'username' => $username, - 'password' => $password, - 'first_name' => $firstName, - 'last_name' => $lastName - ]], - ['upsert' => true] - ); - $this->db->executeBulkWrite($this->collection('user_table'), $bulk); - return true; - } - - public function getClientKey($client_id, $subject) - { - $result = $this->findOne('jwt_table', [ - 'client_id' => $client_id, - 'subject' => $subject - ]); - return $result ? $result['key'] : false; - } - - public function getClientScope($client_id) - { - if (!$clientDetails = $this->getClientDetails($client_id)) { - return false; - } - - if (isset($clientDetails['scope'])) { - return $clientDetails['scope']; - } - - return null; - } - - public function getJti($client_id, $subject, $audience, $expiration, $jti) - { - //TODO: Needs mongodb implementation. - throw new \Exception('getJti() for the MongoDB driver is currently unimplemented.'); - } - - public function setJti($client_id, $subject, $audience, $expiration, $jti) - { - //TODO: Needs mongodb implementation. - throw new \Exception('setJti() for the MongoDB driver is currently unimplemented.'); - } - - - protected function collection($name) - { - return $this->database . '.' . $this->config[$name]; - } - - /** - * - * @param string $collection - * @param array $filter - * @return array | false - */ - protected function findOne($collection, $filter) - { - $query = new Query($filter, ['limit' => 1, ['sort' => ['_id' => -1]]]); - $cursor = $this->db - ->executeQuery($this->collection($collection), $query); - $cursor->setTypeMap([ - 'root' => 'array', - 'document' => 'array' - ]); - $result = $cursor->toArray(); - return current($result); - } - - /** - * - * @param string $collection - * @param array $filter - * @return boolean - */ - protected function delete($collection, $filter) - { - $bulk = new BulkWrite(); - $bulk->delete($filter); - $this->db->executeBulkWrite($this->collection($collection), $bulk); - return true; - } -} + + */ +class MongoDB implements AuthorizationCodeInterface, + AccessTokenInterface, + ClientCredentialsInterface, + UserCredentialsInterface, + RefreshTokenInterface, + JwtBearerInterface, + OpenIDAuthorizationCodeInterface +{ + protected $db; + protected $database; + protected $config; + + public function __construct($connection, $config = array()) + { + if (is_string ($connection)) { + $this->db = new Manager($connection); + if (preg_match('/^mongodb:\\/\\/.+\\/([^?&]+)/s', $connection, $matches)) { + $this->database = $matches[1]; + } else { + throw new \InvalidArgumentException("Unable to determine Database Name from dsn."); + } + } elseif (is_array($connection)) { + $a = array('mongodb://'); + if (!empty($connection['username'])) { + $a[] = $connection['username'] . ':'; + } + if (!empty($connection['password'])) { + $a[] = rawurlencode($connection['password']) . '@'; + } + if (!empty($connection['host'])) { + $a[] = $connection['host']; + } + if (!empty($connection['port'])) { + $a[] = ':' . $connection['port']; + } + if (!empty($connection['database'])) { + $a[] = '/' . $connection['database']; + $this->database = $connection['database']; + } + $dsn = implode('', $a); + + $o = !empty($connection['options']) ? $connection['options'] : array(); + $options = array_merge(array( + 'w' => \MongoDB\Driver\WriteConcern::MAJORITY, + 'j' => true, + 'readPreference' => \MongoDB\Driver\ReadPreference::RP_NEAREST + ), $o); + $driverOptions = !empty($connection['driverOptions']) ? $connection['driverOptions'] : array(); + + $this->db = new Manager($dsn, $options, $driverOptions); + } else { + throw new \InvalidArgumentException('First argument to OAuth2\Storage\MongoDB must be a string or a configuration array'); + } + + $this->db->selectServer($this->db->getReadPreference()); + + $this->config = array_merge(array( + 'client_table' => 'oauth_clients', + 'access_token_table' => 'oauth_access_tokens', + 'refresh_token_table' => 'oauth_refresh_tokens', + 'code_table' => 'oauth_authorization_codes', + 'user_table' => 'oauth_users', + 'jwt_table' => 'oauth_jwt', + ), $config); + } + + /* ClientCredentialsInterface */ + public function checkClientCredentials($client_id, $client_secret = null) + { + if ($result = $this->findOne('client_table', array('client_id' => $client_id))) { + return $result['client_secret'] == $client_secret; + } + return false; + } + + /** + * @param string $client_id + * @return boolean + */ + public function isPublicClient($client_id) + { + if (!$result = $this->findOne('client_table', array('client_id' => $client_id))) { + return false; + } + return empty($result['client_secret']); + } + + /* ClientInterface */ + public function getClientDetails($client_id) + { + return $this->findOne('client_table', array('client_id' => $client_id)); + } + + public function setClientDetails($client_id, $client_secret = null, $redirect_uri = null, $grant_types = null, $scope = null, $user_id = null) + { + $bulk = new BulkWrite(); + $bulk->update( + array('client_id' => $client_id), + array('$set' => array( + 'client_id' => $client_id, + 'client_secret' => $client_secret, + 'redirect_uri' => $redirect_uri, + 'grant_types' => $grant_types, + 'scope' => $scope, + 'user_id' => $user_id, + )), + array('upsert' => true) + ); + $this->db->executeBulkWrite($this->collection('client_table'), $bulk); + return true; + } + + public function unsetClientDetails($client_id) + { + $this->delete('client_table', array('client_id' => $client_id)); + return true; + } + + public function checkRestrictedGrantType($client_id, $grant_type) + { + if ($details = $this->getClientDetails($client_id)) { + if (isset($details['grant_types'])) { + $grant_types = explode(' ', $details['grant_types']); + return in_array($grant_type, $grant_types); + } + } + + // if grant_types are not defined, then none are restricted + return true; + } + + /* AccessTokenInterface */ + public function getAccessToken($access_token) + { + return $this->findOne('access_token_table', array('access_token' => $access_token)); + } + + public function setAccessToken($access_token, $client_id, $user_id, $expires, $scope = null) + { + $bulk = new BulkWrite(); + $bulk->update( + array('access_token' => $access_token), + array('$set' => array( + 'access_token' => $access_token, + 'client_id' => $client_id, + 'expires' => $expires, + 'user_id' => $user_id, + 'scope' => $scope + )), + array('upsert' => true) + ); + $this->db->executeBulkWrite($this->collection('access_token_table'), $bulk); + return true; + } + + public function unsetAccessToken($access_token) + { + $this->delete('access_token_table', array('access_token' => $access_token)); + return true; + } + + + /* AuthorizationCodeInterface */ + public function getAuthorizationCode($code) + { + return $this->findOne('code_table', array('authorization_code' => $code)); + } + + public function setAuthorizationCode($code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null) + { + $bulk = new BulkWrite(); + $bulk->update( + array('authorization_code' => $code), + array('$set' => array( + 'authorization_code' => $code, + 'client_id' => $client_id, + 'user_id' => $user_id, + 'redirect_uri' => $redirect_uri, + 'expires' => $expires, + 'scope' => $scope, + 'id_token' => $id_token, + )), + array('upsert' => true) + ); + $this->db->executeBulkWrite($this->collection('code_table'), $bulk); + return true; + } + + public function expireAuthorizationCode($code) + { + $this->delete('code_table', array('authorization_code' => $code)); + return true; + } + + /* UserCredentialsInterface */ + public function checkUserCredentials($username, $password) + { + if ($user = $this->getUser($username)) { + return $this->checkPassword($user, $password); + } + + return false; + } + + public function getUserDetails($username) + { + if ($user = $this->getUser($username)) { + $user['user_id'] = $user['username']; + } + + return $user; + } + + /* RefreshTokenInterface */ + public function getRefreshToken($refresh_token) + { + return $this->findOne('refresh_token_table', array('refresh_token' => $refresh_token)); + } + + public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null) + { + $bulk = new BulkWrite(); + $bulk->update( + array('refresh_token' => $refresh_token), + array('$set' => array( + 'refresh_token' => $refresh_token, + 'client_id' => $client_id, + 'user_id' => $user_id, + 'expires' => $expires, + 'scope' => $scope + )), + array('upsert' => true) + ); + $this->db->executeBulkWrite($this->collection('refresh_token_table'), $bulk); + return true; + } + + public function unsetRefreshToken($refresh_token) + { + $this->delete('refresh_token_table', array('refresh_token' => $refresh_token)); + return true; + } + + // plaintext passwords are bad! Override this for your application + protected function checkPassword($user, $password) + { + return $user['password'] == $password; + } + + public function getUser($username) + { + return $this->findOne('user_table', array('username' => $username)); + } + + public function setUser($username, $password, $firstName = null, $lastName = null) + { + $bulk = new BulkWrite(); + $bulk->update( + array('username' => $username), + array('$set' => array( + 'username' => $username, + 'password' => $password, + 'first_name' => $firstName, + 'last_name' => $lastName + )), + array('upsert' => true) + ); + $this->db->executeBulkWrite($this->collection('user_table'), $bulk); + return true; + } + + public function getClientKey($client_id, $subject) + { + $result = $this->findOne('jwt_table', array( + 'client_id' => $client_id, + 'subject' => $subject + )); + return $result ? $result['key'] : false; + } + + public function getClientScope($client_id) + { + if (!$clientDetails = $this->getClientDetails($client_id)) { + return false; + } + + if (isset($clientDetails['scope'])) { + return $clientDetails['scope']; + } + + return null; + } + + public function getJti($client_id, $subject, $audience, $expiration, $jti) + { + //TODO: Needs mongodb implementation. + throw new \Exception('getJti() for the MongoDB driver is currently unimplemented.'); + } + + public function setJti($client_id, $subject, $audience, $expiration, $jti) + { + //TODO: Needs mongodb implementation. + throw new \Exception('setJti() for the MongoDB driver is currently unimplemented.'); + } + + + protected function collection($name) + { + return $this->database . '.' . $this->config[$name]; + } + + /** + * + * @param string $collection + * @param array $filter + * @return array | false + */ + protected function findOne($collection, $filter) + { + $query = new Query($filter, array('limit' => 1, array('sort' => array('_id' => -1)))); + $cursor = $this->db + ->executeQuery($this->collection($collection), $query); + $cursor->setTypeMap(array( + 'root' => 'array', + 'document' => 'array' + )); + $result = $cursor->toArray(); + return current($result); + } + + /** + * + * @param string $collection + * @param array $filter + * @return boolean + */ + protected function delete($collection, $filter) + { + $bulk = new BulkWrite(); + $bulk->delete($filter); + $this->db->executeBulkWrite($this->collection($collection), $bulk); + return true; + } +} diff --git a/test/OAuth2/Storage/MongoDBTest.php b/test/OAuth2/Storage/MongoDBTest.php index 715750186..5d3acd2d3 100644 --- a/test/OAuth2/Storage/MongoDBTest.php +++ b/test/OAuth2/Storage/MongoDBTest.php @@ -7,14 +7,16 @@ * * @author Roman Shuplov */ -class MongoDBTest extends BaseTest +class MongoDBTest extends BaseTest { - public function __construct() { + public function __construct() + { $mongodb = Bootstrap::getInstance()->getMongoDB(); } - public function testSetClientDetails() { + public function testSetClientDetails() + { $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); // comment with Bootstrap::getInstance()->getMongoDB(); @@ -34,21 +36,24 @@ public function testSetClientDetails() { $this->assertTrue($db->checkClientCredentials('oauth_test_client', 'testpass')); } - public function testConnection() { + public function testConnection() + { $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); $this->assertNotFalse($db->getClientDetails('oauth_test_client')); $db = new MongoDB(['host' => 'localhost', 'port' => '27017', 'database' => 'oauth2_server_php']); $this->assertNotFalse($db->getClientDetails('oauth_test_client')); } - public function testIsPublicClient() { + public function testIsPublicClient() + { $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); $res = $db->isPublicClient('oauth_test_client'); $this->assertFalse($res); } - public function testAccessToken() { + public function testAccessToken() + { $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); $this->assertNotFalse($db->getAccessToken('testtoken')); @@ -61,7 +66,8 @@ public function testAccessToken() { } - public function testAuthorizationCode() { + public function testAuthorizationCode() + { $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); $this->assertNotFalse($db->getAuthorizationCode('testcode')); @@ -73,7 +79,8 @@ public function testAuthorizationCode() { $this->assertNotFalse($db->getAuthorizationCode('testcode')); } - public function testRefreshToken() { + public function testRefreshToken() + { $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); $this->assertNotFalse($db->getRefreshToken('testrefreshtoken')); @@ -85,18 +92,21 @@ public function testRefreshToken() { $this->assertNotFalse($db->getRefreshToken('testrefreshtoken')); } - public function testCheckUserCredentials() { + public function testCheckUserCredentials() + { $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); $this->assertTrue($db->checkUserCredentials('testuser', 'password')); } - public function testGetUserDetails() { + public function testGetUserDetails() + { $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); $this->assertNotFalse($db->getUserDetails('testuser')); } - public function testUser() { + public function testUser() + { $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); $this->assertNotFalse($db->getUser('testuser')); @@ -104,13 +114,15 @@ public function testUser() { $this->assertTrue($db->checkUserCredentials('testuser', 'password123123')); } - public function testGetClientKey() { + public function testGetClientKey() + { $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); $this->assertNotFalse($db->getClientKey('oauth_test_client', 'test_subject')); } - public function testGetClientScope() { + public function testGetClientScope() + { $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); $this->assertStringMatchesFormat('%S', $db->getClientScope('oauth_test_client')); diff --git a/test/lib/OAuth2/Storage/BaseTest.php b/test/lib/OAuth2/Storage/BaseTest.php index 34eacfc55..672c504ce 100755 --- a/test/lib/OAuth2/Storage/BaseTest.php +++ b/test/lib/OAuth2/Storage/BaseTest.php @@ -1,36 +1,36 @@ -getMemoryStorage(); - $sqlite = Bootstrap::getInstance()->getSqlitePdo(); - $mysql = Bootstrap::getInstance()->getMysqlPdo(); - $postgres = Bootstrap::getInstance()->getPostgresPdo(); - $mongo = Bootstrap::getInstance()->getMongo(); - $mongodb = Bootstrap::getInstance()->getMongoDB(); - $redis = Bootstrap::getInstance()->getRedisStorage(); - $cassandra = Bootstrap::getInstance()->getCassandraStorage(); - $dynamodb = Bootstrap::getInstance()->getDynamoDbStorage(); - $couchbase = Bootstrap::getInstance()->getCouchbase(); - - /* hack until we can fix "default_scope" dependencies in other tests */ - $memory->defaultScope = 'defaultscope1 defaultscope2'; - - return array( - array($memory), - array($sqlite), - array($mysql), - array($postgres), - array($mongo), - array($mongodb), - array($redis), - array($cassandra), - array($dynamodb), - array($couchbase), - ); - } -} +getMemoryStorage(); + $sqlite = Bootstrap::getInstance()->getSqlitePdo(); + $mysql = Bootstrap::getInstance()->getMysqlPdo(); + $postgres = Bootstrap::getInstance()->getPostgresPdo(); + $mongo = Bootstrap::getInstance()->getMongo(); + $mongodb = Bootstrap::getInstance()->getMongoDB(); + $redis = Bootstrap::getInstance()->getRedisStorage(); + $cassandra = Bootstrap::getInstance()->getCassandraStorage(); + $dynamodb = Bootstrap::getInstance()->getDynamoDbStorage(); + $couchbase = Bootstrap::getInstance()->getCouchbase(); + + /* hack until we can fix "default_scope" dependencies in other tests */ + $memory->defaultScope = 'defaultscope1 defaultscope2'; + + return array( + array($memory), + array($sqlite), + array($mysql), + array($postgres), + array($mongo), + array($mongodb), + array($redis), + array($cassandra), + array($dynamodb), + array($couchbase), + ); + } +} \ No newline at end of file diff --git a/test/lib/OAuth2/Storage/Bootstrap.php b/test/lib/OAuth2/Storage/Bootstrap.php index d926a7343..840143501 100755 --- a/test/lib/OAuth2/Storage/Bootstrap.php +++ b/test/lib/OAuth2/Storage/Bootstrap.php @@ -1,996 +1,999 @@ -configDir = __DIR__.'/../../../config'; - } - - public static function getInstance() - { - if (!self::$instance) { - self::$instance = new self(); - } - - return self::$instance; - } - - public function getSqlitePdo() - { - if (!$this->sqlite) { - $this->removeSqliteDb(); - $pdo = new \PDO(sprintf('sqlite://%s', $this->getSqliteDir())); - $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); - $this->createSqliteDb($pdo); - - $this->sqlite = new Pdo($pdo); - } - - return $this->sqlite; - } - - public function getPostgresPdo() - { - if (!$this->postgres) { - if (in_array('pgsql', \PDO::getAvailableDrivers())) { - $this->removePostgresDb(); - $this->createPostgresDb(); - if ($pdo = $this->getPostgresDriver()) { - $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); - $this->populatePostgresDb($pdo); - $this->postgres = new Pdo($pdo); - } - } else { - $this->postgres = new NullStorage('Postgres', 'Missing postgres PDO extension.'); - } - } - - return $this->postgres; - } - - public function getPostgresDriver() - { - try { - $pdo = new \PDO('pgsql:host=localhost;dbname=oauth2_server_php', 'postgres'); - - return $pdo; - } catch (\PDOException $e) { - $this->postgres = new NullStorage('Postgres', $e->getMessage()); - } - } - - public function getMemoryStorage() - { - return new Memory(json_decode(file_get_contents($this->configDir. '/storage.json'), true)); - } - - public function getRedisStorage() - { - if (!$this->redis) { - if (class_exists('Predis\Client')) { - $redis = new \Predis\Client(); - if ($this->testRedisConnection($redis)) { - $redis->flushdb(); - $this->redis = new Redis($redis); - $this->createRedisDb($this->redis); - } else { - $this->redis = new NullStorage('Redis', 'Unable to connect to redis server on port 6379'); - } - } else { - $this->redis = new NullStorage('Redis', 'Missing redis library. Please run "composer.phar require predis/predis:dev-master"'); - } - } - - return $this->redis; - } - - private function testRedisConnection(\Predis\Client $redis) - { - try { - $redis->connect(); - } catch (\Predis\CommunicationException $exception) { - // we were unable to connect to the redis server - return false; - } - - return true; - } - - public function getMysqlPdo() - { - if (!$this->mysql) { - $pdo = null; - try { - $pdo = new \PDO('mysql:host=localhost;', 'root'); - } catch (\PDOException $e) { - $this->mysql = new NullStorage('MySQL', 'Unable to connect to MySQL on root@localhost'); - } - - if ($pdo) { - $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); - $this->removeMysqlDb($pdo); - $this->createMysqlDb($pdo); - - $this->mysql = new Pdo($pdo); - } - } - - return $this->mysql; - } - - public function getMongo() - { - if (!$this->mongo) { - $skipMongo = $this->getEnvVar('SKIP_MONGO_TESTS'); - if (!$skipMongo && class_exists('MongoClient')) { - $mongo = new \MongoClient('mongodb://localhost:27017', array('connect' => false)); - if ($this->testMongoConnection($mongo)) { - $db = $mongo->oauth2_server_php; - $this->removeMongo($db); - $this->createMongo($db); - $this->mongo = new Mongo($db); - } else { - $this->mongo = new NullStorage('Mongo', 'Unable to connect to mongo server on "localhost:27017"'); - } - } else { - $this->mongo = new NullStorage('Mongo', 'Missing mongo php extension. Please install mongo.so'); - } - } - - return $this->mongo; - } - - private function testMongoConnection(\MongoClient $mongo) - { - try { - $mongo->connect(); - } catch (\MongoConnectionException $e) { - return false; - } - - return true; - } - - public function getMongoDB() - { - if (!$this->mongodb) { - $skipMongo = $this->getEnvVar('SKIP_MONGODB_TESTS'); - if (!$skipMongo && class_exists('\MongoDB\Driver\Manager')) { - try { - $this->mongodb = new \MongoDB\Driver\Manager('mongodb://localhost:27017'); - $this->mongodb->selectServer($this->mongodb->getReadPreference()); - } catch (\Exception $e) { - $this->mongodb = new NullStorage('MongoDB', 'Unable to connect to mongoDB server on "localhost:27017"'); - } - $this->removeMongoDB(); - $this->createMongoDB(); - } else { - $this->mongodb = new NullStorage('MongoDB', 'Missing mongoDB php extension. Please install mongodb.so'); - } - } - - return $this->mongodb; - } - - public function getCouchbase() - { - if (!$this->couchbase) { - if ($this->getEnvVar('SKIP_COUCHBASE_TESTS')) { - $this->couchbase = new NullStorage('Couchbase', 'Skipping Couchbase tests'); - } elseif (!class_exists('Couchbase')) { - $this->couchbase = new NullStorage('Couchbase', 'Missing Couchbase php extension. Please install couchbase.so'); - } else { - // round-about way to make sure couchbase is working - // this is required because it throws a "floating point exception" otherwise - $code = "new \Couchbase(array('localhost:8091'), '', '', 'auth', false);"; - $exec = sprintf('php -r "%s"', $code); - $ret = exec($exec, $test, $var); - if ($ret != 0) { - $couchbase = new \Couchbase(array('localhost:8091'), '', '', 'auth', false); - if ($this->testCouchbaseConnection($couchbase)) { - $this->clearCouchbase($couchbase); - $this->createCouchbaseDB($couchbase); - - $this->couchbase = new CouchbaseDB($couchbase); - } else { - $this->couchbase = new NullStorage('Couchbase', 'Unable to connect to Couchbase server on "localhost:8091"'); - } - } else { - $this->couchbase = new NullStorage('Couchbase', 'Error while trying to connect to Couchbase'); - } - } - } - - return $this->couchbase; - } - - private function testCouchbaseConnection(\Couchbase $couchbase) - { - try { - if (count($couchbase->getServers()) > 0) { - return true; - } - } catch (\CouchbaseException $e) { - return false; - } - - return true; - } - - public function getCassandraStorage() - { - if (!$this->cassandra) { - if (class_exists('phpcassa\ColumnFamily')) { - $cassandra = new \phpcassa\Connection\ConnectionPool('oauth2_test', array('127.0.0.1:9160')); - if ($this->testCassandraConnection($cassandra)) { - $this->removeCassandraDb(); - $this->cassandra = new Cassandra($cassandra); - $this->createCassandraDb($this->cassandra); - } else { - $this->cassandra = new NullStorage('Cassandra', 'Unable to connect to cassandra server on "127.0.0.1:9160"'); - } - } else { - $this->cassandra = new NullStorage('Cassandra', 'Missing cassandra library. Please run "composer.phar require thobbs/phpcassa:dev-master"'); - } - } - - return $this->cassandra; - } - - private function testCassandraConnection(\phpcassa\Connection\ConnectionPool $cassandra) - { - try { - new \phpcassa\SystemManager('localhost:9160'); - } catch (\Exception $e) { - return false; - } - - return true; - } - - private function removeCassandraDb() - { - $sys = new \phpcassa\SystemManager('localhost:9160'); - - try { - $sys->drop_keyspace('oauth2_test'); - } catch (\cassandra\InvalidRequestException $e) { - - } - } - - private function createCassandraDb(Cassandra $storage) - { - // create the cassandra keyspace and column family - $sys = new \phpcassa\SystemManager('localhost:9160'); - - $sys->create_keyspace('oauth2_test', array( - "strategy_class" => \phpcassa\Schema\StrategyClass::SIMPLE_STRATEGY, - "strategy_options" => array('replication_factor' => '1') - )); - - $sys->create_column_family('oauth2_test', 'auth'); - $cassandra = new \phpcassa\Connection\ConnectionPool('oauth2_test', array('127.0.0.1:9160')); - $cf = new \phpcassa\ColumnFamily($cassandra, 'auth'); - - // populate the data - $storage->setClientDetails("oauth_test_client", "testpass", "http://example.com", 'implicit password'); - $storage->setAccessToken("testtoken", "Some Client", '', time() + 1000); - $storage->setAuthorizationCode("testcode", "Some Client", '', '', time() + 1000); - - $storage->setScope('supportedscope1 supportedscope2 supportedscope3 supportedscope4'); - $storage->setScope('defaultscope1 defaultscope2', null, 'default'); - - $storage->setScope('clientscope1 clientscope2', 'Test Client ID'); - $storage->setScope('clientscope1 clientscope2', 'Test Client ID', 'default'); - - $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Client ID 2'); - $storage->setScope('clientscope1 clientscope2', 'Test Client ID 2', 'default'); - - $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID'); - $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID', 'default'); - - $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Default Scope Client ID 2'); - $storage->setScope('clientscope3', 'Test Default Scope Client ID 2', 'default'); - - $storage->setClientKey('oauth_test_client', $this->getTestPublicKey(), 'test_subject'); - - $cf->insert("oauth_public_keys:ClientID_One", array('__data' => json_encode(array("public_key" => "client_1_public", "private_key" => "client_1_private", "encryption_algorithm" => "RS256")))); - $cf->insert("oauth_public_keys:ClientID_Two", array('__data' => json_encode(array("public_key" => "client_2_public", "private_key" => "client_2_private", "encryption_algorithm" => "RS256")))); - $cf->insert("oauth_public_keys:", array('__data' => json_encode(array("public_key" => $this->getTestPublicKey(), "private_key" => $this->getTestPrivateKey(), "encryption_algorithm" => "RS256")))); - - $cf->insert("oauth_users:testuser", array('__data' =>json_encode(array("password" => "password", "email" => "testuser@test.com", "email_verified" => true)))); - - } - - private function createSqliteDb(\PDO $pdo) - { - $this->runPdoSql($pdo); - } - - private function removeSqliteDb() - { - if (file_exists($this->getSqliteDir())) { - unlink($this->getSqliteDir()); - } - } - - private function createMysqlDb(\PDO $pdo) - { - $pdo->exec('CREATE DATABASE oauth2_server_php'); - $pdo->exec('USE oauth2_server_php'); - $this->runPdoSql($pdo); - } - - private function removeMysqlDb(\PDO $pdo) - { - $pdo->exec('DROP DATABASE IF EXISTS oauth2_server_php'); - } - - private function createPostgresDb() - { - if (!`psql postgres -tAc "SELECT 1 FROM pg_roles WHERE rolname='postgres'"`) { - `createuser -s -r postgres`; - } - - `createdb -O postgres oauth2_server_php`; - } - - private function populatePostgresDb(\PDO $pdo) - { - $this->runPdoSql($pdo); - } - - private function removePostgresDb() - { - if (trim(`psql -l | grep oauth2_server_php | wc -l`)) { - `dropdb oauth2_server_php`; - } - } - - public function runPdoSql(\PDO $pdo) - { - $storage = new Pdo($pdo); - foreach (explode(';', $storage->getBuildSql()) as $statement) { - $result = $pdo->exec($statement); - } - - // set up scopes - $sql = 'INSERT INTO oauth_scopes (scope) VALUES (?)'; - foreach (explode(' ', 'supportedscope1 supportedscope2 supportedscope3 supportedscope4 clientscope1 clientscope2 clientscope3') as $supportedScope) { - $pdo->prepare($sql)->execute(array($supportedScope)); - } - - $sql = 'INSERT INTO oauth_scopes (scope, is_default) VALUES (?, ?)'; - foreach (array('defaultscope1', 'defaultscope2') as $defaultScope) { - $pdo->prepare($sql)->execute(array($defaultScope, true)); - } - - // set up clients - $sql = 'INSERT INTO oauth_clients (client_id, client_secret, scope, grant_types) VALUES (?, ?, ?, ?)'; - $pdo->prepare($sql)->execute(array('Test Client ID', 'TestSecret', 'clientscope1 clientscope2', null)); - $pdo->prepare($sql)->execute(array('Test Client ID 2', 'TestSecret', 'clientscope1 clientscope2 clientscope3', null)); - $pdo->prepare($sql)->execute(array('Test Default Scope Client ID', 'TestSecret', 'clientscope1 clientscope2', null)); - $pdo->prepare($sql)->execute(array('oauth_test_client', 'testpass', null, 'implicit password')); - - // set up misc - $sql = 'INSERT INTO oauth_access_tokens (access_token, client_id, expires, user_id) VALUES (?, ?, ?, ?)'; - $pdo->prepare($sql)->execute(array('testtoken', 'Some Client', date('Y-m-d H:i:s', strtotime('+1 hour')), null)); - $pdo->prepare($sql)->execute(array('accesstoken-openid-connect', 'Some Client', date('Y-m-d H:i:s', strtotime('+1 hour')), 'testuser')); - - $sql = 'INSERT INTO oauth_authorization_codes (authorization_code, client_id, expires) VALUES (?, ?, ?)'; - $pdo->prepare($sql)->execute(array('testcode', 'Some Client', date('Y-m-d H:i:s', strtotime('+1 hour')))); - - $sql = 'INSERT INTO oauth_users (username, password, email, email_verified) VALUES (?, ?, ?, ?)'; - $pdo->prepare($sql)->execute(array('testuser', 'password', 'testuser@test.com', true)); - - $sql = 'INSERT INTO oauth_public_keys (client_id, public_key, private_key, encryption_algorithm) VALUES (?, ?, ?, ?)'; - $pdo->prepare($sql)->execute(array('ClientID_One', 'client_1_public', 'client_1_private', 'RS256')); - $pdo->prepare($sql)->execute(array('ClientID_Two', 'client_2_public', 'client_2_private', 'RS256')); - - $sql = 'INSERT INTO oauth_public_keys (client_id, public_key, private_key, encryption_algorithm) VALUES (?, ?, ?, ?)'; - $pdo->prepare($sql)->execute(array(null, $this->getTestPublicKey(), $this->getTestPrivateKey(), 'RS256')); - - $sql = 'INSERT INTO oauth_jwt (client_id, subject, public_key) VALUES (?, ?, ?)'; - $pdo->prepare($sql)->execute(array('oauth_test_client', 'test_subject', $this->getTestPublicKey())); - } - - public function getSqliteDir() - { - return $this->configDir. '/test.sqlite'; - } - - public function getConfigDir() - { - return $this->configDir; - } - - private function createCouchbaseDB(\Couchbase $db) - { - $db->set('oauth_clients-oauth_test_client',json_encode(array( - 'client_id' => "oauth_test_client", - 'client_secret' => "testpass", - 'redirect_uri' => "http://example.com", - 'grant_types' => 'implicit password' - ))); - - $db->set('oauth_access_tokens-testtoken',json_encode(array( - 'access_token' => "testtoken", - 'client_id' => "Some Client" - ))); - - $db->set('oauth_authorization_codes-testcode',json_encode(array( - 'access_token' => "testcode", - 'client_id' => "Some Client" - ))); - - $db->set('oauth_users-testuser',json_encode(array( - 'username' => 'testuser', - 'password' => 'password', - 'email' => 'testuser@test.com', - 'email_verified' => true, - ))); - - $db->set('oauth_jwt-oauth_test_client',json_encode(array( - 'client_id' => 'oauth_test_client', - 'key' => $this->getTestPublicKey(), - 'subject' => 'test_subject', - ))); - } - - private function clearCouchbase(\Couchbase $cb) - { - $cb->delete('oauth_authorization_codes-new-openid-code'); - $cb->delete('oauth_access_tokens-newtoken'); - $cb->delete('oauth_authorization_codes-newcode'); - $cb->delete('oauth_refresh_tokens-refreshtoken'); - } - - private function createMongo(\MongoDB $db) - { - $db->oauth_clients->insert(array( - 'client_id' => "oauth_test_client", - 'client_secret' => "testpass", - 'redirect_uri' => "http://example.com", - 'grant_types' => 'implicit password' - )); - - $db->oauth_access_tokens->insert(array( - 'access_token' => "testtoken", - 'client_id' => "Some Client" - )); - - $db->oauth_authorization_codes->insert(array( - 'authorization_code' => "testcode", - 'client_id' => "Some Client" - )); - - $db->oauth_users->insert(array( - 'username' => 'testuser', - 'password' => 'password', - 'email' => 'testuser@test.com', - 'email_verified' => true, - )); - - $db->oauth_jwt->insert(array( - 'client_id' => 'oauth_test_client', - 'key' => $this->getTestPublicKey(), - 'subject' => 'test_subject', - )); - } - - private function createMongoDB() - { - $bulk = new \MongoDB\Driver\BulkWrite(); - $bulk->insert([ - 'client_id' => "oauth_test_client", - 'client_secret' => "testpass", - 'redirect_uri' => "http://example.com", - 'grant_types' => 'implicit password', - 'scope' => 'clientscope1 clientscope2' - ]); - $bulk->insert([ - 'client_id' => "oauth_test_client2", - 'client_secret' => "testpass2", - 'redirect_uri' => "http://example.com", - 'grant_types' => 'implicit password', - 'scope' => 'clientscope3 clientscope4' - ]); - $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_clients', $bulk); - - $bulk = new \MongoDB\Driver\BulkWrite(); - $bulk->insert([ - 'access_token' => "testtoken", - 'client_id' => "Some Client" - ]); - $bulk->insert([ - 'access_token' => "testtoken2", - 'client_id' => "Some Client2" - ]); - $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_access_tokens', $bulk); - - $bulk = new \MongoDB\Driver\BulkWrite(); - $bulk->insert([ - 'authorization_code' => "testcode", - 'client_id' => "Some Client" - ]); - $bulk->insert([ - 'authorization_code' => "testcode2", - 'client_id' => "Some Client2" - ]); - $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_authorization_codes', $bulk); - - $bulk = new \MongoDB\Driver\BulkWrite(); - $bulk->insert([ - 'refresh_token' => 'testrefreshtoken', - 'client_id' => 'Some Client', - ]); - $bulk->insert([ - 'refresh_token' => 'testrefreshtoken2', - 'client_id' => 'Some Client2', - ]); - $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_refresh_tokens', $bulk); - - $bulk = new \MongoDB\Driver\BulkWrite(); - $bulk->insert([ - 'username' => 'testuser', - 'password' => 'password', - 'email' => 'testuser@test.com', - 'email_verified' => true, - ]); - $bulk->insert([ - 'username' => 'testuser2', - 'password' => 'password2', - 'email' => 'testuser@test.com', - 'email_verified' => true, - ]); - $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_users', $bulk); - - $bulk = new \MongoDB\Driver\BulkWrite(); - $bulk->insert([ - 'client_id' => 'oauth_test_client', - 'key' => $this->getTestPublicKey(), - 'subject' => 'test_subject', - ]); - $bulk->insert([ - 'client_id' => 'oauth_test_client2', - 'key' => $this->getTestPublicKey(), - 'subject' => 'test_subject2', - ]); - $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_jwt', $bulk); - } - - private function createRedisDb(Redis $storage) - { - $storage->setClientDetails("oauth_test_client", "testpass", "http://example.com", 'implicit password'); - $storage->setAccessToken("testtoken", "Some Client", '', time() + 1000); - $storage->setAuthorizationCode("testcode", "Some Client", '', '', time() + 1000); - $storage->setUser("testuser", "password"); - - $storage->setScope('supportedscope1 supportedscope2 supportedscope3 supportedscope4'); - $storage->setScope('defaultscope1 defaultscope2', null, 'default'); - - $storage->setScope('clientscope1 clientscope2', 'Test Client ID'); - $storage->setScope('clientscope1 clientscope2', 'Test Client ID', 'default'); - - $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Client ID 2'); - $storage->setScope('clientscope1 clientscope2', 'Test Client ID 2', 'default'); - - $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID'); - $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID', 'default'); - - $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Default Scope Client ID 2'); - $storage->setScope('clientscope3', 'Test Default Scope Client ID 2', 'default'); - - $storage->setClientKey('oauth_test_client', $this->getTestPublicKey(), 'test_subject'); - } - - public function removeMongo(\MongoDB $db) - { - $db->drop(); - } - - public function removeMongoDB() - { - $command = new \MongoDB\Driver\Command(['dropDatabase' => 1]); - $this->mongodb->executeCommand('oauth2_server_php', $command); - } - - public function getTestPublicKey() - { - return file_get_contents(__DIR__.'/../../../config/keys/id_rsa.pub'); - } - - private function getTestPrivateKey() - { - return file_get_contents(__DIR__.'/../../../config/keys/id_rsa'); - } - - public function getDynamoDbStorage() - { - if (!$this->dynamodb) { - // only run once per travis build - if (true == $this->getEnvVar('TRAVIS')) { - if (self::DYNAMODB_PHP_VERSION != $this->getEnvVar('TRAVIS_PHP_VERSION')) { - $this->dynamodb = new NullStorage('DynamoDb', 'Skipping for travis.ci - only run once per build'); - - return; - } - } - if (class_exists('\Aws\DynamoDb\DynamoDbClient')) { - if ($client = $this->getDynamoDbClient()) { - // travis runs a unique set of tables per build, to avoid conflict - $prefix = ''; - if ($build_id = $this->getEnvVar('TRAVIS_JOB_NUMBER')) { - $prefix = sprintf('build_%s_', $build_id); - } else { - if (!$this->deleteDynamoDb($client, $prefix, true)) { - return $this->dynamodb = new NullStorage('DynamoDb', 'Timed out while waiting for DynamoDB deletion (30 seconds)'); - } - } - $this->createDynamoDb($client, $prefix); - $this->populateDynamoDb($client, $prefix); - $config = array( - 'client_table' => $prefix.'oauth_clients', - 'access_token_table' => $prefix.'oauth_access_tokens', - 'refresh_token_table' => $prefix.'oauth_refresh_tokens', - 'code_table' => $prefix.'oauth_authorization_codes', - 'user_table' => $prefix.'oauth_users', - 'jwt_table' => $prefix.'oauth_jwt', - 'scope_table' => $prefix.'oauth_scopes', - 'public_key_table' => $prefix.'oauth_public_keys', - ); - $this->dynamodb = new DynamoDB($client, $config); - } elseif (!$this->dynamodb) { - $this->dynamodb = new NullStorage('DynamoDb', 'unable to connect to DynamoDB'); - } - } else { - $this->dynamodb = new NullStorage('DynamoDb', 'Missing DynamoDB library. Please run "composer.phar require aws/aws-sdk-php:dev-master'); - } - } - - return $this->dynamodb; - } - - private function getDynamoDbClient() - { - $config = array(); - // check for environment variables - if (($key = $this->getEnvVar('AWS_ACCESS_KEY_ID')) && ($secret = $this->getEnvVar('AWS_SECRET_KEY'))) { - $config['key'] = $key; - $config['secret'] = $secret; - } else { - // fall back on ~/.aws/credentials file - // @see http://docs.aws.amazon.com/aws-sdk-php/guide/latest/credentials.html#credential-profiles - if (!file_exists($this->getEnvVar('HOME') . '/.aws/credentials')) { - $this->dynamodb = new NullStorage('DynamoDb', 'No aws credentials file found, and no AWS_ACCESS_KEY_ID or AWS_SECRET_KEY environment variable set'); - - return; - } - - // set profile in AWS_PROFILE environment variable, defaults to "default" - $config['profile'] = $this->getEnvVar('AWS_PROFILE', 'default'); - } - - // set region in AWS_REGION environment variable, defaults to "us-east-1" - $config['region'] = $this->getEnvVar('AWS_REGION', \Aws\Common\Enum\Region::US_EAST_1); - - return \Aws\DynamoDb\DynamoDbClient::factory($config); - } - - private function deleteDynamoDb(\Aws\DynamoDb\DynamoDbClient $client, $prefix = null, $waitForDeletion = false) - { - $tablesList = explode(' ', 'oauth_access_tokens oauth_authorization_codes oauth_clients oauth_jwt oauth_public_keys oauth_refresh_tokens oauth_scopes oauth_users'); - $nbTables = count($tablesList); - - // Delete all table. - foreach ($tablesList as $key => $table) { - try { - $client->deleteTable(array('TableName' => $prefix.$table)); - } catch (\Aws\DynamoDb\Exception\DynamoDbException $e) { - // Table does not exist : nothing to do - } - } - - // Wait for deleting - if ($waitForDeletion) { - $retries = 5; - $nbTableDeleted = 0; - while ($nbTableDeleted != $nbTables) { - $nbTableDeleted = 0; - foreach ($tablesList as $key => $table) { - try { - $result = $client->describeTable(array('TableName' => $prefix.$table)); - } catch (\Aws\DynamoDb\Exception\DynamoDbException $e) { - // Table does not exist : nothing to do - $nbTableDeleted++; - } - } - if ($nbTableDeleted != $nbTables) { - if ($retries < 0) { - // we are tired of waiting - return false; - } - sleep(5); - echo "Sleeping 5 seconds for DynamoDB ($retries more retries)...\n"; - $retries--; - } - } - } - - return true; - } - - private function createDynamoDb(\Aws\DynamoDb\DynamoDbClient $client, $prefix = null) - { - $tablesList = explode(' ', 'oauth_access_tokens oauth_authorization_codes oauth_clients oauth_jwt oauth_public_keys oauth_refresh_tokens oauth_scopes oauth_users'); - $nbTables = count($tablesList); - $client->createTable(array( - 'TableName' => $prefix.'oauth_access_tokens', - 'AttributeDefinitions' => array( - array('AttributeName' => 'access_token','AttributeType' => 'S') - ), - 'KeySchema' => array(array('AttributeName' => 'access_token','KeyType' => 'HASH')), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - $client->createTable(array( - 'TableName' => $prefix.'oauth_authorization_codes', - 'AttributeDefinitions' => array( - array('AttributeName' => 'authorization_code','AttributeType' => 'S') - ), - 'KeySchema' => array(array('AttributeName' => 'authorization_code','KeyType' => 'HASH')), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - $client->createTable(array( - 'TableName' => $prefix.'oauth_clients', - 'AttributeDefinitions' => array( - array('AttributeName' => 'client_id','AttributeType' => 'S') - ), - 'KeySchema' => array(array('AttributeName' => 'client_id','KeyType' => 'HASH')), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - $client->createTable(array( - 'TableName' => $prefix.'oauth_jwt', - 'AttributeDefinitions' => array( - array('AttributeName' => 'client_id','AttributeType' => 'S'), - array('AttributeName' => 'subject','AttributeType' => 'S') - ), - 'KeySchema' => array( - array('AttributeName' => 'client_id','KeyType' => 'HASH'), - array('AttributeName' => 'subject','KeyType' => 'RANGE') - ), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - $client->createTable(array( - 'TableName' => $prefix.'oauth_public_keys', - 'AttributeDefinitions' => array( - array('AttributeName' => 'client_id','AttributeType' => 'S') - ), - 'KeySchema' => array(array('AttributeName' => 'client_id','KeyType' => 'HASH')), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - $client->createTable(array( - 'TableName' => $prefix.'oauth_refresh_tokens', - 'AttributeDefinitions' => array( - array('AttributeName' => 'refresh_token','AttributeType' => 'S') - ), - 'KeySchema' => array(array('AttributeName' => 'refresh_token','KeyType' => 'HASH')), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - $client->createTable(array( - 'TableName' => $prefix.'oauth_scopes', - 'AttributeDefinitions' => array( - array('AttributeName' => 'scope','AttributeType' => 'S'), - array('AttributeName' => 'is_default','AttributeType' => 'S') - ), - 'KeySchema' => array(array('AttributeName' => 'scope','KeyType' => 'HASH')), - 'GlobalSecondaryIndexes' => array( - array( - 'IndexName' => 'is_default-index', - 'KeySchema' => array(array('AttributeName' => 'is_default', 'KeyType' => 'HASH')), - 'Projection' => array('ProjectionType' => 'ALL'), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - ), - ), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - $client->createTable(array( - 'TableName' => $prefix.'oauth_users', - 'AttributeDefinitions' => array(array('AttributeName' => 'username','AttributeType' => 'S')), - 'KeySchema' => array(array('AttributeName' => 'username','KeyType' => 'HASH')), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - // Wait for creation - $nbTableCreated = 0; - while ($nbTableCreated != $nbTables) { - $nbTableCreated = 0; - foreach ($tablesList as $key => $table) { - try { - $result = $client->describeTable(array('TableName' => $prefix.$table)); - if ($result['Table']['TableStatus'] == 'ACTIVE') { - $nbTableCreated++; - } - } catch (\Aws\DynamoDb\Exception\DynamoDbException $e) { - // Table does not exist : nothing to do - $nbTableCreated++; - } - } - if ($nbTableCreated != $nbTables) { - sleep(1); - } - } - } - - private function populateDynamoDb($client, $prefix = null) - { - // set up scopes - foreach (explode(' ', 'supportedscope1 supportedscope2 supportedscope3 supportedscope4 clientscope1 clientscope2 clientscope3') as $supportedScope) { - $client->putItem(array( - 'TableName' => $prefix.'oauth_scopes', - 'Item' => array('scope' => array('S' => $supportedScope)) - )); - } - - foreach (array('defaultscope1', 'defaultscope2') as $defaultScope) { - $client->putItem(array( - 'TableName' => $prefix.'oauth_scopes', - 'Item' => array('scope' => array('S' => $defaultScope), 'is_default' => array('S' => "true")) - )); - } - - $client->putItem(array( - 'TableName' => $prefix.'oauth_clients', - 'Item' => array( - 'client_id' => array('S' => 'Test Client ID'), - 'client_secret' => array('S' => 'TestSecret'), - 'scope' => array('S' => 'clientscope1 clientscope2') - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_clients', - 'Item' => array( - 'client_id' => array('S' => 'Test Client ID 2'), - 'client_secret' => array('S' => 'TestSecret'), - 'scope' => array('S' => 'clientscope1 clientscope2 clientscope3') - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_clients', - 'Item' => array( - 'client_id' => array('S' => 'Test Default Scope Client ID'), - 'client_secret' => array('S' => 'TestSecret'), - 'scope' => array('S' => 'clientscope1 clientscope2') - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_clients', - 'Item' => array( - 'client_id' => array('S' => 'oauth_test_client'), - 'client_secret' => array('S' => 'testpass'), - 'grant_types' => array('S' => 'implicit password') - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_access_tokens', - 'Item' => array( - 'access_token' => array('S' => 'testtoken'), - 'client_id' => array('S' => 'Some Client'), - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_access_tokens', - 'Item' => array( - 'access_token' => array('S' => 'accesstoken-openid-connect'), - 'client_id' => array('S' => 'Some Client'), - 'user_id' => array('S' => 'testuser'), - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_authorization_codes', - 'Item' => array( - 'authorization_code' => array('S' => 'testcode'), - 'client_id' => array('S' => 'Some Client'), - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_users', - 'Item' => array( - 'username' => array('S' => 'testuser'), - 'password' => array('S' => 'password'), - 'email' => array('S' => 'testuser@test.com'), - 'email_verified' => array('S' => 'true'), - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_public_keys', - 'Item' => array( - 'client_id' => array('S' => 'ClientID_One'), - 'public_key' => array('S' => 'client_1_public'), - 'private_key' => array('S' => 'client_1_private'), - 'encryption_algorithm' => array('S' => 'RS256'), - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_public_keys', - 'Item' => array( - 'client_id' => array('S' => 'ClientID_Two'), - 'public_key' => array('S' => 'client_2_public'), - 'private_key' => array('S' => 'client_2_private'), - 'encryption_algorithm' => array('S' => 'RS256'), - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_public_keys', - 'Item' => array( - 'client_id' => array('S' => '0'), - 'public_key' => array('S' => $this->getTestPublicKey()), - 'private_key' => array('S' => $this->getTestPrivateKey()), - 'encryption_algorithm' => array('S' => 'RS256'), - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_jwt', - 'Item' => array( - 'client_id' => array('S' => 'oauth_test_client'), - 'subject' => array('S' => 'test_subject'), - 'public_key' => array('S' => $this->getTestPublicKey()), - ) - )); - } - - public function cleanupTravisDynamoDb($prefix = null) - { - if (is_null($prefix)) { - // skip this when not applicable - if (!$this->getEnvVar('TRAVIS') || self::DYNAMODB_PHP_VERSION != $this->getEnvVar('TRAVIS_PHP_VERSION')) { - return; - } - - $prefix = sprintf('build_%s_', $this->getEnvVar('TRAVIS_JOB_NUMBER')); - } - - $client = $this->getDynamoDbClient(); - $this->deleteDynamoDb($client, $prefix); - } - - private function getEnvVar($var, $default = null) - { - return isset($_SERVER[$var]) ? $_SERVER[$var] : (getenv($var) ?: $default); - } -} +configDir = __DIR__.'/../../../config'; + } + + public static function getInstance() + { + if (!self::$instance) { + self::$instance = new self(); + } + + return self::$instance; + } + + public function getSqlitePdo() + { + if (!$this->sqlite) { + $this->removeSqliteDb(); + $pdo = new \PDO(sprintf('sqlite://%s', $this->getSqliteDir())); + $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); + $this->createSqliteDb($pdo); + + $this->sqlite = new Pdo($pdo); + } + + return $this->sqlite; + } + + public function getPostgresPdo() + { + if (!$this->postgres) { + if (in_array('pgsql', \PDO::getAvailableDrivers())) { + $this->removePostgresDb(); + $this->createPostgresDb(); + if ($pdo = $this->getPostgresDriver()) { + $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); + $this->populatePostgresDb($pdo); + $this->postgres = new Pdo($pdo); + } + } else { + $this->postgres = new NullStorage('Postgres', 'Missing postgres PDO extension.'); + } + } + + return $this->postgres; + } + + public function getPostgresDriver() + { + try { + $pdo = new \PDO('pgsql:host=localhost;dbname=oauth2_server_php', 'postgres'); + + return $pdo; + } catch (\PDOException $e) { + $this->postgres = new NullStorage('Postgres', $e->getMessage()); + } + } + + public function getMemoryStorage() + { + return new Memory(json_decode(file_get_contents($this->configDir. '/storage.json'), true)); + } + + public function getRedisStorage() + { + if (!$this->redis) { + if (class_exists('Predis\Client')) { + $redis = new \Predis\Client(); + if ($this->testRedisConnection($redis)) { + $redis->flushdb(); + $this->redis = new Redis($redis); + $this->createRedisDb($this->redis); + } else { + $this->redis = new NullStorage('Redis', 'Unable to connect to redis server on port 6379'); + } + } else { + $this->redis = new NullStorage('Redis', 'Missing redis library. Please run "composer.phar require predis/predis:dev-master"'); + } + } + + return $this->redis; + } + + private function testRedisConnection(\Predis\Client $redis) + { + try { + $redis->connect(); + } catch (\Predis\CommunicationException $exception) { + // we were unable to connect to the redis server + return false; + } + + return true; + } + + public function getMysqlPdo() + { + if (!$this->mysql) { + $pdo = null; + try { + $pdo = new \PDO('mysql:host=localhost;', 'root'); + } catch (\PDOException $e) { + $this->mysql = new NullStorage('MySQL', 'Unable to connect to MySQL on root@localhost'); + } + + if ($pdo) { + $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); + $this->removeMysqlDb($pdo); + $this->createMysqlDb($pdo); + + $this->mysql = new Pdo($pdo); + } + } + + return $this->mysql; + } + + public function getMongo() + { + if (!$this->mongo) { + $skipMongo = $this->getEnvVar('SKIP_MONGO_TESTS'); + if (!$skipMongo && class_exists('MongoClient')) { + $mongo = new \MongoClient('mongodb://localhost:27017', array('connect' => false)); + if ($this->testMongoConnection($mongo)) { + $db = $mongo->oauth2_server_php; + $this->removeMongo($db); + $this->createMongo($db); + $this->mongo = new Mongo($db); + } else { + $this->mongo = new NullStorage('Mongo', 'Unable to connect to mongo server on "localhost:27017"'); + } + } else { + $this->mongo = new NullStorage('Mongo', 'Missing mongo php extension. Please install mongo.so'); + } + } + + return $this->mongo; + } + + private function testMongoConnection(\MongoClient $mongo) + { + try { + $mongo->connect(); + } catch (\MongoConnectionException $e) { + return false; + } + + return true; + } + + public function getMongoDB() + { + if (!$this->mongodb) { + if ('5.3' === substr(phpversion(), 0, 3)) { + $this->mongodb = new NullStorage('MongoDB', 'The mongodb.so extension is not compatible with PHP 5.3'); + } elseif ($this->getEnvVar('SKIP_MONGODB_TESTS')) { + $this->mongodb = new NullStorage('MongoDB', 'Skipping MongoDB tests'); + } elseif (class_exists('\MongoDB\Driver\Manager')) { + try { + $this->mongodb = new \MongoDB\Driver\Manager('mongodb://localhost:27017'); + $this->mongodb->selectServer($this->mongodb->getReadPreference()); + } catch (\Exception $e) { + $this->mongodb = new NullStorage('MongoDB', 'Unable to connect to MongoDB server on "localhost:27017"'); + } + $this->removeMongoDB(); + $this->createMongoDB(); + } else { + $this->mongodb = new NullStorage('MongoDB', 'Missing MongoDB php extension. Please install mongodb.so'); + } + } + + return $this->mongodb; + } + + public function getCouchbase() + { + if (!$this->couchbase) { + if ($this->getEnvVar('SKIP_COUCHBASE_TESTS')) { + $this->couchbase = new NullStorage('Couchbase', 'Skipping Couchbase tests'); + } elseif (!class_exists('Couchbase')) { + $this->couchbase = new NullStorage('Couchbase', 'Missing Couchbase php extension. Please install couchbase.so'); + } else { + // round-about way to make sure couchbase is working + // this is required because it throws a "floating point exception" otherwise + $code = "new \Couchbase(array('localhost:8091'), '', '', 'auth', false);"; + $exec = sprintf('php -r "%s"', $code); + $ret = exec($exec, $test, $var); + if ($ret != 0) { + $couchbase = new \Couchbase(array('localhost:8091'), '', '', 'auth', false); + if ($this->testCouchbaseConnection($couchbase)) { + $this->clearCouchbase($couchbase); + $this->createCouchbaseDB($couchbase); + + $this->couchbase = new CouchbaseDB($couchbase); + } else { + $this->couchbase = new NullStorage('Couchbase', 'Unable to connect to Couchbase server on "localhost:8091"'); + } + } else { + $this->couchbase = new NullStorage('Couchbase', 'Error while trying to connect to Couchbase'); + } + } + } + + return $this->couchbase; + } + + private function testCouchbaseConnection(\Couchbase $couchbase) + { + try { + if (count($couchbase->getServers()) > 0) { + return true; + } + } catch (\CouchbaseException $e) { + return false; + } + + return true; + } + + public function getCassandraStorage() + { + if (!$this->cassandra) { + if (class_exists('phpcassa\ColumnFamily')) { + $cassandra = new \phpcassa\Connection\ConnectionPool('oauth2_test', array('127.0.0.1:9160')); + if ($this->testCassandraConnection($cassandra)) { + $this->removeCassandraDb(); + $this->cassandra = new Cassandra($cassandra); + $this->createCassandraDb($this->cassandra); + } else { + $this->cassandra = new NullStorage('Cassandra', 'Unable to connect to cassandra server on "127.0.0.1:9160"'); + } + } else { + $this->cassandra = new NullStorage('Cassandra', 'Missing cassandra library. Please run "composer.phar require thobbs/phpcassa:dev-master"'); + } + } + + return $this->cassandra; + } + + private function testCassandraConnection(\phpcassa\Connection\ConnectionPool $cassandra) + { + try { + new \phpcassa\SystemManager('localhost:9160'); + } catch (\Exception $e) { + return false; + } + + return true; + } + + private function removeCassandraDb() + { + $sys = new \phpcassa\SystemManager('localhost:9160'); + + try { + $sys->drop_keyspace('oauth2_test'); + } catch (\cassandra\InvalidRequestException $e) { + + } + } + + private function createCassandraDb(Cassandra $storage) + { + // create the cassandra keyspace and column family + $sys = new \phpcassa\SystemManager('localhost:9160'); + + $sys->create_keyspace('oauth2_test', array( + "strategy_class" => \phpcassa\Schema\StrategyClass::SIMPLE_STRATEGY, + "strategy_options" => array('replication_factor' => '1') + )); + + $sys->create_column_family('oauth2_test', 'auth'); + $cassandra = new \phpcassa\Connection\ConnectionPool('oauth2_test', array('127.0.0.1:9160')); + $cf = new \phpcassa\ColumnFamily($cassandra, 'auth'); + + // populate the data + $storage->setClientDetails("oauth_test_client", "testpass", "http://example.com", 'implicit password'); + $storage->setAccessToken("testtoken", "Some Client", '', time() + 1000); + $storage->setAuthorizationCode("testcode", "Some Client", '', '', time() + 1000); + + $storage->setScope('supportedscope1 supportedscope2 supportedscope3 supportedscope4'); + $storage->setScope('defaultscope1 defaultscope2', null, 'default'); + + $storage->setScope('clientscope1 clientscope2', 'Test Client ID'); + $storage->setScope('clientscope1 clientscope2', 'Test Client ID', 'default'); + + $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Client ID 2'); + $storage->setScope('clientscope1 clientscope2', 'Test Client ID 2', 'default'); + + $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID'); + $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID', 'default'); + + $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Default Scope Client ID 2'); + $storage->setScope('clientscope3', 'Test Default Scope Client ID 2', 'default'); + + $storage->setClientKey('oauth_test_client', $this->getTestPublicKey(), 'test_subject'); + + $cf->insert("oauth_public_keys:ClientID_One", array('__data' => json_encode(array("public_key" => "client_1_public", "private_key" => "client_1_private", "encryption_algorithm" => "RS256")))); + $cf->insert("oauth_public_keys:ClientID_Two", array('__data' => json_encode(array("public_key" => "client_2_public", "private_key" => "client_2_private", "encryption_algorithm" => "RS256")))); + $cf->insert("oauth_public_keys:", array('__data' => json_encode(array("public_key" => $this->getTestPublicKey(), "private_key" => $this->getTestPrivateKey(), "encryption_algorithm" => "RS256")))); + + $cf->insert("oauth_users:testuser", array('__data' =>json_encode(array("password" => "password", "email" => "testuser@test.com", "email_verified" => true)))); + + } + + private function createSqliteDb(\PDO $pdo) + { + $this->runPdoSql($pdo); + } + + private function removeSqliteDb() + { + if (file_exists($this->getSqliteDir())) { + unlink($this->getSqliteDir()); + } + } + + private function createMysqlDb(\PDO $pdo) + { + $pdo->exec('CREATE DATABASE oauth2_server_php'); + $pdo->exec('USE oauth2_server_php'); + $this->runPdoSql($pdo); + } + + private function removeMysqlDb(\PDO $pdo) + { + $pdo->exec('DROP DATABASE IF EXISTS oauth2_server_php'); + } + + private function createPostgresDb() + { + if (!`psql postgres -tAc "SELECT 1 FROM pg_roles WHERE rolname='postgres'"`) { + `createuser -s -r postgres`; + } + + `createdb -O postgres oauth2_server_php`; + } + + private function populatePostgresDb(\PDO $pdo) + { + $this->runPdoSql($pdo); + } + + private function removePostgresDb() + { + if (trim(`psql -l | grep oauth2_server_php | wc -l`)) { + `dropdb oauth2_server_php`; + } + } + + public function runPdoSql(\PDO $pdo) + { + $storage = new Pdo($pdo); + foreach (explode(';', $storage->getBuildSql()) as $statement) { + $result = $pdo->exec($statement); + } + + // set up scopes + $sql = 'INSERT INTO oauth_scopes (scope) VALUES (?)'; + foreach (explode(' ', 'supportedscope1 supportedscope2 supportedscope3 supportedscope4 clientscope1 clientscope2 clientscope3') as $supportedScope) { + $pdo->prepare($sql)->execute(array($supportedScope)); + } + + $sql = 'INSERT INTO oauth_scopes (scope, is_default) VALUES (?, ?)'; + foreach (array('defaultscope1', 'defaultscope2') as $defaultScope) { + $pdo->prepare($sql)->execute(array($defaultScope, true)); + } + + // set up clients + $sql = 'INSERT INTO oauth_clients (client_id, client_secret, scope, grant_types) VALUES (?, ?, ?, ?)'; + $pdo->prepare($sql)->execute(array('Test Client ID', 'TestSecret', 'clientscope1 clientscope2', null)); + $pdo->prepare($sql)->execute(array('Test Client ID 2', 'TestSecret', 'clientscope1 clientscope2 clientscope3', null)); + $pdo->prepare($sql)->execute(array('Test Default Scope Client ID', 'TestSecret', 'clientscope1 clientscope2', null)); + $pdo->prepare($sql)->execute(array('oauth_test_client', 'testpass', null, 'implicit password')); + + // set up misc + $sql = 'INSERT INTO oauth_access_tokens (access_token, client_id, expires, user_id) VALUES (?, ?, ?, ?)'; + $pdo->prepare($sql)->execute(array('testtoken', 'Some Client', date('Y-m-d H:i:s', strtotime('+1 hour')), null)); + $pdo->prepare($sql)->execute(array('accesstoken-openid-connect', 'Some Client', date('Y-m-d H:i:s', strtotime('+1 hour')), 'testuser')); + + $sql = 'INSERT INTO oauth_authorization_codes (authorization_code, client_id, expires) VALUES (?, ?, ?)'; + $pdo->prepare($sql)->execute(array('testcode', 'Some Client', date('Y-m-d H:i:s', strtotime('+1 hour')))); + + $sql = 'INSERT INTO oauth_users (username, password, email, email_verified) VALUES (?, ?, ?, ?)'; + $pdo->prepare($sql)->execute(array('testuser', 'password', 'testuser@test.com', true)); + + $sql = 'INSERT INTO oauth_public_keys (client_id, public_key, private_key, encryption_algorithm) VALUES (?, ?, ?, ?)'; + $pdo->prepare($sql)->execute(array('ClientID_One', 'client_1_public', 'client_1_private', 'RS256')); + $pdo->prepare($sql)->execute(array('ClientID_Two', 'client_2_public', 'client_2_private', 'RS256')); + + $sql = 'INSERT INTO oauth_public_keys (client_id, public_key, private_key, encryption_algorithm) VALUES (?, ?, ?, ?)'; + $pdo->prepare($sql)->execute(array(null, $this->getTestPublicKey(), $this->getTestPrivateKey(), 'RS256')); + + $sql = 'INSERT INTO oauth_jwt (client_id, subject, public_key) VALUES (?, ?, ?)'; + $pdo->prepare($sql)->execute(array('oauth_test_client', 'test_subject', $this->getTestPublicKey())); + } + + public function getSqliteDir() + { + return $this->configDir. '/test.sqlite'; + } + + public function getConfigDir() + { + return $this->configDir; + } + + private function createCouchbaseDB(\Couchbase $db) + { + $db->set('oauth_clients-oauth_test_client',json_encode(array( + 'client_id' => "oauth_test_client", + 'client_secret' => "testpass", + 'redirect_uri' => "http://example.com", + 'grant_types' => 'implicit password' + ))); + + $db->set('oauth_access_tokens-testtoken',json_encode(array( + 'access_token' => "testtoken", + 'client_id' => "Some Client" + ))); + + $db->set('oauth_authorization_codes-testcode',json_encode(array( + 'access_token' => "testcode", + 'client_id' => "Some Client" + ))); + + $db->set('oauth_users-testuser',json_encode(array( + 'username' => 'testuser', + 'password' => 'password', + 'email' => 'testuser@test.com', + 'email_verified' => true, + ))); + + $db->set('oauth_jwt-oauth_test_client',json_encode(array( + 'client_id' => 'oauth_test_client', + 'key' => $this->getTestPublicKey(), + 'subject' => 'test_subject', + ))); + } + + private function clearCouchbase(\Couchbase $cb) + { + $cb->delete('oauth_authorization_codes-new-openid-code'); + $cb->delete('oauth_access_tokens-newtoken'); + $cb->delete('oauth_authorization_codes-newcode'); + $cb->delete('oauth_refresh_tokens-refreshtoken'); + } + + private function createMongo(\MongoDB $db) + { + $db->oauth_clients->insert(array( + 'client_id' => "oauth_test_client", + 'client_secret' => "testpass", + 'redirect_uri' => "http://example.com", + 'grant_types' => 'implicit password' + )); + + $db->oauth_access_tokens->insert(array( + 'access_token' => "testtoken", + 'client_id' => "Some Client" + )); + + $db->oauth_authorization_codes->insert(array( + 'authorization_code' => "testcode", + 'client_id' => "Some Client" + )); + + $db->oauth_users->insert(array( + 'username' => 'testuser', + 'password' => 'password', + 'email' => 'testuser@test.com', + 'email_verified' => true, + )); + + $db->oauth_jwt->insert(array( + 'client_id' => 'oauth_test_client', + 'key' => $this->getTestPublicKey(), + 'subject' => 'test_subject', + )); + } + + private function createMongoDB() + { + $bulk = new \MongoDB\Driver\BulkWrite(); + $bulk->insert(array( + 'client_id' => "oauth_test_client", + 'client_secret' => "testpass", + 'redirect_uri' => "http://example.com", + 'grant_types' => 'implicit password', + 'scope' => 'clientscope1 clientscope2' + )); + $bulk->insert(array( + 'client_id' => "oauth_test_client2", + 'client_secret' => "testpass2", + 'redirect_uri' => "http://example.com", + 'grant_types' => 'implicit password', + 'scope' => 'clientscope3 clientscope4' + )); + $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_clients', $bulk); + + $bulk = new \MongoDB\Driver\BulkWrite(); + $bulk->insert(array( + 'access_token' => "testtoken", + 'client_id' => "Some Client" + )); + $bulk->insert(array( + 'access_token' => "testtoken2", + 'client_id' => "Some Client2" + )); + $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_access_tokens', $bulk); + + $bulk = new \MongoDB\Driver\BulkWrite(); + $bulk->insert(array( + 'authorization_code' => "testcode", + 'client_id' => "Some Client" + )); + $bulk->insert(array( + 'authorization_code' => "testcode2", + 'client_id' => "Some Client2" + )); + $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_authorization_codes', $bulk); + + $bulk = new \MongoDB\Driver\BulkWrite(); + $bulk->insert(array( + 'refresh_token' => 'testrefreshtoken', + 'client_id' => 'Some Client', + )); + $bulk->insert(array( + 'refresh_token' => 'testrefreshtoken2', + 'client_id' => 'Some Client2', + )); + $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_refresh_tokens', $bulk); + + $bulk = new \MongoDB\Driver\BulkWrite(); + $bulk->insert(array( + 'username' => 'testuser', + 'password' => 'password', + 'email' => 'testuser@test.com', + 'email_verified' => true, + )); + $bulk->insert(array( + 'username' => 'testuser2', + 'password' => 'password2', + 'email' => 'testuser@test.com', + 'email_verified' => true, + )); + $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_users', $bulk); + + $bulk = new \MongoDB\Driver\BulkWrite(); + $bulk->insert(array( + 'client_id' => 'oauth_test_client', + 'key' => $this->getTestPublicKey(), + 'subject' => 'test_subject', + )); + $bulk->insert(array( + 'client_id' => 'oauth_test_client2', + 'key' => $this->getTestPublicKey(), + 'subject' => 'test_subject2', + )); + $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_jwt', $bulk); + } + + private function createRedisDb(Redis $storage) + { + $storage->setClientDetails("oauth_test_client", "testpass", "http://example.com", 'implicit password'); + $storage->setAccessToken("testtoken", "Some Client", '', time() + 1000); + $storage->setAuthorizationCode("testcode", "Some Client", '', '', time() + 1000); + $storage->setUser("testuser", "password"); + + $storage->setScope('supportedscope1 supportedscope2 supportedscope3 supportedscope4'); + $storage->setScope('defaultscope1 defaultscope2', null, 'default'); + + $storage->setScope('clientscope1 clientscope2', 'Test Client ID'); + $storage->setScope('clientscope1 clientscope2', 'Test Client ID', 'default'); + + $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Client ID 2'); + $storage->setScope('clientscope1 clientscope2', 'Test Client ID 2', 'default'); + + $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID'); + $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID', 'default'); + + $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Default Scope Client ID 2'); + $storage->setScope('clientscope3', 'Test Default Scope Client ID 2', 'default'); + + $storage->setClientKey('oauth_test_client', $this->getTestPublicKey(), 'test_subject'); + } + + public function removeMongo(\MongoDB $db) + { + $db->drop(); + } + + public function removeMongoDB() + { + $command = new \MongoDB\Driver\Command(array('dropDatabase' => 1)); + $this->mongodb->executeCommand('oauth2_server_php', $command); + } + + public function getTestPublicKey() + { + return file_get_contents(__DIR__.'/../../../config/keys/id_rsa.pub'); + } + + private function getTestPrivateKey() + { + return file_get_contents(__DIR__.'/../../../config/keys/id_rsa'); + } + + public function getDynamoDbStorage() + { + if (!$this->dynamodb) { + // only run once per travis build + if (true == $this->getEnvVar('TRAVIS')) { + if (self::DYNAMODB_PHP_VERSION != $this->getEnvVar('TRAVIS_PHP_VERSION')) { + $this->dynamodb = new NullStorage('DynamoDb', 'Skipping for travis.ci - only run once per build'); + + return; + } + } + if (class_exists('\Aws\DynamoDb\DynamoDbClient')) { + if ($client = $this->getDynamoDbClient()) { + // travis runs a unique set of tables per build, to avoid conflict + $prefix = ''; + if ($build_id = $this->getEnvVar('TRAVIS_JOB_NUMBER')) { + $prefix = sprintf('build_%s_', $build_id); + } else { + if (!$this->deleteDynamoDb($client, $prefix, true)) { + return $this->dynamodb = new NullStorage('DynamoDb', 'Timed out while waiting for DynamoDB deletion (30 seconds)'); + } + } + $this->createDynamoDb($client, $prefix); + $this->populateDynamoDb($client, $prefix); + $config = array( + 'client_table' => $prefix.'oauth_clients', + 'access_token_table' => $prefix.'oauth_access_tokens', + 'refresh_token_table' => $prefix.'oauth_refresh_tokens', + 'code_table' => $prefix.'oauth_authorization_codes', + 'user_table' => $prefix.'oauth_users', + 'jwt_table' => $prefix.'oauth_jwt', + 'scope_table' => $prefix.'oauth_scopes', + 'public_key_table' => $prefix.'oauth_public_keys', + ); + $this->dynamodb = new DynamoDB($client, $config); + } elseif (!$this->dynamodb) { + $this->dynamodb = new NullStorage('DynamoDb', 'unable to connect to DynamoDB'); + } + } else { + $this->dynamodb = new NullStorage('DynamoDb', 'Missing DynamoDB library. Please run "composer.phar require aws/aws-sdk-php:dev-master'); + } + } + + return $this->dynamodb; + } + + private function getDynamoDbClient() + { + $config = array(); + // check for environment variables + if (($key = $this->getEnvVar('AWS_ACCESS_KEY_ID')) && ($secret = $this->getEnvVar('AWS_SECRET_KEY'))) { + $config['key'] = $key; + $config['secret'] = $secret; + } else { + // fall back on ~/.aws/credentials file + // @see http://docs.aws.amazon.com/aws-sdk-php/guide/latest/credentials.html#credential-profiles + if (!file_exists($this->getEnvVar('HOME') . '/.aws/credentials')) { + $this->dynamodb = new NullStorage('DynamoDb', 'No aws credentials file found, and no AWS_ACCESS_KEY_ID or AWS_SECRET_KEY environment variable set'); + + return; + } + + // set profile in AWS_PROFILE environment variable, defaults to "default" + $config['profile'] = $this->getEnvVar('AWS_PROFILE', 'default'); + } + + // set region in AWS_REGION environment variable, defaults to "us-east-1" + $config['region'] = $this->getEnvVar('AWS_REGION', \Aws\Common\Enum\Region::US_EAST_1); + + return \Aws\DynamoDb\DynamoDbClient::factory($config); + } + + private function deleteDynamoDb(\Aws\DynamoDb\DynamoDbClient $client, $prefix = null, $waitForDeletion = false) + { + $tablesList = explode(' ', 'oauth_access_tokens oauth_authorization_codes oauth_clients oauth_jwt oauth_public_keys oauth_refresh_tokens oauth_scopes oauth_users'); + $nbTables = count($tablesList); + + // Delete all table. + foreach ($tablesList as $key => $table) { + try { + $client->deleteTable(array('TableName' => $prefix.$table)); + } catch (\Aws\DynamoDb\Exception\DynamoDbException $e) { + // Table does not exist : nothing to do + } + } + + // Wait for deleting + if ($waitForDeletion) { + $retries = 5; + $nbTableDeleted = 0; + while ($nbTableDeleted != $nbTables) { + $nbTableDeleted = 0; + foreach ($tablesList as $key => $table) { + try { + $result = $client->describeTable(array('TableName' => $prefix.$table)); + } catch (\Aws\DynamoDb\Exception\DynamoDbException $e) { + // Table does not exist : nothing to do + $nbTableDeleted++; + } + } + if ($nbTableDeleted != $nbTables) { + if ($retries < 0) { + // we are tired of waiting + return false; + } + sleep(5); + echo "Sleeping 5 seconds for DynamoDB ($retries more retries)...\n"; + $retries--; + } + } + } + + return true; + } + + private function createDynamoDb(\Aws\DynamoDb\DynamoDbClient $client, $prefix = null) + { + $tablesList = explode(' ', 'oauth_access_tokens oauth_authorization_codes oauth_clients oauth_jwt oauth_public_keys oauth_refresh_tokens oauth_scopes oauth_users'); + $nbTables = count($tablesList); + $client->createTable(array( + 'TableName' => $prefix.'oauth_access_tokens', + 'AttributeDefinitions' => array( + array('AttributeName' => 'access_token','AttributeType' => 'S') + ), + 'KeySchema' => array(array('AttributeName' => 'access_token','KeyType' => 'HASH')), + 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) + )); + + $client->createTable(array( + 'TableName' => $prefix.'oauth_authorization_codes', + 'AttributeDefinitions' => array( + array('AttributeName' => 'authorization_code','AttributeType' => 'S') + ), + 'KeySchema' => array(array('AttributeName' => 'authorization_code','KeyType' => 'HASH')), + 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) + )); + + $client->createTable(array( + 'TableName' => $prefix.'oauth_clients', + 'AttributeDefinitions' => array( + array('AttributeName' => 'client_id','AttributeType' => 'S') + ), + 'KeySchema' => array(array('AttributeName' => 'client_id','KeyType' => 'HASH')), + 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) + )); + + $client->createTable(array( + 'TableName' => $prefix.'oauth_jwt', + 'AttributeDefinitions' => array( + array('AttributeName' => 'client_id','AttributeType' => 'S'), + array('AttributeName' => 'subject','AttributeType' => 'S') + ), + 'KeySchema' => array( + array('AttributeName' => 'client_id','KeyType' => 'HASH'), + array('AttributeName' => 'subject','KeyType' => 'RANGE') + ), + 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) + )); + + $client->createTable(array( + 'TableName' => $prefix.'oauth_public_keys', + 'AttributeDefinitions' => array( + array('AttributeName' => 'client_id','AttributeType' => 'S') + ), + 'KeySchema' => array(array('AttributeName' => 'client_id','KeyType' => 'HASH')), + 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) + )); + + $client->createTable(array( + 'TableName' => $prefix.'oauth_refresh_tokens', + 'AttributeDefinitions' => array( + array('AttributeName' => 'refresh_token','AttributeType' => 'S') + ), + 'KeySchema' => array(array('AttributeName' => 'refresh_token','KeyType' => 'HASH')), + 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) + )); + + $client->createTable(array( + 'TableName' => $prefix.'oauth_scopes', + 'AttributeDefinitions' => array( + array('AttributeName' => 'scope','AttributeType' => 'S'), + array('AttributeName' => 'is_default','AttributeType' => 'S') + ), + 'KeySchema' => array(array('AttributeName' => 'scope','KeyType' => 'HASH')), + 'GlobalSecondaryIndexes' => array( + array( + 'IndexName' => 'is_default-index', + 'KeySchema' => array(array('AttributeName' => 'is_default', 'KeyType' => 'HASH')), + 'Projection' => array('ProjectionType' => 'ALL'), + 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) + ), + ), + 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) + )); + + $client->createTable(array( + 'TableName' => $prefix.'oauth_users', + 'AttributeDefinitions' => array(array('AttributeName' => 'username','AttributeType' => 'S')), + 'KeySchema' => array(array('AttributeName' => 'username','KeyType' => 'HASH')), + 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) + )); + + // Wait for creation + $nbTableCreated = 0; + while ($nbTableCreated != $nbTables) { + $nbTableCreated = 0; + foreach ($tablesList as $key => $table) { + try { + $result = $client->describeTable(array('TableName' => $prefix.$table)); + if ($result['Table']['TableStatus'] == 'ACTIVE') { + $nbTableCreated++; + } + } catch (\Aws\DynamoDb\Exception\DynamoDbException $e) { + // Table does not exist : nothing to do + $nbTableCreated++; + } + } + if ($nbTableCreated != $nbTables) { + sleep(1); + } + } + } + + private function populateDynamoDb($client, $prefix = null) + { + // set up scopes + foreach (explode(' ', 'supportedscope1 supportedscope2 supportedscope3 supportedscope4 clientscope1 clientscope2 clientscope3') as $supportedScope) { + $client->putItem(array( + 'TableName' => $prefix.'oauth_scopes', + 'Item' => array('scope' => array('S' => $supportedScope)) + )); + } + + foreach (array('defaultscope1', 'defaultscope2') as $defaultScope) { + $client->putItem(array( + 'TableName' => $prefix.'oauth_scopes', + 'Item' => array('scope' => array('S' => $defaultScope), 'is_default' => array('S' => "true")) + )); + } + + $client->putItem(array( + 'TableName' => $prefix.'oauth_clients', + 'Item' => array( + 'client_id' => array('S' => 'Test Client ID'), + 'client_secret' => array('S' => 'TestSecret'), + 'scope' => array('S' => 'clientscope1 clientscope2') + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_clients', + 'Item' => array( + 'client_id' => array('S' => 'Test Client ID 2'), + 'client_secret' => array('S' => 'TestSecret'), + 'scope' => array('S' => 'clientscope1 clientscope2 clientscope3') + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_clients', + 'Item' => array( + 'client_id' => array('S' => 'Test Default Scope Client ID'), + 'client_secret' => array('S' => 'TestSecret'), + 'scope' => array('S' => 'clientscope1 clientscope2') + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_clients', + 'Item' => array( + 'client_id' => array('S' => 'oauth_test_client'), + 'client_secret' => array('S' => 'testpass'), + 'grant_types' => array('S' => 'implicit password') + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_access_tokens', + 'Item' => array( + 'access_token' => array('S' => 'testtoken'), + 'client_id' => array('S' => 'Some Client'), + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_access_tokens', + 'Item' => array( + 'access_token' => array('S' => 'accesstoken-openid-connect'), + 'client_id' => array('S' => 'Some Client'), + 'user_id' => array('S' => 'testuser'), + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_authorization_codes', + 'Item' => array( + 'authorization_code' => array('S' => 'testcode'), + 'client_id' => array('S' => 'Some Client'), + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_users', + 'Item' => array( + 'username' => array('S' => 'testuser'), + 'password' => array('S' => 'password'), + 'email' => array('S' => 'testuser@test.com'), + 'email_verified' => array('S' => 'true'), + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_public_keys', + 'Item' => array( + 'client_id' => array('S' => 'ClientID_One'), + 'public_key' => array('S' => 'client_1_public'), + 'private_key' => array('S' => 'client_1_private'), + 'encryption_algorithm' => array('S' => 'RS256'), + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_public_keys', + 'Item' => array( + 'client_id' => array('S' => 'ClientID_Two'), + 'public_key' => array('S' => 'client_2_public'), + 'private_key' => array('S' => 'client_2_private'), + 'encryption_algorithm' => array('S' => 'RS256'), + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_public_keys', + 'Item' => array( + 'client_id' => array('S' => '0'), + 'public_key' => array('S' => $this->getTestPublicKey()), + 'private_key' => array('S' => $this->getTestPrivateKey()), + 'encryption_algorithm' => array('S' => 'RS256'), + ) + )); + + $client->putItem(array( + 'TableName' => $prefix.'oauth_jwt', + 'Item' => array( + 'client_id' => array('S' => 'oauth_test_client'), + 'subject' => array('S' => 'test_subject'), + 'public_key' => array('S' => $this->getTestPublicKey()), + ) + )); + } + + public function cleanupTravisDynamoDb($prefix = null) + { + if (is_null($prefix)) { + // skip this when not applicable + if (!$this->getEnvVar('TRAVIS') || self::DYNAMODB_PHP_VERSION != $this->getEnvVar('TRAVIS_PHP_VERSION')) { + return; + } + + $prefix = sprintf('build_%s_', $this->getEnvVar('TRAVIS_JOB_NUMBER')); + } + + $client = $this->getDynamoDbClient(); + $this->deleteDynamoDb($client, $prefix); + } + + private function getEnvVar($var, $default = null) + { + return isset($_SERVER[$var]) ? $_SERVER[$var] : (getenv($var) ?: $default); + } +} From a34810640ad1a5c82b27da88313dd272c6c76d8f Mon Sep 17 00:00:00 2001 From: Roman Shuplov Date: Tue, 27 Sep 2016 11:47:29 +0400 Subject: [PATCH 3/4] added full namespace in MongoDbTest for Class \OAuth2\Storage\MongoDB --- test/OAuth2/Storage/MongoDBTest.php | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/test/OAuth2/Storage/MongoDBTest.php b/test/OAuth2/Storage/MongoDBTest.php index 5d3acd2d3..8163bfe67 100644 --- a/test/OAuth2/Storage/MongoDBTest.php +++ b/test/OAuth2/Storage/MongoDBTest.php @@ -17,7 +17,7 @@ public function __construct() public function testSetClientDetails() { - $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + $db = new \OAuth2\Storage\MongoDB('mongodb://localhost:27017/oauth2_server_php'); // comment with Bootstrap::getInstance()->getMongoDB(); // $db->setClientDetails('oauth_test_client', 'testpass', 'redirect_uri', [], 'map green', 'oauth_test_user_id'); @@ -38,15 +38,15 @@ public function testSetClientDetails() public function testConnection() { - $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + $db = new \OAuth2\Storage\MongoDB('mongodb://localhost:27017/oauth2_server_php'); $this->assertNotFalse($db->getClientDetails('oauth_test_client')); - $db = new MongoDB(['host' => 'localhost', 'port' => '27017', 'database' => 'oauth2_server_php']); + $db = new \OAuth2\Storage\MongoDB(['host' => 'localhost', 'port' => '27017', 'database' => 'oauth2_server_php']); $this->assertNotFalse($db->getClientDetails('oauth_test_client')); } public function testIsPublicClient() { - $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + $db = new \OAuth2\Storage\MongoDB('mongodb://localhost:27017/oauth2_server_php'); $res = $db->isPublicClient('oauth_test_client'); $this->assertFalse($res); @@ -54,7 +54,7 @@ public function testIsPublicClient() public function testAccessToken() { - $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + $db = new \OAuth2\Storage\MongoDB('mongodb://localhost:27017/oauth2_server_php'); $this->assertNotFalse($db->getAccessToken('testtoken')); $db->setAccessToken('testtoken', 'Some Client!!!', 'oauth_test_user_id', 1); @@ -68,7 +68,7 @@ public function testAccessToken() public function testAuthorizationCode() { - $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + $db = new \OAuth2\Storage\MongoDB('mongodb://localhost:27017/oauth2_server_php'); $this->assertNotFalse($db->getAuthorizationCode('testcode')); $db->setAuthorizationCode('testcode', 'Some Client!!!', 'oauth_test_user_id', 'http://example.com', 0); @@ -81,7 +81,7 @@ public function testAuthorizationCode() public function testRefreshToken() { - $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + $db = new \OAuth2\Storage\MongoDB('mongodb://localhost:27017/oauth2_server_php'); $this->assertNotFalse($db->getRefreshToken('testrefreshtoken')); $db->setRefreshToken('testrefreshtoken', 'Some Client!!!', 'oauth_test_user_id', 0); @@ -94,20 +94,20 @@ public function testRefreshToken() public function testCheckUserCredentials() { - $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + $db = new \OAuth2\Storage\MongoDB('mongodb://localhost:27017/oauth2_server_php'); $this->assertTrue($db->checkUserCredentials('testuser', 'password')); } public function testGetUserDetails() { - $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + $db = new \OAuth2\Storage\MongoDB('mongodb://localhost:27017/oauth2_server_php'); $this->assertNotFalse($db->getUserDetails('testuser')); } public function testUser() { - $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + $db = new \OAuth2\Storage\MongoDB('mongodb://localhost:27017/oauth2_server_php'); $this->assertNotFalse($db->getUser('testuser')); $db->setUser('testuser', 'password123123', 'First Name', 'Last Name'); @@ -116,14 +116,14 @@ public function testUser() public function testGetClientKey() { - $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + $db = new \OAuth2\Storage\MongoDB('mongodb://localhost:27017/oauth2_server_php'); $this->assertNotFalse($db->getClientKey('oauth_test_client', 'test_subject')); } public function testGetClientScope() { - $db = new MongoDB('mongodb://localhost:27017/oauth2_server_php'); + $db = new \OAuth2\Storage\MongoDB('mongodb://localhost:27017/oauth2_server_php'); $this->assertStringMatchesFormat('%S', $db->getClientScope('oauth_test_client')); From 2e3c50f114ada0edb591bba4bc1c0ec443a4f668 Mon Sep 17 00:00:00 2001 From: Roman Shuplov Date: Tue, 27 Sep 2016 13:25:28 +0400 Subject: [PATCH 4/4] fixed using wrong object in test\lib\OAuth\Storage\Bootstrap --- src/OAuth2/Storage/MongoDB.php | 2 -- test/lib/OAuth2/Storage/Bootstrap.php | 27 ++++++++++++++------------- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/src/OAuth2/Storage/MongoDB.php b/src/OAuth2/Storage/MongoDB.php index d203d6eb6..b2df645c0 100644 --- a/src/OAuth2/Storage/MongoDB.php +++ b/src/OAuth2/Storage/MongoDB.php @@ -74,8 +74,6 @@ public function __construct($connection, $config = array()) throw new \InvalidArgumentException('First argument to OAuth2\Storage\MongoDB must be a string or a configuration array'); } - $this->db->selectServer($this->db->getReadPreference()); - $this->config = array_merge(array( 'client_table' => 'oauth_clients', 'access_token_table' => 'oauth_access_tokens', diff --git a/test/lib/OAuth2/Storage/Bootstrap.php b/test/lib/OAuth2/Storage/Bootstrap.php index 840143501..6a9601092 100755 --- a/test/lib/OAuth2/Storage/Bootstrap.php +++ b/test/lib/OAuth2/Storage/Bootstrap.php @@ -177,13 +177,14 @@ public function getMongoDB() $this->mongodb = new NullStorage('MongoDB', 'Skipping MongoDB tests'); } elseif (class_exists('\MongoDB\Driver\Manager')) { try { - $this->mongodb = new \MongoDB\Driver\Manager('mongodb://localhost:27017'); - $this->mongodb->selectServer($this->mongodb->getReadPreference()); + $mongodb = new \MongoDB\Driver\Manager('mongodb://localhost:27017'); + $mongodb->selectServer($mongodb->getReadPreference()); // checking servers + $this->removeMongoDB($mongodb); + $this->createMongoDB($mongodb); + $this->mongodb = new MongoDB('mongodb://localhost:27017'); } catch (\Exception $e) { $this->mongodb = new NullStorage('MongoDB', 'Unable to connect to MongoDB server on "localhost:27017"'); } - $this->removeMongoDB(); - $this->createMongoDB(); } else { $this->mongodb = new NullStorage('MongoDB', 'Missing MongoDB php extension. Please install mongodb.so'); } @@ -499,7 +500,7 @@ private function createMongo(\MongoDB $db) )); } - private function createMongoDB() + private function createMongoDB(\MongoDB\Driver\Manager $mongodb) { $bulk = new \MongoDB\Driver\BulkWrite(); $bulk->insert(array( @@ -516,7 +517,7 @@ private function createMongoDB() 'grant_types' => 'implicit password', 'scope' => 'clientscope3 clientscope4' )); - $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_clients', $bulk); + $mongodb->executeBulkWrite('oauth2_server_php.oauth_clients', $bulk); $bulk = new \MongoDB\Driver\BulkWrite(); $bulk->insert(array( @@ -527,7 +528,7 @@ private function createMongoDB() 'access_token' => "testtoken2", 'client_id' => "Some Client2" )); - $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_access_tokens', $bulk); + $mongodb->executeBulkWrite('oauth2_server_php.oauth_access_tokens', $bulk); $bulk = new \MongoDB\Driver\BulkWrite(); $bulk->insert(array( @@ -538,7 +539,7 @@ private function createMongoDB() 'authorization_code' => "testcode2", 'client_id' => "Some Client2" )); - $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_authorization_codes', $bulk); + $mongodb->executeBulkWrite('oauth2_server_php.oauth_authorization_codes', $bulk); $bulk = new \MongoDB\Driver\BulkWrite(); $bulk->insert(array( @@ -549,7 +550,7 @@ private function createMongoDB() 'refresh_token' => 'testrefreshtoken2', 'client_id' => 'Some Client2', )); - $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_refresh_tokens', $bulk); + $mongodb->executeBulkWrite('oauth2_server_php.oauth_refresh_tokens', $bulk); $bulk = new \MongoDB\Driver\BulkWrite(); $bulk->insert(array( @@ -564,7 +565,7 @@ private function createMongoDB() 'email' => 'testuser@test.com', 'email_verified' => true, )); - $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_users', $bulk); + $mongodb->executeBulkWrite('oauth2_server_php.oauth_users', $bulk); $bulk = new \MongoDB\Driver\BulkWrite(); $bulk->insert(array( @@ -577,7 +578,7 @@ private function createMongoDB() 'key' => $this->getTestPublicKey(), 'subject' => 'test_subject2', )); - $this->mongodb->executeBulkWrite('oauth2_server_php.oauth_jwt', $bulk); + $mongodb->executeBulkWrite('oauth2_server_php.oauth_jwt', $bulk); } private function createRedisDb(Redis $storage) @@ -610,10 +611,10 @@ public function removeMongo(\MongoDB $db) $db->drop(); } - public function removeMongoDB() + public function removeMongoDB(\MongoDB\Driver\Manager $mongodb) { $command = new \MongoDB\Driver\Command(array('dropDatabase' => 1)); - $this->mongodb->executeCommand('oauth2_server_php', $command); + $mongodb->executeCommand('oauth2_server_php', $command); } public function getTestPublicKey()