Example #1
0
        // Generating encoded app request using appname, appid, vendor
        public static async Task <(uint, string)> GenerateEncodedAppRequestAsync()
        {
            Console.WriteLine("\nGenerating application authentication request");
            var authReq = new AuthReq
            {
                AppContainer = true,
                App          = new AppExchangeInfo {
                    Id = ConsoleAppConstants.AppId, Scope = string.Empty, Name = ConsoleAppConstants.AppName, Vendor = ConsoleAppConstants.Vendor
                },
                Containers = new List <ContainerPermissions> {
                    new ContainerPermissions {
                        ContName = "_publicNames", Access = { Insert = true }
                    }
                }
            };

            return(await Session.EncodeAuthReqAsync(authReq));
        }
Example #2
0
        public async Task <ActionResult> Auth(AuthReq req)
        {
            Client.DefaultRequestHeaders.Clear();
            Client.DefaultRequestHeaders.Add("SystemCode", req.SystemCode);
            var result = await Client.RequestPasswordTokenAsync(new PasswordTokenRequest
            {
                Address      = "http://localhost:32354/connect/token",
                ClientId     = "Api",
                ClientSecret = "6CD30DB681204AFA85CEFF8F157FE28E",
                UserName     = req.Name,
                Password     = req.Password,
                Scope        = "Api offline_access"
            }, CancellationToken.None);

            SaveTokenToRedis($"{req.SystemCode}-{req.Name}", result);

            return(Json(new JwtToken(result.AccessToken, result.RefreshToken)));
        }
Example #3
0
        public override async Task <LevelPoints> HandleRequest(
            AuthReq <CardGameInfos, LevelPoints> request,
            CancellationToken cancellationToken = default)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var userId = request.UserId;
            var info   = request.Value.Info;

            // add level
            var list   = info.Select(d => d.WordIdOpenCount.Select(d => d.Key).ToArray()).ToList();
            var levels = await Context.CreateLevels(userId, list).ConfigureAwait(false);

            return(await CalculateMetrics(userId, info, levels, cancellationToken).ConfigureAwait(false));
        }
        // Generating encoded app request using app name, appid, vendor
        public static async Task <(uint, string)> GenerateEncodedAppRequestAsync()
        {
            Logger.Info("Generating application authentication request");
            var authReq = new AuthReq
            {
                AppContainer = true,
                App          = new AppExchangeInfo
                {
                    Id     = Constants.AppId,
                    Scope  = string.Empty,
                    Name   = Constants.AppName,
                    Vendor = Constants.Vendor
                },
                Containers = new List <ContainerPermissions>()
            };

            return(await Session.EncodeAuthReqAsync(authReq));
        }
Example #5
0
        public static async Task <(uint, string)> GenerateEncodedAppRequestAsync(string appId)
        {
            Console.WriteLine("Generating application authentication request");
            var authReq = new AuthReq
            {
                AppContainer = true,
                App          = new AppExchangeInfo {
                    Id = appId, Scope = "", Name = "SAFE Console", Vendor = "MaidSafe.net Ltd"
                },
                Containers = new List <ContainerPermissions> {
                    new ContainerPermissions {
                        ContName = "_publicNames", Access = { Insert = true }
                    }
                }
            };

            return(await Session.EncodeAuthReqAsync(authReq));
        }
Example #6
0
        public static async Task <(uint, string)> GenerateEncodedAuthReqAsync()
        {
            // Create an AuthReq
            var authReq = new AuthReq
            {
                AppContainer = true,
                App          = new AppExchangeInfo
                {
                    Id     = Constants.AppId,
                    Scope  = string.Empty,
                    Name   = Constants.AppName,
                    Vendor = Constants.Vendor
                },
                Containers = new List <ContainerPermissions>()
            };

            // Return encoded AuthReq
            return(await Session.EncodeAuthReqAsync(authReq));
        }
Example #7
0
        private async Task CreateDemoTodoApp()
        {
            AuthReq authReq = new AuthReq
            {
                AppContainer = true,
                App          = new AppExchangeInfo {
                    Id = AppId, Scope = string.Empty, Name = AppName, Vendor = "MaidSafe.net Ltd"
                },
                Containers = new List <ContainerPermissions> {
                    new ContainerPermissions {
                        ContName = "_publicNames", Access = { Insert = true, Update = true, Delete = true }
                    }
                }
            };

            Debug.WriteLine($"Create Test App: {AppName} - {AppId}");
            _session = await CreateTestAppAsync(authReq);

            Debug.WriteLine($"App Created Successfully");
        }
