fix:"隔离验证码投递并统一密码重置受理"
Repository verification / backend (push) Canceled after 0s
Repository verification / frontend (push) Canceled after 0s

This commit is contained in:
xpp committed 2026-10-22 08:49:04 +08:00
1 parent 02c21e5c19
commit ba5dbc195e
16 files changed
+639 -57

No files matched your search

@@ -26,6 +26,11 @@ public class CloudVerificationSender implements VerificationSender {
@Override
public void send(String channel,String account,String code) {
send(channel,account,code,VerificationPurpose.REGISTRATION);
}
@Override
public void send(String channel,String account,String code,VerificationPurpose purpose) {
if(!available(channel)) throw new ApiException("VERIFICATION_UNAVAILABLE","该验证码发送服务尚未配置,请联系管理员",503);
try {
if("email".equals(channel)) {
@@ -47,8 +52,8 @@ public class CloudVerificationSender implements VerificationSender {
SimpleMailMessage message=new SimpleMailMessage();
message.setFrom(value("MOYI_SMTP_FROM"));
message.setTo(account);
message.setSubject("MOYI 注册验证码");
message.setText("您的注册验证码为:"+code+",5 分钟内有效。请勿向他人泄露。若非本人操作,请忽略此邮件。");
message.setSubject("MOYI "+purpose.label+"验证码");
message.setText("您的"+purpose.label+"验证码为:"+code+",5 分钟内有效。请勿向他人泄露。若非本人操作,请忽略此邮件。");
mail.send(message);
} else {
Config config=new Config().setAccessKeyId(value("MOYI_SMS_ACCESS_KEY_ID")).setAccessKeySecret(value("MOYI_SMS_ACCESS_KEY_SECRET")).setEndpoint("dysmsapi.aliyuncs.com").setProtocol("https");
@@ -57,8 +62,7 @@ public class CloudVerificationSender implements VerificationSender {
.setSignName(value("MOYI_SMS_SIGN_NAME")).setTemplateCode(value("MOYI_SMS_TEMPLATE_CODE")).setTemplateParam("{\"code\":\""+code+"\"}");
var response=client.sendSmsWithOptions(request,new RuntimeOptions().setAutoretry(false).setConnectTimeout(5000).setReadTimeout(10000));
if(response.getBody()==null || !"OK".equals(response.getBody().getCode())) {
String resultCode = response.getBody() == null ? "EMPTY_RESPONSE" : String.valueOf(response.getBody().getCode());
log.warn("Aliyun SMS verification rejected: resultCode={}", resultCode);
log.warn("Aliyun SMS verification rejected");
throw new IllegalStateException("SMS rejected");
}
}
@@ -0,0 +1,134 @@
package com.moyi.controlplane.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.moyi.controlplane.common.ApiException;
import com.moyi.controlplane.security.SecretCipher;
import jakarta.annotation.PreDestroy;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
/** Durable, encrypted single-attempt delivery. Never hold a DB transaction over a mail/SMS call. */
@Service
public class VerificationDispatchService {
private static final Logger log = LoggerFactory.getLogger(VerificationDispatchService.class);
private final JdbcTemplate jdbc;
private final VerificationSender sender;
private final SecretCipher cipher;
private final ObjectMapper json;
private final TransactionTemplate transactions;
private final ExecutorService workers = new ThreadPoolExecutor(0, 2, 30, TimeUnit.SECONDS, new SynchronousQueue<>(),
task -> { var thread=new Thread(task, "verification-delivery"); thread.setDaemon(true); return thread; },
new ThreadPoolExecutor.AbortPolicy());
public VerificationDispatchService(JdbcTemplate jdbc, VerificationSender sender, SecretCipher cipher,
ObjectMapper json, PlatformTransactionManager manager) {
this.jdbc=jdbc; this.sender=sender; this.cipher=cipher; this.json=json;
transactions=new TransactionTemplate(manager);
transactions.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
}
public boolean available(String channel) { return cipher.isConfigured() && sender.available(channel); }
/** Called only after common quotas; code generation and queue insert commit or roll back together. */
@Transactional(propagation=Propagation.MANDATORY)
public void enqueue(VerificationPurpose purpose, String account, String code, String codeHash) {
UUID id=UUID.randomUUID();
String payload;
try { payload=cipher.encrypt(json.writeValueAsString(Map.of("id",id.toString(),"purpose",purpose.key,"account",account,"code",code))); }
catch (ApiException error) { throw error; }
catch (Exception error) { throw new ApiException("VERIFICATION_QUEUE_FAILED", "验证码服务暂时不可用", 503); }
jdbc.update("INSERT INTO "+purpose.table+"(account,code_hash,expires_at,delivery_id) VALUES (?,?,clock_timestamp()+interval '5 minutes',?) ON CONFLICT(account) DO UPDATE SET code_hash=excluded.code_hash,expires_at=excluded.expires_at,attempts=0,consumed=false,created_at=clock_timestamp(),delivery_id=excluded.delivery_id", account,codeHash,id);
jdbc.update("INSERT INTO verification_delivery_outbox(id,purpose,payload_ciphertext) VALUES (?,?,?)",id,purpose.key,payload);
}
@Scheduled(fixedDelayString="${moyi.auth.verification-dispatch-interval-ms:1000}")
public void dispatchPending() {
// No queue behind these two workers: a slow provider cannot consume unbounded threads/tasks.
for (int i=0;i<2;i++) {
try { workers.submit(() -> {
try { dispatchOne(); }
catch (RuntimeException error) { log.warn("Verification delivery persistence failed; no automatic replay"); }
}); } catch (RejectedExecutionException busyOrStopping) { break; }
}
}
private record Attempt(UUID id, VerificationPurpose purpose, String ciphertext) {
@Override public String toString() { return "VerificationAttempt[id="+id+"]"; }
}
/** Package-visible for isolated deterministic database tests; not an HTTP operation. */
boolean dispatchOne() {
Attempt attempt=transactions.execute(status -> {
var rows=jdbc.queryForList("SELECT id,purpose,payload_ciphertext FROM verification_delivery_outbox WHERE status='queued' AND expires_at>clock_timestamp() ORDER BY created_at,id LIMIT 1 FOR UPDATE SKIP LOCKED");
if (rows.isEmpty()) return null;
var row=rows.getFirst(); UUID id=(UUID)row.get("id");
jdbc.update("UPDATE verification_delivery_outbox SET status='sending',started_at=clock_timestamp() WHERE id=?",id);
return new Attempt(id,VerificationPurpose.fromKey(String.valueOf(row.get("purpose"))),String.valueOf(row.get("payload_ciphertext")));
});
if (attempt==null) { cleanupExpired(); return false; }
try {
var payload=json.readTree(cipher.decrypt(attempt.ciphertext()));
if (!attempt.id().toString().equals(payload.path("id").asText())
|| !attempt.purpose().key.equals(payload.path("purpose").asText())
|| !payload.path("code").asText().matches("[0-9]{6}")) throw new IllegalArgumentException("Invalid delivery envelope");
String account=payload.path("account").asText(), code=payload.path("code").asText();
if (!isCurrent(attempt,account)) { finish(attempt,"discarded","SUPERSEDED_OR_INACTIVE"); return true; }
if (Thread.currentThread().isInterrupted()) { finish(attempt,"failed","INTERRUPTED"); return true; }
String channel=account.contains("@")?"email":"phone";
// At this point the claim is committed and its connection is released.
sender.send(channel,account,code,attempt.purpose());
} catch (Exception error) {
// Do not attach/log exceptions: providers can echo recipients, OTPs or credentials.
finish(attempt,"failed","DELIVERY_FAILED");
return true;
}
// A storage failure here leaves 'sending'. Never re-send an ambiguously accepted message.
finish(attempt,"sent",null);
return true;
}
private boolean isCurrent(Attempt attempt, String account) {
String activeUser=attempt.purpose()==VerificationPurpose.PASSWORD_RESET
? " AND EXISTS(SELECT 1 FROM users WHERE account=c.account AND status='active')" : "";
return Boolean.TRUE.equals(jdbc.queryForObject("SELECT EXISTS(SELECT 1 FROM "+attempt.purpose().table+" c WHERE account=? AND delivery_id=? AND consumed=false AND attempts<5 AND expires_at>clock_timestamp()"+activeUser+")",Boolean.class,account,attempt.id()));
}
private void finish(Attempt attempt, String state, String failureCode) {
transactions.executeWithoutResult(status -> {
int changed=jdbc.update("UPDATE verification_delivery_outbox SET status=?,payload_ciphertext=NULL,finished_at=clock_timestamp(),failure_code=? WHERE id=? AND status='sending'",state,failureCode,attempt.id());
if (changed>0 && !"sent".equals(state)) {
jdbc.update("UPDATE "+attempt.purpose().table+" SET consumed=true WHERE delivery_id=?",attempt.id());
}
});
}
private void cleanupExpired() {
transactions.executeWithoutResult(status -> {
// 'sending' abandoned on restart is never retried. Erase the encrypted payload after expiry.
jdbc.update("UPDATE verification_delivery_outbox SET status='discarded',payload_ciphertext=NULL,finished_at=clock_timestamp(),failure_code='EXPIRED' WHERE id IN (SELECT id FROM verification_delivery_outbox WHERE status IN ('queued','sending') AND expires_at<=clock_timestamp() LIMIT 100 FOR UPDATE SKIP LOCKED)");
jdbc.update("DELETE FROM verification_delivery_outbox WHERE id IN (SELECT id FROM verification_delivery_outbox WHERE finished_at<clock_timestamp()-interval '2 days' LIMIT 100)");
for (var purpose : VerificationPurpose.values()) jdbc.update("DELETE FROM "+purpose.table+" WHERE account IN (SELECT account FROM "+purpose.table+" WHERE expires_at<clock_timestamp()-interval '1 day' LIMIT 100 FOR UPDATE SKIP LOCKED)");
});
}
@PreDestroy public void close() {
workers.shutdownNow();
try { workers.awaitTermination(3,TimeUnit.SECONDS); }
catch (InterruptedException error) { Thread.currentThread().interrupt(); }
}
}
@@ -0,0 +1,14 @@
package com.moyi.controlplane.auth;
/** Closed purpose set: SQL identifiers and message intent must never come from a request. */
public enum VerificationPurpose {
REGISTRATION("registration", "registration_codes", "注册"),
PASSWORD_RESET("password-reset", "password_reset_codes", "密码重置");
final String key, table, label;
VerificationPurpose(String key, String table, String label) { this.key=key; this.table=table; this.label=label; }
static VerificationPurpose fromKey(String key) {
for (var purpose : values()) if (purpose.key.equals(key)) return purpose;
throw new IllegalArgumentException("Invalid verification purpose");
}
}
@@ -3,4 +3,5 @@ package com.moyi.controlplane.auth;
public interface VerificationSender {
boolean available(String channel);
void send(String channel, String account, String code);
default void send(String channel, String account, String code, VerificationPurpose purpose) { send(channel,account,code); }
}
@@ -4,7 +4,6 @@ import com.moyi.controlplane.common.ApiException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.nio.charset.StandardCharsets;
import java.time.OffsetDateTime;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
@@ -16,13 +15,13 @@ import org.springframework.transaction.annotation.Transactional;
@Service
public class VerificationService {
private final JdbcTemplate jdbc;
private final VerificationSender sender;
private final VerificationDispatchService dispatch;
private final String pepper;
private final SecureRandom random=new SecureRandom();
public VerificationService(JdbcTemplate jdbc,VerificationSender sender,@Value("${moyi.auth.password-pepper}") String pepper) {
this.jdbc=jdbc; this.sender=sender; this.pepper=pepper;
public VerificationService(JdbcTemplate jdbc,VerificationDispatchService dispatch,@Value("${moyi.auth.password-pepper}") String pepper) {
this.jdbc=jdbc; this.dispatch=dispatch; this.pepper=pepper;
}
public Map<String,Boolean> capabilities() { return Map.of("email",sender.available("email"),"phone",sender.available("phone")); }
public Map<String,Boolean> capabilities() { return Map.of("email",dispatch.available("email"),"phone",dispatch.available("phone")); }
public String normalize(String raw) {
String account=raw==null?"":raw.trim().toLowerCase(Locale.ROOT);
if(!account.contains("@")) account=account.replaceAll("[\\s-]","");
@@ -33,29 +32,33 @@ public class VerificationService {
private String registrationDigest(String account,String code) { return digest("registration",account,code); }
private String resetDigest(String account,String code) { return digest("password-reset",account,code); }
@Transactional(noRollbackFor=ApiException.class)
@Transactional
public Map<String,Object> send(String raw,String invitation,String ip) {
String account=normalize(raw), channel=account.contains("@")?"email":"phone";
if(!sender.available(channel)) throw new ApiException("VERIFICATION_UNAVAILABLE","该验证码发送服务尚未配置,请联系管理员",503);
if(!dispatch.available(channel)) throw new ApiException("VERIFICATION_UNAVAILABLE","该验证码发送服务尚未配置,请联系管理员",503);
Integer invites=jdbc.queryForObject("SELECT count(*) FROM invitation_codes WHERE code_hash=? AND disabled_at IS NULL AND used_count<max_uses AND (expires_at IS NULL OR expires_at>now())",Integer.class,AuthService.hashSecret(invitation==null?"":invitation.trim()));
if(invites==null || invites==0) throw new ApiException("INVITATION_INVALID","请先填写有效邀请码",403);
String source=ip==null?"unknown":ip;
// One global lock bounds aggregate sending and serializes account/IP limits across replicas.
jdbc.queryForList("SELECT pg_advisory_xact_lock(734092615)");
Integer limited=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>now()-interval '60 seconds'",Integer.class,account);
Integer daily=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>now()-interval '24 hours'",Integer.class,account);
Integer hourly=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE ip_address=? AND created_at>now()-interval '1 hour'",Integer.class,source);
Integer total=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE created_at>now()-interval '24 hours'",Integer.class);
if(limited>0 || daily>=10 || hourly>=30 || total>=1000) throw new ApiException("VERIFICATION_RATE_LIMIT","发送过于频繁,请稍后重试",429);
admitSend(account,ip);
String code=String.format(Locale.ROOT,"%06d",random.nextInt(1000000));
jdbc.update("INSERT INTO verification_send_events(id,account,ip_address) VALUES (?,?,?)",UUID.randomUUID(),account,source);
jdbc.update("INSERT INTO registration_codes(account,code_hash,expires_at) VALUES (?,?,now()+interval '5 minutes') ON CONFLICT(account) DO UPDATE SET code_hash=excluded.code_hash, expires_at=excluded.expires_at, attempts=0, consumed=false, created_at=now()",account,registrationDigest(account,code));
try { sender.send(channel,account,code); }
catch(ApiException exception) { jdbc.update("UPDATE registration_codes SET consumed=true WHERE account=?",account); throw exception; }
jdbc.update("DELETE FROM verification_send_events WHERE created_at<now()-interval '2 days'");
return Map.of("sent",true,"retryAfterSeconds",60,"expiresInSeconds",300);
dispatch.enqueue(VerificationPurpose.REGISTRATION,account,code,registrationDigest(account,code));
return accepted();
}
private void admitSend(String account,String ip) {
String source=ip==null || ip.isBlank()?"unknown":ip;
// This lock covers only bounded DB work, NEVER the mail/SMS provider.
jdbc.queryForObject("SELECT set_config('lock_timeout','2s',true)",String.class);
jdbc.queryForList("SELECT pg_advisory_xact_lock(734092615)");
jdbc.update("DELETE FROM verification_send_events WHERE id IN (SELECT id FROM verification_send_events WHERE created_at<clock_timestamp()-interval '2 days' LIMIT 500)");
Integer limited=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>clock_timestamp()-interval '60 seconds'",Integer.class,account);
Integer daily=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>clock_timestamp()-interval '24 hours'",Integer.class,account);
Integer hourly=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE ip_address=? AND created_at>clock_timestamp()-interval '1 hour'",Integer.class,source);
Integer total=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE created_at>clock_timestamp()-interval '24 hours'",Integer.class);
if(limited>0 || daily>=10 || hourly>=30 || total>=1000) throw new ApiException("VERIFICATION_RATE_LIMIT","发送过于频繁,请稍后重试",429);
jdbc.update("INSERT INTO verification_send_events(id,account,ip_address,created_at) VALUES (?,?,?,clock_timestamp())",UUID.randomUUID(),account,source);
}
private Map<String,Object> accepted() { return Map.of("sent",true,"retryAfterSeconds",60,"expiresInSeconds",300); }
@Transactional(noRollbackFor=ApiException.class)
public void consume(String raw,String code) {
String account=normalize(raw);
@@ -69,39 +72,30 @@ public class VerificationService {
jdbc.update("UPDATE registration_codes SET consumed=true WHERE account=?",account);
}
@Transactional(noRollbackFor=ApiException.class)
@Transactional
public Map<String,Object> sendReset(String raw,String ip) {
String account=normalize(raw), channel=account.contains("@")?"email":"phone";
if(!sender.available(channel)) throw new ApiException("VERIFICATION_UNAVAILABLE","该验证码发送服务尚未配置,请联系管理员",503);
Integer exists=jdbc.queryForObject("SELECT count(*) FROM users WHERE account=? AND status='active'",Integer.class,account);
// Do not reveal whether an account exists. The client receives the same response either way.
if(exists==null || exists==0) return Map.of("sent",true,"retryAfterSeconds",60,"expiresInSeconds",300);
String source=ip==null?"unknown":ip;
jdbc.queryForList("SELECT pg_advisory_xact_lock(734092615)");
Integer limited=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>now()-interval '60 seconds'",Integer.class,account);
Integer daily=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>now()-interval '24 hours'",Integer.class,account);
Integer hourly=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE ip_address=? AND created_at>now()-interval '1 hour'",Integer.class,source);
Integer total=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE created_at>now()-interval '24 hours'",Integer.class);
if(limited>0 || daily>=10 || hourly>=30 || total>=1000) throw new ApiException("VERIFICATION_RATE_LIMIT","发送过于频繁,请稍后重试",429);
if(!dispatch.available(channel)) throw new ApiException("VERIFICATION_UNAVAILABLE","该验证码发送服务尚未配置,请联系管理员",503);
// Exact same request-side DB/crypto path for active, unknown and disabled accounts.
// Existence is checked ONLY in the worker; no network result reaches this receipt.
admitSend(account,ip);
String code=String.format(Locale.ROOT,"%06d",random.nextInt(1000000));
jdbc.update("INSERT INTO verification_send_events(id,account,ip_address) VALUES (?,?,?)",UUID.randomUUID(),account,source);
jdbc.update("INSERT INTO password_reset_codes(account,code_hash,expires_at) VALUES (?,?,now()+interval '5 minutes') ON CONFLICT(account) DO UPDATE SET code_hash=excluded.code_hash, expires_at=excluded.expires_at, attempts=0, consumed=false, created_at=now()",account,resetDigest(account,code));
try { sender.send(channel,account,code); }
catch(ApiException exception) { jdbc.update("UPDATE password_reset_codes SET consumed=true WHERE account=?",account); throw exception; }
return Map.of("sent",true,"retryAfterSeconds",60,"expiresInSeconds",300);
dispatch.enqueue(VerificationPurpose.PASSWORD_RESET,account,code,resetDigest(account,code));
return accepted();
}
@Transactional(noRollbackFor=ApiException.class)
public String consumeReset(String raw,String code) {
String account=normalize(raw);
var rows=jdbc.queryForList("SELECT * FROM password_reset_codes WHERE account=? FOR UPDATE",account);
if(rows.isEmpty()) throw new ApiException("VERIFICATION_INVALID","请先获取验证码");
if(rows.isEmpty()) throw invalidResetCode();
var row=rows.getFirst();
java.time.Instant expiry=((java.sql.Timestamp)row.get("expires_at")).toInstant();
if(Boolean.TRUE.equals(row.get("consumed")) || expiry.isBefore(java.time.Instant.now()) || ((Number)row.get("attempts")).intValue()>=5) throw new ApiException("VERIFICATION_EXPIRED","验证码已失效,请重新获取");
if(Boolean.TRUE.equals(row.get("consumed")) || !expiry.isAfter(java.time.Instant.now()) || ((Number)row.get("attempts")).intValue()>=5) throw invalidResetCode();
jdbc.update("UPDATE password_reset_codes SET attempts=attempts+1 WHERE account=?",account);
if(code==null || !code.matches("[0-9]{6}") || !MessageDigest.isEqual(String.valueOf(row.get("code_hash")).getBytes(StandardCharsets.UTF_8),resetDigest(account,code).getBytes(StandardCharsets.UTF_8))) throw new ApiException("VERIFICATION_INVALID","验证码错误");
if(code==null || !code.matches("[0-9]{6}") || !MessageDigest.isEqual(String.valueOf(row.get("code_hash")).getBytes(StandardCharsets.UTF_8),resetDigest(account,code).getBytes(StandardCharsets.UTF_8))) throw invalidResetCode();
jdbc.update("UPDATE password_reset_codes SET consumed=true WHERE account=?",account);
return account;
}
private ApiException invalidResetCode() { return new ApiException("VERIFICATION_INVALID","验证码无效或已失效,请重新获取"); }
}
@@ -40,6 +40,9 @@ public class SecretCipher {
}
}
/** Readiness only; never expose key material. */
public boolean isConfigured() { return key != null; }
public String decrypt(String encoded) {
if (key == null) throw new ApiException("CREDENTIAL_ENCRYPTION_NOT_CONFIGURED", "请先配置供应商凭证加密密钥", 500);
try {
@@ -0,0 +1,21 @@
-- One immutable generation per delivery. No plaintext recipient or OTP is stored in this queue.
ALTER TABLE registration_codes ADD COLUMN delivery_id uuid;
ALTER TABLE password_reset_codes ADD COLUMN delivery_id uuid;
CREATE INDEX registration_codes_expiry_idx ON registration_codes(expires_at);
CREATE TABLE verification_delivery_outbox (
id uuid PRIMARY KEY,
purpose varchar(24) NOT NULL CHECK (purpose IN ('registration','password-reset')),
payload_ciphertext text,
status varchar(16) NOT NULL DEFAULT 'queued' CHECK (status IN ('queued','sending','sent','failed','discarded')),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
expires_at timestamptz NOT NULL DEFAULT clock_timestamp()+interval '5 minutes',
started_at timestamptz,
finished_at timestamptz,
failure_code varchar(32),
CHECK ((status IN ('queued','sending') AND payload_ciphertext IS NOT NULL)
OR (status IN ('sent','failed','discarded') AND payload_ciphertext IS NULL))
);
CREATE INDEX verification_delivery_queue_idx ON verification_delivery_outbox(created_at,id) WHERE status='queued';
CREATE INDEX verification_delivery_expiry_idx ON verification_delivery_outbox(expires_at) WHERE status IN ('queued','sending');
CREATE INDEX verification_delivery_finished_idx ON verification_delivery_outbox(finished_at) WHERE status IN ('sent','failed','discarded');
@@ -54,6 +54,7 @@ class PlatformAdminPostgresTest {
private CatalogService catalog;
private WalletService wallet;
private VerificationService verification;
private VerificationDispatchService dispatch;
private TestSender sender;
@BeforeEach void setup() throws Exception {
@@ -87,12 +88,14 @@ class PlatformAdminPostgresTest {
context.registerBean(WalletService.class, () -> new WalletService(jdbc, context.getBean(AuthService.class)));
context.registerBean(UsageAuditService.class, () -> new UsageAuditService(jdbc,json));
context.registerBean(ChatBillingService.class, () -> new ChatBillingService(jdbc,json,context.getBean(UsageAuditService.class)));
context.registerBean(VerificationService.class, () -> new VerificationService(jdbc, sender, "test-pepper"));
context.registerBean(VerificationDispatchService.class, () -> new VerificationDispatchService(jdbc,sender,new SecretCipher("test-delivery-encryption"),json,context.getBean(DataSourceTransactionManager.class)));
context.registerBean(VerificationService.class, () -> new VerificationService(jdbc, context.getBean(VerificationDispatchService.class), "test-pepper"));
context.refresh();
auth = context.getBean(AuthService.class);
catalog = context.getBean(CatalogService.class);
wallet = context.getBean(WalletService.class);
verification = context.getBean(VerificationService.class);
dispatch = context.getBean(VerificationDispatchService.class);
auth.ensureAdmin("test_owner", "local-password", "Test Owner");
ownerToken = auth.login("test_owner", "local-password", meta).token();
memberId = auth.createUser(ownerToken, "test_member", "local-password", "Test Member", meta).id();
@@ -335,6 +338,7 @@ class PlatformAdminPostgresTest {
http.perform(post("/api/auth/register").contentType("application/json").content(json.writeValueAsBytes(input))).andExpect(status().isBadRequest());
http.perform(post("/api/auth/verification").contentType("application/json").content(json.writeValueAsBytes(input)))
.andExpect(status().isOk()).andExpect(jsonPath("$.code").doesNotExist()).andExpect(jsonPath("$.sent").value(true));
assertTrue(VerificationDeliveryFixture.deliverOne(dispatch));
String code = sender.codes.get(account);
assertNotEquals(code,jdbc.queryForObject("SELECT code_hash FROM registration_codes WHERE account=?",String.class,account));
input.put("verificationCode",code);
@@ -350,16 +354,19 @@ class PlatformAdminPostgresTest {
assertThrows(ApiException.class, () -> verification.send(account,"bad-invite","127.0.0.1"));
verification.send(account,invite,"127.0.0.1");
assertThrows(ApiException.class, () -> verification.send(account,invite,"127.0.0.1"));
assertTrue(VerificationDeliveryFixture.deliverOne(dispatch));
String correct=sender.codes.get(account);
String wrong=correct.equals("000000")?"111111":"000000";
for(int i=0;i<5;i++) assertThrows(ApiException.class, () -> verification.consume(account,wrong));
assertEquals(5,jdbc.queryForObject("SELECT attempts FROM registration_codes WHERE account=?",Integer.class,account));
assertThrows(ApiException.class, () -> verification.consume(account,correct));
verification.send("expired@example.test",invite,"127.0.0.1");
assertTrue(VerificationDeliveryFixture.deliverOne(dispatch));
jdbc.update("UPDATE registration_codes SET expires_at=now()-interval '1 second' WHERE account='expired@example.test'");
assertThrows(ApiException.class, () -> verification.consume("expired@example.test",sender.codes.get("expired@example.test")));
sender.fail=true;
assertThrows(ApiException.class, () -> verification.send("failed@example.test",invite,"127.0.0.1"));
assertEquals(true,verification.send("failed@example.test",invite,"127.0.0.1").get("sent"));
assertTrue(VerificationDeliveryFixture.deliverOne(dispatch));
assertTrue(jdbc.queryForObject("SELECT consumed FROM registration_codes WHERE account='failed@example.test'",Boolean.class));
assertEquals(1,jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account='failed@example.test'",Integer.class));
sender.enabled=false;
@@ -0,0 +1,7 @@
package com.moyi.controlplane.auth;
/** Deterministic test-only access; no public production dispatch endpoint. */
public final class VerificationDeliveryFixture {
private VerificationDeliveryFixture() {}
public static boolean deliverOne(VerificationDispatchService dispatch) { return dispatch.dispatchOne(); }
}
@@ -0,0 +1,343 @@
package com.moyi.controlplane.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.moyi.controlplane.common.ApiException;
import com.moyi.controlplane.common.ApiExceptionHandler;
import com.moyi.controlplane.security.SecretCipher;
import java.util.ArrayList;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.sql.DataSource;
import org.flywaydb.core.Flyway;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.IllegalTransactionStateException;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.transaction.support.TransactionTemplate;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@EnabledIfEnvironmentVariable(named="MOYI_AUTH_TEST_JDBC_URL",matches="jdbc:postgresql://127[.]0[.]0[.]1:[0-9]+/.+")
class VerificationDispatchPostgresTest {
@Configuration @EnableTransactionManagement(proxyTargetClass=true) static class Transactions {}
private static final String ACTIVE="active@example.test", UNKNOWN="unknown@example.test", DISABLED="disabled@example.test";
private final ObjectMapper json=new ObjectMapper().findAndRegisterModules();
private final SecretCipher cipher=new SecretCipher("isolated-delivery-encryption");
private DriverManagerDataSource base;
private String schema, invitation;
private JdbcTemplate jdbc;
private AnnotationConfigApplicationContext context;
private VerificationDispatchService dispatch;
private VerificationService verification;
private MockMvc http;
private final TestSender sender=new TestSender();
static class TestSender implements VerificationSender {
final Map<String,String> codes=new ConcurrentHashMap<>();
final AtomicInteger calls=new AtomicInteger();
volatile boolean available=true, fail=false;
volatile CountDownLatch arrived, release;
volatile VerificationPurpose lastPurpose;
public boolean available(String channel) { return available; }
public void send(String channel,String account,String code) { send(channel,account,code,VerificationPurpose.REGISTRATION); }
public void send(String channel,String account,String code,VerificationPurpose purpose) {
assertFalse(TransactionSynchronizationManager.isActualTransactionActive(),"Network delivery must not hold a DB transaction");
calls.incrementAndGet(); lastPurpose=purpose;
if (arrived!=null) arrived.countDown();
if (release!=null) try { assertTrue(release.await(10,TimeUnit.SECONDS)); }
catch (InterruptedException error) { Thread.currentThread().interrupt(); throw new IllegalStateException("Interrupted fixture"); }
if (fail) throw new ApiException("VERIFICATION_SEND_FAILED","Synthetic provider detail must stay private",502);
codes.put(account,code);
}
}
@BeforeEach void setup() {
String url=System.getenv("MOYI_AUTH_TEST_JDBC_URL");
schema="verification_dispatch_"+UUID.randomUUID().toString().replace("-","");
base=new DriverManagerDataSource(url,"moyi_role_test","");
var source=new DriverManagerDataSource(url+"?currentSchema="+schema,"moyi_role_test","");
Flyway.configure().dataSource(base).schemas(schema).defaultSchema(schema).load().migrate();
jdbc=new JdbcTemplate(source); UUID creator=UUID.randomUUID(); invitation="synthetic-invite-"+UUID.randomUUID();
jdbc.update("INSERT INTO users(id,account,account_kind,password_hash,display_name,status) VALUES (?,?,'email','not-a-login-hash','Synthetic','active'),(?,?,'email','not-a-login-hash','Synthetic','disabled')",creator,ACTIVE,UUID.randomUUID(),DISABLED);
jdbc.update("INSERT INTO invitation_codes(id,code_hash,code_prefix,label,max_uses,created_by) VALUES (?,?,?,'Synthetic',100,?)",UUID.randomUUID(),AuthService.hashSecret(invitation),"synthetic",creator);
context=new AnnotationConfigApplicationContext(); context.register(Transactions.class);
context.registerBean(DataSource.class,()->source);
context.registerBean(DataSourceTransactionManager.class,()->new DataSourceTransactionManager(source));
context.registerBean(VerificationDispatchService.class,()->new VerificationDispatchService(jdbc,sender,cipher,json,context.getBean(DataSourceTransactionManager.class)));
context.registerBean(VerificationService.class,()->new VerificationService(jdbc,context.getBean(VerificationDispatchService.class),"isolated-pepper"));
context.refresh(); dispatch=context.getBean(VerificationDispatchService.class); verification=context.getBean(VerificationService.class);
http=MockMvcBuilders.standaloneSetup(new AuthController(mock(AuthService.class),verification,mock(VerifiedAccountService.class),168,true))
.setControllerAdvice(new ApiExceptionHandler()).build();
}
@AfterEach void cleanup() {
if (sender.release!=null) sender.release.countDown();
if (context!=null) context.close();
if (base!=null && schema!=null) new JdbcTemplate(base).execute("DROP SCHEMA "+schema+" CASCADE");
}
private UUID delivery(String account,VerificationPurpose purpose) {
return jdbc.queryForObject("SELECT delivery_id FROM "+purpose.table+" WHERE account=?",UUID.class,account);
}
private void releaseQuota(String account) { jdbc.update("UPDATE verification_send_events SET created_at=clock_timestamp()-interval '61 seconds' WHERE account=?",account); }
private void assertTerminal(UUID id,String state) {
var row=jdbc.queryForMap("SELECT status,payload_ciphertext,finished_at FROM verification_delivery_outbox WHERE id=?",id);
assertEquals(state,row.get("status")); assertNull(row.get("payload_ciphertext")); assertNotNull(row.get("finished_at"));
}
@Test void resetRequestsHaveIdenticalReceiptsAndNoRequestSideDeliveryForAllAccountStates() throws Exception {
String reference=null;
for (String account : java.util.List.of(ACTIVE,UNKNOWN,DISABLED)) {
var response=http.perform(post("/api/auth/password-reset/code").contentType("application/json").content(json.writeValueAsBytes(Map.of("account",account))))
.andExpect(status().isOk()).andExpect(jsonPath("$.sent").value(true)).andExpect(jsonPath("$.code").doesNotExist())
.andExpect(jsonPath("$.token").doesNotExist()).andExpect(cookie().doesNotExist("moyi_session")).andReturn().getResponse().getContentAsString();
if (reference==null) reference=response; else assertEquals(json.readTree(reference),json.readTree(response));
}
assertEquals(0,sender.calls.get());
assertEquals(3,jdbc.queryForObject("SELECT count(*) FROM verification_send_events",Integer.class));
assertEquals(3,jdbc.queryForObject("SELECT count(*) FROM verification_delivery_outbox WHERE status='queued'",Integer.class));
assertEquals(3,jdbc.queryForObject("SELECT count(*) FROM password_reset_codes",Integer.class));
}
@Test void knownAndUnknownRepeatedRequestsExposeTheSameLimit() throws Exception {
for (String account : java.util.List.of(ACTIVE,UNKNOWN,DISABLED)) {
verification.sendReset(account,"127.0.0.1");
http.perform(post("/api/auth/password-reset/code").contentType("application/json").content(json.writeValueAsBytes(Map.of("account",account))))
.andExpect(status().isTooManyRequests()).andExpect(jsonPath("$.error.code").value("VERIFICATION_RATE_LIMIT"));
}
assertEquals(3,jdbc.queryForObject("SELECT count(*) FROM verification_send_events",Integer.class));
}
@Test void workerDeliversOnlyToActiveUsersAndPurgesAllFinishedPayloads() {
for (String account : java.util.List.of(ACTIVE,UNKNOWN,DISABLED)) verification.sendReset(account,"127.0.0.1");
for (int i=0;i<3;i++) assertTrue(dispatch.dispatchOne());
assertEquals(1,sender.calls.get()); assertEquals(VerificationPurpose.PASSWORD_RESET,sender.lastPurpose);
assertTrue(sender.codes.containsKey(ACTIVE)); assertFalse(sender.codes.containsKey(UNKNOWN)); assertFalse(sender.codes.containsKey(DISABLED));
assertTerminal(delivery(ACTIVE,VerificationPurpose.PASSWORD_RESET),"sent");
assertTerminal(delivery(UNKNOWN,VerificationPurpose.PASSWORD_RESET),"discarded");
assertTerminal(delivery(DISABLED,VerificationPurpose.PASSWORD_RESET),"discarded");
}
@Test void payloadContainsNoPlaintextAccountOrOtpAndIsBoundToItsGeneration() throws Exception {
verification.sendReset(ACTIVE,"127.0.0.1"); UUID id=delivery(ACTIVE,VerificationPurpose.PASSWORD_RESET);
String stored=jdbc.queryForObject("SELECT payload_ciphertext FROM verification_delivery_outbox WHERE id=?",String.class,id);
var decoded=json.readTree(cipher.decrypt(stored));
assertTrue(stored.startsWith("v1$")); assertFalse(stored.contains(ACTIVE)); assertFalse(stored.contains("account"));
assertEquals(id.toString(),decoded.path("id").asText()); assertEquals("password-reset",decoded.path("purpose").asText());
assertTrue(decoded.path("code").asText().matches("[0-9]{6}"));
assertNotEquals(decoded.path("code").asText(),jdbc.queryForObject("SELECT code_hash FROM password_reset_codes WHERE account=?",String.class,ACTIVE));
}
@Test void providerFailureStaysOutOfTheReceiptAndIsNotRetried() {
sender.fail=true;
assertEquals(true,verification.sendReset(ACTIVE,"127.0.0.1").get("sent"));
UUID id=delivery(ACTIVE,VerificationPurpose.PASSWORD_RESET); assertTrue(dispatch.dispatchOne());
assertTerminal(id,"failed"); assertEquals(1,sender.calls.get()); assertFalse(dispatch.dispatchOne()); assertEquals(1,sender.calls.get());
assertTrue(jdbc.queryForObject("SELECT consumed FROM password_reset_codes WHERE delivery_id=?",Boolean.class,id));
assertEquals("DELIVERY_FAILED",jdbc.queryForObject("SELECT failure_code FROM verification_delivery_outbox WHERE id=?",String.class,id));
assertEquals(1,jdbc.queryForObject("SELECT count(*) FROM verification_send_events",Integer.class));
}
@Test void sendingDoesNotHoldTheGlobalQuotaLockOrADatabaseTransaction() throws Exception {
verification.sendReset(ACTIVE,"127.0.0.1");
sender.arrived=new CountDownLatch(1); sender.release=new CountDownLatch(1);
try (var executor=Executors.newFixedThreadPool(2)) {
var worker=executor.submit(dispatch::dispatchOne); assertTrue(sender.arrived.await(3,TimeUnit.SECONDS));
var request=executor.submit(()->verification.sendReset(UNKNOWN,"127.0.0.2"));
assertEquals(true,request.get(3,TimeUnit.SECONDS).get("sent"));
assertEquals("sending",jdbc.queryForObject("SELECT status FROM verification_delivery_outbox WHERE id=?",String.class,delivery(ACTIVE,VerificationPurpose.PASSWORD_RESET)));
sender.release.countDown(); assertTrue(worker.get(3,TimeUnit.SECONDS));
}
}
@Test void supersededQueueEntriesCannotDeliverOldCodesOrInvalidateNewOnes() {
verification.sendReset(ACTIVE,"127.0.0.1"); UUID old=delivery(ACTIVE,VerificationPurpose.PASSWORD_RESET);
releaseQuota(ACTIVE); verification.sendReset(ACTIVE,"127.0.0.1"); UUID current=delivery(ACTIVE,VerificationPurpose.PASSWORD_RESET);
assertNotEquals(old,current); assertTrue(dispatch.dispatchOne()); assertTerminal(old,"discarded"); assertEquals(0,sender.calls.get());
assertFalse(jdbc.queryForObject("SELECT consumed FROM password_reset_codes WHERE delivery_id=?",Boolean.class,current));
assertTrue(dispatch.dispatchOne()); assertTerminal(current,"sent"); assertEquals(1,sender.calls.get());
assertEquals(ACTIVE,verification.consumeReset(ACTIVE,sender.codes.get(ACTIVE)));
}
@Test void oldInFlightFailureDoesNotConsumeTheReplacementCode() throws Exception {
verification.sendReset(ACTIVE,"127.0.0.1"); UUID old=delivery(ACTIVE,VerificationPurpose.PASSWORD_RESET);
sender.fail=true; sender.arrived=new CountDownLatch(1); sender.release=new CountDownLatch(1);
try (var executor=Executors.newSingleThreadExecutor()) {
var worker=executor.submit(dispatch::dispatchOne); assertTrue(sender.arrived.await(3,TimeUnit.SECONDS));
releaseQuota(ACTIVE); verification.sendReset(ACTIVE,"127.0.0.2"); UUID replacement=delivery(ACTIVE,VerificationPurpose.PASSWORD_RESET);
sender.release.countDown(); assertTrue(worker.get(3,TimeUnit.SECONDS)); assertTerminal(old,"failed");
assertFalse(jdbc.queryForObject("SELECT consumed FROM password_reset_codes WHERE delivery_id=?",Boolean.class,replacement));
sender.fail=false; sender.arrived=null; sender.release=null; assertTrue(dispatch.dispatchOne()); assertTerminal(replacement,"sent");
}
}
@Test void expiredAndAmbiguousSendingRowsAreErasedWithoutAutomaticReplay() {
verification.sendReset(ACTIVE,"127.0.0.1"); UUID id=delivery(ACTIVE,VerificationPurpose.PASSWORD_RESET);
jdbc.update("UPDATE verification_delivery_outbox SET status='sending',started_at=clock_timestamp() WHERE id=?",id);
assertFalse(dispatch.dispatchOne()); assertEquals(0,sender.calls.get());
jdbc.update("UPDATE verification_delivery_outbox SET expires_at=clock_timestamp()-interval '1 second' WHERE id=?",id);
assertFalse(dispatch.dispatchOne()); assertTerminal(id,"discarded"); assertEquals(0,sender.calls.get());
jdbc.update("UPDATE verification_delivery_outbox SET finished_at=clock_timestamp()-interval '3 days' WHERE id=?",id);
assertFalse(dispatch.dispatchOne()); assertEquals(0,jdbc.queryForObject("SELECT count(*) FROM verification_delivery_outbox",Integer.class));
}
@Test void disabledAfterEnqueueAndAlreadyConsumedCodesAreNotSent() {
verification.sendReset(ACTIVE,"127.0.0.1"); UUID id=delivery(ACTIVE,VerificationPurpose.PASSWORD_RESET);
jdbc.update("UPDATE users SET status='disabled' WHERE account=?",ACTIVE); assertTrue(dispatch.dispatchOne()); assertTerminal(id,"discarded");
jdbc.update("UPDATE users SET status='active' WHERE account=?",ACTIVE); releaseQuota(ACTIVE); verification.sendReset(ACTIVE,"127.0.0.1");
id=delivery(ACTIVE,VerificationPurpose.PASSWORD_RESET); jdbc.update("UPDATE password_reset_codes SET consumed=true WHERE delivery_id=?",id);
assertTrue(dispatch.dispatchOne()); assertTerminal(id,"discarded"); assertEquals(0,sender.calls.get());
}
@Test void missingEncryptionOrDisabledSenderIsAccountIndependentAndCreatesNoWork() {
var missingKey=new VerificationDispatchService(jdbc,sender,new SecretCipher(""),json,context.getBean(DataSourceTransactionManager.class));
try { assertFalse(missingKey.available("email")); assertFalse(missingKey.available("phone")); } finally { missingKey.close(); }
sender.available=false;
for (String account : java.util.List.of(ACTIVE,UNKNOWN,DISABLED)) {
assertEquals("VERIFICATION_UNAVAILABLE",assertThrows(ApiException.class,()->verification.sendReset(account,"127.0.0.1")).getCode());
}
assertEquals(0,jdbc.queryForObject("SELECT count(*) FROM verification_delivery_outbox",Integer.class));
assertEquals(0,jdbc.queryForObject("SELECT count(*) FROM verification_send_events",Integer.class));
}
@Test void queueFailureRollsBackTheCodeAndQuotaRecordTogether() {
jdbc.execute("ALTER TABLE verification_delivery_outbox ADD CONSTRAINT injected_failure CHECK (purpose <> 'password-reset') NOT VALID");
assertThrows(DataIntegrityViolationException.class,()->verification.sendReset(ACTIVE,"127.0.0.1"));
for (String table : java.util.List.of("verification_delivery_outbox","verification_send_events","password_reset_codes")) {
assertEquals(0,jdbc.queryForObject("SELECT count(*) FROM "+table,Integer.class));
}
jdbc.execute("ALTER TABLE verification_delivery_outbox DROP CONSTRAINT injected_failure");
assertEquals(true,verification.sendReset(ACTIVE,"127.0.0.1").get("sent"));
}
@Test void concurrentRequestsAcrossConnectionsCannotDuplicateTheSameAccountAdmission() throws Exception {
var start=new CountDownLatch(1); var results=new ArrayList<String>();
try (var executor=Executors.newFixedThreadPool(2)) {
var requests=new ArrayList<java.util.concurrent.Future<String>>();
for (int i=0;i<2;i++) requests.add(executor.submit(()->{
assertTrue(start.await(3,TimeUnit.SECONDS));
try { verification.sendReset(UNKNOWN,"127.0.0.1"); return "accepted"; } catch (ApiException error) { return error.getCode(); }
}));
start.countDown(); for (var request : requests) results.add(request.get(5,TimeUnit.SECONDS));
}
assertEquals(1,results.stream().filter("accepted"::equals).count()); assertEquals(1,results.stream().filter("VERIFICATION_RATE_LIMIT"::equals).count());
assertEquals(1,jdbc.queryForObject("SELECT count(*) FROM verification_delivery_outbox",Integer.class));
}
@Test void concurrentWorkerClaimsSendAGenerationAtMostOnce() throws Exception {
verification.sendReset(ACTIVE,"127.0.0.1"); var start=new CountDownLatch(1);
try (var executor=Executors.newFixedThreadPool(2)) {
var first=executor.submit(()->{start.await(); return dispatch.dispatchOne();});
var second=executor.submit(()->{start.await(); return dispatch.dispatchOne();}); start.countDown();
assertNotEquals(first.get(5,TimeUnit.SECONDS),second.get(5,TimeUnit.SECONDS));
}
assertEquals(1,sender.calls.get()); assertTerminal(delivery(ACTIVE,VerificationPurpose.PASSWORD_RESET),"sent");
}
@Test void accountDailySourceHourlyAndGlobalBudgetsIncludeUnknownAccounts() {
for (int i=0;i<10;i++) {
verification.sendReset(UNKNOWN,"127.0.0.1"); releaseQuota(UNKNOWN);
}
assertEquals("VERIFICATION_RATE_LIMIT",assertThrows(ApiException.class,()->verification.sendReset(UNKNOWN,"127.0.0.2")).getCode());
jdbc.update("DELETE FROM verification_send_events");
jdbc.execute("INSERT INTO verification_send_events(id,account,ip_address) SELECT md5('source-'||g)::uuid,'synthetic-'||g||'@example.test','127.0.0.9' FROM generate_series(1,30) g");
assertEquals("VERIFICATION_RATE_LIMIT",assertThrows(ApiException.class,()->verification.sendReset(ACTIVE,"127.0.0.9")).getCode());
assertEquals("VERIFICATION_RATE_LIMIT",assertThrows(ApiException.class,()->verification.sendReset("other@example.test","127.0.0.9")).getCode());
jdbc.update("DELETE FROM verification_send_events");
jdbc.execute("INSERT INTO verification_send_events(id,account,ip_address) SELECT md5('global-'||g)::uuid,'synthetic-'||g||'@example.test','192.0.2.1' FROM generate_series(1,1000) g");
assertEquals("VERIFICATION_RATE_LIMIT",assertThrows(ApiException.class,()->verification.sendReset(ACTIVE,"127.0.0.1")).getCode());
assertEquals("VERIFICATION_RATE_LIMIT",assertThrows(ApiException.class,()->verification.sendReset("another@example.test","127.0.0.2")).getCode());
}
@Test void crossPurposeQuotaIsSharedWhileCodesRemainPurposeBound() {
verification.send(UNKNOWN,invitation,"127.0.0.1");
assertEquals("VERIFICATION_RATE_LIMIT",assertThrows(ApiException.class,()->verification.sendReset(UNKNOWN,"127.0.0.1")).getCode());
assertTrue(dispatch.dispatchOne()); String code=sender.codes.get(UNKNOWN);
assertEquals(VerificationPurpose.REGISTRATION,sender.lastPurpose); verification.consume(UNKNOWN,code);
assertEquals("VERIFICATION_INVALID",assertThrows(ApiException.class,()->verification.consumeReset(UNKNOWN,code)).getCode());
}
@Test void allInvalidResetCodeStatesHaveTheSamePublicError() {
String expected=assertThrows(ApiException.class,()->verification.consumeReset(UNKNOWN,"000000")).getMessage();
verification.sendReset(ACTIVE,"127.0.0.1"); assertTrue(dispatch.dispatchOne());
String correct=sender.codes.get(ACTIVE), wrong="000000".equals(correct)?"111111":"000000";
assertEquals(expected,assertThrows(ApiException.class,()->verification.consumeReset(ACTIVE,wrong)).getMessage());
jdbc.update("UPDATE password_reset_codes SET attempts=5 WHERE account=?",ACTIVE);
assertEquals(expected,assertThrows(ApiException.class,()->verification.consumeReset(ACTIVE,correct)).getMessage());
jdbc.update("UPDATE password_reset_codes SET attempts=0,expires_at=clock_timestamp()-interval '1 second' WHERE account=?",ACTIVE);
assertEquals(expected,assertThrows(ApiException.class,()->verification.consumeReset(ACTIVE,correct)).getMessage());
}
@Test void ciphertextTamperingAndEnvelopeSwappingNeverReachTheSender() {
verification.sendReset(ACTIVE,"127.0.0.1"); UUID first=delivery(ACTIVE,VerificationPurpose.PASSWORD_RESET);
jdbc.update("UPDATE verification_delivery_outbox SET payload_ciphertext='v1$invalid$ciphertext' WHERE id=?",first);
assertTrue(dispatch.dispatchOne()); assertTerminal(first,"failed"); assertEquals(0,sender.calls.get());
releaseQuota(ACTIVE); verification.sendReset(ACTIVE,"127.0.0.1");
UUID second=delivery(ACTIVE,VerificationPurpose.PASSWORD_RESET); String valid=jdbc.queryForObject("SELECT payload_ciphertext FROM verification_delivery_outbox WHERE id=?",String.class,second);
verification.sendReset(UNKNOWN,"127.0.0.2"); UUID third=delivery(UNKNOWN,VerificationPurpose.PASSWORD_RESET);
jdbc.update("UPDATE verification_delivery_outbox SET payload_ciphertext=? WHERE id=?",valid,third);
assertTrue(dispatch.dispatchOne()); assertTerminal(second,"sent"); assertTrue(dispatch.dispatchOne()); assertTerminal(third,"failed");
assertEquals(1,sender.calls.get());
}
@Test void enqueuingRequiresTheCallingTransaction() {
assertThrows(IllegalTransactionStateException.class,()->dispatch.enqueue(VerificationPurpose.REGISTRATION,UNKNOWN,"123456","a".repeat(64)));
assertEquals(0,jdbc.queryForObject("SELECT count(*) FROM verification_delivery_outbox",Integer.class));
}
@Test void failedReceiptPersistenceNeverResendsTheMessage() {
verification.sendReset(ACTIVE,"127.0.0.1"); UUID id=delivery(ACTIVE,VerificationPurpose.PASSWORD_RESET);
jdbc.execute("ALTER TABLE verification_delivery_outbox ADD CONSTRAINT injected_receipt_failure CHECK (status <> 'sent') NOT VALID");
assertThrows(DataIntegrityViolationException.class,dispatch::dispatchOne); assertEquals(1,sender.calls.get());
assertEquals("sending",jdbc.queryForObject("SELECT status FROM verification_delivery_outbox WHERE id=?",String.class,id));
jdbc.execute("ALTER TABLE verification_delivery_outbox DROP CONSTRAINT injected_receipt_failure");
assertFalse(dispatch.dispatchOne()); assertEquals(1,sender.calls.get());
}
@Test void scheduledDeliveryHasOnlyTwoWorkersAndNoUnboundedWaitingQueue() throws Exception {
for (int i=0;i<6;i++) verification.send("queued-"+i+"@example.test",invitation,"127.0.0.1");
sender.arrived=new CountDownLatch(2); sender.release=new CountDownLatch(1);
try {
dispatch.dispatchPending(); assertTrue(sender.arrived.await(3,TimeUnit.SECONDS));
for (int i=0;i<10;i++) dispatch.dispatchPending();
assertEquals(2,sender.calls.get());
assertEquals(2,jdbc.queryForObject("SELECT count(*) FROM verification_delivery_outbox WHERE status='sending'",Integer.class));
assertEquals(4,jdbc.queryForObject("SELECT count(*) FROM verification_delivery_outbox WHERE status='queued'",Integer.class));
} finally { sender.release.countDown(); dispatch.close(); }
}
@Test void blockedQuotaLockTimesOutAndDoesNotLeavePartialAdmission() throws Exception {
var locked=new CountDownLatch(1); var unlock=new CountDownLatch(1);
try (var executor=Executors.newSingleThreadExecutor()) {
var blocker=executor.submit(()->new TransactionTemplate(context.getBean(DataSourceTransactionManager.class)).executeWithoutResult(status->{
jdbc.queryForList("SELECT pg_advisory_xact_lock(734092615)"); locked.countDown();
try { assertTrue(unlock.await(8,TimeUnit.SECONDS)); } catch (InterruptedException error) { Thread.currentThread().interrupt(); throw new IllegalStateException(error); }
}));
assertTrue(locked.await(3,TimeUnit.SECONDS)); long start=System.nanoTime();
try {
assertThrows(org.springframework.dao.DataAccessException.class,()->verification.sendReset(UNKNOWN,"127.0.0.1"));
assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()-start)<5000);
} finally { unlock.countDown(); }
blocker.get(3,TimeUnit.SECONDS);
}
assertEquals(0,jdbc.queryForObject("SELECT count(*) FROM verification_send_events",Integer.class));
assertEquals(0,jdbc.queryForObject("SELECT count(*) FROM verification_delivery_outbox",Integer.class));
assertEquals(true,verification.sendReset(UNKNOWN,"127.0.0.1").get("sent"));
}
}
@@ -64,7 +64,7 @@ class VerifiedAccountPostgresTest {
context.registerBean(DataSourceTransactionManager.class, () -> new DataSourceTransactionManager(source));
context.registerBean(AuthService.class, () -> new AuthService(jdbc, hasher, json, 168));
context.registerBean(TotpService.class, () -> new TotpService(jdbc, new SecretCipher("isolated-totp")));
context.registerBean(VerificationService.class, () -> new VerificationService(jdbc, mock(VerificationSender.class), "isolated-verified-pepper"));
context.registerBean(VerificationService.class, () -> new VerificationService(jdbc, mock(VerificationDispatchService.class), "isolated-verified-pepper"));
context.registerBean(VerifiedAccountService.class); context.refresh();
auth = context.getBean(AuthService.class); verification = context.getBean(VerificationService.class); verified = context.getBean(VerifiedAccountService.class);
http = MockMvcBuilders.standaloneSetup(new AuthController(auth, verification, verified, 168, true))
@@ -166,7 +166,7 @@ class VerifiedAccountPostgresTest {
status.setRollbackOnly();
});
assertUnconsumed(reset, 5);
assertEquals("VERIFICATION_EXPIRED", assertThrows(ApiException.class, () -> {
assertEquals(reset ? "VERIFICATION_INVALID" : "VERIFICATION_EXPIRED", assertThrows(ApiException.class, () -> {
if (reset) verified.resetPassword(ACCOUNT, CODE, "replacement-password", meta);
else verified.register(invite, ACCOUNT, PASSWORD, "Test", CODE, meta);
}).getCode());
@@ -206,7 +206,7 @@ class VerifiedAccountPostgresTest {
for (var future : futures) results.add(future.get(15, TimeUnit.SECONDS));
}
assertEquals(1, results.stream().filter("completed"::equals).count());
assertEquals(1, results.stream().filter("VERIFICATION_EXPIRED"::equals).count());
assertEquals(1, results.stream().filter((reset ? "VERIFICATION_INVALID" : "VERIFICATION_EXPIRED")::equals).count());
assertEquals(1, jdbc.queryForObject("SELECT count(*) FROM users WHERE account=?", Integer.class, ACCOUNT));
assertEquals(1, jdbc.queryForObject("SELECT count(*) FROM auth_audit_log WHERE event_type=?", Integer.class, reset ? "user.password_reset" : "user.registered"));
if (!reset) assertEquals(1, jdbc.queryForObject("SELECT count(*) FROM invitation_redemptions", Integer.class));