public void PrintEnumResult(RequestAttributes actual, RequestAttributes required) { Console.WriteLine(string.Format("({0} | {1}): {2}", actual, required, (actual | required))); Console.WriteLine(string.Format("({0} & {1}): {2}", actual, required, (actual & required))); Console.WriteLine(string.Format("({0} ^ {1}): {2}", actual, required, (actual ^ required))); Console.WriteLine(); }
public static StorageOperationTypes GetBlobOperation(string requestMethod, RequestUriParts requestUriParts, RequestQueryParameters queryParams, RequestHeaders headers) { var requestAttributes = new RequestAttributes { Method = new HttpMethod(requestMethod), UriParts = requestUriParts, QueryParams = queryParams, Headers = headers, }; if (requestUriParts.IsAccountRequest) { return(LookupBlobOperation(requestAttributes, _accountOperations)); } else if (requestUriParts.IsContainerRequest) { return(LookupBlobOperation(requestAttributes, _containerOperations)); } else if (requestUriParts.IsBlobRequest) { return(LookupBlobOperation(requestAttributes, _blobOperations)); } else { System.Diagnostics.Debug.Assert(false); } return(StorageOperationTypes.Unknown); }
public UserManager(GotItDbContext dbContext, RequestAttributes requestAttributes, TokenManager tokenManager, MailProvider mailProvider) : base(dbContext) { _requestAttributes = requestAttributes; _tokenManager = tokenManager; _mailProvider = mailProvider; }
public void PrintEnumResult(RequestAttributes actual, RequestAttributes required) { $"({actual} | {required}): {actual | required}".Print(); $"({actual} & {required}): {actual & required}".Print(); $"({actual} ^ {required}): {actual ^ required}".Print(); "".Print(); }
public AspNetRequest(HttpContextBase httpContext, string operationName, RequestAttributes requestAttributes) { this.OperationName = operationName; this.RequestAttributes = requestAttributes; this.request = httpContext.Request; try { this.response = new AspNetResponse(httpContext.Response, this); } catch (Exception ex) { log.Error(ex.Message, ex); } this.RequestPreferences = new RequestPreferences(httpContext); if (httpContext.Items != null && httpContext.Items.Count > 0) { foreach (var key in httpContext.Items.Keys) { var strKey = key as string; if (strKey == null) { continue; } Items[strKey] = httpContext.Items[key]; } } }
public UserController(RequestAttributes requestAttributes, UserManager manager, ItemManager itemManager, RequestManager requestManager) { _requestAttributes = requestAttributes; _manager = manager; _itemManager = itemManager; _requestManager = requestManager; }
public BasicRequest(IMessage message = null, RequestAttributes requestAttributes = RequestAttributes.LocalSubnet | RequestAttributes.MessageQueue) { Message = message ?? new Message(); ContentType = this.ResponseContentType = MimeTypes.Json; this.Headers = PclExportClient.Instance.NewNameValueCollection(); if (Message.Body != null) { PathInfo = "/json/oneway/" + OperationName; RawUrl = AbsoluteUri = "mq://" + PathInfo; Headers = new NameValueCollectionWrapper(Message.ToHeaders().ToNameValueCollection()); } this.IsLocal = true; Response = new BasicResponse(this); this.RequestAttributes = requestAttributes; this.Verb = HttpMethods.Post; this.Cookies = new Dictionary <string, Cookie>(); this.Items = new Dictionary <string, object>(); this.QueryString = PclExportClient.Instance.NewNameValueCollection(); this.FormData = PclExportClient.Instance.NewNameValueCollection(); this.Files = TypeConstants <IHttpFile> .EmptyArray; }
public GenericHandler(string contentType, RequestAttributes handlerAttributes, Feature format) { this.HandlerContentType = contentType; this.ContentTypeAttribute = ContentFormat.GetEndpointAttributes(contentType); this.HandlerAttributes = handlerAttributes; this.format = format; }
public void Enum_masks_are_correct() { const RequestAttributes network = RequestAttributes.Localhost | RequestAttributes.LocalSubnet | RequestAttributes.External; Assert.That((network.ToAllowedFlagsSet() & network) == network); const RequestAttributes security = RequestAttributes.Secure | RequestAttributes.InSecure; Assert.That((security.ToAllowedFlagsSet() & security) == security); const RequestAttributes method = RequestAttributes.HttpHead | RequestAttributes.HttpGet | RequestAttributes.HttpPost | RequestAttributes.HttpPut | RequestAttributes.HttpDelete | RequestAttributes.HttpPatch | RequestAttributes.HttpOptions | RequestAttributes.HttpOther; Assert.That((method.ToAllowedFlagsSet() & method) == method); const RequestAttributes call = RequestAttributes.OneWay | RequestAttributes.Reply; Assert.That((call.ToAllowedFlagsSet() & call) == call); const RequestAttributes format = RequestAttributes.Soap11 | RequestAttributes.Soap12 | RequestAttributes.Xml | RequestAttributes.Json | RequestAttributes.Jsv | RequestAttributes.ProtoBuf | RequestAttributes.Csv | RequestAttributes.Html | RequestAttributes.Yaml | RequestAttributes.MsgPack | RequestAttributes.FormatOther; Assert.That((format.ToAllowedFlagsSet() & format) == format); const RequestAttributes endpoint = RequestAttributes.Http | RequestAttributes.MessageQueue | RequestAttributes.Tcp | RequestAttributes.EndpointOther; Assert.That((endpoint.ToAllowedFlagsSet() & endpoint) == endpoint); }
static StorageOperationTypes GetPutOrCopyBlobOperation(RequestAttributes request) { if (request.Headers.Contains("x-ms-copy-source")) { return StorageOperationTypes.CopyBlob; } return StorageOperationTypes.PutBlob; }
static StorageOperationTypes GetPutOrCopyBlobOperation(RequestAttributes request) { if (request.Headers.Contains("x-ms-copy-source")) { return(StorageOperationTypes.CopyBlob); } return(StorageOperationTypes.PutBlob); }
public NetCoreRequest(HttpContext context, string operationName, RequestAttributes attrs = RequestAttributes.None) { this.context = context; this.OperationName = operationName; this.request = context.Request; this.Items = new Dictionary <string, object>(); this.RequestAttributes = attrs; }
public AspNetRequest(HttpContextBase httpContext, string operationName, RequestAttributes requestAttributes) { this.OperationName = operationName; this.RequestAttributes = requestAttributes; this.request = httpContext.Request; this.response = new AspNetResponse(httpContext.Response); this.RequestPreferences = new RequestPreferences(httpContext); }
public NetCoreRequest(HttpContext context, string operationName, RequestAttributes attrs = RequestAttributes.None, string pathInfo = null) { this.context = context; this.OperationName = operationName; this.request = context.Request; this.Items = new Dictionary <string, object>(); this.RequestAttributes = attrs; this.PathInfo = (pathInfo ?? request.Path.Value).Replace("+", " "); //Kestrel does not decode '+' into space }
public ItemController(RequestAttributes requestAttributes, ItemManager manager, RequestManager requestManager, CommentManager commentManager) { _requestAttributes = requestAttributes; _manager = manager; _requestManager = requestManager; _commentManager = commentManager; }
public void GetEndpointAttributes_AcceptsUserHostAddressFormats(string format, RequestAttributes expected) { var handler = new TestHandler(); var request = new Mock<IHttpRequest>(); request.Expect(req => req.UserHostAddress).Returns(format); request.Expect(req => req.IsSecureConnection).Returns(false); request.Expect(req => req.Verb).Returns("GET"); Assert.AreEqual(expected | RequestAttributes.HttpGet | RequestAttributes.InSecure, request.Object.GetAttributes()); }
public static Feature ToSoapFeature(this RequestAttributes attributes) { if ((RequestAttributes.Soap11 & attributes) == RequestAttributes.Soap11) { return(Feature.Soap11); } if ((RequestAttributes.Soap12 & attributes) == RequestAttributes.Soap12) { return(Feature.Soap12); } return(Feature.None); }
private static bool CanShowToNetwork(RestrictAttribute restrictTo, RequestAttributes reqAttrs) { if (reqAttrs.IsLocalhost()) { return(restrictTo.CanShowTo(RequestAttributes.Localhost) || restrictTo.CanShowTo(RequestAttributes.LocalSubnet)); } return(restrictTo.CanShowTo( reqAttrs.IsLocalSubnet() ? RequestAttributes.LocalSubnet : RequestAttributes.External)); }
static StorageOperationTypes LookupBlobOperation(RequestAttributes attributes, IDictionary <HttpMethod, Dictionary <string, Func <RequestAttributes, StorageOperationTypes> > > lookup) { Dictionary <string, Func <RequestAttributes, StorageOperationTypes> > methodOperations; if (lookup.TryGetValue(attributes.Method, out methodOperations)) { var compParam = attributes.QueryParams.Value("comp", String.Empty); Func <RequestAttributes, StorageOperationTypes> operationDispatch; if (methodOperations.TryGetValue(compParam, out operationDispatch)) { return(operationDispatch(attributes)); } } return(StorageOperationTypes.Unknown); }
public AspNetRequest(HttpContextBase httpContext, string operationName, RequestAttributes requestAttributes) { this.OperationName = operationName; this.RequestAttributes = requestAttributes; this.request = httpContext.Request; try { this.response = new AspNetResponse(httpContext.Response); } catch (Exception ex) { log.Error(ex.Message, ex); } this.RequestPreferences = new RequestPreferences(httpContext); }
public void AssertServiceRestrictions(Type requestType, RequestAttributes actualAttributes) { if (!appHost.Config.EnableAccessRestrictions) { return; } if ((RequestAttributes.InProcess & actualAttributes) == RequestAttributes.InProcess) { return; } RestrictAttribute restrictAttr; var hasNoAccessRestrictions = !requestServiceAttrs.TryGetValue(requestType, out restrictAttr) || restrictAttr.HasNoAccessRestrictions; if (hasNoAccessRestrictions) { return; } var failedScenarios = StringBuilderCache.Allocate(); foreach (var requiredScenario in restrictAttr.AccessibleToAny) { var allServiceRestrictionsMet = (requiredScenario & actualAttributes) == actualAttributes; if (allServiceRestrictionsMet) { return; } var passed = requiredScenario & actualAttributes; var failed = requiredScenario & ~(passed); failedScenarios.Append($"\n -[{failed}]"); } var internalDebugMsg = (RequestAttributes.InternalNetworkAccess & actualAttributes) != 0 ? "\n Unauthorized call was made from: " + actualAttributes : ""; throw new UnauthorizedAccessException( $"Could not execute service '{requestType.GetOperationName()}', The following restrictions were not met: " + $"'{StringBuilderCache.ReturnAndFree(failedScenarios)}'{internalDebugMsg}"); }
public void AssertServiceRestrictions(Type requestType, RequestAttributes actualAttributes) { if (!appHost.Config.EnableAccessRestrictions) { return; } RestrictAttribute restrictAttr; var hasNoAccessRestrictions = !requestServiceAttrs.TryGetValue(requestType, out restrictAttr) || restrictAttr.HasNoAccessRestrictions; if (hasNoAccessRestrictions) { return; } var failedScenarios = new StringBuilder(); foreach (var requiredScenario in restrictAttr.AccessibleToAny) { var allServiceRestrictionsMet = (requiredScenario & actualAttributes) == actualAttributes; if (allServiceRestrictionsMet) { return; } var passed = requiredScenario & actualAttributes; var failed = requiredScenario & ~(passed); failedScenarios.AppendFormat("\n -[{0}]", failed); } var internalDebugMsg = (RequestAttributes.InternalNetworkAccess & actualAttributes) != 0 ? "\n Unauthorized call was made from: " + actualAttributes : ""; throw new UnauthorizedAccessException( string.Format("Could not execute service '{0}', The following restrictions were not met: '{1}'" + internalDebugMsg, requestType.GetOperationName(), failedScenarios)); }
public bool CanAccess(RequestAttributes reqAttrs, Format format, string operationName) { if (HostContext.Config != null && !HostContext.Config.EnableAccessRestrictions) { return(true); } Operation operation; OperationNamesMap.TryGetValue(operationName.ToLower(), out operation); if (operation == null) { return(false); } var canCall = HasImplementation(operation, format); if (!canCall) { return(false); } if (operation.RestrictTo == null) { return(true); } var allow = operation.RestrictTo.HasAccessTo(reqAttrs); if (!allow) { return(false); } var allowsFormat = operation.RestrictTo.HasAccessTo((RequestAttributes)(long)format); return(allowsFormat); }
public BasicRequest(IMessage message = null, RequestAttributes requestAttributes = RequestAttributes.LocalSubnet | RequestAttributes.MessageQueue) { Message = message ?? new Message(); ContentType = this.ResponseContentType = MimeTypes.Json; if (Message.Body != null) { PathInfo = "/json/oneway/" + OperationName; RawUrl = AbsoluteUri = "mq://" + PathInfo; Headers = Message.ToHeaders().ToNameValueCollection(); } this.IsLocal = true; Response = new BasicResponse(this); this.RequestAttributes = requestAttributes; this.Headers = new NameValueCollection(); this.Cookies = new Dictionary <string, Cookie>(); this.Items = new Dictionary <string, object>(); this.QueryString = new NameValueCollection(); this.FormData = new NameValueCollection(); this.Files = new IHttpFile[0]; }
public static StorageOperationTypes GetBlobOperation(string requestMethod, RequestUriParts requestUriParts, RequestQueryParameters queryParams, RequestHeaders headers) { var requestAttributes = new RequestAttributes { Method = new HttpMethod(requestMethod), UriParts = requestUriParts, QueryParams = queryParams, Headers = headers, }; if (requestUriParts.IsAccountRequest) { return LookupBlobOperation(requestAttributes, _accountOperations); } else if (requestUriParts.IsContainerRequest) { return LookupBlobOperation(requestAttributes, _containerOperations); } else if (requestUriParts.IsBlobRequest) { return LookupBlobOperation(requestAttributes, _blobOperations); } else { System.Diagnostics.Debug.Assert(false); } return StorageOperationTypes.Unknown; }
public override object ExecuteService(object requestDto, RequestAttributes requestAttributes) { OrderOfOperations.Add(typeof(AppHost), "ExecuteService"); return(base.ExecuteService(requestDto, requestAttributes)); }
static StorageOperationTypes LookupBlobOperation(RequestAttributes attributes, IDictionary<HttpMethod, Dictionary<string, Func<RequestAttributes, StorageOperationTypes>>> lookup) { Dictionary<string, Func<RequestAttributes, StorageOperationTypes>> methodOperations; if (lookup.TryGetValue(attributes.Method, out methodOperations)) { var compParam = attributes.QueryParams.Value("comp", String.Empty); Func<RequestAttributes, StorageOperationTypes> operationDispatch; if (methodOperations.TryGetValue(compParam, out operationDispatch)) { return operationDispatch(attributes); } } return StorageOperationTypes.Unknown; }
public bool CanShowTo(RequestAttributes restrictions) { return this.VisibleToAny.Any(scenario => (restrictions & scenario) == restrictions); }
public void GetEndpointAttributes_AcceptsUserHostAddressFormats(string format, RequestAttributes expected) { var handler = new TestHandler(); var request = new BasicRequest { UserHostAddress = format, IsSecureConnection = false, Verb = "GET" }; Assert.AreEqual(expected | RequestAttributes.HttpGet | RequestAttributes.InSecure, request.GetAttributes()); }
protected Message ExecuteMessage(Message message, RequestAttributes requestAttributes, IHttpRequest httpRequest, IHttpResponse httpResponse) { var soapFeature = requestAttributes.ToSoapFeature(); HostContext.AssertFeatures(soapFeature); var httpReq = HttpContext.Current != null && httpRequest == null ? new AspNetRequest(HttpContext.Current.Request) : httpRequest; var httpRes = HttpContext.Current != null && httpResponse == null ? new AspNetResponse(HttpContext.Current.Response) : httpResponse; if (httpReq == null) throw new ArgumentNullException("httpRequest"); if (httpRes == null) throw new ArgumentNullException("httpResponse"); if (HostContext.ApplyPreRequestFilters(httpReq, httpRes)) return PrepareEmptyResponse(message, httpReq); var requestMsg = message ?? GetRequestMessageFromStream(httpReq.InputStream); string requestXml = GetRequestXml(requestMsg); var requestType = GetRequestType(requestMsg, requestXml); if (!HostContext.Metadata.CanAccess(requestAttributes, soapFeature.ToFormat(), requestType.Name)) throw HostContext.UnauthorizedAccess(requestAttributes); try { var useXmlSerializerRequest = requestType.HasAttribute<XmlSerializerFormatAttribute>(); var request = useXmlSerializerRequest ? XmlSerializableDeserializer.Instance.Parse(requestXml, requestType) : DataContractDeserializer.Instance.Parse(requestXml, requestType); var requiresSoapMessage = request as IRequiresSoapMessage; if (requiresSoapMessage != null) { requiresSoapMessage.Message = requestMsg; } httpReq.OperationName = requestType.Name; httpReq.SetItem("SoapMessage", requestMsg); var hasRequestFilters = HostContext.GlobalRequestFilters.Count > 0 || FilterAttributeCache.GetRequestFilterAttributes(request.GetType()).Any(); if (hasRequestFilters && HostContext.ApplyRequestFilters(httpReq, httpRes, request)) return EmptyResponse(requestMsg, requestType); var response = ExecuteService(request, requestAttributes, httpReq, httpRes); var hasResponseFilters = HostContext.GlobalResponseFilters.Count > 0 || FilterAttributeCache.GetResponseFilterAttributes(response.GetType()).Any(); if (hasResponseFilters && HostContext.ApplyResponseFilters(httpReq, httpRes, response)) return EmptyResponse(requestMsg, requestType); var httpResult = response as IHttpResult; if (httpResult != null) response = httpResult.Response; var useXmlSerializerResponse = response.GetType().HasAttribute<XmlSerializerFormatAttribute>(); if (useXmlSerializerResponse) return requestMsg.Headers.Action == null ? Message.CreateMessage(requestMsg.Version, null, response, new XmlSerializerWrapper(response.GetType())) : Message.CreateMessage(requestMsg.Version, requestType.Name + "Response", response, new XmlSerializerWrapper(response.GetType())); return requestMsg.Headers.Action == null ? Message.CreateMessage(requestMsg.Version, null, response) : Message.CreateMessage(requestMsg.Version, requestType.Name + "Response", response); } catch (Exception ex) { throw new SerializationException("3) Error trying to deserialize requestType: " + requestType + ", xml body: " + requestXml, ex); } }
public static UnauthorizedAccessException UnauthorizedAccess(RequestAttributes requestAttrs) { return(new UnauthorizedAccessException($"Request with '{requestAttrs}' is not allowed")); }
public SoapHandler(RequestAttributes soapType) { this.HandlerAttributes = soapType; this.appHost = HostContext.AppHost; }
protected Message ExecuteMessage(Message message, RequestAttributes requestAttributes, IRequest httpReq, IResponse httpRes) { var soapFeature = requestAttributes.ToSoapFeature(); HostContext.AppHost.AssertFeatures(soapFeature); if (httpReq == null) httpReq = HostContext.GetCurrentRequest(); if (httpRes == null && httpReq != null) httpRes = httpReq.Response; if (httpReq == null) throw new ArgumentNullException("httpReq"); if (httpRes == null) throw new ArgumentNullException("httpRes"); httpReq.UseBufferedStream = true; var requestMsg = message ?? GetRequestMessageFromStream(httpReq.InputStream); var soapAction = httpReq.GetHeader(HttpHeaders.SOAPAction) ?? GetAction(requestMsg); if (soapAction != null) { httpReq.OperationName = soapAction.Trim('"'); } if (HostContext.ApplyPreRequestFilters(httpReq, httpRes)) return PrepareEmptyResponse(message, httpReq); string requestXml = GetRequestXml(requestMsg); var requestType = GetRequestType(requestMsg, requestXml); httpReq.OperationName = requestType.GetOperationName(); if (!HostContext.Metadata.CanAccess(requestAttributes, soapFeature.ToFormat(), requestType.GetOperationName())) throw HostContext.UnauthorizedAccess(requestAttributes); try { var useXmlSerializerRequest = requestType.HasAttribute<XmlSerializerFormatAttribute>(); var request = useXmlSerializerRequest ? XmlSerializableSerializer.Instance.DeserializeFromString(requestXml, requestType) : Serialization.DataContractSerializer.Instance.DeserializeFromString(requestXml, requestType); httpReq.Dto = request; var requiresSoapMessage = request as IRequiresSoapMessage; if (requiresSoapMessage != null) { requiresSoapMessage.Message = requestMsg; } httpReq.SetItem("SoapMessage", requestMsg); httpRes.ContentType = GetSoapContentType(httpReq.ContentType); var hasRequestFilters = HostContext.GlobalRequestFilters.Count > 0 || FilterAttributeCache.GetRequestFilterAttributes(request.GetType()).Any(); if (hasRequestFilters && HostContext.ApplyRequestFilters(httpReq, httpRes, request)) return EmptyResponse(requestMsg, requestType); httpReq.RequestAttributes |= requestAttributes; var response = ExecuteService(request, httpReq); var taskResponse = response as Task; if (taskResponse != null) { taskResponse.Wait(); response = TypeAccessor.Create(taskResponse.GetType())[taskResponse, "Result"]; } var hasResponseFilters = HostContext.GlobalResponseFilters.Count > 0 || FilterAttributeCache.GetResponseFilterAttributes(response.GetType()).Any(); if (hasResponseFilters && HostContext.ApplyResponseFilters(httpReq, httpRes, response)) return EmptyResponse(requestMsg, requestType); var httpResult = response as IHttpResult; if (httpResult != null) response = httpResult.Response; var noMsgAction = requestMsg.Headers.Action == null; var responseMsg = CreateResponseMessage(response, requestMsg.Version, requestType, noMsgAction); if (httpResult != null) { SetErrorStatusIfAny(httpReq.Response, responseMsg, httpResult.Status); } return responseMsg; } catch (Exception ex) { throw new SerializationException("3) Error trying to deserialize requestType: " + requestType + ", xml body: " + requestXml, ex); } }
protected static object ExecuteService(object request, RequestAttributes requestAttributes, IHttpRequest httpReq, IHttpResponse httpRes) { return HostContext.ExecuteService(request, requestAttributes, httpReq, httpRes); }
public static bool HasAnyRestrictionsOf(RequestAttributes allRestrictions, RequestAttributes restrictions) { return (allRestrictions & restrictions) != 0; }
public bool HasAccessTo(RequestAttributes restrictions) { return this.AccessibleToAny.Any(scenario => (restrictions & scenario) == restrictions); }
public BasicRequest(object requestDto, RequestAttributes requestAttributes = RequestAttributes.LocalSubnet | RequestAttributes.MessageQueue) : this(MessageFactory.Create(requestDto), requestAttributes) { }
public Soap12Handler(RequestAttributes soapType) : base(soapType) { }
public SoapHandler(RequestAttributes soapType) { this.HandlerAttributes = soapType; }
public static bool IsLocalSubnet(this RequestAttributes attrs) { return((RequestAttributes.LocalSubnet & attrs) == RequestAttributes.LocalSubnet); }
public virtual object ExecuteService(object requestDto, RequestAttributes requestAttributes) { return(ServiceController.Execute(requestDto, new BasicRequest(requestDto, requestAttributes))); }
public static bool IsExternal(this RequestAttributes attrs) { return((RequestAttributes.External & attrs) == RequestAttributes.External); }
/// <summary> /// Returns the allowed set of scenarios based on the user-specified restrictions /// </summary> /// <param name="restrictToAny"></param> /// <returns></returns> private static RequestAttributes[] ToAllowedFlagsSet(RequestAttributes[] restrictToAny) { if (restrictToAny.Length == 0) return new[] { RequestAttributes.Any }; var scenarios = new List<RequestAttributes>(); foreach (var restrictToScenario in restrictToAny) { var restrictTo = restrictToScenario.ToAllowedFlagsSet(); scenarios.Add(restrictTo); } return scenarios.ToArray(); }
/// <summary> /// Restrict access and metadata visibility to any of the specified access scenarios /// </summary> /// <value>The restrict access to scenarios.</value> public RestrictAttribute(RequestAttributes[] allowedAccessScenarios, RequestAttributes[] visibleToScenarios) : this() { this.AccessibleToAny = ToAllowedFlagsSet(allowedAccessScenarios); this.VisibleToAny = ToAllowedFlagsSet(visibleToScenarios); }