Example #8
0
        public async Task GetWordsAsync()
        {
            // arrange
            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            await CreateTestContext(context);

            WordSetWordsRequest requestData = new WordSetWordsRequest()
            {
                WordSetId = context.Games.First().GameId
            };
            var request = new AuthReq <WordSetWordsRequest, WordSetWordsReply>(requestData)
            {
                UserId = context.Users.First().UserId
            };

            // act
            var reply = await new GetMarkedWordsHandler(context).Handle(request);

            // assert
            Assert.Equal(2, reply.Words.Count);
        }
Example #9
0
        public override Task <GetLevelsReply> HandleRequest(
            AuthReq <GetLevelsRequest, GetLevelsReply> request,
            CancellationToken cancellationToken = default)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var            requestData    = request.Value;
            int            userId         = request.UserId;
            GetLevelsReply getLevelsReply = new GetLevelsReply();
            // select levels
            var levelsOfGame = Context.GameLevels.Where(l => l.GameId.Equals(requestData.WordSetId));

            // join users score
            var starredLevels = Context.GetStarredLevels(levelsOfGame, request.UserId);

            getLevelsReply.Levels.AddRange(starredLevels);
            return(Task.Run(() => { return getLevelsReply; }));
        }
Example #10
0
        public async void Find_Existed_Account()
        {
            // arrange
            int userId = 1;

            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            await context.AddAccount(userId);

            await context.SaveChangesAsync();

            var request = new AuthReq <Empty, ProfileReply>(new Empty())
            {
                UserId = userId,
            };

            var handler = new GetCurrentProfile(context);
            var result  = await handler.Handle(request);

            // assert
            Assert.Equal(userId, result.UserId);
        }
Example #11
0
        public override Task <ProfileReply> HandleRequest(
            AuthReq <Empty, ProfileReply> request,
            CancellationToken cancellationToken = default)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var userId     = request.UserId;
            var publicInfo = Context.GetProfile(u => u.UserId == userId).SingleOrDefault();

            if (publicInfo == null)
            {
                request.StatusCode = StatusCode.NotFound;
                request.Detail     = Strings.GetDetailMessage(Locale.RuRu, DetailMessage.UserIdNotFound);
                return(Task.Run(() => new ProfileReply()));
            }

            return(Task.Run(() => publicInfo));
        }
Example #12
0
        public override async Task <AddWordsReply> HandleRequest(AuthReq <UpdateWordsRequest, AddWordsReply> request,
                                                                 CancellationToken cancellationToken = default)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var userId      = request.UserId;
            var requestData = request.Value;

            DeleteWordsRequest deleteRequestData = new DeleteWordsRequest();

            deleteRequestData.Delete.AddRange(requestData.Update.Select(d => d.Delete));

            AddWordsRequest addRequestData = new AddWordsRequest();

            addRequestData.Words.AddRange(requestData.Update.Select(d => new AddWordRequest()
            {
                LocalId     = d.LocalId,
                WordForeign = d.WordForeign,
                WordNative  = d.WordNative
            }));

            var addWordsRequest = new AuthReq <AddWordsRequest, AddWordsReply>(addRequestData)
            {
                UserId = userId
            };

            var deleteRequest = new AuthReq <DeleteWordsRequest, Empty>(deleteRequestData)
            {
                UserId = userId
            };

            var addTask = await addWords.Handle(addWordsRequest, cancellationToken).ConfigureAwait(false);

            var deleteTask = await deleteWords.Handle(deleteRequest, cancellationToken).ConfigureAwait(false);

            return(addTask);
        }
Example #13
0
        void auth()
        {
            AuthReq auth_req = new AuthReq();

            auth_req.accessKey = accessKey;
            auth_req.subId     = sub_id;
            auth_req.sign      = Encryptor.GetHashSha256(accessKey, sub_id, accessSecret);
            auth_req.subType   = subType;

            TransferPkg pkg = build_TransferPkg((int)CmdId.AuthReq, ProtoBufEncoder.SerializeToBytes(auth_req));

            TransferPkg auth_res = send_and_recv(pkg);

            if (auth_res == null)
            {
                _logger.Error("Authentication failed, received unexpected response, needed AuthRsp, received nothing.");
                reconnect();
                return;
            }
            //check if auth is successful
            if (auth_res.cmdId == (int)CmdId.AuthRsp)
            {
                AuthRsp rsp = ProtoBufDecoder.DeserializeToObj <AuthRsp>(auth_res.data);
                if (rsp.ack == 0)
                {
                    _logger.Info("Authenticated successfully.");
                    //subscribe
                    sub();
                }
                else
                {
                    throw new Exception("Authentication failed, auth info:" + auth_req.ToString());
                }
            }
            else
            {
                _logger.Error("Authentication failed, received unexpected response, needed AuthRsp, received:" + auth_res.cmdId);
            }
        }
