public void ConstructorSetsProperties()
 {
     var message = new Response();
     var args = new CommunicationsEventArgs("action", message);
     Assert.AreEqual("action", args.Action);
     Assert.AreSame(message, args.Message);
 }
 /// <summary>
 /// Fires the <see cref="ResponseReceived"/> event.
 /// </summary>
 /// <param name="action">The action that the response is for.</param>
 /// <param name="response">The response that was received.</param>
 protected virtual void FireResponseReceived(string action, Response response)
 {
     if (ResponseReceived != null)
     {
         ResponseReceived(this, new CommunicationsEventArgs(action, response));
     }
 }
Esempio n. 3
0
 public void InitialiseNewResponseSetsTheDefaultValues()
 {
     DateTime now = DateTime.Now;
     Response response = new Response();
     Assert.AreEqual(ResponseResult.Unknown, response.Result, "Result wasn't set to failure");
     Assert.IsTrue((now <= response.Timestamp), "Timestamp was not set");
 }
Esempio n. 4
0
 /// <summary>
 /// Initialise a new instance of <see cref="Response"/> from a response.
 /// </summary>
 /// <param name="response">The response to use.</param>
 public Response(Response response)
 {
     errorMessages = response.errorMessages;
     requestIdentifier = response.requestIdentifier;
     result = response.result;
     Timestamp = response.Timestamp;
 }
Esempio n. 5
0
 public void EqualsMatchesResponseWithTheSameIdentifierAndTimestamp()
 {
     Response response1 = new Response();
     Response response2 = new Response();
     response1.RequestIdentifier = response2.RequestIdentifier;
     response1.Timestamp = response2.Timestamp;
     Assert.IsTrue(response1.Equals(response2));
 }
Esempio n. 6
0
 public void EqualsDoesNotMatchesResponseWithDifferentTimestamp()
 {
     Response response1 = new Response();
     Response response2 = new Response();
     response1.Timestamp = DateTime.Now.AddMilliseconds(-1);
     response2.Timestamp = DateTime.Now;
     Assert.IsFalse(response1.Equals(response2));
 }
Esempio n. 7
0
 public void EqualsDoesNotMatchesResponseWithDifferentIdentifier()
 {
     Response response1 = new Response();
     Response response2 = new Response();
     response1.RequestIdentifier = "response1";
     response2.RequestIdentifier = "response2";
     Assert.IsFalse(response1.Equals(response2));
 }
Esempio n. 8
0
 public void InitialiseResponseFromRequestSetsTheDefaultValues()
 {
     DateTime now = DateTime.Now;
     ServerRequest request = new ServerRequest();
     Response response = new Response(request);
     Assert.AreEqual(ResponseResult.Unknown, response.Result, "Result wasn't set to failure");
     Assert.AreEqual(request.Identifier, response.RequestIdentifier, "RequestIdentifier wasn't set to the identifier of the request");
     Assert.IsTrue((now <= response.Timestamp), "Timestamp was not set");
 }
Esempio n. 9
0
 public void GetSetAllPropertiesWorks()
 {
     Response response = new Response();
     response.RequestIdentifier = "new id";
     Assert.AreEqual("new id", response.RequestIdentifier, "RequestIdentifier fails the get/set test");
     response.Result = ResponseResult.Success;
     Assert.AreEqual(ResponseResult.Success, response.Result, "Result fails the get/set test");
     DateTime now = DateTime.Now;
     response.Timestamp = now;
     Assert.AreEqual(now, response.Timestamp, "Timestamp fails the get/set test");
 }
