Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
7 changes: 4 additions & 3 deletions README.id.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ Platform web **E-Learning** dan **Computer Based Test (CBT)** berfitur lengkap u
| **Dashboard** | Statistik mengajar, jadwal ujian CBT mendatang, tugas aktif, dan aktivitas terkini |
| **Materi Belajar** | CRUD + 5 tipe konten (Dokumen, Video, Teks, Link, Audio) + pelacakan pembaca siswa |
| **Tugas Siswa** | CRUD + tenggat waktu + petunjuk pengerjaan + penilaian submission & umpan balik |
| **Ujian CBT** | CRUD + durasi timer + KKM (passing grade) + acak soal/opsi + izin remidi (retry) |
| **Ujian CBT** | CRUD + durasi timer + KKM (passing grade) + acak soal/opsi + izin remidi (retry) + tampilkan atau sembunyikan nilai dari siswa |
| **Bank & Editor Soal** | Pilihan Ganda (A-E), Benar/Salah, Esai + bobot poin + **📥 Import Soal Excel** |
| **Monitor Telemetri** | Pemantauan progres pengerjaan kandidat, indikator soal terjawab, dan deteksi pelanggaran anti-cheat real-time |
| **Cetak Kartu Ujian** | Cetak kartu resmi peserta ujian CBT yang siap digunakan lengkap dengan barcode NIS |
Expand Down Expand Up @@ -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. |
Expand Down Expand Up @@ -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
Expand Down
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ A full-featured web-based **E-Learning** and **Computer Based Test (CBT)** platf
| **Dashboard** | Teaching metrics, scheduled examinations, active assignments, and recent activity |
| **Learning Materials** | CRUD + multi-type content (Document, Video, Text, Link, Audio) + student view tracking |
| **Assignments** | CRUD + deadline dates + instructions + submission grading with feedback |
| **CBT Examinations** | CRUD + duration timer + passing grade (KKM) + randomize questions/options + retry toggles |
| **CBT Examinations** | CRUD + duration timer + passing grade (KKM) + randomize questions/options + retry toggles + show or hide the score from students |
| **Question Builder** | Multiple Choice (A-E), True/False, Essay + points allocation + **📥 Excel Import** |
| **Live Telemetry Monitor** | Real-time WebSocket candidate status, question progress bar, and anti-cheat flag alerts |
| **Exam Hall Tickets** | Print ready-to-use official CBT student candidate cards with NIS barcodes |
Expand Down Expand Up @@ -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. |
Expand Down Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions backend/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

Expand Down Expand Up @@ -73,12 +74,19 @@ public ResponseEntity<ApiResponse<Map<String, Object>>> submitAttempt(
@PathVariable Long attemptId,
@AuthenticationPrincipal UserPrincipal principal) {
ExamAttempt attempt = examRunnerService.submitAttempt(attemptId, principal);
return ResponseEntity.ok(ApiResponse.success(Map.of(
"attemptId", attempt.getId(),
"status", attempt.getStatus(),
"score", attempt.getScore() != null ? attempt.getScore() : 0,
"passed", attempt.getPassed() != null ? attempt.getPassed() : false
), "Exam submitted successfully"));

Map<String, Object> result = new LinkedHashMap<>();
result.put("attemptId", attempt.getId());
result.put("status", attempt.getStatus());
if (examRunnerService.isResultVisibleToStudent(attempt.getId())) {
result.put("score", attempt.getScore() != null ? attempt.getScore() : 0);
result.put("passed", attempt.getPassed() != null ? attempt.getPassed() : false);
result.put("resultHidden", false);
} else {
// The exam does not show results: the student only learns that the attempt was received.
result.put("resultHidden", true);
}
return ResponseEntity.ok(ApiResponse.success(result, "Exam submitted successfully"));
}

@PostMapping("/attempts/{attemptId}/answers/{answerId}/grade-essay")
Expand Down
36 changes: 36 additions & 0 deletions backend/src/main/java/com/elearning/modules/exam/dto/ExamDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,18 @@

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;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;

Expand All @@ -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;

Expand All @@ -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;

Expand All @@ -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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,17 @@ public List<ExamMonitorResponse> getExamMonitor(Long examId, UserPrincipal princ
}).collect(Collectors.toList());
}

/**
* Whether the student may see the score of this attempt: the exam's "show result" setting. The teacher
* can turn it on later to release the results. An unknown attempt shows nothing.
*/
@Transactional(readOnly = true)
public boolean isResultVisibleToStudent(Long attemptId) {
return attemptRepository.findById(attemptId)
.map(attempt -> attempt.getExamination().isShowResult())
.orElse(false);
}

private ExamAttempt createNewAttempt(Examination exam, Student student, int attemptNumber) {
ExamAttempt attempt = ExamAttempt.builder()
.examination(exam)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()));
Expand Down Expand Up @@ -396,6 +395,22 @@ public Map<String, Object> 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())) {
Expand All @@ -414,8 +429,11 @@ private ExamResponse mapToResponse(Examination e, Long studentId) {
if (attempt.isPresent()) {
ExamAttempt att = attempt.get();
attemptStatus = att.getStatus().name();
studentScore = att.getScore();
studentPassed = att.getPassed();
// The score stays hidden from the student until the exam shows results.
if (e.isShowResult()) {
studentScore = att.getScore();
studentPassed = att.getPassed();
}
currentAttemptId = att.getId();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ public GradeReportResponse getStudentGradeReport(UserPrincipal principal) {

List<Subject> subjects = subjectRepository.findAll();
List<ExamAttempt> attempts = attemptRepository.findByStudentId(student.getId()).stream()
.filter(a -> a.getStatus() == AttemptStatus.completed)
// Exams that do not show results are left out, or their scores would leak through the averages.
.filter(a -> a.getStatus() == AttemptStatus.completed && a.getExamination().isShowResult())
.collect(Collectors.toList());

List<AssignmentSubmission> submissions = submissionRepository.findAll().stream()
Expand Down
Loading
Loading