package io.hawt.web.filters; import jakarta.servlet.*; import jakarta.servlet.http.*; import java.io.*; import java.lang.reflect.*; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.util.*; import java.util.regex.Pattern; public final class HawtioUriRegression { static final String ROOT="/jolokia/exec/jdk.management.jfr:type=FlightRecorder/"; static final List results=new ArrayList<>(); static int passed,failed; interface Checked { void run() throws Exception; } static void check(boolean ok,String message) { if(!ok) throw new AssertionError(message); } static void test(String name,Checked body) { try { body.run(); passed++; results.add("{\"name\":\""+name+"\",\"passed\":true}"); } catch(Throwable e) { failed++; results.add("{\"name\":\""+name+"\",\"passed\":false,\"error\":\""+escape(e.toString())+"\"}"); } } static String escape(String s){return s.replace("\\","\\\\").replace("\"","\\\"").replace("\n","\\n").replace("\r","\\r");} static Object zero(Class t) { if(!t.isPrimitive()||t==void.class)return null; if(t==boolean.class)return false; if(t==char.class)return '\0'; if(t==long.class)return 0L; if(t==double.class)return 0D; if(t==float.class)return 0F; if(t==short.class)return (short)0; if(t==byte.class)return (byte)0; return 0; } static HttpServletRequest request(String method,String uri,String servlet) { return (HttpServletRequest)Proxy.newProxyInstance(HawtioUriRegression.class.getClassLoader(),new Class[]{HttpServletRequest.class},(p,m,a)->{ switch(m.getName()) { case "getMethod": return method; case "getRequestURI": case "getPathInfo": return uri; case "getRequestURL": return new StringBuffer("https://example.invalid"+uri); case "getServletPath": return servlet; case "getCharacterEncoding": return "UTF-8"; default:return zero(m.getReturnType()); } }); } static final class Response { final ByteArrayOutputStream bytes=new ByteArrayOutputStream(); final Map headers=new HashMap<>(); final ServletOutputStream stream=new ServletOutputStream(){ public void write(int b){bytes.write(b);} public boolean isReady(){return true;} public void setWriteListener(WriteListener listener){} }; final HttpServletResponse value=(HttpServletResponse)Proxy.newProxyInstance(HawtioUriRegression.class.getClassLoader(),new Class[]{HttpServletResponse.class},(p,m,a)->{ if(m.getName().equals("getOutputStream"))return stream; if(m.getName().equals("setHeader")){headers.put((String)a[0],(String)a[1]);return null;} if(m.getName().equals("getCharacterEncoding"))return "UTF-8"; return zero(m.getReturnType()); }); } static void passthrough(String method,String uri) throws Exception { HttpServletRequest req=request(method,uri,"/jolokia");Response res=new Response();int[] calls={0}; new FlightRecordingDownloadFacade().doFilter(req,res.value,(r,s)->{check(r==req&&s==res.value,"passthrough identity");calls[0]++;}); check(calls[0]==1,"one downstream call"); } static void download(String method,String servlet,String id,int error) throws Exception { String original=ROOT+"downloadRecording(long)/"+id; HttpServletRequest req=request(method,original,servlet);Response res=new Response(); List paths=new ArrayList<>();int[] reads={0}; FilterChain chain=(r,s)->{ HttpServletRequest changed=(HttpServletRequest)r;String path=changed.getRequestURI();paths.add(path); check(changed.getRequestURL().toString().equals("https://example.invalid"+path),"request URL rewrite"); check(changed.getPathInfo().equals(path),"path-info rewrite"); check(!path.contains("downloadRecording("),"operation replacement"); HttpServletResponse out=(HttpServletResponse)s; out.setCharacterEncoding("UTF-8");out.setStatus(error==1?503:200); String json; if(path.contains("/openStream(")){ check(path.equals(ROOT+"openStream(long,javax.management.openmbean.TabularData)/"+id+"/"+(servlet.equals("/proxy")?"%7B%7D":"{}")),"open-stream path"); json=error==2?"{\"status\":500,\"value\":null}":error==3?"{\"status\":200,\"value\":\"invalid\"}":"{\"status\":200,\"value\":7}"; } else if(path.equals(ROOT+"readStream(long)/7")) { json=++reads[0]==1?"{\"status\":200,\"value\":[65,66,67]}":"{\"status\":200,\"value\":null}"; } else {check(path.equals(ROOT+"closeStream(long)/7"),"close-stream path");return;} out.getOutputStream().write(json.getBytes(StandardCharsets.UTF_8)); }; boolean threw=false; try {new FlightRecordingDownloadFacade().doFilter(req,res.value,chain);} catch(IOException|ServletException e){threw=true;check(error>0,"unexpected failure "+e);} check(threw==(error>0),"expected backend error propagation"); if(error==0){ check(paths.size()==4&&reads[0]==2,"open/read/read/close flow"); check(Arrays.equals(res.bytes.toByteArray(),new byte[]{65,66,67}),"download bytes"); check(("attachment; filename=\"recording"+id+".jfr\"").equals(res.headers.get("Content-Disposition")),"download filename"); } } static final class Counted implements CharSequence { final String text;final long[] visits;final int start,end; Counted(String text){this(text,new long[]{0},0,text.length());} Counted(String text,long[] visits,int start,int end){this.text=text;this.visits=visits;this.start=start;this.end=end;} public int length(){return end-start;} public char charAt(int i){if(++visits[0]>1000000)throw new AssertionError("inspection cap");return text.charAt(start+i);} public CharSequence subSequence(int a,int b){return new Counted(text,visits,start+a,start+b);} public String toString(){return text.substring(start,end);} } static void complexity(int suffix) throws Exception { Field f=FlightRecordingDownloadFacade.class.getDeclaredField("recordingPattern");f.setAccessible(true); Pattern p=(Pattern)f.get(null);Counted input=new Counted("/application/status/"+"a".repeat(suffix)); check(!p.matcher(input).find(),"ordinary path must not match"); long budget=32L*input.length()+128; check(input.visits[0]<=budget,"character inspections "+input.visits[0]+" exceed linear budget "+budget); } public static void main(String[] args) throws Exception { test("ordinary GET passthrough",()->passthrough("GET","/application/status")); test("POST passthrough",()->passthrough("POST",ROOT+"downloadRecording(long)/42")); test("HEAD passthrough",()->passthrough("HEAD",ROOT+"downloadRecording(long)/42")); test("missing recording id passthrough",()->passthrough("GET",ROOT+"downloadRecording(long)/")); test("non HTTP passthrough",()->{ ServletRequest req=(ServletRequest)Proxy.newProxyInstance(HawtioUriRegression.class.getClassLoader(),new Class[]{ServletRequest.class},(p,m,a)->zero(m.getReturnType())); Response res=new Response();int[] n={0};new FlightRecordingDownloadFacade().doFilter(req,res.value,(r,s)->{check(r==req,"request identity");n[0]++;});check(n[0]==1,"one chain call"); }); test("local recording download",()->download("GET","/jolokia","42",0)); test("proxy map argument encoding",()->download("GET","/proxy","42",0)); test("case insensitive GET",()->download("get","/jolokia","42",0)); test("recording id zero",()->download("GET","/jolokia","0",0)); test("HTTP backend error",()->download("GET","/jolokia","42",1)); test("Jolokia backend error",()->download("GET","/jolokia","42",2)); test("invalid stream reference",()->download("GET","/jolokia","42",3)); for(int size:new int[]{64,128,256})test("ordinary path inspection budget "+size,()->complexity(size)); String json="{\"suite\":\""+escape(args[0])+"\",\"passed\":"+passed+",\"failed\":"+failed+",\"total\":"+(passed+failed)+",\"results\":["+String.join(",",results)+"]}"; Files.writeString(Path.of(args[1]),json+"\n");System.out.println(json);if(failed>0)System.exit(1); } }