Example #14
0
        public static Task <Session> CreateTestApp()
        {
            var locator = GetRandomString(10);
            var secret  = GetRandomString(10);
            var authReq = new AuthReq
            {
                App = new AppExchangeInfo
                {
                    Id     = GetRandomString(10),
                    Name   = GetRandomString(5),
                    Scope  = null,
                    Vendor = GetRandomString(5)
                },
                AppContainer = true,
                AppPermissionTransferCoins    = true,
                AppPermissionGetBalance       = true,
                AppPermissionPerformMutations = true,
                Containers = new List <ContainerPermissions>()
            };

            return(CreateTestApp(locator, secret, authReq));
        }
Example #15
0
        public async void TrainingIds_Empty()
        {
            int userId  = 1;
            int otherId = 2;

            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            await context.AddAccount(userId);

            await context.AddAccount(otherId);

            await context.SaveChangesAsync();

            var requestObject = new AuthReq <Empty, TrainingIdsReply>(new Empty())
            {
                UserId = userId
            };

            var addWords = new GetTrainingIds(context);
            TrainingIdsReply response = await addWords.HandleRequest(requestObject).ConfigureAwait(false);

            Assert.Empty(response.UserWordPairs);
        }
Example #16
0
        public async void ConfirmValidCode()
        {
            // arrange
            int    userId    = 1;
            int    rightCode = 111111;
            string newEmail  = "*****@*****.**";

            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            await context.AddAccount(userId);

            context.EmailVerifies.Add(new EmailVerifies()
            {
                UserId = userId,
                Code   = rightCode,
                Email  = newEmail
            });
            await context.SaveChangesAsync();

            Account account = context.Accounts.First();

            // act
            var requestObject =
                new AuthReq <ConfirmEmailRequest, ConfirmEmailReply>(
                    new ConfirmEmailRequest()
            {
                Email = newEmail, Code = rightCode
            })
            {
                UserId = account.AccountId
            };

            var registration = new ConfirmEmail(context);
            var test         = await registration.HandleRequest(requestObject).ConfigureAwait(false);

            // assert
            Assert.Equal(0, context.EmailVerifies.Count());
            Assert.Equal(newEmail, test.Email);
            Assert.Equal(newEmail, context.Accounts.First().Email);
        }
Example #17
0
        public async void CustomGames_SaveOnce()
        {
            int userId = 1;

            using InWordsDataContext context = InWordsDataContextFactory.Create();
            await context.AddAccount(userId);

            await context.SaveChangesAsync();

            EstimateTraining handler = new EstimateTraining(context);

            var payload = new TrainingDataRequest();

            var training = new Training
            {
                AudioMetric             = new AudioMetric(),
                ClosedAudioCards2Metric = new ClosedAudioCardsTwoMetric()
            };

            training.AudioMetric.WordIdOpenCount.Add(1, 1);
            training.AudioMetric.WordIdOpenCount.Add(2, 1);
            training.AudioMetric.WordIdOpenCount.Add(3, 1);
            training.ClosedAudioCards2Metric.WordIdOpenCount.Add(1, 1);
            training.ClosedAudioCards2Metric.WordIdOpenCount.Add(2, 1);
            training.ClosedAudioCards2Metric.WordIdOpenCount.Add(3, 1);
            payload.Metrics.Add(training);

            var request = new AuthReq <TrainingDataRequest, TrainingScoreReply>(payload);

            var result = await handler.HandleRequest(request);

            Assert.Single(context.Games);
            Assert.Single(context.GameTags);
            Assert.Equal(GameTags.CustomLevelsHistory, context.GameTags.First().Tags);
            Assert.Single(context.GameLevels);
            Assert.Single(context.Historylevels);
            Assert.Empty(context.GameLevelWords); // Because words 1,2,3 is not not found
        }
Example #18
0
        /// <summary>
        /// Delete account by id if exist
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <exception cref="ArgumentNullException">Account not found</exception>
        /// <returns></returns>
        public override async Task <Empty> HandleRequest(
            AuthReq <DeleteAccountRequest, Empty> request,
            CancellationToken cancellationToken = default)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var     accountId = request.UserId;
            Account account   = await Context.Accounts.FindAsync(accountId).ConfigureAwait(false);

            if (account == default)
            {
                request.StatusCode = StatusCode.NotFound;
            }
            else
            {
                Context.Remove(account);
                await Context.SaveChangesAsync().ConfigureAwait(false);
            }
            return(new Empty());
        }