Esempio n. 10
0
 public void InitialiseResponseFromResponseSetsTheDefaultValues()
 {
     DateTime now = DateTime.Now;
     Response response1 = new Response();
     response1.Result = ResponseResult.Success;
     response1.RequestIdentifier = "original id";
     response1.Timestamp = DateTime.Now.AddMinutes(-1);
     Response response2 = new Response(response1);
     Assert.AreEqual(ResponseResult.Success, response2.Result, "Result wasn't set to failure");
     Assert.AreEqual("original id", response2.RequestIdentifier, "RequestIdentifier wasn't set to the identifier of the request");
     Assert.IsTrue((response1.Timestamp == response2.Timestamp), "Timestamp was not set");
 }
        public void SendMessageEncryptsMessage()
        {
            var innerConnection = new TestConnection();
            var outerConnection = new EncryptingConnection(innerConnection);
            var request = new ServerRequest();
            var expectedResponse = new Response(request);
            var actionName = "DoSomething";
            string iv = null;
            string key = null;

            innerConnection.SendMessageAction = (a, r) =>
            {
                Response sendResponse = null;
                if (a == "RetrievePublicKey")
                {
                    sendResponse = this.GenerateKeyResponse(r);
                }
                else if (a == "InitialiseSecureConnection")
                {
                    Assert.IsInstanceOf<LoginRequest>(r);
                    sendResponse = this.GenerateConnectioResponse(r as LoginRequest, out iv, out key);
                }
                else if (a == "ProcessSecureRequest")
                {
                    Assert.IsInstanceOf<EncryptedRequest>(r);
                    var actualRequest = r as EncryptedRequest;
                    Assert.AreEqual(actionName, actualRequest.Action);

                    var crypto = new RijndaelManaged();
                    crypto.Key = Convert.FromBase64String(key);
                    crypto.IV = Convert.FromBase64String(iv);
                    var requestData = DecryptMessage(crypto, actualRequest.EncryptedData);
                    Assert.AreEqual(request.ToString(), requestData);

                    var encryptedResponse = new EncryptedResponse();
                    encryptedResponse.Result = ResponseResult.Success;
                    encryptedResponse.EncryptedData = EncryptMessage(crypto, expectedResponse.ToString());
                    sendResponse = encryptedResponse;
                }
                else
                {
                    Assert.Fail("Unknown action: " + a);
                }

                return sendResponse;
            };
            var response = outerConnection.SendMessage(actionName, request);
            Assert.IsNotNull(response);
            Assert.AreEqual(expectedResponse.RequestIdentifier, response.RequestIdentifier);
        }
        public void ProcessMessageCorrectlyHandlesAValidMessage()
        {
            // Setup the messages
            ProjectRequest request = new ProjectRequest("123-45", "A test project");
            Response response = new Response(request);
            response.Result = ResponseResult.Success;

            // Initialises the mocks
            ICruiseServer server = mocks.DynamicMock<ICruiseServer>();
            Expect.Call(server.ForceBuild(request)).Return(response);
            mocks.ReplayAll();

            // Run the actual test
            var manager = new ThoughtWorks.CruiseControl.Core.CruiseServerClient(server);
            string responseText = manager.ProcessMessage("ForceBuild", request.ToString());
            Assert.AreEqual(response.ToString(), responseText);
            mocks.VerifyAll();
        }
 /// <summary>
 /// Validates the response from the server.
 /// </summary>
 /// <param name="response"></param>
 private Response ValidateResponse(Response response)
 {
     // If the result has not been set (i.e is Unknown) then assume we have a failure
     if ((response.Result == ResponseResult.Failure) || (response.Result == ResponseResult.Unknown))
     {
         string message = "Request processing has failed on the remote server:" + Environment.NewLine +
             response.ConcatenateErrors();
         var errorType = response.ErrorMessages.Count == 1 ?
             response.ErrorMessages[0].Type :
             null;
         throw new CommunicationsException(message, errorType);
     }
     return response;
 }
 /// <summary>
 /// Initialise a new instance of <see cref="SnapshotResponse"/> from a response.
 /// </summary>
 /// <param name="response">The response to use.</param>
 public SnapshotResponse(Response response)
     : base(response)
 {
 }
        /// <summary>
        /// Processes a message.
        /// </summary>
        /// <param name="action">The action to use.</param>
        /// <param name="message">The request message in an XML format.</param>
        /// <returns>The response message in an XML format.</returns>
        public override string ProcessMessage(string action, string message)
        {
            Response response = new Response();

            try
            {
                // Find the type of message
                var messageXml = new XmlDocument();
                messageXml.LoadXml(message);
                var messageType = XmlConversionUtil.FindMessageType(messageXml.DocumentElement.Name);
                if (messageType == null)
                {
                    response.Result = ResponseResult.Failure;
                    response.ErrorMessages.Add(
                        new ErrorMessage(
                            string.Format(
                                "Unable to translate message: '{0}' is unknown",
                                messageXml.DocumentElement.Name)));
                }

                // Convert the message and invoke the action
                var request = XmlConversionUtil.ConvertXmlToObject(messageType, message);
                response = connection.SendMessage(action, request as ServerRequest);
            }
            catch (Exception error)
            {
                response.Result = ResponseResult.Failure;
                response.ErrorMessages.Add(
                    new ErrorMessage("Unable to process error: " + error.Message));
            }

            return response.ToString();
        }
 public ServerStub(string action, Type message, string projectName, Response response)
 {
     this.action = action;
     this.message = message;
     this.projectName = projectName;
     this.response = response;
 }
 public Response SendMessage(string action, ServerRequest request)
 {
     Assert.AreEqual(this.action, action);
     Assert.AreEqual(this.message, request.GetType());
     if (!string.IsNullOrEmpty(projectName) && (request is ProjectRequest))
     {
         Assert.AreEqual(this.projectName, (request as ProjectRequest).ProjectName);
     }
     if (response == null)
     {
         Response result = new Response(request);
         result.Result = ResponseResult.Success;
         return result;
     }
     else
     {
         return response;
     }
 }
