[FreeNetwork] First steps porting webfinger/lrdd to v3, GET webfinger requests already have a basic result

This commit is contained in:
Diogo Peralta Cordeiro 2021-10-18 13:22:02 +01:00
parent 44cf1fa24c
commit 8544fe157b
Signed by: diogo
GPG Key ID: 18D2D35001FBFAB0
161 changed files with 5163 additions and 103 deletions

View File

@ -0,0 +1,29 @@
<?php
/**
* @author James Walker <james@status.net>
* @author Craig Andrews <candrews@integralblue.com>
* @author Mikael Nordfeldth <mmn@hethane.se>
*/
namespace Component\FreeNetwork\Controller;
use App\Core\Controller;
use App\Core\Event;
use Component\FreeNetwork\Util\Discovery;
use Component\FreeNetwork\Util\XrdController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use XML_XRD;
class HostMeta extends XrdController
{
protected string $default_mimetype = Discovery::XRD_MIMETYPE;
public function setXRD()
{
if (Event::handle('StartHostMetaLinks', [&$this->xrd->links])) {
Event::handle('EndHostMetaLinks', [&$this->xrd->links]);
}
}
}

View File

@ -0,0 +1,62 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
namespace Component\FreeNetwork\Controller;
/**
* @package WebFingerPlugin
*
* @author James Walker <james@status.net>
* @author Mikael Nordfeldth <mmn@hethane.se>
* @copyright 2010 StatusNet, Inc.
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
use App\Entity\LocalUser;
use App\Util\Common;
use Component\FreeNetwork\Util\Discovery;
use Component\FreeNetwork\Util\XrdController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class OwnerXrd extends XrdController
{
protected string $default_mimetype = Discovery::XRD_MIMETYPE;
public function handle(Request $request): array
{
$user = LocalUser::siteOwner();
$nick = common_canonical_nickname($user->nickname);
$this->resource = 'acct:' . $nick . '@' . Common::config('site', 'server');
// We have now set $args['resource'] to the configured value, since
// only this local site configuration knows who the owner is!
return parent::handle($request);
}
protected function setXRD()
{
// Check to see if a $config['webfinger']['owner'] has been set
// and then make sure 'subject' is set to that primary identity.
if (!empty($owner = Common::config('webfinger', 'owner'))) {
$this->xrd->aliases[] = $this->xrd->subject;
$this->xrd->subject = Discovery::normalize($owner);
} else {
$this->xrd->subject = $this->resource;
}
}
}

View File

@ -0,0 +1,76 @@
<?php
/*
* StatusNet - the distributed open-source microblogging tool
* Copyright (C) 2010, StatusNet, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Component\FreeNetwork\Controller;
use App\Core\Event;
use function App\Core\I18n\_m;
use App\Util\Exception\ClientException;
use App\Util\Exception\NoSuchActorException;
use Component\FreeNetwork\Util\Discovery;
use Component\FreeNetwork\Util\WebfingerResource;
use Component\FreeNetwork\Util\XrdController;
use Symfony\Component\HttpFoundation\Request;
/**
* @package WebFingerPlugin
*
* @author James Walker <james@status.net>
* @author Mikael Nordfeldth <mmn@hethane.se>
* @author Diogo Peralta Cordeiro
*/
class Webfinger extends XrdController
{
protected $resource; // string with the resource URI
protected $target; // object of the WebFingerResource class
public function handle(Request $request): array
{
// throws exception if resource is empty
$this->resource = Discovery::normalize($this->string('resource'));
try {
if (Event::handle('StartGetWebFingerResource', [$this->resource, &$this->target, $this->params()])) {
Event::handle('EndGetWebFingerResource', [$this->resource, &$this->target, $this->params()]);
}
} catch (NoSuchActorException $e) {
throw new ClientException($e->getMessage(), 404);
}
if (!$this->target instanceof WebfingerResource) {
// TRANS: Error message when an object URI which we cannot find was requested
throw new ClientException(_m('Resource not found in local database.'), 404);
}
return parent::handle($request);
}
protected function setXRD()
{
$this->xrd->subject = $this->resource;
foreach ($this->target->getAliases() as $alias) {
if ($alias != $this->xrd->subject && !in_array($alias, $this->xrd->aliases)) {
$this->xrd->aliases[] = $alias;
}
}
$this->target->updateXRD($this->xrd);
}
}

View File