Example #19
0
        public async void AddUserWordPair()
        {
            // arrange
            int userId  = 1;
            int otherId = 2;

            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            await context.AddAccount(userId);

            await context.AddAccount(otherId);

            await context.SaveChangesAsync();

            AddWordsRequest addWordsRequest = new AddWordsRequest();

            addWordsRequest.Words.Add(new AddWordRequest()
            {
                LocalId = 0, WordForeign = "0", WordNative = "0-0"
            });
            addWordsRequest.Words.Add(new AddWordRequest()
            {
                LocalId = 2, WordForeign = "2", WordNative = "2-2"
            });

            // act
            var requestObject = new AuthReq <AddWordsRequest, AddWordsReply>(addWordsRequest)
            {
                UserId = userId
            };

            var           addWords = new AddWords(context);
            AddWordsReply response = await addWords.HandleRequest(requestObject).ConfigureAwait(false);

            // assert
            Assert.Equal(2, context.UserWordPairs.Count());
            Assert.Equal(2, response.WordIds.Where(d => d.ServerId > 0).Count());
        }
Example #20
0
        public async void ConfirmInValidCode()
        {
            // arrange
            int    userId    = 1;
            int    rightCode = 111111;
            int    badCode   = 222222;
            string newEmail  = "*****@*****.**";

            await using InWordsDataContext context = InWordsDataContextFactory.Create();
            await context.AddAccount(userId);

            context.EmailVerifies.Add(new EmailVerifies()
            {
                UserId = userId,
                Code   = rightCode,
                Email  = newEmail
            });
            await context.SaveChangesAsync();

            Account account = context.Accounts.First();

            // act
            var requestObject =
                new AuthReq <ConfirmEmailRequest, ConfirmEmailReply>(
                    new ConfirmEmailRequest()
            {
                Email = newEmail, Code = badCode
            })
            {
                UserId = account.AccountId
            };

            // assert
            var registration = new ConfirmEmail(context);
            await Assert.ThrowsAsync <ArgumentNullException>(() => registration.HandleRequest(requestObject));
        }
Example #21
0
        public override async Task <TrainingIdsReply> HandleRequest(AuthReq <Empty, TrainingIdsReply> request,
                                                                    CancellationToken cancellationToken = default)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var userId       = request.UserId;
            var value        = request.Value;
            var inRangeWords = await Context.UserWordPairs.TrainingWords(userId)
                               .Select(d => d.UserWordPairId)
                               .ToArrayAsync()
                               .ConfigureAwait(false);

            TrainingIdsReply trainingIdsReply = new TrainingIdsReply();

            if (inRangeWords != null)
            {
                trainingIdsReply.UserWordPairs.AddRange(inRangeWords);
            }

            return(trainingIdsReply);
        }
Example #22
0
        private Task <LevelPoints> CalculateMetrics(int userId,
                                                    RepeatedField <CardGameInfos.Types.CardGameInfo> info,
                                                    int[] levels,
                                                    CancellationToken cancellationToken)
        {
            CardGameMetrics cardGameMetrics = new CardGameMetrics();

            for (int i = 0; i < levels.Length; i++)
            {
                var cardGameMetric = new CardGameMetric()
                {
                    GameLevelId = levels[i]
                };
                cardGameMetric.WordIdOpenCount.Add(info[i].WordIdOpenCount);
                cardGameMetrics.Metrics.Add(cardGameMetric);
            }

            var estimateRequest = new AuthReq <CardGameMetrics, LevelPoints>(cardGameMetrics)
            {
                UserId = userId
            };

            return(estimateClassicCardGame.Handle(estimateRequest, cancellationToken));
        }
