Example #1
0
        protected virtual string DoExecute(IConfigSectionNode command)
        {
            var cname = command.Name.ToLowerInvariant();

            var tp = Cmdlets.FirstOrDefault(cmd => cmd.Name.EqualsIgnoreCase(cname));

            if (tp == null)
            {
                return(Sky.StringConsts.RT_CMDLET_DONTKNOW_ERROR.Args(cname));
            }

            //Check cmdlet security
            Permission.AuthorizeAndGuardAction(App, tp);
            Permission.AuthorizeAndGuardAction(App, tp.GetMethod(nameof(Execute)));

            var cmdlet = Activator.CreateInstance(tp, this, command) as Cmdlet;

            if (cmdlet == null)
            {
                throw new SkyException(Sky.StringConsts.RT_CMDLET_ACTIVATION_ERROR.Args(cname));
            }

            using (cmdlet)
            {
                App.DependencyInjector.InjectInto(cmdlet);
                return(cmdlet.Execute());
            }
        }
Example #2
0
        private static PropertyInfo findByName(IApplication app, bool isSet, object target, string name, string[] groups)
        {
            if (target != null && name.IsNotNullOrWhiteSpace())
            {
                name = name.Trim();
                var tp = target.GetType();

                var props = suitableProperties(tp);

                foreach (var prop in props)
                {
                    var atr = prop.GetCustomAttributes(typeof(ExternalParameterAttribute), false).FirstOrDefault() as ExternalParameterAttribute;
                    if (atr == null)
                    {
                        continue;
                    }

                    if (groups != null && groups.Length > 0)
                    {
                        if (atr.Groups == null)
                        {
                            continue;
                        }
                        if (!atr.Groups.Intersect(groups).Any())
                        {
                            continue;
                        }
                    }

                    string pname;
                    if (atr.Name.IsNullOrWhiteSpace())
                    {
                        pname = prop.Name;
                    }
                    else
                    {
                        pname = atr.Name;
                    }

                    if (string.Equals(name, pname, StringComparison.InvariantCultureIgnoreCase)) //MATCH
                    {
                        if (                                                                     //check security
                            (isSet && (atr.SecurityCheck & ExternalParameterSecurityCheck.OnSet) != 0) ||
                            (!isSet && (atr.SecurityCheck & ExternalParameterSecurityCheck.OnGet) != 0)
                            )
                        {
                            Permission.AuthorizeAndGuardAction(app, prop);
                        }
                        return(prop);
                    }
                }
            }
            return(null);
        }
Example #3
0
        protected override void DoFilterWork(WorkContext work, IList <WorkFilter> filters, int thisFilterIndex)
        {
            if (m_Permissions != null && m_Permissions.Any())
            {
                if (!m_BypassMatches.Any(match => match.Make(work) != null))
                {
                    work.NeedsSession();
                    Permission.AuthorizeAndGuardAction(App.SecurityManager, m_Permissions, "{0}({1})".Args(GetType().FullName, this.Name), work.Session);
                }
            }

            this.InvokeNextWorker(work, filters, thisFilterIndex);
        }
Example #4
0
        /// <summary>
        /// Override to process request
        /// </summary>
        /// <param name="request"></param>
        /// <param name="execute">Execute vs Describe</param>
        /// <returns>Response object or null if request is unmatched/unsupported</returns>
        protected virtual ExternalCallResponse DoProcessRequest(IConfigSectionNode request, bool execute)
        {
            if (request == null || !request.Exists)
            {
                return(null);                             //unknown request
            }
            //Find the matching handler type out of SUPPORTED (no type injection possible)
            var tr = SupportedRequestTypes.FirstOrDefault(t => t.Name.EqualsOrdIgnoreCase(request.Name));// command-name{ ... }

            if (tr == null)
            {
                return(null);     //unknown
            }
            //Execution MANDATES handler authorization of the calling principal
            if (execute)
            {
                Permission.AuthorizeAndGuardAction(App, tr);
            }

            //Create instance of the appropriate handler
            var handler = (Activator.CreateInstance(tr, Context) as ExternalCallRequest <TContext>).NonNull(
                "Type reg error for `{0}` is not `{1}`".Args(
                    GetType().DisplayNameWithExpandedGenericArgs(),
                    typeof(ExternalCallRequest <TContext>).DisplayNameWithExpandedGenericArgs()));

            //perform DI of app container
            App.InjectInto(handler);

            //configure handler from request properties
            handler.Configure(request);

            //Execute or Describe (which is a form of execution with a different purpose)
            var response = execute ? handler.Execute() : handler.Describe();

            return(response);
        }
Example #5
0
 /// <summary>
 /// Checks the specified permissions in the calling scope security context
 /// </summary>
 /// <param name="app">Non-null app context</param>
 /// <param name="permissions">Permission instances to check</param>
 /// <param name="caller">The caller name is derived from CallerMemebr compiler info</param>
 /// <param name="session">The caller session scope or null in which case an ambient caller scope will be used</param>
 /// <remarks>
 /// Use case:
 /// <code>
 /// app.Authroize(Permission.All(new A(), new B());
 /// app.Authorize(new A().And(new B()).And(new C()));
 /// </code>
 /// </remarks>
 public static void Authorize(this IApplication app, IEnumerable <Permission> permissions, [CallerMemberName] string caller = null, Apps.ISession session = null)
 => Permission.AuthorizeAndGuardAction(app.NonNull(nameof(app)), permissions, caller, session ?? Ambient.CurrentCallSession);
