-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
VEGA-2105 Add JWT verification #minor #54
Merged
Merged
Changes from 16 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
acded5f
Install jwt library
c48118f
Add testify package
e301da8
Add tests for jwt verification
d2e0eef
Implement (most of the) jwt verification
aae3707
Add test to validate JWT subject based on issuer
1c4c1a7
Implement JWT subject verification based on issuer
0f5a2e0
Add tests for constructing a JWTVerifier from env
2401651
Implement JWTVerifier which can be constructed from env
b0bb74c
Incorporate verifier into create lambda
c497010
Wire up JWT verification to create lambda
748d00a
Move header parsing out of lambda
bea3c7f
Add JWT verification to get and update lambdas
9ce63a4
Move header-related code to VerifyHeader()
c54b37c
Add unit tests for VerifyHeader()
95ed047
Tabs, not spaces
5b1b279
Hard-code test JWT secret
6653e82
Reject requests with a 401 if JWT cannot be verified
08b9129
Add API tests for 401 from each lambda
8f80c3b
Show a bit more detail about API tests now there are more
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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) | ||
|
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,122 @@ | ||
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 | ||
func (v JWTVerifier) VerifyHeader(event events.APIGatewayProxyRequest) error { | ||
jwtHeaders := GetEventHeader("X-Jwt-Authorization", event) | ||
|
||
if len(jwtHeaders) > 0 { | ||
tokenStr := bearerRegexp.ReplaceAllString(jwtHeaders[0], "") | ||
return v.VerifyToken(tokenStr) | ||
} | ||
|
||
return errors.New("No JWT authorization header present") | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we return 401 if the token is invalid? Could potentially also build this into the
VerifyHeader
return values.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The only reason I didn't is because the ticket doesn't mention enforcing authorisation, only checking. I'm happy to add it though.
NB it might be that this will break the tests in CI, if the environment isn't set up properly or the env var isn't picked up etc., so might turn into a load more work.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sorry, poorly worded ticket: by "simply check these claims" it was the claims I meant were simple, I think we might as well enforce it off the bat. A classic of the "don't say 'simple' or 'just' lessons".
We're getting "Successfully parsed JWT from event header" in the lambda logs, so CI should pass enforcement 🤞🏽