Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
19 changes: 13 additions & 6 deletions api/src/ever-connect/ever-connect-scheduler.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,15 +205,15 @@ export class EverConnectSchedulerService implements OnModuleInit, OnModuleDestro
const problem = problemOf(error);
if (problem && problem.status === 410) {
// The position is older than what Ever Platform keeps: read the state again, then continue from where it says
await this.applyTypes(['ever.consent', 'ever.entitlements', 'ever.registry.tenant_link']);
await this.applyTypes(['ever.consent', 'ever.entitlements', 'ever.registry.tenant_link'], live.connection.kid);
const lastId = (error as { lastId?: string }).lastId || null;
if (lastId) await live.client.ack(lastId);
await this.connections.update({ id: CONNECTION_ID }, { feedCursor: lastId });
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// The state was read again in full: due work no longer waits for an earlier failed page
this.feedFailed = false;
return 0;
}
await this.connect.handleCallError(error, 'feed');
await this.connect.handleCallError(error, 'feed', live.connection.kid);
return 0;
}
if (!page.events.length) {
Expand All @@ -235,7 +235,10 @@ export class EverConnectSchedulerService implements OnModuleInit, OnModuleDestro
}
}
try {
await this.applyTypes(page.events.map(event => event.type));
await this.applyTypes(
page.events.map(event => event.type),
live.connection.kid,
);
// After the state refresh: a consent in the same page counts for a request that follows it, and a page that
// ended the connection runs no maintenance work
if (this.managed && !failures.length && (await this.isCurrent(live.connection.kid))) {
Expand Down Expand Up @@ -265,14 +268,18 @@ export class EverConnectSchedulerService implements OnModuleInit, OnModuleDestro
return page.events.length;
}

private async applyTypes(types: string[]): Promise<void> {
/**
* Applies what a page (or a full re-read) is about. `kid` is the key of the connection the page was read for: a page
* read before a disconnect and a new connect never ends or changes the connection that replaced it.
*/
private async applyTypes(types: string[], kid: string | null): Promise<void> {
const has = (prefix: string) => types.some(type => type.startsWith(prefix));
if (types.includes('ever.registry.instance.revoked')) {
await this.connect.endedByPlatform('revoked', 'feed');
await this.connect.endedByPlatform('revoked', 'feed', kid);
Comment thread
evereq marked this conversation as resolved.
Resolved
return;
}
if (types.includes('ever.registry.instance.disconnected')) {
await this.connect.endedByPlatform('disconnected', 'feed');
await this.connect.endedByPlatform('disconnected', 'feed', kid);
return;
}
if (has('ever.registry.tenant_link')) {
Expand Down
56 changes: 55 additions & 1 deletion api/src/ever-connect/ever-connect.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ describe('EverConnectService', () => {
audit,
);
const scheduler = new EverConnectSchedulerService(dataSource.getRepository(EverConnectConnection), { ...SETTINGS, ...settings }, connect, false);
return { connect, scheduler, audit };
return { connect, scheduler, audit, instance };
};

beforeEach(async () => {
Expand Down Expand Up @@ -132,6 +132,42 @@ describe('EverConnectService', () => {
expect(connection.feedCursor).toBe('e1');
});

it('never lets a feed page read for an earlier connection end the connection that replaced it', async () => {
// The operator disconnects and connects again while the old connection's long poll is still waiting
let reconnect: (() => Promise<void>) | null = null;
const original = platform.factory;
Object.assign(platform, {
factory: (options => {
const client = original(options);
const events = client.events;
client.events = async (cursor, waitS) => {
const page = await events(cursor, waitS);
if (reconnect) {
const run = reconnect;
reconnect = null;
await run();
}
return page;
};
return client;
}) as typeof platform.factory,
});
const { connect, scheduler } = build();
await connect.connect('EVC-TEST-0000-0001', '', 'user:u1');
const before = (await connect.read()).kid;
reconnect = async () => {
await connect.disconnect('user:u1');
await connect.connect('EVC-TEST-0000-0001', '', 'user:u1');
};
platform.events = [{ id: 'e7', type: 'ever.registry.instance.disconnected' }];

await scheduler.readFeed(0);

const after = await connect.read();
expect(after.kid).not.toBe(before);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
expect(after.status).toBe('active');
});

it('sets the public address only after the instance_url consent', async () => {
const { connect } = build();
await connect.connect('EVC-TEST-0000-0001', '', 'user:u1');
Expand Down Expand Up @@ -173,6 +209,24 @@ describe('EverConnectService', () => {
expect(views.find(view => view.key === 'stats_link').state).toBe('enabled');
});

it('links the statistics again after the operator resets the instance identity', async () => {
const { connect, instance } = build({ statsLoaded: true });
await connect.connect('EVC-TEST-0000-0001', '', 'user:u1');
platform.integrationStates.stats_link = { state: 'enabled', enabled: true, consentId: 'c3', scopeVersion: 1 };
const links = () => platform.calls.filter(call => call.name === 'statsLink').map(call => call.args[0]);

await connect.refreshIntegrations();
await connect.refreshIntegrations();
const first = (await instance.read()).instanceId;
expect(links()).toEqual([{ statsInstanceId: first }]);

const reset = await instance.resetIdentity('u1');
expect(reset.instanceId).not.toBe(first);
await connect.refreshIntegrations();
await connect.refreshIntegrations();
expect(links()).toEqual([{ statsInstanceId: first }, { statsInstanceId: reset.instanceId }]);
});

it('waits for approval, reading only its own state, then starts', async () => {
const { connect, scheduler } = build();
platform.redeemStatus = 'pending_approval';
Expand Down
26 changes: 18 additions & 8 deletions api/src/ever-connect/ever-connect.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -491,7 +491,8 @@
const { connection, client } = live;
const self = await client.self();
if (self.status === 'revoked' || self.status === 'disconnected') {
await this.endedByPlatform(self.status, 'state');
// An answer read for a connection that was replaced meanwhile never ends the new one
await this.endedByPlatform(self.status, 'state', connection.kid);
return;
}
const status = self.status === 'active' || self.status === 'pending_approval' ? self.status : connection.status;
Expand Down Expand Up @@ -556,11 +557,19 @@
if (before !== row.state && (before !== undefined || (row.state !== 'available' && row.state !== 'coming_soon'))) {
await this.audit.record('integration.state', 'platform', `${key}=${row.state}`);
}
// The statistics link is sent until it succeeded once for this consent (a failed send is tried again here)
if (key === 'stats_link' && row.state === 'enabled' && !parseJson<{ linked?: boolean }>(row.config, {}).linked) {
if (await this.linkStats('platform').catch(error => this.handleCallError(error, 'stats_link', live.connection.kid).then(() => false))) {
row.config = JSON.stringify({ linked: true });
await this.integrationRows.save(row);
// The statistics link is sent until it succeeded once for this consent and the current statistics identity: a
// failed send is tried again here, and so is a link of an identity the operator reset since
if (key === 'stats_link' && row.state === 'enabled') {
const identity = await this.instance.read();

Check warning on line 563 in api/src/ever-connect/ever-connect.service.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Unexpected `await` inside a loop.

See more on https://sonarcloud.io/project/issues?id=ever-co_ever-traduora&issues=AaH4mLHeyXQRtUv_dPbl&open=AaH4mLHeyXQRtUv_dPbl&pullRequest=635
const linked = parseJson<{ linked?: boolean; statsInstanceId?: string }>(row.config, {});
if (!linked.linked || !identity || linked.statsInstanceId !== identity.instanceId) {
const sent = await this.linkStats('platform').catch(error =>
Comment thread
evereq marked this conversation as resolved.
Resolved
this.handleCallError(error, 'stats_link', live.connection.kid).then(() => false as const),

Check warning on line 567 in api/src/ever-connect/ever-connect.service.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Avoid nesting promises.

See more on https://sonarcloud.io/project/issues?id=ever-co_ever-traduora&issues=AaH4mLHeyXQRtUv_dPbn&open=AaH4mLHeyXQRtUv_dPbn&pullRequest=635
);

Check warning on line 568 in api/src/ever-connect/ever-connect.service.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Unexpected `await` inside a loop.

See more on https://sonarcloud.io/project/issues?id=ever-co_ever-traduora&issues=AaH4mLHeyXQRtUv_dPbm&open=AaH4mLHeyXQRtUv_dPbm&pullRequest=635
if (sent) {
row.config = JSON.stringify({ linked: true, statsInstanceId: sent });
await this.integrationRows.save(row);
}
}
}
}
Expand Down Expand Up @@ -763,7 +772,8 @@
* `stats_link`: links the anonymous statistics of this installation to its organization, with a statement signed by
* the statistics key (the connection key never signs it). Only when the statistics are loaded.
*/
async linkStats(actorRef: string): Promise<boolean> {
/** Sends the statistics link. Returns the statistics instance id it linked, or `false` when nothing was sent. */
async linkStats(actorRef: string): Promise<string | false> {
if (!this.settings.statsLoaded || this.settings.integrationsDeny.includes('stats_link')) {
return false;
}
Expand All @@ -787,6 +797,6 @@
);
await live.client.statsLink({ statement, statsInstanceId: record.instanceId, statsPublicKey: record.statsPublicKey }, randomUUID());
await this.audit.record('stats_link.sent', actorRef, null);
return true;
return record.instanceId;
}
}
12 changes: 12 additions & 0 deletions api/src/services/ever-id-session.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,18 @@ describeOnSqlite('EverIdSessionService', () => {
expect(await service.listForUser(alice.id)).toEqual([]);
});

it('ends the Ever ID sessions of the account when one of its identities is removed', async () => {
const alices = (await service.link(alice.id, identity('s1'), IdentityLinkMethod.Explicit)) as UserIdentity;
const session = await service.openSession(alice.id, 'https://idp.example.test', 'sid-unlink');
const bobs = await service.openSession(bob.id, 'https://idp.example.test', 'sid-bob');
expect(await service.isRevoked(session.sid, alice.id)).toBe(false);

expect(await service.unlink(alice.id, alices.id)).toBe('removed');
expect(await service.isRevoked(session.sid, alice.id)).toBe(true);
// Another account keeps its sessions
expect(await service.isRevoked(bobs.sid, bob.id)).toBe(false);
});

it('removes the identities of a deleted account', async () => {
await service.link(bob.id, identity('s2'), IdentityLinkMethod.Jit);
await dataSource.getRepository(User).delete({ id: bob.id });
Expand Down
8 changes: 6 additions & 2 deletions api/src/services/ever-id-session.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,8 +168,9 @@ export class EverIdSessionService implements OnApplicationBootstrap, OnModuleDes
}

/**
* Removes one of the account's identities. Returns 'not_found' when the account has no such identity, and
* 'last_sign_in_method' when it would leave the account without any way to sign in (no password, no other identity).
* Removes one of the account's identities and ends the account's Ever ID sessions. Returns 'not_found' when the
* account has no such identity, and 'last_sign_in_method' when it would leave the account without any way to sign in
* (no password, no other identity).
*/
async unlink(userId: string, identityId: string): Promise<'removed' | 'not_found' | 'last_sign_in_method'> {
// With the account's row locked: two disconnects at once must not remove its last two ways to sign in
Expand All @@ -184,6 +185,9 @@ export class EverIdSessionService implements OnApplicationBootstrap, OnModuleDes
return 'last_sign_in_method' as const;
}
await entityManager.delete(UserIdentity, { id: identity.id });
// Sessions record the account, not the identity: end the account's Ever ID sessions, so a token issued through
// the removed identity stops working now (a later logout that names only its subject can no longer find it)
await entityManager.update(EverIdSession, { userId, revokedAt: IsNull() }, { revokedAt: new Date() });
Comment thread
evereq marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return 'removed' as const;
});
}
Expand Down