feat(güvenlik): giriş ve kayıtta Cloudflare Turnstile, IP başına 3 hatalı denemede 15 dk kilit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+90
-12
@@ -1,6 +1,11 @@
|
||||
//! Kimlik doğrulama uç noktaları:
|
||||
//! `POST /api/auth/register`, `POST /api/auth/login`, `POST /api/auth/logout`, `GET /api/auth/me`,
|
||||
//! `PATCH /api/auth/me` (ad), `POST /api/auth/me/password` (şifre değiştir → diğer oturumlar kapanır)
|
||||
//! `PATCH /api/auth/me` (ad), `POST /api/auth/me/password` (şifre değiştir → diğer oturumlar kapanır),
|
||||
//! `GET /api/auth/guard` (bot doğrulama anahtarı + bu IP'nin kilidi).
|
||||
//!
|
||||
//! **Güvenlik (giriş + kayıt):** Cloudflare Turnstile + IP başına üst üste 3 hatada 15 dk kilit
|
||||
//! (`auth::guard`). Doğrulama hataları (`ValidJson`) sayılmaz; yanlış şifre, geçersiz davet,
|
||||
//! kapalı kayıt, kayıtlı e-posta ve başarısız bot doğrulaması sayılır.
|
||||
|
||||
use axum::{Json, extract::State, http::StatusCode};
|
||||
use axum_extra::extract::cookie::CookieJar;
|
||||
@@ -11,7 +16,11 @@ use validator::Validate;
|
||||
|
||||
use crate::{
|
||||
auth::{
|
||||
AuthUser, password,
|
||||
AuthUser,
|
||||
captcha::CaptchaError,
|
||||
client_ip::ClientIp,
|
||||
guard::Outcome,
|
||||
password,
|
||||
session::{COOKIE_NAME, removal_cookie, session_cookie, ttl},
|
||||
},
|
||||
db::col,
|
||||
@@ -42,6 +51,8 @@ pub struct RegisterRequest {
|
||||
/// Verilirse yeni hane kurulmaz, davet eden haneye `member` olarak katılınır.
|
||||
#[validate(length(max = 20, message = "Davet kodu geçersiz"))]
|
||||
invite_code: Option<String>,
|
||||
/// Cloudflare Turnstile jetonu (bot doğrulaması açıksa zorunlu)
|
||||
captcha_token: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Validate, TS)]
|
||||
@@ -53,6 +64,10 @@ pub struct LoginRequest {
|
||||
password: String,
|
||||
#[serde(default)]
|
||||
remember_me: bool,
|
||||
/// Cloudflare Turnstile jetonu (bot doğrulaması açıksa zorunlu)
|
||||
#[serde(default)]
|
||||
#[ts(optional)]
|
||||
captcha_token: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, TS)]
|
||||
@@ -94,13 +109,67 @@ pub struct PasswordChangeRequest {
|
||||
new_password: String,
|
||||
}
|
||||
|
||||
/// Giriş/kayıt sayfası: bot doğrulaması açık mı, bu IP kilitli mi?
|
||||
#[derive(Serialize, TS)]
|
||||
#[ts(export)]
|
||||
pub struct AuthGuardInfo {
|
||||
/// Turnstile site anahtarı (herkese açık); `null` → doğrulama kapalı
|
||||
captcha_site_key: Option<String>,
|
||||
/// Kilit varsa kalan süre (sn); yoksa 0
|
||||
#[ts(type = "number")]
|
||||
locked_seconds: u64,
|
||||
}
|
||||
|
||||
// ---------- Deneme kilidi + bot doğrulaması (giriş ve kayıt ortak) ----------
|
||||
|
||||
/// Kilitliyse 429; değilse bot doğrulaması (başarısızsa hata sayılır)
|
||||
async fn precheck(state: &AppState, ip: &str, token: Option<&str>) -> AppResult<()> {
|
||||
if let Some(secs) = state.guard.locked_for(ip) {
|
||||
return Err(AppError::Locked(secs));
|
||||
}
|
||||
match state.captcha.verify(token, ip).await {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e @ CaptchaError::Rejected) => {
|
||||
if let Outcome::Locked(secs) = state.guard.failure(ip) {
|
||||
tracing::warn!(ip, "deneme kilidi: bot doğrulaması");
|
||||
return Err(AppError::Locked(secs));
|
||||
}
|
||||
Err(e.into_app_error())
|
||||
}
|
||||
Err(e) => Err(e.into_app_error()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Hatalı denemeyi say; kilide ulaşıldıysa kilit hatası, değilse kalan hakla birlikte döner
|
||||
fn count_failure(state: &AppState, ip: &str, what: &str) -> Result<u32, AppError> {
|
||||
match state.guard.failure(ip) {
|
||||
Outcome::Remaining(n) => Ok(n),
|
||||
Outcome::Locked(secs) => {
|
||||
tracing::warn!(ip, "deneme kilidi: {what}");
|
||||
Err(AppError::Locked(secs))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Uç noktalar ----------
|
||||
|
||||
pub async fn guard_info(
|
||||
State(state): State<AppState>,
|
||||
ClientIp(ip): ClientIp,
|
||||
) -> Json<AuthGuardInfo> {
|
||||
Json(AuthGuardInfo {
|
||||
captcha_site_key: state.config.turnstile_site_key.clone(),
|
||||
locked_seconds: state.guard.locked_for(&ip).unwrap_or(0),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn register(
|
||||
State(state): State<AppState>,
|
||||
ClientIp(ip): ClientIp,
|
||||
jar: CookieJar,
|
||||
ValidJson(req): ValidJson<RegisterRequest>,
|
||||
) -> AppResult<(StatusCode, CookieJar, Json<MeResponse>)> {
|
||||
precheck(&state, &ip, req.captcha_token.as_deref()).await?;
|
||||
let name = req.name.trim().to_string();
|
||||
if name.is_empty() {
|
||||
return Err(AppError::BadRequest("Ad boş olamaz".into()));
|
||||
@@ -118,7 +187,7 @@ pub async fn register(
|
||||
.filter(|c| !c.is_empty());
|
||||
|
||||
let password_hash = password::hash(req.password).await?;
|
||||
let created = account::register(
|
||||
let created = match account::register(
|
||||
&state.db,
|
||||
state.config.registration,
|
||||
NewAccount {
|
||||
@@ -129,7 +198,19 @@ pub async fn register(
|
||||
invite_code,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
.await
|
||||
{
|
||||
Ok(c) => c,
|
||||
// Davet kodu tahmini, kapalı kayıt denemesi, kayıtlı e-posta yoklama → hata sayılır
|
||||
Err(
|
||||
e @ (AppError::RegistrationClosed | AppError::BadRequest(_) | AppError::Conflict(_)),
|
||||
) => {
|
||||
count_failure(&state, &ip, "kayıt")?;
|
||||
return Err(e);
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
state.guard.success(&ip);
|
||||
|
||||
let token = state.jwt.issue(
|
||||
created.user_id,
|
||||
@@ -145,16 +226,13 @@ pub async fn register(
|
||||
|
||||
pub async fn login(
|
||||
State(state): State<AppState>,
|
||||
ClientIp(ip): ClientIp,
|
||||
jar: CookieJar,
|
||||
ValidJson(req): ValidJson<LoginRequest>,
|
||||
) -> AppResult<(CookieJar, Json<MeResponse>)> {
|
||||
precheck(&state, &ip, req.captcha_token.as_deref()).await?;
|
||||
let email = normalize_email(&req.email);
|
||||
|
||||
if !state.login_limiter.is_allowed(&email) {
|
||||
tracing::warn!(%email, "giriş deneme sınırı aşıldı");
|
||||
return Err(AppError::TooManyRequests);
|
||||
}
|
||||
|
||||
let user = state
|
||||
.db
|
||||
.collection::<User>(col::USERS)
|
||||
@@ -163,12 +241,12 @@ pub async fn login(
|
||||
|
||||
let hash = user.as_ref().map(|u| u.password_hash.clone());
|
||||
if !password::verify(req.password, hash).await {
|
||||
state.login_limiter.record_failure(&email);
|
||||
return Err(AppError::InvalidCredentials);
|
||||
let left = count_failure(&state, &ip, "giriş")?;
|
||||
return Err(AppError::InvalidCredentialsLeft(left));
|
||||
}
|
||||
// verify() true döndüyse kullanıcı kesin vardır
|
||||
let user = user.ok_or(AppError::InvalidCredentials)?;
|
||||
state.login_limiter.reset(&email);
|
||||
state.guard.success(&ip);
|
||||
|
||||
state
|
||||
.db
|
||||
|
||||
@@ -47,6 +47,7 @@ pub fn router(state: AppState) -> Router {
|
||||
.route("/health", get(health::health))
|
||||
.route("/auth/register", post(auth::register))
|
||||
.route("/auth/registration", get(auth::registration_info))
|
||||
.route("/auth/guard", get(auth::guard_info))
|
||||
.route("/auth/login", post(auth::login))
|
||||
.route("/auth/logout", post(auth::logout))
|
||||
.route("/auth/me", get(auth::me).patch(auth::update_me))
|
||||
|
||||
Reference in New Issue
Block a user