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

Utilise Eddsa & Public Keys - Part 1 #791

Closed
wants to merge 19 commits into from
Closed
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
40 changes: 29 additions & 11 deletions examples/bri-3/prisma/seed.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { PrismaClient } from '@prisma/client';
import { PrismaClient, PublicKeyType } from '@prisma/client';
import { type } from 'os';

const prisma = new PrismaClient();

Expand All @@ -23,17 +24,34 @@ async function main() {

await prisma.bpiSubject.create({
data: {
name: 'BpiAdmin',
description: 'Internal Bpi Subject of this Bpi',
publicKey: '0x044e851fa6118d0d33f11ebf8d4cae2a25dca959f06c1ab87b8fec9ccbf0ca0021b7efc27c786f9480f9f11cfe8df1ae991329654308611148a35a2277ba5909fe',
// private key 0x0fbdb56ab0fecb2f406fa807d9e6558baedacc1c15c0e2703b77d4c08441e4fe, used for testing purposes only
loginNonce: '',
roles: {
connect: {
id: internalBpiSubjectRole.id
},
name: 'BpiAdmin',
description: 'Internal Bpi Subject of this Bpi',
publicKeys: {
createMany: {
data: [
{
type: PublicKeyType.ECDSA,
value:
'0x044e851fa6118d0d33f11ebf8d4cae2a25dca959f06c1ab87b8fec9ccbf0ca0021b7efc27c786f9480f9f11cfe8df1ae991329654308611148a35a2277ba5909fe',
},
biscuitdey marked this conversation as resolved.
Show resolved Hide resolved
// private key 0x0fbdb56ab0fecb2f406fa807d9e6558baedacc1c15c0e2703b77d4c08441e4fe, used for testing purposes only
{
type: PublicKeyType.EDDSA,
value:
'0x038a312f5b75fbd4f677c080c7f35089c898f2cb75002d659e051fdc1c6b3e06',
},
// TODO private key
],
},
}
},

loginNonce: '',
roles: {
connect: {
id: internalBpiSubjectRole.id,
},
},
},
});
}
main()
Expand Down
42 changes: 40 additions & 2 deletions examples/bri-3/src/bri/auth/agent/auth.agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { BpiSubject } from '../../../bri/identity/bpiSubjects/models/bpiSubject'
import { LoggingService } from '../../../shared/logging/logging.service';
import { INVALID_SIGNATURE, USER_NOT_AUTHORIZED } from '../api/err.messages';
import { jwtConstants } from '../constants';
import { buildBabyjub, buildEddsa } from 'circomlibjs';
import * as crypto from 'crypto';

