public ServiceCredentials()
 {
     this.userName = new UserNamePasswordServiceCredential();
     this.clientCertificate = new X509CertificateInitiatorServiceCredential();
     this.serviceCertificate = new X509CertificateRecipientServiceCredential();
     this.windows = new WindowsServiceCredential();
     this.issuedToken = new IssuedTokenServiceCredential();
     this.peer = new PeerCredential();
     this.secureConversation = new SecureConversationServiceCredential();
     this.exceptionMapper = new ExceptionMapper();
     this.UseIdentityConfiguration = false;
 }
        public SecurityTokenAuthenticatorAdapter(SecurityTokenHandler securityTokenHandler, ExceptionMapper exceptionMapper)
        {
            if (securityTokenHandler == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityTokenHandler");
            }

            if (exceptionMapper == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("exceptionMapper");
            }

            _securityTokenHandler = securityTokenHandler;
            _exceptionMapper = exceptionMapper;
        }
        /// <summary>
        /// Initializes an instance of <see cref="WrappedSaml2SecurityTokenAuthenticator"/>
        /// </summary>
        /// <param name="saml2SecurityTokenHandler">The Saml2SecurityTokenHandler to wrap.</param>
        /// <param name="exceptionMapper">Converts token validation exceptions to SOAP faults.</param>
        public WrappedSaml2SecurityTokenAuthenticator( 
            Saml2SecurityTokenHandler saml2SecurityTokenHandler, 
            ExceptionMapper exceptionMapper )
        {
            if ( saml2SecurityTokenHandler == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "wrappedSaml2SecurityTokenHandler" );
            }

            if ( exceptionMapper == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "exceptionMapper" );
            }

            _wrappedSaml2SecurityTokenHandler = saml2SecurityTokenHandler;
            _exceptionMapper = exceptionMapper;
        }
 protected ServiceCredentials(ServiceCredentials other)
 {
     if (other == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("other");
     }
     this.userName = new UserNamePasswordServiceCredential(other.userName);
     this.clientCertificate = new X509CertificateInitiatorServiceCredential(other.clientCertificate);
     this.serviceCertificate = new X509CertificateRecipientServiceCredential(other.serviceCertificate);
     this.windows = new WindowsServiceCredential(other.windows);
     this.issuedToken = new IssuedTokenServiceCredential(other.issuedToken);
     this.peer = new PeerCredential(other.peer);
     this.secureConversation = new SecureConversationServiceCredential(other.secureConversation);
     this.identityConfiguration = other.identityConfiguration;
     this.saveBootstrapTokenInSession = other.saveBootstrapTokenInSession;
     this.exceptionMapper = other.exceptionMapper;
     this.UseIdentityConfiguration = other.useIdentityConfiguration;
 }
        /// <summary>
        /// Initializes an instance of <see cref="WrappedRsaSecurityTokenAuthenticator"/>
        /// </summary>
        /// <param name="wrappedRsaSecurityTokenHandler">The RsaSecurityTokenHandler to wrap.</param>
        /// <param name="exceptionMapper">Converts token validation exceptions to SOAP faults.</param>
        public WrappedRsaSecurityTokenAuthenticator( 
            RsaSecurityTokenHandler wrappedRsaSecurityTokenHandler, 
            ExceptionMapper exceptionMapper )
            : base()
        {
            if ( wrappedRsaSecurityTokenHandler == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "wrappedRsaSecurityTokenHandler" );
            }

            if ( exceptionMapper == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "exceptionMapper" );
            }

            _wrappedRsaSecurityTokenHandler = wrappedRsaSecurityTokenHandler;
            _exceptionMapper = exceptionMapper;
        }
        /// <summary>
        /// Initializes an instance of <see cref="WrappedX509SecurityTokenAuthenticator"/>
        /// </summary>
        /// <param name="wrappedX509SecurityTokenHandler">X509SecurityTokenHandler to wrap.</param>
        /// <param name="exceptionMapper">Converts token validation exceptions to SOAP faults.</param>
        public WrappedX509SecurityTokenAuthenticator(
            X509SecurityTokenHandler wrappedX509SecurityTokenHandler,
            ExceptionMapper exceptionMapper)
            : base(X509CertificateValidator.None, GetMapToWindowsSetting(wrappedX509SecurityTokenHandler), true)
        {
            if (wrappedX509SecurityTokenHandler == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("wrappedX509SecurityTokenHandler");
            }

            if (exceptionMapper == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("exceptionMapper");
            }

            _wrappedX509SecurityTokenHandler = wrappedX509SecurityTokenHandler;
            _exceptionMapper = exceptionMapper;
        }
        /// <summary>
        /// Initializes an instance of <see cref="WrappedRsaSecurityTokenAuthenticator"/>
        /// </summary>
        /// <param name="wrappedRsaSecurityTokenHandler">The RsaSecurityTokenHandler to wrap.</param>
        /// <param name="exceptionMapper">Converts token validation exceptions to SOAP faults.</param>
        public WrappedRsaSecurityTokenAuthenticator(
            RsaSecurityTokenHandler wrappedRsaSecurityTokenHandler,
            ExceptionMapper exceptionMapper)
            : base()
        {
            if (wrappedRsaSecurityTokenHandler == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("wrappedRsaSecurityTokenHandler");
            }

            if (exceptionMapper == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("exceptionMapper");
            }

            _wrappedRsaSecurityTokenHandler = wrappedRsaSecurityTokenHandler;
            _exceptionMapper = exceptionMapper;
        }
Пример #8
0
        /// <summary>
        /// Initializes an instance of <see cref="WrappedSaml11SecurityTokenAuthenticator"/>
        /// </summary>
        /// <param name="saml11SecurityTokenHandler">The Saml11SecurityTokenHandler to wrap.</param>
        /// <param name="exceptionMapper">Converts token validation exceptions to SOAP faults.</param>
        public WrappedSaml11SecurityTokenAuthenticator(
            SamlSecurityTokenHandler saml11SecurityTokenHandler,
            ExceptionMapper exceptionMapper)
            : base(new List <SecurityTokenAuthenticator>())
        {
            if (saml11SecurityTokenHandler == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("wrappedSaml11SecurityTokenHandler");
            }

            if (exceptionMapper == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("exceptionMapper");
            }

            _wrappedSaml11SecurityTokenHandler = saml11SecurityTokenHandler;
            _exceptionMapper = exceptionMapper;
        }
        /// <summary>
        /// Initializes an instance of <see cref="WrappedX509SecurityTokenAuthenticator"/>
        /// </summary>
        /// <param name="wrappedX509SecurityTokenHandler">X509SecurityTokenHandler to wrap.</param>
        /// <param name="exceptionMapper">Converts token validation exceptions to SOAP faults.</param>
        public WrappedX509SecurityTokenAuthenticator( 
            X509SecurityTokenHandler wrappedX509SecurityTokenHandler, 
            ExceptionMapper exceptionMapper )
            : base( X509CertificateValidator.None, GetMapToWindowsSetting( wrappedX509SecurityTokenHandler ), true )
        {
            if ( wrappedX509SecurityTokenHandler == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "wrappedX509SecurityTokenHandler" );
            }

            if ( exceptionMapper == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "exceptionMapper" );
            }

            _wrappedX509SecurityTokenHandler = wrappedX509SecurityTokenHandler;
            _exceptionMapper = exceptionMapper;
        }
Пример #10
0
        internal void IsRecovering_should_return_expected_result_for_message(string message, bool expectedResult)
        {
            var commandResult = new BsonDocument
            {
                { "ok", 0 },
                { "errmsg", message, message != null }
            };
            var exception = ExceptionMapper.MapNotPrimaryOrNodeIsRecovering(_connectionId, new BsonDocument(), commandResult, "errmsg");

            if (expectedResult)
            {
                exception.Should().BeOfType <MongoNodeIsRecoveringException>();
            }
            else
            {
                exception.Should().BeNull();
            }
        }
 protected ServiceCredentials(ServiceCredentials other)
 {
     if (other == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("other");
     }
     this.userName           = new UserNamePasswordServiceCredential(other.userName);
     this.clientCertificate  = new X509CertificateInitiatorServiceCredential(other.clientCertificate);
     this.serviceCertificate = new X509CertificateRecipientServiceCredential(other.serviceCertificate);
     this.windows            = new WindowsServiceCredential(other.windows);
     this.issuedToken        = new IssuedTokenServiceCredential(other.issuedToken);
     this.peer = new PeerCredential(other.peer);
     this.secureConversation          = new SecureConversationServiceCredential(other.secureConversation);
     this.identityConfiguration       = other.identityConfiguration;
     this.saveBootstrapTokenInSession = other.saveBootstrapTokenInSession;
     this.exceptionMapper             = other.exceptionMapper;
     this.UseIdentityConfiguration    = other.useIdentityConfiguration;
 }
Пример #12
0
        /// <summary>
        /// Initializes an instance of <see cref="FederatedSecurityTokenManager"/>.
        /// </summary>
        /// <param name="parentCredentials">ServiceCredentials that created this instance of TokenManager.</param>
        /// <exception cref="ArgumentNullException">The argument 'parentCredentials' is null.</exception>
        public FederatedSecurityTokenManager(ServiceCredentials parentCredentials)
            : base(parentCredentials)
        {
            if (parentCredentials == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parentCredentials");
            }

            if (parentCredentials.IdentityConfiguration == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parentCredentials.IdentityConfiguration");
            }

            _exceptionMapper = parentCredentials.ExceptionMapper;

            _securityTokenHandlerCollection = parentCredentials.IdentityConfiguration.SecurityTokenHandlers;
            _tokenCache       = _securityTokenHandlerCollection.Configuration.Caches.SessionSecurityTokenCache;
            _cookieTransforms = SessionSecurityTokenHandler.DefaultCookieTransforms;
        }
