[ 
https://issues.apache.org/jira/browse/TINKERPOP-2480?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17634841#comment-17634841
 ] 

ASF GitHub Bot commented on TINKERPOP-2480:
-------------------------------------------

divijvaidya commented on code in PR #1838:
URL: https://github.com/apache/tinkerpop/pull/1838#discussion_r1023972230


##########
gremlin-driver/src/test/java/org/apache/tinkerpop/gremlin/driver/WebSocketClientBehaviorIntegrateTest.java:
##########
@@ -88,6 +89,44 @@ public void shutdown() {
         rootLogger.removeAppender(recordingAppender);
     }
 
+    /**
+     * Tests that client is correctly sending user agent during web socket 
handshake by having the server return
+     * the captured user agent.
+     */
+    @Test
+    public void shouldIncludeUserAgentInHandshakeRequest() {

Review Comment:
   Please add the following test scenarios:
   
   1. Validate that the user agent is sent only once per WebSocket connection.



##########
gremlin-server/src/main/java/org/apache/tinkerpop/gremlin/server/handler/WsUserAgentHandler.java:
##########
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.server.handler;
+
+import com.codahale.metrics.MetricRegistry;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.handler.codec.http.HttpHeaders;
+import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
+import io.netty.util.AttributeKey;
+import org.apache.tinkerpop.gremlin.driver.util.UserAgent;
+import org.apache.tinkerpop.gremlin.server.GremlinServer;
+import org.apache.tinkerpop.gremlin.server.util.MetricManager;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Channel handler which extracts a user agent header from a web socket 
handshake if present
+ * then logs the user agent and stores it as a channel attribute for future 
reference.
+ */
+public class WsUserAgentHandler extends ChannelInboundHandlerAdapter {
+
+    private static final Logger logger = 
LoggerFactory.getLogger(WsUserAgentHandler.class);
+    public static final AttributeKey<String> USER_AGENT_ATTR_KEY = 
AttributeKey.valueOf(UserAgent.USER_AGENT_HEADER_NAME);
+
+    @Override
+    public void userEventTriggered(ChannelHandlerContext ctx, java.lang.Object 
evt){
+        if(evt instanceof WebSocketServerProtocolHandler.HandshakeComplete){
+            final HttpHeaders requestHeaders = 
((WebSocketServerProtocolHandler.HandshakeComplete) evt).requestHeaders();
+
+            if(requestHeaders.contains(UserAgent.USER_AGENT_HEADER_NAME)){
+                final String userAgent = 
requestHeaders.get(UserAgent.USER_AGENT_HEADER_NAME);
+
+                ctx.channel().attr(USER_AGENT_ATTR_KEY).set(userAgent);
+                logger.debug(String.format("New Connection on channel [%s] 
with user agent [%s]", ctx.channel().id().asShortText(), userAgent));

Review Comment:
   I would recommend to use [slf4j's parameterized format for logging 
with](https://www.slf4j.org/faq.html#logging_performance) `{}`. That form 
ensures that the arguments in the log line are not evaluated is the log level 
is not satisfied. In the correct scenario, String.format() will always be 
calculated irrespective of the logging level set for the server.
   
   Same comment for other log lines.



##########
docs/src/dev/provider/index.asciidoc:
##########
@@ -848,6 +848,14 @@ Server returns for a single request.  Again, this 
description of Gremlin Server'
 out-of-the-box configuration.  It is quite possible to construct other flows, 
that might be more amenable to a
 particular language or style of processing.
 
+It is recommended but not required that a driver include a `User-Agent` header 
as part of any web socket

Review Comment:
   What are the side effects of enabling it? We should help the users make this 
decision. Please add a jmh benchmark for handshake w/ and w/o the user agent. 
User agent will add additional latency to the handshake and hence, connection 
setup will be slower but by how much?



##########
gremlin-driver/src/main/java/org/apache/tinkerpop/gremlin/driver/util/UserAgent.java:
##########
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.driver.util;
+
+import org.apache.tinkerpop.gremlin.util.Gremlin;
+import javax.naming.NamingException;
+
+public class UserAgent {
+
+    /**
+     * Request header name for user agent
+     */
+    public static final String USER_AGENT_HEADER_NAME = "User-Agent";
+    /**
+     * User Agent body to be sent in web socket handshake
+     * Has the form of:
+     * [Application Name] [GLV Name]/[Version] [Language Runtime Version] 
[OS]/[Version] [CPU Architecture]
+     */
+    public static final String WS_HANDSHAKE_USER_AGENT;
+
+    static {
+        String applicationName = "";
+        try {
+            applicationName = ((String)(new 
javax.naming.InitialContext().lookup("java:app/AppName"))).replace(' ', '_');
+        } catch (NamingException e) {
+            applicationName = "NotAvailable";
+        };
+
+        final String glvVersion = Gremlin.version().replace(' ', '_');
+        final String javaVersion = System.getProperty("java.version", 
"NotAvailable").replace(' ', '_');

Review Comment:
   The information on how to configure the user agent is missing in 
documentation. We should add the information that the user agent is constructed 
from System Properties and could be overridden/set by using `-D`.



##########
gremlin-driver/src/main/java/org/apache/tinkerpop/gremlin/driver/util/UserAgent.java:
##########
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.driver.util;
+
+import org.apache.tinkerpop.gremlin.util.Gremlin;
+import javax.naming.NamingException;
+
+public class UserAgent {

Review Comment:
   From an implementation perspective, we need to decouple the code which 
generates the UserAgent from the code that models the UserAgent. The former 
will reside in `gremlin-driver` and other drivers will write a similar 
implementation for themselves but the latter will reside in server and server 
will use it to represent and parse UserAgent coming from different language 
drivers on both WS and HTTP.



##########
gremlin-server/src/main/java/org/apache/tinkerpop/gremlin/server/channel/WebSocketChannelizer.java:
##########
@@ -108,7 +109,7 @@ public void configure(final ChannelPipeline pipeline) {
                 
closeOnProtocolViolation(false).allowExtensions(true).maxFramePayloadLength(settings.maxContentLength).build();
         pipeline.addLast(PIPELINE_REQUEST_HANDLER, new 
WebSocketServerProtocolHandler(GREMLIN_ENDPOINT,
                 null, false, false, 10000L, wsDecoderConfig));
-
+        pipeline.addLast("ws-user-agent-handler", new WsUserAgentHandler());

Review Comment:
   This handler should go "after" authN has taken place. Else an attacker may 
perform a DoS attack by sending unauthenticated large string in user agent. 



##########
gremlin-server/src/main/java/org/apache/tinkerpop/gremlin/server/channel/WebSocketChannelizer.java:
##########
@@ -108,7 +109,7 @@ public void configure(final ChannelPipeline pipeline) {
                 
closeOnProtocolViolation(false).allowExtensions(true).maxFramePayloadLength(settings.maxContentLength).build();
         pipeline.addLast(PIPELINE_REQUEST_HANDLER, new 
WebSocketServerProtocolHandler(GREMLIN_ENDPOINT,
                 null, false, false, 10000L, wsDecoderConfig));
-
+        pipeline.addLast("ws-user-agent-handler", new WsUserAgentHandler());

Review Comment:
   Please create a JIRA to implement this for HTTP calls as well.





> User agent for Gremlin drivers
> ------------------------------
>
>                 Key: TINKERPOP-2480
>                 URL: https://issues.apache.org/jira/browse/TINKERPOP-2480
>             Project: TinkerPop
>          Issue Type: Improvement
>          Components: driver, server
>    Affects Versions: 3.4.8
>            Reporter: Divij Vaidya
>            Priority: Minor
>
> Currently, a server does not distinguish amongst the different types of 
> clients connecting to it. This issue is to add a new feature to add user 
> agent field in the HTTP and WebSocket request header which could be used to 
> identify the specific client from which the request was made.



--
This message was sent by Atlassian Jira
(v8.20.10#820010)

Reply via email to