2022-11-05 20:17:27 +00:00
|
|
|
from functools import partial
|
2022-11-06 20:48:04 +00:00
|
|
|
from typing import Optional, Tuple
|
|
|
|
from urllib.parse import urlparse
|
2022-11-05 20:17:27 +00:00
|
|
|
|
2022-11-05 23:51:54 +00:00
|
|
|
import httpx
|
2022-11-05 20:17:27 +00:00
|
|
|
import urlman
|
2022-11-07 04:30:07 +00:00
|
|
|
from asgiref.sync import async_to_sync, sync_to_async
|
|
|
|
from cryptography.hazmat.primitives import serialization
|
|
|
|
from cryptography.hazmat.primitives.asymmetric import rsa
|
2022-11-05 20:17:27 +00:00
|
|
|
from django.db import models
|
2022-11-17 15:21:42 +00:00
|
|
|
from django.templatetags.static import static
|
2022-11-05 20:17:27 +00:00
|
|
|
from django.utils import timezone
|
2022-11-05 23:51:54 +00:00
|
|
|
|
2022-11-06 06:07:38 +00:00
|
|
|
from core.ld import canonicalise
|
2022-11-17 15:21:42 +00:00
|
|
|
from core.uploads import upload_namer
|
2022-11-10 05:29:33 +00:00
|
|
|
from stator.models import State, StateField, StateGraph, StatorModel
|
2022-11-06 20:48:04 +00:00
|
|
|
from users.models.domain import Domain
|
2022-11-05 20:17:27 +00:00
|
|
|
|
|
|
|
|
2022-11-10 05:29:33 +00:00
|
|
|
class IdentityStates(StateGraph):
|
|
|
|
outdated = State(try_interval=3600)
|
|
|
|
updated = State()
|
|
|
|
|
2022-11-10 06:48:31 +00:00
|
|
|
outdated.transitions_to(updated)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
async def handle_outdated(cls, identity: "Identity"):
|
|
|
|
# Local identities never need fetching
|
2022-11-10 05:29:33 +00:00
|
|
|
if identity.local:
|
2022-11-10 06:48:31 +00:00
|
|
|
return "updated"
|
|
|
|
# Run the actor fetch and progress to updated if it succeeds
|
|
|
|
if await identity.fetch_actor():
|
|
|
|
return "updated"
|
2022-11-10 05:29:33 +00:00
|
|
|
|
|
|
|
|
|
|
|
class Identity(StatorModel):
|
2022-11-05 20:17:27 +00:00
|
|
|
"""
|
|
|
|
Represents both local and remote Fediverse identities (actors)
|
|
|
|
"""
|
|
|
|
|
2022-11-06 20:48:04 +00:00
|
|
|
# The Actor URI is essentially also a PK - we keep the default numeric
|
|
|
|
# one around as well for making nice URLs etc.
|
2022-11-07 04:30:07 +00:00
|
|
|
actor_uri = models.CharField(max_length=500, unique=True)
|
2022-11-06 20:48:04 +00:00
|
|
|
|
2022-11-10 05:29:33 +00:00
|
|
|
state = StateField(IdentityStates)
|
|
|
|
|
2022-11-06 20:48:04 +00:00
|
|
|
local = models.BooleanField()
|
2022-11-12 05:02:43 +00:00
|
|
|
users = models.ManyToManyField(
|
|
|
|
"users.User",
|
|
|
|
related_name="identities",
|
|
|
|
blank=True,
|
|
|
|
)
|
2022-11-06 20:48:04 +00:00
|
|
|
|
|
|
|
username = models.CharField(max_length=500, blank=True, null=True)
|
|
|
|
# Must be a display domain if present
|
|
|
|
domain = models.ForeignKey(
|
|
|
|
"users.Domain",
|
|
|
|
blank=True,
|
|
|
|
null=True,
|
|
|
|
on_delete=models.PROTECT,
|
2022-11-17 04:12:28 +00:00
|
|
|
related_name="identities",
|
2022-11-06 20:48:04 +00:00
|
|
|
)
|
|
|
|
|
2022-11-05 20:17:27 +00:00
|
|
|
name = models.CharField(max_length=500, blank=True, null=True)
|
2022-11-05 23:51:54 +00:00
|
|
|
summary = models.TextField(blank=True, null=True)
|
2022-11-06 20:48:04 +00:00
|
|
|
manually_approves_followers = models.BooleanField(blank=True, null=True)
|
2022-11-05 23:51:54 +00:00
|
|
|
|
|
|
|
profile_uri = models.CharField(max_length=500, blank=True, null=True)
|
|
|
|
inbox_uri = models.CharField(max_length=500, blank=True, null=True)
|
|
|
|
outbox_uri = models.CharField(max_length=500, blank=True, null=True)
|
|
|
|
icon_uri = models.CharField(max_length=500, blank=True, null=True)
|
|
|
|
image_uri = models.CharField(max_length=500, blank=True, null=True)
|
2022-11-05 20:17:27 +00:00
|
|
|
|
2022-11-05 23:51:54 +00:00
|
|
|
icon = models.ImageField(
|
|
|
|
upload_to=partial(upload_namer, "profile_images"), blank=True, null=True
|
|
|
|
)
|
|
|
|
image = models.ImageField(
|
|
|
|
upload_to=partial(upload_namer, "background_images"), blank=True, null=True
|
2022-11-05 20:17:27 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
private_key = models.TextField(null=True, blank=True)
|
|
|
|
public_key = models.TextField(null=True, blank=True)
|
2022-11-12 22:10:15 +00:00
|
|
|
public_key_id = models.TextField(null=True, blank=True)
|
2022-11-05 20:17:27 +00:00
|
|
|
|
|
|
|
created = models.DateTimeField(auto_now_add=True)
|
|
|
|
updated = models.DateTimeField(auto_now=True)
|
2022-11-05 23:51:54 +00:00
|
|
|
fetched = models.DateTimeField(null=True, blank=True)
|
2022-11-05 20:17:27 +00:00
|
|
|
deleted = models.DateTimeField(null=True, blank=True)
|
|
|
|
|
2022-11-07 04:30:07 +00:00
|
|
|
### Model attributes ###
|
|
|
|
|
2022-11-06 06:07:38 +00:00
|
|
|
class Meta:
|
|
|
|
verbose_name_plural = "identities"
|
2022-11-06 20:48:04 +00:00
|
|
|
unique_together = [("username", "domain")]
|
2022-11-06 06:07:38 +00:00
|
|
|
|
2022-11-07 04:30:07 +00:00
|
|
|
class urls(urlman.Urls):
|
2022-11-16 01:30:30 +00:00
|
|
|
view_nice = "{self._nice_view_url}"
|
2022-11-07 04:30:07 +00:00
|
|
|
view = "/@{self.username}@{self.domain_id}/"
|
|
|
|
action = "{view}action/"
|
|
|
|
activate = "{view}activate/"
|
|
|
|
|
|
|
|
def get_scheme(self, url):
|
|
|
|
return "https"
|
|
|
|
|
|
|
|
def get_hostname(self, url):
|
|
|
|
return self.instance.domain.uri_domain
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
if self.username and self.domain_id:
|
|
|
|
return self.handle
|
|
|
|
return self.actor_uri
|
|
|
|
|
2022-11-16 01:30:30 +00:00
|
|
|
def _nice_view_url(self):
|
|
|
|
"""
|
|
|
|
Returns the "nice" user URL if they're local, otherwise our general one
|
|
|
|
"""
|
|
|
|
if self.local:
|
|
|
|
return f"https://{self.domain.uri_domain}/@{self.username}/"
|
|
|
|
else:
|
|
|
|
return f"/@{self.username}@{self.domain_id}/"
|
|
|
|
|
2022-11-17 15:21:42 +00:00
|
|
|
def local_icon_url(self):
|
|
|
|
"""
|
|
|
|
Returns an icon for us, with fallbacks to a placeholder
|
|
|
|
"""
|
|
|
|
if self.icon:
|
|
|
|
return self.icon.url
|
|
|
|
elif self.icon_uri:
|
|
|
|
return self.icon_uri
|
|
|
|
else:
|
|
|
|
return static("img/unknown-icon-128.png")
|
|
|
|
|
|
|
|
def local_image_url(self):
|
|
|
|
"""
|
|
|
|
Returns a background image for us, returning None if there isn't one
|
|
|
|
"""
|
|
|
|
if self.image:
|
|
|
|
return self.image.url
|
|
|
|
elif self.image_uri:
|
|
|
|
return self.image_uri
|
|
|
|
|
2022-11-07 04:30:07 +00:00
|
|
|
### Alternate constructors/fetchers ###
|
|
|
|
|
2022-11-06 04:49:25 +00:00
|
|
|
@classmethod
|
2022-11-07 07:19:00 +00:00
|
|
|
def by_username_and_domain(cls, username, domain, fetch=False, local=False):
|
|
|
|
if username.startswith("@"):
|
|
|
|
raise ValueError("Username must not start with @")
|
2022-11-17 06:10:55 +00:00
|
|
|
username = username.lower()
|
2022-11-06 04:49:25 +00:00
|
|
|
try:
|
2022-11-06 20:48:04 +00:00
|
|
|
if local:
|
|
|
|
return cls.objects.get(username=username, domain_id=domain, local=True)
|
|
|
|
else:
|
|
|
|
return cls.objects.get(username=username, domain_id=domain)
|
2022-11-06 04:49:25 +00:00
|
|
|
except cls.DoesNotExist:
|
2022-11-06 20:48:04 +00:00
|
|
|
if fetch and not local:
|
2022-11-07 07:19:00 +00:00
|
|
|
actor_uri, handle = async_to_sync(cls.fetch_webfinger)(
|
|
|
|
f"{username}@{domain}"
|
|
|
|
)
|
2022-11-07 04:30:07 +00:00
|
|
|
username, domain = handle.split("@")
|
|
|
|
domain = Domain.get_remote_domain(domain)
|
|
|
|
return cls.objects.create(
|
|
|
|
actor_uri=actor_uri,
|
|
|
|
username=username,
|
|
|
|
domain_id=domain,
|
|
|
|
local=False,
|
|
|
|
)
|
2022-11-06 04:49:25 +00:00
|
|
|
return None
|
|
|
|
|
2022-11-06 06:07:38 +00:00
|
|
|
@classmethod
|
2022-11-12 05:02:43 +00:00
|
|
|
def by_actor_uri(cls, uri, create=False) -> "Identity":
|
2022-11-06 06:07:38 +00:00
|
|
|
try:
|
2022-11-06 20:48:04 +00:00
|
|
|
return cls.objects.get(actor_uri=uri)
|
2022-11-06 06:07:38 +00:00
|
|
|
except cls.DoesNotExist:
|
2022-11-12 05:02:43 +00:00
|
|
|
if create:
|
|
|
|
return cls.objects.create(actor_uri=uri, local=False)
|
|
|
|
else:
|
2022-11-17 05:23:32 +00:00
|
|
|
raise cls.DoesNotExist(f"No identity found with actor_uri {uri}")
|
2022-11-06 21:14:08 +00:00
|
|
|
|
2022-11-07 04:30:07 +00:00
|
|
|
### Dynamic properties ###
|
|
|
|
|
|
|
|
@property
|
|
|
|
def name_or_handle(self):
|
|
|
|
return self.name or self.handle
|
|
|
|
|
2022-11-05 20:17:27 +00:00
|
|
|
@property
|
2022-11-06 20:48:04 +00:00
|
|
|
def handle(self):
|
2022-11-07 04:30:07 +00:00
|
|
|
if self.domain_id:
|
|
|
|
return f"{self.username}@{self.domain_id}"
|
|
|
|
return f"{self.username}@UNKNOWN-DOMAIN"
|
2022-11-05 20:17:27 +00:00
|
|
|
|
2022-11-06 04:49:25 +00:00
|
|
|
@property
|
|
|
|
def data_age(self) -> float:
|
|
|
|
"""
|
|
|
|
How old our copy of this data is, in seconds
|
|
|
|
"""
|
|
|
|
if self.local:
|
|
|
|
return 0
|
|
|
|
if self.fetched is None:
|
|
|
|
return 10000000000
|
|
|
|
return (timezone.now() - self.fetched).total_seconds()
|
|
|
|
|
2022-11-07 04:30:07 +00:00
|
|
|
@property
|
|
|
|
def outdated(self) -> bool:
|
|
|
|
# TODO: Setting
|
|
|
|
return self.data_age > 60 * 24 * 24
|
|
|
|
|
2022-11-17 05:23:32 +00:00
|
|
|
### ActivityPub (outbound) ###
|
2022-11-16 01:30:30 +00:00
|
|
|
|
|
|
|
def to_ap(self):
|
|
|
|
response = {
|
|
|
|
"id": self.actor_uri,
|
|
|
|
"type": "Person",
|
|
|
|
"inbox": self.actor_uri + "inbox/",
|
|
|
|
"preferredUsername": self.username,
|
|
|
|
"publicKey": {
|
|
|
|
"id": self.public_key_id,
|
|
|
|
"owner": self.actor_uri,
|
|
|
|
"publicKeyPem": self.public_key,
|
|
|
|
},
|
|
|
|
"published": self.created.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
2022-11-17 05:23:32 +00:00
|
|
|
"url": str(self.urls.view_nice),
|
2022-11-16 01:30:30 +00:00
|
|
|
}
|
|
|
|
if self.name:
|
|
|
|
response["name"] = self.name
|
|
|
|
if self.summary:
|
|
|
|
response["summary"] = self.summary
|
|
|
|
return response
|
|
|
|
|
2022-11-17 05:23:32 +00:00
|
|
|
### ActivityPub (inbound) ###
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def handle_update_ap(cls, data):
|
|
|
|
"""
|
|
|
|
Takes an incoming update.person message and just forces us to add it
|
|
|
|
to our fetch queue (don't want to bother with two load paths right now)
|
|
|
|
"""
|
|
|
|
# Find by actor
|
|
|
|
try:
|
|
|
|
actor = cls.by_actor_uri(data["actor"])
|
|
|
|
actor.transition_perform(IdentityStates.outdated)
|
|
|
|
except cls.DoesNotExist:
|
|
|
|
pass
|
|
|
|
|
2022-11-07 04:30:07 +00:00
|
|
|
### Actor/Webfinger fetching ###
|
2022-11-05 20:17:27 +00:00
|
|
|
|
2022-11-06 20:48:04 +00:00
|
|
|
@classmethod
|
|
|
|
async def fetch_webfinger(cls, handle: str) -> Tuple[Optional[str], Optional[str]]:
|
|
|
|
"""
|
|
|
|
Given a username@domain handle, returns a tuple of
|
|
|
|
(actor uri, canonical handle) or None, None if it does not resolve.
|
|
|
|
"""
|
|
|
|
domain = handle.split("@")[1]
|
2022-11-05 23:51:54 +00:00
|
|
|
async with httpx.AsyncClient() as client:
|
|
|
|
response = await client.get(
|
2022-11-06 20:48:04 +00:00
|
|
|
f"https://{domain}/.well-known/webfinger?resource=acct:{handle}",
|
2022-11-05 23:51:54 +00:00
|
|
|
headers={"Accept": "application/json"},
|
2022-11-06 04:49:25 +00:00
|
|
|
follow_redirects=True,
|
2022-11-05 23:51:54 +00:00
|
|
|
)
|
|
|
|
if response.status_code >= 400:
|
2022-11-06 20:48:04 +00:00
|
|
|
return None, None
|
2022-11-05 23:51:54 +00:00
|
|
|
data = response.json()
|
2022-11-06 20:48:04 +00:00
|
|
|
if data["subject"].startswith("acct:"):
|
|
|
|
data["subject"] = data["subject"][5:]
|
2022-11-05 23:51:54 +00:00
|
|
|
for link in data["links"]:
|
|
|
|
if (
|
|
|
|
link.get("type") == "application/activity+json"
|
|
|
|
and link.get("rel") == "self"
|
|
|
|
):
|
2022-11-06 20:48:04 +00:00
|
|
|
return link["href"], data["subject"]
|
|
|
|
return None, None
|
2022-11-05 23:51:54 +00:00
|
|
|
|
|
|
|
async def fetch_actor(self) -> bool:
|
2022-11-06 20:48:04 +00:00
|
|
|
"""
|
|
|
|
Fetches the user's actor information, as well as their domain from
|
|
|
|
webfinger if it's available.
|
|
|
|
"""
|
|
|
|
if self.local:
|
|
|
|
raise ValueError("Cannot fetch local identities")
|
2022-11-05 23:51:54 +00:00
|
|
|
async with httpx.AsyncClient() as client:
|
|
|
|
response = await client.get(
|
|
|
|
self.actor_uri,
|
|
|
|
headers={"Accept": "application/json"},
|
2022-11-06 04:49:25 +00:00
|
|
|
follow_redirects=True,
|
2022-11-05 23:51:54 +00:00
|
|
|
)
|
|
|
|
if response.status_code >= 400:
|
|
|
|
return False
|
2022-11-06 20:48:04 +00:00
|
|
|
document = canonicalise(response.json(), include_security=True)
|
2022-11-06 06:07:38 +00:00
|
|
|
self.name = document.get("name")
|
2022-11-06 20:48:04 +00:00
|
|
|
self.profile_uri = document.get("url")
|
2022-11-06 06:07:38 +00:00
|
|
|
self.inbox_uri = document.get("inbox")
|
|
|
|
self.outbox_uri = document.get("outbox")
|
|
|
|
self.summary = document.get("summary")
|
2022-11-06 20:48:04 +00:00
|
|
|
self.username = document.get("preferredUsername")
|
2022-11-12 05:02:43 +00:00
|
|
|
if self.username and "@value" in self.username:
|
2022-11-07 04:30:07 +00:00
|
|
|
self.username = self.username["@value"]
|
2022-11-17 06:10:55 +00:00
|
|
|
if self.username:
|
|
|
|
self.username = self.username.lower()
|
2022-11-06 06:07:38 +00:00
|
|
|
self.manually_approves_followers = document.get(
|
|
|
|
"as:manuallyApprovesFollowers"
|
|
|
|
)
|
|
|
|
self.public_key = document.get("publicKey", {}).get("publicKeyPem")
|
2022-11-12 22:10:15 +00:00
|
|
|
self.public_key_id = document.get("publicKey", {}).get("id")
|
2022-11-06 06:07:38 +00:00
|
|
|
self.icon_uri = document.get("icon", {}).get("url")
|
|
|
|
self.image_uri = document.get("image", {}).get("url")
|
2022-11-06 20:48:04 +00:00
|
|
|
# Now go do webfinger with that info to see if we can get a canonical domain
|
|
|
|
actor_url_parts = urlparse(self.actor_uri)
|
|
|
|
get_domain = sync_to_async(Domain.get_remote_domain)
|
|
|
|
if self.username:
|
|
|
|
webfinger_actor, webfinger_handle = await self.fetch_webfinger(
|
|
|
|
f"{self.username}@{actor_url_parts.hostname}"
|
|
|
|
)
|
|
|
|
if webfinger_handle:
|
|
|
|
webfinger_username, webfinger_domain = webfinger_handle.split("@")
|
|
|
|
self.username = webfinger_username
|
|
|
|
self.domain = await get_domain(webfinger_domain)
|
|
|
|
else:
|
|
|
|
self.domain = await get_domain(actor_url_parts.hostname)
|
|
|
|
else:
|
|
|
|
self.domain = await get_domain(actor_url_parts.hostname)
|
|
|
|
self.fetched = timezone.now()
|
|
|
|
await sync_to_async(self.save)()
|
2022-11-06 06:07:38 +00:00
|
|
|
return True
|
|
|
|
|
2022-11-07 04:30:07 +00:00
|
|
|
### Cryptography ###
|
|
|
|
|
|
|
|
def generate_keypair(self):
|
|
|
|
if not self.local:
|
|
|
|
raise ValueError("Cannot generate keypair for remote user")
|
|
|
|
private_key = rsa.generate_private_key(
|
|
|
|
public_exponent=65537,
|
|
|
|
key_size=2048,
|
|
|
|
)
|
|
|
|
self.private_key = private_key.private_bytes(
|
|
|
|
encoding=serialization.Encoding.PEM,
|
|
|
|
format=serialization.PrivateFormat.PKCS8,
|
|
|
|
encryption_algorithm=serialization.NoEncryption(),
|
|
|
|
).decode("ascii")
|
|
|
|
self.public_key = (
|
|
|
|
private_key.public_key()
|
|
|
|
.public_bytes(
|
|
|
|
encoding=serialization.Encoding.PEM,
|
|
|
|
format=serialization.PublicFormat.SubjectPublicKeyInfo,
|
|
|
|
)
|
|
|
|
.decode("ascii")
|
|
|
|
)
|
2022-11-17 05:23:32 +00:00
|
|
|
self.public_key_id = self.actor_uri + "#main-key"
|
2022-11-07 04:30:07 +00:00
|
|
|
self.save()
|