-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathatproto.py
More file actions
1869 lines (1563 loc) · 73.5 KB
/
Copy pathatproto.py
File metadata and controls
1869 lines (1563 loc) · 73.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""ATProto protocol implementation.
https://atproto.com/
"""
from collections import defaultdict
from datetime import timedelta
import itertools
import logging
import os
import re
from urllib.parse import urljoin, urlparse
from arroba import did
from arroba.did import get_handle
from arroba import datastore_storage
from arroba.datastore_storage import (
AtpRemoteBlob,
AtpRepo,
DatastoreStorage,
MemcacheSequences,
)
from arroba.repo import Repo, Write
import arroba.memcache
import arroba.server
from arroba.storage import Action, CommitData, Sequences
from arroba.util import (
at_uri,
dag_cbor_cid,
InactiveRepo,
next_tid,
parse_at_uri,
service_jwt,
TOMBSTONED,
)
from arroba import xrpc_repo, xrpc_sync
from domain2idna import domain2idna
from flask import abort, redirect, request
from google.cloud import dns
from google.cloud.dns.resource_record_set import ResourceRecordSet
from google.cloud import ndb
import googleapiclient.discovery
from granary import as1, as2, bluesky
from granary.bluesky import Bluesky, FROM_AS1_TYPES, to_external_embed
from granary.source import html_to_text, INCLUDE_LINK, Source
from lexrpc import Client, ValidationError
from lexrpc.base import AT_URI_RE, DID_RE
from requests import RequestException
import oauth_dropins.bluesky
from pymemcache.test.utils import MockMemcacheClient
from webutil import util
from webutil.appengine_config import ndb_client
from webutil.appengine_info import DEBUG, LOCAL_SERVER, TESTING
from webutil import flask_util
from webutil.flask_util import (
canonicalize_request_domain,
FlashErrors,
get_required_param,
)
from webutil.models import StringIdModel
from webutil.util import add, json_dumps, json_loads
from werkzeug.exceptions import HTTPException, NotFound
import common
from common import (
CACHE_CONTROL,
error,
FlashErrors,
USER_AGENT,
)
import config
import domains
from domains import (
DOMAIN_RE,
DOMAINS,
PRIMARY_DOMAIN,
PROTOCOL_DOMAINS,
SUPERDOMAIN,
)
from flask_app import app
import ids
import memcache
from models import Follower, Object, PROTOCOLS, Target, User
from protocol import Protocol
import web
logger = logging.getLogger(__name__)
arroba.server.storage = None # initialized in init() below
appview = Client(f'https://{os.environ["APPVIEW_HOST"]}',
headers={'User-Agent': USER_AGENT},
requests_session=util.session)
LEXICONS = appview.defs
# https://atproto.com/guides/applications#record-types
COLLECTION_TO_TYPE = {
'app.bsky.actor.profile': 'profile',
'app.bsky.feed.like': 'like',
'app.bsky.feed.post': 'post',
'app.bsky.feed.repost': 'repost',
'app.bsky.graph.follow': 'follow',
}
# Bluesky-operated PDSes that only allow accounts they originally created, so we
# can't migrate accounts to them
# https://docs.bsky.app/blog/incoming-migration
MAIN_PDS_DOMAINS = ('bsky.app', 'bsky.network', 'bsky.social')
DNS_GCP_PROJECT = 'brid-gy'
DNS_ZONE = 'brid-gy'
DNS_TTL = 10800 # seconds
logger.info(f'Using GCP DNS project {DNS_GCP_PROJECT} zone {DNS_ZONE}')
# "Cloud DNS API" https://github.com/googleapis/python-dns
dns_client = dns.Client(project=DNS_GCP_PROJECT)
# "Discovery API" https://github.com/googleapis/google-api-python-client
dns_discovery_api = googleapiclient.discovery.build('dns', 'v1')
def init(sequences_cls):
"""Connect arroba's storage and sequence numbers.
Bridgy Fed uses memcache sequence number allocation in production. If we ever
allocated a sequence number from the datastore instead of memcache, we'd allocate
a duplicate from memcache and collide. So, we make all services that use this
module explicitly initialize it with the sequence number class they need.
https://github.com/snarfed/bridgy-fed/issues/2269
Args:
sequences_cls: :class:`arroba.storage.Sequences` subclass
"""
if sequences_cls == MemcacheSequences:
if LOCAL_SERVER:
logger.warning('MemcacheSequences requested! Not connecting arroba to datastore!')
assert arroba.server.storage is None
return
elif not DEBUG and not TESTING:
assert memcache.memcache.client_class != MockMemcacheClient
sequences = MemcacheSequences(
memcache=memcache.memcache,
ndb_client=ndb_client,
ndb_context_kwargs=common.NDB_CONTEXT_KWARGS)
elif sequences_cls == RemoteSequences:
sequences = RemoteSequences(base_url='https://fed.brid.gy/')
else:
assert False, f'unsupported sequences class {sequences_cls}'
arroba.server.storage = DatastoreStorage(
sequences=sequences,
ndb_client=ndb_client,
ndb_context_kwargs=common.NDB_CONTEXT_KWARGS)
def oauth_client_metadata():
return {
**oauth_dropins.bluesky.CLIENT_METADATA_TEMPLATE,
'client_id': domains.host_url('/oauth/bluesky/client-metadata.json'),
'client_name': 'Bridgy Fed',
'client_uri': domains.host_url(),
'redirect_uris': [domains.host_url('/oauth/bluesky/finish')],
}
def chat_client(*, repo, method, **kwargs):
"""Returns a new Bluesky chat :class:`Client` for a given XRPC method.
Args:
repo (arroba.repo.Repo): ATProto user
method (str): XRPC method NSID, eg ``chat.bsky.convo.sendMessage``
kwargs: passed through to the :class:`lexrpc.client.Client` constructor
Returns:
lexrpc.client.Client:
"""
token = service_jwt(host=os.environ['CHAT_HOST'],
aud=os.environ['CHAT_DID'],
repo_did=repo.did,
privkey=repo.signing_key,
lxm=method)
kwargs.setdefault('headers', {}).update({
'User-Agent': USER_AGENT,
'Authorization': f'Bearer {token}',
})
kwargs.setdefault('truncate', True)
return Client(f'https://{os.environ["CHAT_HOST"]}',
requests_session=util.session, **kwargs)
def repo_callback(data=None, lost_seq=None):
common.create_task(queue='atproto-commit', lost_seq=lost_seq)
class RemoteSequences(Sequences):
"""Sequence number implementation that uses remote HTTP endpoints.
Makes requests to ``/admin/sequences/alloc`` and ``/admin/sequences/last``
to allocate and retrieve sequence numbers.
Used for local shells and scripts, outside GCP.
"""
def __init__(self, base_url):
"""Constructor.
Args:
base_url (str): base URL for the remote server, eg ``https://fed.brid.gy/``
"""
super().__init__()
assert base_url
self.base_url = base_url
def allocate(self, nsid):
"""Allocates a sequence number via HTTP POST.
Args:
nsid (str): subscription XRPC method this sequence number is for
Returns:
int:
"""
url = urljoin(self.base_url, '/admin/sequences/alloc')
logger.info(f'allocating seq via remote: {url}')
resp = util.requests_post(url, data={'nsid': nsid},
headers={'Authorization': config.SECRET_KEY})
resp.raise_for_status()
seq = int(resp.text.strip())
logger.info(f' allocated seq {seq}')
return seq
def last(self, nsid):
"""Gets the last sequence number via HTTP GET.
Args:
nsid (str): subscription XRPC method this sequence number is for
Returns:
int or None:
"""
resp = util.requests_get(urljoin(self.base_url, '/admin/sequences/last'),
params={'nsid': nsid},
headers={'Authorization': config.SECRET_KEY})
resp.raise_for_status()
text = resp.text.strip()
return int(text) if text and text != 'None' else None
class DatastoreClient(Client):
"""Bluesky client that uses the datastore as well as remote XRPC calls.
Overrides ``getRecord`` and ``resolveHandle``. If we have a record or DID
document stored locally, uses it as is instead of making a remote XRPC call.
Otherwise, passes through to the server.
Right now, requires that the server address is the same as
``$APPVIEW_HOST``, because ``getRecord`` passes through to ``ATProto.load``
and then to ``ATProto.fetch``, which uses the ``appview`` global.
"""
remote = True
''
def __init__(self, remote=True, *args, **kwargs):
"""
Args:
remote (bool): if False, don't make any external calls, only look
in the datastore
"""
super().__init__(*args, address=f'https://{os.environ["APPVIEW_HOST"]}',
requests_session=util.session, **kwargs)
self.remote = remote
def call(self, nsid, input=None, headers={}, **params):
if nsid == 'com.atproto.repo.getRecord':
return self.get_record(**params) # may return {}
if nsid == 'com.atproto.identity.resolveHandle':
if ret := self.resolve_handle(**params):
return ret
if self.remote:
return super().call(nsid, input=input, headers=headers, **params)
def get_record(self, repo=None, collection=None, rkey=None):
assert repo and collection and rkey, (repo, collection, rkey)
did = repo
uri = at_uri(did=did, collection=collection, rkey=rkey)
record = None
if repo := arroba.server.storage.load_repo(did):
# local record in a repo we own
record = repo.get_record(collection=collection, rkey=rkey)
else:
# remote record that we may have a cached copy of
obj = ATProto.load(uri, remote=(None if self.remote else False),
raise_=False)
if (not obj or not obj.bsky) and self.remote:
obj = ATProto.load(uri, local=False, remote=True, raise_=False)
if obj:
record = obj.bsky
if record:
return {
'uri': uri,
'cid': record.get('cid') or dag_cbor_cid(record).encode('base32'),
'value': record,
}
else:
return {}
@staticmethod
def resolve_handle(handle=None):
assert handle
got = (ATProto.query(ATProto.handle == handle).get() # native Bluesky user
or AtpRepo.query(AtpRepo.handles == handle, # bridged user,
AtpRepo.status == None).get() # non-tombstoned first
or AtpRepo.query(AtpRepo.handles == handle).get())
if got:
return {'did': got.key.id()}
def did_to_handle(did, remote=None):
"""Resolves a DID to a handle.
Args:
did (str)
remote (bool): whether to fetch the object over the network. See
:meth:`Protocol.load`
Returns:
str: handle, or None
"""
assert did.startswith('did:'), did
if did_obj := ATProto.load(did, raw=True, remote=remote):
return get_handle(did_obj.raw)
class ATProto(User, Protocol):
"""AT Protocol class.
Key id is DID, currently either did:plc or did:web.
https://atproto.com/specs/did
"""
ABBREV = 'bsky'
''
PHRASE = 'Bluesky'
''
LOGO_EMOJI = '🦋'
''
LOGO_HTML = '<img src="/oauth_dropins_static/bluesky.svg">'
''
DEFAULT_TARGET = f'https://atproto{SUPERDOMAIN}'
"""Note that PDS hostname is atproto.brid.gy here, not bsky.brid.gy. Also note
that PDS URLs shouldn't include trailing slash.
https://atproto.com/specs/did#did-documents
"""
CONTENT_TYPE = 'application/json'
''
HAS_COPIES = True
''
REQUIRES_AVATAR = True
''
REQUIRES_NAME = False
''
DEFAULT_ENABLED_PROTOCOLS = ('web',)
''
SUPPORTED_AS1_TYPES = frozenset(
tuple(as1.ACTOR_TYPES)
+ tuple(as1.POST_TYPES)
+ tuple(as1.CRUD_VERBS)
+ ('block', 'follow', 'flag', 'like', 'share', 'stop-following')
)
''
SUPPORTED_RECORD_TYPES = frozenset(
type for type in itertools.chain(*FROM_AS1_TYPES.values())
if '#' not in type)
'Which incoming record lexicons we should accept from the firehose.'
SUPPORTED_RECORD_TYPES_BETA_USERS = frozenset([])
'Which incoming record lexicons to accept from the firehose only for beta users.'
STORE_RECORD_TYPES = frozenset(['community.lexicon.payments.webMonetization'])
''
SUPPORTS_DMS = True
''
HTML_PROFILES = False
''
def _pre_put_hook(self):
"""Validate id, require did:plc or non-blocklisted did:web."""
super()._pre_put_hook()
id = self.key.id()
assert id
if id.startswith('did:plc:'):
assert id.removeprefix('did:plc:')
elif id.startswith('did:web:'):
domain = id.removeprefix('did:web:')
assert (DOMAIN_RE.fullmatch(domain)
and not Protocol.is_blocklisted(domain)), domain
else:
assert False, f'{id} is not valid did:plc or did:web'
@ndb.ComputedProperty
def handle(self):
"""Returns handle if the DID document includes one, otherwise None."""
return did_to_handle(self.key.id())
def web_url(self):
return Bluesky.user_url(self.handle_or_id())
@classmethod
def owns_id(cls, id):
return (bool(AT_URI_RE.match(id))
or bool(DID_RE.fullmatch(id))
or id.startswith('https://bsky.app/'))
@classmethod
def owns_handle(cls, handle, allow_internal=False):
# TODO: implement allow_internal?
if not did.HANDLE_RE.fullmatch(handle):
return False
@classmethod
def handle_to_id(cls, handle):
if not handle or cls.owns_handle(handle) is False:
return None
if resp := DatastoreClient.resolve_handle(handle):
return resp['did']
return did.resolve_handle(handle, get_fn=util.requests_get)
def reload_profile(self, **kwargs):
"""Reloads this user's DID doc along with their profile object."""
# load DID doc first so that when we write the ATProto, it populates
# the new handle
self.load(self.key.id(), raw=True, remote=True, **kwargs)
super().reload_profile(**kwargs)
@classmethod
def bridged_web_url_for(cls, user, fallback=False):
"""Returns a bridged user's profile URL on bsky.app.
For example, returns ``https://bsky.app/profile/alice.com.web.brid.gy``
for Web user ``alice.com``.
"""
if not isinstance(user, ATProto):
if did := user.get_copy(ATProto):
# bsky.app doesn't fully support IDNs in profile URLs yet, so use
# punycode. https://github.com/snarfed/bridgy-fed/issues/2222
return Bluesky.user_url(domain2idna(did_to_handle(did)) or did)
return super().bridged_web_url_for(user, fallback=fallback)
@classmethod
def target_for(cls, obj, shared=False):
"""Returns our PDS URL as the target for the given object.
ATProto delivery is indirect. We write all records to the user's local
repo that we host, then relays and other subscribers receive them via the
subscribeRepos event streams. So, we use a single target, our base URL
(eg ``https://atproto.brid.gy``) as the PDS URL, for all activities.
"""
if cls.owns_id(obj.key.id()) is not False:
return cls.DEFAULT_TARGET
@classmethod
def pds_for(cls, obj):
"""Returns the PDS URL for the given object, or None.
Args:
obj (Object)
Returns:
str:
"""
id = obj.key.id()
# logger.debug(f'Finding ATProto PDS for {id}')
if id.startswith('did:'):
if obj.raw:
for service in obj.raw.get('service', []):
if service.get('id') in ('#atproto_pds', f'{id}#atproto_pds'):
return service.get('serviceEndpoint')
logger.info(f"{id}'s DID doc has no ATProto PDS")
return None
if id.startswith('https://bsky.app/'):
return cls.pds_for(Object(id=bluesky.web_url_to_at_uri(id)))
if id.startswith('at://'):
repo, collection, rkey = parse_at_uri(id)
if not repo.startswith('did:'):
# repo is a handle; resolve it
repo_did = cls.handle_to_id(repo)
if repo_did:
return cls.pds_for(Object(id=id.replace(
f'at://{repo}', f'at://{repo_did}')))
else:
return None
did_obj = ATProto.load(repo, raw=True)
if did_obj:
return cls.pds_for(did_obj)
# TODO: what should we do if the DID doesn't exist? should we return
# None here? or do we need this path to return BF's URL so that we
# then create the DID for non-ATP users on demand?
# don't use Object.as1 if bsky is set, since that conversion calls
# pds_for, which would infinite loop
if not obj.bsky and obj.as1:
if owner := as1.get_owner(obj.as1):
if user_key := Protocol.key_for(owner):
if user := user_key.get():
if owner_did := user.get_copy(ATProto):
return cls.pds_for(Object(id=f'at://{owner_did}'))
return None
@classmethod
def is_blocklisted(cls, url, allow_internal=False):
if util.domain_from_link(url) == cls.DEFAULT_TARGET:
return False
return super().is_blocklisted(url, allow_internal=allow_internal)
@classmethod
def create_for(cls, user):
"""Creates an ATProto repo and profile for a non-ATProto user.
If the repo already exists, reactivates it by emitting an #account event
with active: True.
Args:
user (models.User)
Raises:
ValueError: if the user's handle is invalid, eg begins or ends with an
underscore or dash
"""
assert not isinstance(user, ATProto)
handle = user.handle_as('atproto')
if copy_did := user.get_copy(ATProto):
# already bridged and inactive
repo = arroba.server.storage.load_repo(copy_did)
if not repo.status:
# already active; noop
return
elif repo.status == TOMBSTONED:
# tombstoned repos can't be reactivated, have to wipe and start fresh
user.copies = []
if user.obj:
user.obj.copies = []
user.obj.put()
# fall through to create new DID, repo
else:
# deactivated or deleted
arroba.server.storage.activate_repo(repo)
common.create_task(queue='atproto-commit')
if handle.endswith(SUPERDOMAIN):
cls.set_dns(handle=handle, did=copy_did)
return
# create new DID
# PDS URL shouldn't include trailing slash!
# https://atproto.com/specs/did#did-documents
pds_url = domains.host_url().rstrip('/') if DEBUG else cls.DEFAULT_TARGET
logger.info(f'Creating new did:plc for {user.key.id()} {handle} {pds_url}')
did_plc = did.create_plc(handle, pds_url=pds_url, post_fn=util.requests_post,
also_known_as=user.all_ids(except_=cls))
Object.get_or_create(did_plc.did, raw=did_plc.doc, authed_as=did_plc)
cls.set_dns(handle=handle, did=did_plc.did)
# fetch user profile. (we store it later, at the end of this method)
if not user.obj or not user.obj.as1:
user.reload_profile()
# create repo
repo = Repo.create(arroba.server.storage, did_plc.did, handle=handle,
callback=repo_callback, signing_key=did_plc.signing_key,
rotation_key=did_plc.rotation_key)
# create chat declaration
logger.info(f'Storing ATProto chat declaration record')
chat_declaration = {
"$type" : "chat.bsky.actor.declaration",
"allowIncoming" : "none",
}
initial_writes = [Write(action=Action.CREATE, record=chat_declaration,
collection='chat.bsky.actor.declaration', rkey='self')]
arroba.server.storage.commit(repo, initial_writes)
# don't add the copy id until the end, here, until we've fully
# successfully created the DID, repo, etc
user.add('copies', Target(uri=did_plc.did, protocol='atproto'))
user.put()
# create user profile. can't include this in initial writes because
# bluesky.to_as1 in convert fetches the pinned post, which with our
# DatastoreClient looks it up as an ATProto record in the repo.
if user.obj and user.obj.as1:
create_profile = Object(our_as1={
'objectType': 'activity',
'verb': 'post',
'actor': user.key.id(),
'object': user.obj.as1,
}, source_protocol=user.LABEL)
if not cls.send(create_profile, pds_url, from_user=user):
logger.warning(f"couldn't create profile {user.obj_key.id()}")
@classmethod
def set_dns(cls, handle, did):
"""Create _atproto DNS record for handle resolution.
https://atproto.com/specs/handle#handle-resolution
If the DNS record already exists, or if we're not in prod, does nothing.
If the DNS record exists with a different DID, deletes it and recreates
it with this DID.
Args:
handle (str): Bluesky handle, eg ``snarfed.org.web.brid.gy``
did (str): ATProto DID
"""
name = f'_atproto.{handle}.'
val = f'"did={did}"'
logger.info(f'adding GCP DNS TXT record for {name} {val}')
if DEBUG:
logger.info(' skipped since DEBUG is true')
return
elif util.domain_or_parent_in(handle, ids.ATPROTO_HANDLE_DOMAINS):
logger.info(' skipped since domain is in ATPROTO_HANDLE_DOMAINS')
return
# https://cloud.google.com/python/docs/reference/dns/latest
# https://cloud.google.com/dns/docs/reference/rest/v1/
zone = dns_client.zone(DNS_ZONE)
changes = zone.changes()
logger.info('Checking for existing record')
ATProto.remove_dns(handle)
changes.add_record_set(zone.resource_record_set(name=name, record_type='TXT',
ttl=DNS_TTL, rrdatas=[val]))
changes.create()
logger.info('done!')
@classmethod
def remove_dns(cls, handle):
"""Removes an _atproto DNS record.
https://atproto.com/specs/handle#handle-resolution
Args:
handle (str): Bluesky handle, eg ``snarfed.org.web.brid.gy``
"""
name = f'_atproto.{handle}.'
logger.info(f'removing GCP DNS TXT record for {name}')
if DEBUG:
logger.info(' skipped since DEBUG is true')
return
# https://cloud.google.com/python/docs/reference/dns/latest
# https://cloud.google.com/dns/docs/reference/rest/v1/
zone = dns_client.zone(DNS_ZONE)
changes = zone.changes()
# sadly can't check if the record exists with the google.cloud.dns API
# because it doesn't support list_resource_record_sets's name param.
# heed to use the generic discovery-based API instead.
# https://cloud.google.com/python/docs/reference/dns/latest/zone#listresourcerecordsetsmaxresultsnone-pagetokennone-clientnone
# https://github.com/googleapis/python-dns/issues/31#issuecomment-1595105412
# https://cloud.google.com/apis/docs/client-libraries-explained
# https://googleapis.github.io/google-api-python-client/docs/dyn/dns_v1.resourceRecordSets.html
resp = dns_discovery_api.resourceRecordSets().list(
project=DNS_GCP_PROJECT, managedZone=DNS_ZONE, type='TXT', name=name,
).execute()
if rrsets := resp.get('rrsets', []):
for existing in rrsets:
logger.info(f' deleting {existing}')
changes.delete_record_set(ResourceRecordSet.from_api_repr(existing, zone=zone))
changes.create()
@classmethod
def set_username(to_cls, user, username):
if not user.is_enabled(ATProto):
raise ValueError("First, you'll need to bridge your account into Bluesky by following this account.")
copy_did = user.get_copy(ATProto)
username = username.removeprefix('@')
repo = arroba.server.storage.load_repo(copy_did)
assert repo
if repo.status:
raise RuntimeError(f"Couldn't set username, your bridged Bluesky account is {repo.status}.")
elif username == repo.handle:
logger.info(f'repo {repo.did} already has handle {username}, setting anyway')
# resolve_handle checks that username is a valid domain
resolved = did.resolve_handle(username, get_fn=util.requests_get)
if resolved != copy_did:
raise RuntimeError(f"""<p>You'll need to connect that domain to your bridged Bluesky account, either <a href="https://bsky.social/about/blog/4-28-2023-domain-handle-tutorial">with DNS</a> <a href="https://atproto.com/specs/handle#handle-resolution">or HTTP</a>. Your DID is: <code>{copy_did}</code><p>Once you're done, <a href="https://bsky-debug.app/handle?handle={username}">check your work here</a>, then try again.""")
logger.info(f'Setting ATProto handle for {user.key.id()} to {username}')
repo.callback = repo_callback
did.update_plc(did=copy_did, handle=username,
signing_key=repo.signing_key, rotation_key=repo.rotation_key,
get_fn=util.requests_get, post_fn=util.requests_post)
repo.handle = username
arroba.server.storage.store_repo(repo)
arroba.server.storage.write_event(repo=repo, type='identity', handle=username)
# refresh our stored DID doc and repo handle
to_cls.load(copy_did, raw=True, remote=True)
repo.handle = username
@classmethod
def send(to_cls, obj, pds_url, from_user=None, orig_obj_id=None):
"""Creates a record if we own its repo.
If the repo's DID doc doesn't say we're its PDS, does nothing and
returns False.
Doesn't deliver anywhere externally! Relays will receive this record
through ``subscribeRepos`` and then deliver it to AppView(s), which will
notify recipients as necessary.
Exceptions:
* ``flag``s are translated to ``createReport`` to the mod service
* DMs are translated to ``sendMessage`` to the chat service
"""
if util.domain_from_link(pds_url) not in DOMAINS:
logger.info(f'Target PDS {pds_url} is not us')
return False
# determine "base" object, if any
type = as1.object_type(obj.as1)
base_obj = obj
base_obj_as1 = obj.as1
base_id = base_obj.key.id() if base_obj.key else None
allow_opt_out = (type == 'delete')
if type in as1.CRUD_VERBS:
base_obj_as1 = as1.get_object(obj.as1)
base_id = base_obj_as1.get('id')
base_obj_type = as1.object_type(base_obj_as1)
if type == 'undo' and base_obj_type == 'block' and not base_id:
# we allow undo of block without id
# https://github.com/snarfed/bridgy-fed/issues/2073
base_obj = Object(our_as1=base_obj_as1)
else:
if not base_id:
logger.info(f'{type} object has no id!')
return False
base_obj = (from_user or PROTOCOLS[obj.source_protocol]).load(base_id, remote=False)
if type not in ('delete', 'undo'):
if not base_obj: # probably a new repo
base_obj = Object(id=base_id, source_protocol=obj.source_protocol)
base_obj.our_as1 = base_obj_as1
# profile update. if it has a pinned post that's not bridged, do that
# first, before calling convert below
if base_obj_as1.get('objectType') in as1.ACTOR_TYPES:
feat_as1 = as1.get_object(base_obj_as1, 'featured')
if feat_id := as1.get_id(feat_as1, 'items'):
from_cls = obj.owner_protocol()
if ((feat_obj := from_cls.load(feat_id)) and feat_obj.as1
and not feat_obj.get_copy(ATProto)):
logger.info(f'first, creating pinned post {feat_id}')
ATProto.send(feat_obj, pds_url, from_user=from_user)
if not base_obj:
logger.info(f"Can't {type} {base_id}, no original object")
return False
elif type == 'stop-following':
assert from_user
to_id = as1.get_object(obj.as1).get('id')
assert to_id
to_key = Protocol.key_for(to_id, allow_opt_out=True)
follower = Follower.query(Follower.from_ == from_user.key,
Follower.to == to_key).get()
if not follower or not follower.follow:
logger.info(f"Skipping, can't find Follower for {from_user.key.id()} => {to_key.id()} with follow")
return False
base_obj = follower.follow.get()
# convert to Bluesky record; short circuits on error
records = to_cls.convert(base_obj, fetch_blobs=True, from_user=from_user,
multiple=True)
# find user
from_cls = obj.owner_protocol()
if not from_user:
from_key = from_cls.actor_key(obj, allow_opt_out=allow_opt_out)
if not from_key:
logger.info(f"Couldn't find {from_cls.LABEL} user for {obj.key.id() if obj.key else None}")
return False
from_user = from_cls.get_or_create(
from_key.id(), allow_opt_out=allow_opt_out, propagate=True)
# load user's DID
did = from_user.get_copy(ATProto)
assert did and did.startswith('did:'), did
logger.info(f'{from_user.key.id()} is {did}')
if not (did_doc := to_cls.load(did, raw=True)):
logger.warning(f" couldn't load DID doc")
return False
pds = to_cls.pds_for(did_doc) if did_doc else None
if not pds or util.domain_from_link(pds) not in DOMAINS:
logger.warning(f' PDS {pds} is not us')
return False
# load repo
repo = arroba.server.storage.load_repo(did)
assert repo
repo.callback = repo_callback
# non-commit operations:
# * delete actor => deactivate repo
# * flag => send report to mod service
# * stop-following => delete follow record (prepared above)
# * dm => chat message
verb = obj.as1.get('verb')
if verb == 'delete':
atp_base_id = (base_id if ATProto.owns_id(base_id)
else ids.translate_user_id(from_=from_cls, to=to_cls,
id=base_id))
if atp_base_id == did:
logger.info(f'Deactivating bridged ATProto account {did} !')
arroba.server.storage.deactivate_repo(repo)
to_cls.remove_dns(from_user.handle_as('atproto'))
return True
if not records and verb not in ('delete', 'undo'):
# _convert already logged
return False
# check repo status after handling delete actor so that we can re-send
# #account status=deactivate events if necessary
if repo.status:
logger.info(f'{repo.did} is {repo.status}, giving up')
return False
if verb == 'flag':
logger.info(f'flag => createReport with {records[0]}')
return create_report(input=records[0], from_user=from_user)
elif verb == 'stop-following':
logger.info(f'stop-following => delete of {base_obj.key.id()}')
assert base_obj and base_obj.type == 'follow', base_obj
verb = 'delete'
elif verb == 'undo' and base_obj_type == 'block':
# for undo of block without id (eg from dms.unblock()), find and delete
# *all* block records with the given object (subject)
# https://github.com/snarfed/bridgy-fed/issues/2073
blockee = as1.get_object(base_obj_as1).get('id')
if not (blockee_proto := Protocol.for_id(blockee)):
logger.error(f"can't determine protocol for {blockee}")
return False
blockee = (
ids.translate_user_id(id=blockee, from_=blockee_proto, to=to_cls)
or ids.translate_object_id(id=blockee, from_=blockee_proto, to=to_cls))
if not blockee:
logger.error('no object.object for undo block')
return False
if blockee.startswith('did:'):
collection = 'app.bsky.graph.block'
elif parse_at_uri(blockee)[1] == 'app.bsky.graph.list':
collection = 'app.bsky.graph.listblock'
else:
logger.warning(f"unknown block object {blockee}")
return
logger.info(f'Deleting {collection}s for subject {blockee}')
writes = []
resp = xrpc_repo.list_records({}, repo=did, limit=None,
collection=collection)
for record in resp['records']:
if record['value']['subject'] == blockee:
_, _, rkey = parse_at_uri(record['uri'])
writes.append(Write(action=Action.DELETE, collection=collection,
rkey=rkey))
with arroba.memcache.Lease(memcache.memcache, f'arroba-commit-{did}',
retries=250):
arroba.server.storage.commit(repo, writes)
return True
elif recip := as1.recipient_if_dm(obj.as1):
assert recip.startswith('did:'), recip
return send_chat(msg=records[0], from_repo=repo, to_did=recip)
copies = {} # maps string collection to (DID, collection, rkey) tuple
for copy in base_obj.get_copies(to_cls):
copy_did, collection, rkey = parse_at_uri(copy)
if existing := copies.get(collection):
logger.warning(f'{base_id} has multiple {collection}: {existing[2]} {rkey}')
continue
copies[collection] = (copy_did, collection, rkey)
writes = []
# generate commit
if verb in ('delete', 'undo'):
writes = [Write(action=Action.DELETE, collection=collection, rkey=rkey)
for _, collection, rkey in copies.values()]
else:
# create or other verb
for record in records:
type = record['$type']
lex_type = LEXICONS[type]['type']
assert lex_type == 'record', f"Can't store {type} object of type {lex_type}"
copy = copies.get(type)
if verb == 'create' and copy:
logger.info(f'already has ATProto copy {copy}, cowardly refusing to create again')
continue
if verb == 'create' or not copy:
action = Action.CREATE
if not (rkey := generate_rkey(type)):
continue
else: # update
action = Action.UPDATE
copy_did, collection, rkey = copy
assert collection == type
if copy_did != did:
logger.warning(f"Can't update {base_id} {type}, original {copy} is in a different repo")
continue
writes.append(Write(action=action, collection=type,
rkey=rkey, record=record))
if not writes:
logger.info('Nothing to do!')
return False
postprocess_writes(writes, from_user)
logger.info(f'Storing ATProto {writes}')
try:
# serialize commits per repo. constructing and writing the commits can
# take some time, so without serializing, we hit datastore contention,
# which makes us drop sequence numbers, since they're allocated before
# the commit transaction, and those delay hub from emitting commit events
# over the firehose while it waits for the skipped seqs, and sometimes
# those delays mean we drop events entirely.
# https://github.com/snarfed/arroba/issues/74
with arroba.memcache.Lease(memcache.memcache, f'arroba-commit-{did}',
retries=250):
arroba.server.storage.commit(repo, writes)
except ValueError as e:
# if a CREATE conflicts with an existing record, retry as UPDATE.
# (this exception and error message comes from arroba.mst.MST.add)
msg = str(e)
prefix = 'There is already a value at key: '
if not msg.startswith(prefix):
# probably a DELETE but the record doesn't exist
logger.warning(e)
return False
path = msg.removeprefix(prefix)
for i, write in enumerate(writes):
if (write.action == Action.CREATE
and f'{write.collection}/{write.rkey}' == path):
writes[i] = write._replace(action=Action.UPDATE)
logger.info(f'Retrying with UPDATE for conflict at {path}')
arroba.server.storage.commit(repo, writes)
break
else:
# ¯\_(ツ)_/¯
logger.warning(e)
return False
logger.info(f' seq {repo.head.seq}')
if verb not in ('delete', 'undo'):
@ndb.transactional()
def add_copies():
# read_consistency=ndb.STRONG shouldn't be necessary here, but oddly
# it is, ndb seems to use cache inside txes even though it shouldn't
# https://github.com/googleapis/python-ndb/issues/751
# https://github.com/googleapis/python-ndb/issues/888 ?
stored_obj = base_obj.key.get(read_consistency=ndb.STRONG)
for write in writes:
copy = Target(uri=at_uri(did, write.collection, write.rkey),
protocol=to_cls.LABEL)
base_obj.add('copies', copy)