Example #23
0
        public async Task ShareMDataAuthTest()
        {
            var locator = Utils.GetRandomString(10);
            var secret  = Utils.GetRandomString(20);
            var typeTag = 150001;
            var authReq = new AuthReq {
                App = new AppExchangeInfo {
                    Id = "net.maidsafe.test", Name = "TestApp", Scope = null, Vendor = "MaidSafe.net Ltd."
                },
                AppContainer = true,
                Containers   = new List <ContainerPermissions>()
            };
            var session = await Utils.CreateTestApp(locator, secret, authReq);

            var mdInfo = await session.MDataInfoActions.RandomPrivateAsync((ulong)typeTag);

            var actKey   = Utils.GetRandomData(10).ToList();
            var actValue = Utils.GetRandomData(10).ToList();

            using (var userSignKeyHandle = await session.Crypto.AppPubSignKeyAsync())
                using (var permissionsHandle = await session.MDataPermissions.NewAsync()) {
                    var permissionSet = new PermissionSet {
                        Read = true, Insert = true, Delete = false, Update = false, ManagePermissions = false
                    };
                    await session.MDataPermissions.InsertAsync(permissionsHandle, userSignKeyHandle, permissionSet);

                    using (var entriesHandle = await session.MDataEntries.NewAsync()) {
                        var key = await session.MDataInfoActions.EncryptEntryKeyAsync(mdInfo, actKey);

                        var value = await session.MDataInfoActions.EncryptEntryKeyAsync(mdInfo, actValue);

                        await session.MDataEntries.InsertAsync(entriesHandle, key, value);

                        await session.MData.PutAsync(mdInfo, permissionsHandle, entriesHandle);
                    }
                }

            session.Dispose();
            authReq.App = new AppExchangeInfo {
                Id = "net.maidsafe.test.app", Name = "Test App", Scope = null, Vendor = "MaidSafe.net Ltd."
            };
            var msg = await Session.EncodeAuthReqAsync(authReq);

            var authResponse = await Utils.AuthenticateAuthRequest(locator, secret, msg.Item2, true);

            var authGranted = await Session.DecodeIpcMessageAsync(authResponse) as AuthIpcMsg;

            Assert.That(authGranted, Is.Not.Null);
            session = await Session.AppRegisteredAsync(authReq.App.Id, authGranted.AuthGranted);

            var shareMdReq = new ShareMDataReq {
                App   = authReq.App,
                MData = new List <ShareMData> {
                    new ShareMData {
                        Name = mdInfo.Name, TypeTag = mdInfo.TypeTag, Perms = new PermissionSet {
                            Read = true, Insert = true
                        }
                    }
                }
            };
            var ipcMsg = await Session.EncodeShareMDataRequestAsync(shareMdReq);

            var response = await Utils.AuthenticateShareMDataRequest(locator, secret, ipcMsg.Item2, true);

            var responseMsg = await Session.DecodeIpcMessageAsync(response) as ShareMDataIpcMsg;

            Assert.That(responseMsg, Is.Not.Null);
            Assert.That(ipcMsg.Item1, Is.EqualTo(responseMsg.ReqId));
            var keys = await session.MData.ListKeysAsync(mdInfo);

            Assert.That(keys.Count, Is.EqualTo(1));
            session.Dispose();
        }
Example #24
0
        public async Task ConnectAsRegisteredAppTest()
        {
            var authReq = new AuthReq {
                App = new AppExchangeInfo {
                    Id = "net.maidsafe.test", Name = "TestApp", Scope = null, Vendor = "MaidSafe.net Ltd."
                },
                AppContainer = true,
                Containers   = new List <ContainerPermissions>()
            };

            using (var session = await Utils.CreateTestApp(authReq)) {
                using (await session.Crypto.AppPubSignKeyAsync()) { }
            }

            authReq.AppContainer = false;
            using (var session = await Utils.CreateTestApp(authReq)) {
                using (await session.Crypto.AppPubSignKeyAsync()) { }
            }

            authReq.Containers = null;
            using (var session = await Utils.CreateTestApp(authReq)) {
                using (await session.Crypto.AppPubSignKeyAsync()) { }
            }

            authReq.Containers = new List <ContainerPermissions> {
                new ContainerPermissions {
                    ContName = "_public", Access = new PermissionSet {
                        Read = true
                    }
                },
                new ContainerPermissions {
                    ContName = "_videos",
                    Access   = new PermissionSet {
                        Read = true, Insert = true, Delete = false, ManagePermissions = false, Update = false
                    }
                },
                new ContainerPermissions {
                    ContName = "_publicNames",
                    Access   = new PermissionSet {
                        Read = true, Insert = true, Delete = false, ManagePermissions = false, Update = false
                    }
                },
                new ContainerPermissions {
                    ContName = "_documents",
                    Access   = new PermissionSet {
                        Read = true, Insert = true, Delete = false, ManagePermissions = false, Update = false
                    }
                },
                new ContainerPermissions {
                    ContName = "_music",
                    Access   = new PermissionSet {
                        Read = true, Insert = true, Delete = false, ManagePermissions = false, Update = false
                    }
                }
                // TODO - Enable once fixed in authenticator
//        new ContainerPermissions()
//        {
//          ContName = "_pictures",
//          Access = new PermissionSet() { Read = true, Insert = true, Delete = false, ManagePermissions = false, Update = false }
//        }
            };

            using (var session = await Utils.CreateTestApp(authReq)) {
                using (await session.Crypto.AppPubSignKeyAsync()) { }
            }

            var authRequest = await Session.EncodeAuthReqAsync(authReq);

            var response = await Utils.AuthenticateAuthRequest(authRequest.Item2, false);

            Assert.That(async() => await Session.DecodeIpcMessageAsync(response), Throws.TypeOf <IpcMsgException>());

            authReq.Containers =
                new List <ContainerPermissions> {
                new ContainerPermissions {
                    ContName = "someConatiner", Access = new PermissionSet()
                }
            };

            Assert.That(async() => await Utils.CreateTestApp(authReq), Throws.TypeOf <FfiException>());
            authReq.App = new AppExchangeInfo {
                Id = "", Name = "", Scope = "", Vendor = ""
            };
            Assert.That(async() => await Utils.CreateTestApp(authReq), Throws.TypeOf <FfiException>());
            authReq.App = new AppExchangeInfo();
            Assert.That(async() => await Utils.CreateTestApp(authReq), Throws.TypeOf <FfiException>());
        }
