Restricting IP addresses for Jetty and Solr

Lyndsay picture Lyndsay · Jan 19, 2012 · Viewed 17k times · Source

I'm setting up Solr using Jetty. I would like to restrict access to only a few IP addresses. It doesn't seem immediately obvious that this can be done using Jetty. Is it possible and if so, how?

Answer

krivard picture krivard · May 17, 2013

Solr 4.2.1 uses Jetty 8.1.8. Jetty 8 (as noted by jonas789) doesn't support .htaccess. Instead, it uses IPAccessHandler, which doesn't have great documentation available. I had to play with it quite a bit to get it work, so I'm posting an updated solution here.

IPAccessHandler manages a blacklist and a whitelist, accepts arbitrary ranges of IPs, and supports attaching specific URI paths to each white/black -list entry. IPAccessHandler also subclasses HandlerWrapper, which turns out to be important.

The solr app still lives in a WebAppContext (as in Lyndsay's solution), but a WebAppContext is now governed by a ContextHandler, which resides in a ContextHandlerCollection occupying the first handler slot in the server. To stop requests from the wrong IP from getting to the app, we need to wrap it inside an IPAccessHandler somewhere along that path. IPAccessHandler behaves oddly if it's in the wrong spot: I tried inserting it before the context handlers and it gave 403 Forbidden to the wrong machines, threw NullPointerException tantrums with no additional error messages, all sorts of nonsense. I finally got it to work by wrapping the ContextHandlerCollection itself, at the server level.

Go to etc/jetty.xml and scroll to the handlers section. Then wrap the existing ContextHandlerCollection item as follows:

<!-- =========================================================== -->
<!-- Set handler Collection Structure                            --> 
<!-- =========================================================== -->
<Set name="handler">
  <New id="Handlers" class="org.eclipse.jetty.server.handler.HandlerCollection">
    <Set name="handlers">
     <Array type="org.eclipse.jetty.server.Handler">
   <Item>

     <!-- here begins the new stuff -->
     <New class="org.eclipse.jetty.server.handler.IPAccessHandler">
       <Call name="addWhite">
         <Arg>xxx.xxx.xxx.xxx</Arg>
       </Call>
       <Set name="handler">
         <!-- here's where you put what was there before: -->
         <New id="Contexts" class="org.eclipse.jetty.server.handler.ContextHandlerCollection"/>
       </Set>
     </New>
     <!-- here ends the new stuff -->

   </Item>
       <Item>
         <New id="DefaultHandler" class="org.eclipse.jetty.server.handler.DefaultHandler"/>
       </Item>
       <Item>
         <New id="RequestLog" class="org.eclipse.jetty.server.handler.RequestLogHandler"/>
       </Item>
     </Array>
    </Set>
  </New>
</Set>

Resources: