Ejemplo n.º 1
0
 public TmpHost(OptionsAttribute/*!*/ options)
 {
     _options = options;
     _pal = options.Pal != null ? (PlatformAdaptationLayer)Activator.CreateInstance(options.Pal) :
            IsWin8 ? new Win8PAL() :
            PlatformAdaptationLayer.Default;
 }
 public static IServiceCollection AddOptions(this IServiceCollection services,
                                             IConfiguration configuration,
                                             IEnumerable <Assembly> assemblies = null)
 {
     OptionsAttribute.ConfigureOptions(services, configuration, assemblies);
     return(services);
 }
Ejemplo n.º 3
0
        private bool AssumeAllClaims()
        {
            if (_appSecurityOptions.AllClaimsForAnonymous && _userInfo.IsUserRecognized)
            {
                throw new FrameworkException($"Invalid security configuration settings. Both anonymous access and user-level security should not be active at the same time." +
                                             $" Disable '{OptionsAttribute.GetConfigurationPath<AppSecurityOptions>()}:{nameof(AppSecurityOptions.AllClaimsForAnonymous)}' option.");
            }

            return(_userInfo.IsUserRecognized &&
                   _allClaimsForUsers.Contains(_userInfo.UserName) ||
                   _appSecurityOptions.AllClaimsForAnonymous);
        }
Ejemplo n.º 4
0
        private static void ConfigureServices(IServiceCollection services, IConfiguration config)
        {
            var assemblies = new[] { Assembly.GetExecutingAssembly() };

            BindingAttribute.ConfigureBindings(services, assemblies);
            OptionsAttribute.ConfigureOptions(services, config, assemblies);
            FactoryAttribute.ConfigureFactories(services, assemblies);
            services.ConfigureApiClient();
            services.AddSingleton(config);
            services.AddSingleton <IFileSystem, FileSystem>();
            services.AddDbContext <ManagementDbContext>(options => { options.UseSqlite("Data Source=disunity.db"); }, ServiceLifetime.Singleton);
        }
Ejemplo n.º 5
0
        /// <summary>Insert a principal with provided <see cref="PrincipalInfo.Name"/> to database, and populates ID property of <paramref name="principal"/> parameter.</summary>
        /// <remarks>If another concurrent process created a principal, this method will set the ID of the existing one.</remarks>
        public void SafeInsertPrincipal(ref PrincipalInfo principal)
        {
            string username = principal.Name; // Copy to be used for asynchronous logging.

            _logger.Info(() => $"Adding unregistered principal '{username}'. See {OptionsAttribute.GetConfigurationPath<RhetosAppOptions>()}:{nameof(RhetosAppOptions.AuthorizationAddUnregisteredPrincipals)} in configuration files.");
            var  userLock   = CreteCustomLock(username.ToUpper());
            bool newCreated = InsertPrincipalOrGetExisting(ref principal);

            if (!newCreated) // If new principal is created, other requests should wait for current transaction to be committed in order to read the new principal.
            {
                ReleaseCustomLock(userLock);
            }
        }