@ -0,0 +1,46 @@
StartHostMetaLinks: Start /.well-known/host-meta links
- &links: array containing the links elements to be written
EndHostMetaLinks: End /.well-known/host-meta links
- &links: array containing the links elements to be written
StartGetWebFingerResource: Get a WebFingerResource extended object by resource string
- $resource String that contains the requested URI
- &$target WebFingerResource extended object goes here
- $args Array which may contains arguments such as 'rel' filtering values
EndGetWebFingerResource: Last attempts getting a WebFingerResource object
- $resource String that contains the requested URI
- &$target WebFingerResource extended object goes here
- $args Array which may contains arguments such as 'rel' filtering values
StartWebFingerReconstruction: Generate an acct: uri from a Profile object
- $profile: Profile object for which we want a WebFinger ID
- &$acct: String reference where reconstructed ID is stored
EndWebFingerReconstruction: Last attempts to generate an acct: uri from a Profile object
- $profile: Profile object for which we want a WebFinger ID
- &$acct: String reference where reconstructed ID is stored
StartWebFingerNoticeLinks: About to set links for the resource descriptor of a Notice
- $xrd: XML_XRD object being shown
- $target: Notice being shown
EndWebFingerNoticeLinks: Done with links for the resource descriptor of a Notice
- $xrd: XML_XRD object being shown
- $target: Notice being shown
StartWebFingerProfileLinks: About to set links for the resource descriptor of a Profile
- $xrd: XML_XRD object being shown
- $target: Profile being shown
EndWebFingerProfileLinks: Done with links for the resource descriptor of a Profile
- $xrd: XML_XRD object being shown
- $target: Profile being shown
StartDiscoveryMethodRegistration
- $disco: Discovery object that accepts the registrations
EndDiscoveryMethodRegistration: Register remote URI discovery methods
- $disco: Discovery object that accepts the registrations

View File

