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
9 changes: 5 additions & 4 deletions api/src/controllers/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,7 @@ export class AuthController {
}
await this.everIdSessions.touchLastLogin(linked.id);
// Unlike the Google sign-in, no pending invite is accepted here: the account accepts them itself
const accessToken = await this.signOidcUserToken(user, identity.issuer, identity.sid);
const accessToken = await this.signOidcUserToken(user, identity.issuer, identity.subject, identity.sid);
return { data: { id: user.id, email: user.email, name: user.name, accessToken } };
}

Expand Down Expand Up @@ -634,7 +634,7 @@ export class AuthController {
);

await this.welcomeNewUser(account, true);
const accessToken = await this.signOidcUserToken(account, pending.issuer, pending.sid);
const accessToken = await this.signOidcUserToken(account, pending.issuer, pending.subject, pending.sid);
return { data: { id: account.id, email: account.email, name: account.name, accessToken } };
}

Expand Down Expand Up @@ -849,8 +849,9 @@ export class AuthController {
* Signs an access token for a sign-in with an OpenID Connect provider. Like any user token, plus the provider's
* session (`sid`), which a back-channel logout ends, and the token's own id (`jti`).
*/
private async signOidcUserToken(user: User, issuer: string, providerSid: string | undefined): Promise<string> {
const session = await this.everIdSessions.openSession(user.id, issuer, providerSid);
private async signOidcUserToken(user: User, issuer: string, subject: string, providerSid: string | undefined): Promise<string> {
// Only while the identity is still the account's (a disconnect at the same moment ends the sign-in)
const session = await this.everIdSessions.openSession(user.id, issuer, providerSid, subject);
if (!session) {
throw new AuthProviderException(HttpStatus.BAD_REQUEST, 'session_ended', 'This Ever ID session has ended, please sign in again');
}
Expand Down
29 changes: 22 additions & 7 deletions api/src/ever-connect/ever-connect-scheduler.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,10 @@
this.lastFeedAt = now;
await this.readFeed(this.settings.feedMode === 'longpoll' ? LONG_POLL_S : 0);
}
if (connection.status === 'active') {
// A statistics identity the operator reset is linked again within a tick (no feed event announces it)
await this.connect.syncStatsLink(connection.kid).catch(error => this.connect.handleCallError(error, 'stats_link', connection.kid));
}
if (connection.status === 'active' && this.person) {
await this.person.syncLinks().catch(error => this.connect.handleCallError(error, 'person_link', connection.kid));
}
Expand Down Expand Up @@ -205,15 +209,19 @@
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 });
// Only for the connection and the position this read started at (a reconnect meanwhile has its own cursor)
await this.connections.update(
{ id: CONNECTION_ID, kid: live.connection.kid, feedCursor: live.connection.feedCursor === null ? IsNull() : live.connection.feedCursor },

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

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer using nullish coalescing operator (`??`) instead of a ternary expression, as it is simpler to read.

See more on https://sonarcloud.io/project/issues?id=ever-co_ever-traduora&issues=AaH45uOjszKXbpItbWqB&open=AaH45uOjszKXbpItbWqB&pullRequest=635
{ feedCursor: lastId },
);
// 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 +243,10 @@
}
}
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 +276,18 @@
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
63 changes: 62 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,46 @@ 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;
let redemptions = 0;
const original = platform.factory;
Object.assign(platform, {
factory: (options => {
const client = original(options);
// Each redemption gets its own connection key, as Ever Platform gives
const redeem = client.redeem;
client.redeem = async input => ({ ...(await redeem(input)), kid: `kid-${++redemptions}` });
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 +213,27 @@ 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, scheduler } = 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 }]);

