@contember/engine-tenant-api 2.2.0-alpha.7 → 2.2.0-alpha.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/development/src/TenantContainer.cjs +5 -2
- package/dist/development/src/TenantContainer.cjs.map +1 -1
- package/dist/development/src/TenantContainer.js +5 -2
- package/dist/development/src/TenantContainer.js.map +1 -1
- package/dist/development/src/model/commands/apiKey/ProlongApiKeyCommand.cjs +5 -8
- package/dist/development/src/model/commands/apiKey/ProlongApiKeyCommand.cjs.map +1 -1
- package/dist/development/src/model/commands/apiKey/ProlongApiKeyCommand.js +5 -8
- package/dist/development/src/model/commands/apiKey/ProlongApiKeyCommand.js.map +1 -1
- package/dist/development/src/model/commands/authLog/CreateAuthLogEntryCommand.cjs.map +1 -1
- package/dist/development/src/model/commands/authLog/CreateAuthLogEntryCommand.js.map +1 -1
- package/dist/development/src/model/service/IDPSignInManager.cjs +23 -15
- package/dist/development/src/model/service/IDPSignInManager.cjs.map +1 -1
- package/dist/development/src/model/service/IDPSignInManager.js +23 -15
- package/dist/development/src/model/service/IDPSignInManager.js.map +1 -1
- package/dist/development/src/model/service/idp/IdpSessionRevalidator.cjs +42 -31
- package/dist/development/src/model/service/idp/IdpSessionRevalidator.cjs.map +1 -1
- package/dist/development/src/model/service/idp/IdpSessionRevalidator.js +42 -31
- package/dist/development/src/model/service/idp/IdpSessionRevalidator.js.map +1 -1
- package/dist/production/src/TenantContainer.cjs +5 -2
- package/dist/production/src/TenantContainer.cjs.map +1 -1
- package/dist/production/src/TenantContainer.js +5 -2
- package/dist/production/src/TenantContainer.js.map +1 -1
- package/dist/production/src/model/commands/apiKey/ProlongApiKeyCommand.cjs +5 -8
- package/dist/production/src/model/commands/apiKey/ProlongApiKeyCommand.cjs.map +1 -1
- package/dist/production/src/model/commands/apiKey/ProlongApiKeyCommand.js +5 -8
- package/dist/production/src/model/commands/apiKey/ProlongApiKeyCommand.js.map +1 -1
- package/dist/production/src/model/commands/authLog/CreateAuthLogEntryCommand.cjs.map +1 -1
- package/dist/production/src/model/commands/authLog/CreateAuthLogEntryCommand.js.map +1 -1
- package/dist/production/src/model/service/IDPSignInManager.cjs +23 -15
- package/dist/production/src/model/service/IDPSignInManager.cjs.map +1 -1
- package/dist/production/src/model/service/IDPSignInManager.js +23 -15
- package/dist/production/src/model/service/IDPSignInManager.js.map +1 -1
- package/dist/production/src/model/service/idp/IdpSessionRevalidator.cjs +42 -31
- package/dist/production/src/model/service/idp/IdpSessionRevalidator.cjs.map +1 -1
- package/dist/production/src/model/service/idp/IdpSessionRevalidator.js +42 -31
- package/dist/production/src/model/service/idp/IdpSessionRevalidator.js.map +1 -1
- package/dist/tests/cases/integration/mocked/sql/sqlTransaction.d.ts +5 -0
- package/dist/tests/cases/integration/mocked/sql/sqlTransaction.d.ts.map +1 -1
- package/dist/tests/src/IdPMock.d.ts.map +1 -1
- package/dist/tests/src/testTenant.d.ts.map +1 -1
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/dist/types/TenantContainer.d.ts +2 -0
- package/dist/types/TenantContainer.d.ts.map +1 -1
- package/dist/types/model/commands/apiKey/ProlongApiKeyCommand.d.ts +5 -3
- package/dist/types/model/commands/apiKey/ProlongApiKeyCommand.d.ts.map +1 -1
- package/dist/types/model/commands/authLog/CreateAuthLogEntryCommand.d.ts +1 -0
- package/dist/types/model/commands/authLog/CreateAuthLogEntryCommand.d.ts.map +1 -1
- package/dist/types/model/service/IDPSignInManager.d.ts +3 -1
- package/dist/types/model/service/IDPSignInManager.d.ts.map +1 -1
- package/dist/types/model/service/idp/IdpSessionRevalidator.d.ts +3 -1
- package/dist/types/model/service/idp/IdpSessionRevalidator.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +12 -12
- package/src/TenantContainer.ts +7 -2
- package/src/model/commands/apiKey/ProlongApiKeyCommand.ts +10 -11
- package/src/model/commands/authLog/CreateAuthLogEntryCommand.ts +1 -0
- package/src/model/service/IDPSignInManager.ts +26 -14
- package/src/model/service/idp/IdpSessionRevalidator.ts +43 -28
- package/tests/cases/integration/mocked/signInIdpMutation.test.ts +100 -1
- package/tests/cases/integration/mocked/sql/sqlTransaction.ts +16 -0
- package/tests/cases/unit/apiKey/prolongApiKeyCommand.test.ts +19 -9
- package/tests/cases/unit/idp/idpSessionRevalidator.test.ts +37 -4
- package/tests/src/IdPMock.ts +2 -0
- package/tests/src/testTenant.ts +1 -0
|
@@ -33,10 +33,11 @@ const CreateIdpSessionCommand = require("../commands/idp/CreateIdpSessionCommand
|
|
|
33
33
|
const Password = require("../dtos/Password.cjs");
|
|
34
34
|
const AuthLogService = require("./AuthLogService.cjs");
|
|
35
35
|
class IDPSignInManager {
|
|
36
|
-
constructor(apiKeyManager, idpRegistry, claimSyncService) {
|
|
36
|
+
constructor(apiKeyManager, idpRegistry, claimSyncService, logger) {
|
|
37
37
|
this.apiKeyManager = apiKeyManager;
|
|
38
38
|
this.idpRegistry = idpRegistry;
|
|
39
39
|
this.claimSyncService = claimSyncService;
|
|
40
|
+
this.logger = logger;
|
|
40
41
|
}
|
|
41
42
|
async signInIDP(dbContext, idpSlug, responseData, expiration, requestInfo, trustForwardedInfo) {
|
|
42
43
|
return dbContext.transaction(async (db) => {
|
|
@@ -96,7 +97,8 @@ class IDPSignInManager {
|
|
|
96
97
|
let claimMappingFailed = false;
|
|
97
98
|
try {
|
|
98
99
|
mapping = ClaimMapping.parseClaimMapping(provider.configuration);
|
|
99
|
-
} catch {
|
|
100
|
+
} catch (e) {
|
|
101
|
+
this.logger.warn(e, { message: "IdP sign-in: claim mapping configuration is invalid", identityProviderId: provider.id });
|
|
100
102
|
claimMappingFailed = true;
|
|
101
103
|
}
|
|
102
104
|
let claimMappingAudit = null;
|
|
@@ -125,19 +127,25 @@ class IDPSignInManager {
|
|
|
125
127
|
if (!hasTokens || db.providers.encryptionEnabled) {
|
|
126
128
|
await db.commandBus.execute(new CreateIdpSessionCommand.CreateIdpSessionCommand(apiKeyId, provider.id, claim.idpSession));
|
|
127
129
|
} else {
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
130
|
+
try {
|
|
131
|
+
await db.commandBus.transaction(
|
|
132
|
+
(bus) => bus.execute(
|
|
133
|
+
new CreateAuthLogEntryCommand.CreateAuthLogEntryCommand({
|
|
134
|
+
type: "idp_session_revalidation_failed",
|
|
135
|
+
invokedById: personRow.identity_id,
|
|
136
|
+
personId: personRow.id,
|
|
137
|
+
identityProviderId: provider.id,
|
|
138
|
+
success: true,
|
|
139
|
+
errorCode: "encryption_disabled",
|
|
140
|
+
ipAddress: requestInfo?.ip,
|
|
141
|
+
userAgent: requestInfo?.userAgent,
|
|
142
|
+
eventData: { apiKeyId }
|
|
143
|
+
})
|
|
144
|
+
)
|
|
145
|
+
);
|
|
146
|
+
} catch (e) {
|
|
147
|
+
this.logger.error(e, { message: "IdP sign-in: writing the encryption_disabled audit entry failed", identityProviderId: provider.id });
|
|
148
|
+
}
|
|
141
149
|
}
|
|
142
150
|
}
|
|
143
151
|
return new Response.ResponseOk({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IDPSignInManager.cjs","sources":["../../../../../../packages/engine-tenant-api/src/model/service/IDPSignInManager.ts"],"sourcesContent":["import { ApiKeyManager } from './apiKey/index.js'\nimport { IdentityProviderBySlugQuery, PersonByIdPQuery, PersonQuery, PersonRow } from '../queries/index.js'\nimport { IDPHandlerRegistry, IDPResponse, IDPResponseError, IDPValidationError } from './idp/index.js'\nimport { Response, ResponseError, ResponseOk } from '../utils/Response.js'\nimport { InitSignInIdpErrorCode, InitSignInIdpResult, SignInIdpErrorCode } from '../../schema/index.js'\nimport { DatabaseContext } from '../utils/index.js'\nimport { ApiKeyRequestInfo, CreateIdentityCommand, CreatePersonCommand, CreatePersonIdentityProviderIdentifierCommand } from '../commands/index.js'\nimport { CreateIdpSessionCommand } from '../commands/idp/CreateIdpSessionCommand.js'\nimport { CreateAuthLogEntryCommand } from '../commands/authLog/CreateAuthLogEntryCommand.js'\nimport { TenantRole } from '../authorization/index.js'\nimport { NoPassword } from '../dtos/index.js'\nimport { IdentityProviderRow } from '../queries/idp/types.js'\nimport { AuthLogService } from './AuthLogService.js'\nimport { ClaimMappingAudit, IDPClaimSyncService } from './idp/IDPClaimSyncService.js'\nimport { ClaimMapping, parseClaimMapping } from './idp/ClaimMapping.js'\n\nclass IDPSignInManager {\n\tconstructor(\n\t\tprivate readonly apiKeyManager: ApiKeyManager,\n\t\tprivate readonly idpRegistry: IDPHandlerRegistry,\n\t\tprivate readonly claimSyncService: IDPClaimSyncService,\n\t) {}\n\n\tasync signInIDP(\n\t\tdbContext: DatabaseContext,\n\t\tidpSlug: string,\n\t\tresponseData: unknown,\n\t\texpiration?: number,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<IDPSignInManager.SignInIDPResponse> {\n\t\treturn dbContext.transaction(async (db): Promise<IDPSignInManager.SignInIDPResponse> => {\n\t\t\tconst provider = await db.queryHandler.fetch(new IdentityProviderBySlugQuery(idpSlug))\n\t\t\tif (!provider || provider.disabledAt) {\n\t\t\t\tthrow new Error('provider not found')\n\t\t\t}\n\t\t\tconst providerService = this.idpRegistry.getHandler(provider.type)\n\t\t\tconst validatedConfig = providerService.validateConfiguration(provider.configuration)\n\t\t\tlet claim: IDPResponse\n\t\t\ttry {\n\t\t\t\tclaim = await providerService.processResponse(\n\t\t\t\t\tvalidatedConfig,\n\t\t\t\t\tresponseData,\n\t\t\t\t)\n\t\t\t} catch (e) {\n\t\t\t\tif (e instanceof IDPResponseError) {\n\t\t\t\t\treturn new ResponseError('INVALID_IDP_RESPONSE', e.message, {\n\t\t\t\t\t\t[AuthLogService.Key]: new AuthLogService.Bag({\n\t\t\t\t\t\t\tpersonId: undefined,\n\t\t\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\t\t}),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tif (e instanceof IDPValidationError) {\n\t\t\t\t\treturn new ResponseError('IDP_VALIDATION_FAILED', e.message, {\n\t\t\t\t\t\t[AuthLogService.Key]: new AuthLogService.Bag({\n\t\t\t\t\t\t\tpersonId: undefined,\n\t\t\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\t\t}),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tthrow e\n\t\t\t}\n\t\t\tconst resolved = await this.resolvePerson(db, claim, provider)\n\t\t\tconst personRow = resolved.person\n\n\t\t\tif (!personRow) {\n\t\t\t\t// Keep the external error generic (no account-existence leak), but\n\t\t\t\t// record the email-verification gate block distinctly in the audit\n\t\t\t\t// log — it is a takeover-grade event, not an ordinary \"not found\".\n\t\t\t\treturn new ResponseError('PERSON_NOT_FOUND', `Person ${claim.email} not found`, {\n\t\t\t\t\t[AuthLogService.Key]: new AuthLogService.Bag({\n\t\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\t\tpersonInput: claim.email,\n\t\t\t\t\t\tpersonId: resolved.blockedPersonId,\n\t\t\t\t\t\teventData: resolved.blockedReason ? { reason: resolved.blockedReason } : undefined,\n\t\t\t\t\t}),\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (personRow.disabled_at !== null) {\n\t\t\t\treturn new ResponseError('PERSON_DISABLED', `Person with e-mail ${claim.email} is disabled`, {\n\t\t\t\t\t[AuthLogService.Key]: new AuthLogService.Bag({\n\t\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\t\tpersonInput: claim.email,\n\t\t\t\t\t\tpersonId: personRow.id,\n\t\t\t\t\t}),\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// A09 — map IdP claims to project memberships. Returns a `{ before, after }` delta only\n\t\t\t// when something actually changed; the resolver emits the `idp_role_mapped` audit from it\n\t\t\t// (audit stays at the resolver layer).\n\t\t\t//\n\t\t\t// Fail-open on a MALFORMED/out-of-band `claimMapping`: parsing is caught so a bad config can\n\t\t\t// never lock the user out — sign-in proceeds without claim mapping and the resolver emits an\n\t\t\t// `idp_role_mapping_failed` marker. A DB error during the apply itself is NOT caught: it\n\t\t\t// propagates and rolls back the whole sign-in transaction, so a half-applied set of grants is\n\t\t\t// never committed (failing sign-in on an infra error is the safe outcome).\n\t\t\tlet mapping: ClaimMapping | null = null\n\t\t\tlet claimMappingFailed = false\n\t\t\ttry {\n\t\t\t\tmapping = parseClaimMapping(provider.configuration)\n\t\t\t} catch {\n\t\t\t\tclaimMappingFailed = true\n\t\t\t}\n\t\t\tlet claimMappingAudit: ClaimMappingAudit | null = null\n\t\t\tif (mapping) {\n\t\t\t\tconst syncResult = await this.claimSyncService.sync(\n\t\t\t\t\tdb,\n\t\t\t\t\tmapping,\n\t\t\t\t\tclaim,\n\t\t\t\t\t{ id: personRow.identity_id },\n\t\t\t\t\tresolved.isNewPerson === true,\n\t\t\t\t)\n\t\t\t\tclaimMappingAudit = syncResult.audit\n\t\t\t\t// The apply-time safety backstop dropped a configured rule (config-time validation was skipped, or\n\t\t\t\t// the project's ACL drifted since): surface the same fail-open marker as a malformed config, so a\n\t\t\t\t// silently-unapplied grant is visible to the operator. The resolver emits `idp_role_mapping_failed`.\n\t\t\t\tif (syncResult.droppedUnsafeRules) {\n\t\t\t\t\tclaimMappingFailed = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst { id: apiKeyId, token: sessionToken } = await this.apiKeyManager.createSessionApiKeyWithId(\n\t\t\t\tdb,\n\t\t\t\tpersonRow.identity_id,\n\t\t\t\texpiration,\n\t\t\t\trequestInfo,\n\t\t\t\ttrustForwardedInfo,\n\t\t\t)\n\n\t\t\t// Bind the federated-session state to this session so it can be re-validated\n\t\t\t// against the IdP later. Present only when the provider supports it and\n\t\t\t// revalidation is enabled on the IdP configuration (A24). Refresh tokens must be\n\t\t\t// encrypted at rest, so when no encryption key is configured we skip persisting a\n\t\t\t// token-bearing session (it would otherwise crash or store secrets in plaintext) —\n\t\t\t// the session then behaves like a plain session with no re-validation.\n\t\t\tif (claim.idpSession) {\n\t\t\t\tconst hasTokens = !!claim.idpSession.tokens && Object.keys(claim.idpSession.tokens).length > 0\n\t\t\t\tif (!hasTokens || db.providers.encryptionEnabled) {\n\t\t\t\t\tawait db.commandBus.execute(new CreateIdpSessionCommand(apiKeyId, provider.id, claim.idpSession))\n\t\t\t\t} else {\n\t\t\t\t\t// Re-validation is enabled on this IdP but no encryption key is configured, so we\n\t\t\t\t\t// won't store the token-bearing session — it silently degrades to a plain,\n\t\t\t\t\t// non-revalidated session. Audit the downgrade (errorCode `encryption_disabled`)\n\t\t\t\t\t// so the operator can see that a session they expected to be continuously\n\t\t\t\t\t// re-validated is in fact not protected, instead of failing closed at sign-in.\n\t\t\t\t\tawait db.commandBus.execute(\n\t\t\t\t\t\tnew CreateAuthLogEntryCommand({\n\t\t\t\t\t\t\ttype: 'idp_session_revalidation_failed',\n\t\t\t\t\t\t\tinvokedById: personRow.identity_id,\n\t\t\t\t\t\t\tpersonId: personRow.id,\n\t\t\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\t\t\tpersonTokenId: apiKeyId,\n\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\terrorCode: 'encryption_disabled',\n\t\t\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\t\t}),\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn new ResponseOk({\n\t\t\t\tperson: personRow,\n\t\t\t\ttoken: sessionToken,\n\t\t\t\tidpResponse: claim,\n\t\t\t\tclaimMappingAudit,\n\t\t\t\tclaimMappingFailed,\n\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t[AuthLogService.Key]: new AuthLogService.Bag({\n\t\t\t\t\tpersonId: personRow.id,\n\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\tpersonInput: claim.email,\n\t\t\t\t}),\n\t\t\t})\n\t\t})\n\t}\n\n\tasync initSignInIDP(dbContext: DatabaseContext, idpSlug: string, data: unknown): Promise<IDPSignInManager.InitSignInIDPResponse> {\n\t\tconst provider = await dbContext.queryHandler.fetch(new IdentityProviderBySlugQuery(idpSlug))\n\t\tif (!provider || provider.disabledAt) {\n\t\t\treturn new ResponseError('PROVIDER_NOT_FOUND', `Identity provider ${idpSlug} not found`)\n\t\t}\n\t\tconst providerService = this.idpRegistry.getHandler(provider.type)\n\t\tconst validatedConfig = providerService.validateConfiguration(provider.configuration)\n\t\ttry {\n\t\t\tconst initResponse = await providerService.initAuth(validatedConfig, data)\n\n\t\t\tconst publicConfig = providerService.getPublicConfiguration\n\t\t\t\t? providerService.getPublicConfiguration(validatedConfig)\n\t\t\t\t: validatedConfig\n\n\t\t\treturn new ResponseOk({\n\t\t\t\t...initResponse,\n\t\t\t\tidpConfiguration: provider.initReturnsConfig ? publicConfig : null,\n\t\t\t})\n\t\t} catch (e) {\n\t\t\tif (e instanceof IDPValidationError) {\n\t\t\t\treturn new ResponseError('IDP_VALIDATION_FAILED', e.message)\n\t\t\t}\n\t\t\tthrow e\n\t\t}\n\t}\n\n\tprivate async resolvePerson(db: DatabaseContext, claim: IDPResponse, provider: IdentityProviderRow): Promise<IDPSignInManager.ResolvePersonResult> {\n\t\tconst personByIdPQuery = new PersonByIdPQuery(provider.id, claim.externalIdentifier)\n\t\tconst personByIdp = await db.queryHandler.fetch(personByIdPQuery)\n\t\tif (personByIdp) {\n\t\t\treturn { person: personByIdp }\n\t\t}\n\n\t\tif (!provider.exclusive) {\n\t\t\tconst personByEmail = typeof claim.email === 'string' && claim.email\n\t\t\t\t? await db.queryHandler.fetch(PersonQuery.byEmail(claim.email))\n\t\t\t\t: null\n\t\t\tif (personByEmail) {\n\t\t\t\t// Auto-linking an IdP identity to a pre-existing local account by\n\t\t\t\t// e-mail is takeover-grade: if the provider returns an unverified\n\t\t\t\t// (or attacker-controlled) e-mail, it could hijack the account. When\n\t\t\t\t// the provider requires a verified e-mail, refuse to link — and to\n\t\t\t\t// sign in — unless the address is asserted verified. `assumeEmailVerified`\n\t\t\t\t// lets a trusted IdP that never emits the claim still satisfy the gate.\n\t\t\t\tconst emailVerified = provider.assumeEmailVerified || claim.emailVerified === true\n\t\t\t\tif (provider.requireVerifiedEmail && !emailVerified) {\n\t\t\t\t\treturn { person: null, blockedReason: 'idp_email_unverified', blockedPersonId: personByEmail.id }\n\t\t\t\t}\n\t\t\t\tawait this.saveIdpIdentifier(db, provider, claim, personByEmail)\n\t\t\t\treturn { person: personByEmail }\n\t\t\t}\n\t\t}\n\n\t\tif (provider.autoSignUp) {\n\t\t\tconst signedUpPerson = await this.signUp(db, claim, provider)\n\t\t\tawait this.saveIdpIdentifier(db, provider, claim, signedUpPerson)\n\t\t\treturn { person: signedUpPerson, isNewPerson: true }\n\t\t}\n\n\t\treturn { person: null }\n\t}\n\n\tprivate async signUp(db: DatabaseContext, { email, name, externalIdentifier }: IDPResponse, provider: IdentityProviderRow): Promise<PersonRow> {\n\t\tconst roles = [TenantRole.PERSON]\n\t\tconst identityId = await db.commandBus.execute(new CreateIdentityCommand(roles))\n\t\tconst newPerson = await db.commandBus.execute(\n\t\t\tnew CreatePersonCommand({\n\t\t\t\tidentityId,\n\t\t\t\temail: provider.exclusive ? undefined : email,\n\t\t\t\tpassword: NoPassword,\n\t\t\t\tname: name ?? email?.split('@')[0] ?? externalIdentifier,\n\t\t\t\tidpOnly: provider.exclusive,\n\t\t\t}),\n\t\t)\n\n\t\treturn {\n\t\t\t...newPerson,\n\t\t\troles,\n\t\t}\n\t}\n\n\tprivate async saveIdpIdentifier(db: DatabaseContext, provider: IdentityProviderRow, claim: IDPResponse, person: PersonRow) {\n\t\tawait db.commandBus.execute(new CreatePersonIdentityProviderIdentifierCommand(provider.id, person.id, claim.externalIdentifier))\n\t}\n}\n\nnamespace IDPSignInManager {\n\texport type ResolvePersonResult = {\n\t\treadonly person: PersonRow | null\n\t\treadonly blockedReason?: 'idp_email_unverified'\n\t\treadonly blockedPersonId?: string\n\t\t/** True when the person row was just created by auto-sign-up (drives the `sticky` claim-mapping policy). */\n\t\treadonly isNewPerson?: boolean\n\t}\n\n\texport type InitSignInIDPResponse = Response<InitSignInIdpResult, InitSignInIdpErrorCode>\n\n\tinterface SignInIDPResult {\n\t\treadonly person: PersonRow\n\t\treadonly token: string\n\t\treadonly idpResponse?: Record<string, unknown>\n\t\t/** Identity provider the sign-in went through (for the resolver's audit). */\n\t\treadonly identityProviderId?: string\n\t\t/** Claim-mapping (A09) before/after delta — present only when a mapping changed grants. */\n\t\treadonly claimMappingAudit?: ClaimMappingAudit | null\n\t\t/** True when claim mapping failed and was skipped (fail-open) — drives the `idp_role_mapping_failed` audit. */\n\t\treadonly claimMappingFailed?: boolean\n\t\t[AuthLogService.Key]: AuthLogService.Bag\n\t}\n\n\texport type SignInIDPResponse = Response<SignInIDPResult, SignInIdpErrorCode, {\n\t\t[AuthLogService.Key]: AuthLogService.Bag\n\t}>\n}\n\nexport { IDPSignInManager }\n"],"names":["IdentityProviderBySlugQuery","IDPResponseError","ResponseError","AuthLogService","IDPValidationError","parseClaimMapping","CreateIdpSessionCommand","CreateAuthLogEntryCommand","ResponseOk","PersonByIdPQuery","PersonQuery","TenantRole","CreateIdentityCommand","CreatePersonCommand","NoPassword","CreatePersonIdentityProviderIdentifierCommand"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,MAAM,iBAAiB;AAAA,EACtB,YACkB,eACA,aACA,kBAChB;AAHgB,SAAA,gBAAA;AACA,SAAA,cAAA;AACA,SAAA,mBAAA;AAAA,EACf;AAAA,EAEH,MAAM,UACL,WACA,SACA,cACA,YACA,aACA,oBAC8C;AAC9C,WAAO,UAAU,YAAY,OAAO,OAAoD;AACvF,YAAM,WAAW,MAAM,GAAG,aAA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O,SAAS,YAAY,SAAY;AAAA,QACxC,UAAUC,SAAAA;AAAAA,QACV,MAAM,QAAQ,OAAO,MAAM,GAAG,EAAE,CAAC,KAAK;AAAA,QACtC,SAAS,SAAS;AAAA,MAAA,CAClB;AAAA,IAAA;AAGF,WAAO;AAAA,MACN,GAAG;AAAA,MACH;AAAA,IAAA;AAAA,EAEF;AAAA,EAEA,MAAc,kBAAkB,IAAqB,UAA+B,OAAoB,QAAmB;AAC1H,UAAM,GAAG,WAAW,QAAQ,IAAIC,8CAAAA,8CAA8C,SAAS,IAAI,OAAO,IAAI,MAAM,kBAAkB,CAAC;AAAA,EAChI;AACD;;"}
|
|
1
|
+
{"version":3,"file":"IDPSignInManager.cjs","sources":["../../../../../../packages/engine-tenant-api/src/model/service/IDPSignInManager.ts"],"sourcesContent":["import { ApiKeyManager } from './apiKey/index.js'\nimport { IdentityProviderBySlugQuery, PersonByIdPQuery, PersonQuery, PersonRow } from '../queries/index.js'\nimport { IDPHandlerRegistry, IDPResponse, IDPResponseError, IDPValidationError } from './idp/index.js'\nimport { Response, ResponseError, ResponseOk } from '../utils/Response.js'\nimport { InitSignInIdpErrorCode, InitSignInIdpResult, SignInIdpErrorCode } from '../../schema/index.js'\nimport { DatabaseContext } from '../utils/index.js'\nimport { ApiKeyRequestInfo, CreateIdentityCommand, CreatePersonCommand, CreatePersonIdentityProviderIdentifierCommand } from '../commands/index.js'\nimport { CreateIdpSessionCommand } from '../commands/idp/CreateIdpSessionCommand.js'\nimport { CreateAuthLogEntryCommand } from '../commands/authLog/CreateAuthLogEntryCommand.js'\nimport { TenantRole } from '../authorization/index.js'\nimport { NoPassword } from '../dtos/index.js'\nimport { IdentityProviderRow } from '../queries/idp/types.js'\nimport { AuthLogService } from './AuthLogService.js'\nimport { ClaimMappingAudit, IDPClaimSyncService } from './idp/IDPClaimSyncService.js'\nimport { ClaimMapping, parseClaimMapping } from './idp/ClaimMapping.js'\nimport { Logger } from '@contember/logger'\n\nclass IDPSignInManager {\n\tconstructor(\n\t\tprivate readonly apiKeyManager: ApiKeyManager,\n\t\tprivate readonly idpRegistry: IDPHandlerRegistry,\n\t\tprivate readonly claimSyncService: IDPClaimSyncService,\n\t\tprivate readonly logger: Logger,\n\t) {}\n\n\tasync signInIDP(\n\t\tdbContext: DatabaseContext,\n\t\tidpSlug: string,\n\t\tresponseData: unknown,\n\t\texpiration?: number,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<IDPSignInManager.SignInIDPResponse> {\n\t\treturn dbContext.transaction(async (db): Promise<IDPSignInManager.SignInIDPResponse> => {\n\t\t\tconst provider = await db.queryHandler.fetch(new IdentityProviderBySlugQuery(idpSlug))\n\t\t\tif (!provider || provider.disabledAt) {\n\t\t\t\tthrow new Error('provider not found')\n\t\t\t}\n\t\t\tconst providerService = this.idpRegistry.getHandler(provider.type)\n\t\t\tconst validatedConfig = providerService.validateConfiguration(provider.configuration)\n\t\t\tlet claim: IDPResponse\n\t\t\ttry {\n\t\t\t\tclaim = await providerService.processResponse(\n\t\t\t\t\tvalidatedConfig,\n\t\t\t\t\tresponseData,\n\t\t\t\t)\n\t\t\t} catch (e) {\n\t\t\t\tif (e instanceof IDPResponseError) {\n\t\t\t\t\treturn new ResponseError('INVALID_IDP_RESPONSE', e.message, {\n\t\t\t\t\t\t[AuthLogService.Key]: new AuthLogService.Bag({\n\t\t\t\t\t\t\tpersonId: undefined,\n\t\t\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\t\t}),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tif (e instanceof IDPValidationError) {\n\t\t\t\t\treturn new ResponseError('IDP_VALIDATION_FAILED', e.message, {\n\t\t\t\t\t\t[AuthLogService.Key]: new AuthLogService.Bag({\n\t\t\t\t\t\t\tpersonId: undefined,\n\t\t\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\t\t}),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tthrow e\n\t\t\t}\n\t\t\tconst resolved = await this.resolvePerson(db, claim, provider)\n\t\t\tconst personRow = resolved.person\n\n\t\t\tif (!personRow) {\n\t\t\t\t// Keep the external error generic (no account-existence leak), but\n\t\t\t\t// record the email-verification gate block distinctly in the audit\n\t\t\t\t// log — it is a takeover-grade event, not an ordinary \"not found\".\n\t\t\t\treturn new ResponseError('PERSON_NOT_FOUND', `Person ${claim.email} not found`, {\n\t\t\t\t\t[AuthLogService.Key]: new AuthLogService.Bag({\n\t\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\t\tpersonInput: claim.email,\n\t\t\t\t\t\tpersonId: resolved.blockedPersonId,\n\t\t\t\t\t\teventData: resolved.blockedReason ? { reason: resolved.blockedReason } : undefined,\n\t\t\t\t\t}),\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (personRow.disabled_at !== null) {\n\t\t\t\treturn new ResponseError('PERSON_DISABLED', `Person with e-mail ${claim.email} is disabled`, {\n\t\t\t\t\t[AuthLogService.Key]: new AuthLogService.Bag({\n\t\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\t\tpersonInput: claim.email,\n\t\t\t\t\t\tpersonId: personRow.id,\n\t\t\t\t\t}),\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// A09 — map IdP claims to project memberships. Returns a `{ before, after }` delta only\n\t\t\t// when something actually changed; the resolver emits the `idp_role_mapped` audit from it\n\t\t\t// (audit stays at the resolver layer).\n\t\t\t//\n\t\t\t// Fail-open on a MALFORMED/out-of-band `claimMapping`: parsing is caught so a bad config can\n\t\t\t// never lock the user out — sign-in proceeds without claim mapping and the resolver emits an\n\t\t\t// `idp_role_mapping_failed` marker. A DB error during the apply itself is NOT caught: it\n\t\t\t// propagates and rolls back the whole sign-in transaction, so a half-applied set of grants is\n\t\t\t// never committed (failing sign-in on an infra error is the safe outcome).\n\t\t\tlet mapping: ClaimMapping | null = null\n\t\t\tlet claimMappingFailed = false\n\t\t\ttry {\n\t\t\t\tmapping = parseClaimMapping(provider.configuration)\n\t\t\t} catch (e) {\n\t\t\t\tthis.logger.warn(e, { message: 'IdP sign-in: claim mapping configuration is invalid', identityProviderId: provider.id })\n\t\t\t\tclaimMappingFailed = true\n\t\t\t}\n\t\t\tlet claimMappingAudit: ClaimMappingAudit | null = null\n\t\t\tif (mapping) {\n\t\t\t\tconst syncResult = await this.claimSyncService.sync(\n\t\t\t\t\tdb,\n\t\t\t\t\tmapping,\n\t\t\t\t\tclaim,\n\t\t\t\t\t{ id: personRow.identity_id },\n\t\t\t\t\tresolved.isNewPerson === true,\n\t\t\t\t)\n\t\t\t\tclaimMappingAudit = syncResult.audit\n\t\t\t\t// The apply-time safety backstop dropped a configured rule (config-time validation was skipped, or\n\t\t\t\t// the project's ACL drifted since): surface the same fail-open marker as a malformed config, so a\n\t\t\t\t// silently-unapplied grant is visible to the operator. The resolver emits `idp_role_mapping_failed`.\n\t\t\t\tif (syncResult.droppedUnsafeRules) {\n\t\t\t\t\tclaimMappingFailed = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst { id: apiKeyId, token: sessionToken } = await this.apiKeyManager.createSessionApiKeyWithId(\n\t\t\t\tdb,\n\t\t\t\tpersonRow.identity_id,\n\t\t\t\texpiration,\n\t\t\t\trequestInfo,\n\t\t\t\ttrustForwardedInfo,\n\t\t\t)\n\n\t\t\t// Bind the federated-session state to this session so it can be re-validated\n\t\t\t// against the IdP later. Present only when the provider supports it and\n\t\t\t// revalidation is enabled on the IdP configuration (A24). Refresh tokens must be\n\t\t\t// encrypted at rest, so when no encryption key is configured we skip persisting a\n\t\t\t// token-bearing session (it would otherwise crash or store secrets in plaintext) —\n\t\t\t// the session then behaves like a plain session with no re-validation.\n\t\t\tif (claim.idpSession) {\n\t\t\t\tconst hasTokens = !!claim.idpSession.tokens && Object.keys(claim.idpSession.tokens).length > 0\n\t\t\t\tif (!hasTokens || db.providers.encryptionEnabled) {\n\t\t\t\t\tawait db.commandBus.execute(new CreateIdpSessionCommand(apiKeyId, provider.id, claim.idpSession))\n\t\t\t\t} else {\n\t\t\t\t\t// Re-validation is enabled on this IdP but no encryption key is configured, so we\n\t\t\t\t\t// won't store the token-bearing session — it silently degrades to a plain,\n\t\t\t\t\t// non-revalidated session. Audit the downgrade (errorCode `encryption_disabled`)\n\t\t\t\t\t// so the operator can see that a session they expected to be continuously\n\t\t\t\t\t// re-validated is in fact not protected, instead of failing closed at sign-in.\n\t\t\t\t\t// Best-effort, in a savepoint: a failed insert would otherwise abort the whole\n\t\t\t\t\t// sign-in transaction, and a lost audit row must not block the sign-in.\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait db.commandBus.transaction(bus =>\n\t\t\t\t\t\t\tbus.execute(\n\t\t\t\t\t\t\t\tnew CreateAuthLogEntryCommand({\n\t\t\t\t\t\t\t\t\ttype: 'idp_session_revalidation_failed',\n\t\t\t\t\t\t\t\t\tinvokedById: personRow.identity_id,\n\t\t\t\t\t\t\t\t\tpersonId: personRow.id,\n\t\t\t\t\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\t\terrorCode: 'encryption_disabled',\n\t\t\t\t\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\t\t\t\t\teventData: { apiKeyId },\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tthis.logger.error(e, { message: 'IdP sign-in: writing the encryption_disabled audit entry failed', identityProviderId: provider.id })\n\t\t\t\t\t\t// the savepoint is rolled back, the sign-in transaction stays usable\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn new ResponseOk({\n\t\t\t\tperson: personRow,\n\t\t\t\ttoken: sessionToken,\n\t\t\t\tidpResponse: claim,\n\t\t\t\tclaimMappingAudit,\n\t\t\t\tclaimMappingFailed,\n\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t[AuthLogService.Key]: new AuthLogService.Bag({\n\t\t\t\t\tpersonId: personRow.id,\n\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\tpersonInput: claim.email,\n\t\t\t\t}),\n\t\t\t})\n\t\t})\n\t}\n\n\tasync initSignInIDP(dbContext: DatabaseContext, idpSlug: string, data: unknown): Promise<IDPSignInManager.InitSignInIDPResponse> {\n\t\tconst provider = await dbContext.queryHandler.fetch(new IdentityProviderBySlugQuery(idpSlug))\n\t\tif (!provider || provider.disabledAt) {\n\t\t\treturn new ResponseError('PROVIDER_NOT_FOUND', `Identity provider ${idpSlug} not found`)\n\t\t}\n\t\tconst providerService = this.idpRegistry.getHandler(provider.type)\n\t\tconst validatedConfig = providerService.validateConfiguration(provider.configuration)\n\t\ttry {\n\t\t\tconst initResponse = await providerService.initAuth(validatedConfig, data)\n\n\t\t\tconst publicConfig = providerService.getPublicConfiguration\n\t\t\t\t? providerService.getPublicConfiguration(validatedConfig)\n\t\t\t\t: validatedConfig\n\n\t\t\treturn new ResponseOk({\n\t\t\t\t...initResponse,\n\t\t\t\tidpConfiguration: provider.initReturnsConfig ? publicConfig : null,\n\t\t\t})\n\t\t} catch (e) {\n\t\t\tif (e instanceof IDPValidationError) {\n\t\t\t\treturn new ResponseError('IDP_VALIDATION_FAILED', e.message)\n\t\t\t}\n\t\t\tthrow e\n\t\t}\n\t}\n\n\tprivate async resolvePerson(db: DatabaseContext, claim: IDPResponse, provider: IdentityProviderRow): Promise<IDPSignInManager.ResolvePersonResult> {\n\t\tconst personByIdPQuery = new PersonByIdPQuery(provider.id, claim.externalIdentifier)\n\t\tconst personByIdp = await db.queryHandler.fetch(personByIdPQuery)\n\t\tif (personByIdp) {\n\t\t\treturn { person: personByIdp }\n\t\t}\n\n\t\tif (!provider.exclusive) {\n\t\t\tconst personByEmail = typeof claim.email === 'string' && claim.email\n\t\t\t\t? await db.queryHandler.fetch(PersonQuery.byEmail(claim.email))\n\t\t\t\t: null\n\t\t\tif (personByEmail) {\n\t\t\t\t// Auto-linking an IdP identity to a pre-existing local account by\n\t\t\t\t// e-mail is takeover-grade: if the provider returns an unverified\n\t\t\t\t// (or attacker-controlled) e-mail, it could hijack the account. When\n\t\t\t\t// the provider requires a verified e-mail, refuse to link — and to\n\t\t\t\t// sign in — unless the address is asserted verified. `assumeEmailVerified`\n\t\t\t\t// lets a trusted IdP that never emits the claim still satisfy the gate.\n\t\t\t\tconst emailVerified = provider.assumeEmailVerified || claim.emailVerified === true\n\t\t\t\tif (provider.requireVerifiedEmail && !emailVerified) {\n\t\t\t\t\treturn { person: null, blockedReason: 'idp_email_unverified', blockedPersonId: personByEmail.id }\n\t\t\t\t}\n\t\t\t\tawait this.saveIdpIdentifier(db, provider, claim, personByEmail)\n\t\t\t\treturn { person: personByEmail }\n\t\t\t}\n\t\t}\n\n\t\tif (provider.autoSignUp) {\n\t\t\tconst signedUpPerson = await this.signUp(db, claim, provider)\n\t\t\tawait this.saveIdpIdentifier(db, provider, claim, signedUpPerson)\n\t\t\treturn { person: signedUpPerson, isNewPerson: true }\n\t\t}\n\n\t\treturn { person: null }\n\t}\n\n\tprivate async signUp(db: DatabaseContext, { email, name, externalIdentifier }: IDPResponse, provider: IdentityProviderRow): Promise<PersonRow> {\n\t\tconst roles = [TenantRole.PERSON]\n\t\tconst identityId = await db.commandBus.execute(new CreateIdentityCommand(roles))\n\t\tconst newPerson = await db.commandBus.execute(\n\t\t\tnew CreatePersonCommand({\n\t\t\t\tidentityId,\n\t\t\t\temail: provider.exclusive ? undefined : email,\n\t\t\t\tpassword: NoPassword,\n\t\t\t\tname: name ?? email?.split('@')[0] ?? externalIdentifier,\n\t\t\t\tidpOnly: provider.exclusive,\n\t\t\t}),\n\t\t)\n\n\t\treturn {\n\t\t\t...newPerson,\n\t\t\troles,\n\t\t}\n\t}\n\n\tprivate async saveIdpIdentifier(db: DatabaseContext, provider: IdentityProviderRow, claim: IDPResponse, person: PersonRow) {\n\t\tawait db.commandBus.execute(new CreatePersonIdentityProviderIdentifierCommand(provider.id, person.id, claim.externalIdentifier))\n\t}\n}\n\nnamespace IDPSignInManager {\n\texport type ResolvePersonResult = {\n\t\treadonly person: PersonRow | null\n\t\treadonly blockedReason?: 'idp_email_unverified'\n\t\treadonly blockedPersonId?: string\n\t\t/** True when the person row was just created by auto-sign-up (drives the `sticky` claim-mapping policy). */\n\t\treadonly isNewPerson?: boolean\n\t}\n\n\texport type InitSignInIDPResponse = Response<InitSignInIdpResult, InitSignInIdpErrorCode>\n\n\tinterface SignInIDPResult {\n\t\treadonly person: PersonRow\n\t\treadonly token: string\n\t\treadonly idpResponse?: Record<string, unknown>\n\t\t/** Identity provider the sign-in went through (for the resolver's audit). */\n\t\treadonly identityProviderId?: string\n\t\t/** Claim-mapping (A09) before/after delta — present only when a mapping changed grants. */\n\t\treadonly claimMappingAudit?: ClaimMappingAudit | null\n\t\t/** True when claim mapping failed and was skipped (fail-open) — drives the `idp_role_mapping_failed` audit. */\n\t\treadonly claimMappingFailed?: boolean\n\t\t[AuthLogService.Key]: AuthLogService.Bag\n\t}\n\n\texport type SignInIDPResponse = Response<SignInIDPResult, SignInIdpErrorCode, {\n\t\t[AuthLogService.Key]: AuthLogService.Bag\n\t}>\n}\n\nexport { IDPSignInManager }\n"],"names":["IdentityProviderBySlugQuery","IDPResponseError","ResponseError","AuthLogService","IDPValidationError","parseClaimMapping","CreateIdpSessionCommand","CreateAuthLogEntryCommand","ResponseOk","PersonByIdPQuery","PersonQuery","TenantRole","CreateIdentityCommand","CreatePersonCommand","NoPassword","CreatePersonIdentityProviderIdentifierCommand"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,MAAM,iBAAiB;AAAA,EACtB,YACkB,eACA,aACA,kBACA,QAChB;AAJgB,SAAA,gBAAA;AACA,SAAA,cAAA;AACA,SAAA,mBAAA;AACA,SAAA,SAAA;AAAA,EACf;AAAA,EAEH,MAAM,U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AAgB,aAAa,KAAA;AAAA,IAC/C;AAEA,WAAO,EAAE,QAAQ,KAAA;AAAA,EAClB;AAAA,EAEA,MAAc,OAAO,IAAqB,EAAE,OAAO,MAAM,mBAAA,GAAmC,UAAmD;AAC9I,UAAM,QAAQ,CAACC,MAAAA,WAAW,MAAM;AAChC,UAAM,aAAa,MAAM,GAAG,WAAW,QAAQ,IAAIC,sBAAAA,sBAAsB,KAAK,CAAC;AAC/E,UAAM,YAAY,MAAM,GAAG,WAAW;AAAA,MACrC,IAAIC,wCAAoB;AAAA,QACvB;AAAA,QACA,OAAO,SAAS,YAAY,SAAY;AAAA,QACxC,UAAUC,SAAAA;AAAAA,QACV,MAAM,QAAQ,OAAO,MAAM,GAAG,EAAE,CAAC,KAAK;AAAA,QACtC,SAAS,SAAS;AAAA,MAAA,CAClB;AAAA,IAAA;AAGF,WAAO;AAAA,MACN,GAAG;AAAA,MACH;AAAA,IAAA;AAAA,EAEF;AAAA,EAEA,MAAc,kBAAkB,IAAqB,UAA+B,OAAoB,QAAmB;AAC1H,UAAM,GAAG,WAAW,QAAQ,IAAIC,8CAAAA,8CAA8C,SAAS,IAAI,OAAO,IAAI,MAAM,kBAAkB,CAAC;AAAA,EAChI;AACD;;"}
|
|
@@ -31,10 +31,11 @@ import { CreateIdpSessionCommand } from "../commands/idp/CreateIdpSessionCommand
|
|
|
31
31
|
import { NoPassword } from "../dtos/Password.js";
|
|
32
32
|
import { AuthLogService } from "./AuthLogService.js";
|
|
33
33
|
class IDPSignInManager {
|
|
34
|
-
constructor(apiKeyManager, idpRegistry, claimSyncService) {
|
|
34
|
+
constructor(apiKeyManager, idpRegistry, claimSyncService, logger) {
|
|
35
35
|
this.apiKeyManager = apiKeyManager;
|
|
36
36
|
this.idpRegistry = idpRegistry;
|
|
37
37
|
this.claimSyncService = claimSyncService;
|
|
38
|
+
this.logger = logger;
|
|
38
39
|
}
|
|
39
40
|
async signInIDP(dbContext, idpSlug, responseData, expiration, requestInfo, trustForwardedInfo) {
|
|
40
41
|
return dbContext.transaction(async (db) => {
|
|
@@ -94,7 +95,8 @@ class IDPSignInManager {
|
|
|
94
95
|
let claimMappingFailed = false;
|
|
95
96
|
try {
|
|
96
97
|
mapping = parseClaimMapping(provider.configuration);
|
|
97
|
-
} catch {
|
|
98
|
+
} catch (e) {
|
|
99
|
+
this.logger.warn(e, { message: "IdP sign-in: claim mapping configuration is invalid", identityProviderId: provider.id });
|
|
98
100
|
claimMappingFailed = true;
|
|
99
101
|
}
|
|
100
102
|
let claimMappingAudit = null;
|
|
@@ -123,19 +125,25 @@ class IDPSignInManager {
|
|
|
123
125
|
if (!hasTokens || db.providers.encryptionEnabled) {
|
|
124
126
|
await db.commandBus.execute(new CreateIdpSessionCommand(apiKeyId, provider.id, claim.idpSession));
|
|
125
127
|
} else {
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
128
|
+
try {
|
|
129
|
+
await db.commandBus.transaction(
|
|
130
|
+
(bus) => bus.execute(
|
|
131
|
+
new CreateAuthLogEntryCommand({
|
|
132
|
+
type: "idp_session_revalidation_failed",
|
|
133
|
+
invokedById: personRow.identity_id,
|
|
134
|
+
personId: personRow.id,
|
|
135
|
+
identityProviderId: provider.id,
|
|
136
|
+
success: true,
|
|
137
|
+
errorCode: "encryption_disabled",
|
|
138
|
+
ipAddress: requestInfo?.ip,
|
|
139
|
+
userAgent: requestInfo?.userAgent,
|
|
140
|
+
eventData: { apiKeyId }
|
|
141
|
+
})
|
|
142
|
+
)
|
|
143
|
+
);
|
|
144
|
+
} catch (e) {
|
|
145
|
+
this.logger.error(e, { message: "IdP sign-in: writing the encryption_disabled audit entry failed", identityProviderId: provider.id });
|
|
146
|
+
}
|
|
139
147
|
}
|
|
140
148
|
}
|
|
141
149
|
return new ResponseOk({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IDPSignInManager.js","sources":["../../../../../../packages/engine-tenant-api/src/model/service/IDPSignInManager.ts"],"sourcesContent":["import { ApiKeyManager } from './apiKey/index.js'\nimport { IdentityProviderBySlugQuery, PersonByIdPQuery, PersonQuery, PersonRow } from '../queries/index.js'\nimport { IDPHandlerRegistry, IDPResponse, IDPResponseError, IDPValidationError } from './idp/index.js'\nimport { Response, ResponseError, ResponseOk } from '../utils/Response.js'\nimport { InitSignInIdpErrorCode, InitSignInIdpResult, SignInIdpErrorCode } from '../../schema/index.js'\nimport { DatabaseContext } from '../utils/index.js'\nimport { ApiKeyRequestInfo, CreateIdentityCommand, CreatePersonCommand, CreatePersonIdentityProviderIdentifierCommand } from '../commands/index.js'\nimport { CreateIdpSessionCommand } from '../commands/idp/CreateIdpSessionCommand.js'\nimport { CreateAuthLogEntryCommand } from '../commands/authLog/CreateAuthLogEntryCommand.js'\nimport { TenantRole } from '../authorization/index.js'\nimport { NoPassword } from '../dtos/index.js'\nimport { IdentityProviderRow } from '../queries/idp/types.js'\nimport { AuthLogService } from './AuthLogService.js'\nimport { ClaimMappingAudit, IDPClaimSyncService } from './idp/IDPClaimSyncService.js'\nimport { ClaimMapping, parseClaimMapping } from './idp/ClaimMapping.js'\n\nclass IDPSignInManager {\n\tconstructor(\n\t\tprivate readonly apiKeyManager: ApiKeyManager,\n\t\tprivate readonly idpRegistry: IDPHandlerRegistry,\n\t\tprivate readonly claimSyncService: IDPClaimSyncService,\n\t) {}\n\n\tasync signInIDP(\n\t\tdbContext: DatabaseContext,\n\t\tidpSlug: string,\n\t\tresponseData: unknown,\n\t\texpiration?: number,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<IDPSignInManager.SignInIDPResponse> {\n\t\treturn dbContext.transaction(async (db): Promise<IDPSignInManager.SignInIDPResponse> => {\n\t\t\tconst provider = await db.queryHandler.fetch(new IdentityProviderBySlugQuery(idpSlug))\n\t\t\tif (!provider || provider.disabledAt) {\n\t\t\t\tthrow new Error('provider not found')\n\t\t\t}\n\t\t\tconst providerService = this.idpRegistry.getHandler(provider.type)\n\t\t\tconst validatedConfig = providerService.validateConfiguration(provider.configuration)\n\t\t\tlet claim: IDPResponse\n\t\t\ttry {\n\t\t\t\tclaim = await providerService.processResponse(\n\t\t\t\t\tvalidatedConfig,\n\t\t\t\t\tresponseData,\n\t\t\t\t)\n\t\t\t} catch (e) {\n\t\t\t\tif (e instanceof IDPResponseError) {\n\t\t\t\t\treturn new ResponseError('INVALID_IDP_RESPONSE', e.message, {\n\t\t\t\t\t\t[AuthLogService.Key]: new AuthLogService.Bag({\n\t\t\t\t\t\t\tpersonId: undefined,\n\t\t\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\t\t}),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tif (e instanceof IDPValidationError) {\n\t\t\t\t\treturn new ResponseError('IDP_VALIDATION_FAILED', e.message, {\n\t\t\t\t\t\t[AuthLogService.Key]: new AuthLogService.Bag({\n\t\t\t\t\t\t\tpersonId: undefined,\n\t\t\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\t\t}),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tthrow e\n\t\t\t}\n\t\t\tconst resolved = await this.resolvePerson(db, claim, provider)\n\t\t\tconst personRow = resolved.person\n\n\t\t\tif (!personRow) {\n\t\t\t\t// Keep the external error generic (no account-existence leak), but\n\t\t\t\t// record the email-verification gate block distinctly in the audit\n\t\t\t\t// log — it is a takeover-grade event, not an ordinary \"not found\".\n\t\t\t\treturn new ResponseError('PERSON_NOT_FOUND', `Person ${claim.email} not found`, {\n\t\t\t\t\t[AuthLogService.Key]: new AuthLogService.Bag({\n\t\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\t\tpersonInput: claim.email,\n\t\t\t\t\t\tpersonId: resolved.blockedPersonId,\n\t\t\t\t\t\teventData: resolved.blockedReason ? { reason: resolved.blockedReason } : undefined,\n\t\t\t\t\t}),\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (personRow.disabled_at !== null) {\n\t\t\t\treturn new ResponseError('PERSON_DISABLED', `Person with e-mail ${claim.email} is disabled`, {\n\t\t\t\t\t[AuthLogService.Key]: new AuthLogService.Bag({\n\t\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\t\tpersonInput: claim.email,\n\t\t\t\t\t\tpersonId: personRow.id,\n\t\t\t\t\t}),\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// A09 — map IdP claims to project memberships. Returns a `{ before, after }` delta only\n\t\t\t// when something actually changed; the resolver emits the `idp_role_mapped` audit from it\n\t\t\t// (audit stays at the resolver layer).\n\t\t\t//\n\t\t\t// Fail-open on a MALFORMED/out-of-band `claimMapping`: parsing is caught so a bad config can\n\t\t\t// never lock the user out — sign-in proceeds without claim mapping and the resolver emits an\n\t\t\t// `idp_role_mapping_failed` marker. A DB error during the apply itself is NOT caught: it\n\t\t\t// propagates and rolls back the whole sign-in transaction, so a half-applied set of grants is\n\t\t\t// never committed (failing sign-in on an infra error is the safe outcome).\n\t\t\tlet mapping: ClaimMapping | null = null\n\t\t\tlet claimMappingFailed = false\n\t\t\ttry {\n\t\t\t\tmapping = parseClaimMapping(provider.configuration)\n\t\t\t} catch {\n\t\t\t\tclaimMappingFailed = true\n\t\t\t}\n\t\t\tlet claimMappingAudit: ClaimMappingAudit | null = null\n\t\t\tif (mapping) {\n\t\t\t\tconst syncResult = await this.claimSyncService.sync(\n\t\t\t\t\tdb,\n\t\t\t\t\tmapping,\n\t\t\t\t\tclaim,\n\t\t\t\t\t{ id: personRow.identity_id },\n\t\t\t\t\tresolved.isNewPerson === true,\n\t\t\t\t)\n\t\t\t\tclaimMappingAudit = syncResult.audit\n\t\t\t\t// The apply-time safety backstop dropped a configured rule (config-time validation was skipped, or\n\t\t\t\t// the project's ACL drifted since): surface the same fail-open marker as a malformed config, so a\n\t\t\t\t// silently-unapplied grant is visible to the operator. The resolver emits `idp_role_mapping_failed`.\n\t\t\t\tif (syncResult.droppedUnsafeRules) {\n\t\t\t\t\tclaimMappingFailed = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst { id: apiKeyId, token: sessionToken } = await this.apiKeyManager.createSessionApiKeyWithId(\n\t\t\t\tdb,\n\t\t\t\tpersonRow.identity_id,\n\t\t\t\texpiration,\n\t\t\t\trequestInfo,\n\t\t\t\ttrustForwardedInfo,\n\t\t\t)\n\n\t\t\t// Bind the federated-session state to this session so it can be re-validated\n\t\t\t// against the IdP later. Present only when the provider supports it and\n\t\t\t// revalidation is enabled on the IdP configuration (A24). Refresh tokens must be\n\t\t\t// encrypted at rest, so when no encryption key is configured we skip persisting a\n\t\t\t// token-bearing session (it would otherwise crash or store secrets in plaintext) —\n\t\t\t// the session then behaves like a plain session with no re-validation.\n\t\t\tif (claim.idpSession) {\n\t\t\t\tconst hasTokens = !!claim.idpSession.tokens && Object.keys(claim.idpSession.tokens).length > 0\n\t\t\t\tif (!hasTokens || db.providers.encryptionEnabled) {\n\t\t\t\t\tawait db.commandBus.execute(new CreateIdpSessionCommand(apiKeyId, provider.id, claim.idpSession))\n\t\t\t\t} else {\n\t\t\t\t\t// Re-validation is enabled on this IdP but no encryption key is configured, so we\n\t\t\t\t\t// won't store the token-bearing session — it silently degrades to a plain,\n\t\t\t\t\t// non-revalidated session. Audit the downgrade (errorCode `encryption_disabled`)\n\t\t\t\t\t// so the operator can see that a session they expected to be continuously\n\t\t\t\t\t// re-validated is in fact not protected, instead of failing closed at sign-in.\n\t\t\t\t\tawait db.commandBus.execute(\n\t\t\t\t\t\tnew CreateAuthLogEntryCommand({\n\t\t\t\t\t\t\ttype: 'idp_session_revalidation_failed',\n\t\t\t\t\t\t\tinvokedById: personRow.identity_id,\n\t\t\t\t\t\t\tpersonId: personRow.id,\n\t\t\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\t\t\tpersonTokenId: apiKeyId,\n\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\terrorCode: 'encryption_disabled',\n\t\t\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\t\t}),\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn new ResponseOk({\n\t\t\t\tperson: personRow,\n\t\t\t\ttoken: sessionToken,\n\t\t\t\tidpResponse: claim,\n\t\t\t\tclaimMappingAudit,\n\t\t\t\tclaimMappingFailed,\n\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t[AuthLogService.Key]: new AuthLogService.Bag({\n\t\t\t\t\tpersonId: personRow.id,\n\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\tpersonInput: claim.email,\n\t\t\t\t}),\n\t\t\t})\n\t\t})\n\t}\n\n\tasync initSignInIDP(dbContext: DatabaseContext, idpSlug: string, data: unknown): Promise<IDPSignInManager.InitSignInIDPResponse> {\n\t\tconst provider = await dbContext.queryHandler.fetch(new IdentityProviderBySlugQuery(idpSlug))\n\t\tif (!provider || provider.disabledAt) {\n\t\t\treturn new ResponseError('PROVIDER_NOT_FOUND', `Identity provider ${idpSlug} not found`)\n\t\t}\n\t\tconst providerService = this.idpRegistry.getHandler(provider.type)\n\t\tconst validatedConfig = providerService.validateConfiguration(provider.configuration)\n\t\ttry {\n\t\t\tconst initResponse = await providerService.initAuth(validatedConfig, data)\n\n\t\t\tconst publicConfig = providerService.getPublicConfiguration\n\t\t\t\t? providerService.getPublicConfiguration(validatedConfig)\n\t\t\t\t: validatedConfig\n\n\t\t\treturn new ResponseOk({\n\t\t\t\t...initResponse,\n\t\t\t\tidpConfiguration: provider.initReturnsConfig ? publicConfig : null,\n\t\t\t})\n\t\t} catch (e) {\n\t\t\tif (e instanceof IDPValidationError) {\n\t\t\t\treturn new ResponseError('IDP_VALIDATION_FAILED', e.message)\n\t\t\t}\n\t\t\tthrow e\n\t\t}\n\t}\n\n\tprivate async resolvePerson(db: DatabaseContext, claim: IDPResponse, provider: IdentityProviderRow): Promise<IDPSignInManager.ResolvePersonResult> {\n\t\tconst personByIdPQuery = new PersonByIdPQuery(provider.id, claim.externalIdentifier)\n\t\tconst personByIdp = await db.queryHandler.fetch(personByIdPQuery)\n\t\tif (personByIdp) {\n\t\t\treturn { person: personByIdp }\n\t\t}\n\n\t\tif (!provider.exclusive) {\n\t\t\tconst personByEmail = typeof claim.email === 'string' && claim.email\n\t\t\t\t? await db.queryHandler.fetch(PersonQuery.byEmail(claim.email))\n\t\t\t\t: null\n\t\t\tif (personByEmail) {\n\t\t\t\t// Auto-linking an IdP identity to a pre-existing local account by\n\t\t\t\t// e-mail is takeover-grade: if the provider returns an unverified\n\t\t\t\t// (or attacker-controlled) e-mail, it could hijack the account. When\n\t\t\t\t// the provider requires a verified e-mail, refuse to link — and to\n\t\t\t\t// sign in — unless the address is asserted verified. `assumeEmailVerified`\n\t\t\t\t// lets a trusted IdP that never emits the claim still satisfy the gate.\n\t\t\t\tconst emailVerified = provider.assumeEmailVerified || claim.emailVerified === true\n\t\t\t\tif (provider.requireVerifiedEmail && !emailVerified) {\n\t\t\t\t\treturn { person: null, blockedReason: 'idp_email_unverified', blockedPersonId: personByEmail.id }\n\t\t\t\t}\n\t\t\t\tawait this.saveIdpIdentifier(db, provider, claim, personByEmail)\n\t\t\t\treturn { person: personByEmail }\n\t\t\t}\n\t\t}\n\n\t\tif (provider.autoSignUp) {\n\t\t\tconst signedUpPerson = await this.signUp(db, claim, provider)\n\t\t\tawait this.saveIdpIdentifier(db, provider, claim, signedUpPerson)\n\t\t\treturn { person: signedUpPerson, isNewPerson: true }\n\t\t}\n\n\t\treturn { person: null }\n\t}\n\n\tprivate async signUp(db: DatabaseContext, { email, name, externalIdentifier }: IDPResponse, provider: IdentityProviderRow): Promise<PersonRow> {\n\t\tconst roles = [TenantRole.PERSON]\n\t\tconst identityId = await db.commandBus.execute(new CreateIdentityCommand(roles))\n\t\tconst newPerson = await db.commandBus.execute(\n\t\t\tnew CreatePersonCommand({\n\t\t\t\tidentityId,\n\t\t\t\temail: provider.exclusive ? undefined : email,\n\t\t\t\tpassword: NoPassword,\n\t\t\t\tname: name ?? email?.split('@')[0] ?? externalIdentifier,\n\t\t\t\tidpOnly: provider.exclusive,\n\t\t\t}),\n\t\t)\n\n\t\treturn {\n\t\t\t...newPerson,\n\t\t\troles,\n\t\t}\n\t}\n\n\tprivate async saveIdpIdentifier(db: DatabaseContext, provider: IdentityProviderRow, claim: IDPResponse, person: PersonRow) {\n\t\tawait db.commandBus.execute(new CreatePersonIdentityProviderIdentifierCommand(provider.id, person.id, claim.externalIdentifier))\n\t}\n}\n\nnamespace IDPSignInManager {\n\texport type ResolvePersonResult = {\n\t\treadonly person: PersonRow | null\n\t\treadonly blockedReason?: 'idp_email_unverified'\n\t\treadonly blockedPersonId?: string\n\t\t/** True when the person row was just created by auto-sign-up (drives the `sticky` claim-mapping policy). */\n\t\treadonly isNewPerson?: boolean\n\t}\n\n\texport type InitSignInIDPResponse = Response<InitSignInIdpResult, InitSignInIdpErrorCode>\n\n\tinterface SignInIDPResult {\n\t\treadonly person: PersonRow\n\t\treadonly token: string\n\t\treadonly idpResponse?: Record<string, unknown>\n\t\t/** Identity provider the sign-in went through (for the resolver's audit). */\n\t\treadonly identityProviderId?: string\n\t\t/** Claim-mapping (A09) before/after delta — present only when a mapping changed grants. */\n\t\treadonly claimMappingAudit?: ClaimMappingAudit | null\n\t\t/** True when claim mapping failed and was skipped (fail-open) — drives the `idp_role_mapping_failed` audit. */\n\t\treadonly claimMappingFailed?: boolean\n\t\t[AuthLogService.Key]: AuthLogService.Bag\n\t}\n\n\texport type SignInIDPResponse = Response<SignInIDPResult, SignInIdpErrorCode, {\n\t\t[AuthLogService.Key]: AuthLogService.Bag\n\t}>\n}\n\nexport { IDPSignInManager }\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,MAAM,iBAAiB;AA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AAAA,QACA,OAAO,SAAS,YAAY,SAAY;AAAA,QACxC,UAAU;AAAA,QACV,MAAM,QAAQ,OAAO,MAAM,GAAG,EAAE,CAAC,KAAK;AAAA,QACtC,SAAS,SAAS;AAAA,MAAA,CAClB;AAAA,IAAA;AAGF,WAAO;AAAA,MACN,GAAG;AAAA,MACH;AAAA,IAAA;AAAA,EAEF;AAAA,EAEA,MAAc,kBAAkB,IAAqB,UAA+B,OAAoB,QAAmB;AAC1H,UAAM,GAAG,WAAW,QAAQ,IAAI,8CAA8C,SAAS,IAAI,OAAO,IAAI,MAAM,kBAAkB,CAAC;AAAA,EAChI;AACD;"}
|
|
1
|
+
{"version":3,"file":"IDPSignInManager.js","sources":["../../../../../../packages/engine-tenant-api/src/model/service/IDPSignInManager.ts"],"sourcesContent":["import { ApiKeyManager } from './apiKey/index.js'\nimport { IdentityProviderBySlugQuery, PersonByIdPQuery, PersonQuery, PersonRow } from '../queries/index.js'\nimport { IDPHandlerRegistry, IDPResponse, IDPResponseError, IDPValidationError } from './idp/index.js'\nimport { Response, ResponseError, ResponseOk } from '../utils/Response.js'\nimport { InitSignInIdpErrorCode, InitSignInIdpResult, SignInIdpErrorCode } from '../../schema/index.js'\nimport { DatabaseContext } from '../utils/index.js'\nimport { ApiKeyRequestInfo, CreateIdentityCommand, CreatePersonCommand, CreatePersonIdentityProviderIdentifierCommand } from '../commands/index.js'\nimport { CreateIdpSessionCommand } from '../commands/idp/CreateIdpSessionCommand.js'\nimport { CreateAuthLogEntryCommand } from '../commands/authLog/CreateAuthLogEntryCommand.js'\nimport { TenantRole } from '../authorization/index.js'\nimport { NoPassword } from '../dtos/index.js'\nimport { IdentityProviderRow } from '../queries/idp/types.js'\nimport { AuthLogService } from './AuthLogService.js'\nimport { ClaimMappingAudit, IDPClaimSyncService } from './idp/IDPClaimSyncService.js'\nimport { ClaimMapping, parseClaimMapping } from './idp/ClaimMapping.js'\nimport { Logger } from '@contember/logger'\n\nclass IDPSignInManager {\n\tconstructor(\n\t\tprivate readonly apiKeyManager: ApiKeyManager,\n\t\tprivate readonly idpRegistry: IDPHandlerRegistry,\n\t\tprivate readonly claimSyncService: IDPClaimSyncService,\n\t\tprivate readonly logger: Logger,\n\t) {}\n\n\tasync signInIDP(\n\t\tdbContext: DatabaseContext,\n\t\tidpSlug: string,\n\t\tresponseData: unknown,\n\t\texpiration?: number,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<IDPSignInManager.SignInIDPResponse> {\n\t\treturn dbContext.transaction(async (db): Promise<IDPSignInManager.SignInIDPResponse> => {\n\t\t\tconst provider = await db.queryHandler.fetch(new IdentityProviderBySlugQuery(idpSlug))\n\t\t\tif (!provider || provider.disabledAt) {\n\t\t\t\tthrow new Error('provider not found')\n\t\t\t}\n\t\t\tconst providerService = this.idpRegistry.getHandler(provider.type)\n\t\t\tconst validatedConfig = providerService.validateConfiguration(provider.configuration)\n\t\t\tlet claim: IDPResponse\n\t\t\ttry {\n\t\t\t\tclaim = await providerService.processResponse(\n\t\t\t\t\tvalidatedConfig,\n\t\t\t\t\tresponseData,\n\t\t\t\t)\n\t\t\t} catch (e) {\n\t\t\t\tif (e instanceof IDPResponseError) {\n\t\t\t\t\treturn new ResponseError('INVALID_IDP_RESPONSE', e.message, {\n\t\t\t\t\t\t[AuthLogService.Key]: new AuthLogService.Bag({\n\t\t\t\t\t\t\tpersonId: undefined,\n\t\t\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\t\t}),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tif (e instanceof IDPValidationError) {\n\t\t\t\t\treturn new ResponseError('IDP_VALIDATION_FAILED', e.message, {\n\t\t\t\t\t\t[AuthLogService.Key]: new AuthLogService.Bag({\n\t\t\t\t\t\t\tpersonId: undefined,\n\t\t\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\t\t}),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tthrow e\n\t\t\t}\n\t\t\tconst resolved = await this.resolvePerson(db, claim, provider)\n\t\t\tconst personRow = resolved.person\n\n\t\t\tif (!personRow) {\n\t\t\t\t// Keep the external error generic (no account-existence leak), but\n\t\t\t\t// record the email-verification gate block distinctly in the audit\n\t\t\t\t// log — it is a takeover-grade event, not an ordinary \"not found\".\n\t\t\t\treturn new ResponseError('PERSON_NOT_FOUND', `Person ${claim.email} not found`, {\n\t\t\t\t\t[AuthLogService.Key]: new AuthLogService.Bag({\n\t\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\t\tpersonInput: claim.email,\n\t\t\t\t\t\tpersonId: resolved.blockedPersonId,\n\t\t\t\t\t\teventData: resolved.blockedReason ? { reason: resolved.blockedReason } : undefined,\n\t\t\t\t\t}),\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (personRow.disabled_at !== null) {\n\t\t\t\treturn new ResponseError('PERSON_DISABLED', `Person with e-mail ${claim.email} is disabled`, {\n\t\t\t\t\t[AuthLogService.Key]: new AuthLogService.Bag({\n\t\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\t\tpersonInput: claim.email,\n\t\t\t\t\t\tpersonId: personRow.id,\n\t\t\t\t\t}),\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// A09 — map IdP claims to project memberships. Returns a `{ before, after }` delta only\n\t\t\t// when something actually changed; the resolver emits the `idp_role_mapped` audit from it\n\t\t\t// (audit stays at the resolver layer).\n\t\t\t//\n\t\t\t// Fail-open on a MALFORMED/out-of-band `claimMapping`: parsing is caught so a bad config can\n\t\t\t// never lock the user out — sign-in proceeds without claim mapping and the resolver emits an\n\t\t\t// `idp_role_mapping_failed` marker. A DB error during the apply itself is NOT caught: it\n\t\t\t// propagates and rolls back the whole sign-in transaction, so a half-applied set of grants is\n\t\t\t// never committed (failing sign-in on an infra error is the safe outcome).\n\t\t\tlet mapping: ClaimMapping | null = null\n\t\t\tlet claimMappingFailed = false\n\t\t\ttry {\n\t\t\t\tmapping = parseClaimMapping(provider.configuration)\n\t\t\t} catch (e) {\n\t\t\t\tthis.logger.warn(e, { message: 'IdP sign-in: claim mapping configuration is invalid', identityProviderId: provider.id })\n\t\t\t\tclaimMappingFailed = true\n\t\t\t}\n\t\t\tlet claimMappingAudit: ClaimMappingAudit | null = null\n\t\t\tif (mapping) {\n\t\t\t\tconst syncResult = await this.claimSyncService.sync(\n\t\t\t\t\tdb,\n\t\t\t\t\tmapping,\n\t\t\t\t\tclaim,\n\t\t\t\t\t{ id: personRow.identity_id },\n\t\t\t\t\tresolved.isNewPerson === true,\n\t\t\t\t)\n\t\t\t\tclaimMappingAudit = syncResult.audit\n\t\t\t\t// The apply-time safety backstop dropped a configured rule (config-time validation was skipped, or\n\t\t\t\t// the project's ACL drifted since): surface the same fail-open marker as a malformed config, so a\n\t\t\t\t// silently-unapplied grant is visible to the operator. The resolver emits `idp_role_mapping_failed`.\n\t\t\t\tif (syncResult.droppedUnsafeRules) {\n\t\t\t\t\tclaimMappingFailed = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst { id: apiKeyId, token: sessionToken } = await this.apiKeyManager.createSessionApiKeyWithId(\n\t\t\t\tdb,\n\t\t\t\tpersonRow.identity_id,\n\t\t\t\texpiration,\n\t\t\t\trequestInfo,\n\t\t\t\ttrustForwardedInfo,\n\t\t\t)\n\n\t\t\t// Bind the federated-session state to this session so it can be re-validated\n\t\t\t// against the IdP later. Present only when the provider supports it and\n\t\t\t// revalidation is enabled on the IdP configuration (A24). Refresh tokens must be\n\t\t\t// encrypted at rest, so when no encryption key is configured we skip persisting a\n\t\t\t// token-bearing session (it would otherwise crash or store secrets in plaintext) —\n\t\t\t// the session then behaves like a plain session with no re-validation.\n\t\t\tif (claim.idpSession) {\n\t\t\t\tconst hasTokens = !!claim.idpSession.tokens && Object.keys(claim.idpSession.tokens).length > 0\n\t\t\t\tif (!hasTokens || db.providers.encryptionEnabled) {\n\t\t\t\t\tawait db.commandBus.execute(new CreateIdpSessionCommand(apiKeyId, provider.id, claim.idpSession))\n\t\t\t\t} else {\n\t\t\t\t\t// Re-validation is enabled on this IdP but no encryption key is configured, so we\n\t\t\t\t\t// won't store the token-bearing session — it silently degrades to a plain,\n\t\t\t\t\t// non-revalidated session. Audit the downgrade (errorCode `encryption_disabled`)\n\t\t\t\t\t// so the operator can see that a session they expected to be continuously\n\t\t\t\t\t// re-validated is in fact not protected, instead of failing closed at sign-in.\n\t\t\t\t\t// Best-effort, in a savepoint: a failed insert would otherwise abort the whole\n\t\t\t\t\t// sign-in transaction, and a lost audit row must not block the sign-in.\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait db.commandBus.transaction(bus =>\n\t\t\t\t\t\t\tbus.execute(\n\t\t\t\t\t\t\t\tnew CreateAuthLogEntryCommand({\n\t\t\t\t\t\t\t\t\ttype: 'idp_session_revalidation_failed',\n\t\t\t\t\t\t\t\t\tinvokedById: personRow.identity_id,\n\t\t\t\t\t\t\t\t\tpersonId: personRow.id,\n\t\t\t\t\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\t\terrorCode: 'encryption_disabled',\n\t\t\t\t\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\t\t\t\t\teventData: { apiKeyId },\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tthis.logger.error(e, { message: 'IdP sign-in: writing the encryption_disabled audit entry failed', identityProviderId: provider.id })\n\t\t\t\t\t\t// the savepoint is rolled back, the sign-in transaction stays usable\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn new ResponseOk({\n\t\t\t\tperson: personRow,\n\t\t\t\ttoken: sessionToken,\n\t\t\t\tidpResponse: claim,\n\t\t\t\tclaimMappingAudit,\n\t\t\t\tclaimMappingFailed,\n\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t[AuthLogService.Key]: new AuthLogService.Bag({\n\t\t\t\t\tpersonId: personRow.id,\n\t\t\t\t\tidentityProviderId: provider.id,\n\t\t\t\t\tpersonInput: claim.email,\n\t\t\t\t}),\n\t\t\t})\n\t\t})\n\t}\n\n\tasync initSignInIDP(dbContext: DatabaseContext, idpSlug: string, data: unknown): Promise<IDPSignInManager.InitSignInIDPResponse> {\n\t\tconst provider = await dbContext.queryHandler.fetch(new IdentityProviderBySlugQuery(idpSlug))\n\t\tif (!provider || provider.disabledAt) {\n\t\t\treturn new ResponseError('PROVIDER_NOT_FOUND', `Identity provider ${idpSlug} not found`)\n\t\t}\n\t\tconst providerService = this.idpRegistry.getHandler(provider.type)\n\t\tconst validatedConfig = providerService.validateConfiguration(provider.configuration)\n\t\ttry {\n\t\t\tconst initResponse = await providerService.initAuth(validatedConfig, data)\n\n\t\t\tconst publicConfig = providerService.getPublicConfiguration\n\t\t\t\t? providerService.getPublicConfiguration(validatedConfig)\n\t\t\t\t: validatedConfig\n\n\t\t\treturn new ResponseOk({\n\t\t\t\t...initResponse,\n\t\t\t\tidpConfiguration: provider.initReturnsConfig ? publicConfig : null,\n\t\t\t})\n\t\t} catch (e) {\n\t\t\tif (e instanceof IDPValidationError) {\n\t\t\t\treturn new ResponseError('IDP_VALIDATION_FAILED', e.message)\n\t\t\t}\n\t\t\tthrow e\n\t\t}\n\t}\n\n\tprivate async resolvePerson(db: DatabaseContext, claim: IDPResponse, provider: IdentityProviderRow): Promise<IDPSignInManager.ResolvePersonResult> {\n\t\tconst personByIdPQuery = new PersonByIdPQuery(provider.id, claim.externalIdentifier)\n\t\tconst personByIdp = await db.queryHandler.fetch(personByIdPQuery)\n\t\tif (personByIdp) {\n\t\t\treturn { person: personByIdp }\n\t\t}\n\n\t\tif (!provider.exclusive) {\n\t\t\tconst personByEmail = typeof claim.email === 'string' && claim.email\n\t\t\t\t? await db.queryHandler.fetch(PersonQuery.byEmail(claim.email))\n\t\t\t\t: null\n\t\t\tif (personByEmail) {\n\t\t\t\t// Auto-linking an IdP identity to a pre-existing local account by\n\t\t\t\t// e-mail is takeover-grade: if the provider returns an unverified\n\t\t\t\t// (or attacker-controlled) e-mail, it could hijack the account. When\n\t\t\t\t// the provider requires a verified e-mail, refuse to link — and to\n\t\t\t\t// sign in — unless the address is asserted verified. `assumeEmailVerified`\n\t\t\t\t// lets a trusted IdP that never emits the claim still satisfy the gate.\n\t\t\t\tconst emailVerified = provider.assumeEmailVerified || claim.emailVerified === true\n\t\t\t\tif (provider.requireVerifiedEmail && !emailVerified) {\n\t\t\t\t\treturn { person: null, blockedReason: 'idp_email_unverified', blockedPersonId: personByEmail.id }\n\t\t\t\t}\n\t\t\t\tawait this.saveIdpIdentifier(db, provider, claim, personByEmail)\n\t\t\t\treturn { person: personByEmail }\n\t\t\t}\n\t\t}\n\n\t\tif (provider.autoSignUp) {\n\t\t\tconst signedUpPerson = await this.signUp(db, claim, provider)\n\t\t\tawait this.saveIdpIdentifier(db, provider, claim, signedUpPerson)\n\t\t\treturn { person: signedUpPerson, isNewPerson: true }\n\t\t}\n\n\t\treturn { person: null }\n\t}\n\n\tprivate async signUp(db: DatabaseContext, { email, name, externalIdentifier }: IDPResponse, provider: IdentityProviderRow): Promise<PersonRow> {\n\t\tconst roles = [TenantRole.PERSON]\n\t\tconst identityId = await db.commandBus.execute(new CreateIdentityCommand(roles))\n\t\tconst newPerson = await db.commandBus.execute(\n\t\t\tnew CreatePersonCommand({\n\t\t\t\tidentityId,\n\t\t\t\temail: provider.exclusive ? undefined : email,\n\t\t\t\tpassword: NoPassword,\n\t\t\t\tname: name ?? email?.split('@')[0] ?? externalIdentifier,\n\t\t\t\tidpOnly: provider.exclusive,\n\t\t\t}),\n\t\t)\n\n\t\treturn {\n\t\t\t...newPerson,\n\t\t\troles,\n\t\t}\n\t}\n\n\tprivate async saveIdpIdentifier(db: DatabaseContext, provider: IdentityProviderRow, claim: IDPResponse, person: PersonRow) {\n\t\tawait db.commandBus.execute(new CreatePersonIdentityProviderIdentifierCommand(provider.id, person.id, claim.externalIdentifier))\n\t}\n}\n\nnamespace IDPSignInManager {\n\texport type ResolvePersonResult = {\n\t\treadonly person: PersonRow | null\n\t\treadonly blockedReason?: 'idp_email_unverified'\n\t\treadonly blockedPersonId?: string\n\t\t/** True when the person row was just created by auto-sign-up (drives the `sticky` claim-mapping policy). */\n\t\treadonly isNewPerson?: boolean\n\t}\n\n\texport type InitSignInIDPResponse = Response<InitSignInIdpResult, InitSignInIdpErrorCode>\n\n\tinterface SignInIDPResult {\n\t\treadonly person: PersonRow\n\t\treadonly token: string\n\t\treadonly idpResponse?: Record<string, unknown>\n\t\t/** Identity provider the sign-in went through (for the resolver's audit). */\n\t\treadonly identityProviderId?: string\n\t\t/** Claim-mapping (A09) before/after delta — present only when a mapping changed grants. */\n\t\treadonly claimMappingAudit?: ClaimMappingAudit | null\n\t\t/** True when claim mapping failed and was skipped (fail-open) — drives the `idp_role_mapping_failed` audit. */\n\t\treadonly claimMappingFailed?: boolean\n\t\t[AuthLogService.Key]: AuthLogService.Bag\n\t}\n\n\texport type SignInIDPResponse = Response<SignInIDPResult, SignInIdpErrorCode, {\n\t\t[AuthLogService.Key]: AuthLogService.Bag\n\t}>\n}\n\nexport { IDPSignInManager }\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,MAAM,iBAAiB;AAAA,EACtB,YACkB,eACA,aACA,kBACA,QAChB;AAJgB,SAAA,gBAAA;AACA,SAAA,cAAA;AACA,SAAA,mBAAA;AACA,SAAA,SAAA;AAAA,EACf;AAAA,EAEH,MAAM,UACL,WACA,SACA,cACA,YACA,aACA,oBAC8C;AAC9C,WAAO,UAAU,YAAY,OAAO,OAAoD;AACvF,YAAM,WAAW,MAAM,GAAG,aAAa,MAAM,IAAI,4BAA4B,OAAO,CAAC;AACrF,UAAI,CAAC,YAAY,SAAS,YAAY;AACrC,cAAM,IAAI,MAAM,o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,QAAQ,OAAO,MAAM,GAAG,EAAE,CAAC,KAAK;AAAA,QACtC,SAAS,SAAS;AAAA,MAAA,CAClB;AAAA,IAAA;AAGF,WAAO;AAAA,MACN,GAAG;AAAA,MACH;AAAA,IAAA;AAAA,EAEF;AAAA,EAEA,MAAc,kBAAkB,IAAqB,UAA+B,OAAoB,QAAmB;AAC1H,UAAM,GAAG,WAAW,QAAQ,IAAI,8CAA8C,SAAS,IAAI,OAAO,IAAI,MAAM,kBAAkB,CAAC;AAAA,EAChI;AACD;"}
|
|
@@ -11,9 +11,10 @@ const CreateAuthLogEntryCommand = require("../../commands/authLog/CreateAuthLogE
|
|
|
11
11
|
const IDPRevalidation = require("./IDPRevalidation.cjs");
|
|
12
12
|
const ClaimMapping = require("./ClaimMapping.cjs");
|
|
13
13
|
class IdpSessionRevalidator {
|
|
14
|
-
constructor(idpRegistry, claimSyncService) {
|
|
14
|
+
constructor(idpRegistry, claimSyncService, logger) {
|
|
15
15
|
this.idpRegistry = idpRegistry;
|
|
16
16
|
this.claimSyncService = claimSyncService;
|
|
17
|
+
this.logger = logger;
|
|
17
18
|
}
|
|
18
19
|
async revalidate(dbContext, readDbContext, apiKeyRow, requestInfo) {
|
|
19
20
|
const row = await readDbContext.queryHandler.fetch(new IdpSessionByApiKeyQuery.IdpSessionByApiKeyQuery(apiKeyRow.id, readDbContext.providers));
|
|
@@ -39,7 +40,8 @@ class IdpSessionRevalidator {
|
|
|
39
40
|
let claimed;
|
|
40
41
|
try {
|
|
41
42
|
claimed = await dbContext.commandBus.execute(new ClaimIdpRevalidationCommand.ClaimIdpRevalidationCommand(row.id, decision.claimInterval));
|
|
42
|
-
} catch {
|
|
43
|
+
} catch (e) {
|
|
44
|
+
this.logger.warn(e, { message: "IdP session revalidation: claim failed", idpSessionId: row.id });
|
|
43
45
|
return "valid";
|
|
44
46
|
}
|
|
45
47
|
if (!claimed) {
|
|
@@ -49,7 +51,8 @@ class IdpSessionRevalidator {
|
|
|
49
51
|
return await this.runRevalidation(dbContext, handler, row, apiKeyRow, requestInfo);
|
|
50
52
|
}
|
|
51
53
|
setImmediate(() => {
|
|
52
|
-
this.runRevalidation(dbContext, handler, row, apiKeyRow, requestInfo).catch(() => {
|
|
54
|
+
this.runRevalidation(dbContext, handler, row, apiKeyRow, requestInfo).catch((e) => {
|
|
55
|
+
this.logger.error(e, { message: "IdP session revalidation: background run failed", idpSessionId: row.id });
|
|
53
56
|
});
|
|
54
57
|
});
|
|
55
58
|
return "valid";
|
|
@@ -77,14 +80,16 @@ class IdpSessionRevalidator {
|
|
|
77
80
|
let config;
|
|
78
81
|
try {
|
|
79
82
|
config = handler.validateConfiguration(row.providerConfiguration);
|
|
80
|
-
} catch {
|
|
83
|
+
} catch (e) {
|
|
84
|
+
this.logger.warn(e, { message: "IdP session revalidation: stored configuration is invalid", idpSessionId: row.id });
|
|
81
85
|
await this.logRevalidationFailed(dbContext, apiKeyRow, row, "config_invalid", requestInfo);
|
|
82
86
|
return "valid";
|
|
83
87
|
}
|
|
84
88
|
let result;
|
|
85
89
|
try {
|
|
86
90
|
result = await handler.revalidate(config, row.session);
|
|
87
|
-
} catch {
|
|
91
|
+
} catch (e) {
|
|
92
|
+
this.logger.warn(e, { message: "IdP session revalidation: identity provider call failed", idpSessionId: row.id });
|
|
88
93
|
await this.logRevalidationFailed(dbContext, apiKeyRow, row, "revalidation_error", requestInfo);
|
|
89
94
|
return "valid";
|
|
90
95
|
}
|
|
@@ -96,7 +101,8 @@ class IdpSessionRevalidator {
|
|
|
96
101
|
try {
|
|
97
102
|
await dbContext.commandBus.execute(new UpdateIdpSessionCommand.UpdateIdpSessionCommand(row.id, result.idpSession));
|
|
98
103
|
await this.logRevalidated(dbContext, apiKeyRow, row, requestInfo);
|
|
99
|
-
} catch {
|
|
104
|
+
} catch (e) {
|
|
105
|
+
this.logger.error(e, { message: "IdP session revalidation: persisting the rotated session failed", idpSessionId: row.id });
|
|
100
106
|
}
|
|
101
107
|
}
|
|
102
108
|
if (result.claims) {
|
|
@@ -127,7 +133,8 @@ class IdpSessionRevalidator {
|
|
|
127
133
|
if (droppedUnsafeRules) {
|
|
128
134
|
await this.logRoleMapping(dbContext, apiKeyRow, row, "idp_role_mapping_failed", void 0, requestInfo);
|
|
129
135
|
}
|
|
130
|
-
} catch {
|
|
136
|
+
} catch (e) {
|
|
137
|
+
this.logger.warn(e, { message: "IdP session revalidation: claim mapping sync failed", idpSessionId: row.id });
|
|
131
138
|
await this.logRoleMapping(dbContext, apiKeyRow, row, "idp_role_mapping_failed", void 0, requestInfo);
|
|
132
139
|
}
|
|
133
140
|
}
|
|
@@ -143,14 +150,14 @@ class IdpSessionRevalidator {
|
|
|
143
150
|
// (consistent with the project_membership_* audit events).
|
|
144
151
|
targetPersonId: apiKeyRow.person_id ?? void 0,
|
|
145
152
|
identityProviderId: row.identityProviderId,
|
|
146
|
-
personTokenId: apiKeyRow.id,
|
|
147
153
|
success: true,
|
|
148
154
|
eventData,
|
|
149
155
|
ipAddress: requestInfo?.ip,
|
|
150
156
|
userAgent: requestInfo?.userAgent
|
|
151
157
|
})
|
|
152
158
|
);
|
|
153
|
-
} catch {
|
|
159
|
+
} catch (e) {
|
|
160
|
+
this.logger.error(e, { message: `IdP session revalidation: writing the ${type} audit entry failed`, idpSessionId: row.id });
|
|
154
161
|
}
|
|
155
162
|
}
|
|
156
163
|
async logRevalidated(dbContext, apiKeyRow, row, requestInfo) {
|
|
@@ -160,10 +167,10 @@ class IdpSessionRevalidator {
|
|
|
160
167
|
invokedById: apiKeyRow.identity_id,
|
|
161
168
|
personId: apiKeyRow.person_id ?? void 0,
|
|
162
169
|
identityProviderId: row.identityProviderId,
|
|
163
|
-
personTokenId: apiKeyRow.id,
|
|
164
170
|
success: true,
|
|
165
171
|
ipAddress: requestInfo?.ip,
|
|
166
|
-
userAgent: requestInfo?.userAgent
|
|
172
|
+
userAgent: requestInfo?.userAgent,
|
|
173
|
+
eventData: { apiKeyId: apiKeyRow.id }
|
|
167
174
|
})
|
|
168
175
|
);
|
|
169
176
|
}
|
|
@@ -182,37 +189,41 @@ class IdpSessionRevalidator {
|
|
|
182
189
|
invokedById: apiKeyRow.identity_id,
|
|
183
190
|
personId: apiKeyRow.person_id ?? void 0,
|
|
184
191
|
identityProviderId: row.identityProviderId,
|
|
185
|
-
personTokenId: apiKeyRow.id,
|
|
186
192
|
// not a security failure (the session is kept) — a fail-open marker the operator
|
|
187
193
|
// can alert on. `success: true` keeps it out of the failed-login funnels.
|
|
188
194
|
success: true,
|
|
189
195
|
errorCode,
|
|
190
196
|
ipAddress: requestInfo?.ip,
|
|
191
|
-
userAgent: requestInfo?.userAgent
|
|
197
|
+
userAgent: requestInfo?.userAgent,
|
|
198
|
+
eventData: { apiKeyId: apiKeyRow.id }
|
|
192
199
|
})
|
|
193
200
|
);
|
|
194
|
-
} catch {
|
|
201
|
+
} catch (e) {
|
|
202
|
+
this.logger.error(e, { message: "IdP session revalidation: writing the idp_session_revalidation_failed audit entry failed", idpSessionId: row.id });
|
|
195
203
|
}
|
|
196
204
|
}
|
|
197
205
|
async revoke(dbContext, apiKeyRow, row, reason, requestInfo) {
|
|
198
206
|
await dbContext.commandBus.execute(new DisableApiKeyCommand.DisableApiKeyCommand(apiKeyRow.id));
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
207
|
+
try {
|
|
208
|
+
await dbContext.commandBus.execute(
|
|
209
|
+
new CreateAuthLogEntryCommand.CreateAuthLogEntryCommand({
|
|
210
|
+
type: "idp_session_revoked",
|
|
211
|
+
invokedById: apiKeyRow.identity_id,
|
|
212
|
+
personId: apiKeyRow.person_id ?? void 0,
|
|
213
|
+
identityProviderId: row.identityProviderId,
|
|
214
|
+
success: false,
|
|
215
|
+
errorCode: reason,
|
|
216
|
+
ipAddress: requestInfo?.ip,
|
|
217
|
+
userAgent: requestInfo?.userAgent,
|
|
218
|
+
// the action payload belongs in `event_data` (where every other audit event puts
|
|
219
|
+
// it and where the admin UI / AuthLogQueryResolver reads it); `metadata` is for
|
|
220
|
+
// transport context (forwarder IP/UA).
|
|
221
|
+
eventData: { reason, apiKeyId: apiKeyRow.id }
|
|
222
|
+
})
|
|
223
|
+
);
|
|
224
|
+
} catch (e) {
|
|
225
|
+
this.logger.error(e, { message: "IdP session revalidation: writing the idp_session_revoked audit entry failed", idpSessionId: row.id });
|
|
226
|
+
}
|
|
216
227
|
}
|
|
217
228
|
resolveConfig(configuration) {
|
|
218
229
|
const raw = configuration.revalidation ?? {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IdpSessionRevalidator.cjs","sources":["../../../../../../../packages/engine-tenant-api/src/model/service/idp/IdpSessionRevalidator.ts"],"sourcesContent":["import { DatabaseContext } from '../../utils/index.js'\nimport { ApiKeyRequestInfo } from '../../commands/index.js'\nimport { ApiKeyRow } from '../../queries/apiKey/ApiKeyQuery.js'\nimport { IdpSessionByApiKeyQuery, IdpSessionRow } from '../../queries/idp/IdpSessionByApiKeyQuery.js'\nimport { IDPHandlerRegistry } from './IDPHandlerRegistry.js'\nimport { ClaimIdpRevalidationCommand } from '../../commands/idp/ClaimIdpRevalidationCommand.js'\nimport { UpdateIdpSessionCommand } from '../../commands/idp/UpdateIdpSessionCommand.js'\nimport { DisableApiKeyCommand } from '../../commands/index.js'\nimport { CreateAuthLogEntryCommand } from '../../commands/authLog/CreateAuthLogEntryCommand.js'\nimport { REVALIDATION_DEFAULT_FALLBACK_INTERVAL, REVALIDATION_DEFAULT_MIN_INTERVAL, REVALIDATION_DEFAULT_SOFT_THRESHOLD } from './IDPRevalidation.js'\nimport { IdentityProviderHandler, RevalidationResult } from './IdentityProviderHandler.js'\nimport { IDPClaimSyncService } from './IDPClaimSyncService.js'\nimport { parseClaimMapping } from './ClaimMapping.js'\nimport { JSONValue } from '@contember/schema'\n\nexport type RevalidationOutcome = 'valid' | 'revoked'\n\ntype ResolvedRevalidationConfig = {\n\tenabled: boolean\n\tsoftThreshold: number\n\tminInterval: string\n\tfallbackInterval: string\n\tmode: 'auto' | 'blocking'\n}\n\n/**\n * Decision for the current request: whether to attempt a revalidation, and if so whether it\n * must block the request. `claimInterval` is the single-flight floor for the atomic claim.\n */\ntype Decision = null | { blocking: boolean; claimInterval: string }\n\n/**\n * Re-validates IdP-backed sessions against their identity provider on the verify hot path\n * (A24). Invoked from `ApiKeyManager.verifyAndProlong`. Operates entirely through the supplied\n * database contexts and the command bus, so it does not depend on `ApiKeyManager` (no DI cycle).\n *\n * The cadence is driven by the **access-token lifetime**, not a fixed interval:\n * - while the token is fresh (before `softRefreshThreshold` of its lifetime) → skip, free;\n * - past the threshold but not yet expired → a proactive **background (SWR)** refresh, so the\n * request keeps zero added latency and the token is renewed before it dies;\n * - once the token has actually expired → a **blocking** refresh (we can't serve a dead token).\n * `mode: 'blocking'` forces every revalidation synchronous (zero revocation lag). When the IdP\n * returns no token expiry, falls back to a plain `fallbackInterval` background throttle.\n */\nexport class IdpSessionRevalidator {\n\tconstructor(\n\t\tprivate readonly idpRegistry: IDPHandlerRegistry,\n\t\tprivate readonly claimSyncService: IDPClaimSyncService,\n\t) {\n\t}\n\n\tasync revalidate(\n\t\tdbContext: DatabaseContext,\n\t\treadDbContext: DatabaseContext,\n\t\tapiKeyRow: ApiKeyRow,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t): Promise<RevalidationOutcome> {\n\t\tconst row = await readDbContext.queryHandler.fetch(new IdpSessionByApiKeyQuery(apiKeyRow.id, readDbContext.providers))\n\t\tif (!row) {\n\t\t\t// not a federated session (password / IdP without revalidation) — fast no-op\n\t\t\treturn 'valid'\n\t\t}\n\n\t\tconst config = this.resolveConfig(row.providerConfiguration)\n\t\tif (!config.enabled) {\n\t\t\treturn 'valid'\n\t\t}\n\n\t\t// A disabled IdP no longer vouches for its sessions.\n\t\tif (row.providerDisabledAt) {\n\t\t\tawait this.revoke(dbContext, apiKeyRow, row, 'idp_disabled', requestInfo)\n\t\t\treturn 'revoked'\n\t\t}\n\n\t\tconst handler = this.idpRegistry.getHandlerOrNull(row.providerType)\n\t\tif (!handler?.revalidate) {\n\t\t\t// provider can't actively re-validate (e.g. SAML) — rely on expiry / SLO\n\t\t\treturn 'valid'\n\t\t}\n\n\t\tconst decision = this.decide(row, config, dbContext.providers.now())\n\t\tif (!decision) {\n\t\t\t// token still fresh — vouched for, no IdP call\n\t\t\treturn 'valid'\n\t\t}\n\n\t\t// Atomic claim = single-flight. Loser (within the floor window, or lost the race) serves stale.\n\t\tlet claimed: boolean\n\t\ttry {\n\t\t\tclaimed = await dbContext.commandBus.execute(new ClaimIdpRevalidationCommand(row.id, decision.claimInterval))\n\t\t} catch {\n\t\t\t// invalid interval string or transient DB error — fail open, retry next request\n\t\t\treturn 'valid'\n\t\t}\n\t\tif (!claimed) {\n\t\t\treturn 'valid'\n\t\t}\n\n\t\tif (decision.blocking) {\n\t\t\treturn await this.runRevalidation(dbContext, handler, row, apiKeyRow, requestInfo)\n\t\t}\n\n\t\t// SWR: serve this request from the (still valid) token, refresh after the response.\n\t\t// The work runs detached (after the response is sent), so any rejection — a transient\n\t\t// DB error in the revoke / persist writes, a corrupt-config throw — must be swallowed\n\t\t// here; otherwise it becomes an unhandledRejection and can take the worker down. The\n\t\t// session is simply kept and re-tried on a later request (the claim floor throttles).\n\t\tsetImmediate(() => {\n\t\t\tthis.runRevalidation(dbContext, handler, row, apiKeyRow, requestInfo).catch(() => {})\n\t\t})\n\t\treturn 'valid'\n\t}\n\n\t/**\n\t * Decide whether (and how) to revalidate, purely from timestamps — no interval parsing in\n\t * JS (the claim handles intervals in SQL). Returns null to skip.\n\t */\n\tprivate decide(row: IdpSessionRow, config: ResolvedRevalidationConfig, now: Date): Decision {\n\t\tconst expiresAt = row.session.expiresAt\n\t\tconst obtainedAt = row.tokenObtainedAt\n\n\t\t// No lifetime info from the IdP → plain background throttle on fallbackInterval.\n\t\tif (!expiresAt || !obtainedAt) {\n\t\t\treturn { blocking: config.mode === 'blocking', claimInterval: config.fallbackInterval }\n\t\t}\n\n\t\tconst lifetimeMs = expiresAt.getTime() - obtainedAt.getTime()\n\t\tconst softAtMs = obtainedAt.getTime() + lifetimeMs * config.softThreshold\n\t\tconst nowMs = now.getTime()\n\n\t\tif (nowMs < softAtMs) {\n\t\t\treturn null // still within the trusted window\n\t\t}\n\n\t\tconst expired = nowMs >= expiresAt.getTime()\n\t\treturn { blocking: config.mode === 'blocking' || expired, claimInterval: config.minInterval }\n\t}\n\n\tprivate async runRevalidation(\n\t\tdbContext: DatabaseContext,\n\t\thandler: IdentityProviderHandler<{}>,\n\t\trow: IdpSessionRow,\n\t\tapiKeyRow: ApiKeyRow,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t): Promise<RevalidationOutcome> {\n\t\tlet config: {}\n\t\ttry {\n\t\t\tconfig = handler.validateConfiguration(row.providerConfiguration)\n\t\t} catch {\n\t\t\t// corrupt stored config — must NOT revoke; keep the session and retry later. Audit\n\t\t\t// it so the operator can tell \"vouched for\" apart from \"silently broken\" (without an\n\t\t\t// entry, a config typo disables re-validation invisibly for the life of every session).\n\t\t\tawait this.logRevalidationFailed(dbContext, apiKeyRow, row, 'config_invalid', requestInfo)\n\t\t\treturn 'valid'\n\t\t}\n\n\t\tlet result: RevalidationResult\n\t\ttry {\n\t\t\tresult = await handler.revalidate!(config, row.session)\n\t\t} catch {\n\t\t\t// transient failure (network / IdP down) — must NOT revoke; keep the session and retry\n\t\t\t// on a later request (the claim floor prevents hammering the IdP). Audited (throttled\n\t\t\t// to one entry per claim window) so a prolonged IdP outage is visible rather than a\n\t\t\t// silent fail-open.\n\t\t\tawait this.logRevalidationFailed(dbContext, apiKeyRow, row, 'revalidation_error', requestInfo)\n\t\t\treturn 'valid'\n\t\t}\n\n\t\tif (result.status === 'revoked') {\n\t\t\tawait this.revoke(dbContext, apiKeyRow, row, result.reason, requestInfo)\n\t\t\treturn 'revoked'\n\t\t}\n\n\t\t// Still valid — persist the rotated token (resets the lifetime reference) / refreshed\n\t\t// expiry. A rotation is a real, low-frequency event (token-lifetime cadence), so we\n\t\t// audit it as `idp_session_revalidated`; the no-op userinfo/introspection probes\n\t\t// (no rotated session) are intentionally NOT logged to keep the audit log usable.\n\t\t//\n\t\t// The IdP has already vouched for the session, so these post-success writes are pure\n\t\t// best-effort bookkeeping (they only reset the SWR cadence reference). A transient DB\n\t\t// error or an `encrypt()` throw here must NOT fail the request — otherwise a blocking\n\t\t// revalidation fails closed on a successful refresh, contradicting \"fail open\" (the SWR\n\t\t// path already swallows this). Keep the existing row; the claim floor throttles a retry.\n\t\tif (result.idpSession) {\n\t\t\ttry {\n\t\t\t\tawait dbContext.commandBus.execute(new UpdateIdpSessionCommand(row.id, result.idpSession))\n\t\t\t\tawait this.logRevalidated(dbContext, apiKeyRow, row, requestInfo)\n\t\t\t} catch {\n\t\t\t\t// fall through — session stays valid, persist retried on a later request\n\t\t\t}\n\t\t}\n\n\t\t// A09 — re-apply the IdP's claim mapping when the refresh returned fresh claims, so an `always`\n\t\t// mapping keeps an established session's project memberships in sync with the IdP's current claims\n\t\t// without requiring a full re-login. `sticky` mappings self-skip (the sync passes isNewPerson=false).\n\t\t// `claimsComplete` tells the sync whether the refresh rebuilt sign-in's full claim surface, so it can\n\t\t// reconcile (incl. `unmatched: \"remove\"`) exactly like sign-in. Strictly fail-open — see `syncClaims`.\n\t\tif (result.claims) {\n\t\t\tawait this.syncClaims(dbContext, row, apiKeyRow, result.claims, result.claimsComplete === true, requestInfo)\n\t\t}\n\t\treturn 'valid'\n\t}\n\n\t/**\n\t * Re-apply the claim mapping on a successful refresh. Runs in its own transaction (atomic apply of\n\t * the membership changes) and never throws: the IdP has already vouched for the session, so a\n\t * malformed mapping or a transient apply error must not revoke or fail it. A real membership change\n\t * is audited as `idp_role_mapped`; a failure is audited as `idp_role_mapping_failed` (fail-open\n\t * marker), mirroring the sign-in path. `claimsComplete` carries whether the refresh rebuilt sign-in's\n\t * full claim surface (so removal reconciliation is safe) — see `allowRemoval` below.\n\t */\n\tprivate async syncClaims(\n\t\tdbContext: DatabaseContext,\n\t\trow: IdpSessionRow,\n\t\tapiKeyRow: ApiKeyRow,\n\t\tclaims: Record<string, unknown>,\n\t\tclaimsComplete: boolean,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tconst mapping = parseClaimMapping(row.providerConfiguration)\n\t\t\tif (!mapping) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// Atomic apply in its own transaction (the verify path has no surrounding one). `always`-only:\n\t\t\t// the sync passes isNewPerson=false, so a `sticky` mapping self-skips and returns a null audit.\n\t\t\t// Refresh mirrors sign-in as closely as the claim surface allows: when the provider returned its\n\t\t\t// COMPLETE surface (`claimsComplete` — `method: \"refresh\"` rebuilding sign-in's id-token + userinfo\n\t\t\t// merge), `unmatched: \"remove\"` reconciliation runs here too. A partial surface (a userinfo-only\n\t\t\t// probe, or a refresh whose userinfo fetch failed) passes `allowRemoval: false`, so refresh stays\n\t\t\t// additive-only and a membership the IdP still asserts is never stripped off an incomplete surface.\n\t\t\tconst { audit, droppedUnsafeRules } = await dbContext.transaction(db =>\n\t\t\t\tthis.claimSyncService.sync(db, mapping, claims, { id: apiKeyRow.identity_id }, false, { allowRemoval: claimsComplete })\n\t\t\t)\n\t\t\tif (audit) {\n\t\t\t\tawait this.logRoleMapping(dbContext, apiKeyRow, row, 'idp_role_mapped', audit, requestInfo)\n\t\t\t}\n\t\t\t// The apply-time safety backstop dropped a configured rule — emit the fail-open marker so a broken\n\t\t\t// mapping is visible on the refresh path too, mirroring sign-in (the marker carries no claim values).\n\t\t\tif (droppedUnsafeRules) {\n\t\t\t\tawait this.logRoleMapping(dbContext, apiKeyRow, row, 'idp_role_mapping_failed', undefined, requestInfo)\n\t\t\t}\n\t\t} catch {\n\t\t\t// Strictly fail-open: a malformed mapping or a transient apply error must never revoke or\n\t\t\t// fail an already-vouched-for session. The transaction rolls back any partial apply.\n\t\t\tawait this.logRoleMapping(dbContext, apiKeyRow, row, 'idp_role_mapping_failed', undefined, requestInfo)\n\t\t}\n\t}\n\n\tprivate async logRoleMapping(\n\t\tdbContext: DatabaseContext,\n\t\tapiKeyRow: ApiKeyRow,\n\t\trow: IdpSessionRow,\n\t\ttype: 'idp_role_mapped' | 'idp_role_mapping_failed',\n\t\teventData: JSONValue | undefined,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tawait dbContext.commandBus.execute(\n\t\t\t\tnew CreateAuthLogEntryCommand({\n\t\t\t\t\ttype,\n\t\t\t\t\tinvokedById: apiKeyRow.identity_id,\n\t\t\t\t\tpersonId: apiKeyRow.person_id ?? undefined,\n\t\t\t\t\t// The membership change affects this session's own person — record it as the target too,\n\t\t\t\t\t// so an admin querying membership changes by target_person_id sees IdP-driven grants/revokes\n\t\t\t\t\t// (consistent with the project_membership_* audit events).\n\t\t\t\t\ttargetPersonId: apiKeyRow.person_id ?? undefined,\n\t\t\t\t\tidentityProviderId: row.identityProviderId,\n\t\t\t\t\tpersonTokenId: apiKeyRow.id,\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\teventData,\n\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t}),\n\t\t\t)\n\t\t} catch {\n\t\t\t// best-effort audit — never fail the request because the audit write failed\n\t\t}\n\t}\n\n\tprivate async logRevalidated(dbContext: DatabaseContext, apiKeyRow: ApiKeyRow, row: IdpSessionRow, requestInfo?: ApiKeyRequestInfo): Promise<void> {\n\t\tawait dbContext.commandBus.execute(\n\t\t\tnew CreateAuthLogEntryCommand({\n\t\t\t\ttype: 'idp_session_revalidated',\n\t\t\t\tinvokedById: apiKeyRow.identity_id,\n\t\t\t\tpersonId: apiKeyRow.person_id ?? undefined,\n\t\t\t\tidentityProviderId: row.identityProviderId,\n\t\t\t\tpersonTokenId: apiKeyRow.id,\n\t\t\t\tsuccess: true,\n\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t}),\n\t\t)\n\t}\n\n\t/**\n\t * Audit a fail-open: the IdP couldn't be consulted (transient outage) or the stored config is\n\t * corrupt, so we kept the session rather than revoking it. Naturally throttled to one entry\n\t * per claim window (we only reach here after a successful claim, which bumps\n\t * `last_validated_at`). The write is best-effort and self-contained — a failure to audit must\n\t * never propagate and fail a blocking verify request (the whole point of failing open).\n\t */\n\tprivate async logRevalidationFailed(\n\t\tdbContext: DatabaseContext,\n\t\tapiKeyRow: ApiKeyRow,\n\t\trow: IdpSessionRow,\n\t\terrorCode: 'config_invalid' | 'revalidation_error',\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tawait dbContext.commandBus.execute(\n\t\t\t\tnew CreateAuthLogEntryCommand({\n\t\t\t\t\ttype: 'idp_session_revalidation_failed',\n\t\t\t\t\tinvokedById: apiKeyRow.identity_id,\n\t\t\t\t\tpersonId: apiKeyRow.person_id ?? undefined,\n\t\t\t\t\tidentityProviderId: row.identityProviderId,\n\t\t\t\t\tpersonTokenId: apiKeyRow.id,\n\t\t\t\t\t// not a security failure (the session is kept) — a fail-open marker the operator\n\t\t\t\t\t// can alert on. `success: true` keeps it out of the failed-login funnels.\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\terrorCode,\n\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t}),\n\t\t\t)\n\t\t} catch {\n\t\t\t// best-effort observability — never fail the request because the audit write failed\n\t\t}\n\t}\n\n\tprivate async revoke(\n\t\tdbContext: DatabaseContext,\n\t\tapiKeyRow: ApiKeyRow,\n\t\trow: IdpSessionRow,\n\t\treason: string,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t): Promise<void> {\n\t\tawait dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyRow.id))\n\t\tawait dbContext.commandBus.execute(\n\t\t\tnew CreateAuthLogEntryCommand({\n\t\t\t\ttype: 'idp_session_revoked',\n\t\t\t\tinvokedById: apiKeyRow.identity_id,\n\t\t\t\tpersonId: apiKeyRow.person_id ?? undefined,\n\t\t\t\tidentityProviderId: row.identityProviderId,\n\t\t\t\tpersonTokenId: apiKeyRow.id,\n\t\t\t\tsuccess: false,\n\t\t\t\terrorCode: reason,\n\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t// the action payload belongs in `event_data` (where every other audit event puts\n\t\t\t\t// it and where the admin UI / AuthLogQueryResolver reads it); `metadata` is for\n\t\t\t\t// transport context (forwarder IP/UA).\n\t\t\t\teventData: { reason },\n\t\t\t}),\n\t\t)\n\t}\n\n\tprivate resolveConfig(configuration: Record<string, unknown>): ResolvedRevalidationConfig {\n\t\tconst raw = (configuration.revalidation ?? {}) as Record<string, unknown>\n\t\tconst threshold = typeof raw.softRefreshThreshold === 'number' && raw.softRefreshThreshold > 0 && raw.softRefreshThreshold <= 1\n\t\t\t? raw.softRefreshThreshold\n\t\t\t: REVALIDATION_DEFAULT_SOFT_THRESHOLD\n\t\treturn {\n\t\t\tenabled: raw.enabled === true,\n\t\t\tsoftThreshold: threshold,\n\t\t\tminInterval: typeof raw.minInterval === 'string' ? raw.minInterval : REVALIDATION_DEFAULT_MIN_INTERVAL,\n\t\t\tfallbackInterval: typeof raw.fallbackInterval === 'string' ? raw.fallbackInterval : REVALIDATION_DEFAULT_FALLBACK_INTERVAL,\n\t\t\tmode: raw.mode === 'blocking' ? 'blocking' : 'auto',\n\t\t}\n\t}\n}\n"],"names":["IdpSessionByApiKeyQuery","ClaimIdpRevalidationCommand","UpdateIdpSessionCommand","parseClaimMapping","CreateAuthLogEntryCommand","DisableApiKeyCommand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,WAAW,EAAE,OAAA;AAAA,MAAO,CACpB;AAAA,IAAA;AAAA,EAEH;AAAA,EAEQ,cAAc,eAAoE;AACzF,UAAM,MAAO,cAAc,gBAAgB,CAAA;AAC3C,UAAM,YAAY,OAAO,IAAI,yBAAyB,YAAY,IAAI,uBAAuB,KAAK,IAAI,wBAAwB,IAC3H,IAAI,uBACJE,gBAAAA;AACH,WAAO;AAAA,MACN,SAAS,IAAI,YAAY;AAAA,MACzB,eAAe;AAAA,MACf,aAAa,OAAO,IAAI,gBAAgB,WAAW,IAAI,cAAcC,gBAAAA;AAAAA,MACrE,kBAAkB,OAAO,IAAI,qBAAqB,WAAW,IAAI,mBAAmBC,gBAAAA;AAAAA,MACpF,MAAM,IAAI,SAAS,aAAa,aAAa;AAAA,IAAA;AAAA,EAE/C;AACD;;"}
|
|
1
|
+
{"version":3,"file":"IdpSessionRevalidator.cjs","sources":["../../../../../../../packages/engine-tenant-api/src/model/service/idp/IdpSessionRevalidator.ts"],"sourcesContent":["import { DatabaseContext } from '../../utils/index.js'\nimport { ApiKeyRequestInfo } from '../../commands/index.js'\nimport { ApiKeyRow } from '../../queries/apiKey/ApiKeyQuery.js'\nimport { IdpSessionByApiKeyQuery, IdpSessionRow } from '../../queries/idp/IdpSessionByApiKeyQuery.js'\nimport { IDPHandlerRegistry } from './IDPHandlerRegistry.js'\nimport { ClaimIdpRevalidationCommand } from '../../commands/idp/ClaimIdpRevalidationCommand.js'\nimport { UpdateIdpSessionCommand } from '../../commands/idp/UpdateIdpSessionCommand.js'\nimport { DisableApiKeyCommand } from '../../commands/index.js'\nimport { CreateAuthLogEntryCommand } from '../../commands/authLog/CreateAuthLogEntryCommand.js'\nimport { REVALIDATION_DEFAULT_FALLBACK_INTERVAL, REVALIDATION_DEFAULT_MIN_INTERVAL, REVALIDATION_DEFAULT_SOFT_THRESHOLD } from './IDPRevalidation.js'\nimport { IdentityProviderHandler, RevalidationResult } from './IdentityProviderHandler.js'\nimport { IDPClaimSyncService } from './IDPClaimSyncService.js'\nimport { Logger } from '@contember/logger'\nimport { parseClaimMapping } from './ClaimMapping.js'\nimport { JSONValue } from '@contember/schema'\n\nexport type RevalidationOutcome = 'valid' | 'revoked'\n\ntype ResolvedRevalidationConfig = {\n\tenabled: boolean\n\tsoftThreshold: number\n\tminInterval: string\n\tfallbackInterval: string\n\tmode: 'auto' | 'blocking'\n}\n\n/**\n * Decision for the current request: whether to attempt a revalidation, and if so whether it\n * must block the request. `claimInterval` is the single-flight floor for the atomic claim.\n */\ntype Decision = null | { blocking: boolean; claimInterval: string }\n\n/**\n * Re-validates IdP-backed sessions against their identity provider on the verify hot path\n * (A24). Invoked from `ApiKeyManager.verifyAndProlong`. Operates entirely through the supplied\n * database contexts and the command bus, so it does not depend on `ApiKeyManager` (no DI cycle).\n *\n * The cadence is driven by the **access-token lifetime**, not a fixed interval:\n * - while the token is fresh (before `softRefreshThreshold` of its lifetime) → skip, free;\n * - past the threshold but not yet expired → a proactive **background (SWR)** refresh, so the\n * request keeps zero added latency and the token is renewed before it dies;\n * - once the token has actually expired → a **blocking** refresh (we can't serve a dead token).\n * `mode: 'blocking'` forces every revalidation synchronous (zero revocation lag). When the IdP\n * returns no token expiry, falls back to a plain `fallbackInterval` background throttle.\n */\nexport class IdpSessionRevalidator {\n\tconstructor(\n\t\tprivate readonly idpRegistry: IDPHandlerRegistry,\n\t\tprivate readonly claimSyncService: IDPClaimSyncService,\n\t\tprivate readonly logger: Logger,\n\t) {\n\t}\n\n\tasync revalidate(\n\t\tdbContext: DatabaseContext,\n\t\treadDbContext: DatabaseContext,\n\t\tapiKeyRow: ApiKeyRow,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t): Promise<RevalidationOutcome> {\n\t\tconst row = await readDbContext.queryHandler.fetch(new IdpSessionByApiKeyQuery(apiKeyRow.id, readDbContext.providers))\n\t\tif (!row) {\n\t\t\t// not a federated session (password / IdP without revalidation) — fast no-op\n\t\t\treturn 'valid'\n\t\t}\n\n\t\tconst config = this.resolveConfig(row.providerConfiguration)\n\t\tif (!config.enabled) {\n\t\t\treturn 'valid'\n\t\t}\n\n\t\t// A disabled IdP no longer vouches for its sessions.\n\t\tif (row.providerDisabledAt) {\n\t\t\tawait this.revoke(dbContext, apiKeyRow, row, 'idp_disabled', requestInfo)\n\t\t\treturn 'revoked'\n\t\t}\n\n\t\tconst handler = this.idpRegistry.getHandlerOrNull(row.providerType)\n\t\tif (!handler?.revalidate) {\n\t\t\t// provider can't actively re-validate (e.g. SAML) — rely on expiry / SLO\n\t\t\treturn 'valid'\n\t\t}\n\n\t\tconst decision = this.decide(row, config, dbContext.providers.now())\n\t\tif (!decision) {\n\t\t\t// token still fresh — vouched for, no IdP call\n\t\t\treturn 'valid'\n\t\t}\n\n\t\t// Atomic claim = single-flight. Loser (within the floor window, or lost the race) serves stale.\n\t\tlet claimed: boolean\n\t\ttry {\n\t\t\tclaimed = await dbContext.commandBus.execute(new ClaimIdpRevalidationCommand(row.id, decision.claimInterval))\n\t\t} catch (e) {\n\t\t\tthis.logger.warn(e, { message: 'IdP session revalidation: claim failed', idpSessionId: row.id })\n\t\t\t// invalid interval string or transient DB error — fail open, retry next request\n\t\t\treturn 'valid'\n\t\t}\n\t\tif (!claimed) {\n\t\t\treturn 'valid'\n\t\t}\n\n\t\tif (decision.blocking) {\n\t\t\treturn await this.runRevalidation(dbContext, handler, row, apiKeyRow, requestInfo)\n\t\t}\n\n\t\t// SWR: serve this request from the (still valid) token, refresh after the response.\n\t\t// The work runs detached (after the response is sent), so any rejection — a transient\n\t\t// DB error in the revoke / persist writes, a corrupt-config throw — must be swallowed\n\t\t// here; otherwise it becomes an unhandledRejection and can take the worker down. The\n\t\t// session is simply kept and re-tried on a later request (the claim floor throttles).\n\t\tsetImmediate(() => {\n\t\t\tthis.runRevalidation(dbContext, handler, row, apiKeyRow, requestInfo).catch(e => {\n\t\t\t\tthis.logger.error(e, { message: 'IdP session revalidation: background run failed', idpSessionId: row.id })\n\t\t\t})\n\t\t})\n\t\treturn 'valid'\n\t}\n\n\t/**\n\t * Decide whether (and how) to revalidate, purely from timestamps — no interval parsing in\n\t * JS (the claim handles intervals in SQL). Returns null to skip.\n\t */\n\tprivate decide(row: IdpSessionRow, config: ResolvedRevalidationConfig, now: Date): Decision {\n\t\tconst expiresAt = row.session.expiresAt\n\t\tconst obtainedAt = row.tokenObtainedAt\n\n\t\t// No lifetime info from the IdP → plain background throttle on fallbackInterval.\n\t\tif (!expiresAt || !obtainedAt) {\n\t\t\treturn { blocking: config.mode === 'blocking', claimInterval: config.fallbackInterval }\n\t\t}\n\n\t\tconst lifetimeMs = expiresAt.getTime() - obtainedAt.getTime()\n\t\tconst softAtMs = obtainedAt.getTime() + lifetimeMs * config.softThreshold\n\t\tconst nowMs = now.getTime()\n\n\t\tif (nowMs < softAtMs) {\n\t\t\treturn null // still within the trusted window\n\t\t}\n\n\t\tconst expired = nowMs >= expiresAt.getTime()\n\t\treturn { blocking: config.mode === 'blocking' || expired, claimInterval: config.minInterval }\n\t}\n\n\tprivate async runRevalidation(\n\t\tdbContext: DatabaseContext,\n\t\thandler: IdentityProviderHandler<{}>,\n\t\trow: IdpSessionRow,\n\t\tapiKeyRow: ApiKeyRow,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t): Promise<RevalidationOutcome> {\n\t\tlet config: {}\n\t\ttry {\n\t\t\tconfig = handler.validateConfiguration(row.providerConfiguration)\n\t\t} catch (e) {\n\t\t\tthis.logger.warn(e, { message: 'IdP session revalidation: stored configuration is invalid', idpSessionId: row.id })\n\t\t\t// corrupt stored config — must NOT revoke; keep the session and retry later. Audit\n\t\t\t// it so the operator can tell \"vouched for\" apart from \"silently broken\" (without an\n\t\t\t// entry, a config typo disables re-validation invisibly for the life of every session).\n\t\t\tawait this.logRevalidationFailed(dbContext, apiKeyRow, row, 'config_invalid', requestInfo)\n\t\t\treturn 'valid'\n\t\t}\n\n\t\tlet result: RevalidationResult\n\t\ttry {\n\t\t\tresult = await handler.revalidate!(config, row.session)\n\t\t} catch (e) {\n\t\t\tthis.logger.warn(e, { message: 'IdP session revalidation: identity provider call failed', idpSessionId: row.id })\n\t\t\t// transient failure (network / IdP down) — must NOT revoke; keep the session and retry\n\t\t\t// on a later request (the claim floor prevents hammering the IdP). Audited (throttled\n\t\t\t// to one entry per claim window) so a prolonged IdP outage is visible rather than a\n\t\t\t// silent fail-open.\n\t\t\tawait this.logRevalidationFailed(dbContext, apiKeyRow, row, 'revalidation_error', requestInfo)\n\t\t\treturn 'valid'\n\t\t}\n\n\t\tif (result.status === 'revoked') {\n\t\t\tawait this.revoke(dbContext, apiKeyRow, row, result.reason, requestInfo)\n\t\t\treturn 'revoked'\n\t\t}\n\n\t\t// Still valid — persist the rotated token (resets the lifetime reference) / refreshed\n\t\t// expiry. A rotation is a real, low-frequency event (token-lifetime cadence), so we\n\t\t// audit it as `idp_session_revalidated`; the no-op userinfo/introspection probes\n\t\t// (no rotated session) are intentionally NOT logged to keep the audit log usable.\n\t\t//\n\t\t// The IdP has already vouched for the session, so these post-success writes are pure\n\t\t// best-effort bookkeeping (they only reset the SWR cadence reference). A transient DB\n\t\t// error or an `encrypt()` throw here must NOT fail the request — otherwise a blocking\n\t\t// revalidation fails closed on a successful refresh, contradicting \"fail open\" (the SWR\n\t\t// path already swallows this). Keep the existing row; the claim floor throttles a retry.\n\t\tif (result.idpSession) {\n\t\t\ttry {\n\t\t\t\tawait dbContext.commandBus.execute(new UpdateIdpSessionCommand(row.id, result.idpSession))\n\t\t\t\tawait this.logRevalidated(dbContext, apiKeyRow, row, requestInfo)\n\t\t\t} catch (e) {\n\t\t\t\tthis.logger.error(e, { message: 'IdP session revalidation: persisting the rotated session failed', idpSessionId: row.id })\n\t\t\t\t// fall through — session stays valid, persist retried on a later request\n\t\t\t}\n\t\t}\n\n\t\t// A09 — re-apply the IdP's claim mapping when the refresh returned fresh claims, so an `always`\n\t\t// mapping keeps an established session's project memberships in sync with the IdP's current claims\n\t\t// without requiring a full re-login. `sticky` mappings self-skip (the sync passes isNewPerson=false).\n\t\t// `claimsComplete` tells the sync whether the refresh rebuilt sign-in's full claim surface, so it can\n\t\t// reconcile (incl. `unmatched: \"remove\"`) exactly like sign-in. Strictly fail-open — see `syncClaims`.\n\t\tif (result.claims) {\n\t\t\tawait this.syncClaims(dbContext, row, apiKeyRow, result.claims, result.claimsComplete === true, requestInfo)\n\t\t}\n\t\treturn 'valid'\n\t}\n\n\t/**\n\t * Re-apply the claim mapping on a successful refresh. Runs in its own transaction (atomic apply of\n\t * the membership changes) and never throws: the IdP has already vouched for the session, so a\n\t * malformed mapping or a transient apply error must not revoke or fail it. A real membership change\n\t * is audited as `idp_role_mapped`; a failure is audited as `idp_role_mapping_failed` (fail-open\n\t * marker), mirroring the sign-in path. `claimsComplete` carries whether the refresh rebuilt sign-in's\n\t * full claim surface (so removal reconciliation is safe) — see `allowRemoval` below.\n\t */\n\tprivate async syncClaims(\n\t\tdbContext: DatabaseContext,\n\t\trow: IdpSessionRow,\n\t\tapiKeyRow: ApiKeyRow,\n\t\tclaims: Record<string, unknown>,\n\t\tclaimsComplete: boolean,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tconst mapping = parseClaimMapping(row.providerConfiguration)\n\t\t\tif (!mapping) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// Atomic apply in its own transaction (the verify path has no surrounding one). `always`-only:\n\t\t\t// the sync passes isNewPerson=false, so a `sticky` mapping self-skips and returns a null audit.\n\t\t\t// Refresh mirrors sign-in as closely as the claim surface allows: when the provider returned its\n\t\t\t// COMPLETE surface (`claimsComplete` — `method: \"refresh\"` rebuilding sign-in's id-token + userinfo\n\t\t\t// merge), `unmatched: \"remove\"` reconciliation runs here too. A partial surface (a userinfo-only\n\t\t\t// probe, or a refresh whose userinfo fetch failed) passes `allowRemoval: false`, so refresh stays\n\t\t\t// additive-only and a membership the IdP still asserts is never stripped off an incomplete surface.\n\t\t\tconst { audit, droppedUnsafeRules } = await dbContext.transaction(db =>\n\t\t\t\tthis.claimSyncService.sync(db, mapping, claims, { id: apiKeyRow.identity_id }, false, { allowRemoval: claimsComplete })\n\t\t\t)\n\t\t\tif (audit) {\n\t\t\t\tawait this.logRoleMapping(dbContext, apiKeyRow, row, 'idp_role_mapped', audit, requestInfo)\n\t\t\t}\n\t\t\t// The apply-time safety backstop dropped a configured rule — emit the fail-open marker so a broken\n\t\t\t// mapping is visible on the refresh path too, mirroring sign-in (the marker carries no claim values).\n\t\t\tif (droppedUnsafeRules) {\n\t\t\t\tawait this.logRoleMapping(dbContext, apiKeyRow, row, 'idp_role_mapping_failed', undefined, requestInfo)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tthis.logger.warn(e, { message: 'IdP session revalidation: claim mapping sync failed', idpSessionId: row.id })\n\t\t\t// Strictly fail-open: a malformed mapping or a transient apply error must never revoke or\n\t\t\t// fail an already-vouched-for session. The transaction rolls back any partial apply.\n\t\t\tawait this.logRoleMapping(dbContext, apiKeyRow, row, 'idp_role_mapping_failed', undefined, requestInfo)\n\t\t}\n\t}\n\n\tprivate async logRoleMapping(\n\t\tdbContext: DatabaseContext,\n\t\tapiKeyRow: ApiKeyRow,\n\t\trow: IdpSessionRow,\n\t\ttype: 'idp_role_mapped' | 'idp_role_mapping_failed',\n\t\teventData: JSONValue | undefined,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tawait dbContext.commandBus.execute(\n\t\t\t\tnew CreateAuthLogEntryCommand({\n\t\t\t\t\ttype,\n\t\t\t\t\tinvokedById: apiKeyRow.identity_id,\n\t\t\t\t\tpersonId: apiKeyRow.person_id ?? undefined,\n\t\t\t\t\t// The membership change affects this session's own person — record it as the target too,\n\t\t\t\t\t// so an admin querying membership changes by target_person_id sees IdP-driven grants/revokes\n\t\t\t\t\t// (consistent with the project_membership_* audit events).\n\t\t\t\t\ttargetPersonId: apiKeyRow.person_id ?? undefined,\n\t\t\t\t\tidentityProviderId: row.identityProviderId,\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\teventData,\n\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t}),\n\t\t\t)\n\t\t} catch (e) {\n\t\t\tthis.logger.error(e, { message: `IdP session revalidation: writing the ${type} audit entry failed`, idpSessionId: row.id })\n\t\t\t// best-effort audit — never fail the request because the audit write failed\n\t\t}\n\t}\n\n\tprivate async logRevalidated(dbContext: DatabaseContext, apiKeyRow: ApiKeyRow, row: IdpSessionRow, requestInfo?: ApiKeyRequestInfo): Promise<void> {\n\t\tawait dbContext.commandBus.execute(\n\t\t\tnew CreateAuthLogEntryCommand({\n\t\t\t\ttype: 'idp_session_revalidated',\n\t\t\t\tinvokedById: apiKeyRow.identity_id,\n\t\t\t\tpersonId: apiKeyRow.person_id ?? undefined,\n\t\t\t\tidentityProviderId: row.identityProviderId,\n\t\t\t\tsuccess: true,\n\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\teventData: { apiKeyId: apiKeyRow.id },\n\t\t\t}),\n\t\t)\n\t}\n\n\t/**\n\t * Audit a fail-open: the IdP couldn't be consulted (transient outage) or the stored config is\n\t * corrupt, so we kept the session rather than revoking it. Naturally throttled to one entry\n\t * per claim window (we only reach here after a successful claim, which bumps\n\t * `last_validated_at`). The write is best-effort and self-contained — a failure to audit must\n\t * never propagate and fail a blocking verify request (the whole point of failing open).\n\t */\n\tprivate async logRevalidationFailed(\n\t\tdbContext: DatabaseContext,\n\t\tapiKeyRow: ApiKeyRow,\n\t\trow: IdpSessionRow,\n\t\terrorCode: 'config_invalid' | 'revalidation_error',\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tawait dbContext.commandBus.execute(\n\t\t\t\tnew CreateAuthLogEntryCommand({\n\t\t\t\t\ttype: 'idp_session_revalidation_failed',\n\t\t\t\t\tinvokedById: apiKeyRow.identity_id,\n\t\t\t\t\tpersonId: apiKeyRow.person_id ?? undefined,\n\t\t\t\t\tidentityProviderId: row.identityProviderId,\n\t\t\t\t\t// not a security failure (the session is kept) — a fail-open marker the operator\n\t\t\t\t\t// can alert on. `success: true` keeps it out of the failed-login funnels.\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\terrorCode,\n\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\teventData: { apiKeyId: apiKeyRow.id },\n\t\t\t\t}),\n\t\t\t)\n\t\t} catch (e) {\n\t\t\tthis.logger.error(e, { message: 'IdP session revalidation: writing the idp_session_revalidation_failed audit entry failed', idpSessionId: row.id })\n\t\t\t// best-effort observability — never fail the request because the audit write failed\n\t\t}\n\t}\n\n\tprivate async revoke(\n\t\tdbContext: DatabaseContext,\n\t\tapiKeyRow: ApiKeyRow,\n\t\trow: IdpSessionRow,\n\t\treason: string,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t): Promise<void> {\n\t\tawait dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyRow.id))\n\t\ttry {\n\t\t\tawait dbContext.commandBus.execute(\n\t\t\t\tnew CreateAuthLogEntryCommand({\n\t\t\t\t\ttype: 'idp_session_revoked',\n\t\t\t\t\tinvokedById: apiKeyRow.identity_id,\n\t\t\t\t\tpersonId: apiKeyRow.person_id ?? undefined,\n\t\t\t\t\tidentityProviderId: row.identityProviderId,\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terrorCode: reason,\n\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\t// the action payload belongs in `event_data` (where every other audit event puts\n\t\t\t\t\t// it and where the admin UI / AuthLogQueryResolver reads it); `metadata` is for\n\t\t\t\t\t// transport context (forwarder IP/UA).\n\t\t\t\t\teventData: { reason, apiKeyId: apiKeyRow.id },\n\t\t\t\t}),\n\t\t\t)\n\t\t} catch (e) {\n\t\t\tthis.logger.error(e, { message: 'IdP session revalidation: writing the idp_session_revoked audit entry failed', idpSessionId: row.id })\n\t\t\t// best-effort audit: the key is already disabled, so the request must still be answered\n\t\t\t// as revoked rather than fail on the audit write\n\t\t}\n\t}\n\n\tprivate resolveConfig(configuration: Record<string, unknown>): ResolvedRevalidationConfig {\n\t\tconst raw = (configuration.revalidation ?? {}) as Record<string, unknown>\n\t\tconst threshold = typeof raw.softRefreshThreshold === 'number' && raw.softRefreshThreshold > 0 && raw.softRefreshThreshold <= 1\n\t\t\t? raw.softRefreshThreshold\n\t\t\t: REVALIDATION_DEFAULT_SOFT_THRESHOLD\n\t\treturn {\n\t\t\tenabled: raw.enabled === true,\n\t\t\tsoftThreshold: threshold,\n\t\t\tminInterval: typeof raw.minInterval === 'string' ? raw.minInterval : REVALIDATION_DEFAULT_MIN_INTERVAL,\n\t\t\tfallbackInterval: typeof raw.fallbackInterval === 'string' ? raw.fallbackInterval : REVALIDATION_DEFAULT_FALLBACK_INTERVAL,\n\t\t\tmode: raw.mode === 'blocking' ? 'blocking' : 'auto',\n\t\t}\n\t}\n}\n"],"names":["IdpSessionByApiKeyQuery","ClaimIdpRevalidationCommand","UpdateIdpSessionCommand","parseClaimMapping","CreateAuthLogEntryCommand","DisableApiKeyCommand","REVALIDATION_DEFAULT_SOFT_THRESHOLD","REVALIDATION_DEFAULT_MIN_INTERVAL","REVALIDATION_DEFAULT_FALLBACK_INTERVAL"],"mappings":";;;;;;;;;;;;AA6CO,MAAM,sBAAsB;AAAA,EAClC,YACkB,aACA,kBACA,QAChB;AAHgB,SAAA,cAAA;AACA,SAAA,mBAAA;AACA,SAAA,SAAA;AAAA,EAElB;AAAA,EAEA,MAAM,WACL,WACA,eACA,WACA,aAC+B;AAC/B,UAAM,MAAM,MAAM,cAAc,aAAa,MAAM,IAAIA,wBAAAA,wBAAwB,UAAU,IAAI,cAAc,SAAS,CAAC;AACrH,QAAI,CAAC,KAAK;AAET,aAAO;AAAA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