Ejemplo n.º 6
0
        private static void BindServices(IServiceCollection services, IConfigurationRoot configuration)
        {
            Console.WriteLine("Binding services...");

            OptionsAttribute.ConfigureOptions(services, configuration);
            BindingAttribute.ConfigureBindings(services);
            FactoryAttribute.ConfigureFactories(services);

            services // bind third-party services (can't add binding attributes to classes we don't control)
            .AddLogging(builder => builder.AddConsole())
            .AddSingleton(configuration)
            .AddSingleton(new Serializer())
            .AddSingleton <ISlugHelper, SlugHelper>()
            .AddSingleton <CommandService>();
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Finds the cache folder in either build-time or run-time configuration, since plugin scanner is used in both environments.
        /// </summary>
        public static string GetCacheFolder(IConfiguration configuration)
        {
            var    rhetosBuildEnvironment = configuration.GetOptions <RhetosBuildEnvironment>();
            var    rhetosAppOptions       = configuration.GetOptions <RhetosAppOptions>();
            string runtimeAssemblyFolder  = !string.IsNullOrEmpty(rhetosAppOptions.RhetosRuntimePath)
                ? Path.GetDirectoryName(rhetosAppOptions.RhetosRuntimePath) : null;

            string cacheFolder = rhetosBuildEnvironment.CacheFolder ?? runtimeAssemblyFolder;

            if (cacheFolder == null)
            {
                throw new FrameworkException($"Missing configuration settings for build ({OptionsAttribute.GetConfigurationPath<RhetosBuildEnvironment>()}:{nameof(RhetosBuildEnvironment.CacheFolder)})" +
                                             $" or runtime ({OptionsAttribute.GetConfigurationPath<RhetosAppOptions>()}:{nameof(RhetosAppOptions.RhetosRuntimePath)}).");
            }
            return(cacheFolder);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// It searches for type implementations in the provided list of assemblies.
        /// </summary>
        /// <param name="pluginAssemblies">List of DLL file paths that will be searched for plugins when invoking the method <see cref="FindPlugins"/>.</param>
        public PluginScanner(IEnumerable <string> pluginAssemblies, RhetosBuildEnvironment buildEnvironment, ILogProvider logProvider, PluginScannerOptions pluginScannerOptions)
        {
            if (string.IsNullOrEmpty(buildEnvironment.CacheFolder))
            {
                throw new ArgumentException($"Configuration setting '{OptionsAttribute.GetConfigurationPath<RhetosBuildEnvironment>()}:{nameof(RhetosBuildEnvironment.CacheFolder)}' in not provided.");
            }

            _pluginsByExport    = new Lazy <MultiDictionary <string, PluginInfo> >(() => GetPluginsByExport(pluginAssemblies), LazyThreadSafetyMode.ExecutionAndPublication);
            _pluginScannerCache = new PluginScannerCache(buildEnvironment.CacheFolder, logProvider, new FilesUtility(logProvider));
            _performanceLogger  = logProvider.GetLogger("Performance." + GetType().Name);
            _logger             = logProvider.GetLogger(GetType().Name);

            var ignoreList = pluginScannerOptions.PredefinedIgnoreAssemblyFiles.Concat(pluginScannerOptions.IgnoreAssemblyFiles ?? Array.Empty <string>()).Distinct().ToList();

            _ignoreAssemblyFiles    = new HashSet <string>(ignoreList.Where(name => !name.EndsWith("*")), StringComparer.OrdinalIgnoreCase);
            _ignoreAssemblyPrefixes = ignoreList.Where(name => name.EndsWith("*")).Select(name => name.Trim('*')).ToArray();
        }
Ejemplo n.º 9
0
    private static void AddProxy <T>(OptionsAttribute attribute, IServiceCollection services)
        where T : class
    {
        if (attribute is null)
        {
            throw new ArgumentNullException(nameof(attribute));
        }

        if (services is null)
        {
            throw new ArgumentNullException(nameof(services));
        }

        foreach (var contract in typeof(T).GetInterfaces().Concat(new Type[] { typeof(T) }))
        {
            services.AddTransient(contract, provider => ActivatorUtilities.CreateInstance <T>(provider));
        }
    }
Ejemplo n.º 10
0
        private HashSet <string> FromConfigAllClaimsForUsers()
        {
            try
            {
                var setting = _appSecurityOptions.AllClaimsForUsers;
                var users   = setting.Split(',').Select(u => u.Trim()).Where(u => !string.IsNullOrEmpty(u))
                              .Select(u => u.Split('@'))
                              .Select(u => new { UserName = u[0], HostName = u[1] })
                              .ToList();
                var thisMachineUserNames = users
                                           .Where(u => string.Equals(u.HostName, Environment.MachineName, StringComparison.OrdinalIgnoreCase))
                                           .Select(u => u.UserName)
                                           .Distinct();

                return(new HashSet <string>(thisMachineUserNames, StringComparer.OrdinalIgnoreCase));
            }
            catch (Exception ex)
            {
                throw new FrameworkException($"Invalid '{OptionsAttribute.GetConfigurationPath<AppSecurityOptions>()}:{nameof(AppSecurityOptions.AllClaimsForUsers)}' in configuration files. Expected comma-separated list of entries formatted as username@servername.", ex);
            }
        }
Ejemplo n.º 11
0
    private static void AddOptions <T>(OptionsAttribute attribute, IServiceCollection services)
        where T : class, new()
    {
        if (attribute is null)
        {
            throw new ArgumentNullException(nameof(attribute));
        }

        if (services is null)
        {
            throw new ArgumentNullException(nameof(services));
        }

        services
        .AddOptions <T>()
        .Configure <IConfiguration>((options, config) => config.GetSection(attribute.SectionName)?.Bind(options));

        foreach (var contract in typeof(T).GetInterfaces().Concat(new Type[] { typeof(T) }))
        {
            services.AddTransient(contract, ResolveOptions);
        }
Ejemplo n.º 12
0
        private IEnumerable <(string Path, string Value)> GetExpectedConfiguration()
        {
            var configurationItems = new List <(string Path, string Value)>();

            configurationItems.Add(($"{OptionsAttribute.GetConfigurationPath<RhetosAppOptions>()}:{nameof(RhetosAppOptions.RhetosRuntimePath)}",
                                    FilesUtility.AbsoluteToRelativePath(_rhetosBuildEnvironment.ProjectFolder, _rhetosTargetEnvironment.TargetPath)));

            configurationItems.Add(($"{OptionsAttribute.GetConfigurationPath<RhetosAppOptions>()}:{nameof(RhetosAppOptions.AssetsFolder)}",
                                    FilesUtility.AbsoluteToRelativePath(_rhetosBuildEnvironment.ProjectFolder, _rhetosTargetEnvironment.TargetAssetsFolder)));

            if (!string.IsNullOrEmpty(_buildOptions.DatabaseLanguage))
            {
                configurationItems.Add(($"{OptionsAttribute.GetConfigurationPath<RhetosAppOptions>()}:{nameof(RhetosAppOptions.DatabaseLanguage)}", _buildOptions.DatabaseLanguage));
            }

            if (_buildOptions.BuildResourcesFolder)
            {
                configurationItems.Add(($"{OptionsAttribute.GetConfigurationPath<LegacyPathsOptions>()}:{nameof(LegacyPathsOptions.ResourcesFolder)}",
                                        FilesUtility.AbsoluteToRelativePath(_rhetosBuildEnvironment.ProjectFolder, _legacyPathsOptions.ResourcesFolder)));
            }

            return(configurationItems.Where(item => item.Value != null));
        }
Ejemplo n.º 13
0
        public IConfiguration GetBuildConfiguration()
        {
            string rhetosAppRootPath = AppDomain.CurrentDomain.BaseDirectory;

            // This code is mostly copied from DeployPackages build-time configuration.

            var configuration = new ConfigurationBuilder(new ConsoleLogProvider())
                                .AddOptions(new RhetosBuildEnvironment
            {
                ProjectFolder         = rhetosAppRootPath,
                OutputAssemblyName    = null,
                CacheFolder           = Path.Combine(rhetosAppRootPath, "GeneratedFilesCache"),
                GeneratedAssetsFolder = Path.Combine(rhetosAppRootPath),     // Custom for testing
                GeneratedSourceFolder = null,
            })
                                .AddOptions(new LegacyPathsOptions
            {
                BinFolder       = Path.Combine(rhetosAppRootPath, "bin"),
                PluginsFolder   = Path.Combine(rhetosAppRootPath, "bin", "Plugins"),
                ResourcesFolder = Path.Combine(rhetosAppRootPath, "Resources"),
            })
                                .AddOptions(new LegacyPathsOptions
            {
                BinFolder       = Path.Combine(rhetosAppRootPath, "bin"),
                PluginsFolder   = Path.Combine(rhetosAppRootPath, "bin", "Plugins"),
                ResourcesFolder = Path.Combine(rhetosAppRootPath, "Resources"),
            })
                                .AddKeyValue($"{OptionsAttribute.GetConfigurationPath<BuildOptions>()}:{nameof(BuildOptions.GenerateAppSettings)}", false)
                                .AddKeyValue($"{OptionsAttribute.GetConfigurationPath<BuildOptions>()}:{nameof(BuildOptions.BuildResourcesFolder)}", true)
                                .AddWebConfiguration(rhetosAppRootPath)
                                .AddConfigurationManagerConfiguration()
                                .Build();

            LegacyUtilities.Initialize(configuration);

            return(configuration);
        }
Ejemplo n.º 14
0
        /// <summary>
        ///
        /// </summary>
        public void InitFromScript(ScriptLaunchMode Build, PropertyInfo PropInfo)
        {
            Internal        = false;
            Condition       = "true";
            ConditionResult = true;

            ScriptProperty = PropInfo;

            Name                = PropInfo.Name;
            FriendlyCategory    = PropInfo.GetCustomAttribute <CategoryAttribute>()?.Category;
            FriendlyDescription = PropInfo.GetCustomAttribute <DescriptionAttribute>()?.Description;
            FriendlyName        = PropInfo.GetCustomAttribute <DisplayNameAttribute>()?.DisplayName;

            if (PropInfo.PropertyType == typeof(string))
            {
                Value    = PropInfo.GetValue(Build) as string;
                DataType = BuildLaunchVariableDataType.String;
            }
            else if (PropInfo.PropertyType == typeof(int))
            {
                Value    = ((int)PropInfo.GetValue(Build)).ToString();
                DataType = BuildLaunchVariableDataType.Int;
            }
            else if (PropInfo.PropertyType == typeof(float))
            {
                Value    = ((float)PropInfo.GetValue(Build)).ToString();
                DataType = BuildLaunchVariableDataType.Float;
            }
            else if (PropInfo.PropertyType == typeof(bool))
            {
                Value    = ((bool)PropInfo.GetValue(Build)).ToString();
                DataType = BuildLaunchVariableDataType.Bool;
            }

            RangeAttribute Range = PropInfo.GetCustomAttribute <RangeAttribute>();

            if (Range != null)
            {
                Type MaxType = Range.Maximum.GetType();
                Type MinType = Range.Minimum.GetType();
                if (MaxType == typeof(int))
                {
                    MaxValue = (int)Range.Maximum;
                }
                if (MaxType == typeof(float))
                {
                    MaxValue = (float)Range.Maximum;
                }
                if (MaxType == typeof(double))
                {
                    MaxValue = (float)((double)Range.Maximum);
                }
                if (MinType == typeof(int))
                {
                    MinValue = (int)Range.Minimum;
                }
                if (MinType == typeof(float))
                {
                    MinValue = (float)Range.Minimum;
                }
                if (MinType == typeof(double))
                {
                    MinValue = (float)((double)Range.Minimum);
                }
            }

            OptionsAttribute Ops = PropInfo.GetCustomAttribute <OptionsAttribute>();

            if (Ops != null)
            {
                foreach (string Val in Ops.Values)
                {
                    Options.Add(Val);
                }
            }
        }
Ejemplo n.º 15
0
 private void OptionsValueSettingCheck()
 {
     _optionsAttribute = _optionsAttributeTemp;
 }
Ejemplo n.º 16
0
 public TmpHost(OptionsAttribute/*!*/ options)
 {
     _options = options;
     _pal = options.Pal != null ? (PlatformAdaptationLayer)Activator.CreateInstance(options.Pal) :
            IsWin8 ? new Win8PAL() :
            PlatformAdaptationLayer.Default;
 }
Ejemplo n.º 17
0
        public void Execute(HttpRequest request, HttpResponse response)
        {
            if (request.Server.EnableLog(LogType.Debug))
            {
                request.Server.Log(LogType.Debug, $"Gateway {request.RemoteIPAddress} {request.Method} {request.Url} request {UrlRoute.Url}'s get urlroute agent!");
            }
            if (string.Compare(request.Method, "OPTIONS", true) == 0)
            {
                if (!string.IsNullOrEmpty(UrlRoute.AccessControlAllowOrigin))
                {
                    OptionsAttribute oa = new OptionsAttribute();
                    oa.AllowCredentials = UrlRoute.AccessControlAllowCredentials;
                    oa.AllowHeaders     = UrlRoute.AccessControlAllowHeaders;
                    oa.AllowMaxAge      = UrlRoute.AccessControlMaxAge > 0 ? UrlRoute.AccessControlMaxAge.ToString() : null;
                    oa.AllowMethods     = UrlRoute.AccessControlAllowMethods;
                    oa.AllowOrigin      = UrlRoute.AccessControlAllowOrigin;
                    oa.Vary             = UrlRoute.Vary;
                    response.Result(oa);
                    return;
                }
            }
            if (!UrlRoute.ValidateRPS())
            {
                string error = $"Unable to reach [{UrlRoute.Url} route {request.Url}] in  HTTP request, exceeding maximum number of rps limit";
                Events.EventResponseErrorArgs erea = new Events.EventResponseErrorArgs(request, response,
                                                                                       UrlRoute.Gateway, error, Gateway.SERVER_MAX_OF_RPS);
                UrlRoute.Gateway.OnResponseError(erea);
                if (request.Server.EnableLog(LogType.Info))
                {
                    request.Server.Log(LogType.Info, $"Gateway {request.RemoteIPAddress} {request.Method} {request.Url} request {UrlRoute.Url}'s route server exceeding maximum number of rps limit");
                }
                return;
            }

            var agent = UrlRoute.GetServerAgent(request);

            if (agent == null)
            {
                if (request.Server.EnableLog(LogType.Info))
                {
                    request.Server.Log(LogType.Info, $"Gateway {request.RemoteIPAddress} {request.Method} {request.Url} request {UrlRoute.Url}'s route server unavailable");
                }

                Events.EventResponseErrorArgs erea = new Events.EventResponseErrorArgs(
                    request, response, UrlRoute.Gateway, $"The {Url} url route server unavailable", Gateway.URL_NODE_SERVER_UNAVAILABLE);
                UrlRoute.Gateway.OnResponseError(erea);
            }
            else
            {
                if (request.Server.EnableLog(LogType.Debug))
                {
                    request.Server.Log(LogType.Debug, $"Gateway {request.RemoteIPAddress} {request.Method} {request.Url} request {UrlRoute.Url}'s AgentRequesting event!");
                }
                if (UrlRoute.Pluginer.AgentRequesting(request, response, agent.Agent, UrlRoute))
                {
                    agent.Increment();
                    if (agent.ValidateRPS())
                    {
                        if (request.Server.EnableLog(LogType.Debug))
                        {
                            request.Server.Log(LogType.Debug, $"Gateway {request.RemoteIPAddress} {request.Method} {request.Url} request {UrlRoute.Url}'s agent execute!");
                        }
                        agent.Agent.Execute(request, response, agent, UrlRoute);
                    }
                    else
                    {
                        string error = $"Unable to reach {agent.Agent.Uri} HTTP request, exceeding maximum number of rps limit";
                        Events.EventResponseErrorArgs erea = new Events.EventResponseErrorArgs(request, response,
                                                                                               UrlRoute.Gateway, error, Gateway.SERVER_MAX_OF_RPS);
                        UrlRoute.Gateway.OnResponseError(erea);
                        if (request.Server.EnableLog(LogType.Info))
                        {
                            request.Server.Log(LogType.Info, $"Gateway {request.RemoteIPAddress} {request.Method} {request.Url} request {UrlRoute.Url}'s route server exceeding maximum number of rps limit");
                        }
                    }
                }
                else
                {
                    if (request.Server.EnableLog(LogType.Info))
                    {
                        request.Server.Log(LogType.Info, $"Gateway {request.RemoteIPAddress} {request.Method} {request.Url} request {UrlRoute.Url}'s route server exceeding cancel");
                    }
                }
            }
        }