Пример #13
0
        internal void IsNotWritablePrimary_should_return_expected_result_for_code(ServerErrorCode?code, bool expectedResult, Type expectedExceptionType)
        {
            var commandResult = new BsonDocument
            {
                { "ok", 0 },
                { "code", code, code != null }
            };

            var exception = ExceptionMapper.MapNotPrimaryOrNodeIsRecovering(_connectionId, new BsonDocument(), commandResult, "errmsg");

            if (expectedExceptionType != null)
            {
                exception.Should().BeOfType(expectedExceptionType);
            }
            else
            {
                exception.Should().BeNull();
            }
        }
        /// <summary>
        /// Initializes an instance of <see cref="FederatedSecurityTokenManager"/>.
        /// </summary>
        /// <param name="parentCredentials">ServiceCredentials that created this instance of TokenManager.</param>
        /// <exception cref="ArgumentNullException">The argument 'parentCredentials' is null.</exception>
        public FederatedSecurityTokenManager( ServiceCredentials parentCredentials )
            : base( parentCredentials )
        {
            if ( parentCredentials == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "parentCredentials" );
            }

            if ( parentCredentials.IdentityConfiguration == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "parentCredentials.IdentityConfiguration" );
            }

            _exceptionMapper = parentCredentials.ExceptionMapper;

            _securityTokenHandlerCollection = parentCredentials.IdentityConfiguration.SecurityTokenHandlers;                        
            _tokenCache = _securityTokenHandlerCollection.Configuration.Caches.SessionSecurityTokenCache;                        
            _cookieTransforms = SessionSecurityTokenHandler.DefaultCookieTransforms;
        }
        private CursorBatch <TDocument> ProcessReply(ReplyMessage <TDocument> reply)
        {
            if (reply.QueryFailure)
            {
                var document = reply.QueryFailureDocument;

                var mappedException = ExceptionMapper.Map(document);
                if (mappedException != null)
                {
                    throw mappedException;
                }

                var err     = document.GetValue("$err", "Unknown error.");
                var message = string.Format("QueryFailure flag was {0} (response was {1}).", err, document.ToJson());
                throw new MongoQueryException(message, _query, document);
            }

            return(new CursorBatch <TDocument>(reply.CursorId, reply.Documents));
        }
        /// <summary>
        /// Initializes an instance of <see cref="WrappedRsaSecurityTokenAuthenticator"/>
        /// </summary>
        /// <param name="sessionTokenHandler">The sessionTokenHandler to wrap</param>
        /// <param name="wcfSessionAuthenticator">The wcf SessionTokenAuthenticator.</param>
        /// <param name="sctClaimsHandler">Handler that converts WCF generated IAuthorizationPolicy to <see cref="AuthorizationPolicy"/></param>
        /// <param name="exceptionMapper">Converts token validation exception to SOAP faults.</param>
        public WrappedSessionSecurityTokenAuthenticator(SessionSecurityTokenHandler sessionTokenHandler,
                                                        SecurityTokenAuthenticator wcfSessionAuthenticator,
                                                        SctClaimsHandler sctClaimsHandler,
                                                        ExceptionMapper exceptionMapper)
            : base()
        {
            if (sessionTokenHandler == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("sessionTokenHandler");
            }

            if (wcfSessionAuthenticator == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("wcfSessionAuthenticator");
            }

            if (sctClaimsHandler == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("sctClaimsHandler");
            }

            if (exceptionMapper == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("exceptionMapper");
            }

            _issuanceSecurityTokenAuthenticator = wcfSessionAuthenticator as IIssuanceSecurityTokenAuthenticator;
            if (_issuanceSecurityTokenAuthenticator == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4244));
            }

            _communicationObject = wcfSessionAuthenticator as ICommunicationObject;
            if (_communicationObject == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4245));
            }

            _sessionTokenHandler = sessionTokenHandler;
            _sctClaimsHandler    = sctClaimsHandler;

            _exceptionMapper = exceptionMapper;
        }
Пример #17
0
        public void TestThrowsDuplicateKeyExceptionForMongod(int code)
        {
            var response = new BsonDocument
            {
                { "ok", 1 },
                { "err", string.Format("E{0} duplicate key error index: test.foo.$_id_  dup key: {{ : 1.0 }}", code) },
                { "code", code },
                { "n", 0 },
                { "connectionId", 1 }
            };

            var writeConcernResult = new WriteConcernResult(response);

            writeConcernResult.ServerInstance = _primary;
            var ex = ExceptionMapper.Map(writeConcernResult);

            Assert.IsNotNull(ex);
            Assert.IsInstanceOf <MongoDuplicateKeyException>(ex);
        }
Пример #18
0
        public void TestThrowsWriteConcernExceptionWhenOkButHasLastErrorMessage()
        {
            var response = new BsonDocument
            {
                { "err", "oops" },
                { "code", 20 },
                { "n", 0 },
                { "connectionId", 1 },
                { "ok", 1 }
            };

            var writeConcernResult = new WriteConcernResult(response);

            writeConcernResult.ServerInstance = _primary;
            var ex = ExceptionMapper.Map(writeConcernResult);

            Assert.IsNotNull(ex);
            Assert.IsInstanceOf <WriteConcernException>(ex);
        }
Пример #19
0
        internal void ShouldInvalidateServer_should_return_expected_result_for_MongoCommandException(ServerErrorCode?code, string message, bool expectedResult)
        {
            _subject.Initialize();
            var clusterId     = new ClusterId(1);
            var serverId      = new ServerId(clusterId, new DnsEndPoint("localhost", 27017));
            var connectionId  = new ConnectionId(serverId);
            var command       = new BsonDocument("command", 1);
            var commandResult = new BsonDocument
            {
                { "ok", 0 },
                { "code", () => (int)code.Value, code.HasValue },
                { "errmsg", message, message != null }
            };
            var exception =
                ExceptionMapper.MapNotPrimaryOrNodeIsRecovering(connectionId, command, commandResult, "errmsg") ??
                new MongoCommandException(connectionId, "message", command, commandResult); // this needs for cases when we have just a random exception

            var result = _subject.ShouldInvalidateServer(Mock.Of <IConnection>(), exception, new ServerDescription(_subject.ServerId, _subject.EndPoint), out _);

            result.Should().Be(expectedResult);
        }
