Skip to content
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ try {
}
// Magic Auth - Get User Email
try {
// Token metadata helpers validate the DID token and verify that the returned
// metadata belongs to the token signer.
await magic.users.getMetadataByToken("DIDToken");
} catch (e) {
console.log(e);
Expand Down
6 changes: 3 additions & 3 deletions src/modules/token/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-disable prefer-destructuring */
import { BaseModule } from '../base-module';
import { ParsedDIDToken } from '../../types';
import {
Expand Down Expand Up @@ -27,6 +26,7 @@ export class TokenModule extends BaseModule {
[proof, claim] = tokenParseResult.raw;
parsedClaim = tokenParseResult.withParsedClaim[1];
claimedIssuer = parsePublicAddressFromIssuer(parsedClaim.iss);
if (!claimedIssuer) throw createMalformedTokenError();
} catch {
throw createMalformedTokenError();
}
Expand Down Expand Up @@ -74,8 +74,8 @@ export class TokenModule extends BaseModule {

public getPublicAddress(DIDToken: string): string {
const claim = this.decode(DIDToken)[1];
const claimedIssuer = claim.iss.split(':')[2];
return claimedIssuer;
if (!parsePublicAddressFromIssuer(claim.iss)) return '';
return claim.iss.split(':')[2];
}

public getIssuer(DIDToken: string): string {
Expand Down
22 changes: 18 additions & 4 deletions src/modules/users/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { BaseModule } from '../base-module';
import { createApiKeyMissingError } from '../../core/sdk-exceptions';
import { createApiKeyMissingError, createIncorrectSignerAddressError } from '../../core/sdk-exceptions';
import { post, get } from '../../utils/rest';
import { generateIssuerFromPublicAddress } from '../../utils/issuer';
import { generateIssuerFromPublicAddress, parsePublicAddressFromIssuer } from '../../utils/issuer';
import { MagicUserMetadata, MagicWallet, WalletType } from '../../types';

export class UsersModule extends BaseModule {
Expand Down Expand Up @@ -30,8 +30,11 @@ export class UsersModule extends BaseModule {
}

public async getMetadataByToken(DIDToken: string): Promise<MagicUserMetadata> {
this.sdk.token.validate(DIDToken);
const issuer = this.sdk.token.getIssuer(DIDToken);
return this.getMetadataByIssuer(issuer);
const metadata = await this.getMetadataByIssuer(issuer);
this.assertMetadataMatchesIssuer(metadata, issuer);
return metadata;
}

public async getMetadataByPublicAddress(publicAddress: string): Promise<MagicUserMetadata> {
Expand All @@ -40,8 +43,11 @@ export class UsersModule extends BaseModule {
}

public async getMetadataByTokenAndWallet(DIDToken: string, walletType: WalletType): Promise<MagicUserMetadata> {
this.sdk.token.validate(DIDToken);
const issuer = this.sdk.token.getIssuer(DIDToken);
return this.getMetadataByIssuerAndWallet(issuer, walletType);
const metadata = await this.getMetadataByIssuerAndWallet(issuer, walletType);
this.assertMetadataMatchesIssuer(metadata, issuer);
return metadata;
}

public async getMetadataByPublicAddressAndWallet(
Expand Down Expand Up @@ -75,4 +81,12 @@ export class UsersModule extends BaseModule {
wallets: data.wallets ?? null,
};
}

private assertMetadataMatchesIssuer(metadata: MagicUserMetadata, issuer: string): void {
if (
parsePublicAddressFromIssuer(metadata.issuer ?? '') !== parsePublicAddressFromIssuer(issuer)
) {
throw createIncorrectSignerAddressError();
}
}
}
5 changes: 4 additions & 1 deletion src/utils/issuer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,8 @@ export function generateIssuerFromPublicAddress(publicAddress: string, method =
}

export function parsePublicAddressFromIssuer(issuer: string) {
return issuer.split(':')[2]?.toLowerCase() ?? '';
if (typeof issuer !== 'string') return '';

const match = /^did:ethr:(0x[a-fA-F0-9]{40})$/.exec(issuer);
return match?.[0] === issuer ? match[1].toLowerCase() : '';
}
11 changes: 5 additions & 6 deletions src/utils/rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,11 @@ async function emitRequest<TResponse>(url: string, init?: RequestInit): Promise<
* Generates an encoded URL with query string from a dictionary of values.
*/
function generateQuery<T extends Record<string, string | number | boolean>>(url: string, params?: T) {
let query = '?';
if (params) {
for (const [key, value] of Object.entries(params)) query += `${key}=${value}&`;
query = query.slice(0, -1); // Remove trailing "&"
}
return params ? `${url}${query}` : url;
if (!params || Object.keys(params).length === 0) return url;

const query = new URLSearchParams();
for (const [key, value] of Object.entries(params)) query.append(key, String(value));
return `${url}?${query.toString()}`;
}

/**
Expand Down
7 changes: 6 additions & 1 deletion test/spec/modules/token/getPublicAddress.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import { createMagicAdminSDK } from '../../../lib/factories';
import { VALID_DIDT, VALID_DIDT_PARSED_CLAIMS } from '../../../lib/constants';
import { INVALID_SIGNER_DIDT, VALID_DIDT, VALID_DIDT_PARSED_CLAIMS } from '../../../lib/constants';

test('Successfully gets public address from DIDT', () => {
const sdk = createMagicAdminSDK();
const result = sdk.token.getPublicAddress(VALID_DIDT);
const expected = VALID_DIDT_PARSED_CLAIMS.iss.split(':')[2];
expect(result).toBe(expected);
});

test('Returns an empty string for a malformed issuer', () => {
const sdk = createMagicAdminSDK();
expect(sdk.token.getPublicAddress(INVALID_SIGNER_DIDT)).toBe('');
});
65 changes: 63 additions & 2 deletions test/spec/modules/token/validate.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createMagicAdminSDK } from '../../../lib/factories';
import { Wallet } from 'ethers';
import {
VALID_DIDT,
VALID_DIDT_WITH_INVALID_RECOVERY_BIT,
Expand Down Expand Up @@ -32,9 +33,9 @@ test('Successfully validates DIDT with attachment', async () => {
expect(() => sdk.token.validate(VALID_ATTACHMENT_DIDT, 'ravi@magic.link')).not.toThrow();
});

test('Fails when signer address mismatches signature', async () => {
test('Fails when the token issuer is malformed', async () => {
const sdk = createMagicAdminSDK();
const expectedError = createIncorrectSignerAddressError();
const expectedError = createMalformedTokenError();
expect(() => sdk.token.validate(INVALID_SIGNER_DIDT)).toThrow(expectedError);
});

Expand Down Expand Up @@ -67,3 +68,63 @@ test('Fails if aud is incorrect', async () => {
const expectedError = createAudienceMismatchError();
expect(() => sdk.token.validate(VALID_DIDT)).toThrow(expectedError);
});

test('Fails a correctly signed token with an issuer suffix', async () => {
const wallet = Wallet.createRandom();
const now = Math.floor(Date.now() / 1000);
const claim = JSON.stringify({
iat: now,
ext: now + 3600,
iss: `did:ethr:${wallet.address}:&issuer=did:ethr:0x2222222222222222222222222222222222222222`,
sub: 'subject',
aud: 'audience',
nbf: now,
tid: 'token-id',
add: 'none',
});
const proof = await wallet.signMessage(claim);
const didToken = Buffer.from(JSON.stringify([proof, claim])).toString('base64');

const sdk = createMagicAdminSDK(undefined, 'audience');
expect(() => sdk.token.validate(didToken)).toThrow(createMalformedTokenError());
});

test('Validates a correctly signed token with a mixed-case issuer and matching audience', async () => {
const wallet = Wallet.createRandom();
const now = Math.floor(Date.now() / 1000);
const claim = JSON.stringify({
iat: now,
ext: now + 3600,
iss: `did:ethr:${wallet.address}`,
sub: 'subject',
aud: 'audience',
nbf: now,
tid: 'token-id',
add: 'none',
});
const proof = await wallet.signMessage(claim);
const didToken = Buffer.from(JSON.stringify([proof, claim])).toString('base64');

const sdk = createMagicAdminSDK(undefined, 'audience');
expect(() => sdk.token.validate(didToken)).not.toThrow();
});

test('Fails a correctly signed token whose valid issuer belongs to another wallet', async () => {
const signer = Wallet.createRandom();
const now = Math.floor(Date.now() / 1000);
const claim = JSON.stringify({
iat: now,
ext: now + 3600,
iss: 'did:ethr:0x2222222222222222222222222222222222222222',
sub: 'subject',
aud: 'audience',
nbf: now,
tid: 'token-id',
add: 'none',
});
const proof = await signer.signMessage(claim);
const didToken = Buffer.from(JSON.stringify([proof, claim])).toString('base64');

const sdk = createMagicAdminSDK();
expect(() => sdk.token.validate(didToken)).toThrow(createIncorrectSignerAddressError());
});
85 changes: 81 additions & 4 deletions test/spec/modules/users/getMetadataByToken.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
import { createMagicAdminSDK } from '../../../lib/factories';
import { VALID_DIDT, VALID_DIDT_PARSED_CLAIMS } from '../../../lib/constants';
import {
EXPIRED_DIDT,
INVALID_DIDT_MALFORMED_CLAIM,
VALID_DIDT,
VALID_DIDT_PARSED_CLAIMS,
} from '../../../lib/constants';
import { WalletType } from '../../../../src/types/wallet-types';
import { createIncorrectSignerAddressError } from '../../../../src/core/sdk-exceptions';

const matchingMetadata = { issuer: VALID_DIDT_PARSED_CLAIMS.iss };

test('Successfully GETs to metadata endpoint via public address', async () => {
const sdk = createMagicAdminSDK('https://example.com');

const getMetadataStub = jest.fn().mockImplementation(() => Promise.resolve());
const getMetadataStub = jest.fn().mockImplementation(() => Promise.resolve(matchingMetadata));
(sdk.users.getMetadataByIssuer as any) = getMetadataStub;

await expect(sdk.users.getMetadataByToken(VALID_DIDT)).resolves.not.toThrow();
Expand All @@ -17,7 +25,7 @@ test('Successfully GETs to metadata endpoint via public address', async () => {
test('Successfully GETs to metadata endpoint via public address and wallet type', async () => {
const sdk = createMagicAdminSDK('https://example.com');

const getMetadataStub = jest.fn().mockImplementation(() => Promise.resolve());
const getMetadataStub = jest.fn().mockImplementation(() => Promise.resolve(matchingMetadata));
(sdk.users.getMetadataByIssuerAndWallet as any) = getMetadataStub;

await expect(sdk.users.getMetadataByTokenAndWallet(VALID_DIDT, WalletType.ALGOD)).resolves.not.toThrow();
Expand All @@ -29,11 +37,80 @@ test('Successfully GETs to metadata endpoint via public address and wallet type'
test('Successfully GETs to metadata endpoint via public address and none wallet type', async () => {
const sdk = createMagicAdminSDK('https://example.com');

const getMetadataStub = jest.fn().mockImplementation(() => Promise.resolve());
const getMetadataStub = jest.fn().mockImplementation(() => Promise.resolve(matchingMetadata));
(sdk.users.getMetadataByIssuerAndWallet as any) = getMetadataStub;

await expect(sdk.users.getMetadataByTokenAndWallet(VALID_DIDT, WalletType.NONE)).resolves.not.toThrow();

const getMetadataArguments = getMetadataStub.mock.calls[0];
expect(getMetadataArguments).toEqual([VALID_DIDT_PARSED_CLAIMS.iss, 'NONE']);
});

test('Rejects metadata that belongs to a different issuer', async () => {
const sdk = createMagicAdminSDK('https://example.com');
(sdk.users.getMetadataByIssuer as any) = jest.fn().mockResolvedValue({
issuer: 'did:ethr:0x2222222222222222222222222222222222222222',
});

await expect(sdk.users.getMetadataByToken(VALID_DIDT)).rejects.toThrow(createIncorrectSignerAddressError());
});

test('Rejects metadata without a canonical issuer', async () => {
const sdk = createMagicAdminSDK('https://example.com');
(sdk.users.getMetadataByIssuer as any) = jest.fn().mockResolvedValue({ issuer: null });

await expect(sdk.users.getMetadataByToken(VALID_DIDT)).rejects.toThrow(createIncorrectSignerAddressError());
});

test('Rejects metadata with a malformed issuer', async () => {
const sdk = createMagicAdminSDK('https://example.com');
(sdk.users.getMetadataByIssuer as any) = jest.fn().mockResolvedValue({ issuer: 'not-an-issuer' });

await expect(sdk.users.getMetadataByToken(VALID_DIDT)).rejects.toThrow(createIncorrectSignerAddressError());
});

test('Rejects mismatched canonical metadata issuer for wallet-specific lookups', async () => {
const sdk = createMagicAdminSDK('https://example.com');
(sdk.users.getMetadataByIssuerAndWallet as any) = jest.fn().mockResolvedValue({
issuer: 'did:ethr:0x2222222222222222222222222222222222222222',
});

await expect(sdk.users.getMetadataByTokenAndWallet(VALID_DIDT, WalletType.ALGOD)).rejects.toThrow(
createIncorrectSignerAddressError(),
);
});

test('Accepts a differently cased canonical issuer and an alternate wallet address', async () => {
const sdk = createMagicAdminSDK('https://example.com');
const metadata = {
issuer: VALID_DIDT_PARSED_CLAIMS.iss.toLowerCase(),
publicAddress: 'alternate-wallet-address',
};
(sdk.users.getMetadataByIssuerAndWallet as any) = jest.fn().mockResolvedValue(metadata);

await expect(sdk.users.getMetadataByTokenAndWallet(VALID_DIDT, WalletType.ALGOD)).resolves.toEqual(metadata);
});

test.each([['malformed', INVALID_DIDT_MALFORMED_CLAIM], ['expired', EXPIRED_DIDT]])(
'Rejects %s tokens before metadata lookup',
async (_description, didToken) => {
const sdk = createMagicAdminSDK('https://example.com');
const getMetadataStub = jest.fn();
(sdk.users.getMetadataByIssuer as any) = getMetadataStub;

await expect(sdk.users.getMetadataByToken(didToken)).rejects.toThrow();
expect(getMetadataStub).not.toHaveBeenCalled();
},
);

test.each([['malformed', INVALID_DIDT_MALFORMED_CLAIM], ['expired', EXPIRED_DIDT]])(
'Rejects %s tokens before wallet-specific metadata lookup',
async (_description, didToken) => {
const sdk = createMagicAdminSDK('https://example.com');
const getMetadataStub = jest.fn();
(sdk.users.getMetadataByIssuerAndWallet as any) = getMetadataStub;

await expect(sdk.users.getMetadataByTokenAndWallet(didToken, WalletType.ALGOD)).rejects.toThrow();
expect(getMetadataStub).not.toHaveBeenCalled();
},
);
21 changes: 16 additions & 5 deletions test/spec/utils/issuer/parsePublicAddressFromIssuer.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
import { parsePublicAddressFromIssuer } from '../../../../src/utils/issuer';

test('Successfully parses public address from issuer string', async () => {
const result = parsePublicAddressFromIssuer('did:ethr:0x1234');
expect(result).toBe('0x1234');
const result = parsePublicAddressFromIssuer('did:ethr:0xB2ec9b61699762491b6542278E9dFEC9050f8089');
expect(result).toBe('0xb2ec9b61699762491b6542278e9dfec9050f8089');
});

test('Returns empty string if public address fails to parse', async () => {
// Notice that public address should be undefined
const result = parsePublicAddressFromIssuer('did:ethr');
test.each([
'did:ethr',
'did:ethr:0x1234',
'did:key:0xB2ec9b61699762491b6542278E9dFEC9050f8089',
'did:ethr:0xB2ec9b61699762491b6542278E9dFEC9050f8089:&issuer=did:ethr:0x123',
'did:ethr:0xB2ec9b61699762491b6542278E9dFEC9050f8089\n',
'did:ethr:0xB2ec9b61699762491b6542278E9dFEC9050f8089\r\n',
' did:ethr:0xB2ec9b61699762491b6542278E9dFEC9050f8089',
])('Returns empty string for malformed issuer %s', async (issuer) => {
const result = parsePublicAddressFromIssuer(issuer);
expect(result).toBe('');
});

test('Returns empty string for a non-string issuer', async () => {
expect(parsePublicAddressFromIssuer(1234 as any)).toBe('');
});
20 changes: 20 additions & 0 deletions test/spec/utils/rest/get.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,23 @@ test('Successfully GETs to the given endpoint with no query params', async () =>
},
]);
});

test('Successfully GETs to the given endpoint with empty query params', async () => {
const fetchStub = jest.fn().mockImplementation(() => successRes);
(fetch as any) = fetchStub;

await get('https://example.com/hello/world', API_KEY, {});

expect(fetchStub.mock.calls[0][0]).toBe('https://example.com/hello/world');
});

test('Encodes reserved characters in query parameter values', async () => {
const fetchStub = jest.fn().mockImplementation(() => successRes);
(fetch as any) = fetchStub;

await get('https://example.com/hello/world', API_KEY, { issuer: 'did:ethr:0x1234:&issuer=value#fragment%+ ' });

expect(fetchStub.mock.calls[0][0]).toBe(
'https://example.com/hello/world?issuer=did%3Aethr%3A0x1234%3A%26issuer%3Dvalue%23fragment%25%2B+',
);
});
Loading