Example #25
0
 /// <summary>
 /// Initialise Authentication IPC request.
 /// </summary>
 /// <param name="reqId">Request Id.</param>
 /// <param name="authReq">Authentication request.</param>
 public AuthIpcReq(uint reqId, AuthReq authReq)
 {
     ReqId   = reqId;
     AuthReq = authReq;
 }
Example #26
0
        public async Task AppConatinerTest()
        {
            var authReq = new AuthReq
            {
                App = new AppExchangeInfo
                {
                    Id = Utils.GetRandomString(10), Name = Utils.GetRandomString(10), Vendor = Utils.GetRandomString(10)
                },
                AppContainer = true,
                Containers   = new List <ContainerPermissions>()
            };
            var session = await Utils.CreateTestApp(authReq);

            var mDataInfo = await session.AccessContainer.GetMDataInfoAsync("apps/" + authReq.App.Id);

            var perms = await session.MData.ListUserPermissionsAsync(mDataInfo, await session.Crypto.AppPubSignKeyAsync());

            Assert.IsTrue(perms.Insert);
            Assert.IsTrue(perms.Update);
            Assert.IsTrue(perms.Delete);
            Assert.IsTrue(perms.Read);
            Assert.IsTrue(perms.ManagePermissions);
            var keys = await session.MData.ListKeysAsync(mDataInfo);

            Assert.AreEqual(0, keys.Count);
            using (var entriesActionHandle = await session.MDataEntryActions.NewAsync())
            {
                var encKey = await session.MDataInfoActions.EncryptEntryKeyAsync(mDataInfo, Utils.GetRandomData(15).ToList());

                var encVal = await session.MDataInfoActions.EncryptEntryKeyAsync(mDataInfo, Utils.GetRandomData(25).ToList());

                await session.MDataEntryActions.InsertAsync(entriesActionHandle, encKey, encVal);

                await session.MData.MutateEntriesAsync(mDataInfo, entriesActionHandle);
            }

            using (var entriesActionHandle = await session.MDataEntryActions.NewAsync())
                using (var entryHandle = await session.MDataEntries.GetHandleAsync(mDataInfo))
                {
                    keys = await session.MData.ListKeysAsync(mDataInfo);

                    var value = await session.MDataEntries.GetAsync(entryHandle, keys[0].Key);

                    await session.MDataEntryActions.UpdateAsync(
                        entriesActionHandle,
                        keys[0].Key,
                        Utils.GetRandomData(10).ToList(),
                        value.Item2 + 1);

                    await session.MData.MutateEntriesAsync(mDataInfo, entriesActionHandle);
                }

            using (var entriesActionHandle = await session.MDataEntryActions.NewAsync())
                using (var entryHandle = await session.MDataEntries.GetHandleAsync(mDataInfo))
                {
                    keys = await session.MData.ListKeysAsync(mDataInfo);

                    var value = await session.MDataEntries.GetAsync(entryHandle, keys[0].Key);

                    await session.MDataEntryActions.DeleteAsync(entriesActionHandle, keys[0].Key, value.Item2 + 1);

                    await session.MData.MutateEntriesAsync(mDataInfo, entriesActionHandle);
                }
        }
