Extend proxy to support mocking of certain requests
Is it possible to create proxy server which passes all requests to its original destinations except implicitly configured rules?
I.e., I have configuration file "mockserver.js" with next mock:
var mockServer = require('mockserver-client'),
mockServerClient = mockServer.mockServerClient;
mockServerClient("localhost", 1080).mockAnyResponse({
"httpRequest": {
"method": "GET",
"path": "/somePath",
"headers": [
{
"name": "Host",
"values": "google.com"
}
]
},
"httpResponse": {
"statusCode": 200,
"body": "hello world"
},
"times": {
"unlimited": true
}
});
Then, I run server:
java -jar mockserver-netty-3.10.4-jar-with-dependencies.jar -serverPort 1080 -proxyPort 1090
, run configuration code, configure proxy and send request:
node mockserver.js
export http_proxy=http://localhost:1090
wget http://google.com/somePath
Proxy server ignores rule defined above, forwards request to google, and I receive 404 result.
Perhaps "values": "google.com" should be "values": ["google.com"] ?
No, this didn't help. The most interesting is that, with my configuration, when I send request directly to localhost:1080, it works properly. But when I try to use it as forward proxy, it ignores this rule.
I would also be very interested to discover how to do that.
The scenario is quite simple:
- I specify explicit expectations with their proper responses (to mock certain HTTP calls)
- But, I want that the mockserver forwards ALL other HTTP calls to their original destination without even touching it.
This is what I've tried:
mockServer
.when(
request()
.withMethod("PUT")
.withPath("/certain/call")
.withHeader("User-Agent", "TestServer")
.withHeader("Host", someHost)
)
.respond(
response()
.withStatusCode(502)
.withHeader("Server", "TestServer")
.withDelay(new Delay(TimeUnit.SECONDS, 5))
);
mockServer
.when(
request()
)
.forward(
forward()
);
But this did not work, since the forward expect some other parameters, like, e.g., the host. In this case, the host depends on the request... so, if the request has "google.com" as the host, I would need to be aware of that on the forward() scope... :-(
Is there way of doing it?
I'm also interested in operating MockServer in that mode. It would be wonderfully useful!
As I understand, this is not possible due to the way all HTTP clients work and HTTP requests work.
There are two separate concepts that are distinct in networking, as follows:
- destination server (i.e. Host header) - If you want to send a request directly somewhere you specify the host (and port). In this scenario the destination server is the final place the request is going to. If you configure your HTTP client to send a request to MockServer so it can response to a mock then the HTTP request is created by the HTTP client such that MockServer is the final destination and there is no way to tell where you may have actually wanted to send the request (as in your example about).
- proxy server - If you want your client to send requests via somewhere you have to configure a proxy server in your HTTP client. The proxy server is then provided the information about where you request was originally trying to get to. If you configure your HTTP client to send request via the MockServer Proxy then the HTTP client constructs the interaction in such as way that the MockServer Proxy can tell (via the Host header) where the request's final destination is.
These are two separate concepts thus the reason why there are two parts to MockServer:
- the main part (i.e. serverPort) that response to expectations as if it was the destination server, and
- the proxy (i.e. proxyPort) that can record requests and forward then onwards
To attempt to bridge the gap within the constraints of what HTTP will support the forward expectation was introduced. However you have to provide the information about where to forward a request as that is not passed in the original request constructed by your client, so there is no way for the MockServer to know where you finally intend for that request to go to.
The only way to work around these constraints would be to make the MockServer a network switch / router that would need to be installed in your building infrastructure (or whoever administers your local network). This would be massive overkill as such a component would listen to all internet traffic for all users on your local network.
I'm going to close this ticket as MockServer can only work within the limitations of HTTP. Please re-open or raise a new issue if you have additional comments or feel there is something that I have missed.
Hacky Workaround
To make this work using the MockServer there is an approach as detailed below to work around how HTTP works. However I would not recommend this approach due to the issues / limitations I list at the bottom.
A. Configure Hosts File
The host file used for local domain to IP mapping will need to be modify so all requests on the machine runnings the tests will be sent to MockServer. This makes this approach not suitable for build servers, etc.
To do this setup your hosts file so that there is an entry for every domain you are send a request to. Each entry should map that domain to 127.0.0.1 (i.e. your local machine on the assumption MockServer is running locally, if not replace 127.0.0.1 with the IP address of the machine running MockServer.
On Mac or Linux the file you need to edit is /etc/hosts
On Windows that file is typically C:\Windows\System32\drivers\etc\hosts
The file should look roughly as follows:
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
127.0.0.1 some.random.endpoint
127.0.0.1 another.random.endpoint
The entries some.random.endpoint and another.random.endpoint should how each domain you want to route via MockServer should look.
B. Launch MockServer
Launch MockServer configuring ports 80 and 443 both as a serverPort as below.
Note: your'll need to launch your process as privileged application because any application attempting to bind to ports lower the 1024 needs privileged rights. For more information see google, for example allow-non-root-process-to-bind-to-port-80-and-443.
sudo java -jar mockserver-netty-3.10.7-jar-with-dependencies.jar -serverPort 80,443
Or
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
...
startClientAndServer(80, 443)
Unfortunately currently it is not possible to configure the Maven plugin directly with multiple ports, but you could do this as follows:
<plugin>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-maven-plugin</artifactId>
<version>3.10.7</version>
<configuration>
<serverPort>80</serverPort>
</configuration>
</plugin>
Then add an additional port by sending a PUT request to http://localhost:80/bind with the following body:
{
"ports": [
443
]
}
i.e. as a curl it would be curl -X PUT 'http://localhost:80/bind' -d "{ 'ports': [ 443 ] }"
C. Setup Mock Expectations
Setup mocks for all request you want to specifically mock. You need to set these up first then you can add forward expectations (next step) to handle any request that you are not explicitly mocking.
D. Setup Forward Expectations
Add a forward expectation twice (port 80 & port 433) for each domain your want to forward requests to. Any request that has not been already handled by a mock expectation (previous step) will fall through to these catch-all expectations and so will be forwarded to the IP address you specify.
Note: your'll need to know the IP address that each domain normally resolves to, as in the step A above you re-routed all request on you local machine for that domain to you local machine. If you just used the domain name instead of the IP address you would cause an infinite loop.
mockServerClient
.when(
request()
.withHeader("Host", "some.random.endpoint")
.withSecure(false),
unlimited()
)
.forward(
forward()
// "some.random.endpoint"'s actual IP address
.withHost("123.123.123.123")
.withPort(80)
.withScheme(HTTP)
);
mockServerClient
.when(
request()
.withHeader("Host", "some.random.endpoint")
.withSecure(true),
unlimited()
)
.forward(
forward()
// "some.random.endpoint"'s actual IP address
.withHost("123.123.123.123")
.withPort(443)
.withScheme(HTTPS)
);
var mockServerClient = mockServerClient("localhost", 80);
mockServerClient.mockAnyResponse(
{
'httpRequest': {
'headers': [
{
'name': 'Host',
'values': ['some.random.endpoint']
}
]
},
'httpForward': {
'host': '123.123.123.123', // "some.random.endpoint"'s actual IP address
'port': 80,
'scheme': 'HTTP'
},
'times': {
'unlimited': true
}
}
).then(function () {
mockServerClient("localhost", 80).mockAnyResponse(
{
'httpRequest': {
'headers': [
{
'name': 'Host',
'values': ['some.random.endpoint']
}
]
},
'httpForward': {
'host': '123.123.123.123', // "some.random.endpoint"'s actual IP address
'port': 443,
'scheme': 'HTTPS'
},
'times': {
'unlimited': true
}
}
).then(function () {
// do something
}, function (error) {
// handle error
});
}, function (error) {
// handle error
});
Notes / Issues
- sudo / privileged access - MockServer will need to be launched as a privileged / root application because it will need to bind to ports below 1024.
- hosts file - The host file used for local domain to IP mapping will need to be modify so all requests on the machine runnings the tests will be sent to MockServer. This makes this approach not suitable for build servers, etc.
Hi James, and thank you for your answer.
I think I didn't explained myself well enough: my wish is to be able to setup Mock Server in proxy mode, and also instruct it "look, you should proxy all requests as usual, but for the ones I will setup expectations. Only for those requests, you must not forward them as you have done normally, but you must answer my precanned response instead"
Do you think that would be doable?
I think it would be technically doable, but it is probably a fairly big undertaking because all the client and integration test scenarios would need to be implemented.
I do agree it could be a good idea to implement this, although I'll have to finish some other issues / bugs first.
This is a duplicate of #257. I have now implemented support for mocking certain requests in the proxy. If no matching expectations are set then the request will be proxied. Closing this issue as this is now completed.