// Reset with a quiet feed: the scheduler links the new identity without an integration refresh
const reset = await instance.resetIdentity('u1');
expect(reset.instanceId).not.toBe(first);
platform.calls.length = 0;
await scheduler.tick();
await scheduler.tick();
expect(platform.names()).not.toContain('integrations');
expect(links()).toEqual([{ 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
61 changes: 43 additions & 18 deletions api/src/ever-connect/ever-connect.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { InjectRepository } from '@nestjs/typeorm';
import { CONSTANTS, codes, entitlementStatus, INTEGRATIONS, signCompactJws } from '@ever-co/connect-sdk';
import { createHash, randomInt, randomUUID } from 'crypto';
import { Repository } from 'typeorm';
import { IsNull, Repository } from 'typeorm';
import { EverConnectConnection } from '../entity/ever-connect-connection.entity';
import { EverConnectIntegration } from '../entity/ever-connect-integration.entity';
import { EverConnectPersonLink } from '../entity/ever-connect-person-link.entity';
Expand Down Expand Up @@ -387,17 +387,22 @@
if (!connection || connection.status === status) return;
// An answer about an earlier connection key never ends the connection that replaced it
if (kid !== undefined && kid !== connection.kid) return;
connection.status = status;
connection.nextHeartbeatAt = null;
connection.nextEntitlementAt = null;
connection.updatedAt = Date.now();
this.cachedClient = null;
// Ever Platform ended the person links and the consents with the connection (a later connection reads them again)
await this.connections.manager.transaction(async manager => {
await manager.save(connection);
// Ever Platform ended the person links and the consents with the connection (a later connection reads them again).
// Only the connection read above ends: the update matches its key and state, so a disconnect and a new connect
// made meanwhile by another API process are never overwritten, and its rows are deleted only after that update
const ended = await this.connections.manager.transaction(async manager => {
const { affected } = await manager.update(
EverConnectConnection,
{ id: CONNECTION_ID, kid: connection.kid === null ? IsNull() : connection.kid, status: connection.status },

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

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer using nullish coalescing operator (`??`) instead of a ternary expression, as it is simpler to read.

See more on https://sonarcloud.io/project/issues?id=ever-co_ever-traduora&issues=AaH4ockmpmwgqLNKHAOt&open=AaH4ockmpmwgqLNKHAOt&pullRequest=635
{ status, nextHeartbeatAt: null, nextEntitlementAt: null, updatedAt: Date.now() },
);
if (!affected) return false;
await manager.createQueryBuilder().delete().from(EverConnectIntegration).execute();
await manager.createQueryBuilder().delete().from(EverConnectPersonLink).execute();
return true;
});
if (!ended) return;
this.cachedClient = null;
await this.audit.record(`instance.${status}`, 'platform', reason);
this.logger.warn(`ever_connect.connection state=${status} reason=${reason}`);
}
Expand Down Expand Up @@ -491,7 +496,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,17 +562,35 @@
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);
}
if (key === 'stats_link') {
await this.syncStatsLink(live.connection.kid);

Check warning on line 566 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
}
}
return this.integrations();
}

/**
* Sends the statistics link while the `stats_link` integration is enabled and the current statistics identity is not
* the one linked: never sent, a failed send, or an identity the operator reset since. Two reads when nothing changed;
* run after each integration refresh and by the scheduler, so a reset identity is linked without waiting for an event.
*/
async syncStatsLink(kid: string | null): Promise<void> {
const row = await this.integrationRows.findOne({ where: { key: 'stats_link' } });
if (!row || row.state !== 'enabled') return;

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

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer using an optional chain expression instead, as it's more concise and easier to read.

See more on https://sonarcloud.io/project/issues?id=ever-co_ever-traduora&issues=AaH4ockmpmwgqLNKHAOu&open=AaH4ockmpmwgqLNKHAOu&pullRequest=635
const identity = await this.instance.read();
const linked = parseJson<{ linked?: boolean; statsInstanceId?: string }>(row.config, {});
if (linked.linked && identity && linked.statsInstanceId === identity.instanceId) return;
const sent = await this.linkStats('platform').catch(error => this.handleCallError(error, 'stats_link', kid).then(() => false as const));

Check warning on line 583 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=AaH4ockmpmwgqLNKHAOv&open=AaH4ockmpmwgqLNKHAOv&pullRequest=635
if (sent) {
// Only the config, and only while the same consent is still enabled: a switch-off made while the link was sent
// (state, pendingRemoteRevoke) is never undone, and a row deleted meanwhile is not written again
await this.integrationRows.update(
{ key: 'stats_link', state: 'enabled', consentId: row.consentId === null ? IsNull() : row.consentId, pendingRemoteRevoke: false },
{ config: JSON.stringify({ linked: true, statsInstanceId: sent }) },
);
}
}

/** The integrations of Traduora with their definitions, states and scopes (what each one moves). */
async integrations(): Promise<EverConnectIntegrationView[]> {
const rows = await this.integrationRows.find();
Expand Down Expand Up @@ -763,7 +787,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 +812,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;
}
}
22 changes: 22 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,28 @@ 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);
// A sign-in that read the identity before the disconnect gets no session
expect(await service.openSession(alice.id, 'https://idp.example.test', 'sid-late', 's1')).toBeUndefined();
});

it('opens a session for a named identity only while the account still has it', async () => {
await service.link(alice.id, identity('s1'), IdentityLinkMethod.Explicit);
const session = await service.openSession(alice.id, 'https://idp.example.test', 'sid-named', 's1');
expect(await service.isRevoked(session.sid, alice.id)).toBe(false);
// Another account's identity opens nothing
expect(await service.openSession(bob.id, 'https://idp.example.test', 'sid-other', 's1')).toBeUndefined();
});

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
Loading