Skip to content

Commit

Permalink
Merge pull request #14 from logion-network/feature/update-authenticator
Browse files Browse the repository at this point in the history
Update authenticator, clean-up useless stuff.
  • Loading branch information
benoitdevos authored Apr 11, 2024
2 parents 7f89948 + 167eb2f commit b7d50b0
Show file tree
Hide file tree
Showing 10 changed files with 58 additions and 100 deletions.
6 changes: 3 additions & 3 deletions integration/Session.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import { DateTime } from "luxon";
import { runOnTransactionCommit, runOnTransactionRollback } from "typeorm-transactional";
import { connect, executeScript, disconnect, checkNumOfRows } from "../src/TestDb.js";
import { DefaultTransactional, SessionAggregateRoot, SessionRepository } from "../src/index.js";
import { validAccountId } from "../src/TestUtil.js";
import { ValidAccountId } from "@logion/node-api";

const userAddress = validAccountId('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY');
const unknownAddress = validAccountId('5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty');
const userAddress = ValidAccountId.polkadot('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY');
const unknownAddress = ValidAccountId.polkadot('5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty');
const existingSessionId = '0d9c1ca7-a2c5-48f7-b0fb-e66a977bc7b5';
const anotherExistingSessionId = 'fc4bfdc6-9e79-4959-9dd5-fde5b38f1f88';
const unknownSessionId = '5c03194a-1c07-4c7d-b9eb-3df722c15ae9';
Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@logion/rest-api-core",
"version": "0.4.8-6",
"version": "0.4.8-7",
"repository": {
"type": "git",
"url": "git+https://github.com/logion-network/logion-rest-api-core.git"
Expand All @@ -26,7 +26,7 @@
"coverage": "nyc yarn run test"
},
"dependencies": {
"@logion/authenticator": "^0.5.6-4",
"@logion/authenticator": "^0.5.6-5",
"dinoloop": "^2.4.0",
"express": "^4.18.2",
"express-fileupload": "^1.4.0",
Expand All @@ -39,7 +39,7 @@
},
"devDependencies": {
"@istanbuljs/nyc-config-typescript": "^1.0.2",
"@logion/node-api": "^0.29.0-2",
"@logion/node-api": "^0.29.0-4",
"@tsconfig/node16": "^16.1.1",
"@types/express": "^4.17.14",
"@types/express-fileupload": "^1.4.1",
Expand Down
2 changes: 1 addition & 1 deletion src/AuthenticationService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export class AuthenticationService {
}
}

get nodeOwner(): string {
get nodeOwner(): ValidAccountId {
return this.authenticationSystemFactory.nodeOwner;
}
}
5 changes: 3 additions & 2 deletions src/AuthenticationSystemFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Duration } from "luxon";
import PeerId from "peer-id";

import { PolkadotService } from "./PolkadotService.js";
import { ValidAccountId } from "@logion/node-api";