Esempio n. 18
0
 public void ToStringSerialisesAllValues()
 {
     Response response = new Response();
     response.ErrorMessages.Add(new ErrorMessage("Error 1"));
     response.ErrorMessages.Add(new ErrorMessage("Error 2"));
     response.RequestIdentifier = "request";
     response.Result = ResponseResult.Success;
     response.Timestamp = DateTime.Now;
     string actual = response.ToString();
     string expected = string.Format("<response xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
         "timestamp=\"{2:yyyy-MM-ddTHH:mm:ss.FFFFFFFzzz}\" identifier=\"{0}\" result=\"{1}\">" +
         "<error>Error 1</error>" +
         "<error>Error 2</error>" +
         "</response>",
         response.RequestIdentifier,
         response.Result,
         response.Timestamp);
     Assert.AreEqual(expected, actual);
 }
 public ServerStub(string action, Type message, Response response)
     : this(action, message, null, response)
 {
 }
        /// <summary>
        /// Terminate a secure communications connection.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public Response TerminateSecureConnection(ServerRequest request)
        {
            // Remove the connection details
            if (connections.ContainsKey(request.SourceName))
            {
                connections.Remove(request.SourceName);
            }

            // Generate a response
            var response = new Response(request);
            response.Result = ResponseResult.Success;
            return response;
        }
 /// <summary>
 /// Initialise a new <see cref="MessageReceivedEventArgs"/>.
 /// </summary>
 /// <param name="response"></param>
 /// <param name="error"></param>
 /// <param name="cancelled"></param>
 /// <param name="userState"></param>
 public MessageReceivedEventArgs(Response response, Exception error, bool cancelled, object userState)
     : base(error, cancelled, userState)
 {
     this.response = response;
 }
        /// <summary>
        /// Processes a message.
        /// </summary>
        /// <param name="action">The action to use.</param>
        /// <param name="message">The request message.</param>
        /// <returns>The response message.</returns>
        public virtual Response ProcessMessage(string action, ServerRequest message)
        {
            Response response = new Response();

            try
            {
                // Find the action
                Type cruiseType = this.GetType();
                MethodInfo actionMethod = cruiseType.GetMethod(action,
                    BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Public);
                if (actionMethod == null)
                {
                    throw new CruiseControlException(
                        string.Format(
                            CultureInfo.CurrentCulture, "Unable to locate action '{0}'",
                            action));
                }

                // Invoke the action
                message.ChannelInformation = new RemotingChannelSecurityInformation();
                response = actionMethod.Invoke(this,
                    new object[] {
                        message
                    }) as Response;
            }
            catch (Exception error)
            {
                response.Result = ResponseResult.Failure;
                if ((error is TargetInvocationException) && (error.InnerException != null))
                {
                    error = error.InnerException;
                }
                response.ErrorMessages.Add(
                    new ErrorMessage("Unable to process: " + error.Message));
            }

            return response;
        }
        /// <summary>
        /// Initialise a secure communications connection.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public Response InitialiseSecureConnection(LoginRequest request)
        {
            // Decrypt the password
            var cp = new CspParameters();
            cp.KeyContainerName = "CruiseControl.NET Server";
            var provider = new RSACryptoServiceProvider(cp);
            var originalKey = request.FindCredential(LoginRequest.UserNameCredential).Value;
            var decryptedKey = UTF8Encoding.UTF8.GetString(
                provider.Decrypt(Convert.FromBase64String(originalKey), false));
            var originalIv = request.FindCredential(LoginRequest.PasswordCredential).Value;
            var decryptedIv = UTF8Encoding.UTF8.GetString(
                provider.Decrypt(Convert.FromBase64String(originalIv), false));

            // Generate the connection details
            var connection = new SecureConnection
            {
                Expiry = DateTime.Now.AddMinutes(15),
                IV = Convert.FromBase64String(decryptedIv),
                Key = Convert.FromBase64String(decryptedKey)
            };
            connections[request.SourceName] = connection;

            // Generate a response
            var response = new Response(request);
            response.Result = ResponseResult.Success;
            return response;
        }
 /// <summary>
 /// Initialise a new instance of <see cref="ProjectStatusResponse"/> from a response.
 /// </summary>
 /// <param name="response">The response to use.</param>
 public ProjectStatusResponse(Response response)
     : base(response)
 {
 }
 /// <summary>
 /// Initialise a new instance of <see cref="ExternalLinksListResponse"/> from a response.
 /// </summary>
 /// <param name="response">The response to use.</param>
 public ExternalLinksListResponse(Response response)
     : base(response)
 {
 }
