2023-01-04 23:40:16 +00:00
|
|
|
import json
|
2023-10-23 16:33:55 +00:00
|
|
|
import logging
|
2023-01-13 17:53:02 +00:00
|
|
|
import ssl
|
2023-05-04 04:42:37 +00:00
|
|
|
from functools import cached_property
|
2022-11-06 20:48:04 +00:00
|
|
|
from typing import Optional
|
|
|
|
|
2023-01-04 23:40:16 +00:00
|
|
|
import httpx
|
2023-01-18 17:57:28 +00:00
|
|
|
import pydantic
|
2022-11-17 04:12:28 +00:00
|
|
|
import urlman
|
2023-01-04 23:40:16 +00:00
|
|
|
from django.conf import settings
|
2022-11-06 20:48:04 +00:00
|
|
|
from django.db import models
|
|
|
|
|
2023-05-04 04:42:37 +00:00
|
|
|
from core.models import Config
|
2023-01-04 23:40:16 +00:00
|
|
|
from stator.models import State, StateField, StateGraph, StatorModel
|
|
|
|
from users.schemas import NodeInfo
|
2022-11-06 20:48:04 +00:00
|
|
|
|
2023-11-16 17:27:20 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2023-01-04 23:40:16 +00:00
|
|
|
|
|
|
|
class DomainStates(StateGraph):
|
|
|
|
outdated = State(try_interval=60 * 30, force_initial=True)
|
|
|
|
updated = State(try_interval=60 * 60 * 24, attempt_immediately=False)
|
|
|
|
connection_issue = State(externally_progressed=True)
|
|
|
|
purged = State()
|
|
|
|
|
|
|
|
outdated.transitions_to(updated)
|
|
|
|
updated.transitions_to(outdated)
|
2023-07-30 18:22:35 +00:00
|
|
|
updated.transitions_to(updated)
|
2023-01-04 23:40:16 +00:00
|
|
|
|
|
|
|
outdated.transitions_to(connection_issue)
|
|
|
|
outdated.transitions_to(purged)
|
|
|
|
connection_issue.transitions_to(outdated)
|
|
|
|
connection_issue.transitions_to(purged)
|
|
|
|
|
|
|
|
outdated.times_out_to(connection_issue, 60 * 60 * 24)
|
|
|
|
|
|
|
|
@classmethod
|
2023-07-17 06:37:47 +00:00
|
|
|
def handle_outdated(cls, instance: "Domain"):
|
2023-07-22 16:41:58 +00:00
|
|
|
# Don't talk to servers we've blocked
|
|
|
|
if instance.blocked:
|
|
|
|
return cls.updated
|
|
|
|
# Pull their nodeinfo URI
|
2023-07-17 06:37:47 +00:00
|
|
|
info = instance.fetch_nodeinfo()
|
2023-01-04 23:40:16 +00:00
|
|
|
if info:
|
|
|
|
instance.nodeinfo = info.dict()
|
2023-07-17 06:37:47 +00:00
|
|
|
instance.save()
|
2023-01-04 23:40:16 +00:00
|
|
|
return cls.updated
|
|
|
|
|
|
|
|
@classmethod
|
2023-07-17 06:37:47 +00:00
|
|
|
def handle_updated(cls, instance: "Domain"):
|
2023-07-22 16:44:01 +00:00
|
|
|
if instance.blocked:
|
|
|
|
return cls.updated
|
2023-01-04 23:40:16 +00:00
|
|
|
return cls.outdated
|
|
|
|
|
|
|
|
|
|
|
|
class Domain(StatorModel):
|
2022-11-06 20:48:04 +00:00
|
|
|
"""
|
|
|
|
Represents a domain that a user can have an account on.
|
|
|
|
|
|
|
|
For protocol reasons, if we want to allow custom usernames
|
|
|
|
per domain, each "display" domain (the one in the handle) must either let
|
|
|
|
us serve on it directly, or have a "service" domain that maps
|
|
|
|
to it uniquely that we can serve on that.
|
|
|
|
|
|
|
|
That way, someone coming in with just an Actor URI as their
|
|
|
|
entrypoint can still try to webfinger preferredUsername@actorDomain
|
|
|
|
and we can return an appropriate response.
|
|
|
|
|
|
|
|
It's possible to just have one domain do both jobs, of course.
|
|
|
|
This model also represents _other_ servers' domains, which we treat as
|
|
|
|
display domains for now, until we start doing better probing.
|
|
|
|
"""
|
|
|
|
|
|
|
|
domain = models.CharField(max_length=250, primary_key=True)
|
|
|
|
service_domain = models.CharField(
|
|
|
|
max_length=250,
|
|
|
|
null=True,
|
|
|
|
blank=True,
|
|
|
|
db_index=True,
|
|
|
|
unique=True,
|
|
|
|
)
|
|
|
|
|
2023-01-04 23:40:16 +00:00
|
|
|
state = StateField(DomainStates)
|
|
|
|
|
|
|
|
# nodeinfo 2.0 detail about the remote server
|
|
|
|
nodeinfo = models.JSONField(null=True, blank=True)
|
|
|
|
|
2022-11-06 20:48:04 +00:00
|
|
|
# If we own this domain
|
|
|
|
local = models.BooleanField()
|
|
|
|
|
|
|
|
# If we have blocked this domain from interacting with us
|
|
|
|
blocked = models.BooleanField(default=False)
|
|
|
|
|
|
|
|
# Domains can be joinable by any user of the instance (as the default one
|
|
|
|
# should)
|
|
|
|
public = models.BooleanField(default=False)
|
|
|
|
|
2022-11-18 15:28:15 +00:00
|
|
|
# If this is the default domain (shown as the default entry for new users)
|
|
|
|
default = models.BooleanField(default=False)
|
|
|
|
|
2022-11-06 20:48:04 +00:00
|
|
|
# Domains can also be linked to one or more users for their private use
|
|
|
|
# This should be display domains ONLY
|
|
|
|
users = models.ManyToManyField("users.User", related_name="domains", blank=True)
|
|
|
|
|
2023-03-06 23:37:05 +00:00
|
|
|
# Free-form notes field for admins
|
|
|
|
notes = models.TextField(blank=True, null=True)
|
|
|
|
|
2022-11-06 20:48:04 +00:00
|
|
|
created = models.DateTimeField(auto_now_add=True)
|
|
|
|
updated = models.DateTimeField(auto_now=True)
|
|
|
|
|
2022-11-17 04:12:28 +00:00
|
|
|
class urls(urlman.Urls):
|
2022-11-17 04:42:25 +00:00
|
|
|
root = "/admin/domains/"
|
|
|
|
create = "/admin/domains/create/"
|
|
|
|
edit = "/admin/domains/{self.domain}/"
|
2022-11-18 15:28:15 +00:00
|
|
|
delete = "{edit}delete/"
|
2022-11-26 00:52:43 +00:00
|
|
|
root_federation = "/admin/federation/"
|
|
|
|
edit_federation = "/admin/federation/{self.domain}/"
|
2022-11-17 04:12:28 +00:00
|
|
|
|
2023-07-10 16:11:48 +00:00
|
|
|
class Meta:
|
|
|
|
indexes: list = []
|
|
|
|
|
2022-11-06 20:48:04 +00:00
|
|
|
@classmethod
|
2022-11-07 04:30:07 +00:00
|
|
|
def get_remote_domain(cls, domain: str) -> "Domain":
|
2022-11-24 23:27:21 +00:00
|
|
|
return cls.objects.get_or_create(domain=domain.lower(), local=False)[0]
|
2022-11-06 20:48:04 +00:00
|
|
|
|
|
|
|
@classmethod
|
2022-11-10 05:29:33 +00:00
|
|
|
def get_domain(cls, domain: str) -> Optional["Domain"]:
|
2022-11-06 20:48:04 +00:00
|
|
|
try:
|
|
|
|
return cls.objects.get(
|
2022-11-24 23:27:21 +00:00
|
|
|
models.Q(domain=domain.lower())
|
|
|
|
| models.Q(service_domain=domain.lower())
|
2022-11-06 20:48:04 +00:00
|
|
|
)
|
|
|
|
except cls.DoesNotExist:
|
|
|
|
return None
|
|
|
|
|
|
|
|
@property
|
|
|
|
def uri_domain(self) -> str:
|
|
|
|
if self.service_domain:
|
|
|
|
return self.service_domain
|
|
|
|
return self.domain
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def available_for_user(cls, user):
|
|
|
|
"""
|
|
|
|
Returns domains that are available for the user to put an identity on
|
|
|
|
"""
|
|
|
|
return cls.objects.filter(
|
|
|
|
models.Q(public=True) | models.Q(users__id=user.id),
|
|
|
|
local=True,
|
2022-11-18 15:28:15 +00:00
|
|
|
).order_by("-default", "domain")
|
2022-11-06 20:48:04 +00:00
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.domain
|
2022-11-11 06:42:43 +00:00
|
|
|
|
|
|
|
def save(self, *args, **kwargs):
|
|
|
|
# Ensure that we are not conflicting with other domains
|
|
|
|
if Domain.objects.filter(service_domain=self.domain).exists():
|
|
|
|
raise ValueError(
|
|
|
|
f"Domain {self.domain} is already a service domain elsewhere!"
|
|
|
|
)
|
|
|
|
if self.service_domain:
|
|
|
|
if Domain.objects.filter(domain=self.service_domain).exists():
|
|
|
|
raise ValueError(
|
|
|
|
f"Service domain {self.service_domain} is already a domain elsewhere!"
|
|
|
|
)
|
2022-11-12 05:02:43 +00:00
|
|
|
super().save(*args, **kwargs)
|
2023-01-04 23:40:16 +00:00
|
|
|
|
2023-07-17 06:37:47 +00:00
|
|
|
def fetch_nodeinfo(self) -> NodeInfo | None:
|
2023-01-04 23:40:16 +00:00
|
|
|
"""
|
|
|
|
Fetch the /NodeInfo/2.0 for the domain
|
|
|
|
"""
|
2023-01-07 17:36:36 +00:00
|
|
|
nodeinfo20_url = f"https://{self.domain}/nodeinfo/2.0"
|
|
|
|
|
2023-07-17 06:37:47 +00:00
|
|
|
with httpx.Client(
|
2023-01-04 23:40:16 +00:00
|
|
|
timeout=settings.SETUP.REMOTE_TIMEOUT,
|
|
|
|
headers={"User-Agent": settings.TAKAHE_USER_AGENT},
|
|
|
|
) as client:
|
|
|
|
try:
|
2023-07-17 06:37:47 +00:00
|
|
|
response = client.get(
|
2023-01-07 17:36:36 +00:00
|
|
|
f"https://{self.domain}/.well-known/nodeinfo",
|
|
|
|
follow_redirects=True,
|
|
|
|
headers={"Accept": "application/json"},
|
|
|
|
)
|
|
|
|
except httpx.HTTPError:
|
|
|
|
pass
|
2023-07-12 15:51:08 +00:00
|
|
|
except (ssl.SSLCertVerificationError, ssl.SSLError):
|
2023-01-13 17:53:02 +00:00
|
|
|
return None
|
2023-01-07 17:36:36 +00:00
|
|
|
else:
|
|
|
|
try:
|
|
|
|
for link in response.json().get("links", []):
|
|
|
|
if (
|
|
|
|
link.get("rel")
|
|
|
|
== "http://nodeinfo.diaspora.software/ns/schema/2.0"
|
|
|
|
):
|
|
|
|
nodeinfo20_url = link.get("href", nodeinfo20_url)
|
|
|
|
break
|
|
|
|
except json.JSONDecodeError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
try:
|
2023-07-17 06:37:47 +00:00
|
|
|
response = client.get(
|
2023-01-07 17:36:36 +00:00
|
|
|
nodeinfo20_url,
|
2023-01-04 23:40:16 +00:00
|
|
|
follow_redirects=True,
|
|
|
|
headers={"Accept": "application/json"},
|
|
|
|
)
|
|
|
|
response.raise_for_status()
|
2023-01-13 17:53:02 +00:00
|
|
|
except (httpx.HTTPError, ssl.SSLCertVerificationError) as ex:
|
2023-01-04 23:40:16 +00:00
|
|
|
response = getattr(ex, "response", None)
|
|
|
|
if (
|
|
|
|
response
|
|
|
|
and response.status_code < 500
|
2023-01-05 04:45:29 +00:00
|
|
|
and response.status_code not in [401, 403, 404, 406, 410]
|
2023-01-04 23:40:16 +00:00
|
|
|
):
|
2023-11-16 17:27:20 +00:00
|
|
|
logger.warning(
|
|
|
|
"Client error fetching nodeinfo: %d %s %s",
|
|
|
|
response.status_code,
|
|
|
|
nodeinfo20_url,
|
|
|
|
ex,
|
2023-10-23 16:33:55 +00:00
|
|
|
extra={
|
2023-01-19 20:14:55 +00:00
|
|
|
"content": response.content,
|
|
|
|
"domain": self.domain,
|
|
|
|
},
|
2023-01-04 23:40:16 +00:00
|
|
|
)
|
|
|
|
return None
|
|
|
|
|
|
|
|
try:
|
|
|
|
info = NodeInfo(**response.json())
|
2023-01-18 17:57:28 +00:00
|
|
|
except (json.JSONDecodeError, pydantic.ValidationError) as ex:
|
2023-11-16 17:27:20 +00:00
|
|
|
logger.warning(
|
|
|
|
"Client error decoding nodeinfo: %s %s",
|
|
|
|
nodeinfo20_url,
|
|
|
|
ex,
|
2023-10-23 16:33:55 +00:00
|
|
|
extra={
|
2023-01-18 17:57:28 +00:00
|
|
|
"domain": self.domain,
|
|
|
|
},
|
2023-01-04 23:40:16 +00:00
|
|
|
)
|
2023-01-13 17:53:02 +00:00
|
|
|
return None
|
2023-01-04 23:40:16 +00:00
|
|
|
return info
|
2023-01-11 03:31:50 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def software(self):
|
|
|
|
if self.nodeinfo:
|
|
|
|
software = self.nodeinfo.get("software", {})
|
|
|
|
name = software.get("name", "unknown")
|
|
|
|
version = software.get("version", "unknown")
|
|
|
|
return f"{name:.10} - {version:.10}"
|
|
|
|
return None
|
2023-05-04 04:42:37 +00:00
|
|
|
|
2023-07-22 16:54:36 +00:00
|
|
|
def recursively_blocked(self) -> bool:
|
|
|
|
"""
|
|
|
|
Checks for blocks on all right subsets of this domain, except the very
|
|
|
|
last part of the TLD.
|
|
|
|
|
|
|
|
Yes, I know this weirdly lets you block ".co.uk" or whatever, but
|
|
|
|
people can do that if they want I guess.
|
|
|
|
"""
|
|
|
|
# Efficient short-circuit
|
|
|
|
if self.blocked:
|
|
|
|
return True
|
|
|
|
# Build domain list
|
|
|
|
domain_parts = [self.domain]
|
|
|
|
while "." in domain_parts[-1]:
|
|
|
|
domain_parts.append(domain_parts[-1].split(".", 1)[1])
|
|
|
|
# See if any of those are blocked
|
|
|
|
return Domain.objects.filter(domain__in=domain_parts, blocked=True).exists()
|
|
|
|
|
2023-05-04 04:42:37 +00:00
|
|
|
### Config ###
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def config_domain(self) -> Config.DomainOptions:
|
|
|
|
return Config.load_domain(self)
|