From ff4baa24df6b21adeb64777797c95569d1588a61 Mon Sep 17 00:00:00 2001 From: SirLouen Date: Mon, 30 Nov 2026 18:18:33 +0100 Subject: [PATCH 1/9] feat(frontend): say when the invitation limit is reached --- frontend/src/auth/graphTransport.ts | 30 ++++++++++++------ frontend/src/i18n/errorTemplates.ts | 1 + frontend/src/test/invite-transport.test.ts | 21 +++++++++++++ frontend/src/test/users-invited.test.tsx | 30 ++++++++++++++++++ frontend/src/test/users-new.test.tsx | 36 ++++++++++++++++++++++ frontend/src/users/errorMessages.ts | 6 +++- 6 files changed, 113 insertions(+), 11 deletions(-) diff --git a/frontend/src/auth/graphTransport.ts b/frontend/src/auth/graphTransport.ts index acd88e4a..0f42cf7d 100644 --- a/frontend/src/auth/graphTransport.ts +++ b/frontend/src/auth/graphTransport.ts @@ -110,23 +110,33 @@ async function executeWrite( } /** - * Returns the plain error a refused account write fails with, carrying its reason as code. + * Returns the plain error a rejected account write fails with, carrying its reason as code. * @param reason - The stable reason the server named. * @returns The error. */ -function refusedWrite(reason: string): Error { +function writeErrorOf(reason: string): Error { return Object.assign(new Error('account write refused'), { code: reason }) } +/** + * Returns the error a rate limited account write fails with, carrying the reason as code when the server named one. + * @param reason - The stable reason the server named, if any. + * @returns The error. + */ +function rateLimitErrorOf(reason: string | undefined): RateLimitedError { + const error = new RateLimitedError('too many requests') + return reason === undefined ? error : Object.assign(error, { code: reason }) +} + /** * Returns the error an account write request turned down by the server fails with. * @param response - The answer whose status is not ok. * @returns A plain error carrying the reason the answer names, else one naming the status. */ async function refusedRequest(response: Response): Promise { - const answer = (await response.json().catch(() => undefined)) as GraphResult | null | undefined - const reason = answer?.errors?.[0]?.extensions?.reason - return reason ? refusedWrite(reason) : new Error(`graphql request failed with status ${response.status}`) + const body = (await response.json().catch(() => undefined)) as GraphResult | null | undefined + const reason = body?.errors?.[0]?.extensions?.reason + return reason ? writeErrorOf(reason) : new Error(`graphql request failed with status ${response.status}`) } /** @@ -294,12 +304,12 @@ function refuseAccountWrite(result: GraphResult): void { if (code === 'UNAUTHENTICATED') { throw new UnauthorizedError('session expired') } + const error = firstError(result) if (code === 'RATE_LIMITED') { - throw new RateLimitedError('too many requests') + throw rateLimitErrorOf(error?.extensions?.reason) } - const first = result.errors?.[0] - if (first) { - refuseAccountReason(first) + if (error) { + refuseAccountReason(error) } } @@ -325,7 +335,7 @@ function refuseUnmappedReason(error: GraphError): void { throw new ValidationError(error.message, { code: reason, meta }) } if (reason !== undefined) { - throw refusedWrite(reason) + throw writeErrorOf(reason) } } diff --git a/frontend/src/i18n/errorTemplates.ts b/frontend/src/i18n/errorTemplates.ts index 7e5780c1..b291b1ea 100644 --- a/frontend/src/i18n/errorTemplates.ts +++ b/frontend/src/i18n/errorTemplates.ts @@ -20,6 +20,7 @@ export function errorTemplates(): Record { DOMAIN, ), rate_limited: __('Too many attempts. Wait %(retryAfter)s seconds and try again.', DOMAIN), + invitation_limit_reached: __('The limit on invitations is reached for now. Try again later.', DOMAIN), scope_missing: __('This token does not reach %(scope)s.', DOMAIN), capability_missing: __('Your role does not allow %(capability)s.', DOMAIN), contact_name_required: __('A contact needs a name.', DOMAIN), diff --git a/frontend/src/test/invite-transport.test.ts b/frontend/src/test/invite-transport.test.ts index d3340818..2d1e5e1f 100644 --- a/frontend/src/test/invite-transport.test.ts +++ b/frontend/src/test/invite-transport.test.ts @@ -76,6 +76,27 @@ test('invite maps the failures it can meet', async () => { ).rejects.toBeInstanceOf(RateLimitedError) }) +test.each([ + { + operation: 'mutation Invite', + write: () => graphAuthTransport.invite({ email: 'maria@example.com', name: 'Maria Perez' }), + }, + { operation: 'mutation ResendInvite', write: () => graphAuthTransport.resendInvite('maria@example.com') }, +])('$operation past the invitation limit throws RateLimitedError carrying the reason as its code', async ({ + operation, + write, +}) => { + graphResponds( + operation, + graphError('RATE_LIMITED', 'invitation_limit_reached', 'the invitation limit is reached, try again later'), + ) + + const rejection = await write().then(() => undefined, (error: unknown) => error) + + expect(rejection).toBeInstanceOf(RateLimitedError) + expect(rejection).toHaveProperty('code', 'invitation_limit_reached') +}) + /** * Returns what an invitation throws once the graph refuses it with one error. */ diff --git a/frontend/src/test/users-invited.test.tsx b/frontend/src/test/users-invited.test.tsx index 5453e4ec..eba22687 100644 --- a/frontend/src/test/users-invited.test.tsx +++ b/frontend/src/test/users-invited.test.tsx @@ -335,6 +335,36 @@ test('says inside the resend why it failed in the words the reason names, the di expect(screen.queryByText(/no account holds/)).not.toBeInTheDocument() }) +test('says inside the resend that the invitation limit is reached, the dialog open and no toast', async () => { + server.use( + graphql.mutation('ResendInvite', () => + HttpResponse.json({ + data: null, + errors: [ + { + message: 'the invitation limit is reached, try again later', + extensions: { + code: 'RATE_LIMITED', + reason: 'invitation_limit_reached', + retryAfter: 172800, + meta: { retryAfter: 172800 }, + }, + }, + ], + }), + ), + ) + renderAt('/users') + const modal = await openResend() + + await userEvent.click(modal.getByRole('button', { name: 'Resend invitation' })) + + expect(await modal.findByText('The limit on invitations is reached for now. Try again later.')).toBeInTheDocument() + expect(screen.getByRole('dialog', { name: 'Resend invitation' })).toBeInTheDocument() + expect(document.querySelector('.godmin-toast')).toBeNull() + expect(screen.queryByText(/the invitation limit is reached/)).not.toBeInTheDocument() +}) + test('says plainly inside the resend that it failed when the server names no reason, the dialog open', async () => { server.use( graphql.mutation('ResendInvite', () => diff --git a/frontend/src/test/users-new.test.tsx b/frontend/src/test/users-new.test.tsx index 75ed0eee..12cab27a 100644 --- a/frontend/src/test/users-new.test.tsx +++ b/frontend/src/test/users-new.test.tsx @@ -22,6 +22,9 @@ const undeliveredToastAfterUnmount = /** AppRouter is the router the app renders under test. */ type AppRouter = ReturnType['router'] +/** serverInvitationLimitMessage is the server's own message for an invitation past the invitation limit. */ +const serverInvitationLimitMessage = 'the invitation limit is reached, try again later' + /** * Answers every invitation as delivered, recording each one sent. * @returns The invitations sent. @@ -251,6 +254,39 @@ test('puts the focus on the activation link once it replaces the form', async () await waitFor(() => expect(link).toHaveFocus()) }) +test('says in a toast that the invitation limit is reached, never in the server words', async () => { + server.use( + graphql.mutation('Invite', () => + HttpResponse.json({ + data: null, + errors: [ + { + message: serverInvitationLimitMessage, + extensions: { + code: 'RATE_LIMITED', + reason: 'invitation_limit_reached', + retryAfter: 172800, + meta: { retryAfter: 172800 }, + }, + }, + ], + }), + ), + ) + renderAt('/users/new') + await fillAccount() + + await userEvent.click(screen.getByRole('button', { name: 'Send invitation' })) + + expect( + await screen.findByText( + 'Could not send the invitation. The limit on invitations is reached for now. Try again later.', + { selector: '.godmin-toast' }, + ), + ).toBeInTheDocument() + expect(screen.queryByText(serverInvitationLimitMessage, { exact: false })).not.toBeInTheDocument() +}) + test('moves to the list first, then says in a toast that the invitation went out', async () => { deliveredInvites() renderAt('/users/new') diff --git a/frontend/src/users/errorMessages.ts b/frontend/src/users/errorMessages.ts index 1b4ec544..838667ff 100644 --- a/frontend/src/users/errorMessages.ts +++ b/frontend/src/users/errorMessages.ts @@ -10,5 +10,9 @@ import { appErrorTemplates } from '../i18n/errors' */ export function accountErrorMessages(): ErrorMessages { const templates = appErrorTemplates() - return { request_cross_origin: templates.request_cross_origin, tenant_deactivated: templates.tenant_deactivated } + return { + request_cross_origin: templates.request_cross_origin, + tenant_deactivated: templates.tenant_deactivated, + invitation_limit_reached: templates.invitation_limit_reached, + } } From 59d4ff957269e6ee2faaab6a29b92d8dd58c0df2 Mon Sep 17 00:00:00 2001 From: SirLouen Date: Mon, 30 Nov 2026 18:18:33 +0100 Subject: [PATCH 2/9] chore(i18n): carry the invitation limit words in the alphone catalogue --- frontend/src/languages/es-ES.json | 2 +- languages/alphone.pot | 3 +++ languages/es-ES.po | 4 ++++ 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/frontend/src/languages/es-ES.json b/frontend/src/languages/es-ES.json index 39a658c6..4a473c99 100644 --- a/frontend/src/languages/es-ES.json +++ b/frontend/src/languages/es-ES.json @@ -1 +1 @@ -{"":{"lang":"es","plural-forms":"nplurals=3; plural=((n == 1) ? 0 : ((n != 0 && n % 1000000 == 0) ? 1 : 2));"},"\"%(name)s\" revoked.":["«%(name)s» revocado."],"%s token could not be revoked.":["No se ha podido revocar %s token.","No se han podido revocar %s de tokens.","No se han podido revocar %s tokens."],"%s token revoked.":["%s token revocado.","%s de tokens revocados.","%s tokens revocados."],"30 days":["30 días"],"90 days":["90 días"],"A contact needs a name.":["Un contacto necesita un nombre."],"A lifetime is zero days or more.":["Una duración es de cero días o más."],"A lifetime runs to %(maxDays)s days at most.":["Una duración llega como mucho a %(maxDays)s días."],"A name runs to %(max)s characters at most.":["Un nombre tiene como mucho %(max)s caracteres."],"A password runs to %(max)s characters at most.":["Una contraseña tiene como mucho %(max)s caracteres."],"A password runs to %(min)s characters at least.":["Una contraseña tiene al menos %(min)s caracteres."],"A task needs a title.":["Una tarea necesita un título."],"A token needs a name.":["Un token necesita un nombre."],"A year":["Un año"],"API tokens":["Tokens de API"],"Activation link":["Enlace de activación"],"Add Contact":["Añadir contacto"],"Add Token":["Añadir token"],"Add User":["Añadir usuario"],"Add a task above, or open a contact and create one from their page.":["Añade una tarea arriba, o abre un contacto y crea una desde su página."],"Add identity":["Añadir identidad"],"Add task":["Añadir tarea"],"AlphOne cannot write to that channel.":["AlphOne no puede escribir en ese canal."],"AlphOne does not speak that language yet.":["AlphOne todavía no habla ese idioma."],"AlphOne sends no webhook to an internal address the operator has not allowed.":["AlphOne no envía webhooks a una dirección interna que el operador no haya permitido."],"Already on contact %(name)s.":["Ya está en el contacto %(name)s."],"An account needs a name.":["Una cuenta necesita un nombre."],"An event needs the source it came from.":["Un evento necesita la fuente de la que viene."],"Another account already holds that address.":["Ya hay otra cuenta que tiene esa dirección."],"Another contact already holds that address.":["Ya hay otro contacto que tiene esa dirección."],"Areas":["Áreas"],"Ask for between %(min)s and %(max)s at a time.":["Pide entre %(min)s y %(max)s a la vez."],"Ask for tasks by one filter at a time.":["Pide las tareas con un solo filtro a la vez."],"Avatar":["Avatar"],"Breadcrumbs":["Migas de pan"],"Cancel":["Cancelar"],"Channel":["Canal"],"Channels":["Canales"],"Choose at least one area the token reaches.":["Elige al menos un área a la que llegue el token."],"Choose at least one event to send.":["Elige al menos un evento que enviar."],"Choose the channel this address belongs to.":["Elige el canal al que pertenece esta dirección."],"Complete":["Completar"],"Contact":["Contacto"],"Contact added.":["Contacto añadido."],"Contact details":["Detalles del contacto"],"Contact tasks":["Tareas del contacto"],"Contacts":["Contactos"],"Contacts could not be loaded.":["No se han podido cargar los contactos."],"Copied.":["Copiado."],"Copy it by hand.":["Cópialo a mano."],"Copy secret":["Copiar el secreto"],"Copy the secret now, it is never shown again.":["Copia el secreto ahora, no se vuelve a mostrar nunca."],"Could not add the identity.":["No se ha podido añadir la identidad."],"Could not add the task.":["No se ha podido añadir la tarea."],"Could not create the contact.":["No se ha podido crear el contacto."],"Could not create the task.":["No se ha podido crear la tarea."],"Could not create the token.":["No se ha podido crear el token."],"Could not remove the identity.":["No se ha podido quitar la identidad."],"Could not save the contact.":["No se ha podido guardar el contacto."],"Could not save the language.":["No se ha podido guardar el idioma."],"Could not save the task.":["No se ha podido guardar la tarea."],"Could not send the invitation.":["No se ha podido enviar la invitación."],"Could not update the task.":["No se ha podido actualizar la tarea."],"Create a brand new user and add them to this workspace.":["Crea un nuevo usuario y añádelo a este espacio de trabajo."],"Create contact":["Crear contacto"],"Create task":["Crear tarea"],"Create token":["Crear token"],"Created":["Creado"],"Created %(date)s":["Creado el %(date)s"],"Discard":["Descartar"],"Discard changes?":["¿Descartar los cambios?"],"Dismiss this notice":["Descartar este aviso"],"Done":["Hecho"],"Done (%(count)s)":["Hechas (%(count)s)"],"Done tasks":["Tareas hechas"],"Due %(date)s":["Vence el %(date)s"],"Due date":["Fecha de vencimiento"],"Email":["Correo electrónico"],"Expires":["Caduca"],"Identities":["Identidades"],"Identity":["Identidad"],"Identity added.":["Identidad añadida."],"Identity removed.":["Identidad quitada."],"Invitation sent.":["Invitación enviada."],"Keep editing":["Seguir editando"],"Label":["Etiqueta"],"Language":["Idioma"],"Last used":["Último uso"],"Link a contact":["Vincular un contacto"],"Load more":["Cargar más"],"Load more done":["Cargar más hechas"],"Load more overdue":["Cargar más vencidas"],"Load more tasks":["Cargar más tareas"],"Loading contact…":["Cargando el contacto…"],"Loading tasks…":["Cargando las tareas…"],"Loading task…":["Cargando la tarea…"],"Loading…":["Cargando…"],"Manage the people you work with and how to reach them.":["Gestiona las personas con las que trabajas y cómo contactar con ellas."],"Manage the tokens your programs sign in with.":["Gestiona los tokens con los que entran tus programas."],"Name":["Nombre"],"Name updated.":["Nombre actualizado."],"Never expires":["No caduca nunca"],"Never used":["Sin usar"],"New contact":["Contacto nuevo"],"New task":["Tarea nueva"],"New token":["Token nuevo"],"Next day":["Día siguiente"],"No API tokens yet":["Todavía no hay tokens de API"],"No contacts found.":["No se ha encontrado ningún contacto."],"No contacts yet":["Todavía no hay contactos"],"No identities yet.":["Todavía no hay identidades."],"No mail server is configured. Deliver the activation link by hand.":["No hay servidor de correo configurado. Entrega el enlace de activación a mano."],"No mail server is configured. Use Resend invitation in Users to get an activation link.":["No hay servidor de correo configurado. Usa Reenviar invitación en Usuarios para obtener un enlace de activación."],"No open tasks.":["No hay tareas abiertas."],"Nothing declares that role.":["Nada declara ese rol."],"Nothing due today":["No hay nada que venza hoy"],"Open tasks":["Tareas abiertas"],"Overdue":["Vencidas"],"Overdue tasks":["Tareas vencidas"],"Overdue tasks could not be loaded.":["No se han podido cargar las tareas vencidas."],"Please enter an email address.":["Por favor, introduce una dirección de correo electrónico."],"Please provide a name.":["Por favor, facilita un nombre."],"Postpone":["Posponer"],"Previous day":["Día anterior"],"Priority":["Prioridad"],"Privacy policy":["Política de privacidad"],"Read %(area)s":["Leer %(area)s"],"Reading the languages":["Leyendo los idiomas"],"Remove":["Quitar"],"Remove %(identifier)s":["Quitar %(identifier)s"],"Remove %(identifier)s?":["¿Quitar %(identifier)s?"],"Remove %(name)s":["Quitar a %(name)s"],"Rename":["Renombrar"],"Reopen":["Reabrir"],"Revoke":["Revocar"],"Revoke \"%(name)s\"?":["¿Revocar «%(name)s»?"],"Revoke %s token?":["¿Revocar %s token?","¿Revocar %s de tokens?","¿Revocar %s tokens?"],"Save":["Guardar"],"Scopes":["Ámbitos"],"Search contacts…":["Buscar contactos…"],"Search tokens…":["Buscar tokens…"],"Send invitation":["Enviar invitación"],"Sign in to go on.":["Inicia sesión para continuar."],"Somebody must be able to manage users.":["Alguien tiene que poder gestionar los usuarios."],"Something went wrong.":["Algo ha ido mal."],"Something went wrong. Try again.":["Algo ha ido mal. Inténtalo de nuevo."],"Sorry, you are not allowed to edit this user.":["Lo siento, no tienes permisos para modificar este usuario."],"Sorry, you are not allowed to give users that role.":["Lo siento, no tienes permisos para dar ese rol a los usuarios."],"Task":["Tarea"],"Task added for %(date)s.":["Tarea añadida para el %(date)s."],"Task added.":["Tarea añadida."],"Task completed.":["Tarea completada."],"Task moved to %(date)s.":["Tarea movida al %(date)s."],"Task reopened.":["Tarea reabierta."],"Task saved.":["Tarea guardada."],"Task title":["Título de la tarea"],"Tasks":["Tareas"],"Tasks could not be loaded.":["No se han podido cargar las tareas."],"Terms of service":["Condiciones del servicio"],"That account no longer exists.":["Esa cuenta ya no existe."],"That address is no longer on this contact.":["Esa dirección ya no está en este contacto."],"That area is not one AlphOne offers.":["Esa área no es una de las que AlphOne ofrece."],"That contact no longer exists.":["Ese contacto ya no existe."],"That email and password do not match an account.":["Ese correo y esa contraseña no coinciden con ninguna cuenta."],"That event name is not one AlphOne knows.":["Ese nombre de evento no es uno de los que AlphOne conoce."],"That page marker is not one AlphOne issued.":["Ese marcador de página no es uno de los que AlphOne ha emitido."],"That priority is not one AlphOne offers.":["Esa prioridad no es una de las que AlphOne ofrece."],"That status is not one AlphOne offers.":["Ese estado no es uno de los que AlphOne ofrece."],"That task no longer exists.":["Esa tarea ya no existe."],"That token no longer exists.":["Ese token ya no existe."],"That value is not in the form AlphOne expects.":["Ese valor no tiene la forma que AlphOne espera."],"That webhook no longer exists.":["Ese webhook ya no existe."],"The contact could not be loaded.":["No se ha podido cargar el contacto."],"The language changes when the page next loads.":["El idioma cambia la próxima vez que se cargue la página."],"The languages could not be read.":["No se han podido leer los idiomas."],"The name could not be updated.":["No se ha podido actualizar el nombre."],"The name is not saved.":["El nombre no se ha guardado."],"The role of that account just changed. Reload the page and try again.":["El rol de esa cuenta acaba de cambiar. Recarga la página e inténtalo de nuevo."],"The task could not be loaded.":["No se ha podido cargar la tarea."],"The token could not be revoked.":["No se ha podido revocar el token."],"This action cannot be undone.":["Esta acción no se puede deshacer."],"This link is no longer valid. Ask for a new one.":["Este enlace ya no es válido. Pide uno nuevo."],"This request came from a page on another site, so it was refused. Open the admin on this site and try again.":["Esta petición vino de una página de otro sitio, así que se rechazó. Abre la administración en este sitio e inténtalo de nuevo."],"This token does not reach %(scope)s.":["Este token no alcanza %(scope)s."],"This workspace has been deactivated. Contact your operator.":["Este espacio de trabajo ha sido desactivado. Contacta con tu operador."],"Time":["Hora"],"Title":["Título"],"Today":["Hoy"],"Tokens could not be loaded.":["No se han podido cargar los tokens."],"Too many attempts. Wait %(retryAfter)s seconds and try again.":["Demasiados intentos. Espera %(retryAfter)s segundos e inténtalo de nuevo."],"Undo":["Deshacer"],"User sections":["Secciones de usuarios"],"Users":["Usuarios"],"Value":["Valor"],"Write %(area)s":["Escribir %(area)s"],"Write a scope as an area, a colon, then read or write.":["Escribe un ámbito como un área, dos puntos y luego read o write."],"Write the address as a full URL.":["Escribe la dirección como una URL completa."],"Write the address as a full email address.":["Escribe la dirección como una dirección de correo electrónico completa."],"Write the address itself.":["Escribe la dirección."],"You cannot change your own role.":["No puedes cambiar tu propio rol."],"You cannot disable your own account.":["No puedes desactivar tu propia cuenta."],"Your role does not allow %(capability)s.":["Tu rol no permite %(capability)s."],"admin section\u0004API tokens":["Tokens de API"],"admin section\u0004Contacts":["Contactos"],"admin section\u0004Language":["Idioma"],"admin section\u0004Tasks":["Tareas"],"contact channel\u0004Email":["Correo electrónico"],"contact channel\u0004Phone":["Teléfono"],"day heading\u0004%(weekday)s, %(date)s":["%(weekday)s, %(date)s"],"role\u0004Administrator":["Administrador"],"role\u0004Member":["Miembro"],"task priority\u0004High":["Alta"],"task priority\u0004Normal":["Normal"],"toast action\u0004View":["Ver"],"token area\u0004contacts":["contactos"],"token area\u0004events":["eventos"],"token area\u0004meta":["metadatos"],"token area\u0004tasks":["tareas"],"token area\u0004users":["usuarios"],"token area\u0004webhooks":["webhooks"],"token expiry\u0004Expired":["Caducado"],"token lifetime\u0004Never":["Nunca"],"v%(version)s":["v%(version)s"]} +{"":{"lang":"es","plural-forms":"nplurals=3; plural=((n == 1) ? 0 : ((n != 0 && n % 1000000 == 0) ? 1 : 2));"},"\"%(name)s\" revoked.":["«%(name)s» revocado."],"%s token could not be revoked.":["No se ha podido revocar %s token.","No se han podido revocar %s de tokens.","No se han podido revocar %s tokens."],"%s token revoked.":["%s token revocado.","%s de tokens revocados.","%s tokens revocados."],"30 days":["30 días"],"90 days":["90 días"],"A contact needs a name.":["Un contacto necesita un nombre."],"A lifetime is zero days or more.":["Una duración es de cero días o más."],"A lifetime runs to %(maxDays)s days at most.":["Una duración llega como mucho a %(maxDays)s días."],"A name runs to %(max)s characters at most.":["Un nombre tiene como mucho %(max)s caracteres."],"A password runs to %(max)s characters at most.":["Una contraseña tiene como mucho %(max)s caracteres."],"A password runs to %(min)s characters at least.":["Una contraseña tiene al menos %(min)s caracteres."],"A task needs a title.":["Una tarea necesita un título."],"A token needs a name.":["Un token necesita un nombre."],"A year":["Un año"],"API tokens":["Tokens de API"],"Activation link":["Enlace de activación"],"Add Contact":["Añadir contacto"],"Add Token":["Añadir token"],"Add User":["Añadir usuario"],"Add a task above, or open a contact and create one from their page.":["Añade una tarea arriba, o abre un contacto y crea una desde su página."],"Add identity":["Añadir identidad"],"Add task":["Añadir tarea"],"AlphOne cannot write to that channel.":["AlphOne no puede escribir en ese canal."],"AlphOne does not speak that language yet.":["AlphOne todavía no habla ese idioma."],"AlphOne sends no webhook to an internal address the operator has not allowed.":["AlphOne no envía webhooks a una dirección interna que el operador no haya permitido."],"Already on contact %(name)s.":["Ya está en el contacto %(name)s."],"An account needs a name.":["Una cuenta necesita un nombre."],"An event needs the source it came from.":["Un evento necesita la fuente de la que viene."],"Another account already holds that address.":["Ya hay otra cuenta que tiene esa dirección."],"Another contact already holds that address.":["Ya hay otro contacto que tiene esa dirección."],"Areas":["Áreas"],"Ask for between %(min)s and %(max)s at a time.":["Pide entre %(min)s y %(max)s a la vez."],"Ask for tasks by one filter at a time.":["Pide las tareas con un solo filtro a la vez."],"Avatar":["Avatar"],"Breadcrumbs":["Migas de pan"],"Cancel":["Cancelar"],"Channel":["Canal"],"Channels":["Canales"],"Choose at least one area the token reaches.":["Elige al menos un área a la que llegue el token."],"Choose at least one event to send.":["Elige al menos un evento que enviar."],"Choose the channel this address belongs to.":["Elige el canal al que pertenece esta dirección."],"Complete":["Completar"],"Contact":["Contacto"],"Contact added.":["Contacto añadido."],"Contact details":["Detalles del contacto"],"Contact tasks":["Tareas del contacto"],"Contacts":["Contactos"],"Contacts could not be loaded.":["No se han podido cargar los contactos."],"Copied.":["Copiado."],"Copy it by hand.":["Cópialo a mano."],"Copy secret":["Copiar el secreto"],"Copy the secret now, it is never shown again.":["Copia el secreto ahora, no se vuelve a mostrar nunca."],"Could not add the identity.":["No se ha podido añadir la identidad."],"Could not add the task.":["No se ha podido añadir la tarea."],"Could not create the contact.":["No se ha podido crear el contacto."],"Could not create the task.":["No se ha podido crear la tarea."],"Could not create the token.":["No se ha podido crear el token."],"Could not remove the identity.":["No se ha podido quitar la identidad."],"Could not save the contact.":["No se ha podido guardar el contacto."],"Could not save the language.":["No se ha podido guardar el idioma."],"Could not save the task.":["No se ha podido guardar la tarea."],"Could not send the invitation.":["No se ha podido enviar la invitación."],"Could not update the task.":["No se ha podido actualizar la tarea."],"Create a brand new user and add them to this workspace.":["Crea un nuevo usuario y añádelo a este espacio de trabajo."],"Create contact":["Crear contacto"],"Create task":["Crear tarea"],"Create token":["Crear token"],"Created":["Creado"],"Created %(date)s":["Creado el %(date)s"],"Discard":["Descartar"],"Discard changes?":["¿Descartar los cambios?"],"Dismiss this notice":["Descartar este aviso"],"Done":["Hecho"],"Done (%(count)s)":["Hechas (%(count)s)"],"Done tasks":["Tareas hechas"],"Due %(date)s":["Vence el %(date)s"],"Due date":["Fecha de vencimiento"],"Email":["Correo electrónico"],"Expires":["Caduca"],"Identities":["Identidades"],"Identity":["Identidad"],"Identity added.":["Identidad añadida."],"Identity removed.":["Identidad quitada."],"Invitation sent.":["Invitación enviada."],"Keep editing":["Seguir editando"],"Label":["Etiqueta"],"Language":["Idioma"],"Last used":["Último uso"],"Link a contact":["Vincular un contacto"],"Load more":["Cargar más"],"Load more done":["Cargar más hechas"],"Load more overdue":["Cargar más vencidas"],"Load more tasks":["Cargar más tareas"],"Loading contact…":["Cargando el contacto…"],"Loading tasks…":["Cargando las tareas…"],"Loading task…":["Cargando la tarea…"],"Loading…":["Cargando…"],"Manage the people you work with and how to reach them.":["Gestiona las personas con las que trabajas y cómo contactar con ellas."],"Manage the tokens your programs sign in with.":["Gestiona los tokens con los que entran tus programas."],"Name":["Nombre"],"Name updated.":["Nombre actualizado."],"Never expires":["No caduca nunca"],"Never used":["Sin usar"],"New contact":["Contacto nuevo"],"New task":["Tarea nueva"],"New token":["Token nuevo"],"Next day":["Día siguiente"],"No API tokens yet":["Todavía no hay tokens de API"],"No contacts found.":["No se ha encontrado ningún contacto."],"No contacts yet":["Todavía no hay contactos"],"No identities yet.":["Todavía no hay identidades."],"No mail server is configured. Deliver the activation link by hand.":["No hay servidor de correo configurado. Entrega el enlace de activación a mano."],"No mail server is configured. Use Resend invitation in Users to get an activation link.":["No hay servidor de correo configurado. Usa Reenviar invitación en Usuarios para obtener un enlace de activación."],"No open tasks.":["No hay tareas abiertas."],"Nothing declares that role.":["Nada declara ese rol."],"Nothing due today":["No hay nada que venza hoy"],"Open tasks":["Tareas abiertas"],"Overdue":["Vencidas"],"Overdue tasks":["Tareas vencidas"],"Overdue tasks could not be loaded.":["No se han podido cargar las tareas vencidas."],"Please enter an email address.":["Por favor, introduce una dirección de correo electrónico."],"Please provide a name.":["Por favor, facilita un nombre."],"Postpone":["Posponer"],"Previous day":["Día anterior"],"Priority":["Prioridad"],"Privacy policy":["Política de privacidad"],"Read %(area)s":["Leer %(area)s"],"Reading the languages":["Leyendo los idiomas"],"Remove":["Quitar"],"Remove %(identifier)s":["Quitar %(identifier)s"],"Remove %(identifier)s?":["¿Quitar %(identifier)s?"],"Remove %(name)s":["Quitar a %(name)s"],"Rename":["Renombrar"],"Reopen":["Reabrir"],"Revoke":["Revocar"],"Revoke \"%(name)s\"?":["¿Revocar «%(name)s»?"],"Revoke %s token?":["¿Revocar %s token?","¿Revocar %s de tokens?","¿Revocar %s tokens?"],"Save":["Guardar"],"Scopes":["Ámbitos"],"Search contacts…":["Buscar contactos…"],"Search tokens…":["Buscar tokens…"],"Send invitation":["Enviar invitación"],"Sign in to go on.":["Inicia sesión para continuar."],"Somebody must be able to manage users.":["Alguien tiene que poder gestionar los usuarios."],"Something went wrong.":["Algo ha ido mal."],"Something went wrong. Try again.":["Algo ha ido mal. Inténtalo de nuevo."],"Sorry, you are not allowed to edit this user.":["Lo siento, no tienes permisos para modificar este usuario."],"Sorry, you are not allowed to give users that role.":["Lo siento, no tienes permisos para dar ese rol a los usuarios."],"Task":["Tarea"],"Task added for %(date)s.":["Tarea añadida para el %(date)s."],"Task added.":["Tarea añadida."],"Task completed.":["Tarea completada."],"Task moved to %(date)s.":["Tarea movida al %(date)s."],"Task reopened.":["Tarea reabierta."],"Task saved.":["Tarea guardada."],"Task title":["Título de la tarea"],"Tasks":["Tareas"],"Tasks could not be loaded.":["No se han podido cargar las tareas."],"Terms of service":["Condiciones del servicio"],"That account no longer exists.":["Esa cuenta ya no existe."],"That address is no longer on this contact.":["Esa dirección ya no está en este contacto."],"That area is not one AlphOne offers.":["Esa área no es una de las que AlphOne ofrece."],"That contact no longer exists.":["Ese contacto ya no existe."],"That email and password do not match an account.":["Ese correo y esa contraseña no coinciden con ninguna cuenta."],"That event name is not one AlphOne knows.":["Ese nombre de evento no es uno de los que AlphOne conoce."],"That page marker is not one AlphOne issued.":["Ese marcador de página no es uno de los que AlphOne ha emitido."],"That priority is not one AlphOne offers.":["Esa prioridad no es una de las que AlphOne ofrece."],"That status is not one AlphOne offers.":["Ese estado no es uno de los que AlphOne ofrece."],"That task no longer exists.":["Esa tarea ya no existe."],"That token no longer exists.":["Ese token ya no existe."],"That value is not in the form AlphOne expects.":["Ese valor no tiene la forma que AlphOne espera."],"That webhook no longer exists.":["Ese webhook ya no existe."],"The contact could not be loaded.":["No se ha podido cargar el contacto."],"The language changes when the page next loads.":["El idioma cambia la próxima vez que se cargue la página."],"The languages could not be read.":["No se han podido leer los idiomas."],"The limit on invitations is reached for now. Try again later.":["Se ha alcanzado el límite de invitaciones por ahora. Inténtalo más tarde."],"The name could not be updated.":["No se ha podido actualizar el nombre."],"The name is not saved.":["El nombre no se ha guardado."],"The role of that account just changed. Reload the page and try again.":["El rol de esa cuenta acaba de cambiar. Recarga la página e inténtalo de nuevo."],"The task could not be loaded.":["No se ha podido cargar la tarea."],"The token could not be revoked.":["No se ha podido revocar el token."],"This action cannot be undone.":["Esta acción no se puede deshacer."],"This link is no longer valid. Ask for a new one.":["Este enlace ya no es válido. Pide uno nuevo."],"This request came from a page on another site, so it was refused. Open the admin on this site and try again.":["Esta petición vino de una página de otro sitio, así que se rechazó. Abre la administración en este sitio e inténtalo de nuevo."],"This token does not reach %(scope)s.":["Este token no alcanza %(scope)s."],"This workspace has been deactivated. Contact your operator.":["Este espacio de trabajo ha sido desactivado. Contacta con tu operador."],"Time":["Hora"],"Title":["Título"],"Today":["Hoy"],"Tokens could not be loaded.":["No se han podido cargar los tokens."],"Too many attempts. Wait %(retryAfter)s seconds and try again.":["Demasiados intentos. Espera %(retryAfter)s segundos e inténtalo de nuevo."],"Undo":["Deshacer"],"User sections":["Secciones de usuarios"],"Users":["Usuarios"],"Value":["Valor"],"Write %(area)s":["Escribir %(area)s"],"Write a scope as an area, a colon, then read or write.":["Escribe un ámbito como un área, dos puntos y luego read o write."],"Write the address as a full URL.":["Escribe la dirección como una URL completa."],"Write the address as a full email address.":["Escribe la dirección como una dirección de correo electrónico completa."],"Write the address itself.":["Escribe la dirección."],"You cannot change your own role.":["No puedes cambiar tu propio rol."],"You cannot disable your own account.":["No puedes desactivar tu propia cuenta."],"Your role does not allow %(capability)s.":["Tu rol no permite %(capability)s."],"admin section\u0004API tokens":["Tokens de API"],"admin section\u0004Contacts":["Contactos"],"admin section\u0004Language":["Idioma"],"admin section\u0004Tasks":["Tareas"],"contact channel\u0004Email":["Correo electrónico"],"contact channel\u0004Phone":["Teléfono"],"day heading\u0004%(weekday)s, %(date)s":["%(weekday)s, %(date)s"],"role\u0004Administrator":["Administrador"],"role\u0004Member":["Miembro"],"task priority\u0004High":["Alta"],"task priority\u0004Normal":["Normal"],"toast action\u0004View":["Ver"],"token area\u0004contacts":["contactos"],"token area\u0004events":["eventos"],"token area\u0004meta":["metadatos"],"token area\u0004tasks":["tareas"],"token area\u0004users":["usuarios"],"token area\u0004webhooks":["webhooks"],"token expiry\u0004Expired":["Caducado"],"token lifetime\u0004Never":["Nunca"],"v%(version)s":["v%(version)s"]} diff --git a/languages/alphone.pot b/languages/alphone.pot index 7ce12a0b..139b247e 100644 --- a/languages/alphone.pot +++ b/languages/alphone.pot @@ -538,6 +538,9 @@ msgstr "" msgid "The languages could not be read." msgstr "" +msgid "The limit on invitations is reached for now. Try again later." +msgstr "" + msgid "The name could not be updated." msgstr "" diff --git a/languages/es-ES.po b/languages/es-ES.po index e83de28c..0e689f9e 100644 --- a/languages/es-ES.po +++ b/languages/es-ES.po @@ -728,6 +728,10 @@ msgstr "Tarea guardada." msgid "Task title" msgstr "Título de la tarea" +#, fuzzy +msgid "The limit on invitations is reached for now. Try again later." +msgstr "Se ha alcanzado el límite de invitaciones por ahora. Inténtalo más tarde." + #, fuzzy msgid "The name could not be updated." msgstr "No se ha podido actualizar el nombre." From e95d72227c8f5aebd448b049af92f763dd6910e1 Mon Sep 17 00:00:00 2001 From: SirLouen Date: Mon, 30 Nov 2026 18:18:34 +0100 Subject: [PATCH 3/9] test(e2e): raise the invitation and resend limits for the end to end run --- Makefile | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Makefile b/Makefile index fc044a1c..777e83a0 100644 --- a/Makefile +++ b/Makefile @@ -165,6 +165,10 @@ E2E_WEBHOOK_ALLOWED_HOSTS ?= 127.0.0.1/32 E2E_ENCRYPTION_KEY ?= e2e0e2e0e2e0e2e0e2e0e2e0e2e0e2e0e2e0e2e0e2e0e2e0e2e0e2e0e2e0e2e0 E2E_PRIVACY_URL ?= https://example.com/privacy E2E_TERMS_URL ?= https://example.com/terms +E2E_INVITES_PER_INVITER ?= 1000 +E2E_INVITE_RESENDS_PER_INVITER ?= 1000 +E2E_INVITES_PER_TENANT ?= 100000 +E2E_INVITE_RESENDS_PER_TENANT ?= 100000 e2e-build: pnpm --filter @alphone/frontend build @@ -186,6 +190,10 @@ e2e-serve: db-up e2e-build ALPHONE_ENCRYPTION_KEY="$(E2E_ENCRYPTION_KEY)" \ ALPHONE_PRIVACY_URL="$(E2E_PRIVACY_URL)" \ ALPHONE_TERMS_URL="$(E2E_TERMS_URL)" \ + ALPHONE_INVITES_PER_INVITER="$(E2E_INVITES_PER_INVITER)" \ + ALPHONE_INVITE_RESENDS_PER_INVITER="$(E2E_INVITE_RESENDS_PER_INVITER)" \ + ALPHONE_INVITES_PER_TENANT="$(E2E_INVITES_PER_TENANT)" \ + ALPHONE_INVITE_RESENDS_PER_TENANT="$(E2E_INVITE_RESENDS_PER_TENANT)" \ ./alphone serve e2e-db-reset: db-up From 5e42a7ddde05afa6aee7f82ea25c1d8f3b4f1436 Mon Sep 17 00:00:00 2001 From: SirLouen Date: Mon, 30 Nov 2026 18:18:34 +0100 Subject: [PATCH 4/9] feat(graphres): reject invitations and resends past their limits --- internal/graphres/errors_internal_test.go | 33 ++ internal/graphres/graphres.go | 19 +- internal/graphres/invitationlimits_test.go | 414 +++++++++++++++++++++ internal/graphres/invite.go | 126 ++++++- internal/graphres/invite_test.go | 6 +- internal/graphres/invitetenancy_test.go | 123 ++++++ 6 files changed, 710 insertions(+), 11 deletions(-) create mode 100644 internal/graphres/invitationlimits_test.go diff --git a/internal/graphres/errors_internal_test.go b/internal/graphres/errors_internal_test.go index 7c995250..cfc07e52 100644 --- a/internal/graphres/errors_internal_test.go +++ b/internal/graphres/errors_internal_test.go @@ -4,6 +4,7 @@ package graphres import ( "context" + "errors" "fmt" "os" "path/filepath" @@ -87,6 +88,7 @@ func TestEverySpecialPathNamesItsReason(t *testing.T) { }{ {"identity taken", contact.IdentityExistsError{OwnerID: uuid.Nil}, "identity_taken"}, {"rate limited", rateLimitedError{retryAfter: 30 * time.Second}, "rate_limited"}, + {"invitation limit reached", invitationLimitError(30 * time.Second), "invitation_limit_reached"}, {"bad credentials", authkit.ErrInvalidCredentials, "credentials_invalid"}, } for _, tc := range cases { @@ -97,6 +99,37 @@ func TestEverySpecialPathNamesItsReason(t *testing.T) { } } +func TestTheInvitationLimitReasonHasAFrontendMessage(t *testing.T) { + t.Parallel() + + presented := PresentError(context.Background(), invitationLimitError(time.Minute)) + reason, _ := presented.Extensions["reason"].(string) + + if !strings.Contains(frontendTemplates(t), "\t"+reason+": __(") { + t.Errorf("reason %q has no frontend message, want the screens to speak it", reason) + } +} + +func TestTheInvitationLimitAnswersItsWaitInWholeSeconds(t *testing.T) { + t.Parallel() + + presented := PresentError(context.Background(), invitationLimitError(90*time.Second)) + + if got := presented.Extensions["retryAfter"]; got != 90 { + t.Errorf("retryAfter = %v, want 90 seconds", got) + } + meta, _ := presented.Extensions["meta"].(map[string]any) + if got := meta["retryAfter"]; got != 90 { + t.Errorf("meta retryAfter = %v, want 90 seconds", got) + } + if got := presented.Message; got != "the invitation limit is reached, try again later" { + t.Errorf("message = %q, want the invitation limit named", got) + } + if !errors.Is(presented, errInvitationLimitReached) { + t.Error("the presented error does not wrap errInvitationLimitReached, want the sentinel kept") + } +} + func TestAPluginErrorCarriesItsOwnReason(t *testing.T) { t.Parallel() diff --git a/internal/graphres/graphres.go b/internal/graphres/graphres.go index 14695eda..6ba87d18 100644 --- a/internal/graphres/graphres.go +++ b/internal/graphres/graphres.go @@ -173,7 +173,7 @@ type Broadcaster interface { Unsubscribe(names chan event.Name) } -// AttemptLimiter budgets failed logins per client key. +// AttemptLimiter budgets attempts per key. type AttemptLimiter interface { Check(key string) (bool, time.Duration, error) RecordFailure(key string) error @@ -247,7 +247,22 @@ type Resolver struct { // resetCooldownMu serializes the reset cooldown spend. resetCooldownMu sync.Mutex - // Logger records what a neutral reset answer hides and every invitation mail not delivered. Nil discards it. + // InvitationLimiterPerInviter budgets the invitations of one inviting account. Nil sets no limit. + InvitationLimiterPerInviter AttemptLimiter + + // InvitationLimiterPerTenant budgets the invitations of one tenant. Nil sets no limit. + InvitationLimiterPerTenant AttemptLimiter + + // ResendLimiterPerInviter budgets the invitation resends of one inviting account. Nil sets no limit. + ResendLimiterPerInviter AttemptLimiter + + // ResendLimiterPerTenant budgets the invitation resends of one tenant. Nil sets no limit. + ResendLimiterPerTenant AttemptLimiter + + // invitationLimitsMu serializes the check and the count of the invitation and resend limits. + invitationLimitsMu sync.Mutex + + // Logger records what a neutral reset answer hides, undelivered invitation mail and limit rejections. Nil discards it. Logger *slog.Logger // BatchWait bounds the loader batching window. Zero means one millisecond. BatchWait time.Duration diff --git a/internal/graphres/invitationlimits_test.go b/internal/graphres/invitationlimits_test.go new file mode 100644 index 00000000..ded7a308 --- /dev/null +++ b/internal/graphres/invitationlimits_test.go @@ -0,0 +1,414 @@ +// SPDX-License-Identifier: Elastic-2.0 + +package graphres_test + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + gqlclient "github.com/99designs/gqlgen/client" + "github.com/google/uuid" + + "github.com/gopherium/gouncer" + "github.com/gopherium/gouncer/authkit" + "github.com/gopherium/gouncer/authkit/ratelimit" + "github.com/gopherium/gouncer/authkit/testkit" + + "github.com/gopherium/alphone/internal/graphres" + "github.com/gopherium/alphone/internal/role" + "github.com/gopherium/alphone/internal/tenant" +) + +// invitationLimitWindow is the window every limiter of these tests counts over. +const invitationLimitWindow = time.Hour + +// hourlyLimiter returns a limiter allowing limit calls per key in one hour. +func hourlyLimiter(limit int) *ratelimit.Limiter { + return ratelimit.NewLimiter(ratelimit.Config{Limit: limit, Window: invitationLimitWindow}) +} + +// inviteMutationFor returns the invite mutation for one address, asking for the answer and the link. +func inviteMutationFor(address string) string { + return fmt.Sprintf(`mutation { invite(email: %q, name: "Maria Perez") { delivered activationLink } }`, address) +} + +// resendMutationFor returns the resend mutation for one address, asking for the answer and the link. +func resendMutationFor(address string) string { + return fmt.Sprintf(`mutation { resendInvite(email: %q) { delivered activationLink } }`, address) +} + +// errorsOf posts one operation through the client and returns the errors it answers, empty when it answers none. +func errorsOf(t *testing.T, client *gqlclient.Client, query string) json.RawMessage { + t.Helper() + response, err := client.RawPost(query) + if err != nil { + t.Fatalf("RawPost() error = %v, want nil", err) + } + return response.Errors +} + +// wantNoErrors fails the test when one operation answers any error. +func wantNoErrors(t *testing.T, client *gqlclient.Client, query string) { + t.Helper() + if answerErrors := errorsOf(t, client, query); len(answerErrors) != 0 { + t.Fatalf("%s answered %s, want no error", query, answerErrors) + } +} + +// invitationLimitAnswer is the first error a call past an invitation or resend limit answers. +type invitationLimitAnswer struct { + Message string `json:"message"` + Extensions struct { + Code string `json:"code"` + Reason string `json:"reason"` + RetryAfter int `json:"retryAfter"` + Meta struct { + RetryAfter int `json:"retryAfter"` + } `json:"meta"` + } `json:"extensions"` +} + +// wantInvitationLimit checks the first error answers the invitation limit, waiting twice the window. +func wantInvitationLimit(t *testing.T, raw json.RawMessage) { + t.Helper() + var answers []invitationLimitAnswer + if err := json.Unmarshal(raw, &answers); err != nil || len(answers) == 0 { + t.Fatalf("errors = %s, want the call rejected past the invitation limit", raw) + } + firstError := answers[0] + retryAfterSeconds := int((2 * invitationLimitWindow).Seconds()) + if firstError.Message != "the invitation limit is reached, try again later" { + t.Errorf("message = %q, want the invitation limit named", firstError.Message) + } + if firstError.Extensions.Code != "RATE_LIMITED" || firstError.Extensions.Reason != "invitation_limit_reached" { + t.Errorf("code and reason = %q and %q, want RATE_LIMITED and invitation_limit_reached", + firstError.Extensions.Code, firstError.Extensions.Reason) + } + if firstError.Extensions.RetryAfter != retryAfterSeconds || + firstError.Extensions.Meta.RetryAfter != retryAfterSeconds { + t.Errorf("retryAfter = %d and meta %d, want %d", firstError.Extensions.RetryAfter, + firstError.Extensions.Meta.RetryAfter, retryAfterSeconds) + } +} + +// wantNoAccount fails the test when the store holds an account under the address. +func wantNoAccount(t *testing.T, store *testkit.Store, address string) { + t.Helper() + if _, err := store.UserByEmail(t.Context(), address); !errors.Is(err, gouncer.ErrUserNotFound) { + t.Errorf("UserByEmail(%s) error = %v, want no account written past the limit", address, err) + } +} + +func TestAnInvitationPastTheInviterLimitIsRejectedBeforeAnyWrite(t *testing.T) { + t.Parallel() + + store := testkit.NewStore() + mailer := &recordingMailer{} + resolver := newInviteResolver(store, mailer) + resolver.InvitationLimiterPerInviter = hourlyLimiter(1) + client := newGraphClient(t, resolver, uuid.Must(uuid.NewV7())) + wantNoErrors(t, client, inviteMutationFor("first@example.com")) + + wantInvitationLimit(t, errorsOf(t, client, inviteMutationFor("past-the-limit@example.com"))) + + wantNoAccount(t, store, "past-the-limit@example.com") + if len(mailer.invites) != 1 { + t.Errorf("sent %d invitation mails, want only the one under the limit", len(mailer.invites)) + } +} + +func TestAResendPastItsLimitAnswersEveryAddressTheSameWay(t *testing.T) { + t.Parallel() + + store := testkit.NewStore() + mailer := &recordingMailer{} + resolver := newInviteResolver(store, mailer) + actor := pendingElsewhere(t, resolver, store) + if _, err := resolver.Onboarding.InviteInto( + t.Context(), tenant.DefaultID, "pending@example.com", "Maria Perez", role.Member.String(), + ); err != nil { + t.Fatalf("inviting the pending account: %v", err) + } + resolver.ResendLimiterPerInviter = hourlyLimiter(1) + client := newGraphClient(t, resolver, actor) + wantNoErrors(t, client, resendMutationFor("pending@example.com")) + sentUnderTheLimit := len(mailer.invites) + + answers := map[string]json.RawMessage{} + for _, address := range []string{"pending@example.com", "unknown@example.com", "maria@example.com"} { + answers[address] = errorsOf(t, client, resendMutationFor(address)) + wantInvitationLimit(t, answers[address]) + } + + if string(answers["unknown@example.com"]) != string(answers["pending@example.com"]) || + string(answers["maria@example.com"]) != string(answers["pending@example.com"]) { + t.Errorf("answers = %v, want one same answer for a pending, an unknown and an out of reach address", answers) + } + if len(mailer.invites) != sentUnderTheLimit { + t.Errorf("sent %d invitation mails, want none past the limit", len(mailer.invites)-sentUnderTheLimit) + } +} + +func TestResendsKeepTheirOwnCountWhileInvitationsAreAtTheirLimit(t *testing.T) { + t.Parallel() + + mailer := &recordingMailer{} + resolver := newInviteResolver(testkit.NewStore(), mailer) + resolver.InvitationLimiterPerInviter = hourlyLimiter(1) + resolver.ResendLimiterPerInviter = hourlyLimiter(1) + client := newGraphClient(t, resolver, uuid.Must(uuid.NewV7())) + wantNoErrors(t, client, inviteMutationFor("maria@example.com")) + wantInvitationLimit(t, errorsOf(t, client, inviteMutationFor("past-the-limit@example.com"))) + + wantNoErrors(t, client, resendMutationFor("maria@example.com")) + wantInvitationLimit(t, errorsOf(t, client, resendMutationFor("maria@example.com"))) + + if len(mailer.invites) != 2 { + t.Errorf("sent %d invitation mails, want the invitation and the one resend under its own limit", + len(mailer.invites)) + } +} + +func TestAnInvitationOfATakenAddressCountsOnceAgainstInvitations(t *testing.T) { + t.Parallel() + + mailer := &recordingMailer{} + resolver := newInviteResolver(testkit.NewStore(), mailer) + resolver.InvitationLimiterPerInviter = hourlyLimiter(3) + resolver.ResendLimiterPerInviter = hourlyLimiter(1) + client := newGraphClient(t, resolver, uuid.Must(uuid.NewV7())) + wantNoErrors(t, client, inviteMutationFor("maria@example.com")) + wantNoErrors(t, client, inviteMutationFor("maria@example.com")) + + wantNoErrors(t, client, inviteMutationFor("third@example.com")) + wantNoErrors(t, client, resendMutationFor("maria@example.com")) + wantInvitationLimit(t, errorsOf(t, client, inviteMutationFor("past-the-limit@example.com"))) + + if len(mailer.invites) != 4 { + t.Errorf("sent %d invitation mails, want three invitations and one resend", len(mailer.invites)) + } +} + +func TestARoleTheActorMayNotGiveCountsNothing(t *testing.T) { + t.Parallel() + + resolver := newInviteResolver(testkit.NewStore(), &recordingMailer{}) + resolver.InvitationLimiterPerInviter = hourlyLimiter(1) + client := newActingClient(t, resolver, authkit.Identity{ID: uuid.Must(uuid.NewV7()), Role: role.Admin.String()}) + + wantNotGrantable(t, errorsOf(t, client, + `mutation { invite(email: "maria@example.com", name: "Maria Perez", role: "steward") { delivered } }`)) + + wantNoErrors(t, client, inviteMutationFor("maria@example.com")) +} + +func TestWithoutAMailerNothingCountsAndTheLinkComesBack(t *testing.T) { + t.Parallel() + + resolver := newInviteResolver(testkit.NewStore(), nil) + resolver.InvitationLimiterPerInviter = hourlyLimiter(1) + resolver.ResendLimiterPerInviter = hourlyLimiter(1) + client := newGraphClient(t, resolver, uuid.Must(uuid.NewV7())) + + for _, query := range []string{ + inviteMutationFor("first@example.com"), + inviteMutationFor("second@example.com"), + resendMutationFor("first@example.com"), + resendMutationFor("first@example.com"), + } { + var answer struct { + Invite *invitePayload `json:"invite"` + ResendInvite *invitePayload `json:"resendInvite"` + } + client.MustPost(query, &answer) + if link := activationLinkOf(answer.Invite, answer.ResendInvite); link == nil { + t.Errorf("%s answered no activation link, want the link handed back past any count", query) + } + } + + resolver.Mailer = &recordingMailer{} + wantNoErrors(t, client, inviteMutationFor("third@example.com")) + wantNoErrors(t, client, resendMutationFor("first@example.com")) +} + +// activationLinkOf returns the activation link of whichever answer is present. +func activationLinkOf(answers ...*invitePayload) *string { + for _, answer := range answers { + if answer != nil { + return answer.ActivationLink + } + } + return nil +} + +func TestNilLimitersSetNoLimit(t *testing.T) { + t.Parallel() + + mailer := &recordingMailer{} + client := newGraphClient(t, newInviteResolver(testkit.NewStore(), mailer), uuid.Must(uuid.NewV7())) + + for i := range 12 { + wantNoErrors(t, client, inviteMutationFor(fmt.Sprintf("invited%d@example.com", i))) + wantNoErrors(t, client, resendMutationFor(fmt.Sprintf("invited%d@example.com", i))) + } + + if len(mailer.invites) != 24 { + t.Errorf("sent %d invitation mails, want every one with no limiter set", len(mailer.invites)) + } +} + +// invitationMailCounter counts the invitation mail it accepts from any goroutine. +type invitationMailCounter struct { + recordingMailer + deliveries atomic.Int64 +} + +// SendInvite counts one delivered invitation mail. +func (c *invitationMailCounter) SendInvite(context.Context, string, string, string) error { + c.deliveries.Add(1) + return nil +} + +func TestTwoCallsAtTheLastFreeCountLetExactlyOneThrough(t *testing.T) { + t.Parallel() + + mailer := &invitationMailCounter{} + resolver := newInviteResolver(testkit.NewStore(), mailer) + gate := &gatedLimiter{limit: 1, release: make(chan struct{})} + resolver.InvitationLimiterPerInviter = gate + client := newGraphClient(t, resolver, uuid.Must(uuid.NewV7())) + + var wg sync.WaitGroup + var rejectionCount atomic.Int64 + for _, address := range []string{"first@example.com", "second@example.com"} { + wg.Go(func() { + response, err := client.RawPost(inviteMutationFor(address)) + if err == nil && strings.Contains(string(response.Errors), "invitation_limit_reached") { + rejectionCount.Add(1) + } + }) + } + time.Sleep(100 * time.Millisecond) + close(gate.release) + wg.Wait() + + if got := mailer.deliveries.Load(); got != 1 { + t.Errorf("two simultaneous invitations mailed %d times, want the limit to let exactly one through", got) + } + if got := rejectionCount.Load(); got != 1 { + t.Errorf("%d of the two simultaneous invitations were rejected, want exactly one", got) + } +} + +// limitLogEntry is the entry a call past an invitation or resend limit writes to the log. +type limitLogEntry struct { + Level string `json:"level"` + Message string `json:"msg"` + Inviter string `json:"inviter"` + Limit string `json:"limit"` +} + +// logEntriesOf returns every JSON entry a log buffer holds. +func logEntriesOf(t *testing.T, logBuffer *bytes.Buffer) []limitLogEntry { + t.Helper() + var entries []limitLogEntry + for line := range strings.Lines(logBuffer.String()) { + var entry limitLogEntry + if err := json.Unmarshal([]byte(line), &entry); err != nil { + t.Fatalf("decode the log line %q: %v", line, err) + } + entries = append(entries, entry) + } + return entries +} + +func TestEachRejectionLogsTheInviterAndTheLimitButNoAddress(t *testing.T) { + t.Parallel() + + tests := map[string]struct { + arrange func(*graphres.Resolver) + query string + limit string + }{ + "invitations per account": { + arrange: func(r *graphres.Resolver) { r.InvitationLimiterPerInviter = hourlyLimiter(1) }, + query: inviteMutationFor("maria@example.com"), + limit: "invitations per account", + }, + "invitations per workspace": { + arrange: func(r *graphres.Resolver) { r.InvitationLimiterPerTenant = hourlyLimiter(1) }, + query: inviteMutationFor("maria@example.com"), + limit: "invitations per workspace", + }, + "resends per account": { + arrange: func(r *graphres.Resolver) { r.ResendLimiterPerInviter = hourlyLimiter(1) }, + query: resendMutationFor("maria@example.com"), + limit: "resends per account", + }, + "resends per workspace": { + arrange: func(r *graphres.Resolver) { r.ResendLimiterPerTenant = hourlyLimiter(1) }, + query: resendMutationFor("maria@example.com"), + limit: "resends per workspace", + }, + } + for testName, tc := range tests { + t.Run(testName, func(t *testing.T) { + t.Parallel() + + resolver := newInviteResolver(testkit.NewStore(), &recordingMailer{}) + tc.arrange(resolver) + logBuffer := &bytes.Buffer{} + resolver.Logger = slog.New(slog.NewJSONHandler(logBuffer, nil)) + inviter := uuid.Must(uuid.NewV7()) + client := newGraphClient(t, resolver, inviter) + wantNoErrors(t, client, tc.query) + + wantInvitationLimit(t, errorsOf(t, client, tc.query)) + + want := []limitLogEntry{ + {Level: "WARN", Message: "invitation limit reached", Inviter: inviter.String(), Limit: tc.limit}, + } + if got := logEntriesOf(t, logBuffer); len(got) != 1 || got[0] != want[0] { + t.Errorf("logged %+v, want %+v", got, want) + } + if strings.Contains(logBuffer.String(), "maria@example.com") { + t.Errorf("the log holds %q, want no address", logBuffer.String()) + } + }) + } +} + +func TestALimiterFailureSurfacesAndMailsNothing(t *testing.T) { + t.Parallel() + + tests := map[string]graphres.AttemptLimiter{ + "the check fails": stubLimiter{checkErr: errors.New("the limiter is unreachable")}, + "the counting fails": stubLimiter{recordErr: errors.New("the limiter is unreachable")}, + } + for testName, limiter := range tests { + t.Run(testName, func(t *testing.T) { + t.Parallel() + + mailer := &recordingMailer{} + resolver := newInviteResolver(testkit.NewStore(), mailer) + resolver.InvitationLimiterPerTenant = limiter + client := newGraphClient(t, resolver, uuid.Must(uuid.NewV7())) + + if got := firstErrorCode(t, errorsOf(t, client, inviteMutationFor("maria@example.com"))); got != "INTERNAL" { + t.Errorf("code = %q, want the limiter failure surfaced as INTERNAL", got) + } + if len(mailer.invites) != 0 { + t.Errorf("sent %d invitation mails, want none when the limit cannot be read", len(mailer.invites)) + } + }) + } +} diff --git a/internal/graphres/invite.go b/internal/graphres/invite.go index e5932ded..df22bc77 100644 --- a/internal/graphres/invite.go +++ b/internal/graphres/invite.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "strings" + "time" "github.com/gopherium/gouncer" "github.com/gopherium/gouncer/authkit" @@ -25,18 +26,128 @@ func deliveredPayload() *model.InvitePayload { return &model.InvitePayload{Delivered: true} } +// errInvitationLimitReached rejects an invitation or a resend past one of its limits. +var errInvitationLimitReached = errors.New("the invitation limit is reached, try again later") + +// invitationLimitError returns the rejection a call past an invitation or resend limit answers, with its wait. +func invitationLimitError(retryAfter time.Duration) error { + seconds := int(retryAfter.Seconds()) + return sdk.GraphError{ + Code: "RATE_LIMITED", + Reason: "invitation_limit_reached", + Meta: map[string]any{"retryAfter": seconds}, + Extensions: map[string]any{"retryAfter": seconds}, + Err: errInvitationLimitReached, + } +} + +// invitationLimitPair holds the per inviter and per tenant limiters one kind of call counts against. +type invitationLimitPair struct { + callKind string + perInviter AttemptLimiter + perTenant AttemptLimiter +} + +// invitationLimits returns the pair an invitation counts against. +func (r *Resolver) invitationLimits() invitationLimitPair { + return invitationLimitPair{ + callKind: "invitations", perInviter: r.InvitationLimiterPerInviter, perTenant: r.InvitationLimiterPerTenant, + } +} + +// resendLimits returns the pair a resend counts against. +func (r *Resolver) resendLimits() invitationLimitPair { + return invitationLimitPair{ + callKind: "resends", perInviter: r.ResendLimiterPerInviter, perTenant: r.ResendLimiterPerTenant, + } +} + +// invitationLimit is one limiter beside the key a call counts under and the name the log gives the limit. +type invitationLimit struct { + limiter AttemptLimiter + key string + name string +} + +// limitsOf returns the limits of the pair whose limiter is set, each beside the key the caller of ctx counts under. +func (p invitationLimitPair) limitsOf(ctx context.Context) []invitationLimit { + var limits []invitationLimit + if p.perInviter != nil { + limits = append(limits, invitationLimit{ + limiter: p.perInviter, key: authkit.IdentityFromContext(ctx).ID.String(), name: p.callKind + " per account", + }) + } + if p.perTenant != nil { + limits = append(limits, invitationLimit{ + limiter: p.perTenant, key: sdk.TenantOrDefault(ctx).String(), name: p.callKind + " per workspace", + }) + } + return limits +} + +// checkInvitationLimits rejects a call past a limit of the pair or else counts it on both, only while a mailer is set. +func (m MutationResolvers) checkInvitationLimits(ctx context.Context, pair invitationLimitPair) error { + if m.root.Mailer == nil { + return nil + } + limits := pair.limitsOf(ctx) + m.root.invitationLimitsMu.Lock() + defer m.root.invitationLimitsMu.Unlock() + for _, limit := range limits { + if err := m.checkInvitationLimit(ctx, limit); err != nil { + return err + } + } + return countCallOnEveryLimit(limits) +} + +// countCallOnEveryLimit counts one call against each of the limits. +func countCallOnEveryLimit(limits []invitationLimit) error { + for _, limit := range limits { + if err := limit.limiter.RecordFailure(limit.key); err != nil { + return fmt.Errorf("counting the call against the %s limit: %w", limit.name, err) + } + } + return nil +} + +// checkInvitationLimit rejects a call past one limit, logging which limit rejected it. +func (m MutationResolvers) checkInvitationLimit(ctx context.Context, limit invitationLimit) error { + isAllowed, retryAfter, err := limit.limiter.Check(limit.key) + if err != nil { + return fmt.Errorf("checking the %s limit: %w", limit.name, err) + } + if isAllowed { + return nil + } + m.logInvitationLimit(ctx, limit.name) + return invitationLimitError(retryAfter) +} + +// logInvitationLimit records the inviter of ctx and the limit that rejected its call, never the address. +func (m MutationResolvers) logInvitationLimit(ctx context.Context, limitName string) { + if m.root.Logger == nil { + return + } + m.root.Logger.WarnContext(ctx, "invitation limit reached", + "inviter", authkit.IdentityFromContext(ctx).ID.String(), "limit", limitName) +} + // Invite creates an invited account under the role it names and delivers the activation link. func (m MutationResolvers) Invite( - ctx context.Context, email, name string, named *string, + ctx context.Context, email, name string, requestedRole *string, ) (*model.InvitePayload, error) { - stood := role.Member.String() - if named != nil { - stood = *named + roleName := role.Member.String() + if requestedRole != nil { + roleName = *requestedRole } - if err := m.root.refuseGrant(authkit.IdentityFromContext(ctx).Role, stood); err != nil { + if err := m.root.refuseGrant(authkit.IdentityFromContext(ctx).Role, roleName); err != nil { return nil, err } - token, err := m.root.Onboarding.InviteInto(ctx, sdk.TenantOrDefault(ctx), email, name, stood) + if err := m.checkInvitationLimits(ctx, m.root.invitationLimits()); err != nil { + return nil, err + } + token, err := m.root.Onboarding.InviteInto(ctx, sdk.TenantOrDefault(ctx), email, name, roleName) if errors.Is(err, gouncer.ErrEmailTaken) { return m.resend(ctx, email) } @@ -48,6 +159,9 @@ func (m MutationResolvers) Invite( // ResendInvite replaces a pending account's activation link, answering every address the same way. func (m MutationResolvers) ResendInvite(ctx context.Context, email string) (*model.InvitePayload, error) { + if err := m.checkInvitationLimits(ctx, m.root.resendLimits()); err != nil { + return nil, err + } return m.resend(ctx, email) } diff --git a/internal/graphres/invite_test.go b/internal/graphres/invite_test.go index cea4d0fe..fec248a0 100644 --- a/internal/graphres/invite_test.go +++ b/internal/graphres/invite_test.go @@ -92,7 +92,7 @@ func (p *placingInvites) placedIn(email string) uuid.UUID { func newInviteResolver(store *testkit.Store, mailer graphres.Mailer) *graphres.Resolver { roles := stewardRoles() invites := authkit.NewInvites(authkit.InvitesConfig{Store: store, ResetTokensLive: 3, Roles: roles}) - held := &graphres.Resolver{ + resolver := &graphres.Resolver{ Version: "9.9.9", Auth: authkit.New(authkit.Config{Store: store, CookieName: "alphone_session"}), Admin: adminOver(store, roles), @@ -106,9 +106,9 @@ func newInviteResolver(store *testkit.Store, mailer graphres.Mailer) *graphres.R Roles: roles, } if mailer != nil { - held.Mailer = mailer + resolver.Mailer = mailer } - return held + return resolver } // invitePayload holds the answer shape of the invite and resend mutations. diff --git a/internal/graphres/invitetenancy_test.go b/internal/graphres/invitetenancy_test.go index 50859cca..c3e7ca5d 100644 --- a/internal/graphres/invitetenancy_test.go +++ b/internal/graphres/invitetenancy_test.go @@ -3,14 +3,18 @@ package graphres_test import ( + "context" "slices" "testing" + gqlclient "github.com/99designs/gqlgen/client" "github.com/google/uuid" + "github.com/gopherium/gouncer/authkit" "github.com/gopherium/gouncer/authkit/testkit" "github.com/gopherium/alphone/internal/graphres" "github.com/gopherium/alphone/internal/tenant" + "github.com/gopherium/alphone/sdk" ) // pendingElsewhere invites an address and stands it in a tenant of its own. @@ -103,3 +107,122 @@ func TestInviteKeepsAnotherTenantsAddressOutOfReach(t *testing.T) { t.Errorf("invite = %+v, want the neutral answer with no token", response.Invite) } } + +// clientOfActorInTenant returns a graph client acting as the account standing in the tenant. +func clientOfActorInTenant( + t *testing.T, resolver *graphres.Resolver, actorID, tenantID uuid.UUID, +) *gqlclient.Client { + t.Helper() + actor := authkit.Identity{ID: actorID} + return newDecoratedGraphClient(t, resolver, func(ctx context.Context) context.Context { + return sdk.WithTenant(authkit.WithIdentity(ctx, actor), tenantID) + }) +} + +// clientInTenant returns a graph client acting as a new account standing in the tenant. +func clientInTenant(t *testing.T, resolver *graphres.Resolver, tenantID uuid.UUID) *gqlclient.Client { + t.Helper() + return clientOfActorInTenant(t, resolver, uuid.Must(uuid.NewV7()), tenantID) +} + +// limitPairCase sets both limiters of one kind of call and builds that call for one address. +type limitPairCase struct { + setLimiters func(r *graphres.Resolver, perInviter, perTenant graphres.AttemptLimiter) + mutation func(address string) string +} + +// limitPairCases returns the invitation pair and the resend pair, each under its kind. +func limitPairCases() map[string]limitPairCase { + return map[string]limitPairCase{ + "invitations": { + setLimiters: func(r *graphres.Resolver, perInviter, perTenant graphres.AttemptLimiter) { + r.InvitationLimiterPerInviter, r.InvitationLimiterPerTenant = perInviter, perTenant + }, + mutation: inviteMutationFor, + }, + "resends": { + setLimiters: func(r *graphres.Resolver, perInviter, perTenant graphres.AttemptLimiter) { + r.ResendLimiterPerInviter, r.ResendLimiterPerTenant = perInviter, perTenant + }, + mutation: resendMutationFor, + }, + } +} + +func TestACallTheTenantLimitRejectsSpendsNothingOfTheInviterLimit(t *testing.T) { + t.Parallel() + + for testName, tc := range limitPairCases() { + t.Run(testName, func(t *testing.T) { + t.Parallel() + + resolver := newInviteResolver(testkit.NewStore(), &recordingMailer{}) + tc.setLimiters(resolver, hourlyLimiter(2), hourlyLimiter(1)) + actorID := uuid.Must(uuid.NewV7()) + firstTenantClient := clientOfActorInTenant(t, resolver, actorID, uuid.Must(uuid.NewV7())) + secondTenantClient := clientOfActorInTenant(t, resolver, actorID, uuid.Must(uuid.NewV7())) + thirdTenantClient := clientOfActorInTenant(t, resolver, actorID, uuid.Must(uuid.NewV7())) + wantNoErrors(t, firstTenantClient, tc.mutation("first@example.com")) + wantInvitationLimit(t, errorsOf(t, firstTenantClient, tc.mutation("rejected@example.com"))) + + wantNoErrors(t, secondTenantClient, tc.mutation("other-tenant@example.com")) + wantInvitationLimit(t, errorsOf(t, thirdTenantClient, tc.mutation("past-the-limit@example.com"))) + }) + } +} + +func TestACallTheInviterLimitRejectsSpendsNothingOfTheTenantLimit(t *testing.T) { + t.Parallel() + + for testName, tc := range limitPairCases() { + t.Run(testName, func(t *testing.T) { + t.Parallel() + + resolver := newInviteResolver(testkit.NewStore(), &recordingMailer{}) + tc.setLimiters(resolver, hourlyLimiter(1), hourlyLimiter(2)) + tenantID := uuid.Must(uuid.NewV7()) + firstActorClient := clientInTenant(t, resolver, tenantID) + wantNoErrors(t, firstActorClient, tc.mutation("first@example.com")) + wantInvitationLimit(t, errorsOf(t, firstActorClient, tc.mutation("rejected@example.com"))) + + wantNoErrors(t, clientInTenant(t, resolver, tenantID), tc.mutation("second-actor@example.com")) + wantInvitationLimit(t, errorsOf(t, clientInTenant(t, resolver, tenantID), + tc.mutation("past-the-limit@example.com"))) + }) + } +} + +func TestTwoActorsOfOneTenantShareItsLimitAndAnotherTenantKeepsItsOwn(t *testing.T) { + t.Parallel() + + tests := map[string]struct { + arrange func(*graphres.Resolver) + mutation func(address string) string + }{ + "invitations": { + arrange: func(r *graphres.Resolver) { r.InvitationLimiterPerTenant = hourlyLimiter(2) }, + mutation: inviteMutationFor, + }, + "resends": { + arrange: func(r *graphres.Resolver) { r.ResendLimiterPerTenant = hourlyLimiter(2) }, + mutation: resendMutationFor, + }, + } + for testName, tc := range tests { + t.Run(testName, func(t *testing.T) { + t.Parallel() + + resolver := newInviteResolver(testkit.NewStore(), &recordingMailer{}) + tc.arrange(resolver) + firstTenant, secondTenant := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()) + firstActorClient := clientInTenant(t, resolver, firstTenant) + secondActorClient := clientInTenant(t, resolver, firstTenant) + wantNoErrors(t, firstActorClient, tc.mutation("first@example.com")) + wantNoErrors(t, secondActorClient, tc.mutation("second@example.com")) + + wantInvitationLimit(t, errorsOf(t, secondActorClient, tc.mutation("past-the-limit@example.com"))) + + wantNoErrors(t, clientInTenant(t, resolver, secondTenant), tc.mutation("other-tenant@example.com")) + }) + } +} From 04a34bfe8acb64045b4881dcd118c562bbe0e421 Mon Sep 17 00:00:00 2001 From: SirLouen Date: Mon, 30 Nov 2026 18:18:34 +0100 Subject: [PATCH 5/9] feat(settings): read the invitation and resend limits from the environment --- .env.example | 7 + cmd/alphone/invitationlimitwiring_test.go | 163 +++++++++++++++++++ cmd/alphone/mailconfig_test.go | 114 +++++++++++-- cmd/alphone/mailwiring_test.go | 24 ++- cmd/alphone/run.go | 159 ++++++++++++------ cmd/alphone/settings_test.go | 186 +++++++++++++--------- 6 files changed, 518 insertions(+), 135 deletions(-) create mode 100644 cmd/alphone/invitationlimitwiring_test.go diff --git a/.env.example b/.env.example index cbf45fb0..beea5b6d 100644 --- a/.env.example +++ b/.env.example @@ -132,6 +132,13 @@ ALPHONE_TEST_S3_SECRET_ACCESS_KEY=0123456789abcdef0123456789abcdef0123456789abcd # How long invite and reset links live, 168h and 1h when unset. # ALPHONE_INVITE_TTL=168h # ALPHONE_RESET_TTL=1h +# Invitations and resends one inviting account and one workspace may send per window, counted apart +# and only while a mail relay is set, 10, 20, 5 and 10 per 24h when unset. +# ALPHONE_INVITES_PER_INVITER=10 +# ALPHONE_INVITES_PER_TENANT=20 +# ALPHONE_INVITE_RESENDS_PER_INVITER=5 +# ALPHONE_INVITE_RESENDS_PER_TENANT=10 +# ALPHONE_INVITE_LIMIT_WINDOW=24h # Reset requests allowed per client IP within one reset link lifetime, 3 when unset. # ALPHONE_RESET_ATTEMPTS=3 # Reset links that may stand for one account at once, 3 when unset. diff --git a/cmd/alphone/invitationlimitwiring_test.go b/cmd/alphone/invitationlimitwiring_test.go new file mode 100644 index 00000000..83fcb378 --- /dev/null +++ b/cmd/alphone/invitationlimitwiring_test.go @@ -0,0 +1,163 @@ +// SPDX-License-Identifier: Elastic-2.0 + +package main + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strconv" + "strings" + "testing" + + "github.com/gopherium/framework/gonsole/testkit" +) + +// invitationBody is the graph body that invites one address. +const invitationBody = `{"query":"mutation { invite(email: \"%s\", name: \"Maria Perez\") { delivered } }"}` + +// resendBody is the graph body that resends the invitation of one address. +const resendBody = `{"query":"mutation { resendInvite(email: \"%s\") { delivered } }"}` + +// startRunWithARelay serves run over a fresh database, a mock relay and env, answering its address and its database. +func startRunWithARelay(t *testing.T, env map[string]string) (string, string) { + t.Helper() + relay := mailRelay(t) + databaseURL := testDatabaseURL(t) + addr := testkit.FreeAddr(t) + env["ALPHONE_DATABASE_URL"] = databaseURL + env["ALPHONE_ADDR"] = addr + env["ALPHONE_SMTP_HOST"] = "127.0.0.1" + env["ALPHONE_SMTP_PORT"] = strconv.Itoa(relay.PortNumber()) + env["ALPHONE_SMTP_FROM"] = "crm@example.com" + env["ALPHONE_SMTP_TLS"] = "none" + env["ALPHONE_PUBLIC_URL"] = "https://crm.example.com" + ctx, cancel := context.WithCancel(t.Context()) + runErr := make(chan error, 1) + go func() { + runErr <- run(ctx, testkit.Getenv(env), io.Discard, registerPlugins) + }() + t.Cleanup(func() { stopRun(t, cancel, runErr) }) + baseURL := "http://" + addr + waitForServer(t, baseURL) + return baseURL, databaseURL +} + +// adminSessionAs stores an admin under the address and answers the session it logs in with. +func adminSessionAs(t *testing.T, baseURL, databaseURL, address string) *http.Cookie { + t.Helper() + seedAdminAs(t, databaseURL, address) + return loginSessionAs(t, baseURL, address) +} + +// graphAnswerAs posts a graph body with the session cookie and returns the answer, errors included. +func graphAnswerAs(t *testing.T, session *http.Cookie, baseURL, body string) string { + t.Helper() + response := doAuthed(t, t.Context(), session, http.MethodPost, baseURL+"/api/graphql", body) + answer, err := io.ReadAll(response.Body) + _ = response.Body.Close() + if err != nil { + t.Fatalf("reading the graph answer: %v", err) + } + return string(answer) +} + +// wantNoGraphErrors fails the test when the answer carries any error. +func wantNoGraphErrors(t *testing.T, answer string) { + t.Helper() + if strings.Contains(answer, `"errors"`) { + t.Fatalf("answer = %s, want the call allowed under the limit", answer) + } +} + +// wantInvitationLimitAnswer fails the test unless the answer is rejected past a limit that counts over one hour. +func wantInvitationLimitAnswer(t *testing.T, answer string) { + t.Helper() + if !strings.Contains(answer, `"reason":"invitation_limit_reached"`) || !strings.Contains(answer, `"retryAfter":7200`) { + t.Fatalf("answer = %s, want invitation_limit_reached waiting twice the one hour window", answer) + } +} + +// usersWriteTokenSecret mints an API token holding the users write scope through the session and returns its secret. +func usersWriteTokenSecret(t *testing.T, session *http.Cookie, baseURL string) string { + t.Helper() + answer := graphAnswerAs(t, session, baseURL, + `{"query":"mutation { apiTokenCreate(name: \"automation\", scopes: [\"users:write\"]) { secret } }"}`) + var minted struct { + Data struct { + APITokenCreate struct { + Secret string `json:"secret"` + } `json:"apiTokenCreate"` + } `json:"data"` + } + if err := json.Unmarshal([]byte(answer), &minted); err != nil || minted.Data.APITokenCreate.Secret == "" { + t.Fatalf("minting the token answered %s (%v), want a secret", answer, err) + } + return minted.Data.APITokenCreate.Secret +} + +// graphAnswerByToken posts a graph query with the token secret and returns the answer, errors included. +func graphAnswerByToken(t *testing.T, secret, baseURL, query string) string { + t.Helper() + response := postGraphQuery(t, strings.TrimPrefix(baseURL, "http://"), query, bearerOf(secret)) + answer, err := io.ReadAll(response.Body) + _ = response.Body.Close() + if err != nil { + t.Fatalf("reading the graph answer: %v", err) + } + return string(answer) +} + +func TestAnInvitationByAnAPITokenCountsForTheTokensOwner(t *testing.T) { + t.Parallel() + + baseURL, databaseURL := startRunWithARelay(t, map[string]string{ + "ALPHONE_INVITES_PER_INVITER": "1", + "ALPHONE_INVITE_LIMIT_WINDOW": "1h", + }) + session := adminSessionAs(t, baseURL, databaseURL, "first.admin@example.com") + secret := usersWriteTokenSecret(t, session, baseURL) + wantNoGraphErrors(t, graphAnswerAs(t, session, baseURL, fmt.Sprintf(invitationBody, "first@example.com"))) + + wantInvitationLimitAnswer(t, graphAnswerByToken(t, secret, baseURL, + `mutation { invite(email: "second@example.com", name: "Maria Perez") { delivered } }`)) +} + +func TestEachInvitationLimitSettingReachesItsLimiter(t *testing.T) { + t.Parallel() + + tests := map[string]struct { + setting string + body string + isPerTenant bool + }{ + "invitations per inviter": {setting: "ALPHONE_INVITES_PER_INVITER", body: invitationBody}, + "invitations per tenant": {setting: "ALPHONE_INVITES_PER_TENANT", body: invitationBody, isPerTenant: true}, + "resends per inviter": {setting: "ALPHONE_INVITE_RESENDS_PER_INVITER", body: resendBody}, + "resends per tenant": {setting: "ALPHONE_INVITE_RESENDS_PER_TENANT", body: resendBody, isPerTenant: true}, + } + for testName, tc := range tests { + t.Run(testName, func(t *testing.T) { + t.Parallel() + + baseURL, databaseURL := startRunWithARelay(t, map[string]string{ + tc.setting: "1", + "ALPHONE_INVITE_LIMIT_WINDOW": "1h", + }) + firstSession := adminSessionAs(t, baseURL, databaseURL, "first.admin@example.com") + secondSession := adminSessionAs(t, baseURL, databaseURL, "second.admin@example.com") + wantNoGraphErrors(t, graphAnswerAs(t, firstSession, baseURL, fmt.Sprintf(tc.body, "first@example.com"))) + + if tc.isPerTenant { + wantInvitationLimitAnswer(t, + graphAnswerAs(t, secondSession, baseURL, fmt.Sprintf(tc.body, "second@example.com"))) + return + } + wantInvitationLimitAnswer(t, + graphAnswerAs(t, firstSession, baseURL, fmt.Sprintf(tc.body, "second@example.com"))) + wantNoGraphErrors(t, graphAnswerAs(t, secondSession, baseURL, fmt.Sprintf(tc.body, "third@example.com"))) + }) + } +} diff --git a/cmd/alphone/mailconfig_test.go b/cmd/alphone/mailconfig_test.go index 67c68416..0bcdd4b5 100644 --- a/cmd/alphone/mailconfig_test.go +++ b/cmd/alphone/mailconfig_test.go @@ -86,25 +86,25 @@ func TestTheMailDefaultsApply(t *testing.T) { func TestTheTokenLifetimesDefaultWithoutAMailer(t *testing.T) { t.Parallel() - held, err := loadRunConfig(testkit.Getenv(map[string]string{ + settings, err := loadRunConfig(testkit.Getenv(map[string]string{ "ALPHONE_DATABASE_URL": "postgres://localhost/x", })) if err != nil { t.Fatalf("loadRunConfig() error = %v, want nil", err) } - if held.inviteTTL != authkit.DefaultInviteTTL { - t.Errorf("inviteTTL = %v, want the authkit default %v", held.inviteTTL, authkit.DefaultInviteTTL) + if settings.invitation.ttl != authkit.DefaultInviteTTL { + t.Errorf("invitation.ttl = %v, want the authkit default %v", settings.invitation.ttl, authkit.DefaultInviteTTL) } - if held.reset.ttl != authkit.DefaultResetTTL { - t.Errorf("resetTTL = %v, want the authkit default %v", held.reset.ttl, authkit.DefaultResetTTL) + if settings.reset.ttl != authkit.DefaultResetTTL { + t.Errorf("resetTTL = %v, want the authkit default %v", settings.reset.ttl, authkit.DefaultResetTTL) } } func TestTheTokenLifetimesAreReadWithoutAMailer(t *testing.T) { t.Parallel() - held, err := loadRunConfig(testkit.Getenv(map[string]string{ + settings, err := loadRunConfig(testkit.Getenv(map[string]string{ "ALPHONE_DATABASE_URL": "postgres://localhost/x", "ALPHONE_INVITE_TTL": "24h", "ALPHONE_RESET_TTL": "30m", @@ -113,11 +113,11 @@ func TestTheTokenLifetimesAreReadWithoutAMailer(t *testing.T) { if err != nil { t.Fatalf("loadRunConfig() error = %v, want nil", err) } - if held.inviteTTL != 24*time.Hour { - t.Errorf("inviteTTL = %v, want 24h", held.inviteTTL) + if settings.invitation.ttl != 24*time.Hour { + t.Errorf("invitation.ttl = %v, want 24h", settings.invitation.ttl) } - if held.reset.ttl != 30*time.Minute { - t.Errorf("resetTTL = %v, want 30m", held.reset.ttl) + if settings.reset.ttl != 30*time.Minute { + t.Errorf("resetTTL = %v, want 30m", settings.reset.ttl) } } @@ -500,3 +500,97 @@ func TestTheResetCooldownRidesItsOwnWindow(t *testing.T) { t.Errorf("resetCooldownBudget() = %+v, want one mail per 30s", held) } } + +func TestTheInvitationLimitsDefault(t *testing.T) { + t.Parallel() + + settings, err := loadRunConfig(testkit.Getenv(map[string]string{ + "ALPHONE_DATABASE_URL": "postgres://localhost/x", + })) + + if err != nil { + t.Fatalf("loadRunConfig() error = %v, want nil", err) + } + want := invitationSettings{ + ttl: authkit.DefaultInviteTTL, + invitesPerInviter: 10, + invitesPerTenant: 20, + resendsPerInviter: 5, + resendsPerTenant: 10, + window: 24 * time.Hour, + } + if settings.invitation != want { + t.Errorf("invitation = %+v, want the defaults %+v", settings.invitation, want) + } +} + +func TestTheInvitationLimitsAreReadFromTheEnvironment(t *testing.T) { + t.Parallel() + + settings, err := loadRunConfig(testkit.Getenv(map[string]string{ + "ALPHONE_DATABASE_URL": "postgres://localhost/x", + "ALPHONE_INVITE_TTL": "48h", + "ALPHONE_INVITES_PER_INVITER": "3", + "ALPHONE_INVITES_PER_TENANT": "7", + "ALPHONE_INVITE_RESENDS_PER_INVITER": "2", + "ALPHONE_INVITE_RESENDS_PER_TENANT": "4", + "ALPHONE_INVITE_LIMIT_WINDOW": "6h", + })) + + if err != nil { + t.Fatalf("loadRunConfig() error = %v, want nil", err) + } + want := invitationSettings{ + ttl: 48 * time.Hour, + invitesPerInviter: 3, + invitesPerTenant: 7, + resendsPerInviter: 2, + resendsPerTenant: 4, + window: 6 * time.Hour, + } + if settings.invitation != want { + t.Errorf("invitation = %+v, want %+v", settings.invitation, want) + } +} + +func TestAMalformedInvitationLimitIsRejectedWithItsName(t *testing.T) { + t.Parallel() + + tests := map[string]struct { + key string + raw string + }{ + "invitations per inviter in words": {"ALPHONE_INVITES_PER_INVITER", "a few"}, + "no invitations per inviter": {"ALPHONE_INVITES_PER_INVITER", "0"}, + "negative invitations per tenant": {"ALPHONE_INVITES_PER_TENANT", "-1"}, + "resends per inviter in words": {"ALPHONE_INVITE_RESENDS_PER_INVITER", "many"}, + "no resends per tenant": {"ALPHONE_INVITE_RESENDS_PER_TENANT", "0"}, + "a window in words": {"ALPHONE_INVITE_LIMIT_WINDOW", "a day"}, + "no window": {"ALPHONE_INVITE_LIMIT_WINDOW", "0s"}, + "a negative window": {"ALPHONE_INVITE_LIMIT_WINDOW", "-1h"}, + } + for testName, tc := range tests { + t.Run(testName, func(t *testing.T) { + t.Parallel() + + _, err := loadRunConfig(testkit.Getenv(map[string]string{ + "ALPHONE_DATABASE_URL": "postgres://localhost/x", + tc.key: tc.raw, + })) + + if err == nil || !strings.HasPrefix(err.Error(), tc.key+": ") { + t.Errorf("loadRunConfig() with %s=%q error = %v, want it rejected naming %s", tc.key, tc.raw, err, tc.key) + } + }) + } +} + +func TestEachInvitationLimitCountsOverTheWindow(t *testing.T) { + t.Parallel() + + invitation := invitationSettings{window: 6 * time.Hour} + + if got := invitation.budget(7); got.Limit != 7 || got.Window != 6*time.Hour { + t.Errorf("budget(7) = %+v, want limit 7 over 6h", got) + } +} diff --git a/cmd/alphone/mailwiring_test.go b/cmd/alphone/mailwiring_test.go index d7667382..aedde50d 100644 --- a/cmd/alphone/mailwiring_test.go +++ b/cmd/alphone/mailwiring_test.go @@ -5,6 +5,7 @@ package main import ( "context" "encoding/json" + "fmt" "io" "mime/quotedprintable" "net/http" @@ -52,13 +53,19 @@ func stopRun(t *testing.T, cancel context.CancelFunc, runErr <-chan error) { // seedAdmin stores an enabled admin account able to invite. func seedAdmin(t *testing.T, databaseURL string) { + t.Helper() + seedAdminAs(t, databaseURL, "admin@example.com") +} + +// seedAdminAs stores an enabled admin account able to invite under the address. +func seedAdminAs(t *testing.T, databaseURL, address string) { t.Helper() pool, err := pgxpool.New(t.Context(), databaseURL) if err != nil { t.Fatalf("connecting pool: %v", err) } t.Cleanup(pool.Close) - admin, err := gouncer.NewUser("admin@example.com", "Admin", "correct horse battery") + admin, err := gouncer.NewUser(address, "Admin", "correct horse battery") if err != nil { t.Fatalf("gouncer.NewUser() error = %v, want nil", err) } @@ -71,14 +78,19 @@ func seedAdmin(t *testing.T, databaseURL string) { // loginSession logs the seeded admin in and answers the session cookie. func loginSession(t *testing.T, baseURL string) *http.Cookie { t.Helper() - login, err := http.Post(baseURL+"/api/graphql", "application/json", strings.NewReader( - `{"query":"mutation { login(email: \"admin@example.com\",`+ - ` password: \"correct horse battery\") { me { id } } }"}`)) + return loginSessionAs(t, baseURL, "admin@example.com") +} + +// loginSessionAs logs the account under the address in and answers the session cookie. +func loginSessionAs(t *testing.T, baseURL, address string) *http.Cookie { + t.Helper() + response, err := http.Post(baseURL+"/api/graphql", "application/json", strings.NewReader(fmt.Sprintf( + `{"query":"mutation { login(email: \"%s\", password: \"correct horse battery\") { me { id } } }"}`, address))) if err != nil { t.Fatalf("graph login: %v", err) } - defer func() { _ = login.Body.Close() }() - for _, cookie := range login.Cookies() { + defer func() { _ = response.Body.Close() }() + for _, cookie := range response.Cookies() { if cookie.Name == "__Host-alphone_session" { return cookie } diff --git a/cmd/alphone/run.go b/cmd/alphone/run.go index f87d1252..35a32e4e 100644 --- a/cmd/alphone/run.go +++ b/cmd/alphone/run.go @@ -97,47 +97,54 @@ func run( } // inviteConfigOf returns the invitation and reset lifetimes the settings name over the store and roles compose built. -func inviteConfigOf(settings runConfig, built composed) authkit.InvitesConfig { +func inviteConfigOf(settings runConfig, composeResult composed) authkit.InvitesConfig { return authkit.InvitesConfig{ - Store: built.users, - InviteTTL: settings.inviteTTL, + Store: composeResult.users, + InviteTTL: settings.invitation.ttl, ResetTTL: settings.reset.ttl, ResetTokensLive: settings.reset.links, - Roles: built.roles, + Roles: composeResult.roles, } } // graphResolver returns the core graph resolver over what compose built, the login handlers and the settings. -func graphResolver(settings runConfig, built composed, auth *authkit.Handlers, logger *slog.Logger) *graphres.Resolver { - invites := inviteConfigOf(settings, built) +func graphResolver( + settings runConfig, composeResult composed, auth *authkit.Handlers, logger *slog.Logger, +) *graphres.Resolver { + inviteConfig := inviteConfigOf(settings, composeResult) + invitation := settings.invitation return &graphres.Resolver{ - Version: version.Version(), - Contacts: built.contacts, - Tasks: built.tasks, - Webhooks: built.webhooks, - WebhookGuard: built.webhookGuard, - Tenants: built.tenants, - Tokens: built.tokens, - Events: built.events, - Live: built.hub, - Auth: auth, - Admin: authkit.NewAdmin(adminConfig(built)), - Invites: authkit.NewInvites(invites), - Onboarding: postgres.NewOnboarding(built.pool, invites), - Accounts: built.users, - Mailer: built.mailer, - PublicURL: settings.publicURL, - Settings: postgres.NewUserSettingStore(built.pool), - LoginLimiter: ratelimit.NewLimiter(ratelimit.Config{}), - TokenLimiter: ratelimit.NewLimiter(ratelimit.Config{}), - ResetLimiter: ratelimit.NewLimiter(resetBudget(settings)), - ResetCooldown: ratelimit.NewLimiter(resetCooldownBudget(settings)), - Logger: logger, - Paging: settings.paging, - Screens: settings.screens, - Legal: settings.legal, - Roles: built.roles, - HiddenScreens: screensHidden(built.registered, settings.hooks, logger), + Version: version.Version(), + Contacts: composeResult.contacts, + Tasks: composeResult.tasks, + Webhooks: composeResult.webhooks, + WebhookGuard: composeResult.webhookGuard, + Tenants: composeResult.tenants, + Tokens: composeResult.tokens, + Events: composeResult.events, + Live: composeResult.hub, + Auth: auth, + Admin: authkit.NewAdmin(adminConfig(composeResult)), + Invites: authkit.NewInvites(inviteConfig), + Onboarding: postgres.NewOnboarding(composeResult.pool, inviteConfig), + Accounts: composeResult.users, + Mailer: composeResult.mailer, + PublicURL: settings.publicURL, + Settings: postgres.NewUserSettingStore(composeResult.pool), + LoginLimiter: ratelimit.NewLimiter(ratelimit.Config{}), + TokenLimiter: ratelimit.NewLimiter(ratelimit.Config{}), + ResetLimiter: ratelimit.NewLimiter(resetBudget(settings)), + ResetCooldown: ratelimit.NewLimiter(resetCooldownBudget(settings)), + InvitationLimiterPerInviter: ratelimit.NewLimiter(invitation.budget(invitation.invitesPerInviter)), + InvitationLimiterPerTenant: ratelimit.NewLimiter(invitation.budget(invitation.invitesPerTenant)), + ResendLimiterPerInviter: ratelimit.NewLimiter(invitation.budget(invitation.resendsPerInviter)), + ResendLimiterPerTenant: ratelimit.NewLimiter(invitation.budget(invitation.resendsPerTenant)), + Logger: logger, + Paging: settings.paging, + Screens: settings.screens, + Legal: settings.legal, + Roles: composeResult.roles, + HiddenScreens: screensHidden(composeResult.registered, settings.hooks, logger), } } @@ -290,7 +297,7 @@ type runConfig struct { webDir string trustedProxies []string graphiql bool - inviteTTL time.Duration + invitation invitationSettings reset resetSettings screens graphres.Screens legal graphres.LegalLinks @@ -360,6 +367,36 @@ func loadTenantSettings(env gonsole.Env) (tenantSettings, error) { return tenantSettings{held: held, refresh: refresh}, nil } +// invitationSettings names the lifetime of an invitation link and the limits invitations and resends count against. +type invitationSettings struct { + ttl time.Duration + invitesPerInviter int + invitesPerTenant int + resendsPerInviter int + resendsPerTenant int + window time.Duration +} + +// budget returns the rate limit allowing count calls per key in the window the invitation limits count over. +func (s invitationSettings) budget(count int) ratelimit.Config { + return ratelimit.Config{Limit: count, Window: s.window} +} + +// defaultInvitesPerInviter caps the invitations one inviting account sends in one window. +const defaultInvitesPerInviter = 10 + +// defaultInvitesPerTenant caps the invitations one tenant sends in one window. +const defaultInvitesPerTenant = 20 + +// defaultInviteResendsPerInviter caps the invitation resends one inviting account sends in one window. +const defaultInviteResendsPerInviter = 5 + +// defaultInviteResendsPerTenant caps the invitation resends one tenant sends in one window. +const defaultInviteResendsPerTenant = 10 + +// defaultInviteLimitWindow is the window the invitation and resend limits count over. +const defaultInviteLimitWindow = 24 * time.Hour + // resetSettings names the lifetime, stack and rate the reset links ride under. type resetSettings struct { ttl time.Duration @@ -546,19 +583,19 @@ func loadRunConfig(getenv func(string) string) (runConfig, error) { if err != nil { return runConfig{}, err } - shared, err := loadComposeSettings(env) + settingsForCompose, err := loadComposeSettings(env) if err != nil { return runConfig{}, err } - inviteTTL, err := env.Duration("INVITE_TTL", authkit.DefaultInviteTTL) + invitation, err := loadInvitationSettings(env) if err != nil { return runConfig{}, err } - reset, err := loadResetSettings(env) + resetLinkSettings, err := loadResetSettings(env) if err != nil { return runConfig{}, err } - screens, err := loadScreens(env, shared.paging.Cap) + screens, err := loadScreens(env, settingsForCompose.paging.Cap) if err != nil { return runConfig{}, err } @@ -566,7 +603,7 @@ func loadRunConfig(getenv func(string) string) (runConfig, error) { if err != nil { return runConfig{}, err } - legal, err := loadLegalLinks(env, graph.bounds.AnonymousAnswerMaxBytes) + legalLinks, err := loadLegalLinks(env, graph.bounds.AnonymousAnswerMaxBytes) if err != nil { return runConfig{}, err } @@ -574,24 +611,56 @@ func loadRunConfig(getenv func(string) string) (runConfig, error) { if err != nil { return runConfig{}, err } - serving, err := env.Timeouts(servingDefaults) + timeouts, err := env.Timeouts(servingDefaults) return runConfig{ - composeSettings: shared, + composeSettings: settingsForCompose, databaseURL: databaseURL, addr: valueOr(env, "ADDR", "localhost:8080"), webDir: env.Value("WEB_DIR"), trustedProxies: trustedProxies, graphiql: env.Value("DEV_GRAPHIQL") != "", - inviteTTL: inviteTTL, - reset: reset, + invitation: invitation, + reset: resetLinkSettings, screens: screens, - legal: legal, + legal: legalLinks, graph: graph, hooks: hooks, - serving: serving, + serving: timeouts, }, err } +// loadInvitationSettings reads the invitation link lifetime and the invitation and resend limits from the environment. +func loadInvitationSettings(env gonsole.Env) (invitationSettings, error) { + ttl, err := env.Duration("INVITE_TTL", authkit.DefaultInviteTTL) + if err != nil { + return invitationSettings{}, err + } + invitesPerInviter, err := env.Count("INVITES_PER_INVITER", defaultInvitesPerInviter) + if err != nil { + return invitationSettings{}, err + } + invitesPerTenant, err := env.Count("INVITES_PER_TENANT", defaultInvitesPerTenant) + if err != nil { + return invitationSettings{}, err + } + resendsPerInviter, err := env.Count("INVITE_RESENDS_PER_INVITER", defaultInviteResendsPerInviter) + if err != nil { + return invitationSettings{}, err + } + resendsPerTenant, err := env.Count("INVITE_RESENDS_PER_TENANT", defaultInviteResendsPerTenant) + if err != nil { + return invitationSettings{}, err + } + window, err := env.Duration("INVITE_LIMIT_WINDOW", defaultInviteLimitWindow) + if err != nil { + return invitationSettings{}, err + } + return invitationSettings{ + ttl: ttl, invitesPerInviter: invitesPerInviter, invitesPerTenant: invitesPerTenant, + resendsPerInviter: resendsPerInviter, resendsPerTenant: resendsPerTenant, window: window, + }, nil +} + // valueOr returns the setting's value, or fallback when it is empty. func valueOr(env gonsole.Env, name, fallback string) string { if value := env.Value(name); value != "" { diff --git a/cmd/alphone/settings_test.go b/cmd/alphone/settings_test.go index f4a4467a..fad368b9 100644 --- a/cmd/alphone/settings_test.go +++ b/cmd/alphone/settings_test.go @@ -18,85 +18,94 @@ import ( "strconv" "strings" "testing" + "time" "github.com/gopherium/framework/gonsole/testkit" ) -// coreSettings returns one valid value for every core setting the server reads, the mail ones legal together. +// coreSettings returns a copy of coreSettingValues the caller may change. func coreSettings() map[string]string { - return map[string]string{ - "ALPHONE_DATABASE_URL": "postgres://localhost:5433/alphone", - "ALPHONE_ADDR": "127.0.0.1:9000", - "ALPHONE_WEB_DIR": "/srv/alphone/web", - "ALPHONE_TRUSTED_PROXIES": "10.0.0.0/8,192.168.0.0/16", - "ALPHONE_WEBHOOK_ALLOWED_HOSTS": "127.0.0.1/32,n8n:5678", - "ALPHONE_WEBHOOK_PAYLOAD_AGE": "240h", - "ALPHONE_DEV_GRAPHIQL": "1", - "ALPHONE_TENANT_MACHINE_GRACE": "72h", - "ALPHONE_TENANTS_HELD": "8", - "ALPHONE_TENANTS_REFRESH": "30s", - "ALPHONE_CONTACT_MATCH_MAX": "40", - "ALPHONE_SMTP_HOST": "mail.example.com", - "ALPHONE_SMTP_PORT": "2525", - "ALPHONE_SMTP_USERNAME": "crm", - "ALPHONE_SMTP_PASSWORD": "correct horse battery", - "ALPHONE_SMTP_FROM": "crm@example.com", - "ALPHONE_SMTP_TLS": "opportunistic", - "ALPHONE_PUBLIC_URL": "https://crm.example.com", - "ALPHONE_PRIVACY_URL": "https://example.com/legal/privacy", - "ALPHONE_TERMS_URL": "https://example.com/legal/terms", - "ALPHONE_MAIL_TEMPLATE_DIR": "/srv/alphone/mail", - "ALPHONE_INVITE_TTL": "24h", - "ALPHONE_RESET_TTL": "30m", - "ALPHONE_RESET_ATTEMPTS": "5", - "ALPHONE_RESET_LINKS": "4", - "ALPHONE_RESET_COOLDOWN": "2m", - "ALPHONE_GRAPH_PAGE_SIZE": "25", - "ALPHONE_GRAPH_PAGE_CAP": "400", - "ALPHONE_GRAPH_OPERATIONS_PER_USER": "12", - "ALPHONE_GRAPH_OPERATION_TIMEOUT": "45s", - "ALPHONE_GRAPH_BODY_MAX_BYTES": "524288", - "ALPHONE_GRAPH_UPLOAD_MAX_BYTES": "3145728", - "ALPHONE_GRAPH_RETRY_AFTER": "2s", - "ALPHONE_GRAPH_ANONYMOUS_MAX_BYTES": "8192", - "ALPHONE_GRAPH_ANONYMOUS_PER_IP": "3", - "ALPHONE_GRAPH_ANONYMOUS_CEILING": "12", - "ALPHONE_GRAPH_ANONYMOUS_MAX_TOKENS": "48", - "ALPHONE_GRAPH_ANONYMOUS_QUERY_MAX_BYTES": "768", - "ALPHONE_GRAPH_ANONYMOUS_ANSWER_MAX_BYTES": "12288", - "ALPHONE_STREAMS_PER_USER": "4", - "ALPHONE_STREAM_LIFETIME": "3m", - "ALPHONE_TOAST_DURATION": "9s", - "ALPHONE_TOAST_ACTION_DURATION": "14s", - "ALPHONE_DIALOG_WRITE_TIMEOUT": "45s", - "ALPHONE_LIST_PAGE_SIZES": "5,15,30", - "ALPHONE_LIST_PAGE_SIZE": "15", - "ALPHONE_FORMAT_LOCALE": "de-DE", - "ALPHONE_PLUGIN_SCREENS_BUDGET": "250ms", - "ALPHONE_PLUGIN_HOOK_TIMED_FIRINGS": "40", - "ALPHONE_HTTP_READ_HEADER_TIMEOUT": "5s", - "ALPHONE_HTTP_READ_TIMEOUT": "20s", - "ALPHONE_HTTP_IDLE_TIMEOUT": "90s", - "ALPHONE_SHUTDOWN_GRACE": "15s", - "ALPHONE_SHUTDOWN_CANCEL_GRACE": "3s", - "ALPHONE_SHUTDOWN_STOP_GRACE": "4s", - "ALPHONE_STORAGE_DRIVER": "s3", - "ALPHONE_STORAGE_MAX_BYTES": "1048576", - "ALPHONE_STORAGE_CHUNK_BYTES": "65536", - "ALPHONE_STORAGE_CLEANUP_TIMEOUT": "3s", - "ALPHONE_STORAGE_SWEEP_INTERVAL": "15m", - "ALPHONE_STORAGE_SWEEP_AGE": "6h", - "ALPHONE_STORAGE_SWEEP_BATCH": "250", - "ALPHONE_STORAGE_S3_ENDPOINT": "https://files.example.com", - "ALPHONE_STORAGE_S3_REGION": "garage", - "ALPHONE_STORAGE_S3_BUCKET": "example-files", - "ALPHONE_STORAGE_S3_ACCESS_KEY_ID": "GKexample", - "ALPHONE_STORAGE_S3_SECRET_ACCESS_KEY": "example-secret", - "ALPHONE_STORAGE_S3_PATH_STYLE": "true", - "ALPHONE_STORAGE_S3_CHECKSUM": "when_required", - "ALPHONE_ENCRYPTION_KEY": currentEncryptionKey, - "ALPHONE_ENCRYPTION_PREVIOUS_KEYS": olderEncryptionKey, - } + return maps.Clone(coreSettingValues) +} + +// coreSettingValues holds one valid value for every core setting the server reads, the mail ones legal together. +var coreSettingValues = map[string]string{ + "ALPHONE_DATABASE_URL": "postgres://localhost:5433/alphone", + "ALPHONE_ADDR": "127.0.0.1:9000", + "ALPHONE_WEB_DIR": "/srv/alphone/web", + "ALPHONE_TRUSTED_PROXIES": "10.0.0.0/8,192.168.0.0/16", + "ALPHONE_WEBHOOK_ALLOWED_HOSTS": "127.0.0.1/32,n8n:5678", + "ALPHONE_WEBHOOK_PAYLOAD_AGE": "240h", + "ALPHONE_DEV_GRAPHIQL": "1", + "ALPHONE_TENANT_MACHINE_GRACE": "72h", + "ALPHONE_TENANTS_HELD": "8", + "ALPHONE_TENANTS_REFRESH": "30s", + "ALPHONE_CONTACT_MATCH_MAX": "40", + "ALPHONE_SMTP_HOST": "mail.example.com", + "ALPHONE_SMTP_PORT": "2525", + "ALPHONE_SMTP_USERNAME": "crm", + "ALPHONE_SMTP_PASSWORD": "correct horse battery", + "ALPHONE_SMTP_FROM": "crm@example.com", + "ALPHONE_SMTP_TLS": "opportunistic", + "ALPHONE_PUBLIC_URL": "https://crm.example.com", + "ALPHONE_PRIVACY_URL": "https://example.com/legal/privacy", + "ALPHONE_TERMS_URL": "https://example.com/legal/terms", + "ALPHONE_MAIL_TEMPLATE_DIR": "/srv/alphone/mail", + "ALPHONE_INVITE_TTL": "24h", + "ALPHONE_INVITES_PER_INVITER": "12", + "ALPHONE_INVITES_PER_TENANT": "30", + "ALPHONE_INVITE_RESENDS_PER_INVITER": "6", + "ALPHONE_INVITE_RESENDS_PER_TENANT": "15", + "ALPHONE_INVITE_LIMIT_WINDOW": "12h", + "ALPHONE_RESET_TTL": "30m", + "ALPHONE_RESET_ATTEMPTS": "5", + "ALPHONE_RESET_LINKS": "4", + "ALPHONE_RESET_COOLDOWN": "2m", + "ALPHONE_GRAPH_PAGE_SIZE": "25", + "ALPHONE_GRAPH_PAGE_CAP": "400", + "ALPHONE_GRAPH_OPERATIONS_PER_USER": "12", + "ALPHONE_GRAPH_OPERATION_TIMEOUT": "45s", + "ALPHONE_GRAPH_BODY_MAX_BYTES": "524288", + "ALPHONE_GRAPH_UPLOAD_MAX_BYTES": "3145728", + "ALPHONE_GRAPH_RETRY_AFTER": "2s", + "ALPHONE_GRAPH_ANONYMOUS_MAX_BYTES": "8192", + "ALPHONE_GRAPH_ANONYMOUS_PER_IP": "3", + "ALPHONE_GRAPH_ANONYMOUS_CEILING": "12", + "ALPHONE_GRAPH_ANONYMOUS_MAX_TOKENS": "48", + "ALPHONE_GRAPH_ANONYMOUS_QUERY_MAX_BYTES": "768", + "ALPHONE_GRAPH_ANONYMOUS_ANSWER_MAX_BYTES": "12288", + "ALPHONE_STREAMS_PER_USER": "4", + "ALPHONE_STREAM_LIFETIME": "3m", + "ALPHONE_TOAST_DURATION": "9s", + "ALPHONE_TOAST_ACTION_DURATION": "14s", + "ALPHONE_DIALOG_WRITE_TIMEOUT": "45s", + "ALPHONE_LIST_PAGE_SIZES": "5,15,30", + "ALPHONE_LIST_PAGE_SIZE": "15", + "ALPHONE_FORMAT_LOCALE": "de-DE", + "ALPHONE_PLUGIN_SCREENS_BUDGET": "250ms", + "ALPHONE_PLUGIN_HOOK_TIMED_FIRINGS": "40", + "ALPHONE_HTTP_READ_HEADER_TIMEOUT": "5s", + "ALPHONE_HTTP_READ_TIMEOUT": "20s", + "ALPHONE_HTTP_IDLE_TIMEOUT": "90s", + "ALPHONE_SHUTDOWN_GRACE": "15s", + "ALPHONE_SHUTDOWN_CANCEL_GRACE": "3s", + "ALPHONE_SHUTDOWN_STOP_GRACE": "4s", + "ALPHONE_STORAGE_DRIVER": "s3", + "ALPHONE_STORAGE_MAX_BYTES": "1048576", + "ALPHONE_STORAGE_CHUNK_BYTES": "65536", + "ALPHONE_STORAGE_CLEANUP_TIMEOUT": "3s", + "ALPHONE_STORAGE_SWEEP_INTERVAL": "15m", + "ALPHONE_STORAGE_SWEEP_AGE": "6h", + "ALPHONE_STORAGE_SWEEP_BATCH": "250", + "ALPHONE_STORAGE_S3_ENDPOINT": "https://files.example.com", + "ALPHONE_STORAGE_S3_REGION": "garage", + "ALPHONE_STORAGE_S3_BUCKET": "example-files", + "ALPHONE_STORAGE_S3_ACCESS_KEY_ID": "GKexample", + "ALPHONE_STORAGE_S3_SECRET_ACCESS_KEY": "example-secret", + "ALPHONE_STORAGE_S3_PATH_STYLE": "true", + "ALPHONE_STORAGE_S3_CHECKSUM": "when_required", + "ALPHONE_ENCRYPTION_KEY": currentEncryptionKey, + "ALPHONE_ENCRYPTION_PREVIOUS_KEYS": olderEncryptionKey, } // settingsReadElsewhere names the example file settings that gonsole, a command or the Go tests read, not the server. @@ -627,6 +636,29 @@ func TestTheExampleFileStatesTheCommandFallbacks(t *testing.T) { } } +func TestTheExampleFileStatesTheInvitationLimitDefaults(t *testing.T) { + t.Parallel() + + exampleValues := exampleSettings(t) + defaults := map[string]string{ + "ALPHONE_INVITES_PER_INVITER": strconv.Itoa(defaultInvitesPerInviter), + "ALPHONE_INVITES_PER_TENANT": strconv.Itoa(defaultInvitesPerTenant), + "ALPHONE_INVITE_RESENDS_PER_INVITER": strconv.Itoa(defaultInviteResendsPerInviter), + "ALPHONE_INVITE_RESENDS_PER_TENANT": strconv.Itoa(defaultInviteResendsPerTenant), + } + + for key, want := range defaults { + if exampleValues[key] != want { + t.Errorf("the example file states %s=%q, want the default %q", key, exampleValues[key], want) + } + } + window, err := time.ParseDuration(exampleValues["ALPHONE_INVITE_LIMIT_WINDOW"]) + if err != nil || window != defaultInviteLimitWindow { + t.Errorf("the example file states ALPHONE_INVITE_LIMIT_WINDOW=%q, want the default %v", + exampleValues["ALPHONE_INVITE_LIMIT_WINDOW"], defaultInviteLimitWindow) + } +} + func TestABadEncryptionKeyIsNamedWithoutShowingIt(t *testing.T) { t.Parallel() @@ -738,6 +770,12 @@ func TestSettingRefusalsNameTheSettingAndTheReason(t *testing.T) { "a match past a query row bound": { "ALPHONE_CONTACT_MATCH_MAX", "2147483648", "must stand at or below 2147483647", }, + "invitations per inviter in words": {"ALPHONE_INVITES_PER_INVITER", "many", "must be a whole number"}, + "no invitations per tenant": {"ALPHONE_INVITES_PER_TENANT", "0", "must stand above zero"}, + "resends per inviter in words": {"ALPHONE_INVITE_RESENDS_PER_INVITER", "a few", "must be a whole number"}, + "no resends per tenant": {"ALPHONE_INVITE_RESENDS_PER_TENANT", "0", "must stand above zero"}, + "a limit window in words": {"ALPHONE_INVITE_LIMIT_WINDOW", "a day", "must be a duration like 30s"}, + "no limit window": {"ALPHONE_INVITE_LIMIT_WINDOW", "0s", "must stand above zero"}, } for testName, tt := range tests { t.Run(testName, func(t *testing.T) { From b5da980677a46e8e3fe2738434f9d77af2ebbade Mon Sep 17 00:00:00 2001 From: SirLouen Date: Mon, 30 Nov 2026 18:18:35 +0100 Subject: [PATCH 6/9] test(features): pin the invitation and resend limits in a feature --- .../features/invitation-limits.feature | 52 +++++ test/features/features_test.go | 9 + test/features/steps_invitation_limits_test.go | 184 ++++++++++++++++++ test/features/world_test.go | 2 + 4 files changed, 247 insertions(+) create mode 100644 test/features/features/invitation-limits.feature create mode 100644 test/features/steps_invitation_limits_test.go diff --git a/test/features/features/invitation-limits.feature b/test/features/features/invitation-limits.feature new file mode 100644 index 00000000..c1fecd92 --- /dev/null +++ b/test/features/features/invitation-limits.feature @@ -0,0 +1,52 @@ +Feature: Invitations and resends stop at their limits + Each inviting account and each workspace may send only so many + invitations and so many resends in one window. Invitations and resends + are counted apart, and a call past a limit is rejected before anything + is written or mailed, with the same answer for every address. + + Background: + Given a running AlphOne holding an admin and a mail relay + And invitations are limited to 2 per account and 3 per workspace + And resends are limited to 1 per account and 2 per workspace + + Scenario: An invitation past the account limit is rejected + Given the admin invited "first@example.com" as "Maria Perez" + And the admin invited "second@example.com" as "Maria Perez" + When the admin invites "past-the-limit@example.com" as "Maria Perez" + Then the call is rejected as past the invitation limit + And the relay holds 2 mails + And no account answers to "past-the-limit@example.com" + + Scenario: Resends keep their own count + Given the admin invited "first@example.com" as "Maria Perez" + And the admin invited "second@example.com" as "Maria Perez" + When the admin resends the invitation to "first@example.com" + Then the resend answers delivered + And the relay holds 3 mails + When the admin resends the invitation to "second@example.com" + Then the call is rejected as past the invitation limit + And the relay holds 3 mails + + Scenario: A second admin of the same workspace stops at the workspace limit + Given the admin invited "first@example.com" as "Maria Perez" + And the admin invited "second@example.com" as "Maria Perez" + And a second admin stands in the same workspace + And the second admin invited "third@example.com" as "Maria Perez" + When the second admin invites "past-the-limit@example.com" as "Maria Perez" + Then the call is rejected as past the invitation limit + And the relay holds 3 mails + And no account answers to "past-the-limit@example.com" + + Scenario Outline: Past the limit every address gets the same rejection + Given the admin invited "activated@example.com" as "Maria Perez" + And the invited person activated with the password "correct horse battery" + And the admin invited "pending@example.com" as "Maria Perez" + When the admin invites "
" as "Maria Perez" + Then the call is rejected as past the invitation limit + And the relay holds 2 mails + + Examples: + | address | + | unknown@example.com | + | pending@example.com | + | activated@example.com | diff --git a/test/features/features_test.go b/test/features/features_test.go index e093b0cc..32e4168a 100644 --- a/test/features/features_test.go +++ b/test/features/features_test.go @@ -196,6 +196,11 @@ func initializeMail(t *testing.T) func(*godog.ScenarioContext) { return func(sc *godog.ScenarioContext) { registerMailSteps(sc, t) } } +// initializeInvitationLimits registers the invitation limit steps beside the mail ones. +func initializeInvitationLimits(t *testing.T) func(*godog.ScenarioContext) { + return func(sc *godog.ScenarioContext) { registerInvitationLimitSteps(sc, t) } +} + // initializeIdentityFeed registers the identity feed steps beside the tenant ones. func initializeIdentityFeed(t *testing.T) func(*godog.ScenarioContext) { return func(sc *godog.ScenarioContext) { @@ -303,6 +308,10 @@ func TestMail(t *testing.T) { runFeature(t, "features/mail.feature", initializeMail(t)) } +func TestInvitationLimits(t *testing.T) { + runFeature(t, "features/invitation-limits.feature", initializeInvitationLimits(t)) +} + func TestContactPage(t *testing.T) { runFeature(t, "features/contact-page.feature", initializeContactPage(t)) } diff --git a/test/features/steps_invitation_limits_test.go b/test/features/steps_invitation_limits_test.go new file mode 100644 index 00000000..7a1a9f4c --- /dev/null +++ b/test/features/steps_invitation_limits_test.go @@ -0,0 +1,184 @@ +// SPDX-License-Identifier: Elastic-2.0 + +package features_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "testing" + "time" + + "github.com/cucumber/godog" + "github.com/gopherium/gouncer" + "github.com/gopherium/gouncer/authkit" + "github.com/gopherium/gouncer/authkit/ratelimit" + + "github.com/gopherium/alphone/internal/role" +) + +// secondAdminEmail addresses the admin who shares the owner's workspace. +const secondAdminEmail = "second.admin@example.com" + +// scenarioLimitWindow is the window every invitation and resend limit of a scenario counts over. +const scenarioLimitWindow = 24 * time.Hour + +// invitationLimitMessage is the message a call past an invitation or resend limit answers. +const invitationLimitMessage = "the invitation limit is reached, try again later" + +// resendAnswer is the answer a resend carries. +type resendAnswer struct { + Data struct { + ResendInvite struct { + Delivered bool `json:"delivered"` + } `json:"resendInvite"` + } `json:"data"` +} + +// limitRejection is the answer a call past a limit carries. +type limitRejection struct { + Errors []struct { + Message string `json:"message"` + Extensions struct { + Code string `json:"code"` + Reason string `json:"reason"` + RetryAfter int `json:"retryAfter"` + Meta struct { + RetryAfter int `json:"retryAfter"` + } `json:"meta"` + } `json:"extensions"` + } `json:"errors"` +} + +// setLimiters sets the per account and per workspace limiters of invitations or resends on the world's resolver. +func (w *world) setLimiters(callKind string, perAccount, perWorkspace int) { + perInviter := ratelimit.NewLimiter(ratelimit.Config{Limit: perAccount, Window: scenarioLimitWindow}) + perTenant := ratelimit.NewLimiter(ratelimit.Config{Limit: perWorkspace, Window: scenarioLimitWindow}) + if callKind == "resends" { + w.graph.ResendLimiterPerInviter, w.graph.ResendLimiterPerTenant = perInviter, perTenant + return + } + w.graph.InvitationLimiterPerInviter, w.graph.InvitationLimiterPerTenant = perInviter, perTenant +} + +// addSecondAdmin stores an admin beside the owner, in the same workspace, and keeps its session. +func (w *world) addSecondAdmin(ctx context.Context) error { + if _, err := authkit.EnsureAdmin( + ctx, w.users, secondAdminEmail, ownerName, ownerPassword, role.Admin.String(), + ); err != nil { + return fmt.Errorf("seeding the second admin: %w", err) + } + return w.signInAs(ctx, secondAdminEmail, &w.secondAdminSessionCookie) +} + +// inviteAsSecondAdmin asks the second admin's session to invite one address. +func (w *world) inviteAsSecondAdmin(ctx context.Context, email, name string) error { + if w.secondAdminSessionCookie == "" { + return errors.New("no second admin stands in the workspace") + } + return w.postGraphWithCookie(ctx, w.secondAdminSessionCookie, fmt.Sprintf( + `{"query":"mutation { invite(email: \"%s\", name: \"%s\") { delivered } }"}`, email, name)) +} + +// resendAsAdmin asks the admin's session to resend the invitation of one address. +func (w *world) resendAsAdmin(ctx context.Context, email string) error { + return w.postGraphAsSession(ctx, fmt.Sprintf( + `{"query":"mutation { resendInvite(email: \"%s\") { delivered } }"}`, email)) +} + +// checkInvitationLimitRejection checks that the last call was rejected as past an invitation or resend limit. +func (w *world) checkInvitationLimitRejection() error { + var rejection limitRejection + if err := json.Unmarshal(w.answered, &rejection); err != nil { + return fmt.Errorf("decoding the rejection: %w", err) + } + if len(rejection.Errors) == 0 { + return fmt.Errorf("the call was not rejected: %s", w.answered) + } + firstError := rejection.Errors[0] + retryAfterSeconds := int((2 * scenarioLimitWindow).Seconds()) + if firstError.Message != invitationLimitMessage || firstError.Extensions.Code != "RATE_LIMITED" || + firstError.Extensions.Reason != "invitation_limit_reached" || + firstError.Extensions.RetryAfter != retryAfterSeconds || + firstError.Extensions.Meta.RetryAfter != retryAfterSeconds { + return fmt.Errorf("the rejection is %s, want RATE_LIMITED invitation_limit_reached waiting %ds", + w.answered, retryAfterSeconds) + } + return nil +} + +// checkResendDelivered checks that the last resend answered delivered. +func (w *world) checkResendDelivered() error { + var answer resendAnswer + if err := json.Unmarshal(w.answered, &answer); err != nil { + return fmt.Errorf("decoding the resend: %w", err) + } + if !answer.Data.ResendInvite.Delivered { + return fmt.Errorf("the resend was not delivered: %s", w.answered) + } + return nil +} + +// checkRelayHolds checks that the relay received exactly count mails. +func (w *world) checkRelayHolds(count int) error { + if _, err := w.relay.WaitForMessages(count, 5*time.Second); err != nil { + return fmt.Errorf("waiting for %d mails: %w", count, err) + } + if mailCount := len(w.relay.Messages()); mailCount != count { + return fmt.Errorf("the relay holds %d mails, want %d", mailCount, count) + } + return nil +} + +// checkAddressHasNoAccount checks that no account is stored under the address. +func (w *world) checkAddressHasNoAccount(ctx context.Context, email string) error { + _, err := w.users.UserByEmail(ctx, email) + if errors.Is(err, gouncer.ErrUserNotFound) { + return nil + } + if err != nil { + return fmt.Errorf("reading the account behind %s: %w", email, err) + } + return fmt.Errorf("an account answers to %s, want none", email) +} + +// registerInvitationLimitSteps binds the invitation limit steps beside the mail ones. +func registerInvitationLimitSteps(sc *godog.ScenarioContext, t *testing.T) { + registerMailSteps(sc, t) + + sc.Given(`^(invitations|resends) are limited to (\d+) per account and (\d+) per workspace$`, + func(ctx context.Context, callKind string, perAccount, perWorkspace int) error { + worldFrom(ctx).setLimiters(callKind, perAccount, perWorkspace) + return nil + }) + + sc.Given(`^a second admin stands in the same workspace$`, func(ctx context.Context) error { + return worldFrom(ctx).addSecondAdmin(ctx) + }) + + sc.Step(`^the second admin invite[sd] "([^"]*)" as "([^"]*)"$`, + func(ctx context.Context, email, name string) error { + return worldFrom(ctx).inviteAsSecondAdmin(ctx, email, name) + }) + + sc.When(`^the admin resends the invitation to "([^"]*)"$`, func(ctx context.Context, email string) error { + return worldFrom(ctx).resendAsAdmin(ctx, email) + }) + + sc.Then(`^the call is rejected as past the invitation limit$`, func(ctx context.Context) error { + return worldFrom(ctx).checkInvitationLimitRejection() + }) + + sc.Then(`^the resend answers delivered$`, func(ctx context.Context) error { + return worldFrom(ctx).checkResendDelivered() + }) + + sc.Then(`^the relay holds (\d+) mails$`, func(ctx context.Context, count int) error { + return worldFrom(ctx).checkRelayHolds(count) + }) + + sc.Then(`^no account answers to "([^"]*)"$`, func(ctx context.Context, email string) error { + return worldFrom(ctx).checkAddressHasNoAccount(ctx, email) + }) +} diff --git a/test/features/world_test.go b/test/features/world_test.go index 57812e64..c554bc38 100644 --- a/test/features/world_test.go +++ b/test/features/world_test.go @@ -100,6 +100,8 @@ type world struct { entryField string reader *feedReader down *teardown + + secondAdminSessionCookie string } // teardown holds what one world releases, once, when its scenario ends or else when its test does. From 2b13804635aebad9e2d242218fd5c378ed311ef3 Mon Sep 17 00:00:00 2001 From: SirLouen Date: Mon, 30 Nov 2026 18:18:35 +0100 Subject: [PATCH 7/9] docs(self-hosting): document the invitation and resend limits --- .../content/docs/self-hosting/configuration.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/src/content/docs/self-hosting/configuration.md b/docs/src/content/docs/self-hosting/configuration.md index 8e600091..029399f2 100644 --- a/docs/src/content/docs/self-hosting/configuration.md +++ b/docs/src/content/docs/self-hosting/configuration.md @@ -80,9 +80,22 @@ back to. A duration is written like `1h` or `30m` and must be above zero. A count must be a whole number above zero. +`invite` counts against the two invitation limits and `resendInvite` +against the two resend limits, one for the account that calls it and one +for its workspace. A call past either of its two limits is rejected as +rate limited before anything is written or mailed, and it does not +count. A call counts also when it sends no mail, such as a resend for an +address that has no pending invitation. Without `ALPHONE_SMTP_HOST` +nothing counts. + | Variable | Purpose | | --- | --- | | `ALPHONE_INVITE_TTL` | How long the activation link of an invitation lives. Defaults to `168h`, seven days. | +| `ALPHONE_INVITES_PER_INVITER` | How many `invite` calls one account may make within `ALPHONE_INVITE_LIMIT_WINDOW`. Defaults to 10. A call made with an API token counts for the account that owns the token. An `invite` for an address that already has an account counts once, also when it sends the link again. | +| `ALPHONE_INVITES_PER_TENANT` | How many `invite` calls all the accounts of one workspace may make together within `ALPHONE_INVITE_LIMIT_WINDOW`. Defaults to 20. On an install with only one workspace, this is the limit for the whole install. | +| `ALPHONE_INVITE_RESENDS_PER_INVITER` | How many `resendInvite` calls one account may make within `ALPHONE_INVITE_LIMIT_WINDOW`. Defaults to 5. Resends count apart from invitations, so an account that used up its invitations can still resend. A call made with an API token counts for the account that owns the token. | +| `ALPHONE_INVITE_RESENDS_PER_TENANT` | How many `resendInvite` calls all the accounts of one workspace may make together within `ALPHONE_INVITE_LIMIT_WINDOW`. Defaults to 10. On an install with only one workspace, this is the limit for the whole install. | +| `ALPHONE_INVITE_LIMIT_WINDOW` | The time the four invitation and resend counts run over. Defaults to `24h`. The counts run in steps of one window, and with `24h` each step is a day that starts at midnight UTC. The count of the step before fades out over the current step, so around the turn of a step up to about twice a limit can pass within one window. A rejected call answers `retryAfter` in seconds. It is the longest wait, twice the window, so a call can pass sooner. The counts live in the memory of each server process, so a restart starts them again. Each process counts alone, so a deployment that runs more than one process, even for a short time during a rollout, lets more calls through. | | `ALPHONE_RESET_TTL` | How long a password reset link lives. Defaults to `1h`. | | `ALPHONE_RESET_ATTEMPTS` | How many reset requests one client address may make within one reset link lifetime. Defaults to 3. A request over the limit is refused as rate limited. | | `ALPHONE_RESET_LINKS` | How many reset links one account may hold at once. Defaults to 3. Once it holds that many, a further request sends none until one is used or expires. | @@ -477,6 +490,11 @@ ignores them, and `alphone check` names a refused value. the argon2id hashing cost. Passwords must be at least 12 characters. Until multi-factor authentication ships, a long unique password is the account-side defense. +- **Invitation limits** stop `invite` and `resendInvite` at a count per + account and per workspace within a window. Over a limit they answer an + error whose `extensions.code` is `RATE_LIMITED` and whose + `extensions.reason` is `invitation_limit_reached`, see + [Invitations and password resets](#invitations-and-password-resets). - **The session cookie** is `HttpOnly`, `Secure`, `SameSite=Lax`, with the `__Host-` prefix. This is why [HTTPS is mandatory](/self-hosting/install/) in production. On top of the From 282ee3dda4ff58f1c657a10364958c960500de9a Mon Sep 17 00:00:00 2001 From: SirLouen Date: Mon, 30 Nov 2026 18:18:36 +0100 Subject: [PATCH 8/9] docs(reference): name the invitation limit reason and its rate limited answer --- docs/src/content/docs/reference/graphql-api.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/docs/src/content/docs/reference/graphql-api.md b/docs/src/content/docs/reference/graphql-api.md index 6049f8e7..3fc0c191 100644 --- a/docs/src/content/docs/reference/graphql-api.md +++ b/docs/src/content/docs/reference/graphql-api.md @@ -238,6 +238,15 @@ address, an account in another workspace, or an account whose role carries a capability the caller's role lacks. `invite` on an address that already has such an account answers the same. +`invite` and `resendInvite` each count toward their own limits, one for the +calling account and one for its workspace, see +[Invitations and password resets](/self-hosting/configuration/#invitations-and-password-resets). +`invite` counts once, also when it sends the link again to an address that +already has an account. A call past a limit is rejected before anything is +written or mailed, with code `RATE_LIMITED`, the reason +`invitation_limit_reached` and `retryAfter` in seconds. Past the limit the +answer is the same for every address. + ### Roles and scopes together A role narrows the user. A scope narrows what a token carries of that user's @@ -537,7 +546,7 @@ Every error carries a `code` in its `extensions`. | `VALIDATION` | The input was refused. `message` names the field or rule | | `NOT_FOUND` | The id names nothing | | `CONFLICT` | The write clashes with what is stored, such as an identity another contact holds, a full list, an account whose role changed after the check, or a mail too young to delete. For an identity, `ownerContactId` names the owner | -| `RATE_LIMITED` | Too many attempts. `retryAfter` is in seconds | +| `RATE_LIMITED` | Too many attempts, or too many invitations or resends. `retryAfter` is in seconds | | `COMPLEXITY_LIMIT_EXCEEDED` | The query asks for too much, see limits below | | `INTERNAL` | AlphOne failed. The message is deliberately bare | @@ -600,6 +609,7 @@ The reasons the core answers with: | `authentication_required` | | no usable credential | | `credentials_invalid` | | a login that did not match | | `rate_limited` | `retryAfter` | too many attempts | +| `invitation_limit_reached` | `retryAfter` | the account or its workspace made all the invitations or resends its [limit](/self-hosting/configuration/#invitations-and-password-resets) allows | | `scope_missing` | `scope` | the token lacks the area | | `capability_missing` | `scope`, `capability` | the role lacks the capability | | `contact_name_required` | | a contact needs a name | From bf5bf4ecb8b311bac5c1d9423c88721f6245100c Mon Sep 17 00:00:00 2001 From: SirLouen Date: Mon, 30 Nov 2026 18:37:11 +0100 Subject: [PATCH 9/9] fix(graphres): round a part second invitation wait up to a whole second --- internal/graphres/errors_internal_test.go | 24 +++++++++++++++++++++++ internal/graphres/invite.go | 3 ++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/internal/graphres/errors_internal_test.go b/internal/graphres/errors_internal_test.go index cfc07e52..c14b22ff 100644 --- a/internal/graphres/errors_internal_test.go +++ b/internal/graphres/errors_internal_test.go @@ -130,6 +130,30 @@ func TestTheInvitationLimitAnswersItsWaitInWholeSeconds(t *testing.T) { } } +func TestTheInvitationLimitRoundsAPartSecondWaitUp(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + retryAfter time.Duration + wantSeconds int + }{ + {"under one second", 200 * time.Millisecond, 1}, + {"one and a half seconds", 1500 * time.Millisecond, 2}, + {"whole seconds", 90 * time.Second, 90}, + } + for _, tc := range cases { + presented := PresentError(context.Background(), invitationLimitError(tc.retryAfter)) + meta, _ := presented.Extensions["meta"].(map[string]any) + if got := presented.Extensions["retryAfter"]; got != tc.wantSeconds { + t.Errorf("%s retryAfter = %v, want %d", tc.name, got, tc.wantSeconds) + } + if got := meta["retryAfter"]; got != tc.wantSeconds { + t.Errorf("%s meta retryAfter = %v, want %d", tc.name, got, tc.wantSeconds) + } + } +} + func TestAPluginErrorCarriesItsOwnReason(t *testing.T) { t.Parallel() diff --git a/internal/graphres/invite.go b/internal/graphres/invite.go index df22bc77..788bb635 100644 --- a/internal/graphres/invite.go +++ b/internal/graphres/invite.go @@ -6,6 +6,7 @@ import ( "context" "errors" "fmt" + "math" "strings" "time" @@ -31,7 +32,7 @@ var errInvitationLimitReached = errors.New("the invitation limit is reached, try // invitationLimitError returns the rejection a call past an invitation or resend limit answers, with its wait. func invitationLimitError(retryAfter time.Duration) error { - seconds := int(retryAfter.Seconds()) + seconds := int(math.Ceil(retryAfter.Seconds())) return sdk.GraphError{ Code: "RATE_LIMITED", Reason: "invitation_limit_reached",