AWS API Gateway UUID request validation

Viewed 907

I am trying to validate requests coming into API gateway by using the request validator to validate the body of the request. The JSON body which is expected just has one key which is "userId" and the value should be a UUID. I have setup my model like this:

{
  "$schema" : "http://json-schema.org/draft-04/schema#",
  "title" : "newUser",
  "type" : "object",
  "properties" : {
    "userId" : { 
        "type" : "string",
        "format" : "uuid"
    }
  }
}

After a few tests it seems to be working, it accepts a valid UUID and all of these correctly return a bad request:

{
    "userId": null
}

{
    "userId": "text"
}

{
    "userId": 123
}

{
    "userId": "8327a29c-7134-4566-8b58-"
}

{
    "userId": "8327a29c-7134-4566-8b58-46bcf951ef6az"
}

However if you remove a few characters or add a couple of valid hex characters to make it an invalid length then it will pass validation and forward on the request. What is the correct way of validating UUIDs using the request validator in API gateway which actually works?

1 Answers

After investigating more, uuid as a format isn't explicitly defined in the OpenAPI specification. Therefore implementation of format validation is not always consistent with every system. So I think the AWS validator implementation is a little bit funky.

The cleanest solution I have thought of is using regex like this:

{
  "$schema" : "http://json-schema.org/draft-04/schema#",
  "title" : "newUser",
  "type" : "object",
  "properties" : {
    "userId" : { 
        "type" : "string",
        "format" : "uuid",
        "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
    }
  }
}
Related