Esempio n. 26
0
        /// <summary>
        /// Encapsulates the code to process a request.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="permission"></param>
        /// <param name="eventType"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        private Response RunServerRequest(ServerRequest request,
            SecurityPermission? permission,
            SecurityEvent? eventType,
            Action<ServerRequest> action)
        {
            Response response = new Response(request);
            try
            {
                // Validate the request and check the security token
                ValidateRequest(request);
                if (permission.HasValue)
                {
                    CheckSecurity(request.SessionToken,
                        null,
                        permission.Value,
                        eventType);
                }

                // Perform the actual action
                action(request);
                response.Result = ResponseResult.Success;
            }
            catch (Exception error)
            {
                // Security exceptions have already been logged, just need to log any other exception
                if (!(error is SecurityException))
                {
                    Log.Warning(error);
                }

                // Tell the caller the request failed and include the error message (but not the stack trace!)
                response.Result = ResponseResult.Failure;
                response.ErrorMessages.Add(
                    new ErrorMessage(
                        error.Message,
                        error.GetType().Name));
            }
            return response;
        }
Esempio n. 27
0
        /// <summary>
        /// Encapsulates the code to process a request.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="permission"></param>
        /// <param name="eventType"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        private Response RunProjectRequest(ProjectRequest request,
            SecurityPermission? permission,
            SecurityEvent? eventType,
            ProjectRequestAction action)
        {
            var response = new Response(request);
            try
            {
                // Validate the request and check the security token
                ValidateRequest(request);
                if (permission.HasValue)
                {
                    CheckSecurity(request.SessionToken,
                        request.ProjectName,
                        permission.Value,
                        eventType);
                }

                // Perform the actual action
                action(request, response);
                if (response.Result == ResponseResult.Unknown)
                {
                    response.Result = ResponseResult.Success;
                }
            }
            catch (Exception error)
            {
                // Log any errors to help diagnosing issues
                Log.Warning(error);
                response.Result = ResponseResult.Failure;
                response.ErrorMessages.Add(
                    new ErrorMessage(
                        error.Message,
                        error.GetType().Name));
            }
            return response;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ListBuildSummaryResponse"/> class.
 /// </summary>
 /// <param name="response">The response.</param>
 /// <param name="summaries">The summaries.</param>
 public ListBuildSummaryResponse(Response response, IList<BuildSummary> summaries)
     : base(response)
 {
     this.summaries = new List<BuildSummary>(summaries);
 }
Esempio n. 29
0
 /// <summary>
 /// Validate the response from the server.
 /// </summary>
 /// <param name="response"></param>
 private void ValidateResponse(Response response)
 {
     if (response.Result == ResponseResult.Failure)
 {
         string message = "Request request has failed on the remote server:" + Environment.NewLine +
             response.ConcatenateErrors();
         throw new CruiseControlException(message);
 }
 }
        /// <summary>
        /// Processes a message.
        /// </summary>
        /// <param name="action">The action to use.</param>
        /// <param name="message">The request message in an XML format.</param>
        /// <returns>The response message in an XML format.</returns>
        public virtual string ProcessMessage(string action, string message)
        {
            var response = new Response();

            try
            {
                // Find the action and message type, extract the message and invoke the method
                response = ExtractAndInvokeMessage(message, action, new RemotingChannelSecurityInformation());
            }
            catch (Exception error)
            {
                response.Result = ResponseResult.Failure;
                response.ErrorMessages.Add(
                    new ErrorMessage("Unable to process: " + error.Message));
            }

            var responseText = response.ToString();
            return responseText;
        }