Skip to content

PostgreSQL backup tool with Point-In-Time-Recovery and restore verification

FEATURE (users): Let administrators require an emailed code at password sign-in, so a leaked password alone no longer opens the instance

Rostislav Dugin21b3383f4ce7
diff --git a/README.md b/README.md
index ff60cca0..c2c55196 100644
--- a/README.md
+++ b/README.md
@@ -94,6 +94,7 @@ Databasus performs a real restore to confirm backups are usable, not just intact
- **Zero-trust storage**: Backups are encrypted and remain useless to attackers, so you can safely store them in shared storage like S3, Azure Blob Storage, etc.
- **Encryption for secrets**: Any sensitive data is encrypted and never exposed, even in logs or error messages
- **Read-only user**: Databasus uses a read-only user by default for backups and never stores anything that can modify your data
+- **Two-factor authentication**: Password sign-in can require a six-digit code emailed to the account. Sign-in through Google or GitHub keeps relying on the provider's own checks
### 👥 **Suitable for teams** <a href="https://databasus.com/access-management">(docs)</a>
@@ -276,6 +277,14 @@ docker exec -it databasus ./main --list-admins
The output names every administrator account with its email address, display name, creation date and active state, and marks the one the instance recognizes as its administrator. It prints no password material.
+If two-factor authentication is on and the mail server stops delivering the codes, nobody can sign in with a password. Switch the second factor off from the host:
+
+```bash
+docker exec -it databasus ./main --disable-2fa
+```
+
+The command reports what it changed, succeeds without complaint when the setting is already off, and records the change in the audit log.
+
### 💾 Backuping Databasus itself
After installation, it is also recommended to <a href="https://databasus.com/faq#backup-databasus">backup your Databasus itself</a> or, at least, to copy secret key used for encryption (30 seconds is needed). So you are able to restore from your encrypted backups if you lose access to the server with Databasus or it is corrupted.
diff --git a/assets/readme/README.es.md b/assets/readme/README.es.md
index 5c7f706a..e429b20e 100644
--- a/assets/readme/README.es.md
+++ b/assets/readme/README.es.md
@@ -94,6 +94,7 @@ Databasus ejecuta una restauración real para confirmar que las copias sirven, e
- **Almacenamiento de confianza cero**: las copias están cifradas y resultan inútiles para un atacante, así que puede guardarlas sin riesgo en almacenamientos compartidos como S3, Azure Blob Storage, etc.
- **Cifrado de los secretos**: todo dato sensible se cifra y nunca se expone, ni siquiera en los registros o en los mensajes de error
- **Usuario de solo lectura**: Databasus usa por defecto un usuario de solo lectura para los respaldos y nunca guarda nada que pueda modificar sus datos
+- **Autenticación de dos factores**: el inicio de sesión con contraseña puede exigir un código de seis dígitos enviado al correo de la cuenta. Entrar con Google o GitHub sigue apoyándose en las comprobaciones de esos proveedores
### 👥 **Adecuado para equipos** <a href="https://databasus.com/es/access-management/">(documentación)</a>
@@ -276,6 +277,14 @@ docker exec -it databasus ./main --list-admins
La salida nombra cada cuenta de administrador con su correo electrónico, nombre visible, fecha de creación y estado de actividad, y marca la que la instancia reconoce como su administrador. No imprime ninguna contraseña ni su hash.
+Si la autenticación de dos factores está activada y el servidor de correo deja de entregar los códigos, nadie puede entrar con contraseña. Desactive el segundo factor desde el propio servidor:
+
+```bash
+docker exec -it databasus ./main --disable-2fa
+```
+
+El comando informa de lo que ha cambiado, termina sin quejarse cuando el ajuste ya está desactivado y registra el cambio en el historial de auditoría.
+
### 💾 Respaldar el propio Databasus
Después de instalarlo, conviene también <a href="https://databasus.com/es/faq/#backup-databasus">respaldar su propio Databasus</a> o, al menos, copiar la clave secreta que se usa para el cifrado (bastan 30 segundos). Así podrá restaurar desde sus copias cifradas si pierde el acceso al servidor con Databasus o si este se corrompe.
diff --git a/assets/readme/README.fr.md b/assets/readme/README.fr.md
index 6967ea66..ca3ca0df 100644
--- a/assets/readme/README.fr.md
+++ b/assets/readme/README.fr.md
@@ -94,6 +94,7 @@ Databasus effectue une vraie restauration pour confirmer que les sauvegardes son
- **Stockage zero-trust** : les sauvegardes sont chiffrées et restent inutilisables pour un attaquant, vous pouvez donc les déposer sans risque sur un stockage partagé comme S3, Azure Blob Storage, etc.
- **Chiffrement des secrets** : toute donnée sensible est chiffrée et n'est jamais exposée, pas même dans les logs ou les messages d'erreur
- **Utilisateur en lecture seule** : par défaut, Databasus sauvegarde via un utilisateur en lecture seule et ne conserve rien qui permette de modifier vos données
+- **Authentification à deux facteurs** : la connexion par mot de passe peut exiger un code à six chiffres envoyé à l'adresse du compte. Se connecter par Google ou GitHub continue de s'appuyer sur les vérifications de ces fournisseurs
### 👥 **Adapté aux équipes** <a href="https://databasus.com/fr/access-management/">(docs)</a>
@@ -276,6 +277,14 @@ docker exec -it databasus ./main --list-admins
La sortie nomme chaque compte administrateur avec son adresse e-mail, son nom affiché, sa date de création et son état d'activité, et marque celui que l'instance reconnaît comme son administrateur. Aucun mot de passe ni empreinte de mot de passe n'est affiché.
+Si l'authentification à deux facteurs est activée et que le serveur de messagerie cesse de délivrer les codes, plus personne n'entre avec un mot de passe. Désactivez le second facteur depuis le serveur :
+
+```bash
+docker exec -it databasus ./main --disable-2fa
+```
+
+La commande indique ce qu'elle a changé, se termine sans se plaindre quand le réglage est déjà désactivé, et inscrit le changement au journal d'audit.
+
### 💾 Sauvegarder Databasus lui-même
Après l'installation, il est aussi recommandé de <a href="https://databasus.com/fr/faq/#backup-databasus">sauvegarder Databasus lui-même</a> ou, au minimum, de copier la clé secrète utilisée pour le chiffrement (30 secondes suffisent). Vous pourrez ainsi restaurer vos sauvegardes chiffrées si vous perdez l'accès au serveur qui héberge Databasus ou s'il est corrompu.
diff --git a/assets/readme/README.pt.md b/assets/readme/README.pt.md
index da52e4c2..504ad27f 100644
--- a/assets/readme/README.pt.md
+++ b/assets/readme/README.pt.md
@@ -94,6 +94,7 @@ O Databasus faz uma restauração de verdade para confirmar que os backups serve
- **Armazenamento zero-trust**: os backups são criptografados e continuam inúteis para um atacante, então você pode guardá-los com segurança em armazenamentos compartilhados como S3, Azure Blob Storage, etc.
- **Criptografia de segredos**: qualquer dado sensível é criptografado e nunca fica exposto, nem em logs nem em mensagens de erro
- **Usuário somente leitura**: por padrão, o Databasus usa um usuário somente leitura para os backups e nunca guarda nada capaz de alterar os seus dados
+- **Autenticação de dois fatores**: o login por senha pode exigir um código de seis dígitos enviado ao e-mail da conta. Entrar pelo Google ou pelo GitHub continua contando com as verificações desses provedores
### 👥 **Adequado para equipes** <a href="https://databasus.com/pt/access-management/">(docs)</a>
@@ -276,6 +277,14 @@ docker exec -it databasus ./main --list-admins
A saída nomeia cada conta de administrador com seu e-mail, nome de exibição, data de criação e estado de atividade, e marca aquela que a instância reconhece como seu administrador. Nenhuma senha ou hash de senha é impresso.
+Se a autenticação de dois fatores estiver ligada e o servidor de e-mail parar de entregar os códigos, ninguém consegue entrar com senha. Desligue o segundo fator direto no servidor:
+
+```bash
+docker exec -it databasus ./main --disable-2fa
+```
+
+O comando informa o que mudou, termina sem reclamar quando a opção já está desligada e registra a mudança no log de auditoria.
+
### 💾 Fazer backup do próprio Databasus
Depois de instalar, também é recomendável <a href="https://databasus.com/pt/faq/#backup-databasus">fazer backup do próprio Databasus</a> ou, no mínimo, copiar a chave secreta usada na criptografia (leva 30 segundos). Assim você consegue restaurar a partir dos seus backups criptografados se perder o acesso ao servidor com o Databasus ou se ele for corrompido.
diff --git a/assets/readme/README.ru.md b/assets/readme/README.ru.md
index 63c0ced6..0cc70379 100644
--- a/assets/readme/README.ru.md
+++ b/assets/readme/README.ru.md
@@ -94,6 +94,7 @@ Databasus по-настоящему восстанавливает бекап,
- **Хранилище с нулевым доверием**: бекапы зашифрованы и бесполезны для злоумышленника, поэтому их можно спокойно держать в общих хранилищах вроде S3, Azure Blob Storage и других
- **Шифрование секретов**: любые чувствительные данные шифруются и никогда не раскрываются, даже в логах и сообщениях об ошибках
- **Доступ только на чтение**: по умолчанию Databasus работает под read-only пользователем и не хранит ничего, что позволило бы изменить ваши данные
+- **Двухфакторная аутентификация**: вход по паролю можно закрыть шестизначным кодом, который приходит на почту аккаунта. Вход через Google или GitHub по-прежнему опирается на проверки самих провайдеров
### 👥 **Подходит командам** <a href="https://databasus.com/ru/access-management/">(документация)</a>
@@ -276,6 +277,14 @@ docker exec -it databasus ./main --list-admins
В выводе перечислены все учетные записи администраторов с их email, именем, датой создания и состоянием активности, а та, которую инстанс считает своим администратором, отмечена отдельно. Пароли и их хеши не выводятся.
+Если включена двухфакторная аутентификация, а почтовый сервер перестал доставлять коды, по паролю не войдет никто. Выключите второй фактор прямо на сервере:
+
+```bash
+docker exec -it databasus ./main --disable-2fa
+```
+
+Команда сообщает, что изменила, спокойно отрабатывает, если настройка уже выключена, и записывает изменение в журнал аудита.
+
### 💾 Бекап самого Databasus
После установки стоит еще и <a href="https://databasus.com/ru/faq/#backup-databasus">забекапить сам Databasus</a> или, как минимум, скопировать секретный ключ шифрования (это займет 30 секунд). Тогда вы сможете восстановиться из своих зашифрованных бекапов, даже если потеряете доступ к серверу с Databasus или он выйдет из строя.
diff --git a/assets/readme/README.zh.md b/assets/readme/README.zh.md
index c490d1b7..685a29ee 100644
--- a/assets/readme/README.zh.md
+++ b/assets/readme/README.zh.md
@@ -94,6 +94,7 @@ Databasus 会真正执行一次恢复,确认备份可用,而不只是检查
- **零信任存储**:备份是加密的,落到攻击者手里也毫无用处,因此可以放心存在 S3 之类的共享存储中
- **密钥与凭据加密**:任何敏感数据都会加密,绝不外泄,日志和错误信息里也看不到
- **只读用户**:Databasus 默认使用只读用户来备份,不会保存任何能修改你数据的东西
+- **双因素验证**:密码登录可以额外要求发送到账号邮箱的六位验证码。通过 Google 或 GitHub 登录仍然依赖这些服务商自己的验证
### 👥 **适合团队** <a href="https://databasus.com/zh/access-management/">(文档)</a>
@@ -276,6 +277,14 @@ docker exec -it databasus ./main --list-admins
输出会列出每个管理员账户的邮箱、显示名称、创建日期和活动状态,并标记实例所认可的管理员。不会输出任何密码或密码哈希。
+如果开启了双因素验证,而邮件服务器不再送达验证码,谁都无法用密码登录。请直接在服务器上关掉第二重验证:
+
+```bash
+docker exec -it databasus ./main --disable-2fa
+```
+
+命令会说明它改了什么,设置本来就关着时也会正常结束,并把这次改动写入审计日志。
+
### 💾 给 Databasus 自身做备份
装好之后,建议再<a href="https://databasus.com/zh/faq/#backup-databasus">给 Databasus 自身做一次备份</a>,至少也要把用于加密的密钥复制一份(只要 30 秒)。这样即使装有 Databasus 的服务器丢失访问权限或者损坏,你依然能从加密备份中恢复。
diff --git a/backend/cmd/main.go b/backend/cmd/main.go
index 34ba2ddc..25178134 100644
--- a/backend/cmd/main.go
+++ b/backend/cmd/main.go
@@ -110,6 +110,8 @@ func main() {
resetPasswordIfRequested(ctx, log, commandLineOptions)
+ disableTwoFactorAuthIfRequested(ctx, log, commandLineOptions)
+
go generateSwaggerDocs(log)
gin.SetMode(gin.ReleaseMode)
@@ -142,10 +144,11 @@ func main() {
}
type commandLineOptions struct {
- shouldTestStorage bool
- shouldListAdmins bool
- newPassword string
- passwordResetEmail string
+ shouldTestStorage bool
+ shouldListAdmins bool
+ shouldDisableTwoFactor bool
+ newPassword string
+ passwordResetEmail string
}
func parseCommandLineOptions() commandLineOptions {
@@ -155,15 +158,23 @@ func parseCommandLineOptions() commandLineOptions {
"Save and delete a local storage probe",
)
shouldListAdmins := flag.Bool("list-admins", false, "Print every administrator account of this instance")
+ // The name carries a digit, unlike every other flag here, because it is the
+ // term an owner locked out by a dead mail server searches for.
+ shouldDisableTwoFactor := flag.Bool(
+ "disable-2fa",
+ false,
+ "Stop requiring an emailed code at sign-in",
+ )
newPassword := flag.String("new-password", "", "Set a new password for the user")
passwordResetEmail := flag.String("email", "", "Email of the user to reset password")
flag.Parse()
return commandLineOptions{
- shouldTestStorage: *shouldTestStorage,
- shouldListAdmins: *shouldListAdmins,
- newPassword: *newPassword,
- passwordResetEmail: *passwordResetEmail,
+ shouldTestStorage: *shouldTestStorage,
+ shouldListAdmins: *shouldListAdmins,
+ shouldDisableTwoFactor: *shouldDisableTwoFactor,
+ newPassword: *newPassword,
+ passwordResetEmail: *passwordResetEmail,
}
}
@@ -192,6 +203,32 @@ func listAdminsIfRequested(
logger.ExitAfterFlush(0)
}
+func disableTwoFactorAuthIfRequested(
+ ctx context.Context,
+ log *slog.Logger,
+ commandLineOptions commandLineOptions,
+) {
+ if !commandLineOptions.shouldDisableTwoFactor {
+ return
+ }
+
+ audit_logs.SetupDependencies()
+
+ isChanged, err := users_services.GetSettingsService().DisableTwoFactorAuth(ctx)
+ if err != nil {
+ log.ErrorContext(ctx, "failed to switch the second factor off", "error", err)
+ logger.ExitAfterFlush(1)
+ }
+
+ if isChanged {
+ fmt.Println("Two-factor authentication is now off. The next password sign-in needs no code.")
+ } else {
+ fmt.Println("Two-factor authentication was already off. Nothing changed.")
+ }
+
+ logger.ExitAfterFlush(0)
+}
+
func resetPasswordIfRequested(
ctx context.Context,
log *slog.Logger,
@@ -408,6 +445,10 @@ func runBackgroundTasks(log *slog.Logger) {
storages.GetStorageFileDeletionWorker().Run(ctx)
})
+ go runWithPanicLogging(log, "sign-in code cleanup background service", func() {
+ users_services.GetSignInCodeBackgroundService().Run(ctx)
+ })
+
go runWithPanicLogging(log, "telemetry background service", func() {
telemetry.GetTelemetryBackgroundService().Run(ctx)
})
diff --git a/backend/internal/features/email/email.go b/backend/internal/features/email/email.go
index accc0de1..7c7c1a21 100644
--- a/backend/internal/features/email/email.go
+++ b/backend/internal/features/email/email.go
@@ -30,6 +30,10 @@ type EmailSMTPSender struct {
isConfigured bool
}
+func (s *EmailSMTPSender) IsConfigured() bool {
+ return s.isConfigured
+}
+
func (s *EmailSMTPSender) SendEmail(to, subject, body string) error {
if !s.isConfigured {
s.logger.Warn("Skipping email send, SMTP not initialized", "to", to, "subject", subject)
diff --git a/backend/internal/features/users/controllers/e2e_test.go b/backend/internal/features/users/controllers/e2e_test.go
index 73454b86..d47fca55 100644
--- a/backend/internal/features/users/controllers/e2e_test.go
+++ b/backend/internal/features/users/controllers/e2e_test.go
@@ -1,6 +1,7 @@
package users_controllers
import (
+ "context"
"net/http"
"testing"
@@ -9,6 +10,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
+ "databasus-backend/internal/features/email"
users_dto "databasus-backend/internal/features/users/dto"
users_enums "databasus-backend/internal/features/users/enums"
users_middleware "databasus-backend/internal/features/users/middleware"
@@ -203,6 +205,29 @@ func createSettingsTestRouter() *gin.Engine {
return router
}
+// A settings test that reads the mail-server answer has to own the sender the
+// answer comes from, because the wired one reports whatever the environment
+// running the suite happens to configure.
+func createSettingsTestRouterWithMailSender(
+ t *testing.T,
+ isMailServerMissing bool,
+) (*gin.Engine, *users_testing.MockEmailSender) {
+ router := createSettingsTestRouter()
+
+ mockEmailSender := users_testing.NewMockEmailSender()
+ mockEmailSender.IsMailServerMissing = isMailServerMissing
+ users_services.GetSettingsService().SetEmailSender(mockEmailSender)
+
+ // The services are process-global, so a mock left installed would decide
+ // what every later test in the package believes about the mail server.
+ t.Cleanup(func() {
+ users_services.GetSettingsService().SetEmailSender(email.GetEmailSMTPSender())
+ users_testing.ResetSettingsToDefaults(context.Background())
+ })
+
+ return router, mockEmailSender
+}
+
func createManagementTestRouter() *gin.Engine {
gin.SetMode(gin.TestMode)
router := gin.New()
diff --git a/backend/internal/features/users/controllers/settings_controller.go b/backend/internal/features/users/controllers/settings_controller.go
index 54961855..b75a2446 100644
--- a/backend/internal/features/users/controllers/settings_controller.go
+++ b/backend/internal/features/users/controllers/settings_controller.go
@@ -5,9 +5,9 @@ import (
"github.com/gin-gonic/gin"
+ users_dto "databasus-backend/internal/features/users/dto"
user_enums "databasus-backend/internal/features/users/enums"
user_middleware "databasus-backend/internal/features/users/middleware"
- user_models "databasus-backend/internal/features/users/models"
users_services "databasus-backend/internal/features/users/services"
)
@@ -30,13 +30,13 @@ func (c *SettingsController) RegisterRoutes(router *gin.RouterGroup) {
// @Tags settings
// @Produce json
// @Security BearerAuth
-// @Success 200 {object} users_models.UsersSettings
+// @Success 200 {object} users_dto.SettingsResponseDTO
// @Failure 401 {object} map[string]string "Unauthorized"
// @Failure 403 {object} map[string]string "Forbidden"
// @Failure 500 {object} map[string]string "Internal server error"
// @Router /users/settings [get]
func (c *SettingsController) GetUsersSettings(ctx *gin.Context) {
- settings, err := c.settingsService.GetSettings(ctx.Request.Context())
+ settings, err := c.settingsService.GetSettingsResponse(ctx.Request.Context())
if err != nil {
_ = ctx.Error(err)
@@ -54,8 +54,8 @@ func (c *SettingsController) GetUsersSettings(ctx *gin.Context) {
// @Accept json
// @Produce json
// @Security BearerAuth
-// @Param request body users_models.UsersSettings true "Settings update data"
-// @Success 200 {object} users_models.UsersSettings
+// @Param request body users_dto.UpdateSettingsRequestDTO true "Settings update data"
+// @Success 200 {object} users_dto.SettingsResponseDTO
// @Failure 400 {object} map[string]string "Bad request"
// @Failure 401 {object} map[string]string "Unauthorized"
// @Failure 403 {object} map[string]string "Forbidden"
@@ -67,7 +67,7 @@ func (c *SettingsController) UpdateUsersSettings(ctx *gin.Context) {
return
}
- var request user_models.UsersSettings
+ var request users_dto.UpdateSettingsRequestDTO
if err := ctx.ShouldBindJSON(&request); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request format"})
return
diff --git a/backend/internal/features/users/controllers/settings_controller_test.go b/backend/internal/features/users/controllers/settings_controller_test.go
index 8cbbc329..e05c7326 100644
--- a/backend/internal/features/users/controllers/settings_controller_test.go
+++ b/backend/internal/features/users/controllers/settings_controller_test.go
@@ -1,13 +1,18 @@
package users_controllers
import (
+ "context"
+ "encoding/json"
"net/http"
+ "strings"
"testing"
"github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ users_dto "databasus-backend/internal/features/users/dto"
users_enums "databasus-backend/internal/features/users/enums"
- users_models "databasus-backend/internal/features/users/models"
+ users_services "databasus-backend/internal/features/users/services"
users_testing "databasus-backend/internal/features/users/testing"
test_utils "databasus-backend/internal/util/testing"
)
@@ -19,7 +24,7 @@ func Test_GetUserSettings_WhenUserIsAdmin_ReturnsSettings(t *testing.T) {
// Create admin user and get token
testUser := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
- var response users_models.UsersSettings
+ var response users_dto.SettingsResponseDTO
test_utils.MakeGetRequestAndUnmarshal(
t,
router,
@@ -33,6 +38,10 @@ func Test_GetUserSettings_WhenUserIsAdmin_ReturnsSettings(t *testing.T) {
assert.True(t, response.IsAllowExternalRegistrations)
assert.True(t, response.IsAllowMemberInvitations)
assert.True(t, response.IsMemberAllowedToCreateWorkspaces)
+
+ // The second factor is the exception: an instance asks for one factor until
+ // an administrator says otherwise.
+ assert.False(t, response.IsTwoFactorAuthRequired)
}
func Test_GetUserSettings_WhenUserIsMember_ReturnsSettings(t *testing.T) {
@@ -66,13 +75,13 @@ func Test_UpdateUserSettings_WhenUserIsAdmin_SettingsUpdated(t *testing.T) {
testUser := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
// Update some settings
- request := users_models.UsersSettings{
+ request := users_dto.UpdateSettingsRequestDTO{
IsAllowExternalRegistrations: false,
IsAllowMemberInvitations: true,
IsMemberAllowedToCreateWorkspaces: false,
}
- var response users_models.UsersSettings
+ var response users_dto.SettingsResponseDTO
test_utils.MakePutRequestAndUnmarshal(
t,
router,
@@ -97,14 +106,14 @@ func Test_UpdateUserSettings_WithPartialData_SettingsUpdated(t *testing.T) {
testUser := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
// Update only one setting
- request := users_models.UsersSettings{
+ request := users_dto.UpdateSettingsRequestDTO{
IsAllowExternalRegistrations: false,
// Other fields will use default values
IsAllowMemberInvitations: true,
IsMemberAllowedToCreateWorkspaces: true,
}
- var response users_models.UsersSettings
+ var response users_dto.SettingsResponseDTO
test_utils.MakePutRequestAndUnmarshal(
t,
router,
@@ -129,7 +138,7 @@ func Test_UpdateUserSettings_WhenUserIsMember_ReturnsForbidden(t *testing.T) {
// Create member user and get token
testUser := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)
- request := users_models.UsersSettings{
+ request := users_dto.UpdateSettingsRequestDTO{
IsAllowExternalRegistrations: false,
}
@@ -167,7 +176,7 @@ func Test_UpdateUserSettings_WithoutAuth_ReturnsUnauthorized(t *testing.T) {
users_testing.ResetSettingsToDefaults(t.Context())
router := createSettingsTestRouter()
- request := users_models.UsersSettings{
+ request := users_dto.UpdateSettingsRequestDTO{
IsAllowExternalRegistrations: false,
}
@@ -180,3 +189,271 @@ func Test_UpdateUserSettings_WithoutAuth_ReturnsUnauthorized(t *testing.T) {
http.StatusUnauthorized,
)
}
+
+func Test_GetUserSettings_WhenMailServerIsConfigured_ReportsItConfigured(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ router, _ := createSettingsTestRouterWithMailSender(t, false)
+
+ admin := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
+
+ var response users_dto.SettingsResponseDTO
+ test_utils.MakeGetRequestAndUnmarshal(
+ t,
+ router,
+ "/api/v1/users/settings",
+ "Bearer "+admin.Token,
+ http.StatusOK,
+ &response,
+ )
+
+ assert.True(t, response.IsEmailConfigured)
+}
+
+func Test_GetUserSettings_WhenMailServerIsMissing_ReportsItUnconfigured(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ router, _ := createSettingsTestRouterWithMailSender(t, true)
+
+ admin := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
+
+ var response users_dto.SettingsResponseDTO
+ test_utils.MakeGetRequestAndUnmarshal(
+ t,
+ router,
+ "/api/v1/users/settings",
+ "Bearer "+admin.Token,
+ http.StatusOK,
+ &response,
+ )
+
+ assert.False(t, response.IsEmailConfigured)
+}
+
+func Test_UpdateUserSettings_WhenRequestCarriesTheDerivedField_StoredRowIsUntouched(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ router, _ := createSettingsTestRouterWithMailSender(t, true)
+
+ admin := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
+
+ response := test_utils.MakeRequest(t, router, test_utils.RequestOptions{
+ Method: "PUT",
+ URL: "/api/v1/users/settings",
+ Body: map[string]any{
+ "isAllowExternalRegistrations": true,
+ "isAllowMemberInvitations": true,
+ "isMemberAllowedToCreateWorkspaces": true,
+ "isTwoFactorAuthRequired": false,
+ "isEmailConfigured": true,
+ },
+ AuthToken: "Bearer " + admin.Token,
+ ExpectedStatus: http.StatusOK,
+ })
+
+ var updateResponse users_dto.SettingsResponseDTO
+ require.NoError(t, json.Unmarshal(response.Body, &updateResponse))
+ assert.False(t, updateResponse.IsEmailConfigured)
+
+ storedSettings, err := users_services.GetSettingsService().GetSettings(t.Context())
+ require.NoError(t, err)
+ assert.False(t, storedSettings.IsTwoFactorAuthRequired)
+}
+
+func Test_UpdateUserSettings_TurningTwoFactorOn_ReadsBackTheNewValue(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ router, _ := createSettingsTestRouterWithMailSender(t, false)
+ users_testing.DeleteAllUsers()
+
+ admin := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
+
+ var beforeUpdate users_dto.SettingsResponseDTO
+ test_utils.MakeGetRequestAndUnmarshal(
+ t,
+ router,
+ "/api/v1/users/settings",
+ "Bearer "+admin.Token,
+ http.StatusOK,
+ &beforeUpdate,
+ )
+ assert.False(t, beforeUpdate.IsTwoFactorAuthRequired)
+
+ var afterUpdate users_dto.SettingsResponseDTO
+ test_utils.MakePutRequestAndUnmarshal(
+ t,
+ router,
+ "/api/v1/users/settings",
+ "Bearer "+admin.Token,
+ enableTwoFactorRequest(),
+ http.StatusOK,
+ &afterUpdate,
+ )
+ assert.True(t, afterUpdate.IsTwoFactorAuthRequired)
+
+ var readBack users_dto.SettingsResponseDTO
+ test_utils.MakeGetRequestAndUnmarshal(
+ t,
+ router,
+ "/api/v1/users/settings",
+ "Bearer "+admin.Token,
+ http.StatusOK,
+ &readBack,
+ )
+ assert.True(t, readBack.IsTwoFactorAuthRequired)
+}
+
+func Test_UpdateUserSettings_WhenASwitchChanges_AuditLogCarriesItsOldAndNewValue(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ router, _ := createSettingsTestRouterWithMailSender(t, false)
+ users_testing.DeleteAllUsers()
+
+ admin := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
+ recorder := users_testing.GetAuditLogRecorder()
+
+ test_utils.MakePutRequest(
+ t,
+ router,
+ "/api/v1/users/settings",
+ "Bearer "+admin.Token,
+ users_dto.UpdateSettingsRequestDTO{
+ IsAllowExternalRegistrations: false,
+ IsAllowMemberInvitations: false,
+ IsMemberAllowedToCreateWorkspaces: false,
+ IsTwoFactorAuthRequired: true,
+ },
+ http.StatusOK,
+ )
+
+ expectedEntries := []string{
+ "isAllowExternalRegistrations: true -> false",
+ "isAllowMemberInvitations: true -> false",
+ "isMemberAllowedToCreateWorkspaces: true -> false",
+ "isTwoFactorAuthRequired: false -> true",
+ }
+
+ for _, expected := range expectedEntries {
+ assert.Equal(t, 1, countAuditEntries(recorder, expected), expected)
+ }
+}
+
+func Test_UpdateUserSettings_WhenNothingChanges_WritesNoAuditEntry(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ router, _ := createSettingsTestRouterWithMailSender(t, false)
+
+ admin := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
+ recorder := users_testing.GetAuditLogRecorder()
+
+ test_utils.MakePutRequest(
+ t,
+ router,
+ "/api/v1/users/settings",
+ "Bearer "+admin.Token,
+ users_dto.UpdateSettingsRequestDTO{
+ IsAllowExternalRegistrations: true,
+ IsAllowMemberInvitations: true,
+ IsMemberAllowedToCreateWorkspaces: true,
+ IsTwoFactorAuthRequired: false,
+ },
+ http.StatusOK,
+ )
+
+ assert.Equal(t, 0, countAuditEntries(recorder, "isTwoFactorAuthRequired"))
+ assert.Equal(t, 0, countAuditEntries(recorder, "isAllowExternalRegistrations"))
+}
+
+func Test_UpdateUserSettings_WhenMailServerIsMissing_RefusesToRequireTwoFactor(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ router, _ := createSettingsTestRouterWithMailSender(t, true)
+ users_testing.DeleteAllUsers()
+
+ admin := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
+
+ response := test_utils.MakePutRequest(
+ t,
+ router,
+ "/api/v1/users/settings",
+ "Bearer "+admin.Token,
+ enableTwoFactorRequest(),
+ http.StatusBadRequest,
+ )
+ assert.Contains(t, string(response.Body), "no mail server configured")
+
+ storedSettings, err := users_services.GetSettingsService().GetSettings(t.Context())
+ require.NoError(t, err)
+ assert.False(t, storedSettings.IsTwoFactorAuthRequired)
+}
+
+func Test_UpdateUserSettings_WhenAnAdminHasNoUsableAddress_RefusesAndNamesTheAccount(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ router, _ := createSettingsTestRouterWithMailSender(t, false)
+ users_testing.DeleteAllUsers()
+
+ admin := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
+ unreachableAdmin := users_testing.CreateTestUserWithEmail(
+ t.Context(),
+ users_enums.UserRoleAdmin,
+ "admin",
+ )
+ t.Cleanup(func() { users_testing.DeleteTestUser(context.Background(), unreachableAdmin.UserID) })
+
+ response := test_utils.MakePutRequest(
+ t,
+ router,
+ "/api/v1/users/settings",
+ "Bearer "+admin.Token,
+ enableTwoFactorRequest(),
+ http.StatusBadRequest,
+ )
+ assert.Contains(t, string(response.Body), "admin")
+ assert.Contains(t, string(response.Body), "no valid email address")
+
+ storedSettings, err := users_services.GetSettingsService().GetSettings(t.Context())
+ require.NoError(t, err)
+ assert.False(t, storedSettings.IsTwoFactorAuthRequired)
+}
+
+func Test_UpdateUserSettings_WhenAnInactiveAdminHasNoUsableAddress_StillAccepts(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ router, _ := createSettingsTestRouterWithMailSender(t, false)
+ users_testing.DeleteAllUsers()
+
+ admin := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
+ retiredAdmin := users_testing.CreateTestUserWithEmail(
+ t.Context(),
+ users_enums.UserRoleAdmin,
+ "retired-admin",
+ )
+ users_testing.DeactivateTestUser(t.Context(), retiredAdmin.UserID)
+ t.Cleanup(func() { users_testing.DeleteTestUser(context.Background(), retiredAdmin.UserID) })
+
+ var response users_dto.SettingsResponseDTO
+ test_utils.MakePutRequestAndUnmarshal(
+ t,
+ router,
+ "/api/v1/users/settings",
+ "Bearer "+admin.Token,
+ enableTwoFactorRequest(),
+ http.StatusOK,
+ &response,
+ )
+
+ assert.True(t, response.IsTwoFactorAuthRequired)
+}
+
+func enableTwoFactorRequest() users_dto.UpdateSettingsRequestDTO {
+ return users_dto.UpdateSettingsRequestDTO{
+ IsAllowExternalRegistrations: true,
+ IsAllowMemberInvitations: true,
+ IsMemberAllowedToCreateWorkspaces: true,
+ IsTwoFactorAuthRequired: true,
+ }
+}
+
+func countAuditEntries(recorder *users_testing.RecordingAuditLogWriter, fragment string) int {
+ count := 0
+
+ for _, entry := range recorder.GetEntries() {
+ if strings.Contains(entry.Message, fragment) {
+ count++
+ }
+ }
+
+ return count
+}
diff --git a/backend/internal/features/users/controllers/turnstile.go b/backend/internal/features/users/controllers/turnstile.go
new file mode 100644
index 00000000..e254a2eb
--- /dev/null
+++ b/backend/internal/features/users/controllers/turnstile.go
@@ -0,0 +1,31 @@
+package users_controllers
+
+import (
+ "net/http"
+
+ "github.com/gin-gonic/gin"
+
+ cloudflare_turnstile "databasus-backend/internal/util/cloudflare_turnstile"
+)
+
+func verifyTurnstileOrRespond(ctx *gin.Context, token *string) bool {
+ turnstileService := cloudflare_turnstile.GetCloudflareTurnstileService()
+ if !turnstileService.IsEnabled() {
+ return true
+ }
+
+ if token == nil || *token == "" {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Cloudflare Turnstile verification required"})
+
+ return false
+ }
+
+ isValid, err := turnstileService.VerifyToken(*token, ctx.ClientIP())
+ if err != nil || !isValid {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Cloudflare Turnstile verification failed"})
+
+ return false
+ }
+
+ return true
+}
diff --git a/backend/internal/features/users/controllers/two_factor_controller.go b/backend/internal/features/users/controllers/two_factor_controller.go
new file mode 100644
index 00000000..a4606f4b
--- /dev/null
+++ b/backend/internal/features/users/controllers/two_factor_controller.go
@@ -0,0 +1,95 @@
+package users_controllers
+
+import (
+ "net/http"
+ "time"
+
+ "github.com/gin-gonic/gin"
+
+ user_dto "databasus-backend/internal/features/users/dto"
+ "databasus-backend/internal/util/ratelimiter"
+)
+
+const (
+ signInCodeVerificationScope = "signin-code-verification"
+ signInCodeVerificationLimit = 10
+ signInCodeVerificationWindow = time.Minute
+)
+
+// VerifySignInCode
+// @Summary Finish a two-step sign-in
+// @Description Exchange a pending sign-in and the code sent by email for an access token
+// @Tags users
+// @Accept json
+// @Produce json
+// @Param request body users_dto.VerifySignInCodeRequestDTO true "Pending sign-in and code"
+// @Success 200 {object} users_dto.SignInResponseDTO
+// @Failure 400 {object} map[string]string "The code is incorrect"
+// @Failure 410 {object} map[string]string "The pending sign-in can no longer be completed"
+// @Failure 429 {object} map[string]string "Rate limit exceeded"
+// @Router /users/verify-signin-code [post]
+func (c *UserController) VerifySignInCode(ctx *gin.Context) {
+ var request user_dto.VerifySignInCodeRequestDTO
+ if err := ctx.ShouldBindJSON(&request); err != nil {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request format"})
+ return
+ }
+
+ if !verifyTurnstileOrRespond(ctx, request.CloudflareTurnstileToken) {
+ return
+ }
+
+ if !c.checkRateLimitOrRespond(ctx, ratelimiter.Attempt{
+ Scope: signInCodeVerificationScope,
+ Identifier: request.PendingSignInID.String(),
+ Limit: signInCodeVerificationLimit,
+ Window: signInCodeVerificationWindow,
+ }) {
+ return
+ }
+
+ response, err := c.userService.VerifyTwoFactorCode(
+ ctx.Request.Context(),
+ request.PendingSignInID,
+ request.Code,
+ )
+ if err != nil {
+ respondToSignInError(ctx, err)
+ return
+ }
+
+ ctx.JSON(http.StatusOK, response)
+}
+
+// ResendSignInCode
+// @Summary Send another sign-in code
+// @Description Replace the code of a pending sign-in with a fresh one
+// @Tags users
+// @Accept json
+// @Produce json
+// @Param request body users_dto.ResendSignInCodeRequestDTO true "Pending sign-in"
+// @Success 200 {object} users_dto.PendingSignInResponseDTO
+// @Failure 400 {object} map[string]string
+// @Failure 410 {object} map[string]string "The pending sign-in can no longer be completed"
+// @Failure 429 {object} map[string]string "Rate limit exceeded"
+// @Failure 503 {object} map[string]string "The code could not be sent"
+// @Router /users/resend-signin-code [post]
+func (c *UserController) ResendSignInCode(ctx *gin.Context) {
+ var request user_dto.ResendSignInCodeRequestDTO
+ if err := ctx.ShouldBindJSON(&request); err != nil {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request format"})
+ return
+ }
+
+ if !verifyTurnstileOrRespond(ctx, request.CloudflareTurnstileToken) {
+ return
+ }
+
+ response, err := c.userService.ResendTwoFactorCode(ctx.Request.Context(), request.PendingSignInID)
+ if err != nil {
+ respondToSignInError(ctx, err)
+ return
+ }
+
+ ctx.JSON(http.StatusOK, response)
+}
diff --git a/backend/internal/features/users/controllers/two_factor_controller_test.go b/backend/internal/features/users/controllers/two_factor_controller_test.go
new file mode 100644
index 00000000..8b935366
--- /dev/null
+++ b/backend/internal/features/users/controllers/two_factor_controller_test.go
@@ -0,0 +1,990 @@
+package users_controllers
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "golang.org/x/oauth2"
+
+ "databasus-backend/internal/features/email"
+ users_dto "databasus-backend/internal/features/users/dto"
+ users_models "databasus-backend/internal/features/users/models"
+ users_repositories "databasus-backend/internal/features/users/repositories"
+ users_services "databasus-backend/internal/features/users/services"
+ users_testing "databasus-backend/internal/features/users/testing"
+ "databasus-backend/internal/storage"
+ cloudflare_turnstile "databasus-backend/internal/util/cloudflare_turnstile"
+ test_utils "databasus-backend/internal/util/testing"
+)
+
+const twoFactorTestPassword = "twofactorpassword123"
+
+func Test_SignIn_WhenTheSecondFactorIsOn_AnswersWithAPendingSignInAndSendsOneCode(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ pendingSignIn := submitPassword(t, router, account, http.StatusOK)
+
+ assert.NotEqual(t, uuid.Nil, pendingSignIn.PendingSignInID)
+ assert.Equal(t, account, pendingSignIn.Email)
+
+ require.Len(t, mailSender.SentEmails, 1)
+ assert.Equal(t, account, mailSender.SentEmails[0].To)
+
+ pendingCode := readPendingSignIn(t, pendingSignIn.PendingSignInID)
+ assert.False(t, pendingCode.IsUsed)
+}
+
+func Test_SignIn_WhenTheSecondFactorIsOn_CarriesNoToken(t *testing.T) {
+ router, _ := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ var response users_dto.SignInResponseDTO
+ test_utils.MakePostRequestAndUnmarshal(
+ t,
+ router,
+ "/api/v1/users/signin",
+ "",
+ users_dto.SignInRequestDTO{Email: account, Password: twoFactorTestPassword},
+ http.StatusOK,
+ &response,
+ )
+
+ assert.Empty(t, response.Token)
+}
+
+func Test_SignIn_WhenTheSecondFactorIsOn_StoresTheCodeOnlyHashed(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ pendingSignIn := submitPassword(t, router, account, http.StatusOK)
+ code := extractCodeFromEmail(mailSender.SentEmails[0].Body)
+ require.Len(t, code, 6)
+
+ pendingCode := readPendingSignIn(t, pendingSignIn.PendingSignInID)
+ assert.NotContains(t, pendingCode.HashedCode, code)
+}
+
+func Test_SignIn_CodeMessage_CarriesTheCodeAndTheRulesItFollows(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ submitPassword(t, router, account, http.StatusOK)
+
+ require.Len(t, mailSender.SentEmails, 1)
+ message := mailSender.SentEmails[0].Body
+
+ assert.Contains(t, message, extractCodeFromEmail(message))
+ assert.Contains(t, message, "stops working")
+ assert.Contains(t, message, "10 minutes")
+ assert.Contains(t, message, "Requesting another code replaces this one")
+}
+
+func Test_VerifySignInCode_WithTheCodeThatArrived_ReturnsAToken(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ pendingSignIn := submitPassword(t, router, account, http.StatusOK)
+ code := extractCodeFromEmail(mailSender.SentEmails[0].Body)
+
+ var response users_dto.SignInResponseDTO
+ test_utils.MakePostRequestAndUnmarshal(
+ t,
+ router,
+ "/api/v1/users/verify-signin-code",
+ "",
+ users_dto.VerifySignInCodeRequestDTO{PendingSignInID: pendingSignIn.PendingSignInID, Code: code},
+ http.StatusOK,
+ &response,
+ )
+
+ assert.NotEmpty(t, response.Token)
+ assert.Equal(t, account, response.Email)
+ assert.True(t, readPendingSignIn(t, pendingSignIn.PendingSignInID).IsUsed)
+}
+
+func Test_VerifySignInCode_WhenTheCodeAlreadyCompletedASignIn_IsRefused(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ pendingSignIn := submitPassword(t, router, account, http.StatusOK)
+ code := extractCodeFromEmail(mailSender.SentEmails[0].Body)
+
+ verifyCode(t, router, pendingSignIn.PendingSignInID, code, http.StatusOK)
+ verifyCode(t, router, pendingSignIn.PendingSignInID, code, http.StatusGone)
+}
+
+func Test_VerifySignInCode_WhenTheCodeHasExpired_IsRefused(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ pendingSignIn := submitPassword(t, router, account, http.StatusOK)
+ code := extractCodeFromEmail(mailSender.SentEmails[0].Body)
+
+ expirePendingSignIn(t, pendingSignIn.PendingSignInID)
+
+ verifyCode(t, router, pendingSignIn.PendingSignInID, code, http.StatusGone)
+}
+
+func Test_VerifySignInCode_WithACodeFromAnotherPendingSignIn_IsRefused(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ firstAccount := registerTwoFactorTestAccount(t, router)
+ secondAccount := registerTwoFactorTestAccount(t, router)
+
+ firstPendingSignIn := submitPassword(t, router, firstAccount, http.StatusOK)
+ firstCode := extractCodeFromEmail(mailSender.SentEmails[0].Body)
+
+ secondPendingSignIn := submitPassword(t, router, secondAccount, http.StatusOK)
+
+ verifyCode(t, router, secondPendingSignIn.PendingSignInID, firstCode, http.StatusBadRequest)
+ assert.NotEqual(t, firstPendingSignIn.PendingSignInID, secondPendingSignIn.PendingSignInID)
+}
+
+func Test_VerifySignInCode_WithAnIdentifierThatNeverExisted_IsRefused(t *testing.T) {
+ router, _ := createTwoFactorTestRouter(t)
+
+ verifyCode(t, router, uuid.New(), "123456", http.StatusGone)
+}
+
+func Test_VerifySignInCode_AfterFiveWrongCodes_TheCorrectOneNoLongerWorks(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+ recorder := users_testing.GetAuditLogRecorder()
+
+ pendingSignIn := submitPassword(t, router, account, http.StatusOK)
+ code := extractCodeFromEmail(mailSender.SentEmails[0].Body)
+
+ for range users_models.MaxTwoFactorCodeAttempts - 1 {
+ verifyCode(t, router, pendingSignIn.PendingSignInID, wrongCodeFor(code), http.StatusBadRequest)
+ }
+
+ // The attempt that exhausts them destroys the pending sign-in, which is a
+ // different answer from a wrong guess the user may try again after.
+ verifyCode(t, router, pendingSignIn.PendingSignInID, wrongCodeFor(code), http.StatusGone)
+
+ verifyCode(t, router, pendingSignIn.PendingSignInID, code, http.StatusGone)
+ assert.True(t, recorder.HasEntryContaining("Two-factor sign-in abandoned", account))
+}
+
+func Test_ResendSignInCode_WithinTheSameMinute_IsRefused(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ pendingSignIn := submitPassword(t, router, account, http.StatusOK)
+
+ var resent users_dto.PendingSignInResponseDTO
+ test_utils.MakePostRequestAndUnmarshal(
+ t,
+ router,
+ "/api/v1/users/resend-signin-code",
+ "",
+ users_dto.ResendSignInCodeRequestDTO{PendingSignInID: pendingSignIn.PendingSignInID},
+ http.StatusOK,
+ &resent,
+ )
+ messagesAfterFirstResend := len(mailSender.SentEmails)
+
+ resendCode(t, router, resent.PendingSignInID, http.StatusTooManyRequests)
+ assert.Len(t, mailSender.SentEmails, messagesAfterFirstResend)
+}
+
+func Test_ResendSignInCode_AfterASuccessfulResend_ThePreviousCodeStopsWorking(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ pendingSignIn := submitPassword(t, router, account, http.StatusOK)
+ firstCode := extractCodeFromEmail(mailSender.SentEmails[0].Body)
+
+ var resent users_dto.PendingSignInResponseDTO
+ test_utils.MakePostRequestAndUnmarshal(
+ t,
+ router,
+ "/api/v1/users/resend-signin-code",
+ "",
+ users_dto.ResendSignInCodeRequestDTO{PendingSignInID: pendingSignIn.PendingSignInID},
+ http.StatusOK,
+ &resent,
+ )
+
+ require.Len(t, mailSender.SentEmails, 2)
+ secondCode := extractCodeFromEmail(mailSender.SentEmails[1].Body)
+
+ verifyCode(t, router, pendingSignIn.PendingSignInID, firstCode, http.StatusGone)
+ verifyCode(t, router, resent.PendingSignInID, secondCode, http.StatusOK)
+}
+
+func Test_SignIn_WhileAPendingSignInIsStillLive_ReturnsItAndSendsNothing(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ firstPendingSignIn := submitPassword(t, router, account, http.StatusOK)
+ code := extractCodeFromEmail(mailSender.SentEmails[0].Body)
+
+ secondPendingSignIn := submitPassword(t, router, account, http.StatusOK)
+
+ assert.Equal(t, firstPendingSignIn.PendingSignInID, secondPendingSignIn.PendingSignInID)
+ assert.Len(t, mailSender.SentEmails, 1)
+ assert.Equal(t, int64(1), countRecentCodes(t, firstPendingSignIn.PendingSignInID))
+
+ verifyCode(t, router, firstPendingSignIn.PendingSignInID, code, http.StatusOK)
+}
+
+func Test_SignIn_WhenTheAccountHasReachedTheHourlyCap_RefusesBeforeSendingMail(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ for range 5 {
+ pendingSignIn := submitPassword(t, router, account, http.StatusOK)
+ expirePendingSignIn(t, pendingSignIn.PendingSignInID)
+ }
+
+ messagesBeforeTheCap := len(mailSender.SentEmails)
+ require.Equal(t, 5, messagesBeforeTheCap)
+
+ response := test_utils.MakePostRequest(
+ t,
+ router,
+ "/api/v1/users/signin",
+ "",
+ users_dto.SignInRequestDTO{Email: account, Password: twoFactorTestPassword},
+ http.StatusTooManyRequests,
+ )
+
+ assert.Contains(t, string(response.Body), "too many codes")
+ assert.Contains(t, string(response.Body), `"code":"too_many_sign_in_codes"`)
+ assert.Len(t, mailSender.SentEmails, messagesBeforeTheCap)
+}
+
+func Test_SignIn_WhenTheMailServerIsMissing_FailsClosed(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ mailSender.IsMailServerMissing = true
+
+ response := test_utils.MakePostRequest(
+ t,
+ router,
+ "/api/v1/users/signin",
+ "",
+ users_dto.SignInRequestDTO{Email: account, Password: twoFactorTestPassword},
+ http.StatusServiceUnavailable,
+ )
+
+ assert.Contains(t, string(response.Body), "could not send the sign-in code")
+ assert.Nil(t, findLivePendingSignIn(t, account))
+}
+
+func Test_SignIn_WhenTheSendFails_FailsClosed(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ mailSender.ShouldFail = true
+
+ response := test_utils.MakePostRequest(
+ t,
+ router,
+ "/api/v1/users/signin",
+ "",
+ users_dto.SignInRequestDTO{Email: account, Password: twoFactorTestPassword},
+ http.StatusServiceUnavailable,
+ )
+
+ assert.Contains(t, string(response.Body), "could not send the sign-in code")
+ assert.Nil(t, findLivePendingSignIn(t, account))
+}
+
+func Test_VerifySignInCode_WhenTheAccountWasDeactivated_IsRefused(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ pendingSignIn := submitPassword(t, router, account, http.StatusOK)
+ code := extractCodeFromEmail(mailSender.SentEmails[0].Body)
+
+ pendingCode := readPendingSignIn(t, pendingSignIn.PendingSignInID)
+ users_testing.DeactivateTestUser(t.Context(), pendingCode.UserID)
+
+ verifyCode(t, router, pendingSignIn.PendingSignInID, code, http.StatusGone)
+}
+
+func Test_VerifySignInCode_WhenThePasswordChangedInTheMeantime_IsRefused(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ pendingSignIn := submitPassword(t, router, account, http.StatusOK)
+ code := extractCodeFromEmail(mailSender.SentEmails[0].Body)
+
+ pendingCode := readPendingSignIn(t, pendingSignIn.PendingSignInID)
+ require.NoError(
+ t,
+ users_services.GetUserService().ChangeUserPassword(t.Context(), pendingCode.UserID, "another-password-123"),
+ )
+
+ verifyCode(t, router, pendingSignIn.PendingSignInID, code, http.StatusGone)
+}
+
+func Test_SignIn_AfterThePasswordChangedDuringAPendingSignIn_SendsAFreshCode(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ stalePendingSignIn := submitPassword(t, router, account, http.StatusOK)
+ stalePendingCode := readPendingSignIn(t, stalePendingSignIn.PendingSignInID)
+ require.NoError(
+ t,
+ users_services.GetUserService().
+ ChangeUserPassword(t.Context(), stalePendingCode.UserID, "another-password-123"),
+ )
+
+ var freshPendingSignIn users_dto.PendingSignInResponseDTO
+ test_utils.MakePostRequestAndUnmarshal(
+ t,
+ router,
+ "/api/v1/users/signin",
+ "",
+ users_dto.SignInRequestDTO{Email: account, Password: "another-password-123"},
+ http.StatusOK,
+ &freshPendingSignIn,
+ )
+
+ assert.NotEqual(t, stalePendingSignIn.PendingSignInID, freshPendingSignIn.PendingSignInID)
+ require.Len(t, mailSender.SentEmails, 2)
+
+ freshCode := extractCodeFromEmail(mailSender.SentEmails[1].Body)
+ verifyCode(t, router, freshPendingSignIn.PendingSignInID, freshCode, http.StatusOK)
+}
+
+func Test_VerifySignInCode_WhenTheSameCodeArrivesTwiceAtOnce_IssuesOneToken(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ pendingSignIn := submitPassword(t, router, account, http.StatusOK)
+ code := extractCodeFromEmail(mailSender.SentEmails[0].Body)
+
+ statuses := postConcurrently(
+ router,
+ "/api/v1/users/verify-signin-code",
+ users_dto.VerifySignInCodeRequestDTO{PendingSignInID: pendingSignIn.PendingSignInID, Code: code},
+ 4,
+ )
+
+ assert.Equal(t, 1, countStatus(statuses, http.StatusOK))
+ assert.Equal(t, 3, countStatus(statuses, http.StatusGone))
+}
+
+func Test_VerifySignInCode_WhenWrongCodesArriveAtOnce_ChecksNoMoreThanTheAllowedFive(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ pendingSignIn := submitPassword(t, router, account, http.StatusOK)
+ code := extractCodeFromEmail(mailSender.SentEmails[0].Body)
+
+ statuses := postConcurrently(
+ router,
+ "/api/v1/users/verify-signin-code",
+ users_dto.VerifySignInCodeRequestDTO{
+ PendingSignInID: pendingSignIn.PendingSignInID,
+ Code: wrongCodeFor(code),
+ },
+ 10,
+ )
+
+ // Four guesses are told the code is wrong, the fifth destroys the pending
+ // sign-in, and the rest find nothing left to guess at.
+ assert.Equal(t, users_models.MaxTwoFactorCodeAttempts-1, countStatus(statuses, http.StatusBadRequest))
+ assert.Equal(
+ t,
+ 10-(users_models.MaxTwoFactorCodeAttempts-1),
+ countStatus(statuses, http.StatusGone),
+ )
+ assert.Equal(
+ t,
+ users_models.MaxTwoFactorCodeAttempts,
+ readPendingSignIn(t, pendingSignIn.PendingSignInID).FailedAttemptCount,
+ )
+}
+
+func Test_SignIn_WhenTwoPasswordStepsArriveAtOnce_SendsOneCode(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ statuses := postConcurrently(
+ router,
+ "/api/v1/users/signin",
+ users_dto.SignInRequestDTO{Email: account, Password: twoFactorTestPassword},
+ 3,
+ )
+
+ assert.Equal(t, 3, countStatus(statuses, http.StatusOK))
+ assert.Len(t, mailSender.SentEmails, 1)
+}
+
+func Test_SignInCodeRefusals_CarryACodeTheInterfaceCanTranslate(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ pendingSignIn := submitPassword(t, router, account, http.StatusOK)
+ code := extractCodeFromEmail(mailSender.SentEmails[0].Body)
+
+ wrongCodeResponse := verifyCode(
+ t, router, pendingSignIn.PendingSignInID, wrongCodeFor(code), http.StatusBadRequest,
+ )
+ assert.Contains(t, string(wrongCodeResponse.Body), `"code":"sign_in_code_incorrect"`)
+
+ var resent users_dto.PendingSignInResponseDTO
+ test_utils.MakePostRequestAndUnmarshal(
+ t,
+ router,
+ "/api/v1/users/resend-signin-code",
+ "",
+ users_dto.ResendSignInCodeRequestDTO{PendingSignInID: pendingSignIn.PendingSignInID},
+ http.StatusOK,
+ &resent,
+ )
+
+ tooSoonResponse := resendCode(t, router, resent.PendingSignInID, http.StatusTooManyRequests)
+ assert.Contains(t, string(tooSoonResponse.Body), `"code":"sign_in_code_resent_too_soon"`)
+
+ goneResponse := verifyCode(t, router, pendingSignIn.PendingSignInID, code, http.StatusGone)
+ assert.Contains(t, string(goneResponse.Body), `"code":"pending_sign_in_not_usable"`)
+}
+
+func Test_VerifySignInCode_AfterTheSettingWasSwitchedOff_StillCompletes(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ pendingSignIn := submitPassword(t, router, account, http.StatusOK)
+ code := extractCodeFromEmail(mailSender.SentEmails[0].Body)
+
+ users_testing.DisableTwoFactorAuth(t.Context())
+
+ verifyCode(t, router, pendingSignIn.PendingSignInID, code, http.StatusOK)
+}
+
+func Test_SignIn_WithAWrongPassword_SendsNoMailAndAnswersAsItDoesWithOneFactor(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ response := test_utils.MakePostRequest(
+ t,
+ router,
+ "/api/v1/users/signin",
+ "",
+ users_dto.SignInRequestDTO{Email: account, Password: "not-the-password"},
+ http.StatusBadRequest,
+ )
+
+ assert.Contains(t, string(response.Body), "password is incorrect")
+ assert.Empty(t, mailSender.SentEmails)
+ assert.Nil(t, findLivePendingSignIn(t, account))
+}
+
+func Test_SignIn_WithAnUnknownAddress_SendsNoMailAndCreatesNoPendingSignIn(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ unknownAddress := "nobody-" + uuid.New().String() + "@example.com"
+
+ response := test_utils.MakePostRequest(
+ t,
+ router,
+ "/api/v1/users/signin",
+ "",
+ users_dto.SignInRequestDTO{Email: unknownAddress, Password: twoFactorTestPassword},
+ http.StatusBadRequest,
+ )
+
+ assert.Contains(t, string(response.Body), "does not exist")
+ assert.Empty(t, mailSender.SentEmails)
+ assert.Nil(t, findLivePendingSignIn(t, unknownAddress))
+}
+
+func Test_SignIn_WhenTheSecondFactorIsOff_ReturnsATokenInOneStep(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ users_testing.DisableTwoFactorAuth(t.Context())
+
+ var response users_dto.SignInResponseDTO
+ test_utils.MakePostRequestAndUnmarshal(
+ t,
+ router,
+ "/api/v1/users/signin",
+ "",
+ users_dto.SignInRequestDTO{Email: account, Password: twoFactorTestPassword},
+ http.StatusOK,
+ &response,
+ )
+
+ assert.NotEmpty(t, response.Token)
+ assert.Empty(t, mailSender.SentEmails)
+}
+
+func Test_SignIn_TheAuditTrailRecordsTheStepThatGrantsAccess(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+ recorder := users_testing.GetAuditLogRecorder()
+
+ pendingSignIn := submitPassword(t, router, account, http.StatusOK)
+ assert.False(t, recorder.HasEntryContaining("User signed in with email", account))
+
+ code := extractCodeFromEmail(mailSender.SentEmails[0].Body)
+ verifyCode(t, router, pendingSignIn.PendingSignInID, code, http.StatusOK)
+
+ assert.Equal(t, 1, countAuditEntries(recorder, "User signed in with email: "+account))
+}
+
+func Test_VerifySignInCode_WhenTheChallengeIsEnabled_RefusesWithoutAnAnswer(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ pendingSignIn := submitPassword(t, router, account, http.StatusOK)
+ code := extractCodeFromEmail(mailSender.SentEmails[0].Body)
+
+ t.Cleanup(cloudflare_turnstile.EnableChallengeForTesting("test-secret-key"))
+
+ response := test_utils.MakePostRequest(
+ t,
+ router,
+ "/api/v1/users/verify-signin-code",
+ "",
+ users_dto.VerifySignInCodeRequestDTO{PendingSignInID: pendingSignIn.PendingSignInID, Code: code},
+ http.StatusBadRequest,
+ )
+
+ assert.Contains(t, string(response.Body), "Turnstile verification required")
+ assert.False(t, readPendingSignIn(t, pendingSignIn.PendingSignInID).IsUsed)
+}
+
+func Test_ResendSignInCode_WhenTheChallengeIsEnabled_RefusesWithoutAnAnswer(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ pendingSignIn := submitPassword(t, router, account, http.StatusOK)
+ messagesBeforeTheResend := len(mailSender.SentEmails)
+
+ t.Cleanup(cloudflare_turnstile.EnableChallengeForTesting("test-secret-key"))
+
+ response := test_utils.MakePostRequest(
+ t,
+ router,
+ "/api/v1/users/resend-signin-code",
+ "",
+ users_dto.ResendSignInCodeRequestDTO{PendingSignInID: pendingSignIn.PendingSignInID},
+ http.StatusBadRequest,
+ )
+
+ assert.Contains(t, string(response.Body), "Turnstile verification required")
+ assert.Len(t, mailSender.SentEmails, messagesBeforeTheResend)
+}
+
+func Test_SweepPendingSignIns_RemovesOnlyWhatIsPastItsRetention(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ agedPendingSignIn := submitPassword(t, router, account, http.StatusOK)
+ agePendingSignIn(t, agedPendingSignIn.PendingSignInID, 2*time.Hour)
+ expirePendingSignIn(t, agedPendingSignIn.PendingSignInID)
+
+ mailSender.SentEmails = nil
+ freshPendingSignIn := submitPassword(t, router, account, http.StatusOK)
+
+ require.NoError(t, users_services.GetUserService().SweepPendingSignInsPastRetention(t.Context()))
+
+ assert.Nil(t, findPendingSignIn(t, agedPendingSignIn.PendingSignInID))
+ assert.NotNil(t, findPendingSignIn(t, freshPendingSignIn.PendingSignInID))
+}
+
+func Test_SignIn_AfterASweep_TheHourlyCapStillCounts(t *testing.T) {
+ router, _ := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ for range 5 {
+ pendingSignIn := submitPassword(t, router, account, http.StatusOK)
+ expirePendingSignIn(t, pendingSignIn.PendingSignInID)
+ }
+
+ require.NoError(t, users_services.GetUserService().SweepPendingSignInsPastRetention(t.Context()))
+
+ test_utils.MakePostRequest(
+ t,
+ router,
+ "/api/v1/users/signin",
+ "",
+ users_dto.SignInRequestDTO{Email: account, Password: twoFactorTestPassword},
+ http.StatusTooManyRequests,
+ )
+}
+
+func createTwoFactorTestRouter(t *testing.T) (*gin.Engine, *users_testing.MockEmailSender) {
+ router := createUserTestRouter()
+
+ mailSender := users_testing.NewMockEmailSender()
+ users_services.GetUserService().SetEmailSender(mailSender)
+
+ users_testing.ResetSettingsToDefaults(t.Context())
+ users_testing.EnableTwoFactorAuth(t.Context())
+ t.Cleanup(func() {
+ users_services.GetUserService().SetEmailSender(email.GetEmailSMTPSender())
+ users_testing.ResetSettingsToDefaults(context.Background())
+ })
+
+ return router, mailSender
+}
+
+func registerTwoFactorTestAccount(t *testing.T, router *gin.Engine) string {
+ address := "twofactor-" + uuid.New().String() + "@example.com"
+
+ test_utils.MakePostRequest(
+ t,
+ router,
+ "/api/v1/users/signup",
+ "",
+ users_dto.SignUpRequestDTO{
+ Email: address,
+ Password: twoFactorTestPassword,
+ Name: "Two Factor User",
+ },
+ http.StatusOK,
+ )
+
+ return address
+}
+
+func submitPassword(
+ t *testing.T,
+ router *gin.Engine,
+ address string,
+ expectedStatus int,
+) users_dto.PendingSignInResponseDTO {
+ var pendingSignIn users_dto.PendingSignInResponseDTO
+
+ test_utils.MakePostRequestAndUnmarshal(
+ t,
+ router,
+ "/api/v1/users/signin",
+ "",
+ users_dto.SignInRequestDTO{Email: address, Password: twoFactorTestPassword},
+ expectedStatus,
+ &pendingSignIn,
+ )
+
+ return pendingSignIn
+}
+
+func verifyCode(
+ t *testing.T,
+ router *gin.Engine,
+ pendingSignInID uuid.UUID,
+ code string,
+ expectedStatus int,
+) *test_utils.TestResponse {
+ return test_utils.MakePostRequest(
+ t,
+ router,
+ "/api/v1/users/verify-signin-code",
+ "",
+ users_dto.VerifySignInCodeRequestDTO{PendingSignInID: pendingSignInID, Code: code},
+ expectedStatus,
+ )
+}
+
+func resendCode(
+ t *testing.T,
+ router *gin.Engine,
+ pendingSignInID uuid.UUID,
+ expectedStatus int,
+) *test_utils.TestResponse {
+ return test_utils.MakePostRequest(
+ t,
+ router,
+ "/api/v1/users/resend-signin-code",
+ "",
+ users_dto.ResendSignInCodeRequestDTO{PendingSignInID: pendingSignInID},
+ expectedStatus,
+ )
+}
+
+func readPendingSignIn(t *testing.T, pendingSignInID uuid.UUID) *users_models.TwoFactorCode {
+ pendingCode := findPendingSignIn(t, pendingSignInID)
+ require.NotNil(t, pendingCode)
+
+ return pendingCode
+}
+
+func findPendingSignIn(t *testing.T, pendingSignInID uuid.UUID) *users_models.TwoFactorCode {
+ pendingCode, err := (&users_repositories.TwoFactorRepository{}).
+ GetCodeByID(t.Context(), pendingSignInID)
+ require.NoError(t, err)
+
+ return pendingCode
+}
+
+func findLivePendingSignIn(t *testing.T, address string) *users_models.TwoFactorCode {
+ user, err := (&users_repositories.UserRepository{}).GetUserByEmail(t.Context(), address)
+ require.NoError(t, err)
+
+ if user == nil {
+ return nil
+ }
+
+ var pendingCodes []users_models.TwoFactorCode
+
+ require.NoError(t, storage.GetDb().WithContext(t.Context()).
+ Where(
+ "user_id = ? AND is_used = ? AND failed_attempt_count < ? AND expires_at > ?",
+ user.ID,
+ false,
+ users_models.MaxTwoFactorCodeAttempts,
+ time.Now().UTC(),
+ ).
+ Order("created_at DESC").
+ Limit(1).
+ Find(&pendingCodes).Error)
+
+ if len(pendingCodes) == 0 {
+ return nil
+ }
+
+ return &pendingCodes[0]
+}
+
+func countRecentCodes(t *testing.T, pendingSignInID uuid.UUID) int64 {
+ pendingCode := readPendingSignIn(t, pendingSignInID)
+
+ var count int64
+
+ require.NoError(t, storage.GetDb().WithContext(t.Context()).
+ Model(&users_models.TwoFactorCode{}).
+ Where("user_id = ? AND created_at > ?", pendingCode.UserID, time.Now().UTC().Add(-time.Hour)).
+ Count(&count).Error)
+
+ return count
+}
+
+func expirePendingSignIn(t *testing.T, pendingSignInID uuid.UUID) {
+ require.NoError(t, storage.GetDb().Model(&users_models.TwoFactorCode{}).
+ Where("id = ?", pendingSignInID).
+ Update("expires_at", time.Now().UTC().Add(-time.Minute)).Error)
+}
+
+func agePendingSignIn(t *testing.T, pendingSignInID uuid.UUID, age time.Duration) {
+ require.NoError(t, storage.GetDb().Model(&users_models.TwoFactorCode{}).
+ Where("id = ?", pendingSignInID).
+ Update("created_at", time.Now().UTC().Add(-age)).Error)
+}
+
+// Requests go straight to the router rather than through test_utils, whose
+// assertions may not run outside the test goroutine.
+func postConcurrently(router *gin.Engine, url string, body any, requestCount int) []int {
+ encodedBody, err := json.Marshal(body)
+ if err != nil {
+ panic(err)
+ }
+
+ statuses := make([]int, requestCount)
+
+ var requestsDone sync.WaitGroup
+
+ for requestIndex := range requestCount {
+ requestsDone.Go(func() {
+ request := httptest.NewRequest(http.MethodPost, url, bytes.NewReader(encodedBody))
+ request.Header.Set("Content-Type", "application/json")
+
+ recorder := httptest.NewRecorder()
+ router.ServeHTTP(recorder, request)
+
+ statuses[requestIndex] = recorder.Code
+ })
+ }
+
+ requestsDone.Wait()
+
+ return statuses
+}
+
+func countStatus(statuses []int, status int) int {
+ matchingCount := 0
+
+ for _, receivedStatus := range statuses {
+ if receivedStatus == status {
+ matchingCount++
+ }
+ }
+
+ return matchingCount
+}
+
+func wrongCodeFor(code string) string {
+ if code == "000000" {
+ return "111111"
+ }
+
+ return "000000"
+}
+
+func Test_GitHubOAuth_WhenTheSecondFactorIsOn_StillIssuesATokenDirectly(t *testing.T) {
+ _, mailSender := createTwoFactorTestRouter(t)
+
+ address := "github-twofactor-" + uuid.New().String() + "@example.com"
+ oauthServer := startGitHubOAuthMockServer(t, address)
+
+ response, err := users_services.GetUserService().HandleGitHubOAuthWithMockEndpoint(
+ t.Context(),
+ "test-code",
+ "http://localhost:3000/auth/callback",
+ oauth2.Endpoint{
+ AuthURL: oauthServer.URL + "/login/oauth/authorize",
+ TokenURL: oauthServer.URL + "/login/oauth/access_token",
+ },
+ oauthServer.URL+"/user",
+ )
+
+ require.NoError(t, err)
+ assert.NotEmpty(t, response.Token)
+ assert.Empty(t, mailSender.SentEmails)
+}
+
+func Test_GoogleOAuth_WhenTheSecondFactorIsOn_StillIssuesATokenDirectly(t *testing.T) {
+ _, mailSender := createTwoFactorTestRouter(t)
+
+ address := "google-twofactor-" + uuid.New().String() + "@example.com"
+ oauthServer := startGoogleOAuthMockServer(t, address)
+
+ response, err := users_services.GetUserService().HandleGoogleOAuthWithMockEndpoint(
+ t.Context(),
+ "test-code",
+ "http://localhost:3000/auth/callback",
+ oauth2.Endpoint{
+ AuthURL: oauthServer.URL + "/o/oauth2/auth",
+ TokenURL: oauthServer.URL + "/token",
+ },
+ oauthServer.URL+"/userinfo",
+ )
+
+ require.NoError(t, err)
+ assert.NotEmpty(t, response.Token)
+ assert.Empty(t, mailSender.SentEmails)
+}
+
+func startGitHubOAuthMockServer(t *testing.T, address string) *httptest.Server {
+ oauthID := int64(uuid.New().ID())
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+
+ switch r.URL.Path {
+ case "/login/oauth/access_token":
+ _ = json.NewEncoder(w).Encode(map[string]string{
+ "access_token": "mock-access-token",
+ "token_type": "bearer",
+ })
+ case "/user":
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "id": oauthID,
+ "email": address,
+ "name": "GitHub Two Factor User",
+ "login": "githubtwofactor",
+ })
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ t.Cleanup(server.Close)
+
+ return server
+}
+
+func startGoogleOAuthMockServer(t *testing.T, address string) *httptest.Server {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+
+ switch r.URL.Path {
+ case "/token":
+ _ = json.NewEncoder(w).Encode(map[string]string{
+ "access_token": "mock-access-token",
+ "token_type": "bearer",
+ })
+ case "/userinfo":
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "id": uuid.New().String(),
+ "email": address,
+ "name": "Google Two Factor User",
+ })
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ t.Cleanup(server.Close)
+
+ return server
+}
+
+func Test_SignIn_WhenTheAccountIsTheBootstrapAdministrator_StillAsksForACode(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ users_testing.DeleteAllUsers()
+
+ // The first account on an empty instance administers it, and the second
+ // factor covers it like any other account.
+ account := registerTwoFactorTestAccount(t, router)
+
+ rootAdmin, err := (&users_repositories.UserRepository{}).GetRootAdmin(t.Context())
+ require.NoError(t, err)
+ require.NotNil(t, rootAdmin)
+ require.Equal(t, account, rootAdmin.Email)
+
+ pendingSignIn := submitPassword(t, router, account, http.StatusOK)
+
+ assert.NotEqual(t, uuid.Nil, pendingSignIn.PendingSignInID)
+ require.Len(t, mailSender.SentEmails, 1)
+}
+
+func Test_TurningTheSecondFactorOn_LeavesSessionsThatAlreadyExistWorking(t *testing.T) {
+ router, _ := createTwoFactorTestRouter(t)
+ users_testing.DisableTwoFactorAuth(t.Context())
+
+ account := registerTwoFactorTestAccount(t, router)
+
+ var signIn users_dto.SignInResponseDTO
+ test_utils.MakePostRequestAndUnmarshal(
+ t,
+ router,
+ "/api/v1/users/signin",
+ "",
+ users_dto.SignInRequestDTO{Email: account, Password: twoFactorTestPassword},
+ http.StatusOK,
+ &signIn,
+ )
+ require.NotEmpty(t, signIn.Token)
+
+ users_testing.EnableTwoFactorAuth(t.Context())
+
+ test_utils.MakeGetRequest(t, router, "/api/v1/users/me", "Bearer "+signIn.Token, http.StatusOK)
+}
+
+func Test_VerifyAndResend_WithAnAddressInsteadOfTheIdentifier_AreRefused(t *testing.T) {
+ router, mailSender := createTwoFactorTestRouter(t)
+ account := registerTwoFactorTestAccount(t, router)
+
+ submitPassword(t, router, account, http.StatusOK)
+ messagesBefore := len(mailSender.SentEmails)
+
+ // Neither request has a field to put an address in, so a caller who knows
+ // one cannot name the account with it.
+ for _, url := range []string{"/api/v1/users/verify-signin-code", "/api/v1/users/resend-signin-code"} {
+ test_utils.MakeRequest(t, router, test_utils.RequestOptions{
+ Method: "POST",
+ URL: url,
+ Body: map[string]any{"email": account, "code": "123456"},
+ ExpectedStatus: http.StatusBadRequest,
+ })
+ }
+
+ assert.Len(t, mailSender.SentEmails, messagesBefore)
+}
diff --git a/backend/internal/features/users/controllers/user_controller.go b/backend/internal/features/users/controllers/user_controller.go
index 393e6122..ac5f333f 100644
--- a/backend/internal/features/users/controllers/user_controller.go
+++ b/backend/internal/features/users/controllers/user_controller.go
@@ -13,7 +13,6 @@ import (
users_errors "databasus-backend/internal/features/users/errors"
user_middleware "databasus-backend/internal/features/users/middleware"
users_services "databasus-backend/internal/features/users/services"
- cloudflare_turnstile "databasus-backend/internal/util/cloudflare_turnstile"
"databasus-backend/internal/util/ratelimiter"
)
@@ -26,6 +25,8 @@ type UserController struct {
func (c *UserController) RegisterRoutes(router *gin.RouterGroup) {
router.POST("/users/signup", c.SignUp)
router.POST("/users/signin", c.SignIn)
+ router.POST("/users/verify-signin-code", c.VerifySignInCode)
+ router.POST("/users/resend-signin-code", c.ResendSignInCode)
router.GET("/users/is-any-user-exist", c.HasAnyUser)
@@ -62,26 +63,8 @@ func (c *UserController) SignUp(ctx *gin.Context) {
return
}
- // Verify Cloudflare Turnstile if enabled
- turnstileService := cloudflare_turnstile.GetCloudflareTurnstileService()
- if turnstileService.IsEnabled() {
- if request.CloudflareTurnstileToken == nil || *request.CloudflareTurnstileToken == "" {
- ctx.JSON(
- http.StatusBadRequest,
- gin.H{"error": "Cloudflare Turnstile verification required"},
- )
- return
- }
-
- clientIP := ctx.ClientIP()
- isValid, err := turnstileService.VerifyToken(*request.CloudflareTurnstileToken, clientIP)
- if err != nil || !isValid {
- ctx.JSON(
- http.StatusBadRequest,
- gin.H{"error": "Cloudflare Turnstile verification failed"},
- )
- return
- }
+ if !verifyTurnstileOrRespond(ctx, request.CloudflareTurnstileToken) {
+ return
}
user, err := c.userService.SignUp(ctx.Request.Context(), &request)
@@ -103,12 +86,12 @@ func (c *UserController) SignUp(ctx *gin.Context) {
// SignIn
// @Summary Authenticate a user
-// @Description Authenticate a user with email and password
+// @Description Authenticate a user with email and password. With the second factor on, a correct password answers with a pending sign-in instead of a token, and the emailed code completes it through /users/verify-signin-code.
// @Tags users
// @Accept json
// @Produce json
// @Param request body users_dto.SignInRequestDTO true "User signin data"
-// @Success 200 {object} users_dto.SignInResponseDTO
+// @Success 200 {object} users_dto.SignInOutcomeResponseDTO "An access token when the instance asks for one factor, and a pending sign-in when it asks for an emailed code"
// @Failure 400
// @Failure 429 {object} map[string]string "Rate limit exceeded"
// @Router /users/signin [post]
@@ -119,50 +102,31 @@ func (c *UserController) SignIn(ctx *gin.Context) {
return
}
- // Verify Cloudflare Turnstile if enabled
- turnstileService := cloudflare_turnstile.GetCloudflareTurnstileService()
- if turnstileService.IsEnabled() {
- if request.CloudflareTurnstileToken == nil || *request.CloudflareTurnstileToken == "" {
- ctx.JSON(
- http.StatusBadRequest,
- gin.H{"error": "Cloudflare Turnstile verification required"},
- )
- return
- }
+ if !verifyTurnstileOrRespond(ctx, request.CloudflareTurnstileToken) {
+ return
+ }
- clientIP := ctx.ClientIP()
- isValid, err := turnstileService.VerifyToken(*request.CloudflareTurnstileToken, clientIP)
- if err != nil || !isValid {
- ctx.JSON(
- http.StatusBadRequest,
- gin.H{"error": "Cloudflare Turnstile verification failed"},
- )
- return
- }
+ if !c.checkRateLimitOrRespond(ctx, ratelimiter.Attempt{
+ Scope: "signin",
+ Identifier: request.Email,
+ Limit: 10,
+ Window: time.Minute,
+ }) {
+ return
}
- isAllowed, err := c.rateLimiter.RecordAttemptAndCheckIsAllowed(
- ctx.Request.Context(),
- ratelimiter.Attempt{Scope: "signin", Identifier: request.Email, Limit: 10, Window: time.Minute},
- )
+ outcome, err := c.userService.SignIn(ctx.Request.Context(), &request)
if err != nil {
- c.logger.ErrorContext(ctx.Request.Context(), "failed to evaluate sign-in rate limit", "error", err)
- }
- if err != nil || !isAllowed {
- ctx.JSON(
- http.StatusTooManyRequests,
- gin.H{"error": "Rate limit exceeded. Please try again later."},
- )
+ respondToSignInError(ctx, err)
return
}
- response, err := c.userService.SignIn(ctx.Request.Context(), &request)
- if err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ if outcome.PendingSignIn != nil {
+ ctx.JSON(http.StatusOK, outcome.PendingSignIn)
return
}
- ctx.JSON(http.StatusOK, response)
+ ctx.JSON(http.StatusOK, outcome.CompletedSignIn)
}
// HasAnyUser
@@ -411,49 +375,20 @@ func (c *UserController) SendResetPasswordCode(ctx *gin.Context) {
return
}
- // Verify Cloudflare Turnstile if enabled
- turnstileService := cloudflare_turnstile.GetCloudflareTurnstileService()
- if turnstileService.IsEnabled() {
- if request.CloudflareTurnstileToken == nil || *request.CloudflareTurnstileToken == "" {
- ctx.JSON(
- http.StatusBadRequest,
- gin.H{"error": "Cloudflare Turnstile verification required"},
- )
- return
- }
-
- clientIP := ctx.ClientIP()
- isValid, err := turnstileService.VerifyToken(*request.CloudflareTurnstileToken, clientIP)
- if err != nil || !isValid {
- ctx.JSON(
- http.StatusBadRequest,
- gin.H{"error": "Cloudflare Turnstile verification failed"},
- )
- return
- }
+ if !verifyTurnstileOrRespond(ctx, request.CloudflareTurnstileToken) {
+ return
}
- isAllowed, err := c.rateLimiter.RecordAttemptAndCheckIsAllowed(
- ctx.Request.Context(),
- ratelimiter.Attempt{
- Scope: "reset-password",
- Identifier: request.Email,
- Limit: 3,
- Window: time.Hour,
- },
- )
- if err != nil {
- c.logger.ErrorContext(ctx.Request.Context(), "failed to evaluate password reset rate limit", "error", err)
- }
- if err != nil || !isAllowed {
- ctx.JSON(
- http.StatusTooManyRequests,
- gin.H{"error": "Rate limit exceeded. Please try again later."},
- )
+ if !c.checkRateLimitOrRespond(ctx, ratelimiter.Attempt{
+ Scope: "reset-password",
+ Identifier: request.Email,
+ Limit: 3,
+ Window: time.Hour,
+ }) {
return
}
- err = c.userService.SendResetPasswordCode(ctx.Request.Context(), request.Email)
+ err := c.userService.SendResetPasswordCode(ctx.Request.Context(), request.Email)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
@@ -487,3 +422,46 @@ func (c *UserController) ResetPassword(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"message": "Password reset successfully"})
}
+
+func (c *UserController) checkRateLimitOrRespond(ctx *gin.Context, attempt ratelimiter.Attempt) bool {
+ isAllowed, err := c.rateLimiter.RecordAttemptAndCheckIsAllowed(ctx.Request.Context(), attempt)
+ if err != nil {
+ c.logger.ErrorContext(ctx.Request.Context(), "failed to evaluate a rate limit",
+ "scope", attempt.Scope, "error", err)
+ }
+
+ if err != nil || !isAllowed {
+ ctx.JSON(
+ http.StatusTooManyRequests,
+ gin.H{"error": "Rate limit exceeded. Please try again later.", "code": "rate_limit_exceeded"},
+ )
+
+ return false
+ }
+
+ return true
+}
+
+// Each refusal carries a code, because the status alone does not tell the
+// interface what happened: a wrong code and a failed challenge are both 400, and
+// a resend inside its minute and an exhausted hourly cap are both 429.
+func respondToSignInError(ctx *gin.Context, err error) {
+ switch {
+ case errors.Is(err, users_errors.ErrPendingSignInNotUsable):
+ respondWithCode(ctx, http.StatusGone, err, "pending_sign_in_not_usable")
+ case errors.Is(err, users_errors.ErrSignInCodeNotSent):
+ respondWithCode(ctx, http.StatusServiceUnavailable, err, "sign_in_code_not_sent")
+ case errors.Is(err, users_errors.ErrTooManySignInCodes):
+ respondWithCode(ctx, http.StatusTooManyRequests, err, "too_many_sign_in_codes")
+ case errors.Is(err, users_errors.ErrSignInCodeResentTooSoon):
+ respondWithCode(ctx, http.StatusTooManyRequests, err, "sign_in_code_resent_too_soon")
+ case errors.Is(err, users_errors.ErrSignInCodeIncorrect):
+ respondWithCode(ctx, http.StatusBadRequest, err, "sign_in_code_incorrect")
+ default:
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ }
+}
+
+func respondWithCode(ctx *gin.Context, status int, err error, code string) {
+ ctx.JSON(status, gin.H{"error": err.Error(), "code": code})
+}
diff --git a/backend/internal/features/users/dto/dto.go b/backend/internal/features/users/dto/dto.go
index 94577196..7782b58f 100644
--- a/backend/internal/features/users/dto/dto.go
+++ b/backend/internal/features/users/dto/dto.go
@@ -27,6 +27,42 @@ type SignInResponseDTO struct {
Token string `json:"token"`
}
+// SignInOutcomeResponseDTO exists for the published API description, which
+// cannot express two alternative bodies for one status. The token fields arrive
+// when the instance asks for one factor, and pendingSignInId arrives when it
+// asks for an emailed code. Nothing serializes this type.
+type SignInOutcomeResponseDTO struct {
+ UserID uuid.UUID `json:"userId"`
+ Email string `json:"email"`
+ Token string `json:"token,omitzero"`
+ PendingSignInID uuid.UUID `json:"pendingSignInId,omitzero"`
+}
+
+// A sign-in answers with one of these shapes, never both: a token when the
+// instance asks for one factor, and a pending sign-in when it asks for two.
+type SignInOutcome struct {
+ CompletedSignIn *SignInResponseDTO
+ PendingSignIn *PendingSignInResponseDTO
+}
+
+// The address is carried back so the code screen can say where the message went,
+// and the identifier is the only way to name the pending sign-in afterwards.
+type PendingSignInResponseDTO struct {
+ PendingSignInID uuid.UUID `json:"pendingSignInId"`
+ Email string `json:"email"`
+}
+
+type VerifySignInCodeRequestDTO struct {
+ PendingSignInID uuid.UUID `json:"pendingSignInId" binding:"required"`
+ Code string `json:"code" binding:"required"`
+ CloudflareTurnstileToken *string `json:"cloudflareTurnstileToken"`
+}
+
+type ResendSignInCodeRequestDTO struct {
+ PendingSignInID uuid.UUID `json:"pendingSignInId" binding:"required"`
+ CloudflareTurnstileToken *string `json:"cloudflareTurnstileToken"`
+}
+
// The wire name is isExist rather than hasAnyUser because the client already
// reads that key (frontend/src/entity/users/api/userApi.ts).
type HasAnyUserResponseDTO struct {
@@ -103,3 +139,21 @@ type ResetPasswordRequestDTO struct {
Code string `json:"code" binding:"required"`
NewPassword string `json:"newPassword" binding:"required,min=8"`
}
+
+// The mail-server answer is the instance's own, not the build-time flag the
+// interface used to predict it from, and it is derived rather than stored, so
+// the update request cannot carry it back.
+type SettingsResponseDTO struct {
+ IsAllowExternalRegistrations bool `json:"isAllowExternalRegistrations"`
+ IsAllowMemberInvitations bool `json:"isAllowMemberInvitations"`
+ IsMemberAllowedToCreateWorkspaces bool `json:"isMemberAllowedToCreateWorkspaces"`
+ IsTwoFactorAuthRequired bool `json:"isTwoFactorAuthRequired"`
+ IsEmailConfigured bool `json:"isEmailConfigured"`
+}
+
+type UpdateSettingsRequestDTO struct {
+ IsAllowExternalRegistrations bool `json:"isAllowExternalRegistrations"`
+ IsAllowMemberInvitations bool `json:"isAllowMemberInvitations"`
+ IsMemberAllowedToCreateWorkspaces bool `json:"isMemberAllowedToCreateWorkspaces"`
+ IsTwoFactorAuthRequired bool `json:"isTwoFactorAuthRequired"`
+}
diff --git a/backend/internal/features/users/errors/errors.go b/backend/internal/features/users/errors/errors.go
index e4045892..08d9d1ea 100644
--- a/backend/internal/features/users/errors/errors.go
+++ b/backend/internal/features/users/errors/errors.go
@@ -3,3 +3,21 @@ package users_errors
import "errors"
var ErrInsufficientPermissionsToInviteUsers = errors.New("insufficient permissions to invite users")
+
+var (
+ // The instance could not deliver the code, so it admits nobody through
+ // password sign-in while the second factor is on.
+ ErrSignInCodeNotSent = errors.New(
+ "could not send the sign-in code, please try again later",
+ )
+ ErrTooManySignInCodes = errors.New(
+ "too many codes requested for this account, please try again later",
+ )
+ ErrSignInCodeResentTooSoon = errors.New(
+ "a code was sent less than a minute ago, please wait before requesting another",
+ )
+ ErrPendingSignInNotUsable = errors.New(
+ "this sign-in can no longer be completed, please sign in again",
+ )
+ ErrSignInCodeIncorrect = errors.New("the code is incorrect")
+)
diff --git a/backend/internal/features/users/interfaces/interfaces.go b/backend/internal/features/users/interfaces/interfaces.go
index d1c720f7..818cdeab 100644
--- a/backend/internal/features/users/interfaces/interfaces.go
+++ b/backend/internal/features/users/interfaces/interfaces.go
@@ -11,5 +11,8 @@ type AuditLogWriter interface {
}
type EmailSender interface {
+ // SendEmail reports no error when the instance has no mail server, so a
+ // caller that must not admit a silent skip asks this first.
+ IsConfigured() bool
SendEmail(to, subject, body string) error
}
diff --git a/backend/internal/features/users/models/two_factor_code.go b/backend/internal/features/users/models/two_factor_code.go
new file mode 100644
index 00000000..a301fa6b
--- /dev/null
+++ b/backend/internal/features/users/models/two_factor_code.go
@@ -0,0 +1,36 @@
+package users_models
+
+import (
+ "time"
+
+ "github.com/google/uuid"
+)
+
+// The row stays behind once a pending sign-in is destroyed, because the hourly
+// cap counts it.
+const MaxTwoFactorCodeAttempts = 5
+
+type TwoFactorCode struct {
+ ID uuid.UUID `json:"id" gorm:"column:id"`
+ UserID uuid.UUID `json:"userId" gorm:"column:user_id"`
+ HashedCode string `json:"-" gorm:"column:hashed_code"`
+ // The password the first step accepted, so the second step can refuse a
+ // pending sign-in whose account has changed its password since.
+ PasswordCreationTime time.Time `json:"passwordCreationTime" gorm:"column:password_creation_time"`
+ ExpiresAt time.Time `json:"expiresAt" gorm:"column:expires_at"`
+ IsUsed bool `json:"isUsed" gorm:"column:is_used"`
+ FailedAttemptCount int `json:"failedAttemptCount" gorm:"column:failed_attempt_count"`
+ CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"`
+}
+
+func (TwoFactorCode) TableName() string {
+ return "two_factor_codes"
+}
+
+func (c *TwoFactorCode) IsValid() bool {
+ return !c.IsUsed && !c.IsDestroyed() && time.Now().UTC().Before(c.ExpiresAt)
+}
+
+func (c *TwoFactorCode) IsDestroyed() bool {
+ return c.FailedAttemptCount >= MaxTwoFactorCodeAttempts
+}
diff --git a/backend/internal/features/users/models/users_settings.go b/backend/internal/features/users/models/users_settings.go
index 23c882aa..dee9313e 100644
--- a/backend/internal/features/users/models/users_settings.go
+++ b/backend/internal/features/users/models/users_settings.go
@@ -10,6 +10,8 @@ type UsersSettings struct {
IsAllowMemberInvitations bool `json:"isAllowMemberInvitations" gorm:"column:is_allow_member_invitations"`
// means that any user with role MEMBER can create their own workspaces
IsMemberAllowedToCreateWorkspaces bool `json:"isMemberAllowedToCreateWorkspaces" gorm:"column:is_member_allowed_to_create_workspaces"`
+ // means that a password sign-in also has to present a code emailed to the account
+ IsTwoFactorAuthRequired bool `json:"isTwoFactorAuthRequired" gorm:"column:is_two_factor_auth_required"`
}
func (UsersSettings) TableName() string {
diff --git a/backend/internal/features/users/repositories/di.go b/backend/internal/features/users/repositories/di.go
index af676239..c615705d 100644
--- a/backend/internal/features/users/repositories/di.go
+++ b/backend/internal/features/users/repositories/di.go
@@ -4,6 +4,7 @@ var (
userRepository = &UserRepository{}
usersSettingsRepository = &UsersSettingsRepository{}
passwordResetRepository = &PasswordResetRepository{}
+ twoFactorRepository = &TwoFactorRepository{}
)
func GetUserRepository() *UserRepository {
@@ -17,3 +18,7 @@ func GetUsersSettingsRepository() *UsersSettingsRepository {
func GetPasswordResetRepository() *PasswordResetRepository {
return passwordResetRepository
}
+
+func GetTwoFactorRepository() *TwoFactorRepository {
+ return twoFactorRepository
+}
diff --git a/backend/internal/features/users/repositories/two_factor_repository.go b/backend/internal/features/users/repositories/two_factor_repository.go
new file mode 100644
index 00000000..320fb7aa
--- /dev/null
+++ b/backend/internal/features/users/repositories/two_factor_repository.go
@@ -0,0 +1,194 @@
+package users_repositories
+
+import (
+ "context"
+ "errors"
+ "time"
+
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+
+ users_models "databasus-backend/internal/features/users/models"
+ "databasus-backend/internal/storage"
+)
+
+// ErrHourlyCodeCapReached is how the repository refuses a code the account has
+// no allowance left for.
+var ErrHourlyCodeCapReached = errors.New("hourly sign-in code cap reached")
+
+type TwoFactorRepository struct{}
+
+// CreateCodeUnlessLive hands back the pending sign-in the account is already
+// waiting on instead of creating a second one. The live row must carry the
+// password the new one would, because a row issued before a password change
+// can no longer be completed and would otherwise be handed back until it expired.
+func (r *TwoFactorRepository) CreateCodeUnlessLive(
+ ctx context.Context,
+ code *users_models.TwoFactorCode,
+ countedSince time.Time,
+ maxCodesPerHour int64,
+) (*users_models.TwoFactorCode, error) {
+ var liveCode *users_models.TwoFactorCode
+
+ err := storage.GetDb().WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if err := lockUserRow(tx, code.UserID); err != nil {
+ return err
+ }
+
+ var existingCode users_models.TwoFactorCode
+
+ err := tx.
+ Where(
+ "user_id = ? AND password_creation_time = ? AND is_used = ? "+
+ "AND failed_attempt_count < ? AND expires_at > ?",
+ code.UserID,
+ code.PasswordCreationTime,
+ false,
+ users_models.MaxTwoFactorCodeAttempts,
+ time.Now().UTC(),
+ ).
+ Order("created_at DESC").
+ First(&existingCode).Error
+ if err == nil {
+ liveCode = &existingCode
+
+ return nil
+ }
+
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return err
+ }
+
+ return createCodeWithinHourlyCap(tx, code, countedSince, maxCodesPerHour)
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ return liveCode, nil
+}
+
+// CreateCodeWithinHourlyCap creates the code only while the account has fewer
+// than maxCodesPerHour codes issued since countedSince, and answers
+// ErrHourlyCodeCapReached otherwise.
+func (r *TwoFactorRepository) CreateCodeWithinHourlyCap(
+ ctx context.Context,
+ code *users_models.TwoFactorCode,
+ countedSince time.Time,
+ maxCodesPerHour int64,
+) error {
+ return storage.GetDb().WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if err := lockUserRow(tx, code.UserID); err != nil {
+ return err
+ }
+
+ return createCodeWithinHourlyCap(tx, code, countedSince, maxCodesPerHour)
+ })
+}
+
+// A caller that hands over an identifier nobody issued gets no row and no error,
+// because an unknown identifier is refused the same way an unusable one is.
+func (r *TwoFactorRepository) GetCodeByID(
+ ctx context.Context,
+ codeID uuid.UUID,
+) (*users_models.TwoFactorCode, error) {
+ var code users_models.TwoFactorCode
+
+ err := storage.GetDb().WithContext(ctx).Where("id = ?", codeID).First(&code).Error
+ if err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, nil
+ }
+
+ return nil, err
+ }
+
+ return &code, nil
+}
+
+// SpendCode marks the code used only if it is still usable, so two requests
+// carrying the same correct code cannot both be let in.
+func (r *TwoFactorRepository) SpendCode(ctx context.Context, codeID uuid.UUID) (bool, error) {
+ result := storage.GetDb().WithContext(ctx).Model(&users_models.TwoFactorCode{}).
+ Where("id = ? AND is_used = ? AND expires_at > ?", codeID, false, time.Now().UTC()).
+ Update("is_used", true)
+
+ return result.RowsAffected == 1, result.Error
+}
+
+func (r *TwoFactorRepository) MarkCodeAsUsed(ctx context.Context, codeID uuid.UUID) error {
+ return storage.GetDb().WithContext(ctx).Model(&users_models.TwoFactorCode{}).
+ Where("id = ?", codeID).
+ Update("is_used", true).Error
+}
+
+// ClaimAttempt spends one of the pending sign-in's attempts before the code is
+// compared, and answers false once none are left. Claiming first is what keeps
+// a burst of simultaneous guesses at five: each guess needs a slot the database
+// hands out one at a time. A correct code spends its slot too, which changes
+// nothing, because the row is spent with it.
+func (r *TwoFactorRepository) ClaimAttempt(
+ ctx context.Context,
+ codeID uuid.UUID,
+) (int, bool, error) {
+ var code users_models.TwoFactorCode
+
+ result := storage.GetDb().WithContext(ctx).Model(&code).
+ Clauses(clause.Returning{Columns: []clause.Column{{Name: "failed_attempt_count"}}}).
+ Where(
+ "id = ? AND is_used = ? AND failed_attempt_count < ? AND expires_at > ?",
+ codeID,
+ false,
+ users_models.MaxTwoFactorCodeAttempts,
+ time.Now().UTC(),
+ ).
+ UpdateColumn("failed_attempt_count", gorm.Expr("failed_attempt_count + 1"))
+ if result.Error != nil {
+ return 0, false, result.Error
+ }
+
+ return code.FailedAttemptCount, result.RowsAffected == 1, nil
+}
+
+// The sweep goes by age rather than by expiry, because the hourly cap counts
+// rows whose codes stopped working fifty minutes ago.
+func (r *TwoFactorRepository) DeleteCodesCreatedBefore(ctx context.Context, cutoff time.Time) error {
+ return storage.GetDb().WithContext(ctx).
+ Where("created_at < ?", cutoff).
+ Delete(&users_models.TwoFactorCode{}).Error
+}
+
+// Two password steps arriving together would otherwise both find no live row
+// and both stay under the cap, and each would mail a code. Holding the account's
+// row for the length of the transaction makes the second one wait and see the
+// first one's code.
+func lockUserRow(tx *gorm.DB, userID uuid.UUID) error {
+ return tx.Exec("SELECT 1 FROM users WHERE id = ? FOR UPDATE", userID).Error
+}
+
+func createCodeWithinHourlyCap(
+ tx *gorm.DB,
+ code *users_models.TwoFactorCode,
+ countedSince time.Time,
+ maxCodesPerHour int64,
+) error {
+ var recentCodeCount int64
+
+ err := tx.Model(&users_models.TwoFactorCode{}).
+ Where("user_id = ? AND created_at > ?", code.UserID, countedSince).
+ Count(&recentCodeCount).Error
+ if err != nil {
+ return err
+ }
+
+ if recentCodeCount >= maxCodesPerHour {
+ return ErrHourlyCodeCapReached
+ }
+
+ if code.ID == uuid.Nil {
+ code.ID = uuid.New()
+ }
+
+ return tx.Create(code).Error
+}
diff --git a/backend/internal/features/users/services/background_service.go b/backend/internal/features/users/services/background_service.go
new file mode 100644
index 00000000..6367b5e7
--- /dev/null
+++ b/backend/internal/features/users/services/background_service.go
@@ -0,0 +1,65 @@
+package users_services
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "sync/atomic"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+const signInCodeCleanupJobName = "sign_in_code_cleanup"
+
+const signInCodeCleanupInterval = 10 * time.Minute
+
+// Both tables hold single-use codes that nobody comes back for, and neither was
+// ever swept: password_reset_codes has had a cleanup method and no caller since
+// it was written.
+type SignInCodeBackgroundService struct {
+ userService *UserService
+ logger *slog.Logger
+
+ hasRun atomic.Bool
+}
+
+func (s *SignInCodeBackgroundService) Run(ctx context.Context) {
+ if s.hasRun.Swap(true) {
+ panic(fmt.Sprintf("%T.Run() called multiple times", s))
+ }
+
+ lifecycleLogger := s.logger.With("job_name", signInCodeCleanupJobName)
+
+ lifecycleLogger.InfoContext(ctx, "sign-in code cleanup started")
+
+ if ctx.Err() != nil {
+ return
+ }
+
+ ticker := time.NewTicker(signInCodeCleanupInterval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ lifecycleLogger.InfoContext(ctx, "sign-in code cleanup stopped")
+
+ return
+ case <-ticker.C:
+ s.sweep(ctx)
+ }
+ }
+}
+
+func (s *SignInCodeBackgroundService) sweep(ctx context.Context) {
+ logger := s.logger.With("job_id", uuid.New(), "job_name", signInCodeCleanupJobName)
+
+ if err := s.userService.SweepPendingSignInsPastRetention(ctx); err != nil {
+ logger.ErrorContext(ctx, "failed to delete pending sign-ins past their retention", "error", err)
+ }
+
+ if err := s.userService.SweepExpiredPasswordResetCodes(); err != nil {
+ logger.ErrorContext(ctx, "failed to delete expired password reset codes", "error", err)
+ }
+}
diff --git a/backend/internal/features/users/services/background_service_test.go b/backend/internal/features/users/services/background_service_test.go
new file mode 100644
index 00000000..ae0c33ae
--- /dev/null
+++ b/backend/internal/features/users/services/background_service_test.go
@@ -0,0 +1,96 @@
+package users_services_test
+
+import (
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "golang.org/x/crypto/bcrypt"
+
+ users_enums "databasus-backend/internal/features/users/enums"
+ users_models "databasus-backend/internal/features/users/models"
+ users_repositories "databasus-backend/internal/features/users/repositories"
+ users_services "databasus-backend/internal/features/users/services"
+ users_testing "databasus-backend/internal/features/users/testing"
+ "databasus-backend/internal/storage"
+)
+
+func Test_SweepPendingSignIns_WithRowsOfBothAges_RemovesOnlyThePastItsRetention(t *testing.T) {
+ user := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)
+
+ agedCode := seedPendingSignIn(t, user.UserID, 2*time.Hour)
+ freshCode := seedPendingSignIn(t, user.UserID, time.Minute)
+
+ require.NoError(t, users_services.GetUserService().SweepPendingSignInsPastRetention(t.Context()))
+
+ repository := &users_repositories.TwoFactorRepository{}
+
+ sweptCode, err := repository.GetCodeByID(t.Context(), agedCode)
+ require.NoError(t, err)
+ assert.Nil(t, sweptCode)
+
+ keptCode, err := repository.GetCodeByID(t.Context(), freshCode)
+ require.NoError(t, err)
+ assert.NotNil(t, keptCode)
+}
+
+func Test_SweepExpiredPasswordResetCodes_WithRowsOfBothAges_RemovesOnlyTheExpired(t *testing.T) {
+ user := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)
+
+ expiredCode := seedPasswordResetCode(t, user.UserID, -time.Minute)
+ liveCode := seedPasswordResetCode(t, user.UserID, time.Hour)
+
+ require.NoError(t, users_services.GetUserService().SweepExpiredPasswordResetCodes())
+
+ assert.False(t, hasPasswordResetCode(t, expiredCode))
+ assert.True(t, hasPasswordResetCode(t, liveCode))
+}
+
+func seedPendingSignIn(t *testing.T, userID uuid.UUID, age time.Duration) uuid.UUID {
+ hashedCode, err := bcrypt.GenerateFromPassword([]byte("123456"), bcrypt.MinCost)
+ require.NoError(t, err)
+
+ createdAt := time.Now().UTC().Add(-age)
+ code := &users_models.TwoFactorCode{
+ ID: uuid.New(),
+ UserID: userID,
+ HashedCode: string(hashedCode),
+ PasswordCreationTime: createdAt,
+ ExpiresAt: createdAt.Add(10 * time.Minute),
+ CreatedAt: createdAt,
+ }
+
+ require.NoError(t, storage.GetDb().WithContext(t.Context()).Create(code).Error)
+
+ return code.ID
+}
+
+func seedPasswordResetCode(t *testing.T, userID uuid.UUID, timeToExpiry time.Duration) uuid.UUID {
+ hashedCode, err := bcrypt.GenerateFromPassword([]byte("123456"), bcrypt.MinCost)
+ require.NoError(t, err)
+
+ code := &users_models.PasswordResetCode{
+ ID: uuid.New(),
+ UserID: userID,
+ HashedCode: string(hashedCode),
+ ExpiresAt: time.Now().UTC().Add(timeToExpiry),
+ CreatedAt: time.Now().UTC(),
+ }
+
+ require.NoError(t, (&users_repositories.PasswordResetRepository{}).CreateResetCode(code))
+
+ return code.ID
+}
+
+func hasPasswordResetCode(t *testing.T, codeID uuid.UUID) bool {
+ var count int64
+
+ require.NoError(t, storage.GetDb().WithContext(t.Context()).
+ Model(&users_models.PasswordResetCode{}).
+ Where("id = ?", codeID).
+ Count(&count).Error)
+
+ return count > 0
+}
diff --git a/backend/internal/features/users/services/di.go b/backend/internal/features/users/services/di.go
index d61937c8..dde156d6 100644
--- a/backend/internal/features/users/services/di.go
+++ b/backend/internal/features/users/services/di.go
@@ -1,10 +1,13 @@
package users_services
import (
+ "sync/atomic"
+
"databasus-backend/internal/features/email"
"databasus-backend/internal/features/encryption/secrets"
users_repositories "databasus-backend/internal/features/users/repositories"
"databasus-backend/internal/util/logger"
+ "databasus-backend/internal/util/ratelimiter"
)
var userService = &UserService{
@@ -14,12 +17,22 @@ var userService = &UserService{
nil,
email.GetEmailSMTPSender(),
users_repositories.GetPasswordResetRepository(),
+ users_repositories.GetTwoFactorRepository(),
+ ratelimiter.GetCounter(),
logger.GetLogger(),
}
var settingsService = &SettingsService{
users_repositories.GetUsersSettingsRepository(),
+ users_repositories.GetUserRepository(),
nil,
+ email.GetEmailSMTPSender(),
+}
+
+var signInCodeBackgroundService = &SignInCodeBackgroundService{
+ userService,
+ logger.GetLogger(),
+ atomic.Bool{},
}
var managementService = &UserManagementService{
@@ -38,3 +51,7 @@ func GetSettingsService() *SettingsService {
func GetManagementService() *UserManagementService {
return managementService
}
+
+func GetSignInCodeBackgroundService() *SignInCodeBackgroundService {
+ return signInCodeBackgroundService
+}
diff --git a/backend/internal/features/users/services/disable_two_factor_test.go b/backend/internal/features/users/services/disable_two_factor_test.go
new file mode 100644
index 00000000..47e85afb
--- /dev/null
+++ b/backend/internal/features/users/services/disable_two_factor_test.go
@@ -0,0 +1,47 @@
+package users_services_test
+
+import (
+ "context"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ users_services "databasus-backend/internal/features/users/services"
+ users_testing "databasus-backend/internal/features/users/testing"
+)
+
+func Test_DisableTwoFactorAuth_WhenTheSettingIsAlreadyOff_ReportsNoChange(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+
+ recorder := users_testing.InstallAuditLogRecorder()
+ users_services.GetSettingsService().SetAuditLogWriter(recorder)
+
+ isChanged, err := users_services.GetSettingsService().DisableTwoFactorAuth(t.Context())
+
+ require.NoError(t, err)
+ assert.False(t, isChanged)
+ assert.False(t, recorder.HasEntryContaining("isTwoFactorAuthRequired"))
+}
+
+func Test_DisableTwoFactorAuth_WhenTheSettingIsOn_SwitchesItOffAndLeavesATrace(t *testing.T) {
+ users_testing.ResetSettingsToDefaults(t.Context())
+ users_testing.EnableTwoFactorAuth(t.Context())
+ t.Cleanup(func() { users_testing.ResetSettingsToDefaults(context.Background()) })
+
+ recorder := users_testing.InstallAuditLogRecorder()
+ users_services.GetSettingsService().SetAuditLogWriter(recorder)
+
+ isChanged, err := users_services.GetSettingsService().DisableTwoFactorAuth(t.Context())
+ require.NoError(t, err)
+ assert.True(t, isChanged)
+
+ settings, err := users_services.GetSettingsService().GetSettings(t.Context())
+ require.NoError(t, err)
+ assert.False(t, settings.IsTwoFactorAuthRequired)
+
+ assert.True(
+ t,
+ recorder.HasEntryContaining("isTwoFactorAuthRequired: true -> false", "host console"),
+ )
+}
diff --git a/backend/internal/features/users/services/settings_service.go b/backend/internal/features/users/services/settings_service.go
index 957ed4db..51577a02 100644
--- a/backend/internal/features/users/services/settings_service.go
+++ b/backend/internal/features/users/services/settings_service.go
@@ -4,30 +4,60 @@ import (
"context"
"fmt"
+ "github.com/go-playground/validator/v10"
+
audit_logs_models "databasus-backend/internal/features/audit_logs/models"
+ users_dto "databasus-backend/internal/features/users/dto"
users_interfaces "databasus-backend/internal/features/users/interfaces"
users_models "databasus-backend/internal/features/users/models"
users_repositories "databasus-backend/internal/features/users/repositories"
)
+// The gate and the profile form must not disagree about what counts as an
+// address, so the gate asks the validator the request binding already uses
+// (UpdateUserInfoRequestDTO binds omitempty,email) rather than matching a
+// pattern of its own.
+var addressValidator = validator.New()
+
type SettingsService struct {
userSettingsRepository *users_repositories.UsersSettingsRepository
+ userRepository *users_repositories.UserRepository
auditLogWriter users_interfaces.AuditLogWriter
+ emailSender users_interfaces.EmailSender
}
func (s *SettingsService) SetAuditLogWriter(writer users_interfaces.AuditLogWriter) {
s.auditLogWriter = writer
}
+func (s *SettingsService) SetEmailSender(sender users_interfaces.EmailSender) {
+ s.emailSender = sender
+}
+
func (s *SettingsService) GetSettings(ctx context.Context) (*users_models.UsersSettings, error) {
return s.userSettingsRepository.GetSettings(ctx)
}
+func (s *SettingsService) GetSettingsResponse(
+ ctx context.Context,
+) (*users_dto.SettingsResponseDTO, error) {
+ settings, err := s.userSettingsRepository.GetSettings(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ return s.buildSettingsResponse(settings), nil
+}
+
+func (s *SettingsService) IsEmailConfigured() bool {
+ return s.emailSender != nil && s.emailSender.IsConfigured()
+}
+
func (s *SettingsService) UpdateSettings(
ctx context.Context,
- request users_models.UsersSettings,
+ request users_dto.UpdateSettingsRequestDTO,
updatedBy *users_models.User,
-) (*users_models.UsersSettings, error) {
+) (*users_dto.SettingsResponseDTO, error) {
if !updatedBy.CanUpdateSettings() {
return nil, fmt.Errorf("insufficient permissions to update settings")
}
@@ -37,34 +67,57 @@ func (s *SettingsService) UpdateSettings(
return nil, fmt.Errorf("failed to get current settings: %w", err)
}
- auditLogMessages := []string{}
+ if request.IsTwoFactorAuthRequired && !existingSettings.IsTwoFactorAuthRequired {
+ if err := s.checkCodesCanReachEveryAdmin(ctx); err != nil {
+ return nil, err
+ }
+ }
- if request.IsAllowExternalRegistrations != existingSettings.IsAllowExternalRegistrations {
- existingSettings.IsAllowExternalRegistrations = request.IsAllowExternalRegistrations
- auditLogMessages = append(
- auditLogMessages,
- fmt.Sprintf(
- "isAllowExternalRegistrations: %t -> %t",
- existingSettings.IsAllowExternalRegistrations,
- request.IsAllowExternalRegistrations,
- ),
- )
+ switches := []struct {
+ name string
+ current *bool
+ proposed bool
+ }{
+ {
+ "isAllowExternalRegistrations",
+ &existingSettings.IsAllowExternalRegistrations,
+ request.IsAllowExternalRegistrations,
+ },
+ {
+ "isAllowMemberInvitations",
+ &existingSettings.IsAllowMemberInvitations,
+ request.IsAllowMemberInvitations,
+ },
+ {
+ "isMemberAllowedToCreateWorkspaces",
+ &existingSettings.IsMemberAllowedToCreateWorkspaces,
+ request.IsMemberAllowedToCreateWorkspaces,
+ },
+ {
+ "isTwoFactorAuthRequired",
+ &existingSettings.IsTwoFactorAuthRequired,
+ request.IsTwoFactorAuthRequired,
+ },
}
- if request.IsAllowMemberInvitations != existingSettings.IsAllowMemberInvitations {
- existingSettings.IsAllowMemberInvitations = request.IsAllowMemberInvitations
+ auditLogMessages := []string{}
+
+ for _, settingSwitch := range switches {
+ if *settingSwitch.current == settingSwitch.proposed {
+ continue
+ }
+
auditLogMessages = append(
auditLogMessages,
fmt.Sprintf(
- "isAllowMemberInvitations: %t -> %t",
- existingSettings.IsAllowMemberInvitations,
- request.IsAllowMemberInvitations,
+ "%s: %t -> %t",
+ settingSwitch.name,
+ *settingSwitch.current,
+ settingSwitch.proposed,
),
)
- }
- if request.IsMemberAllowedToCreateWorkspaces != existingSettings.IsMemberAllowedToCreateWorkspaces {
- existingSettings.IsMemberAllowedToCreateWorkspaces = request.IsMemberAllowedToCreateWorkspaces
+ *settingSwitch.current = settingSwitch.proposed
}
if err := s.userSettingsRepository.UpdateSettings(ctx, existingSettings); err != nil {
@@ -72,12 +125,94 @@ func (s *SettingsService) UpdateSettings(
}
for _, message := range auditLogMessages {
- s.auditLogWriter.WriteAuditLog(ctx, audit_logs_models.AuditEntry{
+ s.writeAuditLog(ctx, audit_logs_models.AuditEntry{
Message: message,
UserID: &updatedBy.ID,
WorkspaceID: nil,
})
}
- return existingSettings, nil
+ return s.buildSettingsResponse(existingSettings), nil
+}
+
+// DisableTwoFactorAuth is the way back into an instance whose mail server has
+// died, so it takes no caller and asks no permission: whoever can run it already
+// runs commands inside the instance. The entry it writes is what keeps the host
+// from being a way to move a security switch unobserved.
+func (s *SettingsService) DisableTwoFactorAuth(ctx context.Context) (bool, error) {
+ settings, err := s.userSettingsRepository.GetSettings(ctx)
+ if err != nil {
+ return false, fmt.Errorf("failed to get current settings: %w", err)
+ }
+
+ if !settings.IsTwoFactorAuthRequired {
+ return false, nil
+ }
+
+ settings.IsTwoFactorAuthRequired = false
+
+ if err := s.userSettingsRepository.UpdateSettings(ctx, settings); err != nil {
+ return false, fmt.Errorf("failed to update settings: %w", err)
+ }
+
+ s.writeAuditLog(ctx, audit_logs_models.AuditEntry{
+ Message: "isTwoFactorAuthRequired: true -> false (switched off from the host console)",
+ UserID: nil,
+ WorkspaceID: nil,
+ })
+
+ return true, nil
+}
+
+// Turning the second factor on is what locks an instance out, so both ways that
+// can happen are refused here: no mail server at all, and an administrator whose
+// address no message can reach.
+func (s *SettingsService) checkCodesCanReachEveryAdmin(ctx context.Context) error {
+ if !s.IsEmailConfigured() {
+ return fmt.Errorf(
+ "cannot require two-factor authentication: the instance has no mail server configured",
+ )
+ }
+
+ admins, err := s.userRepository.GetAdmins(ctx)
+ if err != nil {
+ return fmt.Errorf("failed to list administrators: %w", err)
+ }
+
+ for _, admin := range admins {
+ if !admin.IsActiveUser() {
+ continue
+ }
+
+ if addressValidator.Var(admin.Email, "required,email") != nil {
+ return fmt.Errorf(
+ "cannot require two-factor authentication: administrator %q has no valid email address",
+ admin.Email,
+ )
+ }
+ }
+
+ return nil
+}
+
+func (s *SettingsService) buildSettingsResponse(
+ settings *users_models.UsersSettings,
+) *users_dto.SettingsResponseDTO {
+ return &users_dto.SettingsResponseDTO{
+ IsAllowExternalRegistrations: settings.IsAllowExternalRegistrations,
+ IsAllowMemberInvitations: settings.IsAllowMemberInvitations,
+ IsMemberAllowedToCreateWorkspaces: settings.IsMemberAllowedToCreateWorkspaces,
+ IsTwoFactorAuthRequired: settings.IsTwoFactorAuthRequired,
+ IsEmailConfigured: s.IsEmailConfigured(),
+ }
+}
+
+// The console commands reach this service without installing a writer, and a
+// missing entry must not take the process down.
+func (s *SettingsService) writeAuditLog(ctx context.Context, entry audit_logs_models.AuditEntry) {
+ if s.auditLogWriter == nil {
+ return
+ }
+
+ s.auditLogWriter.WriteAuditLog(ctx, entry)
}
diff --git a/backend/internal/features/users/services/two_factor_auth.go b/backend/internal/features/users/services/two_factor_auth.go
new file mode 100644
index 00000000..93586206
--- /dev/null
+++ b/backend/internal/features/users/services/two_factor_auth.go
@@ -0,0 +1,278 @@
+package users_services
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "io"
+ "time"
+
+ "github.com/google/uuid"
+ "golang.org/x/crypto/bcrypt"
+
+ audit_logs_models "databasus-backend/internal/features/audit_logs/models"
+ users_dto "databasus-backend/internal/features/users/dto"
+ users_errors "databasus-backend/internal/features/users/errors"
+ users_models "databasus-backend/internal/features/users/models"
+ users_repositories "databasus-backend/internal/features/users/repositories"
+ "databasus-backend/internal/util/ratelimiter"
+)
+
+const (
+ twoFactorCodeLifetime = 10 * time.Minute
+
+ // A row is counted for an hour and swept once it is older, so the window the
+ // cap reads over and the window the rows survive are the same hour.
+ twoFactorCodeRetention = time.Hour
+
+ maxTwoFactorCodesPerHour int64 = 5
+
+ twoFactorResendScope = "signin-code-resend"
+ twoFactorResendWindow = time.Minute
+)
+
+// StartTwoFactorSignIn is reached only once the password has been accepted. A
+// pending sign-in that is still live is handed back unchanged, so reloading the
+// code screen neither sends a second message nor spends the hourly allowance.
+func (s *UserService) StartTwoFactorSignIn(
+ ctx context.Context,
+ user *users_models.User,
+) (*users_dto.PendingSignInResponseDTO, error) {
+ return s.issueTwoFactorCode(ctx, user, true)
+}
+
+func (s *UserService) VerifyTwoFactorCode(
+ ctx context.Context,
+ pendingSignInID uuid.UUID,
+ code string,
+) (*users_dto.SignInResponseDTO, error) {
+ pendingCode, user, err := s.loadUsablePendingSignIn(ctx, pendingSignInID)
+ if err != nil {
+ return nil, err
+ }
+
+ attemptCount, isAttemptClaimed, err := s.twoFactorRepository.ClaimAttempt(ctx, pendingCode.ID)
+ if err != nil {
+ return nil, fmt.Errorf("failed to count the sign-in attempt: %w", err)
+ }
+
+ if !isAttemptClaimed {
+ return nil, users_errors.ErrPendingSignInNotUsable
+ }
+
+ if bcrypt.CompareHashAndPassword([]byte(pendingCode.HashedCode), []byte(code)) != nil {
+ return nil, s.refuseWrongTwoFactorCode(ctx, attemptCount, user)
+ }
+
+ isSpent, err := s.twoFactorRepository.SpendCode(ctx, pendingCode.ID)
+ if err != nil {
+ return nil, fmt.Errorf("failed to spend the sign-in code: %w", err)
+ }
+
+ if !isSpent {
+ return nil, users_errors.ErrPendingSignInNotUsable
+ }
+
+ return s.completeSignIn(ctx, user)
+}
+
+// The previous code is invalidated only once the replacement is on its way, so a
+// refused resend leaves the user with the code they already have.
+func (s *UserService) ResendTwoFactorCode(
+ ctx context.Context,
+ pendingSignInID uuid.UUID,
+) (*users_dto.PendingSignInResponseDTO, error) {
+ pendingCode, user, err := s.loadUsablePendingSignIn(ctx, pendingSignInID)
+ if err != nil {
+ return nil, err
+ }
+
+ isAllowed, err := s.rateLimiter.RecordAttemptAndCheckIsAllowed(ctx, ratelimiter.Attempt{
+ Scope: twoFactorResendScope,
+ Identifier: user.ID.String(),
+ Limit: 1,
+ Window: twoFactorResendWindow,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("failed to evaluate the sign-in code resend limit: %w", err)
+ }
+
+ if !isAllowed {
+ return nil, users_errors.ErrSignInCodeResentTooSoon
+ }
+
+ pendingSignIn, err := s.issueTwoFactorCode(ctx, user, false)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := s.twoFactorRepository.MarkCodeAsUsed(ctx, pendingCode.ID); err != nil {
+ return nil, fmt.Errorf("failed to invalidate the previous sign-in code: %w", err)
+ }
+
+ return pendingSignIn, nil
+}
+
+func (s *UserService) SweepPendingSignInsPastRetention(ctx context.Context) error {
+ return s.twoFactorRepository.DeleteCodesCreatedBefore(
+ ctx,
+ time.Now().UTC().Add(-twoFactorCodeRetention),
+ )
+}
+
+func (s *UserService) SweepExpiredPasswordResetCodes() error {
+ return s.passwordResetRepository.DeleteExpiredCodes()
+}
+
+// The pending sign-in proves that a password was correct minutes ago, not that
+// the account may be let in now, so the checks the password step made are made
+// again. The second-factor setting is deliberately not among them: switching it
+// off must not strand somebody holding a code.
+func (s *UserService) loadUsablePendingSignIn(
+ ctx context.Context,
+ pendingSignInID uuid.UUID,
+) (*users_models.TwoFactorCode, *users_models.User, error) {
+ pendingCode, err := s.twoFactorRepository.GetCodeByID(ctx, pendingSignInID)
+ if err != nil {
+ return nil, nil, fmt.Errorf("failed to load the pending sign-in: %w", err)
+ }
+
+ if pendingCode == nil || !pendingCode.IsValid() {
+ return nil, nil, users_errors.ErrPendingSignInNotUsable
+ }
+
+ user, err := s.userRepository.GetUserByID(ctx, pendingCode.UserID)
+ if err != nil || user == nil {
+ return nil, nil, users_errors.ErrPendingSignInNotUsable
+ }
+
+ if !user.IsActiveUser() {
+ return nil, nil, users_errors.ErrPendingSignInNotUsable
+ }
+
+ if !user.PasswordCreationTime.Truncate(time.Microsecond).
+ Equal(pendingCode.PasswordCreationTime.Truncate(time.Microsecond)) {
+ return nil, nil, users_errors.ErrPendingSignInNotUsable
+ }
+
+ return pendingCode, user, nil
+}
+
+func (s *UserService) refuseWrongTwoFactorCode(
+ ctx context.Context,
+ attemptCount int,
+ user *users_models.User,
+) error {
+ if attemptCount < users_models.MaxTwoFactorCodeAttempts {
+ return users_errors.ErrSignInCodeIncorrect
+ }
+
+ s.writeAuditLog(ctx, audit_logs_models.AuditEntry{
+ Message: fmt.Sprintf(
+ "Two-factor sign-in abandoned after too many incorrect codes: %s",
+ user.Email,
+ ),
+ UserID: &user.ID,
+ WorkspaceID: nil,
+ })
+
+ return users_errors.ErrPendingSignInNotUsable
+}
+
+// Nothing is created before the instance has said it can deliver, and a send
+// that fails leaves the row it counted behind while making it unusable, so the
+// caller never sees a code screen for a message that will not arrive. A resend
+// replaces the live code, so only the password step hands a live one back.
+func (s *UserService) issueTwoFactorCode(
+ ctx context.Context,
+ user *users_models.User,
+ shouldReuseLiveCode bool,
+) (*users_dto.PendingSignInResponseDTO, error) {
+ if s.emailSender == nil || !s.emailSender.IsConfigured() {
+ s.logger.ErrorContext(ctx, "sign-in code not sent: the instance has no mail server",
+ "user_id", user.ID)
+
+ return nil, users_errors.ErrSignInCodeNotSent
+ }
+
+ code, err := generateSixDigitCode()
+ if err != nil {
+ return nil, err
+ }
+
+ hashedCode, err := bcrypt.GenerateFromPassword([]byte(code), bcrypt.DefaultCost)
+ if err != nil {
+ return nil, fmt.Errorf("failed to hash the sign-in code: %w", err)
+ }
+
+ now := time.Now().UTC()
+ pendingCode := &users_models.TwoFactorCode{
+ ID: uuid.New(),
+ UserID: user.ID,
+ HashedCode: string(hashedCode),
+ PasswordCreationTime: user.PasswordCreationTime,
+ ExpiresAt: now.Add(twoFactorCodeLifetime),
+ IsUsed: false,
+ FailedAttemptCount: 0,
+ CreatedAt: now,
+ }
+ countedSince := now.Add(-twoFactorCodeRetention)
+
+ if shouldReuseLiveCode {
+ liveCode, err := s.twoFactorRepository.CreateCodeUnlessLive(
+ ctx, pendingCode, countedSince, maxTwoFactorCodesPerHour,
+ )
+ if err != nil {
+ return nil, toIssueError(err)
+ }
+
+ if liveCode != nil {
+ return &users_dto.PendingSignInResponseDTO{
+ PendingSignInID: liveCode.ID,
+ Email: user.Email,
+ }, nil
+ }
+ } else {
+ err := s.twoFactorRepository.CreateCodeWithinHourlyCap(
+ ctx, pendingCode, countedSince, maxTwoFactorCodesPerHour,
+ )
+ if err != nil {
+ return nil, toIssueError(err)
+ }
+ }
+
+ if err := s.emailSender.SendEmail(user.Email, twoFactorCodeSubject, twoFactorCodeBody(code)); err != nil {
+ s.logger.ErrorContext(ctx, "failed to send the sign-in code", "user_id", user.ID, "error", err)
+
+ if markErr := s.twoFactorRepository.MarkCodeAsUsed(ctx, pendingCode.ID); markErr != nil {
+ s.logger.ErrorContext(ctx, "failed to discard an unsent pending sign-in",
+ "user_id", user.ID, "error", markErr)
+ }
+
+ return nil, users_errors.ErrSignInCodeNotSent
+ }
+
+ return &users_dto.PendingSignInResponseDTO{
+ PendingSignInID: pendingCode.ID,
+ Email: user.Email,
+ }, nil
+}
+
+func toIssueError(err error) error {
+ if errors.Is(err, users_repositories.ErrHourlyCodeCapReached) {
+ return users_errors.ErrTooManySignInCodes
+ }
+
+ return fmt.Errorf("failed to create the pending sign-in: %w", err)
+}
+
+func generateSixDigitCode() (string, error) {
+ randomBytes := make([]byte, 4)
+ if _, err := io.ReadFull(rand.Reader, randomBytes); err != nil {
+ return "", fmt.Errorf("failed to generate the sign-in code: %w", err)
+ }
+
+ return fmt.Sprintf("%06d", binary.BigEndian.Uint32(randomBytes)%1000000), nil
+}
diff --git a/backend/internal/features/users/services/two_factor_email.go b/backend/internal/features/users/services/two_factor_email.go
new file mode 100644
index 00000000..8a43c81b
--- /dev/null
+++ b/backend/internal/features/users/services/two_factor_email.go
@@ -0,0 +1,41 @@
+package users_services
+
+import "fmt"
+
+const twoFactorCodeSubject = "Sign-In Code"
+
+func twoFactorCodeBody(code string) string {
+ return fmt.Sprintf(`
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+</head>
+<body style="margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;">
+ <div style="max-width: 600px; margin: 0 auto; background-color: #ffffff; padding: 20px;">
+ <h2 style="color: #333333; margin-bottom: 20px;">Sign-In Code</h2>
+ <p style="color: #666666; line-height: 1.6; margin-bottom: 20px;">
+ Somebody signed in to Databasus with your password. Enter the following code to finish signing in:
+ </p>
+ <div style="background-color: #f8f9fa; border: 2px solid #e9ecef; border-radius: 8px; padding: 20px; text-align: center; margin: 30px 0;">
+ <h1 style="color: #2c3e50; font-size: 36px; margin: 0; letter-spacing: 8px; font-family: monospace;">%s</h1>
+ </div>
+ <p style="color: #666666; line-height: 1.6; margin-bottom: 20px;">
+ This code stops working <strong>10 minutes</strong> after it was sent.
+ </p>
+ <p style="color: #666666; line-height: 1.6; margin-bottom: 20px;">
+ Requesting another code replaces this one, so only the newest code works.
+ </p>
+ <p style="color: #666666; line-height: 1.6; margin-bottom: 20px;">
+ If you did not try to sign in, change your password: somebody else knows it.
+ </p>
+ <hr style="border: none; border-top: 1px solid #e9ecef; margin: 30px 0;">
+ <p style="color: #999999; font-size: 12px; line-height: 1.6;">
+ This is an automated message. Please do not reply to this email.
+ </p>
+ </div>
+</body>
+</html>
+`, code)
+}
diff --git a/backend/internal/features/users/services/user_services.go b/backend/internal/features/users/services/user_services.go
index 8cb93fd6..38b45b83 100644
--- a/backend/internal/features/users/services/user_services.go
+++ b/backend/internal/features/users/services/user_services.go
@@ -2,7 +2,6 @@ package users_services
import (
"context"
- "crypto/rand"
"encoding/json"
"errors"
"fmt"
@@ -28,6 +27,7 @@ import (
users_interfaces "databasus-backend/internal/features/users/interfaces"
users_models "databasus-backend/internal/features/users/models"
users_repositories "databasus-backend/internal/features/users/repositories"
+ "databasus-backend/internal/util/ratelimiter"
)
// bootstrapAdminIndexName is the partial unique index that admits a single
@@ -42,6 +42,8 @@ type UserService struct {
auditLogWriter users_interfaces.AuditLogWriter
emailSender users_interfaces.EmailSender
passwordResetRepository *users_repositories.PasswordResetRepository
+ twoFactorRepository *users_repositories.TwoFactorRepository
+ rateLimiter ratelimiter.Counter
logger *slog.Logger
}
@@ -136,7 +138,7 @@ func isBootstrapAdminTaken(err error) bool {
func (s *UserService) SignIn(
ctx context.Context,
request *users_dto.SignInRequestDTO,
-) (*users_dto.SignInResponseDTO, error) {
+) (*users_dto.SignInOutcome, error) {
// Failed sign-ins are the only signal that someone is guessing credentials, so every branch that
// refuses one is logged. The handler's addresses are masked centrally by the log handler.
user, err := s.userRepository.GetUserByEmail(ctx, request.Email)
@@ -181,20 +183,26 @@ func (s *UserService) SignIn(
return nil, errors.New("password is incorrect")
}
- s.logger.InfoContext(ctx, "user signed in", "user_id", user.ID)
+ settings, err := s.settingsService.GetSettings(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("failed to get settings: %w", err)
+ }
- response, err := s.GenerateAccessToken(ctx, user)
+ if settings.IsTwoFactorAuthRequired {
+ pendingSignIn, err := s.StartTwoFactorSignIn(ctx, user)
+ if err != nil {
+ return nil, err
+ }
+
+ return &users_dto.SignInOutcome{PendingSignIn: pendingSignIn}, nil
+ }
+
+ response, err := s.completeSignIn(ctx, user)
if err != nil {
return nil, err
}
- s.writeAuditLog(ctx, audit_logs_models.AuditEntry{
- Message: fmt.Sprintf("User signed in with email: %s", user.Email),
- UserID: &user.ID,
- WorkspaceID: nil,
- })
-
- return response, nil
+ return &users_dto.SignInOutcome{CompletedSignIn: response}, nil
}
func (s *UserService) GetUserFromToken(ctx context.Context, token string) (*users_models.User, error) {
@@ -521,26 +529,11 @@ func (s *UserService) SendResetPasswordCode(ctx context.Context, email string) e
return errors.New("too many password reset attempts, please try again later")
}
- // Generate 6-digit random code using crypto/rand for better randomness
- codeNum := make([]byte, 4)
- _, err = io.ReadFull(rand.Reader, codeNum)
+ code, err := generateSixDigitCode()
if err != nil {
- return fmt.Errorf("failed to generate random code: %w", err)
- }
-
- // Convert bytes to uint32 and modulo to get 6 digits
- randomInt := uint32(
- codeNum[0],
- )<<24 | uint32(
- codeNum[1],
- )<<16 | uint32(
- codeNum[2],
- )<<8 | uint32(
- codeNum[3],
- )
- code := fmt.Sprintf("%06d", randomInt%1000000)
+ return err
+ }
- // Hash the code
hashedCode, err := bcrypt.GenerateFromPassword([]byte(code), bcrypt.DefaultCost)
if err != nil {
return fmt.Errorf("failed to hash code: %w", err)
@@ -651,6 +644,28 @@ func (s *UserService) ResetPassword(ctx context.Context, email, code, newPasswor
return nil
}
+// The audit trail records a sign-in where access is actually granted, which is
+// the password step with one factor and the code step with two.
+func (s *UserService) completeSignIn(
+ ctx context.Context,
+ user *users_models.User,
+) (*users_dto.SignInResponseDTO, error) {
+ s.logger.InfoContext(ctx, "user signed in", "user_id", user.ID)
+
+ response, err := s.GenerateAccessToken(ctx, user)
+ if err != nil {
+ return nil, err
+ }
+
+ s.writeAuditLog(ctx, audit_logs_models.AuditEntry{
+ Message: fmt.Sprintf("User signed in with email: %s", user.Email),
+ UserID: &user.ID,
+ WorkspaceID: nil,
+ })
+
+ return response, nil
+}
+
// Every audit entry this service writes goes through here, because the console
// path reaches the service without installing a writer and a missing entry must
// not take the process down.
diff --git a/backend/internal/features/users/testing/mocks.go b/backend/internal/features/users/testing/mocks.go
index 93b85b38..450dceee 100644
--- a/backend/internal/features/users/testing/mocks.go
+++ b/backend/internal/features/users/testing/mocks.go
@@ -1,10 +1,17 @@
package users_testing
-import "errors"
+import (
+ "errors"
+ "sync"
+)
type MockEmailSender struct {
- SentEmails []EmailCall
- ShouldFail bool
+ SentEmails []EmailCall
+ ShouldFail bool
+ IsMailServerMissing bool
+
+ // Concurrent sign-in tests send from several requests at once.
+ sentEmailsMutex sync.Mutex
}
type EmailCall struct {
@@ -20,7 +27,14 @@ func NewMockEmailSender() *MockEmailSender {
}
}
+func (m *MockEmailSender) IsConfigured() bool {
+ return !m.IsMailServerMissing
+}
+
func (m *MockEmailSender) SendEmail(to, subject, body string) error {
+ m.sentEmailsMutex.Lock()
+ defer m.sentEmailsMutex.Unlock()
+
m.SentEmails = append(m.SentEmails, EmailCall{
To: to,
Subject: subject,
diff --git a/backend/internal/features/users/testing/settings_utils.go b/backend/internal/features/users/testing/settings_utils.go
index 307d9393..55af1a89 100644
--- a/backend/internal/features/users/testing/settings_utils.go
+++ b/backend/internal/features/users/testing/settings_utils.go
@@ -30,6 +30,14 @@ func DisableMemberWorkspaceCreation(ctx context.Context) {
updateUsersSetting(ctx, "is_member_allowed_to_create_workspaces", false)
}
+func EnableTwoFactorAuth(ctx context.Context) {
+ updateUsersSetting(ctx, "is_two_factor_auth_required", true)
+}
+
+func DisableTwoFactorAuth(ctx context.Context) {
+ updateUsersSetting(ctx, "is_two_factor_auth_required", false)
+}
+
func ResetSettingsToDefaults(ctx context.Context) {
repository := &users_repositories.UsersSettingsRepository{}
settings, err := repository.GetSettings(ctx)
@@ -40,6 +48,7 @@ func ResetSettingsToDefaults(ctx context.Context) {
settings.IsAllowExternalRegistrations = true
settings.IsAllowMemberInvitations = true
settings.IsMemberAllowedToCreateWorkspaces = true
+ settings.IsTwoFactorAuthRequired = false
err = repository.UpdateSettings(ctx, settings)
if err != nil {
@@ -61,6 +70,8 @@ func updateUsersSetting(ctx context.Context, column string, value bool) {
settings.IsAllowExternalRegistrations = value
case "is_member_allowed_to_create_workspaces":
settings.IsMemberAllowedToCreateWorkspaces = value
+ case "is_two_factor_auth_required":
+ settings.IsTwoFactorAuthRequired = value
}
err = repository.UpdateSettings(ctx, settings)
diff --git a/backend/internal/features/users/testing/user_utils.go b/backend/internal/features/users/testing/user_utils.go
index 94c18a34..d093b601 100644
--- a/backend/internal/features/users/testing/user_utils.go
+++ b/backend/internal/features/users/testing/user_utils.go
@@ -29,6 +29,46 @@ func CreateTestUser(ctx context.Context, role users_enums.UserRole) *users_dto.S
return response
}
+// An address the profile form would refuse is only reachable this way: the API
+// binds the address of every account it creates.
+func CreateTestUserWithEmail(
+ ctx context.Context,
+ role users_enums.UserRole,
+ email string,
+) *users_dto.SignInResponseDTO {
+ user := insertTestUser(role, false)
+
+ if err := storage.GetDb().WithContext(ctx).Model(&users_models.User{}).
+ Where("id = ?", user.ID).
+ Update("email", email).Error; err != nil {
+ panic(fmt.Errorf("failed to set the address of a test user: %w", err))
+ }
+
+ response, err := users_services.GetUserService().GenerateAccessToken(ctx, user)
+ if err != nil {
+ panic(err)
+ }
+
+ response.Email = email
+
+ return response
+}
+
+func DeactivateTestUser(ctx context.Context, userID uuid.UUID) {
+ userRepository := &users_repositories.UserRepository{}
+ if err := userRepository.UpdateUserStatus(userID, users_enums.UserStatusInactive); err != nil {
+ panic(fmt.Errorf("failed to deactivate a test user: %w", err))
+ }
+}
+
+func DeleteTestUser(ctx context.Context, userID uuid.UUID) {
+ if err := storage.GetDb().WithContext(ctx).
+ Where("id = ?", userID).
+ Delete(&users_models.User{}).Error; err != nil {
+ panic(fmt.Errorf("failed to delete a test user: %w", err))
+ }
+}
+
// The token is minted from the account RecreateInitialAdmin just created rather
// than read back by address, which would hand a nil user to GenerateAccessToken
// once that address changes.
diff --git a/backend/internal/util/cloudflare_turnstile/testing.go b/backend/internal/util/cloudflare_turnstile/testing.go
new file mode 100644
index 00000000..fbf1a858
--- /dev/null
+++ b/backend/internal/util/cloudflare_turnstile/testing.go
@@ -0,0 +1,13 @@
+package cloudflare_turnstile
+
+// A test that has to see an endpoint refuse an unanswered challenge cannot get
+// there through the environment, because the service reads it once at startup.
+// The returned function puts the previous key back.
+func EnableChallengeForTesting(secretKey string) func() {
+ previousSecretKey := cloudflareTurnstileService.secretKey
+ cloudflareTurnstileService.secretKey = secretKey
+
+ return func() {
+ cloudflareTurnstileService.secretKey = previousSecretKey
+ }
+}
diff --git a/backend/migrations/20260920215925_add_two_factor_auth.sql b/backend/migrations/20260920215925_add_two_factor_auth.sql
new file mode 100644
index 00000000..2c5b97c8
--- /dev/null
+++ b/backend/migrations/20260920215925_add_two_factor_auth.sql
@@ -0,0 +1,57 @@
+-- +goose Up
+-- +goose StatementBegin
+
+ALTER TABLE users_settings
+ ADD COLUMN is_two_factor_auth_required BOOLEAN NOT NULL DEFAULT FALSE;
+
+-- One row is one code issued to one account: the password step created it, the
+-- verification step spends it, and the hourly cap counts the rows an account
+-- collected. That is why a row outlives the ten minutes its code works for.
+CREATE TABLE two_factor_codes (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id UUID NOT NULL,
+ hashed_code TEXT NOT NULL,
+ -- The password the first step accepted. The second step refuses a row whose
+ -- account has changed its password since, because that change is what
+ -- invalidates tokens already issued.
+ password_creation_time TIMESTAMPTZ NOT NULL,
+ expires_at TIMESTAMPTZ NOT NULL,
+ is_used BOOLEAN NOT NULL DEFAULT FALSE,
+ failed_attempt_count INTEGER NOT NULL DEFAULT 0,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+ALTER TABLE two_factor_codes
+ ADD CONSTRAINT fk_two_factor_codes_user_id
+ FOREIGN KEY (user_id)
+ REFERENCES users (id)
+ ON DELETE CASCADE;
+
+ALTER TABLE two_factor_codes
+ ADD CONSTRAINT ck_two_factor_codes_failed_attempt_count_not_negative CHECK (failed_attempt_count >= 0);
+
+CREATE INDEX idx_two_factor_codes_user_id ON two_factor_codes (user_id);
+
+-- The hourly cap and the sweep both read this column.
+CREATE INDEX idx_two_factor_codes_created_at ON two_factor_codes (created_at);
+
+-- +goose StatementEnd
+
+-- +goose Down
+-- +goose StatementBegin
+
+DROP INDEX IF EXISTS idx_two_factor_codes_created_at;
+DROP INDEX IF EXISTS idx_two_factor_codes_user_id;
+
+ALTER TABLE two_factor_codes
+ DROP CONSTRAINT IF EXISTS ck_two_factor_codes_failed_attempt_count_not_negative;
+
+ALTER TABLE two_factor_codes
+ DROP CONSTRAINT IF EXISTS fk_two_factor_codes_user_id;
+
+DROP TABLE IF EXISTS two_factor_codes;
+
+ALTER TABLE users_settings
+ DROP COLUMN IF EXISTS is_two_factor_auth_required;
+
+-- +goose StatementEnd
diff --git a/frontend/src/entity/users/api/readSignInOutcome.test.ts b/frontend/src/entity/users/api/readSignInOutcome.test.ts
new file mode 100644
index 00000000..aeb89ddb
--- /dev/null
+++ b/frontend/src/entity/users/api/readSignInOutcome.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+
+import { readSignInOutcome } from './readSignInOutcome';
+
+describe('readSignInOutcome', () => {
+ it('reads a finished sign-in from a body carrying a token', () => {
+ const outcome = readSignInOutcome({ userId: 'user-1', email: '[email protected]', token: 'jwt' });
+
+ expect(outcome.isCompleted).toBe(true);
+ expect(outcome.isCompleted && outcome.signIn.token).toBe('jwt');
+ });
+
+ it('reads a pending sign-in from a body carrying an identifier', () => {
+ const outcome = readSignInOutcome({ pendingSignInId: 'pending-1', email: '[email protected]' });
+
+ expect(outcome.isCompleted).toBe(false);
+ expect(!outcome.isCompleted && outcome.pendingSignIn.pendingSignInId).toBe('pending-1');
+ });
+
+ it('refuses a body carrying neither', () => {
+ expect(() => readSignInOutcome({ email: '[email protected]' })).toThrow();
+ });
+});
diff --git a/frontend/src/entity/users/api/readSignInOutcome.ts b/frontend/src/entity/users/api/readSignInOutcome.ts
new file mode 100644
index 00000000..cf8f9d48
--- /dev/null
+++ b/frontend/src/entity/users/api/readSignInOutcome.ts
@@ -0,0 +1,20 @@
+import type { PendingSignIn } from '../model/PendingSignIn';
+import type { SignInOutcome } from '../model/SignInOutcome';
+import type { SignInResponse } from '../model/SignInResponse';
+
+// Only the finished shape carries a token, so the token is what tells the two
+// apart. A body carrying neither is a backend the client does not understand,
+// and storing nothing is safer than storing an empty token.
+export const readSignInOutcome = (response: unknown): SignInOutcome => {
+ const body = response as Partial<SignInResponse & PendingSignIn> | null;
+
+ if (body?.token) {
+ return { isCompleted: true, signIn: body as SignInResponse };
+ }
+
+ if (body?.pendingSignInId) {
+ return { isCompleted: false, pendingSignIn: body as PendingSignIn };
+ }
+
+ throw new Error('sign-in response carries neither a token nor a pending sign-in');
+};
diff --git a/frontend/src/entity/users/api/settingsApi.ts b/frontend/src/entity/users/api/settingsApi.ts
index 28b8ba22..6ef29388 100644
--- a/frontend/src/entity/users/api/settingsApi.ts
+++ b/frontend/src/entity/users/api/settingsApi.ts
@@ -2,9 +2,10 @@ import { getApplicationServer } from '../../../constants';
import RequestOptions from '../../../shared/api/RequestOptions';
import { apiHelper } from '../../../shared/api/apiHelper';
import type { UsersSettings } from '../model/UsersSettings';
+import type { UsersSettingsResponse } from '../model/UsersSettingsResponse';
export const settingsApi = {
- async getSettings(): Promise<UsersSettings> {
+ async getSettings(): Promise<UsersSettingsResponse> {
const requestOptions: RequestOptions = new RequestOptions();
return apiHelper.fetchGetJson(
`${getApplicationServer()}/api/v1/users/settings`,
@@ -12,7 +13,7 @@ export const settingsApi = {
);
},
- async updateSettings(settings: UsersSettings): Promise<UsersSettings> {
+ async updateSettings(settings: UsersSettings): Promise<UsersSettingsResponse> {
const requestOptions: RequestOptions = new RequestOptions();
requestOptions.setBody(JSON.stringify(settings));
return apiHelper.fetchPutJson(
diff --git a/frontend/src/entity/users/api/userApi.ts b/frontend/src/entity/users/api/userApi.ts
index 877e7659..1b626a45 100644
--- a/frontend/src/entity/users/api/userApi.ts
+++ b/frontend/src/entity/users/api/userApi.ts
@@ -7,13 +7,18 @@ import type { InviteUserRequest } from '../model/InviteUserRequest';
import type { InviteUserResponse } from '../model/InviteUserResponse';
import type { OAuthCallbackRequest } from '../model/OAuthCallbackRequest';
import type { OAuthCallbackResponse } from '../model/OAuthCallbackResponse';
+import type { PendingSignIn } from '../model/PendingSignIn';
+import type { ResendSignInCodeRequest } from '../model/ResendSignInCodeRequest';
import type { ResetPasswordRequest } from '../model/ResetPasswordRequest';
import type { SendResetPasswordCodeRequest } from '../model/SendResetPasswordCodeRequest';
+import type { SignInOutcome } from '../model/SignInOutcome';
import type { SignInRequest } from '../model/SignInRequest';
import type { SignInResponse } from '../model/SignInResponse';
import type { SignUpRequest } from '../model/SignUpRequest';
import type { UpdateUserInfoRequest } from '../model/UpdateUserInfoRequest';
import type { UserProfile } from '../model/UserProfile';
+import type { VerifySignInCodeRequest } from '../model/VerifySignInCodeRequest';
+import { readSignInOutcome } from './readSignInOutcome';
const listeners: (() => void)[] = [];
@@ -43,12 +48,30 @@ export const userApi = {
});
},
- async signIn(signInRequest: SignInRequest): Promise<SignInResponse> {
+ async signIn(signInRequest: SignInRequest): Promise<SignInOutcome> {
const requestOptions: RequestOptions = new RequestOptions();
requestOptions.setBody(JSON.stringify(signInRequest));
return apiHelper
.fetchPostJson(`${getApplicationServer()}/api/v1/users/signin`, requestOptions)
+ .then((response: unknown): SignInOutcome => {
+ const outcome = readSignInOutcome(response);
+
+ if (outcome.isCompleted) {
+ saveAuthorizedData(outcome.signIn.token, outcome.signIn.userId);
+ notifyAuthListeners();
+ }
+
+ return outcome;
+ });
+ },
+
+ async verifySignInCode(request: VerifySignInCodeRequest): Promise<SignInResponse> {
+ const requestOptions: RequestOptions = new RequestOptions();
+ requestOptions.setBody(JSON.stringify(request));
+
+ return apiHelper
+ .fetchPostJson(`${getApplicationServer()}/api/v1/users/verify-signin-code`, requestOptions)
.then((response: unknown): SignInResponse => {
const typedResponse = response as SignInResponse;
saveAuthorizedData(typedResponse.token, typedResponse.userId);
@@ -57,6 +80,16 @@ export const userApi = {
});
},
+ async resendSignInCode(request: ResendSignInCodeRequest): Promise<PendingSignIn> {
+ const requestOptions: RequestOptions = new RequestOptions();
+ requestOptions.setBody(JSON.stringify(request));
+
+ return apiHelper.fetchPostJson(
+ `${getApplicationServer()}/api/v1/users/resend-signin-code`,
+ requestOptions,
+ );
+ },
+
async isAnyUserExists(): Promise<boolean> {
const requestOptions: RequestOptions = new RequestOptions();
return apiHelper
diff --git a/frontend/src/entity/users/index.ts b/frontend/src/entity/users/index.ts
index 85147f19..1021728f 100644
--- a/frontend/src/entity/users/index.ts
+++ b/frontend/src/entity/users/index.ts
@@ -6,6 +6,10 @@ export { userManagementApi } from './api/userManagementApi';
// Types and Enums
export type { SignInRequest } from './model/SignInRequest';
export type { SignInResponse } from './model/SignInResponse';
+export type { SignInOutcome } from './model/SignInOutcome';
+export type { PendingSignIn } from './model/PendingSignIn';
+export type { VerifySignInCodeRequest } from './model/VerifySignInCodeRequest';
+export type { ResendSignInCodeRequest } from './model/ResendSignInCodeRequest';
export type { SignUpRequest } from './model/SignUpRequest';
export type { ChangePasswordRequest } from './model/ChangePasswordRequest';
export type { InviteUserRequest } from './model/InviteUserRequest';
@@ -16,6 +20,7 @@ export type { ListUsersRequest } from './model/ListUsersRequest';
export type { ListUsersResponse } from './model/ListUsersResponse';
export type { ChangeUserRoleRequest } from './model/ChangeUserRoleRequest';
export type { UsersSettings } from './model/UsersSettings';
+export type { UsersSettingsResponse } from './model/UsersSettingsResponse';
export type { SendResetPasswordCodeRequest } from './model/SendResetPasswordCodeRequest';
export type { ResetPasswordRequest } from './model/ResetPasswordRequest';
export { UserRole } from './model/UserRole';
diff --git a/frontend/src/entity/users/model/PendingSignIn.ts b/frontend/src/entity/users/model/PendingSignIn.ts
new file mode 100644
index 00000000..b67f020c
--- /dev/null
+++ b/frontend/src/entity/users/model/PendingSignIn.ts
@@ -0,0 +1,4 @@
+export interface PendingSignIn {
+ pendingSignInId: string;
+ email: string;
+}
diff --git a/frontend/src/entity/users/model/ResendSignInCodeRequest.ts b/frontend/src/entity/users/model/ResendSignInCodeRequest.ts
new file mode 100644
index 00000000..fd988021
--- /dev/null
+++ b/frontend/src/entity/users/model/ResendSignInCodeRequest.ts
@@ -0,0 +1,4 @@
+export interface ResendSignInCodeRequest {
+ pendingSignInId: string;
+ cloudflareTurnstileToken?: string;
+}
diff --git a/frontend/src/entity/users/model/SignInOutcome.ts b/frontend/src/entity/users/model/SignInOutcome.ts
new file mode 100644
index 00000000..44e724bb
--- /dev/null
+++ b/frontend/src/entity/users/model/SignInOutcome.ts
@@ -0,0 +1,8 @@
+import type { PendingSignIn } from './PendingSignIn';
+import type { SignInResponse } from './SignInResponse';
+
+// A correct password produces one of these, never both: a finished sign-in when
+// the instance asks for one factor, and a pending one when it asks for a code.
+export type SignInOutcome =
+ | { isCompleted: true; signIn: SignInResponse }
+ | { isCompleted: false; pendingSignIn: PendingSignIn };
diff --git a/frontend/src/entity/users/model/UsersSettings.ts b/frontend/src/entity/users/model/UsersSettings.ts
index 67ff4e20..3e237a65 100644
--- a/frontend/src/entity/users/model/UsersSettings.ts
+++ b/frontend/src/entity/users/model/UsersSettings.ts
@@ -2,4 +2,5 @@ export interface UsersSettings {
isAllowExternalRegistrations: boolean;
isAllowMemberInvitations: boolean;
isMemberAllowedToCreateWorkspaces: boolean;
+ isTwoFactorAuthRequired: boolean;
}
diff --git a/frontend/src/entity/users/model/UsersSettingsResponse.ts b/frontend/src/entity/users/model/UsersSettingsResponse.ts
new file mode 100644
index 00000000..1af112aa
--- /dev/null
+++ b/frontend/src/entity/users/model/UsersSettingsResponse.ts
@@ -0,0 +1,7 @@
+import type { UsersSettings } from './UsersSettings';
+
+// The instance answers with its own judgement about the mail server, which the
+// settings screen needs and no request may set.
+export interface UsersSettingsResponse extends UsersSettings {
+ isEmailConfigured: boolean;
+}
diff --git a/frontend/src/entity/users/model/VerifySignInCodeRequest.ts b/frontend/src/entity/users/model/VerifySignInCodeRequest.ts
new file mode 100644
index 00000000..53fc9bb3
--- /dev/null
+++ b/frontend/src/entity/users/model/VerifySignInCodeRequest.ts
@@ -0,0 +1,5 @@
+export interface VerifySignInCodeRequest {
+ pendingSignInId: string;
+ code: string;
+ cloudflareTurnstileToken?: string;
+}
diff --git a/frontend/src/features/settings/ui/SettingsComponent.tsx b/frontend/src/features/settings/ui/SettingsComponent.tsx
index 45a8ea00..e38cbf23 100644
--- a/frontend/src/features/settings/ui/SettingsComponent.tsx
+++ b/frontend/src/features/settings/ui/SettingsComponent.tsx
@@ -4,8 +4,7 @@ import { useEffect, useRef, useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { getApplicationServer } from '../../../constants';
-import { settingsApi } from '../../../entity/users/api/settingsApi';
-import type { UsersSettings } from '../../../entity/users/model/UsersSettings';
+import { type UsersSettings, type UsersSettingsResponse, settingsApi } from '../../../entity/users';
import { getWebsitePageUrl, translateApiError, useLocale } from '../../../shared/i18n';
import { ClipboardHelper } from '../../../shared/lib/ClipboardHelper';
import { VerificationAgentsComponent } from '../../verification/agents';
@@ -15,11 +14,20 @@ interface Props {
contentHeight: number;
}
+// The response carries the instance's answer about its mail server, which the
+// form neither edits nor sends back.
+const toFormSettings = (settings: UsersSettingsResponse): UsersSettings => ({
+ isAllowExternalRegistrations: settings.isAllowExternalRegistrations,
+ isAllowMemberInvitations: settings.isAllowMemberInvitations,
+ isMemberAllowedToCreateWorkspaces: settings.isMemberAllowedToCreateWorkspaces,
+ isTwoFactorAuthRequired: settings.isTwoFactorAuthRequired,
+});
+
export function SettingsComponent({ contentHeight }: Props) {
const { t } = useTranslation();
const { locale } = useLocale();
const { message } = App.useApp();
- const [settings, setSettings] = useState<UsersSettings | undefined>(undefined);
+ const [settings, setSettings] = useState<UsersSettingsResponse | undefined>(undefined);
const [isLoading, setIsLoading] = useState(true);
const [isSaving, setIsSaving] = useState(false);
const [hasChanges, setHasChanges] = useState(false);
@@ -32,6 +40,7 @@ export function SettingsComponent({ contentHeight }: Props) {
isAllowExternalRegistrations: false,
isAllowMemberInvitations: false,
isMemberAllowedToCreateWorkspaces: false,
+ isTwoFactorAuthRequired: false,
});
useEffect(() => {
@@ -44,7 +53,7 @@ export function SettingsComponent({ contentHeight }: Props) {
try {
const currentSettings = await settingsApi.getSettings();
setSettings(currentSettings);
- setFormSettings(currentSettings);
+ setFormSettings(toFormSettings(currentSettings));
setHasChanges(false);
} catch (error: unknown) {
message.error(translateApiError(error, t));
@@ -75,7 +84,7 @@ export function SettingsComponent({ contentHeight }: Props) {
try {
const updatedSettings = await settingsApi.updateSettings(formSettings);
setSettings(updatedSettings);
- setFormSettings(updatedSettings);
+ setFormSettings(toFormSettings(updatedSettings));
setHasChanges(false);
message.success(t('settings.updated'));
} catch (error: unknown) {
@@ -87,7 +96,7 @@ export function SettingsComponent({ contentHeight }: Props) {
const handleReset = () => {
if (settings) {
- setFormSettings(settings);
+ setFormSettings(toFormSettings(settings));
setHasChanges(false);
}
};
@@ -190,6 +199,58 @@ export function SettingsComponent({ contentHeight }: Props) {
/>
</div>
</div>
+
+ <div className="flex items-start justify-between border-b border-gray-200 pb-4 dark:border-gray-700">
+ <div className="flex-1 pr-20">
+ <div className="font-medium text-gray-900 dark:text-white">
+ {t('settings.twoFactorAuth.title')}
+ </div>
+
+ <div className="mt-1 text-gray-500 dark:text-gray-400">
+ {t('settings.twoFactorAuth.description')}
+ </div>
+
+ <div className="mt-1 text-gray-500 dark:text-gray-400">
+ {t('settings.twoFactorAuth.appliesToNextSignIn')}
+ </div>
+
+ {!settings?.isEmailConfigured && (
+ <div className="mt-1 text-gray-500 dark:text-gray-400">
+ <Trans
+ i18nKey="settings.twoFactorAuth.mailServerRequired"
+ components={{
+ docsLink: (
+ <a
+ href={getWebsitePageUrl('advancedConfigEmailSmtp', locale)}
+ target="_blank"
+ rel="noreferrer"
+ className="!text-blue-600"
+ />
+ ),
+ }}
+ />
+ </div>
+ )}
+ </div>
+ <div className="ml-4">
+ <Switch
+ checked={formSettings.isTwoFactorAuthRequired}
+ // Switching off needs no mail server, so an instance that has
+ // lost one can still be taken back to one factor from here.
+ disabled={
+ !settings?.isEmailConfigured && !settings?.isTwoFactorAuthRequired
+ }
+ onChange={(checked) =>
+ handleSettingChange('isTwoFactorAuthRequired', checked)
+ }
+ style={{
+ backgroundColor: formSettings.isTwoFactorAuthRequired
+ ? '#155dfc'
+ : undefined,
+ }}
+ />
+ </div>
+ </div>
</div>
{/* Action Buttons */}
diff --git a/frontend/src/features/users/index.ts b/frontend/src/features/users/index.ts
index 459da774..3f84ad92 100644
--- a/frontend/src/features/users/index.ts
+++ b/frontend/src/features/users/index.ts
@@ -2,5 +2,6 @@ export { AuthNavbarComponent } from './ui/AuthNavbarComponent';
export { ProfileComponent } from './ui/ProfileComponent';
export { RequestResetPasswordComponent } from './ui/RequestResetPasswordComponent';
export { ResetPasswordComponent } from './ui/ResetPasswordComponent';
+export { SignInCodeComponent } from './ui/SignInCodeComponent';
export { SignInComponent } from './ui/SignInComponent';
export { SignUpComponent } from './ui/SignUpComponent';
diff --git a/frontend/src/features/users/ui/SignInCodeComponent.tsx b/frontend/src/features/users/ui/SignInCodeComponent.tsx
new file mode 100644
index 00000000..8bf14eb7
--- /dev/null
+++ b/frontend/src/features/users/ui/SignInCodeComponent.tsx
@@ -0,0 +1,167 @@
+import { App, Button, Input } from 'antd';
+import { type JSX, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useCloudflareTurnstile } from '../../../shared/hooks/useCloudflareTurnstile';
+
+import { CLOUDFLARE_TURNSTILE_SITE_KEY } from '../../../constants';
+import { type PendingSignIn, userApi } from '../../../entity/users';
+import { ApiError } from '../../../shared/api';
+import { translateApiError } from '../../../shared/i18n';
+import { CloudflareTurnstileWidget } from '../../../shared/ui/CloudflareTurnstileWidget';
+
+interface SignInCodeComponentProps {
+ pendingSignIn: PendingSignIn;
+ onPendingSignInReplaced: (pendingSignIn: PendingSignIn) => void;
+ onPendingSignInLost: () => void;
+ onSwitchToSignIn: () => void;
+}
+
+// The one refusal that ends the code step rather than leaving the user on it.
+// eslint-disable-next-line i18next/no-literal-string -- backend error code
+const PENDING_SIGN_IN_NOT_USABLE_CODE = 'pending_sign_in_not_usable';
+
+export function SignInCodeComponent({
+ pendingSignIn,
+ onPendingSignInReplaced,
+ onPendingSignInLost,
+ onSwitchToSignIn,
+}: SignInCodeComponentProps): JSX.Element {
+ const { t } = useTranslation();
+ const { message } = App.useApp();
+ const [code, setCode] = useState('');
+ const [isCodeError, setCodeError] = useState(false);
+ const [isLoading, setLoading] = useState(false);
+ const [isResending, setResending] = useState(false);
+ const [failure, setFailure] = useState<unknown>();
+
+ const { token, containerRef, resetCloudflareTurnstile } = useCloudflareTurnstile();
+
+ const reportFailure = (error: unknown) => {
+ if (error instanceof ApiError && error.code === PENDING_SIGN_IN_NOT_USABLE_CODE) {
+ message.error(translateApiError(error, t));
+ onPendingSignInLost();
+
+ return;
+ }
+
+ setFailure(error);
+ };
+
+ const onVerify = async () => {
+ setFailure(undefined);
+
+ if (!/^\d{6}$/.test(code)) {
+ setCodeError(true);
+
+ return;
+ }
+
+ setLoading(true);
+
+ try {
+ await userApi.verifySignInCode({
+ pendingSignInId: pendingSignIn.pendingSignInId,
+ code,
+ cloudflareTurnstileToken: token,
+ });
+ } catch (e) {
+ reportFailure(e);
+ resetCloudflareTurnstile();
+ }
+
+ setLoading(false);
+ };
+
+ const onResend = async () => {
+ setFailure(undefined);
+ setResending(true);
+
+ try {
+ const resentSignIn = await userApi.resendSignInCode({
+ pendingSignInId: pendingSignIn.pendingSignInId,
+ cloudflareTurnstileToken: token,
+ });
+
+ setCode('');
+ onPendingSignInReplaced(resentSignIn);
+ message.success(t('users.signInCode.codeResent'));
+ } catch (e) {
+ reportFailure(e);
+ }
+
+ // The challenge answer is single-use, and the resend spent it whether or not
+ // it succeeded, so the next verification needs a fresh one.
+ resetCloudflareTurnstile();
+
+ setResending(false);
+ };
+
+ return (
+ <div className="w-full max-w-[300px]">
+ <div className="mb-5 text-center text-2xl font-bold">{t('users.signInCode.title')}</div>
+
+ <div className="mb-4 text-center text-sm text-gray-600 dark:text-gray-400">
+ {t('users.signInCode.description', { email: pendingSignIn.email })}
+ </div>
+
+ <div className="my-1 text-xs font-semibold">{t('users.signInCode.code')}</div>
+ <Input
+ placeholder="123456"
+ value={code}
+ onChange={(e) => {
+ setCodeError(false);
+ setFailure(undefined);
+ setCode(e.currentTarget.value.replace(/\D/g, '').slice(0, 6));
+ }}
+ status={isCodeError ? 'error' : undefined}
+ maxLength={6}
+ />
+
+ <div className="mt-3" />
+
+ <CloudflareTurnstileWidget containerRef={containerRef} />
+
+ <Button
+ disabled={isLoading || (!!CLOUDFLARE_TURNSTILE_SITE_KEY && !token)}
+ loading={isLoading}
+ className="w-full"
+ onClick={() => {
+ onVerify();
+ }}
+ type="primary"
+ >
+ {t('users.signInCode.submit')}
+ </Button>
+
+ {(isCodeError || failure !== undefined) && (
+ <div className="mt-3 flex justify-center text-center text-sm text-red-600">
+ {isCodeError ? t('users.signInCode.invalidCode') : translateApiError(failure, t)}
+ </div>
+ )}
+
+ <div className="mt-4 text-center text-sm text-gray-600 dark:text-gray-400">
+ <button
+ type="button"
+ onClick={() => {
+ onResend();
+ }}
+ disabled={isResending || (!!CLOUDFLARE_TURNSTILE_SITE_KEY && !token)}
+ className="cursor-pointer font-medium text-blue-600 hover:text-blue-700 dark:!text-blue-500"
+ >
+ {t('users.signInCode.resend')}
+ </button>
+ <br />
+ <button
+ type="button"
+ onClick={onSwitchToSignIn}
+ className="cursor-pointer font-medium text-blue-600 hover:text-blue-700 dark:!text-blue-500"
+ >
+ {t('users.signInCode.backToSignIn')}
+ </button>
+ </div>
+
+ <div className="mb-10" />
+ </div>
+ );
+}
diff --git a/frontend/src/features/users/ui/SignInComponent.tsx b/frontend/src/features/users/ui/SignInComponent.tsx
index 37a13031..0695227f 100644
--- a/frontend/src/features/users/ui/SignInComponent.tsx
+++ b/frontend/src/features/users/ui/SignInComponent.tsx
@@ -11,7 +11,7 @@ import {
GOOGLE_CLIENT_ID,
IS_EMAIL_CONFIGURED,
} from '../../../constants';
-import { userApi } from '../../../entity/users';
+import { type PendingSignIn, userApi } from '../../../entity/users';
import { translateApiError } from '../../../shared/i18n';
import { FormValidator } from '../../../shared/lib/FormValidator';
import { CloudflareTurnstileWidget } from '../../../shared/ui/CloudflareTurnstileWidget';
@@ -21,11 +21,13 @@ import { GoogleOAuthComponent } from './oauth/GoogleOAuthComponent';
interface SignInComponentProps {
onSwitchToSignUp?: () => void;
onSwitchToResetPassword?: () => void;
+ onCodeRequired?: (pendingSignIn: PendingSignIn) => void;
}
export function SignInComponent({
onSwitchToSignUp,
onSwitchToResetPassword,
+ onCodeRequired,
}: SignInComponentProps): JSX.Element {
const { t } = useTranslation();
const [email, setEmail] = useState('');
@@ -70,11 +72,15 @@ export function SignInComponent({
setLoading(true);
try {
- await userApi.signIn({
+ const outcome = await userApi.signIn({
email,
password,
cloudflareTurnstileToken: token,
});
+
+ if (!outcome.isCompleted) {
+ onCodeRequired?.(outcome.pendingSignIn);
+ }
} catch (e) {
setSignInError(e);
resetCloudflareTurnstile();
diff --git a/frontend/src/pages/AuthPageComponent.tsx b/frontend/src/pages/AuthPageComponent.tsx
index 1edac6e9..bcbcd038 100644
--- a/frontend/src/pages/AuthPageComponent.tsx
+++ b/frontend/src/pages/AuthPageComponent.tsx
@@ -3,11 +3,12 @@ import { Spin } from 'antd';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { userApi } from '../entity/users';
+import { type PendingSignIn, userApi } from '../entity/users';
import {
AuthNavbarComponent,
RequestResetPasswordComponent,
ResetPasswordComponent,
+ SignInCodeComponent,
SignInComponent,
SignUpComponent,
} from '../features/users';
@@ -17,13 +18,19 @@ import { translateApiError } from '../shared/i18n';
export function AuthPageComponent() {
const { t } = useTranslation();
const [isAnyUserExist, setIsAnyUserExist] = useState(true);
- const [authMode, setAuthMode] = useState<'signIn' | 'signUp' | 'requestReset' | 'resetPassword'>(
- 'signUp',
- );
+ const [authMode, setAuthMode] = useState<
+ 'signIn' | 'signUp' | 'requestReset' | 'resetPassword' | 'signInCode'
+ >('signUp');
const [resetEmail, setResetEmail] = useState('');
+ const [pendingSignIn, setPendingSignIn] = useState<PendingSignIn | undefined>(undefined);
const [isLoading, setLoading] = useState(true);
const screenHeight = useScreenHeight();
+ const returnToPasswordStep = () => {
+ setPendingSignIn(undefined);
+ setAuthMode('signIn');
+ };
+
useEffect(() => {
setLoading(true);
@@ -60,6 +67,17 @@ export function AuthPageComponent() {
<SignInComponent
onSwitchToSignUp={() => setAuthMode('signUp')}
onSwitchToResetPassword={() => setAuthMode('requestReset')}
+ onCodeRequired={(newPendingSignIn) => {
+ setPendingSignIn(newPendingSignIn);
+ setAuthMode('signInCode');
+ }}
+ />
+ ) : authMode === 'signInCode' && pendingSignIn ? (
+ <SignInCodeComponent
+ pendingSignIn={pendingSignIn}
+ onPendingSignInReplaced={setPendingSignIn}
+ onPendingSignInLost={returnToPasswordStep}
+ onSwitchToSignIn={returnToPasswordStep}
/>
) : authMode === 'requestReset' ? (
<RequestResetPasswordComponent
diff --git a/frontend/src/shared/i18n/locales/en.ts b/frontend/src/shared/i18n/locales/en.ts
index 580fdc7b..16cc3f8c 100644
--- a/frontend/src/shared/i18n/locales/en.ts
+++ b/frontend/src/shared/i18n/locales/en.ts
@@ -130,6 +130,15 @@ export const en = {
networkUnreachable: 'Cannot reach the Databasus server. Check your connection and try again.',
requestFailed:
'The server could not complete the request (HTTP {{status}}). Please try again later.',
+ signInCodeIncorrect: 'The code is incorrect.',
+ pendingSignInNotUsable: 'This sign-in can no longer be completed. Sign in again.',
+ signInCodeNotSent:
+ 'The instance could not send the sign-in code. Try again later or ask an administrator.',
+ tooManySignInCodes:
+ 'Too many sign-in codes were requested for this account in the last hour. Try again later.',
+ signInCodeResentTooSoon:
+ 'A code was sent less than a minute ago. Wait a minute before requesting another.',
+ rateLimitExceeded: 'Too many attempts. Wait a little and try again.',
},
status: {
logicalBackup: {
@@ -236,6 +245,14 @@ export const en = {
description:
'When enabled, members (non-admin users) can create new workspaces. If not - only admins can create workspaces.',
},
+ twoFactorAuth: {
+ title: 'Require a code at sign-in',
+ description:
+ "When enabled, a password sign-in also has to present a six-digit code sent to the account's email address. Sign-in through Google or GitHub is not covered.",
+ appliesToNextSignIn:
+ 'The setting applies to the next sign-in. Sessions that are already open keep working.',
+ mailServerRequired: 'This needs a mail server. <docsLink>Configure SMTP</docsLink> first.',
+ },
saving: 'Saving...',
saveChanges: 'Save Changes',
reset: 'Reset',
@@ -862,6 +879,17 @@ export const en = {
noAccount: "Don't have an account? <signUpLink>Sign up</signUpLink>",
forgotPassword: 'Forgot password?',
},
+ signInCode: {
+ title: 'Enter the code',
+ description:
+ 'We sent a six-digit code to {{email}}. It stops working 10 minutes after it was sent.',
+ code: 'Sign-in code',
+ submit: 'Sign in',
+ resend: 'Send another code',
+ backToSignIn: 'Back to sign in',
+ invalidCode: 'Code must be 6 digits',
+ codeResent: 'A new code is on its way. The previous one no longer works.',
+ },
signUp: {
title: 'Sign up',
namePlaceholder: 'John Doe',
diff --git a/frontend/src/shared/i18n/locales/es.ts b/frontend/src/shared/i18n/locales/es.ts
index 7ab6536d..c404d751 100644
--- a/frontend/src/shared/i18n/locales/es.ts
+++ b/frontend/src/shared/i18n/locales/es.ts
@@ -133,6 +133,16 @@ export const es: typeof en = {
'No se puede conectar con el servidor de Databasus. Compruebe su conexión e inténtelo de nuevo.',
requestFailed:
'El servidor no pudo completar la solicitud (HTTP {{status}}). Inténtelo de nuevo más tarde.',
+ signInCodeIncorrect: 'El código no es correcto.',
+ pendingSignInNotUsable:
+ 'Este inicio de sesión ya no puede completarse. Vuelva a iniciar sesión.',
+ signInCodeNotSent:
+ 'La instancia no ha podido enviar el código de acceso. Inténtelo más tarde o avise a un administrador.',
+ tooManySignInCodes:
+ 'Se han pedido demasiados códigos de acceso para esta cuenta en la última hora. Inténtelo más tarde.',
+ signInCodeResentTooSoon:
+ 'Se envió un código hace menos de un minuto. Espere un minuto antes de pedir otro.',
+ rateLimitExceeded: 'Demasiados intentos. Espere un poco e inténtelo de nuevo.',
},
status: {
logicalBackup: {
@@ -239,6 +249,15 @@ export const es: typeof en = {
description:
'Si está activado, los miembros (usuarios que no son administradores) pueden crear espacios de trabajo. Si no, solo pueden crearlos los administradores.',
},
+ twoFactorAuth: {
+ title: 'Pedir un código al iniciar sesión',
+ description:
+ 'Si se activa, además de la contraseña hay que introducir un código de seis dígitos enviado al correo de la cuenta. No se aplica al inicio de sesión con Google ni con GitHub.',
+ appliesToNextSignIn:
+ 'El ajuste se aplica al siguiente inicio de sesión. Las sesiones ya abiertas siguen funcionando.',
+ mailServerRequired:
+ 'Hace falta un servidor de correo. <docsLink>Configure SMTP</docsLink> primero.',
+ },
saving: 'Guardando...',
saveChanges: 'Guardar cambios',
reset: 'Restablecer',
@@ -882,6 +901,17 @@ export const es: typeof en = {
noAccount: '¿No tiene cuenta? <signUpLink>Regístrese</signUpLink>',
forgotPassword: '¿Olvidó su contraseña?',
},
+ signInCode: {
+ title: 'Introduzca el código',
+ description:
+ 'Hemos enviado un código de seis dígitos a {{email}}. Deja de funcionar 10 minutos después de enviarse.',
+ code: 'Código de acceso',
+ submit: 'Iniciar sesión',
+ resend: 'Enviar otro código',
+ backToSignIn: 'Volver al inicio de sesión',
+ invalidCode: 'El código tiene 6 dígitos',
+ codeResent: 'Hemos enviado un código nuevo. El anterior ya no funciona.',
+ },
signUp: {
title: 'Registro',
namePlaceholder: 'Juan Pérez',
diff --git a/frontend/src/shared/i18n/locales/fr.ts b/frontend/src/shared/i18n/locales/fr.ts
index 9639a1da..6981365f 100644
--- a/frontend/src/shared/i18n/locales/fr.ts
+++ b/frontend/src/shared/i18n/locales/fr.ts
@@ -133,6 +133,15 @@ export const fr: typeof en = {
'Impossible de joindre le serveur Databasus. Vérifiez votre connexion et réessayez.',
requestFailed:
"Le serveur n'a pas pu traiter la requête (HTTP {{status}}). Réessayez plus tard.",
+ signInCodeIncorrect: 'Le code est incorrect.',
+ pendingSignInNotUsable: 'Cette connexion ne peut plus aboutir. Reconnectez-vous.',
+ signInCodeNotSent:
+ "L'instance n'a pas pu envoyer le code de connexion. Réessayez plus tard ou prévenez un administrateur.",
+ tooManySignInCodes:
+ 'Trop de codes de connexion ont été demandés pour ce compte au cours de la dernière heure. Réessayez plus tard.',
+ signInCodeResentTooSoon:
+ "Un code a été envoyé il y a moins d'une minute. Attendez une minute avant d'en demander un autre.",
+ rateLimitExceeded: 'Trop de tentatives. Patientez un peu et réessayez.',
},
status: {
logicalBackup: {
@@ -239,6 +248,15 @@ export const fr: typeof en = {
description:
"Si l'option est activée, les membres (utilisateurs non administrateurs) peuvent créer des espaces de travail. Sinon, seuls les administrateurs peuvent en créer.",
},
+ twoFactorAuth: {
+ title: 'Demander un code à la connexion',
+ description:
+ "Une fois activé, la connexion par mot de passe demande aussi un code à six chiffres envoyé à l'adresse du compte. La connexion par Google ou GitHub n'est pas concernée.",
+ appliesToNextSignIn:
+ "Le réglage s'applique à la prochaine connexion. Les sessions déjà ouvertes continuent de fonctionner.",
+ mailServerRequired:
+ "Il faut un serveur de messagerie. <docsLink>Configurez le SMTP</docsLink> d'abord.",
+ },
saving: 'Enregistrement...',
saveChanges: 'Enregistrer les modifications',
reset: 'Réinitialiser',
@@ -888,6 +906,17 @@ export const fr: typeof en = {
noAccount: 'Pas encore de compte ? <signUpLink>Inscrivez-vous</signUpLink>',
forgotPassword: 'Mot de passe oublié ?',
},
+ signInCode: {
+ title: 'Saisissez le code',
+ description:
+ 'Nous avons envoyé un code à six chiffres à {{email}}. Il cesse de fonctionner 10 minutes après son envoi.',
+ code: 'Code de connexion',
+ submit: 'Se connecter',
+ resend: 'Envoyer un autre code',
+ backToSignIn: 'Retour à la connexion',
+ invalidCode: 'Le code comporte 6 chiffres',
+ codeResent: 'Un nouveau code est parti. Le précédent ne fonctionne plus.',
+ },
signUp: {
title: 'Inscription',
namePlaceholder: 'Jean Dupont',
diff --git a/frontend/src/shared/i18n/locales/pt.ts b/frontend/src/shared/i18n/locales/pt.ts
index 729c3566..b46d4609 100644
--- a/frontend/src/shared/i18n/locales/pt.ts
+++ b/frontend/src/shared/i18n/locales/pt.ts
@@ -134,6 +134,15 @@ export const pt: typeof en = {
'Não foi possível acessar o servidor do Databasus. Verifique sua conexão e tente novamente.',
requestFailed:
'O servidor não conseguiu concluir a solicitação (HTTP {{status}}). Tente novamente mais tarde.',
+ signInCodeIncorrect: 'Código incorreto.',
+ pendingSignInNotUsable: 'Este login não pode mais ser concluído. Entre novamente.',
+ signInCodeNotSent:
+ 'A instância não conseguiu enviar o código de acesso. Tente mais tarde ou fale com um administrador.',
+ tooManySignInCodes:
+ 'Foram solicitados códigos de acesso demais para esta conta na última hora. Tente mais tarde.',
+ signInCodeResentTooSoon:
+ 'Um código foi enviado há menos de um minuto. Espere um minuto antes de pedir outro.',
+ rateLimitExceeded: 'Tentativas demais. Espere um pouco e tente novamente.',
},
status: {
logicalBackup: {
@@ -240,6 +249,15 @@ export const pt: typeof en = {
description:
'Quando ativado, os membros (usuários que não são administradores) podem criar novos espaços de trabalho. Quando desativado, só os administradores podem criá-los.',
},
+ twoFactorAuth: {
+ title: 'Pedir um código ao entrar',
+ description:
+ 'Quando ativado, além da senha é preciso informar um código de seis dígitos enviado para o e-mail da conta. Não vale para o login pelo Google ou pelo GitHub.',
+ appliesToNextSignIn:
+ 'A configuração vale a partir do próximo login. As sessões já abertas continuam funcionando.',
+ mailServerRequired:
+ 'É preciso ter um servidor de e-mail. <docsLink>Configure o SMTP</docsLink> primeiro.',
+ },
saving: 'Salvando...',
saveChanges: 'Salvar alterações',
reset: 'Redefinir',
@@ -879,6 +897,17 @@ export const pt: typeof en = {
noAccount: 'Não tem uma conta? <signUpLink>Crie uma</signUpLink>',
forgotPassword: 'Esqueceu a senha?',
},
+ signInCode: {
+ title: 'Digite o código',
+ description:
+ 'Enviamos um código de seis dígitos para {{email}}. Ele para de funcionar 10 minutos depois do envio.',
+ code: 'Código de acesso',
+ submit: 'Entrar',
+ resend: 'Enviar outro código',
+ backToSignIn: 'Voltar para o login',
+ invalidCode: 'O código tem 6 dígitos',
+ codeResent: 'Enviamos um novo código. O anterior não funciona mais.',
+ },
signUp: {
title: 'Criar conta',
namePlaceholder: 'João Silva',
diff --git a/frontend/src/shared/i18n/locales/ru.ts b/frontend/src/shared/i18n/locales/ru.ts
index da23913c..21bccedf 100644
--- a/frontend/src/shared/i18n/locales/ru.ts
+++ b/frontend/src/shared/i18n/locales/ru.ts
@@ -130,6 +130,15 @@ export const ru: typeof en = {
unknown: 'Что-то пошло не так. Попробуйте еще раз.',
networkUnreachable: 'Сервер Databasus недоступен. Проверьте подключение и попробуйте еще раз.',
requestFailed: 'Сервер не смог выполнить запрос (HTTP {{status}}). Попробуйте позже.',
+ signInCodeIncorrect: 'Неверный код.',
+ pendingSignInNotUsable: 'Этот вход больше нельзя завершить. Войдите заново.',
+ signInCodeNotSent:
+ 'Не удалось отправить код входа. Попробуйте позже или обратитесь к администратору.',
+ tooManySignInCodes:
+ 'За последний час для этого аккаунта запросили слишком много кодов входа. Попробуйте позже.',
+ signInCodeResentTooSoon:
+ 'Код отправлен меньше минуты назад. Подождите минуту, прежде чем запрашивать новый.',
+ rateLimitExceeded: 'Слишком много попыток. Подождите немного и попробуйте снова.',
},
status: {
logicalBackup: {
@@ -236,6 +245,14 @@ export const ru: typeof en = {
description:
'Если включено, участники (не администраторы) могут создавать новые рабочие пространства. Если выключено — только администраторы.',
},
+ twoFactorAuth: {
+ title: 'Запрашивать код при входе',
+ description:
+ 'Если включено, после пароля нужно ввести шестизначный код, отправленный на почту аккаунта. На вход через Google и GitHub это не распространяется.',
+ appliesToNextSignIn:
+ 'Настройка действует со следующего входа. Уже открытые сессии продолжают работать.',
+ mailServerRequired: 'Нужен почтовый сервер. Сначала <docsLink>настройте SMTP</docsLink>.',
+ },
saving: 'Сохраняем...',
saveChanges: 'Сохранить изменения',
reset: 'Сбросить',
@@ -865,6 +882,17 @@ export const ru: typeof en = {
noAccount: 'Нет аккаунта? <signUpLink>Зарегистрируйтесь</signUpLink>',
forgotPassword: 'Забыли пароль?',
},
+ signInCode: {
+ title: 'Введите код',
+ description:
+ 'Мы отправили шестизначный код на {{email}}. Он перестает работать через 10 минут после отправки.',
+ code: 'Код входа',
+ submit: 'Войти',
+ resend: 'Отправить код еще раз',
+ backToSignIn: 'Вернуться ко входу',
+ invalidCode: 'Код состоит из 6 цифр',
+ codeResent: 'Новый код отправлен. Предыдущий больше не работает.',
+ },
signUp: {
title: 'Регистрация',
namePlaceholder: 'Иван Иванов',
diff --git a/frontend/src/shared/i18n/locales/zh.ts b/frontend/src/shared/i18n/locales/zh.ts
index 804b0cbe..48956ae2 100644
--- a/frontend/src/shared/i18n/locales/zh.ts
+++ b/frontend/src/shared/i18n/locales/zh.ts
@@ -128,6 +128,12 @@ export const zh: typeof en = {
unknown: '出了点问题,请重试。',
networkUnreachable: '无法连接 Databasus 服务器。请检查网络连接后重试。',
requestFailed: '服务器未能完成请求(HTTP {{status}})。请稍后重试。',
+ signInCodeIncorrect: '验证码不正确。',
+ pendingSignInNotUsable: '这次登录无法继续,请重新登录。',
+ signInCodeNotSent: '实例无法发送登录验证码,请稍后重试或联系管理员。',
+ tooManySignInCodes: '该账户在过去一小时内请求的登录验证码过多,请稍后重试。',
+ signInCodeResentTooSoon: '验证码发送不到一分钟,请稍等一分钟后再请求新的验证码。',
+ rateLimitExceeded: '尝试次数过多,请稍后重试。',
},
status: {
logicalBackup: {
@@ -232,6 +238,13 @@ export const zh: typeof en = {
description:
'开启后,成员(非管理员用户)可以创建新的工作区。关闭后,只有管理员能创建工作区。',
},
+ twoFactorAuth: {
+ title: '登录时要求验证码',
+ description:
+ '启用后,输入密码之后还需要填写发送到账号邮箱的六位验证码。通过 Google 或 GitHub 登录不受此设置影响。',
+ appliesToNextSignIn: '该设置从下次登录开始生效,已经打开的会话不受影响。',
+ mailServerRequired: '这需要邮件服务器,请先<docsLink>配置 SMTP</docsLink>。',
+ },
saving: '正在保存…',
saveChanges: '保存更改',
reset: '重置',
@@ -830,6 +843,16 @@ export const zh: typeof en = {
noAccount: '还没有账号?<signUpLink>注册</signUpLink>',
forgotPassword: '忘记密码?',
},
+ signInCode: {
+ title: '输入验证码',
+ description: '我们已将六位验证码发送到 {{email}},它在发送 10 分钟后失效。',
+ code: '登录验证码',
+ submit: '登录',
+ resend: '重新发送验证码',
+ backToSignIn: '返回登录',
+ invalidCode: '验证码为 6 位数字',
+ codeResent: '新的验证码已发送,之前的验证码已失效。',
+ },
signUp: {
title: '注册',
namePlaceholder: '张三',
diff --git a/frontend/src/shared/i18n/translateApiError.test.ts b/frontend/src/shared/i18n/translateApiError.test.ts
index 2b42cd92..fb4ff420 100644
--- a/frontend/src/shared/i18n/translateApiError.test.ts
+++ b/frontend/src/shared/i18n/translateApiError.test.ts
@@ -25,6 +25,14 @@ describe('translateApiError', () => {
expect(translateApiError(error, t)).toContain('502');
});
+ it('tells the two sign-in code refusals that share a status apart', () => {
+ const resentTooSoon = new ApiError({ code: 'sign_in_code_resent_too_soon', status: 429 });
+ const hourlyCapReached = new ApiError({ code: 'too_many_sign_in_codes', status: 429 });
+
+ expect(translateApiError(resentTooSoon, t)).toBe(t('errors.signInCodeResentTooSoon'));
+ expect(translateApiError(hourlyCapReached, t)).toBe(t('errors.tooManySignInCodes'));
+ });
+
it('shows the backend message for an unknown code', () => {
const error = new ApiError({
message: 'storage quota exceeded',
diff --git a/frontend/src/shared/i18n/translateApiError.ts b/frontend/src/shared/i18n/translateApiError.ts
index 154a05ea..fa2e8983 100644
--- a/frontend/src/shared/i18n/translateApiError.ts
+++ b/frontend/src/shared/i18n/translateApiError.ts
@@ -9,6 +9,12 @@ import type { TranslationKey } from './TranslationKey';
const API_ERROR_CODE_KEYS: Record<string, TranslationKey> = {
[API_ERROR_CODES.networkUnreachable]: 'errors.networkUnreachable',
[API_ERROR_CODES.requestFailed]: 'errors.requestFailed',
+ rate_limit_exceeded: 'errors.rateLimitExceeded',
+ sign_in_code_incorrect: 'errors.signInCodeIncorrect',
+ pending_sign_in_not_usable: 'errors.pendingSignInNotUsable',
+ sign_in_code_not_sent: 'errors.signInCodeNotSent',
+ too_many_sign_in_codes: 'errors.tooManySignInCodes',
+ sign_in_code_resent_too_soon: 'errors.signInCodeResentTooSoon',
};
// The one way an error reaches the screen. The message of anything that is not an ApiError comes
diff --git a/frontend/src/shared/i18n/websitePages.test.ts b/frontend/src/shared/i18n/websitePages.test.ts
index c5187032..7221ce0e 100644
--- a/frontend/src/shared/i18n/websitePages.test.ts
+++ b/frontend/src/shared/i18n/websitePages.test.ts
@@ -51,6 +51,15 @@ describe('getWebsitePageUrl', () => {
);
});
+ it('links the SMTP section of the configuration page', () => {
+ expect(getWebsitePageUrl('advancedConfigEmailSmtp', 'en')).toBe(
+ 'https://databasus.com/advanced-config/#email-smtp',
+ );
+ expect(getWebsitePageUrl('advancedConfigEmailSmtp', 'fr')).toBe(
+ 'https://databasus.com/fr/advanced-config/#email-smtp',
+ );
+ });
+
it('links the home page with and without a language', () => {
expect(getWebsitePageUrl('home', 'en')).toBe('https://databasus.com/');
expect(getWebsitePageUrl('home', 'ru')).toBe('https://databasus.com/ru/');
diff --git a/frontend/src/shared/i18n/websitePages.ts b/frontend/src/shared/i18n/websitePages.ts
index 67fd491e..f3f275c8 100644
--- a/frontend/src/shared/i18n/websitePages.ts
+++ b/frontend/src/shared/i18n/websitePages.ts
@@ -22,6 +22,11 @@ export const WEBSITE_PAGES = {
anchor: 'global-settings',
isTranslated: true,
},
+ advancedConfigEmailSmtp: {
+ path: 'advanced-config',
+ anchor: 'email-smtp',
+ isTranslated: true,
+ },
restoreVerification: { path: 'restore-verification', isTranslated: true },
faqLocalhost: { path: 'faq/localhost', isTranslated: true },
faqSupabase: { path: 'faq/supabase', isTranslated: true },
diff --git a/website/app/(en)/page.tsx b/website/app/(en)/page.tsx
index 1e2841db..34ed6514 100644
--- a/website/app/(en)/page.tsx
+++ b/website/app/(en)/page.tsx
@@ -178,7 +178,7 @@ export default function Index() {
name: "How does Databasus ensure security?",
acceptedAnswer: {
"@type": "Answer",
- text: "Databasus enforces security on three levels: (1) Sensitive data encryption — all passwords, tokens and credentials are encrypted with AES-256-GCM and stored separately from the database; (2) Backup encryption — each backup file is encrypted with a unique key derived from a master key, backup ID and random salt, making backups useless without your encryption key even if someone gains storage access; (3) Read-only database access — Databasus only requires SELECT permissions and performs comprehensive checks to ensure no write privileges exist, preventing data corruption even if the tool is compromised. Beyond runtime, security and reliability are engineered into every commit and PR: CodeQL static analysis, CodeRabbit with gitleaks and semgrep, Dependabot CVE monitoring, Trivy image and Dockerfile scans, and periodic Codex Security audits from OpenAI. Integration tests run against real PostgreSQL, MySQL, MariaDB and MongoDB containers and verify full backup-then-restore cycles on every PR. GitHub Actions are pinned to commit SHAs and workflows follow least-privilege permissions. All operations run in containers you control on servers you own, and because it's open source, your security team can audit every line of code before deployment.",
+ text: "Databasus enforces security on three levels: (1) Sensitive data encryption — all passwords, tokens and credentials are encrypted with AES-256-GCM and stored separately from the database; (2) Backup encryption — each backup file is encrypted with a unique key derived from a master key, backup ID and random salt, making backups useless without your encryption key even if someone gains storage access; (3) Read-only database access — Databasus only requires SELECT permissions and performs comprehensive checks to ensure no write privileges exist, preventing data corruption even if the tool is compromised. Sign-in itself can require a second factor: with it on, a correct password is followed by a six-digit code emailed to the account, while sign-in through Google or GitHub keeps relying on the provider's own checks. Beyond runtime, security and reliability are engineered into every commit and PR: CodeQL static analysis, CodeRabbit with gitleaks and semgrep, Dependabot CVE monitoring, Trivy image and Dockerfile scans, and periodic Codex Security audits from OpenAI. Integration tests run against real PostgreSQL, MySQL, MariaDB and MongoDB containers and verify full backup-then-restore cycles on every PR. GitHub Actions are pinned to commit SHAs and workflows follow least-privilege permissions. All operations run in containers you control on servers you own, and because it's open source, your security team can audit every line of code before deployment.",
},
},
{
@@ -226,7 +226,7 @@ export default function Index() {
name: "I forgot my admin email or password",
acceptedAnswer: {
"@type": "Answer",
- text: 'The first account created on the instance administers it. If you cannot remember which address that is, run docker exec -it databasus ./main --list-admins on the server where Databasus runs — it names every administrator account with its email address, display name, creation date and active state, and prints no password material. To set a new password for that account, run docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]". An instance created before the first account administered it still carries the placeholder address admin until its owner replaces it. Both commands are documented on the password page.',
+ text: 'The first account created on the instance administers it. If you cannot remember which address that is, run docker exec -it databasus ./main --list-admins on the server where Databasus runs — it names every administrator account with its email address, display name, creation date and active state, and prints no password material. To set a new password for that account, run docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]". An instance created before the first account administered it still carries the placeholder address admin until its owner replaces it. If the instance also requires an emailed code at sign-in and the mail server has stopped delivering it, run docker exec -it databasus ./main --disable-2fa to stop requiring the code. All three commands are documented on the password page.',
},
},
],
@@ -1316,6 +1316,12 @@ export default function Index() {
tool is compromised.
<br />
<br />
+ Sign-in itself can require a second factor: with it on, a
+ correct password is followed by a six-digit code emailed to
+ the account, while sign-in through Google or GitHub keeps
+ relying on the provider&apos;s own checks.
+ <br />
+ <br />
Beyond runtime, security and reliability are engineered into
every commit and PR: CodeQL static analysis, CodeRabbit with
gitleaks and semgrep, Dependabot CVE monitoring, Trivy image
@@ -1669,8 +1675,11 @@ export default function Index() {
--new-password=&quot;YourNewSecurePassword123&quot;
--email=&quot;[email protected]&quot;. An instance created
before the first account administered it still carries the
- placeholder address admin until its owner replaces it. Both
- commands are documented on the{" "}
+ placeholder address admin until its owner replaces it. If the
+ instance also requires an emailed code at sign-in and the mail
+ server has stopped delivering it, run docker exec -it
+ databasus ./main --disable-2fa to stop requiring the code. All
+ three commands are documented on the{" "}
<a
href="/password"
className="text-blue-400 hover:text-blue-600"
diff --git a/website/app/(en)/password/page.tsx b/website/app/(en)/password/page.tsx
index 10044aca..fac71219 100644
--- a/website/app/(en)/password/page.tsx
+++ b/website/app/(en)/password/page.tsx
@@ -40,6 +40,7 @@ export const metadata: Metadata = {
export default function PasswordResetPage() {
const resetPasswordCommand = `docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]"`;
const listAdminsCommand = `docker exec -it databasus ./main --list-admins`;
+ const disableTwoFactorCommand = `docker exec -it databasus ./main --disable-2fa`;
return (
<>
@@ -172,6 +173,32 @@ export default function PasswordResetPage() {
nobody has created an account yet, it reports that the instance
has no administrator.
</p>
+ <h2 id="disable-two-factor">Stop requiring a sign-in code</h2>
+
+ <p>
+ An instance can require a six-digit code emailed at sign-in on
+ top of the password. If the mail server stops delivering those
+ codes, nobody gets in with a password, and a password reset
+ alone does not help. Switch the second factor off on the server
+ where Databasus is running:
+ </p>
+
+ <div className="relative my-6">
+ <pre className="overflow-x-auto rounded-lg bg-gray-900 p-4 text-sm text-gray-100">
+ <code>{disableTwoFactorCommand}</code>
+ </pre>
+ <div className="absolute right-2 top-2">
+ <CopyButton text={disableTwoFactorCommand} />
+ </div>
+ </div>
+
+ <p>
+ The command reports whether it changed anything, succeeds
+ without complaint when the second factor is already off, and
+ records the change in the audit log. The next password sign-in
+ then needs no code, and an administrator can turn the setting
+ back on once mail works again.
+ </p>
</article>
</div>
</main>
diff --git a/website/app/(en)/security/page.tsx b/website/app/(en)/security/page.tsx
index ad321fb2..4ff192be 100644
--- a/website/app/(en)/security/page.tsx
+++ b/website/app/(en)/security/page.tsx
@@ -42,6 +42,7 @@ export const metadata: Metadata = {
export default function SecurityPage() {
const encryptionPipeline = `PostgreSQL pg_dump → Compression → Encryption → Cloud Storage`;
+ const disableTwoFactorCommand = `docker exec -it databasus ./main --disable-2fa`;
return (
<>
@@ -266,6 +267,61 @@ export default function SecurityPage() {
decrypted, attackers cannot corrupt your database.
</p>
+ <h2 id="two-factor-authentication">
+ Two-factor authentication at sign-in
+ </h2>
+
+ <p>
+ A password alone opens every database credential, storage key
+ and backup the instance holds, so an administrator can require a
+ second factor for password sign-in. With it on, a correct
+ password sends a six-digit code to the account&apos;s email
+ address, and the sign-in finishes only once that code is
+ entered. The code stops working ten minutes after it was sent,
+ is discarded after five wrong guesses, and requesting another
+ one replaces it. Turning the setting on guards the next sign-in
+ and leaves sessions that are already open working.
+ </p>
+
+ <p>
+ The setting covers password sign-in. Signing in through Google
+ or GitHub still issues a token directly, because those providers
+ run their own multi-factor checks - an instance that wants the
+ second factor to cover everybody does not configure them.
+ </p>
+
+ <p>
+ It can only be turned on when the instance has a mail server and
+ every active administrator holds a real email address, so nobody
+ switches it on and locks the instance out. If the mail server
+ later stops delivering, nobody gets in with a password, which is
+ deliberate: a broken mail server must not quietly downgrade
+ authentication back to one factor. An operator with shell access
+ on the server switches it off again:
+ </p>
+
+ <div className="relative my-6">
+ <pre className="overflow-x-auto rounded-lg bg-gray-900 p-4 text-sm text-gray-100">
+ <code>{disableTwoFactorCommand}</code>
+ </pre>
+ <div className="absolute right-2 top-2">
+ <CopyButton text={disableTwoFactorCommand} />
+ </div>
+ </div>
+
+ <p>
+ The command reports what it changed and records it in the audit
+ log, so an instance that stopped asking for codes says why. It
+ is documented beside password recovery on the{" "}
+ <a
+ href="/password#disable-two-factor"
+ className="text-blue-400 hover:text-blue-600"
+ >
+ password page
+ </a>
+ .
+ </p>
+
<h2 id="security-and-reliability-engineering">
🛡️ Security &amp; reliability engineering
</h2>
diff --git a/website/app/[lang]/content/es.tsx b/website/app/[lang]/content/es.tsx
index 620e3af4..6211e60f 100644
--- a/website/app/[lang]/content/es.tsx
+++ b/website/app/[lang]/content/es.tsx
@@ -178,7 +178,7 @@ export default function Index() {
name: "¿Cómo garantiza Databasus la seguridad?",
acceptedAnswer: {
"@type": "Answer",
- text: "Databasus aplica seguridad en tres niveles: (1) Cifrado de datos sensibles: todas las contraseñas, tokens y credenciales se cifran con AES-256-GCM y se guardan separados de la base de datos; (2) Cifrado de las copias de seguridad: cada archivo de respaldo se cifra con una clave única derivada de una clave maestra, el ID de la copia y una sal aleatoria, de modo que las copias resultan inútiles sin su clave de cifrado aunque alguien acceda al almacenamiento; (3) Acceso de solo lectura a la base de datos: Databasus solo requiere permisos SELECT y realiza comprobaciones exhaustivas para asegurar que no existen privilegios de escritura, lo que evita la corrupción de datos incluso si la herramienta se ve comprometida. Más allá del tiempo de ejecución, la seguridad y la fiabilidad se integran en cada commit y PR: análisis estático con CodeQL, CodeRabbit con gitleaks y semgrep, monitoreo de CVE con Dependabot, escaneo de imágenes y Dockerfiles con Trivy, y auditorías periódicas de Codex Security de OpenAI. Las pruebas de integración se ejecutan contra contenedores reales de PostgreSQL, MySQL, MariaDB y MongoDB y verifican ciclos completos de copia y restauración en cada PR. Las GitHub Actions están fijadas a SHA de commit y los flujos de trabajo siguen permisos de privilegio mínimo. Todas las operaciones se ejecutan en contenedores que usted controla, en servidores que le pertenecen, y al ser código abierto, su equipo de seguridad puede auditar cada línea de código antes del despliegue.",
+ text: "Databasus aplica seguridad en tres niveles: (1) Cifrado de datos sensibles: todas las contraseñas, tokens y credenciales se cifran con AES-256-GCM y se guardan separados de la base de datos; (2) Cifrado de las copias de seguridad: cada archivo de respaldo se cifra con una clave única derivada de una clave maestra, el ID de la copia y una sal aleatoria, de modo que las copias resultan inútiles sin su clave de cifrado aunque alguien acceda al almacenamiento; (3) Acceso de solo lectura a la base de datos: Databasus solo requiere permisos SELECT y realiza comprobaciones exhaustivas para asegurar que no existen privilegios de escritura, lo que evita la corrupción de datos incluso si la herramienta se ve comprometida. El propio inicio de sesión puede exigir un segundo factor: con él activado, tras la contraseña correcta llega un código de seis dígitos al correo de la cuenta, mientras que el inicio de sesión con Google o GitHub sigue apoyándose en las comprobaciones de esos proveedores. Más allá del tiempo de ejecución, la seguridad y la fiabilidad se integran en cada commit y PR: análisis estático con CodeQL, CodeRabbit con gitleaks y semgrep, monitoreo de CVE con Dependabot, escaneo de imágenes y Dockerfiles con Trivy, y auditorías periódicas de Codex Security de OpenAI. Las pruebas de integración se ejecutan contra contenedores reales de PostgreSQL, MySQL, MariaDB y MongoDB y verifican ciclos completos de copia y restauración en cada PR. Las GitHub Actions están fijadas a SHA de commit y los flujos de trabajo siguen permisos de privilegio mínimo. Todas las operaciones se ejecutan en contenedores que usted controla, en servidores que le pertenecen, y al ser código abierto, su equipo de seguridad puede auditar cada línea de código antes del despliegue.",
},
},
{
@@ -226,7 +226,7 @@ export default function Index() {
name: "Olvidé el correo o la contraseña del administrador",
acceptedAnswer: {
"@type": "Answer",
- text: 'La primera cuenta creada en la instancia es la que la administra. Si no recuerda cuál es esa dirección, ejecute docker exec -it databasus ./main --list-admins en el servidor donde se ejecuta Databasus: nombra cada cuenta de administrador con su correo electrónico, nombre visible, fecha de creación y estado de actividad, y no imprime ninguna contraseña. Para establecer una nueva contraseña para esa cuenta, ejecute docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]". Una instancia creada antes de que la primera cuenta la administrara todavía lleva la dirección provisional admin hasta que su propietario la reemplace. Ambos comandos están documentados en la página de contraseña.',
+ text: 'La primera cuenta creada en la instancia es la que la administra. Si no recuerda cuál es esa dirección, ejecute docker exec -it databasus ./main --list-admins en el servidor donde se ejecuta Databasus: nombra cada cuenta de administrador con su correo electrónico, nombre visible, fecha de creación y estado de actividad, y no imprime ninguna contraseña. Para establecer una nueva contraseña para esa cuenta, ejecute docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]". Una instancia creada antes de que la primera cuenta la administrara todavía lleva la dirección provisional admin hasta que su propietario la reemplace. Si además la instancia exige un código al iniciar sesión y el servidor de correo ha dejado de entregarlo, ejecute docker exec -it databasus ./main --disable-2fa para que deje de pedirlo. Los tres comandos están documentados en la página de contraseña.',
},
},
],
@@ -1338,6 +1338,13 @@ export default function Index() {
de datos incluso si la herramienta se ve comprometida.
<br />
<br />
+ El propio inicio de sesión puede exigir un segundo factor: con
+ él activado, tras la contraseña correcta llega un código de
+ seis dígitos al correo de la cuenta, mientras que el inicio de
+ sesión con Google o GitHub sigue apoyándose en las
+ comprobaciones de esos proveedores.
+ <br />
+ <br />
Más allá del tiempo de ejecución, la seguridad y la fiabilidad
se integran en cada commit y PR: análisis estático con CodeQL,
CodeRabbit con gitleaks y semgrep, monitoreo de CVE con
@@ -1713,7 +1720,10 @@ export default function Index() {
--email=&quot;[email protected]&quot;. Una instancia creada
antes de que la primera cuenta la administrara todavía lleva
la dirección provisional admin hasta que su propietario la
- reemplace. Ambos comandos están documentados en
+ reemplace. Si además la instancia exige un código al iniciar
+ sesión y el servidor de correo ha dejado de entregarlo,
+ ejecute docker exec -it databasus ./main --disable-2fa para
+ que deje de pedirlo. Los tres comandos están documentados en
<a
href="/es/password"
className="text-blue-400 hover:text-blue-600"
diff --git a/website/app/[lang]/content/fr.tsx b/website/app/[lang]/content/fr.tsx
index 2b0cfb15..08b55a4e 100644
--- a/website/app/[lang]/content/fr.tsx
+++ b/website/app/[lang]/content/fr.tsx
@@ -178,7 +178,7 @@ export default function Index() {
name: "Comment Databasus assure-t-il la sécurité ?",
acceptedAnswer: {
"@type": "Answer",
- text: "Databasus applique la sécurité à trois niveaux : (1) Chiffrement des données sensibles — tous les mots de passe, jetons et identifiants sont chiffrés avec AES-256-GCM et stockés séparément de la base de données ; (2) Chiffrement des sauvegardes — chaque fichier de sauvegarde est chiffré avec une clé unique dérivée d'une clé maître, de l'ID de la sauvegarde et d'un sel aléatoire, ce qui rend les sauvegardes inutilisables sans votre clé de chiffrement même si quelqu'un accède au stockage ; (3) Accès en lecture seule à la base — Databasus ne requiert que des permissions SELECT et effectue des vérifications complètes pour s'assurer qu'aucun privilège d'écriture n'existe, ce qui empêche toute corruption de données même si l'outil est compromis. Au-delà de l'exécution, la sécurité et la fiabilité sont intégrées à chaque commit et PR : analyse statique CodeQL, CodeRabbit avec gitleaks et semgrep, surveillance des CVE par Dependabot, scans Trivy des images et Dockerfiles, et audits périodiques Codex Security d'OpenAI. Les tests d'intégration s'exécutent contre de vrais conteneurs PostgreSQL, MySQL, MariaDB et MongoDB et vérifient des cycles complets sauvegarde puis restauration à chaque PR. Les GitHub Actions sont épinglées sur des SHA de commit et les workflows suivent le principe du moindre privilège. Toutes les opérations tournent dans des conteneurs que vous contrôlez sur des serveurs qui vous appartiennent, et comme le projet est open source, votre équipe de sécurité peut auditer chaque ligne de code avant le déploiement.",
+ text: "Databasus applique la sécurité à trois niveaux : (1) Chiffrement des données sensibles — tous les mots de passe, jetons et identifiants sont chiffrés avec AES-256-GCM et stockés séparément de la base de données ; (2) Chiffrement des sauvegardes — chaque fichier de sauvegarde est chiffré avec une clé unique dérivée d'une clé maître, de l'ID de la sauvegarde et d'un sel aléatoire, ce qui rend les sauvegardes inutilisables sans votre clé de chiffrement même si quelqu'un accède au stockage ; (3) Accès en lecture seule à la base — Databasus ne requiert que des permissions SELECT et effectue des vérifications complètes pour s'assurer qu'aucun privilège d'écriture n'existe, ce qui empêche toute corruption de données même si l'outil est compromis. La connexion elle-même peut exiger un second facteur : une fois activé, un mot de passe correct est suivi d'un code à six chiffres envoyé à l'adresse du compte, tandis que la connexion par Google ou GitHub continue de s'appuyer sur les vérifications de ces fournisseurs. Au-delà de l'exécution, la sécurité et la fiabilité sont intégrées à chaque commit et PR : analyse statique CodeQL, CodeRabbit avec gitleaks et semgrep, surveillance des CVE par Dependabot, scans Trivy des images et Dockerfiles, et audits périodiques Codex Security d'OpenAI. Les tests d'intégration s'exécutent contre de vrais conteneurs PostgreSQL, MySQL, MariaDB et MongoDB et vérifient des cycles complets sauvegarde puis restauration à chaque PR. Les GitHub Actions sont épinglées sur des SHA de commit et les workflows suivent le principe du moindre privilège. Toutes les opérations tournent dans des conteneurs que vous contrôlez sur des serveurs qui vous appartiennent, et comme le projet est open source, votre équipe de sécurité peut auditer chaque ligne de code avant le déploiement.",
},
},
{
@@ -226,7 +226,7 @@ export default function Index() {
name: "J'ai oublié l'e-mail ou le mot de passe de l'administrateur",
acceptedAnswer: {
"@type": "Answer",
- text: "Le premier compte créé sur l'instance est celui qui l'administre. Si vous ne savez plus quelle est cette adresse, exécutez docker exec -it databasus ./main --list-admins sur le serveur où Databasus tourne : la commande nomme chaque compte administrateur avec son adresse e-mail, son nom affiché, sa date de création et son état d'activité, et n'affiche aucun mot de passe. Pour définir un nouveau mot de passe pour ce compte, exécutez docker exec -it databasus ./main --new-password=\"YourNewSecurePassword123\" --email=\"[email protected]\". Une instance créée avant que le premier compte ne l'administre porte encore l'adresse provisoire admin tant que son propriétaire ne l'a pas remplacée. Les deux commandes sont documentées sur la page mot de passe.",
+ text: "Le premier compte créé sur l'instance est celui qui l'administre. Si vous ne savez plus quelle est cette adresse, exécutez docker exec -it databasus ./main --list-admins sur le serveur où Databasus tourne : la commande nomme chaque compte administrateur avec son adresse e-mail, son nom affiché, sa date de création et son état d'activité, et n'affiche aucun mot de passe. Pour définir un nouveau mot de passe pour ce compte, exécutez docker exec -it databasus ./main --new-password=\"YourNewSecurePassword123\" --email=\"[email protected]\". Une instance créée avant que le premier compte ne l'administre porte encore l'adresse provisoire admin tant que son propriétaire ne l'a pas remplacée. Si l'instance exige en plus un code à la connexion et que le serveur de messagerie ne le délivre plus, exécutez docker exec -it databasus ./main --disable-2fa pour qu'elle cesse de le demander. Les trois commandes sont documentées sur la page mot de passe.",
},
},
],
@@ -1344,6 +1344,13 @@ export default function Index() {
si l&apos;outil est compromis.
<br />
<br />
+ La connexion elle-même peut exiger un second facteur : une
+ fois activé, un mot de passe correct est suivi d&apos;un code
+ à six chiffres envoyé à l&apos;adresse du compte, tandis que
+ la connexion par Google ou GitHub continue de s&apos;appuyer
+ sur les vérifications de ces fournisseurs.
+ <br />
+ <br />
Au-delà de l&apos;exécution, la sécurité et la fiabilité sont
intégrées à chaque commit et PR : analyse statique CodeQL,
CodeRabbit avec gitleaks et semgrep, surveillance des CVE par
@@ -1728,8 +1735,11 @@ export default function Index() {
--email=&quot;[email protected]&quot;. Une instance créée
avant que le premier compte ne l&apos;administre porte encore
l&apos;adresse provisoire admin tant que son propriétaire ne
- l&apos;a pas remplacée. Les deux commandes sont documentées
- sur la
+ l&apos;a pas remplacée. Si l&apos;instance exige en plus un
+ code à la connexion et que le serveur de messagerie ne le
+ délivre plus, exécutez docker exec -it databasus ./main
+ --disable-2fa pour qu&apos;elle cesse de le demander. Les
+ trois commandes sont documentées sur la
<a
href="/fr/password"
className="text-blue-400 hover:text-blue-600"
diff --git a/website/app/[lang]/content/pt.tsx b/website/app/[lang]/content/pt.tsx
index 0e1c02e5..feac3e21 100644
--- a/website/app/[lang]/content/pt.tsx
+++ b/website/app/[lang]/content/pt.tsx
@@ -178,7 +178,7 @@ export default function Index() {
name: "Como o Databasus garante a segurança?",
acceptedAnswer: {
"@type": "Answer",
- text: "O Databasus aplica segurança em três níveis: (1) Criptografia de dados sensíveis — todas as senhas, tokens e credenciais são criptografados com AES-256-GCM e guardados separadamente da base de dados; (2) Criptografia de backups — cada arquivo de backup é criptografado com uma chave única derivada de uma chave mestra, do ID do backup e de um salt aleatório, tornando os backups inúteis sem a sua chave de criptografia mesmo que alguém obtenha acesso ao armazenamento; (3) Acesso somente leitura à base de dados — o Databasus exige apenas permissões SELECT e faz verificações completas para garantir que não existem privilégios de escrita, evitando corrupção de dados mesmo que a ferramenta seja comprometida. Além do tempo de execução, segurança e confiabilidade fazem parte de cada commit e PR: análise estática com CodeQL, CodeRabbit com gitleaks e semgrep, monitoramento de CVEs pelo Dependabot, varreduras de imagem e Dockerfile com Trivy e auditorias periódicas do Codex Security da OpenAI. Testes de integração rodam contra contêineres reais de PostgreSQL, MySQL, MariaDB e MongoDB e verificam ciclos completos de backup e restauração em cada PR. As GitHub Actions são fixadas em SHAs de commit e os workflows seguem permissões de privilégio mínimo. Todas as operações rodam em contêineres sob o seu controle, em servidores seus, e como o código é aberto, a sua equipe de segurança pode auditar cada linha antes da implantação.",
+ text: "O Databasus aplica segurança em três níveis: (1) Criptografia de dados sensíveis — todas as senhas, tokens e credenciais são criptografados com AES-256-GCM e guardados separadamente da base de dados; (2) Criptografia de backups — cada arquivo de backup é criptografado com uma chave única derivada de uma chave mestra, do ID do backup e de um salt aleatório, tornando os backups inúteis sem a sua chave de criptografia mesmo que alguém obtenha acesso ao armazenamento; (3) Acesso somente leitura à base de dados — o Databasus exige apenas permissões SELECT e faz verificações completas para garantir que não existem privilégios de escrita, evitando corrupção de dados mesmo que a ferramenta seja comprometida. O próprio login pode exigir um segundo fator: com ele ativado, depois da senha correta chega um código de seis dígitos ao e-mail da conta, enquanto o login pelo Google ou pelo GitHub continua contando com as verificações desses provedores. Além do tempo de execução, segurança e confiabilidade fazem parte de cada commit e PR: análise estática com CodeQL, CodeRabbit com gitleaks e semgrep, monitoramento de CVEs pelo Dependabot, varreduras de imagem e Dockerfile com Trivy e auditorias periódicas do Codex Security da OpenAI. Testes de integração rodam contra contêineres reais de PostgreSQL, MySQL, MariaDB e MongoDB e verificam ciclos completos de backup e restauração em cada PR. As GitHub Actions são fixadas em SHAs de commit e os workflows seguem permissões de privilégio mínimo. Todas as operações rodam em contêineres sob o seu controle, em servidores seus, e como o código é aberto, a sua equipe de segurança pode auditar cada linha antes da implantação.",
},
},
{
@@ -226,7 +226,7 @@ export default function Index() {
name: "Esqueci o email ou a senha do administrador",
acceptedAnswer: {
"@type": "Answer",
- text: 'A primeira conta criada na instância é quem a administra. Se você não lembra qual é esse endereço, execute docker exec -it databasus ./main --list-admins no servidor onde o Databasus está em execução: ele nomeia cada conta de administrador com seu endereço de email, nome de exibição, data de criação e estado de atividade, e não imprime nenhuma senha. Para definir uma nova senha para essa conta, execute docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]". Uma instância criada antes de a primeira conta administrá-la ainda carrega o endereço provisório admin até que seu dono o substitua. Os dois comandos estão documentados na página de senha.',
+ text: 'A primeira conta criada na instância é quem a administra. Se você não lembra qual é esse endereço, execute docker exec -it databasus ./main --list-admins no servidor onde o Databasus está em execução: ele nomeia cada conta de administrador com seu endereço de email, nome de exibição, data de criação e estado de atividade, e não imprime nenhuma senha. Para definir uma nova senha para essa conta, execute docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]". Uma instância criada antes de a primeira conta administrá-la ainda carrega o endereço provisório admin até que seu dono o substitua. Se a instância também exigir um código ao entrar e o servidor de e-mail tiver parado de entregá-lo, execute docker exec -it databasus ./main --disable-2fa para que ela pare de pedir o código. Os três comandos estão documentados na página de senha.',
},
},
],
@@ -1331,6 +1331,12 @@ export default function Index() {
mesmo que a ferramenta seja comprometida.
<br />
<br />
+ O próprio login pode exigir um segundo fator: com ele ativado,
+ depois da senha correta chega um código de seis dígitos ao
+ e-mail da conta, enquanto o login pelo Google ou pelo GitHub
+ continua contando com as verificações desses provedores.
+ <br />
+ <br />
Além do tempo de execução, segurança e confiabilidade fazem
parte de cada commit e PR: análise estática com CodeQL,
CodeRabbit com gitleaks e semgrep, monitoramento de CVEs pelo
@@ -1699,8 +1705,11 @@ export default function Index() {
--new-password=&quot;YourNewSecurePassword123&quot;
--email=&quot;[email protected]&quot;. Uma instância criada
antes de a primeira conta administrá-la ainda carrega o
- endereço provisório admin até que seu dono o substitua. Os
- dois comandos estão documentados na
+ endereço provisório admin até que seu dono o substitua. Se a
+ instância também exigir um código ao entrar e o servidor de
+ e-mail tiver parado de entregá-lo, execute docker exec -it
+ databasus ./main --disable-2fa para que ela pare de pedir o
+ código. Os três comandos estão documentados na
<a
href="/pt/password"
className="text-blue-400 hover:text-blue-600"
diff --git a/website/app/[lang]/content/ru.tsx b/website/app/[lang]/content/ru.tsx
index 2b078e8c..45a45736 100644
--- a/website/app/[lang]/content/ru.tsx
+++ b/website/app/[lang]/content/ru.tsx
@@ -178,7 +178,7 @@ export default function Index() {
name: "Как Databasus обеспечивает безопасность?",
acceptedAnswer: {
"@type": "Answer",
- text: "Databasus обеспечивает безопасность на трех уровнях: (1) шифрование чувствительных данных — все пароли, токены и учетные данные шифруются AES-256-GCM и хранятся отдельно от базы данных; (2) шифрование бекапов — каждый файл бекапа шифруется уникальным ключом, выведенным из мастер-ключа, ID бекапа и случайной соли, так что без вашего ключа бекапы бесполезны, даже если кто-то получит доступ к хранилищу; (3) доступ к базе только на чтение — Databasus требует лишь права SELECT и тщательно проверяет отсутствие прав на запись, что защищает данные от порчи даже при компрометации инструмента. Помимо этого, безопасность и надежность встроены в каждый коммит и PR: статический анализ CodeQL, CodeRabbit с gitleaks и semgrep, мониторинг CVE через Dependabot, сканирование образов и Dockerfile через Trivy и периодические аудиты Codex Security от OpenAI. Интеграционные тесты гоняются на реальных контейнерах PostgreSQL, MySQL, MariaDB и MongoDB и проверяют полный цикл «бекап, затем восстановление» на каждом PR. GitHub Actions закреплены на SHA коммитов, а воркфлоу следуют принципу минимальных привилегий. Все операции выполняются в контейнерах под вашим контролем на ваших серверах, и поскольку это open source, ваша команда безопасности может проверить каждую строку кода до развертывания.",
+ text: "Databasus обеспечивает безопасность на трех уровнях: (1) шифрование чувствительных данных — все пароли, токены и учетные данные шифруются AES-256-GCM и хранятся отдельно от базы данных; (2) шифрование бекапов — каждый файл бекапа шифруется уникальным ключом, выведенным из мастер-ключа, ID бекапа и случайной соли, так что без вашего ключа бекапы бесполезны, даже если кто-то получит доступ к хранилищу; (3) доступ к базе только на чтение — Databasus требует лишь права SELECT и тщательно проверяет отсутствие прав на запись, что защищает данные от порчи даже при компрометации инструмента. Сам вход тоже можно закрыть вторым фактором: когда он включен, после верного пароля на почту аккаунта приходит шестизначный код, а вход через Google или GitHub по-прежнему опирается на проверки самих провайдеров. Помимо этого, безопасность и надежность встроены в каждый коммит и PR: статический анализ CodeQL, CodeRabbit с gitleaks и semgrep, мониторинг CVE через Dependabot, сканирование образов и Dockerfile через Trivy и периодические аудиты Codex Security от OpenAI. Интеграционные тесты гоняются на реальных контейнерах PostgreSQL, MySQL, MariaDB и MongoDB и проверяют полный цикл «бекап, затем восстановление» на каждом PR. GitHub Actions закреплены на SHA коммитов, а воркфлоу следуют принципу минимальных привилегий. Все операции выполняются в контейнерах под вашим контролем на ваших серверах, и поскольку это open source, ваша команда безопасности может проверить каждую строку кода до развертывания.",
},
},
{
@@ -226,7 +226,7 @@ export default function Index() {
name: "Я забыл email или пароль администратора",
acceptedAnswer: {
"@type": "Answer",
- text: 'Первая учетная запись, созданная на инстансе, им и управляет. Если вы не помните, какой это адрес, выполните docker exec -it databasus ./main --list-admins на сервере, где запущен Databasus — команда перечислит все учетные записи администраторов с их email, именем, датой создания и состоянием активности и не выведет ни одного пароля. Чтобы задать новый пароль этой учетной записи, выполните docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]". Инстанс, созданный до того, как первая учетная запись стала им управлять, до сих пор носит адрес-заглушку admin, пока владелец его не заменит. Обе команды описаны на странице про пароль.',
+ text: 'Первая учетная запись, созданная на инстансе, им и управляет. Если вы не помните, какой это адрес, выполните docker exec -it databasus ./main --list-admins на сервере, где запущен Databasus — команда перечислит все учетные записи администраторов с их email, именем, датой создания и состоянием активности и не выведет ни одного пароля. Чтобы задать новый пароль этой учетной записи, выполните docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]". Инстанс, созданный до того, как первая учетная запись стала им управлять, до сих пор носит адрес-заглушку admin, пока владелец его не заменит. Если инстанс еще и требует код при входе, а почта перестала его доставлять, выполните docker exec -it databasus ./main --disable-2fa, чтобы инстанс перестал запрашивать код. Все три команды описаны на странице про пароль.',
},
},
],
@@ -1316,6 +1316,12 @@ export default function Index() {
защищает данные от порчи даже при компрометации инструмента.
<br />
<br />
+ Сам вход тоже можно закрыть вторым фактором: когда он включен,
+ после верного пароля на почту аккаунта приходит шестизначный
+ код, а вход через Google или GitHub по-прежнему опирается на
+ проверки самих провайдеров.
+ <br />
+ <br />
Помимо этого, безопасность и надежность встроены в каждый
коммит и PR: статический анализ CodeQL, CodeRabbit с gitleaks
и semgrep, мониторинг CVE через Dependabot, сканирование
@@ -1662,7 +1668,10 @@ export default function Index() {
--new-password=&quot;YourNewSecurePassword123&quot;
--email=&quot;[email protected]&quot;. Инстанс, созданный до
того, как первая учетная запись стала им управлять, до сих пор
- носит адрес-заглушку admin, пока владелец его не заменит. Обе
+ носит адрес-заглушку admin, пока владелец его не заменит. Если
+ инстанс еще и требует код при входе, а почта перестала его
+ доставлять, выполните docker exec -it databasus ./main
+ --disable-2fa, чтобы инстанс перестал запрашивать код. Все три
команды описаны на
<a
href="/ru/password"
diff --git a/website/app/[lang]/content/zh.tsx b/website/app/[lang]/content/zh.tsx
index 2be70fad..11ccf863 100644
--- a/website/app/[lang]/content/zh.tsx
+++ b/website/app/[lang]/content/zh.tsx
@@ -178,7 +178,7 @@ export default function Index() {
name: "Databasus 如何保证安全性?",
acceptedAnswer: {
"@type": "Answer",
- text: "Databasus 从三个层面保障安全:(1)敏感数据加密——所有密码、令牌和凭据均使用 AES-256-GCM 加密,并与数据库分开存储;(2)备份加密——每个备份文件都使用由主密钥、备份 ID 和随机盐派生出的唯一密钥加密,即使有人获得了存储的访问权限,没有你的加密密钥备份也毫无用处;(3)只读数据库访问——Databasus 只需要 SELECT 权限,并会做全面检查确保不存在任何写权限,即使工具本身被攻破也不会破坏数据。在运行时之外,安全性和可靠性也被落实到每一次提交和 PR:CodeQL 静态分析、集成 gitleaks 和 semgrep 的 CodeRabbit、Dependabot CVE 监控、Trivy 镜像与 Dockerfile 扫描,以及 OpenAI 定期进行的 Codex Security 审计。集成测试针对真实的 PostgreSQL、MySQL、MariaDB 和 MongoDB 容器运行,并在每个 PR 上验证完整的备份加恢复流程。GitHub Actions 固定到提交 SHA,工作流遵循最小权限原则。所有操作都在你控制的容器和你拥有的服务器上运行,而且因为它是开源的,你的安全团队可以在部署前审计每一行代码。",
+ text: "Databasus 从三个层面保障安全:(1)敏感数据加密——所有密码、令牌和凭据均使用 AES-256-GCM 加密,并与数据库分开存储;(2)备份加密——每个备份文件都使用由主密钥、备份 ID 和随机盐派生出的唯一密钥加密,即使有人获得了存储的访问权限,没有你的加密密钥备份也毫无用处;(3)只读数据库访问——Databasus 只需要 SELECT 权限,并会做全面检查确保不存在任何写权限,即使工具本身被攻破也不会破坏数据。登录本身也可以要求第二重验证:启用后,密码正确之后账号邮箱会收到六位验证码,而通过 Google 或 GitHub 登录仍然依赖这些服务商自己的验证。在运行时之外,安全性和可靠性也被落实到每一次提交和 PR:CodeQL 静态分析、集成 gitleaks 和 semgrep 的 CodeRabbit、Dependabot CVE 监控、Trivy 镜像与 Dockerfile 扫描,以及 OpenAI 定期进行的 Codex Security 审计。集成测试针对真实的 PostgreSQL、MySQL、MariaDB 和 MongoDB 容器运行,并在每个 PR 上验证完整的备份加恢复流程。GitHub Actions 固定到提交 SHA,工作流遵循最小权限原则。所有操作都在你控制的容器和你拥有的服务器上运行,而且因为它是开源的,你的安全团队可以在部署前审计每一行代码。",
},
},
{
@@ -226,7 +226,7 @@ export default function Index() {
name: "我忘记了管理员邮箱或密码",
acceptedAnswer: {
"@type": "Answer",
- text: '实例上创建的第一个账户就是它的管理员。如果你不记得那个地址,可以在运行 Databasus 的服务器上执行 docker exec -it databasus ./main --list-admins:它会列出每个管理员账户的邮箱、显示名称、创建日期和活动状态,并且不会输出任何密码。要为该账户设置新密码,请执行 docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]"。在第一个账户成为管理员之前创建的实例,在其所有者替换之前仍使用占位地址 admin。这两条命令都记录在密码页面上。',
+ text: '实例上创建的第一个账户就是它的管理员。如果你不记得那个地址,可以在运行 Databasus 的服务器上执行 docker exec -it databasus ./main --list-admins:它会列出每个管理员账户的邮箱、显示名称、创建日期和活动状态,并且不会输出任何密码。要为该账户设置新密码,请执行 docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]"。在第一个账户成为管理员之前创建的实例,在其所有者替换之前仍使用占位地址 admin。如果实例还要求登录验证码,而邮件服务器已经无法送达,请执行 docker exec -it databasus ./main --disable-2fa,让实例不再要求验证码。这三条命令都记录在密码页面上。',
},
},
],
@@ -1275,6 +1275,10 @@ export default function Index() {
权限,并会做全面检查确保不存在任何写权限,即使工具本身被攻破也不会破坏数据。
<br />
<br />
+ 登录本身也可以要求第二重验证:启用后,密码正确之后账号邮箱会收到六位验证码,而通过
+ Google 或 GitHub 登录仍然依赖这些服务商自己的验证。
+ <br />
+ <br />
在运行时之外,安全性和可靠性也被落实到每一次提交和 PR:CodeQL
静态分析、集成 gitleaks 和 semgrep 的 CodeRabbit、Dependabot
CVE 监控、Trivy 镜像与 Dockerfile 扫描,以及 OpenAI 定期进行的
@@ -1586,7 +1590,9 @@ export default function Index() {
docker exec -it databasus ./main
--new-password=&quot;YourNewSecurePassword123&quot;
--email=&quot;[email protected]&quot;。在第一个账户成为管理员之前创建的实例,在其所有者替换之前仍使用占位地址
- admin。这两条命令都记录在
+ admin。如果实例还要求登录验证码,而邮件服务器已经无法送达,请执行
+ docker exec -it databasus ./main
+ --disable-2fa,让实例不再要求验证码。这三条命令都记录在
<a
href="/zh/password"
className="text-blue-400 hover:text-blue-600"
diff --git a/website/app/[lang]/password/content/es.tsx b/website/app/[lang]/password/content/es.tsx
index 942e727e..68e7d06e 100644
--- a/website/app/[lang]/password/content/es.tsx
+++ b/website/app/[lang]/password/content/es.tsx
@@ -41,6 +41,7 @@ export const metadata: Metadata = {
export default function PasswordResetPage() {
const resetPasswordCommand = `docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]"`;
const listAdminsCommand = `docker exec -it databasus ./main --list-admins`;
+ const disableTwoFactorCommand = `docker exec -it databasus ./main --disable-2fa`;
return (
<>
@@ -176,6 +177,34 @@ export default function PasswordResetPage() {
ningún token. En una instancia donde todavía nadie ha creado una
cuenta, informa de que la instancia no tiene administrador.
</p>
+ <h2 id="disable-two-factor">
+ Dejar de pedir un código al iniciar sesión
+ </h2>
+
+ <p>
+ Una instancia puede exigir, además de la contraseña, un código
+ de seis dígitos enviado por correo al iniciar sesión. Si el
+ servidor de correo deja de entregar esos códigos, nadie entra
+ con contraseña, y restablecerla no basta. Desactive el segundo
+ factor en el servidor donde se ejecuta Databasus:
+ </p>
+
+ <div className="relative my-6">
+ <pre className="overflow-x-auto rounded-lg bg-gray-900 p-4 text-sm text-gray-100">
+ <code>{disableTwoFactorCommand}</code>
+ </pre>
+ <div className="absolute right-2 top-2">
+ <CopyButton text={disableTwoFactorCommand} />
+ </div>
+ </div>
+
+ <p>
+ El comando informa de si ha cambiado algo, termina sin quejarse
+ cuando el segundo factor ya está desactivado y registra el
+ cambio en el historial de auditoría. El siguiente inicio de
+ sesión con contraseña ya no pide código, y un administrador
+ puede volver a activar el ajuste cuando el correo funcione.
+ </p>
</article>
</div>
</main>
diff --git a/website/app/[lang]/password/content/fr.tsx b/website/app/[lang]/password/content/fr.tsx
index 95e87676..50cd5cae 100644
--- a/website/app/[lang]/password/content/fr.tsx
+++ b/website/app/[lang]/password/content/fr.tsx
@@ -41,6 +41,7 @@ export const metadata: Metadata = {
export default function PasswordResetPage() {
const resetPasswordCommand = `docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]"`;
const listAdminsCommand = `docker exec -it databasus ./main --list-admins`;
+ const disableTwoFactorCommand = `docker exec -it databasus ./main --disable-2fa`;
return (
<>
@@ -180,6 +181,36 @@ export default function PasswordResetPage() {
personne n&apos;a encore créé de compte, elle indique que
l&apos;instance n&apos;a pas d&apos;administrateur.
</p>
+ <h2 id="disable-two-factor">
+ Cesser de demander un code à la connexion
+ </h2>
+
+ <p>
+ Une instance peut exiger, en plus du mot de passe, un code à six
+ chiffres envoyé par e-mail à la connexion. Si le serveur de
+ messagerie cesse de délivrer ces codes, plus personne
+ n&apos;entre avec un mot de passe, et réinitialiser le mot de
+ passe n&apos;y change rien. Désactivez le second facteur sur le
+ serveur où Databasus tourne :
+ </p>
+
+ <div className="relative my-6">
+ <pre className="overflow-x-auto rounded-lg bg-gray-900 p-4 text-sm text-gray-100">
+ <code>{disableTwoFactorCommand}</code>
+ </pre>
+ <div className="absolute right-2 top-2">
+ <CopyButton text={disableTwoFactorCommand} />
+ </div>
+ </div>
+
+ <p>
+ La commande indique si elle a changé quelque chose, se termine
+ sans se plaindre quand le second facteur est déjà désactivé, et
+ inscrit le changement au journal d&apos;audit. La prochaine
+ connexion par mot de passe se passe alors de code, et un
+ administrateur pourra réactiver le réglage dès que la messagerie
+ refonctionnera.
+ </p>
</article>
</div>
</main>
diff --git a/website/app/[lang]/password/content/pt.tsx b/website/app/[lang]/password/content/pt.tsx
index 3c881e42..cca2fc75 100644
--- a/website/app/[lang]/password/content/pt.tsx
+++ b/website/app/[lang]/password/content/pt.tsx
@@ -41,6 +41,7 @@ export const metadata: Metadata = {
export default function PasswordResetPage() {
const resetPasswordCommand = `docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]"`;
const listAdminsCommand = `docker exec -it databasus ./main --list-admins`;
+ const disableTwoFactorCommand = `docker exec -it databasus ./main --disable-2fa`;
return (
<>
@@ -175,6 +176,34 @@ export default function PasswordResetPage() {
instância onde ninguém criou uma conta ainda, ela informa que a
instância não tem administrador.
</p>
+ <h2 id="disable-two-factor">
+ Parar de pedir um código no login
+ </h2>
+
+ <p>
+ Uma instância pode exigir, além da senha, um código de seis
+ dígitos enviado por e-mail no login. Se o servidor de e-mail
+ parar de entregar esses códigos, ninguém entra com senha, e
+ redefinir a senha sozinho não resolve. Desligue o segundo fator
+ no servidor onde o Databasus está em execução:
+ </p>
+
+ <div className="relative my-6">
+ <pre className="overflow-x-auto rounded-lg bg-gray-900 p-4 text-sm text-gray-100">
+ <code>{disableTwoFactorCommand}</code>
+ </pre>
+ <div className="absolute right-2 top-2">
+ <CopyButton text={disableTwoFactorCommand} />
+ </div>
+ </div>
+
+ <p>
+ O comando informa se mudou alguma coisa, termina sem reclamar
+ quando o segundo fator já está desligado e registra a mudança no
+ log de auditoria. O próximo login por senha dispensa o código, e
+ um administrador pode ligar a opção de novo assim que o e-mail
+ voltar a funcionar.
+ </p>
</article>
</div>
</main>
diff --git a/website/app/[lang]/password/content/ru.tsx b/website/app/[lang]/password/content/ru.tsx
index 78f46bc5..758b1f11 100644
--- a/website/app/[lang]/password/content/ru.tsx
+++ b/website/app/[lang]/password/content/ru.tsx
@@ -41,6 +41,7 @@ export const metadata: Metadata = {
export default function PasswordResetPage() {
const resetPasswordCommand = `docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]"`;
const listAdminsCommand = `docker exec -it databasus ./main --list-admins`;
+ const disableTwoFactorCommand = `docker exec -it databasus ./main --disable-2fa`;
return (
<>
@@ -171,6 +172,34 @@ export default function PasswordResetPage() {
где еще никто не завел учетную запись, команда сообщит, что
администратора нет.
</p>
+ <h2 id="disable-two-factor">
+ Перестать запрашивать код при входе
+ </h2>
+
+ <p>
+ Инстанс может требовать при входе шестизначный код, присланный
+ по почте, в дополнение к паролю. Если почтовый сервер перестал
+ доставлять такие письма, по паролю не войдет никто, и сброс
+ пароля сам по себе не поможет. Выключите второй фактор на
+ сервере, где запущен Databasus:
+ </p>
+
+ <div className="relative my-6">
+ <pre className="overflow-x-auto rounded-lg bg-gray-900 p-4 text-sm text-gray-100">
+ <code>{disableTwoFactorCommand}</code>
+ </pre>
+ <div className="absolute right-2 top-2">
+ <CopyButton text={disableTwoFactorCommand} />
+ </div>
+ </div>
+
+ <p>
+ Команда сообщает, изменила ли она что-нибудь, спокойно
+ отрабатывает, если второй фактор уже выключен, и записывает
+ изменение в журнал аудита. Следующий вход по паролю пройдет без
+ кода, а когда почта заработает, администратор может снова
+ включить настройку.
+ </p>
</article>
</div>
</main>
diff --git a/website/app/[lang]/password/content/zh.tsx b/website/app/[lang]/password/content/zh.tsx
index 896cfd40..96d4a167 100644
--- a/website/app/[lang]/password/content/zh.tsx
+++ b/website/app/[lang]/password/content/zh.tsx
@@ -41,6 +41,7 @@ export const metadata: Metadata = {
export default function PasswordResetPage() {
const resetPasswordCommand = `docker exec -it databasus ./main --new-password="YourNewSecurePassword123" --email="[email protected]"`;
const listAdminsCommand = `docker exec -it databasus ./main --list-admins`;
+ const disableTwoFactorCommand = `docker exec -it databasus ./main --disable-2fa`;
return (
<>
@@ -161,6 +162,25 @@ export default function PasswordResetPage() {
<p>
输出会列出每个管理员账户的邮箱、显示名称、创建日期和活动状态,并标记实例所认可的管理员。不会输出任何密码、密码哈希或令牌。如果实例上还没有人创建账户,命令会提示该实例没有管理员。
</p>
+ <h2 id="disable-two-factor">不再要求登录验证码</h2>
+
+ <p>
+ 实例可以在密码之外,要求输入通过邮件发送的六位登录验证码。如果邮件服务器不再送达这些验证码,谁都无法用密码登录,单靠重置密码也不管用。请在运行
+ Databasus 的服务器上关掉第二重验证:
+ </p>
+
+ <div className="relative my-6">
+ <pre className="overflow-x-auto rounded-lg bg-gray-900 p-4 text-sm text-gray-100">
+ <code>{disableTwoFactorCommand}</code>
+ </pre>
+ <div className="absolute right-2 top-2">
+ <CopyButton text={disableTwoFactorCommand} />
+ </div>
+ </div>
+
+ <p>
+ 命令会说明它是否改动了设置,第二重验证本来就关着时也会正常结束,并把这次改动写入审计日志。之后的密码登录不再需要验证码;等邮件恢复正常,管理员可以重新打开该设置。
+ </p>
</article>
</div>
</main>
diff --git a/website/app/[lang]/security/content/es.tsx b/website/app/[lang]/security/content/es.tsx
index 0f8e49d6..a23626bd 100644
--- a/website/app/[lang]/security/content/es.tsx
+++ b/website/app/[lang]/security/content/es.tsx
@@ -43,6 +43,7 @@ export const metadata: Metadata = {
export default function SecurityPage() {
const encryptionPipeline = `PostgreSQL pg_dump → Compression → Encryption → Cloud Storage`;
+ const disableTwoFactorCommand = `docker exec -it databasus ./main --disable-2fa`;
return (
<>
@@ -276,6 +277,65 @@ export default function SecurityPage() {
podrán corromper su base de datos.
</p>
+ <h2 id="two-factor-authentication">
+ Autenticación de dos factores al iniciar sesión
+ </h2>
+
+ <p>
+ Una contraseña por sí sola abre todas las credenciales de bases
+ de datos, las claves de almacenamiento y las copias de seguridad
+ que guarda la instancia, así que un administrador puede exigir
+ un segundo factor al iniciar sesión con contraseña. Con la
+ opción activada, una contraseña correcta envía un código de seis
+ dígitos al correo de la cuenta y el inicio de sesión termina
+ solo cuando se introduce ese código. El código deja de funcionar
+ diez minutos después de enviarse o tras cinco intentos fallidos,
+ y pedir otro anula el anterior. Activar el ajuste protege el
+ siguiente inicio de sesión y deja funcionando las sesiones ya
+ abiertas.
+ </p>
+
+ <p>
+ El ajuste cubre el inicio de sesión con contraseña. Entrar con
+ Google o GitHub sigue entregando un token directamente, porque
+ esos proveedores hacen sus propias comprobaciones de varios
+ factores: una instancia que quiera el segundo factor para todo
+ el mundo simplemente no los configura.
+ </p>
+
+ <p>
+ Solo se puede activar cuando la instancia tiene servidor de
+ correo y cada administrador activo lleva una dirección real, de
+ modo que nadie lo active y deje la instancia cerrada. Si más
+ tarde el correo deja de entregarse, nadie entra con contraseña,
+ y eso es deliberado: un servidor de correo averiado no debe
+ rebajar en silencio la autenticación a un solo factor. Un
+ operador con acceso al servidor vuelve a desactivarlo:
+ </p>
+
+ <div className="relative my-6">
+ <pre className="overflow-x-auto rounded-lg bg-gray-900 p-4 text-sm text-gray-100">
+ <code>{disableTwoFactorCommand}</code>
+ </pre>
+ <div className="absolute right-2 top-2">
+ <CopyButton text={disableTwoFactorCommand} />
+ </div>
+ </div>
+
+ <p>
+ El comando informa de lo que ha cambiado y lo registra en el
+ historial de auditoría, así que una instancia que dejó de pedir
+ códigos explica por qué. Está documentado junto a la
+ recuperación de contraseña en{" "}
+ <a
+ href="/es/password#disable-two-factor"
+ className="text-blue-400 hover:text-blue-600"
+ >
+ la página de contraseña
+ </a>
+ .
+ </p>
+
<h2 id="security-and-reliability-engineering">
🛡️ Ingeniería de seguridad y fiabilidad
</h2>
diff --git a/website/app/[lang]/security/content/fr.tsx b/website/app/[lang]/security/content/fr.tsx
index d6ba690d..49e099aa 100644
--- a/website/app/[lang]/security/content/fr.tsx
+++ b/website/app/[lang]/security/content/fr.tsx
@@ -43,6 +43,7 @@ export const metadata: Metadata = {
export default function SecurityPage() {
const encryptionPipeline = `PostgreSQL pg_dump → Compression → Encryption → Cloud Storage`;
+ const disableTwoFactorCommand = `docker exec -it databasus ./main --disable-2fa`;
return (
<>
@@ -291,6 +292,66 @@ export default function SecurityPage() {
de données.
</p>
+ <h2 id="two-factor-authentication">
+ Authentification à deux facteurs à la connexion
+ </h2>
+
+ <p>
+ Un mot de passe seul ouvre tous les identifiants de bases, les
+ clés de stockage et les sauvegardes que l&apos;instance
+ conserve, donc un administrateur peut exiger un second facteur
+ pour la connexion par mot de passe. Une fois activé, un mot de
+ passe correct envoie un code à six chiffres à l&apos;adresse du
+ compte, et la connexion n&apos;aboutit qu&apos;après la saisie
+ de ce code. Le code cesse de fonctionner dix minutes après son
+ envoi ou après cinq essais erronés, et en demander un autre
+ annule le précédent. Activer le réglage protège la prochaine
+ connexion et laisse fonctionner les sessions déjà ouvertes.
+ </p>
+
+ <p>
+ Le réglage couvre la connexion par mot de passe. Se connecter
+ par Google ou GitHub délivre toujours un jeton directement,
+ parce que ces fournisseurs font leurs propres vérifications
+ multifacteurs : une instance qui veut le second facteur pour
+ tout le monde ne les configure tout simplement pas.
+ </p>
+
+ <p>
+ Il ne peut être activé que si l&apos;instance dispose d&apos;un
+ serveur de messagerie et que chaque administrateur actif porte
+ une vraie adresse, pour que personne ne l&apos;active et ne se
+ retrouve bloqué hors de l&apos;instance. Si la messagerie cesse
+ ensuite de distribuer les e-mails, plus personne n&apos;entre
+ avec un mot de passe, et c&apos;est délibéré : un serveur de
+ messagerie en panne ne doit pas ramener discrètement la
+ connexion à un seul facteur. Un opérateur ayant accès au serveur
+ le désactive :
+ </p>
+
+ <div className="relative my-6">
+ <pre className="overflow-x-auto rounded-lg bg-gray-900 p-4 text-sm text-gray-100">
+ <code>{disableTwoFactorCommand}</code>
+ </pre>
+ <div className="absolute right-2 top-2">
+ <CopyButton text={disableTwoFactorCommand} />
+ </div>
+ </div>
+
+ <p>
+ La commande indique ce qu&apos;elle a changé et l&apos;inscrit
+ au journal d&apos;audit, si bien qu&apos;une instance qui a
+ cessé de demander des codes en explique la raison. Elle est
+ documentée à côté de la récupération de mot de passe sur la{" "}
+ <a
+ href="/fr/password#disable-two-factor"
+ className="text-blue-400 hover:text-blue-600"
+ >
+ page mot de passe
+ </a>
+ .
+ </p>
+
<h2 id="security-and-reliability-engineering">
🛡️ Ingénierie de sécurité et de fiabilité
</h2>
diff --git a/website/app/[lang]/security/content/pt.tsx b/website/app/[lang]/security/content/pt.tsx
index ca140c17..04d6db81 100644
--- a/website/app/[lang]/security/content/pt.tsx
+++ b/website/app/[lang]/security/content/pt.tsx
@@ -43,6 +43,7 @@ export const metadata: Metadata = {
export default function SecurityPage() {
const encryptionPipeline = `PostgreSQL pg_dump → Compression → Encryption → Cloud Storage`;
+ const disableTwoFactorCommand = `docker exec -it databasus ./main --disable-2fa`;
return (
<>
@@ -273,6 +274,63 @@ export default function SecurityPage() {
corromper a sua base de dados.
</p>
+ <h2 id="two-factor-authentication">
+ Autenticação de dois fatores no login
+ </h2>
+
+ <p>
+ Só a senha já abre todas as credenciais de bases de dados, as
+ chaves de armazenamento e os backups que a instância guarda, por
+ isso um administrador pode exigir um segundo fator no login por
+ senha. Com a opção ligada, a senha correta envia um código de
+ seis dígitos para o e-mail da conta e o login termina apenas
+ quando esse código é informado. O código para de funcionar dez
+ minutos depois do envio ou após cinco tentativas erradas, e
+ pedir outro cancela o anterior. Ligar a opção protege o próximo
+ login e mantém funcionando as sessões já abertas.
+ </p>
+
+ <p>
+ A configuração vale para o login por senha. Entrar pelo Google
+ ou pelo GitHub continua entregando um token direto, porque esses
+ provedores fazem as próprias verificações de vários fatores: uma
+ instância que queira o segundo fator para todo mundo
+ simplesmente não os configura.
+ </p>
+
+ <p>
+ Ela só pode ser ligada quando a instância tem servidor de e-mail
+ e todo administrador ativo tem um endereço de verdade, para que
+ ninguém ligue a opção e tranque a instância. Se o e-mail parar
+ de ser entregue depois, ninguém entra com senha, e isso é
+ proposital: um servidor de e-mail quebrado não pode rebaixar o
+ login para um fator em silêncio. Um operador com acesso ao
+ servidor desliga a opção de novo:
+ </p>
+
+ <div className="relative my-6">
+ <pre className="overflow-x-auto rounded-lg bg-gray-900 p-4 text-sm text-gray-100">
+ <code>{disableTwoFactorCommand}</code>
+ </pre>
+ <div className="absolute right-2 top-2">
+ <CopyButton text={disableTwoFactorCommand} />
+ </div>
+ </div>
+
+ <p>
+ O comando informa o que mudou e registra isso no log de
+ auditoria, então uma instância que parou de pedir códigos
+ explica o motivo. Ele está documentado ao lado da recuperação de
+ senha na{" "}
+ <a
+ href="/pt/password#disable-two-factor"
+ className="text-blue-400 hover:text-blue-600"
+ >
+ página de senha
+ </a>
+ .
+ </p>
+
<h2 id="security-and-reliability-engineering">
🛡️ Engenharia de segurança e confiabilidade
</h2>
diff --git a/website/app/[lang]/security/content/ru.tsx b/website/app/[lang]/security/content/ru.tsx
index f3255023..48e6bdb1 100644
--- a/website/app/[lang]/security/content/ru.tsx
+++ b/website/app/[lang]/security/content/ru.tsx
@@ -43,6 +43,7 @@ export const metadata: Metadata = {
export default function SecurityPage() {
const encryptionPipeline = `PostgreSQL pg_dump → Compression → Encryption → Cloud Storage`;
+ const disableTwoFactorCommand = `docker exec -it databasus ./main --disable-2fa`;
return (
<>
@@ -274,6 +275,61 @@ export default function SecurityPage() {
вашу базу.
</p>
+ <h2 id="two-factor-authentication">
+ Двухфакторная аутентификация при входе
+ </h2>
+
+ <p>
+ Один пароль открывает все учетные данные баз, ключи хранилищ и
+ бекапы, которые держит инстанс, поэтому администратор может
+ потребовать второй фактор при входе по паролю. Когда он включен,
+ после верного пароля на почту аккаунта уходит шестизначный код,
+ и вход завершается только после его ввода. Код перестает
+ работать через десять минут после отправки или после пяти
+ неверных попыток, а запрос нового кода отменяет предыдущий.
+ Включение настройки защищает следующий вход и не завершает уже
+ открытые сессии.
+ </p>
+
+ <p>
+ Настройка касается входа по паролю. Вход через Google или GitHub
+ по-прежнему сразу выдает токен, потому что эти провайдеры
+ проводят собственные многофакторные проверки &mdash; инстанс,
+ которому нужен второй фактор для всех, просто не подключает их.
+ </p>
+
+ <p>
+ Включить настройку можно, только если у инстанса есть почтовый
+ сервер и у каждого активного администратора указан настоящий
+ адрес, чтобы никто не включил ее и не закрыл себе вход. Если
+ почта перестанет доставлять письма позже, по паролю не войдет
+ никто, и это сделано намеренно: сломанный почтовый сервер не
+ должен тихо возвращать вход к одному фактору. Оператор с
+ доступом к серверу выключает настройку обратно:
+ </p>
+
+ <div className="relative my-6">
+ <pre className="overflow-x-auto rounded-lg bg-gray-900 p-4 text-sm text-gray-100">
+ <code>{disableTwoFactorCommand}</code>
+ </pre>
+ <div className="absolute right-2 top-2">
+ <CopyButton text={disableTwoFactorCommand} />
+ </div>
+ </div>
+
+ <p>
+ Команда сообщает, что изменила, и записывает это в журнал
+ аудита, так что инстанс, переставший запрашивать коды, объясняет
+ почему. Она описана рядом с восстановлением пароля на{" "}
+ <a
+ href="/ru/password#disable-two-factor"
+ className="text-blue-400 hover:text-blue-600"
+ >
+ странице про пароль
+ </a>
+ .
+ </p>
+
<h2 id="security-and-reliability-engineering">
🛡️ Инженерия безопасности и надежности
</h2>
diff --git a/website/app/[lang]/security/content/zh.tsx b/website/app/[lang]/security/content/zh.tsx
index 8ea2c4f8..6b4c0c47 100644
--- a/website/app/[lang]/security/content/zh.tsx
+++ b/website/app/[lang]/security/content/zh.tsx
@@ -43,6 +43,7 @@ export const metadata: Metadata = {
export default function SecurityPage() {
const encryptionPipeline = `PostgreSQL pg_dump → Compression → Encryption → Cloud Storage`;
+ const disableTwoFactorCommand = `docker exec -it databasus ./main --disable-2fa`;
return (
<>
@@ -232,6 +233,41 @@ export default function SecurityPage() {
密钥被盗、凭据被解密,攻击者也破坏不了你的数据库。
</p>
+ <h2 id="two-factor-authentication">登录的双因素验证</h2>
+
+ <p>
+ 仅凭密码就能拿到实例保管的所有数据库凭据、存储密钥和备份,因此管理员可以为密码登录要求第二重验证。启用后,密码正确会把六位验证码发到账号邮箱,只有输入该验证码才算完成登录。验证码在发送十分钟后或五次错误尝试后失效,重新索取会让上一个验证码作废。启用该设置只保护下一次登录,已经打开的会话仍可继续使用。
+ </p>
+
+ <p>
+ 该设置只覆盖密码登录。通过 Google 或 GitHub
+ 登录仍然直接签发令牌,因为这些服务商有自己的多因素验证;想让第二重验证覆盖所有人的实例,干脆不要配置它们。
+ </p>
+
+ <p>
+ 只有实例配置了邮件服务器、并且每个在用的管理员都填了真实邮箱时才能启用,免得有人打开开关把自己关在门外。如果邮件之后无法送达,谁都无法用密码登录,这是故意的:坏掉的邮件服务器不该悄悄把登录退回到单因素。有服务器访问权限的运维可以再把它关掉:
+ </p>
+
+ <div className="relative my-6">
+ <pre className="overflow-x-auto rounded-lg bg-gray-900 p-4 text-sm text-gray-100">
+ <code>{disableTwoFactorCommand}</code>
+ </pre>
+ <div className="absolute right-2 top-2">
+ <CopyButton text={disableTwoFactorCommand} />
+ </div>
+ </div>
+
+ <p>
+ 命令会说明它改了什么,并把这次改动写入审计日志,于是不再要求验证码的实例能说清原因。它和密码找回一起记录在
+ <a
+ href="/zh/password#disable-two-factor"
+ className="text-blue-400 hover:text-blue-600"
+ >
+ 密码页面
+ </a>
+ 上。
+ </p>
+
<h2 id="security-and-reliability-engineering">
🛡️ 安全与可靠性工程
</h2>