Example #6
0
        private ResponseMsg doWork(RequestMsg request)
        {
            var contract = request.Contract;                                                       //this throws when contract can't be found
            var server   = getServerImplementer(request.ServerTransport.ServerEndpoint, contract); //throws when no implementor match found

            if (server.AuthenticationSupport)
            {
                interpretAuthenticationHeader(request);
            }


            //Authorizes user to the whole server contract and implementing class
            Permission.AuthorizeAndGuardAction(App, server.Contract);
            Permission.AuthorizeAndGuardAction(App, server.Implementation);

            serverImplementer.mapping mapped = server.SpecToMethodInfos(request.Method);


            Permission.AuthorizeAndGuardAction(App, mapped.miContract);
            Permission.AuthorizeAndGuardAction(App, mapped.miImplementation);


            Guid?checkedOutID;
            bool lockTaken;
            var  instance = getServerInstance(server, request, out checkedOutID, out lockTaken);       //throws when instance expired or cant be locked

            try
            {
                Guid?instanceID = null;
                bool isCtor     = false;
                bool isDctor    = false;

                if (server.InstanceMode == ServerInstanceMode.Stateful ||
                    server.InstanceMode == ServerInstanceMode.AutoConstructedStateful)
                {
                    instanceID = request.RemoteInstance;
                    isCtor     = Attribute.IsDefined(mapped.miContract, typeof(ConstructorAttribute));
                    isDctor    = Attribute.IsDefined(mapped.miContract, typeof(DestructorAttribute));


                    if (isCtor && isDctor)
                    {
                        throw new ServerMethodInvocationException(StringConsts.GLUE_AMBIGUOUS_CTOR_DCTOR_DEFINITION_ERROR
                                                                  .Args(contract.FullName, request.MethodName));
                    }

                    if (server.InstanceMode != ServerInstanceMode.AutoConstructedStateful &&
                        !instanceID.HasValue &&
                        !isCtor)
                    {
                        throw new ServerMethodInvocationException(StringConsts.GLUE_NO_SERVER_INSTANCE_ERROR
                                                                  .Args(contract.FullName, request.MethodName));
                    }
                }

                //========================================================================================================
                object result;
                try
                {
                    var any = request as RequestAnyMsg;
                    if (any != null)
                    {
                        result = mapped.miContract.Invoke(instance, any.Arguments);       //do actual contract-implementing method work
                    }
                    else
                    {
                        //call functor using typed RequestMsg derivative
                        if (mapped.fBody == null)
                        {
                            throw new ServerMethodInvocationException(StringConsts.GLUE_NO_ARGS_MARSHAL_LAMBDA_ERROR
                                                                      .Args(contract.FullName, request.MethodName));
                        }
                        result = mapped.fBody(instance, request);      //do actual contract-implementing method work via Lambda
                    }
                }
                catch (Exception bodyError)
                {
                    Exception err = bodyError;
                    if (err is TargetInvocationException)        //unwrap the inner error which is wrapped by Invoke()
                    {
                        if (err.InnerException != null)
                        {
                            err = err.InnerException;
                        }
                    }

                    throw new ServerMethodInvocationException(StringConsts.GLUE_SERVER_CONTRACT_METHOD_INVOCATION_ERROR
                                                              .Args(contract.FullName, request.MethodName, err.ToMessageWithType()),
                                                              err);
                }
                //========================================================================================================

                if (server.InstanceMode == ServerInstanceMode.Stateful ||
                    server.InstanceMode == ServerInstanceMode.AutoConstructedStateful)
                {
                    if (isCtor || (server.InstanceMode == ServerInstanceMode.AutoConstructedStateful && !isDctor && !instanceID.HasValue))
                    {
                        instanceID = Guid.NewGuid();
                        App.ObjectStore.CheckIn(instanceID.Value, instance, server.InstanceTimeoutMs);
                    }
                    else
                    if (isDctor)
                    {
                        if (instanceID.HasValue)
                        {
                            App.ObjectStore.Delete(instanceID.Value);
                            instanceID   = null;
                            checkedOutID = null;
                        }
                    }
                }


                if (request.OneWay)
                {
                    return(null);
                }

                var response = new ResponseMsg(request.RequestID, instanceID, result);
                response.__SetBindingSpecificContext(request);
                return(response);
            }
            finally
            {
                if (lockTaken)
                {
                    Monitor.Exit(instance);
                }
                if (checkedOutID.HasValue)
                {
                    App.ObjectStore.CheckIn(checkedOutID.Value, server.InstanceTimeoutMs);
                }
            }
        }
Example #7
0
 /// <summary>
 /// Checks a single specified permission in the calling scope security context
 /// </summary>
 /// <param name="app">Non-null app context</param>
 /// <param name="permission">Permission instance to check</param>
 /// <param name="caller">The caller name is derived from CallerMemebr compiler info</param>
 /// <param name="session">The caller session scope or null in which case an ambient caller scope will be used</param>
 /// <remarks>
 /// Use case:
 /// <code>
 /// app.Authroize(new A());
 /// </code>
 /// </remarks>
 public static void Authorize(this IApplication app, Permission permission, [CallerMemberName] string caller = null, Apps.ISession session = null)
 => Permission.AuthorizeAndGuardAction(app.NonNull(nameof(app)).SecurityManager, permission, caller, session ?? Ambient.CurrentCallSession);