1
0
Fork 0
mirror of https://we.phorge.it/source/phorge.git synced 2024-09-19 16:58:48 +02:00

OAuth - Phabricator OAuth server and Phabricator client for new Phabricator OAuth Server

Summary:
adds a Phabricator OAuth server, which has three big commands:
 - auth - allows $user to authorize a given client or application.  if $user has already authorized, it hands an authoization code back to $redirect_uri
 - token - given a valid authorization code, this command returns an authorization token
 - whoami - Conduit.whoami, all nice and purdy relative to the oauth server.
Also has a "test" handler, which I used to create some test data.  T850 will
delete this as it adds the ability to create this data in the Phabricator
product.

This diff also adds the corresponding client in Phabricator for the Phabricator
OAuth Server.  (Note that clients are known as "providers" in the Phabricator
codebase but client makes more sense relative to the server nomenclature)

Also, related to make this work well
 - clean up the diagnostics page by variabilizing the provider-specific
information and extending the provider classes as appropriate.
 - augment Conduit.whoami for more full-featured OAuth support, at least where
the Phabricator client is concerned

What's missing here...   See T844, T848, T849, T850, and T852.

Test Plan:
- created a dummy client via the test handler.   setup development.conf to have
have proper variables for this dummy client.  went through authorization and
de-authorization flows
- viewed the diagnostics page for all known oauth providers and saw
provider-specific debugging information

Reviewers: epriestley

CC: aran, epriestley

Maniphest Tasks: T44, T797

Differential Revision: https://secure.phabricator.com/D1595
This commit is contained in:
Bob Trahan 2012-02-03 16:21:40 -08:00
parent 9748520b0e
commit 7a3f33b5c2
34 changed files with 1161 additions and 14 deletions

View file

