Introduction
When I was playing around with my pet-project
Kyiv Station Walk, I noticed that manually removing test data is tedious and I need to come up with a concept of the admin page. This required some sort of authentication endpoint, some super-lightweight service that would check login and password against a pair of super-user credentials.
Serverless is quite useful for this simple nano service. This brings some cost-saving as serverless comes to me almost free due to the low execution rate that I anticipate for the admin page of my low-popular service. Also, I would argue that this brings me some architectural benefit because it allows me to split my core domain from cross-cutting concern. For my task, I’ve decided to use AWS Lambda. I’ve also decided to use Go, due to its minimalistic nature which would be useful for Lambda instantiation.
Setup
Our lambda function is to be called from outside over HTTP, so we place the HTTP Gateway in front of it so it would look something like below in the AWS Console.
Authentication
For our purposes, we’ll omit the usage of persistent storage since one pair of credentials is enough. Still, we need to hash stored password in with the hash function which will allow for the defender to verify password in acceptable time, but will require a lot of resources for an attacker to guess a password from the hash. Argon2
is recommended for such a task. So to start off, we’ll need the
"github.com/aws/aws-lambda-go/lambda"
package.
Argon2 is implemented in
"golang.org/x/crypto/argon2",
so the authentication is quite straightforward.
- func HandleRequest(ctx context.Context, credentials Credentials) (string, error)
-
-
- if credentials.Login != login
-
-
- key := argon2.Key([]byte(credentials.Password), []byte(salt), 3, 128, 1, 32)
- if areSlicesEqual(key, password)
-
-
- return "auth failed", errors.New("auth failed")
- }
Note how for both wrong login and incorrect password we’re returning the same message in order to disclose as little information as possible. This allows us to prevent an account enumeration attack.
Building it:
- go build -o main main.go
- And zipping it
- ~\Go\Bin\build-lambda-zip.exe -o main.zip main
Leveraging environment variables
You can leverage environment variables instead with the help of an os
package.
- login := os.Getenv("LOGIN")
- salt := os.Getenv("SALT")
Here’s how you set them up in an AWS console:
JWT Generation
Once the service verifies that credentials are valid, it issues a token that allows it’s bearer to act as a super-user. For this purpose, we’ll use
JWT which is a de-facto standard format for access tokens.
We’ll need the following package:
- "github.com/dgrijalva/jwt-go"
The JWT generation code looks like the following:
- type Claims struct
-
-
-
-
- func issueJwtToken(login string) (string, error)
-
-
-
-
-
-
-
-
- ,
- }
- token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
- return token.SignedString(jwtKey)
- }
Since an adversary who intercepts such token may act on behalf of super-user, we don’t want this token to be effective infinitely because this will grant adversary infinite privileges. So, we set the token expiration time for one hour.
Integration with API gateway
It turns out that our endpoint is not yet ready to be consumed from the outside, because we have to provide the response of a special format for API gateway. To fix this, let's install github.com/aws/aws-lambda-go/events
package.
Here’s an example of a successful response:
- events.APIGatewayProxyResponse
-
-
-
Now our API is ready to be consumed. Here’s a brief snippet from the main service that deletes a route only if the user has sufficient rights.
- let delete (id: string) =
- fun (next: HttpFunc) (httpContext : HttpContext) ->
- let result =
- AuthApi.authorize httpContext
- |> Result.bind (fun _ -> ElasticAdapter.deleteRoute id)
- match result with
- | Ok _ -> text "" next httpContext
- | Error "ItemNotFound" -> RequestErrors.BAD_REQUEST "" next httpContext
- | Error "Forbidden" -> RequestErrors.FORBIDDEN "" next httpContext
- | Error _ -> ServerErrors.INTERNAL_ERROR "" next httpContext
-
- let authorize (httpContext : HttpContext) =
- let authorizationHeader = httpContext.GetRequestHeader "Authorization"
- let authorizationResult =
- authorizationHeader
- |> Result.bind JwtValidator.validateToken
- authorizationResult
-
- let validateToken (token: string) =
- try
- let tokenHandler = JwtSecurityTokenHandler()
- let validationParameters = createValidationParameters
- let mutable resToken : SecurityToken = null
- tokenHandler.ValidateToken(token, validationParameters, &resToken)
- |> ignore
- Result.Ok()
- with
- | _ -> Result.Error "Forbidden"
Minimizing attack surface
At this point, our function is open to some vulnerabilities, so we have to perform some additional work on our API gateway.
Endpoint throttling
The default settings are too high for authorization function that is not expected to be invoked often. Let’s change this.
IP whitelist
We also don't want our function to be accessible from any IP possible. The following snippet in the “Resource policy” API gateway settings section allows us to create a whitelist of IP addresses that can access our lambda.
In order to obtain ARN, we can navigate back to the Lambda configuration page and check it by clicking on the API Gateway icon.
Conclusion
Serverless is a great option for small-ish nanoservices. Due to its minimalistic philosophy, Go is suitable not only for applications that leverage sophisticated concurrency, but also for simple operations such as the one described above.