@Injectable()
export class AuthAgent {
Expand All @@ -23,12 +25,14 @@ export class AuthAgent {
signature: string,
publicKey: string,
): void {
if (!this.verifySignatureAgainstPublicKey(message, signature, publicKey)) {
if (
!this.verifyEcdsaSignatureAgainstPublicKey(message, signature, publicKey)
) {
throw new UnauthorizedException(INVALID_SIGNATURE);
}
}

verifySignatureAgainstPublicKey(
verifyEcdsaSignatureAgainstPublicKey(
message: string,
signature: string,
senderPublicKey: string,
Expand Down Expand Up @@ -63,6 +67,40 @@ export class AuthAgent {
return isValid;
}

async verifyEddsaSignatureAgainstPublicKey(
message: string,
signature: string,
senderPublicKey: string,
): Promise<boolean> {
const eddsa = await buildEddsa();
const babyJub = await buildBabyjub();

const hashedPayload = crypto
.createHash(`${process.env.MERKLE_TREE_HASH_ALGH}`)
.update(JSON.stringify(message))
.digest();

const publicKey = Uint8Array.from(Buffer.from(signature, 'hex'));
const publicKeyPoints = babyJub.unpackPoint(publicKey);

const eddsaSignature = Uint8Array.from(Buffer.from(signature, 'hex'));
const unpackedSignature = eddsa.unpackSignature(eddsaSignature);

const isValid = eddsa.verifyPedersen(
hashedPayload,
unpackedSignature,
publicKeyPoints,
);

if (!isValid) {
this.logger.logWarn(
`Signature: ${signature} for public key ${senderPublicKey} is invalid.`,
);
}

return isValid;
}

async getBpiSubjectByPublicKey(publicKey: string) {
return this.bpiSubjectStorageAgent.getBpiSubjectByPublicKey(publicKey);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ import { MessageController } from './messages.controller';
import { mockDeep, DeepMockProxy } from 'jest-mock-extended';
import { PrismaService } from '../../../shared/prisma/prisma.service';
import { PrismaClient } from '@prisma/client';
import {
PublicKey,
PublicKeyType,
} from '../../identity/bpiSubjects/models/publicKey';

describe('MessageController', () => {
let mController: MessageController;
Expand All @@ -56,14 +60,29 @@ describe('MessageController', () => {
'',
'name',
'desc',
'0x047a197a795a747c154dd92b217a048d315ef9ca1bfa9c15bfefe4e02fb338a70af23e7683b565a8dece5104a85ed24a50d791d8c5cb09ee21aabc927c98516539',
[
new PublicKey(
'123',
PublicKeyType.ECDSA,
'0x047a197a795a747c154dd92b217a048d315ef9ca1bfa9c15bfefe4e02fb338a70af23e7683b565a8dece5104a85ed24a50d791d8c5cb09ee21aabc927c98516539',
'',
),
],

[],
);
existingBpiSubject2 = new BpiSubject(
'',
'name2',
'desc2',
'0x04203db7d27bab8d711acc52479efcfa9d7846e4e176d82389689f95cf06a51818b0b9ab1c2c8d72f1a32e236e6296c91c922a0dc3d0cb9afc269834fc5646b980',
[
new PublicKey(
'123',
PublicKeyType.ECDSA,
'0x04203db7d27bab8d711acc52479efcfa9d7846e4e176d82389689f95cf06a51818b0b9ab1c2c8d72f1a32e236e6296c91c922a0dc3d0cb9afc269834fc5646b980',
'',
),
],
[],
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export class CreateBpiMessageCommandHandler
this.authAgent.throwIfSignatureVerificationFails(
command.content,
command.signature,
fromBpiSubject.publicKey,
fromBpiSubject.publicKeys[0].value,
);

const newBpiMessageCandidate = this.agent.createNewBpiMessage(
Expand All @@ -47,7 +47,7 @@ export class CreateBpiMessageCommandHandler
);

await this.messagingAgent.publishMessage(
toBpiSubject.publicKey,
toBpiSubject.publicKeys[0].value,
this.messagingAgent.serializeBpiMessage(newBpiMessage),
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,12 @@ export class ProcessInboundMessageCommandHandler
return false;
}

const isSignatureValid = this.authAgent.verifySignatureAgainstPublicKey(
command.content,
command.signature,
fromBpiSubject.publicKey,
);
const isSignatureValid =
this.authAgent.verifyEcdsaSignatureAgainstPublicKey(
command.content,
command.signature,
fromBpiSubject.publicKeys[0].value,
);

if (!isSignatureValid) {
return false;
Expand All @@ -55,7 +56,7 @@ export class ProcessInboundMessageCommandHandler
);

await this.messagingAgent.publishMessage(
toBpiSubject.publicKey,
toBpiSubject.publicKeys[0].value,
this.messagingAgent.serializeBpiMessage(newBpiMessage),
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { SubjectsProfile } from '../../bpiSubjects/subjects.profile';
import { mockDeep, DeepMockProxy } from 'jest-mock-extended';
import { BpiSubjectAccount } from '../models/bpiSubjectAccount';
import { uuid } from 'uuidv4';
import { PublicKey, PublicKeyType } from '../../bpiSubjects/models/publicKey';

describe('SubjectAccountController', () => {
let subjectAccountController: SubjectAccountController;
Expand Down Expand Up @@ -70,14 +71,14 @@ describe('SubjectAccountController', () => {
'123',
'owner',
'desc',
'publicKey',
[new PublicKey('223', PublicKeyType.ECDSA, 'publicKey', '123')],
[],
);
const creatorBpiSubject = new BpiSubject(
'321',
'creator',
'desc',
'publicKey',
[new PublicKey('223', PublicKeyType.ECDSA, 'publicKey', '321')],
[],
);

Expand Down Expand Up @@ -195,7 +196,7 @@ describe('SubjectAccountController', () => {
'123',
'owner',
'desc',
'publicKey',
[new PublicKey('223', PublicKeyType.ECDSA, 'publicKey', '123')],
[],
);
const creatorBpiSubjectId = 'not-existing-id';
Expand All @@ -219,7 +220,7 @@ describe('SubjectAccountController', () => {
'123',
'creator',
'desc',
'publicKey',
[new PublicKey('223', PublicKeyType.ECDSA, 'publicKey', '123')],
[],
);
const ownerBpiSubjectId = 'not-existing-id';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import {
} from '../api/err.messages';
import { BpiSubjectStorageAgent } from './bpiSubjectsStorage.agent';
import { BpiSubjectRoleName } from '../models/bpiSubjectRole';
import { PublicKeyDto } from '../api/dtos/request/publicKey.dto';
import { PublicKey, PublicKeyType } from '../models/publicKey';

// Agent methods have extremely declarative names and perform a single task
@Injectable()
Expand All @@ -27,12 +29,36 @@ export class BpiSubjectAgent {
public async createNewExternalBpiSubject(
name: string,
description: string,
publicKey: string,
publicKeys: PublicKeyDto[],
): Promise<BpiSubject> {
const externalRole = await this.storageAgent.getBpiSubjectRoleByName(
BpiSubjectRoleName.EXTERNAL_BPI_SUBJECT,
);
return new BpiSubject(v4(), name, description, publicKey, [externalRole]);

const bpiSubjectId = v4();

const publicKeyCandidates = publicKeys.map((key) => {
let publicKeyType;

switch (key.type.toLowerCase()) {
case 'ecdsa':
publicKeyType = PublicKeyType.ECDSA;
break;
case 'eddsa':
publicKeyType = PublicKeyType.EDDSA;
break;
default:
}
return new PublicKey(v4(), publicKeyType, key.value, bpiSubjectId);
});

return new BpiSubject(
bpiSubjectId,
name,
description,
publicKeyCandidates,
[externalRole],
);
}

public async fetchUpdateCandidateAndThrowIfUpdateValidationFails(
Expand Down Expand Up @@ -64,11 +90,11 @@ export class BpiSubjectAgent {
bpiSubjectToUpdate: BpiSubject,
name: string,
description: string,
publicKey: string,
publicKeys: PublicKeyDto[],
) {
bpiSubjectToUpdate.updateName(name);
bpiSubjectToUpdate.updateDescription(description);
bpiSubjectToUpdate.updatePublicKey(publicKey);
bpiSubjectToUpdate.updatePublicKeys(publicKeys);
}

public async fetchDeleteCandidateAndThrowIfDeleteValidationFails(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,8 @@ export class BpiSubjectStorageAgent extends PrismaService {
};
}),
},
publicKey: {
connect: bpiSubject.publicKeys.map((pk) => {
return {
id: pk.id,
};
}),
publicKeys: {
createMany: { data: bpiSubject.publicKeys },
},
},
});
Expand All @@ -131,12 +127,12 @@ export class BpiSubjectStorageAgent extends PrismaService {
};
}),
},
publicKey: {
connect: bpiSubject.publicKeys.map((pk) => {
return {
id: pk.id,
};
}),
publicKeys: {
upsert: bpiSubject.publicKeys.map((pk) => ({
where: { id: pk.id },
create: { type: pk.type, value: pk.value },
update: { value: pk.value },
})),
},
},
});
Expand All @@ -152,14 +148,14 @@ export class BpiSubjectStorageAgent extends PrismaService {
async getBpiSubjectByPublicKey(publicKeyValue: string): Promise<BpiSubject> {
const bpiSubjectModel = await this.prisma.bpiSubject.findFirst({
where: {
publicKey: {
publicKeys: {
some: {
value: publicKeyValue,
},
},
},
include: {
publicKey: true,
publicKeys: true,
},
});

Expand Down
Loading
Loading