Vertx: How to verify auth before handle body request? - vert.x

How to verify auth before handle body request?
I'm using vertx:
vertxVersion = '3.8.3'
implementation "io.vertx:vertx-core:$rootProject.vertxVersion"
implementation "io.vertx:vertx-web:$rootProject.vertxVersion"
implementation "io.vertx:vertx-lang-kotlin:$rootProject.vertxVersion"
implementation "io.vertx:vertx-lang-kotlin-coroutines:$rootProject.vertxVersion"
implementation "io.vertx:vertx-mongo-client:$rootProject.vertxVersion"
implementation "io.vertx:vertx-auth-mongo:$rootProject.vertxVersion"
implementation "io.vertx:vertx-auth-jwt:$rootProject.vertxVersion"
I want to verify auth before handle body request. But I got error java.lang.IllegalStateException: Request has already been read
Reproduce by use delay on suspend function:
router.handler { context ->
launch {
context.request().setExpectMultipart(true)
delay(100) //This line is sample for a verify auth process
context.next()
}
}
.handler {context ->
println("2")
context.request()
.handler {
b -> println("buff ${b.length()}")
}
.endHandler {
println("end handle")
context.success("ok")
}
}.baseHandle(
fn
).failureHandler {
println("fail: ${it.failure()}")
it.error()
}
When run delay(100) (this's sample for a verify process), I got the error above. If I comment delay(100), It's will be working fine.

This happens because by the time you auhenticated the request, the content has kept arriving and has been dropped.
You need to invoke context.request().pause() in you first handler and then context.request().resume() when you're ready.
In most cases though it's easier to let the BodyHandler manage payload for you.

Finally, I did solve it.
My router is working with the flows:
router.post("/api/upload/file")
.baseHandle { checkAuthorization(it) }
.handleFileUpload { updateFileOnItem(it) }
And Following step:
fun checkAuthorization(context: RoutingContext) {
val request = context.request()
val tkCookie = request.getCookie("user")
...do something to verify user permission
request.pause()
context.next()
context.request().resume()
}
Next:
fun updateFileOnItem(context: RoutingContext) {
val file = context.fileUploads()
...do something
}
It's working with me. Hope it can be help you. Thanks!

Related

cannot get rest service

This drives me crazy, I have 2 http requests in a sample application:
open class RestController : Controller() {
val api = Rest()
init {
api.baseURI = "http://127.0.0.1:5059/"
}
}
class PendingCtlr : RestController() {
fun load(): ObservableList<PendingEntity> {
val txt = api.get("pendings").list()
val temp = txt.toModel<PendingEntity>()
return temp.observable()
}
}
class ConfirmedCtrl : RestController() {
fun load(id: Long): ObservableList<ConfirmedEntity> {
val li= api.get("confirmeds").list()
val temp = li.toModel<ConfirmedEntity>()
return temp.observable()
}
}
The first one works, the second one doesn't even hit the application level, it gets rejected with 400 BadRequest by my backend (Werkzeug).
I see absolutely no difference in both functions, and I can call both routes from my Swagger, as well as from python as well as from curl! Could someone please advise at least where to look for debug?
EDIT: The problem was on server side -_- Solved

Keycloack admin client hangs when attempting to make requests

I'm trying to get some user data out of Keycloack using the admin-client SDK. I've built the client like so:
Keycloak kc = KeycloakBuilder.builder() //
.serverUrl("some_url")
.realm("some-realm")
.username("admin") //
.password("password") //
.clientId("curl")
.resteasyClient(new ResteasyClientBuilder().connectionPoolSize(10).connectionCheckoutTimeout(10, TimeUnit.SECONDS).build()) //
.build();
System.out.println("built");
UsersResource baz = kc.realm(keycloakConfiguration.getRealm()).users();
System.out.println(baz.count());
What seems to happen is that my program hangs indefinitely when attempting to fetch baz - my debugger never hits it. I'm not quite sure what's going on - my credentials are correct. What is the correct way to cause the builder to either 1. fail after a certain time period, or 2.verify that my credentials are correct? It's maddeninly frustrating to debug.
You could create a custom method to check if you client is "online". This method could look like:
public boolean isKeycloakClientValid(Keycloak keycloakClient) {
try {
tryToPingKeycloak(keycloakClient);
} catch (Exception e) {
logger.error("Error while pinging the keycloak server", e);
return false;
}
return true;
}
With the help method:
private void tryToPingKeycloak(KeycloakClient keycloakClient) {
keycloakClient.serverInfo().getInfo();
}
Now you could check your client before using it:
if (isKeycloakClientValid(kc)) {
UsersResource baz = kc.realm(keycloakConfiguration.getRealm()).users();
}

Spray route rejections

I am building some custom directives with Spray and I find a problem:
When a route is rejected I thought that it was immediately completed with a rejection. However it is not and it tries to complete the inner route. For example, in this code:
path("users") {
post {
entity(as[User]){
user =>
directive_always_reject(){
println("Hello")
complete(200, "Hello")
}
}
}
}
The "hello" is always printed, even if the directive is rejected.
I always thought that when a route is rejected it does not continue to inner routes (or at least is how I understand it)
Did I misunderstand something with Spray or there is a bug somewhere in my code?
Thanks you!
[UPDATE 1]
An implementation of directive_always_reject() could be:
def directive_always_reject[T]() : Directive0 = {
reject(
new ValidationRejection("Some error")
)
}
[UPDATE 2]
I see that a solution could be put the println inside the complete function.
path("users") {
post {
entity(as[User]){
user =>
directive_always_reject(){
complete {
println("Hello")
"Hello"
}
}
}
}
}
However this solution does not apply to me because in my real code I pass the RequestContext to another actor who is the one that completes the request.

Execute some logic asynchronously in spray routing

Here is my simple routing application:
object Main extends App with SimpleRoutingApp {
implicit val system = ActorSystem("my-system")
startServer(interface = "0.0.0.0", port = System.getenv("PORT").toInt) {
import format.UsageJsonFormat._
import spray.httpx.SprayJsonSupport._
path("") {
get {
complete("OK")
}
} ~
path("meter" / JavaUUID) {
meterUUID => pathEnd {
post {
entity(as[Usage]) {
usage =>
// execute some logic asynchronously
// do not wait for the result
complete("OK")
}
}
}
}
}
}
What I want to achieve is to execute some logic asynchronously in my path directive, do not wait for the result and return immediately HTTP 200 OK.
I am quite new to Scala and spray and wondering if there is any spray way to solve this specific problem. Otherwise I would go into direction of creating Actor for every request and letting it to do the job. Please advice.
There's no special way of handling this in spray: simply fire your async action (a method returning a Future, a message sent to an actor, whatever) and call complete right after.
def doStuffAsync = Future {
// literally anything
}
path("meter" / JavaUUID) { meterUUID =>
pathEnd {
post {
entity(as[Usage]) { usage =>
doStuffAsync()
complete("OK")
}
}
}
}
Conversely, if you need to wait for an async action to complete before sending the response, you can use spray-specific directives for working with Futures or Actors.

concurrent requests limit of Twitter-Finagle

I create a thrift server using Finagle like this
val server = Thrift.serveIface(bindAddr(), new MyService[Future] {
def myRPCFuction() {}
})
But, I found that the maximum number of concurrent requests is five( why 5? when more than 5, the server just ignore the excessed ones.) I look through the doc of Finagle really hard (http://twitter.github.io/finagle/guide/Protocols.html#thrift-and-scrooge), but find nothing hint to configure the max-request-limit.
How to config the maximum concurrent request num of Finagle? Thanks
I've solved this problem by myself and I share it here to help others who may run into the same case. Because I m a thrift user before and in Thrift when you return from the RPC function you return the values back to calling client. While in Finagle only when you use Future.value() you return the value to client. And when use Finagle, you should totally use the asynchronous way, that's to say you had better not sleep or do some other RPC synchronously in the RPC function.
/* THIS is BAD */
val server = Thrift.serveIface(bindAddr(), new MyService[Future] {
def myRPCFuction() {
val rpcFuture = rpcClient.callOtherRpc() // call other rpc which return a future
val result = Await.result(rpcFuture, TwitterDuration(rpcTimeoutSec()*1000, MILLISECONDS))
Future.value(result)
}
})
/* This is GOOD */
val server = Thrift.serveIface(bindAddr(), new MyService[Future] {
def myRPCFuction() {
val rpcFuture = rpcClient.callOtherRpc() // call other rpc which return a future
rpcFuture onSuccess { // do you job when success (you can return to client using Future.value) }
rpcFuture onFailure { // do your job when fail }
}
})
Then, can get a satisfactory concurrency. Hope it helps others who have the same issue.