Пример #20
0
        protected WriteConcernResult ReadWriteConcernResult(MongoConnection connection, SendMessageWithWriteConcernResult sendMessageResult)
        {
            var writeConcernResultSerializer = BsonSerializer.LookupSerializer(typeof(WriteConcernResult));
            var replyMessage = connection.ReceiveMessage <WriteConcernResult>(ReaderSettings, writeConcernResultSerializer, null);

            if (replyMessage.NumberReturned == 0)
            {
                throw new MongoCommandException("Command 'getLastError' failed. No response returned");
            }
            var writeConcernResult = replyMessage.Documents[0];

            writeConcernResult.Command = sendMessageResult.GetLastErrorCommand;

            var mappedException = ExceptionMapper.Map(writeConcernResult);

            if (mappedException != null)
            {
                throw mappedException;
            }

            return(writeConcernResult);
        }
Пример #21
0
        /// <summary>
        /// If error results exist in the context, maps each error code to a specific exception
        /// type, then builds and throws a <see cref="MultiStatusException{T}"/>, with specific
        /// exceptions nested within.
        /// </summary>
        /// <typeparam name="T">The type of data entity.</typeparam>
        /// <param name="context">The object of state through the pipeline.</param>
        /// <param name="logger">The logging instance.</param>
        /// <param name="cancellationToken">
        /// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The completed asynchronous task.</returns>
        protected override Task _ProcessAsync <T>(
            PipelineContext <T> context,
            ILogger logger,
            CancellationToken cancellationToken)
        {
            if (context.Results == null || !context.Results.ErrorItems.Any())
            {
                return(Task.CompletedTask);
            }

            var exceptions = new List <ApiException>();

            foreach (ErrorItem <T> errorItem in context.Results.ErrorItems)
            {
                exceptions.Add(ExceptionMapper.Map(errorItem.Code, errorItem.Message, errorItem.Extra));
            }

            throw new MultiStatusException <T>(
                      "One or more items in the batch failed. See inner exception for details.",
                      new AggregateException(exceptions),
                      context.Results);
        }
Пример #22
0
        public static T GetResponse <T>(this Uri uri, string domainKey, string domainPassword) where T : class
        {
            var    request = (HttpWebRequest)HttpWebRequest.Create(uri.OriginalString);
            string encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", domainKey, domainPassword)));

            request.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", encoded);

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        throw ExceptionMapper.GetException(response.StatusCode);
                    }

                    using (var stream = new StreamReader(response.GetResponseStream()))
                    {
                        string fullResponse = stream.ReadToEnd();


                        if (CloudSponge.Format.Equals("json", StringComparison.OrdinalIgnoreCase))
                        {
                            return(JsonConvert.DeserializeObject <T>(fullResponse));
                        }
                        else
                        {
                            return(ParseXml <T>(fullResponse));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ExceptionMapper.GetException(ex.Message);
            }
        }
Пример #23
0
        // public methods
        public Exception ToWriteConcernException(ConnectionId connectionId, MongoBulkWriteOperationException bulkWriteException)
        {
            var writeConcernResult = ToWriteConcernResult(bulkWriteException.Result, bulkWriteException);

            var exception = ExceptionMapper.Map(connectionId, writeConcernResult.Response);

            if (exception == null)
            {
                exception = ExceptionMapper.Map(connectionId, writeConcernResult);
            }
            if (exception == null)
            {
                exception = new MongoWriteConcernException(connectionId, bulkWriteException.Message, writeConcernResult);
            }

            var writeConcernException = exception as MongoWriteConcernException;

            if (writeConcernException != null)
            {
                writeConcernException.Data["results"] = new List <WriteConcernResult>(new[] { writeConcernResult });
            }

            return(exception); // usually a WriteConcernException unless ExceptionMapper chose a different type
        }
Пример #24
0
        private CursorBatch <TDocument> ProcessReply(ConnectionId connectionId, ReplyMessage <TDocument> reply)
        {
            if (reply.QueryFailure)
            {
                var response = reply.QueryFailureDocument;

                var notPrimaryOrNodeIsRecoveringException = ExceptionMapper.MapNotPrimaryOrNodeIsRecovering(connectionId, response, "$err");
                if (notPrimaryOrNodeIsRecoveringException != null)
                {
                    throw notPrimaryOrNodeIsRecoveringException;
                }

                var mappedException = ExceptionMapper.Map(connectionId, response);
                if (mappedException != null)
                {
                    throw mappedException;
                }

                var message = string.Format("QueryFailure flag was true (response was {0}).", response.ToJson());
                throw new MongoQueryException(connectionId, message, _query, response);
            }

            return(new CursorBatch <TDocument>(reply.CursorId, reply.Documents));
        }
 public void ExceptionMapper_MapsUnmappedExceptionsAsExpected()
 {
     Assert.IsInstanceOfType(ExceptionMapper.Map(999), typeof(UnmappedApiException));
 }
 public void ExceptionMapper_MapsServerExceptionsAsExpected()
 {
     Assert.IsInstanceOfType(ExceptionMapper.Map(500), typeof(InternalServerException));
     Assert.IsInstanceOfType(ExceptionMapper.Map(501), typeof(MethodNotImplementedException));
     Assert.IsInstanceOfType(ExceptionMapper.Map(503), typeof(ServiceUnavailableException));
 }
