From 5cfba2d46dfd9d0b3e8af897099135cf9f0caea7 Mon Sep 17 00:00:00 2001 From: M Fari Madyan Date: Fri, 27 Nov 2026 23:30:23 +0700 Subject: [PATCH 1/3] fix(exam): make answer saving, schedule validation, time zone and rate limits reliable - Exam runner: answers go through a save queue with automatic retries. A failed save stays visible and blocks submit, essays are saved after a typing pause instead of on every keystroke, and the automatic submit at the fifth violation and when time runs out now works. - Attempts waiting for essay grading are shown as such instead of offering the exam again. - Schedules: reject an end time before the start time and a duration that does not fit in the window; the form shows the server's validation message. - Admins can create an exam by choosing the teacher who owns it. - Rate limiting: authenticated requests are limited per user instead of per IP and the per-IP login limit is configurable, so a school lab behind one public address is not locked out. - Run the backend in Asia/Jakarta (TZ / APP_TIMEZONE) so schedule times entered as local time are read as local time. --- .env.example | 12 + README.id.md | 5 +- README.md | 5 +- backend/Dockerfile | 5 + .../elearning/modules/exam/dto/ExamDto.java | 36 ++ .../modules/exam/service/ExamService.java | 19 +- .../security/LoginRateLimiterService.java | 20 +- .../security/RateLimitingFilter.java | 97 +++- backend/src/main/resources/application.yml | 8 + .../exam/dto/ExamDtoValidationTest.java | 96 ++++ docker-compose.gcp.yml | 5 + docker-compose.prod.yml | 5 + docker-compose.yml | 2 + docs/ARCHITECTURE.md | 2 +- frontend/src/i18n/messages/examList.ts | 12 + frontend/src/i18n/messages/examMonitor.ts | 2 + frontend/src/i18n/messages/examRunner.ts | 36 +- frontend/src/pages/exams/ExamList.tsx | 84 +++- frontend/src/pages/exams/ExamMonitor.tsx | 1 + frontend/src/pages/exams/ExamRunner.tsx | 459 ++++++++++++++---- frontend/src/pages/exams/answerSaver.ts | 177 +++++++ frontend/src/types/index.ts | 2 +- frontend/src/utils/errors.ts | 13 + 23 files changed, 965 insertions(+), 138 deletions(-) create mode 100644 backend/src/test/java/com/elearning/modules/exam/dto/ExamDtoValidationTest.java create mode 100644 frontend/src/pages/exams/answerSaver.ts create mode 100644 frontend/src/utils/errors.ts diff --git a/.env.example b/.env.example index 4c589d6..b14ef1e 100644 --- a/.env.example +++ b/.env.example @@ -26,6 +26,18 @@ APP_REGISTRATION_ENABLED=false SPRINGDOC_ENABLED=false LOG_LEVEL_APP=INFO +# --- Time zone --- +# The school's time zone. Exam start/end times and assignment deadlines are compared against this clock. +# Asia/Jakarta = WIB, Asia/Makassar = WITA, Asia/Jayapura = WIT. +APP_TIMEZONE=Asia/Jakarta + +# --- Login rate limits (requests per minute from one IP address) --- +# Must fit every student who signs in from the same public IP within a minute (a computer lab, or the +# whole school). Guessing one account stays limited to 5 attempts per minute per e-mail. +# AUTH covers login + first-login password change, so keep it at about twice LOGIN. +APP_RATE_LIMIT_LOGIN_PER_IP=100 +APP_RATE_LIMIT_AUTH_PER_IP=200 + # --- Storage Configuration --- STORAGE_UPLOAD_DIR=/app/storage/uploads diff --git a/README.id.md b/README.id.md index cb9f28e..add14e2 100644 --- a/README.id.md +++ b/README.id.md @@ -174,7 +174,7 @@ graph TD | **A04: Insecure Design** | Kunci jawaban dan pembahasan disembunyikan (`null`) dari payload siswa saat ujian; durasi ujian dikalkulasi di sisi server (*server-side deadline*), tidak mempercayai jam lokal klien. | | **A05: Security Misconfiguration** | Endpoint Actuator diblokir (`404`) dari Nginx publik; semua port Docker internal diikat ke loopback `127.0.0.1`; header keamanan HTTP (`nosniff`, `SAMEORIGIN`) aktif. | | **A06: Vulnerable Components** | Java 21 LTS, Spring Boot 3.5.7, PostgreSQL 16, Redis 7, React 19. Multi-stage Docker container berjalan menggunakan pengguna non-root `spring:spring`. | -| **A07: Identification Failures** | **Rate Limiter Login Bucket4j**: Dibatasi maksimal 5 percobaan per menit per alamat IP (`CF-Connecting-IP` / `X-Forwarded-For`) dan per email akun, menghasilkan HTTP `429 Too Many Requests` disertai header `Retry-After`. | +| **A07: Identification Failures** | **Rate Limiter Login**: Dibatasi 5 percobaan per menit per email akun dan 100 per menit per alamat IP (cukup untuk satu lab komputer di balik satu IP publik, `APP_RATE_LIMIT_LOGIN_PER_IP`), menghasilkan HTTP `429 Too Many Requests` disertai header `Retry-After`. Panggilan API setelah login dibatasi per pengguna, bukan per IP. | | **A08: Software & Data Integrity** | Whitelist ketat ekstensi file upload (`.pdf`, `.docx`, `.xlsx`, `.jpg`, `.png`, dll); ekstensi yang dapat dieksekusi atau berisi skrip (`.html`, `.svg`, `.exe`, `.sh`) ditolak keras untuk mencegah Stored XSS; unduhan disajikan dengan `Content-Disposition` aman. | | **A09: Logging & Monitoring** | Log pelanggaran anti-cheat ujian tercatat lengkap dengan identitas NIS siswa; probe internal `/actuator/health` tersedia untuk healthcheck container. | | **A10: SSRF** | Tidak ada fitur backend yang melakukan pemanggilan HTTP outbound ke URL luar dari input pengguna. | @@ -372,7 +372,8 @@ Untuk menerapkan ke server production: 8. Refresh token disimpan di cookie httpOnly `Secure`, jadi aplikasi harus diakses lewat HTTPS. Set `APP_REFRESH_COOKIE_SECURE=false` hanya untuk menjalankan lokal tanpa HTTPS (`docker-compose.yml` lokal sudah mengaturnya). 9. SPA mengirim header Content-Security-Policy. Jika memakai analytics, izinkan host-nya di container frontend, misalnya `CSP_SCRIPT_SRC_EXTRA="https://www.googletagmanager.com"` dan `CSP_CONNECT_SRC_EXTRA="https://*.google-analytics.com"`. 10. **Beberapa instance backend:** set `APP_REALTIME_MODE=redis`, `APP_RATE_LIMIT_STORE=redis`, dan `APP_STORAGE_TYPE=s3` dengan `APP_STORAGE_S3_BUCKET` (ditambah `APP_STORAGE_S3_ENDPOINT` dan `APP_STORAGE_S3_PATH_STYLE=true` untuk MinIO), lalu aktifkan sticky session untuk `/ws`. Detail ada di [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md#scaling-limits-and-roadmap). -11. **IP asli klien / rate limiting:** backend hanya mempercayai `X-Forwarded-For` dari proxy internal (jaringan Docker). Jika situs berada di belakang Cloudflare, pulihkan IP pengunjung di Nginx host, jika tidak semua user akan berbagi IP Cloudflare untuk rate limit: +11. **Zona waktu:** jadwal ujian dan tenggat tugas dibandingkan dengan jam backend. Image berjalan di `Asia/Jakarta` (WIB); set `APP_TIMEZONE=Asia/Makassar` (WITA) atau `Asia/Jayapura` (WIT) untuk daerah lain. Ubah di luar jam ujian, karena attempt yang sedang berjalan dihitung dengan jam ini. +12. **IP asli klien / rate limiting:** backend hanya mempercayai `X-Forwarded-For` dari proxy internal (jaringan Docker). Jika situs berada di belakang Cloudflare, pulihkan IP pengunjung di Nginx host, jika tidak semua user akan berbagi IP Cloudflare untuk rate limit: ```nginx # blok http {} di nginx host — samakan daftarnya dengan https://www.cloudflare.com/ips/ set_real_ip_from 173.245.48.0/20; # ...tambahkan semua range IPv4/IPv6 Cloudflare diff --git a/README.md b/README.md index bdd24af..35aecb3 100644 --- a/README.md +++ b/README.md @@ -174,7 +174,7 @@ graph TD | **A04: Insecure Design** | Examination answer keys and explanations strictly stripped (`null`) from student payloads; examination duration deadlines enforced on the server-side, not trusting client clocks. | | **A05: Security Misconfiguration** | Spring Boot Actuator endpoints strictly blocked (`404`) from public Nginx reverse proxy; all Docker service ports bound to loopback `127.0.0.1`; security headers (`X-Content-Type-Options: nosniff`, `X-Frame-Options: SAMEORIGIN`) enforced. | | **A06: Vulnerable Components** | Java 21 LTS, Spring Boot 3.5.7, PostgreSQL 16, Redis 7, React 19. Multi-stage Docker containers running under non-root `spring:spring` user. | -| **A07: Identification Failures** | **Bucket4j Login Rate Limiter**: 5 attempts per minute per IP address (`CF-Connecting-IP` / `X-Forwarded-For`) and per account email, returning `429 Too Many Requests` with `Retry-After` header. | +| **A07: Identification Failures** | **Login Rate Limiter**: 5 attempts per minute per account email and 100 per minute per IP address (sized for a computer lab behind one public IP, `APP_RATE_LIMIT_LOGIN_PER_IP`), returning `429 Too Many Requests` with `Retry-After` header. Signed-in API calls are limited per user, not per IP. | | **A08: Software & Data Integrity** | Strict file upload extension whitelist (`.pdf`, `.docx`, `.xlsx`, `.jpg`, `.png`, etc.); executable and scriptable types (`.html`, `.svg`, `.exe`, `.sh`) explicitly rejected to prevent Stored XSS; safe download `Content-Disposition`. | | **A09: Logging & Monitoring** | Anti-cheat proctoring violation alerts logged with student NIS; internal `/actuator/health` probe available for container healthchecks. | | **A10: SSRF** | Zero user-controlled outbound HTTP requests from backend services. | @@ -373,7 +373,8 @@ For production deployments: 8. The refresh token is an httpOnly `Secure` cookie, so serve the app over HTTPS. Set `APP_REFRESH_COOKIE_SECURE=false` only for plain-HTTP local runs (the local `docker-compose.yml` already does). 9. The SPA sends a Content-Security-Policy. If you enable analytics, allow its hosts on the frontend container, e.g. `CSP_SCRIPT_SRC_EXTRA="https://www.googletagmanager.com"` and `CSP_CONNECT_SRC_EXTRA="https://*.google-analytics.com"`. 10. **Several backend instances:** set `APP_REALTIME_MODE=redis`, `APP_RATE_LIMIT_STORE=redis`, and `APP_STORAGE_TYPE=s3` with `APP_STORAGE_S3_BUCKET` (plus `APP_STORAGE_S3_ENDPOINT` and `APP_STORAGE_S3_PATH_STYLE=true` for MinIO), and enable sticky sessions for `/ws`. Details in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md#scaling-limits-and-roadmap). -11. **Real client IP / rate limiting:** the backend trusts `X-Forwarded-For` only from internal proxies (Docker network). If the site is behind Cloudflare, restore the visitor IP on the host Nginx, otherwise all users share Cloudflare's IPs for rate limiting: +11. **Time zone:** exam schedules and deadlines are compared against the backend's clock. The image runs in `Asia/Jakarta` (WIB); set `APP_TIMEZONE=Asia/Makassar` (WITA) or `Asia/Jayapura` (WIT) for other regions. Change it outside exam hours: attempts in progress are timed against this clock. +12. **Real client IP / rate limiting:** the backend trusts `X-Forwarded-For` only from internal proxies (Docker network). If the site is behind Cloudflare, restore the visitor IP on the host Nginx, otherwise all users share Cloudflare's IPs for rate limiting: ```nginx # http {} block of the host nginx — keep the list in sync with https://www.cloudflare.com/ips/ set_real_ip_from 173.245.48.0/20; # ...add every Cloudflare IPv4/IPv6 range diff --git a/backend/Dockerfile b/backend/Dockerfile index efac255..cf33641 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -11,5 +11,10 @@ RUN addgroup -S spring && adduser -S spring -G spring && \ chown -R spring:spring /app USER spring:spring COPY --from=build /app/target/*.jar app.jar +# Exam schedules, deadlines and timestamps are stored as local wall-clock time, so the JVM must run in the +# school's time zone. Without this the container runs in UTC and an exam scheduled for 07:00 WIB opens at 14:00. +# Override with the TZ environment variable (Asia/Makassar for WITA, Asia/Jayapura for WIT). +ENV TZ=Asia/Jakarta + EXPOSE 8080 ENTRYPOINT ["java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "app.jar"] diff --git a/backend/src/main/java/com/elearning/modules/exam/dto/ExamDto.java b/backend/src/main/java/com/elearning/modules/exam/dto/ExamDto.java index b26cecf..a44d7a4 100644 --- a/backend/src/main/java/com/elearning/modules/exam/dto/ExamDto.java +++ b/backend/src/main/java/com/elearning/modules/exam/dto/ExamDto.java @@ -2,6 +2,10 @@ import com.elearning.common.enums.ExamType; import com.elearning.common.enums.Status; +import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.validation.constraints.AssertTrue; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import lombok.AllArgsConstructor; @@ -9,6 +13,7 @@ import lombok.Data; import lombok.NoArgsConstructor; +import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; @@ -23,6 +28,12 @@ public class ExamDto { @NotNull(message = "Classroom ID is required") private Long classroomId; + /** + * Teacher who owns the exam. Only read when an admin creates the exam (an admin has no teacher + * profile); a teacher always owns the exams they create. + */ + private Long teacherId; + @NotBlank(message = "Title is required") private String title; @@ -31,9 +42,14 @@ public class ExamDto { @Builder.Default private ExamType type = ExamType.quiz; + @NotNull(message = "Duration is required") + @Min(value = 1, message = "Duration must be at least 1 minute") @Builder.Default private Integer durationMinutes = 60; + @NotNull(message = "Passing score is required") + @Min(value = 0, message = "Passing score must be between 0 and 100") + @Max(value = 100, message = "Passing score must be between 0 and 100") @Builder.Default private Integer passingScore = 75; @@ -59,4 +75,24 @@ public class ExamDto { @Builder.Default private Status status = Status.draft; + + /** The exam window must close after it opens; otherwise no student could ever start the exam. */ + @JsonIgnore + @AssertTrue(message = "End time must be after start time") + public boolean isEndAfterStart() { + if (startAt == null || endAt == null) { + return true; // reported by @NotNull + } + return endAt.isAfter(startAt); + } + + /** A student who starts at the opening time must be able to use the whole duration. */ + @JsonIgnore + @AssertTrue(message = "Duration does not fit between start time and end time") + public boolean isDurationWithinWindow() { + if (startAt == null || endAt == null || durationMinutes == null || !endAt.isAfter(startAt)) { + return true; // reported by the other constraints + } + return durationMinutes <= Duration.between(startAt, endAt).toMinutes(); + } } diff --git a/backend/src/main/java/com/elearning/modules/exam/service/ExamService.java b/backend/src/main/java/com/elearning/modules/exam/service/ExamService.java index 5684746..31bc180 100644 --- a/backend/src/main/java/com/elearning/modules/exam/service/ExamService.java +++ b/backend/src/main/java/com/elearning/modules/exam/service/ExamService.java @@ -105,8 +105,7 @@ public ExamResponse getExamById(Long id, UserPrincipal principal) { @Transactional public ExamResponse createExam(ExamDto dto, UserPrincipal principal) { - Teacher teacher = teacherRepository.findByUserId(principal.getId()) - .orElseThrow(() -> new IllegalArgumentException("Teacher profile not found")); + Teacher teacher = resolveOwnerTeacher(dto.getTeacherId(), principal); Subject subject = subjectRepository.findById(dto.getSubjectId()) .orElseThrow(() -> new IllegalArgumentException("Subject not found: " + dto.getSubjectId())); @@ -396,6 +395,22 @@ public Map importQuestionsFromExcel(Long examId, MultipartFile f return result; } + /** + * A teacher owns the exams they create. An admin has no teacher profile, so an admin names the + * owning teacher with {@code teacherId}; a teacher cannot create exams on behalf of someone else. + */ + private Teacher resolveOwnerTeacher(Long teacherId, UserPrincipal principal) { + boolean isAdmin = principal.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN")); + if (isAdmin && teacherId != null) { + return teacherRepository.findById(teacherId) + .orElseThrow(() -> new IllegalArgumentException("Teacher not found: " + teacherId)); + } + return teacherRepository.findByUserId(principal.getId()) + .orElseThrow(() -> new IllegalArgumentException(isAdmin + ? "Choose the teacher who owns this exam" + : "Teacher profile not found")); + } + private void validateTeacherOwnership(Examination exam, UserPrincipal principal) { boolean isAdmin = principal.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN")); if (!isAdmin && !exam.getTeacher().getUser().getId().equals(principal.getId())) { diff --git a/backend/src/main/java/com/elearning/security/LoginRateLimiterService.java b/backend/src/main/java/com/elearning/security/LoginRateLimiterService.java index d0eb443..e006a6c 100644 --- a/backend/src/main/java/com/elearning/security/LoginRateLimiterService.java +++ b/backend/src/main/java/com/elearning/security/LoginRateLimiterService.java @@ -4,6 +4,7 @@ import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; @@ -18,14 +19,21 @@ public class LoginRateLimiterService { private final RateLimiter rateLimiter; private static final Duration WINDOW = Duration.ofMinutes(1); - // 5 login attempts per minute per IP address - private static final int MAX_ATTEMPTS_PER_IP = 5; - // 5 login attempts per minute per account email - private static final int MAX_ATTEMPTS_PER_EMAIL = 5; + /** + * Login attempts per minute from one IP address, successful ones included. A school computer lab shares + * one public IP, so this must fit a whole class signing in at the start of an exam. Guessing the password + * of a single account is stopped by the much lower per-e-mail limit below. + */ + @Value("${app.rate-limit.login-per-ip:100}") + private int maxAttemptsPerIp = 100; + + /** Login attempts per minute for one account e-mail (reset after a successful login). */ + @Value("${app.rate-limit.login-per-email:5}") + private int maxAttemptsPerEmail = 5; public void checkLoginAllowed(String clientIp, String email) { if (clientIp != null && !clientIp.isBlank()) { - if (!rateLimiter.tryAcquire("login:ip:" + clientIp, MAX_ATTEMPTS_PER_IP, WINDOW)) { + if (!rateLimiter.tryAcquire("login:ip:" + clientIp, maxAttemptsPerIp, WINDOW)) { log.warn("Login rate limit exceeded for IP: {}", clientIp); throw new RateLimitExceededException("Terlalu banyak percobaan login dari alamat IP ini. Silakan tunggu 1 menit sebelum mencoba lagi."); } @@ -33,7 +41,7 @@ public void checkLoginAllowed(String clientIp, String email) { if (email != null && !email.isBlank()) { String normalizedEmail = email.trim().toLowerCase(); - if (!rateLimiter.tryAcquire("login:email:" + normalizedEmail, MAX_ATTEMPTS_PER_EMAIL, WINDOW)) { + if (!rateLimiter.tryAcquire("login:email:" + normalizedEmail, maxAttemptsPerEmail, WINDOW)) { log.warn("Login rate limit exceeded for email: {}", email); throw new RateLimitExceededException("Terlalu banyak percobaan login gagal untuk akun ini. Silakan tunggu 1 menit sebelum mencoba lagi."); } diff --git a/backend/src/main/java/com/elearning/security/RateLimitingFilter.java b/backend/src/main/java/com/elearning/security/RateLimitingFilter.java index 46fe73d..045123e 100644 --- a/backend/src/main/java/com/elearning/security/RateLimitingFilter.java +++ b/backend/src/main/java/com/elearning/security/RateLimitingFilter.java @@ -6,6 +6,7 @@ import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.lang.NonNull; @@ -13,27 +14,45 @@ import org.springframework.web.filter.OncePerRequestFilter; import java.io.IOException; - import java.time.Duration; /** * Server-side rate limiting filter (counters in memory or in Redis, see {@link RateLimiter}). * Intercepts incoming HTTP requests at the Servlet Filter layer before hitting controllers, * protecting against brute-force attacks, DDoS, and excessive API burst traffic. + * + *

