Exemplo n.º 1
0
            public async Task <ASObject> ClientToServer(APEntity outbox, ASObject activity)
            {
                var stagingStore = new StagingEntityStore(_mainStore);
                var userId       = (string)outbox.Data["attributedTo"].Single().Primitive;
                var user         = await _mainStore.GetEntity(userId, false);

                if (!_entityData.IsActivity(activity))
                {
#pragma warning disable CS0618 // Type or member is obsolete
                    if (_entityData.IsActivity((string)activity["type"].First().Primitive))
#pragma warning restore CS0618 // Type or member is obsolete
                    {
                        throw new UnauthorizedAccessException("Sending an Activity without an actor isn't allowed. Are you sure you wanted to do that?");
                    }

                    var createActivity = new ASObject();
                    createActivity["type"].Add(new ASTerm("Create"));
                    createActivity["to"].AddRange(activity["to"]);
                    createActivity["bto"].AddRange(activity["bto"]);
                    createActivity["cc"].AddRange(activity["cc"]);
                    createActivity["bcc"].AddRange(activity["bcc"]);
                    createActivity["audience"].AddRange(activity["audience"]);
                    createActivity["actor"].Add(new ASTerm(userId));
                    createActivity["object"].Add(new ASTerm(activity));
                    activity = createActivity;
                }

                if (activity["type"].Any(a => (string)a.Primitive == "Create"))
                {
                    activity["id"].Clear();
                    if (activity["object"].SingleOrDefault()?.SubObject != null)
                    {
                        activity["object"].Single().SubObject["id"].Clear();
                    }
                }

                var flattened = await _flattener.FlattenAndStore(stagingStore, activity);

                using (var transaction = _context.Database.BeginTransaction())
                {
                    foreach (var type in _clientToServerHandlers)
                    {
                        var handler = (BaseHandler)ActivatorUtilities.CreateInstance(_serviceProvider, type,
                                                                                     stagingStore, flattened, user, outbox, _user);
                        var handled = await handler.Handle();

                        flattened = handler.MainObject;
                        if (!handled)
                        {
                            break;
                        }
                    }

                    await _context.SaveChangesAsync();

                    transaction.Commit();

                    return(flattened.Data);
                }
            }
Exemplo n.º 2
0
        public async Task <APEntity> ClientToServer(APEntity outbox, ASObject activity)
        {
            var stagingStore = new StagingEntityStore(_mainStore);
            var userId       = outbox.Data["attributedTo"].Single().Id;
            var user         = await _mainStore.GetEntity(userId, false);

            if (!EntityData.IsActivity(activity))
            {
#pragma warning disable CS0618 // Type or member is obsolete
                if (EntityData.IsActivity(activity.Type.FirstOrDefault()))
#pragma warning restore CS0618 // Type or member is obsolete
                {
                    throw new UnauthorizedAccessException("Sending an Activity without an actor isn't allowed. Are you sure you wanted to do that?");
                }

                var createActivity = new ASObject();
                createActivity.Type.Add("https://www.w3.org/ns/activitystreams#Create");
                createActivity["to"].AddRange(activity["to"]);
                createActivity["bto"].AddRange(activity["bto"]);
                createActivity["cc"].AddRange(activity["cc"]);
                createActivity["bcc"].AddRange(activity["bcc"]);
                createActivity["audience"].AddRange(activity["audience"]);
                createActivity["actor"].Add(ASTerm.MakeId(userId));
                createActivity["object"].Add(ASTerm.MakeSubObject(activity));
                activity = createActivity;
            }

            if (activity.Type.Contains("https://www.w3.org/ns/activitystreams#Create"))
            {
                activity.Id = null;
                if (activity["object"].SingleOrDefault()?.SubObject != null)
                {
                    activity["object"].Single().SubObject.Id = null;
                }
            }

            var flattened = await _flattener.FlattenAndStore(stagingStore, activity);

            IEntityStore store = stagingStore;

            foreach (var type in ServerConfig.ClientToServerHandlers)
            {
                var handler = (BaseHandler)ActivatorUtilities.CreateInstance(_serviceProvider, type,
                                                                             store, flattened, user, outbox, _user);
                var handled = await handler.Handle();

                flattened = handler.MainObject;
                if (!handled)
                {
                    break;
                }
                if (type == typeof(CommitChangesHandler))
                {
                    store = _mainStore;
                }
            }

            return(flattened);
        }
Exemplo n.º 3
0
 protected BaseHandler(StagingEntityStore entityStore, APEntity mainObject, APEntity actor, APEntity targetBox, ClaimsPrincipal user)
 {
     EntityStore = entityStore;
     MainObject  = mainObject;
     Actor       = actor;
     TargetBox   = targetBox;
     User        = user;
 }
