public void ApiKey_ExecutionRequestShouldValidateApiKey()
        {
            RegisterDb();
            ServiceProxySystem.Register <ApiKeyRequiredEcho>();
            string        testName         = MethodBase.GetCurrentMethod().Name;
            IUserResolver mockUserResolver = Substitute.For <IUserResolver>();

            mockUserResolver.GetUser(Arg.Any <IHttpContext>()).Returns("testUser");
            LocalApiKeyManager.Default.UserResolver = mockUserResolver;

            IApplicationNameProvider nameProvider = new TestApplicationNameProvider(testName.RandomLetters(6));
            IApiKeyProvider          keyProvider  = new LocalApiKeyProvider();

            ExecutionRequest er = new ExecutionRequest("ApiKeyRequiredEcho", "Send", "json")
            {
                ApiKeyResolver = new ApiKeyResolver(keyProvider, nameProvider),
                Request        = new ServiceProxyTestHelpers.JsonTestRequest()
            };

            string data = ApiParameters.ParametersToJsonParamsObjectString("some random data");

            er.InputString = data;

            ValidationResult result = er.Validate();

            result.Success.IsFalse();
            List <ValidationFailures> failures = new List <ValidationFailures>(result.ValidationFailures);

            failures.Contains(ValidationFailures.InvalidApiKeyToken).IsTrue();
        }