Пример #27
0
 public override void Given()
 {
     ExceptionMapper = new ExceptionMapper(ExceptionExploders, ExceptionMappers);
 }
Пример #28
0
        // internal methods
        internal void ReadFrom(BsonBuffer buffer, IBsonSerializationOptions serializationOptions)
        {
            if (serializationOptions == null && typeof(TDocument) == typeof(BsonDocument))
            {
                serializationOptions = DocumentSerializationOptions.AllowDuplicateNamesInstance;
            }

            var messageStartPosition = buffer.Position;

            ReadMessageHeaderFrom(buffer);
            _responseFlags  = (ResponseFlags)buffer.ReadInt32();
            _cursorId       = buffer.ReadInt64();
            _startingFrom   = buffer.ReadInt32();
            _numberReturned = buffer.ReadInt32();

            if ((_responseFlags & ResponseFlags.CursorNotFound) != 0)
            {
                throw new MongoQueryException("Cursor not found.");
            }
            if ((_responseFlags & ResponseFlags.QueryFailure) != 0)
            {
                BsonDocument document;
                using (BsonReader bsonReader = new BsonBinaryReader(buffer, false, _readerSettings))
                {
                    document = (BsonDocument)BsonDocumentSerializer.Instance.Deserialize(bsonReader, typeof(BsonDocument), null);
                }

                var mappedException = ExceptionMapper.Map(document);
                if (mappedException != null)
                {
                    throw mappedException;
                }

                var err     = document.GetValue("$err", "Unknown error.");
                var message = string.Format("QueryFailure flag was {0} (response was {1}).", err, document.ToJson());
                throw new MongoQueryException(message, document);
            }

            _documents = new List <TDocument>(_numberReturned);
            for (int i = 0; i < _numberReturned; i++)
            {
                BsonBuffer sliceBuffer;
                if (buffer.ByteBuffer is MultiChunkBuffer)
                {
                    // we can use slightly faster SingleChunkBuffers for all documents that don't span chunk boundaries
                    var position = buffer.Position;
                    var length   = buffer.ReadInt32();
                    var slice    = buffer.ByteBuffer.GetSlice(position, length);
                    buffer.Position = position + length;
                    sliceBuffer     = new BsonBuffer(slice, true);
                }
                else
                {
                    sliceBuffer = new BsonBuffer(buffer.ByteBuffer, false);
                }

                using (var bsonReader = new BsonBinaryReader(sliceBuffer, true, _readerSettings))
                {
                    var document = (TDocument)_serializer.Deserialize(bsonReader, typeof(TDocument), serializationOptions);
                    _documents.Add(document);
                }
            }
        }