@ -48,21 +48,20 @@ class FreenetworkActor extends Entity
{
// {{{ Autocode
// @codeCoverageIgnoreStart
private string $actor_uri;
private string $source;
private string $profile_page;
private int $actor_id;
private bool $is_local;
private DateTimeInterface $created;
private DateTimeInterface $modified;
public function getActorUri(): string
public function getProfilepage(): string
{
return $this->actor_uri;
return $this->profile_page;
}
public function setActorUri(string $actor_uri): void
public function setProfilepage(string $profile_page): void
{
$this->actor_uri = $actor_uri;
$this->profile_page = $profile_page;
}
public function getSource(): string
@ -85,7 +84,7 @@ class FreenetworkActor extends Entity
$this->actor_id = $actor_id;
}
public function isIsLocal(): bool
public function getIsLocal(): bool
{
return $this->is_local;
}
@ -117,35 +116,15 @@ class FreenetworkActor extends Entity
// @codeCoverageIgnoreEnd
// }}} Autocode
public static function getOrCreateById($actor_id, $source): self
public static function getOrCreateByRemoteUri($actor_uri): self
{
$fnactor = self::getWithPK(['actor_id' => $actor_id, 'source' => $source]);
if ($fnactor === null) {
$actor_uri = null;
Event::handle('FreeNetworkGenerateLocalActorUri', [$source, $actor_id, &$actor_uri]);
$fnactor = self::create([
'actor_uri' => $actor_uri,
'source' => $source,
'actor_id' => $actor_id,
'is_local' => true,
]);
DB::persist($fnactor);
return $fnactor;
} else {
return $fnactor;
}
}
public static function getOrCreateByUri($actor_uri, $source): self
{
$fnactor = DB::findBy('freenetwork_actor', ['actor_uri' => $actor_uri, 'source' => $source]);
$fnactor = DB::findBy('freenetwork_actor', ['profile_page' => $actor_uri, 'is_local' => false]);
if ($fnactor === []) {
// TODO grab with webfinger
// If already has for a different protocol and isn't local, update
// else create actor and then fnactor
$fnactor = self::create([
'actor_uri' => $actor_uri,
'source' => $source,
'profile_page' => $actor_uri,
'actor_id' => 1,
'is_local' => false,
]);
@ -161,16 +140,15 @@ class FreenetworkActor extends Entity
return [
'name' => 'freenetwork_actor',
'fields' => [
'actor_uri' => ['type' => 'text', 'not null' => true],
'source' => ['type' => 'varchar', 'not null' => true, 'foreign key' => true, 'length' => 32, 'target' => 'NoteSource.code', 'multiplicity' => 'many to one', 'description' => 'fkey to source of note, like "web", "im", or "clientname"'],
'actor_id' => ['type' => 'int', 'not null' => true],
'is_local' => ['type' => 'bool', 'not null' => true, 'description' => 'whether this was a locally generated or an imported actor'],
'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'],
'modified' => ['type' => 'timestamp', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'],
'profile_page' => ['type' => 'text', 'not null' => true],
'actor_id' => ['type' => 'int', 'not null' => true],
'is_local' => ['type' => 'bool', 'not null' => true, 'description' => 'whether this was a locally generated or an imported actor'],
'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'],
'modified' => ['type' => 'timestamp', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'],
],
'primary key' => ['actor_id', 'source'],
'primary key' => ['profile_page'],
'indexes' => [
'freenetwork_actor_uri_idx' => ['actor_uri', 'source'],
'freenetwork_profile_page_idx' => ['actor_id'],
],
'foreign keys' => [
'freenetwork_actor_actor_id_fkey' => ['actor', ['actor_id' => 'id']],

View File

@ -0,0 +1,58 @@
<?php
/**
* StatusNet, the distributed open-source microblogging tool
*
* Class for an exception when a WebFinger acct: URI can not be constructed
* using the data we have in a Profile.
*
* PHP version 5
*
* LICENCE: This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @category Exception
* @package StatusNet
*
* @author Mikael Nordfeldth <mmn@hethane.se>
* @copyright 2013 Free Software Foundation, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
*
* @see http://status.net/
*/
namespace Component\FreeNetwork\Exception;
use function App\Core\I18n\_m;
use App\Util\Exception\ServerException;
use Throwable;
/**
* Class for an exception when a WebFinger acct: URI can not be constructed
* using the data we have in a Profile.
*
* @category Exception
* @package StatusNet
*
* @author Mikael Nordfeldth <mmn@hethane.se>
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
*
* @see http://status.net/
*/
class WebfingerReconstructionException extends ServerException
{
public function __construct(string $message = '', int $code = 500, Throwable $previous = null)
{
// We could log an entry here with the search parameters
parent::__construct(_m('WebFinger URI generation failed.'));
}
}

View File

@ -21,8 +21,332 @@ declare(strict_types = 1);
namespace Component\FreeNetwork;
use App\Core\DB\DB;
use App\Core\Event;
use App\Core\Router\Router;
use Component\FreeNetwork\Entity\FreenetworkActor;
use function App\Core\I18n\_m;
use App\Core\Log;
use App\Core\Modules\Component;
use App\Core\Router\RouteLoader;
use App\Entity\Actor;
use App\Entity\LocalUser;
use App\Entity\Note;
use App\Util\Common;
use App\Util\Exception\ClientException;
use App\Util\Exception\NoSuchActorException;
use App\Util\Exception\ServerException;
use App\Util\Nickname;
use Component\FreeNetwork\Controller\HostMeta;
use Component\FreeNetwork\Controller\OwnerXrd;
use Component\FreeNetwork\Controller\Webfinger;
use Component\FreeNetwork\Util\Discovery;
use Component\FreeNetwork\Util\WebfingerResource;
use Component\FreeNetwork\Util\WebfingerResource\WebfingerResourceActor;
use Doctrine\ORM\NoResultException;
use Exception;
use Plugin\ActivityPub\Entity\ActivitypubActivity;
use Plugin\ActivityPub\Util\Response\TypeResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use XML_XRD_Element_Link;
/**
* Implements WebFinger (RFC7033) for GNU social, as well as Link-based Resource Descriptor Discovery based on RFC6415,
* Web Host Metadata ('.well-known/host-meta') resource.
*
* @package GNUsocial
*
* @author Mikael Nordfeldth <mmn@hethane.se>
* @author Diogo Peralta Cordeiro <mail@diogo.site>
*/
class FreeNetwork extends Component
{
const PLUGIN_VERSION = '0.1.0';
const OAUTH_ACCESS_TOKEN_REL = 'http://apinamespace.org/oauth/access_token';
const OAUTH_REQUEST_TOKEN_REL = 'http://apinamespace.org/oauth/request_token';
const OAUTH_AUTHORIZE_REL = 'http://apinamespace.org/oauth/authorize';
public function onAddRoute(RouteLoader $m): bool
{
$m->connect('freenetwork_hostmeta', '.well-known/host-meta', [HostMeta::class, 'handle']);
$m->connect('freenetwork_hostmeta_format', '.well-known/host-meta.:format',
[HostMeta::class, 'handle'],
['format' => '(xml|json)']);
// the resource GET parameter can be anywhere, so don't mention it here
$m->connect('freenetwork_webfinger', '.well-known/webfinger', [Webfinger::class, 'handle']);
$m->connect('freenetwork_webfinger_format', '.well-known/webfinger.:format',
[Webfinger::class, 'handle'],
['format' => '(xml|json)']);
$m->connect('freenetwork_ownerxrd', 'main/ownerxrd', [OwnerXrd::class, 'handle']);
return Event::next;
}
public function onLoginAction($action, &$login)
{
switch ($action) {
case 'hostmeta':
case 'webfinger':
$login = true;
return false;
}
return true;
}
/**
* @param Actor $actor
* @param LocalUser $user
* @return bool
*/
// public function onSuccessfulLocalUserRegistration(Actor $actor, LocalUser $user): bool
// {
// //$profile_page = Router::url(id: 'actor_view_nickname', args: ['nickname' => $actor->getNickname()], type: Router::ABSOLUTE_URL);
// $profile_page = $actor->getUrl(Router::ABSOLUTE_URL);
// $actor_uri = $actor->getUri(Router::ABSOLUTE_URL);
// Event::handle('FreeNetworkSaveProfilePage', [$source = 'user', $actor_id = $actor->getId(), &$profile_page, &$actor_uri]);
// $fnactorpp = FreenetworkActor::create([
// 'actor_uri' => $profile_page,
// 'source' => $source,
// 'actor_id' => $actor_id,
// 'is_local' => true,
// ]);
// DB::persist($fnactorpp);
// if ($profile_page !== $actor_uri) {
// $fnactoruri = FreenetworkActor::create([
// 'actor_uri' => $actor_uri,
// 'source' => $source,
// 'actor_id' => $actor_id,
// 'is_local' => true,
// ]);
// DB::persist($fnactoruri);
// }
// return Event::next;
// }
public function onStartGetProfileAcctUri(Actor $profile, &$acct)
{
$wfr = new WebFingerResourceActor($profile);
try {
$acct = $wfr->reconstructAcct();
} catch (Exception $e) {
return true;
}
return false;
}
public function onEndGetWebFingerResource($resource, WebfingerResource &$target = null, array $args = [])
{
// * Either we didn't find the profile, then we want to make
// the $profile variable null for clarity.
// * Or we did find it but for a possibly malicious remote
// user who might've set their profile URL to a Note URL
// which would've caused a sort of DoS unless we continue
// our search here by discarding the remote profile.
$profile = null;
if (Discovery::isAcct($resource)) {
$parts = explode('@', substr(urldecode($resource), 5)); // 5 is strlen of 'acct:'
if (count($parts) == 2) {
list($nick, $domain) = $parts;
if ($domain !== $_ENV['SOCIAL_DOMAIN']) {// XXX: Common::config('site', 'server')) {
throw new ServerException(_m('Remote profiles not supported via WebFinger yet.'));
}
$nick = Nickname::normalize(nickname: $nick, check_already_used: false, check_is_allowed: false);
$freenetwork_actor = LocalUser::getWithPK(['nickname' => $nick]);
if (!($freenetwork_actor instanceof LocalUser)) {
throw new NoSuchActorException($nick);
}
$profile = $freenetwork_actor->getActor();
}
} elseif (!filter_var($resource, FILTER_VALIDATE_URL)) {
// Try the User URI lookup!
try {
$resource_parts = parse_url($resource);
if ($resource_parts['host'] === $_ENV['SOCIAL_DOMAIN']) {
$str = parse_url($resource_parts['path']);
// actor_view_nickname
$renick = '/\/@(' . Nickname::DISPLAY_FMT . ')\/?/m';
// actor_view_id
$reuri = '/\/actor/(\d+)\/?/m';
if (preg_match_all($renick, $str, $matches, PREG_SET_ORDER, 0) === 1) {
$profile = LocalUser::getWithPK(['nickname' => $matches[1]])->getActor();
} else if (preg_match_all($reuri, $str, $matches, PREG_SET_ORDER, 0) === 1) {
$profile = Actor::getById($matches[1]);
}
} else {
throw new NoResultException();
}
} catch (NoResultException $e) {
// not a User, maybe a Note? we'll try that further down...
}
} else {
// this means $resource is a common_valid_http_url (or https)
// First build up a set of alternative resource URLs that we can use.
try {
Log::debug(__METHOD__ . ': Finding User URI for WebFinger lookup on resource==' . $resource);
$freenetwork_actor = FreenetworkActor::getWithPK(['profile_page' => $resource]);
if ($freenetwork_actor !== null) {
$profile = Actor::getById($freenetwork_actor->getActorId());
}
unset($freenetwork_actor);
} catch (Exception $e) {
// Most likely a UserNoProfileException, if it ever happens
// and then we need to do some debugging and perhaps fixes.
Log::error(get_class($e) . ': ' . $e->getMessage());
throw $e;
}
// try {
// Log::debug(__METHOD__ . ': Finding User_group URI for WebFinger lookup on resource==' . $resource);
// $group = new User_group();
// $group->whereAddIn('uri', array_keys($alt_urls), $group->columnType('uri'));
// $group->limit(1);
// if ($group->find(true)) {
// $profile = $group->getProfile();
// }
// unset($group);
// } catch (Exception $e) {
// Log::error(get_class($e) . ': ' . $e->getMessage());
// throw $e;
// }
}
if ($profile instanceof Actor) {
Log::debug(__METHOD__ . ': Found Profile with ID==' . $profile->getID() . ' for resource==' . $resource);
$target = new WebfingerResourceActor($profile);
return false; // We got our target, stop handler execution
}
$APNote = ActivitypubActivity::getWithPK(['object_uri' => $resource]);
if ($APNote instanceof ActivitypubActivity) {
$target = new WebfingerResource\WebfingerResourceNote(Note::getWithPK(['id' => $APNote->getObjectId()]));
return false;
}
return true;
}
public function onStartHostMetaLinks(array &$links)
{
foreach (Discovery::supportedMimeTypes() as $type) {
$links[] = new XML_XRD_Element_Link(Discovery::LRDD_REL,
Router::url(id: 'freenetwork_webfinger', args: [], type: Router::ABSOLUTE_URL) . '?resource={uri}',
$type,
isTemplate: true);
}
// TODO OAuth connections
//$links[] = new XML_XRD_Element_link(self::OAUTH_ACCESS_TOKEN_REL, common_local_url('ApiOAuthAccessToken'));
//$links[] = new XML_XRD_Element_link(self::OAUTH_REQUEST_TOKEN_REL, common_local_url('ApiOAuthRequestToken'));
//$links[] = new XML_XRD_Element_link(self::OAUTH_AUTHORIZE_REL, common_local_url('ApiOAuthAuthorize'));
}
/**
* Add a link header for LRDD Discovery
*
* @param mixed $action
*/
public function onStartShowHTML($action)
{
if ($action instanceof ShowstreamAction) {
$resource = $action->getTarget()->getUri();
$url = common_local_url('webfinger') . '?resource=' . urlencode($resource);
foreach ([Discovery::JRD_MIMETYPE, Discovery::XRD_MIMETYPE] as $type) {
header('Link: <' . $url . '>; rel="' . Discovery::LRDD_REL . '"; type="' . $type . '"', false);
}
}
}
public function onStartDiscoveryMethodRegistration(Discovery $disco)
{
$disco->registerMethod('LRDDMethod_WebFinger');
}
public function onEndDiscoveryMethodRegistration(Discovery $disco)
{
$disco->registerMethod('LRDDMethod_HostMeta');
$disco->registerMethod('LRDDMethod_LinkHeader');
$disco->registerMethod('LRDDMethod_LinkHTML');
}
/**
* @throws ClientException
* @throws ServerException
*/
public function onControllerResponseInFormat(string $route, array $accept_header, array $vars, ?TypeResponse &$response = null): bool
{
if (!in_array($route, ['freenetwork_hostmeta', 'freenetwork_hostmeta_format', 'freenetwork_webfinger', 'freenetwork_webfinger_format', 'freenetwork_ownerxrd'])) {
return Event::next;
}
$mimeType = array_intersect(array_values(Discovery::supportedMimeTypes()), $accept_header);
/*
* "A WebFinger resource MUST return a JRD as the representation
* for the resource if the client requests no other supported
* format explicitly via the HTTP "Accept" header. [...]
* The WebFinger resource MUST silently ignore any requested
* representations that it does not understand and support."
* -- RFC 7033 (WebFinger)
* http://tools.ietf.org/html/rfc7033
*/
$mimeType = count($mimeType) !== 0 ? array_pop($mimeType) : $vars['default_mimetype'];
$headers = [];
if (Common::config('discovery', 'cors')) {
$headers['Access-Control-Allow-Origin'] = '*';
}
$headers['Content-Type'] = $mimeType;
$response = match ($mimeType) {
Discovery::XRD_MIMETYPE => new Response(content: $vars['xrd']->to('xml'), headers: $headers),
Discovery::JRD_MIMETYPE, Discovery::JRD_MIMETYPE_OLD => new JsonResponse(data: $vars['xrd']->to('json'), headers: $headers, json: true),
};
return Event::stop;
}
/**
* Fetch all the aliases of some remote profile
*
* @param string $uri profile's URI
*
* @throws Exception (If the Discovery's HTTP requests fail)
*
* @return null|array aliases
*
* @author Bruno Casteleiro <brunoccast@fc.up.pt>
*/
public static function grab_profile_aliases(string $uri): ?array
{
$disco = new Discovery();
$xrd = $disco->lookup($uri);
$all_ids = array_merge([$xrd->subject], $xrd->aliases);
if (!in_array($uri, $all_ids)) {
Log::info('The original URI was not listed itself when doing discovery on it!');
return null;
}
return $all_ids;
}
public function onPluginVersion(array &$versions): bool
{
$versions[] = [
'name' => 'WebFinger',
'version' => self::PLUGIN_VERSION,
'author' => 'Mikael Nordfeldth',
'homepage' => GNUSOCIAL_ENGINE_URL,
// TRANS: Plugin description.
'rawdescription' => _m('WebFinger and LRDD support'),
];
return true;
}
}

View File

@ -0,0 +1,2 @@
The FreeNetwork component adds WebFinger (RFC7033) lookup and implements Link-based Resource Descriptor Discovery (LRDD)
based on RFC6415, Web Host Metadata.

View File

@ -0,0 +1,233 @@
<?php
/**
* StatusNet - the distributed open-source microblogging tool
* Copyright (C) 2010, StatusNet, Inc.
*
* This class performs lookups based on methods implemented in separate
* classes, where a resource uri is given. Examples are WebFinger (RFC7033)
* and the LRDD (Link-based Resource Descriptor Discovery) in RFC6415.
*
* PHP version 5
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @category Discovery
* @package GNUsocial
*
* @author James Walker <james@status.net>
* @author Mikael Nordfeldth <mmn@hethane.se>
* @copyright 2010 StatusNet, Inc.
* @copyright 2013 Free Software Foundation, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
*
* @see http://www.gnu.org/software/social/
*/
namespace Component\FreeNetwork\Util;
use App\Core\Event;
use App\Core\HTTPClient;
use App\Core\Log;
use App\Util\Exception\ClientException;
use XML_XRD;
use function App\Core\I18n\_m;
class Discovery
{
const LRDD_REL = 'lrdd';
const UPDATESFROM = 'http://schemas.google.com/g/2010#updates-from';
const HCARD = 'http://microformats.org/profile/hcard';
const MF2_HCARD = 'http://microformats.org/profile/h-card'; // microformats2 h-card
const JRD_MIMETYPE_OLD = 'application/json'; // RFC6415 uses this
const JRD_MIMETYPE = 'application/jrd+json';
const XRD_MIMETYPE = 'application/xrd+xml';
public $methods = [];
/**
* Constructor for a discovery object
*
* Registers different discovery methods.
*
* @return void
*/
public function __construct()
{
if (Event::handle('StartDiscoveryMethodRegistration', [$this])) {
Event::handle('EndDiscoveryMethodRegistration', [$this]);
}
}
public static function supportedMimeTypes()
{
return [
'json' => self::JRD_MIMETYPE,
'jsonold' => self::JRD_MIMETYPE_OLD,
'xml' => self::XRD_MIMETYPE,
];
}
/**
* Register a discovery class
*
* @param string $class Class name
*
* @return void
*/
public function registerMethod($class)
{
$this->methods[] = $class;
}
/**
* Given a user ID, return the first available resource descriptor
*
* @param string $id User ID URI
*
* @return XML_XRD object for the resource descriptor of the id
*/
public function lookup($id)
{
// Normalize the incoming $id to make sure we have a uri
$uri = self::normalize($id);
Log::debug(sprintf('Performing discovery for "%s" (normalized "%s")', $id, $uri));
foreach ($this->methods as $class) {
try {
$xrd = new XML_XRD();
Log::debug("LRDD discovery method for '{$uri}': {$class}");
$lrdd = new $class;
$links = $lrdd->discover($uri);
$link = self::getService($links, self::LRDD_REL);
// Load the LRDD XRD
if (!empty($link->template)) {
$xrd_uri = self::applyTemplate($link->template, $uri);
} elseif (!empty($link->href)) {
$xrd_uri = $link->href;
} else {
throw new Exception('No resource descriptor URI in link.');
}
$client = new HTTPClient();
$headers = [];
if (!is_null($link->type)) {
$headers[] = "Accept: {$link->type}";
}
$response = $client->get($xrd_uri, $headers);
if ($response->getStatus() != 200) {
throw new Exception('Unexpected HTTP status code.');
}
switch (common_bare_mime($response->getHeader('content-type'))) {
case self::JRD_MIMETYPE_OLD:
case self::JRD_MIMETYPE:
$type = 'json';
break;
case self::XRD_MIMETYPE:
$type = 'xml';
break;
default:
// fall back to letting XML_XRD auto-detect
Log::debug('No recognized content-type header for resource descriptor body on ' . _ve($xrd_uri));
$type = null;
}
$xrd->loadString($response->getBody(), $type);
return $xrd;
} catch (ClientException $e) {
if ($e->getCode() === 403) {
Log::info(sprintf('%s: Aborting discovery on URL %s: %s', _ve($class), _ve($uri), _ve($e->getMessage())));
break;
}
} catch (Exception $e) {
Log::info(sprintf('%s: Failed for %s: %s', _ve($class), _ve($uri), _ve($e->getMessage())));
continue;
}
}
// TRANS: Exception. %s is an ID.
throw new Exception(sprintf(_('Unable to find services for %s.'), $id));
}
/**
* Given an array of links, returns the matching service
*
* @param array $links Links to check (as instances of XML_XRD_Element_Link)
* @param string $service Service to find
*
* @return array $link assoc array representing the link
*/
public static function getService(array $links, $service)
{
foreach ($links as $link) {
if ($link->rel === $service) {
return $link;
}
Log::debug('LINK: rel ' . $link->rel . ' !== ' . $service);
}
throw new Exception('No service link found');
}
/**
* Given a "user id" make sure it's normalized to an acct: uri
*
* @param string $user_id User ID to normalize
* @param mixed $uri
*
* @return string normalized acct: URI
*/
public static function normalize($uri)
{
if (is_null($uri) || $uri === '') {
throw new Exception(_m('No resource given.'));
}
$parts = parse_url($uri);
// If we don't have a scheme, but the path implies user@host,
// though this is far from a perfect matching procedure...
if (!isset($parts['scheme']) && isset($parts['path'])
&& preg_match('/[\w@\w]/u', $parts['path'])) {
return 'acct:' . $uri;
}
return $uri;
}
public static function isAcct($uri)
{
return mb_strtolower(mb_substr($uri, 0, 5)) == 'acct:';
}
/**
* Apply a template using an ID
*
* Replaces {uri} in template string with the ID given.
*
* @param string $template Template to match
* @param string $uri URI to replace with
*
* @return string replaced values
*/
public static function applyTemplate($template, $uri)
{
$template = str_replace('{uri}', urlencode($uri), $template);
return $template;
}
}

View File

@ -0,0 +1,127 @@
<?php
/**
* StatusNet - the distributed open-source microblogging tool
* Copyright (C) 2010, StatusNet, Inc.
*
* Parse HTTP response for interesting Link: headers
*
* PHP version 5
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @category Discovery
* @package StatusNet
*
* @author James Walker <james@status.net>
* @copyright 2010 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
*
* @see http://status.net/
*/
namespace Component\FreeNetwork\Util;
/**
* Class to represent Link: headers in an HTTP response
*
* Since these are a fairly important part of Hammer-stack discovery, they're
* reified and implemented here.
*
* @category Discovery
* @package StatusNet
*
* @author James Walker <james@status.net>
* @copyright 2010 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
*
* @see http://status.net/
* @see Discovery
*/
class LinkHeader
{
public $href;
public $rel;
public $type;
/**
* Initialize from a string
*
* @param string $str Link: header value
*/
public function __construct(string $str = '')
{
preg_match('/^<[^>]+>/', $str, $uri_reference);
//if (empty($uri_reference)) return;
$this->href = trim($uri_reference[0], '<>');
$this->rel = [];
$this->type = null;
// remove uri-reference from header
$str = substr($str, strlen($uri_reference[0]));
// parse link-params
$params = explode(';', $str);
foreach ($params as $param) {
if (empty($param)) {
continue;
}
list($param_name, $param_value) = explode('=', $param, 2);
$param_name = trim($param_name);
$param_value = preg_replace('(^"|"$)', '', trim($param_value));
// for now we only care about 'rel' and 'type' link params
// TODO do something with the other links-params
switch ($param_name) {
case 'rel':
$this->rel = trim($param_value);
break;
case 'type':
$this->type = trim($param_value);
}
}
}
/**
* Given an HTTP response, return the requested Link: header
*
* @param HTTP_Request2_Response $response response to check
* @param string $rel relationship to look for
* @param string $type media type to look for
*
* @return LinkHeader discovered header, or null on failure
*/
public static function getLink($response, $rel = null, $type = null)
{
$headers = $response->getHeader('Link');
if ($headers) {
// Can get an array or string, so try to simplify the path
if (!is_array($headers)) {
$headers = [$headers];
}
foreach ($headers as $header) {
$lh = new self($header);
if ((is_null($rel) || $lh->rel == $rel) && (is_null($type) || $lh->type == $type)) {
return $lh->href;
}
}
}
return null;
}
}

View File

@ -0,0 +1,68 @@
<?php
namespace Component\FreeNetwork\Util;
use App\Core\Event;
use App\Core\HTTPClient;
use XML_XRD;
/**
* Abstract class for LRDD discovery methods
*
* Objects that extend this class can retrieve an array of
* resource descriptor links for the URI. The array consists
* of XML_XRD_Element_Link elements.
*
* @category Discovery
* @package StatusNet
*
* @author James Walker <james@status.net>
* @copyright 2010 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
*
* @see http://status.net/
*/
abstract class LrddMethod
{
protected $xrd;
public function __construct()
{
$this->xrd = new XML_XRD();
}
/**
* Discover interesting info about the URI
*
* @param string $uri URI to inquire about
*
* @return array of XML_XRD_Element_Link elements to discovered resource descriptors
*/
abstract public function discover($uri);
protected function fetchUrl($url, $method = HTTPClient::METHOD_GET)
{
// If we have a blacklist enabled, let's check against it
Event::handle('UrlBlacklistTest', [$url]);
$client = new HTTPClient();
// GAAHHH, this method sucks! How about we make a better HTTPClient interface?
switch ($method) {
case HTTPClient::METHOD_GET:
$response = $client->get($url);
break;
case HTTPClient::METHOD_HEAD:
$response = $client->head($url);
break;
default:
throw new Exception('Bad HTTP method.');
}
if ($response->getStatus() != 200) {
throw new Exception('Unexpected HTTP status code.');
}
return $response;
}
}

View File

@ -0,0 +1,85 @@
<?php
namespace Component\FreeNetwork\Util\LrddMethod;
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
use App\Core\Log;
use Component\FreeNetwork\Util\LrddMethod;
use Exception;
/**
* Implementation of discovery using host-meta file
*
* Discovers resource descriptor file for a user by going to the
* organization's host-meta file and trying to find a template for LRDD.
*
* @category Discovery
* @package GNUsocial
*
* @author James Walker <james@status.net>
* @copyright 2010 StatusNet, Inc.
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class LrddMethodHostMeta extends LRDDMethod
{
/**
* For RFC6415 and HTTP URIs, fetch the host-meta file
* and look for LRDD templates
*
* @param mixed $uri
*/
public function discover($uri)
{
// This is allowed for RFC6415 but not the 'WebFinger' RFC7033.
$try_schemes = ['https', 'http'];
$scheme = mb_strtolower(parse_url($uri, PHP_URL_SCHEME));
switch ($scheme) {
case 'acct':
// We can't use parse_url data for this, since the 'host'
// entry is only set if the scheme has '://' after it.
$parts = explode('@', parse_url($uri, PHP_URL_PATH), 2);
if (!Discovery::isAcct($uri) || count($parts) != 2) {
throw new Exception('Bad resource URI: ' . $uri);
}
[, $domain] = $parts;
break;
case 'http':
case 'https':
$domain = mb_strtolower(parse_url($uri, PHP_URL_HOST));
$try_schemes = [$scheme];
break;
default:
throw new Exception('Unable to discover resource descriptor endpoint.');
}
foreach ($try_schemes as $scheme) {
$url = $scheme . '://' . $domain . '/.well-known/host-meta';
try {
$response = self::fetchUrl($url);
$this->xrd->loadString($response->getBody());
} catch (Exception $e) {
Log::debug('LRDD could not load resource descriptor: ' . $url . ' (' . $e->getMessage() . ')');
continue;
}
return $this->xrd->links;
}
throw new Exception('Unable to retrieve resource descriptor links.');
}
}

View File

@ -0,0 +1,65 @@
<?php
namespace Component\FreeNetwork\Util\LrddMethod;
use App\Core\HTTPClient;
use App\Core\Log;
use Component\FreeNetwork\Util\LinkHeader;
use Component\FreeNetwork\Util\LrddMethod;
use Exception;
use XML_XRD_Element_Link;
/**
* Implementation of discovery using HTTP Link header
*
* Discovers XRD file for a user by fetching the URL and reading any
* Link: headers in the HTTP response.
*
* @category Discovery
* @package StatusNet
*
* @author James Walker <james@status.net>
* @copyright 2010 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
*
* @see http://status.net/
*/
class LrddMethodLinkHeader extends LRDDMethod
{
/**
* For HTTP IDs fetch the URL and look for Link headers.
*
* @param mixed $uri
*
* @todo fail out of WebFinger URIs faster
*
*/
public function discover($uri)
{
$response = self::fetchUrl($uri, HTTPClient::METHOD_HEAD);
$link_header = $response->getHeader('Link');
if (empty($link_header)) {
throw new Exception('No Link header found');
}
Log::debug('LRDD LinkHeader found: ' . var_export($link_header, true));
return self::parseHeader($link_header);
}
/**
* Given a string or array of headers, returns JRD-like assoc array
*
* @param array|string $header string or array of strings for headers
*
* @return array of associative arrays in JRD-like array format
*/
protected static function parseHeader($header)
{
$lh = new LinkHeader($header);
$link = new XML_XRD_Element_Link($lh->rel, $lh->href, $lh->type);
return [$link];
}
}

View File

@ -0,0 +1,106 @@
<?php
namespace Component\FreeNetwork\Util\LrddMethod;
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
use Component\FreeNetwork\Util\LrddMethod;
use XML_XRD_Element_Link;
/**
* Implementation of discovery using HTML <link> element
*
* Discovers XRD file for a user by fetching the URL and reading any
* <link> elements in the HTML response.
*
* @category Discovery
* @package GNUsocial
*
* @author James Walker <james@status.net>
* @copyright 2010 StatusNet, Inc.
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class LrddMethodLinkHtml extends LRDDMethod
{
/**
* For HTTP IDs, fetch the URL and look for <link> elements
* in the HTML response.
*
* @param mixed $uri
*
* @todo fail out of WebFinger URIs faster
*
*/
public function discover($uri)
{
$response = self::fetchUrl($uri);
return self::parse($response->getBody());
}
/**
* Parse HTML and return <link> elements
*
* Given an HTML string, scans the string for <link> elements
*
* @param string $html HTML to scan
*
* @return array array of associative arrays in JRD-ish array format
*/
public function parse($html)
{
$links = [];
preg_match('/<head(\s[^>]*)?>(.*?)<\/head>/is', $html, $head_matches);
if (count($head_matches) != 3) {
return [];
}
[, , $head_html] = $head_matches;
preg_match_all('/<link\s[^>]*>/i', $head_html, $link_matches);
foreach ($link_matches[0] as $link_html) {
$link_url = null;
$link_rel = null;
$link_type = null;
preg_match('/\srel=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $rel_matches);
if (count($rel_matches) > 3) {
$link_rel = $rel_matches[3];
} elseif (count($rel_matches) > 1) {
$link_rel = $rel_matches[1];
}
preg_match('/\shref=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $href_matches);
if (count($href_matches) > 3) {
$link_uri = $href_matches[3];
} elseif (count($href_matches) > 1) {
$link_uri = $href_matches[1];
}
preg_match('/\stype=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $type_matches);
if (count($type_matches) > 3) {
$link_type = $type_matches[3];
} elseif (count($type_matches) > 1) {
$link_type = $type_matches[1];
}
$links[] = new XML_XRD_Element_Link($link_rel, $link_uri, $link_type);
}
return $links;
}
}

View File

@ -0,0 +1,64 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
namespace Component\FreeNetwork\Util\LrddMethod;
use Component\FreeNetwork\Util\Discovery;
use Component\FreeNetwork\Util\LrddMethod;
use Exception;
use XML_XRD_Element_Link;
/**
* Implementation of WebFinger resource discovery (RFC7033)
*
* @category Discovery
* @package GNUsocial
*
* @author Mikael Nordfeldth <mmn@hethane.se>
* @copyright 2013 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class LrddMethodWebfinger extends LRDDMethod
{
/**
* Simply returns the WebFinger URL over HTTPS at the uri's domain:
* https://{domain}/.well-known/webfinger?resource={uri}
*
* @param mixed $uri
*/
public function discover($uri)
{
$parts = explode('@', parse_url($uri, PHP_URL_PATH), 2);
if (!Discovery::isAcct($uri) || count($parts) != 2) {
throw new Exception('Bad resource URI: ' . $uri);
}
[, $domain] = $parts;
if (!filter_var($domain, FILTER_VALIDATE_IP)
&& !filter_var(gethostbyname($domain), FILTER_VALIDATE_IP)) {
throw new Exception('Bad resource host.');
}
$link = new XML_XRD_Element_Link(
Discovery::LRDD_REL