Skip to content
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

feat: add threshold in DateProvider #242

Merged
merged 7 commits into from
Jan 23, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bundle/bundle.js

Large diffs are not rendered by default.

10 changes: 5 additions & 5 deletions lib/build/claims/primitiveArrayClaim.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 7 additions & 7 deletions lib/build/claims/primitiveClaim.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion lib/build/fetch.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions lib/build/recipeImplementation.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion lib/build/types.d.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions lib/build/utils/dateProvider/defaultImplementation.d.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions lib/build/utils/dateProvider/defaultImplementation.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions lib/build/utils/dateProvider/types.d.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 5 additions & 5 deletions lib/ts/claims/primitiveArrayClaim.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export class PrimitiveArrayClaim<ValueType> {
id?: string
): SessionClaimValidator => {
const DateProvider = DateProviderReference.getReferenceOrThrow().dateProvider;
if (maxAgeInSeconds && maxAgeInSeconds < DateProvider.getThresholdInSeconds()) {
if (maxAgeInSeconds !== undefined && maxAgeInSeconds < DateProvider.getThresholdInSeconds()) {
throw new Error(
`maxAgeInSeconds must be greater than the DateProvider threshold value -> ${DateProvider.getThresholdInSeconds()}`
);
Expand Down Expand Up @@ -80,7 +80,7 @@ export class PrimitiveArrayClaim<ValueType> {
id?: string
): SessionClaimValidator => {
const DateProvider = DateProviderReference.getReferenceOrThrow().dateProvider;
if (maxAgeInSeconds && maxAgeInSeconds < DateProvider.getThresholdInSeconds()) {
if (maxAgeInSeconds !== undefined && maxAgeInSeconds < DateProvider.getThresholdInSeconds()) {
throw new Error(
`maxAgeInSeconds must be greater than the DateProvider threshold value -> ${DateProvider.getThresholdInSeconds()}`
);
Expand Down Expand Up @@ -131,7 +131,7 @@ export class PrimitiveArrayClaim<ValueType> {
id?: string
): SessionClaimValidator => {
const DateProvider = DateProviderReference.getReferenceOrThrow().dateProvider;
if (maxAgeInSeconds && maxAgeInSeconds < DateProvider.getThresholdInSeconds()) {
if (maxAgeInSeconds !== undefined && maxAgeInSeconds < DateProvider.getThresholdInSeconds()) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these checks should be in shouldRefresh

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

throw new Error(
`maxAgeInSeconds must be greater than the DateProvider threshold value -> ${DateProvider.getThresholdInSeconds()}`
);
Expand Down Expand Up @@ -179,7 +179,7 @@ export class PrimitiveArrayClaim<ValueType> {
id?: string
): SessionClaimValidator => {
const DateProvider = DateProviderReference.getReferenceOrThrow().dateProvider;
if (maxAgeInSeconds && maxAgeInSeconds < DateProvider.getThresholdInSeconds()) {
if (maxAgeInSeconds !== undefined && maxAgeInSeconds < DateProvider.getThresholdInSeconds()) {
throw new Error(
`maxAgeInSeconds must be greater than the DateProvider threshold value -> ${DateProvider.getThresholdInSeconds()}`
);
Expand Down Expand Up @@ -231,7 +231,7 @@ export class PrimitiveArrayClaim<ValueType> {
id?: string
): SessionClaimValidator => {
const DateProvider = DateProviderReference.getReferenceOrThrow().dateProvider;
if (maxAgeInSeconds && maxAgeInSeconds < DateProvider.getThresholdInSeconds()) {
if (maxAgeInSeconds !== undefined && maxAgeInSeconds < DateProvider.getThresholdInSeconds()) {
throw new Error(
`maxAgeInSeconds must be greater than the DateProvider threshold value -> ${DateProvider.getThresholdInSeconds()}`
);
Expand Down
22 changes: 13 additions & 9 deletions lib/ts/claims/primitiveClaim.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,22 @@ export class PrimitiveClaim<ValueType> {
id?: string
): SessionClaimValidator => {
const DateProvider = DateProviderReference.getReferenceOrThrow().dateProvider;
if (maxAgeInSeconds && maxAgeInSeconds < DateProvider.getThresholdInSeconds()) {
throw new Error(
`maxAgeInSeconds must be greater than the DateProvider threshold value -> ${DateProvider.getThresholdInSeconds()}`
);
}
return {
id: id !== undefined ? id : this.id,
refresh: ctx => this.refresh(ctx),
shouldRefresh: (payload, ctx) =>
this.getValueFromPayload(payload, ctx) === undefined ||
// We know payload[this.id] is defined since the value is not undefined in this branch
(maxAgeInSeconds !== undefined && payload[this.id].t < DateProvider.now() - maxAgeInSeconds * 1000),
shouldRefresh: (payload, ctx) => {
if (maxAgeInSeconds !== undefined && maxAgeInSeconds < DateProvider.getThresholdInSeconds()) {
throw new Error(
`maxAgeInSeconds must be greater than the DateProvider threshold value -> ${DateProvider.getThresholdInSeconds()}`
);
}
return (
this.getValueFromPayload(payload, ctx) === undefined ||
// We know payload[this.id] is defined since the value is not undefined in this branch
(maxAgeInSeconds !== undefined &&
payload[this.id].t < DateProvider.now() - maxAgeInSeconds * 1000)
);
},
validate: (payload, ctx) => {
const claimVal = this.getValueFromPayload(payload, ctx);
if (claimVal === undefined) {
Expand Down
2 changes: 1 addition & 1 deletion lib/ts/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -951,7 +951,7 @@ export const updateClockSkewUsingFrontToken = ({
}

const frontTokenPayload = parseFrontToken(frontToken);
const clockSkewInMillis = AuthHttpRequest.recipeImpl.getClockSkewInMillis({
const clockSkewInMillis = AuthHttpRequest.recipeImpl.calculateClockSkewInMillis({
accessTokenPayload: frontTokenPayload.up,
responseHeaders
});
Expand Down
8 changes: 4 additions & 4 deletions lib/ts/recipeImplementation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,25 +311,25 @@ export default function RecipeImplementation(recipeImplInput: {
}
},

getClockSkewInMillis: function ({
calculateClockSkewInMillis: function ({
accessTokenPayload
}: {
accessTokenPayload: any;
responseHeaders: Headers;
}): number {
logDebugMessage("getClockSkewInMillis: called");
logDebugMessage("calculateClockSkewInMillis: called");

const tokenIssuedAt = accessTokenPayload?.iat;
if (tokenIssuedAt === undefined || typeof tokenIssuedAt !== "number") {
logDebugMessage(
`getClockSkewInMillis: payload iat is undefined or not a number. This may happen due to an unsupported backend sdk. Returning 0`
`calculateClockSkewInMillis: payload iat is undefined or not a number. This may happen due to an unsupported backend sdk. Returning 0`
);
return 0;
}

const estimatedServerTimeNow = tokenIssuedAt * 1000;
const clockSkewInMillis = estimatedServerTimeNow - Date.now();
logDebugMessage("getClockSkewInMillis: returning " + clockSkewInMillis);
logDebugMessage("calculateClockSkewInMillis: returning " + clockSkewInMillis);

return clockSkewInMillis;
}
Expand Down
2 changes: 1 addition & 1 deletion lib/ts/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ export type RecipeInterface = {
sessionTokenBackendDomain: string | undefined
): boolean;

getClockSkewInMillis(params: { accessTokenPayload: any; responseHeaders: Headers }): number;
calculateClockSkewInMillis(params: { accessTokenPayload: any; responseHeaders: Headers }): number;
};

export type ClaimValidationResult = { isValid: true } | { isValid: false; reason?: any };
Expand Down
4 changes: 4 additions & 0 deletions lib/ts/utils/dateProvider/defaultImplementation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ export class DateProvider {
return this.thresholdInSeconds;
}

setThresholdInSeconds(thresholdInSeconds: number): void {
this.thresholdInSeconds = thresholdInSeconds;
}

setClientClockSkewInMillis(clockSkewInMillis: number): void {
this.clockSkewInMillis = Math.abs(clockSkewInMillis) > this.thresholdInSeconds * 1000 ? clockSkewInMillis : 0;
const localStorage = WindowHandlerReference.getReferenceOrThrow().windowHandler.localStorage;
Expand Down
1 change: 1 addition & 0 deletions lib/ts/utils/dateProvider/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

export interface DateProviderInterface {
getThresholdInSeconds(): number;
setThresholdInSeconds(thresholdInSeconds: number): void;
now(): number;
setClientClockSkewInMillis(clockSkewInMillis: number): void;
getClientClockSkewInMillis(): number;
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
18 changes: 11 additions & 7 deletions test/interception.claims.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ addGenericTestCases((name, transferMethod, setupFunc, setupArgs = []) => {
{
// enableDebugLogs: true,
// This isn't used in all tests but it only produces some extra logs
override: ["log_getClockSkewInMillis"]
override: ["log_calculateClockSkewInMillis"]
},
...setupArgs
);
Expand Down Expand Up @@ -266,7 +266,7 @@ addGenericTestCases((name, transferMethod, setupFunc, setupArgs = []) => {
}
});

it("should call the claim refresh endpoint once for multiple `shouldRefresh` calls with adjusted clock skew (client clock behind)", async function () {
it("should call the claim refresh endpoint as many times as `shouldRefresh` calls with adjusted clock skew (client clock behind)", async function () {
await startST(2 * 60 * 60); // setting accessTokenValidity to 2 hours to avoid refresh issues due to clock skew
try {
let customClaimRefreshCalledCount = 0;
Expand Down Expand Up @@ -317,7 +317,12 @@ addGenericTestCases((name, transferMethod, setupFunc, setupArgs = []) => {
body: JSON.stringify({
"st-custom": {
v: true,
t: originalNow()
// We intentionally expire the claim during an update. In an ideal scenario,
// the `shouldRefresh` function would consistently return true as the claim is expired.
// However, if the client clock is behind, the `shouldRefresh` function may erroneously return false.
// The responsibility of handling this situation lies with the DateProvider,
// ensuring that `shouldRefresh` correctly returns true regardless of potential clock discrepancies.
t: originalNow() - 10 * 60 * 1000
}
})
});
Expand All @@ -332,19 +337,18 @@ addGenericTestCases((name, transferMethod, setupFunc, setupArgs = []) => {
await supertokens.validateClaims(() => [customSessionClaimValidator]);
});

assert.strictEqual(customClaimRefreshCalledCount, 1);
assert.strictEqual(customClaimRefreshCalledCount, 3);
} finally {
await browser.close();
}
});

it("should call getClockSkewInMillis with appropriate headers", async function () {
it("should call calculateClockSkewInMillis with appropriate headers", async function () {
await startST();
let clockSkewParams = [];
page.on("console", ev => {
const text = ev.text();
// console.log(text);
const key = "TEST_getClockSkewInMillis$";
const key = "TEST_calculateClockSkewInMillis$";
if (text.startsWith(key)) {
clockSkewParams.push(JSON.parse(text.substr(key.length)));
}
Expand Down
Loading
Loading