Пример #29
0
 public override void When()
 {
     ActualResult = ExceptionMapper.Map(Input);
 }
        public SecurityTokenAuthenticatorAdapter(SecurityTokenHandler securityTokenHandler, ExceptionMapper exceptionMapper)
        {
            if (securityTokenHandler == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityTokenHandler");
            }

            if (exceptionMapper == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("exceptionMapper");
            }

            _securityTokenHandler = securityTokenHandler;
            _exceptionMapper      = exceptionMapper;
        }
        private TCommandResult ProcessReply(ConnectionId connectionId, ReplyMessage <RawBsonDocument> reply)
        {
            if (reply.NumberReturned == 0)
            {
                throw new MongoCommandException(connectionId, "Command returned no documents.", _command);
            }
            if (reply.NumberReturned > 1)
            {
                throw new MongoCommandException(connectionId, "Command returned multiple documents.", _command);
            }
            if (reply.QueryFailure)
            {
                var failureDocument = reply.QueryFailureDocument;
                throw ExceptionMapper.Map(connectionId, failureDocument) ?? new MongoCommandException(connectionId, "Command failed.", _command, failureDocument);
            }

            using (var rawDocument = reply.Documents[0])
            {
                if (!rawDocument.GetValue("ok", false).ToBoolean())
                {
                    var binaryReaderSettings = new BsonBinaryReaderSettings();
                    if (_messageEncoderSettings != null)
                    {
                        binaryReaderSettings.Encoding           = _messageEncoderSettings.GetOrDefault <UTF8Encoding>(MessageEncoderSettingsName.ReadEncoding, Utf8Encodings.Strict);
                        binaryReaderSettings.GuidRepresentation = _messageEncoderSettings.GetOrDefault <GuidRepresentation>(MessageEncoderSettingsName.GuidRepresentation, GuidRepresentation.CSharpLegacy);
                    }
                    ;
                    var materializedDocument = rawDocument.Materialize(binaryReaderSettings);

                    var commandName = _command.GetElement(0).Name;
                    if (commandName == "$query")
                    {
                        commandName = _command["$query"].AsBsonDocument.GetElement(0).Name;
                    }

                    var notPrimaryOrNodeIsRecoveringException = ExceptionMapper.MapNotPrimaryOrNodeIsRecovering(connectionId, materializedDocument, "errmsg");
                    if (notPrimaryOrNodeIsRecoveringException != null)
                    {
                        throw notPrimaryOrNodeIsRecoveringException;
                    }

                    string    message;
                    BsonValue errmsgBsonValue;
                    if (materializedDocument.TryGetValue("errmsg", out errmsgBsonValue) && errmsgBsonValue.IsString)
                    {
                        var errmsg = errmsgBsonValue.ToString();
                        message = string.Format("Command {0} failed: {1}.", commandName, errmsg);
                    }
                    else
                    {
                        message = string.Format("Command {0} failed.", commandName);
                    }

                    var mappedException = ExceptionMapper.Map(connectionId, materializedDocument);
                    if (mappedException != null)
                    {
                        throw mappedException;
                    }

                    throw new MongoCommandException(connectionId, message, _command, materializedDocument);
                }

                using (var stream = new ByteBufferStream(rawDocument.Slice, ownsBuffer: false))
                {
                    var encoderFactory = new BinaryMessageEncoderFactory(stream, _messageEncoderSettings);
                    var encoder        = (ReplyMessageBinaryEncoder <TCommandResult>)encoderFactory.GetReplyMessageEncoder <TCommandResult>(_resultSerializer);
                    using (var reader = encoder.CreateBinaryReader())
                    {
                        var context = BsonDeserializationContext.CreateRoot(reader);
                        return(_resultSerializer.Deserialize(context));
                    }
                }
            }
        }
        private TCommandResult ProcessReply(ConnectionId connectionId, ReplyMessage <RawBsonDocument> reply)
        {
            if (reply.NumberReturned == 0)
            {
                throw new MongoCommandException(connectionId, "Command returned no documents.", _command);
            }
            if (reply.NumberReturned > 1)
            {
                throw new MongoCommandException(connectionId, "Command returned multiple documents.", _command);
            }
            if (reply.QueryFailure)
            {
                var failureDocument = reply.QueryFailureDocument;
                throw ExceptionMapper.Map(connectionId, failureDocument) ?? new MongoCommandException(connectionId, "Command failed.", _command, failureDocument);
            }

            using (var rawDocument = reply.Documents[0])
            {
                var binaryReaderSettings = new BsonBinaryReaderSettings();
                if (_messageEncoderSettings != null)
                {
                    binaryReaderSettings.Encoding = _messageEncoderSettings.GetOrDefault <UTF8Encoding>(MessageEncoderSettingsName.ReadEncoding, Utf8Encodings.Strict);
#pragma warning disable 618
                    if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2)
                    {
                        binaryReaderSettings.GuidRepresentation = _messageEncoderSettings.GetOrDefault <GuidRepresentation>(MessageEncoderSettingsName.GuidRepresentation, GuidRepresentation.CSharpLegacy);
                    }
#pragma warning restore 618
                }
                ;

                BsonValue clusterTime;
                if (rawDocument.TryGetValue("$clusterTime", out clusterTime))
                {
                    // note: we are assuming that _session is an instance of ClusterClockAdvancingClusterTime
                    // and that calling _session.AdvanceClusterTime will have the side effect of advancing the cluster's ClusterTime also
                    var materializedClusterTime = ((RawBsonDocument)clusterTime).Materialize(binaryReaderSettings);
                    _session.AdvanceClusterTime(materializedClusterTime);
                }
                BsonValue operationTime;
                if (rawDocument.TryGetValue("operationTime", out operationTime))
                {
                    _session.AdvanceOperationTime(operationTime.AsBsonTimestamp);
                }

                if (!rawDocument.GetValue("ok", false).ToBoolean())
                {
                    var materializedDocument = rawDocument.Materialize(binaryReaderSettings);

                    var commandName = _command.GetElement(0).Name;
                    if (commandName == "$query")
                    {
                        commandName = _command["$query"].AsBsonDocument.GetElement(0).Name;
                    }

                    var notPrimaryOrNodeIsRecoveringException = ExceptionMapper.MapNotPrimaryOrNodeIsRecovering(connectionId, _command, materializedDocument, "errmsg");
                    if (notPrimaryOrNodeIsRecoveringException != null)
                    {
                        throw notPrimaryOrNodeIsRecoveringException;
                    }

                    string    message;
                    BsonValue errmsgBsonValue;
                    if (materializedDocument.TryGetValue("errmsg", out errmsgBsonValue) && errmsgBsonValue.IsString)
                    {
                        var errmsg = errmsgBsonValue.ToString();
                        message = string.Format("Command {0} failed: {1}.", commandName, errmsg);
                    }
                    else
                    {
                        message = string.Format("Command {0} failed.", commandName);
                    }

                    var mappedException = ExceptionMapper.Map(connectionId, materializedDocument);
                    if (mappedException != null)
                    {
                        throw mappedException;
                    }

                    throw new MongoCommandException(connectionId, message, _command, materializedDocument);
                }

                if (rawDocument.Contains("writeConcernError"))
                {
                    var materializedDocument = rawDocument.Materialize(binaryReaderSettings);
                    var writeConcernError    = materializedDocument["writeConcernError"].AsBsonDocument;
                    var message            = writeConcernError.AsBsonDocument.GetValue("errmsg", null)?.AsString;
                    var writeConcernResult = new WriteConcernResult(materializedDocument);
                    throw new MongoWriteConcernException(connectionId, message, writeConcernResult);
                }

                using (var stream = new ByteBufferStream(rawDocument.Slice, ownsBuffer: false))
                {
                    var encoderFactory = new BinaryMessageEncoderFactory(stream, _messageEncoderSettings);
                    var encoder        = (ReplyMessageBinaryEncoder <TCommandResult>)encoderFactory.GetReplyMessageEncoder <TCommandResult>(_resultSerializer);
                    using (var reader = encoder.CreateBinaryReader())
                    {
                        var context = BsonDeserializationContext.CreateRoot(reader);
                        return(_resultSerializer.Deserialize(context));
                    }
                }
            }
        }
