Skip to content

Commit

Permalink
fix(lambda): preTokenGenerator can't change reserved claims
Browse files Browse the repository at this point in the history
  • Loading branch information
jagregory committed Dec 9, 2021
1 parent f4a470f commit 407122f
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 4 deletions.
46 changes: 46 additions & 0 deletions src/services/tokenGenerator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,52 @@ describe("JwtTokenGenerator", () => {
attributeValue("email", user.Attributes)
);
});

describe.each([
"acr",
"amr",
"aud",
"at_hash",
"auth_time",
"azp",
"cognito:username",
"exp",
"iat",
"identities",
"iss",
"jti",
"nbf",
"nonce",
"origin_jti",
"sub",
"token_use",
])("reserved claim %s", (claim) => {
it("cannot override a reserved claim", async () => {
mockTriggers.enabled.mockImplementation((name) => {
return name === "PreTokenGeneration";
});
mockTriggers.preTokenGeneration.mockResolvedValue({
claimsOverrideDetails: {
claimsToAddOrOverride: {
[claim]: "value",
},
},
});

const tokens = await tokenGenerator.generate(
TestContext,
user,
"clientId",
"userPoolId",
{ client: "metadata" },
"RefreshTokens"
);

expect(jwt.decode(tokens.IdToken)).not.toMatchObject({
[claim]: "value",
});
});
});
});

describe("TokenGeneration lambda is not configured", () => {
Expand Down
35 changes: 31 additions & 4 deletions src/services/tokenGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,17 +35,44 @@ interface TokenOverrides {
groupOverrideDetails?: GroupOverrideDetails | undefined;
}

const RESERVED_CLAIMS = [
"acr",
"amr",
"aud",
"at_hash",
"auth_time",
"azp",
"cognito:username",
"exp",
"iat",
"identities",
"iss",
"jti",
"nbf",
"nonce",
"origin_jti",
"sub",
"token_use",
];

const applyTokenOverrides = (
token: Record<string, string | number | boolean | undefined>,
overrides: TokenOverrides
): Record<string, string | number | boolean | undefined> => {
// TODO: support group overrides

const claimsToSuppress = (overrides?.claimsToSuppress ?? []).filter(
(claim) => !RESERVED_CLAIMS.includes(claim)
);

const claimsToOverride = Object.entries(
overrides?.claimsToAddOrOverride ?? []
).filter(([claim]) => !RESERVED_CLAIMS.includes(claim));

return Object.fromEntries(
[
...Object.entries(token),
...Object.entries(overrides?.claimsToAddOrOverride ?? []),
].filter(([k]) => !overrides?.claimsToSuppress?.includes(k))
[...Object.entries(token), ...claimsToOverride].filter(
([claim]) => !claimsToSuppress.includes(claim)
)
);
};

Expand Down

0 comments on commit 407122f

Please sign in to comment.