Ejemplo n.º 2
0
        protected void SendCsProxyCode(IRequest request, IResponse response)
        {
            string    appName            = AppConf.AppNameFromUri(request.Url, BamConf.AppConfigs);
            string    defaultBaseAddress = ServiceProxySystem.GetBaseAddress(request.Url);
            string    nameSpace          = request.QueryString["namespace"] ?? "ServiceProxyClients";
            string    contractNameSpace  = "{0}.Contracts"._Format(nameSpace);
            Incubator combined           = new Incubator();

            combined.CopyFrom(CommonServiceProvider);

            if (AppServiceProviders.ContainsKey(appName))
            {
                Incubator appProviders = AppServiceProviders[appName];
                combined.CopyFrom(appProviders, true);
            }

            string[] classNames = request.QueryString["classes"] == null ? combined.ClassNames : request.QueryString["classes"].DelimitSplit(",", ";");

            StringBuilder csharpCode = ServiceProxySystem.GenerateCSharpProxyCode(defaultBaseAddress, classNames, nameSpace, contractNameSpace, combined, Logger, request.UserHostAddress.StartsWith("127.0.0.1"));

            response.Headers.Add("Content-Disposition", "attachment;filename=" + nameSpace + ".cs");
            response.Headers.Add("Content-Type", "text/plain");
            byte[] data = Encoding.UTF8.GetBytes(csharpCode.ToString());
            response.OutputStream.Write(data, 0, data.Length);
        }
        public void ApiKey_ExecutionRequestValidationShouldFailIfBadToken()
        {
            RegisterDb();
            ServiceProxySystem.Register <ApiKeyRequiredEcho>();

            IUserResolver mockUserResolver = Substitute.For <IUserResolver>();

            mockUserResolver.GetUser(Arg.Any <IHttpContext>()).Returns("testUser");
            LocalApiKeyManager.Default.UserResolver = mockUserResolver;

            string methodName = MethodBase.GetCurrentMethod().Name;
            IApplicationNameProvider nameProvider = new TestApplicationNameProvider(methodName.RandomLetters(4));
            IApiKeyProvider          keyProvider  = new LocalApiKeyProvider();

            ExecutionRequest er = new ExecutionRequest("ApiKeyRequiredEcho", "Send", "json")
            {
                ApiKeyResolver = new ApiKeyResolver(keyProvider, nameProvider),
                Request        = new ServiceProxyTestHelpers.JsonTestRequest()
            };
            string data = ApiParameters.ParametersToJsonParamsObjectString("some random data");

            er.InputString = data;
            ApiKeyResolver resolver = new ApiKeyResolver(keyProvider, nameProvider);

            resolver.SetKeyToken(er.Request.Headers, data);

            er.Request.Headers[Headers.KeyToken] = "bad token value";

            ValidationResult result = er.Validate();

            Expect.IsFalse(result.Success, "Validation should have failed");
            List <ValidationFailures> failures = new List <ValidationFailures>(result.ValidationFailures);

            Expect.IsTrue(failures.Contains(ValidationFailures.InvalidApiKeyToken), "ValidationFailure should have been InvalidApiKeyToken");
        }
        public void ApiKey_ExecutionRequestValidationShouldSucceedIfGoodToken()
        {
            Prepare();
            ServiceProxySystem.Register <ApiKeyRequiredEcho>();

            string methodName = MethodBase.GetCurrentMethod().Name;
            IApplicationNameProvider nameProvider = new TestApplicationNameProvider(methodName);
            IApiKeyProvider          keyProvider  = new LocalApiKeyProvider();

            string           className = "ApiKeyRequiredEcho";
            string           method    = "Send";
            string           data      = ApiParameters.ParametersToJsonParamsArray("some random data").ToJson();
            ExecutionRequest er        = new ExecutionRequest(className, method, "json")
            {
                JsonParams     = data,
                ApiKeyResolver = new ApiKeyResolver(keyProvider, nameProvider),
                Request        = new ServiceProxyTestHelpers.FormUrlEncodedTestRequest()
            };

            er.ApiKeyResolver.SetKeyToken(er.Request.Headers, ApiParameters.GetStringToHash(className, method, data));

            ValidationResult result = er.Validate();

            Expect.IsTrue(result.Success);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Build a form to be used as parameters for the specified method
        /// </summary>
        /// <param name="type"></param>
        /// <param name="wrapperTagName"></param>
        /// <param name="methodName"></param>
        /// <param name="defaults"></param>
        /// <param name="registerProxy"></param>
        /// <param name="paramCount"></param>
        /// <returns></returns>
        public TagBuilder MethodForm(Type type, string wrapperTagName, string methodName, Dictionary <string, object> defaults, bool registerProxy, out int paramCount)
        {
            Args.ThrowIfNull(type, "InvocationType");
            if (registerProxy)
            {
                ServiceProxySystem.Register(type);
            }

            MethodInfo method = type.GetMethod(methodName);

            defaults = defaults ?? new Dictionary <string, object>();

            System.Reflection.ParameterInfo[] parameters = method.GetParameters();
            paramCount = parameters.Length;
            TagBuilder form = new TagBuilder(wrapperTagName);

            for (int i = 0; i < parameters.Length; i++)
            {
                System.Reflection.ParameterInfo parameter = parameters[i];
                object defaultValue  = defaults.ContainsKey(parameter.Name) ? defaults[parameter.Name] : null;
                string defaultString = defaultValue == null ? string.Empty : defaultValue.ToString();

                TagBuilder label = new TagBuilder("label")
                                   .Html(string.Format(this.LabelFormat, parameter.Name.PascalSplit(" ")))
                                   .Css(this.LabelCssClass);

                bool addLabel  = this.AddLabels;
                bool addValue  = true;
                bool wasObject = false;
                bool handled   = false;
                TryBuildPrimitiveInput(parameter, defaultValue, ref addValue, ref handled, out TagBuilder toAdd, out Type paramType);

                if (!handled)
                {
                    string legend = GetLegend(paramType);
                    toAdd     = FieldsetFor(paramType, defaultValue, legend);
                    addLabel  = false;
                    addValue  = false;
                    wasObject = true;
                }

                toAdd.DataSet("parameter-name", parameter.Name)
                .DataSetIf(!wasObject, "type", parameter.ParameterType.Name.ToLowerInvariant())
                .ValueIf(!string.IsNullOrEmpty(defaultString) && addValue, defaultString);

                if (addLabel)
                {
                    form.Child(label).BrIf(this.Layout == ParameterLayouts.BreakAfterLabels);
                }

                form.Child(toAdd).BrIf(
                    this.Layout != ParameterLayouts.NoBreaks &&
                    i != parameters.Length - 1 &&
                    !wasObject);
            }

            return(form.DataSet("method", methodName)
                   .FirstChildIf(wrapperTagName.Equals("fieldset"), new TagBuilder("legend")
                                 .Text(GetLegend(method))));
        }
Ejemplo n.º 6
0
        public void TestGetInterfaceMethods()
        {
            string methods    = string.Join(",", typeof(ITestInterface).GetMethods().Select(m => m.Name));
            string spsMethods = string.Join(",", ServiceProxySystem.GetProxiedMethods(typeof(ITestInterface)).Select(m => m.Name));

            OutLine(methods);
            Expect.AreEqual(methods, spsMethods);
        }
        public void WillProxyTest()
        {
            MethodInfo method1 = typeof(TestProxy).GetMethod("MethodExclude");
            MethodInfo method2 = typeof(TestProxy).GetMethod("MethodLocal");

            Expect.IsFalse(ServiceProxySystem.WillProxyMethod(method1));
            Expect.IsFalse(ServiceProxySystem.WillProxyMethod(method2));
        }
Ejemplo n.º 8
0
        public void ShouldSetContext()
        {
            ExecutionRequest execRequest = CreateExecutionRequest("/TakesContextTest/Monkey.json");

            ServiceProxySystem.Register <TakesContextTest>();
            Expect.IsFalse(_setContextCalled.Value);
            execRequest.Execute();
            Expect.IsTrue(_setContextCalled.Value);
        }
Ejemplo n.º 9
0
        protected internal ApiKeyInfo GenerateApiKeyInfo(ApplicationRegistration.Application app)
        {
            ApiKeyInfo info = new ApiKeyInfo();

            info.ApplicationNameProvider = new StaticApplicationNameProvider(app.Name);
            info.ApplicationClientId     = app.Cuid;
            info.ApiKey = ServiceProxySystem.GenerateId();
            return(info);
        }
        public void UnregisteredClassShoudReturnClassNotRegistered()
        {
            ServiceProxySystem.Unregister <TestClass>();
            ExecutionRequest er     = new ExecutionRequest("TestClass", "ShouldWork", "json");
            ValidationResult result = er.Validate();

            Expect.IsFalse(result.Success);
            Expect.IsTrue(result.ValidationFailures.ToList().Contains(ValidationFailures.ClassNotRegistered));
            Message.PrintLine(result.Message);
        }
        public void MethodNotFoundShouldBeReturned()
        {
            ServiceProxySystem.Register <TestClass>();
            ExecutionRequest er     = new ExecutionRequest("TestClass", "MissingMethod", "json");
            ValidationResult result = er.Validate();

            Expect.IsFalse(result.Success);
            Expect.IsTrue(result.ValidationFailures.ToList().Contains(ValidationFailures.MethodNotFound));
            Message.PrintLine(result.Message);
        }
Ejemplo n.º 12
0
        public void MissingMethodShouldReturnMethodNotSpecified()
        {
            ServiceProxySystem.Register <TestClass>();
            ExecutionRequest er     = new ExecutionRequest("TestClass", "", "json");
            ValidationResult result = er.Validate();

            Expect.IsFalse(result.Success);
            Expect.IsTrue(result.ValidationFailures.ToList().Contains(ValidationFailures.MethodNameNotSpecified));
            OutLineFormat(result.Message);
        }
        public void ExecuteShouldSucceed()
        {
            ServiceProxySystem.Register <TestClass>();
            ExecutionRequest er     = new ExecutionRequest("TestClass", "ShouldWork", "json");
            ValidationResult result = er.Validate();

            Expect.IsTrue(result.Success);
            er.Execute();
            Expect.IsTrue(er.Result.Equals("Yay"));
            Message.PrintLine(er.Result.ToString());
        }
Ejemplo n.º 14
0
        protected internal ApiKeyInfo GenerateApiKeyInfo(CoreServices.ApplicationRegistration.Data.Application app)
        {
            ApiKeyInfo info = new ApiKeyInfo
            {
                ApplicationNameProvider = new StaticApplicationNameProvider(app.Name),
                ApplicationClientId     = app.Cuid,
                ApiKey = ServiceProxySystem.GenerateId()
            };

            return(info);
        }
Ejemplo n.º 15
0
 private void SetClientCode()
 {
     if (ServiceSettings.DownloadClient)
     {
         Code = ServiceSettings.DownloadClientCode(ServiceType);
     }
     else
     {
         Code = ServiceProxySystem.GenerateCSharpProxyCode(ServiceSettings.Protocol.ToString(), ServiceSettings.Host, ServiceSettings.Port, ServiceType.Namespace, ServiceType);
     }
 }
Ejemplo n.º 16
0
        public static MvcHtmlString ServiceProxyPartial(this HtmlHelper helper, string viewName, object model)
        {
            Type   type = model.GetType();
            string view = string.Format("{0}/{1}", type.Name, viewName);

            if (!ServiceProxySystem.ServiceProxyPartialExists(type, viewName))
            {
                ServiceProxySystem.WriteServiceProxyPartial(type, viewName);
            }

            return(helper.Partial(view, model));
        }
Ejemplo n.º 17
0
        public static ApiKey AddKey(Application app, IUserResolver userResolver, IHttpContext context, Database database = null)
        {
            ApiKey key = app.ApiKeysByApplicationId.AddNew();

            key.ClientId     = GetClientId(app.Name);
            key.Disabled     = false;
            key.SharedSecret = ServiceProxySystem.GenerateId();
            key.CreatedBy    = userResolver.GetUser(context);
            key.CreatedAt    = new Instant();
            key.Save(database);
            return(key);
        }
        public void ParameterCountMismatchShouldBeReturned()
        {
            ServiceProxySystem.Register <TestClass>();
            ExecutionRequest er = new ExecutionRequest("TestClass", "TestMethod", "json");

            er.Arguments = new object[] { new { }, new { } };
            ValidationResult result = er.Validate();

            Expect.IsFalse(result.Success);
            Expect.IsTrue(result.ValidationFailures.ToList().Contains(ValidationFailures.ParameterCountMismatch));
            Message.PrintLine(result.Message);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Build a fieldset element for the specified method of the specified
        /// class.
        /// </summary>
        /// <param name="helper">The FileExtHelper</param>
        /// <param name="type">The Type whose method will be called</param>
        /// <param name="methodName">The name of the method that will be called</param>
        /// <param name="defaults">A dictionary of default values to fill into the resulting
        /// form keyed by the names of the method parameters</param>
        /// <returns>MvchtmlString</returns>
        public static MvcHtmlString ParamsFor(this HtmlHelper helper,
                                              Type type,
                                              string methodName,
                                              string wrapperTagName = "fieldset",
                                              Dictionary <string, object> defaults = null,
                                              object htmlAttributes = null)
        {
            if (ServiceProxySystem.Incubator[type] == null)
            {
                ServiceProxySystem.Register(type);
            }
            int        ignore = -1;
            TagBuilder form   = GetParamsBuilder(type, methodName, wrapperTagName, defaults, htmlAttributes, out ignore);

            return(MvcHtmlString.Create(form.ToString()));
        }
Ejemplo n.º 20
0
        protected void SendJsProxyScript(IRequest request, IResponse response)
        {
            string appName             = AppConf.AppNameFromUri(request.Url, BamConf.AppConfigs);
            bool   includeLocalMethods = request.UserHostAddress.StartsWith("127.0.0.1");

            StringBuilder script = ServiceProxySystem.GenerateJsProxyScript(CommonServiceProvider, CommonServiceProvider.ClassNames, includeLocalMethods);

            if (AppServiceProviders.ContainsKey(appName))
            {
                Incubator appProviders = AppServiceProviders[appName];
                script.AppendLine(ServiceProxySystem.GenerateJsProxyScript(appProviders, appProviders.ClassNames, includeLocalMethods).ToString());
            }

            response.ContentType = "application/javascript";
            byte[] data = Encoding.UTF8.GetBytes(script.ToString());
            response.OutputStream.Write(data, 0, data.Length);
        }
Ejemplo n.º 21
0
        public ProxySettingsValidation Validate()
        {
            Args.ThrowIfNull(ServiceType, nameof(ServiceType));
            ProxySettingsValidation result = new ProxySettingsValidation();
            List <MethodInfo>       nonOverridableMethods = new List <MethodInfo>();

            ServiceProxySystem.GetProxiedMethods(ServiceType, IncludeLocalMethods)
            .Where(mi => !mi.IsOverridable())
            .Each(new { NonOverridableMethods = nonOverridableMethods }, (ctx, mi) => ctx.NonOverridableMethods.Add(mi));

            string nonVirtualMethodsMessage = $"Non virtual proxied methods were found; proxies cannot be automatically generated for the specified type {ServiceType.Namespace}.{ServiceType.Name} because proxyable methods were not declared virtual and will subsequently not properly delegate to the remote \"{Host}\"";

            nonVirtualMethodsMessage += $"\r\n\t{string.Join("\r\n\t", nonOverridableMethods.Select(m=> m.Name))}\r\n";
            result.Success            = nonOverridableMethods.Count == 0;
            result.Message            = result.Success ? string.Empty : nonVirtualMethodsMessage;
            result.NonVirtualMethods  = nonOverridableMethods.ToArray();
            return(result);
        }
        public void LocalMethodShouldValidateIfLocalClient()
        {
            ServiceProxySystem.Register <TestClass>();
            IRequest request = Substitute.For <IRequest>();

            request.QueryString.Returns(new NameValueCollection());
            request.UserHostAddress.Returns("127.0.0.1:80");
            IResponse    response = Substitute.For <IResponse>();
            IHttpContext context  = Substitute.For <IHttpContext>();

            context.Request.Returns(request);
            context.Response.Returns(response);
            ExecutionRequest er = new ExecutionRequest("TestClass", "LocalMethod", "json")
            {
                Context = context
            };
            ValidationResult result = er.Validate();

            Expect.IsTrue(result.Success);
        }
        public void LocalMethodShouldNotValidateIfNotLoopback()
        {
            ServiceProxySystem.Register <TestClass>();
            IRequest request = Substitute.For <IRequest>();

            request.QueryString.Returns(new NameValueCollection());
            request.UserHostAddress.Returns("192.168.0.80:80");
            IResponse    response = Substitute.For <IResponse>();
            IHttpContext context  = Substitute.For <IHttpContext>();

            context.Request.Returns(request);
            context.Response.Returns(response);
            ExecutionRequest er = new ExecutionRequest("TestClass", "LocalMethod", "json")
            {
                Context = context
            };
            ValidationResult result = er.Validate();

            Expect.IsFalse(result.Success);
            Expect.IsTrue(result.ValidationFailures.ToList().Contains(ValidationFailures.RemoteExecutionNotAllowed));
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Creates a new Confirmation with the Created and
        /// Token properties set
        /// </summary>
        /// <returns></returns>
        public static Account Create(User user, string provider, string providerUserId, bool isConfirmed = false, Database db = null)
        {
            DateTime now    = DateTime.UtcNow;
            Account  result = new Account();

            result.CreationDate   = now;
            result.Provider       = provider;
            result.ProviderUserId = providerUserId;
            result.Comment        = "Account for ({0})::confirmed({1})"._Format(user.UserName, isConfirmed ? "Y" : "N");
            if (isConfirmed)
            {
                result.ConfirmationDate = now;
            }

            result.IsConfirmed = isConfirmed;
            result.UserId      = user.Id;
            result.Token       = ServiceProxySystem.GenerateId();
            result.IsConfirmed = false;
            result.Save(db);
            user.AccountsByUserId.Reload();
            return(result);
        }
Ejemplo n.º 25
0
        public void ResetPasswordShouldBeLoginnable()
        {
            string userName = MethodBase.GetCurrentMethod().Name;
            string email    = "*****@*****.**";

            UserTestTools.SignUp(userName, email);
            User user = User.GetByEmail(email);

            Expect.AreEqual(0, user.PasswordResetsByUserId.Count);

            UserManager userMgr = UserTestTools.CreateTestUserManager("Stickerize");

            userMgr.HttpContext         = A.Fake <IHttpContext>();
            userMgr.HttpContext.Request = new TestRequest();

            string password = ServiceProxySystem.GenerateId();
            ForgotPasswordResponse forgot = userMgr.ForgotPassword(email);
            PasswordResetResponse  reset  = userMgr.ResetPassword(password.Sha1(), (string)forgot.Data);
            LoginResponse          login  = userMgr.Login(user.UserName, password.Sha1());

            Expect.IsTrue(login.Success, "Login failed");
        }
Ejemplo n.º 26
0
        internal static Dictionary <string, List <DocInfo> > FromDocAttributes(Type type)
        {
            Dictionary <string, List <DocInfo> > documentation = new Dictionary <string, List <DocInfo> >();
            List <DocInfo> docInfos = new List <DocInfo>();

            docInfos.Add(new DocInfo(type));
            PropertyInfo[] properties = type.GetProperties();
            properties.Each(p =>
            {
                docInfos.Add(new DocInfo(p));
            });
            MethodInfo[] methods = type.GetMethods();
            methods.Each(m =>
            {
                if (ServiceProxySystem.WillProxyMethod(m))
                {
                    docInfos.Add(new DocInfo(m));
                }
            });

            documentation.Add(type.AssemblyQualifiedName, docInfos);
            return(documentation);
        }
        public void TimeGenerateVsNewGuid()
        {
            string   generatedId;
            TimeSpan generateTime = Exec.Time(() =>
            {
                generatedId = ServiceProxySystem.GenerateSecureRandomString();
            });

            string   guid;
            TimeSpan guidTime = Exec.Time(() =>
            {
                guid = Guid.NewGuid().ToString();
            });

            string   sha256;
            TimeSpan guidTimeSha256 = Exec.Time(() =>
            {
                sha256 = Guid.NewGuid().ToString().Sha256();
            });

            Message.PrintLine("Generate took: {0}", generateTime.ToString());
            Message.PrintLine("-NewGuid took: {0}", guidTime.ToString());
            Message.PrintLine("HashGuid took: {0}", guidTimeSha256.ToString());
        }
Ejemplo n.º 28
0
        public void TimeGenerateVsNewGuid()
        {
            string   generatedId;
            TimeSpan generateTime = Exec.Time(() =>
            {
                generatedId = ServiceProxySystem.GenerateId();
            });

            string   guid;
            TimeSpan guidTime = Exec.Time(() =>
            {
                guid = Guid.NewGuid().ToString();
            });

            string   sha256;
            TimeSpan guidTimeSha256 = Exec.Time(() =>
            {
                sha256 = Guid.NewGuid().ToString().Sha256();
            });

            OutLineFormat("Generate took: {0}", generateTime.ToString());
            OutLineFormat("-NewGuid took: {0}", guidTime.ToString());
            OutLineFormat("HashGuid took: {0}", guidTimeSha256.ToString());
        }
Ejemplo n.º 29
0
        public void ApiKey_ExecutionRequestShouldValidateApiKey()
        {
            RegisterDb();
            ServiceProxySystem.Register <ApiKeyRequiredEcho>();
            string testName = MethodBase.GetCurrentMethod().Name;
            IApplicationNameProvider nameProvider = new TestApplicationNameProvider(testName.RandomLetters(6));
            IApiKeyProvider          keyProvider  = new LocalApiKeyProvider();

            ExecutionRequest er = new ExecutionRequest("ApiKeyRequiredEcho", "Send", "json");

            er.ApiKeyResolver = new ApiKeyResolver(keyProvider, nameProvider);

            er.Request = new ServiceProxyTestHelpers.JsonTestRequest();
            string data = ApiParameters.ParametersToJsonParamsObjectString("some random data");

            er.InputString = data;

            ValidationResult result = er.Validate();

            Expect.IsFalse(result.Success);
            List <ValidationFailures> failures = new List <ValidationFailures>(result.ValidationFailures);

            Expect.IsTrue(failures.Contains(ValidationFailures.InvalidApiKeyToken));
        }
Ejemplo n.º 30
0
 public static void RegisterYaml(this ServiceProxySystem sys)
 {
     Register();
 }