-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
VEGA-2105 Add JWT verification #minor (#54)
* Install jwt library * Add testify package * Add tests for jwt verification * Implement (most of the) jwt verification * Add test to validate JWT subject based on issuer Assumption at present is that the UID for MRLPA will be at least a one character string. * Implement JWT subject verification based on issuer * Add tests for constructing a JWTVerifier from env * Implement JWTVerifier which can be constructed from env * Incorporate verifier into create lambda * Wire up JWT verification to create lambda * Add JWT_SECRET_KEY variable to Makefile * Modify api-test/tester to send JWT header * Use X-Jwt-Authorization header for now to avoid clashes with AWS Authorization header (added by signer) * Expose JWT_SECRET_KEY as env var to create lambda * Add method for parsing a value out of an incoming event header * Log incoming JWT, whether verified or error * Move header parsing out of lambda Hopefully makes it slightly more reusable. * Add JWT verification to get and update lambdas * Move header-related code to VerifyHeader() * Add unit tests for VerifyHeader() * Tabs, not spaces * Hard-code test JWT secret * Reject requests with a 401 if JWT cannot be verified * Add API tests for 401 from each lambda * Show a bit more detail about API tests now there are more Makes it easier to figure out which test failed (if any). --------- Co-authored-by: Elliot Smith <[email protected]>
- Loading branch information
1 parent
425d275
commit c5f2b60
Showing
13 changed files
with
417 additions
and
25 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -12,18 +12,22 @@ import ( | |
|
||
"github.com/aws/aws-sdk-go/aws/session" | ||
v4 "github.com/aws/aws-sdk-go/aws/signer/v4" | ||
"github.com/golang-jwt/jwt/v5" | ||
"github.com/google/uuid" | ||
) | ||
|
||
// call with UID to generate a UID, or with | ||
// -expectedStatus=200 REQUEST <METHOD> <URL> <REQUEST BODY> to make a test request | ||
// ./api-test/tester UID -> generate a UID | ||
// ./api-test/tester -jwtSecret=secret -expectedStatus=200 REQUEST <METHOD> <URL> <REQUEST BODY> | ||
// -> make a test request with a JWT generated using secret "secret" and expected status 200 | ||
// note that the jwtSecret sends a boilerplate JWT for now with valid iat, exp, iss and sub fields | ||
func main() { | ||
expectedStatusCode := flag.Int("expectedStatus", 200, "Expected response status code") | ||
jwtSecret := flag.String("jwtSecret", "", "Add JWT Authorization header signed with this secret") | ||
flag.Parse() | ||
|
||
args := flag.Args() | ||
|
||
// early exit if we're just generating a UID | ||
// early exit if we're just generating a UID or JWT | ||
if args[0] == "UID" { | ||
fmt.Print("M-" + strings.ToUpper(uuid.NewString()[9:23])) | ||
os.Exit(0) | ||
|
@@ -33,9 +37,6 @@ func main() { | |
panic("Unrecognised command") | ||
} | ||
|
||
sess := session.Must(session.NewSession()) | ||
signer := v4.NewSigner(sess.Config.Credentials) | ||
|
||
method := args[1] | ||
url := args[2] | ||
body := strings.NewReader(args[3]) | ||
|
@@ -47,6 +48,25 @@ func main() { | |
|
||
req.Header.Add("Content-type", "application/json") | ||
|
||
if *jwtSecret != "" { | ||
secretKey := []byte(*jwtSecret) | ||
|
||
claims := jwt.MapClaims{ | ||
"exp": time.Now().Add(time.Hour * 24).Unix(), | ||
"iat": time.Now().Add(time.Hour * -24).Unix(), | ||
"iss": "opg.poas.sirius", | ||
"sub": "[email protected]", | ||
} | ||
|
||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) | ||
tokenString, _ := token.SignedString(secretKey) | ||
|
||
req.Header.Add("X-Jwt-Authorization", fmt.Sprintf("Bearer: %s", tokenString)) | ||
} | ||
|
||
sess := session.Must(session.NewSession()) | ||
signer := v4.NewSigner(sess.Config.Credentials) | ||
|
||
_, err = signer.Sign(req, body, "execute-api", "eu-west-1", time.Now()) | ||
if err != nil { | ||
panic(err) | ||
|
@@ -68,6 +88,6 @@ func main() { | |
log.Printf("invalid status code %d; expected: %d", resp.StatusCode, *expectedStatusCode) | ||
log.Printf("error response: %s", buf.String()) | ||
} else { | ||
log.Printf("Test passed - %d: %s", resp.StatusCode, buf.String()) | ||
log.Printf("Test passed - %s to %s - %d: %s", method, url, resp.StatusCode, buf.String()) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
package shared | ||
|
||
import ( | ||
"strings" | ||
|
||
"github.com/aws/aws-lambda-go/events" | ||
) | ||
|
||
func GetEventHeader(headerName string, event events.APIGatewayProxyRequest) []string { | ||
headerValues, ok := event.MultiValueHeaders[strings.Title(headerName)] | ||
|
||
if !ok { | ||
headerValues, ok = event.MultiValueHeaders[strings.ToLower(headerName)] | ||
} | ||
|
||
if !ok { | ||
headerValues = []string{} | ||
} | ||
|
||
return headerValues | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,127 @@ | ||
package shared | ||
|
||
import ( | ||
"errors" | ||
"fmt" | ||
"os" | ||
"regexp" | ||
"time" | ||
|
||
"github.com/aws/aws-lambda-go/events" | ||
"github.com/golang-jwt/jwt/v5" | ||
) | ||
|
||
const ( | ||
sirius string = "opg.poas.sirius" | ||
mrlpa = "opg.poas.makeregister" | ||
) | ||
|
||
var validIssuers []string = []string{ | ||
sirius, | ||
mrlpa, | ||
} | ||
|
||
type lpaStoreClaims struct { | ||
jwt.RegisteredClaims | ||
} | ||
|
||
// note that default validation for RegisteredClaims checks exp is in the future | ||
func (l lpaStoreClaims) Validate() error { | ||
// validate issued at (iat) | ||
iat, err := l.GetIssuedAt() | ||
if err != nil { | ||
return err | ||
} | ||
|
||
if iat.Time.After(time.Now()) { | ||
return errors.New("IssuedAt must not be in the future") | ||
} | ||
|
||
// validate issuer (iss) | ||
iss, err := l.GetIssuer() | ||
if err != nil { | ||
return err | ||
} | ||
|
||
isValid := false | ||
for _, validIssuer := range validIssuers { | ||
if validIssuer == iss { | ||
isValid = true | ||
break | ||
} | ||
} | ||
|
||
if !isValid { | ||
return errors.New("Invalid Issuer") | ||
} | ||
|
||
// validate subject (sub) depending on the issuer value | ||
sub, err := l.GetSubject() | ||
if err != nil { | ||
return err | ||
} | ||
|
||
if iss == sirius { | ||
emailRegex := regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$") | ||
if !emailRegex.MatchString(sub) { | ||
return errors.New("Subject is not a valid email") | ||
} | ||
} | ||
|
||
if iss == mrlpa { | ||
uidRegex := regexp.MustCompile("^.+$") | ||
if !uidRegex.MatchString(sub) { | ||
return errors.New("Subject is not a valid UID") | ||
} | ||
} | ||
|
||
return nil | ||
} | ||
|
||
type JWTVerifier struct { | ||
secretKey []byte | ||
} | ||
|
||
func NewJWTVerifier() JWTVerifier { | ||
return JWTVerifier{ | ||
secretKey: []byte(os.Getenv("JWT_SECRET_KEY")), | ||
} | ||
} | ||
|
||
// tokenStr is the JWT token, minus any "Bearer: " prefix | ||
func (v JWTVerifier) VerifyToken(tokenStr string) error { | ||
lsc := lpaStoreClaims{} | ||
|
||
parsedToken, err := jwt.ParseWithClaims(tokenStr, &lsc, func(token *jwt.Token) (interface{}, error) { | ||
return v.secretKey, nil | ||
}) | ||
|
||
if err != nil { | ||
return err | ||
} | ||
|
||
if !parsedToken.Valid { | ||
return fmt.Errorf("Invalid JWT") | ||
} | ||
|
||
return nil | ||
} | ||
|
||
var bearerRegexp = regexp.MustCompile("^Bearer:[ ]+") | ||
|
||
// verify JWT from event header | ||
// returns true if verified, false otherwise | ||
func (v JWTVerifier) VerifyHeader(event events.APIGatewayProxyRequest) bool { | ||
jwtHeaders := GetEventHeader("X-Jwt-Authorization", event) | ||
|
||
if len(jwtHeaders) < 1 { | ||
return false | ||
} | ||
|
||
tokenStr := bearerRegexp.ReplaceAllString(jwtHeaders[0], "") | ||
if v.VerifyToken(tokenStr) != nil { | ||
return false | ||
} | ||
|
||
return true | ||
} |
Oops, something went wrong.