repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/exception/PhabricatorAuthInviteDialogException.php
src/applications/auth/exception/PhabricatorAuthInviteDialogException.php
<?php abstract class PhabricatorAuthInviteDialogException extends PhabricatorAuthInviteException { private $title; private $body; private $submitButtonText; private $submitButtonURI; private $cancelButtonText; private $cancelButtonURI; public function __construct($title, $body) { $this->title = $title; $this->body = $body; parent::__construct(pht('%s: %s', $title, $body)); } public function getTitle() { return $this->title; } public function getBody() { return $this->body; } public function setSubmitButtonText($submit_button_text) { $this->submitButtonText = $submit_button_text; return $this; } public function getSubmitButtonText() { return $this->submitButtonText; } public function setSubmitButtonURI($submit_button_uri) { $this->submitButtonURI = $submit_button_uri; return $this; } public function getSubmitButtonURI() { return $this->submitButtonURI; } public function setCancelButtonText($cancel_button_text) { $this->cancelButtonText = $cancel_button_text; return $this; } public function getCancelButtonText() { return $this->cancelButtonText; } public function setCancelButtonURI($cancel_button_uri) { $this->cancelButtonURI = $cancel_button_uri; return $this; } public function getCancelButtonURI() { return $this->cancelButtonURI; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/exception/PhutilAuthException.php
src/applications/auth/exception/PhutilAuthException.php
<?php /** * Abstract exception class for errors encountered during authentication * workflows. */ abstract class PhutilAuthException extends Exception {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/exception/PhabricatorAuthHighSecurityRequiredException.php
src/applications/auth/exception/PhabricatorAuthHighSecurityRequiredException.php
<?php final class PhabricatorAuthHighSecurityRequiredException extends Exception { private $cancelURI; private $factors; private $factorValidationResults; private $isSessionUpgrade; public function setFactorValidationResults(array $results) { assert_instances_of($results, 'PhabricatorAuthFactorResult'); $this->factorValidationResults = $results; return $this; } public function getFactorValidationResults() { return $this->factorValidationResults; } public function setFactors(array $factors) { assert_instances_of($factors, 'PhabricatorAuthFactorConfig'); $this->factors = $factors; return $this; } public function getFactors() { return $this->factors; } public function setCancelURI($cancel_uri) { $this->cancelURI = $cancel_uri; return $this; } public function getCancelURI() { return $this->cancelURI; } public function setIsSessionUpgrade($is_upgrade) { $this->isSessionUpgrade = $is_upgrade; return $this; } public function getIsSessionUpgrade() { return $this->isSessionUpgrade; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/exception/PhutilAuthUserAbortedException.php
src/applications/auth/exception/PhutilAuthUserAbortedException.php
<?php /** * The user aborted the authentication workflow, by clicking "Cancel" or "Deny" * or taking some similar action. * * For example, in OAuth/OAuth2 workflows, the authentication provider * generally presents the user with a confirmation dialog with two options, * "Approve" and "Deny". * * If an adapter detects that the user has explicitly bailed out of the * workflow, it should throw this exception. */ final class PhutilAuthUserAbortedException extends PhutilAuthException {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/exception/PhabricatorAuthInviteInvalidException.php
src/applications/auth/exception/PhabricatorAuthInviteInvalidException.php
<?php /** * Exception raised when an invite code is invalid. */ final class PhabricatorAuthInviteInvalidException extends PhabricatorAuthInviteDialogException {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/exception/PhabricatorAuthInviteRegisteredException.php
src/applications/auth/exception/PhabricatorAuthInviteRegisteredException.php
<?php /** * Exception raised when the user is already registered and the invite is a * no-op. */ final class PhabricatorAuthInviteRegisteredException extends PhabricatorAuthInviteException {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/exception/PhabricatorAuthInviteVerifyException.php
src/applications/auth/exception/PhabricatorAuthInviteVerifyException.php
<?php /** * Exception raised when the user needs to verify an action. */ final class PhabricatorAuthInviteVerifyException extends PhabricatorAuthInviteDialogException {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/exception/PhutilAuthConfigurationException.php
src/applications/auth/exception/PhutilAuthConfigurationException.php
<?php /** * Authentication is not configured correctly. */ final class PhutilAuthConfigurationException extends PhutilAuthException {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/exception/PhabricatorAuthInviteException.php
src/applications/auth/exception/PhabricatorAuthInviteException.php
<?php abstract class PhabricatorAuthInviteException extends Exception {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/exception/PhabricatorAuthInviteAccountException.php
src/applications/auth/exception/PhabricatorAuthInviteAccountException.php
<?php /** * Exception raised when the user is logged in to the wrong account. */ final class PhabricatorAuthInviteAccountException extends PhabricatorAuthInviteDialogException {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/exception/PhabricatorAuthInviteLoginException.php
src/applications/auth/exception/PhabricatorAuthInviteLoginException.php
<?php /** * Exception raised when the user must log in to continue with the invite * workflow (for example, the because the email address is already bound to an * account). */ final class PhabricatorAuthInviteLoginException extends PhabricatorAuthInviteDialogException {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/exception/privatekey/PhabricatorAuthSSHPrivateKeyPassphraseException.php
src/applications/auth/exception/privatekey/PhabricatorAuthSSHPrivateKeyPassphraseException.php
<?php abstract class PhabricatorAuthSSHPrivateKeyPassphraseException extends PhabricatorAuthSSHPrivateKeyException { final public function isFormatException() { return false; } final public function isPassphraseException() { return true; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/exception/privatekey/PhabricatorAuthSSHPrivateKeyUnknownException.php
src/applications/auth/exception/privatekey/PhabricatorAuthSSHPrivateKeyUnknownException.php
<?php final class PhabricatorAuthSSHPrivateKeyUnknownException extends PhabricatorAuthSSHPrivateKeyException { public function isFormatException() { return true; } public function isPassphraseException() { return true; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/exception/privatekey/PhabricatorAuthSSHPrivateKeyFormatException.php
src/applications/auth/exception/privatekey/PhabricatorAuthSSHPrivateKeyFormatException.php
<?php final class PhabricatorAuthSSHPrivateKeyFormatException extends PhabricatorAuthSSHPrivateKeyException { public function isFormatException() { return true; } public function isPassphraseException() { return false; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/exception/privatekey/PhabricatorAuthSSHPrivateKeyIncorrectPassphraseException.php
src/applications/auth/exception/privatekey/PhabricatorAuthSSHPrivateKeyIncorrectPassphraseException.php
<?php final class PhabricatorAuthSSHPrivateKeyIncorrectPassphraseException extends PhabricatorAuthSSHPrivateKeyPassphraseException {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/exception/privatekey/PhabricatorAuthSSHPrivateKeyMissingPassphraseException.php
src/applications/auth/exception/privatekey/PhabricatorAuthSSHPrivateKeyMissingPassphraseException.php
<?php final class PhabricatorAuthSSHPrivateKeyMissingPassphraseException extends PhabricatorAuthSSHPrivateKeyPassphraseException {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/exception/privatekey/PhabricatorAuthSSHPrivateKeyException.php
src/applications/auth/exception/privatekey/PhabricatorAuthSSHPrivateKeyException.php
<?php abstract class PhabricatorAuthSSHPrivateKeyException extends Exception { abstract public function isFormatException(); abstract public function isPassphraseException(); }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/exception/privatekey/PhabricatorAuthSSHPrivateKeySurplusPassphraseException.php
src/applications/auth/exception/privatekey/PhabricatorAuthSSHPrivateKeySurplusPassphraseException.php
<?php final class PhabricatorAuthSSHPrivateKeySurplusPassphraseException extends PhabricatorAuthSSHPrivateKeyPassphraseException {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/guidance/PhabricatorAuthProvidersGuidanceEngineExtension.php
src/applications/auth/guidance/PhabricatorAuthProvidersGuidanceEngineExtension.php
<?php final class PhabricatorAuthProvidersGuidanceEngineExtension extends PhabricatorGuidanceEngineExtension { const GUIDANCEKEY = 'core.auth.providers'; public function canGenerateGuidance(PhabricatorGuidanceContext $context) { return ($context instanceof PhabricatorAuthProvidersGuidanceContext); } public function generateGuidance(PhabricatorGuidanceContext $context) { $configs = id(new PhabricatorAuthProviderConfigQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withIsEnabled(true) ->execute(); $allows_registration = false; foreach ($configs as $config) { $provider = $config->getProvider(); if ($provider->shouldAllowRegistration()) { $allows_registration = true; break; } } // If no provider allows registration, we don't need provide any warnings // about registration being too open. if (!$allows_registration) { return array(); } $domains_key = 'auth.email-domains'; $domains_link = $this->renderConfigLink($domains_key); $domains_value = PhabricatorEnv::getEnvConfig($domains_key); $approval_key = 'auth.require-approval'; $approval_link = $this->renderConfigLink($approval_key); $approval_value = PhabricatorEnv::getEnvConfig($approval_key); $results = array(); if ($domains_value) { $message = pht( 'This server is configured with an email domain whitelist (in %s), so '. 'only users with a verified email address at one of these %s '. 'allowed domain(s) will be able to register an account: %s', $domains_link, phutil_count($domains_value), phutil_tag('strong', array(), implode(', ', $domains_value))); $results[] = $this->newGuidance('core.auth.email-domains.on') ->setMessage($message); } else { $message = pht( 'Anyone who can browse to this this server will be able to '. 'register an account. To add email domain restrictions, configure '. '%s.', $domains_link); $results[] = $this->newGuidance('core.auth.email-domains.off') ->setMessage($message); } if ($approval_value) { $message = pht( 'Administrative approvals are enabled (in %s), so all new users must '. 'have their accounts approved by an administrator.', $approval_link); $results[] = $this->newGuidance('core.auth.require-approval.on') ->setMessage($message); } else { $message = pht( 'Administrative approvals are disabled, so users who register will '. 'be able to use their accounts immediately. To enable approvals, '. 'configure %s.', $approval_link); $results[] = $this->newGuidance('core.auth.require-approval.off') ->setMessage($message); } if (!$domains_value && !$approval_value) { $message = pht( 'You can safely ignore these warnings if the install itself has '. 'access controls (for example, it is deployed on a VPN) or if all of '. 'the configured providers have access controls (for example, they are '. 'all private LDAP or OAuth servers).'); $results[] = $this->newWarning('core.auth.warning') ->setMessage($message); } $locked_config_key = 'auth.lock-config'; $is_locked = PhabricatorEnv::getEnvConfig($locked_config_key); if ($is_locked) { $message = pht( 'Authentication provider configuration is locked, and can not be '. 'changed without being unlocked. See the configuration setting %s '. 'for details.', phutil_tag( 'a', array( 'href' => '/config/edit/'.$locked_config_key, ), $locked_config_key)); $results[] = $this->newWarning('auth.locked-config') ->setPriority(500) ->setMessage($message); } return $results; } private function renderConfigLink($key) { return phutil_tag( 'a', array( 'href' => '/config/edit/'.$key.'/', 'target' => '_blank', ), $key); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/guidance/PhabricatorAuthProvidersGuidanceContext.php
src/applications/auth/guidance/PhabricatorAuthProvidersGuidanceContext.php
<?php final class PhabricatorAuthProvidersGuidanceContext extends PhabricatorGuidanceContext { private $canManage = false; public function setCanManage($can_manage) { $this->canManage = $can_manage; return $this; } public function getCanManage() { return $this->canManage; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/application/PhabricatorAuthApplication.php
src/applications/auth/application/PhabricatorAuthApplication.php
<?php final class PhabricatorAuthApplication extends PhabricatorApplication { public function canUninstall() { return false; } public function getBaseURI() { return '/auth/'; } public function getIcon() { return 'fa-key'; } public function isPinnedByDefault(PhabricatorUser $viewer) { return $viewer->getIsAdmin(); } public function getName() { return pht('Auth'); } public function getShortDescription() { return pht('Login/Registration'); } public function getHelpDocumentationArticles(PhabricatorUser $viewer) { // NOTE: Although reasonable help exists for this in "Configuring Accounts // and Registration", specifying help items here means we get the menu // item in all the login/link interfaces, which is confusing and not // helpful. // TODO: Special case this, or split the auth and auth administration // applications? return array(); } public function getApplicationGroup() { return self::GROUP_ADMIN; } public function getRoutes() { return array( '/auth/' => array( '' => 'PhabricatorAuthListController', 'config/' => array( 'new/' => 'PhabricatorAuthNewController', 'edit/(?:(?P<id>\d+)/)?' => 'PhabricatorAuthEditController', '(?P<action>enable|disable)/(?P<id>\d+)/' => 'PhabricatorAuthDisableController', 'view/(?P<id>\d+)/' => 'PhabricatorAuthProviderViewController', ), 'login/(?P<pkey>[^/]+)/(?:(?P<extra>[^/]+)/)?' => 'PhabricatorAuthLoginController', '(?P<loggedout>loggedout)/' => 'PhabricatorAuthStartController', 'invite/(?P<code>[^/]+)/' => 'PhabricatorAuthInviteController', 'register/(?:(?P<akey>[^/]+)/)?' => 'PhabricatorAuthRegisterController', 'start/' => 'PhabricatorAuthStartController', 'validate/' => 'PhabricatorAuthValidateController', 'finish/' => 'PhabricatorAuthFinishController', 'unlink/(?P<id>\d+)/' => 'PhabricatorAuthUnlinkController', '(?P<action>link|refresh)/(?P<id>\d+)/' => 'PhabricatorAuthLinkController', 'confirmlink/(?P<akey>[^/]+)/' => 'PhabricatorAuthConfirmLinkController', 'session/terminate/(?P<id>[^/]+)/' => 'PhabricatorAuthTerminateSessionController', 'token/revoke/(?P<id>[^/]+)/' => 'PhabricatorAuthRevokeTokenController', 'session/downgrade/' => 'PhabricatorAuthDowngradeSessionController', 'enroll/' => array( '(?:(?P<pageKey>[^/]+)/)?' => 'PhabricatorAuthNeedsMultiFactorController', ), 'sshkey/' => array( $this->getQueryRoutePattern('for/(?P<forPHID>[^/]+)/') => 'PhabricatorAuthSSHKeyListController', 'generate/' => 'PhabricatorAuthSSHKeyGenerateController', 'upload/' => 'PhabricatorAuthSSHKeyEditController', 'edit/(?P<id>\d+)/' => 'PhabricatorAuthSSHKeyEditController', 'revoke/(?P<id>\d+)/' => 'PhabricatorAuthSSHKeyRevokeController', 'view/(?P<id>\d+)/' => 'PhabricatorAuthSSHKeyViewController', ), 'password/' => 'PhabricatorAuthSetPasswordController', 'external/' => 'PhabricatorAuthSetExternalController', 'mfa/' => array( $this->getQueryRoutePattern() => 'PhabricatorAuthFactorProviderListController', $this->getEditRoutePattern('edit/') => 'PhabricatorAuthFactorProviderEditController', '(?P<id>[1-9]\d*)/' => 'PhabricatorAuthFactorProviderViewController', 'message/(?P<id>[1-9]\d*)/' => 'PhabricatorAuthFactorProviderMessageController', 'challenge/status/(?P<id>[1-9]\d*)/' => 'PhabricatorAuthChallengeStatusController', ), 'message/' => array( $this->getQueryRoutePattern() => 'PhabricatorAuthMessageListController', $this->getEditRoutePattern('edit/') => 'PhabricatorAuthMessageEditController', '(?P<id>[^/]+)/' => 'PhabricatorAuthMessageViewController', ), 'contact/' => array( $this->getEditRoutePattern('edit/') => 'PhabricatorAuthContactNumberEditController', '(?P<id>[1-9]\d*)/' => 'PhabricatorAuthContactNumberViewController', '(?P<action>disable|enable)/(?P<id>[1-9]\d*)/' => 'PhabricatorAuthContactNumberDisableController', 'primary/(?P<id>[1-9]\d*)/' => 'PhabricatorAuthContactNumberPrimaryController', 'test/(?P<id>[1-9]\d*)/' => 'PhabricatorAuthContactNumberTestController', ), ), '/oauth/(?P<provider>\w+)/login/' => 'PhabricatorAuthOldOAuthRedirectController', '/login/' => array( '' => 'PhabricatorAuthStartController', 'email/' => 'PhabricatorEmailLoginController', 'once/'. '(?P<type>[^/]+)/'. '(?P<id>\d+)/'. '(?P<key>[^/]+)/'. '(?:(?P<emailID>\d+)/)?' => 'PhabricatorAuthOneTimeLoginController', 'refresh/' => 'PhabricatorRefreshCSRFController', 'mustverify/' => 'PhabricatorMustVerifyEmailController', ), '/emailverify/(?P<code>[^/]+)/' => 'PhabricatorEmailVerificationController', '/logout/' => 'PhabricatorLogoutController', ); } protected function getCustomCapabilities() { return array( AuthManageProvidersCapability::CAPABILITY => array( 'default' => PhabricatorPolicies::POLICY_ADMIN, ), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/factor/PhabricatorAuthMFASyncTemporaryTokenType.php
src/applications/auth/factor/PhabricatorAuthMFASyncTemporaryTokenType.php
<?php final class PhabricatorAuthMFASyncTemporaryTokenType extends PhabricatorAuthTemporaryTokenType { const TOKENTYPE = 'mfa.sync'; const DIGEST_KEY = 'mfa.sync'; public function getTokenTypeDisplayName() { return pht('MFA Sync'); } public function getTokenReadableTypeName( PhabricatorAuthTemporaryToken $token) { return pht('MFA Sync Token'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/factor/PhabricatorAuthFactorResult.php
src/applications/auth/factor/PhabricatorAuthFactorResult.php
<?php final class PhabricatorAuthFactorResult extends Phobject { private $answeredChallenge; private $isWait = false; private $isError = false; private $isContinue = false; private $errorMessage; private $value; private $issuedChallenges = array(); private $icon; private $statusChallenge; public function setAnsweredChallenge(PhabricatorAuthChallenge $challenge) { if (!$challenge->getIsAnsweredChallenge()) { throw new PhutilInvalidStateException('markChallengeAsAnswered'); } if ($challenge->getIsCompleted()) { throw new Exception( pht( 'A completed challenge was provided as an answered challenge. '. 'The underlying factor is implemented improperly, challenges '. 'may not be reused.')); } $this->answeredChallenge = $challenge; return $this; } public function getAnsweredChallenge() { return $this->answeredChallenge; } public function setStatusChallenge(PhabricatorAuthChallenge $challenge) { $this->statusChallenge = $challenge; return $this; } public function getStatusChallenge() { return $this->statusChallenge; } public function getIsValid() { return (bool)$this->getAnsweredChallenge(); } public function setIsWait($is_wait) { $this->isWait = $is_wait; return $this; } public function getIsWait() { return $this->isWait; } public function setIsError($is_error) { $this->isError = $is_error; return $this; } public function getIsError() { return $this->isError; } public function setIsContinue($is_continue) { $this->isContinue = $is_continue; return $this; } public function getIsContinue() { return $this->isContinue; } public function setErrorMessage($error_message) { $this->errorMessage = $error_message; return $this; } public function getErrorMessage() { return $this->errorMessage; } public function setValue($value) { $this->value = $value; return $this; } public function getValue() { return $this->value; } public function setIcon(PHUIIconView $icon) { $this->icon = $icon; return $this; } public function getIcon() { return $this->icon; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/factor/PhabricatorDuoAuthFactor.php
src/applications/auth/factor/PhabricatorDuoAuthFactor.php
<?php final class PhabricatorDuoAuthFactor extends PhabricatorAuthFactor { const PROP_CREDENTIAL = 'duo.credentialPHID'; const PROP_ENROLL = 'duo.enroll'; const PROP_USERNAMES = 'duo.usernames'; const PROP_HOSTNAME = 'duo.hostname'; public function getFactorKey() { return 'duo'; } public function getFactorName() { return pht('Duo Security'); } public function getFactorShortName() { return pht('Duo'); } public function getFactorCreateHelp() { return pht('Support for Duo push authentication.'); } public function getFactorDescription() { return pht( 'When you need to authenticate, a request will be pushed to the '. 'Duo application on your phone.'); } public function getEnrollDescription( PhabricatorAuthFactorProvider $provider, PhabricatorUser $user) { return pht( 'To add a Duo factor, first download and install the Duo application '. 'on your phone. Once you have launched the application and are ready '. 'to perform setup, click continue.'); } public function canCreateNewConfiguration( PhabricatorAuthFactorProvider $provider, PhabricatorUser $user) { if ($this->loadConfigurationsForProvider($provider, $user)) { return false; } return true; } public function getConfigurationCreateDescription( PhabricatorAuthFactorProvider $provider, PhabricatorUser $user) { $messages = array(); if ($this->loadConfigurationsForProvider($provider, $user)) { $messages[] = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_WARNING) ->setErrors( array( pht( 'You already have Duo authentication attached to your account '. 'for this provider.'), )); } return $messages; } public function getConfigurationListDetails( PhabricatorAuthFactorConfig $config, PhabricatorAuthFactorProvider $provider, PhabricatorUser $viewer) { $duo_user = $config->getAuthFactorConfigProperty('duo.username'); return pht('Duo Username: %s', $duo_user); } public function newEditEngineFields( PhabricatorEditEngine $engine, PhabricatorAuthFactorProvider $provider) { $viewer = $engine->getViewer(); $credential_phid = $provider->getAuthFactorProviderProperty( self::PROP_CREDENTIAL); $hostname = $provider->getAuthFactorProviderProperty(self::PROP_HOSTNAME); $usernames = $provider->getAuthFactorProviderProperty(self::PROP_USERNAMES); $enroll = $provider->getAuthFactorProviderProperty(self::PROP_ENROLL); $credential_type = PassphrasePasswordCredentialType::CREDENTIAL_TYPE; $provides_type = PassphrasePasswordCredentialType::PROVIDES_TYPE; $credentials = id(new PassphraseCredentialQuery()) ->setViewer($viewer) ->withIsDestroyed(false) ->withProvidesTypes(array($provides_type)) ->execute(); $xaction_hostname = PhabricatorAuthFactorProviderDuoHostnameTransaction::TRANSACTIONTYPE; $xaction_credential = PhabricatorAuthFactorProviderDuoCredentialTransaction::TRANSACTIONTYPE; $xaction_usernames = PhabricatorAuthFactorProviderDuoUsernamesTransaction::TRANSACTIONTYPE; $xaction_enroll = PhabricatorAuthFactorProviderDuoEnrollTransaction::TRANSACTIONTYPE; return array( id(new PhabricatorTextEditField()) ->setLabel(pht('Duo API Hostname')) ->setKey('duo.hostname') ->setValue($hostname) ->setTransactionType($xaction_hostname) ->setIsRequired(true), id(new PhabricatorCredentialEditField()) ->setLabel(pht('Duo API Credential')) ->setKey('duo.credential') ->setValue($credential_phid) ->setTransactionType($xaction_credential) ->setCredentialType($credential_type) ->setCredentials($credentials), id(new PhabricatorSelectEditField()) ->setLabel(pht('Duo Username')) ->setKey('duo.usernames') ->setValue($usernames) ->setTransactionType($xaction_usernames) ->setOptions( array( 'username' => pht( 'Use %s Username', PlatformSymbols::getPlatformServerName()), 'email' => pht('Use Primary Email Address'), )), id(new PhabricatorSelectEditField()) ->setLabel(pht('Create Accounts')) ->setKey('duo.enroll') ->setValue($enroll) ->setTransactionType($xaction_enroll) ->setOptions( array( 'deny' => pht('Require Existing Duo Account'), 'allow' => pht('Create New Duo Account'), )), ); } public function processAddFactorForm( PhabricatorAuthFactorProvider $provider, AphrontFormView $form, AphrontRequest $request, PhabricatorUser $user) { $token = $this->loadMFASyncToken($provider, $request, $form, $user); if ($this->isAuthResult($token)) { $form->appendChild($this->newAutomaticControl($token)); return; } $enroll = $token->getTemporaryTokenProperty('duo.enroll'); $duo_id = $token->getTemporaryTokenProperty('duo.user-id'); $duo_uri = $token->getTemporaryTokenProperty('duo.uri'); $duo_user = $token->getTemporaryTokenProperty('duo.username'); $is_external = ($enroll === 'external'); $is_auto = ($enroll === 'auto'); $is_blocked = ($enroll === 'blocked'); if (!$token->getIsNewTemporaryToken()) { if ($is_auto) { return $this->newDuoConfig($user, $duo_user); } else if ($is_external || $is_blocked) { $parameters = array( 'username' => $duo_user, ); $result = $this->newDuoFuture($provider) ->setMethod('preauth', $parameters) ->resolve(); $result_code = $result['response']['result']; switch ($result_code) { case 'auth': case 'allow': return $this->newDuoConfig($user, $duo_user); case 'enroll': if ($is_blocked) { // We'll render an equivalent static control below, so skip // rendering here. We explicitly don't want to give the user // an enroll workflow. break; } $duo_uri = $result['response']['enroll_portal_url']; $waiting_icon = id(new PHUIIconView()) ->setIcon('fa-mobile', 'red'); $waiting_control = id(new PHUIFormTimerControl()) ->setIcon($waiting_icon) ->setError(pht('Not Complete')) ->appendChild( pht( 'You have not completed Duo enrollment yet. '. 'Complete enrollment, then click continue.')); $form->appendControl($waiting_control); break; default: case 'deny': break; } } else { $parameters = array( 'user_id' => $duo_id, 'activation_code' => $duo_uri, ); $future = $this->newDuoFuture($provider) ->setMethod('enroll_status', $parameters); $result = $future->resolve(); $response = $result['response']; switch ($response) { case 'success': return $this->newDuoConfig($user, $duo_user); case 'waiting': $waiting_icon = id(new PHUIIconView()) ->setIcon('fa-mobile', 'red'); $waiting_control = id(new PHUIFormTimerControl()) ->setIcon($waiting_icon) ->setError(pht('Not Complete')) ->appendChild( pht( 'You have not activated this enrollment in the Duo '. 'application on your phone yet. Complete activation, then '. 'click continue.')); $form->appendControl($waiting_control); break; case 'invalid': default: throw new Exception( pht( 'This Duo enrollment attempt is invalid or has '. 'expired ("%s"). Cancel the workflow and try again.', $response)); } } } if ($is_blocked) { $blocked_icon = id(new PHUIIconView()) ->setIcon('fa-times', 'red'); $blocked_control = id(new PHUIFormTimerControl()) ->setIcon($blocked_icon) ->appendChild( pht( 'Your Duo account ("%s") has not completed Duo enrollment. '. 'Check your email and complete enrollment to continue.', phutil_tag('strong', array(), $duo_user))); $form->appendControl($blocked_control); } else if ($is_auto) { $auto_icon = id(new PHUIIconView()) ->setIcon('fa-check', 'green'); $auto_control = id(new PHUIFormTimerControl()) ->setIcon($auto_icon) ->appendChild( pht( 'Duo account ("%s") is fully enrolled.', phutil_tag('strong', array(), $duo_user))); $form->appendControl($auto_control); } else { $duo_button = phutil_tag( 'a', array( 'href' => $duo_uri, 'class' => 'button button-grey', 'target' => ($is_external ? '_blank' : null), ), pht('Enroll Duo Account: %s', $duo_user)); $duo_button = phutil_tag( 'div', array( 'class' => 'mfa-form-enroll-button', ), $duo_button); if ($is_external) { $form->appendRemarkupInstructions( pht( 'Complete enrolling your phone with Duo:')); $form->appendControl( id(new AphrontFormMarkupControl()) ->setValue($duo_button)); } else { $form->appendRemarkupInstructions( pht( 'Scan this QR code with the Duo application on your mobile '. 'phone:')); $qr_code = $this->newQRCode($duo_uri); $form->appendChild($qr_code); $form->appendRemarkupInstructions( pht( 'If you are currently using your phone to view this page, '. 'click this button to open the Duo application:')); $form->appendControl( id(new AphrontFormMarkupControl()) ->setValue($duo_button)); } $form->appendRemarkupInstructions( pht( 'Once you have completed setup on your phone, click continue.')); } } protected function newMFASyncTokenProperties( PhabricatorAuthFactorProvider $provider, PhabricatorUser $user) { $duo_user = $this->getDuoUsername($provider, $user); // Duo automatically normalizes usernames to lowercase. Just do that here // so that our value agrees more closely with Duo. $duo_user = phutil_utf8_strtolower($duo_user); $parameters = array( 'username' => $duo_user, ); $result = $this->newDuoFuture($provider) ->setMethod('preauth', $parameters) ->resolve(); $external_uri = null; $result_code = $result['response']['result']; $status_message = $result['response']['status_msg']; switch ($result_code) { case 'auth': case 'allow': // If the user already has a Duo account, they don't need to do // anything. return array( 'duo.enroll' => 'auto', 'duo.username' => $duo_user, ); case 'enroll': if (!$this->shouldAllowDuoEnrollment($provider)) { return array( 'duo.enroll' => 'blocked', 'duo.username' => $duo_user, ); } $external_uri = $result['response']['enroll_portal_url']; // Otherwise, enrollment is permitted so we're going to continue. break; default: case 'deny': return $this->newResult() ->setIsError(true) ->setErrorMessage( pht( 'Your Duo account ("%s") is not permitted to access this '. 'system. Contact your Duo administrator for help. '. 'The Duo preauth API responded with status message ("%s"): %s', $duo_user, $result_code, $status_message)); } // Duo's "/enroll" API isn't repeatable for the same username. If we're // the first call, great: we can do inline enrollment, which is way more // user friendly. Otherwise, we have to send the user on an adventure. $parameters = array( 'username' => $duo_user, 'valid_secs' => phutil_units('1 hour in seconds'), ); try { $result = $this->newDuoFuture($provider) ->setMethod('enroll', $parameters) ->resolve(); } catch (HTTPFutureHTTPResponseStatus $ex) { return array( 'duo.enroll' => 'external', 'duo.username' => $duo_user, 'duo.uri' => $external_uri, ); } return array( 'duo.enroll' => 'inline', 'duo.uri' => $result['response']['activation_code'], 'duo.username' => $duo_user, 'duo.user-id' => $result['response']['user_id'], ); } protected function newIssuedChallenges( PhabricatorAuthFactorConfig $config, PhabricatorUser $viewer, array $challenges) { // If we already issued a valid challenge for this workflow and session, // don't issue a new one. $challenge = $this->getChallengeForCurrentContext( $config, $viewer, $challenges); if ($challenge) { return array(); } if (!$this->hasCSRF($config)) { return $this->newResult() ->setIsContinue(true) ->setErrorMessage( pht( 'An authorization request will be pushed to the Duo '. 'application on your phone.')); } $provider = $config->getFactorProvider(); // Otherwise, issue a new challenge. $duo_user = (string)$config->getAuthFactorConfigProperty('duo.username'); $parameters = array( 'username' => $duo_user, ); $response = $this->newDuoFuture($provider) ->setMethod('preauth', $parameters) ->resolve(); $response = $response['response']; $next_step = $response['result']; $status_message = $response['status_msg']; switch ($next_step) { case 'auth': // We're good to go. break; case 'allow': // Duo is telling us to bypass MFA. For now, refuse. return $this->newResult() ->setIsError(true) ->setErrorMessage( pht( 'Duo is not requiring a challenge, which defeats the '. 'purpose of MFA. Duo must be configured to challenge you.')); case 'enroll': return $this->newResult() ->setIsError(true) ->setErrorMessage( pht( 'Your Duo account ("%s") requires enrollment. Contact your '. 'Duo administrator for help. Duo status message: %s', $duo_user, $status_message)); case 'deny': default: return $this->newResult() ->setIsError(true) ->setErrorMessage( pht( 'Your Duo account ("%s") is not permitted to access this '. 'system. Contact your Duo administrator for help. The Duo '. 'preauth API responded with status message ("%s"): %s', $duo_user, $next_step, $status_message)); } $has_push = false; $devices = $response['devices']; foreach ($devices as $device) { $capabilities = array_fuse($device['capabilities']); if (isset($capabilities['push'])) { $has_push = true; break; } } if (!$has_push) { return $this->newResult() ->setIsError(true) ->setErrorMessage( pht( 'This factor has been removed from your device, so this server '. 'can not send you a challenge. To continue, an administrator '. 'must strip this factor from your account.')); } $push_info = array( pht('Domain') => $this->getInstallDisplayName(), ); $push_info = phutil_build_http_querystring($push_info); $parameters = array( 'username' => $duo_user, 'factor' => 'push', 'async' => '1', // Duo allows us to specify a device, or to pass "auto" to have it pick // the first one. For now, just let it pick. 'device' => 'auto', // This is a hard-coded prefix for the word "... request" in the Duo UI, // which defaults to "Login". We could pass richer information from // workflows here, but it's not very flexible anyway. 'type' => 'Authentication', 'display_username' => $viewer->getUsername(), 'pushinfo' => $push_info, ); $result = $this->newDuoFuture($provider) ->setMethod('auth', $parameters) ->resolve(); $duo_xaction = $result['response']['txid']; // The Duo push timeout is 60 seconds. Set our challenge to expire slightly // more quickly so that we'll re-issue a new challenge before Duo times out. // This should keep users away from a dead-end where they can't respond to // Duo but we won't issue a new challenge yet. $ttl_seconds = 55; return array( $this->newChallenge($config, $viewer) ->setChallengeKey($duo_xaction) ->setChallengeTTL(PhabricatorTime::getNow() + $ttl_seconds), ); } protected function newResultFromIssuedChallenges( PhabricatorAuthFactorConfig $config, PhabricatorUser $viewer, array $challenges) { $challenge = $this->getChallengeForCurrentContext( $config, $viewer, $challenges); if ($challenge->getIsAnsweredChallenge()) { return $this->newResult() ->setAnsweredChallenge($challenge); } $provider = $config->getFactorProvider(); $duo_xaction = $challenge->getChallengeKey(); $parameters = array( 'txid' => $duo_xaction, ); // This endpoint always long-polls, so use a timeout to force it to act // more asynchronously. try { $result = $this->newDuoFuture($provider) ->setHTTPMethod('GET') ->setMethod('auth_status', $parameters) ->setTimeout(3) ->resolve(); $state = $result['response']['result']; $status = $result['response']['status']; } catch (HTTPFutureCURLResponseStatus $exception) { if ($exception->isTimeout()) { $state = 'waiting'; $status = 'poll'; } else { throw $exception; } } $now = PhabricatorTime::getNow(); switch ($state) { case 'allow': $ttl = PhabricatorTime::getNow() + phutil_units('15 minutes in seconds'); $challenge ->markChallengeAsAnswered($ttl); return $this->newResult() ->setAnsweredChallenge($challenge); case 'waiting': // If we didn't just issue this challenge, give the user a stronger // hint that they need to follow the instructions. if (!$challenge->getIsNewChallenge()) { return $this->newResult() ->setIsContinue(true) ->setIcon( id(new PHUIIconView()) ->setIcon('fa-exclamation-triangle', 'yellow')) ->setErrorMessage( pht( 'You must approve the challenge which was sent to your '. 'phone. Open the Duo application and confirm the challenge, '. 'then continue.')); } // Otherwise, we'll construct a default message later on. break; default: case 'deny': if ($status === 'timeout') { return $this->newResult() ->setIsError(true) ->setErrorMessage( pht( 'This request has timed out because you took too long to '. 'respond.')); } else { $wait_duration = ($challenge->getChallengeTTL() - $now) + 1; return $this->newResult() ->setIsWait(true) ->setErrorMessage( pht( 'You denied this request. Wait %s second(s) to try again.', new PhutilNumber($wait_duration))); } break; } return null; } public function renderValidateFactorForm( PhabricatorAuthFactorConfig $config, AphrontFormView $form, PhabricatorUser $viewer, PhabricatorAuthFactorResult $result) { $control = $this->newAutomaticControl($result); $control ->setLabel(pht('Duo')) ->setCaption(pht('Factor Name: %s', $config->getFactorName())); $form->appendChild($control); } public function getRequestHasChallengeResponse( PhabricatorAuthFactorConfig $config, AphrontRequest $request) { return false; } protected function newResultFromChallengeResponse( PhabricatorAuthFactorConfig $config, PhabricatorUser $viewer, AphrontRequest $request, array $challenges) { return $this->getResultForPrompt( $config, $viewer, $request, $challenges); } protected function newResultForPrompt( PhabricatorAuthFactorConfig $config, PhabricatorUser $viewer, AphrontRequest $request, array $challenges) { $result = $this->newResult() ->setIsContinue(true) ->setErrorMessage( pht( 'A challenge has been sent to your phone. Open the Duo '. 'application and confirm the challenge, then continue.')); $challenge = $this->getChallengeForCurrentContext( $config, $viewer, $challenges); if ($challenge) { $result ->setStatusChallenge($challenge) ->setIcon( id(new PHUIIconView()) ->setIcon('fa-refresh', 'green ph-spin')); } return $result; } private function newDuoFuture(PhabricatorAuthFactorProvider $provider) { $credential_phid = $provider->getAuthFactorProviderProperty( self::PROP_CREDENTIAL); $omnipotent = PhabricatorUser::getOmnipotentUser(); $credential = id(new PassphraseCredentialQuery()) ->setViewer($omnipotent) ->withPHIDs(array($credential_phid)) ->needSecrets(true) ->executeOne(); if (!$credential) { throw new Exception( pht( 'Unable to load Duo API credential ("%s").', $credential_phid)); } $duo_key = $credential->getUsername(); $duo_secret = $credential->getSecret(); if (!$duo_secret) { throw new Exception( pht( 'Duo API credential ("%s") has no secret key.', $credential_phid)); } $duo_host = $provider->getAuthFactorProviderProperty( self::PROP_HOSTNAME); self::requireDuoAPIHostname($duo_host); return id(new PhabricatorDuoFuture()) ->setIntegrationKey($duo_key) ->setSecretKey($duo_secret) ->setAPIHostname($duo_host) ->setTimeout(10) ->setHTTPMethod('POST'); } private function getDuoUsername( PhabricatorAuthFactorProvider $provider, PhabricatorUser $user) { $mode = $provider->getAuthFactorProviderProperty(self::PROP_USERNAMES); switch ($mode) { case 'username': return $user->getUsername(); case 'email': return $user->loadPrimaryEmailAddress(); default: throw new Exception( pht( 'Duo username pairing mode ("%s") is not supported.', $mode)); } } private function shouldAllowDuoEnrollment( PhabricatorAuthFactorProvider $provider) { $mode = $provider->getAuthFactorProviderProperty(self::PROP_ENROLL); switch ($mode) { case 'deny': return false; case 'allow': return true; default: throw new Exception( pht( 'Duo enrollment mode ("%s") is not supported.', $mode)); } } private function newDuoConfig(PhabricatorUser $user, $duo_user) { $config_properties = array( 'duo.username' => $duo_user, ); $config = $this->newConfigForUser($user) ->setFactorName(pht('Duo (%s)', $duo_user)) ->setProperties($config_properties); return $config; } public static function requireDuoAPIHostname($hostname) { if (preg_match('/\.duosecurity\.com\z/', $hostname)) { return; } throw new Exception( pht( 'Duo API hostname ("%s") is invalid, hostname must be '. '"*.duosecurity.com".', $hostname)); } public function newChallengeStatusView( PhabricatorAuthFactorConfig $config, PhabricatorAuthFactorProvider $provider, PhabricatorUser $viewer, PhabricatorAuthChallenge $challenge) { $duo_xaction = $challenge->getChallengeKey(); $parameters = array( 'txid' => $duo_xaction, ); $default_result = id(new PhabricatorAuthChallengeUpdate()) ->setRetry(true); try { $result = $this->newDuoFuture($provider) ->setHTTPMethod('GET') ->setMethod('auth_status', $parameters) ->setTimeout(5) ->resolve(); $state = $result['response']['result']; } catch (HTTPFutureCURLResponseStatus $exception) { // If we failed or timed out, retry. Usually, this is a timeout. return id(new PhabricatorAuthChallengeUpdate()) ->setRetry(true); } // For now, don't update the view for anything but an "Allow". Updates // here are just about providing more visual feedback for user convenience. if ($state !== 'allow') { return id(new PhabricatorAuthChallengeUpdate()) ->setRetry(false); } $icon = id(new PHUIIconView()) ->setIcon('fa-check-circle-o', 'green'); $view = id(new PHUIFormTimerControl()) ->setIcon($icon) ->appendChild(pht('You responded to this challenge correctly.')) ->newTimerView(); return id(new PhabricatorAuthChallengeUpdate()) ->setState('allow') ->setRetry(false) ->setMarkup($view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/factor/PhabricatorSMSAuthFactor.php
src/applications/auth/factor/PhabricatorSMSAuthFactor.php
<?php final class PhabricatorSMSAuthFactor extends PhabricatorAuthFactor { public function getFactorKey() { return 'sms'; } public function getFactorName() { return pht('Text Message (SMS)'); } public function getFactorShortName() { return pht('SMS'); } public function getFactorCreateHelp() { return pht( 'Allow users to receive a code via SMS.'); } public function getFactorDescription() { return pht( 'When you need to authenticate, a text message with a code will '. 'be sent to your phone.'); } public function getFactorOrder() { // Sort this factor toward the end of the list because SMS is relatively // weak. return 2000; } public function isContactNumberFactor() { return true; } public function canCreateNewProvider() { return $this->isSMSMailerConfigured(); } public function getProviderCreateDescription() { $messages = array(); if (!$this->isSMSMailerConfigured()) { $messages[] = id(new PHUIInfoView()) ->setErrors( array( pht( 'You have not configured an outbound SMS mailer. You must '. 'configure one before you can set up SMS. See: %s', phutil_tag( 'a', array( 'href' => '/config/edit/cluster.mailers/', ), 'cluster.mailers')), )); } $messages[] = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_WARNING) ->setErrors( array( pht( 'SMS is weak, and relatively easy for attackers to compromise. '. 'Strongly consider using a different MFA provider.'), )); return $messages; } public function canCreateNewConfiguration( PhabricatorAuthFactorProvider $provider, PhabricatorUser $user) { if (!$this->loadUserContactNumber($user)) { return false; } if ($this->loadConfigurationsForProvider($provider, $user)) { return false; } return true; } public function getConfigurationCreateDescription( PhabricatorAuthFactorProvider $provider, PhabricatorUser $user) { $messages = array(); if (!$this->loadUserContactNumber($user)) { $messages[] = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_WARNING) ->setErrors( array( pht( 'You have not configured a primary contact number. Configure '. 'a contact number before adding SMS as an authentication '. 'factor.'), )); } if ($this->loadConfigurationsForProvider($provider, $user)) { $messages[] = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_WARNING) ->setErrors( array( pht( 'You already have SMS authentication attached to your account.'), )); } return $messages; } public function getEnrollDescription( PhabricatorAuthFactorProvider $provider, PhabricatorUser $user) { return pht( 'To verify your phone as an authentication factor, a text message with '. 'a secret code will be sent to the phone number you have listed as '. 'your primary contact number.'); } public function getEnrollButtonText( PhabricatorAuthFactorProvider $provider, PhabricatorUser $user) { $contact_number = $this->loadUserContactNumber($user); return pht('Send SMS: %s', $contact_number->getDisplayName()); } public function processAddFactorForm( PhabricatorAuthFactorProvider $provider, AphrontFormView $form, AphrontRequest $request, PhabricatorUser $user) { $token = $this->loadMFASyncToken($provider, $request, $form, $user); $code = $request->getStr('sms.code'); $e_code = true; if (!$token->getIsNewTemporaryToken()) { $expect_code = $token->getTemporaryTokenProperty('code'); $okay = phutil_hashes_are_identical( $this->normalizeSMSCode($code), $this->normalizeSMSCode($expect_code)); if ($okay) { $config = $this->newConfigForUser($user) ->setFactorName(pht('SMS')); return $config; } else { if (!strlen($code)) { $e_code = pht('Required'); } else { $e_code = pht('Invalid'); } } } $form->appendRemarkupInstructions( pht( 'Enter the code from the text message which was sent to your '. 'primary contact number.')); $form->appendChild( id(new PHUIFormNumberControl()) ->setLabel(pht('SMS Code')) ->setName('sms.code') ->setValue($code) ->setError($e_code)); } protected function newIssuedChallenges( PhabricatorAuthFactorConfig $config, PhabricatorUser $viewer, array $challenges) { // If we already issued a valid challenge for this workflow and session, // don't issue a new one. $challenge = $this->getChallengeForCurrentContext( $config, $viewer, $challenges); if ($challenge) { return array(); } if (!$this->loadUserContactNumber($viewer)) { return $this->newResult() ->setIsError(true) ->setErrorMessage( pht( 'Your account has no primary contact number.')); } if (!$this->isSMSMailerConfigured()) { return $this->newResult() ->setIsError(true) ->setErrorMessage( pht( 'No outbound mailer which can deliver SMS messages is '. 'configured.')); } if (!$this->hasCSRF($config)) { return $this->newResult() ->setIsContinue(true) ->setErrorMessage( pht( 'A text message with an authorization code will be sent to your '. 'primary contact number.')); } // Otherwise, issue a new challenge. $challenge_code = $this->newSMSChallengeCode(); $envelope = new PhutilOpaqueEnvelope($challenge_code); $this->sendSMSCodeToUser($envelope, $viewer); $ttl_seconds = phutil_units('15 minutes in seconds'); return array( $this->newChallenge($config, $viewer) ->setChallengeKey($challenge_code) ->setChallengeTTL(PhabricatorTime::getNow() + $ttl_seconds), ); } protected function newResultFromIssuedChallenges( PhabricatorAuthFactorConfig $config, PhabricatorUser $viewer, array $challenges) { $challenge = $this->getChallengeForCurrentContext( $config, $viewer, $challenges); if ($challenge->getIsAnsweredChallenge()) { return $this->newResult() ->setAnsweredChallenge($challenge); } return null; } public function renderValidateFactorForm( PhabricatorAuthFactorConfig $config, AphrontFormView $form, PhabricatorUser $viewer, PhabricatorAuthFactorResult $result) { $control = $this->newAutomaticControl($result); if (!$control) { $value = $result->getValue(); $error = $result->getErrorMessage(); $name = $this->getChallengeResponseParameterName($config); $control = id(new PHUIFormNumberControl()) ->setName($name) ->setDisableAutocomplete(true) ->setValue($value) ->setError($error); } $control ->setLabel(pht('SMS Code')) ->setCaption(pht('Factor Name: %s', $config->getFactorName())); $form->appendChild($control); } public function getRequestHasChallengeResponse( PhabricatorAuthFactorConfig $config, AphrontRequest $request) { $value = $this->getChallengeResponseFromRequest($config, $request); return (bool)strlen($value); } protected function newResultFromChallengeResponse( PhabricatorAuthFactorConfig $config, PhabricatorUser $viewer, AphrontRequest $request, array $challenges) { $challenge = $this->getChallengeForCurrentContext( $config, $viewer, $challenges); $code = $this->getChallengeResponseFromRequest( $config, $request); $result = $this->newResult() ->setValue($code); if ($challenge->getIsAnsweredChallenge()) { return $result->setAnsweredChallenge($challenge); } if (phutil_hashes_are_identical($code, $challenge->getChallengeKey())) { $ttl = PhabricatorTime::getNow() + phutil_units('15 minutes in seconds'); $challenge ->markChallengeAsAnswered($ttl); return $result->setAnsweredChallenge($challenge); } if (strlen($code)) { $error_message = pht('Invalid'); } else { $error_message = pht('Required'); } $result->setErrorMessage($error_message); return $result; } private function newSMSChallengeCode() { $value = Filesystem::readRandomInteger(0, 99999999); $value = sprintf('%08d', $value); return $value; } private function isSMSMailerConfigured() { $mailers = PhabricatorMetaMTAMail::newMailers( array( 'outbound' => true, 'media' => array( PhabricatorMailSMSMessage::MESSAGETYPE, ), )); return (bool)$mailers; } private function loadUserContactNumber(PhabricatorUser $user) { $contact_numbers = id(new PhabricatorAuthContactNumberQuery()) ->setViewer($user) ->withObjectPHIDs(array($user->getPHID())) ->withStatuses( array( PhabricatorAuthContactNumber::STATUS_ACTIVE, )) ->withIsPrimary(true) ->execute(); if (count($contact_numbers) !== 1) { return null; } return head($contact_numbers); } protected function newMFASyncTokenProperties( PhabricatorAuthFactorProvider $providerr, PhabricatorUser $user) { $sms_code = $this->newSMSChallengeCode(); $envelope = new PhutilOpaqueEnvelope($sms_code); $this->sendSMSCodeToUser($envelope, $user); return array( 'code' => $sms_code, ); } private function sendSMSCodeToUser( PhutilOpaqueEnvelope $envelope, PhabricatorUser $user) { return id(new PhabricatorMetaMTAMail()) ->setMessageType(PhabricatorMailSMSMessage::MESSAGETYPE) ->addTos(array($user->getPHID())) ->setForceDelivery(true) ->setSensitiveContent(true) ->setBody( pht( '%s (%s) MFA Code: %s', PlatformSymbols::getPlatformServerName(), $this->getInstallDisplayName(), $envelope->openEnvelope())) ->save(); } private function normalizeSMSCode($code) { return trim($code); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/factor/PhabricatorAuthFactor.php
src/applications/auth/factor/PhabricatorAuthFactor.php
<?php abstract class PhabricatorAuthFactor extends Phobject { abstract public function getFactorName(); abstract public function getFactorShortName(); abstract public function getFactorKey(); abstract public function getFactorCreateHelp(); abstract public function getFactorDescription(); abstract public function processAddFactorForm( PhabricatorAuthFactorProvider $provider, AphrontFormView $form, AphrontRequest $request, PhabricatorUser $user); abstract public function renderValidateFactorForm( PhabricatorAuthFactorConfig $config, AphrontFormView $form, PhabricatorUser $viewer, PhabricatorAuthFactorResult $validation_result); public function getParameterName( PhabricatorAuthFactorConfig $config, $name) { return 'authfactor.'.$config->getID().'.'.$name; } public static function getAllFactors() { return id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->setUniqueMethod('getFactorKey') ->execute(); } protected function newConfigForUser(PhabricatorUser $user) { return id(new PhabricatorAuthFactorConfig()) ->setUserPHID($user->getPHID()) ->setFactorSecret(''); } protected function newResult() { return new PhabricatorAuthFactorResult(); } public function newIconView() { return id(new PHUIIconView()) ->setIcon('fa-mobile'); } public function canCreateNewProvider() { return true; } public function getProviderCreateDescription() { return null; } public function canCreateNewConfiguration( PhabricatorAuthFactorProvider $provider, PhabricatorUser $user) { return true; } public function getConfigurationCreateDescription( PhabricatorAuthFactorProvider $provider, PhabricatorUser $user) { return null; } public function getConfigurationListDetails( PhabricatorAuthFactorConfig $config, PhabricatorAuthFactorProvider $provider, PhabricatorUser $viewer) { return null; } public function newEditEngineFields( PhabricatorEditEngine $engine, PhabricatorAuthFactorProvider $provider) { return array(); } public function newChallengeStatusView( PhabricatorAuthFactorConfig $config, PhabricatorAuthFactorProvider $provider, PhabricatorUser $viewer, PhabricatorAuthChallenge $challenge) { return null; } /** * Is this a factor which depends on the user's contact number? * * If a user has a "contact number" factor configured, they can not modify * or switch their primary contact number. * * @return bool True if this factor should lock contact numbers. */ public function isContactNumberFactor() { return false; } abstract public function getEnrollDescription( PhabricatorAuthFactorProvider $provider, PhabricatorUser $user); public function getEnrollButtonText( PhabricatorAuthFactorProvider $provider, PhabricatorUser $user) { return pht('Continue'); } public function getFactorOrder() { return 1000; } final public function newSortVector() { return id(new PhutilSortVector()) ->addInt($this->canCreateNewProvider() ? 0 : 1) ->addInt($this->getFactorOrder()) ->addString($this->getFactorName()); } protected function newChallenge( PhabricatorAuthFactorConfig $config, PhabricatorUser $viewer) { $engine = $config->getSessionEngine(); return PhabricatorAuthChallenge::initializeNewChallenge() ->setUserPHID($viewer->getPHID()) ->setSessionPHID($viewer->getSession()->getPHID()) ->setFactorPHID($config->getPHID()) ->setIsNewChallenge(true) ->setWorkflowKey($engine->getWorkflowKey()); } abstract public function getRequestHasChallengeResponse( PhabricatorAuthFactorConfig $config, AphrontRequest $response); final public function getNewIssuedChallenges( PhabricatorAuthFactorConfig $config, PhabricatorUser $viewer, array $challenges) { assert_instances_of($challenges, 'PhabricatorAuthChallenge'); $now = PhabricatorTime::getNow(); // Factor implementations may need to perform writes in order to issue // challenges, particularly push factors like SMS. $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); $new_challenges = $this->newIssuedChallenges( $config, $viewer, $challenges); if ($this->isAuthResult($new_challenges)) { unset($unguarded); return $new_challenges; } assert_instances_of($new_challenges, 'PhabricatorAuthChallenge'); foreach ($new_challenges as $new_challenge) { $ttl = $new_challenge->getChallengeTTL(); if (!$ttl) { throw new Exception( pht('Newly issued MFA challenges must have a valid TTL!')); } if ($ttl < $now) { throw new Exception( pht( 'Newly issued MFA challenges must have a future TTL. This '. 'factor issued a bad TTL ("%s"). (Did you use a relative '. 'time instead of an epoch?)', $ttl)); } } foreach ($new_challenges as $challenge) { $challenge->save(); } unset($unguarded); return $new_challenges; } abstract protected function newIssuedChallenges( PhabricatorAuthFactorConfig $config, PhabricatorUser $viewer, array $challenges); final public function getResultFromIssuedChallenges( PhabricatorAuthFactorConfig $config, PhabricatorUser $viewer, array $challenges) { assert_instances_of($challenges, 'PhabricatorAuthChallenge'); $result = $this->newResultFromIssuedChallenges( $config, $viewer, $challenges); if ($result === null) { return $result; } if (!$this->isAuthResult($result)) { throw new Exception( pht( 'Expected "newResultFromIssuedChallenges()" to return null or '. 'an object of class "%s"; got something else (in "%s").', 'PhabricatorAuthFactorResult', get_class($this))); } return $result; } final public function getResultForPrompt( PhabricatorAuthFactorConfig $config, PhabricatorUser $viewer, AphrontRequest $request, array $challenges) { assert_instances_of($challenges, 'PhabricatorAuthChallenge'); $result = $this->newResultForPrompt( $config, $viewer, $request, $challenges); if (!$this->isAuthResult($result)) { throw new Exception( pht( 'Expected "newResultForPrompt()" to return an object of class "%s", '. 'but it returned something else ("%s"; in "%s").', 'PhabricatorAuthFactorResult', phutil_describe_type($result), get_class($this))); } return $result; } protected function newResultForPrompt( PhabricatorAuthFactorConfig $config, PhabricatorUser $viewer, AphrontRequest $request, array $challenges) { return $this->newResult(); } abstract protected function newResultFromIssuedChallenges( PhabricatorAuthFactorConfig $config, PhabricatorUser $viewer, array $challenges); final public function getResultFromChallengeResponse( PhabricatorAuthFactorConfig $config, PhabricatorUser $viewer, AphrontRequest $request, array $challenges) { assert_instances_of($challenges, 'PhabricatorAuthChallenge'); $result = $this->newResultFromChallengeResponse( $config, $viewer, $request, $challenges); if (!$this->isAuthResult($result)) { throw new Exception( pht( 'Expected "newResultFromChallengeResponse()" to return an object '. 'of class "%s"; got something else (in "%s").', 'PhabricatorAuthFactorResult', get_class($this))); } return $result; } abstract protected function newResultFromChallengeResponse( PhabricatorAuthFactorConfig $config, PhabricatorUser $viewer, AphrontRequest $request, array $challenges); final protected function newAutomaticControl( PhabricatorAuthFactorResult $result) { $is_error = $result->getIsError(); if ($is_error) { return $this->newErrorControl($result); } $is_continue = $result->getIsContinue(); if ($is_continue) { return $this->newContinueControl($result); } $is_answered = (bool)$result->getAnsweredChallenge(); if ($is_answered) { return $this->newAnsweredControl($result); } $is_wait = $result->getIsWait(); if ($is_wait) { return $this->newWaitControl($result); } return null; } private function newWaitControl( PhabricatorAuthFactorResult $result) { $error = $result->getErrorMessage(); $icon = $result->getIcon(); if (!$icon) { $icon = id(new PHUIIconView()) ->setIcon('fa-clock-o', 'red'); } return id(new PHUIFormTimerControl()) ->setIcon($icon) ->appendChild($error) ->setError(pht('Wait')); } private function newAnsweredControl( PhabricatorAuthFactorResult $result) { $icon = $result->getIcon(); if (!$icon) { $icon = id(new PHUIIconView()) ->setIcon('fa-check-circle-o', 'green'); } return id(new PHUIFormTimerControl()) ->setIcon($icon) ->appendChild( pht('You responded to this challenge correctly.')); } private function newErrorControl( PhabricatorAuthFactorResult $result) { $error = $result->getErrorMessage(); $icon = $result->getIcon(); if (!$icon) { $icon = id(new PHUIIconView()) ->setIcon('fa-times', 'red'); } return id(new PHUIFormTimerControl()) ->setIcon($icon) ->appendChild($error) ->setError(pht('Error')); } private function newContinueControl( PhabricatorAuthFactorResult $result) { $error = $result->getErrorMessage(); $icon = $result->getIcon(); if (!$icon) { $icon = id(new PHUIIconView()) ->setIcon('fa-commenting', 'green'); } $control = id(new PHUIFormTimerControl()) ->setIcon($icon) ->appendChild($error); $status_challenge = $result->getStatusChallenge(); if ($status_challenge) { $id = $status_challenge->getID(); $uri = "/auth/mfa/challenge/status/{$id}/"; $control->setUpdateURI($uri); } return $control; } /* -( Synchronizing New Factors )------------------------------------------ */ final protected function loadMFASyncToken( PhabricatorAuthFactorProvider $provider, AphrontRequest $request, AphrontFormView $form, PhabricatorUser $user) { // If the form included a synchronization key, load the corresponding // token. The user must synchronize to a key we generated because this // raises the barrier to theoretical attacks where an attacker might // provide a known key for factors like TOTP. // (We store and verify the hash of the key, not the key itself, to limit // how useful the data in the table is to an attacker.) $sync_type = PhabricatorAuthMFASyncTemporaryTokenType::TOKENTYPE; $sync_token = null; $sync_key = $request->getStr($this->getMFASyncTokenFormKey()); if (phutil_nonempty_string($sync_key)) { $sync_key_digest = PhabricatorHash::digestWithNamedKey( $sync_key, PhabricatorAuthMFASyncTemporaryTokenType::DIGEST_KEY); $sync_token = id(new PhabricatorAuthTemporaryTokenQuery()) ->setViewer($user) ->withTokenResources(array($user->getPHID())) ->withTokenTypes(array($sync_type)) ->withExpired(false) ->withTokenCodes(array($sync_key_digest)) ->executeOne(); } if (!$sync_token) { // Don't generate a new sync token if there are too many outstanding // tokens already. This is mostly relevant for push factors like SMS, // where generating a token has the side effect of sending a user a // message. $outstanding_limit = 10; $outstanding_tokens = id(new PhabricatorAuthTemporaryTokenQuery()) ->setViewer($user) ->withTokenResources(array($user->getPHID())) ->withTokenTypes(array($sync_type)) ->withExpired(false) ->execute(); if (count($outstanding_tokens) > $outstanding_limit) { throw new Exception( pht( 'Your account has too many outstanding, incomplete MFA '. 'synchronization attempts. Wait an hour and try again.')); } $now = PhabricatorTime::getNow(); $sync_key = Filesystem::readRandomCharacters(32); $sync_key_digest = PhabricatorHash::digestWithNamedKey( $sync_key, PhabricatorAuthMFASyncTemporaryTokenType::DIGEST_KEY); $sync_ttl = $this->getMFASyncTokenTTL(); $sync_token = id(new PhabricatorAuthTemporaryToken()) ->setIsNewTemporaryToken(true) ->setTokenResource($user->getPHID()) ->setTokenType($sync_type) ->setTokenCode($sync_key_digest) ->setTokenExpires($now + $sync_ttl); $properties = $this->newMFASyncTokenProperties( $provider, $user); if ($this->isAuthResult($properties)) { return $properties; } foreach ($properties as $key => $value) { $sync_token->setTemporaryTokenProperty($key, $value); } $sync_token->save(); } $form->addHiddenInput($this->getMFASyncTokenFormKey(), $sync_key); return $sync_token; } protected function newMFASyncTokenProperties( PhabricatorAuthFactorProvider $provider, PhabricatorUser $user) { return array(); } private function getMFASyncTokenFormKey() { return 'sync.key'; } private function getMFASyncTokenTTL() { return phutil_units('1 hour in seconds'); } final protected function getChallengeForCurrentContext( PhabricatorAuthFactorConfig $config, PhabricatorUser $viewer, array $challenges) { $session_phid = $viewer->getSession()->getPHID(); $engine = $config->getSessionEngine(); $workflow_key = $engine->getWorkflowKey(); foreach ($challenges as $challenge) { if ($challenge->getSessionPHID() !== $session_phid) { continue; } if ($challenge->getWorkflowKey() !== $workflow_key) { continue; } if ($challenge->getIsCompleted()) { continue; } if ($challenge->getIsReusedChallenge()) { continue; } return $challenge; } return null; } /** * @phutil-external-symbol class QRcode */ final protected function newQRCode($uri) { $root = dirname(phutil_get_library_root('phabricator')); require_once $root.'/externals/phpqrcode/phpqrcode.php'; $lines = QRcode::text($uri); $total_width = 240; $cell_size = floor($total_width / count($lines)); $rows = array(); foreach ($lines as $line) { $cells = array(); for ($ii = 0; $ii < strlen($line); $ii++) { if ($line[$ii] == '1') { $color = '#000'; } else { $color = '#fff'; } $cells[] = phutil_tag( 'td', array( 'width' => $cell_size, 'height' => $cell_size, 'style' => 'background: '.$color, ), ''); } $rows[] = phutil_tag('tr', array(), $cells); } return phutil_tag( 'table', array( 'style' => 'margin: 24px auto;', ), $rows); } final protected function getInstallDisplayName() { $uri = PhabricatorEnv::getURI('/'); $uri = new PhutilURI($uri); return $uri->getDomain(); } final protected function getChallengeResponseParameterName( PhabricatorAuthFactorConfig $config) { return $this->getParameterName($config, 'mfa.response'); } final protected function getChallengeResponseFromRequest( PhabricatorAuthFactorConfig $config, AphrontRequest $request) { $name = $this->getChallengeResponseParameterName($config); $value = $request->getStr($name); $value = (string)$value; $value = trim($value); return $value; } final protected function hasCSRF(PhabricatorAuthFactorConfig $config) { $engine = $config->getSessionEngine(); $request = $engine->getRequest(); if (!$request->isHTTPPost()) { return false; } return $request->validateCSRF(); } final protected function loadConfigurationsForProvider( PhabricatorAuthFactorProvider $provider, PhabricatorUser $user) { return id(new PhabricatorAuthFactorConfigQuery()) ->setViewer($user) ->withUserPHIDs(array($user->getPHID())) ->withFactorProviderPHIDs(array($provider->getPHID())) ->execute(); } final protected function isAuthResult($object) { return ($object instanceof PhabricatorAuthFactorResult); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/factor/PhabricatorTOTPAuthFactor.php
src/applications/auth/factor/PhabricatorTOTPAuthFactor.php
<?php final class PhabricatorTOTPAuthFactor extends PhabricatorAuthFactor { public function getFactorKey() { return 'totp'; } public function getFactorName() { return pht('Mobile Phone App (TOTP)'); } public function getFactorShortName() { return pht('TOTP'); } public function getFactorCreateHelp() { return pht( 'Allow users to attach a mobile authenticator application (like '. 'Google Authenticator) to their account.'); } public function getFactorDescription() { return pht( 'Attach a mobile authenticator application (like Authy '. 'or Google Authenticator) to your account. When you need to '. 'authenticate, you will enter a code shown on your phone.'); } public function getEnrollDescription( PhabricatorAuthFactorProvider $provider, PhabricatorUser $user) { return pht( 'To add a TOTP factor to your account, you will first need to install '. 'a mobile authenticator application on your phone. Two applications '. 'which work well are **Google Authenticator** and **Authy**, but any '. 'other TOTP application should also work.'. "\n\n". 'If you haven\'t already, download and install a TOTP application on '. 'your phone now. Once you\'ve launched the application and are ready '. 'to add a new TOTP code, continue to the next step.'); } public function getConfigurationListDetails( PhabricatorAuthFactorConfig $config, PhabricatorAuthFactorProvider $provider, PhabricatorUser $viewer) { $bits = strlen($config->getFactorSecret()) * 8; return pht('%d-Bit Secret', $bits); } public function processAddFactorForm( PhabricatorAuthFactorProvider $provider, AphrontFormView $form, AphrontRequest $request, PhabricatorUser $user) { $sync_token = $this->loadMFASyncToken( $provider, $request, $form, $user); $secret = $sync_token->getTemporaryTokenProperty('secret'); $code = $request->getStr('totpcode'); $e_code = true; if (!$sync_token->getIsNewTemporaryToken()) { $okay = (bool)$this->getTimestepAtWhichResponseIsValid( $this->getAllowedTimesteps($this->getCurrentTimestep()), new PhutilOpaqueEnvelope($secret), $code); if ($okay) { $config = $this->newConfigForUser($user) ->setFactorName(pht('Mobile App (TOTP)')) ->setFactorSecret($secret) ->setMFASyncToken($sync_token); return $config; } else { if (!strlen($code)) { $e_code = pht('Required'); } else { $e_code = pht('Invalid'); } } } $form->appendInstructions( pht( 'Scan the QR code or manually enter the key shown below into the '. 'application.')); $prod_uri = new PhutilURI(PhabricatorEnv::getProductionURI('/')); $issuer = $prod_uri->getDomain(); $uri = urisprintf( 'otpauth://totp/%s:%s?secret=%s&issuer=%s', $issuer, $user->getUsername(), $secret, $issuer); $qrcode = $this->newQRCode($uri); $form->appendChild($qrcode); $form->appendChild( id(new AphrontFormStaticControl()) ->setLabel(pht('Key')) ->setValue(phutil_tag('strong', array(), $secret))); $form->appendInstructions( pht( '(If given an option, select that this key is "Time Based", not '. '"Counter Based".)')); $form->appendInstructions( pht( 'After entering the key, the application should display a numeric '. 'code. Enter that code below to confirm that you have configured '. 'the authenticator correctly:')); $form->appendChild( id(new PHUIFormNumberControl()) ->setLabel(pht('TOTP Code')) ->setName('totpcode') ->setValue($code) ->setAutofocus(true) ->setError($e_code)); } protected function newIssuedChallenges( PhabricatorAuthFactorConfig $config, PhabricatorUser $viewer, array $challenges) { $current_step = $this->getCurrentTimestep(); // If we already issued a valid challenge, don't issue a new one. if ($challenges) { return array(); } // Otherwise, generate a new challenge for the current timestep and compute // the TTL. // When computing the TTL, note that we accept codes within a certain // window of the challenge timestep to account for clock skew and users // needing time to enter codes. // We don't want this challenge to expire until after all valid responses // to it are no longer valid responses to any other challenge we might // issue in the future. If the challenge expires too quickly, we may issue // a new challenge which can accept the same TOTP code response. // This means that we need to keep this challenge alive for double the // window size: if we're currently at timestep 3, the user might respond // with the code for timestep 5. This is valid, since timestep 5 is within // the window for timestep 3. // But the code for timestep 5 can be used to respond at timesteps 3, 4, 5, // 6, and 7. To prevent any valid response to this challenge from being // used again, we need to keep this challenge active until timestep 8. $window_size = $this->getTimestepWindowSize(); $step_duration = $this->getTimestepDuration(); $ttl_steps = ($window_size * 2) + 1; $ttl_seconds = ($ttl_steps * $step_duration); return array( $this->newChallenge($config, $viewer) ->setChallengeKey($current_step) ->setChallengeTTL(PhabricatorTime::getNow() + $ttl_seconds), ); } public function renderValidateFactorForm( PhabricatorAuthFactorConfig $config, AphrontFormView $form, PhabricatorUser $viewer, PhabricatorAuthFactorResult $result) { $control = $this->newAutomaticControl($result); if (!$control) { $value = $result->getValue(); $error = $result->getErrorMessage(); $name = $this->getChallengeResponseParameterName($config); $control = id(new PHUIFormNumberControl()) ->setName($name) ->setDisableAutocomplete(true) ->setAutofocus(true) ->setValue($value) ->setError($error); } $control ->setLabel(pht('App Code')) ->setCaption(pht('Factor Name: %s', $config->getFactorName())); $form->appendChild($control); } public function getRequestHasChallengeResponse( PhabricatorAuthFactorConfig $config, AphrontRequest $request) { $value = $this->getChallengeResponseFromRequest($config, $request); return (bool)strlen($value); } protected function newResultFromIssuedChallenges( PhabricatorAuthFactorConfig $config, PhabricatorUser $viewer, array $challenges) { // If we've already issued a challenge at the current timestep or any // nearby timestep, require that it was issued to the current session. // This is defusing attacks where you (broadly) look at someone's phone // and type the code in more quickly than they do. $session_phid = $viewer->getSession()->getPHID(); $now = PhabricatorTime::getNow(); $engine = $config->getSessionEngine(); $workflow_key = $engine->getWorkflowKey(); $current_timestep = $this->getCurrentTimestep(); foreach ($challenges as $challenge) { $challenge_timestep = (int)$challenge->getChallengeKey(); $wait_duration = ($challenge->getChallengeTTL() - $now) + 1; if ($challenge->getSessionPHID() !== $session_phid) { return $this->newResult() ->setIsWait(true) ->setErrorMessage( pht( 'This factor recently issued a challenge to a different login '. 'session. Wait %s second(s) for the code to cycle, then try '. 'again.', new PhutilNumber($wait_duration))); } if ($challenge->getWorkflowKey() !== $workflow_key) { return $this->newResult() ->setIsWait(true) ->setErrorMessage( pht( 'This factor recently issued a challenge for a different '. 'workflow. Wait %s second(s) for the code to cycle, then try '. 'again.', new PhutilNumber($wait_duration))); } // If the current realtime timestep isn't a valid response to the current // challenge but the challenge hasn't expired yet, we're locking out // the factor to prevent challenge windows from overlapping. Let the user // know that they should wait for a new challenge. $challenge_timesteps = $this->getAllowedTimesteps($challenge_timestep); if (!isset($challenge_timesteps[$current_timestep])) { return $this->newResult() ->setIsWait(true) ->setErrorMessage( pht( 'This factor recently issued a challenge which has expired. '. 'A new challenge can not be issued yet. Wait %s second(s) for '. 'the code to cycle, then try again.', new PhutilNumber($wait_duration))); } if ($challenge->getIsReusedChallenge()) { return $this->newResult() ->setIsWait(true) ->setErrorMessage( pht( 'You recently provided a response to this factor. Responses '. 'may not be reused. Wait %s second(s) for the code to cycle, '. 'then try again.', new PhutilNumber($wait_duration))); } } return null; } protected function newResultFromChallengeResponse( PhabricatorAuthFactorConfig $config, PhabricatorUser $viewer, AphrontRequest $request, array $challenges) { $code = $this->getChallengeResponseFromRequest( $config, $request); $result = $this->newResult() ->setValue($code); // We expect to reach TOTP validation with exactly one valid challenge. if (count($challenges) !== 1) { throw new Exception( pht( 'Reached TOTP challenge validation with an unexpected number of '. 'unexpired challenges (%d), expected exactly one.', phutil_count($challenges))); } $challenge = head($challenges); // If the client has already provided a valid answer to this challenge and // submitted a token proving they answered it, we're all set. if ($challenge->getIsAnsweredChallenge()) { return $result->setAnsweredChallenge($challenge); } $challenge_timestep = (int)$challenge->getChallengeKey(); $current_timestep = $this->getCurrentTimestep(); $challenge_timesteps = $this->getAllowedTimesteps($challenge_timestep); $current_timesteps = $this->getAllowedTimesteps($current_timestep); // We require responses be both valid for the challenge and valid for the // current timestep. A longer challenge TTL doesn't let you use older // codes for a longer period of time. $valid_timestep = $this->getTimestepAtWhichResponseIsValid( array_intersect_key($challenge_timesteps, $current_timesteps), new PhutilOpaqueEnvelope($config->getFactorSecret()), $code); if ($valid_timestep) { $ttl = PhabricatorTime::getNow() + 60; $challenge ->setProperty('totp.timestep', $valid_timestep) ->markChallengeAsAnswered($ttl); $result->setAnsweredChallenge($challenge); } else { if (strlen($code)) { $error_message = pht('Invalid'); } else { $error_message = pht('Required'); } $result->setErrorMessage($error_message); } return $result; } public static function generateNewTOTPKey() { return strtoupper(Filesystem::readRandomCharacters(32)); } public static function base32Decode($buf) { $buf = strtoupper($buf); $map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; $map = str_split($map); $map = array_flip($map); $out = ''; $len = strlen($buf); $acc = 0; $bits = 0; for ($ii = 0; $ii < $len; $ii++) { $chr = $buf[$ii]; $val = $map[$chr]; $acc = $acc << 5; $acc = $acc + $val; $bits += 5; if ($bits >= 8) { $bits = $bits - 8; $out .= chr(($acc & (0xFF << $bits)) >> $bits); } } return $out; } public static function getTOTPCode(PhutilOpaqueEnvelope $key, $timestamp) { $binary_timestamp = pack('N*', 0).pack('N*', $timestamp); $binary_key = self::base32Decode($key->openEnvelope()); $hash = hash_hmac('sha1', $binary_timestamp, $binary_key, true); // See RFC 4226. $offset = ord($hash[19]) & 0x0F; $code = ((ord($hash[$offset + 0]) & 0x7F) << 24) | ((ord($hash[$offset + 1]) & 0xFF) << 16) | ((ord($hash[$offset + 2]) & 0xFF) << 8) | ((ord($hash[$offset + 3]) ) ); $code = ($code % 1000000); $code = str_pad($code, 6, '0', STR_PAD_LEFT); return $code; } private function getTimestepDuration() { return 30; } private function getCurrentTimestep() { $duration = $this->getTimestepDuration(); return (int)(PhabricatorTime::getNow() / $duration); } private function getAllowedTimesteps($at_timestep) { $window = $this->getTimestepWindowSize(); $range = range($at_timestep - $window, $at_timestep + $window); return array_fuse($range); } private function getTimestepWindowSize() { // The user is allowed to provide a code from the recent past or the // near future to account for minor clock skew between the client // and server, and the time it takes to actually enter a code. return 1; } private function getTimestepAtWhichResponseIsValid( array $timesteps, PhutilOpaqueEnvelope $key, $code) { foreach ($timesteps as $timestep) { $expect_code = self::getTOTPCode($key, $timestep); if (phutil_hashes_are_identical($code, $expect_code)) { return $timestep; } } return null; } protected function newMFASyncTokenProperties( PhabricatorAuthFactorProvider $providerr, PhabricatorUser $user) { return array( 'secret' => self::generateNewTOTPKey(), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/factor/__tests__/PhabricatorTOTPAuthFactorTestCase.php
src/applications/auth/factor/__tests__/PhabricatorTOTPAuthFactorTestCase.php
<?php final class PhabricatorTOTPAuthFactorTestCase extends PhabricatorTestCase { public function testTOTPCodeGeneration() { $tests = array( array( 'AAAABBBBCCCCDDDD', 46620383, '724492', ), array( 'AAAABBBBCCCCDDDD', 46620390, '935803', ), array( 'Z3RFWEFJN233R23P', 46620398, '273030', ), // This is testing the case where the code has leading zeroes. array( 'Z3RFWEFJN233R23W', 46620399, '072346', ), ); foreach ($tests as $test) { list($key, $time, $code) = $test; $this->assertEqual( $code, PhabricatorTOTPAuthFactor::getTOTPCode( new PhutilOpaqueEnvelope($key), $time)); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/factor/__tests__/PhabricatorAuthFactorTestCase.php
src/applications/auth/factor/__tests__/PhabricatorAuthFactorTestCase.php
<?php final class PhabricatorAuthFactorTestCase extends PhabricatorTestCase { public function testGetAllFactors() { PhabricatorAuthFactor::getAllFactors(); $this->assertTrue(true); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/factor/__tests__/PhabricatorAuthInviteTestCase.php
src/applications/auth/factor/__tests__/PhabricatorAuthInviteTestCase.php
<?php final class PhabricatorAuthInviteTestCase extends PhabricatorTestCase { protected function getPhabricatorTestCaseConfiguration() { return array( self::PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES => true, ); } /** * Test that invalid invites can not be accepted. */ public function testInvalidInvite() { $viewer = $this->generateUser(); $engine = $this->generateEngine($viewer); $caught = null; try { $engine->processInviteCode('asdf1234'); } catch (PhabricatorAuthInviteInvalidException $ex) { $caught = $ex; } $this->assertTrue($caught instanceof Exception); } /** * Test that invites can be accepted exactly once. */ public function testDuplicateInvite() { $author = $this->generateUser(); $viewer = $this->generateUser(); $address = Filesystem::readRandomCharacters(16).'@example.com'; $invite = id(new PhabricatorAuthInvite()) ->setAuthorPHID($author->getPHID()) ->setEmailAddress($address) ->save(); $engine = $this->generateEngine($viewer); $engine->setUserHasConfirmedVerify(true); $caught = null; try { $result = $engine->processInviteCode($invite->getVerificationCode()); } catch (Exception $ex) { $caught = $ex; } // This first time should accept the invite and verify the address. $this->assertTrue( ($caught instanceof PhabricatorAuthInviteRegisteredException)); try { $result = $engine->processInviteCode($invite->getVerificationCode()); } catch (Exception $ex) { $caught = $ex; } // The second time through, the invite should not be acceptable. $this->assertTrue( ($caught instanceof PhabricatorAuthInviteInvalidException)); } /** * Test easy invite cases, where the email is not anywhere in the system. */ public function testInviteWithNewEmail() { $expect_map = array( 'out' => array( null, null, ), 'in' => array( 'PhabricatorAuthInviteVerifyException', 'PhabricatorAuthInviteRegisteredException', ), ); $author = $this->generateUser(); $logged_in = $this->generateUser(); $logged_out = new PhabricatorUser(); foreach (array('out', 'in') as $is_logged_in) { foreach (array(0, 1) as $should_verify) { $address = Filesystem::readRandomCharacters(16).'@example.com'; $invite = id(new PhabricatorAuthInvite()) ->setAuthorPHID($author->getPHID()) ->setEmailAddress($address) ->save(); switch ($is_logged_in) { case 'out': $viewer = $logged_out; break; case 'in': $viewer = $logged_in; break; } $engine = $this->generateEngine($viewer); $engine->setUserHasConfirmedVerify($should_verify); $caught = null; try { $result = $engine->processInviteCode($invite->getVerificationCode()); } catch (Exception $ex) { $caught = $ex; } $expect = $expect_map[$is_logged_in]; $expect = $expect[$should_verify]; $this->assertEqual( ($expect !== null), ($caught instanceof Exception), pht( 'user=%s, should_verify=%s', $is_logged_in, $should_verify)); if ($expect === null) { $this->assertEqual($invite->getPHID(), $result->getPHID()); } else { $this->assertEqual( $expect, get_class($caught), pht('Actual exception: %s', $caught->getMessage())); } } } } /** * Test hard invite cases, where the email is already known and attached * to some user account. */ public function testInviteWithKnownEmail() { // This tests all permutations of: // // - Is the user logged out, logged in with a different account, or // logged in with the correct account? // - Is the address verified, or unverified? // - Is the address primary, or nonprimary? // - Has the user confirmed that they want to verify the address? $expect_map = array( 'out' => array( array( array( // For example, this corresponds to a logged out user trying to // follow an invite with an unverified, nonprimary address, and // they haven't clicked the "Verify" button yet. We ask them to // verify that they want to register a new account. 'PhabricatorAuthInviteVerifyException', // In this case, they have clicked the verify button. The engine // continues the workflow. null, ), array( // And so on. All of the rest of these cases cover the other // permutations. 'PhabricatorAuthInviteLoginException', 'PhabricatorAuthInviteLoginException', ), ), array( array( 'PhabricatorAuthInviteLoginException', 'PhabricatorAuthInviteLoginException', ), array( 'PhabricatorAuthInviteLoginException', 'PhabricatorAuthInviteLoginException', ), ), ), 'in' => array( array( array( 'PhabricatorAuthInviteVerifyException', array(true, 'PhabricatorAuthInviteRegisteredException'), ), array( 'PhabricatorAuthInviteAccountException', 'PhabricatorAuthInviteAccountException', ), ), array( array( 'PhabricatorAuthInviteAccountException', 'PhabricatorAuthInviteAccountException', ), array( 'PhabricatorAuthInviteAccountException', 'PhabricatorAuthInviteAccountException', ), ), ), 'same' => array( array( array( 'PhabricatorAuthInviteVerifyException', array(true, 'PhabricatorAuthInviteRegisteredException'), ), array( 'PhabricatorAuthInviteVerifyException', array(true, 'PhabricatorAuthInviteRegisteredException'), ), ), array( array( 'PhabricatorAuthInviteRegisteredException', 'PhabricatorAuthInviteRegisteredException', ), array( 'PhabricatorAuthInviteRegisteredException', 'PhabricatorAuthInviteRegisteredException', ), ), ), ); $author = $this->generateUser(); $logged_in = $this->generateUser(); $logged_out = new PhabricatorUser(); foreach (array('out', 'in', 'same') as $is_logged_in) { foreach (array(0, 1) as $is_verified) { foreach (array(0, 1) as $is_primary) { foreach (array(0, 1) as $should_verify) { $other = $this->generateUser(); switch ($is_logged_in) { case 'out': $viewer = $logged_out; break; case 'in'; $viewer = $logged_in; break; case 'same': $viewer = clone $other; break; } $email = $this->generateEmail($other, $is_verified, $is_primary); $invite = id(new PhabricatorAuthInvite()) ->setAuthorPHID($author->getPHID()) ->setEmailAddress($email->getAddress()) ->save(); $code = $invite->getVerificationCode(); $engine = $this->generateEngine($viewer); $engine->setUserHasConfirmedVerify($should_verify); $caught = null; try { $result = $engine->processInviteCode($code); } catch (Exception $ex) { $caught = $ex; } $expect = $expect_map[$is_logged_in]; $expect = $expect[$is_verified]; $expect = $expect[$is_primary]; $expect = $expect[$should_verify]; if (is_array($expect)) { list($expect_reassign, $expect_exception) = $expect; } else { $expect_reassign = false; $expect_exception = $expect; } $case_info = pht( 'user=%s, verified=%s, primary=%s, should_verify=%s', $is_logged_in, $is_verified, $is_primary, $should_verify); $this->assertEqual( ($expect_exception !== null), ($caught instanceof Exception), $case_info); if ($expect_exception === null) { $this->assertEqual($invite->getPHID(), $result->getPHID()); } else { $this->assertEqual( $expect_exception, get_class($caught), pht('%s, exception=%s', $case_info, $caught->getMessage())); } if ($expect_reassign) { $email->reload(); $this->assertEqual( $viewer->getPHID(), $email->getUserPHID(), pht( 'Expected email address reassignment (%s).', $case_info)); } switch ($expect_exception) { case 'PhabricatorAuthInviteRegisteredException': $invite->reload(); $this->assertEqual( $viewer->getPHID(), $invite->getAcceptedByPHID(), pht( 'Expected invite accepted (%s).', $case_info)); break; } } } } } } private function generateUser() { return $this->generateNewTestUser(); } private function generateEngine(PhabricatorUser $viewer) { return id(new PhabricatorAuthInviteEngine()) ->setViewer($viewer); } private function generateEmail( PhabricatorUser $user, $is_verified, $is_primary) { // NOTE: We're being a little bit sneaky here because UserEditor will not // let you make an unverified address a primary account address, and // the test user will already have a verified primary address. $email = id(new PhabricatorUserEmail()) ->setAddress(Filesystem::readRandomCharacters(16).'@example.com') ->setIsVerified((int)($is_verified || $is_primary)) ->setIsPrimary(0); $editor = id(new PhabricatorUserEditor()) ->setActor($user); $editor->addEmail($user, $email); if ($is_primary) { $editor->changePrimaryEmail($user, $email); } $email->setIsVerified((int)$is_verified); $email->save(); return $email; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/__tests__/PhabricatorAuthPasswordTestCase.php
src/applications/auth/__tests__/PhabricatorAuthPasswordTestCase.php
<?php final class PhabricatorAuthPasswordTestCase extends PhabricatorTestCase { protected function getPhabricatorTestCaseConfiguration() { return array( self::PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES => true, ); } public function testCompare() { $password1 = new PhutilOpaqueEnvelope('hunter2'); $password2 = new PhutilOpaqueEnvelope('hunter3'); $user = $this->generateNewTestUser(); $type = PhabricatorAuthPassword::PASSWORD_TYPE_TEST; $pass = PhabricatorAuthPassword::initializeNewPassword($user, $type) ->setPassword($password1, $user) ->save(); $this->assertTrue( $pass->comparePassword($password1, $user), pht('Good password should match.')); $this->assertFalse( $pass->comparePassword($password2, $user), pht('Bad password should not match.')); } public function testPasswordEngine() { $password1 = new PhutilOpaqueEnvelope('the quick'); $password2 = new PhutilOpaqueEnvelope('brown fox'); $user = $this->generateNewTestUser(); $test_type = PhabricatorAuthPassword::PASSWORD_TYPE_TEST; $account_type = PhabricatorAuthPassword::PASSWORD_TYPE_ACCOUNT; $content_source = $this->newContentSource(); $engine = id(new PhabricatorAuthPasswordEngine()) ->setViewer($user) ->setContentSource($content_source) ->setPasswordType($test_type) ->setObject($user); $account_engine = id(new PhabricatorAuthPasswordEngine()) ->setViewer($user) ->setContentSource($content_source) ->setPasswordType($account_type) ->setObject($user); // We haven't set any passwords yet, so both passwords should be // invalid. $this->assertFalse($engine->isValidPassword($password1)); $this->assertFalse($engine->isValidPassword($password2)); $pass = PhabricatorAuthPassword::initializeNewPassword($user, $test_type) ->setPassword($password1, $user) ->save(); // The password should now be valid. $this->assertTrue($engine->isValidPassword($password1)); $this->assertFalse($engine->isValidPassword($password2)); // But, since the password is a "test" password, it should not be a valid // "account" password. $this->assertFalse($account_engine->isValidPassword($password1)); $this->assertFalse($account_engine->isValidPassword($password2)); // Both passwords are unique for the "test" engine, since an active // password of a given type doesn't collide with itself. $this->assertTrue($engine->isUniquePassword($password1)); $this->assertTrue($engine->isUniquePassword($password2)); // The "test" password is no longer unique for the "account" engine. $this->assertFalse($account_engine->isUniquePassword($password1)); $this->assertTrue($account_engine->isUniquePassword($password2)); $this->revokePassword($user, $pass); // Now that we've revoked the password, it should no longer be valid. $this->assertFalse($engine->isValidPassword($password1)); $this->assertFalse($engine->isValidPassword($password2)); // But it should be a revoked password. $this->assertTrue($engine->isRevokedPassword($password1)); $this->assertFalse($engine->isRevokedPassword($password2)); // It should be revoked for both roles: revoking a "test" password also // prevents you from choosing it as a new "account" password. $this->assertTrue($account_engine->isRevokedPassword($password1)); $this->assertFalse($account_engine->isValidPassword($password2)); // The revoked password makes this password non-unique for all account // types. $this->assertFalse($engine->isUniquePassword($password1)); $this->assertTrue($engine->isUniquePassword($password2)); $this->assertFalse($account_engine->isUniquePassword($password1)); $this->assertTrue($account_engine->isUniquePassword($password2)); } public function testPasswordBlocklisting() { $user = $this->generateNewTestUser(); $user ->setUsername('iasimov') ->setRealName('Isaac Asimov') ->save(); $test_type = PhabricatorAuthPassword::PASSWORD_TYPE_TEST; $content_source = $this->newContentSource(); $engine = id(new PhabricatorAuthPasswordEngine()) ->setViewer($user) ->setContentSource($content_source) ->setPasswordType($test_type) ->setObject($user); $env = PhabricatorEnv::beginScopedEnv(); $env->overrideEnvConfig('account.minimum-password-length', 4); $passwords = array( 'a23li432m9mdf' => true, // Empty. '' => false, // Password length tests. 'xh3' => false, 'xh32' => true, // In common password blocklist. 'password1' => false, // Tests for the account identifier blocklist. 'isaac' => false, 'iasimov' => false, 'iasimov1' => false, 'asimov' => false, 'iSaAc' => false, '32IASIMOV' => false, 'i-am-iasimov-this-is-my-long-strong-password' => false, 'iasimo' => false, // These are okay: although they're visually similar, they aren't mutual // substrings of any identifier. 'iasimo1' => true, 'isa1mov' => true, ); foreach ($passwords as $password => $expect) { $this->assertBlocklistedPassword($engine, $password, $expect); } } private function assertBlocklistedPassword( PhabricatorAuthPasswordEngine $engine, $raw_password, $expect_valid) { $envelope_1 = new PhutilOpaqueEnvelope($raw_password); $envelope_2 = new PhutilOpaqueEnvelope($raw_password); $caught = null; try { $engine->checkNewPassword($envelope_1, $envelope_2); } catch (PhabricatorAuthPasswordException $exception) { $caught = $exception; } $this->assertEqual( $expect_valid, !($caught instanceof PhabricatorAuthPasswordException), pht('Validity of password "%s".', $raw_password)); } public function testPasswordUpgrade() { $weak_hasher = new PhabricatorIteratedMD5PasswordHasher(); // Make sure we have two different hashers, and that the second one is // stronger than iterated MD5. The most common reason this would fail is // if an install does not have bcrypt available. $strong_hasher = PhabricatorPasswordHasher::getBestHasher(); if ($strong_hasher->getStrength() <= $weak_hasher->getStrength()) { $this->assertSkipped( pht( 'Multiple password hashers of different strengths are not '. 'available, so hash upgrading can not be tested.')); } $envelope = new PhutilOpaqueEnvelope('lunar1997'); $user = $this->generateNewTestUser(); $type = PhabricatorAuthPassword::PASSWORD_TYPE_TEST; $content_source = $this->newContentSource(); $engine = id(new PhabricatorAuthPasswordEngine()) ->setViewer($user) ->setContentSource($content_source) ->setPasswordType($type) ->setObject($user); $password = PhabricatorAuthPassword::initializeNewPassword($user, $type) ->setPasswordWithHasher($envelope, $user, $weak_hasher) ->save(); $weak_name = $weak_hasher->getHashName(); $strong_name = $strong_hasher->getHashName(); // Since we explicitly used the weak hasher, the password should have // been hashed with it. $actual_hasher = $password->getHasher(); $this->assertEqual($weak_name, $actual_hasher->getHashName()); $is_valid = $engine ->setUpgradeHashers(false) ->isValidPassword($envelope, $user); $password->reload(); // Since we disabled hasher upgrading, the password should not have been // rehashed. $this->assertTrue($is_valid); $actual_hasher = $password->getHasher(); $this->assertEqual($weak_name, $actual_hasher->getHashName()); $is_valid = $engine ->setUpgradeHashers(true) ->isValidPassword($envelope, $user); $password->reload(); // Now that we enabled hasher upgrading, the password should have been // automatically rehashed into the stronger format. $this->assertTrue($is_valid); $actual_hasher = $password->getHasher(); $this->assertEqual($strong_name, $actual_hasher->getHashName()); // We should also have an "upgrade" transaction in the transaction record // now which records the two hasher names. $xactions = id(new PhabricatorAuthPasswordTransactionQuery()) ->setViewer($user) ->withObjectPHIDs(array($password->getPHID())) ->withTransactionTypes( array( PhabricatorAuthPasswordUpgradeTransaction::TRANSACTIONTYPE, )) ->execute(); $this->assertEqual(1, count($xactions)); $xaction = head($xactions); $this->assertEqual($weak_name, $xaction->getOldValue()); $this->assertEqual($strong_name, $xaction->getNewValue()); $is_valid = $engine ->isValidPassword($envelope, $user); // Finally, the password should still be valid after all the dust has // settled. $this->assertTrue($is_valid); } private function revokePassword( PhabricatorUser $actor, PhabricatorAuthPassword $password) { $content_source = $this->newContentSource(); $revoke_type = PhabricatorAuthPasswordRevokeTransaction::TRANSACTIONTYPE; $xactions = array(); $xactions[] = $password->getApplicationTransactionTemplate() ->setTransactionType($revoke_type) ->setNewValue(true); $editor = $password->getApplicationTransactionEditor() ->setActor($actor) ->setContinueOnNoEffect(true) ->setContinueOnMissingFields(true) ->setContentSource($content_source) ->applyTransactions($password, $xactions); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/__tests__/PhabricatorAuthSSHKeyTestCase.php
src/applications/auth/__tests__/PhabricatorAuthSSHKeyTestCase.php
<?php final class PhabricatorAuthSSHKeyTestCase extends PhabricatorTestCase { protected function getPhabricatorTestCaseConfiguration() { return array( self::PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES => true, ); } public function testRevokeSSHKey() { $user = $this->generateNewTestUser(); $raw_key = 'ssh-rsa hunter2'; $ssh_key = PhabricatorAuthSSHKey::initializeNewSSHKey($user, $user); // Add the key to the user's account. $xactions = array(); $xactions[] = $ssh_key->getApplicationTransactionTemplate() ->setTransactionType(PhabricatorAuthSSHKeyTransaction::TYPE_NAME) ->setNewValue('key1'); $xactions[] = $ssh_key->getApplicationTransactionTemplate() ->setTransactionType(PhabricatorAuthSSHKeyTransaction::TYPE_KEY) ->setNewValue($raw_key); $this->applyTransactions($user, $ssh_key, $xactions); $ssh_key->reload(); $this->assertTrue((bool)$ssh_key->getIsActive()); // Revoke it. $xactions = array(); $xactions[] = $ssh_key->getApplicationTransactionTemplate() ->setTransactionType(PhabricatorAuthSSHKeyTransaction::TYPE_DEACTIVATE) ->setNewValue(true); $this->applyTransactions($user, $ssh_key, $xactions); $ssh_key->reload(); $this->assertFalse((bool)$ssh_key->getIsActive()); // Try to add the revoked key back. This should fail with a validation // error because the key was previously revoked by the user. $revoked_key = PhabricatorAuthSSHKey::initializeNewSSHKey($user, $user); $xactions = array(); $xactions[] = $ssh_key->getApplicationTransactionTemplate() ->setTransactionType(PhabricatorAuthSSHKeyTransaction::TYPE_NAME) ->setNewValue('key2'); $xactions[] = $ssh_key->getApplicationTransactionTemplate() ->setTransactionType(PhabricatorAuthSSHKeyTransaction::TYPE_KEY) ->setNewValue($raw_key); $caught = null; try { $this->applyTransactions($user, $ssh_key, $xactions); } catch (PhabricatorApplicationTransactionValidationException $ex) { $errors = $ex->getErrors(); $this->assertEqual(1, count($errors)); $caught = head($errors)->getType(); } $this->assertEqual(PhabricatorAuthSSHKeyTransaction::TYPE_KEY, $caught); } private function applyTransactions( PhabricatorUser $actor, PhabricatorAuthSSHKey $key, array $xactions) { $content_source = $this->newContentSource(); $editor = $key->getApplicationTransactionEditor() ->setActor($actor) ->setContinueOnNoEffect(true) ->setContinueOnMissingFields(true) ->setContentSource($content_source) ->applyTransactions($key, $xactions); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/garbagecollector/PhabricatorAuthChallengeGarbageCollector.php
src/applications/auth/garbagecollector/PhabricatorAuthChallengeGarbageCollector.php
<?php final class PhabricatorAuthChallengeGarbageCollector extends PhabricatorGarbageCollector { const COLLECTORCONST = 'auth.challenges'; public function getCollectorName() { return pht('Authentication Challenges'); } public function hasAutomaticPolicy() { return true; } protected function collectGarbage() { $challenge_table = new PhabricatorAuthChallenge(); $conn = $challenge_table->establishConnection('w'); queryfx( $conn, 'DELETE FROM %R WHERE challengeTTL < UNIX_TIMESTAMP() LIMIT 100', $challenge_table); return ($conn->getAffectedRows() == 100); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/garbagecollector/PhabricatorAuthSessionGarbageCollector.php
src/applications/auth/garbagecollector/PhabricatorAuthSessionGarbageCollector.php
<?php final class PhabricatorAuthSessionGarbageCollector extends PhabricatorGarbageCollector { const COLLECTORCONST = 'auth.sessions'; public function getCollectorName() { return pht('Authentication Sessions'); } public function hasAutomaticPolicy() { return true; } protected function collectGarbage() { $session_table = new PhabricatorAuthSession(); $conn_w = $session_table->establishConnection('w'); queryfx( $conn_w, 'DELETE FROM %T WHERE sessionExpires <= UNIX_TIMESTAMP() LIMIT 100', $session_table->getTableName()); return ($conn_w->getAffectedRows() == 100); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/garbagecollector/PhabricatorAuthTemporaryTokenGarbageCollector.php
src/applications/auth/garbagecollector/PhabricatorAuthTemporaryTokenGarbageCollector.php
<?php final class PhabricatorAuthTemporaryTokenGarbageCollector extends PhabricatorGarbageCollector { const COLLECTORCONST = 'auth.tokens'; public function getCollectorName() { return pht('Authentication Tokens'); } public function hasAutomaticPolicy() { return true; } protected function collectGarbage() { $session_table = new PhabricatorAuthTemporaryToken(); $conn_w = $session_table->establishConnection('w'); queryfx( $conn_w, 'DELETE FROM %T WHERE tokenExpires <= UNIX_TIMESTAMP() LIMIT 100', $session_table->getTableName()); return ($conn_w->getAffectedRows() == 100); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/view/PhabricatorAuthChallengeUpdate.php
src/applications/auth/view/PhabricatorAuthChallengeUpdate.php
<?php final class PhabricatorAuthChallengeUpdate extends Phobject { private $retry = false; private $state; private $markup; public function setRetry($retry) { $this->retry = $retry; return $this; } public function getRetry() { return $this->retry; } public function setState($state) { $this->state = $state; return $this; } public function getState() { return $this->state; } public function setMarkup($markup) { $this->markup = $markup; return $this; } public function getMarkup() { return $this->markup; } public function newContent() { return array( 'retry' => $this->getRetry(), 'state' => $this->getState(), 'markup' => $this->getMarkup(), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/view/PhabricatorAuthInviteActionTableView.php
src/applications/auth/view/PhabricatorAuthInviteActionTableView.php
<?php final class PhabricatorAuthInviteActionTableView extends AphrontView { private $inviteActions; private $handles; public function setInviteActions(array $invite_actions) { $this->inviteActions = $invite_actions; return $this; } public function getInviteActions() { return $this->inviteActions; } public function setHandles(array $handles) { $this->handles = $handles; return $this; } public function render() { $actions = $this->getInviteActions(); $handles = $this->handles; $rows = array(); $rowc = array(); foreach ($actions as $action) { $issues = $action->getIssues(); foreach ($issues as $key => $issue) { $issues[$key] = $action->getShortNameForIssue($issue); } $issues = implode(', ', $issues); if (!$action->willSend()) { $rowc[] = 'highlighted'; } else { $rowc[] = null; } $action_icon = $action->getIconForAction($action->getAction()); $action_name = $action->getShortNameForAction($action->getAction()); $rows[] = array( $action->getRawInput(), $action->getEmailAddress(), ($action->getUserPHID() ? $handles[$action->getUserPHID()]->renderLink() : null), $issues, $action_icon, $action_name, ); } $table = id(new AphrontTableView($rows)) ->setRowClasses($rowc) ->setHeaders( array( pht('Raw Address'), pht('Parsed Address'), pht('User'), pht('Issues'), null, pht('Action'), )) ->setColumnClasses( array( '', '', '', 'wide', 'icon', '', )); return $table; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/view/PhabricatorAuthSSHKeyTableView.php
src/applications/auth/view/PhabricatorAuthSSHKeyTableView.php
<?php final class PhabricatorAuthSSHKeyTableView extends AphrontView { private $keys; private $canEdit; private $noDataString; private $showTrusted; private $showID; public static function newKeyActionsMenu( PhabricatorUser $viewer, PhabricatorSSHPublicKeyInterface $object) { $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $object, PhabricatorPolicyCapability::CAN_EDIT); try { PhabricatorSSHKeyGenerator::assertCanGenerateKeypair(); $can_generate = true; } catch (Exception $ex) { $can_generate = false; } $object_phid = $object->getPHID(); $generate_uri = "/auth/sshkey/generate/?objectPHID={$object_phid}"; $upload_uri = "/auth/sshkey/upload/?objectPHID={$object_phid}"; $view_uri = "/auth/sshkey/for/{$object_phid}/"; $action_view = id(new PhabricatorActionListView()) ->setUser($viewer) ->addAction( id(new PhabricatorActionView()) ->setHref($upload_uri) ->setWorkflow(true) ->setDisabled(!$can_edit) ->setName(pht('Upload Public Key')) ->setIcon('fa-upload')) ->addAction( id(new PhabricatorActionView()) ->setHref($generate_uri) ->setWorkflow(true) ->setDisabled(!$can_edit || !$can_generate) ->setName(pht('Generate Keypair')) ->setIcon('fa-lock')) ->addAction( id(new PhabricatorActionView()) ->setHref($view_uri) ->setName(pht('View History')) ->setIcon('fa-list-ul')); return id(new PHUIButtonView()) ->setTag('a') ->setText(pht('SSH Key Actions')) ->setHref('#') ->setIcon('fa-gear') ->setDropdownMenu($action_view); } public function setNoDataString($no_data_string) { $this->noDataString = $no_data_string; return $this; } public function setCanEdit($can_edit) { $this->canEdit = $can_edit; return $this; } public function setShowTrusted($show_trusted) { $this->showTrusted = $show_trusted; return $this; } public function setShowID($show_id) { $this->showID = $show_id; return $this; } public function setKeys(array $keys) { assert_instances_of($keys, 'PhabricatorAuthSSHKey'); $this->keys = $keys; return $this; } public function render() { $keys = $this->keys; $viewer = $this->getUser(); $trusted_icon = id(new PHUIIconView()) ->setIcon('fa-star blue'); $untrusted_icon = id(new PHUIIconView()) ->setIcon('fa-times grey'); $rows = array(); foreach ($keys as $key) { $rows[] = array( $key->getID(), javelin_tag( 'a', array( 'href' => $key->getURI(), ), $key->getName()), $key->getIsTrusted() ? $trusted_icon : $untrusted_icon, $key->getKeyComment(), $key->getKeyType(), phabricator_datetime($key->getDateCreated(), $viewer), ); } $table = id(new AphrontTableView($rows)) ->setNoDataString($this->noDataString) ->setHeaders( array( pht('ID'), pht('Name'), pht('Trusted'), pht('Comment'), pht('Type'), pht('Added'), )) ->setColumnVisibility( array( $this->showID, true, $this->showTrusted, )) ->setColumnClasses( array( '', 'wide pri', 'center', '', '', 'right', )); return $table; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/view/PhabricatorAuthAccountView.php
src/applications/auth/view/PhabricatorAuthAccountView.php
<?php final class PhabricatorAuthAccountView extends AphrontView { private $externalAccount; private $provider; public function setExternalAccount( PhabricatorExternalAccount $external_account) { $this->externalAccount = $external_account; return $this; } public function setAuthProvider(PhabricatorAuthProvider $provider) { $this->provider = $provider; return $this; } public function render() { $account = $this->externalAccount; $provider = $this->provider; require_celerity_resource('auth-css'); $content = array(); $dispname = $account->getDisplayName(); $username = $account->getUsername(); $realname = $account->getRealName(); $use_name = null; if (strlen($dispname)) { $use_name = $dispname; } else if (strlen($username) && strlen($realname)) { $use_name = $username.' ('.$realname.')'; } else if (strlen($username)) { $use_name = $username; } else if (strlen($realname)) { $use_name = $realname; } $content[] = phutil_tag( 'div', array( 'class' => 'auth-account-view-name', ), $use_name); if ($provider) { $prov_name = pht('%s Account', $provider->getProviderName()); } else { $prov_name = pht('"%s" Account', $account->getProviderType()); } $content[] = phutil_tag( 'div', array( 'class' => 'auth-account-view-provider-name', ), array( $prov_name, )); $account_uri = $account->getAccountURI(); if (strlen($account_uri)) { // Make sure we don't link a "javascript:" URI if a user somehow // managed to get one here. if (PhabricatorEnv::isValidRemoteURIForLink($account_uri)) { $account_uri = phutil_tag( 'a', array( 'href' => $account_uri, 'target' => '_blank', 'rel' => 'noreferrer', ), $account_uri); } $content[] = phutil_tag( 'div', array( 'class' => 'auth-account-view-account-uri', ), $account_uri); } $image_file = $account->getProfileImageFile(); $xform = PhabricatorFileTransform::getTransformByKey( PhabricatorFileThumbnailTransform::TRANSFORM_PROFILE); $image_uri = $image_file->getURIForTransform($xform); list($x, $y) = $xform->getTransformedDimensions($image_file); $profile_image = phutil_tag( 'div', array( 'class' => 'auth-account-view-profile-image', 'style' => 'background-image: url('.$image_uri.');', )); return phutil_tag( 'div', array( 'class' => 'auth-account-view', ), array( $profile_image, $content, )); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/provider/PhabricatorOAuthAuthProvider.php
src/applications/auth/provider/PhabricatorOAuthAuthProvider.php
<?php abstract class PhabricatorOAuthAuthProvider extends PhabricatorAuthProvider { const PROPERTY_NOTE = 'oauth:app:note'; protected $adapter; abstract protected function newOAuthAdapter(); abstract protected function getIDKey(); abstract protected function getSecretKey(); public function getDescriptionForCreate() { return pht('Configure %s OAuth.', $this->getProviderName()); } public function getAdapter() { if (!$this->adapter) { $adapter = $this->newOAuthAdapter(); $this->adapter = $adapter; $this->configureAdapter($adapter); } return $this->adapter; } public function isLoginFormAButton() { return true; } public function readFormValuesFromProvider() { $config = $this->getProviderConfig(); $id = $config->getProperty($this->getIDKey()); $secret = $config->getProperty($this->getSecretKey()); $note = $config->getProperty(self::PROPERTY_NOTE); return array( $this->getIDKey() => $id, $this->getSecretKey() => $secret, self::PROPERTY_NOTE => $note, ); } public function readFormValuesFromRequest(AphrontRequest $request) { return array( $this->getIDKey() => $request->getStr($this->getIDKey()), $this->getSecretKey() => $request->getStr($this->getSecretKey()), self::PROPERTY_NOTE => $request->getStr(self::PROPERTY_NOTE), ); } protected function processOAuthEditForm( AphrontRequest $request, array $values, $id_error, $secret_error) { $errors = array(); $issues = array(); $key_id = $this->getIDKey(); $key_secret = $this->getSecretKey(); if (!strlen($values[$key_id])) { $errors[] = $id_error; $issues[$key_id] = pht('Required'); } if (!strlen($values[$key_secret])) { $errors[] = $secret_error; $issues[$key_secret] = pht('Required'); } // If the user has not changed the secret, don't update it (that is, // don't cause a bunch of "****" to be written to the database). if (preg_match('/^[*]+$/', $values[$key_secret])) { unset($values[$key_secret]); } return array($errors, $issues, $values); } public function getConfigurationHelp() { $help = $this->getProviderConfigurationHelp(); return $help."\n\n". pht( 'Use the **OAuth App Notes** field to record details about which '. 'account the external application is registered under.'); } abstract protected function getProviderConfigurationHelp(); protected function extendOAuthEditForm( AphrontRequest $request, AphrontFormView $form, array $values, array $issues, $id_label, $secret_label) { $key_id = $this->getIDKey(); $key_secret = $this->getSecretKey(); $key_note = self::PROPERTY_NOTE; $v_id = $values[$key_id]; $v_secret = $values[$key_secret]; if ($v_secret) { $v_secret = str_repeat('*', strlen($v_secret)); } $v_note = $values[$key_note]; $e_id = idx($issues, $key_id, $request->isFormPost() ? null : true); $e_secret = idx($issues, $key_secret, $request->isFormPost() ? null : true); $form ->appendChild( id(new AphrontFormTextControl()) ->setLabel($id_label) ->setName($key_id) ->setValue($v_id) ->setError($e_id)) ->appendChild( id(new AphrontFormPasswordControl()) ->setLabel($secret_label) ->setDisableAutocomplete(true) ->setName($key_secret) ->setValue($v_secret) ->setError($e_secret)) ->appendChild( id(new AphrontFormTextAreaControl()) ->setLabel(pht('OAuth App Notes')) ->setHeight(AphrontFormTextAreaControl::HEIGHT_VERY_SHORT) ->setName($key_note) ->setValue($v_note)); } public function renderConfigPropertyTransactionTitle( PhabricatorAuthProviderConfigTransaction $xaction) { $author_phid = $xaction->getAuthorPHID(); $old = $xaction->getOldValue(); $new = $xaction->getNewValue(); $key = $xaction->getMetadataValue( PhabricatorAuthProviderConfigTransaction::PROPERTY_KEY); switch ($key) { case self::PROPERTY_NOTE: if (strlen($old)) { return pht( '%s updated the OAuth application notes for this provider.', $xaction->renderHandleLink($author_phid)); } else { return pht( '%s set the OAuth application notes for this provider.', $xaction->renderHandleLink($author_phid)); } } return parent::renderConfigPropertyTransactionTitle($xaction); } protected function willSaveAccount(PhabricatorExternalAccount $account) { parent::willSaveAccount($account); $this->synchronizeOAuthAccount($account); } abstract protected function synchronizeOAuthAccount( PhabricatorExternalAccount $account); }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/provider/PhabricatorAsanaAuthProvider.php
src/applications/auth/provider/PhabricatorAsanaAuthProvider.php
<?php final class PhabricatorAsanaAuthProvider extends PhabricatorOAuth2AuthProvider implements DoorkeeperRemarkupURIInterface { public function getProviderName() { return pht('Asana'); } protected function getProviderConfigurationHelp() { $app_uri = PhabricatorEnv::getProductionURI('/'); $login_uri = PhabricatorEnv::getURI($this->getLoginURI()); return pht( "To configure Asana OAuth, create a new application here:". "\n\n". "https://app.asana.com/-/account_api". "\n\n". "When creating your application, use these settings:". "\n\n". " - **App URL:** Set this to: `%s`\n". " - **Redirect URL:** Set this to: `%s`". "\n\n". "After completing configuration, copy the **Client ID** and ". "**Client Secret** to the fields above.", $app_uri, $login_uri); } protected function newOAuthAdapter() { return new PhutilAsanaAuthAdapter(); } protected function getLoginIcon() { return 'Asana'; } public static function getAsanaProvider() { $providers = self::getAllEnabledProviders(); foreach ($providers as $provider) { if ($provider instanceof PhabricatorAsanaAuthProvider) { return $provider; } } return null; } /* -( DoorkeeperRemarkupURIInterface )------------------------------------- */ public function getDoorkeeperURIRef(PhutilURI $uri) { $uri_string = phutil_string_cast($uri); $pattern = '(https://app\\.asana\\.com/0/(\\d+)/(\\d+))'; $matches = null; if (!preg_match($pattern, $uri_string, $matches)) { return null; } if (strlen($uri->getFragment())) { return null; } if ($uri->getQueryParamsAsPairList()) { return null; } $context_id = $matches[1]; $task_id = $matches[2]; return id(new DoorkeeperURIRef()) ->setURI($uri) ->setApplicationType(DoorkeeperBridgeAsana::APPTYPE_ASANA) ->setApplicationDomain(DoorkeeperBridgeAsana::APPDOMAIN_ASANA) ->setObjectType(DoorkeeperBridgeAsana::OBJTYPE_TASK) ->setObjectID($task_id); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/provider/PhabricatorPhabricatorAuthProvider.php
src/applications/auth/provider/PhabricatorPhabricatorAuthProvider.php
<?php final class PhabricatorPhabricatorAuthProvider extends PhabricatorOAuth2AuthProvider { const PROPERTY_PHABRICATOR_NAME = 'oauth2:phabricator:name'; const PROPERTY_PHABRICATOR_URI = 'oauth2:phabricator:uri'; public function getProviderName() { return PlatformSymbols::getPlatformServerName(); } public function getConfigurationHelp() { if ($this->isCreate()) { return pht( "**Step 1 of 2 - Name Remote Server**\n\n". 'Choose a permanent name for the remote server you want to connect '. 'to. This name is used internally to keep track of the remote '. 'server, in case the URL changes later.'); } return parent::getConfigurationHelp(); } protected function getProviderConfigurationHelp() { $config = $this->getProviderConfig(); $base_uri = rtrim( $config->getProperty(self::PROPERTY_PHABRICATOR_URI), '/'); $login_uri = PhabricatorEnv::getURI($this->getLoginURI()); return pht( "**Step 2 of 2 - Configure OAuth Server**\n\n". "To configure OAuth, create a new application here:". "\n\n". "%s/oauthserver/client/create/". "\n\n". "When creating your application, use these settings:". "\n\n". " - **Redirect URI:** Set this to: `%s`". "\n\n". "After completing configuration, copy the **Client ID** and ". "**Client Secret** to the fields above. (You may need to generate the ". "client secret by clicking 'New Secret' first.)", $base_uri, $login_uri); } protected function newOAuthAdapter() { $config = $this->getProviderConfig(); return id(new PhutilPhabricatorAuthAdapter()) ->setAdapterDomain($config->getProviderDomain()) ->setPhabricatorBaseURI( $config->getProperty(self::PROPERTY_PHABRICATOR_URI)); } protected function getLoginIcon() { return PlatformSymbols::getPlatformServerName(); } private function isCreate() { return !$this->getProviderConfig()->getID(); } public function readFormValuesFromProvider() { $config = $this->getProviderConfig(); $uri = $config->getProperty(self::PROPERTY_PHABRICATOR_URI); return parent::readFormValuesFromProvider() + array( self::PROPERTY_PHABRICATOR_NAME => $this->getProviderDomain(), self::PROPERTY_PHABRICATOR_URI => $uri, ); } public function readFormValuesFromRequest(AphrontRequest $request) { $is_setup = $this->isCreate(); if ($is_setup) { $parent_values = array(); $name = $request->getStr(self::PROPERTY_PHABRICATOR_NAME); } else { $parent_values = parent::readFormValuesFromRequest($request); $name = $this->getProviderDomain(); } return $parent_values + array( self::PROPERTY_PHABRICATOR_NAME => $name, self::PROPERTY_PHABRICATOR_URI => $request->getStr(self::PROPERTY_PHABRICATOR_URI), ); } public function processEditForm( AphrontRequest $request, array $values) { $is_setup = $this->isCreate(); if (!$is_setup) { list($errors, $issues, $values) = parent::processEditForm($request, $values); } else { $errors = array(); $issues = array(); } $key_name = self::PROPERTY_PHABRICATOR_NAME; $key_uri = self::PROPERTY_PHABRICATOR_URI; if (!strlen($values[$key_name])) { $errors[] = pht('Server name is required.'); $issues[$key_name] = pht('Required'); } else if (!preg_match('/^[a-z0-9.]+\z/', $values[$key_name])) { $errors[] = pht( 'Server name must contain only lowercase letters, '. 'digits, and periods.'); $issues[$key_name] = pht('Invalid'); } if (!strlen($values[$key_uri])) { $errors[] = pht('Base URI is required.'); $issues[$key_uri] = pht('Required'); } else { $uri = new PhutilURI($values[$key_uri]); if (!$uri->getProtocol()) { $errors[] = pht( 'Base URI should include protocol (like "%s").', 'https://'); $issues[$key_uri] = pht('Invalid'); } } if (!$errors && $is_setup) { $config = $this->getProviderConfig(); $config->setProviderDomain($values[$key_name]); } return array($errors, $issues, $values); } public function extendEditForm( AphrontRequest $request, AphrontFormView $form, array $values, array $issues) { $is_setup = $this->isCreate(); $e_required = $request->isFormPost() ? null : true; $v_name = $values[self::PROPERTY_PHABRICATOR_NAME]; if ($is_setup) { $e_name = idx($issues, self::PROPERTY_PHABRICATOR_NAME, $e_required); } else { $e_name = null; } $v_uri = $values[self::PROPERTY_PHABRICATOR_URI]; $e_uri = idx($issues, self::PROPERTY_PHABRICATOR_URI, $e_required); if ($is_setup) { $form ->appendChild( id(new AphrontFormTextControl()) ->setLabel(pht('Server Name')) ->setValue($v_name) ->setName(self::PROPERTY_PHABRICATOR_NAME) ->setError($e_name) ->setCaption(pht( 'Use lowercase letters, digits, and periods. For example: %s', phutil_tag( 'tt', array(), '`example.oauthserver`')))); } else { $form ->appendChild( id(new AphrontFormStaticControl()) ->setLabel(pht('Server Name')) ->setValue($v_name)); } $form ->appendChild( id(new AphrontFormTextControl()) ->setLabel(pht('Base URI')) ->setValue($v_uri) ->setName(self::PROPERTY_PHABRICATOR_URI) ->setCaption( pht( 'The URI where the OAuth server is installed. For example: %s', phutil_tag('tt', array(), 'https://devtools.example.com/'))) ->setError($e_uri)); if (!$is_setup) { parent::extendEditForm($request, $form, $values, $issues); } } public function hasSetupStep() { return true; } public function getPhabricatorURI() { $config = $this->getProviderConfig(); return $config->getProperty(self::PROPERTY_PHABRICATOR_URI); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/provider/PhabricatorSlackAuthProvider.php
src/applications/auth/provider/PhabricatorSlackAuthProvider.php
<?php final class PhabricatorSlackAuthProvider extends PhabricatorOAuth2AuthProvider { public function getProviderName() { return pht('Slack'); } protected function getProviderConfigurationHelp() { $login_uri = PhabricatorEnv::getURI($this->getLoginURI()); return pht( "To configure Slack OAuth, create a new application here:". "\n\n". "https://api.slack.com/docs/sign-in-with-slack#create_slack_app". "\n\n". "When creating your application, use these settings:". "\n\n". " - **Redirect URI:** Set this to: `%s`". "\n\n". "After completing configuration, copy the **Client ID** and ". "**Client Secret** to the fields above. (You may need to generate the ". "client secret by clicking 'New Secret' first.)", $login_uri); } protected function newOAuthAdapter() { return new PhutilSlackAuthAdapter(); } protected function getLoginIcon() { return 'Slack'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/provider/PhabricatorAuthProvider.php
src/applications/auth/provider/PhabricatorAuthProvider.php
<?php abstract class PhabricatorAuthProvider extends Phobject { private $providerConfig; public function attachProviderConfig(PhabricatorAuthProviderConfig $config) { $this->providerConfig = $config; return $this; } public function hasProviderConfig() { return (bool)$this->providerConfig; } public function getProviderConfig() { if ($this->providerConfig === null) { throw new PhutilInvalidStateException('attachProviderConfig'); } return $this->providerConfig; } public function getProviderConfigPHID() { return $this->getProviderConfig()->getPHID(); } public function getConfigurationHelp() { return null; } public function getDefaultProviderConfig() { return id(new PhabricatorAuthProviderConfig()) ->setProviderClass(get_class($this)) ->setIsEnabled(1) ->setShouldAllowLogin(1) ->setShouldAllowRegistration(1) ->setShouldAllowLink(1) ->setShouldAllowUnlink(1); } public function getNameForCreate() { return $this->getProviderName(); } public function getDescriptionForCreate() { return null; } public function getProviderKey() { return $this->getAdapter()->getAdapterKey(); } public function getProviderType() { return $this->getAdapter()->getAdapterType(); } public function getProviderDomain() { return $this->getAdapter()->getAdapterDomain(); } public static function getAllBaseProviders() { return id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->execute(); } public static function getAllProviders() { static $providers; if ($providers === null) { $objects = self::getAllBaseProviders(); $configs = id(new PhabricatorAuthProviderConfigQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->execute(); $providers = array(); foreach ($configs as $config) { if (!isset($objects[$config->getProviderClass()])) { // This configuration is for a provider which is not installed. continue; } $object = clone $objects[$config->getProviderClass()]; $object->attachProviderConfig($config); $key = $object->getProviderKey(); if (isset($providers[$key])) { throw new Exception( pht( "Two authentication providers use the same provider key ". "('%s'). Each provider must be identified by a unique key.", $key)); } $providers[$key] = $object; } } return $providers; } public static function getAllEnabledProviders() { $providers = self::getAllProviders(); foreach ($providers as $key => $provider) { if (!$provider->isEnabled()) { unset($providers[$key]); } } return $providers; } public static function getEnabledProviderByKey($provider_key) { return idx(self::getAllEnabledProviders(), $provider_key); } abstract public function getProviderName(); abstract public function getAdapter(); public function isEnabled() { return $this->getProviderConfig()->getIsEnabled(); } public function shouldAllowLogin() { return $this->getProviderConfig()->getShouldAllowLogin(); } public function shouldAllowRegistration() { if (!$this->shouldAllowLogin()) { return false; } return $this->getProviderConfig()->getShouldAllowRegistration(); } public function shouldAllowAccountLink() { return $this->getProviderConfig()->getShouldAllowLink(); } public function shouldAllowAccountUnlink() { return $this->getProviderConfig()->getShouldAllowUnlink(); } public function shouldTrustEmails() { return $this->shouldAllowEmailTrustConfiguration() && $this->getProviderConfig()->getShouldTrustEmails(); } /** * Should we allow the adapter to be marked as "trusted". This is true for * all adapters except those that allow the user to type in emails (see * @{class:PhabricatorPasswordAuthProvider}). */ public function shouldAllowEmailTrustConfiguration() { return true; } public function buildLoginForm(PhabricatorAuthStartController $controller) { return $this->renderLoginForm($controller->getRequest(), $mode = 'start'); } public function buildInviteForm(PhabricatorAuthStartController $controller) { return $this->renderLoginForm($controller->getRequest(), $mode = 'invite'); } abstract public function processLoginRequest( PhabricatorAuthLoginController $controller); public function buildLinkForm($controller) { return $this->renderLoginForm($controller->getRequest(), $mode = 'link'); } public function shouldAllowAccountRefresh() { return true; } public function buildRefreshForm( PhabricatorAuthLinkController $controller) { return $this->renderLoginForm($controller->getRequest(), $mode = 'refresh'); } protected function renderLoginForm(AphrontRequest $request, $mode) { throw new PhutilMethodNotImplementedException(); } public function createProviders() { return array($this); } protected function willSaveAccount(PhabricatorExternalAccount $account) { return; } final protected function newExternalAccountForIdentifiers( array $identifiers) { assert_instances_of($identifiers, 'PhabricatorExternalAccountIdentifier'); if (!$identifiers) { throw new Exception( pht( 'Authentication provider (of class "%s") is attempting to '. 'load or create an external account, but provided no account '. 'identifiers.', get_class($this))); } $config = $this->getProviderConfig(); $viewer = PhabricatorUser::getOmnipotentUser(); $raw_identifiers = mpull($identifiers, 'getIdentifierRaw'); $accounts = id(new PhabricatorExternalAccountQuery()) ->setViewer($viewer) ->withProviderConfigPHIDs(array($config->getPHID())) ->withRawAccountIdentifiers($raw_identifiers) ->needAccountIdentifiers(true) ->execute(); if (!$accounts) { $account = $this->newExternalAccount(); } else if (count($accounts) === 1) { $account = head($accounts); } else { throw new Exception( pht( 'Authentication provider (of class "%s") is attempting to load '. 'or create an external account, but provided a list of '. 'account identifiers which map to more than one account: %s.', get_class($this), implode(', ', $raw_identifiers))); } // See T13493. Add all the identifiers to the account. In the case where // an account initially has a lower-quality identifier (like an email // address) and later adds a higher-quality identifier (like a GUID), this // allows us to automatically upgrade toward the higher-quality identifier // and survive API changes which remove the lower-quality identifier more // gracefully. foreach ($identifiers as $identifier) { $account->appendIdentifier($identifier); } return $this->didUpdateAccount($account); } final protected function newExternalAccountForUser(PhabricatorUser $user) { $config = $this->getProviderConfig(); // When a user logs in with a provider like username/password, they // always already have a Phabricator account (since there's no way they // could have a username otherwise). // These users should never go to registration, so we're building a // dummy "external account" which just links directly back to their // internal account. $account = id(new PhabricatorExternalAccountQuery()) ->setViewer($user) ->withProviderConfigPHIDs(array($config->getPHID())) ->withUserPHIDs(array($user->getPHID())) ->executeOne(); if (!$account) { $account = $this->newExternalAccount() ->setUserPHID($user->getPHID()); } return $this->didUpdateAccount($account); } private function didUpdateAccount(PhabricatorExternalAccount $account) { $adapter = $this->getAdapter(); $account->setUsername($adapter->getAccountName()); $account->setRealName($adapter->getAccountRealName()); $account->setEmail($adapter->getAccountEmail()); $account->setAccountURI($adapter->getAccountURI()); $account->setProfileImagePHID(null); $image_uri = $adapter->getAccountImageURI(); if ($image_uri) { try { $name = PhabricatorSlug::normalize($this->getProviderName()); $name = $name.'-profile.jpg'; // TODO: If the image has not changed, we do not need to make a new // file entry for it, but there's no convenient way to do this with // PhabricatorFile right now. The storage will get shared, so the impact // here is negligible. $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); $image_file = PhabricatorFile::newFromFileDownload( $image_uri, array( 'name' => $name, 'viewPolicy' => PhabricatorPolicies::POLICY_NOONE, )); if ($image_file->isViewableImage()) { $image_file ->setViewPolicy(PhabricatorPolicies::getMostOpenPolicy()) ->setCanCDN(true) ->save(); $account->setProfileImagePHID($image_file->getPHID()); } else { $image_file->delete(); } unset($unguarded); } catch (Exception $ex) { // Log this but proceed, it's not especially important that we // be able to pull profile images. phlog($ex); } } $this->willSaveAccount($account); $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); $account->save(); unset($unguarded); return $account; } public function getLoginURI() { $app = PhabricatorApplication::getByClass('PhabricatorAuthApplication'); return $app->getApplicationURI('/login/'.$this->getProviderKey().'/'); } public function getSettingsURI() { return '/settings/panel/external/'; } public function getStartURI() { $app = PhabricatorApplication::getByClass('PhabricatorAuthApplication'); $uri = $app->getApplicationURI('/start/'); return $uri; } public function isDefaultRegistrationProvider() { return false; } public function shouldRequireRegistrationPassword() { return false; } public function newDefaultExternalAccount() { return $this->newExternalAccount(); } protected function newExternalAccount() { $config = $this->getProviderConfig(); $adapter = $this->getAdapter(); $account = id(new PhabricatorExternalAccount()) ->setProviderConfigPHID($config->getPHID()) ->attachAccountIdentifiers(array()); // TODO: Remove this when these columns are removed. They no longer have // readers or writers (other than this callsite). $account ->setAccountType($adapter->getAdapterType()) ->setAccountDomain($adapter->getAdapterDomain()); // TODO: Remove this when "accountID" is removed; the column is not // nullable. $account->setAccountID(''); return $account; } public function getLoginOrder() { return '500-'.$this->getProviderName(); } protected function getLoginIcon() { return 'Generic'; } public function newIconView() { return id(new PHUIIconView()) ->setSpriteSheet(PHUIIconView::SPRITE_LOGIN) ->setSpriteIcon($this->getLoginIcon()); } public function isLoginFormAButton() { return false; } public function renderConfigPropertyTransactionTitle( PhabricatorAuthProviderConfigTransaction $xaction) { return null; } public function readFormValuesFromProvider() { return array(); } public function readFormValuesFromRequest(AphrontRequest $request) { return array(); } public function processEditForm( AphrontRequest $request, array $values) { $errors = array(); $issues = array(); return array($errors, $issues, $values); } public function extendEditForm( AphrontRequest $request, AphrontFormView $form, array $values, array $issues) { return; } public function willRenderLinkedAccount( PhabricatorUser $viewer, PHUIObjectItemView $item, PhabricatorExternalAccount $account) { $account_view = id(new PhabricatorAuthAccountView()) ->setExternalAccount($account) ->setAuthProvider($this); $item->appendChild( phutil_tag( 'div', array( 'class' => 'mmr mml mst mmb', ), $account_view)); } /** * Return true to use a two-step configuration (setup, configure) instead of * the default single-step configuration. In practice, this means that * creating a new provider instance will redirect back to the edit page * instead of the provider list. * * @return bool True if this provider uses two-step configuration. */ public function hasSetupStep() { return false; } /** * Render a standard login/register button element. * * The `$attributes` parameter takes these keys: * * - `uri`: URI the button should take the user to when clicked. * - `method`: Optional HTTP method the button should use, defaults to GET. * * @param AphrontRequest HTTP request. * @param string Request mode string. * @param map Additional parameters, see above. * @return wild Log in button. */ protected function renderStandardLoginButton( AphrontRequest $request, $mode, array $attributes = array()) { PhutilTypeSpec::checkMap( $attributes, array( 'method' => 'optional string', 'uri' => 'string', 'sigil' => 'optional string', )); $viewer = $request->getUser(); $adapter = $this->getAdapter(); if ($mode == 'link') { $button_text = pht('Link External Account'); } else if ($mode == 'refresh') { $button_text = pht('Refresh Account Link'); } else if ($mode == 'invite') { $button_text = pht('Register Account'); } else if ($this->shouldAllowRegistration()) { $button_text = pht('Log In or Register'); } else { $button_text = pht('Log In'); } $icon = id(new PHUIIconView()) ->setSpriteSheet(PHUIIconView::SPRITE_LOGIN) ->setSpriteIcon($this->getLoginIcon()); $button = id(new PHUIButtonView()) ->setSize(PHUIButtonView::BIG) ->setColor(PHUIButtonView::GREY) ->setIcon($icon) ->setText($button_text) ->setSubtext($this->getProviderName()); $uri = $attributes['uri']; $uri = new PhutilURI($uri); $params = $uri->getQueryParamsAsPairList(); $uri->removeAllQueryParams(); $content = array($button); foreach ($params as $pair) { list($key, $value) = $pair; $content[] = phutil_tag( 'input', array( 'type' => 'hidden', 'name' => $key, 'value' => $value, )); } $static_response = CelerityAPI::getStaticResourceResponse(); $static_response->addContentSecurityPolicyURI('form-action', (string)$uri); foreach ($this->getContentSecurityPolicyFormActions() as $csp_uri) { $static_response->addContentSecurityPolicyURI('form-action', $csp_uri); } return phabricator_form( $viewer, array( 'method' => idx($attributes, 'method', 'GET'), 'action' => (string)$uri, 'sigil' => idx($attributes, 'sigil'), ), $content); } public function renderConfigurationFooter() { return null; } public function getAuthCSRFCode(AphrontRequest $request) { $phcid = $request->getCookie(PhabricatorCookies::COOKIE_CLIENTID); if (!strlen($phcid)) { throw new AphrontMalformedRequestException( pht('Missing Client ID Cookie'), pht( 'Your browser did not submit a "%s" cookie with client state '. 'information in the request. Check that cookies are enabled. '. 'If this problem persists, you may need to clear your cookies.', PhabricatorCookies::COOKIE_CLIENTID), true); } return PhabricatorHash::weakDigest($phcid); } protected function verifyAuthCSRFCode(AphrontRequest $request, $actual) { $expect = $this->getAuthCSRFCode($request); if (!strlen($actual)) { throw new Exception( pht( 'The authentication provider did not return a client state '. 'parameter in its response, but one was expected. If this '. 'problem persists, you may need to clear your cookies.')); } if (!phutil_hashes_are_identical($actual, $expect)) { throw new Exception( pht( 'The authentication provider did not return the correct client '. 'state parameter in its response. If this problem persists, you may '. 'need to clear your cookies.')); } } public function supportsAutoLogin() { return false; } public function getAutoLoginURI(AphrontRequest $request) { throw new PhutilMethodNotImplementedException(); } protected function getContentSecurityPolicyFormActions() { return array(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/provider/PhabricatorOAuth1SecretTemporaryTokenType.php
src/applications/auth/provider/PhabricatorOAuth1SecretTemporaryTokenType.php
<?php final class PhabricatorOAuth1SecretTemporaryTokenType extends PhabricatorAuthTemporaryTokenType { const TOKENTYPE = 'oauth1:request:secret'; public function getTokenTypeDisplayName() { return pht('OAuth1 Handshake Secret'); } public function getTokenReadableTypeName( PhabricatorAuthTemporaryToken $token) { return pht('OAuth1 Handshake Token'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/provider/PhabricatorLDAPAuthProvider.php
src/applications/auth/provider/PhabricatorLDAPAuthProvider.php
<?php final class PhabricatorLDAPAuthProvider extends PhabricatorAuthProvider { private $adapter; public function getProviderName() { return pht('LDAP'); } public function getDescriptionForCreate() { return pht( 'Configure a connection to an LDAP server so that users can use their '. 'LDAP credentials to log in.'); } public function getDefaultProviderConfig() { return parent::getDefaultProviderConfig() ->setProperty(self::KEY_PORT, 389) ->setProperty(self::KEY_VERSION, 3); } public function getAdapter() { if (!$this->adapter) { $conf = $this->getProviderConfig(); $realname_attributes = $conf->getProperty(self::KEY_REALNAME_ATTRIBUTES); if (!is_array($realname_attributes)) { $realname_attributes = array(); } $search_attributes = $conf->getProperty(self::KEY_SEARCH_ATTRIBUTES); $search_attributes = phutil_split_lines($search_attributes, false); $search_attributes = array_filter($search_attributes); $adapter = id(new PhutilLDAPAuthAdapter()) ->setHostname( $conf->getProperty(self::KEY_HOSTNAME)) ->setPort( $conf->getProperty(self::KEY_PORT)) ->setBaseDistinguishedName( $conf->getProperty(self::KEY_DISTINGUISHED_NAME)) ->setSearchAttributes($search_attributes) ->setUsernameAttribute( $conf->getProperty(self::KEY_USERNAME_ATTRIBUTE)) ->setRealNameAttributes($realname_attributes) ->setLDAPVersion( $conf->getProperty(self::KEY_VERSION)) ->setLDAPReferrals( $conf->getProperty(self::KEY_REFERRALS)) ->setLDAPStartTLS( $conf->getProperty(self::KEY_START_TLS)) ->setAlwaysSearch($conf->getProperty(self::KEY_ALWAYS_SEARCH)) ->setAnonymousUsername( $conf->getProperty(self::KEY_ANONYMOUS_USERNAME)) ->setAnonymousPassword( new PhutilOpaqueEnvelope( $conf->getProperty(self::KEY_ANONYMOUS_PASSWORD))) ->setActiveDirectoryDomain( $conf->getProperty(self::KEY_ACTIVEDIRECTORY_DOMAIN)); $this->adapter = $adapter; } return $this->adapter; } protected function renderLoginForm(AphrontRequest $request, $mode) { $viewer = $request->getUser(); $dialog = id(new AphrontDialogView()) ->setSubmitURI($this->getLoginURI()) ->setUser($viewer); if ($mode == 'link') { $dialog->setTitle(pht('Link LDAP Account')); $dialog->addSubmitButton(pht('Link Accounts')); $dialog->addCancelButton($this->getSettingsURI()); } else if ($mode == 'refresh') { $dialog->setTitle(pht('Refresh LDAP Account')); $dialog->addSubmitButton(pht('Refresh Account')); $dialog->addCancelButton($this->getSettingsURI()); } else { if ($this->shouldAllowRegistration()) { $dialog->setTitle(pht('Log In or Register with LDAP')); $dialog->addSubmitButton(pht('Log In or Register')); } else { $dialog->setTitle(pht('Log In with LDAP')); $dialog->addSubmitButton(pht('Log In')); } if ($mode == 'login') { $dialog->addCancelButton($this->getStartURI()); } } $v_user = $request->getStr('ldap_username'); $e_user = null; $e_pass = null; $errors = array(); if ($request->isHTTPPost()) { // NOTE: This is intentionally vague so as not to disclose whether a // given username exists. $e_user = pht('Invalid'); $e_pass = pht('Invalid'); $errors[] = pht('Username or password are incorrect.'); } $form = id(new PHUIFormLayoutView()) ->setUser($viewer) ->setFullWidth(true) ->appendChild( id(new AphrontFormTextControl()) ->setLabel(pht('LDAP Username')) ->setName('ldap_username') ->setAutofocus(true) ->setValue($v_user) ->setError($e_user)) ->appendChild( id(new AphrontFormPasswordControl()) ->setLabel(pht('LDAP Password')) ->setName('ldap_password') ->setError($e_pass)); if ($errors) { $errors = id(new PHUIInfoView())->setErrors($errors); } $dialog->appendChild($errors); $dialog->appendChild($form); return $dialog; } public function processLoginRequest( PhabricatorAuthLoginController $controller) { $request = $controller->getRequest(); $viewer = $request->getUser(); $response = null; $account = null; $username = $request->getStr('ldap_username'); $password = $request->getStr('ldap_password'); $has_password = strlen($password); $password = new PhutilOpaqueEnvelope($password); if (!strlen($username) || !$has_password) { $response = $controller->buildProviderPageResponse( $this, $this->renderLoginForm($request, 'login')); return array($account, $response); } if ($request->isFormPost()) { try { if (strlen($username) && $has_password) { $adapter = $this->getAdapter(); $adapter->setLoginUsername($username); $adapter->setLoginPassword($password); // TODO: This calls ldap_bind() eventually, which dumps cleartext // passwords to the error log. See note in PhutilLDAPAuthAdapter. // See T3351. DarkConsoleErrorLogPluginAPI::enableDiscardMode(); $identifiers = $adapter->getAccountIdentifiers(); DarkConsoleErrorLogPluginAPI::disableDiscardMode(); } else { throw new Exception(pht('Username and password are required!')); } } catch (PhutilAuthCredentialException $ex) { $response = $controller->buildProviderPageResponse( $this, $this->renderLoginForm($request, 'login')); return array($account, $response); } catch (Exception $ex) { // TODO: Make this cleaner. throw $ex; } } $account = $this->newExternalAccountForIdentifiers($identifiers); return array($account, $response); } const KEY_HOSTNAME = 'ldap:host'; const KEY_PORT = 'ldap:port'; const KEY_DISTINGUISHED_NAME = 'ldap:dn'; const KEY_SEARCH_ATTRIBUTES = 'ldap:search-attribute'; const KEY_USERNAME_ATTRIBUTE = 'ldap:username-attribute'; const KEY_REALNAME_ATTRIBUTES = 'ldap:realname-attributes'; const KEY_VERSION = 'ldap:version'; const KEY_REFERRALS = 'ldap:referrals'; const KEY_START_TLS = 'ldap:start-tls'; // TODO: This is misspelled! See T13005. const KEY_ANONYMOUS_USERNAME = 'ldap:anoynmous-username'; const KEY_ANONYMOUS_PASSWORD = 'ldap:anonymous-password'; const KEY_ALWAYS_SEARCH = 'ldap:always-search'; const KEY_ACTIVEDIRECTORY_DOMAIN = 'ldap:activedirectory-domain'; private function getPropertyKeys() { return array_keys($this->getPropertyLabels()); } private function getPropertyLabels() { return array( self::KEY_HOSTNAME => pht('LDAP Hostname'), self::KEY_PORT => pht('LDAP Port'), self::KEY_DISTINGUISHED_NAME => pht('Base Distinguished Name'), self::KEY_SEARCH_ATTRIBUTES => pht('Search Attributes'), self::KEY_ALWAYS_SEARCH => pht('Always Search'), self::KEY_ANONYMOUS_USERNAME => pht('Anonymous Username'), self::KEY_ANONYMOUS_PASSWORD => pht('Anonymous Password'), self::KEY_USERNAME_ATTRIBUTE => pht('Username Attribute'), self::KEY_REALNAME_ATTRIBUTES => pht('Realname Attributes'), self::KEY_VERSION => pht('LDAP Version'), self::KEY_REFERRALS => pht('Enable Referrals'), self::KEY_START_TLS => pht('Use TLS'), self::KEY_ACTIVEDIRECTORY_DOMAIN => pht('ActiveDirectory Domain'), ); } public function readFormValuesFromProvider() { $properties = array(); foreach ($this->getPropertyLabels() as $key => $ignored) { $properties[$key] = $this->getProviderConfig()->getProperty($key); } return $properties; } public function readFormValuesFromRequest(AphrontRequest $request) { $values = array(); foreach ($this->getPropertyKeys() as $key) { switch ($key) { case self::KEY_REALNAME_ATTRIBUTES: $values[$key] = $request->getStrList($key, array()); break; default: $values[$key] = $request->getStr($key); break; } } return $values; } public function processEditForm( AphrontRequest $request, array $values) { $errors = array(); $issues = array(); return array($errors, $issues, $values); } public static function assertLDAPExtensionInstalled() { if (!function_exists('ldap_bind')) { throw new Exception( pht( 'Before you can set up or use LDAP, you need to install the PHP '. 'LDAP extension. It is not currently installed, so PHP can not '. 'talk to LDAP. Usually you can install it with '. '`%s`, `%s`, or a similar package manager command.', 'yum install php-ldap', 'apt-get install php5-ldap')); } } public function extendEditForm( AphrontRequest $request, AphrontFormView $form, array $values, array $issues) { self::assertLDAPExtensionInstalled(); $labels = $this->getPropertyLabels(); $captions = array( self::KEY_HOSTNAME => pht('Example: %s%sFor LDAPS, use: %s', phutil_tag('tt', array(), pht('ldap.example.com')), phutil_tag('br'), phutil_tag('tt', array(), pht('ldaps://ldaps.example.com/'))), self::KEY_DISTINGUISHED_NAME => pht('Example: %s', phutil_tag('tt', array(), pht('ou=People, dc=example, dc=com'))), self::KEY_USERNAME_ATTRIBUTE => pht('Example: %s', phutil_tag('tt', array(), pht('sn'))), self::KEY_REALNAME_ATTRIBUTES => pht('Example: %s', phutil_tag('tt', array(), pht('firstname, lastname'))), self::KEY_REFERRALS => pht('Follow referrals. Disable this for Windows AD 2003.'), self::KEY_START_TLS => pht('Start TLS after binding to the LDAP server.'), self::KEY_ALWAYS_SEARCH => pht('Always bind and search, even without a username and password.'), ); $types = array( self::KEY_REFERRALS => 'checkbox', self::KEY_START_TLS => 'checkbox', self::KEY_SEARCH_ATTRIBUTES => 'textarea', self::KEY_REALNAME_ATTRIBUTES => 'list', self::KEY_ANONYMOUS_PASSWORD => 'password', self::KEY_ALWAYS_SEARCH => 'checkbox', ); $instructions = array( self::KEY_SEARCH_ATTRIBUTES => pht( "When a user provides their LDAP username and password, this ". "software can either bind to LDAP with those credentials directly ". "(which is simpler, but not as powerful) or bind to LDAP with ". "anonymous credentials, then search for record matching the supplied ". "credentials (which is more complicated, but more powerful).\n\n". "For many installs, direct binding is sufficient. However, you may ". "want to search first if:\n\n". " - You want users to be able to log in with either their username ". " or their email address.\n". " - The login/username is not part of the distinguished name in ". " your LDAP records.\n". " - You want to restrict logins to a subset of users (like only ". " those in certain departments).\n". " - Your LDAP server is configured in some other way that prevents ". " direct binding from working correctly.\n\n". "**To bind directly**, enter the LDAP attribute corresponding to the ". "login name into the **Search Attributes** box below. Often, this is ". "something like `sn` or `uid`. This is the simplest configuration, ". "but will only work if the username is part of the distinguished ". "name, and won't let you apply complex restrictions to logins.\n\n". " lang=text,name=Simple Direct Binding\n". " sn\n\n". "**To search first**, provide an anonymous username and password ". "below (or check the **Always Search** checkbox), then enter one ". "or more search queries into this field, one per line. ". "After binding, these queries will be used to identify the ". "record associated with the login name the user typed.\n\n". "Searches will be tried in order until a matching record is found. ". "Each query can be a simple attribute name (like `sn` or `mail`), ". "which will search for a matching record, or it can be a complex ". "query that uses the string `\${login}` to represent the login ". "name.\n\n". "A common simple configuration is just an attribute name, like ". "`sn`, which will work the same way direct binding works:\n\n". " lang=text,name=Simple Example\n". " sn\n\n". "A slightly more complex configuration might let the user log in with ". "either their login name or email address:\n\n". " lang=text,name=Match Several Attributes\n". " mail\n". " sn\n\n". "If your LDAP directory is more complex, or you want to perform ". "sophisticated filtering, you can use more complex queries. Depending ". "on your directory structure, this example might allow users to log ". "in with either their email address or username, but only if they're ". "in specific departments:\n\n". " lang=text,name=Complex Example\n". " (&(mail=\${login})(|(departmentNumber=1)(departmentNumber=2)))\n". " (&(sn=\${login})(|(departmentNumber=1)(departmentNumber=2)))\n\n". "All of the attribute names used here are just examples: your LDAP ". "server may use different attribute names."), self::KEY_ALWAYS_SEARCH => pht( 'To search for an LDAP record before authenticating, either check '. 'the **Always Search** checkbox or enter an anonymous '. 'username and password to use to perform the search.'), self::KEY_USERNAME_ATTRIBUTE => pht( 'Optionally, specify a username attribute to use to prefill usernames '. 'when registering a new account. This is purely cosmetic and does not '. 'affect the login process, but you can configure it to make sure '. 'users get the same default username as their LDAP username, so '. 'usernames remain consistent across systems.'), self::KEY_REALNAME_ATTRIBUTES => pht( 'Optionally, specify one or more comma-separated attributes to use to '. 'prefill the "Real Name" field when registering a new account. This '. 'is purely cosmetic and does not affect the login process, but can '. 'make registration a little easier.'), ); foreach ($labels as $key => $label) { $caption = idx($captions, $key); $type = idx($types, $key); $value = idx($values, $key); $control = null; switch ($type) { case 'checkbox': $control = id(new AphrontFormCheckboxControl()) ->addCheckbox( $key, 1, hsprintf('<strong>%s:</strong> %s', $label, $caption), $value); break; case 'list': $control = id(new AphrontFormTextControl()) ->setName($key) ->setLabel($label) ->setCaption($caption) ->setValue($value ? implode(', ', $value) : null); break; case 'password': $control = id(new AphrontFormPasswordControl()) ->setName($key) ->setLabel($label) ->setCaption($caption) ->setDisableAutocomplete(true) ->setValue($value); break; case 'textarea': $control = id(new AphrontFormTextAreaControl()) ->setName($key) ->setLabel($label) ->setCaption($caption) ->setValue($value); break; default: $control = id(new AphrontFormTextControl()) ->setName($key) ->setLabel($label) ->setCaption($caption) ->setValue($value); break; } $instruction_text = idx($instructions, $key); if (strlen($instruction_text)) { $form->appendRemarkupInstructions($instruction_text); } $form->appendChild($control); } } public function renderConfigPropertyTransactionTitle( PhabricatorAuthProviderConfigTransaction $xaction) { $author_phid = $xaction->getAuthorPHID(); $old = $xaction->getOldValue(); $new = $xaction->getNewValue(); $key = $xaction->getMetadataValue( PhabricatorAuthProviderConfigTransaction::PROPERTY_KEY); $labels = $this->getPropertyLabels(); if (isset($labels[$key])) { $label = $labels[$key]; $mask = false; switch ($key) { case self::KEY_ANONYMOUS_PASSWORD: $mask = true; break; } if ($mask) { return pht( '%s updated the "%s" value.', $xaction->renderHandleLink($author_phid), $label); } if ($old === null || $old === '') { return pht( '%s set the "%s" value to "%s".', $xaction->renderHandleLink($author_phid), $label, $new); } else { return pht( '%s changed the "%s" value from "%s" to "%s".', $xaction->renderHandleLink($author_phid), $label, $old, $new); } } return parent::renderConfigPropertyTransactionTitle($xaction); } public static function getLDAPProvider() { $providers = self::getAllEnabledProviders(); foreach ($providers as $provider) { if ($provider instanceof PhabricatorLDAPAuthProvider) { return $provider; } } return null; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/provider/PhabricatorJIRAAuthProvider.php
src/applications/auth/provider/PhabricatorJIRAAuthProvider.php
<?php final class PhabricatorJIRAAuthProvider extends PhabricatorOAuth1AuthProvider implements DoorkeeperRemarkupURIInterface { public function getProviderName() { return pht('JIRA'); } public function getDescriptionForCreate() { return pht('Configure JIRA OAuth. NOTE: Only supports JIRA 6.'); } public function getConfigurationHelp() { return $this->getProviderConfigurationHelp(); } protected function getProviderConfigurationHelp() { if ($this->isSetup()) { return pht( "**Step 1 of 2**: Provide the name and URI for your JIRA install.\n\n". "In the next step, you will configure JIRA."); } else { $login_uri = PhabricatorEnv::getURI($this->getLoginURI()); return pht( "**Step 2 of 2**: In this step, you will configure JIRA.\n\n". "**Create a JIRA Application**: Log into JIRA and go to ". "**Administration**, then **Add-ons**, then **Application Links**. ". "Click the button labeled **Add Application Link**, and use these ". "settings to create an application:\n\n". " - **Server URL**: `%s`\n". " - Then, click **Next**. On the second page:\n". " - **Application Name**: `%s`\n". " - **Application Type**: `Generic Application`\n". " - Then, click **Create**.\n\n". "**Configure Your Application**: Find the application you just ". "created in the table, and click the **Configure** link under ". "**Actions**. Select **Incoming Authentication** and click the ". "**OAuth** tab (it may be selected by default). Then, use these ". "settings:\n\n". " - **Consumer Key**: Set this to the \"Consumer Key\" value in the ". "form above.\n". " - **Consumer Name**: `%s`\n". " - **Public Key**: Set this to the \"Public Key\" value in the ". "form above.\n". " - **Consumer Callback URL**: `%s`\n". "Click **Save** in JIRA. Authentication should now be configured, ". "and this provider should work correctly.", PhabricatorEnv::getProductionURI('/'), PlatformSymbols::getPlatformServerName(), PlatformSymbols::getPlatformServerName(), $login_uri); } } protected function newOAuthAdapter() { $config = $this->getProviderConfig(); return id(new PhutilJIRAAuthAdapter()) ->setAdapterDomain($config->getProviderDomain()) ->setJIRABaseURI($config->getProperty(self::PROPERTY_JIRA_URI)) ->setPrivateKey( new PhutilOpaqueEnvelope( $config->getProperty(self::PROPERTY_PRIVATE_KEY))); } protected function getLoginIcon() { return 'Jira'; } private function isSetup() { return !$this->getProviderConfig()->getID(); } const PROPERTY_JIRA_NAME = 'oauth1:jira:name'; const PROPERTY_JIRA_URI = 'oauth1:jira:uri'; const PROPERTY_PUBLIC_KEY = 'oauth1:jira:key:public'; const PROPERTY_PRIVATE_KEY = 'oauth1:jira:key:private'; const PROPERTY_REPORT_LINK = 'oauth1:jira:report:link'; const PROPERTY_REPORT_COMMENT = 'oauth1:jira:report:comment'; public function readFormValuesFromProvider() { $config = $this->getProviderConfig(); $uri = $config->getProperty(self::PROPERTY_JIRA_URI); return array( self::PROPERTY_JIRA_NAME => $this->getProviderDomain(), self::PROPERTY_JIRA_URI => $uri, ); } public function readFormValuesFromRequest(AphrontRequest $request) { $is_setup = $this->isSetup(); if ($is_setup) { $name = $request->getStr(self::PROPERTY_JIRA_NAME); } else { $name = $this->getProviderDomain(); } return array( self::PROPERTY_JIRA_NAME => $name, self::PROPERTY_JIRA_URI => $request->getStr(self::PROPERTY_JIRA_URI), self::PROPERTY_REPORT_LINK => $request->getInt(self::PROPERTY_REPORT_LINK, 0), self::PROPERTY_REPORT_COMMENT => $request->getInt(self::PROPERTY_REPORT_COMMENT, 0), ); } public function processEditForm( AphrontRequest $request, array $values) { $errors = array(); $issues = array(); $is_setup = $this->isSetup(); $key_name = self::PROPERTY_JIRA_NAME; $key_uri = self::PROPERTY_JIRA_URI; if (!strlen($values[$key_name])) { $errors[] = pht('JIRA instance name is required.'); $issues[$key_name] = pht('Required'); } else if (!preg_match('/^[a-z0-9.]+\z/', $values[$key_name])) { $errors[] = pht( 'JIRA instance name must contain only lowercase letters, digits, and '. 'period.'); $issues[$key_name] = pht('Invalid'); } if (!strlen($values[$key_uri])) { $errors[] = pht('JIRA base URI is required.'); $issues[$key_uri] = pht('Required'); } else { $uri = new PhutilURI($values[$key_uri]); if (!$uri->getProtocol()) { $errors[] = pht( 'JIRA base URI should include protocol (like "https://").'); $issues[$key_uri] = pht('Invalid'); } } if (!$errors && $is_setup) { $config = $this->getProviderConfig(); $config->setProviderDomain($values[$key_name]); $consumer_key = 'phjira.'.Filesystem::readRandomCharacters(16); list($public, $private) = PhutilJIRAAuthAdapter::newJIRAKeypair(); $config->setProperty(self::PROPERTY_PUBLIC_KEY, $public); $config->setProperty(self::PROPERTY_PRIVATE_KEY, $private); $config->setProperty(self::PROPERTY_CONSUMER_KEY, $consumer_key); } return array($errors, $issues, $values); } public function extendEditForm( AphrontRequest $request, AphrontFormView $form, array $values, array $issues) { if (!function_exists('openssl_pkey_new')) { // TODO: This could be a bit prettier. throw new Exception( pht( "The PHP 'openssl' extension is not installed. You must install ". "this extension in order to add a JIRA authentication provider, ". "because JIRA OAuth requests use the RSA-SHA1 signing algorithm. ". "Install the 'openssl' extension, restart everything, and try ". "again.")); } $form->appendRemarkupInstructions( pht( 'NOTE: This provider **only supports JIRA 6**. It will not work with '. 'JIRA 5 or earlier.')); $is_setup = $this->isSetup(); $viewer = $request->getViewer(); $e_required = $request->isFormPost() ? null : true; $v_name = $values[self::PROPERTY_JIRA_NAME]; if ($is_setup) { $e_name = idx($issues, self::PROPERTY_JIRA_NAME, $e_required); } else { $e_name = null; } $v_uri = $values[self::PROPERTY_JIRA_URI]; $e_uri = idx($issues, self::PROPERTY_JIRA_URI, $e_required); if ($is_setup) { $form ->appendRemarkupInstructions( pht( "**JIRA Instance Name**\n\n". "Choose a permanent name for this instance of JIRA. This name is ". "used internally to keep track of this particular instance of ". "JIRA, in case the URL changes later.\n\n". "Use lowercase letters, digits, and period. For example, ". "`jira`, `jira.mycompany` or `jira.engineering` are reasonable ". "names.")) ->appendChild( id(new AphrontFormTextControl()) ->setLabel(pht('JIRA Instance Name')) ->setValue($v_name) ->setName(self::PROPERTY_JIRA_NAME) ->setError($e_name)); } else { $form ->appendChild( id(new AphrontFormStaticControl()) ->setLabel(pht('JIRA Instance Name')) ->setValue($v_name)); } $form ->appendChild( id(new AphrontFormTextControl()) ->setLabel(pht('JIRA Base URI')) ->setValue($v_uri) ->setName(self::PROPERTY_JIRA_URI) ->setCaption( pht( 'The URI where JIRA is installed. For example: %s', phutil_tag('tt', array(), 'https://jira.mycompany.com/'))) ->setError($e_uri)); if (!$is_setup) { $config = $this->getProviderConfig(); $ckey = $config->getProperty(self::PROPERTY_CONSUMER_KEY); $ckey = phutil_tag('tt', array(), $ckey); $pkey = $config->getProperty(self::PROPERTY_PUBLIC_KEY); $pkey = phutil_escape_html_newlines($pkey); $pkey = phutil_tag('tt', array(), $pkey); $form ->appendRemarkupInstructions( pht( 'NOTE: **To complete setup**, copy and paste these keys into JIRA '. 'according to the instructions below.')) ->appendChild( id(new AphrontFormStaticControl()) ->setLabel(pht('Consumer Key')) ->setValue($ckey)) ->appendChild( id(new AphrontFormStaticControl()) ->setLabel(pht('Public Key')) ->setValue($pkey)); $form ->appendRemarkupInstructions( pht( '= Integration Options = '."\n". 'Configure how to record Revisions on JIRA tasks.'."\n\n". 'Note you\'ll have to restart the daemons for this to take '. 'effect.')) ->appendChild( id(new AphrontFormCheckboxControl()) ->addCheckbox( self::PROPERTY_REPORT_LINK, 1, new PHUIRemarkupView( $viewer, pht( 'Create **Issue Link** to the Revision, as an "implemented '. 'in" relationship.')), $this->shouldCreateJIRALink())) ->appendChild( id(new AphrontFormCheckboxControl()) ->addCheckbox( self::PROPERTY_REPORT_COMMENT, 1, new PHUIRemarkupView( $viewer, pht( '**Post a comment** in the JIRA task.')), $this->shouldCreateJIRAComment())); } } /** * JIRA uses a setup step to generate public/private keys. */ public function hasSetupStep() { return true; } public static function getJIRAProvider() { $providers = self::getAllEnabledProviders(); foreach ($providers as $provider) { if ($provider instanceof PhabricatorJIRAAuthProvider) { return $provider; } } return null; } public function newJIRAFuture( PhabricatorExternalAccount $account, $path, $method, $params = array()) { $adapter = clone $this->getAdapter(); $adapter->setToken($account->getProperty('oauth1.token')); $adapter->setTokenSecret($account->getProperty('oauth1.token.secret')); return $adapter->newJIRAFuture($path, $method, $params); } public function shouldCreateJIRALink() { $config = $this->getProviderConfig(); return $config->getProperty(self::PROPERTY_REPORT_LINK, true); } public function shouldCreateJIRAComment() { $config = $this->getProviderConfig(); return $config->getProperty(self::PROPERTY_REPORT_COMMENT, true); } /* -( DoorkeeperRemarkupURIInterface )------------------------------------- */ public function getDoorkeeperURIRef(PhutilURI $uri) { $uri_string = phutil_string_cast($uri); $pattern = '((https?://\S+?)/browse/([A-Z][A-Z0-9]*-[1-9]\d*))'; $matches = null; if (!preg_match($pattern, $uri_string, $matches)) { return null; } if (strlen($uri->getFragment())) { return null; } if ($uri->getQueryParamsAsPairList()) { return null; } $domain = $matches[1]; $issue = $matches[2]; $config = $this->getProviderConfig(); $base_uri = $config->getProperty(self::PROPERTY_JIRA_URI); if ($domain !== rtrim($base_uri, '/')) { return null; } return id(new DoorkeeperURIRef()) ->setURI($uri) ->setApplicationType(DoorkeeperBridgeJIRA::APPTYPE_JIRA) ->setApplicationDomain($this->getProviderDomain()) ->setObjectType(DoorkeeperBridgeJIRA::OBJTYPE_ISSUE) ->setObjectID($issue); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/provider/PhabricatorBitbucketAuthProvider.php
src/applications/auth/provider/PhabricatorBitbucketAuthProvider.php
<?php final class PhabricatorBitbucketAuthProvider extends PhabricatorOAuth1AuthProvider { public function getProviderName() { return pht('Bitbucket'); } protected function getProviderConfigurationHelp() { return pht( "To configure Bitbucket OAuth, log in to Bitbucket and go to ". "**Manage Account** > **Access Management** > **OAuth**.\n\n". "Click **Add Consumer** and create a new application.\n\n". "After completing configuration, copy the **Key** and ". "**Secret** to the fields above."); } protected function newOAuthAdapter() { return new PhutilBitbucketAuthAdapter(); } protected function getLoginIcon() { return 'Bitbucket'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/provider/PhabricatorTwitterAuthProvider.php
src/applications/auth/provider/PhabricatorTwitterAuthProvider.php
<?php final class PhabricatorTwitterAuthProvider extends PhabricatorOAuth1AuthProvider { public function getProviderName() { return pht('Twitter'); } protected function getProviderConfigurationHelp() { $login_uri = PhabricatorEnv::getURI($this->getLoginURI()); return pht( "To configure Twitter OAuth, create a new application here:". "\n\n". "https://dev.twitter.com/apps". "\n\n". "When creating your application, use these settings:". "\n\n". " - **Callback URL:** Set this to: `%s`". "\n\n". "After completing configuration, copy the **Consumer Key** and ". "**Consumer Secret** to the fields above.", $login_uri); } protected function newOAuthAdapter() { return new PhutilTwitterAuthAdapter(); } protected function getLoginIcon() { return 'Twitter'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/provider/PhabricatorOAuth2AuthProvider.php
src/applications/auth/provider/PhabricatorOAuth2AuthProvider.php
<?php abstract class PhabricatorOAuth2AuthProvider extends PhabricatorOAuthAuthProvider { const PROPERTY_APP_ID = 'oauth:app:id'; const PROPERTY_APP_SECRET = 'oauth:app:secret'; protected function getIDKey() { return self::PROPERTY_APP_ID; } protected function getSecretKey() { return self::PROPERTY_APP_SECRET; } protected function configureAdapter(PhutilOAuthAuthAdapter $adapter) { $config = $this->getProviderConfig(); $adapter->setClientID($config->getProperty(self::PROPERTY_APP_ID)); $adapter->setClientSecret( new PhutilOpaqueEnvelope( $config->getProperty(self::PROPERTY_APP_SECRET))); $adapter->setRedirectURI(PhabricatorEnv::getURI($this->getLoginURI())); return $adapter; } protected function renderLoginForm(AphrontRequest $request, $mode) { $adapter = $this->getAdapter(); $adapter->setState($this->getAuthCSRFCode($request)); $scope = $request->getStr('scope'); if ($scope) { $adapter->setScope($scope); } $attributes = array( 'method' => 'GET', 'uri' => $adapter->getAuthenticateURI(), ); return $this->renderStandardLoginButton($request, $mode, $attributes); } public function processLoginRequest( PhabricatorAuthLoginController $controller) { $request = $controller->getRequest(); $adapter = $this->getAdapter(); $account = null; $response = null; $error = $request->getStr('error'); if ($error) { $response = $controller->buildProviderErrorResponse( $this, pht( 'The OAuth provider returned an error: %s', $error)); return array($account, $response); } $this->verifyAuthCSRFCode($request, $request->getStr('state')); $code = $request->getStr('code'); if (!strlen($code)) { $response = $controller->buildProviderErrorResponse( $this, pht( 'The OAuth provider did not return a "code" parameter in its '. 'response.')); return array($account, $response); } $adapter->setCode($code); // NOTE: As a side effect, this will cause the OAuth adapter to request // an access token. try { $identifiers = $adapter->getAccountIdentifiers(); } catch (Exception $ex) { // TODO: Handle this in a more user-friendly way. throw $ex; } if (!$identifiers) { $response = $controller->buildProviderErrorResponse( $this, pht( 'The OAuth provider failed to retrieve an account ID.')); return array($account, $response); } $account = $this->newExternalAccountForIdentifiers($identifiers); return array($account, $response); } public function processEditForm( AphrontRequest $request, array $values) { return $this->processOAuthEditForm( $request, $values, pht('Application ID is required.'), pht('Application secret is required.')); } public function extendEditForm( AphrontRequest $request, AphrontFormView $form, array $values, array $issues) { return $this->extendOAuthEditForm( $request, $form, $values, $issues, pht('OAuth App ID'), pht('OAuth App Secret')); } public function renderConfigPropertyTransactionTitle( PhabricatorAuthProviderConfigTransaction $xaction) { $author_phid = $xaction->getAuthorPHID(); $old = $xaction->getOldValue(); $new = $xaction->getNewValue(); $key = $xaction->getMetadataValue( PhabricatorAuthProviderConfigTransaction::PROPERTY_KEY); switch ($key) { case self::PROPERTY_APP_ID: if (strlen($old)) { return pht( '%s updated the OAuth application ID for this provider from '. '"%s" to "%s".', $xaction->renderHandleLink($author_phid), $old, $new); } else { return pht( '%s set the OAuth application ID for this provider to '. '"%s".', $xaction->renderHandleLink($author_phid), $new); } case self::PROPERTY_APP_SECRET: if (strlen($old)) { return pht( '%s updated the OAuth application secret for this provider.', $xaction->renderHandleLink($author_phid)); } else { return pht( '%s set the OAuth application secret for this provider.', $xaction->renderHandleLink($author_phid)); } case self::PROPERTY_NOTE: if (strlen($old)) { return pht( '%s updated the OAuth application notes for this provider.', $xaction->renderHandleLink($author_phid)); } else { return pht( '%s set the OAuth application notes for this provider.', $xaction->renderHandleLink($author_phid)); } } return parent::renderConfigPropertyTransactionTitle($xaction); } protected function synchronizeOAuthAccount( PhabricatorExternalAccount $account) { $adapter = $this->getAdapter(); $oauth_token = $adapter->getAccessToken(); $account->setProperty('oauth.token.access', $oauth_token); if ($adapter->supportsTokenRefresh()) { $refresh_token = $adapter->getRefreshToken(); $account->setProperty('oauth.token.refresh', $refresh_token); } else { $account->setProperty('oauth.token.refresh', null); } $expires = $adapter->getAccessTokenExpires(); $account->setProperty('oauth.token.access.expires', $expires); } public function getOAuthAccessToken( PhabricatorExternalAccount $account, $force_refresh = false) { if ($account->getProviderConfigPHID() !== $this->getProviderConfigPHID()) { throw new Exception(pht('Account does not match provider!')); } if (!$force_refresh) { $access_expires = $account->getProperty('oauth.token.access.expires'); $access_token = $account->getProperty('oauth.token.access'); // Don't return a token with fewer than this many seconds remaining until // it expires. $shortest_token = 60; if ($access_token) { if ($access_expires === null || $access_expires > (time() + $shortest_token)) { return $access_token; } } } $refresh_token = $account->getProperty('oauth.token.refresh'); if ($refresh_token) { $adapter = $this->getAdapter(); if ($adapter->supportsTokenRefresh()) { $adapter->refreshAccessToken($refresh_token); $this->synchronizeOAuthAccount($account); $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); $account->save(); unset($unguarded); return $account->getProperty('oauth.token.access'); } } return null; } public function willRenderLinkedAccount( PhabricatorUser $viewer, PHUIObjectItemView $item, PhabricatorExternalAccount $account) { // Get a valid token, possibly refreshing it. If we're unable to refresh // it, render a message to that effect. The user may be able to repair the // link by manually reconnecting. $is_invalid = false; try { $oauth_token = $this->getOAuthAccessToken($account); } catch (Exception $ex) { $oauth_token = null; $is_invalid = true; } $item->addAttribute(pht('OAuth2 Account')); if ($oauth_token) { $oauth_expires = $account->getProperty('oauth.token.access.expires'); if ($oauth_expires) { $item->addAttribute( pht( 'Active OAuth Token (Expires: %s)', phabricator_datetime($oauth_expires, $viewer))); } else { $item->addAttribute( pht('Active OAuth Token')); } } else if ($is_invalid) { $item->addAttribute(pht('Invalid OAuth Access Token')); } else { $item->addAttribute(pht('No OAuth Access Token')); } parent::willRenderLinkedAccount($viewer, $item, $account); } public function supportsAutoLogin() { return true; } public function getAutoLoginURI(AphrontRequest $request) { $csrf_code = $this->getAuthCSRFCode($request); $adapter = $this->getAdapter(); $adapter->setState($csrf_code); return $adapter->getAuthenticateURI(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/provider/PhabricatorDisqusAuthProvider.php
src/applications/auth/provider/PhabricatorDisqusAuthProvider.php
<?php final class PhabricatorDisqusAuthProvider extends PhabricatorOAuth2AuthProvider { public function getProviderName() { return pht('Disqus'); } protected function getProviderConfigurationHelp() { $login_uri = PhabricatorEnv::getURI($this->getLoginURI()); return pht( "To configure Disqus OAuth, create a new application here:". "\n\n". "http://disqus.com/api/applications/". "\n\n". "Create an application, then adjust these settings:". "\n\n". " - **Callback URL:** Set this to `%s`". "\n\n". "After creating an application, copy the **Public Key** and ". "**Secret Key** to the fields above (the **Public Key** goes in ". "**OAuth App ID**).", $login_uri); } protected function newOAuthAdapter() { return new PhutilDisqusAuthAdapter(); } protected function getLoginIcon() { return 'Disqus'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/provider/PhabricatorAmazonAuthProvider.php
src/applications/auth/provider/PhabricatorAmazonAuthProvider.php
<?php final class PhabricatorAmazonAuthProvider extends PhabricatorOAuth2AuthProvider { public function getProviderName() { return pht('Amazon'); } protected function getProviderConfigurationHelp() { $login_uri = PhabricatorEnv::getURI($this->getLoginURI()); $uri = new PhutilURI(PhabricatorEnv::getProductionURI('/')); $https_note = null; if ($uri->getProtocol() !== 'https') { $https_note = pht( 'NOTE: Amazon **requires** HTTPS, but this service does '. 'not use HTTPS. **You will not be able to add Amazon as an '. 'authentication provider until you configure HTTPS on this install**.'); } return pht( "%s\n\n". "To configure Amazon OAuth, create a new 'API Project' here:". "\n\n". "http://login.amazon.com/manageApps". "\n\n". "Use these settings:". "\n\n". " - **Allowed Return URLs:** Add this: `%s`". "\n\n". "After completing configuration, copy the **Client ID** and ". "**Client Secret** to the fields above.", $https_note, $login_uri); } protected function newOAuthAdapter() { return new PhutilAmazonAuthAdapter(); } protected function getLoginIcon() { return 'Amazon'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/provider/PhabricatorPasswordAuthProvider.php
src/applications/auth/provider/PhabricatorPasswordAuthProvider.php
<?php final class PhabricatorPasswordAuthProvider extends PhabricatorAuthProvider { private $adapter; public function getProviderName() { return pht('Username/Password'); } public function getConfigurationHelp() { return pht( "(WARNING) Examine the table below for information on how password ". "hashes will be stored in the database.\n\n". "(NOTE) You can select a minimum password length by setting ". "`%s` in configuration.", 'account.minimum-password-length'); } public function renderConfigurationFooter() { $hashers = PhabricatorPasswordHasher::getAllHashers(); $hashers = msort($hashers, 'getStrength'); $hashers = array_reverse($hashers); $yes = phutil_tag( 'strong', array( 'style' => 'color: #009900', ), pht('Yes')); $no = phutil_tag( 'strong', array( 'style' => 'color: #990000', ), pht('Not Installed')); $best_hasher_name = null; try { $best_hasher = PhabricatorPasswordHasher::getBestHasher(); $best_hasher_name = $best_hasher->getHashName(); } catch (PhabricatorPasswordHasherUnavailableException $ex) { // There are no suitable hashers. The user might be able to enable some, // so we don't want to fatal here. We'll fatal when users try to actually // use this stuff if it isn't fixed before then. Until then, we just // don't highlight a row. In practice, at least one hasher should always // be available. } $rows = array(); $rowc = array(); foreach ($hashers as $hasher) { $is_installed = $hasher->canHashPasswords(); $rows[] = array( $hasher->getHumanReadableName(), $hasher->getHashName(), $hasher->getHumanReadableStrength(), ($is_installed ? $yes : $no), ($is_installed ? null : $hasher->getInstallInstructions()), ); $rowc[] = ($best_hasher_name == $hasher->getHashName()) ? 'highlighted' : null; } $table = new AphrontTableView($rows); $table->setRowClasses($rowc); $table->setHeaders( array( pht('Algorithm'), pht('Name'), pht('Strength'), pht('Installed'), pht('Install Instructions'), )); $table->setColumnClasses( array( '', '', '', '', 'wide', )); $header = id(new PHUIHeaderView()) ->setHeader(pht('Password Hash Algorithms')) ->setSubheader( pht( 'Stronger algorithms are listed first. The highlighted algorithm '. 'will be used when storing new hashes. Older hashes will be '. 'upgraded to the best algorithm over time.')); return id(new PHUIObjectBoxView()) ->setHeader($header) ->setTable($table); } public function getDescriptionForCreate() { return pht( 'Allow users to log in or register using a username and password.'); } public function getAdapter() { if (!$this->adapter) { $adapter = new PhutilEmptyAuthAdapter(); $adapter->setAdapterType('password'); $adapter->setAdapterDomain('self'); $this->adapter = $adapter; } return $this->adapter; } public function getLoginOrder() { // Make sure username/password appears first if it is enabled. return '100-'.$this->getProviderName(); } public function shouldAllowAccountLink() { return false; } public function shouldAllowAccountUnlink() { return false; } public function isDefaultRegistrationProvider() { return true; } public function buildLoginForm( PhabricatorAuthStartController $controller) { $request = $controller->getRequest(); return $this->renderPasswordLoginForm($request); } public function buildInviteForm( PhabricatorAuthStartController $controller) { $request = $controller->getRequest(); $viewer = $request->getViewer(); $form = id(new AphrontFormView()) ->setUser($viewer) ->addHiddenInput('invite', true) ->appendChild( id(new AphrontFormTextControl()) ->setLabel(pht('Username')) ->setName('username')); $dialog = id(new AphrontDialogView()) ->setUser($viewer) ->setTitle(pht('Register an Account')) ->appendForm($form) ->setSubmitURI('/auth/register/') ->addSubmitButton(pht('Continue')); return $dialog; } public function buildLinkForm($controller) { throw new Exception(pht("Password providers can't be linked.")); } private function renderPasswordLoginForm( AphrontRequest $request, $require_captcha = false, $captcha_valid = false) { $viewer = $request->getUser(); $dialog = id(new AphrontDialogView()) ->setSubmitURI($this->getLoginURI()) ->setUser($viewer) ->setTitle(pht('Log In')) ->addSubmitButton(pht('Log In')); if ($this->shouldAllowRegistration()) { $dialog->addCancelButton( '/auth/register/', pht('Register New Account')); } $dialog->addFooter( phutil_tag( 'a', array( 'href' => '/login/email/', ), pht('Forgot your password?'))); $v_user = nonempty( $request->getStr('username'), $request->getCookie(PhabricatorCookies::COOKIE_USERNAME)); $e_user = null; $e_pass = null; $e_captcha = null; $errors = array(); if ($require_captcha && !$captcha_valid) { if (AphrontFormRecaptchaControl::hasCaptchaResponse($request)) { $e_captcha = pht('Invalid'); $errors[] = pht('CAPTCHA was not entered correctly.'); } else { $e_captcha = pht('Required'); $errors[] = pht( 'Too many login failures recently. You must '. 'submit a CAPTCHA with your login request.'); } } else if ($request->isHTTPPost()) { // NOTE: This is intentionally vague so as not to disclose whether a // given username or email is registered. $e_user = pht('Invalid'); $e_pass = pht('Invalid'); $errors[] = pht('Username or password are incorrect.'); } if ($errors) { $errors = id(new PHUIInfoView())->setErrors($errors); } $form = id(new PHUIFormLayoutView()) ->setFullWidth(true) ->appendChild($errors) ->appendChild( id(new AphrontFormTextControl()) ->setLabel(pht('Username or Email')) ->setName('username') ->setAutofocus(true) ->setValue($v_user) ->setError($e_user)) ->appendChild( id(new AphrontFormPasswordControl()) ->setLabel(pht('Password')) ->setName('password') ->setError($e_pass)); if ($require_captcha) { $form->appendChild( id(new AphrontFormRecaptchaControl()) ->setError($e_captcha)); } $dialog->appendChild($form); return $dialog; } public function processLoginRequest( PhabricatorAuthLoginController $controller) { $request = $controller->getRequest(); $viewer = $request->getUser(); $content_source = PhabricatorContentSource::newFromRequest($request); $rate_actor = PhabricatorSystemActionEngine::newActorFromRequest($request); PhabricatorSystemActionEngine::willTakeAction( array($rate_actor), new PhabricatorAuthTryPasswordAction(), 1); // If the same remote address has submitted several failed login attempts // recently, require they provide a CAPTCHA response for new attempts. $require_captcha = false; $captcha_valid = false; if (AphrontFormRecaptchaControl::isRecaptchaEnabled()) { try { PhabricatorSystemActionEngine::willTakeAction( array($rate_actor), new PhabricatorAuthTryPasswordWithoutCAPTCHAAction(), 1); } catch (PhabricatorSystemActionRateLimitException $ex) { $require_captcha = true; $captcha_valid = AphrontFormRecaptchaControl::processCaptcha($request); } } $response = null; $account = null; $log_user = null; if ($request->isFormPost()) { if (!$require_captcha || $captcha_valid) { $username_or_email = $request->getStr('username'); if (strlen($username_or_email)) { $user = id(new PhabricatorUser())->loadOneWhere( 'username = %s', $username_or_email); if (!$user) { $user = PhabricatorUser::loadOneWithEmailAddress( $username_or_email); } if ($user) { $envelope = new PhutilOpaqueEnvelope($request->getStr('password')); $engine = id(new PhabricatorAuthPasswordEngine()) ->setViewer($user) ->setContentSource($content_source) ->setPasswordType(PhabricatorAuthPassword::PASSWORD_TYPE_ACCOUNT) ->setObject($user); if ($engine->isValidPassword($envelope)) { $account = $this->newExternalAccountForUser($user); $log_user = $user; } } } } } if (!$account) { if ($request->isFormPost()) { $log = PhabricatorUserLog::initializeNewLog( null, $log_user ? $log_user->getPHID() : null, PhabricatorLoginFailureUserLogType::LOGTYPE); $log->save(); } $request->clearCookie(PhabricatorCookies::COOKIE_USERNAME); $response = $controller->buildProviderPageResponse( $this, $this->renderPasswordLoginForm( $request, $require_captcha, $captcha_valid)); } return array($account, $response); } public function shouldRequireRegistrationPassword() { return true; } public static function getPasswordProvider() { $providers = self::getAllEnabledProviders(); foreach ($providers as $provider) { if ($provider instanceof PhabricatorPasswordAuthProvider) { return $provider; } } return null; } public function willRenderLinkedAccount( PhabricatorUser $viewer, PHUIObjectItemView $item, PhabricatorExternalAccount $account) { return; } public function shouldAllowAccountRefresh() { return false; } public function shouldAllowEmailTrustConfiguration() { return false; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/provider/PhabricatorTwitchAuthProvider.php
src/applications/auth/provider/PhabricatorTwitchAuthProvider.php
<?php final class PhabricatorTwitchAuthProvider extends PhabricatorOAuth2AuthProvider { public function getProviderName() { return pht('Twitch.tv'); } protected function getProviderConfigurationHelp() { $login_uri = PhabricatorEnv::getURI($this->getLoginURI()); return pht( "To configure Twitch.tv OAuth, create a new application here:". "\n\n". "http://www.twitch.tv/settings/applications". "\n\n". "When creating your application, use these settings:". "\n\n". " - **Redirect URI:** Set this to: `%s`". "\n\n". "After completing configuration, copy the **Client ID** and ". "**Client Secret** to the fields above. (You may need to generate the ". "client secret by clicking 'New Secret' first.)", $login_uri); } protected function newOAuthAdapter() { return new PhutilTwitchAuthAdapter(); } protected function getLoginIcon() { return 'TwitchTV'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/provider/PhabricatorWordPressAuthProvider.php
src/applications/auth/provider/PhabricatorWordPressAuthProvider.php
<?php final class PhabricatorWordPressAuthProvider extends PhabricatorOAuth2AuthProvider { public function getProviderName() { return pht('WordPress.com'); } protected function getProviderConfigurationHelp() { $uri = PhabricatorEnv::getProductionURI('/'); $callback_uri = PhabricatorEnv::getURI($this->getLoginURI()); return pht( "To configure WordPress.com OAuth, create a new WordPress.com ". "Application here:\n\n". "https://developer.wordpress.com/apps/new/.". "\n\n". "You should use these settings in your application:". "\n\n". " - **URL:** Set this to your full domain with protocol. For this ". " server, the correct value is: `%s`\n". " - **Redirect URL**: Set this to: `%s`\n". "\n\n". "Once you've created an application, copy the **Client ID** and ". "**Client Secret** into the fields above.", $uri, $callback_uri); } protected function newOAuthAdapter() { return new PhutilWordPressAuthAdapter(); } protected function getLoginIcon() { return 'WordPressCOM'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/provider/PhabricatorFacebookAuthProvider.php
src/applications/auth/provider/PhabricatorFacebookAuthProvider.php
<?php final class PhabricatorFacebookAuthProvider extends PhabricatorOAuth2AuthProvider { public function getProviderName() { return pht('Facebook'); } protected function getProviderConfigurationHelp() { $uri = PhabricatorEnv::getProductionURI($this->getLoginURI()); $domain = id(new PhutilURI($uri))->getDomain(); $table = array( 'Client OAuth Login' => pht('No'), 'Web OAuth Login' => pht('Yes'), 'Enforce HTTPS' => pht('Yes'), 'Force Web OAuth Reauthentication' => pht('Yes (Optional)'), 'Embedded Browser OAuth Login' => pht('No'), 'Use Strict Mode for Redirect URIs' => pht('Yes'), 'Login from Devices' => pht('No'), 'Valid OAuth Redirect URIs' => '`'.(string)$uri.'`', 'App Domains' => '`'.$domain.'`', ); $rows = array(); foreach ($table as $k => $v) { $rows[] = sprintf('| %s | %s |', $k, $v); $rows[] = sprintf('|----| |'); } $rows = implode("\n", $rows); return pht( 'To configure Facebook OAuth, create a new Facebook Application here:'. "\n\n". 'https://developers.facebook.com/apps'. "\n\n". 'You should use these settings in your application:'. "\n\n". "%s\n". "\n\n". "After creating your new application, copy the **App ID** and ". "**App Secret** to the fields above.", $rows); } protected function newOAuthAdapter() { return new PhutilFacebookAuthAdapter(); } protected function getLoginIcon() { return 'Facebook'; } protected function getContentSecurityPolicyFormActions() { return array( // See T13254. After login with a mobile device, Facebook may redirect // to the mobile site. 'https://m.facebook.com/', ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/provider/PhabricatorGitHubAuthProvider.php
src/applications/auth/provider/PhabricatorGitHubAuthProvider.php
<?php final class PhabricatorGitHubAuthProvider extends PhabricatorOAuth2AuthProvider { public function getProviderName() { return pht('GitHub'); } protected function getProviderConfigurationHelp() { $uri = PhabricatorEnv::getProductionURI('/'); $callback_uri = PhabricatorEnv::getURI($this->getLoginURI()); return pht( "To configure GitHub OAuth, create a new GitHub Application here:". "\n\n". "https://github.com/settings/applications/new". "\n\n". "You should use these settings in your application:". "\n\n". " - **URL:** Set this to your full domain with protocol. For this ". " server, the correct value is: `%s`\n". " - **Callback URL**: Set this to: `%s`\n". "\n\n". "Once you've created an application, copy the **Client ID** and ". "**Client Secret** into the fields above.", $uri, $callback_uri); } protected function newOAuthAdapter() { return new PhutilGitHubAuthAdapter(); } protected function getLoginIcon() { return 'Github'; } public function getLoginURI() { // TODO: Clean this up. See PhabricatorAuthOldOAuthRedirectController. return '/oauth/github/login/'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/provider/PhabricatorGoogleAuthProvider.php
src/applications/auth/provider/PhabricatorGoogleAuthProvider.php
<?php final class PhabricatorGoogleAuthProvider extends PhabricatorOAuth2AuthProvider { public function getProviderName() { return pht('Google'); } protected function getProviderConfigurationHelp() { $login_uri = PhabricatorEnv::getURI($this->getLoginURI()); return pht( "To configure Google OAuth, create a new 'API Project' here:". "\n\n". "https://console.developers.google.com/". "\n\n". "Adjust these configuration settings for your project:". "\n\n". " - Under **APIs & auth > APIs**, scroll down the list and enable ". " the **Google+ API**.\n". " - You will need to consent to the **Google+ API** terms if you ". " have not before.\n". " - Under **APIs & auth > Credentials**, click **Create New Client". " ID** in the **OAuth** section. Then use these settings:\n". " - **Application Type**: Web Application\n". " - **Authorized Javascript origins**: Leave this empty.\n". " - **Authorized redirect URI**: Set this to `%s`.\n". "\n\n". "After completing configuration, copy the **Client ID** and ". "**Client Secret** from the Google console to the fields above.", $login_uri); } protected function newOAuthAdapter() { return new PhutilGoogleAuthAdapter(); } protected function getLoginIcon() { return 'Google'; } public function getLoginURI() { // TODO: Clean this up. See PhabricatorAuthOldOAuthRedirectController. return '/oauth/google/login/'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/provider/PhabricatorOAuth1AuthProvider.php
src/applications/auth/provider/PhabricatorOAuth1AuthProvider.php
<?php abstract class PhabricatorOAuth1AuthProvider extends PhabricatorOAuthAuthProvider { protected $adapter; const PROPERTY_CONSUMER_KEY = 'oauth1:consumer:key'; const PROPERTY_CONSUMER_SECRET = 'oauth1:consumer:secret'; const PROPERTY_PRIVATE_KEY = 'oauth1:private:key'; protected function getIDKey() { return self::PROPERTY_CONSUMER_KEY; } protected function getSecretKey() { return self::PROPERTY_CONSUMER_SECRET; } protected function configureAdapter(PhutilOAuth1AuthAdapter $adapter) { $config = $this->getProviderConfig(); $adapter->setConsumerKey($config->getProperty(self::PROPERTY_CONSUMER_KEY)); $secret = $config->getProperty(self::PROPERTY_CONSUMER_SECRET); if (phutil_nonempty_string($secret)) { $adapter->setConsumerSecret(new PhutilOpaqueEnvelope($secret)); } $adapter->setCallbackURI(PhabricatorEnv::getURI($this->getLoginURI())); return $adapter; } protected function renderLoginForm(AphrontRequest $request, $mode) { $attributes = array( 'method' => 'POST', 'uri' => $this->getLoginURI(), ); return $this->renderStandardLoginButton($request, $mode, $attributes); } public function processLoginRequest( PhabricatorAuthLoginController $controller) { $request = $controller->getRequest(); $adapter = $this->getAdapter(); $account = null; $response = null; if ($request->isHTTPPost()) { // Add a CSRF code to the callback URI, which we'll verify when // performing the login. $client_code = $this->getAuthCSRFCode($request); $callback_uri = $adapter->getCallbackURI(); $callback_uri = $callback_uri.$client_code.'/'; $adapter->setCallbackURI($callback_uri); $uri = $adapter->getClientRedirectURI(); $this->saveHandshakeTokenSecret( $client_code, $adapter->getTokenSecret()); $response = id(new AphrontRedirectResponse()) ->setIsExternal(true) ->setURI($uri); return array($account, $response); } $denied = $request->getStr('denied'); if (strlen($denied)) { // Twitter indicates that the user cancelled the login attempt by // returning "denied" as a parameter. throw new PhutilAuthUserAbortedException(); } // NOTE: You can get here via GET, this should probably be a bit more // user friendly. $this->verifyAuthCSRFCode($request, $controller->getExtraURIData()); $token = $request->getStr('oauth_token'); $verifier = $request->getStr('oauth_verifier'); if (!$token) { throw new Exception(pht("Expected '%s' in request!", 'oauth_token')); } if (!$verifier) { throw new Exception(pht("Expected '%s' in request!", 'oauth_verifier')); } $adapter->setToken($token); $adapter->setVerifier($verifier); $client_code = $this->getAuthCSRFCode($request); $token_secret = $this->loadHandshakeTokenSecret($client_code); $adapter->setTokenSecret($token_secret); // NOTE: As a side effect, this will cause the OAuth adapter to request // an access token. try { $identifiers = $adapter->getAccountIdentifiers(); } catch (Exception $ex) { // TODO: Handle this in a more user-friendly way. throw $ex; } if (!$identifiers) { $response = $controller->buildProviderErrorResponse( $this, pht( 'The OAuth provider failed to retrieve an account ID.')); return array($account, $response); } $account = $this->newExternalAccountForIdentifiers($identifiers); return array($account, $response); } public function processEditForm( AphrontRequest $request, array $values) { $key_ckey = self::PROPERTY_CONSUMER_KEY; $key_csecret = self::PROPERTY_CONSUMER_SECRET; return $this->processOAuthEditForm( $request, $values, pht('Consumer key is required.'), pht('Consumer secret is required.')); } public function extendEditForm( AphrontRequest $request, AphrontFormView $form, array $values, array $issues) { return $this->extendOAuthEditForm( $request, $form, $values, $issues, pht('OAuth Consumer Key'), pht('OAuth Consumer Secret')); } public function renderConfigPropertyTransactionTitle( PhabricatorAuthProviderConfigTransaction $xaction) { $author_phid = $xaction->getAuthorPHID(); $old = $xaction->getOldValue(); $new = $xaction->getNewValue(); $key = $xaction->getMetadataValue( PhabricatorAuthProviderConfigTransaction::PROPERTY_KEY); switch ($key) { case self::PROPERTY_CONSUMER_KEY: if (strlen($old)) { return pht( '%s updated the OAuth consumer key for this provider from '. '"%s" to "%s".', $xaction->renderHandleLink($author_phid), $old, $new); } else { return pht( '%s set the OAuth consumer key for this provider to '. '"%s".', $xaction->renderHandleLink($author_phid), $new); } case self::PROPERTY_CONSUMER_SECRET: if (strlen($old)) { return pht( '%s updated the OAuth consumer secret for this provider.', $xaction->renderHandleLink($author_phid)); } else { return pht( '%s set the OAuth consumer secret for this provider.', $xaction->renderHandleLink($author_phid)); } } return parent::renderConfigPropertyTransactionTitle($xaction); } protected function synchronizeOAuthAccount( PhabricatorExternalAccount $account) { $adapter = $this->getAdapter(); $oauth_token = $adapter->getToken(); $oauth_token_secret = $adapter->getTokenSecret(); $account->setProperty('oauth1.token', $oauth_token); $account->setProperty('oauth1.token.secret', $oauth_token_secret); } public function willRenderLinkedAccount( PhabricatorUser $viewer, PHUIObjectItemView $item, PhabricatorExternalAccount $account) { $item->addAttribute(pht('OAuth1 Account')); parent::willRenderLinkedAccount($viewer, $item, $account); } protected function getContentSecurityPolicyFormActions() { return $this->getAdapter()->getContentSecurityPolicyFormActions(); } /* -( Temporary Secrets )-------------------------------------------------- */ private function saveHandshakeTokenSecret($client_code, $secret) { $secret_type = PhabricatorOAuth1SecretTemporaryTokenType::TOKENTYPE; $key = $this->getHandshakeTokenKeyFromClientCode($client_code); $type = $this->getTemporaryTokenType($secret_type); // Wipe out an existing token, if one exists. $token = id(new PhabricatorAuthTemporaryTokenQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withTokenResources(array($key)) ->withTokenTypes(array($type)) ->executeOne(); if ($token) { $token->delete(); } // Save the new secret. id(new PhabricatorAuthTemporaryToken()) ->setTokenResource($key) ->setTokenType($type) ->setTokenExpires(time() + phutil_units('1 hour in seconds')) ->setTokenCode($secret) ->save(); } private function loadHandshakeTokenSecret($client_code) { $secret_type = PhabricatorOAuth1SecretTemporaryTokenType::TOKENTYPE; $key = $this->getHandshakeTokenKeyFromClientCode($client_code); $type = $this->getTemporaryTokenType($secret_type); $token = id(new PhabricatorAuthTemporaryTokenQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withTokenResources(array($key)) ->withTokenTypes(array($type)) ->withExpired(false) ->executeOne(); if (!$token) { throw new Exception( pht( 'Unable to load your OAuth1 token secret from storage. It may '. 'have expired. Try authenticating again.')); } return $token->getTokenCode(); } private function getTemporaryTokenType($core_type) { // Namespace the type so that multiple providers don't step on each // others' toes if a user starts Mediawiki and Bitbucket auth at the // same time. // TODO: This isn't really a proper use of the table and should get // cleaned up some day: the type should be constant. return $core_type.':'.$this->getProviderConfig()->getID(); } private function getHandshakeTokenKeyFromClientCode($client_code) { // NOTE: This is very slightly coercive since the TemporaryToken table // expects an "objectPHID" as an identifier, but nothing about the storage // is bound to PHIDs. return 'oauth1:secret/'.$client_code; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/message/PhabricatorAuthMessageType.php
src/applications/auth/message/PhabricatorAuthMessageType.php
<?php abstract class PhabricatorAuthMessageType extends Phobject { final public function getMessageTypeKey() { return $this->getPhobjectClassConstant('MESSAGEKEY', 64); } final public static function getAllMessageTypes() { return id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->setUniqueMethod('getMessageTypeKey') ->execute(); } final public static function newFromKey($key) { $types = self::getAllMessageTypes(); if (empty($types[$key])) { throw new Exception( pht( 'No message type exists with key "%s".', $key)); } return clone $types[$key]; } abstract public function getDisplayName(); abstract public function getShortDescription(); public function getFullDescription() { return null; } public function getDefaultMessageText() { return null; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/message/PhabricatorAuthChangeUsernameMessageType.php
src/applications/auth/message/PhabricatorAuthChangeUsernameMessageType.php
<?php final class PhabricatorAuthChangeUsernameMessageType extends PhabricatorAuthMessageType { const MESSAGEKEY = 'user.edit.username'; public function getDisplayName() { return pht('Username Change Instructions'); } public function getShortDescription() { return pht( 'Guidance in the "Change Username" dialog for requesting a '. 'username change.'); } public function getFullDescription() { return pht( 'When users click the "Change Username" action on their profile pages '. 'but do not have the required permissions, they will be presented with '. 'a message explaining that they are not authorized to make the edit.'. "\n\n". 'You can optionally provide additional instructions here to help users '. 'request a username change, if there is someone specific they should '. 'contact or a particular workflow they should use.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/message/PhabricatorAuthWelcomeMailMessageType.php
src/applications/auth/message/PhabricatorAuthWelcomeMailMessageType.php
<?php final class PhabricatorAuthWelcomeMailMessageType extends PhabricatorAuthMessageType { const MESSAGEKEY = 'mail.welcome'; public function getDisplayName() { return pht('Mail Body: Welcome'); } public function getShortDescription() { return pht( 'Custom instructions included in "Welcome" mail when an '. 'administrator creates a user account.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/message/PhabricatorAuthLoginMessageType.php
src/applications/auth/message/PhabricatorAuthLoginMessageType.php
<?php final class PhabricatorAuthLoginMessageType extends PhabricatorAuthMessageType { const MESSAGEKEY = 'auth.login'; public function getDisplayName() { return pht('Login Screen Instructions'); } public function getShortDescription() { return pht( 'Guidance shown on the main login screen before users log in or '. 'register.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/message/PhabricatorAuthEmailSetPasswordMessageType.php
src/applications/auth/message/PhabricatorAuthEmailSetPasswordMessageType.php
<?php final class PhabricatorAuthEmailSetPasswordMessageType extends PhabricatorAuthMessageType { const MESSAGEKEY = 'mail.set-password'; public function getDisplayName() { return pht('Mail Body: Set Password'); } public function getShortDescription() { return pht( 'Guidance in the message body when users set a password on an account '. 'which did not previously have a password.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/message/PhabricatorAuthEmailLoginMessageType.php
src/applications/auth/message/PhabricatorAuthEmailLoginMessageType.php
<?php final class PhabricatorAuthEmailLoginMessageType extends PhabricatorAuthMessageType { const MESSAGEKEY = 'mail.login'; public function getDisplayName() { return pht('Mail Body: Email Login'); } public function getShortDescription() { return pht( 'Guidance in the message body when users request an email link '. 'to access their account.'); } public function getFullDescription() { return pht( 'Guidance included in the mail message body when users request an '. 'email link to access their account.'. "\n\n". 'For installs with password authentication enabled, users access this '. 'workflow by using the "Forgot your password?" link on the login '. 'screen.'. "\n\n". 'For installs without password authentication enabled, users access '. 'this workflow by using the "Send a login link to your email address." '. 'link on the login screen. This workflow allows users to recover '. 'access to their account if there is an issue with an external '. 'login service.'); } public function getDefaultMessageText() { return pht( 'You (or someone pretending to be you) recently requested an account '. 'recovery link be sent to this email address. If you did not make '. 'this request, you can ignore this message.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/message/PhabricatorAuthWaitForApprovalMessageType.php
src/applications/auth/message/PhabricatorAuthWaitForApprovalMessageType.php
<?php final class PhabricatorAuthWaitForApprovalMessageType extends PhabricatorAuthMessageType { const MESSAGEKEY = 'auth.wait-for-approval'; public function getDisplayName() { return pht('Wait For Approval Instructions'); } public function getShortDescription() { return pht( 'Instructions on the "Wait For Approval" screen, shown to users who '. 'have registered an account that has not yet been approved by an '. 'administrator.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/message/PhabricatorAuthLinkMessageType.php
src/applications/auth/message/PhabricatorAuthLinkMessageType.php
<?php final class PhabricatorAuthLinkMessageType extends PhabricatorAuthMessageType { const MESSAGEKEY = 'auth.link'; public function getDisplayName() { return pht('Unlinked Account Instructions'); } public function getShortDescription() { return pht( 'Guidance shown after a user logs in with an email link and is '. 'prompted to link an external account.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/phid/PhabricatorAuthInvitePHIDType.php
src/applications/auth/phid/PhabricatorAuthInvitePHIDType.php
<?php final class PhabricatorAuthInvitePHIDType extends PhabricatorPHIDType { const TYPECONST = 'AINV'; public function getTypeName() { return pht('Auth Invite'); } public function newObject() { return new PhabricatorAuthInvite(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorAuthApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { throw new PhutilMethodNotImplementedException(); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { foreach ($handles as $phid => $handle) { $invite = $objects[$phid]; } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/phid/PhabricatorAuthAuthFactorPHIDType.php
src/applications/auth/phid/PhabricatorAuthAuthFactorPHIDType.php
<?php final class PhabricatorAuthAuthFactorPHIDType extends PhabricatorPHIDType { const TYPECONST = 'AFTR'; public function getTypeName() { return pht('Auth Factor'); } public function newObject() { return new PhabricatorAuthFactorConfig(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorAuthApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { // TODO: Maybe we need this eventually? throw new PhutilMethodNotImplementedException(); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { foreach ($handles as $phid => $handle) { $factor = $objects[$phid]; $handle->setName($factor->getFactorName()); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/phid/PhabricatorAuthSSHKeyPHIDType.php
src/applications/auth/phid/PhabricatorAuthSSHKeyPHIDType.php
<?php final class PhabricatorAuthSSHKeyPHIDType extends PhabricatorPHIDType { const TYPECONST = 'AKEY'; public function getTypeName() { return pht('Public SSH Key'); } public function newObject() { return new PhabricatorAuthSSHKey(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorAuthApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { return id(new PhabricatorAuthSSHKeyQuery()) ->withPHIDs($phids); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { foreach ($handles as $phid => $handle) { $key = $objects[$phid]; $handle->setName(pht('SSH Key %d', $key->getID())); if (!$key->getIsActive()) { $handle->setStatus(PhabricatorObjectHandle::STATUS_CLOSED); } } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/phid/PhabricatorAuthContactNumberPHIDType.php
src/applications/auth/phid/PhabricatorAuthContactNumberPHIDType.php
<?php final class PhabricatorAuthContactNumberPHIDType extends PhabricatorPHIDType { const TYPECONST = 'CTNM'; public function getTypeName() { return pht('Contact Number'); } public function newObject() { return new PhabricatorAuthContactNumber(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorAuthApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { return id(new PhabricatorAuthContactNumberQuery()) ->withPHIDs($phids); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { foreach ($handles as $phid => $handle) { $contact_number = $objects[$phid]; } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/phid/PhabricatorAuthMessagePHIDType.php
src/applications/auth/phid/PhabricatorAuthMessagePHIDType.php
<?php final class PhabricatorAuthMessagePHIDType extends PhabricatorPHIDType { const TYPECONST = 'AMSG'; public function getTypeName() { return pht('Auth Message'); } public function newObject() { return new PhabricatorAuthMessage(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorAuthApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { return id(new PhabricatorAuthMessageQuery()) ->withPHIDs($phids); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { foreach ($handles as $phid => $handle) { $message = $objects[$phid]; $handle->setURI($message->getURI()); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/phid/PhabricatorAuthAuthFactorProviderPHIDType.php
src/applications/auth/phid/PhabricatorAuthAuthFactorProviderPHIDType.php
<?php final class PhabricatorAuthAuthFactorProviderPHIDType extends PhabricatorPHIDType { const TYPECONST = 'FPRV'; public function getTypeName() { return pht('MFA Provider'); } public function newObject() { return new PhabricatorAuthFactorProvider(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorAuthApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { return id(new PhabricatorAuthFactorProviderQuery()) ->withPHIDs($phids); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { foreach ($handles as $phid => $handle) { $provider = $objects[$phid]; $handle->setURI($provider->getURI()); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/phid/PhabricatorAuthAuthProviderPHIDType.php
src/applications/auth/phid/PhabricatorAuthAuthProviderPHIDType.php
<?php final class PhabricatorAuthAuthProviderPHIDType extends PhabricatorPHIDType { const TYPECONST = 'AUTH'; public function getTypeName() { return pht('Auth Provider'); } public function newObject() { return new PhabricatorAuthProviderConfig(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorAuthApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { return id(new PhabricatorAuthProviderConfigQuery()) ->withPHIDs($phids); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { foreach ($handles as $phid => $handle) { $provider = $objects[$phid]->getProvider(); if ($provider) { $handle->setName($provider->getProviderName()); } } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/phid/PhabricatorAuthChallengePHIDType.php
src/applications/auth/phid/PhabricatorAuthChallengePHIDType.php
<?php final class PhabricatorAuthChallengePHIDType extends PhabricatorPHIDType { const TYPECONST = 'CHAL'; public function getTypeName() { return pht('Auth Challenge'); } public function newObject() { return new PhabricatorAuthChallenge(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorAuthApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { return new PhabricatorAuthChallengeQuery(); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { return; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/phid/PhabricatorAuthPasswordPHIDType.php
src/applications/auth/phid/PhabricatorAuthPasswordPHIDType.php
<?php final class PhabricatorAuthPasswordPHIDType extends PhabricatorPHIDType { const TYPECONST = 'APAS'; public function getTypeName() { return pht('Auth Password'); } public function newObject() { return new PhabricatorAuthPassword(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorAuthApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { return id(new PhabricatorAuthPasswordQuery()) ->withPHIDs($phids); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { foreach ($handles as $phid => $handle) { $password = $objects[$phid]; } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/phid/PhabricatorAuthSessionPHIDType.php
src/applications/auth/phid/PhabricatorAuthSessionPHIDType.php
<?php final class PhabricatorAuthSessionPHIDType extends PhabricatorPHIDType { const TYPECONST = 'SSSN'; public function getTypeName() { return pht('Session'); } public function newObject() { return new PhabricatorAuthSession(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorAuthApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { return id(new PhabricatorAuthSessionQuery()) ->withPHIDs($phids); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { return; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/revoker/PhabricatorAuthTemporaryTokenRevoker.php
src/applications/auth/revoker/PhabricatorAuthTemporaryTokenRevoker.php
<?php final class PhabricatorAuthTemporaryTokenRevoker extends PhabricatorAuthRevoker { const REVOKERKEY = 'temporary'; public function getRevokerName() { return pht('Temporary Tokens'); } public function getRevokerDescription() { return pht( "Revokes temporary authentication tokens.\n\n". "Temporary tokens are used in password reset mail, welcome mail, and ". "by some other systems like Git LFS. Revoking temporary tokens will ". "invalidate existing links in password reset and invite mail that ". "was sent before the revocation occurred."); } public function revokeAllCredentials() { $table = new PhabricatorAuthTemporaryToken(); $conn = $table->establishConnection('w'); queryfx( $conn, 'DELETE FROM %T', $table->getTableName()); return $conn->getAffectedRows(); } public function revokeCredentialsFrom($object) { $table = new PhabricatorAuthTemporaryToken(); $conn = $table->establishConnection('w'); queryfx( $conn, 'DELETE FROM %T WHERE tokenResource = %s', $table->getTableName(), $object->getPHID()); return $conn->getAffectedRows(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/revoker/PhabricatorAuthConduitTokenRevoker.php
src/applications/auth/revoker/PhabricatorAuthConduitTokenRevoker.php
<?php final class PhabricatorAuthConduitTokenRevoker extends PhabricatorAuthRevoker { const REVOKERKEY = 'conduit'; public function getRevokerName() { return pht('Conduit API Tokens'); } public function getRevokerDescription() { return pht( "Revokes all Conduit API tokens used to access the API.\n\n". "Users will need to use `arc install-certificate` to install new ". "API tokens before `arc` commands will work. Bots and scripts which ". "access the API will need to have new tokens generated and ". "installed."); } public function revokeAllCredentials() { $table = id(new PhabricatorConduitToken()); $conn = $table->establishConnection('w'); queryfx( $conn, 'DELETE FROM %T', $table->getTableName()); return $conn->getAffectedRows(); } public function revokeCredentialsFrom($object) { $table = id(new PhabricatorConduitToken()); $conn = $table->establishConnection('w'); queryfx( $conn, 'DELETE FROM %T WHERE objectPHID = %s', $table->getTableName(), $object->getPHID()); return $conn->getAffectedRows(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/revoker/PhabricatorAuthPasswordRevoker.php
src/applications/auth/revoker/PhabricatorAuthPasswordRevoker.php
<?php final class PhabricatorAuthPasswordRevoker extends PhabricatorAuthRevoker { const REVOKERKEY = 'password'; public function getRevokerName() { return pht('Passwords'); } public function getRevokerDescription() { return pht( "Revokes all stored passwords.\n\n". "Account passwords and VCS passwords (used to access repositories ". "over HTTP) will both be revoked. Passwords for any third party ". "applications which use shared password infrastructure will also ". "be revoked.\n\n". "Users will need to reset account passwords, possibly by using the ". "\"Forgot Password?\" link on the login page. They will also need ". "to reset VCS passwords.\n\n". "Passwords are revoked, not just removed. Users will be unable to ". "select the passwords they used previously and must choose new, ". "unique passwords.\n\n". "Revoking passwords will not terminate outstanding login sessions. ". "Use the \"session\" revoker in conjunction with this revoker to force ". "users to login again."); } public function getRevokerNextSteps() { return pht( 'NOTE: Revoking passwords does not terminate existing sessions which '. 'were established using the old passwords. To terminate existing '. 'sessions, run the "session" revoker now.'); } public function revokeAllCredentials() { $query = new PhabricatorAuthPasswordQuery(); return $this->revokeWithQuery($query); } public function revokeCredentialsFrom($object) { $query = id(new PhabricatorAuthPasswordQuery()) ->withObjectPHIDs(array($object->getPHID())); return $this->revokeWithQuery($query); } private function revokeWithQuery(PhabricatorAuthPasswordQuery $query) { $viewer = $this->getViewer(); $passwords = $query ->setViewer($viewer) ->withIsRevoked(false) ->execute(); $content_source = PhabricatorContentSource::newForSource( PhabricatorDaemonContentSource::SOURCECONST); $revoke_type = PhabricatorAuthPasswordRevokeTransaction::TRANSACTIONTYPE; $auth_phid = id(new PhabricatorAuthApplication())->getPHID(); foreach ($passwords as $password) { $xactions = array(); $xactions[] = $password->getApplicationTransactionTemplate() ->setTransactionType($revoke_type) ->setNewValue(true); $editor = $password->getApplicationTransactionEditor() ->setActor($viewer) ->setActingAsPHID($auth_phid) ->setContinueOnNoEffect(true) ->setContinueOnMissingFields(true) ->setContentSource($content_source) ->applyTransactions($password, $xactions); } return count($passwords); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/revoker/PhabricatorAuthRevoker.php
src/applications/auth/revoker/PhabricatorAuthRevoker.php
<?php abstract class PhabricatorAuthRevoker extends Phobject { private $viewer; abstract public function revokeAllCredentials(); abstract public function revokeCredentialsFrom($object); abstract public function getRevokerName(); abstract public function getRevokerDescription(); public function getRevokerNextSteps() { return null; } public function setViewer(PhabricatorUser $viewer) { $this->viewer = $viewer; return $this; } public function getViewer() { return $this->viewer; } final public function getRevokerKey() { return $this->getPhobjectClassConstant('REVOKERKEY'); } final public static function getAllRevokers() { return id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->setUniqueMethod('getRevokerKey') ->execute(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/revoker/PhabricatorAuthSessionRevoker.php
src/applications/auth/revoker/PhabricatorAuthSessionRevoker.php
<?php final class PhabricatorAuthSessionRevoker extends PhabricatorAuthRevoker { const REVOKERKEY = 'session'; public function getRevokerName() { return pht('Sessions'); } public function getRevokerDescription() { return pht( "Revokes all active login sessions.\n\n". "Affected users will be logged out and need to log in again."); } public function revokeAllCredentials() { $table = new PhabricatorAuthSession(); $conn = $table->establishConnection('w'); queryfx( $conn, 'DELETE FROM %T', $table->getTableName()); return $conn->getAffectedRows(); } public function revokeCredentialsFrom($object) { $table = new PhabricatorAuthSession(); $conn = $table->establishConnection('w'); queryfx( $conn, 'DELETE FROM %T WHERE userPHID = %s', $table->getTableName(), $object->getPHID()); return $conn->getAffectedRows(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/revoker/PhabricatorAuthSSHRevoker.php
src/applications/auth/revoker/PhabricatorAuthSSHRevoker.php
<?php final class PhabricatorAuthSSHRevoker extends PhabricatorAuthRevoker { const REVOKERKEY = 'ssh'; public function getRevokerName() { return pht('SSH Keys'); } public function getRevokerDescription() { return pht( "Revokes all SSH public keys.\n\n". "SSH public keys are revoked, not just removed. Users will need to ". "generate and upload new, unique keys before they can access ". "repositories or other services over SSH."); } public function revokeAllCredentials() { $query = new PhabricatorAuthSSHKeyQuery(); return $this->revokeWithQuery($query); } public function revokeCredentialsFrom($object) { $query = id(new PhabricatorAuthSSHKeyQuery()) ->withObjectPHIDs(array($object->getPHID())); return $this->revokeWithQuery($query); } private function revokeWithQuery(PhabricatorAuthSSHKeyQuery $query) { $viewer = $this->getViewer(); // We're only going to revoke keys which have not already been revoked. $ssh_keys = $query ->setViewer($viewer) ->withIsActive(true) ->execute(); $content_source = PhabricatorContentSource::newForSource( PhabricatorDaemonContentSource::SOURCECONST); $auth_phid = id(new PhabricatorAuthApplication())->getPHID(); foreach ($ssh_keys as $ssh_key) { $xactions = array(); $xactions[] = $ssh_key->getApplicationTransactionTemplate() ->setTransactionType(PhabricatorAuthSSHKeyTransaction::TYPE_DEACTIVATE) ->setNewValue(1); $editor = $ssh_key->getApplicationTransactionEditor() ->setActor($viewer) ->setActingAsPHID($auth_phid) ->setContinueOnNoEffect(true) ->setContinueOnMissingFields(true) ->setContentSource($content_source) ->setIsAdministrativeEdit(true) ->applyTransactions($ssh_key, $xactions); } return count($ssh_keys); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/conduit/PhabricatorAuthConduitAPIMethod.php
src/applications/auth/conduit/PhabricatorAuthConduitAPIMethod.php
<?php abstract class PhabricatorAuthConduitAPIMethod extends ConduitAPIMethod { final public function getApplication() { return PhabricatorApplication::getByClass('PhabricatorAuthApplication'); } public function getMethodStatus() { return self::METHOD_STATUS_UNSTABLE; } public function getMethodStatusDescription() { return pht('These methods are recently introduced and subject to change.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/conduit/PhabricatorAuthQueryPublicKeysConduitAPIMethod.php
src/applications/auth/conduit/PhabricatorAuthQueryPublicKeysConduitAPIMethod.php
<?php final class PhabricatorAuthQueryPublicKeysConduitAPIMethod extends PhabricatorAuthConduitAPIMethod { public function getAPIMethodName() { return 'auth.querypublickeys'; } public function getMethodDescription() { return pht('Query public keys.'); } protected function defineParamTypes() { return array( 'ids' => 'optional list<id>', 'phids' => 'optional list<phid>', 'objectPHIDs' => 'optional list<phid>', 'keys' => 'optional list<string>', ) + self::getPagerParamTypes(); } protected function defineReturnType() { return 'result-set'; } protected function execute(ConduitAPIRequest $request) { $viewer = $request->getUser(); $query = id(new PhabricatorAuthSSHKeyQuery()) ->setViewer($viewer) ->withIsActive(true); $ids = $request->getValue('ids'); if ($ids !== null) { $query->withIDs($ids); } $phids = $request->getValue('phids'); if ($phids !== null) { $query->withPHIDs($phids); } $object_phids = $request->getValue('objectPHIDs'); if ($object_phids !== null) { $query->withObjectPHIDs($object_phids); } $keys = $request->getValue('keys'); if ($keys !== null) { $key_objects = array(); foreach ($keys as $key) { $key_objects[] = PhabricatorAuthSSHPublicKey::newFromRawKey($key); } $query->withKeys($key_objects); } $pager = $this->newPager($request); $public_keys = $query->executeWithCursorPager($pager); $data = array(); foreach ($public_keys as $public_key) { $data[] = array( 'id' => $public_key->getID(), 'name' => $public_key->getName(), 'phid' => $public_key->getPHID(), 'objectPHID' => $public_key->getObjectPHID(), 'isTrusted' => (bool)$public_key->getIsTrusted(), 'key' => $public_key->getEntireKey(), ); } $results = array( 'data' => $data, ); return $this->addPagerResults($results, $pager); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/conduit/PhabricatorAuthLogoutConduitAPIMethod.php
src/applications/auth/conduit/PhabricatorAuthLogoutConduitAPIMethod.php
<?php final class PhabricatorAuthLogoutConduitAPIMethod extends PhabricatorAuthConduitAPIMethod { public function getAPIMethodName() { return 'auth.logout'; } public function getMethodSummary() { return pht('Terminate all login sessions.'); } public function getMethodDescription() { return pht( 'Terminate all web login sessions. If called via OAuth, also terminate '. 'the current OAuth token.'. "\n\n". 'WARNING: This method does what it claims on the label. If you call '. 'this method via the test console in the web UI, it will log you out!'); } protected function defineParamTypes() { return array(); } protected function defineReturnType() { return 'void'; } public function getRequiredScope() { return self::SCOPE_ALWAYS; } protected function execute(ConduitAPIRequest $request) { $viewer = $request->getUser(); // Destroy all web sessions. $engine = id(new PhabricatorAuthSessionEngine()); $engine->terminateLoginSessions($viewer); // If we were called via OAuth, destroy the OAuth token. $oauth_token = $request->getOAuthToken(); if ($oauth_token) { $oauth_token->delete(); } return null; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/data/PhabricatorAuthHighSecurityToken.php
src/applications/auth/data/PhabricatorAuthHighSecurityToken.php
<?php final class PhabricatorAuthHighSecurityToken extends Phobject { private $isUnchallengedToken = false; public function setIsUnchallengedToken($is_unchallenged_token) { $this->isUnchallengedToken = $is_unchallenged_token; return $this; } public function getIsUnchallengedToken() { return $this->isUnchallengedToken; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/data/PhabricatorAuthInviteAction.php
src/applications/auth/data/PhabricatorAuthInviteAction.php
<?php final class PhabricatorAuthInviteAction extends Phobject { private $rawInput; private $emailAddress; private $userPHID; private $issues = array(); private $action; const ACTION_SEND = 'invite.send'; const ACTION_ERROR = 'invite.error'; const ACTION_IGNORE = 'invite.ignore'; const ISSUE_PARSE = 'invite.parse'; const ISSUE_DUPLICATE = 'invite.duplicate'; const ISSUE_UNVERIFIED = 'invite.unverified'; const ISSUE_VERIFIED = 'invite.verified'; const ISSUE_INVITED = 'invite.invited'; const ISSUE_ACCEPTED = 'invite.accepted'; public function getRawInput() { return $this->rawInput; } public function getEmailAddress() { return $this->emailAddress; } public function getUserPHID() { return $this->userPHID; } public function getIssues() { return $this->issues; } public function setAction($action) { $this->action = $action; return $this; } public function getAction() { return $this->action; } public function willSend() { return ($this->action == self::ACTION_SEND); } public function getShortNameForIssue($issue) { $map = array( self::ISSUE_PARSE => pht('Not a Valid Email Address'), self::ISSUE_DUPLICATE => pht('Address Duplicated in Input'), self::ISSUE_UNVERIFIED => pht('Unverified User Email'), self::ISSUE_VERIFIED => pht('Verified User Email'), self::ISSUE_INVITED => pht('Previously Invited'), self::ISSUE_ACCEPTED => pht('Already Accepted Invite'), ); return idx($map, $issue); } public function getShortNameForAction($action) { $map = array( self::ACTION_SEND => pht('Will Send Invite'), self::ACTION_ERROR => pht('Address Error'), self::ACTION_IGNORE => pht('Will Ignore Address'), ); return idx($map, $action); } public function getIconForAction($action) { switch ($action) { case self::ACTION_SEND: $icon = 'fa-envelope-o'; $color = 'green'; break; case self::ACTION_IGNORE: $icon = 'fa-ban'; $color = 'grey'; break; case self::ACTION_ERROR: $icon = 'fa-exclamation-triangle'; $color = 'red'; break; } return id(new PHUIIconView()) ->setIcon("{$icon} {$color}"); } public static function newActionListFromAddresses( PhabricatorUser $viewer, array $addresses) { $results = array(); foreach ($addresses as $address) { $result = new PhabricatorAuthInviteAction(); $result->rawInput = $address; $email = new PhutilEmailAddress($address); $result->emailAddress = phutil_utf8_strtolower($email->getAddress()); if (!preg_match('/^\S+@\S+\.\S+\z/', $result->emailAddress)) { $result->issues[] = self::ISSUE_PARSE; } $results[] = $result; } // Identify duplicates. $address_groups = mgroup($results, 'getEmailAddress'); foreach ($address_groups as $address => $group) { if (count($group) > 1) { foreach ($group as $action) { $action->issues[] = self::ISSUE_DUPLICATE; } } } // Identify addresses which are already in the system. $addresses = mpull($results, 'getEmailAddress'); $email_objects = id(new PhabricatorUserEmail())->loadAllWhere( 'address IN (%Ls)', $addresses); $email_map = array(); foreach ($email_objects as $email_object) { $address_key = phutil_utf8_strtolower($email_object->getAddress()); $email_map[$address_key] = $email_object; } // Identify outstanding invites. $invites = id(new PhabricatorAuthInviteQuery()) ->setViewer($viewer) ->withEmailAddresses($addresses) ->execute(); $invite_map = mpull($invites, null, 'getEmailAddress'); foreach ($results as $action) { $email = idx($email_map, $action->getEmailAddress()); if ($email) { if ($email->getUserPHID()) { $action->userPHID = $email->getUserPHID(); if ($email->getIsVerified()) { $action->issues[] = self::ISSUE_VERIFIED; } else { $action->issues[] = self::ISSUE_UNVERIFIED; } } } $invite = idx($invite_map, $action->getEmailAddress()); if ($invite) { if ($invite->getAcceptedByPHID()) { $action->issues[] = self::ISSUE_ACCEPTED; if (!$action->userPHID) { // This could be different from the user who is currently attached // to the email address if the address was removed or added to a // different account later. Only show it if the address was // removed, since the current status is more up-to-date otherwise. $action->userPHID = $invite->getAcceptedByPHID(); } } else { $action->issues[] = self::ISSUE_INVITED; } } } foreach ($results as $result) { foreach ($result->getIssues() as $issue) { switch ($issue) { case self::ISSUE_PARSE: $result->action = self::ACTION_ERROR; break; case self::ISSUE_ACCEPTED: case self::ISSUE_VERIFIED: $result->action = self::ACTION_IGNORE; break; } } if (!$result->action) { $result->action = self::ACTION_SEND; } } return $results; } public function sendInvite(PhabricatorUser $actor, $template) { if (!$this->willSend()) { throw new Exception(pht('Invite action is not a send action!')); } if (!preg_match('/{\$INVITE_URI}/', $template)) { throw new Exception(pht('Invite template does not include invite URI!')); } PhabricatorWorker::scheduleTask( 'PhabricatorAuthInviteWorker', array( 'address' => $this->getEmailAddress(), 'template' => $template, 'authorPHID' => $actor->getPHID(), )); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/data/PhabricatorAuthSessionInfo.php
src/applications/auth/data/PhabricatorAuthSessionInfo.php
<?php final class PhabricatorAuthSessionInfo extends Phobject { private $sessionType; private $identityPHID; private $isPartial; public function setSessionType($session_type) { $this->sessionType = $session_type; return $this; } public function getSessionType() { return $this->sessionType; } public function setIdentityPHID($identity_phid) { $this->identityPHID = $identity_phid; return $this; } public function getIdentityPHID() { return $this->identityPHID; } public function setIsPartial($is_partial) { $this->isPartial = $is_partial; return $this; } public function getIsPartial() { return $this->isPartial; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/engine/PhabricatorAuthInviteEngine.php
src/applications/auth/engine/PhabricatorAuthInviteEngine.php
<?php /** * This class does an unusual amount of flow control via exceptions. The intent * is to make the workflows highly testable, because this code is high-stakes * and difficult to test. */ final class PhabricatorAuthInviteEngine extends Phobject { private $viewer; private $userHasConfirmedVerify; public function setViewer(PhabricatorUser $viewer) { $this->viewer = $viewer; return $this; } public function getViewer() { if (!$this->viewer) { throw new PhutilInvalidStateException('setViewer'); } return $this->viewer; } public function setUserHasConfirmedVerify($confirmed) { $this->userHasConfirmedVerify = $confirmed; return $this; } private function shouldVerify() { return $this->userHasConfirmedVerify; } public function processInviteCode($code) { $viewer = $this->getViewer(); $invite = id(new PhabricatorAuthInviteQuery()) ->setViewer($viewer) ->withVerificationCodes(array($code)) ->executeOne(); if (!$invite) { throw id(new PhabricatorAuthInviteInvalidException( pht('Bad Invite Code'), pht( 'The invite code in the link you clicked is invalid. Check that '. 'you followed the link correctly.'))) ->setCancelButtonURI('/') ->setCancelButtonText(pht('Curses!')); } $accepted_phid = $invite->getAcceptedByPHID(); if ($accepted_phid) { if ($accepted_phid == $viewer->getPHID()) { throw id(new PhabricatorAuthInviteInvalidException( pht('Already Accepted'), pht( 'You have already accepted this invitation.'))) ->setCancelButtonURI('/') ->setCancelButtonText(pht('Awesome')); } else { throw id(new PhabricatorAuthInviteInvalidException( pht('Already Accepted'), pht( 'The invite code in the link you clicked has already '. 'been accepted.'))) ->setCancelButtonURI('/') ->setCancelButtonText(pht('Continue')); } } $email = id(new PhabricatorUserEmail())->loadOneWhere( 'address = %s', $invite->getEmailAddress()); if ($viewer->isLoggedIn()) { $this->handleLoggedInInvite($invite, $viewer, $email); } if ($email) { $other_user = $this->loadUserForEmail($email); if ($email->getIsVerified()) { throw id(new PhabricatorAuthInviteLoginException( pht('Already Registered'), pht( 'The email address you just clicked a link from is already '. 'verified and associated with a registered account (%s). Log '. 'in to continue.', phutil_tag('strong', array(), $other_user->getName())))) ->setCancelButtonText(pht('Log In')) ->setCancelButtonURI($this->getLoginURI()); } else if ($email->getIsPrimary()) { throw id(new PhabricatorAuthInviteLoginException( pht('Already Registered'), pht( 'The email address you just clicked a link from is already '. 'the primary email address for a registered account (%s). Log '. 'in to continue.', phutil_tag('strong', array(), $other_user->getName())))) ->setCancelButtonText(pht('Log In')) ->setCancelButtonURI($this->getLoginURI()); } else if (!$this->shouldVerify()) { throw id(new PhabricatorAuthInviteVerifyException( pht('Already Associated'), pht( 'The email address you just clicked a link from is already '. 'associated with a registered account (%s), but is not '. 'verified. Log in to that account to continue. If you can not '. 'log in, you can register a new account.', phutil_tag('strong', array(), $other_user->getName())))) ->setCancelButtonText(pht('Log In')) ->setCancelButtonURI($this->getLoginURI()) ->setSubmitButtonText(pht('Register New Account')); } else { // NOTE: The address is not verified and not a primary address, so // we will eventually steal it if the user completes registration. } } // The invite and email address are OK, but the user needs to register. return $invite; } private function handleLoggedInInvite( PhabricatorAuthInvite $invite, PhabricatorUser $viewer, PhabricatorUserEmail $email = null) { if ($email && ($email->getUserPHID() !== $viewer->getPHID())) { $other_user = $this->loadUserForEmail($email); if ($email->getIsVerified()) { throw id(new PhabricatorAuthInviteAccountException( pht('Wrong Account'), pht( 'You are logged in as %s, but the email address you just '. 'clicked a link from is already verified and associated '. 'with another account (%s). Switch accounts, then try again.', phutil_tag('strong', array(), $viewer->getUsername()), phutil_tag('strong', array(), $other_user->getName())))) ->setSubmitButtonText(pht('Log Out')) ->setSubmitButtonURI($this->getLogoutURI()) ->setCancelButtonURI('/'); } else if ($email->getIsPrimary()) { // NOTE: We never steal primary addresses from other accounts, even // if they are unverified. This would leave the other account with // no address. Users can use password recovery to access the other // account if they really control the address. throw id(new PhabricatorAuthInviteAccountException( pht('Wrong Account'), pht( 'You are logged in as %s, but the email address you just '. 'clicked a link from is already the primary email address '. 'for another account (%s). Switch accounts, then try again.', phutil_tag('strong', array(), $viewer->getUsername()), phutil_tag('strong', array(), $other_user->getName())))) ->setSubmitButtonText(pht('Log Out')) ->setSubmitButtonURI($this->getLogoutURI()) ->setCancelButtonURI('/'); } else if (!$this->shouldVerify()) { throw id(new PhabricatorAuthInviteVerifyException( pht('Verify Email'), pht( 'You are logged in as %s, but the email address (%s) you just '. 'clicked a link from is already associated with another '. 'account (%s). You can log out to switch accounts, or verify '. 'the address and attach it to your current account. Attach '. 'email address %s to user account %s?', phutil_tag('strong', array(), $viewer->getUsername()), phutil_tag('strong', array(), $invite->getEmailAddress()), phutil_tag('strong', array(), $other_user->getName()), phutil_tag('strong', array(), $invite->getEmailAddress()), phutil_tag('strong', array(), $viewer->getUsername())))) ->setSubmitButtonText( pht( 'Verify %s', $invite->getEmailAddress())) ->setCancelButtonText(pht('Log Out')) ->setCancelButtonURI($this->getLogoutURI()); } } if (!$email) { $email = id(new PhabricatorUserEmail()) ->setAddress($invite->getEmailAddress()) ->setIsVerified(0) ->setIsPrimary(0); } if (!$email->getIsVerified()) { // We're doing this check here so that we can verify the address if // it's already attached to the viewer's account, just not verified. if (!$this->shouldVerify()) { throw id(new PhabricatorAuthInviteVerifyException( pht('Verify Email'), pht( 'Verify this email address (%s) and attach it to your '. 'account (%s)?', phutil_tag('strong', array(), $invite->getEmailAddress()), phutil_tag('strong', array(), $viewer->getUsername())))) ->setSubmitButtonText( pht( 'Verify %s', $invite->getEmailAddress())) ->setCancelButtonURI('/'); } $editor = id(new PhabricatorUserEditor()) ->setActor($viewer); // If this is a new email, add it to the user's account. if (!$email->getUserPHID()) { $editor->addEmail($viewer, $email); } // If another user added this email (but has not verified it), // take it from them. $editor->reassignEmail($viewer, $email); $editor->verifyEmail($viewer, $email); } $invite->setAcceptedByPHID($viewer->getPHID()); $invite->save(); // If we make it here, the user was already logged in with the email // address attached to their account and verified, or we attached it to // their account (if it was not already attached) and verified it. throw new PhabricatorAuthInviteRegisteredException(); } private function loadUserForEmail(PhabricatorUserEmail $email) { $user = id(new PhabricatorHandleQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withPHIDs(array($email->getUserPHID())) ->executeOne(); if (!$user) { throw new Exception( pht( 'Email record ("%s") has bad associated user PHID ("%s").', $email->getAddress(), $email->getUserPHID())); } return $user; } private function getLoginURI() { return '/auth/start/'; } private function getLogoutURI() { return '/logout/'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/engine/PhabricatorAuthContactNumberMFAEngine.php
src/applications/auth/engine/PhabricatorAuthContactNumberMFAEngine.php
<?php final class PhabricatorAuthContactNumberMFAEngine extends PhabricatorEditEngineMFAEngine { public function shouldTryMFA() { return true; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/engine/PhabricatorAuthFactorProviderMFAEngine.php
src/applications/auth/engine/PhabricatorAuthFactorProviderMFAEngine.php
<?php final class PhabricatorAuthFactorProviderMFAEngine extends PhabricatorEditEngineMFAEngine { public function shouldTryMFA() { return true; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/engine/PhabricatorAuthSessionEngine.php
src/applications/auth/engine/PhabricatorAuthSessionEngine.php
<?php /** * * @task use Using Sessions * @task new Creating Sessions * @task hisec High Security * @task partial Partial Sessions * @task onetime One Time Login URIs * @task cache User Cache */ final class PhabricatorAuthSessionEngine extends Phobject { /** * Session issued to normal users after they login through a standard channel. * Associates the client with a standard user identity. */ const KIND_USER = 'U'; /** * Session issued to users who login with some sort of credentials but do not * have full accounts. These are sometimes called "grey users". * * TODO: We do not currently issue these sessions, see T4310. */ const KIND_EXTERNAL = 'X'; /** * Session issued to logged-out users which has no real identity information. * Its purpose is to protect logged-out users from CSRF. */ const KIND_ANONYMOUS = 'A'; /** * Session kind isn't known. */ const KIND_UNKNOWN = '?'; const ONETIME_RECOVER = 'recover'; const ONETIME_RESET = 'reset'; const ONETIME_WELCOME = 'welcome'; const ONETIME_USERNAME = 'rename'; private $workflowKey; private $request; public function setWorkflowKey($workflow_key) { $this->workflowKey = $workflow_key; return $this; } public function getWorkflowKey() { // TODO: A workflow key should become required in order to issue an MFA // challenge, but allow things to keep working for now until we can update // callsites. if ($this->workflowKey === null) { return 'legacy'; } return $this->workflowKey; } public function getRequest() { return $this->request; } /** * Get the session kind (e.g., anonymous, user, external account) from a * session token. Returns a `KIND_` constant. * * @param string Session token. * @return const Session kind constant. */ public static function getSessionKindFromToken($session_token) { if (strpos($session_token, '/') === false) { // Old-style session, these are all user sessions. return self::KIND_USER; } list($kind, $key) = explode('/', $session_token, 2); switch ($kind) { case self::KIND_ANONYMOUS: case self::KIND_USER: case self::KIND_EXTERNAL: return $kind; default: return self::KIND_UNKNOWN; } } /** * Load the user identity associated with a session of a given type, * identified by token. * * When the user presents a session token to an API, this method verifies * it is of the correct type and loads the corresponding identity if the * session exists and is valid. * * NOTE: `$session_type` is the type of session that is required by the * loading context. This prevents use of a Conduit sesssion as a Web * session, for example. * * @param const The type of session to load. * @param string The session token. * @return PhabricatorUser|null * @task use */ public function loadUserForSession($session_type, $session_token) { $session_kind = self::getSessionKindFromToken($session_token); switch ($session_kind) { case self::KIND_ANONYMOUS: // Don't bother trying to load a user for an anonymous session, since // neither the session nor the user exist. return null; case self::KIND_UNKNOWN: // If we don't know what kind of session this is, don't go looking for // it. return null; case self::KIND_USER: break; case self::KIND_EXTERNAL: // TODO: Implement these (T4310). return null; } $session_table = new PhabricatorAuthSession(); $user_table = new PhabricatorUser(); $conn = $session_table->establishConnection('r'); // TODO: See T13225. We're moving sessions to a more modern digest // algorithm, but still accept older cookies for compatibility. $session_key = PhabricatorAuthSession::newSessionDigest( new PhutilOpaqueEnvelope($session_token)); $weak_key = PhabricatorHash::weakDigest($session_token); $cache_parts = $this->getUserCacheQueryParts($conn); list($cache_selects, $cache_joins, $cache_map, $types_map) = $cache_parts; $info = queryfx_one( $conn, 'SELECT s.id AS s_id, s.phid AS s_phid, s.sessionExpires AS s_sessionExpires, s.sessionStart AS s_sessionStart, s.highSecurityUntil AS s_highSecurityUntil, s.isPartial AS s_isPartial, s.signedLegalpadDocuments as s_signedLegalpadDocuments, IF(s.sessionKey = %P, 1, 0) as s_weak, u.* %Q FROM %R u JOIN %R s ON u.phid = s.userPHID AND s.type = %s AND s.sessionKey IN (%P, %P) %Q', new PhutilOpaqueEnvelope($weak_key), $cache_selects, $user_table, $session_table, $session_type, new PhutilOpaqueEnvelope($session_key), new PhutilOpaqueEnvelope($weak_key), $cache_joins); if (!$info) { return null; } // TODO: Remove this, see T13225. $is_weak = (bool)$info['s_weak']; unset($info['s_weak']); $session_dict = array( 'userPHID' => $info['phid'], 'sessionKey' => $session_key, 'type' => $session_type, ); $cache_raw = array_fill_keys($cache_map, null); foreach ($info as $key => $value) { if (strncmp($key, 's_', 2) === 0) { unset($info[$key]); $session_dict[substr($key, 2)] = $value; continue; } if (isset($cache_map[$key])) { unset($info[$key]); $cache_raw[$cache_map[$key]] = $value; continue; } } $user = $user_table->loadFromArray($info); $cache_raw = $this->filterRawCacheData($user, $types_map, $cache_raw); $user->attachRawCacheData($cache_raw); switch ($session_type) { case PhabricatorAuthSession::TYPE_WEB: // Explicitly prevent bots and mailing lists from establishing web // sessions. It's normally impossible to attach authentication to these // accounts, and likewise impossible to generate sessions, but it's // technically possible that a session could exist in the database. If // one does somehow, refuse to load it. if (!$user->canEstablishWebSessions()) { return null; } break; } $session = id(new PhabricatorAuthSession())->loadFromArray($session_dict); $this->extendSession($session); // TODO: Remove this, see T13225. if ($is_weak) { $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); $conn_w = $session_table->establishConnection('w'); queryfx( $conn_w, 'UPDATE %T SET sessionKey = %P WHERE id = %d', $session->getTableName(), new PhutilOpaqueEnvelope($session_key), $session->getID()); unset($unguarded); } $user->attachSession($session); return $user; } /** * Issue a new session key for a given identity. Phabricator supports * different types of sessions (like "web" and "conduit") and each session * type may have multiple concurrent sessions (this allows a user to be * logged in on multiple browsers at the same time, for instance). * * Note that this method is transport-agnostic and does not set cookies or * issue other types of tokens, it ONLY generates a new session key. * * You can configure the maximum number of concurrent sessions for various * session types in the Phabricator configuration. * * @param const Session type constant (see * @{class:PhabricatorAuthSession}). * @param phid|null Identity to establish a session for, usually a user * PHID. With `null`, generates an anonymous session. * @param bool True to issue a partial session. * @return string Newly generated session key. */ public function establishSession($session_type, $identity_phid, $partial) { // Consume entropy to generate a new session key, forestalling the eventual // heat death of the universe. $session_key = Filesystem::readRandomCharacters(40); if ($identity_phid === null) { return self::KIND_ANONYMOUS.'/'.$session_key; } $session_table = new PhabricatorAuthSession(); $conn_w = $session_table->establishConnection('w'); // This has a side effect of validating the session type. $session_ttl = PhabricatorAuthSession::getSessionTypeTTL( $session_type, $partial); $digest_key = PhabricatorAuthSession::newSessionDigest( new PhutilOpaqueEnvelope($session_key)); // Logging-in users don't have CSRF stuff yet, so we have to unguard this // write. $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); id(new PhabricatorAuthSession()) ->setUserPHID($identity_phid) ->setType($session_type) ->setSessionKey($digest_key) ->setSessionStart(time()) ->setSessionExpires(time() + $session_ttl) ->setIsPartial($partial ? 1 : 0) ->setSignedLegalpadDocuments(0) ->save(); $log = PhabricatorUserLog::initializeNewLog( null, $identity_phid, ($partial ? PhabricatorPartialLoginUserLogType::LOGTYPE : PhabricatorLoginUserLogType::LOGTYPE)); $log->setDetails( array( 'session_type' => $session_type, )); $log->setSession($digest_key); $log->save(); unset($unguarded); $info = id(new PhabricatorAuthSessionInfo()) ->setSessionType($session_type) ->setIdentityPHID($identity_phid) ->setIsPartial($partial); $extensions = PhabricatorAuthSessionEngineExtension::getAllExtensions(); foreach ($extensions as $extension) { $extension->didEstablishSession($info); } return $session_key; } /** * Terminate all of a user's login sessions. * * This is used when users change passwords, linked accounts, or add * multifactor authentication. * * @param PhabricatorUser User whose sessions should be terminated. * @param string|null Optionally, one session to keep. Normally, the current * login session. * * @return void */ public function terminateLoginSessions( PhabricatorUser $user, PhutilOpaqueEnvelope $except_session = null) { $sessions = id(new PhabricatorAuthSessionQuery()) ->setViewer($user) ->withIdentityPHIDs(array($user->getPHID())) ->execute(); if ($except_session !== null) { $except_session = PhabricatorAuthSession::newSessionDigest( $except_session); } foreach ($sessions as $key => $session) { if ($except_session !== null) { $is_except = phutil_hashes_are_identical( $session->getSessionKey(), $except_session); if ($is_except) { continue; } } $session->delete(); } } public function logoutSession( PhabricatorUser $user, PhabricatorAuthSession $session) { $log = PhabricatorUserLog::initializeNewLog( $user, $user->getPHID(), PhabricatorLogoutUserLogType::LOGTYPE); $log->save(); $extensions = PhabricatorAuthSessionEngineExtension::getAllExtensions(); foreach ($extensions as $extension) { $extension->didLogout($user, array($session)); } $session->delete(); } /* -( High Security )------------------------------------------------------ */ /** * Require the user respond to a high security (MFA) check. * * This method differs from @{method:requireHighSecuritySession} in that it * does not upgrade the user's session as a side effect. This method is * appropriate for one-time checks. * * @param PhabricatorUser User whose session needs to be in high security. * @param AphrontRequest Current request. * @param string URI to return the user to if they cancel. * @return PhabricatorAuthHighSecurityToken Security token. * @task hisec */ public function requireHighSecurityToken( PhabricatorUser $viewer, AphrontRequest $request, $cancel_uri) { return $this->newHighSecurityToken( $viewer, $request, $cancel_uri, false, false); } /** * Require high security, or prompt the user to enter high security. * * If the user's session is in high security, this method will return a * token. Otherwise, it will throw an exception which will eventually * be converted into a multi-factor authentication workflow. * * This method upgrades the user's session to high security for a short * period of time, and is appropriate if you anticipate they may need to * take multiple high security actions. To perform a one-time check instead, * use @{method:requireHighSecurityToken}. * * @param PhabricatorUser User whose session needs to be in high security. * @param AphrontRequest Current request. * @param string URI to return the user to if they cancel. * @param bool True to jump partial sessions directly into high * security instead of just upgrading them to full * sessions. * @return PhabricatorAuthHighSecurityToken Security token. * @task hisec */ public function requireHighSecuritySession( PhabricatorUser $viewer, AphrontRequest $request, $cancel_uri, $jump_into_hisec = false) { return $this->newHighSecurityToken( $viewer, $request, $cancel_uri, $jump_into_hisec, true); } private function newHighSecurityToken( PhabricatorUser $viewer, AphrontRequest $request, $cancel_uri, $jump_into_hisec, $upgrade_session) { if (!$viewer->hasSession()) { throw new Exception( pht('Requiring a high-security session from a user with no session!')); } // TODO: If a user answers a "requireHighSecurityToken()" prompt and hits // a "requireHighSecuritySession()" prompt a short time later, the one-shot // token should be good enough to upgrade the session. $session = $viewer->getSession(); // Check if the session is already in high security mode. $token = $this->issueHighSecurityToken($session); if ($token) { return $token; } // Load the multi-factor auth sources attached to this account. Note that // we order factors from oldest to newest, which is not the default query // ordering but makes the greatest sense in context. $factors = id(new PhabricatorAuthFactorConfigQuery()) ->setViewer($viewer) ->withUserPHIDs(array($viewer->getPHID())) ->withFactorProviderStatuses( array( PhabricatorAuthFactorProviderStatus::STATUS_ACTIVE, PhabricatorAuthFactorProviderStatus::STATUS_DEPRECATED, )) ->execute(); // Sort factors in the same order that they appear in on the Settings // panel. This means that administrators changing provider statuses may // change the order of prompts for users, but the alternative is that the // Settings panel order disagrees with the prompt order, which seems more // disruptive. $factors = msortv($factors, 'newSortVector'); // If the account has no associated multi-factor auth, just issue a token // without putting the session into high security mode. This is generally // easier for users. A minor but desirable side effect is that when a user // adds an auth factor, existing sessions won't get a free pass into hisec, // since they never actually got marked as hisec. if (!$factors) { return $this->issueHighSecurityToken($session, true) ->setIsUnchallengedToken(true); } $this->request = $request; foreach ($factors as $factor) { $factor->setSessionEngine($this); } // Check for a rate limit without awarding points, so the user doesn't // get partway through the workflow only to get blocked. PhabricatorSystemActionEngine::willTakeAction( array($viewer->getPHID()), new PhabricatorAuthTryFactorAction(), 0); $now = PhabricatorTime::getNow(); // We need to do challenge validation first, since this happens whether you // submitted responses or not. You can't get a "bad response" error before // you actually submit a response, but you can get a "wait, we can't // issue a challenge yet" response. Load all issued challenges which are // currently valid. $challenges = id(new PhabricatorAuthChallengeQuery()) ->setViewer($viewer) ->withFactorPHIDs(mpull($factors, 'getPHID')) ->withUserPHIDs(array($viewer->getPHID())) ->withChallengeTTLBetween($now, null) ->execute(); PhabricatorAuthChallenge::newChallengeResponsesFromRequest( $challenges, $request); $challenge_map = mgroup($challenges, 'getFactorPHID'); $validation_results = array(); $ok = true; // Validate each factor against issued challenges. For example, this // prevents you from receiving or responding to a TOTP challenge if another // challenge was recently issued to a different session. foreach ($factors as $factor) { $factor_phid = $factor->getPHID(); $issued_challenges = idx($challenge_map, $factor_phid, array()); $provider = $factor->getFactorProvider(); $impl = $provider->getFactor(); $new_challenges = $impl->getNewIssuedChallenges( $factor, $viewer, $issued_challenges); // NOTE: We may get a list of challenges back, or may just get an early // result. For example, this can happen on an SMS factor if all SMS // mailers have been disabled. if ($new_challenges instanceof PhabricatorAuthFactorResult) { $result = $new_challenges; if (!$result->getIsValid()) { $ok = false; } $validation_results[$factor_phid] = $result; $challenge_map[$factor_phid] = $issued_challenges; continue; } foreach ($new_challenges as $new_challenge) { $issued_challenges[] = $new_challenge; } $challenge_map[$factor_phid] = $issued_challenges; if (!$issued_challenges) { continue; } $result = $impl->getResultFromIssuedChallenges( $factor, $viewer, $issued_challenges); if (!$result) { continue; } if (!$result->getIsValid()) { $ok = false; } $validation_results[$factor_phid] = $result; } if ($request->isHTTPPost()) { $request->validateCSRF(); if ($request->getExists(AphrontRequest::TYPE_HISEC)) { // Limit factor verification rates to prevent brute force attacks. $any_attempt = false; foreach ($factors as $factor) { $factor_phid = $factor->getPHID(); $provider = $factor->getFactorProvider(); $impl = $provider->getFactor(); // If we already have a result (normally "wait..."), we won't try // to validate whatever the user submitted, so this doesn't count as // an attempt for rate limiting purposes. if (isset($validation_results[$factor_phid])) { continue; } if ($impl->getRequestHasChallengeResponse($factor, $request)) { $any_attempt = true; break; } } if ($any_attempt) { PhabricatorSystemActionEngine::willTakeAction( array($viewer->getPHID()), new PhabricatorAuthTryFactorAction(), 1); } foreach ($factors as $factor) { $factor_phid = $factor->getPHID(); // If we already have a validation result from previously issued // challenges, skip validating this factor. if (isset($validation_results[$factor_phid])) { continue; } $issued_challenges = idx($challenge_map, $factor_phid, array()); $provider = $factor->getFactorProvider(); $impl = $provider->getFactor(); $validation_result = $impl->getResultFromChallengeResponse( $factor, $viewer, $request, $issued_challenges); if (!$validation_result->getIsValid()) { $ok = false; } $validation_results[$factor_phid] = $validation_result; } if ($ok) { // We're letting you through, so mark all the challenges you // responded to as completed. These challenges can never be used // again, even by the same session and workflow: you can't use the // same response to take two different actions, even if those actions // are of the same type. foreach ($validation_results as $validation_result) { $challenge = $validation_result->getAnsweredChallenge() ->markChallengeAsCompleted(); } // Give the user a credit back for a successful factor verification. if ($any_attempt) { PhabricatorSystemActionEngine::willTakeAction( array($viewer->getPHID()), new PhabricatorAuthTryFactorAction(), -1); } if ($session->getIsPartial() && !$jump_into_hisec) { // If we have a partial session and are not jumping directly into // hisec, just issue a token without putting it in high security // mode. return $this->issueHighSecurityToken($session, true); } // If we aren't upgrading the session itself, just issue a token. if (!$upgrade_session) { return $this->issueHighSecurityToken($session, true); } $until = time() + phutil_units('15 minutes in seconds'); $session->setHighSecurityUntil($until); queryfx( $session->establishConnection('w'), 'UPDATE %T SET highSecurityUntil = %d WHERE id = %d', $session->getTableName(), $until, $session->getID()); $log = PhabricatorUserLog::initializeNewLog( $viewer, $viewer->getPHID(), PhabricatorEnterHisecUserLogType::LOGTYPE); $log->save(); } else { $log = PhabricatorUserLog::initializeNewLog( $viewer, $viewer->getPHID(), PhabricatorFailHisecUserLogType::LOGTYPE); $log->save(); } } } $token = $this->issueHighSecurityToken($session); if ($token) { return $token; } // If we don't have a validation result for some factors yet, fill them // in with an empty result so form rendering doesn't have to care if the // results exist or not. This happens when you first load the form and have // not submitted any responses yet. foreach ($factors as $factor) { $factor_phid = $factor->getPHID(); if (isset($validation_results[$factor_phid])) { continue; } $issued_challenges = idx($challenge_map, $factor_phid, array()); $validation_results[$factor_phid] = $impl->getResultForPrompt( $factor, $viewer, $request, $issued_challenges); } throw id(new PhabricatorAuthHighSecurityRequiredException()) ->setCancelURI($cancel_uri) ->setIsSessionUpgrade($upgrade_session) ->setFactors($factors) ->setFactorValidationResults($validation_results); } /** * Issue a high security token for a session, if authorized. * * @param PhabricatorAuthSession Session to issue a token for. * @param bool Force token issue. * @return PhabricatorAuthHighSecurityToken|null Token, if authorized. * @task hisec */ private function issueHighSecurityToken( PhabricatorAuthSession $session, $force = false) { if ($session->isHighSecuritySession() || $force) { return new PhabricatorAuthHighSecurityToken(); } return null; } /** * Render a form for providing relevant multi-factor credentials. * * @param PhabricatorUser Viewing user. * @param AphrontRequest Current request. * @return AphrontFormView Renderable form. * @task hisec */ public function renderHighSecurityForm( array $factors, array $validation_results, PhabricatorUser $viewer, AphrontRequest $request) { assert_instances_of($validation_results, 'PhabricatorAuthFactorResult'); $form = id(new AphrontFormView()) ->setUser($viewer) ->appendRemarkupInstructions(''); $answered = array(); foreach ($factors as $factor) { $result = $validation_results[$factor->getPHID()]; $provider = $factor->getFactorProvider(); $impl = $provider->getFactor(); $impl->renderValidateFactorForm( $factor, $form, $viewer, $result); $answered_challenge = $result->getAnsweredChallenge(); if ($answered_challenge) { $answered[] = $answered_challenge; } } $form->appendRemarkupInstructions(''); if ($answered) { $http_params = PhabricatorAuthChallenge::newHTTPParametersFromChallenges( $answered); foreach ($http_params as $key => $value) { $form->addHiddenInput($key, $value); } } return $form; } /** * Strip the high security flag from a session. * * Kicks a session out of high security and logs the exit. * * @param PhabricatorUser Acting user. * @param PhabricatorAuthSession Session to return to normal security. * @return void * @task hisec */ public function exitHighSecurity( PhabricatorUser $viewer, PhabricatorAuthSession $session) { if (!$session->getHighSecurityUntil()) { return; } queryfx( $session->establishConnection('w'), 'UPDATE %T SET highSecurityUntil = NULL WHERE id = %d', $session->getTableName(), $session->getID()); $log = PhabricatorUserLog::initializeNewLog( $viewer, $viewer->getPHID(), PhabricatorExitHisecUserLogType::LOGTYPE); $log->save(); } /* -( Partial Sessions )--------------------------------------------------- */ /** * Upgrade a partial session to a full session. * * @param PhabricatorAuthSession Session to upgrade. * @return void * @task partial */ public function upgradePartialSession(PhabricatorUser $viewer) { if (!$viewer->hasSession()) { throw new Exception( pht('Upgrading partial session of user with no session!')); } $session = $viewer->getSession(); if (!$session->getIsPartial()) { throw new Exception(pht('Session is not partial!')); } $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); $session->setIsPartial(0); queryfx( $session->establishConnection('w'), 'UPDATE %T SET isPartial = %d WHERE id = %d', $session->getTableName(), 0, $session->getID()); $log = PhabricatorUserLog::initializeNewLog( $viewer, $viewer->getPHID(), PhabricatorFullLoginUserLogType::LOGTYPE); $log->save(); unset($unguarded); } /* -( Legalpad Documents )-------------------------------------------------- */ /** * Upgrade a session to have all legalpad documents signed. * * @param PhabricatorUser User whose session should upgrade. * @param array LegalpadDocument objects * @return void * @task partial */ public function signLegalpadDocuments(PhabricatorUser $viewer, array $docs) { if (!$viewer->hasSession()) { throw new Exception( pht('Signing session legalpad documents of user with no session!')); } $session = $viewer->getSession(); if ($session->getSignedLegalpadDocuments()) { throw new Exception(pht( 'Session has already signed required legalpad documents!')); } $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); $session->setSignedLegalpadDocuments(1); queryfx( $session->establishConnection('w'), 'UPDATE %T SET signedLegalpadDocuments = %d WHERE id = %d', $session->getTableName(), 1, $session->getID()); if (!empty($docs)) { $log = PhabricatorUserLog::initializeNewLog( $viewer, $viewer->getPHID(), PhabricatorSignDocumentsUserLogType::LOGTYPE); $log->save(); } unset($unguarded); } /* -( One Time Login URIs )------------------------------------------------ */ /** * Retrieve a temporary, one-time URI which can log in to an account. * * These URIs are used for password recovery and to regain access to accounts * which users have been locked out of. * * @param PhabricatorUser User to generate a URI for. * @param PhabricatorUserEmail Optionally, email to verify when * link is used. * @param string Optional context string for the URI. This is purely cosmetic * and used only to customize workflow and error messages. * @param bool True to generate a URI which forces an immediate upgrade to * a full session, bypassing MFA and other login checks. * @return string Login URI. * @task onetime */ public function getOneTimeLoginURI( PhabricatorUser $user, PhabricatorUserEmail $email = null, $type = self::ONETIME_RESET, $force_full_session = false) { $key = Filesystem::readRandomCharacters(32); $key_hash = $this->getOneTimeLoginKeyHash($user, $email, $key); $onetime_type = PhabricatorAuthOneTimeLoginTemporaryTokenType::TOKENTYPE; $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); $token = id(new PhabricatorAuthTemporaryToken()) ->setTokenResource($user->getPHID()) ->setTokenType($onetime_type) ->setTokenExpires(time() + phutil_units('1 day in seconds')) ->setTokenCode($key_hash) ->setShouldForceFullSession($force_full_session) ->save(); unset($unguarded); $uri = '/login/once/'.$type.'/'.$user->getID().'/'.$key.'/'; if ($email) { $uri = $uri.$email->getID().'/'; } try { $uri = PhabricatorEnv::getProductionURI($uri); } catch (Exception $ex) { // If a user runs `bin/auth recover` before configuring the base URI, // just show the path. We don't have any way to figure out the domain. // See T4132. } return $uri; } /** * Load the temporary token associated with a given one-time login key. * * @param PhabricatorUser User to load the token for. * @param PhabricatorUserEmail Optionally, email to verify when * link is used. * @param string Key user is presenting as a valid one-time login key. * @return PhabricatorAuthTemporaryToken|null Token, if one exists. * @task onetime */ public function loadOneTimeLoginKey( PhabricatorUser $user, PhabricatorUserEmail $email = null, $key = null) { $key_hash = $this->getOneTimeLoginKeyHash($user, $email, $key); $onetime_type = PhabricatorAuthOneTimeLoginTemporaryTokenType::TOKENTYPE; return id(new PhabricatorAuthTemporaryTokenQuery()) ->setViewer($user) ->withTokenResources(array($user->getPHID())) ->withTokenTypes(array($onetime_type)) ->withTokenCodes(array($key_hash)) ->withExpired(false) ->executeOne(); } /** * Hash a one-time login key for storage as a temporary token. * * @param PhabricatorUser User this key is for. * @param PhabricatorUserEmail Optionally, email to verify when * link is used. * @param string The one time login key. * @return string Hash of the key. * task onetime */ private function getOneTimeLoginKeyHash( PhabricatorUser $user, PhabricatorUserEmail $email = null, $key = null) { $parts = array( $key, $user->getAccountSecret(), ); if ($email) { $parts[] = $email->getVerificationCode(); } return PhabricatorHash::weakDigest(implode(':', $parts)); } /* -( User Cache )--------------------------------------------------------- */ /** * @task cache */ private function getUserCacheQueryParts(AphrontDatabaseConnection $conn) { $cache_selects = array(); $cache_joins = array(); $cache_map = array(); $keys = array(); $types_map = array(); $cache_types = PhabricatorUserCacheType::getAllCacheTypes(); foreach ($cache_types as $cache_type) { foreach ($cache_type->getAutoloadKeys() as $autoload_key) { $keys[] = $autoload_key; $types_map[$autoload_key] = $cache_type; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
true
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/engine/PhabricatorAuthPasswordEngine.php
src/applications/auth/engine/PhabricatorAuthPasswordEngine.php
<?php final class PhabricatorAuthPasswordEngine extends Phobject { private $viewer; private $contentSource; private $object; private $passwordType; private $upgradeHashers = true; public function setViewer(PhabricatorUser $viewer) { $this->viewer = $viewer; return $this; } public function getViewer() { return $this->viewer; } public function setContentSource(PhabricatorContentSource $content_source) { $this->contentSource = $content_source; return $this; } public function getContentSource() { return $this->contentSource; } public function setObject(PhabricatorAuthPasswordHashInterface $object) { $this->object = $object; return $this; } public function getObject() { return $this->object; } public function setPasswordType($password_type) { $this->passwordType = $password_type; return $this; } public function getPasswordType() { return $this->passwordType; } public function setUpgradeHashers($upgrade_hashers) { $this->upgradeHashers = $upgrade_hashers; return $this; } public function getUpgradeHashers() { return $this->upgradeHashers; } public function checkNewPassword( PhutilOpaqueEnvelope $password, PhutilOpaqueEnvelope $confirm, $can_skip = false) { $raw_password = $password->openEnvelope(); if (!strlen($raw_password)) { if ($can_skip) { throw new PhabricatorAuthPasswordException( pht('You must choose a password or skip this step.'), pht('Required')); } else { throw new PhabricatorAuthPasswordException( pht('You must choose a password.'), pht('Required')); } } $min_len = PhabricatorEnv::getEnvConfig('account.minimum-password-length'); $min_len = (int)$min_len; if ($min_len) { if (strlen($raw_password) < $min_len) { throw new PhabricatorAuthPasswordException( pht( 'The selected password is too short. Passwords must be a minimum '. 'of %s characters long.', new PhutilNumber($min_len)), pht('Too Short')); } } $raw_confirm = $confirm->openEnvelope(); if (!strlen($raw_confirm)) { throw new PhabricatorAuthPasswordException( pht('You must confirm the selected password.'), null, pht('Required')); } if ($raw_password !== $raw_confirm) { throw new PhabricatorAuthPasswordException( pht('The password and confirmation do not match.'), pht('Invalid'), pht('Invalid')); } if (PhabricatorCommonPasswords::isCommonPassword($raw_password)) { throw new PhabricatorAuthPasswordException( pht( 'The selected password is very weak: it is one of the most common '. 'passwords in use. Choose a stronger password.'), pht('Very Weak')); } // If we're creating a brand new object (like registering a new user) // and it does not have a PHID yet, it isn't possible for it to have any // revoked passwords or colliding passwords either, so we can skip these // checks. $object = $this->getObject(); if ($object->getPHID()) { if ($this->isRevokedPassword($password)) { throw new PhabricatorAuthPasswordException( pht( 'The password you entered has been revoked. You can not reuse '. 'a password which has been revoked. Choose a new password.'), pht('Revoked')); } if (!$this->isUniquePassword($password)) { throw new PhabricatorAuthPasswordException( pht( 'The password you entered is the same as another password '. 'associated with your account. Each password must be unique.'), pht('Not Unique')); } } // Prevent use of passwords which are similar to any object identifier. // For example, if your username is "alincoln", your password may not be // "alincoln", "lincoln", or "alincoln1". $viewer = $this->getViewer(); $blocklist = $object->newPasswordBlocklist($viewer, $this); // Smallest number of overlapping characters that we'll consider to be // too similar. $minimum_similarity = 4; // Add the domain name to the blocklist. $base_uri = PhabricatorEnv::getAnyBaseURI(); $base_uri = new PhutilURI($base_uri); $blocklist[] = $base_uri->getDomain(); // Generate additional subterms by splitting the raw blocklist on // characters like "@", " " (space), and "." to break up email addresses, // readable names, and domain names into components. $terms_map = array(); foreach ($blocklist as $term) { $terms_map[$term] = $term; foreach (preg_split('/[ @.]/', $term) as $subterm) { $terms_map[$subterm] = $term; } } // Skip very short terms: it's okay if your password has the substring // "com" in it somewhere even if the install is on "mycompany.com". foreach ($terms_map as $term => $source) { if (strlen($term) < $minimum_similarity) { unset($terms_map[$term]); } } // Normalize terms for comparison. $normal_map = array(); foreach ($terms_map as $term => $source) { $term = phutil_utf8_strtolower($term); $normal_map[$term] = $source; } // Finally, make sure that none of the terms appear in the password, // and that the password does not appear in any of the terms. $normal_password = phutil_utf8_strtolower($raw_password); if (strlen($normal_password) >= $minimum_similarity) { foreach ($normal_map as $term => $source) { // See T2312. This may be required if the term list includes numeric // strings like "12345", which will be cast to integers when used as // array keys. $term = phutil_string_cast($term); if (strpos($term, $normal_password) === false && strpos($normal_password, $term) === false) { continue; } throw new PhabricatorAuthPasswordException( pht( 'The password you entered is very similar to a nonsecret account '. 'identifier (like a username or email address). Choose a more '. 'distinct password.'), pht('Not Distinct')); } } } public function isValidPassword(PhutilOpaqueEnvelope $envelope) { $this->requireSetup(); $password_type = $this->getPasswordType(); $passwords = $this->newQuery() ->withPasswordTypes(array($password_type)) ->withIsRevoked(false) ->execute(); $matches = $this->getMatches($envelope, $passwords); if (!$matches) { return false; } if ($this->shouldUpgradeHashers()) { $this->upgradeHashers($envelope, $matches); } return true; } public function isUniquePassword(PhutilOpaqueEnvelope $envelope) { $this->requireSetup(); $password_type = $this->getPasswordType(); // To test that the password is unique, we're loading all active and // revoked passwords for all roles for the given user, then throwing out // the active passwords for the current role (so a password can't // collide with itself). // Note that two different objects can have the same password (say, // users @alice and @bailey). We're only preventing @alice from using // the same password for everything. $passwords = $this->newQuery() ->execute(); foreach ($passwords as $key => $password) { $same_type = ($password->getPasswordType() === $password_type); $is_active = !$password->getIsRevoked(); if ($same_type && $is_active) { unset($passwords[$key]); } } $matches = $this->getMatches($envelope, $passwords); return !$matches; } public function isRevokedPassword(PhutilOpaqueEnvelope $envelope) { $this->requireSetup(); // To test if a password is revoked, we're loading all revoked passwords // across all roles for the given user. If a password was revoked in one // role, you can't reuse it in a different role. $passwords = $this->newQuery() ->withIsRevoked(true) ->execute(); $matches = $this->getMatches($envelope, $passwords); return (bool)$matches; } private function requireSetup() { if (!$this->getObject()) { throw new PhutilInvalidStateException('setObject'); } if (!$this->getPasswordType()) { throw new PhutilInvalidStateException('setPasswordType'); } if (!$this->getViewer()) { throw new PhutilInvalidStateException('setViewer'); } if ($this->shouldUpgradeHashers()) { if (!$this->getContentSource()) { throw new PhutilInvalidStateException('setContentSource'); } } } private function shouldUpgradeHashers() { if (!$this->getUpgradeHashers()) { return false; } if (PhabricatorEnv::isReadOnly()) { // Don't try to upgrade hashers if we're in read-only mode, since we // won't be able to write the new hash to the database. return false; } return true; } private function newQuery() { $viewer = $this->getViewer(); $object = $this->getObject(); $password_type = $this->getPasswordType(); return id(new PhabricatorAuthPasswordQuery()) ->setViewer($viewer) ->withObjectPHIDs(array($object->getPHID())); } private function getMatches( PhutilOpaqueEnvelope $envelope, array $passwords) { $object = $this->getObject(); $matches = array(); foreach ($passwords as $password) { try { $is_match = $password->comparePassword($envelope, $object); } catch (PhabricatorPasswordHasherUnavailableException $ex) { $is_match = false; } if ($is_match) { $matches[] = $password; } } return $matches; } private function upgradeHashers( PhutilOpaqueEnvelope $envelope, array $passwords) { assert_instances_of($passwords, 'PhabricatorAuthPassword'); $need_upgrade = array(); foreach ($passwords as $password) { if (!$password->canUpgrade()) { continue; } $need_upgrade[] = $password; } if (!$need_upgrade) { return; } $upgrade_type = PhabricatorAuthPasswordUpgradeTransaction::TRANSACTIONTYPE; $viewer = $this->getViewer(); $content_source = $this->getContentSource(); $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); foreach ($need_upgrade as $password) { // This does the actual upgrade. We then apply a transaction to make // the upgrade more visible and auditable. $old_hasher = $password->getHasher(); $password->upgradePasswordHasher($envelope, $this->getObject()); $new_hasher = $password->getHasher(); // NOTE: We must save the change before applying transactions because // the editor will reload the object to obtain a read lock. $password->save(); $xactions = array(); $xactions[] = $password->getApplicationTransactionTemplate() ->setTransactionType($upgrade_type) ->setNewValue($new_hasher->getHashName()); $editor = $password->getApplicationTransactionEditor() ->setActor($viewer) ->setContinueOnNoEffect(true) ->setContinueOnMissingFields(true) ->setContentSource($content_source) ->setOldHasher($old_hasher) ->applyTransactions($password, $xactions); } unset($unguarded); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/engine/PhabricatorAuthSessionEngineExtension.php
src/applications/auth/engine/PhabricatorAuthSessionEngineExtension.php
<?php abstract class PhabricatorAuthSessionEngineExtension extends Phobject { final public function getExtensionKey() { return $this->getPhobjectClassConstant('EXTENSIONKEY'); } final public static function getAllExtensions() { return id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->setUniqueMethod('getExtensionKey') ->execute(); } abstract public function getExtensionName(); public function didEstablishSession(PhabricatorAuthSessionInfo $info) { return; } public function willServeRequestForUser(PhabricatorUser $user) { return; } public function didLogout(PhabricatorUser $user, array $sessions) { return; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/engine/PhabricatorAuthCSRFEngine.php
src/applications/auth/engine/PhabricatorAuthCSRFEngine.php
<?php final class PhabricatorAuthCSRFEngine extends Phobject { private $salt; private $secret; public function setSalt($salt) { $this->salt = $salt; return $this; } public function getSalt() { return $this->salt; } public function setSecret(PhutilOpaqueEnvelope $secret) { $this->secret = $secret; return $this; } public function getSecret() { return $this->secret; } public function newSalt() { $salt_length = $this->getSaltLength(); return Filesystem::readRandomCharacters($salt_length); } public function newToken() { $salt = $this->getSalt(); if (!$salt) { throw new PhutilInvalidStateException('setSalt'); } $token = $this->newRawToken($salt); $prefix = $this->getBREACHPrefix(); return sprintf('%s%s%s', $prefix, $salt, $token); } public function isValidToken($token) { $salt_length = $this->getSaltLength(); // We expect a BREACH-mitigating token. See T3684. $breach_prefix = $this->getBREACHPrefix(); $breach_prelen = strlen($breach_prefix); if (strncmp($token, $breach_prefix, $breach_prelen) !== 0) { return false; } $salt = substr($token, $breach_prelen, $salt_length); $token = substr($token, $breach_prelen + $salt_length); foreach ($this->getWindowOffsets() as $offset) { $expect_token = $this->newRawToken($salt, $offset); if (phutil_hashes_are_identical($expect_token, $token)) { return true; } } return false; } private function newRawToken($salt, $offset = 0) { $now = PhabricatorTime::getNow(); $cycle_frequency = $this->getCycleFrequency(); $time_block = (int)floor($now / $cycle_frequency); $time_block = $time_block + $offset; $secret = $this->getSecret(); if (!$secret) { throw new PhutilInvalidStateException('setSecret'); } $secret = $secret->openEnvelope(); $hash = PhabricatorHash::digestWithNamedKey( $secret.$time_block.$salt, 'csrf'); return substr($hash, 0, $this->getTokenLength()); } private function getBREACHPrefix() { return 'B@'; } private function getSaltLength() { return 8; } private function getTokenLength() { return 16; } private function getCycleFrequency() { return phutil_units('1 hour in seconds'); } private function getWindowOffsets() { // We accept some tokens from the recent past and near future. Users may // have older tokens if they close their laptop and open it up again // later. Users may have newer tokens if there are multiple web hosts with // a bit of clock skew. // Javascript on the client tries to keep CSRF tokens up to date, but // it may fail, and it doesn't run if the user closes their laptop. // The window during which our tokens remain valid is generally more // conservative than other platforms. For example, Rails uses "session // duration" and Django uses "forever". return range(-6, 1); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/engine/PhabricatorAuthSessionEngineExtensionModule.php
src/applications/auth/engine/PhabricatorAuthSessionEngineExtensionModule.php
<?php final class PhabricatorAuthSessionEngineExtensionModule extends PhabricatorConfigModule { public function getModuleKey() { return 'sessionengine'; } public function getModuleName() { return pht('Engine: Session'); } public function renderModuleStatus(AphrontRequest $request) { $viewer = $request->getViewer(); $extensions = PhabricatorAuthSessionEngineExtension::getAllExtensions(); $rows = array(); foreach ($extensions as $extension) { $rows[] = array( get_class($extension), $extension->getExtensionKey(), $extension->getExtensionName(), ); } return id(new AphrontTableView($rows)) ->setNoDataString( pht('There are no registered session engine extensions.')) ->setHeaders( array( pht('Class'), pht('Key'), pht('Name'), )) ->setColumnClasses( array( null, null, 'wide pri', )); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/capability/AuthManageProvidersCapability.php
src/applications/auth/capability/AuthManageProvidersCapability.php
<?php final class AuthManageProvidersCapability extends PhabricatorPolicyCapability { const CAPABILITY = 'auth.manage.providers'; public function getCapabilityName() { return pht('Can Manage Auth Providers'); } public function describeCapabilityRejection() { return pht( 'You do not have permission to manage authentication providers.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/adapter/PhutilEmptyAuthAdapter.php
src/applications/auth/adapter/PhutilEmptyAuthAdapter.php
<?php /** * Empty authentication adapter with no logic. * * This adapter can be used when you need an adapter for some technical reason * but it doesn't make sense to put logic inside it. */ final class PhutilEmptyAuthAdapter extends PhutilAuthAdapter { private $accountID; private $adapterType; private $adapterDomain; public function setAdapterDomain($adapter_domain) { $this->adapterDomain = $adapter_domain; return $this; } public function getAdapterDomain() { return $this->adapterDomain; } public function setAdapterType($adapter_type) { $this->adapterType = $adapter_type; return $this; } public function getAdapterType() { return $this->adapterType; } public function setAccountID($account_id) { $this->accountID = $account_id; return $this; } public function getAccountID() { return $this->accountID; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/adapter/PhutilAsanaAuthAdapter.php
src/applications/auth/adapter/PhutilAsanaAuthAdapter.php
<?php /** * Authentication adapter for Asana OAuth2. */ final class PhutilAsanaAuthAdapter extends PhutilOAuthAuthAdapter { public function getAdapterType() { return 'asana'; } public function getAdapterDomain() { return 'asana.com'; } public function getAccountID() { // See T13453. The Asana API has changed to string IDs and now returns a // "gid" field (previously, it returned an "id" field). return $this->getOAuthAccountData('gid'); } public function getAccountEmail() { return $this->getOAuthAccountData('email'); } public function getAccountName() { return null; } public function getAccountImageURI() { $photo = $this->getOAuthAccountData('photo', array()); if (is_array($photo)) { return idx($photo, 'image_128x128'); } else { return null; } } public function getAccountURI() { return null; } public function getAccountRealName() { return $this->getOAuthAccountData('name'); } protected function getAuthenticateBaseURI() { return 'https://app.asana.com/-/oauth_authorize'; } protected function getTokenBaseURI() { return 'https://app.asana.com/-/oauth_token'; } public function getScope() { return null; } public function getExtraAuthenticateParameters() { return array( 'response_type' => 'code', ); } public function getExtraTokenParameters() { return array( 'grant_type' => 'authorization_code', ); } public function getExtraRefreshParameters() { return array( 'grant_type' => 'refresh_token', ); } public function supportsTokenRefresh() { return true; } protected function loadOAuthAccountData() { return id(new PhutilAsanaFuture()) ->setAccessToken($this->getAccessToken()) ->setRawAsanaQuery('users/me') ->resolve(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false