export function unauthorized(error: string): UnauthorizedException<{ error: string }> {
return new UnauthorizedException({ error });
Expand Down Expand Up @@ -45,7 +46,7 @@ export class AuthenticationSystemFactory {
this.tokenConfig = {
nodePeerId: PeerId.createFromB58String(process.env.JWT_ISSUER),
nodeKey: Buffer.from(process.env.JWT_SECRET, "hex"),
nodeOwner: process.env.OWNER,
nodeOwner: ValidAccountId.polkadot(process.env.OWNER),
jwtTimeToLive: Duration.fromObject({ seconds: Number(process.env.JWT_TTL_SEC) }),
};
}
Expand All @@ -54,7 +55,7 @@ export class AuthenticationSystemFactory {

private _authenticationSystem: AuthenticationSystem | undefined;

get nodeOwner(): string {
get nodeOwner(): ValidAccountId {
return this.tokenConfig.nodeOwner;
}
}
23 changes: 10 additions & 13 deletions src/TestApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,10 @@ import { Mock } from "moq.ts";
import { AuthenticationService } from "./AuthenticationService.js";
import { UnauthorizedException } from "dinoloop/modules/builtin/exceptions/exceptions.js";
import { buildBaseExpress } from "./Express.js";
import { AccountId, AnyAccountId } from "@logion/node-api";
import { AccountId, AnyAccountId, ValidAccountId } from "@logion/node-api";

export const ALICE = "vQx5kESPn8dWyX4KxMCKqUyCaWUwtui1isX6PVNcZh2Ghjitr";
export const BOB = "vQvWaxNDdzuX5N3qSvGMtjdHcQdw1TAcPNgx4S1Utd3MTxYeN";
const ALICE_ACCOUNT = new AnyAccountId(ALICE, "Polkadot").toValidAccountId();

export * from "./TestUtil.js";
export const BOB = ValidAccountId.polkadot("vQvWaxNDdzuX5N3qSvGMtjdHcQdw1TAcPNgx4S1Utd3MTxYeN");
export const ALICE = ValidAccountId.polkadot("vQx5kESPn8dWyX4KxMCKqUyCaWUwtui1isX6PVNcZh2Ghjitr");

export function setupApp<T>(
controller: Function & { prototype: T; }, // eslint-disable-line @typescript-eslint/ban-types
Expand Down Expand Up @@ -66,7 +63,7 @@ export interface AuthenticationServiceMock {
authenticatedUser: () => Promise<AuthenticatedUser>;
authenticatedUserIs: () => Promise<AuthenticatedUser>;
authenticatedUserIsOneOf: () => Promise<AuthenticatedUser>;
nodeOwner: string;
nodeOwner: ValidAccountId;
ensureAuthorizationBearer: () => void;
}

Expand Down Expand Up @@ -118,7 +115,7 @@ export function mockAuthenticationForUserOrLegalOfficer(isLegalOfficer: boolean,
const authenticatedUser = new Mock<AuthenticatedUser>();
const validAccount = account ?
new AnyAccountId(account.address, account.type).toValidAccountId() :
ALICE_ACCOUNT;
ALICE;
authenticatedUser.setup(instance => instance.address).returns(validAccount.address);
authenticatedUser.setup(instance => instance.type).returns(validAccount.type);
authenticatedUser.setup(instance => instance.isPolkadot()).returns(validAccount.type === "Polkadot");
Expand All @@ -140,7 +137,7 @@ export function mockAuthenticationForUserOrLegalOfficer(isLegalOfficer: boolean,
throw new UnauthorizedException();
}
})
authenticatedUser.setup(instance => instance.toValidAccountId()).returns(validAccount)
authenticatedUser.setup(instance => instance.validAccountId).returns(validAccount)
return mockAuthenticationWithAuthenticatedUser(authenticatedUser.object());
}

Expand All @@ -161,7 +158,7 @@ export function mockAuthenticatedUser(conditionFulfilled: boolean, account?: Acc
const authenticatedUser = new Mock<AuthenticatedUser>();
const validAccount = account ?
new AnyAccountId(account.address, account.type).toValidAccountId() :
ALICE_ACCOUNT;
ALICE;
authenticatedUser.setup(instance => instance.address).returns(validAccount.address);
authenticatedUser.setup(instance => instance.type).returns(validAccount.type);
authenticatedUser.setup(instance => instance.isPolkadot()).returns(validAccount.type === "Polkadot");
Expand All @@ -177,13 +174,13 @@ export function mockAuthenticatedUser(conditionFulfilled: boolean, account?: Acc
authenticatedUser.setup(instance => instance.isNodeOwner).returns(() => conditionFulfilled);
authenticatedUser.setup(instance => instance.isLegalOfficer()).returnsAsync(conditionFulfilled);
authenticatedUser.setup(instance => instance.requireLegalOfficerOnNode).returns(() => {
if (account?.address === ALICE) {
if (ALICE.equals(account)) {
return Promise.resolve(authenticatedUser.object());
} else {
throw new UnauthorizedException();
}
});
authenticatedUser.setup(instance => instance.toValidAccountId()).returns(validAccount)
authenticatedUser.setup(instance => instance.validAccountId).returns(validAccount)
return authenticatedUser.object();
}

Expand All @@ -205,7 +202,7 @@ export function mockLegalOfficerOnNode(account: AccountId): AuthenticatedUser {
authenticatedUser.setup(instance => instance.isNodeOwner()).returns(true);
authenticatedUser.setup(instance => instance.isLegalOfficer()).returnsAsync(true);
authenticatedUser.setup(instance => instance.requireLegalOfficerOnNode()).returns(Promise.resolve(authenticatedUser.object()));
authenticatedUser.setup(instance => instance.toValidAccountId()).returns(validAccount)
authenticatedUser.setup(instance => instance.validAccountId).returns(validAccount)
return authenticatedUser.object();
}

Expand Down
28 changes: 0 additions & 28 deletions src/TestUtil.ts

This file was deleted.

51 changes: 25 additions & 26 deletions test/AuthenticationController.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import {
setupApp,
ALICE,
BOB,
validAccountId,
} from "../src/TestApp.js";
import { ValidAccountId } from "@logion/node-api";

Expand All @@ -45,8 +44,8 @@ describe("AuthenticationController", () => {
.post('/api/auth/sign-in')
.send({
addresses: [
validAccountId(ALICE).toKey(),
validAccountId(BOB).toKey(),
ALICE.toKey(),
BOB.toKey(),
]
})
.expect(200)
Expand All @@ -61,12 +60,12 @@ describe("AuthenticationController", () => {
const authenticateRequest: AuthenticateRequestView = {
signatures: {}
};
authenticateRequest.signatures![validAccountId(ALICE).toKey()] = {
authenticateRequest.signatures![ALICE.toKey()] = {
signature: "signature-ALICE",
signedOn: TIMESTAMP,
type: "POLKADOT",
};
authenticateRequest.signatures![validAccountId(BOB).toKey()] = {
authenticateRequest.signatures![BOB.toKey()] = {
signature: "signature-BOB",
signedOn: TIMESTAMP,
type: "POLKADOT",
Expand All @@ -79,8 +78,8 @@ describe("AuthenticationController", () => {
.expect('Content-Type', /application\/json/)
.then(response => {
expect(response.body.tokens).toBeDefined();
expect(response.body.tokens[validAccountId(ALICE).toKey()].value).toBe(TOKEN_ALICE);
expect(response.body.tokens[validAccountId(BOB).toKey()].value).toBe(TOKEN_BOB);
expect(response.body.tokens[ALICE.toKey()].value).toBe(TOKEN_ALICE);
expect(response.body.tokens[BOB.toKey()].value).toBe(TOKEN_BOB);
});
})

Expand All @@ -89,12 +88,12 @@ describe("AuthenticationController", () => {
const authenticateRequest: AuthenticateRequestView = {
signatures: {}
};
authenticateRequest.signatures![validAccountId(ALICE).toKey()] = {
authenticateRequest.signatures![ALICE.toKey()] = {
signature: "signature-ALICE",
signedOn: TIMESTAMP,
type: "POLKADOT",
};
authenticateRequest.signatures![validAccountId(BOB).toKey()] = {
authenticateRequest.signatures![BOB.toKey()] = {
signature: "signature-BOB",
signedOn: TIMESTAMP,
type: "POLKADOT",
Expand All @@ -115,12 +114,12 @@ describe("AuthenticationController", () => {
const authenticateRequest: AuthenticateRequestView = {
signatures: {}
};
authenticateRequest.signatures![validAccountId(ALICE).toKey()] = {
authenticateRequest.signatures![ALICE.toKey()] = {
signature: "signature-ALICE",
signedOn: TIMESTAMP,
type: "POLKADOT",
};
authenticateRequest.signatures![validAccountId(BOB).toKey()] = {
authenticateRequest.signatures![BOB.toKey()] = {
signature: "signature-BOB",
signedOn: TIMESTAMP,
type: "POLKADOT",
Expand All @@ -141,12 +140,12 @@ describe("AuthenticationController", () => {
const authenticateRequest: AuthenticateRequestView = {
signatures: {}
};
authenticateRequest.signatures![`Unknown:${ ALICE }`] = {
authenticateRequest.signatures![`Unknown:${ ALICE.address }`] = {
signature: "signature-ALICE",
signedOn: TIMESTAMP,
type: "POLKADOT",
};
authenticateRequest.signatures![`Unknown:${ BOB }`] = {
authenticateRequest.signatures![`Unknown:${ BOB.address }`] = {
signature: "signature-BOB",
signedOn: TIMESTAMP,
type: "POLKADOT",
Expand All @@ -173,18 +172,18 @@ function mockDependenciesForSignIn(container: Container): void {
container.bind(SessionFactory).toConstantValue(sessionFactory.object());

const aliceSession = new Mock<SessionAggregateRoot>();
aliceSession.setup(instance => instance.userAddress).returns(ALICE);
aliceSession.setup(instance => instance.userAddress).returns(ALICE.address);

sessionFactory.setup(instance => instance.newSession(It.Is<NewSessionParameters>(
params => params.account.address === ALICE && params.account.type === "Polkadot"
params => params.account.equals(ALICE)
)))
.returns(aliceSession.object());

const bobSession = new Mock<SessionAggregateRoot>();
bobSession.setup(instance => instance.userAddress).returns(BOB);
bobSession.setup(instance => instance.userAddress).returns(BOB.address);

sessionFactory.setup(instance => instance.newSession(It.Is<NewSessionParameters>(
params => params.account.address === BOB && params.account.type === "Polkadot"
params => params.account.equals(BOB)
)))
.returns(bobSession.object());

Expand Down Expand Up @@ -222,18 +221,18 @@ function mockDependenciesForAuth(container: Container, verifies: boolean, sessio
});

const session = new Mock<Session>();
session.setup(instance => instance.addresses).returns([ ALICE, BOB ]);
session.setup(instance => instance.addresses).returns([ ALICE.address, BOB.address ]);

if(verifies) {
const signatures: SessionSignature[] = [
{
address: ALICE,
address: ALICE.address,
signature: "SIG_ALICE",
signedOn: requireDefined(DateTime.now().toISO()),
type: "POLKADOT",
},
{
address: BOB,
address: BOB.address,
signature: "SIG_BOB",
signedOn: requireDefined(DateTime.now().toISO()),
type: "POLKADOT",
Expand All @@ -246,13 +245,13 @@ function mockDependenciesForAuth(container: Container, verifies: boolean, sessio
const tokens: Token[] = [
{
type: "Polkadot",
address: ALICE,
address: ALICE.address,
value: TOKEN_ALICE,
expiredOn: DateTime.now(),
},
{
type: "Polkadot",
address: BOB,
address: BOB.address,
value: TOKEN_BOB,
expiredOn: DateTime.now(),
}
Expand All @@ -268,23 +267,23 @@ function mockDependenciesForAuth(container: Container, verifies: boolean, sessio
const sessionRepository = new Mock<SessionRepository>();
if (sessionExists) {
sessionRepository.setup(instance => instance.find(
It.Is<ValidAccountId>(accountId => accountId.address === ALICE && accountId.type === "Polkadot"),
It.Is<ValidAccountId>(accountId => accountId.equals(ALICE)),
SESSION_ID)
)
.returns(Promise.resolve(sessionAlice.object()))
sessionRepository.setup(instance => instance.find(
It.Is<ValidAccountId>(accountId => accountId.address === BOB && accountId.type === "Polkadot"),
It.Is<ValidAccountId>(accountId => accountId.equals(BOB)),
SESSION_ID)
)
.returns(Promise.resolve(sessionAlice.object()))
} else {
sessionRepository.setup(instance => instance.find(
It.Is<ValidAccountId>(accountId => accountId.address === ALICE && accountId.type === "Polkadot"),
It.Is<ValidAccountId>(accountId => accountId.equals(ALICE)),
SESSION_ID)
)
.returns(Promise.resolve(null))
sessionRepository.setup(instance => instance.find(
It.Is<ValidAccountId>(accountId => accountId.address === BOB && accountId.type === "Polkadot"),
It.Is<ValidAccountId>(accountId => accountId.equals(BOB)),
SESSION_ID)
)
.returns(Promise.resolve(null))
Expand Down
4 changes: 2 additions & 2 deletions test/Session.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ import { DateTime } from "luxon";
import { v4 as uuid } from "uuid";

import { SessionFactory, SessionAggregateRoot, NewSessionParameters } from "../src/index.js";
import { ALICE, validAccountId } from "../src/TestApp.js";
import { ALICE } from "../src/TestApp.js";

describe("SessionFactory", () => {

it("createSession", () => {
const sessionId = givenSessionId()
const params: NewSessionParameters = {
sessionId,
account: validAccountId(ALICE),
account: ALICE,
createdOn: DateTime.now()
}
whenCreatingSession(params);
Expand Down
11 changes: 0 additions & 11 deletions test/TestUtil.spec.ts

This file was deleted.

Loading

0 comments on commit b7d50b0

Please sign in to comment.