Runway 1.0.1
This commit is contained in:
1 parent
dcf819146b
commit
ce217fc952
259 files changed
+22226
-206
No files matched your search
@@ -0,0 +1,69 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import java.util.List;
|
||||
import mx.quest.runway.spi.service.SitePages;
|
||||
|
||||
/**
|
||||
* Read-only status model for the console surfaces (dashboard card + admin fragment), read by template bean name,
|
||||
* e.g. {@code ${@contactAdminModel.count(tenantSiteId)}} and iterated for the recent-submissions table. Also
|
||||
* exposes the SMTP <b>readiness</b> ({@link #smtpConfigured(String)}) and the test-action URL so the admin
|
||||
* fragment can show "Configured / Not configured" and offer the operator-only SMTP self-test, plus the
|
||||
* ready-made-page <b>install status</b> ({@link #pageInstalled(String)} / {@link #pagePath(String)}) — read
|
||||
* fresh from the kernel's {@link SitePages#pathOf} so a moved/renamed page reports its current path. Gated in the console
|
||||
* by the plugin's {@code settings} control point.
|
||||
*/
|
||||
public class ContactAdminModel {
|
||||
|
||||
private static final int RECENT = 20;
|
||||
|
||||
private final ContactStore store;
|
||||
private final ContactMailer mailer;
|
||||
private final SitePages pages;
|
||||
|
||||
public ContactAdminModel(ContactStore store, ContactMailer mailer, SitePages pages) {
|
||||
this.store = store;
|
||||
this.mailer = mailer;
|
||||
this.pages = pages;
|
||||
}
|
||||
|
||||
/** Total stored submissions for the site. */
|
||||
public int count(String siteId) {
|
||||
return store.count(siteId);
|
||||
}
|
||||
|
||||
/** The most recent submissions (newest first) for the admin listing. */
|
||||
public List<ContactSubmission> recent(String siteId) {
|
||||
return store.recent(siteId, RECENT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this site has a usable SMTP relay (a non-blank host AND recipient). When false, submissions are
|
||||
* stored only — the readiness badge shows "Not configured" and no email is sent.
|
||||
*/
|
||||
public boolean smtpConfigured(String siteId) {
|
||||
return mailer.settingsFor(siteId).isConfigured();
|
||||
}
|
||||
|
||||
/** The recipient address configured for this site (for display), or an empty string when none is set. */
|
||||
public String recipient(String siteId) {
|
||||
return mailer.settingsFor(siteId).to();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this site already has the ready-made contact page (the one {@code /contact/install-page} seeds).
|
||||
* Read fresh through {@link SitePages#pathOf} by the installer's stable slug, in any state (a draft or a page
|
||||
* waiting for review counts), so it stays true even after the operator moves or renames the page (the slug is
|
||||
* the page's identity; only its path changes).
|
||||
*/
|
||||
public boolean pageInstalled(String siteId) {
|
||||
return pages.pathOf(siteId, ContactEndpoint.INSTALLED_PAGE_SLUG).isPresent();
|
||||
}
|
||||
|
||||
/**
|
||||
* The current URL path of the installed contact page (e.g. {@code /contact}, or wherever the operator moved
|
||||
* it), or an empty string when it is not installed. Read live so the console always shows the real location.
|
||||
*/
|
||||
public String pagePath(String siteId) {
|
||||
return pages.pathOf(siteId, ContactEndpoint.INSTALLED_PAGE_SLUG).orElse("");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import mx.quest.runway.spi.CaptchaService;
|
||||
import mx.quest.runway.spi.ContentWidget;
|
||||
import mx.quest.runway.spi.EndpointContributor;
|
||||
import mx.quest.runway.spi.service.AccessCheck;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.PluginSiteFiles;
|
||||
import mx.quest.runway.spi.service.SitePages;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* The plugin's {@code mainClass} — the single {@code @Configuration} registered into the host context before
|
||||
* refresh. Beans are wired EXPLICITLY (no {@code @ComponentScan}). The package {@code mx.quest.contact} lives
|
||||
* OUTSIDE {@code mx.quest.runway} so the host never double-scans it.
|
||||
*
|
||||
* <p><b>SPI only.</b> Everything this plugin needs from the kernel arrives as an SPI service (SPI 1.0.0):
|
||||
* {@link PluginSettings} (this plugin's per-site settings, and the SMTP password secret in clear) and
|
||||
* {@link PluginSiteFiles} (this plugin's per-site folder, where submissions are kept) are bound to this plugin by
|
||||
* the jar this class was loaded from; {@link Messages}, {@link AccessCheck}, {@link SitePages} and the
|
||||
* {@link CaptchaService} are kernel singletons. Nothing outside {@code mx.quest.runway.spi} is linked.
|
||||
*
|
||||
* <p>The {@link ContactWidget} ({@code ContentWidget}) and {@link ContactEndpoint} ({@code EndpointContributor})
|
||||
* are list-collected SPIs — plain {@code @Bean}s, NEVER {@code @Primary}. Every bean name starts with the plugin
|
||||
* id ({@code contact…}), the kernel's rule for a bean namespace plugins share. The email seam is
|
||||
* {@link MailTransport} ({@link JakartaMailTransport} in production, using the Jakarta Mail stack the KERNEL
|
||||
* bundles as a core capability).
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class ContactConfig {
|
||||
|
||||
@Bean
|
||||
public ContactStore contactStore(PluginSiteFiles files) {
|
||||
return new ContactStore(files);
|
||||
}
|
||||
|
||||
/** The production send seam — delegates to {@code jakarta.mail.Transport} (the kernel bundles Jakarta Mail). */
|
||||
@Bean
|
||||
public MailTransport contactMailTransport() {
|
||||
return new JakartaMailTransport();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ContactMailer contactMailer(PluginSettings settings, MailTransport transport) {
|
||||
return new ContactMailer(settings, transport);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ContentWidget contactWidget(PluginSettings settings, Messages messages, CaptchaService captcha) {
|
||||
return new ContactWidget(settings, messages, captcha);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public EndpointContributor contactEndpoint(ContactStore store, ContactMailer mailer, PluginSettings settings,
|
||||
Messages messages, AccessCheck access, CaptchaService captcha,
|
||||
SitePages pages) {
|
||||
return new ContactEndpoint(store, mailer, settings, messages, access, captcha, pages);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ContactAdminModel contactAdminModel(ContactStore store, ContactMailer mailer, SitePages pages) {
|
||||
return new ContactAdminModel(store, mailer, pages);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.CaptchaService;
|
||||
import mx.quest.runway.spi.EndpointContributor;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.CaptchaWidget;
|
||||
import mx.quest.runway.spi.model.Finding;
|
||||
import mx.quest.runway.spi.model.InstallResult;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import mx.quest.runway.spi.model.Route;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
import mx.quest.runway.spi.model.StarterPage;
|
||||
import mx.quest.runway.spi.model.SurfacePosture;
|
||||
import mx.quest.runway.spi.service.AccessCheck;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.SitePages;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* The contact plugin's tiny request-handling surface — it owns <b>no visible page</b>. The contact form lives on a
|
||||
* normal, editable site page (via the {@link ContactWidget} anchor; the operator installs the ready-made one from
|
||||
* the plugin settings). This endpoint only:
|
||||
* <ul>
|
||||
* <li><b>{@code POST /contact/submit}</b> — an <b>anonymous</b> route ({@code Route.anonymousPost}): the kernel
|
||||
* exempts exactly this method and path from CSRF (a public form on a cacheable page has no session token),
|
||||
* hands it only {@code application/x-www-form-urlencoded} bodies and runs it with no principal. The fields
|
||||
* are read from the <b>form body only</b> — a field put in the query string is ignored, so a visitor's
|
||||
* personal data never has to travel in a URL. It stores + emails the submission, then answers {@code 303}
|
||||
* back to the page the form lives on (the {@code return} field, or the {@code Referer}) with a
|
||||
* {@code ?contact=sent|invalid|captcha|queued} flag the widget re-renders the outcome from. The abuse guards
|
||||
* stay in front of the store: a filled honeypot fakes success (stores/sends nothing), an invalid submission
|
||||
* or an unsolved CAPTCHA (verified with the kernel-gated {@code clientIp}) redirects with an error flag, and
|
||||
* the platform's per-address rate limit (the protection plugin's edge guard) applies to this path like any
|
||||
* other. A valid submission is <b>stored first</b> ({@link ContactStore}) and then <b>emailed</b> over the
|
||||
* site's own relay, so a send failure never loses the message. Any other method on this path is a 404.</li>
|
||||
* <li><b>{@code POST /contact/install-page}</b> — operator-gated ({@code contact|settings}): installs a real,
|
||||
* editable page carrying the contact-form widget through {@link SitePages#install}, which respects the
|
||||
* site's editorial level and never overwrites; the operator is told which of the outcomes happened.</li>
|
||||
* <li><b>{@code POST /contact/smtp-test}</b> — operator-gated SMTP self-test; an optional {@code to} field of the
|
||||
* form body overrides the recipient.</li>
|
||||
* </ul>
|
||||
* The two operator actions change something (a page is created, an email is sent), so they are <b>ordinary,
|
||||
* non-anonymous {@code POST} routes</b>: the kernel's tenant chain demands the console session's CSRF token on them
|
||||
* (the admin fragment's forms carry it), which is what stops another web site from triggering them through a
|
||||
* signed-in operator's browser with a link or an {@code <img>}. A {@code GET} on either path matches no route and
|
||||
* changes nothing (the kernel answers 404); {@link #handle} refuses any other method too, as a second line.
|
||||
* Neither action reads the query string.
|
||||
* Honors the per-site {@code enabled} setting (disabled ⇒ a submission is a no-op 404). All redirect targets are
|
||||
* validated as same-origin local paths.
|
||||
*/
|
||||
public class ContactEndpoint implements EndpointContributor {
|
||||
|
||||
/** The anonymous form-submission route; the {@link ContactForm} posts here. */
|
||||
static final String SUBMIT_PATH = "/contact/submit";
|
||||
static final String INSTALL_PATH = "/contact/install-page";
|
||||
static final String SMTP_TEST_PATH = "/contact/smtp-test";
|
||||
/** The slug/path the ready-made contact page is installed at (then owned + movable by the operator). */
|
||||
static final String INSTALLED_PAGE_SLUG = "contact";
|
||||
static final String SETTINGS_PERMISSION = "contact|settings";
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ContactEndpoint.class);
|
||||
|
||||
private final ContactStore store;
|
||||
private final ContactMailer mailer;
|
||||
private final PluginSettings settings;
|
||||
private final Messages messages;
|
||||
private final AccessCheck access;
|
||||
private final CaptchaService captcha;
|
||||
private final SitePages pages;
|
||||
|
||||
public ContactEndpoint(ContactStore store, ContactMailer mailer, PluginSettings settings, Messages messages,
|
||||
AccessCheck access, CaptchaService captcha, SitePages pages) {
|
||||
this.store = store;
|
||||
this.mailer = mailer;
|
||||
this.settings = settings;
|
||||
this.messages = messages;
|
||||
this.access = access;
|
||||
this.captcha = captcha;
|
||||
this.pages = pages;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "contact/form";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Route> routes() {
|
||||
// No public /contact PAGE — the form lives on a normal editable page. These are the submit handler + the
|
||||
// two operator actions; all safeDefault (noindex/no-store), never advertised or crawled. The operator
|
||||
// actions are POST and NOT anonymous: they change state, so the kernel's CSRF check must apply to them.
|
||||
return List.of(
|
||||
Route.anonymousPost(SUBMIT_PATH, SurfacePosture.safeDefault()),
|
||||
new Route("POST", INSTALL_PATH, Realm.TENANT, SurfacePosture.safeDefault()),
|
||||
new Route("POST", SMTP_TEST_PATH, Realm.TENANT, SurfacePosture.safeDefault()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public RouteResponse handle(RouteRequest req) {
|
||||
// Every route here is POST-only; the kernel dispatches by method + path, and this check is the second line.
|
||||
if (!"POST".equalsIgnoreCase(req.method())) {
|
||||
return RouteResponse.notFound();
|
||||
}
|
||||
return switch (req.path()) {
|
||||
case SUBMIT_PATH -> handleSubmit(req);
|
||||
case INSTALL_PATH -> handleInstallPage(req);
|
||||
case SMTP_TEST_PATH -> handleSmtpTest(req);
|
||||
default -> RouteResponse.notFound();
|
||||
};
|
||||
}
|
||||
|
||||
/** Stores + emails a submission, then redirects back to the form's page with an outcome flag. */
|
||||
private RouteResponse handleSubmit(RouteRequest req) {
|
||||
String siteId = req.site().id();
|
||||
if (!settings.site(siteId).bool("enabled", true)) {
|
||||
return RouteResponse.notFound();
|
||||
}
|
||||
String back = resolveReturn(req);
|
||||
String name = formField(req, "name");
|
||||
String email = formField(req, "email");
|
||||
String message = formField(req, "message");
|
||||
String honeypot = formField(req, "website");
|
||||
|
||||
if (!honeypot.isBlank()) {
|
||||
return redirect(back, "sent"); // a bot filled the trap — fake success, store/send nothing
|
||||
}
|
||||
if (message.isBlank() || !isEmail(email)) {
|
||||
return redirect(back, "invalid");
|
||||
}
|
||||
CaptchaWidget widget = captcha.widgetForSite(siteId);
|
||||
if (widget.active() && !captcha.verify(siteId, formField(req, widget.tokenField()), req.clientIp())) {
|
||||
return redirect(back, "captcha");
|
||||
}
|
||||
// Belt-and-suspenders: STORE first (never lose a message), THEN email over the site's relay.
|
||||
store.add(siteId, name, email, message, System.currentTimeMillis());
|
||||
MailSendResult sent = mailer.send(siteId, req.site().displayName(), name, email, message);
|
||||
// "queued" ⇒ stored but the configured relay failed (an unobtrusive "delivery delayed" note); NOT_CONFIGURED
|
||||
// is silent (the site simply stores messages) — so only a real relay failure downgrades to "queued".
|
||||
boolean delayed = sent != null && !sent.wasSent()
|
||||
&& sent.status() != MailSendResult.Status.NOT_CONFIGURED;
|
||||
return redirect(back, delayed ? "queued" : "sent");
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs the ready-made, editable contact page (idempotent). {@code POST} only, CSRF-checked by the kernel;
|
||||
* operator-gated, failing closed with a 404.
|
||||
*/
|
||||
private RouteResponse handleInstallPage(RouteRequest req) {
|
||||
if (!access.may(SETTINGS_PERMISSION)) {
|
||||
return RouteResponse.notFound();
|
||||
}
|
||||
String siteId = req.site().id();
|
||||
Locale siteDefault = req.site().defaultLocale();
|
||||
String title = messages.site(siteId, siteDefault, "contact.page.title", "Contact");
|
||||
StarterPage page = new StarterPage(INSTALLED_PAGE_SLUG, "/" + INSTALLED_PAGE_SLUG,
|
||||
Map.of(siteDefault.getLanguage(), title), installedPageHtml(title), installedPageLogic(), false);
|
||||
InstallResult result;
|
||||
try {
|
||||
result = pages.install(siteId, page);
|
||||
} catch (RuntimeException e) {
|
||||
// IllegalStateException: a path another page serves, an unknown site, a failed write (no stray draft
|
||||
// is left behind). Anything else is equally "not installed" to the operator.
|
||||
log.warn("contact page install failed for site {}: {}", siteId, e.toString());
|
||||
return RouteResponse.text(500, console("contact.page.failed", "Could not install the contact page."));
|
||||
}
|
||||
return RouteResponse.text(200, describe(result));
|
||||
}
|
||||
|
||||
/** The operator's words for each install outcome; an outcome added in a later SPI MINOR gets a neutral line. */
|
||||
private String describe(InstallResult result) {
|
||||
String path = result.path();
|
||||
return switch (result.outcome()) {
|
||||
case PUBLISHED -> console("contact.page.installed", "Contact page installed at") + " " + path;
|
||||
case PENDING_REVIEW -> console("contact.page.pending",
|
||||
"The contact page was created and is waiting in the review queue:") + " " + path;
|
||||
case DRAFT_BLOCKED -> {
|
||||
StringBuilder text = new StringBuilder(console("contact.page.blocked",
|
||||
"The contact page was created as a draft because the quality checks blocked publishing; "
|
||||
+ "fix it in the page editor:")).append(' ').append(path);
|
||||
for (Finding finding : result.blocking()) {
|
||||
text.append("\n- ").append(finding.code()).append(": ").append(finding.message());
|
||||
}
|
||||
yield text.toString();
|
||||
}
|
||||
case ALREADY_EXISTS -> console("contact.page.exists", "A contact page already exists at") + " " + path;
|
||||
default -> console("contact.page.other", "The contact page install finished:") + " "
|
||||
+ result.outcome() + " " + path;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The operator-only SMTP self-test ({@code POST}, CSRF-checked by the kernel) — fails closed unless the caller
|
||||
* holds {@code contact|settings}.
|
||||
*/
|
||||
private RouteResponse handleSmtpTest(RouteRequest req) {
|
||||
if (!access.may(SETTINGS_PERMISSION)) {
|
||||
return RouteResponse.notFound();
|
||||
}
|
||||
// The override recipient comes from the form body only — never the query string.
|
||||
MailSendResult result = mailer.sendTest(req.site().id(), req.site().displayName(), formField(req, "to"));
|
||||
String text = switch (result.status()) {
|
||||
case SENT -> console("contact.test.ok", "Test message sent.");
|
||||
case NOT_CONFIGURED -> console("contact.test.notConfigured", "No SMTP relay is configured for this site.");
|
||||
case PROVIDER_MISSING -> console("contact.test.providerMissing",
|
||||
"Mail libraries are not available on the server.");
|
||||
case FAILED -> console("contact.test.failed", "Test message failed:") + " " + result.detail();
|
||||
};
|
||||
return RouteResponse.text(result.wasSent() ? 200 : 502, text);
|
||||
}
|
||||
|
||||
/** The page the form lives on: the same-origin {@code return} field, else the {@code Referer} path, else "/". */
|
||||
private static String resolveReturn(RouteRequest req) {
|
||||
String fromField = safeLocalPath(formField(req, "return"));
|
||||
if (fromField != null) {
|
||||
return fromField;
|
||||
}
|
||||
String fromReferer = safeLocalPath(refererPath(req.headers().get("referer")));
|
||||
return fromReferer != null ? fromReferer : "/";
|
||||
}
|
||||
|
||||
/** The path (with query stripped) of a Referer, or {@code null} when absent. */
|
||||
private static String refererPath(String referer) {
|
||||
if (referer == null || referer.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
int scheme = referer.indexOf("://");
|
||||
String path = referer;
|
||||
if (scheme >= 0) {
|
||||
int slash = referer.indexOf('/', scheme + 3);
|
||||
path = slash < 0 ? "/" : referer.substring(slash);
|
||||
}
|
||||
int q = path.indexOf('?');
|
||||
return q < 0 ? path : path.substring(0, q);
|
||||
}
|
||||
|
||||
/**
|
||||
* A {@code 303 See Other} back to {@code path} carrying only the outcome flag (never a submitted value); the
|
||||
* browser follows it with a GET and the widget on that page re-renders from the flag (post/redirect/get, so a
|
||||
* reload never resubmits).
|
||||
*/
|
||||
private static RouteResponse redirect(String path, String outcome) {
|
||||
String location = path + (path.contains("?") ? "&" : "?") + "contact=" + outcome;
|
||||
return new RouteResponse(303, Map.of("Location", location), new byte[0]);
|
||||
}
|
||||
|
||||
/** Reduces a candidate to a safe same-origin path (a single leading "/", no scheme/backslash/space/control). */
|
||||
private static String safeLocalPath(String p) {
|
||||
if (p == null || p.isBlank() || !p.startsWith("/") || p.startsWith("//") || p.contains("://")) {
|
||||
return null;
|
||||
}
|
||||
for (int i = 0; i < p.length(); i++) {
|
||||
char c = p.charAt(i);
|
||||
if (c < 0x20 || c == '\\' || c == ' ') {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
/**
|
||||
* The body of the installed page: chrome seams ({@code head}/{@code #site-header}/{@code #site-footer}, filled
|
||||
* from the master by {@link #installedPageLogic()}) and a {@code #content} carrying the contact-form widget
|
||||
* anchor. The anchor bears both an {@code id} and {@code data-widget="contact/form"} on one element (the
|
||||
* widget-binding contract), so the host renders the form in place.
|
||||
*/
|
||||
private static String installedPageHtml(String title) {
|
||||
String t = Html.escape(title);
|
||||
return "<!DOCTYPE html>\n<html>\n<head><title>" + t + "</title></head>\n<body>\n"
|
||||
+ "<header id=\"site-header\"></header>\n<main id=\"content\">\n"
|
||||
+ " <h1 id=\"contact-page-title\">" + t + "</h1>\n"
|
||||
+ " <div id=\"contact-form\" data-widget=\"contact/form\"></div>\n"
|
||||
+ "</main>\n<footer id=\"site-footer\"></footer>\n</body>\n</html>\n";
|
||||
}
|
||||
|
||||
/** The decoupled logic of the installed page: pulls the master chrome via {@code ${master}} (never a literal). */
|
||||
private static String installedPageLogic() {
|
||||
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<thlogic>\n"
|
||||
+ " <attr sel=\"head\" th:replace=\"~{${master} :: head}\"/>\n"
|
||||
+ " <attr sel=\"#site-header\" th:replace=\"~{${master} :: #site-header}\"/>\n"
|
||||
+ " <attr sel=\"#site-footer\" th:replace=\"~{${master} :: #site-footer}\"/>\n"
|
||||
+ " <attr sel=\"#contact-page-title\" th:text=\"${pageTitle}\"/>\n"
|
||||
+ "</thlogic>\n";
|
||||
}
|
||||
|
||||
private static boolean isEmail(String value) {
|
||||
int at = value.indexOf('@');
|
||||
return at > 0 && at < value.length() - 1 && value.indexOf('.', at) > at;
|
||||
}
|
||||
|
||||
/** A field of the form BODY (never the query string), stripped; "" when absent. */
|
||||
private static String formField(RouteRequest req, String name) {
|
||||
List<String> values = req.form().get(name);
|
||||
return (values == null || values.isEmpty()) ? "" : values.get(0).strip();
|
||||
}
|
||||
|
||||
private String console(String code, String fallback) {
|
||||
return messages.console(code, fallback);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("endpoint.tenant", "contact.form");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import java.util.Locale;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
|
||||
/**
|
||||
* Builds the contact-form markup the {@link ContactWidget} renders inline on a page. The form <b>POSTs</b> an
|
||||
* {@code application/x-www-form-urlencoded} body to {@value ContactEndpoint#SUBMIT_PATH}, a route the
|
||||
* {@link ContactEndpoint} declares <b>anonymous</b> ({@code Route.anonymousPost}): the kernel exempts exactly that
|
||||
* method and path from CSRF, because a public form on a cacheable page cannot carry a per-session token. So the
|
||||
* visitor's name, email and message travel in the request body — never in a URL, browser history, a
|
||||
* {@code Referer} or a proxy log. A hidden honeypot field ({@code website}) catches naive bots; {@code captchaHtml}
|
||||
* (when non-empty) adds the site's CAPTCHA challenge from the platform's {@code CaptchaService} — trusted,
|
||||
* pre-rendered markup. Every label is looked up with {@link Messages#site} for the visitor's locale; every value
|
||||
* that came from a request or a setting is HTML-escaped.
|
||||
*/
|
||||
final class ContactForm {
|
||||
|
||||
private ContactForm() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the contact form. It submits to the anonymous {@code POST} handler, which stores + emails the message
|
||||
* and answers {@code 303} back to {@code returnPath} with a {@code ?contact=sent|invalid|captcha|queued} flag —
|
||||
* so the visible page stays a normal, editable site page (the widget re-renders the outcome from that flag).
|
||||
*/
|
||||
static String render(Messages messages, String siteId, Locale locale, String error, String captchaHtml,
|
||||
String returnPath) {
|
||||
String nameLbl = messages.site(siteId, locale, "contact.form.name", "Name");
|
||||
String emailLbl = messages.site(siteId, locale, "contact.form.email", "Email");
|
||||
String messageLbl = messages.site(siteId, locale, "contact.form.message", "Message");
|
||||
String submitLbl = messages.site(siteId, locale, "contact.form.submit", "Send");
|
||||
|
||||
StringBuilder b = new StringBuilder(768);
|
||||
b.append("<link rel=\"stylesheet\" href=\"/__plugin/contact/static/contact.css\">")
|
||||
.append("<form class=\"rw-contact\" method=\"post\" action=\"").append(ContactEndpoint.SUBMIT_PATH)
|
||||
.append("\" enctype=\"application/x-www-form-urlencoded\">")
|
||||
// Where the submit handler redirects back to (this page); validated server-side as a local path.
|
||||
.append("<input type=\"hidden\" name=\"return\" value=\"").append(Html.escape(returnPath)).append("\">");
|
||||
if (error != null && !error.isBlank()) {
|
||||
b.append("<p class=\"rw-contact-error\">").append(Html.escape(error)).append("</p>");
|
||||
}
|
||||
b.append(field("text", "name", nameLbl))
|
||||
.append(field("email", "email", emailLbl))
|
||||
.append("<label class=\"rw-contact-label\">").append(Html.escape(messageLbl))
|
||||
.append("<textarea class=\"rw-contact-input\" name=\"message\" rows=\"5\" required></textarea></label>")
|
||||
// Honeypot: hidden from humans, left blank; a bot that fills it is dropped as spam.
|
||||
.append("<div class=\"rw-contact-hp\" aria-hidden=\"true\">")
|
||||
.append("<label>Website<input type=\"text\" name=\"website\" tabindex=\"-1\" autocomplete=\"off\"></label></div>");
|
||||
// Real CAPTCHA challenge (only when the site configured one — trusted markup from the platform seam).
|
||||
if (captchaHtml != null && !captchaHtml.isBlank()) {
|
||||
b.append("<div class=\"rw-contact-captcha\">").append(captchaHtml).append("</div>");
|
||||
}
|
||||
b.append("<button class=\"rw-contact-submit\" type=\"submit\">").append(Html.escape(submitLbl))
|
||||
.append("</button></form>");
|
||||
return b.toString();
|
||||
}
|
||||
|
||||
private static String field(String type, String fieldName, String label) {
|
||||
return "<label class=\"rw-contact-label\">" + Html.escape(label)
|
||||
+ "<input class=\"rw-contact-input\" type=\"" + type + "\" name=\"" + fieldName + "\" required></label>";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import jakarta.mail.Authenticator;
|
||||
import jakarta.mail.Message;
|
||||
import jakarta.mail.MessagingException;
|
||||
import jakarta.mail.PasswordAuthentication;
|
||||
import jakarta.mail.Session;
|
||||
import jakarta.mail.internet.InternetAddress;
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Properties;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Builds and sends the notification email for a contact submission over the <b>site's own</b> SMTP relay, then
|
||||
* reports the outcome as a {@link MailSendResult}. It NEVER stores anything and NEVER throws for an operational
|
||||
* failure — the {@link ContactEndpoint} always stores the submission first, so a relay problem degrades to a
|
||||
* reported (not lost) message.
|
||||
*
|
||||
* <p><b>Isolation.</b> The relay coordinates come only from {@link SmtpSettings#from} over this site's settings
|
||||
* ({@link PluginSettings}, bound by the kernel to this plugin), so a site sends exclusively through the relay it
|
||||
* configured (a tenant can never send through another's). The password is the site's {@code smtpPassword} secret,
|
||||
* read in clear with {@link PluginSettings#secret} at send time and never kept.
|
||||
*
|
||||
* <p><b>Degrade-don't-crash.</b> Three non-fatal outcomes are reported rather than thrown:
|
||||
* <ul>
|
||||
* <li>{@link MailSendResult#notConfigured()} — no host/recipient set (nothing to send to);</li>
|
||||
* <li>{@link MailSendResult#providerMissing()} — the Jakarta Mail classes are not on the classloader (a
|
||||
* {@link NoClassDefFoundError}/{@link LinkageError} at the seam). The kernel now bundles Jakarta Mail as a
|
||||
* core capability, so this is effectively unreachable; the guard is kept purely so a broken deployment can
|
||||
* never crash the request;</li>
|
||||
* <li>{@link MailSendResult#failed(String)} — a configured relay rejected the message or was unreachable.</li>
|
||||
* </ul>
|
||||
* The build/send seam is {@link MailTransport}, injected so tests exercise the full MIME build against a mock
|
||||
* with no socket opened.
|
||||
*/
|
||||
public class ContactMailer {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ContactMailer.class);
|
||||
private static final int MAX_SUBJECT_SOURCE = 120;
|
||||
/** The declared {@code type: secret} key of the SMTP password (plugin.yml). */
|
||||
static final String PASSWORD_KEY = "smtpPassword";
|
||||
|
||||
private final PluginSettings settings;
|
||||
private final MailTransport transport;
|
||||
|
||||
public ContactMailer(PluginSettings settings, MailTransport transport) {
|
||||
this.settings = settings;
|
||||
this.transport = transport;
|
||||
}
|
||||
|
||||
/** This site's current SMTP settings (the secret password in clear). Used by the send and the readiness badge. */
|
||||
public SmtpSettings settingsFor(String siteId) {
|
||||
return SmtpSettings.from(settings.site(siteId), settings.secret(siteId, PASSWORD_KEY));
|
||||
}
|
||||
|
||||
/**
|
||||
* Emails a stored submission's contents to the site's recipient. Never throws for an operational failure —
|
||||
* the outcome is always a {@link MailSendResult}.
|
||||
*
|
||||
* @param siteId the bound site (its own relay is used)
|
||||
* @param displayName the site's display name (for the subject / body context)
|
||||
* @param name the submitter's name
|
||||
* @param email the submitter's email (used as Reply-To so a reply reaches the visitor)
|
||||
* @param message the message body
|
||||
*/
|
||||
public MailSendResult send(String siteId, String displayName, String name, String email, String message) {
|
||||
SmtpSettings smtp = settingsFor(siteId);
|
||||
if (!smtp.isConfigured()) {
|
||||
return MailSendResult.notConfigured();
|
||||
}
|
||||
String subject = "[" + displayName + "] " + subjectExcerpt(name, message);
|
||||
String body = "New contact submission on " + displayName + "\n\n"
|
||||
+ "Name: " + orDash(name) + "\n"
|
||||
+ "Email: " + orDash(email) + "\n\n"
|
||||
+ message;
|
||||
return dispatch(smtp, smtp.effectiveFrom(), smtp.to(), subject, body, blankToNull(email));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a diagnostic test message to {@code testTo} over the site's relay, to verify the SMTP configuration
|
||||
* from the console. Same degrade contract as {@link #send} — the outcome is reported, never thrown.
|
||||
*/
|
||||
public MailSendResult sendTest(String siteId, String displayName, String testTo) {
|
||||
SmtpSettings smtp = settingsFor(siteId);
|
||||
// A test still needs a usable relay (host + a configured recipient) even though we override the To.
|
||||
if (!smtp.isConfigured()) {
|
||||
return MailSendResult.notConfigured();
|
||||
}
|
||||
String to = (testTo == null || testTo.isBlank()) ? smtp.to() : testTo.strip();
|
||||
String body = "This is a test message from the Runway contact plugin for site '" + displayName + "'.\n"
|
||||
+ "If you received it, the site's SMTP relay is configured correctly.";
|
||||
return dispatch(smtp, smtp.effectiveFrom(), to, "[" + displayName + "] SMTP test", body, null);
|
||||
}
|
||||
|
||||
private MailSendResult dispatch(SmtpSettings smtp, String from, String to, String subject, String body,
|
||||
String replyTo) {
|
||||
try {
|
||||
MimeMessage msg = build(smtp, from, to, subject, body, replyTo);
|
||||
transport.send(msg);
|
||||
return MailSendResult.sent();
|
||||
} catch (MessagingException e) {
|
||||
log.warn("contact mail send failed for relay {}: {}", smtp, e.toString());
|
||||
return MailSendResult.failed(rootMessage(e));
|
||||
} catch (LinkageError e) {
|
||||
// Jakarta Mail not on the classpath. The kernel bundles it as a core capability, so this is
|
||||
// effectively unreachable; guard it anyway so a broken deployment never crashes the request.
|
||||
log.warn("contact mail send skipped: Jakarta Mail unavailable on the classloader: {}", e.toString());
|
||||
return MailSendResult.providerMissing();
|
||||
}
|
||||
}
|
||||
|
||||
/** Builds the MIME message from the site's relay settings. Package-visible for direct MIME-shape testing. */
|
||||
MimeMessage build(SmtpSettings smtp, String from, String to, String subject, String body, String replyTo)
|
||||
throws MessagingException {
|
||||
Session session = session(smtp);
|
||||
MimeMessage msg = new MimeMessage(session);
|
||||
msg.setFrom(new InternetAddress(from));
|
||||
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
|
||||
if (replyTo != null) {
|
||||
try {
|
||||
msg.setReplyTo(InternetAddress.parse(replyTo, false));
|
||||
} catch (MessagingException badReplyTo) {
|
||||
// A visitor-supplied email that isn't a valid address must not block the notification.
|
||||
log.debug("ignoring invalid Reply-To '{}': {}", replyTo, badReplyTo.toString());
|
||||
}
|
||||
}
|
||||
msg.setSubject(subject, StandardCharsets.UTF_8.name());
|
||||
msg.setText(body, StandardCharsets.UTF_8.name());
|
||||
return msg;
|
||||
}
|
||||
|
||||
/**
|
||||
* A Jakarta Mail {@link Session} from the relay settings (host/port, TLS mode + auth).
|
||||
*
|
||||
* <p><b>The protocol is always {@code smtp}, even for implicit TLS.</b> We send with the static
|
||||
* {@link jakarta.mail.Transport#send(jakarta.mail.Message)}, which resolves an {@code rfc822} recipient to
|
||||
* the {@code smtp} transport via Jakarta Mail's address map — that lookup <b>ignores</b>
|
||||
* {@code mail.transport.protocol}. Selecting {@code smtps} therefore leaves {@code mail.smtp.host} unset, so
|
||||
* the send silently dials {@code localhost:25} and fails with "Connection refused". Implicit TLS (SMTPS, e.g.
|
||||
* port 465) must instead ride {@code mail.smtp.ssl.enable}; explicit TLS (e.g. 587) rides
|
||||
* {@code mail.smtp.starttls.enable}. Package-visible so a test can assert the resolved properties.
|
||||
*/
|
||||
static Session session(SmtpSettings smtp) {
|
||||
boolean ssl = smtp.ssl();
|
||||
Properties props = new Properties();
|
||||
props.put("mail.transport.protocol", "smtp");
|
||||
props.put("mail.smtp.host", smtp.host());
|
||||
props.put("mail.smtp.port", String.valueOf(smtp.port()));
|
||||
props.put("mail.smtp.auth", String.valueOf(smtp.auth()));
|
||||
if (ssl) {
|
||||
props.put("mail.smtp.ssl.enable", "true"); // implicit TLS on connect (SMTPS, e.g. 465)
|
||||
} else {
|
||||
props.put("mail.smtp.starttls.enable", String.valueOf(smtp.starttls())); // opportunistic STARTTLS (e.g. 587)
|
||||
}
|
||||
if (smtp.auth()) {
|
||||
Authenticator auth = new Authenticator() {
|
||||
@Override
|
||||
protected PasswordAuthentication getPasswordAuthentication() {
|
||||
return new PasswordAuthentication(smtp.username(), smtp.password());
|
||||
}
|
||||
};
|
||||
return Session.getInstance(props, auth);
|
||||
}
|
||||
return Session.getInstance(props);
|
||||
}
|
||||
|
||||
private static String subjectExcerpt(String name, String message) {
|
||||
String source = (name != null && !name.isBlank()) ? name : message;
|
||||
String s = source == null ? "message" : source.strip().replaceAll("\\s+", " ");
|
||||
if (s.isEmpty()) {
|
||||
s = "message";
|
||||
}
|
||||
return s.length() <= MAX_SUBJECT_SOURCE ? s : s.substring(0, MAX_SUBJECT_SOURCE).stripTrailing() + "…";
|
||||
}
|
||||
|
||||
private static String rootMessage(Throwable t) {
|
||||
Throwable cur = t;
|
||||
while (cur.getCause() != null && cur.getCause() != cur) {
|
||||
cur = cur.getCause();
|
||||
}
|
||||
String m = cur.getMessage();
|
||||
return (m == null || m.isBlank()) ? cur.getClass().getSimpleName() : m;
|
||||
}
|
||||
|
||||
private static String orDash(String value) {
|
||||
return (value == null || value.isBlank()) ? "—" : value.strip();
|
||||
}
|
||||
|
||||
private static String blankToNull(String value) {
|
||||
return (value == null || value.isBlank()) ? null : value.strip();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import mx.quest.runway.spi.service.PluginSiteFiles;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Persists contact-form submissions as tenant-owned data in this plugin's per-site folder, through the kernel's
|
||||
* {@link PluginSiteFiles}: {@value #FILE} under {@code sites/<id>/plugins/contact/}; an existing file is read and
|
||||
* appended in place. The folder is <b>outside</b> the served {@code static/} tree (never publicly downloadable) and
|
||||
* inside the site folder, so full backups carry it. The file holds what visitors typed, so {@code plugin.yml}
|
||||
* declares it <b>personal data</b> ({@code siteData.personal}) and a transfer copy of the site leaves it out.
|
||||
*
|
||||
* <p>One tab-separated line per submission ({@code epochMillis \t name \t email \t message}); fields are
|
||||
* sanitized to strip tabs/newlines so the format stays unambiguous, and each field is capped at
|
||||
* {@value #MAX_FIELD} characters. The file is bounded to the most recent {@link #MAX_SUBMISSIONS}, so it stays
|
||||
* a few MiB — well under the kernel's per-write cap.
|
||||
*
|
||||
* <p><b>Concurrency.</b> Each kernel write is atomic, but appending is a read-modify-write, which the service
|
||||
* leaves to the plugin: it is serialized here per site (contact volume is low). <b>Failure.</b> A read failure
|
||||
* during {@link #add} aborts the append rather than rewriting the file from nothing (which would lose every
|
||||
* stored submission); the console reads ({@link #count}, {@link #recent}) degrade to empty with a warning so an
|
||||
* unreadable file never takes the settings screen down.
|
||||
*/
|
||||
public class ContactStore {
|
||||
|
||||
static final int MAX_SUBMISSIONS = 500;
|
||||
static final String FILE = "submissions.tsv";
|
||||
static final int MAX_FIELD = 4000;
|
||||
private static final Logger log = LoggerFactory.getLogger(ContactStore.class);
|
||||
|
||||
private final PluginSiteFiles files;
|
||||
private final ConcurrentMap<String, Object> locks = new ConcurrentHashMap<>();
|
||||
|
||||
public ContactStore(PluginSiteFiles files) {
|
||||
this.files = files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends a submission (stamped {@code epochMillis}), keeping only the most recent {@link #MAX_SUBMISSIONS}.
|
||||
*
|
||||
* @throws UncheckedIOException when the file cannot be read or written (nothing is lost: an unreadable file is
|
||||
* left untouched)
|
||||
*/
|
||||
public void add(String siteId, String name, String email, String message, long epochMillis) {
|
||||
String line = epochMillis + "\t" + sanitize(name) + "\t" + sanitize(email) + "\t" + sanitize(message);
|
||||
synchronized (locks.computeIfAbsent(siteId, k -> new Object())) {
|
||||
try {
|
||||
List<String> lines = new ArrayList<>(rawLines(siteId));
|
||||
lines.add(line);
|
||||
if (lines.size() > MAX_SUBMISSIONS) {
|
||||
lines = lines.subList(lines.size() - MAX_SUBMISSIONS, lines.size());
|
||||
}
|
||||
files.writeText(siteId, FILE, String.join("\n", lines) + "\n");
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("storing a contact submission for site " + siteId, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The most recent submissions, newest first, at most {@code limit}; empty when the file cannot be read. */
|
||||
public List<ContactSubmission> recent(String siteId, int limit) {
|
||||
List<String> lines = new ArrayList<>(readableLines(siteId));
|
||||
Collections.reverse(lines);
|
||||
List<ContactSubmission> out = new ArrayList<>();
|
||||
for (String line : lines) {
|
||||
if (out.size() >= limit) {
|
||||
break;
|
||||
}
|
||||
ContactSubmission s = parse(line);
|
||||
if (s != null) {
|
||||
out.add(s);
|
||||
}
|
||||
}
|
||||
return List.copyOf(out);
|
||||
}
|
||||
|
||||
/** The total number of stored submissions; 0 when the file cannot be read. */
|
||||
public int count(String siteId) {
|
||||
return readableLines(siteId).size();
|
||||
}
|
||||
|
||||
private List<String> readableLines(String siteId) {
|
||||
try {
|
||||
return rawLines(siteId);
|
||||
} catch (IOException e) {
|
||||
log.warn("contact submissions of site {} could not be read: {}", siteId, e.toString());
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> rawLines(String siteId) throws IOException {
|
||||
return files.readText(siteId, FILE)
|
||||
.map(text -> List.of(text.split("\n")).stream().filter(l -> !l.isBlank()).toList())
|
||||
.orElse(List.of());
|
||||
}
|
||||
|
||||
private static ContactSubmission parse(String line) {
|
||||
String[] p = line.split("\t", 4);
|
||||
if (p.length < 4) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return new ContactSubmission(Long.parseLong(p[0].trim()), p[1], p[2], p[3]);
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String sanitize(String value) {
|
||||
if (value == null) {
|
||||
return "";
|
||||
}
|
||||
String s = value.replace('\t', ' ').replace('\r', ' ').replace('\n', ' ').strip();
|
||||
return s.length() > MAX_FIELD ? s.substring(0, MAX_FIELD) : s;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
/**
|
||||
* One stored contact-form submission. Immutable; fields are already sanitized (no tabs/newlines) by
|
||||
* {@link ContactStore} so the on-disk TSV format stays unambiguous.
|
||||
*
|
||||
* @param epochMillis when it was received
|
||||
* @param name the submitter's name
|
||||
* @param email the submitter's email
|
||||
* @param message the message (newlines collapsed to spaces on storage)
|
||||
*/
|
||||
public record ContactSubmission(long epochMillis, String name, String email, String message) {
|
||||
|
||||
private static final DateTimeFormatter WHEN =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(ZoneId.systemDefault());
|
||||
|
||||
/** A {@code yyyy-MM-dd HH:mm} timestamp for display. */
|
||||
public String time() {
|
||||
return WHEN.format(Instant.ofEpochMilli(epochMillis));
|
||||
}
|
||||
|
||||
/** A short excerpt of the message for a listing cell. */
|
||||
public String excerpt() {
|
||||
String m = message == null ? "" : message.strip();
|
||||
return m.length() <= 80 ? m : m.substring(0, 80).stripTrailing() + "…";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import java.util.Locale;
|
||||
import mx.quest.runway.spi.CaptchaService;
|
||||
import mx.quest.runway.spi.ContentWidget;
|
||||
import mx.quest.runway.spi.model.Capabilities;
|
||||
import mx.quest.runway.spi.model.RenderFragment;
|
||||
import mx.quest.runway.spi.model.SettingsView;
|
||||
import mx.quest.runway.spi.model.WidgetView;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
|
||||
/**
|
||||
* The {@code contact} content widget: a site manager drops
|
||||
* {@code <div id="contact" data-widget="contact/form"></div>} on a page and the host renders the contact form
|
||||
* inline (it POSTs to the {@link ContactEndpoint}). Honors the per-site {@code enabled} setting (disabled ⇒
|
||||
* {@link RenderFragment#empty()}). The markup is the shared {@link ContactForm}; public text comes from
|
||||
* {@link Messages#site} in the visitor's locale.
|
||||
*/
|
||||
public class ContactWidget implements ContentWidget {
|
||||
|
||||
private final PluginSettings settings;
|
||||
private final Messages messages;
|
||||
private final CaptchaService captcha;
|
||||
|
||||
public ContactWidget(PluginSettings settings, Messages messages, CaptchaService captcha) {
|
||||
this.settings = settings;
|
||||
this.messages = messages;
|
||||
this.captcha = captcha;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return "contact";
|
||||
}
|
||||
|
||||
@Override
|
||||
public RenderFragment render(WidgetView view) {
|
||||
String siteId = view.site().id();
|
||||
SettingsView config = settings.site(siteId);
|
||||
if (!config.bool("enabled", true)) {
|
||||
return RenderFragment.empty();
|
||||
}
|
||||
Locale locale = view.locale();
|
||||
// The submit handler redirects back here with ?contact=sent|invalid|captcha; the widget re-renders the
|
||||
// outcome from that flag. A pure read of the request — the store/send side effects live in the endpoint.
|
||||
String outcome = view.query().get("contact");
|
||||
if ("sent".equals(outcome) || "queued".equals(outcome)) {
|
||||
String success = config.string("successMessage",
|
||||
messages.site(siteId, locale, "contact.success", "Thanks — your message has been sent."));
|
||||
String html = "<p class=\"rw-contact-success\">" + Html.escape(success.strip()) + "</p>";
|
||||
if ("queued".equals(outcome)) {
|
||||
// Stored, but the site's relay failed: say so quietly, so the visitor does not send it again.
|
||||
html += "<p class=\"rw-contact-note\">" + Html.escape(messages.site(siteId, locale,
|
||||
"contact.note.stored", "Your message was received; email delivery is delayed.")) + "</p>";
|
||||
}
|
||||
return RenderFragment.of(html);
|
||||
}
|
||||
String error = null;
|
||||
if ("invalid".equals(outcome)) {
|
||||
error = messages.site(siteId, locale, "contact.error.invalid", "Please enter your email and a message.");
|
||||
} else if ("captcha".equals(outcome)) {
|
||||
error = messages.site(siteId, locale, "contact.error.captcha",
|
||||
"Please complete the challenge and try again.");
|
||||
}
|
||||
String captchaHtml = captcha.widgetForSite(siteId).html();
|
||||
// Land the visitor back on THIS page after submit: the request path as served (locale prefix and all),
|
||||
// from the view — NEVER built from the slug, which for a content source's page (a blog entry rendering
|
||||
// this widget in the master chrome) is a composite identity like "blog:my-post", not a path. The slug
|
||||
// form remains only as the legacy fallback for a host that predates WidgetView.path.
|
||||
String returnPath = view.path().isEmpty() ? "/" + view.page().slug() : view.path();
|
||||
return RenderFragment.of(ContactForm.render(messages, siteId, locale, error, captchaHtml, returnPath));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Capabilities capabilities() {
|
||||
return Capabilities.of("widget.contact");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
/**
|
||||
* Minimal HTML escaping for the values the contact plugin interpolates into its form and its stored/echoed
|
||||
* submissions. The plugin owns escaping of its own output so a crafted name/email/message can never inject
|
||||
* markup into the form page, the thank-you page, or the admin listing.
|
||||
*/
|
||||
final class Html {
|
||||
|
||||
private Html() {
|
||||
}
|
||||
|
||||
static String escape(String value) {
|
||||
if (value == null || value.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
return value.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
.replace("\"", """).replace("'", "'");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import jakarta.mail.MessagingException;
|
||||
import jakarta.mail.Transport;
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
|
||||
/**
|
||||
* The production {@link MailTransport}: hands the message to {@code jakarta.mail.Transport}, which resolves the
|
||||
* {@code smtp}/{@code smtps} provider from the message's {@link jakarta.mail.Session} (the Angus reference
|
||||
* implementation, discovered at runtime via {@code META-INF/services/jakarta.mail.Provider} — now supplied by
|
||||
* the KERNEL, which bundles the Jakarta Mail stack as a core capability and is reached parent-first from the
|
||||
* plugin classloader).
|
||||
*
|
||||
* <p>Authentication is carried on the {@code Session} the {@link ContactMailer} built (with {@code mail.smtp.auth}
|
||||
* and a static {@link jakarta.mail.Authenticator} when the relay requires it), so {@link Transport#send(jakarta.mail.Message)}
|
||||
* with the message alone is sufficient — no separate connect/credentials call. Stateless and thread-safe.
|
||||
*/
|
||||
public class JakartaMailTransport implements MailTransport {
|
||||
|
||||
@Override
|
||||
public void send(MimeMessage message) throws MessagingException {
|
||||
Transport.send(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
/**
|
||||
* The reported outcome of trying to email a contact submission. A submission is <b>always</b> stored first
|
||||
* (belt-and-suspenders), so this result is <em>advisory</em> — it never means the message was lost, only whether
|
||||
* the email went out. The {@link ContactEndpoint} uses it to decide what the visitor sees; the plugin logs a
|
||||
* failure but keeps the stored copy.
|
||||
*/
|
||||
public record MailSendResult(Status status, String detail) {
|
||||
|
||||
/** Which way the send went. */
|
||||
public enum Status {
|
||||
/** The message was handed to the site's SMTP relay successfully. */
|
||||
SENT,
|
||||
/** No relay is configured for this site (blank host or recipient) — nothing was sent, only stored. */
|
||||
NOT_CONFIGURED,
|
||||
/** Jakarta Mail is not on the classpath (a broken deployment; the kernel bundles it) — stored only. */
|
||||
PROVIDER_MISSING,
|
||||
/** A relay is configured but the send failed (rejected / unreachable / auth) — {@link #detail} says why. */
|
||||
FAILED
|
||||
}
|
||||
|
||||
/** The email was sent. */
|
||||
public static MailSendResult sent() {
|
||||
return new MailSendResult(Status.SENT, null);
|
||||
}
|
||||
|
||||
/** No SMTP relay configured for this site (stored only). */
|
||||
public static MailSendResult notConfigured() {
|
||||
return new MailSendResult(Status.NOT_CONFIGURED, null);
|
||||
}
|
||||
|
||||
/** Jakarta Mail is unavailable on the classloader (a broken deployment; stored only). */
|
||||
public static MailSendResult providerMissing() {
|
||||
return new MailSendResult(Status.PROVIDER_MISSING, null);
|
||||
}
|
||||
|
||||
/** The send failed for the given reason (stored only). */
|
||||
public static MailSendResult failed(String detail) {
|
||||
return new MailSendResult(Status.FAILED, detail);
|
||||
}
|
||||
|
||||
/** Whether the email actually went out (as opposed to being stored only). */
|
||||
public boolean wasSent() {
|
||||
return status == Status.SENT;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import jakarta.mail.MessagingException;
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
|
||||
/**
|
||||
* The send seam: the single point where a built {@link MimeMessage} actually leaves the JVM over SMTP. Factored
|
||||
* out as an interface so the {@link ContactMailer}'s build-and-send logic can be unit-tested against a mock
|
||||
* transport with <b>no socket opened</b> (the production {@link JakartaMailTransport} delegates to
|
||||
* {@code jakarta.mail.Transport}).
|
||||
*
|
||||
* <p>Implementations MUST NOT swallow a failure — a broken relay has to be reported so the {@link ContactMailer}
|
||||
* can surface it (the stored copy of the submission still lands regardless). A {@link MessagingException} means
|
||||
* the send failed; returning normally means it was handed to the relay.
|
||||
*/
|
||||
public interface MailTransport {
|
||||
|
||||
/**
|
||||
* Sends an already-built, already-addressed message.
|
||||
*
|
||||
* @param message the MIME message to transmit (From/To/Subject/body all set by the caller)
|
||||
* @throws MessagingException if the relay rejected the message or could not be reached
|
||||
*/
|
||||
void send(MimeMessage message) throws MessagingException;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import mx.quest.runway.spi.model.SettingsView;
|
||||
|
||||
/**
|
||||
* The per-site SMTP relay configuration, materialized from a site's {@code contact} plugin settings (the
|
||||
* {@code smtp*} + {@code fromAddress}/{@code toAddress} {@code siteSettings}). Immutable; a pure value.
|
||||
*
|
||||
* <p><b>Isolation.</b> Every field comes from <em>this</em> site's own {@code sites/<id>/plugins/contact.yml};
|
||||
* a site can therefore only ever send through the relay <em>it</em> configured — never another tenant's.
|
||||
*
|
||||
* <p><b>Secret handling.</b> The password is a {@code secret} setting, stored {@code ENC(...)}-encrypted by the
|
||||
* platform. It never appears in the {@link SettingsView} (the kernel leaves secret keys out of it); the caller
|
||||
* hands it over separately, already in clear, from {@code PluginSettings.secret(siteId, "smtpPassword")}. The
|
||||
* plaintext lives only in this transient value and is handed straight to Jakarta Mail, never logged (see
|
||||
* {@link #toString()}) and never stored by this plugin.
|
||||
*
|
||||
* @param host the SMTP server host; blank ⇒ {@link #isConfigured()} is false (mail is skipped)
|
||||
* @param port the SMTP server port (1..65535; default 25)
|
||||
* @param auth whether to authenticate (SMTP AUTH) with {@code username}/{@code password}
|
||||
* @param username the SMTP username (used only when {@code auth})
|
||||
* @param password the SMTP password in PLAINTEXT (already decrypted; used only when {@code auth})
|
||||
* @param starttls whether to upgrade a plain connection with STARTTLS
|
||||
* @param ssl whether to open an implicit-TLS (SMTPS) connection
|
||||
* @param from the envelope/From address; blank ⇒ falls back to {@code to}
|
||||
* @param to the recipient address; blank ⇒ {@link #isConfigured()} is false (mail is skipped)
|
||||
*/
|
||||
public record SmtpSettings(String host, int port, boolean auth, String username, String password,
|
||||
boolean starttls, boolean ssl, String from, String to) {
|
||||
|
||||
/**
|
||||
* Reads the SMTP relay from a site's contact settings.
|
||||
*
|
||||
* @param view the site's effective contact settings ({@code PluginSettings.site}) — declared defaults
|
||||
* overlaid by what the operator saved; secret keys are absent from it by contract
|
||||
* @param password the {@code smtpPassword} secret in clear ({@code PluginSettings.secret}); empty when unset
|
||||
* or undecryptable — the relay then authenticates with a blank password and reports the failure
|
||||
* @return the materialized, immutable settings (never {@code null}); {@link #isConfigured()} reports usability
|
||||
*/
|
||||
public static SmtpSettings from(SettingsView view, Optional<String> password) {
|
||||
Objects.requireNonNull(view, "view");
|
||||
String host = text(view, "smtpHost");
|
||||
int port = (int) view.integer("smtpPort", 25L, 1, 65535);
|
||||
boolean auth = view.bool("smtpAuth", false);
|
||||
String username = text(view, "smtpUsername");
|
||||
String clear = password == null ? "" : password.orElse("");
|
||||
boolean starttls = view.bool("smtpStarttls", false);
|
||||
boolean ssl = view.bool("smtpSsl", false);
|
||||
String from = text(view, "fromAddress");
|
||||
String to = text(view, "toAddress");
|
||||
return new SmtpSettings(host, port, auth, username, clear, starttls, ssl, from, to);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether enough is set to attempt a send: a non-blank host AND a non-blank recipient. When false the
|
||||
* {@link ContactMailer} reports {@code NOT_CONFIGURED} and the submission is stored only (never lost).
|
||||
*/
|
||||
public boolean isConfigured() {
|
||||
return host != null && !host.isBlank() && to != null && !to.isBlank();
|
||||
}
|
||||
|
||||
/** The effective From address: the configured one, or the recipient when From is blank (a sane default). */
|
||||
public String effectiveFrom() {
|
||||
return (from == null || from.isBlank()) ? to : from;
|
||||
}
|
||||
|
||||
private static String text(SettingsView view, String key) {
|
||||
return view.string(key, "").strip();
|
||||
}
|
||||
|
||||
/** Never leak the password in logs / diagnostics. */
|
||||
@Override
|
||||
public String toString() {
|
||||
return "SmtpSettings[host=" + host + ", port=" + port + ", auth=" + auth + ", username=" + username
|
||||
+ ", starttls=" + starttls + ", ssl=" + ssl + ", from=" + from + ", to=" + to
|
||||
+ ", password=" + (password == null || password.isBlank() ? "<none>" : "<set>") + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import mx.quest.runway.spi.model.Route;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The console side of the CSRF fix: every operator action the endpoint declares (a non-anonymous {@code POST}) is
|
||||
* reached from the admin fragment by a {@code <form method="post">} that carries the console session's CSRF token,
|
||||
* and no link points at it any more (a link is a {@code GET}, and a {@code GET} on those paths changes nothing).
|
||||
* The markup is read from {@code templates/} as shipped; the token binding from the sibling {@code .th.xml}.
|
||||
*/
|
||||
class ContactAdminTemplateTest {
|
||||
|
||||
private static final Pattern FORM = Pattern.compile("(?s)<form\\b([^>]*)>(.*?)</form>");
|
||||
private static final Pattern CSRF_INPUT =
|
||||
Pattern.compile("<input\\b[^>]*\\bid=\"([^\"]+)\"[^>]*\\bname=\"_csrf\"[^>]*>");
|
||||
private static final String TOKEN_BINDING =
|
||||
"th:attr=\"name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}\"";
|
||||
|
||||
private static String read(String file) throws IOException {
|
||||
return Files.readString(Path.of("templates", file), StandardCharsets.UTF_8).replaceAll("(?s)<!--.*?-->", "");
|
||||
}
|
||||
|
||||
private static List<String> operatorActions() {
|
||||
ContactEndpoint endpoint = new ContactEndpoint(null, null, new FakePluginSettings(), new FakeSiteServices(),
|
||||
new FakeSiteServices(), null, new FakeSiteServices());
|
||||
List<String> paths = new ArrayList<>();
|
||||
for (Route r : endpoint.routes()) {
|
||||
if (!r.anonymous()) {
|
||||
paths.add(r.pathPattern());
|
||||
}
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOperatorActionsAreTheInstallAndTheSmtpTest() {
|
||||
assertEquals(List.of("/contact/install-page", "/contact/smtp-test"), operatorActions());
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyOperatorActionIsAPostFormCarryingTheCsrfToken() throws IOException {
|
||||
String html = read("admin.html");
|
||||
String logic = read("admin.th.xml");
|
||||
for (String action : operatorActions()) {
|
||||
Matcher form = FORM.matcher(html);
|
||||
boolean found = false;
|
||||
while (form.find()) {
|
||||
String attrs = form.group(1);
|
||||
if (!attrs.contains("action=\"" + action + "\"")) {
|
||||
continue;
|
||||
}
|
||||
found = true;
|
||||
assertTrue(attrs.contains("method=\"post\""), action + " must be submitted by POST: " + attrs);
|
||||
Matcher csrf = CSRF_INPUT.matcher(form.group(2));
|
||||
assertTrue(csrf.find(), action + "'s form carries a hidden _csrf field");
|
||||
String id = csrf.group(1);
|
||||
assertTrue(logic.contains("<attr sel=\"#" + id + "\"\n " + TOKEN_BINDING + "/>"),
|
||||
"#" + id + " is bound to the console session's CSRF token in admin.th.xml");
|
||||
}
|
||||
assertTrue(found, "the admin fragment has a form for " + action);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void noLinkPointsAtAnOperatorAction() throws IOException {
|
||||
String html = read("admin.html");
|
||||
for (String action : operatorActions()) {
|
||||
assertFalse(html.contains("href=\"" + action), "a link is a GET and would not carry the token: " + action);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theAdminFragmentsIdsAreUnique() throws IOException {
|
||||
// A duplicate id in a decoupled template is a hard Thymeleaf error that would 500 the settings page.
|
||||
Matcher ids = Pattern.compile("\\bid=\"([^\"]+)\"").matcher(read("admin.html"));
|
||||
Set<String> seen = new HashSet<>();
|
||||
while (ids.find()) {
|
||||
assertTrue(seen.add(ids.group(1)), "duplicate id " + ids.group(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import mx.quest.runway.spi.CaptchaService;
|
||||
import mx.quest.runway.spi.ContentWidget;
|
||||
import mx.quest.runway.spi.EndpointContributor;
|
||||
import mx.quest.runway.spi.model.CaptchaWidget;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.PluginSiteFiles;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
|
||||
/**
|
||||
* The plugin's contract with the host, checked at build time: the wiring over SPI services only, the bean-name
|
||||
* rule, the bean names the templates reference, the descriptor (SPI floor, release version, the personal-data
|
||||
* declaration matching the file the store writes), the i18n bundles, and that the compiled classes link nothing of
|
||||
* the host but the SPI — the same things the kernel's load-time checks warn about (and refuse from Runway 1.0).
|
||||
*/
|
||||
class ContactConfigTest {
|
||||
|
||||
private static final String PREFIX = "contact";
|
||||
|
||||
private static Set<String> beanMethodNames() {
|
||||
return Arrays.stream(ContactConfig.class.getDeclaredMethods())
|
||||
.filter(m -> m.isAnnotationPresent(Bean.class))
|
||||
.map(Method::getName)
|
||||
.collect(Collectors.toCollection(TreeSet::new));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, Object> descriptor() throws IOException {
|
||||
try (Reader in = Files.newBufferedReader(Path.of("plugin.yml"), StandardCharsets.UTF_8)) {
|
||||
return (Map<String, Object>) new Yaml().load(in);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void wiresEverythingFromSpiServicesUnderPrefixedNames(@TempDir Path sites) throws IOException {
|
||||
Files.createDirectories(sites.resolve("acme"));
|
||||
FakeSiteServices kernel = new FakeSiteServices()
|
||||
.site(new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null))
|
||||
.page("acme", "contact", "/kontakt");
|
||||
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
|
||||
ctx.registerBean(PluginSettings.class, () -> new FakePluginSettings()
|
||||
.site("acme", Map.of("smtpHost", "mail.example.com", "toAddress", "owner@example.com")));
|
||||
ctx.registerBean(PluginSiteFiles.class, () -> new TempDirSiteFiles(sites, "contact"));
|
||||
ctx.registerBean(FakeSiteServices.class, () -> kernel);
|
||||
ctx.registerBean(CaptchaService.class, () -> new CaptchaService() {
|
||||
@Override
|
||||
public CaptchaWidget widgetForSite(String siteId) {
|
||||
return CaptchaWidget.inactive();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(String siteId, String token, String clientIp) {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
ctx.register(ContactConfig.class);
|
||||
ctx.refresh();
|
||||
|
||||
assertInstanceOf(ContactWidget.class, ctx.getBean("contactWidget", ContentWidget.class));
|
||||
assertInstanceOf(ContactEndpoint.class, ctx.getBean("contactEndpoint", EndpointContributor.class));
|
||||
ctx.getBean("contactStore", ContactStore.class).add("acme", "Ann", "a@example.com", "hi", 1L);
|
||||
ContactAdminModel model = ctx.getBean("contactAdminModel", ContactAdminModel.class);
|
||||
assertEquals(1, model.count("acme"), "the admin model reads the store over the injected site files");
|
||||
assertTrue(model.smtpConfigured("acme"), "…and the relay over the injected settings");
|
||||
assertEquals("/kontakt", model.pagePath("acme"), "…and the page through SitePages");
|
||||
assertTrue(model.pageInstalled("acme"));
|
||||
assertFalse(model.pageInstalled("other"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyBeanNameStartsWithThePluginIdInLowerCamelCase() {
|
||||
Set<String> names = beanMethodNames();
|
||||
assertEquals(Set.of("contactStore", "contactMailTransport", "contactMailer", "contactWidget",
|
||||
"contactEndpoint", "contactAdminModel"), names);
|
||||
for (Method m : ContactConfig.class.getDeclaredMethods()) {
|
||||
Bean bean = m.getAnnotation(Bean.class);
|
||||
if (bean != null) {
|
||||
for (String alias : bean.name()) {
|
||||
assertTrue(alias.startsWith(PREFIX), "an explicit bean name must start with " + PREFIX + ": " + alias);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyBeanTheTemplatesReferenceIsOneOfOurs() throws IOException {
|
||||
Set<String> referenced = new TreeSet<>();
|
||||
try (Stream<Path> files = Files.list(Path.of("templates"))) {
|
||||
for (Path file : files.filter(p -> p.toString().endsWith(".th.xml")).toList()) {
|
||||
// XML comments explain the ${@bean} rules in prose; only the live attributes count.
|
||||
String live = Files.readString(file, StandardCharsets.UTF_8).replaceAll("(?s)<!--.*?-->", "");
|
||||
Matcher m = Pattern.compile("\\$\\{\\s*!?\\s*@(\\w+)").matcher(live);
|
||||
while (m.find()) {
|
||||
referenced.add(m.group(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
assertEquals(Set.of("contactAdminModel"), referenced, "the console templates read the admin model only");
|
||||
assertTrue(beanMethodNames().containsAll(referenced), "templates reference unknown beans: " + referenced);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDescriptorDeclaresTheSpiFloorAndTheReleaseVersion() throws IOException {
|
||||
Map<String, Object> yml = descriptor();
|
||||
assertEquals(">=1.0.0", yml.get("requiresSpi"), "built for the frozen SPI 1.0.0 contract");
|
||||
String pom = Files.readString(Path.of("pom.xml"), StandardCharsets.UTF_8);
|
||||
Matcher version = Pattern.compile("<artifactId>runway-plugin-contact</artifactId>\\s*<version>([^<]+)")
|
||||
.matcher(pom);
|
||||
assertTrue(version.find());
|
||||
assertEquals(version.group(1), String.valueOf(yml.get("version")), "plugin.yml and pom.xml agree on the version");
|
||||
assertFalse(pom.contains("<artifactId>runway-app</artifactId>"), "no runway-app dependency in any scope");
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void theSubmissionsFileIsDeclaredPersonalDataSoTransferCopiesLeaveItOut() throws IOException {
|
||||
Map<String, Object> siteData = (Map<String, Object>) descriptor().get("siteData");
|
||||
assertTrue(siteData != null, "plugin.yml declares siteData");
|
||||
List<String> personal = (List<String>) siteData.get("personal");
|
||||
assertEquals(List.of(ContactStore.FILE), personal,
|
||||
"exactly the file the store writes (visitor names, emails, messages) is personal data");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSmtpPasswordIsDeclaredASecret() throws IOException {
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, Object>> schema = (List<Map<String, Object>>) descriptor().get("siteSettings");
|
||||
Map<String, Object> password = schema.stream()
|
||||
.filter(s -> ContactMailer.PASSWORD_KEY.equals(s.get("key"))).findFirst().orElseThrow();
|
||||
assertEquals("secret", password.get("type"),
|
||||
"PluginSettings.secret hands out only keys declared type: secret (and site() leaves them out)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSmtpPasswordIsBoundToTheRelayLogin() throws IOException {
|
||||
// secretBoundTo: a save that changes the relay's host, port or username without retyping the password makes
|
||||
// the kernel drop the stored password, so a settings editor cannot repoint the saved credentials at a server
|
||||
// of their choosing. Every bound key must be a declared setting, or the binding silently binds nothing.
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, Object>> schema = (List<Map<String, Object>>) descriptor().get("siteSettings");
|
||||
Map<String, Object> password = schema.stream()
|
||||
.filter(s -> ContactMailer.PASSWORD_KEY.equals(s.get("key"))).findFirst().orElseThrow();
|
||||
assertEquals(List.of("smtpHost", "smtpPort", "smtpUsername", "smtpStarttls", "smtpSsl"), password.get("secretBoundTo"),
|
||||
"the stored SMTP password is bound to the host, port and username it was typed for");
|
||||
List<Object> declared = schema.stream().map(s -> s.get("key")).toList();
|
||||
for (Object bound : (List<?>) password.get("secretBoundTo")) {
|
||||
assertTrue(declared.contains(bound), "secretBoundTo names a declared setting: " + bound);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theEnglishAndSpanishBundlesDefineTheSameKeys() throws IOException {
|
||||
assertEquals(keys("i18n/messages.properties"), keys("i18n/messages_es.properties"));
|
||||
Set<String> en = keys("i18n/messages.properties");
|
||||
for (String key : List.of("contact.page.installed", "contact.page.pending", "contact.page.blocked",
|
||||
"contact.page.exists", "contact.page.failed", "contact.page.other")) {
|
||||
assertTrue(en.contains(key), "every install outcome has words: " + key);
|
||||
}
|
||||
}
|
||||
|
||||
private static Set<String> keys(String file) throws IOException {
|
||||
Properties p = new Properties();
|
||||
try (Reader in = Files.newBufferedReader(Path.of(file), StandardCharsets.UTF_8)) {
|
||||
p.load(in);
|
||||
}
|
||||
return new TreeSet<>(p.stringPropertyNames());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCompiledClassesLinkNoHostInternals() throws IOException {
|
||||
Path classes = Path.of("target", "classes");
|
||||
Pattern host = Pattern.compile("mx[/.]quest[/.]runway[/.](?!spi[/.])[\\w/.$]*");
|
||||
List<String> problems = new ArrayList<>();
|
||||
int scanned = 0;
|
||||
try (Stream<Path> files = Files.walk(classes)) {
|
||||
for (Path file : files.filter(p -> p.toString().endsWith(".class")).toList()) {
|
||||
scanned++;
|
||||
String rel = classes.relativize(file).toString().replace('\\', '/');
|
||||
if (rel.startsWith("mx/quest/runway/")) {
|
||||
problems.add(rel + " lives under mx.quest.runway");
|
||||
}
|
||||
// The constant pool holds class names and descriptors as (modified) UTF-8; Latin-1 keeps every
|
||||
// byte as one char, so an ASCII pattern finds them without parsing the class file.
|
||||
Matcher m = host.matcher(new String(Files.readAllBytes(file), StandardCharsets.ISO_8859_1));
|
||||
while (m.find()) {
|
||||
problems.add(rel + " → " + m.group());
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(scanned >= 12, "the compiled classes were found (" + scanned + ")");
|
||||
assertTrue(problems.isEmpty(), "host linkage: " + problems);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.CaptchaService;
|
||||
import mx.quest.runway.spi.model.CaptchaWidget;
|
||||
import mx.quest.runway.spi.model.Finding;
|
||||
import mx.quest.runway.spi.model.InstallResult;
|
||||
import mx.quest.runway.spi.model.Route;
|
||||
import mx.quest.runway.spi.model.RouteRequest;
|
||||
import mx.quest.runway.spi.model.RouteResponse;
|
||||
import mx.quest.runway.spi.model.Severity;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.model.StarterPage;
|
||||
import mx.quest.runway.spi.service.SitePages;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The contact plugin's request surface — it owns <b>no visible page</b>. Covered here: the anonymous
|
||||
* {@code POST /contact/submit} handler (303 back to the form's page with a {@code ?contact=…} outcome; POST only,
|
||||
* fields from the body only; store-then-send ordering; honeypot, invalid and CAPTCHA gating with the gated client
|
||||
* IP; return-path safety), the operator-gated {@code POST /contact/install-page} with each {@code SitePages}
|
||||
* outcome, and the operator-gated {@code POST /contact/smtp-test}. Both operator actions change state, so they are
|
||||
* non-anonymous POST routes (the kernel's CSRF check applies) and a GET changes nothing. The form's HTML is covered
|
||||
* in {@link ContactWidgetTest}; the console forms that carry the CSRF token in {@link ContactAdminTemplateTest}.
|
||||
*/
|
||||
class ContactEndpointTest {
|
||||
|
||||
private static final SiteView ACME = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null);
|
||||
private static final String CLIENT_IP = "203.0.113.7";
|
||||
|
||||
private ContactStore store;
|
||||
private ContactMailer mailer;
|
||||
private FakePluginSettings settings;
|
||||
private FakeSiteServices kernel;
|
||||
private CaptchaService captcha;
|
||||
private ContactEndpoint endpoint;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
store = mock(ContactStore.class);
|
||||
mailer = mock(ContactMailer.class);
|
||||
when(mailer.send(anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(MailSendResult.sent());
|
||||
settings = new FakePluginSettings().defaults(Map.of("enabled", true));
|
||||
kernel = new FakeSiteServices().site(ACME).current("acme");
|
||||
captcha = mock(CaptchaService.class);
|
||||
// Default: no challenge configured (submissions flow through the non-CAPTCHA path).
|
||||
when(captcha.widgetForSite(any())).thenReturn(CaptchaWidget.inactive());
|
||||
endpoint = new ContactEndpoint(store, mailer, settings, kernel, kernel, captcha, kernel);
|
||||
}
|
||||
|
||||
private static RouteRequest request(String method, String path, Map<String, List<String>> query,
|
||||
Map<String, List<String>> form, Map<String, String> headers) {
|
||||
return new RouteRequest(ACME, Locale.ENGLISH, method, path, query, headers, new byte[0], form, CLIENT_IP,
|
||||
"https://acme.test");
|
||||
}
|
||||
|
||||
/** A POST /contact/submit with the given BODY fields; carries a {@code return} of /home. */
|
||||
private RouteResponse submit(Map<String, List<String>> fields) {
|
||||
Map<String, List<String>> form = new HashMap<>(fields);
|
||||
form.putIfAbsent("return", List.of("/home"));
|
||||
return endpoint.handle(request("POST", "/contact/submit", Map.of(), form, Map.of()));
|
||||
}
|
||||
|
||||
private static Map<String, List<String>> valid() {
|
||||
return Map.of("name", List.of("Ann"), "email", List.of("ann@example.com"),
|
||||
"message", List.of("Hello there"), "website", List.of(""));
|
||||
}
|
||||
|
||||
private static Map<String, List<String>> with(Map<String, List<String>> base, String key, String value) {
|
||||
Map<String, List<String>> copy = new HashMap<>(base);
|
||||
copy.put(key, List.of(value));
|
||||
return copy;
|
||||
}
|
||||
|
||||
private static String location(RouteResponse res) {
|
||||
return res.headers().get("Location");
|
||||
}
|
||||
|
||||
private static String text(RouteResponse res) {
|
||||
return new String(res.body(), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private void verifyNothingStoredOrSent() {
|
||||
verify(store, never()).add(anyString(), anyString(), anyString(), anyString(), anyLong());
|
||||
verify(mailer, never()).send(anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
// ---- routes ----------------------------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void theSubmitRouteIsAnAnonymousPostAndTheOperatorActionsAreNot() {
|
||||
List<Route> routes = endpoint.routes();
|
||||
Route submit = routes.stream().filter(r -> r.pathPattern().equals("/contact/submit")).findFirst().orElseThrow();
|
||||
assertEquals("POST", submit.method());
|
||||
assertTrue(submit.anonymous(), "declared anonymous: the kernel exempts exactly this POST from CSRF");
|
||||
assertEquals(1, routes.stream().filter(r -> r.pathPattern().equals("/contact/submit")).count(),
|
||||
"no GET submit route remains");
|
||||
for (Route r : routes) {
|
||||
if (!r.pathPattern().equals("/contact/submit")) {
|
||||
assertFalse(r.anonymous(), "the operator actions keep the principal (and the CSRF rule): " + r);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyRouteIsAPostSoNoLinkOrImageCanChangeState() {
|
||||
List<Route> routes = endpoint.routes();
|
||||
assertEquals(List.of("/contact/submit", "/contact/install-page", "/contact/smtp-test"),
|
||||
routes.stream().map(Route::pathPattern).toList());
|
||||
for (Route r : routes) {
|
||||
assertEquals("POST", r.method(), "a GET route would let a cross-site link trigger it: " + r);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- POST /contact/submit --------------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void aValidPostRedirects303SentAndStoresAndEmails() {
|
||||
RouteResponse res = submit(valid());
|
||||
assertEquals(303, res.status(), "post/redirect/get");
|
||||
assertEquals("/home?contact=sent", location(res), "it lands back on the form's page with a success flag");
|
||||
verify(store).add(eq("acme"), eq("Ann"), eq("ann@example.com"), eq("Hello there"), anyLong());
|
||||
verify(mailer).send(eq("acme"), eq("Acme"), eq("Ann"), eq("ann@example.com"), eq("Hello there"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRedirectCarriesTheOutcomeOnlyNeverASubmittedValue() {
|
||||
String where = location(submit(valid()));
|
||||
for (String personal : List.of("Ann", "ann", "example.com", "Hello")) {
|
||||
assertFalse(where.contains(personal), "no personal data in the Location: " + where);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGetSubmissionIsNotAcceptedAndStoresNothing() {
|
||||
Map<String, List<String>> query = with(valid(), "return", "/home");
|
||||
RouteResponse res = endpoint.handle(request("GET", "/contact/submit", query, Map.of(), Map.of()));
|
||||
assertEquals(404, res.status(), "1.x's GET submission is gone: only the anonymous POST is handled");
|
||||
verifyNothingStoredOrSent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void fieldsInTheQueryStringAreIgnoredOnAPost() {
|
||||
Map<String, List<String>> query = valid();
|
||||
RouteResponse res = endpoint.handle(request("POST", "/contact/submit", query,
|
||||
Map.of("return", List.of("/home")), Map.of()));
|
||||
assertEquals("/home?contact=invalid", location(res), "personal data is read from the body only");
|
||||
verifyNothingStoredOrSent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFilledHoneypotFakesSuccessWithoutStoringOrEmailing() {
|
||||
RouteResponse res = submit(with(valid(), "website", "http://spam.example"));
|
||||
assertEquals("/home?contact=sent", location(res), "the bot sees a fake success");
|
||||
verifyNothingStoredOrSent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInvalidEmailRedirectsWithTheInvalidFlag() {
|
||||
assertEquals("/home?contact=invalid", location(submit(with(valid(), "email", "not-an-email"))));
|
||||
verifyNothingStoredOrSent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlankMessageRedirectsWithTheInvalidFlag() {
|
||||
assertEquals("/home?contact=invalid", location(submit(with(valid(), "message", " "))));
|
||||
verifyNothingStoredOrSent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActiveCaptchaWithoutATokenRefusesThePost() {
|
||||
when(captcha.widgetForSite(any())).thenReturn(new CaptchaWidget(
|
||||
true, "g-recaptcha-response", "<div class=\"g-recaptcha\"></div>"));
|
||||
when(captcha.verify(any(), any(), any())).thenReturn(false);
|
||||
RouteResponse res = submit(valid());
|
||||
assertEquals("/home?contact=captcha", location(res));
|
||||
verify(captcha).verify("acme", "", CLIENT_IP);
|
||||
verifyNothingStoredOrSent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActiveCaptchaIsVerifiedWithTheBodyTokenAndTheGatedClientIp() {
|
||||
when(captcha.widgetForSite(any())).thenReturn(new CaptchaWidget(
|
||||
true, "g-recaptcha-response", "<div class=\"g-recaptcha\"></div>"));
|
||||
when(captcha.verify(eq("acme"), eq("good-token"), eq(CLIENT_IP))).thenReturn(true);
|
||||
RouteResponse res = submit(with(valid(), "g-recaptcha-response", "good-token"));
|
||||
assertEquals("/home?contact=sent", location(res));
|
||||
verify(store).add(eq("acme"), eq("Ann"), eq("ann@example.com"), eq("Hello there"), anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCaptchaTokenOnlyInTheQueryStringDoesNotCount() {
|
||||
when(captcha.widgetForSite(any())).thenReturn(new CaptchaWidget(
|
||||
true, "g-recaptcha-response", "<div class=\"g-recaptcha\"></div>"));
|
||||
when(captcha.verify(eq("acme"), eq("good-token"), any())).thenReturn(true);
|
||||
Map<String, List<String>> form = with(valid(), "return", "/home");
|
||||
RouteResponse res = endpoint.handle(request("POST", "/contact/submit",
|
||||
Map.of("g-recaptcha-response", List.of("good-token")), form, Map.of()));
|
||||
assertEquals("/home?contact=captcha", location(res));
|
||||
verifyNothingStoredOrSent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActiveCaptchaThatFailsRedirectsWithTheCaptchaFlag() {
|
||||
when(captcha.widgetForSite(any())).thenReturn(new CaptchaWidget(
|
||||
true, "g-recaptcha-response", "<div class=\"g-recaptcha\"></div>"));
|
||||
when(captcha.verify(any(), any(), any())).thenReturn(false);
|
||||
assertEquals("/home?contact=captcha", location(submit(with(valid(), "g-recaptcha-response", "bad"))));
|
||||
verifyNothingStoredOrSent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledContactReturns404() {
|
||||
settings.site("acme", Map.of("enabled", false));
|
||||
assertEquals(404, submit(valid()).status());
|
||||
verifyNothingStoredOrSent();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedSendRedirectsQueuedButStillStores() {
|
||||
when(mailer.send(anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(MailSendResult.failed("relay refused"));
|
||||
assertEquals("/home?contact=queued", location(submit(valid())), "a real relay failure is a delayed note");
|
||||
verify(store).add(eq("acme"), eq("Ann"), eq("ann@example.com"), eq("Hello there"), anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnconfiguredRelayRedirectsSentSilentlyAndStores() {
|
||||
when(mailer.send(anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(MailSendResult.notConfigured());
|
||||
assertEquals("/home?contact=sent", location(submit(valid())), "a store-only site never shows a delivery note");
|
||||
verify(store).add(eq("acme"), eq("Ann"), eq("ann@example.com"), eq("Hello there"), anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRefererIsUsedWhenNoReturnFieldIsGiven() {
|
||||
RouteResponse res = endpoint.handle(request("POST", "/contact/submit", Map.of(), valid(),
|
||||
Map.of("Referer", "https://acme.test/contact-us?x=1")));
|
||||
assertEquals("/contact-us?contact=sent", location(res), "it lands back on the Referer page (query stripped)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aForeignReturnFieldIsRejectedAndFallsBackToRoot() {
|
||||
RouteResponse res = submit(with(valid(), "return", "https://evil.example/steal"));
|
||||
assertEquals("/?contact=sent", location(res), "an off-origin return target is ignored (no open redirect)");
|
||||
assertEquals("/?contact=sent", location(submit(with(valid(), "return", "//evil.example/x"))));
|
||||
}
|
||||
|
||||
// ---- /contact/install-page (operator-gated) ---------------------------------------------------------------
|
||||
|
||||
private RouteResponse install() {
|
||||
return endpoint.handle(request("POST", "/contact/install-page", Map.of(), Map.of(), Map.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theInstallPageIsHiddenFromCallersWithoutThePermission() {
|
||||
RouteResponse res = install();
|
||||
assertEquals(404, res.status(), "fail closed: the action is not revealed to the unauthorized");
|
||||
assertTrue(kernel.installs().isEmpty(), "nothing was installed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGetOnTheInstallPathInstallsNothingEvenForAnAuthorizedOperator() {
|
||||
kernel.grant("contact|settings");
|
||||
for (String method : List.of("GET", "HEAD", "PUT", "DELETE")) {
|
||||
RouteResponse res = endpoint.handle(request(method, "/contact/install-page", Map.of(), Map.of(), Map.of()));
|
||||
assertEquals(404, res.status(), method + " is not the install action");
|
||||
}
|
||||
assertTrue(kernel.installs().isEmpty(), "following a link (or loading an <img>) must not install the page");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theInstallMethodIsMatchedCaseInsensitively() {
|
||||
kernel.grant("contact|settings");
|
||||
RouteResponse res = endpoint.handle(request("post", "/contact/install-page", Map.of(), Map.of(), Map.of()));
|
||||
assertEquals(200, res.status());
|
||||
assertEquals(1, kernel.installs().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInstallThatPublishesSaysWhereThePageIs() {
|
||||
kernel.grant("contact|settings").message("acme", "contact.page.title", "Contact us");
|
||||
RouteResponse res = install();
|
||||
assertEquals(200, res.status());
|
||||
assertEquals("Contact page installed at /contact", text(res));
|
||||
StarterPage page = kernel.installs().get(0);
|
||||
assertEquals("contact", page.slug(), "installed at the stable slug");
|
||||
assertEquals("/contact", page.path());
|
||||
assertEquals(Map.of("en", "Contact us"), page.titles(), "titled in the site's default language");
|
||||
assertFalse(page.noindex(), "a contact page is meant to be found");
|
||||
assertTrue(page.html().contains("data-widget=\"contact/form\""), "the page carries the widget anchor");
|
||||
assertTrue(page.html().contains("<title>Contact us</title>"));
|
||||
assertTrue(page.logic().contains("${master}"), "the chrome comes from the master");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInstallOnAReviewedSiteSaysItIsWaitingForReview() {
|
||||
kernel.grant("contact|settings").nextInstall(InstallResult.Outcome.PENDING_REVIEW);
|
||||
RouteResponse res = install();
|
||||
assertEquals(200, res.status());
|
||||
assertTrue(text(res).contains("waiting in the review queue"), text(res));
|
||||
assertTrue(text(res).endsWith("/contact"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInstallBlockedByTheQualityChecksSaysItIsADraftAndWhy() {
|
||||
kernel.grant("contact|settings").nextInstall(InstallResult.Outcome.DRAFT_BLOCKED,
|
||||
new Finding(Severity.ERROR, "content.thin", "The page has almost no text."));
|
||||
RouteResponse res = install();
|
||||
assertEquals(200, res.status());
|
||||
assertTrue(text(res).contains("as a draft"), text(res));
|
||||
assertTrue(text(res).contains("- content.thin: The page has almost no text."), "the blocking finding: " + text(res));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSecondInstallChangesNothingAndSaysWhereTheExistingPageIs() {
|
||||
kernel.grant("contact|settings").page("acme", "contact", "/hola");
|
||||
RouteResponse res = install();
|
||||
assertEquals(200, res.status(), "an existing page is not an error — the action is idempotent");
|
||||
assertEquals("A contact page already exists at /hola", text(res), "the page's current path, wherever it moved");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedInstallIsA500WithTheOperatorsMessage() {
|
||||
SitePages failing = mock(SitePages.class);
|
||||
when(failing.install(any(), any())).thenThrow(new IllegalStateException("/contact is served by another page"));
|
||||
kernel.grant("contact|settings");
|
||||
ContactEndpoint withFailingPages = new ContactEndpoint(store, mailer, settings, kernel, kernel, captcha, failing);
|
||||
RouteResponse res = withFailingPages.handle(request("POST", "/contact/install-page", Map.of(), Map.of(), Map.of()));
|
||||
assertEquals(500, res.status());
|
||||
assertEquals("Could not install the contact page.", text(res));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOperatorAnswersAreConsoleMessages() {
|
||||
kernel.grant("contact|settings").message(null, "contact.page.installed", "Página de contacto instalada en");
|
||||
assertEquals("Página de contacto instalada en /contact", text(install()),
|
||||
"in the operator's console language (Messages.console), not the visitor's");
|
||||
}
|
||||
|
||||
// ---- /contact/smtp-test (operator-gated) ------------------------------------------------------------------
|
||||
|
||||
private RouteResponse smtpTest(Map<String, List<String>> form) {
|
||||
return endpoint.handle(request("POST", "/contact/smtp-test", Map.of(), form, Map.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSmtpTestIsHiddenFromCallersWithoutThePermission() {
|
||||
assertEquals(404, smtpTest(Map.of()).status(), "fail closed: the surface is not revealed to the unauthorized");
|
||||
verifyNoInteractions(mailer);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSmtpTestSendsForAnAuthorizedCaller() {
|
||||
kernel.grant("contact|settings");
|
||||
when(mailer.sendTest(eq("acme"), eq("Acme"), eq("me@example.com"))).thenReturn(MailSendResult.sent());
|
||||
RouteResponse res = smtpTest(Map.of("to", List.of(" me@example.com ")));
|
||||
assertEquals(200, res.status());
|
||||
assertEquals("Test message sent.", text(res));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSmtpTestWithoutARecipientUsesTheConfiguredOne() {
|
||||
kernel.grant("contact|settings");
|
||||
when(mailer.sendTest(eq("acme"), eq("Acme"), eq(""))).thenReturn(MailSendResult.sent());
|
||||
assertEquals(200, smtpTest(Map.of()).status());
|
||||
verify(mailer).sendTest("acme", "Acme", "");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGetOnTheSmtpTestPathSendsNothingEvenForAnAuthorizedOperator() {
|
||||
kernel.grant("contact|settings");
|
||||
RouteResponse res = endpoint.handle(request("GET", "/contact/smtp-test",
|
||||
Map.of("to", List.of("victim@example.com")), Map.of(), Map.of()));
|
||||
assertEquals(404, res.status(), "a cross-site link must not make the server send an email");
|
||||
verifyNoInteractions(mailer);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSmtpTestRecipientIsReadFromTheBodyNeverTheQueryString() {
|
||||
kernel.grant("contact|settings");
|
||||
when(mailer.sendTest(anyString(), anyString(), any())).thenReturn(MailSendResult.sent());
|
||||
endpoint.handle(request("POST", "/contact/smtp-test", Map.of("to", List.of("victim@example.com")),
|
||||
Map.of(), Map.of()));
|
||||
verify(mailer).sendTest("acme", "Acme", "");
|
||||
verify(mailer, never()).sendTest(anyString(), anyString(), eq("victim@example.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedSmtpTestReportsA502() {
|
||||
kernel.grant("contact|settings");
|
||||
when(mailer.sendTest(anyString(), anyString(), any())).thenReturn(MailSendResult.failed("timeout"));
|
||||
RouteResponse res = smtpTest(Map.of());
|
||||
assertEquals(502, res.status(), "a failed test reports a bad-gateway status");
|
||||
assertTrue(text(res).contains("timeout"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import jakarta.mail.Message;
|
||||
import jakarta.mail.MessagingException;
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
import jakarta.mail.PasswordAuthentication;
|
||||
import jakarta.mail.Session;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
/**
|
||||
* The send path: {@link ContactMailer} builds the expected MIME message and hands it to a MOCK
|
||||
* {@link MailTransport} (no socket), reports a send failure without throwing, reports "not configured" when no
|
||||
* relay is set, and takes the SMTP password ONLY from {@code PluginSettings.secret(site, "smtpPassword")} — the
|
||||
* kernel decrypts the {@code ENC(...)} value; the plugin never sees ciphertext, never reads a password out of the
|
||||
* settings view, and never prints it.
|
||||
*/
|
||||
class ContactMailerTest {
|
||||
|
||||
private static final Map<String, Object> RELAY = Map.of(
|
||||
"smtpHost", "mail.example.com",
|
||||
"smtpPort", 587L,
|
||||
"smtpAuth", true,
|
||||
"smtpUsername", "postmaster",
|
||||
"smtpStarttls", true,
|
||||
"fromAddress", "site@example.com",
|
||||
"toAddress", "owner@example.com");
|
||||
|
||||
/** The plugin's per-site settings as the kernel hands them over: RELAY for acme, the password a secret. */
|
||||
private static FakePluginSettings settings(Map<String, Object> acme) {
|
||||
return new FakePluginSettings().site("acme", acme).secret("acme", "smtpPassword", "s3cret");
|
||||
}
|
||||
|
||||
/** The password the built session's authenticator would answer the relay with. */
|
||||
private static PasswordAuthentication credentials(Session session) {
|
||||
return session.requestPasswordAuthentication(null, 587, "smtp", null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSubmissionBuildsTheExpectedMimeMessageAndCallsTheTransport() throws Exception {
|
||||
MailTransport transport = mock(MailTransport.class);
|
||||
ContactMailer mailer = new ContactMailer(settings(RELAY), transport);
|
||||
|
||||
MailSendResult result = mailer.send("acme", "Acme", "Ann", "ann@example.com", "Hello there");
|
||||
|
||||
assertEquals(MailSendResult.Status.SENT, result.status());
|
||||
ArgumentCaptor<MimeMessage> captor = ArgumentCaptor.forClass(MimeMessage.class);
|
||||
verify(transport).send(captor.capture());
|
||||
MimeMessage msg = captor.getValue();
|
||||
assertEquals("site@example.com", ((jakarta.mail.internet.InternetAddress) msg.getFrom()[0]).getAddress());
|
||||
assertEquals("owner@example.com",
|
||||
((jakarta.mail.internet.InternetAddress) msg.getRecipients(Message.RecipientType.TO)[0]).getAddress());
|
||||
// Reply-To is the visitor so the site can reply straight to them.
|
||||
assertEquals("ann@example.com",
|
||||
((jakarta.mail.internet.InternetAddress) msg.getReplyTo()[0]).getAddress());
|
||||
assertTrue(msg.getSubject().startsWith("[Acme] "), "subject is site-prefixed: " + msg.getSubject());
|
||||
String body = (String) msg.getContent();
|
||||
assertTrue(body.contains("ann@example.com"), "the body carries the submitter email");
|
||||
assertTrue(body.contains("Hello there"), "the body carries the message");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTransportFailureIsReportedNotThrown() throws Exception {
|
||||
MailTransport transport = mock(MailTransport.class);
|
||||
doThrow(new MessagingException("relay refused")).when(transport).send(any());
|
||||
ContactMailer mailer = new ContactMailer(settings(RELAY), transport);
|
||||
|
||||
MailSendResult result = mailer.send("acme", "Acme", "Ann", "ann@example.com", "Hi");
|
||||
|
||||
assertEquals(MailSendResult.Status.FAILED, result.status());
|
||||
assertNotNull(result.detail());
|
||||
assertTrue(result.detail().contains("relay refused"), "the reason is surfaced: " + result.detail());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnconfiguredRelayReportsNotConfiguredAndNeverTouchesTheTransport() throws Exception {
|
||||
MailTransport transport = mock(MailTransport.class);
|
||||
// Blank host + recipient ⇒ not configured.
|
||||
ContactMailer mailer = new ContactMailer(settings(Map.of()), transport);
|
||||
|
||||
MailSendResult result = mailer.send("acme", "Acme", "Ann", "ann@example.com", "Hi");
|
||||
|
||||
assertEquals(MailSendResult.Status.NOT_CONFIGURED, result.status());
|
||||
verify(transport, never()).send(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSmtpTestSendsToTheGivenAddress() throws Exception {
|
||||
MailTransport transport = mock(MailTransport.class);
|
||||
ContactMailer mailer = new ContactMailer(settings(RELAY), transport);
|
||||
|
||||
MailSendResult result = mailer.sendTest("acme", "Acme", "check@example.com");
|
||||
|
||||
assertEquals(MailSendResult.Status.SENT, result.status());
|
||||
ArgumentCaptor<MimeMessage> captor = ArgumentCaptor.forClass(MimeMessage.class);
|
||||
verify(transport).send(captor.capture());
|
||||
assertEquals("check@example.com", ((jakarta.mail.internet.InternetAddress)
|
||||
captor.getValue().getRecipients(Message.RecipientType.TO)[0]).getAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePasswordIsTheSitesSecretInClearAndReachesTheRelayCredentials() throws Exception {
|
||||
MailTransport transport = mock(MailTransport.class);
|
||||
ContactMailer mailer = new ContactMailer(settings(RELAY), transport);
|
||||
|
||||
SmtpSettings smtp = mailer.settingsFor("acme");
|
||||
assertEquals("s3cret", smtp.password(), "PluginSettings.secret supplies the password, already in clear");
|
||||
mailer.send("acme", "Acme", "Ann", "ann@example.com", "Hi");
|
||||
ArgumentCaptor<MimeMessage> captor = ArgumentCaptor.forClass(MimeMessage.class);
|
||||
verify(transport).send(captor.capture());
|
||||
PasswordAuthentication auth = credentials(captor.getValue().getSession());
|
||||
assertEquals("postmaster", auth.getUserName());
|
||||
assertEquals("s3cret", auth.getPassword(), "the relay is offered the secret's clear value");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPasswordFoundInTheSettingsViewIsNeverUsed() {
|
||||
// The kernel leaves secret keys out of the view; a value there anyway (a hand-built view, a future change)
|
||||
// must not become the password: only the declared secret, read through secret(), is trusted.
|
||||
Map<String, Object> withLeak = new HashMap<>(RELAY);
|
||||
withLeak.put("smtpPassword", "ENC(ciphertext-not-a-password)");
|
||||
ContactMailer viewOnly = new ContactMailer(new FakePluginSettings().site("acme", withLeak),
|
||||
mock(MailTransport.class));
|
||||
assertEquals("", viewOnly.settingsFor("acme").password(), "no secret ⇒ no password, whatever the view holds");
|
||||
|
||||
ContactMailer both = new ContactMailer(settings(withLeak), mock(MailTransport.class));
|
||||
assertEquals("s3cret", both.settingsFor("acme").password(), "the secret wins over anything in the view");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSecretIsReadForTheSendingSiteOnly() {
|
||||
FakePluginSettings settings = settings(RELAY).site("other", RELAY).secret("other", "smtpPassword", "other-pw");
|
||||
ContactMailer mailer = new ContactMailer(settings, mock(MailTransport.class));
|
||||
assertEquals("s3cret", mailer.settingsFor("acme").password());
|
||||
assertEquals("other-pw", mailer.settingsFor("other").password(), "each site authenticates with its own secret");
|
||||
assertEquals("", mailer.settingsFor("nobody").password(), "a site with no secret has no password");
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePasswordNeverAppearsInTheSettingsText() {
|
||||
String text = new ContactMailer(settings(RELAY), mock(MailTransport.class)).settingsFor("acme").toString();
|
||||
assertFalse(text.contains("s3cret"), "masked in logs: " + text);
|
||||
assertTrue(text.contains("password=<set>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void settingsAreReadTypedWithTheDescriptorDefaultsAndAClampedPort() {
|
||||
Map<String, Object> odd = new HashMap<>(RELAY);
|
||||
odd.put("smtpPort", 99999L);
|
||||
odd.put("smtpHost", " mail.example.com ");
|
||||
SmtpSettings smtp = new ContactMailer(settings(odd), mock(MailTransport.class)).settingsFor("acme");
|
||||
assertEquals(65535, smtp.port(), "the port is clamped to 1..65535");
|
||||
assertEquals("mail.example.com", smtp.host(), "values are stripped");
|
||||
SmtpSettings bare = new ContactMailer(new FakePluginSettings(), mock(MailTransport.class)).settingsFor("acme");
|
||||
assertEquals(25, bare.port(), "port 25 when unset");
|
||||
assertFalse(bare.auth());
|
||||
assertFalse(bare.isConfigured(), "no host and no recipient");
|
||||
}
|
||||
|
||||
@Test
|
||||
void implicitTlsRidesSslEnableOnTheSmtpProtocol() {
|
||||
// Regression: implicit TLS (SMTPS, e.g. 465) must ride mail.smtp.ssl.enable on the smtp protocol. Switching
|
||||
// to "smtps" left mail.smtp.host unset, so the static Transport.send() (which maps rfc822 -> smtp, ignoring
|
||||
// mail.transport.protocol) dialed localhost:25 and failed with "Connection refused".
|
||||
jakarta.mail.Session s = ContactMailer.session(new SmtpSettings(
|
||||
"mail.example.com", 465, true, "postmaster", "pw", false, true, "site@example.com", "owner@example.com"));
|
||||
|
||||
assertEquals("smtp", s.getProperty("mail.transport.protocol"), "protocol stays smtp (address map ignores smtps)");
|
||||
assertEquals("mail.example.com", s.getProperty("mail.smtp.host"), "host on mail.smtp.* (what the send reads)");
|
||||
assertEquals("465", s.getProperty("mail.smtp.port"));
|
||||
assertEquals("true", s.getProperty("mail.smtp.ssl.enable"), "implicit TLS on connect");
|
||||
assertNull(s.getProperty("mail.smtps.host"), "no smtps-scoped host the static send would silently ignore");
|
||||
assertNull(s.getProperty("mail.smtp.starttls.enable"), "implicit TLS and STARTTLS are mutually exclusive");
|
||||
}
|
||||
|
||||
@Test
|
||||
void starttlsRidesStarttlsEnableOnTheSmtpProtocol() {
|
||||
jakarta.mail.Session s = ContactMailer.session(new SmtpSettings(
|
||||
"mail.example.com", 587, false, null, null, true, false, "site@example.com", "owner@example.com"));
|
||||
|
||||
assertEquals("smtp", s.getProperty("mail.transport.protocol"));
|
||||
assertEquals("587", s.getProperty("mail.smtp.port"));
|
||||
assertEquals("true", s.getProperty("mail.smtp.starttls.enable"), "opportunistic STARTTLS");
|
||||
assertNull(s.getProperty("mail.smtp.ssl.enable"), "STARTTLS mode must not also enable implicit TLS");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* The submission store over {@code PluginSiteFiles} (the testkit's {@link TempDirSiteFiles}, which applies the
|
||||
* kernel's confinement rules): append + newest-first read, field sanitization, the bound, per-site isolation, the
|
||||
* on-disk location shared with 1.x, and that an unreadable file is never overwritten.
|
||||
*/
|
||||
class ContactStoreTest {
|
||||
|
||||
@TempDir
|
||||
Path sites;
|
||||
private TempDirSiteFiles files;
|
||||
private ContactStore store;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
Files.createDirectories(sites.resolve("acme"));
|
||||
Files.createDirectories(sites.resolve("other"));
|
||||
files = new TempDirSiteFiles(sites, "contact");
|
||||
store = new ContactStore(files);
|
||||
}
|
||||
|
||||
@Test
|
||||
void appendsAndReadsNewestFirst() {
|
||||
store.add("acme", "Ann", "ann@example.com", "First message", 1000L);
|
||||
store.add("acme", "Bob", "bob@example.com", "Second message", 2000L);
|
||||
|
||||
assertEquals(2, store.count("acme"));
|
||||
List<ContactSubmission> recent = store.recent("acme", 10);
|
||||
assertEquals("Bob", recent.get(0).name(), "newest first");
|
||||
assertEquals("Ann", recent.get(1).name());
|
||||
assertEquals("ann@example.com", recent.get(1).email());
|
||||
assertEquals(1, store.recent("acme", 1).size(), "the limit is honoured");
|
||||
}
|
||||
|
||||
@Test
|
||||
void writesTheSameFileAs1xSoExistingSubmissionsCarryOver() throws IOException {
|
||||
Path file = sites.resolve("acme/plugins/contact/submissions.tsv");
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.writeString(file, "500\tOld\told@example.com\tfrom contact 1.1.2\n", StandardCharsets.UTF_8);
|
||||
|
||||
store.add("acme", "New", "new@example.com", "after the upgrade", 900L);
|
||||
|
||||
assertEquals(2, store.count("acme"), "the 1.x submission is read from the same file");
|
||||
List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
|
||||
assertEquals(List.of("500\tOld\told@example.com\tfrom contact 1.1.2", "900\tNew\tnew@example.com\tafter the upgrade"),
|
||||
lines, "appended in place, one TSV line each");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tabsAndNewlinesAreSanitizedSoTheTsvFormatHolds() {
|
||||
store.add("acme", "Eve\tEvil", "e@example.com", "line one\nline two\tindented", 1000L);
|
||||
ContactSubmission s = store.recent("acme", 10).get(0);
|
||||
assertEquals("Eve Evil", s.name(), "tabs stripped from the field");
|
||||
assertEquals("line one line two indented", s.message(), "newlines/tabs collapsed to spaces");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFieldIsCappedAndTheFileKeepsOnlyTheMostRecentSubmissions() {
|
||||
store.add("acme", "Long", "l@example.com", "x".repeat(ContactStore.MAX_FIELD + 50), 1L);
|
||||
assertEquals(ContactStore.MAX_FIELD, store.recent("acme", 1).get(0).message().length());
|
||||
for (int i = 2; i <= ContactStore.MAX_SUBMISSIONS + 1; i++) {
|
||||
store.add("acme", "N" + i, "n@example.com", "m", i);
|
||||
}
|
||||
assertEquals(ContactStore.MAX_SUBMISSIONS, store.count("acme"), "bounded to the most recent");
|
||||
assertEquals("N" + (ContactStore.MAX_SUBMISSIONS + 1), store.recent("acme", 1).get(0).name());
|
||||
assertTrue(store.recent("acme", ContactStore.MAX_SUBMISSIONS).stream().noneMatch(s -> s.name().equals("Long")),
|
||||
"the oldest one was dropped");
|
||||
}
|
||||
|
||||
@Test
|
||||
void submissionsAreIsolatedPerSite() {
|
||||
store.add("acme", "Ann", "a@example.com", "for acme", 1000L);
|
||||
assertEquals(1, store.count("acme"));
|
||||
assertEquals(0, store.count("other"), "another site sees none of acme's submissions");
|
||||
assertTrue(store.recent("other", 10).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnreadableFileIsNeverOverwrittenAndTheConsoleReadsDegradeToEmpty() throws IOException {
|
||||
// A file over the read cap cannot be read: an append must fail rather than rewrite it from nothing.
|
||||
ContactStore small = new ContactStore(new TempDirSiteFiles(sites, "contact", 64));
|
||||
Path file = sites.resolve("acme/plugins/contact/submissions.tsv");
|
||||
Files.createDirectories(file.getParent());
|
||||
String big = "1\tA\ta@example.com\t" + "y".repeat(200) + "\n";
|
||||
Files.writeString(file, big, StandardCharsets.UTF_8);
|
||||
|
||||
assertThrows(UncheckedIOException.class, () -> small.add("acme", "B", "b@example.com", "hi", 2L));
|
||||
assertEquals(big, Files.readString(file, StandardCharsets.UTF_8), "the stored submissions are untouched");
|
||||
assertEquals(0, small.count("acme"), "the console count degrades to 0 instead of failing the screen");
|
||||
assertTrue(small.recent("acme", 10).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSiteWithoutAFolderIsAnErrorNotASilentCreate() {
|
||||
assertThrows(UncheckedIOException.class, () -> store.add("ghost", "A", "a@example.com", "hi", 1L),
|
||||
"the kernel refuses to create a deleted site's folder; the store reports it");
|
||||
assertTrue(Files.notExists(sites.resolve("ghost")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package mx.quest.contact;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import mx.quest.runway.spi.CaptchaService;
|
||||
import mx.quest.runway.spi.model.CaptchaWidget;
|
||||
import mx.quest.runway.spi.model.PageMeta;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.model.WidgetView;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The {@code contact} content widget renders the form inline on a normal page and re-renders the submit outcome
|
||||
* from the {@code ?contact=…} query the endpoint redirects back with. All rendering (form, thank-you, error
|
||||
* re-render, CAPTCHA, escaping) lives here — the endpoint only stores/sends/redirects. Settings and messages come
|
||||
* from the SPI services (testkit fakes).
|
||||
*/
|
||||
class ContactWidgetTest {
|
||||
|
||||
private static final SiteView ACME = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null);
|
||||
|
||||
private FakePluginSettings settings;
|
||||
private FakeSiteServices kernel;
|
||||
private final AtomicReference<CaptchaWidget> challenge = new AtomicReference<>(CaptchaWidget.inactive());
|
||||
private ContactWidget widget;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
settings = new FakePluginSettings().defaults(Map.of("enabled", true));
|
||||
kernel = new FakeSiteServices().site(ACME);
|
||||
CaptchaService captcha = new CaptchaService() {
|
||||
@Override
|
||||
public CaptchaWidget widgetForSite(String siteId) {
|
||||
return challenge.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(String siteId, String token, String clientIp) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
widget = new ContactWidget(settings, kernel, captcha);
|
||||
}
|
||||
|
||||
private String render(Map<String, String> query) {
|
||||
PageMeta page = new PageMeta("home", "Home", "", List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
|
||||
return widget.render(new WidgetView(ACME, page, Locale.ENGLISH, "contact", false, Map.of(), query)).html();
|
||||
}
|
||||
|
||||
@Test
|
||||
void theFormPostsAUrlEncodedBodyToTheAnonymousSubmitRoute() {
|
||||
String html = render(Map.of());
|
||||
assertTrue(html.contains("method=\"post\""), "the form POSTs — its fields never ride a URL: " + html);
|
||||
assertFalse(html.contains("method=\"get\""));
|
||||
assertTrue(html.contains("action=\"/contact/submit\""), "to the anonymous submit route");
|
||||
assertTrue(html.contains("enctype=\"application/x-www-form-urlencoded\""),
|
||||
"the only body an anonymous route accepts");
|
||||
assertFalse(html.contains("_csrf"), "no session token: the route is CSRF-exempt by declaration");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBareRenderShowsTheFormWithTheHoneypotAndTheReturnPath() {
|
||||
String html = render(Map.of());
|
||||
assertTrue(html.contains("name=\"message\""), "the message field is present");
|
||||
assertTrue(html.contains("name=\"website\""), "the honeypot field is present");
|
||||
// Lands the visitor back on this page (its slug path) after submit; a moved page is caught server-side by Referer.
|
||||
assertTrue(html.contains("name=\"return\" value=\"/home\""), "the return path is the page the widget lives on");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theReturnPathIsTheRequestPathWhenTheHostProvidesIt() {
|
||||
// A blog entry (a content source's page) renders this widget from the master chrome: its PageMeta slug
|
||||
// is a composite identity ("blog:my-post"), NOT a path — the request path from the view must win.
|
||||
PageMeta entry = new PageMeta("blog:my-post", "My post", "", List.of(Locale.ENGLISH), Locale.ENGLISH,
|
||||
true, false, "blog");
|
||||
String html = widget.render(new WidgetView(ACME, entry, Locale.ENGLISH, "contact", true, Map.of(),
|
||||
Map.of(), "/es/blog/mi-entrada")).html();
|
||||
assertTrue(html.contains("name=\"return\" value=\"/es/blog/mi-entrada\""),
|
||||
"the return path is the URL as served — never built from the composite slug");
|
||||
assertFalse(html.contains("/blog:my-post"), "the composite identity never leaks into a path");
|
||||
}
|
||||
|
||||
@Test
|
||||
void labelsComeFromTheSitesMessagesAndAreEscaped() {
|
||||
kernel.message("acme", "contact.form.submit", "Envoyer <maintenant>");
|
||||
String html = render(Map.of());
|
||||
assertTrue(html.contains(">Envoyer <maintenant></button>"), "Messages.site for the label: " + html);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSentOutcomeShowsAThankYouNotTheForm() {
|
||||
String html = render(Map.of("contact", "sent"));
|
||||
assertTrue(html.contains("rw-contact-success"), "a thank-you is shown");
|
||||
assertTrue(html.contains("Thanks — your message has been sent."), "the default thank-you text");
|
||||
assertFalse(html.contains("name=\"message\""), "the form is replaced by the confirmation");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theQueuedOutcomeThanksAndNotesTheDelayedDeliveryInsteadOfShowingTheFormAgain() {
|
||||
String html = render(Map.of("contact", "queued"));
|
||||
assertTrue(html.contains("rw-contact-success"), "the message was stored: thank the visitor");
|
||||
assertTrue(html.contains("email delivery is delayed"), "and say the email is late: " + html);
|
||||
assertFalse(html.contains("name=\"message\""), "no empty form inviting a duplicate submission");
|
||||
assertFalse(render(Map.of("contact", "sent")).contains("delayed"), "a plain success carries no note");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theConfiguredThankYouWinsAndIsEscaped() {
|
||||
settings.site("acme", Map.of("successMessage", "<b>x</b>"));
|
||||
String html = render(Map.of("contact", "sent"));
|
||||
assertFalse(html.contains("<b>x</b>"), "the configured thank-you is HTML-escaped");
|
||||
assertTrue(html.contains("<b>x</b>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInvalidOutcomeReRendersTheFormWithAnError() {
|
||||
String html = render(Map.of("contact", "invalid"));
|
||||
assertTrue(html.contains("rw-contact-error"), "the validation error is surfaced");
|
||||
assertTrue(html.contains("name=\"message\""), "the form re-renders so the visitor can retry");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCaptchaOutcomeReRendersTheFormWithAnError() {
|
||||
String html = render(Map.of("contact", "captcha"));
|
||||
assertTrue(html.contains("Please complete the challenge"), "the challenge error is surfaced");
|
||||
assertTrue(html.contains("name=\"message\""), "the form re-renders so the visitor can retry");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConfiguredChallengeRendersOnTheForm() {
|
||||
challenge.set(new CaptchaWidget(true, "g-recaptcha-response", "<div class=\"g-recaptcha\" data-sitekey=\"KEY\"></div>"));
|
||||
String html = render(Map.of());
|
||||
assertTrue(html.contains("data-sitekey=\"KEY\""), "the site's CAPTCHA renders inline");
|
||||
assertTrue(html.indexOf("data-sitekey") < html.indexOf("</form>"), "inside the form, so its token is posted");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDisabledContactRendersNothing() {
|
||||
settings.site("acme", Map.of("enabled", false));
|
||||
assertTrue(render(Map.of()).isEmpty(), "a disabled contact widget renders an empty fragment");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user