Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
22 changes: 17 additions & 5 deletions api/src/controllers/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,8 @@ export class AuthController {
code_verifier?: string;
}): Promise<{ data: { id: string; email: string; name: string; accessToken: string } }> {
const slug = payload.provider;
// Before the code exchange and the account checks: a subject-only logout after this ends the sign-in
const signedInAt = Date.now();
const identity = await this.verifyOidcCode(slug, payload);

const linked = await this.everIdSessions.findIdentity(identity.issuer, identity.subject);
Expand Down Expand Up @@ -562,7 +564,10 @@ export class AuthController {
throw new AuthProviderException(HttpStatus.FORBIDDEN, 'signup_disabled', 'Signups are invitation based only.');
}

const pending = this.everIdSessions.seal({ purpose: 'signup', ...this.everIdSessions.pendingFrom(slug, identity) }, SIGNUP_PENDING_TTL_SECONDS);
const pending = this.everIdSessions.seal(
{ purpose: 'signup', ...this.everIdSessions.pendingFrom(slug, identity), signedInAt },
SIGNUP_PENDING_TTL_SECONDS,
);
throw new AuthProviderException(HttpStatus.CONFLICT, 'signup_confirmation_required', 'Confirm to create your account', {
pending,
name: identity.name,
Expand Down Expand Up @@ -634,7 +639,13 @@ export class AuthController {
);

await this.welcomeNewUser(account, true);
const accessToken = await this.signOidcUserToken(account, pending.issuer, pending.subject, pending.sid);
const accessToken = await this.signOidcUserToken(
account,
pending.issuer,
pending.subject,
pending.sid,
new Date(typeof pending.signedInAt === 'number' ? pending.signedInAt : (pending.exp - SIGNUP_PENDING_TTL_SECONDS) * 1000),
);
return { data: { id: account.id, email: account.email, name: account.name, accessToken } };
}

Expand Down Expand Up @@ -849,9 +860,10 @@ 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, 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);
private async signOidcUserToken(user: User, issuer: string, subject: string, providerSid: string | undefined, signedInAt?: Date): Promise<string> {
// Only while the identity is still the account's (a disconnect at the same moment ends the sign-in), and not after
// a logout that named only the subject once the person signed in with the provider
const session = await this.everIdSessions.openSession(user.id, issuer, providerSid, subject, signedInAt);
if (!session) {
throw new AuthProviderException(HttpStatus.BAD_REQUEST, 'session_ended', 'This Ever ID session has ended, please sign in again');
}
Expand Down
11 changes: 11 additions & 0 deletions api/src/ever-connect/ever-connect-person.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,17 @@ describeOnSqlite('EverConnectPersonService', () => {
expect(platform.calls).toEqual([]);
});

it('stops a round once the scheduler lost its lease', async () => {
const { connect, person } = await connected();
await enableEverIdLogin(connect);
await linkIdentity(alice, 's1', { method: IdentityLinkMethod.Explicit });
await linkIdentity(bob, 's2', { method: IdentityLinkMethod.Jit });
let asked = 0;
expect(await person.syncLinks(Date.now(), true, async () => ++asked <= 1)).toEqual({ reported: 1, removed: 0 });
// The next round (with the lease) reports the other one
expect(await person.syncLinks(Date.now(), true)).toEqual({ reported: 1, removed: 0 });
});

it('reports each Ever ID a user signed in with, once, and never anything else', async () => {
const { connect, person } = await connected();
await enableEverIdLogin(connect);
Expand Down
26 changes: 24 additions & 2 deletions api/src/ever-connect/ever-connect-person.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import { EverConnectPlatformClient, PersonRequestAnswer, PlatformEvent, problemOf } from './ever-connect-platform.client';
import { CONNECTION_ID, EverConnectService } from './ever-connect.service';
import { EVER_CONNECT_SETTINGS, EverConnectSettings } from './ever-connect.settings';
import { lockAccount } from '../services/ever-id-session.service';

/** The feed events of a person's requests, by the kind of request. */
export const PERSON_REQUEST_TYPES: Readonly<Record<string, 'deletion' | 'export'>> = Object.freeze({
Expand Down Expand Up @@ -291,6 +292,11 @@
*/
private async deleteIdentities(manager: EntityManager, matches: IdentityRow[]): Promise<void> {
const now = Date.now();
// Each account's row locked first, as a sign-in that opens a session locks it (in one order: two deletions never
// deadlock), so a sign-in that read the identity just before cannot open a session once it is removed
for (const userId of Array.from(new Set(matches.map(identity => identity.userId))).sort((a, b) => a.localeCompare(b))) {
await lockAccount(manager, userId);

Check warning on line 298 in api/src/ever-connect/ever-connect-person.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=AaH52uefDWcCRGzbciLm&open=AaH52uefDWcCRGzbciLm&pullRequest=638
}
for (const identity of matches) {
await manager.update(EverIdSession, { userId: identity.userId, revokedAt: IsNull() }, { revokedAt: new Date(now) });
await manager.delete(UserIdentity, { id: identity.id });
Expand Down Expand Up @@ -482,7 +488,11 @@
* tenant link) is reported, while the integration allows it. A call that fails is tried again an hour later, so other
* links go first meanwhile. Calls nothing while there is nothing to tell.
*/
async syncLinks(now = Date.now(), force = false): Promise<{ reported: number; removed: number }> {
/**
* `keepLease` is asked before each call to Ever Platform (the scheduler renews its lease there): once it answers
* false, another API process holds the background calls and this round stops.
*/
async syncLinks(now = Date.now(), force = false, keepLease?: () => Promise<boolean>): Promise<{ reported: number; removed: number }> {

Check failure on line 495 in api/src/ever-connect/ever-connect-person.service.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 57 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=ever-co_ever-traduora&issues=AaH52uefDWcCRGzbciLn&open=AaH52uefDWcCRGzbciLn&pullRequest=638
if (!force && !this.syncRequested && now - this.lastSyncAt < PERSON_LINK_SYNC_MS) {
return { reported: 0, removed: 0 };
}
Expand All @@ -504,8 +514,15 @@
let reported = 0;

// Removals first: a removal names the user, so a link reported for the same user afterwards is not removed with it
let leaseLost = false;
const leaseHeld = async (): Promise<boolean> => {
if (!keepLease || (await keepLease())) return true;
leaseLost = true;
return false;
};
for (const row of await this.links.find()) {
if (byId.has(row.userIdentityId) || waiting(row) || calls >= PERSON_LINK_CALLS_PER_SYNC) continue;
if (!(await leaseHeld())) break;
calls += 1;
try {
await client.removePersonLink(row.userId);
Expand All @@ -522,6 +539,9 @@
removed += 1;
}

if (leaseLost) {
return { reported, removed };
}
if (!(await this.reporting())) {
// Nothing is reported while the integration is off; once it is on again, every link is reported again
await this.links.update({ reportedAt: Not(IsNull()) }, { reportedAt: null, tenantLinkId: null, updatedAt: now });
Expand All @@ -533,7 +553,9 @@
const row = known.get(identity.id);
const current = !!row && !!row.reportedAt && row.tenantLinkId === tenantLinkId;
if (current || waiting(row) || calls >= PERSON_LINK_CALLS_PER_SYNC) continue;
// Checked again before each report: once the integration is switched off here, no further report starts
if (!(await leaseHeld())) break;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// Checked again before each report (after the lease renewal): once the integration is switched off here, no
// further report starts
if (!(await this.reporting())) break;
calls += 1;
try {
Expand Down
15 changes: 13 additions & 2 deletions api/src/ever-connect/ever-connect-scheduler.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,11 @@ export class EverConnectSchedulerService implements OnModuleInit, OnModuleDestro
return result.affected === 1;
}

/** Extends the lease while this process still holds it; false once another process took it over. */
private renew(): Promise<boolean> {
return this.acquire(Date.now());
}

private async release(): Promise<void> {
await this.connections
.createQueryBuilder()
Expand Down Expand Up @@ -175,16 +180,22 @@ export class EverConnectSchedulerService implements OnModuleInit, OnModuleDestro
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));
// Long rounds renew the lease before each call and stop once another process holds it
if (!(await this.renew())) return;
await this.person
.syncLinks(Date.now(), false, () => this.renew())
.catch(error => this.connect.handleCallError(error, 'person_link', connection.kid));
Comment thread
evereq marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
if (connection.status === 'active' && this.managed) {
// Stop when another process took the lease during the person-link round
if (!(await this.renew())) return;
const live = await this.connect.liveClient();
// Only for the connection that is still active now (the feed may have ended it)
if (live && live.connection.status === 'active' && live.connection.kid === connection.kid) {
// Not while a state refresh of the feed failed: a revoked consent may not have been applied yet
if (!this.feedFailed) {
await this.managed
.runDue(live.client, connection.kid, Date.now(), () => this.isCurrent(connection.kid))
.runDue(live.client, connection.kid, Date.now(), async () => (await this.renew()) && (await this.isCurrent(connection.kid)))
.catch(error => this.connect.handleCallError(error, 'managed', connection.kid));
}
}
Expand Down
33 changes: 33 additions & 0 deletions api/src/ever-connect/ever-connect.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,39 @@ describe('EverConnectService', () => {
expect(links()).toEqual([{ statsInstanceId: reset.instanceId }]);
});

it('never lets a refresh undo an integration the operator switched off while it read the states', async () => {
let during: (() => Promise<void>) | null = null;
const original = platform.factory;
Object.assign(platform, {
factory: (options => {
const client = original(options);
const integrations = client.integrations;
client.integrations = async () => {
const states = await integrations();
if (during) {
const run = during;
during = null;
await run();
}
return states;
};
return client;
}) as typeof platform.factory,
});
const { connect } = build();
await connect.connect('EVC-TEST-0000-0001', '', 'user:u1');
platform.integrationStates.instance_url = { state: 'enabled', enabled: true, consentId: 'c1', scopeVersion: 1 };
await connect.refreshIntegrations();
expect((await connect.integrations()).find(view => view.key === 'instance_url').state).toBe('enabled');

// The states are read as enabled, then the operator switches the integration off before they are stored
during = async () => {
await connect.disableIntegration('instance_url', 'user:u1');
};
const views = await connect.refreshIntegrations();
expect(views.find(view => view.key === 'instance_url').state).toBe('disabled');
});

it('waits for approval, reading only its own state, then starts', async () => {
const { connect, scheduler } = build();
platform.redeemStatus = 'pending_approval';
Expand Down
46 changes: 43 additions & 3 deletions api/src/ever-connect/ever-connect.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { CONSTANTS, codes, entitlementStatus, INTEGRATIONS, signCompactJws } from '@ever-co/connect-sdk';
import { createHash, randomInt, randomUUID } from 'crypto';
import { IsNull, Repository } from 'typeorm';
import { isUniqueViolation } from '../services/ever-id-session.service';
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 @@ -530,6 +531,10 @@
if (!live) {
return this.integrations();
}
// When each row last changed before the remote states were read: a row changed meanwhile (an operator switched the
// integration off or on) keeps that local decision; the next refresh reads both again
const decision = (row: EverConnectIntegration) => `${row.updatedAt}|${row.state}|${row.pendingRemoteRevoke}|${row.consentId}`;
const readAt = new Map((await this.integrationRows.find()).map(row => [row.key, decision(row)]));
const states = await live.client.integrations();
// A disconnect (or another connection) while the states were read: they belong to a connection that has ended
const current = await this.read();
Expand All @@ -538,8 +543,15 @@
}
for (const key of TRADUORA_INTEGRATIONS) {
const remote = states[key];
const row =
(await this.integrationRows.findOne({ where: { key } })) || Object.assign(new EverConnectIntegration(), { key, pendingRemoteRevoke: false });
const stored = await this.integrationRows.findOne({ where: { key } });

Check warning on line 546 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=AaH52uXpDWcCRGzbciLk&open=AaH52uXpDWcCRGzbciLk&pullRequest=638
if (stored ? decision(stored) !== readAt.get(key) : readAt.has(key)) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
continue;
Comment thread
evereq marked this conversation as resolved.
Resolved
}
// The decision as read: the write below applies only while the row still holds it
const seen = stored
? { updatedAt: stored.updatedAt, state: stored.state, pendingRemoteRevoke: stored.pendingRemoteRevoke, consentId: stored.consentId }
: null;
const row = stored || Object.assign(new EverConnectIntegration(), { key, pendingRemoteRevoke: false });
const before = row.state;
const remoteState = remote ? remote.state : INTEGRATIONS[key].status === 'coming_soon' ? 'coming_soon' : 'available';
// Switched off here while Ever Platform could not be told: it stays off here until the revoke is delivered
Expand All @@ -557,7 +569,35 @@
if (key === 'stats_link' && row.state !== 'enabled') {
row.config = null;
}
await this.integrationRows.save(row);
if (seen) {
// One statement compares and writes: a switch-off that lands after the read above wins, and nothing follows
const { affected } = await this.integrationRows.update(
{
key,
updatedAt: seen.updatedAt,
state: seen.state,
pendingRemoteRevoke: seen.pendingRemoteRevoke,
consentId: seen.consentId === null ? IsNull() : seen.consentId,
},
{
state: row.state,
consentId: row.consentId,
scopeVersion: row.scopeVersion,
pendingRemoteRevoke: row.pendingRemoteRevoke,
updatedAt: row.updatedAt,
config: row.config,
},
);

Check warning on line 590 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=AaH6hlIHptuosZlfyWtq&open=AaH6hlIHptuosZlfyWtq&pullRequest=638
if (!affected) continue;
Comment thread
evereq marked this conversation as resolved.
Resolved
} else {
try {
await this.integrationRows.insert(row);

Check warning on line 594 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=AaH6hlIHptuosZlfyWtr&open=AaH6hlIHptuosZlfyWtr&pullRequest=638
} catch (error) {
// Another refresh or a local decision created the row meanwhile: it stands
if (isUniqueViolation(error)) continue;
throw error;
}
}
// A first reading that finds nothing on is not a change
if (before !== row.state && (before !== undefined || (row.state !== 'available' && row.state !== 'coming_soon'))) {
await this.audit.record('integration.state', 'platform', `${key}=${row.state}`);
Expand Down
11 changes: 11 additions & 0 deletions api/src/services/ever-id-session.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,17 @@ describeOnSqlite('EverIdSessionService', () => {
expect(await service.isRevoked(bobs.sid, bob.id)).toBe(false);
});

it('refuses a pending sign-in made before a logout that named only the subject', async () => {
await service.link(alice.id, identity('s1'), IdentityLinkMethod.Explicit);
const signedIn = new Date(Date.now() - 5000);
await service.revokeIdentity(ISSUER, 's1');
expect(await service.openSession(alice.id, ISSUER, 'sid-pending', 's1', signedIn)).toBeUndefined();
// A sign-in made after the logout opens its session
const later = await service.openSession(alice.id, ISSUER, 'sid-after', 's1', new Date(Date.now() + 5000));
expect(later).toBeDefined();
expect(await service.isRevoked(later.sid, alice.id)).toBe(false);
});

it('accepts a logout token id once per issuer, and again after it was released', async () => {
expect(await service.rememberLogoutJti(ISSUER, 'jti-1')).toBe(true);
expect(await service.rememberLogoutJti(ISSUER, 'jti-1')).toBe(false);
Expand Down
Loading