Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(core): add Sentinel guard #6374

Merged
merged 1 commit into from
Aug 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import {
SentinelActionResult,
SentinelActivityTargetType,
SentinelDecision,
type InteractionIdentifier,
type Sentinel,
type SentinelActivityAction,
} from '@logto/schemas';
import { sha256 } from 'hash-wasm';

import RequestError from '#src/errors/RequestError/index.js';
import { i18next } from '#src/utils/i18n.js';

/**
* Applies a sentinel guard to a verification promise.
*
* @remarks
* If the user is blocked, the verification will still be performed, but the promise will be
* rejected with a {@link RequestError} with the code `session.verification_blocked_too_many_attempts`.
*
* If the user is not blocked, but the verification throws, the promise will be rejected with
* the error thrown by the verification.
*
* @throws {RequestError} If the user is blocked.
* @throws original verification error if user is not blocked
*/
export async function withSentinel<T>(
{
sentinel,
action,
identifier,
payload,
}: {
sentinel: Sentinel;
action: SentinelActivityAction;
identifier: InteractionIdentifier;
payload: Record<string, unknown>;
},
verificationPromise: Promise<T>
): Promise<T> {
const [result, error] = await (async () => {
try {
return [await verificationPromise, undefined];
} catch (error) {
return [undefined, error instanceof Error ? error : new Error(String(error))];
}
})();

const actionResult = error ? SentinelActionResult.Failed : SentinelActionResult.Success;

const [decision, decisionExpiresAt] = await sentinel.reportActivity({
targetType: SentinelActivityTargetType.User,
targetHash: await sha256(identifier.value),
action,
actionResult,
payload,
});

if (decision === SentinelDecision.Blocked) {
const rtf = new Intl.RelativeTimeFormat([...i18next.languages]);
throw new RequestError({
code: 'session.verification_blocked_too_many_attempts',
relativeTime: rtf.format(Math.round((decisionExpiresAt - Date.now()) / 1000 / 60), 'minute'),
});
}

if (error) {
throw error;
}

return result;
}

Check warning on line 72 in packages/core/src/routes/experience/classes/libraries/sentinel-guard.ts

View check run for this annotation

Codecov / codecov/patch

packages/core/src/routes/experience/classes/libraries/sentinel-guard.ts#L28-L72

Added lines #L28 - L72 were not covered by tests
Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
import { passwordVerificationPayloadGuard, VerificationType } from '@logto/schemas';
import {
passwordVerificationPayloadGuard,
SentinelActivityAction,
VerificationType,
} from '@logto/schemas';
import { Action } from '@logto/schemas/lib/types/log/interaction.js';
import type Router from 'koa-router';
import { z } from 'zod';

import koaGuard from '#src/middleware/koa-guard.js';
import type TenantContext from '#src/tenants/TenantContext.js';

import { withSentinel } from '../classes/libraries/sentinel-guard.js';
import { PasswordVerification } from '../classes/verifications/password-verification.js';
import { experienceRoutes } from '../const.js';
import koaExperienceVerificationsAuditLog from '../middleware/koa-experience-verifications-audit-log.js';
import { type ExperienceInteractionRouterContext } from '../types.js';

export default function passwordVerificationRoutes<T extends ExperienceInteractionRouterContext>(
router: Router<unknown, T>,
{ libraries, queries }: TenantContext
{ libraries, queries, sentinel }: TenantContext
) {
router.post(
`${experienceRoutes.verification}/password`,
Expand All @@ -29,6 +34,7 @@
action: Action.Submit,
}),
async (ctx, next) => {
const { experienceInteraction } = ctx;

Check warning on line 37 in packages/core/src/routes/experience/verification-routes/password-verification.ts

View check run for this annotation

Codecov / codecov/patch

packages/core/src/routes/experience/verification-routes/password-verification.ts#L37

Added line #L37 was not covered by tests
const { identifier, password } = ctx.guard.body;

ctx.verificationAuditLog.append({
Expand All @@ -39,9 +45,22 @@
});

const passwordVerification = PasswordVerification.create(libraries, queries, identifier);
await passwordVerification.verify(password);
ctx.experienceInteraction.setVerificationRecord(passwordVerification);
await ctx.experienceInteraction.save();

await withSentinel(
{
sentinel,
action: SentinelActivityAction.Password,
identifier,
payload: {
event: experienceInteraction.interactionEvent,
verificationId: passwordVerification.id,
},
},
passwordVerification.verify(password)
);

experienceInteraction.setVerificationRecord(passwordVerification);
await experienceInteraction.save();

Check warning on line 63 in packages/core/src/routes/experience/verification-routes/password-verification.ts

View check run for this annotation

Codecov / codecov/patch

packages/core/src/routes/experience/verification-routes/password-verification.ts#L48-L63

Added lines #L48 - L63 were not covered by tests

ctx.body = { verificationId: passwordVerification.id };

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
InteractionEvent,
SentinelActivityAction,
type VerificationCodeIdentifier,
verificationCodeIdentifierGuard,
} from '@logto/schemas';
Expand All @@ -12,6 +13,7 @@
import type TenantContext from '#src/tenants/TenantContext.js';

import type ExperienceInteraction from '../classes/experience-interaction.js';
import { withSentinel } from '../classes/libraries/sentinel-guard.js';
import { codeVerificationIdentifierRecordTypeMap } from '../classes/utils.js';
import { createNewCodeVerificationRecord } from '../classes/verifications/code-verification.js';
import { experienceRoutes } from '../const.js';
Expand All @@ -30,7 +32,7 @@

export default function verificationCodeRoutes<T extends ExperienceInteractionRouterContext>(
router: Router<unknown, T>,
{ libraries, queries }: TenantContext
{ libraries, queries, sentinel }: TenantContext
) {
router.post(
`${experienceRoutes.verification}/verification-code`,
Expand Down Expand Up @@ -99,6 +101,7 @@
}),
async (ctx, next) => {
const { verificationId, code, identifier } = ctx.guard.body;
const { experienceInteraction } = ctx;

Check warning on line 104 in packages/core/src/routes/experience/verification-routes/verification-code.ts

View check run for this annotation

Codecov / codecov/patch

packages/core/src/routes/experience/verification-routes/verification-code.ts#L104

Added line #L104 was not covered by tests

const log = createVerificationCodeAuditLog(
ctx,
Expand All @@ -120,7 +123,18 @@
verificationId
);

await codeVerificationRecord.verify(identifier, code);
await withSentinel(
{
sentinel,
action: SentinelActivityAction.VerificationCode,
identifier,
payload: {
event: experienceInteraction.interactionEvent,
verificationId: codeVerificationRecord.id,
},
},
codeVerificationRecord.verify(identifier, code)
);

Check warning on line 137 in packages/core/src/routes/experience/verification-routes/verification-code.ts

View check run for this annotation

Codecov / codecov/patch

packages/core/src/routes/experience/verification-routes/verification-code.ts#L126-L137

Added lines #L126 - L137 were not covered by tests

await ctx.experienceInteraction.save();

Expand Down
Loading