Example #27
0
 /// <summary>
 /// Encodes an authentication request.
 /// </summary>
 /// <param name="authReq">Authentication Request.</param>
 /// <returns>RequestId, Encoded authentication request.</returns>
 public static Task <(uint, string)> EncodeAuthReqAsync(AuthReq authReq)
 {
     return(AppBindings.EncodeAuthReqAsync(ref authReq));
 }
Example #28
0
        public static async Task <Session> CreateTestApp(string locator, string secret, AuthReq authReq)
        {
            var authenticator = await Authenticator.CreateAccountAsync(locator, secret, GetRandomString(5));

            var(_, reqMsg) = await Session.EncodeAuthReqAsync(authReq);

            var ipcReq = await authenticator.DecodeIpcMessageAsync(reqMsg);

            Assert.That(ipcReq, Is.TypeOf <AuthIpcReq>());
            var authIpcReq = ipcReq as AuthIpcReq;
            var resMsg     = await authenticator.EncodeAuthRespAsync(authIpcReq, true);

            var ipcResponse = await Session.DecodeIpcMessageAsync(resMsg);

            Assert.That(ipcResponse, Is.TypeOf <AuthIpcMsg>());
            var authResponse = ipcResponse as AuthIpcMsg;

            Assert.That(authResponse, Is.Not.Null);
            authenticator.Dispose();
            return(await Session.AppRegisteredAsync(authReq.App.Id, authResponse.AuthGranted));
        }
Example #29
0
        public async Task SharedMutableData()
        {
            var locator = Utils.GetRandomString(10);
            var secret  = Utils.GetRandomString(10);
            var authReq = new AuthReq
            {
                App = new AppExchangeInfo {
                    Id = "net.maidsafe.sample", Name = "Inbox", Scope = null, Vendor = "MaidSafe.net Ltd"
                },
                Containers = new List <ContainerPermissions>()
            };
            var session = await Utils.CreateTestApp(locator, secret, authReq);

            var typeTag   = 16000;
            var mDataInfo = await session.MDataInfoActions.RandomPrivateAsync((ulong)typeTag);

            using (var permissionsH = await session.MDataPermissions.NewAsync())
            {
                using (var appSignKeyH = await session.Crypto.AppPubSignKeyAsync())
                {
                    var ownerPermission = new PermissionSet {
                        Insert = true, ManagePermissions = true, Read = true
                    };
                    await session.MDataPermissions.InsertAsync(permissionsH, appSignKeyH, ownerPermission);

                    var sharePermissions = new PermissionSet {
                        Insert = true
                    };
                    await session.MDataPermissions.InsertAsync(permissionsH, NativeHandle.EmptyMDataPermissions, sharePermissions);

                    await session.MData.PutAsync(mDataInfo, permissionsH, NativeHandle.EmptyMDataEntries);
                }
            }

            using (var entriesHandle = await session.MDataEntryActions.NewAsync())
            {
                var key = await session.MDataInfoActions.EncryptEntryKeyAsync(mDataInfo, Utils.GetRandomData(10).ToList());

                var value = await session.MDataInfoActions.EncryptEntryValueAsync(mDataInfo, Utils.GetRandomData(10).ToList());

                await session.MDataEntryActions.InsertAsync(entriesHandle, key, value);

                await session.MData.MutateEntriesAsync(mDataInfo, entriesHandle);
            }

            using (var entriesHandle = await session.MDataEntries.GetHandleAsync(mDataInfo))
            {
                var keys = await session.MData.ListKeysAsync(mDataInfo);

                foreach (var key in keys)
                {
                    var encKey = await session.MDataEntries.GetAsync(entriesHandle, key.Key);

                    await session.MDataInfoActions.DecryptAsync(mDataInfo, encKey.Item1);
                }
            }

            session.Dispose();

            authReq = new AuthReq
            {
                App = new AppExchangeInfo {
                    Id = "net.maidsafe.share.md", Name = "Share Chat", Vendor = "MaidSafe.net Ltd"
                },
                AppContainer = false,
                Containers   = new List <ContainerPermissions>()
            };
            var session2 = await Utils.CreateTestApp(authReq);

            using (var entriesHandle = await session2.MDataEntryActions.NewAsync())
            {
                var key = await session2.MDataInfoActions.EncryptEntryKeyAsync(mDataInfo, Utils.GetRandomData(10).ToList());

                var value = await session2.MDataInfoActions.EncryptEntryValueAsync(mDataInfo, Utils.GetRandomData(10).ToList());

                await session2.MDataEntryActions.InsertAsync(entriesHandle, key, value);

                await session2.MData.MutateEntriesAsync(mDataInfo, entriesHandle);
            }

            using (var entriesHandle = await session2.MDataEntries.GetHandleAsync(mDataInfo))
            {
                var entries = await session2.MData.ListEntriesAsync(entriesHandle);

                foreach (var entry in entries)
                {
                    await session2.MDataInfoActions.DecryptAsync(mDataInfo, entry.Key.Key);
                }
            }

            using (var entryAction = await session2.MDataEntryActions.NewAsync())
                using (var entriesHandle = await session2.MDataEntries.GetHandleAsync(mDataInfo))
                {
                    var keys = await session2.MData.ListKeysAsync(mDataInfo);

                    foreach (var key in keys)
                    {
                        var encKey = await session2.MDataEntries.GetAsync(entriesHandle, key.Key);

                        await session2.MDataEntryActions.DeleteAsync(entryAction, key.Key, encKey.Item2);
                    }

                    Assert.That(
                        async() => { await session2.MData.MutateEntriesAsync(mDataInfo, entryAction); },
                        Throws.TypeOf <FfiException>());
                }

            session2.Dispose();
        }