Пример #33
0
        private void ApplyApplicationError(BsonDocument applicationError)
        {
            var expectedKeys = new[]
            {
                "address",
                "generation", // optional
                "maxWireVersion",
                "when",
                "type",
                "response" // optional
            };

            JsonDrivenHelper.EnsureAllFieldsAreValid(applicationError, expectedKeys);
            var       address            = applicationError["address"].AsString;
            var       endPoint           = EndPointHelper.Parse(address);
            var       server             = (Server)_serverFactory.GetServer(endPoint);
            var       connectionId       = new ConnectionId(server.ServerId);
            var       type               = applicationError["type"].AsString;
            var       maxWireVersion     = applicationError["maxWireVersion"].AsInt32;
            Exception simulatedException = null;

            switch (type)
            {
            case "command":
                var response = applicationError["response"].AsBsonDocument;
                var command  = new BsonDocument("Link", "start!");
                simulatedException = ExceptionMapper.MapNotPrimaryOrNodeIsRecovering(connectionId, command, response, "errmsg");
                Ensure.IsNotNull(simulatedException, nameof(simulatedException));
                break;

            case "network":
            {
                var innerException = CoreExceptionHelper.CreateException("IOExceptionWithNetworkUnreachableSocketException");
                simulatedException = new MongoConnectionException(connectionId, "Ignorance, yet knowledge.", innerException);
                break;
            }

            case "timeout":
            {
                var innerException = CoreExceptionHelper.CreateException("IOExceptionWithTimedOutSocketException");
                simulatedException = new MongoConnectionException(connectionId, "Chaos, yet harmony.", innerException);
                break;
            }

            default:
                throw new ArgumentException($"Unsupported value of {type} for type");
            }

            var mockConnection = new Mock <IConnectionHandle>();
            var isMasterResult = new IsMasterResult(new BsonDocument {
                { "compressors", new BsonArray() }
            });
            var serverVersion   = WireVersionHelper.MapWireVersionToServerVersion(maxWireVersion);
            var buildInfoResult = new BuildInfoResult(new BsonDocument {
                { "version", serverVersion }
            });

            mockConnection.SetupGet(c => c.Description)
            .Returns(new ConnectionDescription(connectionId, isMasterResult, buildInfoResult));
            var generation = applicationError.Contains("generation") ? applicationError["generation"].AsInt32 : 0;

            mockConnection.SetupGet(c => c.Generation).Returns(generation);
            var when = applicationError["when"].AsString;

            switch (when)
            {
            case "beforeHandshakeCompletes":
                server.HandleBeforeHandshakeCompletesException(mockConnection.Object, simulatedException);
                break;

            case "afterHandshakeCompletes":
                server.HandleChannelException(mockConnection.Object, simulatedException);
                break;

            default:
                throw new ArgumentException($"Unsupported value of {when} for when.");
            }
        }
        private TCommandResult ProcessResponse(ConnectionId connectionId, CommandMessage responseMessage)
        {
            using (new CommandMessageDisposer(responseMessage))
            {
                var rawDocument = responseMessage.Sections.OfType <Type0CommandMessageSection <RawBsonDocument> >().Single().Document;

                var binaryReaderSettings = new BsonBinaryReaderSettings();
                if (_messageEncoderSettings != null)
                {
                    binaryReaderSettings.Encoding           = _messageEncoderSettings.GetOrDefault <UTF8Encoding>(MessageEncoderSettingsName.ReadEncoding, Utf8Encodings.Strict);
                    binaryReaderSettings.GuidRepresentation = _messageEncoderSettings.GetOrDefault <GuidRepresentation>(MessageEncoderSettingsName.GuidRepresentation, GuidRepresentation.CSharpLegacy);
                }
                ;

                BsonValue clusterTime;
                if (rawDocument.TryGetValue("$clusterTime", out clusterTime))
                {
                    // note: we are assuming that _session is an instance of ClusterClockAdvancingClusterTime
                    // and that calling _session.AdvanceClusterTime will have the side effect of advancing the cluster's ClusterTime also
                    var materializedClusterTime = ((RawBsonDocument)clusterTime).Materialize(binaryReaderSettings);
                    _session.AdvanceClusterTime(materializedClusterTime);
                }

                BsonValue operationTime;
                if (rawDocument.TryGetValue("operationTime", out operationTime))
                {
                    _session.AdvanceOperationTime(operationTime.AsBsonTimestamp);
                }

                if (!rawDocument.GetValue("ok", false).ToBoolean())
                {
                    var materializedDocument = rawDocument.Materialize(binaryReaderSettings);

                    var commandName = _command.GetElement(0).Name;
                    if (commandName == "$query")
                    {
                        commandName = _command["$query"].AsBsonDocument.GetElement(0).Name;
                    }

                    var notPrimaryOrNodeIsRecoveringException = ExceptionMapper.MapNotPrimaryOrNodeIsRecovering(connectionId, materializedDocument, "errmsg");
                    if (notPrimaryOrNodeIsRecoveringException != null)
                    {
                        throw notPrimaryOrNodeIsRecoveringException;
                    }

                    var mappedException = ExceptionMapper.Map(connectionId, materializedDocument);
                    if (mappedException != null)
                    {
                        throw mappedException;
                    }

                    string    message;
                    BsonValue errmsgBsonValue;
                    if (materializedDocument.TryGetValue("errmsg", out errmsgBsonValue) && errmsgBsonValue.IsString)
                    {
                        var errmsg = errmsgBsonValue.ToString();
                        message = string.Format("Command {0} failed: {1}.", commandName, errmsg);
                    }
                    else
                    {
                        message = string.Format("Command {0} failed.", commandName);
                    }

                    throw new MongoCommandException(connectionId, message, _command, materializedDocument);
                }

                using (var stream = new ByteBufferStream(rawDocument.Slice, ownsBuffer: false))
                {
                    using (var reader = new BsonBinaryReader(stream, binaryReaderSettings))
                    {
                        var context = BsonDeserializationContext.CreateRoot(reader);
                        return(_resultSerializer.Deserialize(context));
                    }
                }
            }
        }
        private TCommandResult ProcessResponse(ConnectionId connectionId, CommandMessage responseMessage)
        {
            using (new CommandMessageDisposer(responseMessage))
            {
                var rawDocument = responseMessage.Sections.OfType <Type0CommandMessageSection <RawBsonDocument> >().Single().Document;

                var binaryReaderSettings = new BsonBinaryReaderSettings();
                if (_messageEncoderSettings != null)
                {
                    binaryReaderSettings.Encoding = _messageEncoderSettings.GetOrDefault <UTF8Encoding>(MessageEncoderSettingsName.ReadEncoding, Utf8Encodings.Strict);
#pragma warning disable 618
                    if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2)
                    {
                        binaryReaderSettings.GuidRepresentation = _messageEncoderSettings.GetOrDefault <GuidRepresentation>(MessageEncoderSettingsName.GuidRepresentation, GuidRepresentation.CSharpLegacy);
                    }
#pragma warning restore 618
                }
                ;

                BsonValue clusterTime;
                if (rawDocument.TryGetValue("$clusterTime", out clusterTime))
                {
                    // note: we are assuming that _session is an instance of ClusterClockAdvancingClusterTime
                    // and that calling _session.AdvanceClusterTime will have the side effect of advancing the cluster's ClusterTime also
                    var materializedClusterTime = ((RawBsonDocument)clusterTime).Materialize(binaryReaderSettings);
                    _session.AdvanceClusterTime(materializedClusterTime);
                }

                BsonValue operationTime;
                if (rawDocument.TryGetValue("operationTime", out operationTime))
                {
                    _session.AdvanceOperationTime(operationTime.AsBsonTimestamp);
                }

                if (rawDocument.GetValue("ok", false).ToBoolean())
                {
                    if (rawDocument.TryGetValue("recoveryToken", out var rawRecoveryToken))
                    {
                        var recoveryToken = ((RawBsonDocument)rawRecoveryToken).Materialize(binaryReaderSettings);
                        _session.CurrentTransaction.RecoveryToken = recoveryToken;
                    }
                }
                else
                {
                    var materializedDocument = rawDocument.Materialize(binaryReaderSettings);

                    var commandName = _command.GetElement(0).Name;
                    if (commandName == "$query")
                    {
                        commandName = _command["$query"].AsBsonDocument.GetElement(0).Name;
                    }

                    var notPrimaryOrNodeIsRecoveringException = ExceptionMapper.MapNotPrimaryOrNodeIsRecovering(connectionId, _command, materializedDocument, "errmsg");
                    if (notPrimaryOrNodeIsRecoveringException != null)
                    {
                        throw notPrimaryOrNodeIsRecoveringException;
                    }

                    var mappedException = ExceptionMapper.Map(connectionId, materializedDocument);
                    if (mappedException != null)
                    {
                        throw mappedException;
                    }

                    string    message;
                    BsonValue errmsgBsonValue;
                    if (materializedDocument.TryGetValue("errmsg", out errmsgBsonValue) && errmsgBsonValue.IsString)
                    {
                        var errmsg = errmsgBsonValue.ToString();
                        message = string.Format("Command {0} failed: {1}.", commandName, errmsg);
                    }
                    else
                    {
                        message = string.Format("Command {0} failed.", commandName);
                    }

                    var exception = new MongoCommandException(connectionId, message, _command, materializedDocument);

                    // https://jira.mongodb.org/browse/CSHARP-2678
                    if (IsRetryableWriteExceptionAndDeploymentDoesNotSupportRetryableWrites(exception))
                    {
                        throw WrapNotSupportedRetryableWriteException(exception);
                    }
                    else
                    {
                        throw exception;
                    }
                }

                if (rawDocument.Contains("writeConcernError"))
                {
                    var materializedDocument = rawDocument.Materialize(binaryReaderSettings);
                    var writeConcernError    = materializedDocument["writeConcernError"].AsBsonDocument;
                    var message            = writeConcernError.AsBsonDocument.GetValue("errmsg", null)?.AsString;
                    var writeConcernResult = new WriteConcernResult(materializedDocument);
                    throw new MongoWriteConcernException(connectionId, message, writeConcernResult);
                }

                using (var stream = new ByteBufferStream(rawDocument.Slice, ownsBuffer: false))
                {
                    using (var reader = new BsonBinaryReader(stream, binaryReaderSettings))
                    {
                        var context = BsonDeserializationContext.CreateRoot(reader);
                        return(_resultSerializer.Deserialize(context));
                    }
                }
            }
        }