// [CRUCIBLE-SEED]
// category: xss
// severity: high
// language: java
// expected: Stored XSS — user-supplied comment written to DB then reflected without escaping

import java.io.*;
import java.sql.*;
import javax.servlet.http.*;

public class CommentServlet extends HttpServlet {
    private Connection conn;

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException, SQLException {
        String comment  = req.getParameter("comment");
        String username = req.getParameter("username");
        // Store raw (vulnerable: no sanitization before storage)
        PreparedStatement ps = conn.prepareStatement(
            "INSERT INTO comments(username, body) VALUES (?, ?)");
        ps.setString(1, username);
        ps.setString(2, comment);
        ps.executeUpdate();
        resp.sendRedirect("/comments");
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException, SQLException {
        PrintWriter out = resp.getWriter();
        ResultSet rs = conn.createStatement().executeQuery(
            "SELECT username, body FROM comments ORDER BY id DESC LIMIT 20");
        while (rs.next()) {
            // Vulnerable: stored comment reflected without escaping
            out.println("<div><b>" + rs.getString("username") + "</b>: "
                + rs.getString("body") + "</div>");
        }
    }
}