Example #30
0
        public async Task AddRemoveUserPermission()
        {
            var locator = Utils.GetRandomString(10);
            var secret  = Utils.GetRandomString(10);
            var authReq = new AuthReq
            {
                App = new AppExchangeInfo {
                    Id = "net.maidsafe.mdata.permission", Name = "CMS", Vendor = "MaidSafe.net Ltd"
                },
                AppContainer = true,
                Containers   = new List <ContainerPermissions>()
            };
            var cmsApp = await Utils.CreateTestApp(locator, secret, authReq);

            var mDataInfo = await Utils.PreparePublicDirectory(cmsApp);

            authReq.App.Name = "Hosting";
            authReq.App.Id   = "net.maidsafe.mdata.host";
            var ipcMsg = await Session.EncodeAuthReqAsync(authReq);

            var response = await Utils.AuthenticateAuthRequest(locator, secret, ipcMsg.Item2, true);

            var decodedResponse = await Session.DecodeIpcMessageAsync(response) as AuthIpcMsg;

            Assert.NotNull(decodedResponse);
            var hostingApp = await Session.AppRegisteredAsync(authReq.App.Id, decodedResponse.AuthGranted);

            var ipcReq = await Session.EncodeShareMDataRequestAsync(
                new ShareMDataReq
            {
                App   = authReq.App,
                MData = new List <ShareMData>
                {
                    new ShareMData
                    {
                        Name    = mDataInfo.Name,
                        TypeTag = mDataInfo.TypeTag,
                        Perms   = new PermissionSet {
                            Insert = true, Read = true
                        }
                    }
                }
            });

            await Utils.AuthenticateShareMDataRequest(locator, secret, ipcReq.Item2, true);

            await hostingApp.AccessContainer.RefreshAccessInfoAsync();

            using (var entryhandle = await hostingApp.MDataEntryActions.NewAsync())
            {
                await hostingApp.MDataEntryActions.InsertAsync(
                    entryhandle,
                    Encoding.UTF8.GetBytes("default.html").ToList(),
                    Encoding.UTF8.GetBytes("<html><body>Hello Default</body></html>").ToList());

                await hostingApp.MData.MutateEntriesAsync(mDataInfo, entryhandle);
            }

            var version = await cmsApp.MData.GetVersionAsync(mDataInfo);

            using (var permissionHandle = await cmsApp.MData.ListPermissionsAsync(mDataInfo))
            {
                var userPermissions = await cmsApp.MDataPermissions.ListAsync(permissionHandle);

                Assert.That(await cmsApp.MDataPermissions.LenAsync(permissionHandle), Is.EqualTo(userPermissions.Count));
                var userPermissionToDel = userPermissions.Find(userPerm => userPerm.Item2.ManagePermissions == false);
                await cmsApp.MData.DelUserPermissionsAsync(mDataInfo, userPermissionToDel.Item1, version + 1);

                userPermissions.ForEach(perm => perm.Item1.Dispose());
            }

            using (var entryHandle = await hostingApp.MDataEntryActions.NewAsync())
            {
                await hostingApp.MDataEntryActions.InsertAsync(
                    entryHandle,
                    Encoding.UTF8.GetBytes("home.html").ToList(),
                    Encoding.UTF8.GetBytes("<html><body>Hello Home!</body></html>").ToList());

                Assert.That(
                    async() => { await hostingApp.MData.MutateEntriesAsync(mDataInfo, entryHandle); },
                    Throws.TypeOf <FfiException>());
            }

            cmsApp.Dispose();
            hostingApp.Dispose();
        }