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

Validate nbf field #40

Merged
merged 2 commits into from
Jun 11, 2020
Merged
Show file tree
Hide file tree
Changes from all 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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@

- ...

## `1.2.0` - 06/11/2020

#### Added

- Enforce the `nbf` field for DID Tokens parsed via `TokenModule.validate`.

## `1.1.0` - 05/25/2020

#### Added
Expand Down
7 changes: 7 additions & 0 deletions src/core/sdk-exceptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ export function createTokenExpiredError() {
return new MagicAdminSDKError(ErrorCode.TokenExpired, 'DID Token has expired. Request failed authentication.');
}

export function createTokenCannotBeUsedYetError() {
return new MagicAdminSDKError(
ErrorCode.TokenCannotBeUsedYet,
'Given DID Token cannot be used at this time. Please check the `nbf` field and regenerate a new token with a suitable value.',
);
}

export function createIncorrectSignerAddressError() {
return new MagicAdminSDKError(
ErrorCode.IncorrectSignerAddress,
Expand Down
11 changes: 10 additions & 1 deletion src/modules/token/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
createIncorrectSignerAddressError,
createTokenExpiredError,
createMalformedTokenError,
createTokenCannotBeUsedYetError,
} from '../../core/sdk-exceptions';
import { ecRecover } from '../../utils/ec-recover';
import { parseDIDToken } from '../../utils/parse-didt';
Expand Down Expand Up @@ -44,10 +45,18 @@ export class TokenModule extends BaseModule {
throw createIncorrectSignerAddressError();
}

const timeSecs = Math.floor(Date.now() / 1000);
const nbfTimeSecs = 300; // 5 min grace period

// Assert the token is not expired
if (parsedClaim.ext < Math.floor(Date.now() / 1000) - 30) {
if (parsedClaim.ext < timeSecs) {
throw createTokenExpiredError();
}

// Assert the token is not used before allowed.
if (parsedClaim.nbf > timeSecs - nbfTimeSecs) {
throw createTokenCannotBeUsedYetError();
}
}

public decode(DIDToken: string): ParsedDIDToken {
Expand Down
1 change: 1 addition & 0 deletions src/types/exception-types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export enum ErrorCode {
MissingAuthHeader = 'ERROR_MISSING_AUTH_HEADER',
TokenExpired = 'ERROR_DIDT_EXPIRED',
TokenCannotBeUsedYet = 'ERROR_DIDT_CANNOT_BE_USED_YET',
IncorrectSignerAddress = 'ERROR_INCORRECT_SIGNER_ADDR',
FailedRecoveryProof = 'ERROR_FAILED_RECOVERING_PROOF',
ApiKeyMissing = 'ERROR_SECRET_API_KEY_MISSING',
Expand Down
1 change: 1 addition & 0 deletions src/utils/type-guards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ function isNil(value: any): value is null | undefined {
return isNull(value) || isUndefined(value);
}

/** Assert `value` contains all required DID Token members. */
export function isDIDTClaim(value: any): value is Claim {
return (
!isNil(value) &&
Expand Down
3 changes: 3 additions & 0 deletions test/lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ export const VALID_DIDT_DECODED = [
VALID_DIDT_PARSED_CLAIMS,
];

export const VALID_FUTURE_MARKED_DIDT =
'WyIweDkzZjRiNTViYzRlN2E1ZWJkZTdmMzVkYzczMWE5NWFmOGYwZjVlMWQyMWQ5ZDYwZWQxM2Y4YmYzMmNiN2UwOTQ1MDM0MGI1Y2IyNTIxODZkNWQ3OTFiOTAyODZhYmY1NzM3YzMxN2M5NzNhMmQzMGY0MWZmYmFlNGU0NTdmMjE4MWIiLCJ7XCJpYXRcIjoxNTkxOTE0NTgyLFwiZXh0XCI6MjIyMjcxNDU4MixcImlzc1wiOlwiZGlkOmV0aHI6MHg0YzMzMmQ5QzRhMmEwNjY1YzNmODg1MTU1YjlFOTFmZEIzMDBlRTc2XCIsXCJzdWJcIjpcIms4NUtaR09Ycl9vMTYxNGdFVGN6Yzlac0phTjV4cjF2TVFXSWhnbjQ1Slk9XCIsXCJhdWRcIjpcImRpZDptYWdpYzoyMWI4ZjRkZS02ZmIzLTQ0M2YtOGM0MC04ODcwODJjNDQ1MjNcIixcIm5iZlwiOjE5MDczMTQ1ODIsXCJ0aWRcIjpcIjVhMjhjMjQwLWRmYzYtNDg2Ni04ODk1LTVkYzBhOTVkNWJkN1wiLFwiYWRkXCI6XCIweGRlMmI1ODgyNjUyZGExOTY4YWNlZTIyYWUyNGI2OWYxNThlZjg1NDQzOGE0OTlmMThjZGZlZDU3MzEwOGIxNzExYjQ2OWQ3MzQ5NzdhNGQ4NGJlM2RiODc2OTBkZjFmZjk4MTVjN2Y3NDIxNjIxMGY4Y2JhMGJmYzQ2ZGIwYjhkMWNcIn0iXQ==';

export const INVALID_DIDT_MALFORMED_CLAIM =
'WyIweDRiN2Y0ODgzNTczOGM2ZjViZmI5MTIyYmEzN2EwN2EyZDYwMTUwZjM2NGNhMDIwZjUyYWVlZjc3MmNlODk2ZWExYmJlYzc3OGZlMmFhNWNjODc3ZmVmOWQyOTJmN2U2MWZhMGZjY2M2NWIwZWZlZGVkMThmNzI0MzZkNjQ4MzdjMWMiLCJ7XCJ0aGlzSXNXUk9OR1wiOlwiSEVMTE8gV09STERcIn0iXQ==';

Expand Down
23 changes: 17 additions & 6 deletions test/spec/core/sdk-exceptions/error-factories.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
createApiKeyMissingError,
createServiceError,
createExpectedBearerStringError,
createTokenCannotBeUsedYetError,
} from '../../../../src/core/sdk-exceptions';

function errorAssertions<T extends ExecutionContext<any>>(
Expand All @@ -29,7 +30,17 @@ test('#01: Creates `ERROR_DIDT_EXPIRED` error', async t => {
errorAssertions(t, error, 'ERROR_DIDT_EXPIRED', 'DID Token has expired. Request failed authentication.');
});

test('#02: Creates `ERROR_INCORRECT_SIGNER_ADDR` error', async t => {
test('#02: Creates `ERROR_DIDT_CANNOT_BE_USED_YET` error', async t => {
const error = createTokenCannotBeUsedYetError();
errorAssertions(
t,
error,
'ERROR_DIDT_CANNOT_BE_USED_YET',
'Given DID Token cannot be used at this time. Please check the `nbf` field and regenerate a new token with a suitable value.',
);
});

test('#03: Creates `ERROR_INCORRECT_SIGNER_ADDR` error', async t => {
const error = createIncorrectSignerAddressError();
errorAssertions(
t,
Expand All @@ -39,12 +50,12 @@ test('#02: Creates `ERROR_INCORRECT_SIGNER_ADDR` error', async t => {
);
});

test('#03: Creates `ERROR_FAILED_RECOVERING_PROOF` error', async t => {
test('#04: Creates `ERROR_FAILED_RECOVERING_PROOF` error', async t => {
const error = createFailedRecoveringProofError();
errorAssertions(t, error, 'ERROR_FAILED_RECOVERING_PROOF', 'Failed to recover proof. Request failed authentication.');
});

test('#04: Creates `ERROR_SECRET_API_KEY_MISSING` error', async t => {
test('#05: Creates `ERROR_SECRET_API_KEY_MISSING` error', async t => {
const error = createApiKeyMissingError();
errorAssertions(
t,
Expand All @@ -54,7 +65,7 @@ test('#04: Creates `ERROR_SECRET_API_KEY_MISSING` error', async t => {
);
});

test('#05: Creates `SERVICE_ERROR` error with empty `data` property', async t => {
test('#06: Creates `SERVICE_ERROR` error with empty `data` property', async t => {
const error = createServiceError();
errorAssertions(
t,
Expand All @@ -64,7 +75,7 @@ test('#05: Creates `SERVICE_ERROR` error with empty `data` property', async t =>
);
});

test('#06: Creates `SERVICE_ERROR` error with non-empty `data` property', async t => {
test('#07: Creates `SERVICE_ERROR` error with non-empty `data` property', async t => {
const error = createServiceError('hello', 'world');
errorAssertions(
t,
Expand All @@ -75,7 +86,7 @@ test('#06: Creates `SERVICE_ERROR` error with non-empty `data` property', async
);
});

test('#07: Creates `EXPECTED_BEARER_STRING` error', async t => {
test('#08: Creates `EXPECTED_BEARER_STRING` error', async t => {
const error = createExpectedBearerStringError();
errorAssertions(
t,
Expand Down
27 changes: 21 additions & 6 deletions test/spec/modules/token/validate.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,52 @@ import test from 'ava';
import sinon from 'sinon';
import { recoverPersonalSignature } from 'eth-sig-util';
import { createMagicAdminSDK } from '../../../lib/factories';
import { VALID_DIDT, INVALID_SIGNER_DIDT, EXPIRED_DIDT, INVALID_DIDT_MALFORMED_CLAIM } from '../../../lib/constants';
import {
VALID_DIDT,
INVALID_SIGNER_DIDT,
EXPIRED_DIDT,
INVALID_DIDT_MALFORMED_CLAIM,
VALID_FUTURE_MARKED_DIDT,
} from '../../../lib/constants';
import {
createIncorrectSignerAddressError,
MagicAdminSDKError,
createTokenExpiredError,
createFailedRecoveringProofError,
createMalformedTokenError,
createTokenCannotBeUsedYetError,
} from '../../../../src/core/sdk-exceptions';

test('#01: Successfully validates DIDT', async t => {
test.serial('#01: Successfully validates DIDT', async t => {
const sdk = createMagicAdminSDK();
t.notThrows(() => sdk.token.validate(VALID_DIDT));
});

test('#02: Fails when signer address mismatches signature', async t => {
test.serial('#02: Fails when signer address mismatches signature', async t => {
const sdk = createMagicAdminSDK();
const expectedError = createIncorrectSignerAddressError();
const error: MagicAdminSDKError = t.throws(() => sdk.token.validate(INVALID_SIGNER_DIDT));
t.is(error.code, expectedError.code);
t.is(error.message, expectedError.message);
});

test('#03: Fails when given expired token', async t => {
test.serial('#03: Fails when given expired token', async t => {
const sdk = createMagicAdminSDK();
const expectedError = createTokenExpiredError();
const error: MagicAdminSDKError = t.throws(() => sdk.token.validate(EXPIRED_DIDT));
t.is(error.code, expectedError.code);
t.is(error.message, expectedError.message);
});

test('#04: Fails if signature recovery rejects', async t => {
test.serial('#04: Fails when given a token with a future `nbf` timestamp', async t => {
const sdk = createMagicAdminSDK();
const expectedError = createTokenCannotBeUsedYetError();
const error: MagicAdminSDKError = t.throws(() => sdk.token.validate(VALID_FUTURE_MARKED_DIDT));
t.is(error.code, expectedError.code);
t.is(error.message, expectedError.message);
});

test.serial('#05: Fails if signature recovery rejects', async t => {
const recoverStub = sinon.stub().throws();
(recoverPersonalSignature as any) = recoverStub;

Expand All @@ -43,7 +58,7 @@ test('#04: Fails if signature recovery rejects', async t => {
t.is(error.message, expectedError.message);
});

test('#05: Fails if decoding token fails', async t => {
test.serial('#06: Fails if decoding token fails', async t => {
const recoverStub = sinon.stub().throws();
(recoverPersonalSignature as any) = recoverStub;

Expand Down