jagregory / cognito-local

Local emulator for Amazon Cognito
MIT License
289 stars 74 forks source link

Feature Request: Flag to allow actual aws cognito errors to be thrown #309

Closed codyburrito closed 1 year ago

codyburrito commented 2 years ago

Currently cognito-local returns custom errors defined in errors.ts. This means you may have to write custom error handler code just for cognito-local which is less than ideal.

I assume throwing actual aws cognito errors by default will be a breaking change so this will probably have to be a flag that is false by default.

I may be able to work on this soon!

charlieparkes-Q commented 1 year ago

Just ran into this. Is there a reason for returning non-standard error codes? There's no simple way for the client side to understand what's happening with errors returning as they are.

charlieparkes-Q commented 1 year ago

workaround in golang

func newClient(t *testing.T, session *session.Session) *cognitoidentityprovider.CognitoIdentityProvider {
    t.Helper()
    interceptSessionErrors(t, session)
    client := cognitoidentityprovider.New(session)
    return client
}

func interceptSessionErrors(t *testing.T, session *session.Session) {
    t.Helper()
    session.Handlers.UnmarshalError.PushFront(unmarshalError)
}

func unmarshalError(req *request.Request) {
    body, err := io.ReadAll(req.HTTPResponse.Body)
    if err != nil {
        panic(err)
    }
    var payload map[string]json.RawMessage
    err = json.Unmarshal(body, &payload)
    if err != nil {
        panic(err)
    }
    code, ok := payload["code"]
    if ok {
        if bytes.HasPrefix(code, []byte("CognitoLocal#")) {
            code = bytes.Replace([]byte(code), []byte("CognitoLocal#"), []byte("Cognito#"), 1)
        }
        payload["__type"] = code
    }
    body, err = json.Marshal(&payload)
    if err != nil {
        panic(err)
    }
    req.HTTPResponse.Body = io.NopCloser(bytes.NewBuffer(body))
}
jagregory commented 1 year ago

I've merged @paullallier's changes, which should fix some of the issues you've all been seeing. I'm going to close this issue assuming Paul's changes work for everyone, but please reopen if that's not the case. v3.21.2

Just for clarity, this repo has a suite of integration tests which use the actual NodeJS AWS SDK to test these APIs with error handling, so it was my understanding that I was actually using the correct Cognito errors! It wasn't intentional that cognito-local would have a different set of error codes to the actual Cognito, that defeats the object of an emulator entirely. These issues appear to be variations in how the different SDKs handle errors (and I assume the NodeJS SDK is more lenient than others).

I'm happy to accept PRs to fix these issues, but unfortunately I don't have any means to reproduce these issues myself, so PRs will have to be accepted on good faith that they fix issues.