Requests that carry a valid access token are counted per user. A school computer lab usually shares + * one public IP address, so counting per IP would make a whole class share one budget and lock students + * out while they save answers. Only requests without a valid token (and the auth endpoints, where no + * token exists yet) are counted per IP. */ @Component @RequiredArgsConstructor @Slf4j public class RateLimitingFilter extends OncePerRequestFilter { + private static final Duration WINDOW = Duration.ofMinutes(1); + private static final String USER_KEY_PREFIX = "user:"; + private static final String IP_KEY_PREFIX = "ip:"; + private static final String BEARER_PREFIX = "Bearer "; + /** In-memory or Redis-backed, see {@code RateLimitConfig}. */ private final RateLimiter rateLimiter; - private static final Duration WINDOW = Duration.ofMinutes(1); + /** Reads the user id from the access token; this filter runs before {@link JwtAuthenticationFilter}. */ + private final JwtProvider jwtProvider; + + // Requests per minute (see app.rate-limit.* in application.yml) + @Value("${app.rate-limit.auth-per-ip:200}") + private int authPerIp = 200; + + @Value("${app.rate-limit.exam-per-user:120}") + private int examPerUser = 120; - // Rate limit thresholds - private static final int AUTH_CAPACITY = 10; // 10 login/auth requests per minute per IP - private static final int SUBMIT_CAPACITY = 60; // 60 autosave/submit requests per minute per IP - private static final int GENERAL_CAPACITY = 120; // 120 general API requests per minute per IP + @Value("${app.rate-limit.api-per-user:120}") + private int apiPerUser = 120; + + @Value("${app.rate-limit.anonymous-per-ip:300}") + private int anonymousPerIp = 300; @Override protected boolean shouldNotFilter(@NonNull HttpServletRequest request) { @@ -57,29 +76,27 @@ protected void doFilterInternal( String clientIp = LoginRateLimiterService.getClientIp(request); String requestUri = request.getRequestURI(); - // 1. Strictest tier: Auth endpoints (Login, Refresh, Register) - if (requestUri.startsWith("/api/v1/auth/login") || requestUri.startsWith("/api/v1/auth/register") - || requestUri.startsWith("/api/v1/auth/change-password")) { - if (!rateLimiter.tryAcquire("api:auth:" + clientIp, AUTH_CAPACITY, WINDOW)) { + if (isAuthEndpoint(requestUri)) { + // 1. Auth endpoints (login, register, change password): no trusted identity yet, so count per IP. + // Brute force on a single account is limited separately, per e-mail, in LoginRateLimiterService. + if (!rateLimiter.tryAcquire("api:auth:" + clientIp, authPerIp, WINDOW)) { log.warn("Rate limit [AUTH] exceeded for IP {} on {}", clientIp, requestUri); sendRateLimitResponse(response, "Terlalu banyak percobaan autentikasi dari alamat IP ini. Silakan tunggu 1 menit sebelum mencoba lagi."); return; } - } - - // 2. Medium tier: Exam autosave and submissions (anti-flood during high-concurrency CBT) - else if (requestUri.contains("/exams/") && (requestUri.endsWith("/submit") || requestUri.endsWith("/answer") || requestUri.endsWith("/answers"))) { - if (!rateLimiter.tryAcquire("api:submit:" + clientIp, SUBMIT_CAPACITY, WINDOW)) { - log.warn("Rate limit [EXAM SUBMIT] exceeded for IP {} on {}", clientIp, requestUri); - sendRateLimitResponse(response, "Terlalu banyak permintaan submit ujian secara bersamaan. Silakan tunggu beberapa saat."); + } else if (isExamWriteEndpoint(requestUri)) { + // 2. Exam autosave and submissions (anti-flood during high-concurrency CBT), per student. + String clientKey = resolveClientKey(request, clientIp); + if (!rateLimiter.tryAcquire("api:submit:" + clientKey, capacityFor(clientKey, examPerUser), WINDOW)) { + log.warn("Rate limit [EXAM SUBMIT] exceeded for {} on {}", clientKey, requestUri); + sendRateLimitResponse(response, "Terlalu banyak permintaan simpan jawaban dalam waktu singkat. Silakan tunggu beberapa saat."); return; } - } - - // 3. General API tier: All other /api/v1/** endpoints - else if (requestUri.startsWith("/api/v1")) { - if (!rateLimiter.tryAcquire("api:general:" + clientIp, GENERAL_CAPACITY, WINDOW)) { - log.warn("Rate limit [GENERAL API] exceeded for IP {} on {}", clientIp, requestUri); + } else if (requestUri.startsWith("/api/v1")) { + // 3. Every other /api/v1/** endpoint, per user. + String clientKey = resolveClientKey(request, clientIp); + if (!rateLimiter.tryAcquire("api:general:" + clientKey, capacityFor(clientKey, apiPerUser), WINDOW)) { + log.warn("Rate limit [GENERAL API] exceeded for {} on {}", clientKey, requestUri); sendRateLimitResponse(response, "Batas permintaan API terlampaui. Silakan kurangi frekuensi permintaan Anda."); return; } @@ -88,6 +105,40 @@ else if (requestUri.startsWith("/api/v1")) { filterChain.doFilter(request, response); } + private static boolean isAuthEndpoint(String requestUri) { + return requestUri.startsWith("/api/v1/auth/login") + || requestUri.startsWith("/api/v1/auth/register") + || requestUri.startsWith("/api/v1/auth/change-password"); + } + + private static boolean isExamWriteEndpoint(String requestUri) { + return requestUri.contains("/exams/") + && (requestUri.endsWith("/submit") || requestUri.endsWith("/answer") || requestUri.endsWith("/answers")); + } + + /** + * {@code "user:"} when the request carries a valid access token, otherwise {@code "ip:

"}. + * A forged or expired token never selects a user bucket, so it cannot be used to dodge the IP limit. + */ + String resolveClientKey(HttpServletRequest request, String clientIp) { + String header = request.getHeader("Authorization"); + if (header != null && header.startsWith(BEARER_PREFIX)) { + String token = header.substring(BEARER_PREFIX.length()); + try { + if (jwtProvider.validateAccessToken(token)) { + return USER_KEY_PREFIX + jwtProvider.getUserIdFromToken(token); + } + } catch (RuntimeException e) { + // Malformed token or subject: fall through and count the request per IP. + } + } + return IP_KEY_PREFIX + clientIp; + } + + private int capacityFor(String clientKey, int perUserCapacity) { + return clientKey.startsWith(USER_KEY_PREFIX) ? perUserCapacity : anonymousPerIp; + } + private void sendRateLimitResponse(HttpServletResponse response, String message) throws IOException { response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value()); response.setContentType(MediaType.APPLICATION_JSON_VALUE); diff --git a/backend/src/main/resources/application.yml b/backend/src/main/resources/application.yml index 2dd3f41..8accf2d 100644 --- a/backend/src/main/resources/application.yml +++ b/backend/src/main/resources/application.yml @@ -83,6 +83,14 @@ app: rate-limit: # memory = per instance; redis = shared by all instances store: ${APP_RATE_LIMIT_STORE:memory} + # Requests per minute. Signed-in users are counted per account, so a computer lab behind one public + # IP address does not share a single budget. Only requests without a valid token are counted per IP. + login-per-ip: ${APP_RATE_LIMIT_LOGIN_PER_IP:100} # login attempts from one IP address + login-per-email: ${APP_RATE_LIMIT_LOGIN_PER_EMAIL:5} # login attempts for one account (brute force) + auth-per-ip: ${APP_RATE_LIMIT_AUTH_PER_IP:200} # login + register + change-password from one IP + exam-per-user: ${APP_RATE_LIMIT_EXAM_PER_USER:120} # answer autosave + submit of one student + api-per-user: ${APP_RATE_LIMIT_API_PER_USER:120} # every other API call of one user + anonymous-per-ip: ${APP_RATE_LIMIT_ANONYMOUS_PER_IP:300} # API calls without a valid access token realtime: # local = in-memory STOMP broker of this instance; redis = relay exam events to every instance mode: ${APP_REALTIME_MODE:local} diff --git a/backend/src/test/java/com/elearning/modules/exam/dto/ExamDtoValidationTest.java b/backend/src/test/java/com/elearning/modules/exam/dto/ExamDtoValidationTest.java new file mode 100644 index 0000000..1857fe3 --- /dev/null +++ b/backend/src/test/java/com/elearning/modules/exam/dto/ExamDtoValidationTest.java @@ -0,0 +1,96 @@ +package com.elearning.modules.exam.dto; + +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import jakarta.validation.ValidatorFactory; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.time.LocalDateTime; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; + +/** Schedule rules of an exam: the window must be open, and the duration must fit inside it. */ +class ExamDtoValidationTest { + + private static final LocalDateTime START = LocalDateTime.of(2026, 12, 1, 7, 0); + + private static ValidatorFactory factory; + private static Validator validator; + + @BeforeAll + static void createValidator() { + factory = Validation.buildDefaultValidatorFactory(); + validator = factory.getValidator(); + } + + @AfterAll + static void closeValidator() { + factory.close(); + } + + /** 60 minutes inside a two-hour window. */ + private static ExamDto.ExamDtoBuilder validExam() { + return ExamDto.builder() + .subjectId(1L) + .classroomId(1L) + .title("Ujian Harian") + .durationMinutes(60) + .startAt(START) + .endAt(START.plusHours(2)); + } + + private static Set violatedProperties(ExamDto dto) { + return validator.validate(dto).stream() + .map(violation -> violation.getPropertyPath().toString()) + .collect(Collectors.toSet()); + } + + @Test + void acceptsADurationThatFitsTheWindow() { + assertThat(violatedProperties(validExam().build())).isEmpty(); + } + + @Test + void acceptsADurationThatFillsTheWholeWindow() { + assertThat(violatedProperties(validExam().durationMinutes(120).build())).isEmpty(); + } + + @Test + void rejectsAnEndTimeBeforeTheStartTime() { + ExamDto dto = validExam().endAt(START.minusMinutes(1)).build(); + + assertThat(violatedProperties(dto)).containsExactly("endAfterStart"); + } + + @Test + void rejectsAnEndTimeEqualToTheStartTime() { + ExamDto dto = validExam().endAt(START).build(); + + assertThat(violatedProperties(dto)).containsExactly("endAfterStart"); + } + + @Test + void rejectsADurationLongerThanTheWindow() { + ExamDto dto = validExam().durationMinutes(121).build(); + + assertThat(violatedProperties(dto)).containsExactly("durationWithinWindow"); + } + + @Test + void reportsMissingTimesOnlyAsMissing() { + ExamDto dto = validExam().startAt(null).endAt(null).build(); + + assertThat(violatedProperties(dto)).containsExactlyInAnyOrder("startAt", "endAt"); + } + + @Test + void rejectsAPassingScoreAbove100() { + ExamDto dto = validExam().passingScore(101).build(); + + assertThat(violatedProperties(dto)).containsExactly("passingScore"); + } +} diff --git a/docker-compose.gcp.yml b/docker-compose.gcp.yml index fd1c9b5..8e6964a 100644 --- a/docker-compose.gcp.yml +++ b/docker-compose.gcp.yml @@ -76,6 +76,11 @@ services: APP_NOTIFY_EXAM_RESULTS: ${APP_NOTIFY_EXAM_RESULTS:-true} APP_OUTBOX_PUBLISHER: pubsub APP_OUTBOX_PUBSUB_TOPIC: projects/${GCP_PROJECT:?GCP_PROJECT is required}/topics/exam-results + # School time zone: exam schedules and deadlines are compared against this clock (WIB by default). + TZ: ${APP_TIMEZONE:-Asia/Jakarta} + # Logins per minute from one IP address: must fit a computer lab behind one public IP. + APP_RATE_LIMIT_LOGIN_PER_IP: ${APP_RATE_LIMIT_LOGIN_PER_IP:-100} + APP_RATE_LIMIT_AUTH_PER_IP: ${APP_RATE_LIMIT_AUTH_PER_IP:-200} APP_CORS_ALLOWED_ORIGINS: https://${DOMAIN:?DOMAIN is required} APP_DEMO_MODE: ${APP_DEMO_MODE:-false} APP_REGISTRATION_ENABLED: ${APP_REGISTRATION_ENABLED:-false} diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index 90433da..35ba284 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -44,6 +44,11 @@ services: SPRING_DATA_REDIS_HOST: redis SPRING_DATA_REDIS_PORT: 6379 JWT_SECRET: ${JWT_SECRET:?JWT_SECRET is required (openssl rand -base64 32)} + # School time zone: exam schedules and deadlines are compared against this clock (WIB by default). + TZ: ${APP_TIMEZONE:-Asia/Jakarta} + # Logins per minute from one IP address: must fit a computer lab behind one public IP. + APP_RATE_LIMIT_LOGIN_PER_IP: ${APP_RATE_LIMIT_LOGIN_PER_IP:-100} + APP_RATE_LIMIT_AUTH_PER_IP: ${APP_RATE_LIMIT_AUTH_PER_IP:-200} STORAGE_UPLOAD_DIR: /app/storage/uploads APP_CORS_ALLOWED_ORIGINS: ${APP_CORS_ALLOWED_ORIGINS:-http://localhost:3000,http://localhost:5173} APP_DEMO_MODE: ${APP_DEMO_MODE:-false} diff --git a/docker-compose.yml b/docker-compose.yml index 821b6ce..7d6d9ce 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -58,6 +58,8 @@ services: SPRING_DATA_REDIS_HOST: redis SPRING_DATA_REDIS_PORT: 6379 JWT_SECRET: ${JWT_SECRET:?JWT_SECRET is required - create .env with output of openssl rand -base64 32} + # School time zone: exam schedules and deadlines are compared against this clock (WIB by default). + TZ: ${APP_TIMEZONE:-Asia/Jakarta} STORAGE_UPLOAD_DIR: /app/storage/uploads APP_DEMO_MODE: ${APP_DEMO_MODE:-false} # Local stack is served over plain HTTP, so the refresh-token cookie cannot be Secure here. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 5770b4e..cb5b66b 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -158,7 +158,7 @@ sequenceDiagram participant DB as PostgreSQL B->>API: POST /api/v1/auth/login (email, password) - API->>API: Rate limit per IP and per email (5/min) + API->>API: Rate limit per email (5/min) and per IP (100/min) API->>DB: Load user, verify BCrypt hash API->>R: SET auth:refresh:{jti} = userId (TTL 7d) API-->>B: accessToken in body + Set-Cookie refresh_token (httpOnly, Secure, SameSite=Strict, Path=/api/v1/auth) diff --git a/frontend/src/i18n/messages/examList.ts b/frontend/src/i18n/messages/examList.ts index 82c56d7..1dca624 100644 --- a/frontend/src/i18n/messages/examList.ts +++ b/frontend/src/i18n/messages/examList.ts @@ -39,6 +39,12 @@ export const examList = defineMessages({ shuffleQuestions: 'Acak Soal', shuffleOptions: 'Acak Pilihan Jawaban', createAndPublish: 'Buat & Publikasikan Ujian', + ownerTeacher: 'Guru Pemilik Ujian', + chooseTeacher: '-- Pilih Guru --', + endBeforeStart: 'Waktu selesai harus setelah waktu mulai.', + durationTooLong: 'Durasi {duration} menit tidak muat di antara waktu mulai dan waktu selesai ({window} menit).', + awaitingGrading: 'Menunggu penilaian guru', + alreadySubmitted: 'Sudah dikumpulkan', }, en: { title: 'CBT Exams (Computer-Based Test)', @@ -78,5 +84,11 @@ export const examList = defineMessages({ shuffleQuestions: 'Shuffle Questions', shuffleOptions: 'Shuffle Answer Options', createAndPublish: 'Create & Publish Exam', + ownerTeacher: 'Teacher Who Owns the Exam', + chooseTeacher: '-- Choose Teacher --', + endBeforeStart: 'The end time must be after the start time.', + durationTooLong: 'A duration of {duration} minutes does not fit between the start and end time ({window} minutes).', + awaitingGrading: 'Waiting for teacher grading', + alreadySubmitted: 'Already submitted', }, }); diff --git a/frontend/src/i18n/messages/examMonitor.ts b/frontend/src/i18n/messages/examMonitor.ts index be9961e..8a074d8 100644 --- a/frontend/src/i18n/messages/examMonitor.ts +++ b/frontend/src/i18n/messages/examMonitor.ts @@ -33,6 +33,7 @@ export const examMonitor = defineMessages({ statusSubmitted: 'Dikumpulkan', statusNeedsGrading: 'Perlu dinilai', statusCompleted: 'Selesai', + statusForceFinished: 'Dihentikan pengawas', warningCount: '{count} Peringatan', warningOne: '1 Peringatan', noFlags: '0 Tanda', @@ -70,6 +71,7 @@ export const examMonitor = defineMessages({ statusSubmitted: 'Submitted', statusNeedsGrading: 'Needs grading', statusCompleted: 'Completed', + statusForceFinished: 'Stopped by proctor', warningCount: '{count} Warnings', warningOne: '1 Warning', noFlags: '0 Flags', diff --git a/frontend/src/i18n/messages/examRunner.ts b/frontend/src/i18n/messages/examRunner.ts index d9603ac..bab4578 100644 --- a/frontend/src/i18n/messages/examRunner.ts +++ b/frontend/src/i18n/messages/examRunner.ts @@ -16,7 +16,23 @@ export const examRunner = defineMessages({ notPassed: 'REMIDIAL (TIDAK LULUS)', backToExams: 'Kembali ke Halaman Ujian', activeSession: 'Sesi Aktif', - autoSaved: 'Tersimpan Otomatis', + allSaved: 'Semua jawaban tersimpan', + unsavedCount: '{count} jawaban belum tersimpan', + notSaved: 'Belum tersimpan', + saveFailedBanner: 'Koneksi bermasalah. {count} jawaban belum tersimpan dan akan dikirim ulang otomatis.', + retryNow: 'Coba sekarang', + unsavedBlocksSubmit: 'Masih ada {count} jawaban yang belum tersimpan. Periksa koneksi, lalu coba lagi.', + submitting: 'Mengumpulkan...', + autoSubmitting: 'Mengumpulkan jawaban Anda. Jangan tutup halaman ini.', + timeUpTitle: 'Waktu Habis', + timeUpText: 'Waktu ujian sudah habis. Jawaban Anda dikumpulkan secara otomatis.', + autoSubmittedTitle: 'Ujian Dikumpulkan Otomatis', + closedTitle: 'Ujian Sudah Ditutup', + closedText: 'Ujian ini sudah ditutup oleh sistem, sehingga jawaban tidak bisa diubah lagi.', + lostAnswers: '{count} jawaban terakhir tidak sempat tersimpan sebelum ujian ditutup.', + pendingGradingTitle: 'Menunggu Penilaian Guru', + pendingGradingText: 'Jawaban esai Anda akan dinilai oleh guru. Nilai akhir tampil setelah penilaian selesai.', + provisionalScore: 'Nilai sementara dari soal yang dinilai otomatis', toggleFullscreen: 'Aktifkan/nonaktifkan layar penuh', securityAlert: 'Peringatan Keamanan: {count}/5 pelanggaran tercatat. Meninggalkan tab ujian akan mengumpulkan ujian Anda secara otomatis!', @@ -54,7 +70,23 @@ export const examRunner = defineMessages({ notPassed: 'REMEDIAL (NOT PASSED)', backToExams: 'Back to Exams', activeSession: 'Active Session', - autoSaved: 'Auto-saved', + allSaved: 'All answers saved', + unsavedCount: '{count} answers not saved yet', + notSaved: 'Not saved yet', + saveFailedBanner: 'Connection problem. {count} answers are not saved yet and will be sent again automatically.', + retryNow: 'Retry now', + unsavedBlocksSubmit: '{count} answers are still not saved. Check your connection, then try again.', + submitting: 'Submitting...', + autoSubmitting: 'Submitting your answers. Do not close this page.', + timeUpTitle: 'Time Is Up', + timeUpText: 'The exam time has run out. Your answers were submitted automatically.', + autoSubmittedTitle: 'Exam Submitted Automatically', + closedTitle: 'Exam Already Closed', + closedText: 'This exam was closed by the system, so the answers can no longer be changed.', + lostAnswers: '{count} of your last answers could not be saved before the exam was closed.', + pendingGradingTitle: 'Waiting for Teacher Grading', + pendingGradingText: 'Your essay answers will be graded by the teacher. The final score appears once grading is done.', + provisionalScore: 'Provisional score from automatically graded questions', toggleFullscreen: 'Toggle fullscreen', securityAlert: 'Security Alert: {count}/5 violations recorded. Leaving the exam tab will submit your exam automatically!', diff --git a/frontend/src/pages/exams/ExamList.tsx b/frontend/src/pages/exams/ExamList.tsx index 39774ea..79b1e06 100644 --- a/frontend/src/pages/exams/ExamList.tsx +++ b/frontend/src/pages/exams/ExamList.tsx @@ -1,7 +1,8 @@ import React, { useEffect, useState } from 'react'; import api from '../../api/client'; import { useAuthStore } from '../../store/authStore'; -import type { Exam, Subject, Classroom, ApiResponse } from '../../types'; +import type { Exam, Subject, Classroom, Teacher, ApiResponse } from '../../types'; +import { apiErrorMessage } from '../../utils/errors'; import { FileCheck2, Plus, @@ -12,6 +13,7 @@ import { CheckCircle, X, FileQuestion, + Hourglass, } from 'lucide-react'; import { Link } from 'react-router-dom'; import { useI18n } from '../../i18n'; @@ -20,8 +22,11 @@ export const ExamList: React.FC = () => { const [exams, setExams] = useState([]); const [subjects, setSubjects] = useState([]); const [classrooms, setClassrooms] = useState([]); + // Only an admin picks the owning teacher; a teacher always owns the exams they create. + const [teachers, setTeachers] = useState([]); const [loading, setLoading] = useState(true); const [modalOpen, setModalOpen] = useState(false); + const [formError, setFormError] = useState(null); const { user } = useAuthStore(); const { t, locale } = useI18n(); @@ -38,6 +43,7 @@ export const ExamList: React.FC = () => { title: '', subjectId: '', classroomId: '', + teacherId: '', type: 'quiz', durationMinutes: 60, passingScore: 75, @@ -61,6 +67,10 @@ export const ExamList: React.FC = () => { setExams(eRes.data.data); setSubjects(sRes.data.data); setClassrooms(cRes.data.data); + if (isAdmin) { + const tRes = await api.get>('/teachers'); + setTeachers(tRes.data.data); + } } catch (e) { console.error(e); } finally { @@ -72,13 +82,38 @@ export const ExamList: React.FC = () => { loadData(); }, []); + /** The same schedule rules the server enforces, checked first so the form can say what to fix. */ + const scheduleError = (): string | null => { + const start = new Date(form.startAt).getTime(); + const end = new Date(form.endAt).getTime(); + if (Number.isNaN(start) || Number.isNaN(end)) return null; // left to the required fields + if (end <= start) return t('examList.endBeforeStart'); + const windowMinutes = Math.floor((end - start) / 60000); + if (Number(form.durationMinutes) > windowMinutes) { + return t('examList.durationTooLong', { duration: Number(form.durationMinutes), window: windowMinutes }); + } + return null; + }; + + const openCreateModal = () => { + setFormError(null); + setModalOpen(true); + }; + const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); + const invalidSchedule = scheduleError(); + if (invalidSchedule) { + setFormError(invalidSchedule); + return; + } + setFormError(null); try { const payload = { title: form.title, subjectId: Number(form.subjectId), classroomId: Number(form.classroomId), + teacherId: isAdmin && form.teacherId ? Number(form.teacherId) : undefined, type: form.type, durationMinutes: Number(form.durationMinutes), passingScore: Number(form.passingScore), @@ -95,8 +130,8 @@ export const ExamList: React.FC = () => { await api.post('/exams', payload); setModalOpen(false); loadData(); - } catch (err: any) { - alert(err.response?.data?.message || t('examList.createFailed')); + } catch (err) { + setFormError(apiErrorMessage(err, t('examList.createFailed'))); } }; @@ -116,7 +151,7 @@ export const ExamList: React.FC = () => { {(isAdmin || isTeacher) && ( + + )} + {/* Proctoring Warning Banner */} {violations > 0 && (
@@ -297,14 +527,21 @@ export const ExamRunner: React.FC = () => { {t('examRunner.questionOf', { current: currentIndex + 1, total: session.questions.length })}
- {saving ? ( - {t('examRunner.saving')} - ) : ( + {currentUnsaved ? ( + saveState === 'error' ? ( + + + {t('examRunner.notSaved')} + + ) : ( + {t('examRunner.saving')} + ) + ) : isAnswered(currentQ.id) ? ( {t('examRunner.saved')} - )} + ) : null}
@@ -323,7 +560,7 @@ export const ExamRunner: React.FC = () => {