Exemplo n.º 4
0
        public async Task <IActionResult> SharedInbox()
        {
            var userId = await _verifier.Verify(Request.Scheme + "://" + Request.Host.ToUriComponent() + Request.Path, HttpContext);

            if (userId == null)
            {
                return(Unauthorized());
            }
            var reader = new StreamReader(Request.Body);
            var data   = ASObject.Parse(await reader.ReadToEndAsync());

            if (!EntityData.IsActivity(data))
            {
                return(StatusCode(403, "Not an activity?"));
            }

            await _connection.OpenAsync();

            using (var transaction = _connection.BeginTransaction())
            {
                APEntity resultEntity;
                if (data["actor"].Any((a) => a.Id == userId))
                {
                    var temporaryStore = new StagingEntityStore(_entityStore);
                    resultEntity = await _entityFlattener.FlattenAndStore(temporaryStore, data, false);

                    await temporaryStore.TrimDown((new Uri(new Uri(userId), "/")).ToString());

                    await temporaryStore.CommitChanges();
                }
                else
                {
                    resultEntity = await _entityStore.GetEntity(data.Id, true);

                    if (resultEntity == null)
                    {
                        return(StatusCode(202));
                    }
                    data = resultEntity.Data;
                }

                var users = await _deliveryService.GetUsersForSharedInbox(data);

                foreach (var user in users)
                {
                    await DeliverToActivityPubTask.Make(new DeliverToActivityPubData { ObjectId = resultEntity.Id, TargetInbox = user.Data["inbox"].First().Id }, _connection);
                }

                transaction.Commit();
                return(StatusCode(202));
            }
        }
Exemplo n.º 5
0
        public async Task <IActionResult> SharedInbox()
        {
            var userId = await _verifier.Verify(Request.Scheme + "://" + Request.Host.ToUriComponent() + Request.Path, HttpContext);

            if (userId == null)
            {
                return(Unauthorized());
            }
            var reader = new StreamReader(Request.Body);
            var data   = ASObject.Parse(await reader.ReadToEndAsync());

            if (!_entityConfiguration.IsActivity(data))
            {
                return(StatusCode(403, "Not an activity?"));
            }
            if (!data["actor"].Any((a) => (string)a.Primitive == userId))
            {
                return(StatusCode(403, "Invalid signature!"));
            }

            var temporaryStore = new StagingEntityStore(_entityStore);
            var resultEntity   = await _entityFlattener.FlattenAndStore(temporaryStore, data, false);

            temporaryStore.TrimDown((new Uri(new Uri(userId), "/")).ToString());
            await temporaryStore.CommitChanges(); // shouuuuld be safe

            var users = await _deliveryService.GetUsersForSharedInbox(data);

            foreach (var user in users)
            {
                if (user.IsOwner)
                {
                    _context.EventQueue.Add(DeliverToActivityPubTask.Make(new DeliverToActivityPubData {
                        ObjectId = resultEntity.Id, TargetInbox = (string)user.Data["inbox"].First().Primitive
                    }));
                }
            }

            await _context.SaveChangesAsync();

            return(StatusCode(202));
        }
Exemplo n.º 6
0
        public async Task <IActionResult> MakeNewActor(NewActorModel model)
        {
            var data = await _getUserInfo();

            if (string.IsNullOrWhiteSpace(model.Username))
            {
                return(View("NewActor", model));
            }
            var user = model.Username;

            var obj = new ASObject();

            obj["type"].Add(new ASTerm("Person"));
            obj["preferredUsername"].Add(new ASTerm(user));
            obj["name"].Add(new ASTerm(string.IsNullOrWhiteSpace(model.Name) ? "Unnamed" : model.Name));
            if (!string.IsNullOrWhiteSpace(model.Summary))
            {
                obj["summary"].Add(new ASTerm(model.Summary));
            }

            var create = new ASObject();

            create["type"].Add(new ASTerm("Create"));
            create["object"].Add(new ASTerm(obj));
            create["to"].Add(new ASTerm("https://www.w3.org/ns/activitystreams#Public"));

            var stagingStore = new StagingEntityStore(_entityStore);
            var apo          = await _flattener.FlattenAndStore(stagingStore, create);

            var handler = new CreateActorHandler(stagingStore, apo, null, null, User, _collectionTools, _entityData, _context);
            await handler.Handle();

            var resultUser = await _entityStore.GetEntity((string)handler.MainObject.Data["object"].First().Primitive, false);

            var outbox = await _entityStore.GetEntity((string)resultUser.Data["outbox"].First().Primitive, false);

            var delivery = new DeliveryHandler(stagingStore, handler.MainObject, resultUser, outbox, User, _collectionTools, _provider.GetRequiredService <DeliveryService>());
            await delivery.Handle();

            return(RedirectToAction("Edit", new { id = resultUser.Id }));
        }
