From 0f0a3012806e4ba8f154d575681c9cd6a6027e14 Mon Sep 17 00:00:00 2001 From: Michael Date: Tue, 8 Jun 2021 17:32:41 +0000 Subject: [PATCH 1/6] Move basic auth functionality to the new class --- src/Security/BasicAuth.php | 97 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 94 insertions(+), 3 deletions(-) diff --git a/src/Security/BasicAuth.php b/src/Security/BasicAuth.php index 18564d289..2f47a9337 100644 --- a/src/Security/BasicAuth.php +++ b/src/Security/BasicAuth.php @@ -21,8 +21,15 @@ namespace Friendica\Security; +use Exception; +use Friendica\Core\Hook; +use Friendica\Core\Logger; +use Friendica\Core\Session; use Friendica\Database\DBA; use Friendica\DI; +use Friendica\Model\User; +use Friendica\Network\HTTPException\UnauthorizedException; +use Friendica\Util\DateTimeFormat; /** * Authentification via the basic auth method @@ -49,9 +56,7 @@ class BasicAuth public static function getCurrentUserID(bool $login) { if (empty(self::$current_user_id)) { - api_login(DI::app(), $login); - - self::$current_user_id = api_user(); + self::$current_user_id = self::getUserIdByAuth($login); } return (int)self::$current_user_id; @@ -85,4 +90,90 @@ class BasicAuth return self::$current_token; } + + /** + * Fetch the user id via the auth header information + * + * @param boolean $do_login Perform a login request if not logged in + * + * @return integer User ID + */ + private static function getUserIdByAuth(bool $do_login = true):int + { + $a = DI::app(); + Session::set('allow_api', false); + self::$current_user_id = 0; + + // workaround for HTTP-auth in CGI mode + if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) { + $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)); + if (strlen($userpass)) { + list($name, $password) = explode(':', $userpass); + $_SERVER['PHP_AUTH_USER'] = $name; + $_SERVER['PHP_AUTH_PW'] = $password; + } + } + + $user = $_SERVER['PHP_AUTH_USER'] ?? ''; + $password = $_SERVER['PHP_AUTH_PW'] ?? ''; + + // allow "user@server" login (but ignore 'server' part) + $at = strstr($user, "@", true); + if ($at) { + $user = $at; + } + + // next code from mod/auth.php. needs better solution + $record = null; + + $addon_auth = [ + 'username' => trim($user), + 'password' => trim($password), + 'authenticated' => 0, + 'user_record' => null, + ]; + + /* + * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record + * Addons should never set 'authenticated' except to indicate success - as hooks may be chained + * and later addons should not interfere with an earlier one that succeeded. + */ + Hook::callAll('authenticate', $addon_auth); + + if ($addon_auth['authenticated'] && !empty($addon_auth['user_record'])) { + $record = $addon_auth['user_record']; + } else { + try { + $user_id = User::getIdFromPasswordAuthentication(trim($user), trim($password), true); + $record = DBA::selectFirst('user', [], ['uid' => $user_id]); + } catch (Exception $ex) { + $record = []; + } + } + + if (empty($record)) { + if (!$do_login) { + return 0; + } + Logger::debug('failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]); + header('WWW-Authenticate: Basic realm="Friendica"'); + throw new UnauthorizedException("This API requires login"); + } + + // Don't refresh the login date more often than twice a day to spare database writes + $login_refresh = strcmp(DateTimeFormat::utc('now - 12 hours'), $record['login_date']) > 0; + + DI::auth()->setForUser($a, $record, false, false, $login_refresh); + + Session::set('allow_api', true); + + Hook::callAll('logged_in', $a->user); + + if (Session::get('allow_api')) { + self::$current_user_id = local_user(); + } else { + self::$current_user_id = 0; + } + return self::$current_user_id; + } } From 8bf5dd187b5892e0724b66ab75c6896c55b21f99 Mon Sep 17 00:00:00 2001 From: Michael Date: Tue, 8 Jun 2021 17:48:41 +0000 Subject: [PATCH 2/6] Added "source" detection --- src/Security/BasicAuth.php | 49 +++++++++++++++++++++++++------------- 1 file changed, 33 insertions(+), 16 deletions(-) diff --git a/src/Security/BasicAuth.php b/src/Security/BasicAuth.php index 2f47a9337..b76073e8b 100644 --- a/src/Security/BasicAuth.php +++ b/src/Security/BasicAuth.php @@ -77,10 +77,27 @@ class BasicAuth return self::$current_token; } + $source = $_REQUEST['source'] ?? ''; + + // Support for known clients that doesn't send a source name + if (empty($source) && !empty($_SERVER['HTTP_USER_AGENT'])) { + if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) { + $source = 'Twidere'; + } + + Logger::info('Unrecognized user-agent', ['http_user_agent' => $_SERVER['HTTP_USER_AGENT']]); + } else { + Logger::info('Empty user-agent'); + } + + if (empty($source)) { + $source = 'api'; + } + self::$current_token = [ 'uid' => self::$current_user_id, 'id' => 0, - 'name' => api_source(), + 'name' => $source, 'website' => '', 'created_at' => DBA::NULL_DATETIME, 'read' => true, @@ -114,32 +131,32 @@ class BasicAuth } } - $user = $_SERVER['PHP_AUTH_USER'] ?? ''; + $user = $_SERVER['PHP_AUTH_USER'] ?? ''; $password = $_SERVER['PHP_AUTH_PW'] ?? ''; - + // allow "user@server" login (but ignore 'server' part) $at = strstr($user, "@", true); if ($at) { $user = $at; } - + // next code from mod/auth.php. needs better solution $record = null; - + $addon_auth = [ 'username' => trim($user), 'password' => trim($password), 'authenticated' => 0, 'user_record' => null, ]; - + /* * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record * Addons should never set 'authenticated' except to indicate success - as hooks may be chained * and later addons should not interfere with an earlier one that succeeded. */ Hook::callAll('authenticate', $addon_auth); - + if ($addon_auth['authenticated'] && !empty($addon_auth['user_record'])) { $record = $addon_auth['user_record']; } else { @@ -148,32 +165,32 @@ class BasicAuth $record = DBA::selectFirst('user', [], ['uid' => $user_id]); } catch (Exception $ex) { $record = []; - } + } } - + if (empty($record)) { if (!$do_login) { return 0; } - Logger::debug('failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]); + Logger::debug('Access denied', ['parameters' => $_SERVER]); header('WWW-Authenticate: Basic realm="Friendica"'); throw new UnauthorizedException("This API requires login"); } - + // Don't refresh the login date more often than twice a day to spare database writes $login_refresh = strcmp(DateTimeFormat::utc('now - 12 hours'), $record['login_date']) > 0; - + DI::auth()->setForUser($a, $record, false, false, $login_refresh); - + Session::set('allow_api', true); - + Hook::callAll('logged_in', $a->user); - + if (Session::get('allow_api')) { self::$current_user_id = local_user(); } else { self::$current_user_id = 0; } return self::$current_user_id; - } + } } From e4be1e0cd57d64c6d11e185218b26e488ce3bd1a Mon Sep 17 00:00:00 2001 From: Michael Date: Tue, 8 Jun 2021 20:41:46 +0000 Subject: [PATCH 3/6] Get rid of "api_user()" function --- src/Module/BaseApi.php | 24 ++++++++---------------- 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/src/Module/BaseApi.php b/src/Module/BaseApi.php index adad7636a..af5298cce 100644 --- a/src/Module/BaseApi.php +++ b/src/Module/BaseApi.php @@ -61,52 +61,44 @@ class BaseApi extends BaseModule public static function delete(array $parameters = []) { - if (!api_user()) { - throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.')); - } + self::checkAllowedScope(self::SCOPE_WRITE); $a = DI::app(); - if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) { + if (!empty($a->user['uid']) && $a->user['uid'] != self::getCurrentUserID()) { throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.')); } } public static function patch(array $parameters = []) { - if (!api_user()) { - throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.')); - } + self::checkAllowedScope(self::SCOPE_WRITE); $a = DI::app(); - if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) { + if (!empty($a->user['uid']) && $a->user['uid'] != self::getCurrentUserID()) { throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.')); } } public static function post(array $parameters = []) { - if (!api_user()) { - throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.')); - } + self::checkAllowedScope(self::SCOPE_WRITE); $a = DI::app(); - if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) { + if (!empty($a->user['uid']) && $a->user['uid'] != self::getCurrentUserID()) { throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.')); } } public static function put(array $parameters = []) { - if (!api_user()) { - throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.')); - } + self::checkAllowedScope(self::SCOPE_WRITE); $a = DI::app(); - if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) { + if (!empty($a->user['uid']) && $a->user['uid'] != self::getCurrentUserID()) { throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.')); } } From 385c03364f61b234924c787e090c9b7e44859bee Mon Sep 17 00:00:00 2001 From: Michael Date: Tue, 8 Jun 2021 20:45:58 +0000 Subject: [PATCH 4/6] The function is now protected again --- src/Module/BaseApi.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Module/BaseApi.php b/src/Module/BaseApi.php index af5298cce..bae466c90 100644 --- a/src/Module/BaseApi.php +++ b/src/Module/BaseApi.php @@ -181,7 +181,7 @@ class BaseApi extends BaseModule * * @return int User ID */ - public static function getCurrentUserID() + protected static function getCurrentUserID() { $uid = OAuth::getCurrentUserID(); From 3d219e1d0065df08324a12b21d53cb48e536f00f Mon Sep 17 00:00:00 2001 From: Michael Date: Wed, 9 Jun 2021 02:53:26 +0000 Subject: [PATCH 5/6] Amaroq is said to be working as well --- doc/API-Mastodon.md | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/API-Mastodon.md b/doc/API-Mastodon.md index 85e23f525..cff3829ca 100644 --- a/doc/API-Mastodon.md +++ b/doc/API-Mastodon.md @@ -20,6 +20,7 @@ Supported mobile apps: - [Twidere](https://github.com/TwidereProject/) - [twitlatte](https://github.com/moko256/twitlatte) - [Yuito](https://github.com/accelforce/Yuito) +- [Amaroq](https://github.com/ReticentJohn/Amaroq/tree/master) Unsupported mobile apps: From d5aeb8f12c590c24dc5555a3a7cfbf4b2e3f1ea2 Mon Sep 17 00:00:00 2001 From: Michael Date: Wed, 9 Jun 2021 05:16:27 +0000 Subject: [PATCH 6/6] Added more apps --- doc/API-Mastodon.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/doc/API-Mastodon.md b/doc/API-Mastodon.md index cff3829ca..34ce884fa 100644 --- a/doc/API-Mastodon.md +++ b/doc/API-Mastodon.md @@ -11,7 +11,7 @@ Authentication is the same as described in [Using the APIs](help/api#Authenticat ## Clients -Supported mobile apps: +Supported apps: - [AndStatus](http://andstatus.org) - [Husky](https://husky.fwgs.ru) @@ -22,10 +22,15 @@ Supported mobile apps: - [Yuito](https://github.com/accelforce/Yuito) - [Amaroq](https://github.com/ReticentJohn/Amaroq/tree/master) -Unsupported mobile apps: +Unsupported apps: - [Fedilab](https://framagit.org/tom79/fedilab) Automatically uses the legacy API, see issue: https://framagit.org/tom79/fedilab/-/issues/520 - [Mammut](https://github.com/jamiesanson/Mammut) There are problems with the token request, see issue https://github.com/jamiesanson/Mammut/issues/19 +- [Mast](https://github.com/Beesitech/Mast) Doesn't accept the entered instance name. Claims that it is invalid (Message is: "Not a valid instance (may be closed or dead)") +- [Pinafore](https://github.com/nolanlawson/pinafore) Returns message "Error: NetworkError when attempting to fetch resource.. Is this a valid Mastodon instance?" +- [Mastonaut](https://mastonaut.app/) +- [Toot!](https://apps.apple.com/app/toot/id1229021451) +- [Halycon](https://www.halcyon.social/) Doesn't load content, creates masses of HTTP requests ## Entities