1010import io .github .easy4j .opencli .exception .OpenCliExecutableFailureException ;
1111import io .github .easy4j .opencli .exception .OpenCliNonZeroExitException ;
1212import io .github .easy4j .opencli .exception .OpenCliRemoteProtocolException ;
13+ import io .github .easy4j .opencli .exception .OpenCliRemoteResponseLimitException ;
1314import io .github .easy4j .opencli .meta .OpenCliExternalClient ;
1415import java .io .ByteArrayOutputStream ;
1516import java .io .IOException ;
1920import java .io .StringWriter ;
2021import java .net .InetSocketAddress ;
2122import java .nio .charset .StandardCharsets ;
23+ import java .time .Duration ;
2224import java .util .Arrays ;
2325import java .util .Scanner ;
2426import java .util .UUID ;
27+ import java .util .concurrent .CountDownLatch ;
28+ import java .util .concurrent .TimeUnit ;
2529import java .util .concurrent .atomic .AtomicInteger ;
2630import java .util .regex .Matcher ;
2731import java .util .regex .Pattern ;
32+ import java .util .zip .GZIPOutputStream ;
2833import org .junit .jupiter .api .Assertions ;
2934import org .junit .jupiter .api .Test ;
3035import org .junit .jupiter .params .ParameterizedTest ;
@@ -95,6 +100,132 @@ void collectFailureIncludesRawBodyWhenEnabled() throws IOException {
95100 }
96101 }
97102
103+ @ Test
104+ void permitsABodyAtTheByteLimitAndRejectsOneByteLess () throws IOException {
105+ String body = "{\" success\" :true,\" items\" :[\" 你好\" ]}" ;
106+ try (JsonCollectStub stub = JsonCollectStub .start (body )) {
107+ OpenCliProperties props = baseProps (stub .port ());
108+ props .setMaxRemoteResponseBytes (body .getBytes (StandardCharsets .UTF_8 ).length );
109+ props .setRemoteCaptureRawHttpResponse (true );
110+ try (OpenCliRemoteAgentHttpClient client = new OpenCliRemoteAgentHttpClient (props )) {
111+ OpenCliCollectRequest request = OpenCliCollectRequest .builder ().site ("npm" ).command ("search" ).build ();
112+ Assertions .assertEquals (body , client .collect (request ).getRemoteRawHttpBody ());
113+ props .setMaxRemoteResponseBytes (props .getMaxRemoteResponseBytes () - 1 );
114+ OpenCliRemoteResponseLimitException exception = Assertions .assertThrows (
115+ OpenCliRemoteResponseLimitException .class , () -> client .collect (request ));
116+ Assertions .assertEquals (200 , exception .getHttpStatus ());
117+ Assertions .assertEquals (props .getMaxRemoteResponseBytes (), exception .getMaxResponseBytes ());
118+ Assertions .assertNull (exception .getPartialResult ());
119+ props .setMaxRemoteResponseBytes (props .getMaxRemoteResponseBytes () + 1 );
120+ Assertions .assertEquals (body , client .collect (request ).getRemoteRawHttpBody ());
121+ }
122+ }
123+ }
124+
125+ @ ParameterizedTest
126+ @ ValueSource (ints = {200 , 503 })
127+ void stopsReadingOversizedChunkedBodiesWithoutWaitingForEof (int status ) throws IOException {
128+ CountDownLatch release = new CountDownLatch (1 );
129+ byte [] prefix = ("{\" success\" :true,\" items\" :[\" private-body-" + UUID .randomUUID ()).getBytes (StandardCharsets .UTF_8 );
130+ try (JsonCollectStub stub = JsonCollectStub .start (exchange -> {
131+ exchange .sendResponseHeaders (status , 0 );
132+ try (OutputStream output = exchange .getResponseBody ()) {
133+ output .write (prefix );
134+ output .flush ();
135+ try {
136+ release .await (10 , TimeUnit .SECONDS );
137+ } catch (InterruptedException interrupted ) {
138+ Thread .currentThread ().interrupt ();
139+ }
140+ }
141+ })) {
142+ try {
143+ OpenCliProperties props = baseProps (stub .port ());
144+ props .setMaxRemoteResponseBytes (24 );
145+ props .setCommandTimeoutMillis (8_000 );
146+ props .setRemoteCaptureRawHttpResponse (true );
147+ try (OpenCliRemoteAgentHttpClient client = new OpenCliRemoteAgentHttpClient (props )) {
148+ OpenCliCollectRequest request = OpenCliCollectRequest .builder ().site ("npm" ).command ("search" ).build ();
149+ OpenCliRemoteResponseLimitException exception = Assertions .assertTimeoutPreemptively (
150+ Duration .ofSeconds (3 ), () -> Assertions .assertThrows (
151+ OpenCliRemoteResponseLimitException .class , () -> client .collect (request )));
152+ Assertions .assertEquals (status , exception .getHttpStatus ());
153+ Assertions .assertEquals (24 , exception .getMaxResponseBytes ());
154+ Assertions .assertFalse (exception .getMessage ().contains ("private-body-" ));
155+ Assertions .assertNull (exception .getCause ());
156+ Assertions .assertNull (exception .getPartialResult ());
157+ Assertions .assertEquals (1 , stub .requests ());
158+ }
159+ } finally {
160+ release .countDown ();
161+ }
162+ }
163+ }
164+
165+ @ Test
166+ void capsDecodedGzipBodyRatherThanCompressedContentLength () throws IOException {
167+ StringBuilder body = new StringBuilder ("{\" success\" :true,\" items\" :[\" " );
168+ for (int i = 0 ; i < 500 ; i ++) {
169+ body .append ('a' );
170+ }
171+ body .append ("\" ]}" );
172+ ByteArrayOutputStream compressed = new ByteArrayOutputStream ();
173+ try (GZIPOutputStream gzip = new GZIPOutputStream (compressed )) {
174+ gzip .write (body .toString ().getBytes (StandardCharsets .UTF_8 ));
175+ }
176+ Assertions .assertTrue (compressed .size () < 128 );
177+ try (JsonCollectStub stub = JsonCollectStub .start (exchange -> {
178+ exchange .getResponseHeaders ().set ("Content-Encoding" , "gzip" );
179+ exchange .sendResponseHeaders (200 , compressed .size ());
180+ try (OutputStream output = exchange .getResponseBody ()) {
181+ compressed .writeTo (output );
182+ }
183+ })) {
184+ OpenCliProperties props = baseProps (stub .port ());
185+ props .setMaxRemoteResponseBytes (128 );
186+ try (OpenCliRemoteAgentHttpClient client = new OpenCliRemoteAgentHttpClient (props )) {
187+ OpenCliCollectRequest request = OpenCliCollectRequest .builder ().site ("npm" ).command ("search" ).build ();
188+ OpenCliRemoteResponseLimitException exception = Assertions .assertThrows (
189+ OpenCliRemoteResponseLimitException .class , () -> client .collect (request ));
190+ Assertions .assertTrue (exception .getMessage ().contains ("response body exceeded" ));
191+ }
192+ }
193+ }
194+
195+ @ Test
196+ void rejectsNonpositiveResponseLimitBeforeHttp () throws IOException {
197+ try (JsonCollectStub stub = JsonCollectStub .start ("{\" success\" :true}" )) {
198+ OpenCliProperties props = baseProps (stub .port ());
199+ props .setMaxRemoteResponseBytes (0 );
200+ try (OpenCliRemoteAgentHttpClient client = new OpenCliRemoteAgentHttpClient (props )) {
201+ OpenCliCollectRequest request = OpenCliCollectRequest .builder ().site ("npm" ).command ("search" ).build ();
202+ Assertions .assertThrows (IllegalArgumentException .class , () -> client .collect (request ));
203+ Assertions .assertEquals (0 , stub .requests ());
204+ }
205+ }
206+ }
207+
208+ @ Test
209+ void keepsDeclaredCharsetWithinTheResponseLimit () throws IOException {
210+ String body = "{\" success\" :true,\" items\" :[\" café\" ]}" ;
211+ byte [] bytes = body .getBytes (StandardCharsets .ISO_8859_1 );
212+ try (JsonCollectStub stub = JsonCollectStub .start (exchange -> {
213+ exchange .getResponseHeaders ().set ("Content-Type" , "application/json; charset=ISO-8859-1" );
214+ exchange .sendResponseHeaders (200 , bytes .length );
215+ try (OutputStream output = exchange .getResponseBody ()) {
216+ output .write (bytes );
217+ }
218+ })) {
219+ OpenCliProperties props = baseProps (stub .port ());
220+ props .setMaxRemoteResponseBytes (bytes .length );
221+ props .setRemoteCaptureRawHttpResponse (true );
222+ try (OpenCliRemoteAgentHttpClient client = new OpenCliRemoteAgentHttpClient (props )) {
223+ OpenCliCollectRequest request = OpenCliCollectRequest .builder ().site ("npm" ).command ("search" ).build ();
224+ Assertions .assertEquals (body , client .collect (request ).getRemoteRawHttpBody ());
225+ }
226+ }
227+ }
228+
98229 @ Test
99230 void nonSuccessHttpResponseDoesNotExposeBodyCanaryInException () throws IOException {
100231 String canary = "body-secret-" + UUID .randomUUID ();
@@ -307,6 +438,15 @@ static JsonCollectStub start(String jsonBody) throws IOException {
307438
308439 static JsonCollectStub start (String jsonBody , int status ) throws IOException {
309440 byte [] bytes = jsonBody .getBytes (StandardCharsets .UTF_8 );
441+ return start (exchange -> {
442+ exchange .sendResponseHeaders (status , bytes .length );
443+ try (OutputStream os = exchange .getResponseBody ()) {
444+ os .write (bytes );
445+ }
446+ });
447+ }
448+
449+ static JsonCollectStub start (HttpHandler response ) throws IOException {
310450 HttpServer server = HttpServer .create (new InetSocketAddress (0 ), 0 );
311451 JsonCollectStub stub = new JsonCollectStub (server , server .getAddress ().getPort ());
312452 server .createContext (
@@ -327,10 +467,7 @@ public void handle(HttpExchange exchange) throws IOException {
327467 exchange
328468 .getResponseHeaders ()
329469 .set ("Content-Type" , "application/json; charset=utf-8" );
330- exchange .sendResponseHeaders (status , bytes .length );
331- try (OutputStream os = exchange .getResponseBody ()) {
332- os .write (bytes );
333- }
470+ response .handle (exchange );
334471 }
335472 });
336473 server .start ();
0 commit comments