Exemplo n.º 7
0
 public CommitChangesHandler(StagingEntityStore entityStore, APEntity mainObject, APEntity actor, APEntity targetBox, ClaimsPrincipal user) : base(entityStore, mainObject, actor, targetBox, user)
 {
 }
Exemplo n.º 8
0
            public async Task <ASObject> ServerToServer(APEntity inbox, ASObject activity, string subject = null)
            {
                var stagingStore = new StagingEntityStore(_mainStore);
                var userId       = (string)inbox.Data["attributedTo"].Single().Primitive;
                var user         = await _mainStore.GetEntity(userId, false);

                APEntity flattened;

                var subjectUri = new Uri(subject);
                var prefix     = $"{subjectUri.Scheme}://{subjectUri.Host}";

                if (subjectUri.Port != 0)
                {
                    prefix += $":{subjectUri.Port}";
                }
                prefix += "/";

                var id = (string)activity["id"].Single().Primitive;

                flattened = await _mainStore.GetEntity(id, false);

                if (flattened == null)
                {
                    flattened = await _flattener.FlattenAndStore(stagingStore, activity, false);
                }

                stagingStore.TrimDown(prefix); // remove all staging entities that may be faked

                var sentBy = (string)activity["actor"].First().Primitive;

                if (subject != null && sentBy != subject)
                {
                    throw new UnauthorizedAccessException("Invalid authorization header for this subject!");
                }

                if (user.Data["blocks"].Any())
                {
                    var blocks = await _mainStore.GetEntity((string)user.Data["blocks"].First().Primitive, false);

                    if (await _collectionTools.Contains((string)blocks.Data["_blocked"].First().Primitive, sentBy))
                    {
                        throw new UnauthorizedAccessException("You are blocked.");
                    }
                }

                if (await _collectionTools.Contains(inbox.Id, id))
                {
                    return(flattened.Data);
                }

                _serverToServerMutex.WaitOne();

                try
                {
                    using (var transaction = _context.Database.BeginTransaction())
                    {
                        foreach (var type in _serverToServerHandlers)
                        {
                            var handler = (BaseHandler)ActivatorUtilities.CreateInstance(_serviceProvider, type,
                                                                                         stagingStore, flattened, user, inbox, _user);
                            var handled = await handler.Handle();

                            flattened = handler.MainObject;
                            if (!handled)
                            {
                                break;
                            }
                        }

                        await _context.SaveChangesAsync();

                        transaction.Commit();

                        return(flattened.Data);
                    }
                }
                finally
                {
                    _serverToServerMutex.Release();
                }
            }
Exemplo n.º 9
0
 public UndoHandler(StagingEntityStore entityStore, APEntity mainObject, APEntity actor, APEntity targetBox, ClaimsPrincipal user, CollectionTools collection) : base(entityStore, mainObject, actor, targetBox, user)
 {
     _collection = collection;
 }
Exemplo n.º 10
0
 public DeliveryHandler(StagingEntityStore entityStore, APEntity mainObject, APEntity actor, APEntity targetBox, ClaimsPrincipal user, CollectionTools collection, DeliveryService deliveryService) : base(entityStore, mainObject, actor, targetBox, user)
 {
     _collection      = collection;
     _deliveryService = deliveryService;
 }
Exemplo n.º 11
0
 public CreateActorHandler(StagingEntityStore entityStore, APEntity mainObject, APEntity actor, APEntity targetBox, ClaimsPrincipal user, CollectionTools collection, EntityData entityData, APContext context) : base(entityStore, mainObject, actor, targetBox, user)
 {
     _collection = collection;
     _entityData = entityData;
     _context    = context;
 }
Exemplo n.º 12
0
 public ObjectWrapperHandler(StagingEntityStore entityStore, APEntity mainObject, APEntity actor, APEntity targetBox, ClaimsPrincipal user, EntityData entityData)
     : base(entityStore, mainObject, actor, targetBox, user)
 {
     _entityData = entityData;
 }
Exemplo n.º 13
0
 public VerifyOwnershipHandler(StagingEntityStore entityStore, APEntity mainObject, APEntity actor, APEntity targetBox, ClaimsPrincipal user) : base(entityStore, mainObject, actor, targetBox, user)
 {
 }
Exemplo n.º 14
0
 public FollowResponseHandler(StagingEntityStore entityStore, APEntity mainObject, APEntity actor, APEntity targetBox, ClaimsPrincipal user, CollectionTools collection, RelevantEntitiesService relevantEntities) : base(entityStore, mainObject, actor, targetBox, user)
 {
     _collection       = collection;
     _relevantEntities = relevantEntities;
 }
Exemplo n.º 15
0
 public ActivityMissingFieldsHandler(StagingEntityStore entityStore, APEntity mainObject, APEntity actor, APEntity targetBox, ClaimsPrincipal user) : base(entityStore, mainObject, actor, targetBox, user)
 {
 }
Exemplo n.º 16
0
 public WebSubHandler(StagingEntityStore entityStore, APEntity mainObject, APEntity actor, APEntity targetBox, ClaimsPrincipal user, APContext context) : base(entityStore, mainObject, actor, targetBox, user)
 {
     _context = context;
 }
Exemplo n.º 17
0
 public FollowLikeHandler(StagingEntityStore entityStore, APEntity mainObject, APEntity actor, APEntity targetBox, ClaimsPrincipal user, CollectionTools collection, EntityData data) : base(entityStore, mainObject, actor, targetBox, user)
 {
     _collection = collection;
     _data       = data;
 }
Exemplo n.º 18
0
        public async Task <APEntity> ServerToServer(APEntity inbox, ASObject activity, string subject = null)
        {
            var stagingStore = new StagingEntityStore(_mainStore);
            var userId       = inbox.Data["attributedTo"].Single().Id;
            var user         = await _mainStore.GetEntity(userId, false);

            APEntity flattened;

            string prefix = "";

            if (subject != null)
            {
                var subjectUri = new Uri(subject);
                prefix = $"{subjectUri.Scheme}://{subjectUri.Host}";
                if (!subjectUri.IsDefaultPort)
                {
                    prefix += $":{subjectUri.Port}";
                }
                prefix += "/";
            }

            var id = activity.Id;

            flattened = await _mainStore.GetEntity(id, false);

            if (flattened == null)
            {
                flattened = await _flattener.FlattenAndStore(stagingStore, activity, false);
            }

            await stagingStore.TrimDown(prefix);     // remove all staging entities that may be faked

            var sentBy = activity["actor"].First().Id;

            if (subject != null && sentBy != subject)
            {
                throw new UnauthorizedAccessException("Invalid authorization header for this subject!");
            }

            if (user.Data["blocks"].Any())
            {
                var blocks = await _mainStore.GetEntity(user.Data["blocks"].First().Id, false);

                var blocked = await _mainStore.GetEntity(blocks.Data["blocked"].First().Id, false);

                if (await _collectionTools.Contains(blocked, sentBy))
                {
                    throw new UnauthorizedAccessException("You are blocked.");
                }
            }

            if (await _collectionTools.Contains(inbox, id))
            {
                return(flattened);
            }

            await stagingStore.CommitChanges();

            foreach (var type in ServerConfig.ServerToServerHandlers)
            {
                var handler = (BaseHandler)ActivatorUtilities.CreateInstance(_serviceProvider, type,
                                                                             _mainStore, flattened, user, inbox, _user);
                var handled = await handler.Handle();

                flattened = handler.MainObject;
                if (!handled)
                {
                    break;
                }
            }

            return(flattened);
        }
Exemplo n.º 19
0
 public LikeFollowAnnounceHandler(StagingEntityStore entityStore, APEntity mainObject, APEntity actor, APEntity targetBox, ClaimsPrincipal user, CollectionTools collection, EntityData data, RelevantEntitiesService relevantEntities, IServiceProvider serviceProvider) : base(entityStore, mainObject, actor, targetBox, user)
 {
     _collection = collection;
     _data       = data;
 }
Exemplo n.º 20
0
 public UpdateDeleteActivityHandler(StagingEntityStore entityStore, APEntity mainObject, APEntity actor, APEntity targetBox, ClaimsPrincipal user, ActivityService activityService) : base(entityStore, mainObject, actor, targetBox, user)
 {
     _activityService = activityService;
 }
Exemplo n.º 21
0
 public AcceptRejectFollowHandler(StagingEntityStore entityStore, APEntity mainObject, APEntity actor, APEntity targetBox, ClaimsPrincipal user, EntityData data, CollectionTools collection) : base(entityStore, mainObject, actor, targetBox, user)
 {
     _data       = data;
     _collection = collection;
 }