@ -329,7 +329,7 @@ return array(
'account.minimum-password-length' => 8,
// -- Facebook ------------------------------------------------------------ //
// -- Facebook OAuth -------------------------------------------------------- //
// Can users use Facebook credentials to login to Phabricator?
'facebook.auth-enabled' => false,
@ -348,7 +348,7 @@ return array(
'facebook.application-secret' => null,
// -- GitHub ---------------------------------------------------------------- //
// -- GitHub OAuth ---------------------------------------------------------- //
// Can users use GitHub credentials to login to Phabricator?
'github.auth-enabled' => false,
@ -367,7 +367,7 @@ return array(
'github.application-secret' => null,
// -- Google ---------------------------------------------------------------- //
// -- Google OAuth ---------------------------------------------------------- //
// Can users use Google credentials to login to Phabricator?
'google.auth-enabled' => false,
@ -385,6 +385,30 @@ return array(
// The Google "Client Secret" to use for Google API access.
'google.application-secret' => null,
// -- Phabricator OAuth ----------------------------------------------------- //
// Meta-town -- Phabricator is itself an OAuth Provider
// TODO -- T887 -- make this support multiple Phabricator instances!
// The URI of the Phabricator instance to use as an OAuth server.
'phabricator.oauth-uri' => null,
// Can users use Phabricator credentials to login to Phabricator?
'phabricator.auth-enabled' => false,
// Can users use Phabricator credentials to create new Phabricator accounts?
'phabricator.registration-enabled' => true,
// Are Phabricator accounts permanently linked to Phabricator accounts, or can
// the user unlink them?
'phabricator.auth-permanent' => false,
// The Phabricator "Client ID" to use for Phabricator API access.
'phabricator.application-id' => null,
// The Phabricator "Client Secret" to use for Phabricator API access.
'phabricator.application-secret' => null,
// -- Recaptcha ------------------------------------------------------------- //
// Is Recaptcha enabled? If disabled, captchas will not appear. You should

View file

@ -8,4 +8,4 @@ CREATE TABLE phabricator_chatlog.chatlog_event (
message LONGBLOB NOT NULL,
loggedByPHID VARCHAR(64) BINARY NOT NULL,
KEY (channel, epoch)
);
);

View file

@ -0,0 +1,51 @@
CREATE DATABASE IF NOT EXISTS `phabricator_oauth_server`;
CREATE TABLE `phabricator_oauth_server`.`oauth_server_oauthserverclient` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`phid` varchar(64) BINARY NOT NULL,
`name` varchar(255) NOT NULL,
`secret` varchar(32) NOT NULL,
`redirectURI` varchar(255) NOT NULL,
`creatorPHID` varchar(64) BINARY NOT NULL,
`dateCreated` int(10) unsigned NOT NULL,
`dateModified` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `phid` (`phid`)
) ENGINE=InnoDB;
CREATE TABLE `phabricator_oauth_server`.`oauth_server_oauthclientauthorization` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`phid` varchar(64) BINARY NOT NULL,
`userPHID` varchar(64) BINARY NOT NULL,
`clientPHID` varchar(64) BINARY NOT NULL,
`dateCreated` int(10) unsigned NOT NULL,
`dateModified` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `phid` (`phid`),
UNIQUE KEY `userPHID` (`userPHID`,`clientPHID`)
) ENGINE=InnoDB;
CREATE TABLE `phabricator_oauth_server`.`oauth_server_oauthserverauthorizationcode` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`code` varchar(32) NOT NULL,
`clientPHID` varchar(64) BINARY NOT NULL,
`clientSecret` varchar(32) NOT NULL,
`userPHID` varchar(64) BINARY NOT NULL,
`dateCreated` int(10) unsigned NOT NULL,
`dateModified` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code` (`code`)
) ENGINE=InnoDB;
CREATE TABLE `phabricator_oauth_server`.`oauth_server_oauthserveraccesstoken` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`token` varchar(32) NOT NULL,
`userPHID` varchar(64) BINARY NOT NULL,
`clientPHID` varchar(64) BINARY NOT NULL,
`dateExpires` int(10) unsigned NOT NULL,
`dateCreated` int(10) unsigned NOT NULL,
`dateModified` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `token` (`token`)
) ENGINE=InnoDB;

View file

@ -597,6 +597,7 @@ phutil_register_library_map(array(
'PhabricatorMetaMTASendGridReceiveController' => 'applications/metamta/controller/sendgridreceive',
'PhabricatorMetaMTAViewController' => 'applications/metamta/controller/view',
'PhabricatorMySQLFileStorageEngine' => 'applications/files/engine/mysql',
'PhabricatorOAuthClientAuthorization' => 'applications/oauthserver/storage/clientauthorization',
'PhabricatorOAuthDefaultRegistrationController' => 'applications/auth/controller/oauthregistration/default',
'PhabricatorOAuthDiagnosticsController' => 'applications/auth/controller/oauthdiagnostics',
'PhabricatorOAuthFailureView' => 'applications/auth/view/oauthfailure',
@ -605,7 +606,17 @@ phutil_register_library_map(array(
'PhabricatorOAuthProviderFacebook' => 'applications/auth/oauth/provider/facebook',
'PhabricatorOAuthProviderGitHub' => 'applications/auth/oauth/provider/github',
'PhabricatorOAuthProviderGoogle' => 'applications/auth/oauth/provider/google',
'PhabricatorOAuthProviderPhabricator' => 'applications/auth/oauth/provider/phabricator',
'PhabricatorOAuthRegistrationController' => 'applications/auth/controller/oauthregistration/base',
'PhabricatorOAuthResponse' => 'applications/oauthserver/response',
'PhabricatorOAuthServer' => 'applications/oauthserver/server',
'PhabricatorOAuthServerAccessToken' => 'applications/oauthserver/storage/accesstoken',
'PhabricatorOAuthServerAuthController' => 'applications/oauthserver/controller/auth',
'PhabricatorOAuthServerAuthorizationCode' => 'applications/oauthserver/storage/authorizationcode',
'PhabricatorOAuthServerClient' => 'applications/oauthserver/storage/client',
'PhabricatorOAuthServerDAO' => 'applications/oauthserver/storage/base',
'PhabricatorOAuthServerTestController' => 'applications/oauthserver/controller/test',
'PhabricatorOAuthServerTokenController' => 'applications/oauthserver/controller/token',
'PhabricatorOAuthUnlinkController' => 'applications/auth/controller/unlink',
'PhabricatorObjectAttachmentEditor' => 'applications/search/editor/attach',
'PhabricatorObjectGraph' => 'applications/phid/graph',
@ -1324,6 +1335,7 @@ phutil_register_library_map(array(
'PhabricatorMetaMTASendGridReceiveController' => 'PhabricatorMetaMTAController',
'PhabricatorMetaMTAViewController' => 'PhabricatorMetaMTAController',
'PhabricatorMySQLFileStorageEngine' => 'PhabricatorFileStorageEngine',
'PhabricatorOAuthClientAuthorization' => 'PhabricatorOAuthServerDAO',
'PhabricatorOAuthDefaultRegistrationController' => 'PhabricatorOAuthRegistrationController',
'PhabricatorOAuthDiagnosticsController' => 'PhabricatorAuthController',
'PhabricatorOAuthFailureView' => 'AphrontView',
@ -1331,7 +1343,16 @@ phutil_register_library_map(array(
'PhabricatorOAuthProviderFacebook' => 'PhabricatorOAuthProvider',
'PhabricatorOAuthProviderGitHub' => 'PhabricatorOAuthProvider',
'PhabricatorOAuthProviderGoogle' => 'PhabricatorOAuthProvider',
'PhabricatorOAuthProviderPhabricator' => 'PhabricatorOAuthProvider',
'PhabricatorOAuthRegistrationController' => 'PhabricatorAuthController',
'PhabricatorOAuthResponse' => 'AphrontResponse',
'PhabricatorOAuthServerAccessToken' => 'PhabricatorOAuthServerDAO',
'PhabricatorOAuthServerAuthController' => 'PhabricatorAuthController',
'PhabricatorOAuthServerAuthorizationCode' => 'PhabricatorOAuthServerDAO',
'PhabricatorOAuthServerClient' => 'PhabricatorOAuthServerDAO',
'PhabricatorOAuthServerDAO' => 'PhabricatorLiskDAO',
'PhabricatorOAuthServerTestController' => 'PhabricatorAuthController',
'PhabricatorOAuthServerTokenController' => 'PhabricatorAuthController',
'PhabricatorOAuthUnlinkController' => 'PhabricatorAuthController',
'PhabricatorObjectGraph' => 'AbstractDirectedGraph',
'PhabricatorObjectHandleStatus' => 'PhabricatorObjectHandleConstants',

View file

@ -151,6 +151,12 @@ class AphrontDefaultApplicationConfiguration
),
),
'/oauthserver/' => array(
'auth/' => 'PhabricatorOAuthServerAuthController',
'token/' => 'PhabricatorOAuthServerTokenController',
'test/' => 'PhabricatorOAuthServerTestController',
),
'/xhprof/' => array(
'profile/(?P<phid>[^/]+)/$' => 'PhabricatorXHProfProfileController',
),

View file

@ -35,9 +35,8 @@ final class AphrontAjaxResponse extends AphrontResponse {
$this->content,
$this->error);
return $this->encodeJSONForHTTPResponse(
$object,
$use_javelin_shield = true);
$response_json = $this->encodeJSONForHTTPResponse($object);
return $this->addJSONShield($response_json, $use_javelin_shield = true);
}
public function getHeaders() {

View file

@ -84,6 +84,11 @@ abstract class AphrontResponse {
array('\u003c', '\u003e'),
$response);
return $response;
}
protected function addJSONShield($json_response, $use_javelin_shield) {
// Add a shield to prevent "JSON Hijacking" attacks where an attacker
// requests a JSON response using a normal <script /> tag and then uses
// Object.prototype.__defineSetter__() or similar to read response data.
@ -96,7 +101,7 @@ abstract class AphrontResponse {
? 'for (;;);'
: 'for(;;);';
$response = $shield.$response;
$response = $shield.$json_response;
return $response;
}

View file

@ -29,10 +29,8 @@ final class AphrontJSONResponse extends AphrontResponse {
}
public function buildResponseString() {
$response = $this->encodeJSONForHTTPResponse(
$this->content,
$use_javelin_shield = false);
return $response;
$response = $this->encodeJSONForHTTPResponse($this->content);
return $this->addJSONShield($response, $use_javelin_shield = false);
}
public function getHeaders() {

View file

@ -21,6 +21,7 @@ abstract class PhabricatorOAuthProvider {
const PROVIDER_FACEBOOK = 'facebook';
const PROVIDER_GITHUB = 'github';
const PROVIDER_GOOGLE = 'google';
const PROVIDER_PHABRICATOR = 'phabricator';
private $accessToken;
@ -108,6 +109,9 @@ abstract class PhabricatorOAuthProvider {
case self::PROVIDER_GOOGLE:
$class = 'PhabricatorOAuthProviderGoogle';
break;
case self::PROVIDER_PHABRICATOR:
$class = 'PhabricatorOAuthProviderPhabricator';
break;
default:
throw new Exception('Unknown OAuth provider.');
}
@ -120,6 +124,7 @@ abstract class PhabricatorOAuthProvider {
self::PROVIDER_FACEBOOK,
self::PROVIDER_GITHUB,
self::PROVIDER_GOOGLE,
self::PROVIDER_PHABRICATOR,
);
$providers = array();
foreach ($all as $provider) {

View file

@ -0,0 +1,127 @@
<?php
/*
* Copyright 2012 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
final class PhabricatorOAuthProviderPhabricator
extends PhabricatorOAuthProvider {
private $userData;
public function decodeTokenResponse($response) {
$decoded = json_decode($response, true);
if (!is_array($decoded)) {
throw new Exception('Invalid token response.');
}
return $decoded;
}
public function getProviderKey() {
return self::PROVIDER_PHABRICATOR;
}
public function getProviderName() {
return 'Phabricator';
}
public function isProviderEnabled() {
return PhabricatorEnv::getEnvConfig('phabricator.auth-enabled');
}
public function isProviderLinkPermanent() {
return PhabricatorEnv::getEnvConfig('phabricator.auth-permanent');
}
public function isProviderRegistrationEnabled() {
return PhabricatorEnv::getEnvConfig('phabricator.registration-enabled');
}
public function getClientID() {
return PhabricatorEnv::getEnvConfig('phabricator.application-id');
}
public function renderGetClientIDHelp() {
return null;
}
public function getClientSecret() {
return PhabricatorEnv::getEnvConfig('phabricator.application-secret');
}
public function renderGetClientSecretHelp() {
return null;
}
public function getAuthURI() {
return $this->getURI('/oauthserver/auth/');
}
public function getTestURIs() {
return array(
$this->getURI('/'),
$this->getURI('/api/user.whoami/')
);
}
public function getTokenURI() {
return $this->getURI('/oauthserver/token/');
}
public function getUserInfoURI() {
return $this->getURI('/api/user.whoami/');
}
public function getMinimumScope() {
return 'email';
}
public function setUserData($data) {
$data = json_decode($data, true);
$this->userData = $data['result'];
return $this;
}
public function retrieveUserID() {
return $this->userData['phid'];
}
public function retrieveUserEmail() {
return $this->userData['email'];
}
public function retrieveUserAccountName() {
return $this->userData['userName'];
}
public function retrieveUserProfileImage() {
$uri = $this->userData['image'];
return @file_get_contents($uri);
}
public function retrieveUserAccountURI() {
return $this->userData['uri'];
}
public function retrieveUserRealName() {
return $this->userData['realName'];
}
private function getURI($path) {
return
rtrim(PhabricatorEnv::getEnvConfig('phabricator.oauth-uri'), '/') .
$path;
}
}

View file

@ -0,0 +1,13 @@
<?php
/**
* This file is automatically generated. Lint this module to rebuild it.
* @generated
*/
phutil_require_module('phabricator', 'applications/auth/oauth/provider/base');
phutil_require_module('phabricator', 'infrastructure/env');
phutil_require_source('PhabricatorOAuthProviderPhabricator.php');

View file

@ -1,7 +1,7 @@
<?php
/*
* Copyright 2011 Facebook, Inc.
* Copyright 2012 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -22,10 +22,21 @@
abstract class ConduitAPI_user_Method extends ConduitAPIMethod {
protected function buildUserInformationDictionary(PhabricatorUser $user) {
$src_phid = $user->getProfileImagePHID();
$file = id(new PhabricatorFile())->loadOneWhere('phid = %s', $src_phid);
if ($file) {
$picture = $file->getBestURI();
} else {
$picture = null;
}
return array(
'phid' => $user->getPHID(),
'userName' => $user->getUserName(),
'realName' => $user->getRealName(),
'email' => $user->getEmail(),
'image' => $picture,
'uri' => PhabricatorEnv::getURI('/p/'.$user->getUsername().'/'),
);
}

View file

@ -7,6 +7,10 @@
phutil_require_module('phabricator', 'applications/conduit/method/base');
phutil_require_module('phabricator', 'applications/files/storage/file');
phutil_require_module('phabricator', 'infrastructure/env');
phutil_require_module('phutil', 'utils');
phutil_require_source('ConduitAPI_user_Method.php');

View file

@ -0,0 +1,130 @@
<?php
/*
* Copyright 2012 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @group oauthserver
*/
final class PhabricatorOAuthServerAuthController
extends PhabricatorAuthController {
public function shouldRequireLogin() {
return true;
}
public function processRequest() {
$request = $this->getRequest();
$current_user = $request->getUser();
$server = new PhabricatorOAuthServer($current_user);
$client_phid = $request->getStr('client_id');
$scope = $request->getStr('scope');
$redirect_uri = $request->getStr('redirect_uri');
$response = new PhabricatorOAuthResponse();
$errors = array();
if (!$client_phid) {
return $response->setMalformed(
'Required parameter client_id not specified.'
);
}
$client = id(new PhabricatorOAuthServerClient())
->loadOneWhere('phid = %s', $client_phid);
if (!$client) {
return $response->setNotFound(
'Client with id '.$client_phid.' not found. '
);
}
if ($server->userHasAuthorizedClient($client)) {
$return_auth_code = true;
$unguarded_write = AphrontWriteGuard::beginScopedUnguardedWrites();
} else if ($request->isFormPost()) {
$server->authorizeClient($client);
$return_auth_code = true;
$unguarded_write = null;
} else {
$return_auth_code = false;
$unguarded_write = null;
}
if ($return_auth_code) {
// step 1 -- generate authorization code
$auth_code =
$server->generateAuthorizationCode($client);
// step 2 -- error or return it
if (!$auth_code) {
$errors[] = 'Failed to generate an authorization code. '.
'Try again.';
} else {
$client_uri = new PhutilURI($client->getRedirectURI());
if (!$redirect_uri) {
$uri = $client_uri;
} else {
$redirect_uri = new PhutilURI($redirect_uri);
if ($redirect_uri->getDomain() !=
$client_uri->getDomain()) {
$uri = $client_uri;
} else {
$uri = $redirect_uri;
}
}
$uri->setQueryParam('code', $auth_code->getCode());
return $response->setRedirect($uri);
}
}
unset($unguarded_write);
$error_view = null;
if ($errors) {
$error_view = new AphrontErrorView();
$error_view->setTitle('Authorization Code Errors');
$error_view->setErrors($errors);
}
$name = phutil_escape_html($client->getName());
$title = 'Authorize ' . $name . '?';
$panel = new AphrontPanelView();
$panel->setWidth(AphrontPanelView::WIDTH_FORM);
$panel->setHeader($title);
// TODO -- T848 (add scope to Phabricator OAuth)
// generally inform user what this means as this fleshes out
$description =
"Do want to authorize {$name} to access your ".
"Phabricator account data?";
$form = id(new AphrontFormView())
->setUser($current_user)
->appendChild(
id(new AphrontFormStaticControl())
->setValue($description))
->appendChild(
id(new AphrontFormSubmitControl())
->setValue('Authorize')
->addCancelButton('/'));
// TODO -- T889 (make "cancel" do something more sensible)
$panel->appendChild($form);
return $this->buildStandardPageResponse(
array($error_view,
$panel),
array('title' => $title));
}
}

View file

@ -0,0 +1,25 @@
<?php
/**
* This file is automatically generated. Lint this module to rebuild it.
* @generated
*/
phutil_require_module('phabricator', 'aphront/writeguard');
phutil_require_module('phabricator', 'applications/auth/controller/base');
phutil_require_module('phabricator', 'applications/oauthserver/response');
phutil_require_module('phabricator', 'applications/oauthserver/server');
phutil_require_module('phabricator', 'applications/oauthserver/storage/client');
phutil_require_module('phabricator', 'view/form/base');
phutil_require_module('phabricator', 'view/form/control/static');
phutil_require_module('phabricator', 'view/form/control/submit');
phutil_require_module('phabricator', 'view/form/error');
phutil_require_module('phabricator', 'view/layout/panel');
phutil_require_module('phutil', 'markup');
phutil_require_module('phutil', 'parser/uri');
phutil_require_module('phutil', 'utils');
phutil_require_source('PhabricatorOAuthServerAuthController.php');

View file

@ -0,0 +1,88 @@
<?php
/*
* Copyright 2012 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @group oauthserver
*/
final class PhabricatorOAuthServerTestController
extends PhabricatorAuthController {
public function shouldRequireLogin() {
return true;
}
public function shouldRequireAdmin() {
return true;
}
public function processRequest() {
$request = $this->getRequest();
$current_user = $request->getUser();
$server = new PhabricatorOAuthServer($current_user);
$forms = array();
$form = id(new AphrontFormView())
->setUser($current_user)
->appendChild(
id(new AphrontFormStaticControl())
->setValue('Create Test Client'))
->appendChild(
id(new AphrontFormTextControl())
->setLabel('Name')
->setName('name')
->setValue(''))
->appendChild(
id(new AphrontFormTextControl())
->setLabel('Redirect URI')
->setName('redirect_uri')
->setValue(''))
->appendChild(
id(new AphrontFormSubmitControl())
->setValue('Create Client'));
$forms[] = $form;
$result = array();
if ($request->isFormPost()) {
$name = $request->getStr('name');
$redirect_uri = $request->getStr('redirect_uri');
$secret = Filesystem::readRandomCharacters(32);
$client = new PhabricatorOAuthServerClient();
$client->setName($name);
$client->setSecret($secret);
$client->setCreatorPHID($current_user->getPHID());
$client->setRedirectURI($redirect_uri);
$client->save();
$id = $client->getID();
$phid = $client->getPHID();
$name = phutil_escape_html($name);
$results = array();
$results[] = "New client named {$name} with secret {$secret}.";
$results[] = "Client has id {$id} and phid {$phid}.";
$result = implode('<br />', $results);
}
$title = 'Test OAuthServer Stuff';
$panel = new AphrontPanelView();
$panel->setWidth(AphrontPanelView::WIDTH_FORM);
$panel->setHeader($title);
$panel->appendChild($result);
$panel->appendChild($forms);
return $this->buildStandardPageResponse(
$panel,
array('title' => $title));
}
}

View file

@ -0,0 +1,23 @@
<?php
/**
* This file is automatically generated. Lint this module to rebuild it.
* @generated
*/
phutil_require_module('phabricator', 'applications/auth/controller/base');
phutil_require_module('phabricator', 'applications/oauthserver/server');
phutil_require_module('phabricator', 'applications/oauthserver/storage/client');
phutil_require_module('phabricator', 'view/form/base');
phutil_require_module('phabricator', 'view/form/control/static');
phutil_require_module('phabricator', 'view/form/control/submit');
phutil_require_module('phabricator', 'view/form/control/text');
phutil_require_module('phabricator', 'view/layout/panel');
phutil_require_module('phutil', 'filesystem');
phutil_require_module('phutil', 'markup');
phutil_require_module('phutil', 'utils');
phutil_require_source('PhabricatorOAuthServerTestController.php');

View file

@ -0,0 +1,90 @@
<?php
/*
* Copyright 2012 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @group oauthserver
*/
final class PhabricatorOAuthServerTokenController
extends PhabricatorAuthController {
public function shouldRequireLogin() {
return false;
}
public function processRequest() {
$request = $this->getRequest();
$code = $request->getStr('code');
$client_phid = $request->getStr('client_id');
$client_secret = $request->getStr('client_secret');
$response = new PhabricatorOAuthResponse();
if (!$code) {
return $response->setMalformed(
'Required parameter code missing.'
);
}
if (!$client_phid) {
return $response->setMalformed(
'Required parameter client_id missing.'
);
}
if (!$client_secret) {
return $response->setMalformed(
'Required parameter client_secret missing.'
);
}
$auth_code = id(new PhabricatorOAuthServerAuthorizationCode())
->loadOneWhere('code = %s', $code);
if (!$auth_code) {
return $response->setNotFound(
'Authorization code '.$code.' not found.'
);
}
$user = id(new PhabricatorUser())
->loadOneWhere('phid = %s', $auth_code->getUserPHID());
$server = new PhabricatorOAuthServer($user);
$test_code = new PhabricatorOAuthServerAuthorizationCode();
$test_code->setClientSecret($client_secret);
$test_code->setClientPHID($client_phid);
$is_good_code = $server->validateAuthorizationCode($auth_code,
$test_code);
if (!$is_good_code) {
return $response->setMalformed(
'Invalid authorization code '.$code.'.'
);
}
$client = id(new PhabricatorOAuthServerClient())
->loadOneWhere('phid = %s', $client_phid);
if (!$client) {
return $response->setNotFound(
'Client with client_id '.$client_phid.' not found.'
);
}
$scope = AphrontWriteGuard::beginScopedUnguardedWrites();
$access_token = $server->generateAccessToken($client);
if ($access_token) {
$auth_code->delete();
$result = array('access_token' => $access_token->getToken());
return $response->setContent($result);
}
return $response->setMalformed('Request is malformed in some way.');
}
}

View file

@ -0,0 +1,20 @@
<?php
/**
* This file is automatically generated. Lint this module to rebuild it.
* @generated
*/
phutil_require_module('phabricator', 'aphront/writeguard');
phutil_require_module('phabricator', 'applications/auth/controller/base');
phutil_require_module('phabricator', 'applications/oauthserver/response');
phutil_require_module('phabricator', 'applications/oauthserver/server');
phutil_require_module('phabricator', 'applications/oauthserver/storage/authorizationcode');
phutil_require_module('phabricator', 'applications/oauthserver/storage/client');
phutil_require_module('phabricator', 'applications/people/storage/user');
phutil_require_module('phutil', 'utils');
phutil_require_source('PhabricatorOAuthServerTokenController.php');

View file

@ -0,0 +1,93 @@
<?php
/*
* Copyright 2012 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @group oauthserver
*/
final class PhabricatorOAuthResponse extends AphrontResponse {
private $content;
private $uri;
public function setContent($content) {
$this->content = $content;
return $this;
}
private function getContent() {
return $this->content;
}
private function setURI($uri) {
$this->uri = $uri;
return $this;
}
private function getURI() {
return $this->uri;
}
public function setMalformed($malformed) {
if ($malformed) {
$this->setHTTPResponseCode(400);
$this->setContent(array('error' => $malformed));
}
return $this;
}
public function setNotFound($not_found) {
if ($not_found) {
$this->setHTTPResponseCode(404);
$this->setContent(array('error' => $not_found));
}
return $this;
}
public function setRedirect(PhutilURI $uri) {
if ($uri) {
$this->setHTTPResponseCode(302);
$this->setURI($uri);
$this->setContent(null);
}
return $this;
}
public function __construct() {
$this->setHTTPResponseCode(200);
return $this;
}
public function getHeaders() {
$headers = array(
array('Content-Type', 'application/json'),
);
if ($this->getURI()) {
$headers[] = array('Location', $this->getURI());
}
// TODO -- T844 set headers with X-Auth-Scopes, etc
$headers = array_merge(parent::getHeaders(), $headers);
return $headers;
}
public function buildResponseString() {
$content = $this->getContent();
if ($content) {
return $this->encodeJSONForHTTPResponse($content);
}
return '';
}
}

View file

@ -0,0 +1,12 @@
<?php
/**
* This file is automatically generated. Lint this module to rebuild it.
* @generated
*/
phutil_require_module('phabricator', 'aphront/response/base');
phutil_require_source('PhabricatorOAuthResponse.php');

View file

@ -0,0 +1,151 @@
<?php
/*
* Copyright 2012 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Implements core OAuth 2.0 Server logic.
*
* This class should be used behind business logic that parses input to
* determine pertinent @{class:PhabricatorUser} $user,
* @{class:PhabricatorOAuthServerClient} $client(s),
* @{class:PhabricatorOAuthServerAuthorizationCode} $code(s), and.
* @{class:PhabricatorOAuthServerAccessToken} $token(s).
*
* For an OAuth 2.0 server, there are two main steps:
*
* 1) Authorization - the user authorizes a given client to access the data
* the OAuth 2.0 server protects. Once this is achieved / if it has
* been achived already, the OAuth server sends the client an authorization
* code.
* 2) Access Token - the client should send the authorization code received in
* step 1 along with its id and secret to the OAuth server to receive an
* access token. This access token can later be used to access Phabricator
* data on behalf of the user.
*
* @task auth Authorizing @{class:PhabricatorOAuthServerClient}s and
* generating @{class:PhabricatorOAuthServerAuthorizationCode}s
* @task token Validating @{class:PhabricatorOAuthServerAuthorizationCode}s
* and generating @{class:PhabricatorOAuthServerAccessToken}s
* @task internal Internals
*
* @group oauthserver
*/
final class PhabricatorOAuthServer {
const AUTHORIZATION_CODE_TIMEOUT = 300;
private $user;
/**
* @group internal
*/
private function getUser() {
return $this->user;
}
public function __construct(PhabricatorUser $user) {
if (!$user) {
throw new Exception('Must specify a Phabricator $user to constructor!');
}
$this->user = $user;
}
/**
* @task auth
*/
public function userHasAuthorizedClient(
PhabricatorOAuthServerClient $client) {
$authorization = id(new PhabricatorOAuthClientAuthorization())->
loadOneWhere('userPHID = %s AND clientPHID = %s',
$this->getUser()->getPHID(),
$client->getPHID());
if (empty($authorization)) {
return false;
}
return true;
}
/**
* @task auth
*/
public function authorizeClient(PhabricatorOAuthServerClient $client) {
$authorization = new PhabricatorOAuthClientAuthorization();
$authorization->setUserPHID($this->getUser()->getPHID());
$authorization->setClientPHID($client->getPHID());
$authorization->save();
}
/**
* @task auth
*/
public function generateAuthorizationCode(
PhabricatorOAuthServerClient $client) {
$code = Filesystem::readRandomCharacters(32);
$authorization_code = new PhabricatorOAuthServerAuthorizationCode();
$authorization_code->setCode($code);
$authorization_code->setClientPHID($client->getPHID());
$authorization_code->setClientSecret($client->getSecret());
$authorization_code->setUserPHID($this->getUser()->getPHID());
$authorization_code->save();
return $authorization_code;
}
/**
* @task token
*/
public function generateAccessToken(PhabricatorOAuthServerClient $client) {
$token = Filesystem::readRandomCharacters(32);
$access_token = new PhabricatorOAuthServerAccessToken();
$access_token->setToken($token);
$access_token->setUserPHID($this->getUser()->getPHID());
$access_token->setClientPHID($client->getPHID());
$access_token->setDateExpires(0);
$access_token->save();
return $access_token;
}
/**
* @task token
*/
public function validateAuthorizationCode(
PhabricatorOAuthServerAuthorizationCode $test_code,
PhabricatorOAuthServerAuthorizationCode $valid_code) {
// check that all the meta data matches
if ($test_code->getClientPHID() != $valid_code->getClientPHID()) {
return false;
}
if ($test_code->getClientSecret() != $valid_code->getClientSecret()) {
return false;
}
// check that the authorization code hasn't timed out
$created_time = $test_code->getDateCreated();
$must_be_used_by = $created_time + self::AUTHORIZATION_CODE_TIMEOUT;
return (time() < $must_be_used_by);
}
}

View file

@ -0,0 +1,17 @@
<?php
/**
* This file is automatically generated. Lint this module to rebuild it.
* @generated
*/
phutil_require_module('phabricator', 'applications/oauthserver/storage/accesstoken');
phutil_require_module('phabricator', 'applications/oauthserver/storage/authorizationcode');
phutil_require_module('phabricator', 'applications/oauthserver/storage/clientauthorization');
phutil_require_module('phutil', 'filesystem');
phutil_require_module('phutil', 'utils');
phutil_require_source('PhabricatorOAuthServer.php');

View file

@ -0,0 +1,29 @@
<?php
/*
* Copyright 2012 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @group oauthserver
*/
final class PhabricatorOAuthServerAccessToken
extends PhabricatorOAuthServerDAO {
protected $id;
protected $token;
protected $userPHID;
protected $clientPHID;
protected $dateExpires;
}

View file

@ -0,0 +1,12 @@
<?php
/**
* This file is automatically generated. Lint this module to rebuild it.
* @generated
*/
phutil_require_module('phabricator', 'applications/oauthserver/storage/base');
phutil_require_source('PhabricatorOAuthServerAccessToken.php');

View file

@ -0,0 +1,30 @@
<?php
/*
* Copyright 2012 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @group oauthserver
*/
final class PhabricatorOAuthServerAuthorizationCode
extends PhabricatorOAuthServerDAO {
protected $id;
protected $code;
protected $clientPHID;
protected $clientSecret;
protected $userPHID;
}

View file

@ -0,0 +1,12 @@
<?php
/**
* This file is automatically generated. Lint this module to rebuild it.
* @generated
*/
phutil_require_module('phabricator', 'applications/oauthserver/storage/base');
phutil_require_source('PhabricatorOAuthServerAuthorizationCode.php');

View file

@ -0,0 +1,26 @@
<?php
/*
* Copyright 2012 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @group oauthserver
*/
abstract class PhabricatorOAuthServerDAO extends PhabricatorLiskDAO {
public function getApplicationName() {
return 'oauth_server';
}
}

View file

@ -0,0 +1,12 @@
<?php
/**
* This file is automatically generated. Lint this module to rebuild it.
* @generated
*/
phutil_require_module('phabricator', 'applications/base/storage/lisk');
phutil_require_source('PhabricatorOAuthServerDAO.php');

View file

@ -0,0 +1,43 @@
<?php
/*
* Copyright 2012 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @group oauthserver
*/
final class PhabricatorOAuthServerClient
extends PhabricatorOAuthServerDAO {
protected $id;
protected $phid;
protected $secret;
protected $name;
protected $redirectURI;
protected $creatorPHID;
public function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(
PhabricatorPHIDConstants::PHID_TYPE_OASC);
}
}

View file

@ -0,0 +1,14 @@
<?php
/**
* This file is automatically generated. Lint this module to rebuild it.
* @generated
*/
phutil_require_module('phabricator', 'applications/oauthserver/storage/base');
phutil_require_module('phabricator', 'applications/phid/constants');
phutil_require_module('phabricator', 'applications/phid/storage/phid');
phutil_require_source('PhabricatorOAuthServerClient.php');

View file

@ -0,0 +1,41 @@
<?php
/*
* Copyright 2012 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @group oauthserver
*/
final class PhabricatorOAuthClientAuthorization
extends PhabricatorOAuthServerDAO {
protected $id;
protected $phid;
protected $userPHID;
protected $clientPHID;
public function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(
PhabricatorPHIDConstants::PHID_TYPE_OASA);
}
}

View file

@ -0,0 +1,14 @@
<?php
/**
* This file is automatically generated. Lint this module to rebuild it.
* @generated
*/
phutil_require_module('phabricator', 'applications/oauthserver/storage/base');
phutil_require_module('phabricator', 'applications/phid/constants');
phutil_require_module('phabricator', 'applications/phid/storage/phid');
phutil_require_source('PhabricatorOAuthClientAuthorization.php');

View file

@ -37,5 +37,6 @@ final class PhabricatorPHIDConstants {
const PHID_TYPE_ACMT = 'ACMT';
const PHID_TYPE_DRYR = 'DRYR';
const PHID_TYPE_DRYL = 'DRYL';
const PHID_TYPE_OASC = 'OASC';
const PHID_TYPE_OASA = 'OASA';
}