protected override void Given() { var handshakeResponse = new HandshakeResponse { Ok = true, WebSocketUrl = "some-valid-url" }; GetMockFor <IHandshakeClient>() .Setup(x => x.FirmShake(SlackKey)) .ReturnsAsync(handshakeResponse); Connection = new SlackConnectionStub(); SlackFactoryStub.Create_Value = Connection; GetMockFor <IConnectionFactory>() .Setup(x => x.CreateHandshakeClient()) .Returns(GetMockFor <IHandshakeClient>().Object); ProxySettings = new ProxySettings("hi", "you", "ok?"); GetMockFor <IConnectionFactory>() .Setup(x => x.CreateWebSocketClient(handshakeResponse.WebSocketUrl, ProxySettings)) .Returns(GetMockFor <IWebSocketClient>().Object); GetMockFor <IWebSocketClient>() .Setup(x => x.Connect()) .Returns(Task.Factory.StartNew(() => { })); }
private Dictionary <string, SlackChatHub> GetChatHubs(HandshakeResponse handshakeResponse) { var hubs = new Dictionary <string, SlackChatHub>(); foreach (Channel channel in handshakeResponse.Channels.Where(x => !x.IsArchived)) { if (channel.IsMember) { hubs.Add(channel.Id, _cachedDataProvider.GetChatHub(channel)); } } foreach (Group group in handshakeResponse.Groups.Where(x => !x.IsArchived)) { if (group.Members.Any(x => x == handshakeResponse.Self.Id)) { var users = new List <User>(); foreach (var userId in group.Members) { users.Add(handshakeResponse.Users.FirstOrDefault(x => x.Id == userId)); } var usersName = users.Select(x => x?.Name); hubs.Add(group.Id, _cachedDataProvider.GetChatHub(group, usersName?.ToArray())); } } foreach (Im im in handshakeResponse.Ims) { User user = handshakeResponse.Users.FirstOrDefault(x => x.Id == im.User); var userName = user?.Name; hubs.Add(im.Id, _cachedDataProvider.GetChatHub(im, userName)); } return(hubs); }
private Dictionary <string, SlackUser> GenerateUsers(HandshakeResponse handshakeResponse) { var users = new Dictionary <string, SlackUser>(); foreach (var user in handshakeResponse.Users) { var slackUser = new SlackUser { Id = user.Id, Name = user.Name, IsBot = false, Icons = user.Profile?.Icons }; users.Add(user.Id, slackUser); } foreach (var bot in handshakeResponse.Bots) { var slackUser = new SlackUser { Id = bot.Id, Name = bot.Name, IsBot = true, Icons = bot.Icons }; users.Add(bot.Id, slackUser); } return(users); }
public void Constructor_InitializesPropertiesForError() { var response = new HandshakeResponse(MessageResponseCode.Error, protocolVersion: null); Assert.Equal(MessageResponseCode.Error, response.ResponseCode); Assert.Null(response.ProtocolVersion); }
public void Constructor_InitializesPropertiesForSuccess() { var response = new HandshakeResponse(MessageResponseCode.Success, _version); Assert.Equal(MessageResponseCode.Success, response.ResponseCode); Assert.Equal(_version, response.ProtocolVersion); }
public static void ClientFinish(TlsConnection connection, int length) { Log.Info("Recv ClientFinish"); var sha256 = SHA256.Create(); var handshakeData = connection.HandshakeMessages.GetRange(0, connection.HandshakeMessages.Count - length - 4).ToArray(); var handshakeHash = sha256.ComputeHash(handshakeData); var prfClient = new PseudoRandomFunction(connection.MasterSecretBytes, "client finished", handshakeHash); byte[] clientVerifyData = prfClient.GenerateBytes(12); byte[] data = connection.Buffer.Read(12); for (uint i = 0; i < 12; i++) { if (clientVerifyData[i] != data[i]) { Log.Error("Invalid ClientFinish!"); return; } } HandshakeResponse.ServerChangeCipherSpec(connection); connection.SendEncrypted = true; HandshakeResponse.ServerServerFinish(connection); }
protected override void Given() { HandshakeResponse = new HandshakeResponse { Ok = true, Self = new Detail { Id = "my-id", Name = "my-name" }, Team = new Detail { Id = "team-id", Name = "team-name" }, Users = new[] { new User { Id = "user-1-id", Name = "user-1-name" }, new User { Id = "user-2-id", Name = "user-2-name" }, }, Channels = new[] { new Channel { Id = "i-am-a-channel", Name = "channel-name", IsMember = true } }, Groups = new[] { new Group { Id = "i-am-a-group", Name = "group-name", Members = new [] { "my-id" } }, }, Ims = new[] { new Im { Id = "i-am-a-im", User = "******" } }, WebSocketUrl = "some-valid-url" }; GetMockFor <IHandshakeClient>() .Setup(x => x.FirmShake(SlackKey)) .ReturnsAsync(HandshakeResponse); Connection = new SlackConnectionStub(); SlackFactoryStub.Create_Value = Connection; GetMockFor <IConnectionFactory>() .Setup(x => x.CreateHandshakeClient()) .Returns(GetMockFor <IHandshakeClient>().Object); GetMockFor <IConnectionFactory>() .Setup(x => x.CreateWebSocketClient(HandshakeResponse.WebSocketUrl, null)) .Returns(GetMockFor <IWebSocketClient>().Object); GetMockFor <IWebSocketClient>() .Setup(x => x.Connect()) .Returns(Task.Factory.StartNew(() => { })); }
private async Task <IWebSocketClient> GetWebSocket(HandshakeResponse handshakeResponse, ProxySettings proxySettings) { var webSocketClient = _connectionFactory.CreateWebSocketClient(handshakeResponse.WebSocketUrl, proxySettings); await webSocketClient.Connect(); return(webSocketClient); }
/// <summary> /// 分组命令 /// </summary> /// <param name="response">握手返回值</param> /// <param name="secrets">密码列表</param> /// <param name="groupNumber">当前组数量 从1 开始</param> public GroupingCommandRequest(HandshakeResponse response, List <UInt64> secrets, int groupNumber, shareAction1 s1, shareAction2 s2) : base(response, s1, s2) { this.dataBelong = 0; this.number = groupNumber; this.dotPwoer = secrets.Count(); var baseOffset = (groupNumber - 1) * 4; var maxOffset = baseOffset + 4; List <UInt64> secretsInt = new List <UInt64>(); if (baseOffset + 4 >= secrets.Count()) { maxOffset = secrets.Count(); } for (int i = baseOffset; i < maxOffset; i++) { secretsInt.Add(secrets[i]); } if (secretsInt.Count() < 4) { var count = secretsInt.Count(); for (int i = 0; i < 4 - count; i++) { secretsInt.Add(0); } } this.request += secretsInt[0] << 48; this.request += secretsInt[1] << 32; this.request += secretsInt[2] << 16; this.request += secretsInt[3]; }
public async Task should_return_expected_connection() { // given var handshakeResponse = new HandshakeResponse { Ok = true, Self = new Detail { Id = "my-id", Name = "my-name" }, WebSocketUrl = _webSocketUrl }; _handshakeClient .Setup(x => x.FirmShake(_slackKey)) .ReturnsAsync(handshakeResponse); var expectedConnection = new Mock <ISlackConnection>().Object; _slackConnectionFactory .Setup(x => x.Create(It.IsAny <ConnectionInformation>())) .ReturnsAsync(expectedConnection); // when var result = await _slackConnector.Connect(_slackKey); // then result.ShouldBe(expectedConnection); }
public async Task should_initialise_connection_with_expected_users_details() { // given var handshakeResponse = new HandshakeResponse { Ok = true, Users = new[] { new User { Id = "user-1-id", Name = "user-1-name" }, new User { Id = "user-2-id", Name = "user-2-name" }, }, WebSocketUrl = _webSocketUrl }; _handshakeClient .Setup(x => x.FirmShake(_slackKey)) .ReturnsAsync(handshakeResponse); // when await _slackConnector.Connect(_slackKey); // then _slackConnectionFactory .Verify(x => x.Create(It.Is((ConnectionInformation p) => p.Users.Count == 2)), Times.Once); _slackConnectionFactory .Verify(x => x.Create(It.Is((ConnectionInformation p) => p.Users["user-1-id"].Name == "user-1-name")), Times.Once); _slackConnectionFactory .Verify(x => x.Create(It.Is((ConnectionInformation p) => p.Users["user-2-id"].Name == "user-2-name")), Times.Once); }
public async Task should_not_contain_channels_that_are_archived_and_bot_is_not_a_member_off() { // given var handshakeResponse = new HandshakeResponse { Ok = true, Channels = new[] { new Channel { Id = "Id1", Name = "Name1", IsArchived = false, IsMember = false } } }; _handshakeClient .Setup(x => x.FirmShake(It.IsAny <string>())) .ReturnsAsync(handshakeResponse); // when await _slackConnector.Connect("something"); // then _slackConnectionFactory .Verify(x => x.Create(It.Is((ConnectionInformation p) => p.SlackChatHubs.Count == 0)), Times.Once); }
public async Task <ISlackConnection> Connect(string slackKey) { if (string.IsNullOrEmpty(slackKey)) { throw new ArgumentNullException(nameof(slackKey)); } var handshakeClient = this._connectionFactory.CreateHandshakeClient(); HandshakeResponse handshakeResponse = await handshakeClient.FirmShake(slackKey); if (!handshakeResponse.Ok) { throw new HandshakeException(handshakeResponse.Error); } Dictionary <string, SlackUser> users = this.GenerateUsers(handshakeResponse.Users); var connectionInfo = new ConnectionInformation { SlackKey = slackKey, Self = new ContactDetails { Id = handshakeResponse.Self.Id, Name = handshakeResponse.Self.Name }, Team = new ContactDetails { Id = handshakeResponse.Team.Id, Name = handshakeResponse.Team.Name }, Users = users, SlackChatHubs = this.GetChatHubs(handshakeResponse, users.Values.ToArray()), WebSocket = await this._connectionFactory.CreateWebSocketClient(handshakeResponse.WebSocketUrl, null) }; var connection = await this._slackConnectionFactory.Create(connectionInfo); return(connection); }
public async Task should_initialise_connection_with_expected_self_details() { // given var handshakeResponse = new HandshakeResponse { Ok = true, Self = new Detail { Id = "my-id", Name = "my-name" }, WebSocketUrl = _webSocketUrl }; _handshakeClient .Setup(x => x.FirmShake(_slackKey)) .ReturnsAsync(handshakeResponse); // when await _slackConnector.Connect(_slackKey); // then _slackConnectionFactory .Verify(x => x.Create(It.Is((ConnectionInformation p) => p.Self.Id == handshakeResponse.Self.Id)), Times.Once); _slackConnectionFactory .Verify(x => x.Create(It.Is((ConnectionInformation p) => p.Self.Name == handshakeResponse.Self.Name)), Times.Once); }
public async Task should_not_contain_archived_groups() { // given var handshakeResponse = new HandshakeResponse { Ok = true, Groups = new[] { new Group { Id = "group-id", Name = "group-name", IsArchived = true } } }; _handshakeClient .Setup(x => x.FirmShake(It.IsAny <string>())) .ReturnsAsync(handshakeResponse); // when await _slackConnector.Connect("something"); // then _slackConnectionFactory .Verify(x => x.Create(It.Is((ConnectionInformation p) => p.SlackChatHubs.Count == 0)), Times.Once); }
public async Task should_call_expected_url_with_given_slack_key() { // given const string slackKey = "I-is-da-key-yeah"; var expectedResponse = new HandshakeResponse { Ok = true, WebSocketUrl = "some-url" }; _httpTest.RespondWithJson(expectedResponse); // when var result = await _handshakeClient.FirmShake(slackKey); // then _responseVerifierMock.Verify(x => x.VerifyResponse(Looks.Like(expectedResponse))); _httpTest .ShouldHaveCalled(ClientConstants.SlackApiHost.AppendPathSegment(FlurlHandshakeClient.HANDSHAKE_PATH)) .WithQueryParamValue("token", slackKey) .Times(1); result.ToExpectedObject().ShouldEqual(expectedResponse); }
public void Write(IContext context, object msg) { HttpResponse response = msg as HttpResponse; if (response != null) { bool isContinue = true; if (_config.StatusListener != null && response.Status != 200) { isContinue = _config.StatusListener(response); } if (isContinue) { response.KeepAlive = _keepalive; if (_config.DisableGzip) { response.Gzip = false; } HttpResponseEncoder.WriteResponse(response); context.FirePreWrite(msg); } } else { HandshakeResponse websockethandshake = msg as HandshakeResponse; if (websockethandshake != null) { HttpResponseEncoder.WriteWebSocketHandshakeResponse(websockethandshake); //升级协议为websocket _source.SetState(new WebSocketState(context, _source, _config)); } context.FirePreWrite(msg); } }
public void HandleResponse_SecondResponseIsIgnored() { using (var test = new OutboundRequestContextTest()) { var payload = new HandshakeResponse(MessageResponseCode.Error, protocolVersion: null); var firstResponse = MessageUtilities.Create( test.Request.RequestId, MessageType.Response, test.Request.Method, payload); test.Context.HandleResponse(firstResponse); var response = test.Context.CompletionTask.Result; payload = new HandshakeResponse(MessageResponseCode.Success, ProtocolConstants.CurrentVersion); var secondResponse = MessageUtilities.Create( test.Request.RequestId, MessageType.Response, test.Request.Method, payload); test.Context.HandleResponse(secondResponse); Assert.Same(response, test.Context.CompletionTask.Result); } }
public async Task <ISlackConnection> Connect(string slackKey, ProxySettings proxySettings = null) { if (string.IsNullOrEmpty(slackKey)) { throw new ArgumentNullException(nameof(slackKey)); } var handshakeClient = _connectionFactory.CreateHandshakeClient(); HandshakeResponse handshakeResponse = await handshakeClient.FirmShake(slackKey); if (!handshakeResponse.Ok) { throw new HandshakeException(handshakeResponse.Error); } var connectionInfo = new ConnectionInformation { SlackKey = slackKey, Self = new ContactDetails { Id = handshakeResponse.Self.Id, Name = handshakeResponse.Self.Name }, Team = new ContactDetails { Id = handshakeResponse.Team.Id, Name = handshakeResponse.Team.Name }, Users = GenerateUsers(handshakeResponse.Users), SlackChatHubs = GetChatHubs(handshakeResponse), WebSocket = await GetWebSocket(handshakeResponse, proxySettings) }; return(_slackConnectionFactory.Create(connectionInfo)); }
private Dictionary <string, SlackChatHub> GetChatHubs(HandshakeResponse handshakeResponse, SlackUser[] users) { var hubs = new Dictionary <string, SlackChatHub>(); foreach (Channel channel in handshakeResponse.Channels.Where(x => !x.IsArchived)) { if (channel.IsMember) { var newChannel = channel.ToChatHub(); hubs.Add(channel.Id, newChannel); } } foreach (Group group in handshakeResponse.Groups.Where(x => !x.IsArchived)) { if ((group.Members ?? new string[0]).Any(x => x == handshakeResponse.Self.Id)) { var newGroup = group.ToChatHub(); hubs.Add(group.Id, newGroup); } } foreach (Im im in handshakeResponse.Ims) { hubs.Add(im.Id, im.ToChatHub(users)); } return(hubs); }
public async Task should_initialise_connection_with_websocket_and_return_expected_connection() { // given var handshakeResponse = new HandshakeResponse { Ok = true, WebSocketUrl = _webSocketUrl }; _handshakeClient .Setup(x => x.FirmShake(_slackKey)) .ReturnsAsync(handshakeResponse); var expectedConnection = new Mock <ISlackConnection>().Object; _slackConnectionFactory .Setup(x => x.Create(It.IsAny <ConnectionInformation>())) .ReturnsAsync(expectedConnection); // when var result = await _slackConnector.Connect(_slackKey); // then result.ShouldBe(expectedConnection); _slackConnectionFactory .Verify(x => x.Create(It.Is((ConnectionInformation p) => p.WebSocket == _webSocketClient.Object)), Times.Once); _connectionFactory.Verify(x => x.CreateWebSocketClient(_webSocketUrl)); }
public async Task CloseAsync() { ThrowIfNotStarted(); Logger.LogInformation("Closing socket connection."); try { State = ReadyState.Closing; //don't receive anything from underlying socket anymore _pingPongSubscription.Dispose(); _messageSubscription.Dispose(); _disconnectSubscription.Dispose(); //clean anything set during socket startup/run time _packetId = -1; _currentHandshake = null; _sentPingPackets.Clear(); //finally stop the socket await _socket.StopOrFail(WebSocketCloseStatus.NormalClosure, string.Empty); } catch (Exception ex) { Logger.LogError(ex, "Error while stopping socket."); throw; } finally { Logger.LogInformation("Socket connection closed."); State = ReadyState.Closed; } }
public PushScoreCommandRequest(HandshakeResponse response, shareAction1 s1, shareAction2 s2, long problemNumber, String answer) : base(response, s1, s2) { this.dataBelong = 64; this.number = 130; this.dotPwoer = SubVoteDisplayAction.GetSubVoteDisplayAction(answer); this.request = SubVoteDisplayAction.GetDisplayData(answer); this.handshakeSecretKey = 2; }
internal void SendAuthChallenge(string challenge) { HandshakeResponse handshakeResponse = new HandshakeResponse(HttpStatusCode.Unauthorized); handshakeResponse.Headers["WWW-Authenticate"] = challenge; this._stream.WriteHandshake(handshakeResponse); this._request = this._stream.ReadHandshake <HandshakeRequest>(new Func <string[], HandshakeRequest>(HandshakeRequest.Parse), 15000); }
public void JsonSerialization_ReturnsCorrectJson() { var response = new HandshakeResponse(MessageResponseCode.Success, _version); var json = TestUtilities.Serialize(response); Assert.Equal("{\"ResponseCode\":\"Success\",\"ProtocolVersion\":\"1.0.0\"}", json); }
internal void SendAuthChallenge(string challenge) { var res = new HandshakeResponse(HttpStatusCode.Unauthorized); res.Headers ["WWW-Authenticate"] = challenge; _stream.WriteHandshake(res); _request = _stream.ReadHandshake <HandshakeRequest> (HandshakeRequest.Parse, 15000); }
public ActionResult <HandshakeResponse> Handshake() { var response = new HandshakeResponse { UploadId = Guid.NewGuid() }; return(Ok(response)); }
public void SendHandshakeResponse(ClientConnectionInfo connection, HandshakeResponseCode responseCode) { var handShakeResponse = new HandshakeResponse { ResponseCode = responseCode }; DefaultSend(connection, handShakeResponse.Create(), ChannelID.Handshaking, true); }
/// <summary> /// Websocket 握手输出 /// </summary> /// <param name="response"></param> public static void WriteWebSocketHandshakeResponse(HandshakeResponse response) { HeaderBuilder builder = HeaderBuilder.NewResonse(101, "Switching Protocols"); builder.Add("Upgrade", "websocket"); builder.Add("Connection", "Upgrade"); builder.Add("Sec-WebSocket-Accept", response.CreateResponseKey()); builder.Add("Server", Utility.PRODUCT_NAME); response.Stream.WriteBytes(builder.ToByteArray()); }
public static Byte[] Decrypt(Byte[] list, HandshakeResponse hand) { List <Byte> finlist = new List <byte>(); for (int i = 4; i < 20; i++) { finlist.Add(list[i]); } return(Decrypt(finlist, list[3], list[2])); }
internal void SendAuthChallenge (string challenge) { var res = new HandshakeResponse (HttpStatusCode.Unauthorized); res.Headers ["WWW-Authenticate"] = challenge; _stream.WriteHandshake (res); _request = _stream.ReadHandshake<HandshakeRequest> (HandshakeRequest.Parse, 15000); }
static HandshakeResponse() { Accepted = new HandshakeResponse(true); Rejected = new HandshakeResponse(false); }
private void ServerMessageReceived(NetworkClient senderClient, int messageType, ByteString messageContent) { Debug.Log("Server message Type={0} Size={1}.", messageType, messageContent.Length); switch (messageType) { /* Handshake request. */ case MessageType.ClientHandshakeRequest: { HandshakeRequest request = HandshakeRequest.Parser.ParseFrom(messageContent); senderClient.UpdatePublicKey(request.Key); PublicKey serverPublic = this.ServerKey; if (serverPublic == null) { Debug.Error("Server public key is invalid."); return; } HandshakeResponse response = new HandshakeResponse(); response.Key = serverPublic; senderClient.SendMessage(MessageType.ClientHandshakeResponse, response); } break; /* Authorization request. */ case MessageType.AuthorizationRequest: { AuthorizationRequest request = AuthorizationRequest.Parser.ParseFrom(messageContent); senderClient.Profile.UpdateProfile(request); AuthorizationResponse response = new AuthorizationResponse(); response.ServerName = this.m_serverConfig.ServerName; senderClient.SendMessage(MessageType.AuthorizationResponse, response); Task.Run(() => { ContactUpdate contactUpdate = new ContactUpdate(); contactUpdate.Add.Add(senderClient.ContactClient); foreach (NetworkClient connectedClient in this.m_connectedClients) { if (connectedClient.ClientId == senderClient.ClientId) continue; Debug.Log("Sending contact update to ClientId={0}.", connectedClient.ClientId); connectedClient.SendMessage(MessageType.ContactUpdate, contactUpdate); } }); } break; /* Contact list update. */ case MessageType.ContactUpdateRequest: { ContactUpdateRequest request = ContactUpdateRequest.Parser.ParseFrom(messageContent); ContactUpdate contactUpdate = new ContactUpdate(); List<long> clientList = request.Clients.ToList(); foreach (NetworkClient connectedClient in this.m_connectedClients) { // if (connectedClient.ClientId == senderClient.ClientId) continue; if (!connectedClient.Profile.Valid) continue; if (clientList.Contains(connectedClient.ClientId)) { Debug.Log("Client {0} has got ClientId={1}.", senderClient.ClientId, connectedClient.ClientId); clientList.Remove(connectedClient.ClientId); } else { Debug.Log("Client {0} requires ClientId={1}.", senderClient.ClientId, connectedClient.ClientId); contactUpdate.Add.Add(connectedClient.ContactClient); } } Debug.Log("Trash clients count={0}.", clientList.Count); if (clientList.Count > 0) { contactUpdate.Remove.Add(clientList); } senderClient.SendMessage(MessageType.ContactUpdate, contactUpdate); } break; case MessageType.ContactUpdateChangeRequest: { ContactUpdateChangeRequest clientRequestedChange = ContactUpdateChangeRequest.Parser.ParseFrom(messageContent); var senderProfile = senderClient.Profile; if (senderProfile.Name != clientRequestedChange.Name || senderProfile.Surname != clientRequestedChange.Surname) { Debug.Log("Updating client data. This is not implemented on the client side. ;)"); } else if(senderProfile.Status != clientRequestedChange.Online) { senderProfile.Status = clientRequestedChange.Online; ContactUpdateStatus statusUpdate = new ContactUpdateStatus(); statusUpdate.Online = clientRequestedChange.Online; statusUpdate.ClientId = senderClient.ClientId; foreach (NetworkClient connectedClient in this.m_connectedClients) { // if (connectedClient.ClientId == senderClient.ClientId) continue; Debug.Log("Sending status update to ClientId={0}.", connectedClient.ClientId); connectedClient.SendMessage(MessageType.ContactUpdateStatus, statusUpdate); } } } break; /* Client Public Key request. */ case MessageType.MessageClientPublicRequest: { MessageRequestClientPublic requestMessage = MessageRequestClientPublic.Parser.ParseFrom(messageContent); PublicKey responseKey = null; foreach (NetworkClient connectedClient in this.m_connectedClients) { if (connectedClient.ClientId == requestMessage.ClientId) { responseKey = connectedClient.ClientPublic; } } if (responseKey != null) { MessageResponseClientPublic responseMessage = new MessageResponseClientPublic(); responseMessage.ClientId = requestMessage.ClientId; responseMessage.Key = responseKey; senderClient.SendMessage(MessageType.MessageClientPublicResponse, responseMessage); } else Debug.Warn("ClientId={0} has invalid public key."); } break; } }