Runway 1.1.0

This commit is contained in:
Runway committed 2026-10-29 09:22:38 -06:00
1 parent ce217fc952
commit 07d5bd7e9a
223 files changed
+21147 -255

No files matched your search

@@ -441,6 +441,26 @@ class BackupServiceTest {
assertEquals(List.of("moved.test"), fresh.find("b").orElseThrow().hosts(), "b keeps it");
}
@Test
void aSiteManagersRestoreKeepsHowTheSiteIsReachedAPlatformAdminsBringsTheBackupsBack() throws IOException {
SiteStore store = new SiteStore(layout, new YamlStore());
store.save(new Site("r", "R", List.of("old.test"), Locale.ENGLISH, List.of(Locale.ENGLISH),
"https://evil.example", SiteStatus.ACTIVE)); // what an archive written by hand could say
ByteArrayOutputStream archive = new ByteArrayOutputStream();
svc.backup("r", archive);
store.save(store.find("r").orElseThrow().withHosts(List.of("r.test")).withBaseUrl(null));
svc.restore("r", new ByteArrayInputStream(archive.toByteArray()), true); // the site realm
Site kept = new SiteStore(layout, new YamlStore()).find("r").orElseThrow();
assertEquals(List.of("r.test"), kept.hosts());
assertEquals(null, kept.baseUrl());
svc.restore("r", new ByteArrayInputStream(archive.toByteArray())); // the application realm
Site back = new SiteStore(layout, new YamlStore()).find("r").orElseThrow();
assertEquals(List.of("old.test"), back.hosts());
assertEquals("https://evil.example", back.baseUrl());
}
@Test
void createFromBackupRejectsAnExistingId() throws IOException {
new SiteStore(layout, new YamlStore()).save(new Site("src", "Source", List.of(), Locale.ENGLISH,
@@ -28,10 +28,13 @@ import mx.quest.runway.spi.model.Realm;
import mx.quest.runway.storage.StorageLayout;
import mx.quest.runway.storage.StorageProperties;
import mx.quest.runway.storage.YamlStore;
import mx.quest.runway.web.ForwardedFor;
import mx.quest.runway.web.ProxyResolution;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
@@ -128,6 +131,39 @@ class AppAboutPageTest {
.andExpect(content().string(Matchers.containsString("href=\"/__app/settings\"")));
}
@Test
void aboutShowsThisRequestAsRunwaySeesIt() throws Exception {
MockHttpSession session = login();
mvc().perform(get("/__app/about").session(session).locale(Locale.ENGLISH))
.andExpect(status().isOk())
.andExpect(content().string(Matchers.containsString("This request")))
.andExpect(content().string(Matchers.containsString("Client address used")))
.andExpect(content().string(Matchers.containsString("Scheme and host")));
}
@Test
void theRequestRowsShowHowTheProxyGateAttributedIt() {
MockHttpServletRequest trusted = new MockHttpServletRequest("GET", "/__app/about");
trusted.setAttribute(ProxyResolution.ATTRIBUTE, new ProxyResolution("10.0.0.5", true, true,
new ForwardedFor.Chain(List.of("6.6.6.6", "203.0.113.7"), 2), "203.0.113.7"));
assertThat(info.request(trusted)).extracting(RuntimeInfoService.NameValue::value)
.containsExactly("10.0.0.5 (trusted proxy)", "6.6.6.6, 203.0.113.7", "203.0.113.7",
"http://localhost");
MockHttpServletRequest direct = new MockHttpServletRequest("GET", "/__app/about");
direct.setAttribute(ProxyResolution.ATTRIBUTE, new ProxyResolution("198.51.100.9", false, false,
new ForwardedFor.Chain(List.of("6.6.6.6"), 1), "198.51.100.9"));
assertThat(info.request(direct)).extracting(RuntimeInfoService.NameValue::value)
.containsExactly("198.51.100.9 (not a trusted proxy)", "6.6.6.6 (ignored)", "198.51.100.9",
"http://localhost");
MockHttpServletRequest none = new MockHttpServletRequest("GET", "/__app/about");
none.setAttribute(ProxyResolution.ATTRIBUTE,
new ProxyResolution("127.0.0.1", true, true, ForwardedFor.Chain.NONE, "127.0.0.1"));
assertThat(info.request(none)).extracting(RuntimeInfoService.NameValue::value)
.containsExactly("127.0.0.1 (trusted proxy)", "none", "127.0.0.1", "http://localhost");
}
@Test
void aboutRequiresAuthentication() throws Exception {
mvc().perform(get("/__app/about")).andExpect(status().is3xxRedirection());
@@ -2,6 +2,7 @@ package mx.quest.runway.console;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
@@ -9,6 +10,7 @@ import static org.springframework.security.test.web.servlet.setup.SecurityMockMv
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.io.IOException;
@@ -214,26 +216,62 @@ class AppSettingsScreenTest {
assertTrue(smtp.isConfigured());
}
private org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder passwordSave(String host,
String password)
throws Exception {
return passwordSave(host, password, "postmaster");
}
private org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder passwordSave(String host,
String password,
String username)
throws Exception {
return post("/__app/settings").session(sessionFor("admin")).with(csrf())
.param("defaultSiteId", "").param("passwordStrength", "")
.param("smtpHost", host).param("smtpFrom", "noreply@example.com")
.param("smtpAuth", "true").param("smtpUsername", username)
.param("smtpPassword", password);
}
@Test
void aBlankPasswordOnResavePreservesTheStoredSecret() throws Exception {
mvc.perform(post("/__app/settings").session(sessionFor("admin")).with(csrf())
.param("defaultSiteId", "").param("passwordStrength", "")
.param("smtpHost", "smtp.example.com").param("smtpFrom", "noreply@example.com")
.param("smtpAuth", "true").param("smtpUsername", "postmaster")
.param("smtpPassword", "original"))
.andExpect(status().is3xxRedirection());
void thePasswordAlsoFollowsThePortAndTheUsername() throws Exception {
mvc.perform(passwordSave("smtp.example.com", "original")).andExpect(status().is3xxRedirection());
mvc.perform(passwordSave("smtp.example.com", "").param("smtpPort", "2525"))
.andExpect(flash().attribute("flash", Matchers.containsString("SMTP password was cleared")));
assertNull(platform.get().smtp().password(), "another port: not sent there");
mvc.perform(passwordSave("smtp.example.com", "retyped").param("smtpPort", "2525"))
.andExpect(flash().attribute("flash", "Platform settings saved."));
mvc.perform(passwordSave("smtp.example.com", "", "someone-else").param("smtpPort", "2525"))
.andExpect(flash().attribute("flash", Matchers.containsString("SMTP password was cleared")));
assertNull(platform.get().smtp().password(), "another account: not sent for it");
}
@Test
void aBlankPasswordOnResaveKeepsTheStoredSecretOnlyForTheSameServer() throws Exception {
mvc.perform(passwordSave("smtp.example.com", "original")).andExpect(status().is3xxRedirection());
String stored = platform.get().smtp().password();
// Re-save with the password field BLANK and a changed host: the stored secret must be kept.
mvc.perform(post("/__app/settings").session(sessionFor("admin")).with(csrf())
.param("defaultSiteId", "").param("passwordStrength", "")
.param("smtpHost", "smtp2.example.com").param("smtpFrom", "noreply@example.com")
.param("smtpAuth", "true").param("smtpUsername", "postmaster")
.param("smtpPassword", ""))
.andExpect(status().is3xxRedirection());
// Same server, password field blank, another field changed: the stored secret is kept.
mvc.perform(passwordSave("SMTP.example.com", "").param("smtpStarttls", "true"))
.andExpect(flash().attribute("flash", "Platform settings saved."));
assertEquals(stored, platform.get().smtp().password(), "same host (any case): the secret stays");
// Another server with the field blank: the secret is not sent there, it is cleared and must be re-entered.
mvc.perform(passwordSave("smtp.attacker.example", ""))
.andExpect(status().is3xxRedirection())
.andExpect(flash().attribute("flash", Matchers.containsString("SMTP password was cleared")));
PlatformSettings.Smtp after = platform.get().smtp();
assertEquals(stored, after.password(), "a blank password field keeps the stored secret");
assertEquals("smtp2.example.com", after.host(), "the other fields still update");
assertNull(after.password(), "a blank field never carries the secret to a new host");
assertEquals("smtp.attacker.example", after.host(), "the other fields still update");
assertTrue(activityLog.tail(5).stream().anyMatch(line -> line.contains("platform.settings-changed")
&& line.contains("mail host") && line.contains("cleared SMTP password")
&& !line.contains("attacker")), "the log names what changed, never a value");
// Retyped with the new host: stored again.
mvc.perform(passwordSave("smtp.attacker.example", "retyped"))
.andExpect(flash().attribute("flash", "Platform settings saved."));
assertTrue(platform.get().smtp().password().startsWith("ENC("));
}
@Test
@@ -251,6 +289,117 @@ class AppSettingsScreenTest {
.andExpect(content().string(Matchers.not(Matchers.containsString("ENC("))));
}
private org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder oauthSave(String tokenUrl,
String secret,
boolean starttls)
throws Exception {
return oauthSave(tokenUrl, secret, starttls, "smtp.office365.com", "587", "client-1",
"https://outlook.office365.com/.default");
}
private org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder oauthSave(String tokenUrl,
String secret, boolean starttls, String host, String port, String clientId, String scope) throws Exception {
var post = post("/__app/settings").session(sessionFor("admin")).with(csrf())
.param("defaultSiteId", "").param("passwordStrength", "")
.param("smtpHost", host).param("smtpPort", port)
.param("smtpFrom", "noreply@example.com")
.param("smtpAuth", "true").param("smtpUsername", "noreply@example.com")
.param("smtpAuthMethod", "oauth2").param("smtpOauthTokenUrl", tokenUrl)
.param("smtpOauthClientId", clientId).param("smtpOauthClientSecret", secret)
.param("smtpOauthScope", scope);
return starttls ? post.param("smtpStarttls", "true") : post;
}
@Test
void theClientSecretFollowsTheClientTheMailServerAndTheScope() throws Exception {
String endpoint = "https://login.microsoftonline.com/t-1/oauth2/v2.0/token";
String scope = "https://outlook.office365.com/.default";
mvc.perform(oauthSave(endpoint, "client-s3cret", true)).andExpect(flash().attributeExists("flash"));
String stored = platform.get().smtp().oauthClientSecret();
// Each with the secret field blank: refused, nothing changed. The token minted from the secret would go to
// that server, or be asked for another scope.
for (var move : List.of(oauthSave(endpoint, "", true, "smtp.attacker.example", "587", "client-1", scope),
oauthSave(endpoint, "", true, "smtp.office365.com", "2525", "client-1", scope),
oauthSave(endpoint, "", true, "smtp.office365.com", "587", "client-2", scope),
oauthSave(endpoint, "", true, "smtp.office365.com", "587", "client-1", "https://graph.example/.default"))) {
mvc.perform(move).andExpect(flash().attribute("error",
Matchers.containsString("Enter the OAuth2 client secret again")));
PlatformSettings.Smtp now = platform.get().smtp();
assertEquals(stored, now.oauthClientSecret());
assertEquals("smtp.office365.com", now.host());
assertEquals(587, now.port());
assertEquals("client-1", now.oauthClientId());
assertEquals(scope, now.oauthScope());
}
// The same move with the secret typed again is saved.
mvc.perform(oauthSave(endpoint, "typed-again", true, "smtp.example.net", "587", "client-1", scope))
.andExpect(flash().attribute("flash", "Platform settings saved."));
assertEquals("smtp.example.net", platform.get().smtp().host());
}
@Test
void savingAnOAuth2AccountStoresItAndEncryptsTheClientSecret() throws Exception {
mvc.perform(oauthSave("https://login.microsoftonline.com/t-1/oauth2/v2.0/token", "client-s3cret", true))
.andExpect(status().is3xxRedirection())
.andExpect(flash().attributeExists("flash"));
PlatformSettings.Smtp smtp = platform.get().smtp();
assertTrue(smtp.usesOAuth2());
assertEquals("https://login.microsoftonline.com/t-1/oauth2/v2.0/token", smtp.oauthTokenUrl());
assertEquals("client-1", smtp.oauthClientId());
assertEquals("https://outlook.office365.com/.default", smtp.oauthScope());
assertTrue(smtp.oauthClientSecret().startsWith("ENC("), "the client secret is stored encrypted");
assertFalse(smtp.oauthClientSecret().contains("client-s3cret"));
// Re-save with the secret field blank: the stored secret is kept.
String stored = smtp.oauthClientSecret();
mvc.perform(oauthSave("https://login.microsoftonline.com/t-1/oauth2/v2.0/token", "", true))
.andExpect(flash().attributeExists("flash"));
assertEquals(stored, platform.get().smtp().oauthClientSecret());
// A new token endpoint with the field blank is refused: the stored secret is never sent to it.
mvc.perform(oauthSave("https://login.attacker.example/token", "", true))
.andExpect(flash().attribute("error", Matchers.containsString("Enter the OAuth2 client secret again")));
assertEquals("https://login.microsoftonline.com/t-1/oauth2/v2.0/token", platform.get().smtp().oauthTokenUrl(),
"the refused save changed nothing");
assertEquals(stored, platform.get().smtp().oauthClientSecret());
mvc.perform(get("/__app/settings").session(sessionFor("admin")))
.andExpect(status().isOk())
.andExpect(content().string(Matchers.containsString("name=\"smtpOauthClientSecret\"")))
.andExpect(content().string(Matchers.containsString(
"value=\"https://login.microsoftonline.com/t-1/oauth2/v2.0/token\"")))
.andExpect(content().string(Matchers.matchesRegex(
"(?s).*<option[^>]*value=\"oauth2\"[^>]*selected.*|.*<option[^>]*selected[^>]*value=\"oauth2\".*")))
.andExpect(content().string(Matchers.not(Matchers.containsString("client-s3cret"))))
.andExpect(content().string(Matchers.not(Matchers.containsString("ENC("))));
}
@Test
void anOAuth2AccountWithoutTlsOrWithAPlainHttpEndpointIsRefusedOnSave() throws Exception {
mvc.perform(oauthSave("https://login.microsoftonline.com/t-1/oauth2/v2.0/token", "x", false))
.andExpect(flash().attribute("error", Matchers.containsString("STARTTLS or implicit TLS")));
mvc.perform(oauthSave("http://login.example.com/token", "x", true))
.andExpect(flash().attribute("error", Matchers.containsString("must use https")));
mvc.perform(oauthSave("https://login.microsoftonline.com/t-1/oauth2/v2.0/token", "", true))
.andExpect(flash().attribute("error", Matchers.containsString("client secret")));
assertNull(platform.get().smtp(), "nothing was stored");
}
@Test
void aTestEmailThatCannotGetATokenSaysSo() throws Exception {
// Loopback http is allowed; nothing listens on port 1, so the token request fails before any SMTP.
mvc.perform(oauthSave("http://127.0.0.1:1/token", "x", true)).andExpect(flash().attributeExists("flash"));
mvc.perform(post("/__app/settings/test-email").session(sessionFor("admin")).with(csrf())
.param("testTo", "someone@example.com"))
.andExpect(status().is3xxRedirection())
.andExpect(flash().attribute("error", Matchers.allOf(
Matchers.containsString("no OAuth2 token"),
Matchers.containsString("OAuth2 token request to 127.0.0.1 failed"))));
}
@Test
void aTestEmailWithoutAConfiguredAccountRedirectsWithoutSending() throws Exception {
// Nothing configured (EMPTY seeded in setUp): the test action must not 500 — it redirects with an error.
@@ -80,6 +80,10 @@ class AppSiteHostsScreenTest {
sites.save(new Site("beta", "Beta", List.of("beta.test"), EN, List.of(EN), null, SiteStatus.ACTIVE));
sites.save(new Site("gamma", "Gamma", List.of("gamma.test"), EN, List.of(EN), null, SiteStatus.ACTIVE));
sites.save(new Site("delta", "Delta", List.of("delta.test"), EN, List.of(EN), null, SiteStatus.ACTIVE));
// The default site: with runway.console.hosts unset, the console's reset links go to its address.
sites.save(new Site("main", "Main", List.of("main.test"), EN, List.of(EN), null, SiteStatus.ACTIVE));
new mx.quest.runway.platform.PlatformSettingsStore(StorageLayout.from(props), new YamlStore())
.update(current -> current.withDefaultSiteId("main"));
new GrantStore(StorageLayout.from(props), new YamlStore())
.saveAppGrants(GrantFile.empty().withUserPermission("app-hosts", "MANAGE_SITE_HOSTS"));
registry.add("runway.storage.external", () -> external.toString());
@@ -151,6 +155,29 @@ class AppSiteHostsScreenTest {
.andExpect(status().isForbidden());
}
@Test
void onlyAPlatformAdminChangesTheDefaultSitesHostsOrBaseUrl() throws Exception {
MockHttpSession hoster = login("hoster", OPERATOR_PW);
mvc.perform(post("/__app/sites/main/hosts").session(hoster).with(csrf())
.param("hosts", "main.test").param("baseUrl", "https://evil.example"))
.andExpect(status().isForbidden());
mvc.perform(post("/__app/sites/main/hosts").session(hoster).with(csrf()).param("hosts", "evil.example"))
.andExpect(status().isForbidden());
Site main = siteStore.find("main").orElseThrow();
assertEquals(List.of("main.test"), main.hosts());
assertEquals(null, main.baseUrl());
String html = mvc.perform(get("/__app/sites").session(hoster)).andReturn().getResponse().getContentAsString();
assertFalse(html.contains("/__app/sites/main/hosts"), "no Edit hosts on the default site's row for them");
assertTrue(html.contains("/__app/sites/gamma/hosts") || html.contains("/__app/sites/acme/hosts"),
"the other rows keep it");
MockHttpSession master = login("admin", MASTER_PW);
mvc.perform(post("/__app/sites/main/hosts").session(master).with(csrf())
.param("hosts", "main.test, www.main.test"))
.andExpect(status().is3xxRedirection());
assertEquals(List.of("main.test", "www.main.test"), siteStore.find("main").orElseThrow().hosts());
}
@Test
void theBaseUrlIsSetCheckedAndClearedInTheSameDialog() throws Exception {
MockHttpSession session = login("admin", MASTER_PW);
@@ -13,6 +13,7 @@ import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import mx.quest.runway.platform.PlatformSettings;
import mx.quest.runway.platform.PlatformSettingsStore;
@@ -23,6 +24,9 @@ import mx.quest.runway.security.PasswordStrength;
import mx.quest.runway.security.Roles;
import mx.quest.runway.security.User;
import mx.quest.runway.security.UserStore;
import mx.quest.runway.site.Site;
import mx.quest.runway.site.SiteStatus;
import mx.quest.runway.site.SiteStore;
import mx.quest.runway.spi.model.Realm;
import mx.quest.runway.storage.YamlStore;
import org.hamcrest.Matchers;
@@ -71,6 +75,8 @@ class RecoveryScreenTest {
private RecoveryTokenStore tokens;
@Autowired
private AppUserStore appUsers;
@Autowired
private SiteStore sites;
private MockMvc mvc;
@BeforeEach
@@ -160,12 +166,21 @@ class RecoveryScreenTest {
}
@Test
void theLoginPageShowsForgotOnlyWhenMailIsConfigured() throws Exception {
void theLoginPageShowsForgotOnlyWithMailAndAnAddressForTheLink() throws Exception {
mvc.perform(get("/app/login"))
.andExpect(status().isOk())
.andExpect(content().string(Matchers.not(Matchers.containsString("/app/forgot-password"))));
// Mail alone is not enough: with no runway.console.hosts and no default site with a host name, there is no
// address a reset link may point at (never the request's own host), so recovery is not offered.
configureMail();
mvc.perform(get("/app/login"))
.andExpect(status().isOk())
.andExpect(content().string(Matchers.not(Matchers.containsString("/app/forgot-password"))));
sites.save(new Site("main", "Main", List.of("www.main.test"), Locale.ENGLISH, List.of(Locale.ENGLISH), null,
SiteStatus.ACTIVE, false, null));
platform.update(current -> current.withDefaultSiteId("main"));
mvc.perform(get("/app/login"))
.andExpect(status().isOk())
.andExpect(content().string(Matchers.containsString("/app/forgot-password")));
@@ -191,6 +191,6 @@ class TenantAuditRecordingTest {
@Test
void aTenantSignOutIsJournaled() throws Exception {
mvc.perform(post("/logout").session(admin()).with(csrf())).andExpect(status().is3xxRedirection());
verify(siteLog).audit("acme", "admin", "logout", "");
verify(siteLog).audit("acme", "admin", "logout", "ip=127.0.0.1"); // MockMvc's client address
}
}
@@ -22,7 +22,7 @@ import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.junit.jupiter.api.AfterEach;
/** The audit listener records tenant login outcomes, and skips app-realm logins (no bound site). */
/** The audit listener records tenant login outcomes with the client address, and skips app-realm logins. */
class AuditEventListenerTest {
private static Site site() {
@@ -88,7 +88,26 @@ class AuditEventListenerTest {
new AuditEventListener(resolver, logs)
.onLogout(new LogoutSuccessEvent(new UsernamePasswordAuthenticationToken("bob", "x")));
verify(logs).audit("acme", "bob", "logout", "");
verify(logs).audit("acme", "bob", "logout", "ip=127.0.0.1");
}
@Test
void aLoginRecordsTheResolvedClientAddressNotTheProxy() {
SiteResolver resolver = mock(SiteResolver.class);
when(resolver.current()).thenReturn(Optional.of(site()));
SiteLogService logs = mock(SiteLogService.class);
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/login");
request.setRemoteAddr("198.51.100.7"); // what TrustedForwardedHeaderFilter left after reading the proxy's XFF
request.addHeader("X-Forwarded-For", "203.0.113.66"); // never read here
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
AuditEventListener listener = new AuditEventListener(resolver, logs);
listener.onSuccess(new AuthenticationSuccessEvent(new UsernamePasswordAuthenticationToken("bob", "x")));
listener.onFailure(new AuthenticationFailureBadCredentialsEvent(
new UsernamePasswordAuthenticationToken("mallory", "x"), new BadCredentialsException("bad")));
verify(logs).audit("acme", "bob", "login.success", "ip=198.51.100.7");
verify(logs).audit("acme", "mallory", "login.failure", "ip=198.51.100.7");
}
@Test
@@ -0,0 +1,362 @@
package mx.quest.runway.mail;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* The OAuth2 client-credentials exchange against a real HTTP server on loopback: what is posted, what is cached and
* for how long, how a refusal is reported (with the provider's reason and never the secret), and which endpoints are
* accepted at all.
*/
class OAuth2TokenClientTest {
private static final String SECRET = "s3cr3t~value+/=";
/** A clock the test moves by hand. */
private static final class TestClock extends Clock {
Instant now = Instant.parse("2026-10-28T22:00:00Z");
@Override public ZoneId getZone() {
return ZoneOffset.UTC;
}
@Override public Clock withZone(ZoneId zone) {
return this;
}
@Override public Instant instant() {
return now;
}
}
private HttpServer server;
private final List<Map<String, String>> posted = new ArrayList<>();
private final List<String> contentTypes = new ArrayList<>();
private volatile int status = 200;
private volatile String responseBody;
private volatile String location;
private int issued;
private final TestClock clock = new TestClock();
private OAuth2TokenClient client;
@BeforeEach
void start() throws IOException {
server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
server.createContext("/tenant/oauth2/v2.0/token", exchange -> {
String form = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
Map<String, String> fields = new LinkedHashMap<>();
for (String pair : form.split("&")) {
String[] kv = pair.split("=", 2);
fields.put(URLDecoder.decode(kv[0], StandardCharsets.UTF_8),
kv.length > 1 ? URLDecoder.decode(kv[1], StandardCharsets.UTF_8) : "");
}
synchronized (posted) {
posted.add(fields);
contentTypes.add(exchange.getRequestHeaders().getFirst("Content-Type"));
issued++;
}
String body = responseBody != null ? responseBody
: "{\"token_type\":\"Bearer\",\"expires_in\":3600,\"access_token\":\"token-" + issued + "\"}";
if (location != null) {
exchange.getResponseHeaders().add("Location", location);
}
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(status, bytes.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(bytes);
}
});
server.start();
// The application's own client, so a test of redirects or timeouts tests what runs in production.
client = new OAuth2TokenClient(OAuth2TokenClient.httpClient(), clock);
}
@AfterEach
void stop() {
server.stop(0);
}
private OAuth2TokenClient.Request request() {
return new OAuth2TokenClient.Request(
"http://127.0.0.1:" + server.getAddress().getPort() + "/tenant/oauth2/v2.0/token",
"client-123", SECRET, "https://outlook.office365.com/.default");
}
@Test
void postsAClientCredentialsGrantAndReturnsTheToken() throws Exception {
assertThat(client.token(request())).isEqualTo("token-1");
assertThat(posted).hasSize(1);
assertThat(posted.getFirst()).containsExactly(
Map.entry("grant_type", "client_credentials"),
Map.entry("client_id", "client-123"),
Map.entry("client_secret", SECRET), // form-encoded on the wire, decoded intact
Map.entry("scope", "https://outlook.office365.com/.default"));
assertThat(contentTypes.getFirst()).isEqualTo("application/x-www-form-urlencoded");
}
@Test
void aBlankScopeIsNotSent() throws Exception {
OAuth2TokenClient.Request r = request();
client.token(new OAuth2TokenClient.Request(r.tokenUrl(), r.clientId(), r.clientSecret(), " "));
assertThat(posted.getFirst()).doesNotContainKey("scope");
}
@Test
void aTokenIsReusedUntilFiveMinutesBeforeItExpires() throws Exception {
assertThat(client.token(request())).isEqualTo("token-1");
clock.now = clock.now.plusSeconds(3600 - 300 - 1);
assertThat(client.token(request())).isEqualTo("token-1");
assertThat(posted).hasSize(1);
clock.now = clock.now.plusSeconds(1);
assertThat(client.token(request())).isEqualTo("token-2");
assertThat(posted).hasSize(2);
}
@Test
void aShortLivedTokenIsRenewedAtHalfItsLifetime() throws Exception {
responseBody = "{\"token_type\":\"Bearer\",\"expires_in\":\"60\",\"access_token\":\"short\"}";
client.token(request());
clock.now = clock.now.plusSeconds(29);
client.token(request());
assertThat(posted).hasSize(1);
clock.now = clock.now.plusSeconds(1);
client.token(request());
assertThat(posted).hasSize(2);
}
@Test
void changingAnyPartOfTheRequestOrForgettingAsksAgain() throws Exception {
client.token(request());
OAuth2TokenClient.Request r = request();
assertThat(client.token(new OAuth2TokenClient.Request(r.tokenUrl(), r.clientId(), "rotated", r.scope())))
.isEqualTo("token-2");
assertThat(client.token(new OAuth2TokenClient.Request(r.tokenUrl(), "other", "rotated", r.scope())))
.isEqualTo("token-3");
client.forget();
assertThat(client.token(new OAuth2TokenClient.Request(r.tokenUrl(), "other", "rotated", r.scope())))
.isEqualTo("token-4");
}
@Test
void aRefusalNamesTheStatusAndTheProvidersReasonButNeverTheSecret() {
status = 401;
responseBody = "{\"error\":\"invalid_client\",\"error_description\":\"AADSTS7000215: Invalid client "
+ "secret provided.\\r\\nTrace ID: abc\"}";
assertThatThrownBy(() -> client.token(request()))
.isInstanceOf(OAuth2TokenClient.TokenException.class)
.hasMessageContaining("127.0.0.1")
.hasMessageContaining("HTTP 401")
.hasMessageContaining("invalid_client")
.hasMessageContaining("AADSTS7000215: Invalid client secret provided. Trace ID: abc")
.hasMessageNotContaining(SECRET);
}
@Test
void aRefusalIsNotCached() throws Exception {
status = 500;
responseBody = "oops";
assertThatThrownBy(() -> client.token(request())).hasMessageContaining("HTTP 500");
status = 200;
responseBody = null;
assertThat(client.token(request())).isEqualTo("token-2");
}
@Test
void aResponseWithoutABearerTokenIsRefused() {
responseBody = "{\"token_type\":\"Bearer\",\"expires_in\":3600}";
assertThatThrownBy(() -> client.token(request())).hasMessageContaining("has no access_token");
responseBody = "{\"token_type\":\"mac\",\"access_token\":\"t\"}";
assertThatThrownBy(() -> client.token(request())).hasMessageContaining("not a bearer token");
responseBody = "<html>login page</html>";
assertThatThrownBy(() -> client.token(request())).hasMessageContaining("has no access_token");
}
@Test
void anOversizedResponseIsRefused() {
responseBody = "{\"access_token\":\"" + "a".repeat(OAuth2TokenClient.MAX_RESPONSE_BYTES) + "\"}";
assertThatThrownBy(() -> client.token(request())).hasMessageContaining("larger than");
}
@Test
void aServerThatStallsInTheMiddleOfTheBodyIsCutOffAtTheDeadline() throws Exception {
CountDownLatch release = new CountDownLatch(1);
server.createContext("/stall", exchange -> {
exchange.getRequestBody().readAllBytes();
exchange.sendResponseHeaders(200, 1000); // headers at once, then the body never comes
try (OutputStream out = exchange.getResponseBody()) {
out.write("{\"access_token\":".getBytes(StandardCharsets.UTF_8));
out.flush();
release.await(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (IOException closed) {
// the client gave up
}
});
OAuth2TokenClient bounded = new OAuth2TokenClient(OAuth2TokenClient.httpClient(), clock,
Duration.ofSeconds(2));
OAuth2TokenClient.Request r = request();
long start = System.nanoTime();
try {
assertThatThrownBy(() -> bounded.token(new OAuth2TokenClient.Request(
r.tokenUrl().replace("/tenant/oauth2/v2.0/token", "/stall"), r.clientId(), r.clientSecret(),
r.scope())))
.isInstanceOf(OAuth2TokenClient.TokenException.class)
.hasMessageContaining("did not complete within 2 seconds");
} finally {
release.countDown();
}
assertThat(Duration.ofNanos(System.nanoTime() - start)).isLessThan(Duration.ofSeconds(10));
}
@Test
void sendersWaitingOnAStalledProviderShareOneRequestAndOneDeadline() throws Exception {
CountDownLatch release = new CountDownLatch(1);
java.util.concurrent.atomic.AtomicInteger stalled = new java.util.concurrent.atomic.AtomicInteger();
server.createContext("/stall", exchange -> {
stalled.incrementAndGet();
exchange.getRequestBody().readAllBytes();
try {
release.await(30, TimeUnit.SECONDS); // no answer at all
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
exchange.close();
});
OAuth2TokenClient bounded = new OAuth2TokenClient(OAuth2TokenClient.httpClient(), clock,
Duration.ofSeconds(2));
OAuth2TokenClient.Request r = request();
OAuth2TokenClient.Request stalling = new OAuth2TokenClient.Request(
r.tokenUrl().replace("/tenant/oauth2/v2.0/token", "/stall"), r.clientId(), r.clientSecret(), r.scope());
java.util.concurrent.ExecutorService senders = java.util.concurrent.Executors.newFixedThreadPool(4);
long start = System.nanoTime();
try {
List<java.util.concurrent.Future<Throwable>> results = new ArrayList<>();
for (int i = 0; i < 4; i++) {
results.add(senders.submit(() -> {
try {
bounded.token(stalling);
return null;
} catch (Throwable t) {
return t;
}
}));
}
for (var result : results) {
assertThat(result.get(20, TimeUnit.SECONDS)).isInstanceOf(OAuth2TokenClient.TokenException.class);
}
} finally {
release.countDown();
senders.shutdownNow();
}
// One deadline for all four (2 s, plus a moment), not four in turn.
assertThat(Duration.ofNanos(System.nanoTime() - start)).isLessThan(Duration.ofMillis(4500));
assertThat(stalled.get()).isEqualTo(1);
}
@Test
void concurrentSendersGetOneTokenFromOneRequest() throws Exception {
java.util.concurrent.ExecutorService senders = java.util.concurrent.Executors.newFixedThreadPool(4);
try {
List<java.util.concurrent.Future<String>> tokens = new ArrayList<>();
for (int i = 0; i < 4; i++) {
tokens.add(senders.submit(() -> client.token(request())));
}
for (var token : tokens) {
assertThat(token.get(20, TimeUnit.SECONDS)).isEqualTo("token-1");
}
} finally {
senders.shutdownNow();
}
assertThat(issued).isEqualTo(1);
}
@Test
void aRedirectIsNotFollowedSoTheSecretGoesNowhereElse() {
status = 302;
location = "https://elsewhere.example/steal";
responseBody = "";
assertThatThrownBy(() -> client.token(request())).hasMessageContaining("HTTP 302");
// 307 is the one a following client would answer by POSTing the form, secret included, again.
status = 307;
location = "/tenant/oauth2/v2.0/token";
assertThatThrownBy(() -> client.token(request())).hasMessageContaining("HTTP 307");
assertThat(posted).hasSize(2); // one POST per call: nothing re-sent
}
@Test
void anUnreachableEndpointIsReportedAsATokenFailure() {
server.stop(0);
assertThatThrownBy(() -> client.token(request()))
.isInstanceOf(OAuth2TokenClient.TokenException.class)
.hasMessageContaining("OAuth2 token request to 127.0.0.1 failed");
}
@Test
void onlyHttpsOrLoopbackHttpEndpointsAreAccepted() throws Exception {
assertThat(OAuth2TokenClient.endpoint(endpoint("https://login.microsoftonline.com/t/oauth2/v2.0/token")))
.hasHost("login.microsoftonline.com");
assertThat(OAuth2TokenClient.endpoint(endpoint("http://localhost:9000/token"))).hasHost("localhost");
assertThat(OAuth2TokenClient.endpoint(endpoint("http://[::1]:9000/token"))).hasPort(9000);
for (String refused : List.of("http://login.example.com/token", "http://10.0.0.5/token",
"ftp://login.example.com/token", "https://user:pw@login.example.com/token",
"https://login.example.com/token#x", "login.example.com/token", "https://", "not a url")) {
assertThatThrownBy(() -> OAuth2TokenClient.endpoint(endpoint(refused)))
.as(refused).isInstanceOf(OAuth2TokenClient.TokenException.class);
}
}
@Test
void anIncompleteRequestIsRefusedBeforeAnyCall() {
for (OAuth2TokenClient.Request incomplete : List.of(
new OAuth2TokenClient.Request(null, "c", "s", null),
new OAuth2TokenClient.Request("https://l.example/t", " ", "s", null),
new OAuth2TokenClient.Request("https://l.example/t", "c", null, null))) {
assertThatThrownBy(() -> client.token(incomplete)).hasMessageContaining("needs a token endpoint");
}
assertThat(posted).isEmpty();
}
@Test
void theRequestNeverPrintsItsSecret() {
assertThat(request().toString()).doesNotContain(SECRET).contains("client-123");
}
private static OAuth2TokenClient.Request endpoint(String url) {
return new OAuth2TokenClient.Request(url, "c", "s", null);
}
}
@@ -6,12 +6,16 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import jakarta.mail.AuthenticationFailedException;
import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.internet.MimeMessage;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import mx.quest.runway.crypto.SecretCipher;
import mx.quest.runway.platform.PlatformSettings;
@@ -76,7 +80,7 @@ class PlatformMailerTest {
@Test
void isConfiguredReflectsHostAndFrom(@TempDir Path root) {
PlatformSettingsStore settings = store(root);
PlatformMailer mailer = new PlatformMailer(settings, new RecordingCipher(), new CapturingTransport());
PlatformMailer mailer = new PlatformMailer(settings, new RecordingCipher(), new CapturingTransport(), new OAuth2TokenClient());
assertFalse(mailer.isConfigured(), "no smtp block ⇒ not configured");
settings.update(previous -> PlatformSettings.EMPTY.withSmtp(
@@ -94,7 +98,7 @@ class PlatformMailerTest {
settings.update(previous -> PlatformSettings.EMPTY.withSmtp(
new PlatformSettings.Smtp("smtp.example.com", 587, false, null, null, "noreply@example.com", true, false)));
CapturingTransport transport = new CapturingTransport();
PlatformMailer mailer = new PlatformMailer(settings, new RecordingCipher(), transport);
PlatformMailer mailer = new PlatformMailer(settings, new RecordingCipher(), transport, new OAuth2TokenClient());
mailer.send("user@example.org", "Reset your password", "Click the link.");
@@ -110,7 +114,7 @@ class PlatformMailerTest {
void anUnconfiguredAccountRefusesToSend(@TempDir Path root) {
PlatformSettingsStore settings = store(root);
CapturingTransport transport = new CapturingTransport();
PlatformMailer mailer = new PlatformMailer(settings, new RecordingCipher(), transport);
PlatformMailer mailer = new PlatformMailer(settings, new RecordingCipher(), transport, new OAuth2TokenClient());
assertThrows(MessagingException.class, () -> mailer.send("a@b.com", "s", "b"));
assertEquals(0, transport.count, "nothing is sent when the platform account is not configured");
@@ -128,7 +132,7 @@ class PlatformMailerTest {
}
};
CapturingTransport transport = new CapturingTransport();
PlatformMailer mailer = new PlatformMailer(settings, wrongKey, transport);
PlatformMailer mailer = new PlatformMailer(settings, wrongKey, transport, new OAuth2TokenClient());
// Callers handle MessagingException (recovery stays non-enumerating, the test-send shows an error);
// an IllegalStateException would escape them.
@@ -144,7 +148,7 @@ class PlatformMailerTest {
String stored = cipher.encrypt("hunter2");
settings.update(previous -> PlatformSettings.EMPTY.withSmtp(new PlatformSettings.Smtp(
"smtp.example.com", 587, true, "postmaster", stored, "noreply@example.com", true, false)));
PlatformMailer mailer = new PlatformMailer(settings, cipher, new CapturingTransport());
PlatformMailer mailer = new PlatformMailer(settings, cipher, new CapturingTransport(), new OAuth2TokenClient());
mailer.send("user@example.org", "s", "b");
@@ -160,7 +164,7 @@ class PlatformMailerTest {
// mail.transport.protocol); a "smtps" value left mail.smtp.host unset, so the send dialed localhost:25 and
// failed with "Connection refused". Implicit TLS must ride mail.smtp.ssl.enable on the smtp protocol.
RecordingCipher cipher = new RecordingCipher();
PlatformMailer mailer = new PlatformMailer(store(root), cipher, new CapturingTransport());
PlatformMailer mailer = new PlatformMailer(store(root), cipher, new CapturingTransport(), new OAuth2TokenClient());
Session s = mailer.session(new PlatformSettings.Smtp(
"mail.example.com", 465, true, "postmaster", cipher.encrypt("pw"), "noreply@example.com", false, true));
@@ -175,7 +179,7 @@ class PlatformMailerTest {
@Test
void starttlsRidesStarttlsEnableOnTheSmtpProtocol(@TempDir Path root) throws MessagingException {
PlatformMailer mailer = new PlatformMailer(store(root), new RecordingCipher(), new CapturingTransport());
PlatformMailer mailer = new PlatformMailer(store(root), new RecordingCipher(), new CapturingTransport(), new OAuth2TokenClient());
Session s = mailer.session(new PlatformSettings.Smtp(
"mail.example.com", 587, false, null, null, "noreply@example.com", true, false));
@@ -191,7 +195,7 @@ class PlatformMailerTest {
@Test
void everySessionHasBoundedWaitsAndImplicitTlsChecksTheServerName(@TempDir Path root) throws MessagingException {
RecordingCipher cipher = new RecordingCipher();
PlatformMailer mailer = new PlatformMailer(store(root), cipher, new CapturingTransport());
PlatformMailer mailer = new PlatformMailer(store(root), cipher, new CapturingTransport(), new OAuth2TokenClient());
for (PlatformSettings.Smtp smtp : java.util.List.of(
new PlatformSettings.Smtp("m.example.com", 25, false, null, null, "n@example.com", false, false),
new PlatformSettings.Smtp("m.example.com", 587, false, null, null, "n@example.com", true, false),
@@ -210,4 +214,186 @@ class PlatformMailerTest {
assertEquals("false", plain.getProperty("mail.smtp.starttls.enable"), "plain says so explicitly");
assertNull(plain.getProperty("mail.smtp.starttls.required"));
}
/** A token client that hands out a fixed token and counts what it was asked, with no HTTP. */
private static final class FixedTokens extends OAuth2TokenClient {
final List<Request> asked = new ArrayList<>();
int forgotten;
FixedTokens() {
super(null, java.time.Clock.systemUTC());
}
@Override public synchronized String token(Request request) {
asked.add(request);
return "eyJ0eXAi.token";
}
@Override public synchronized void forget() {
forgotten++;
}
}
private static PlatformSettings.Smtp oauth(RecordingCipher cipher, String username, boolean starttls) {
return new PlatformSettings.Smtp("smtp.office365.com", 587, true, username, null, "noreply@example.com",
starttls, false, PlatformSettings.Smtp.AUTH_OAUTH2,
"https://login.microsoftonline.com/tenant-1/oauth2/v2.0/token", "client-1",
cipher.encrypt("client-secret"), "https://outlook.office365.com/.default");
}
private static PasswordAuthentication credentials(Session session) {
return session.requestPasswordAuthentication(null, 587, "smtp", null, null);
}
@Test
void anOAuth2AccountSignsInWithXoauth2AndTheTokenAsThePassword(@TempDir Path root) throws MessagingException {
RecordingCipher cipher = new RecordingCipher();
FixedTokens tokens = new FixedTokens();
PlatformMailer mailer = new PlatformMailer(store(root), cipher, new CapturingTransport(), tokens);
Session s = mailer.session(oauth(cipher, "mailbox@example.com", true));
assertEquals("XOAUTH2", s.getProperty("mail.smtp.auth.mechanisms"),
"only XOAUTH2: a server without it must not receive the token as a PLAIN password");
assertEquals("true", s.getProperty("mail.smtp.auth"));
assertEquals("true", s.getProperty("mail.smtp.starttls.required"));
PasswordAuthentication pa = credentials(s);
assertEquals("mailbox@example.com", pa.getUserName());
assertEquals("eyJ0eXAi.token", pa.getPassword());
assertEquals(List.of(new OAuth2TokenClient.Request(
"https://login.microsoftonline.com/tenant-1/oauth2/v2.0/token", "client-1", "client-secret",
"https://outlook.office365.com/.default")), tokens.asked, "the client secret was decrypted first");
}
@Test
void anOAuth2AccountWithNoUsernameSendsAsTheFromMailbox(@TempDir Path root) throws MessagingException {
RecordingCipher cipher = new RecordingCipher();
PlatformMailer mailer = new PlatformMailer(store(root), cipher, new CapturingTransport(), new FixedTokens());
assertEquals("noreply@example.com", credentials(mailer.session(oauth(cipher, " ", true))).getUserName());
}
@Test
void anOAuth2AccountWithoutTlsIsRefusedBeforeAnyTokenIsFetched(@TempDir Path root) {
RecordingCipher cipher = new RecordingCipher();
FixedTokens tokens = new FixedTokens();
PlatformMailer mailer = new PlatformMailer(store(root), cipher, new CapturingTransport(), tokens);
MessagingException e = assertThrows(MessagingException.class,
() -> mailer.session(oauth(cipher, "m@example.com", false)));
assertTrue(e.getMessage().contains("STARTTLS or implicit TLS"), e.getMessage());
assertTrue(tokens.asked.isEmpty());
}
@Test
void aPasswordAccountNamesNoMechanism(@TempDir Path root) throws MessagingException {
RecordingCipher cipher = new RecordingCipher();
FixedTokens tokens = new FixedTokens();
PlatformMailer mailer = new PlatformMailer(store(root), cipher, new CapturingTransport(), tokens);
// The OAuth2 fields are ignored while the method is "password" (switching back keeps them stored).
PlatformSettings.Smtp o = oauth(cipher, "u", true);
Session s = mailer.session(new PlatformSettings.Smtp(o.host(), o.port(), true, "u", cipher.encrypt("pw"),
o.from(), true, false, PlatformSettings.Smtp.AUTH_PASSWORD, o.oauthTokenUrl(), o.oauthClientId(),
o.oauthClientSecret(), o.oauthScope()));
assertNull(s.getProperty("mail.smtp.auth.mechanisms"));
assertEquals("pw", credentials(s).getPassword());
assertTrue(tokens.asked.isEmpty());
}
@Test
void aRefusedTokenIsForgottenSoTheNextSendAsksForANewOne(@TempDir Path root) {
RecordingCipher cipher = new RecordingCipher();
PlatformSettingsStore settings = store(root);
settings.update(previous -> PlatformSettings.EMPTY.withSmtp(oauth(cipher, "m@example.com", true)));
FixedTokens tokens = new FixedTokens();
MailTransport refusing = message -> {
throw new AuthenticationFailedException("535 5.7.3 Authentication unsuccessful");
};
PlatformMailer mailer = new PlatformMailer(settings, cipher, refusing, tokens);
assertThrows(AuthenticationFailedException.class, () -> mailer.send("u@example.org", "s", "b"));
assertEquals(1, tokens.forgotten);
}
@Test
void theXoauth2ExchangeOnTheWireCarriesTheMailboxAndTheBearerToken(@TempDir Path root) throws Exception {
// What the mailer configures, sent by the bundled Angus Mail to a scripted SMTP server: proves that "the token
// as the password, with mail.smtp.auth.mechanisms=XOAUTH2" yields RFC-shaped XOAUTH2. Only TLS is switched
// off for the test server; the mailer itself refuses OAuth2 without TLS.
RecordingCipher cipher = new RecordingCipher();
PlatformMailer mailer = new PlatformMailer(store(root), cipher, new CapturingTransport(), new FixedTokens());
Session configured = mailer.session(oauth(cipher, "mailbox@example.com", true));
try (java.net.ServerSocket listener = new java.net.ServerSocket(0, 1, java.net.InetAddress.getLoopbackAddress())) {
java.util.concurrent.CompletableFuture<List<String>> dialogue =
java.util.concurrent.CompletableFuture.supplyAsync(() -> scriptedSmtp(listener));
java.util.Properties props = new java.util.Properties();
props.putAll(configured.getProperties());
props.put("mail.smtp.host", "127.0.0.1");
props.put("mail.smtp.port", String.valueOf(listener.getLocalPort()));
props.put("mail.smtp.starttls.enable", "false");
props.put("mail.smtp.starttls.required", "false");
PasswordAuthentication pa = credentials(configured);
Session session = Session.getInstance(props, new jakarta.mail.Authenticator() {
@Override protected PasswordAuthentication getPasswordAuthentication() {
return pa;
}
});
MimeMessage message = mailer.build(oauth(cipher, "mailbox@example.com", true), "u@example.org", "s", "b");
jakarta.mail.Transport transport = session.getTransport("smtp");
transport.connect();
transport.sendMessage(message, message.getAllRecipients());
transport.close();
List<String> lines = dialogue.get(10, java.util.concurrent.TimeUnit.SECONDS);
String auth = lines.stream().filter(l -> l.startsWith("AUTH ")).findFirst().orElseThrow();
String[] parts = auth.split(" ");
assertEquals("XOAUTH2", parts[1], auth);
assertEquals("user=mailbox@example.com\u0001auth=Bearer eyJ0eXAi.token\u0001\u0001",
new String(Base64.getDecoder().decode(parts[2]), java.nio.charset.StandardCharsets.UTF_8));
assertTrue(lines.contains("MAIL FROM:<noreply@example.com>"), lines.toString());
}
}
/** A one-connection SMTP server offering AUTH XOAUTH2 that accepts anything; returns the client's lines. */
private static List<String> scriptedSmtp(java.net.ServerSocket listener) {
List<String> lines = new ArrayList<>();
try (java.net.Socket socket = listener.accept()) {
socket.setSoTimeout(10_000);
java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(
socket.getInputStream(), java.nio.charset.StandardCharsets.US_ASCII));
java.io.Writer out = new java.io.OutputStreamWriter(socket.getOutputStream(),
java.nio.charset.StandardCharsets.US_ASCII);
out.write("220 test ESMTP\r\n");
out.flush();
String line;
while ((line = in.readLine()) != null) {
lines.add(line);
String verb = line.length() >= 4 ? line.substring(0, 4).toUpperCase(java.util.Locale.ROOT) : line;
switch (verb) {
case "EHLO" -> out.write("250-test\r\n250-AUTH XOAUTH2 PLAIN LOGIN\r\n250 OK\r\n");
case "AUTH" -> out.write("235 2.7.0 Authentication successful\r\n");
case "DATA" -> {
out.write("354 go\r\n");
out.flush();
String body;
while ((body = in.readLine()) != null && !body.equals(".")) {
// the message itself is not checked here
}
out.write("250 queued\r\n");
}
case "QUIT" -> {
out.write("221 bye\r\n");
out.flush();
return lines;
}
default -> out.write("250 OK\r\n");
}
out.flush();
}
} catch (java.io.IOException e) {
throw new java.io.UncheckedIOException(e);
}
return lines;
}
}
@@ -71,4 +71,32 @@ class PlatformSettingsSmtpTest {
assertFalse(smtp.toString().contains("ENC(secret)"), "the (encrypted) password is masked in toString");
assertTrue(smtp.toString().contains("<set>"));
}
@Test
void theOAuth2FieldsRoundTripAndAPasswordOnlyFileLoadsAsPassword(@TempDir Path root) throws IOException {
PlatformSettingsStore store = store(root);
PlatformSettings.Smtp smtp = new PlatformSettings.Smtp("smtp.office365.com", 587, true, "box@x.io", null,
"box@x.io", true, false, PlatformSettings.Smtp.AUTH_OAUTH2, "https://login.example/t/token", "cid",
"ENC(client)", "https://outlook.office365.com/.default");
store.update(previous -> PlatformSettings.EMPTY.withSmtp(smtp));
assertEquals(smtp, store(root).get().smtp());
assertTrue(store(root).get().smtp().usesOAuth2());
// A 1.0.x file: an smtp block with no OAuth2 keys reads as a password account.
Path file = root.resolve("external").resolve("platform.yml");
Files.writeString(file, "smtp:\n host: \"m.x.io\"\n auth: true\n username: \"u\"\n"
+ " password: \"ENC(p)\"\n from: \"f@x.io\"\n");
PlatformSettings.Smtp old = store(root).get().smtp();
assertEquals("ENC(p)", old.password());
assertNull(old.authMethod());
assertFalse(old.usesOAuth2());
}
@Test
void theSmtpToStringMasksTheClientSecret() {
PlatformSettings.Smtp smtp = new PlatformSettings.Smtp("h", 587, true, "u", null, "f@x", true, false,
PlatformSettings.Smtp.AUTH_OAUTH2, "https://l.example/t", "cid", "ENC(client-secret)", null);
assertFalse(smtp.toString().contains("client-secret"));
assertTrue(smtp.toString().contains("oauthClientSecret=<set>"));
}
}
@@ -33,7 +33,8 @@ class KernelBeanNamesTest {
/** The first-party plugin ids (runway-plugins plus the essential plugin). */
static final List<String> FIRST_PARTY = List.of("blog", "carousel-manager", "contact", "runway-demo",
"discoverability", "search", "search-lucene", "lucene-provider", "protection");
"discoverability", "search", "search-lucene", "lucene-provider", "protection", "database",
"database-postgresql", "database-mariadb", "runway-demo-database");
@DynamicPropertySource
static void config(DynamicPropertyRegistry registry) throws IOException {
@@ -16,6 +16,7 @@ import java.nio.file.Path;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import mx.quest.runway.backup.BackupParticipantRegistry;
import mx.quest.runway.content.ContentSourceRegistry;
import mx.quest.runway.endpoint.EndpointContributorRegistry;
@@ -32,6 +33,7 @@ import mx.quest.runway.spi.model.PageView;
import mx.quest.runway.spi.model.RenderFragment;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.model.WidgetView;
import mx.quest.runway.spi.service.PluginSettings;
import mx.quest.runway.widget.ContentWidgetRegistry;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
@@ -392,6 +394,33 @@ class PluginContributionPolicyTest {
return new org.springframework.beans.factory.InjectionPoint(type.getDeclaredField(field));
}
@Test
void theFactoryHandsAPluginItsOwnAppLevelSecretFromTheRunningEnvironmentAndNothingElse() throws Exception {
assumeTrue(PluginFixture.compilerAvailable());
PluginDescriptor withSecret = PluginDescriptor.read(new ByteArrayInputStream((
"id: p1\nversion: 1.0.0\nmainClass: x.Y\nsettings:\n"
+ " - { key: apiKey, type: secret, label: l }\n"
+ " - { key: host, type: string, label: l }\n").getBytes(StandardCharsets.UTF_8)));
PluginOwnership owners = PluginOwnership.of(new PluginRuntime(
List.of(new LoadedPlugin(withSecret, root.resolve("p1")), loaded("p2")), loader, Map.of(), false));
mx.quest.runway.storage.StorageProperties props = new mx.quest.runway.storage.StorageProperties();
props.setExternal(root.resolve("external"));
mx.quest.runway.storage.StorageLayout layout = mx.quest.runway.storage.StorageLayout.from(props);
org.springframework.mock.env.MockEnvironment env = new org.springframework.mock.env.MockEnvironment()
.withProperty("runway.plugin.p1.apiKey", "p1-key")
.withProperty("runway.plugin.p1.host", "db.example")
.withProperty("runway.plugin.p2.apiKey", "p2-key");
PluginScopedServices scoped = new PluginScopedServices(owners,
new SitePluginConfigService(layout, null, event -> { }), null, layout, 1024, env);
PluginSettings p1 = scoped.pluginSettings(pointIn(head("p1", "k", false).getClass(), "key"));
PluginSettings p2 = scoped.pluginSettings(pointIn(head("p2", "k", false).getClass(), "key"));
assertEquals(Optional.of("p1-key"), p1.appSecret("apiKey"), "the running value of its own declared secret");
assertEquals(Optional.empty(), p1.appSecret("host"), "a non-secret app setting is never handed out here");
assertEquals(Optional.empty(), p2.appSecret("apiKey"),
"p2 declared no app-level secret, so the environment's value is not handed out");
}
@Test
void anInjectionPointInAPluginsOwnJarBindsToThatPlugin() throws Exception {
assumeTrue(PluginFixture.compilerAvailable());
@@ -191,4 +191,86 @@ class PluginSettingsImplTest {
assertEquals("Demo's", settings("demo").site("acme").string("title", ""));
assertEquals("Other's", settings("other").site("acme").string("title", ""));
}
// ---- app-level secrets (SPI 1.1.0) -------------------------------------------------------------
private static final List<PluginSettingDef> APP_SCHEMA = List.of(
new PluginSettingDef("password", "secret", null, "l", null),
new PluginSettingDef("host", "string", "localhost", "l", null));
private final java.util.Map<String, String> environment = new java.util.HashMap<>();
private PluginSettingsImpl withApp(String plugin) {
return new PluginSettingsImpl(plugin, SCHEMA, APP_SCHEMA, environment::get, config, cipher);
}
@Test
void anAppSecretIsReadFromTheRunningEnvironmentUnderTheCallersOwnPrefixAndDecrypted() {
environment.put("runway.plugin.database.password", cipher.encrypt("s3cret"));
environment.put("runway.plugin.other.password", "not-mine");
assertEquals(Optional.of("s3cret"), withApp("database").appSecret("password"));
assertEquals(Optional.empty(), withApp("unconfigured").appSecret("password"),
"the lookup is keyed by the bound plugin's own id: another plugin's value is never read");
}
@Test
void aHandWrittenPlaintextAppSecretIsReturnedUnchanged() {
environment.put("runway.plugin.database.password", "plain");
assertEquals(Optional.of("plain"), withApp("database").appSecret("password"));
}
@Test
void onlyAKeyDeclaredSecretInTheAppLevelSchemaIsHandedOut() {
environment.put("runway.plugin.database.host", "db.example");
environment.put("runway.plugin.database.smtpPassword", "site-level-key");
environment.put("runway.plugin.database.undeclared", "x");
PluginSettingsImpl settings = withApp("database");
assertEquals(Optional.empty(), settings.appSecret("host"), "declared, but not a secret");
assertEquals(Optional.empty(), settings.appSecret("smtpPassword"),
"a secret declared only in siteSettings: is not an app-level secret");
assertEquals(Optional.empty(), settings.appSecret("undeclared"));
assertEquals(Optional.empty(), settings.appSecret(null));
}
@Test
void anUnsetBlankOrUndecryptableAppSecretIsEmpty() {
PluginSettingsImpl settings = withApp("database");
assertEquals(Optional.empty(), settings.appSecret("password"), "unset");
environment.put("runway.plugin.database.password", " ");
assertEquals(Optional.empty(), settings.appSecret("password"), "blank");
environment.put("runway.plugin.database.password", cipher.encrypt("s3cret"));
cipherAvailable = false;
assertEquals(Optional.empty(), settings.appSecret("password"), "no usable platform secret key");
cipherAvailable = true;
cipherBroken = true;
assertEquals(Optional.empty(), settings.appSecret("password"), "wrong key or corrupted value");
}
@Test
void theValueFollowsTheEnvironmentItIsHandedNotAFileSavedSinceStartup() {
PluginSettingsImpl settings = withApp("database");
environment.put("runway.plugin.database.password", "first");
assertEquals(Optional.of("first"), settings.appSecret("password"));
environment.put("runway.plugin.database.password", "second");
assertEquals(Optional.of("second"), settings.appSecret("password"), "not cached past the environment");
}
@Test
void theSiteOnlyConstructorHasNoAppSecretsAndTheSpiDefaultIsEmpty() {
environment.put("runway.plugin.database.password", "plain");
assertEquals(Optional.empty(), settings("database").appSecret("password"));
mx.quest.runway.spi.service.PluginSettings bare = new mx.quest.runway.spi.service.PluginSettings() {
@Override
public SettingsView site(String siteId) {
return new SettingsView(java.util.Map.of());
}
@Override
public Optional<String> secret(String siteId, String key) {
return Optional.empty();
}
};
assertEquals(Optional.empty(), bare.appSecret("password"),
"an implementation written against SPI 1.0 still compiles and answers empty");
}
}
@@ -4,13 +4,16 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermission;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import mx.quest.runway.spi.model.FileEntry;
import mx.quest.runway.storage.StorageLayout;
import mx.quest.runway.storage.StorageProperties;
@@ -77,6 +80,26 @@ class PluginSiteFilesImplTest {
assertEquals(Optional.empty(), files.readText("ghost-site", "a.txt"), "an unknown site has no files");
}
@Test
void aFileWhoseFolderCannotBeSearchedIsAnErrorNotAbsent() throws IOException {
files.writeText("acme", "dir/token.yml", "token: x");
Path dir = root.resolve("dir");
Set<PosixFilePermission> before = Files.getPosixFilePermissions(dir);
Files.setPosixFilePermissions(dir, Set.of());
try {
assumeFalse(Files.isReadable(dir.resolve("token.yml")), "running as a user that ignores permissions");
// A caller that took "cannot tell" for "absent" would act as if the file were gone (the database plugin
// read a missing token as a recreated site and retired its data).
assertThrows(IOException.class, () -> files.readText("acme", "dir/token.yml"));
assertThrows(IOException.class, () -> files.stat("acme", "dir/token.yml"));
assertThrows(IOException.class, () -> files.list("acme", "dir/sub"));
assertThrows(IOException.class, () -> files.list("acme", "dir"), "a folder that cannot be listed");
} finally {
Files.setPosixFilePermissions(dir, before);
}
assertEquals(Optional.of("token: x"), files.readText("acme", "dir/token.yml"));
}
@Test
void aWriteReplacesTheFileAtomicallyAndLeavesNoTemporaryBehind() throws IOException {
files.writeText("acme", "a.txt", "one");
@@ -0,0 +1,182 @@
package mx.quest.runway.recovery;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import java.nio.file.Path;
import java.util.List;
import java.util.Locale;
import java.util.function.Function;
import mx.quest.runway.console.AppRecoveryController;
import mx.quest.runway.console.TenantRecoveryController;
import mx.quest.runway.platform.PlatformSettingsStore;
import mx.quest.runway.site.Site;
import mx.quest.runway.site.SiteResolver;
import mx.quest.runway.site.SiteStatus;
import mx.quest.runway.site.SiteStore;
import mx.quest.runway.storage.StorageLayout;
import mx.quest.runway.storage.StorageProperties;
import mx.quest.runway.storage.YamlStore;
import mx.quest.runway.web.ConsoleHostProperties;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.springframework.mock.web.MockHttpServletRequest;
/**
* Where a password-reset link points. The request's own host never decides it: a request that names a made-up host
* (directly, or as {@code X-Forwarded-Host} through a proxy) must not get the platform to mail a real user a link to
* the sender's site. Checked on {@link RecoveryLinks} and through both recovery controllers, by capturing the link the
* mail would carry.
*/
class RecoveryLinksTest {
@TempDir
Path external;
private SiteStore sites;
private PlatformSettingsStore platform;
@BeforeEach
void setUp() {
StorageProperties props = new StorageProperties();
props.setExternal(external);
StorageLayout layout = StorageLayout.from(props);
YamlStore yaml = new YamlStore();
sites = new SiteStore(layout, yaml);
platform = new PlatformSettingsStore(layout, yaml);
sites.save(site("main", List.of("www.main.test", "main.test"), null));
sites.save(site("plain", List.of("plain.test"), "http://plain.test:8080"));
sites.save(site("hostless", List.of(), null));
}
private static Site site(String id, List<String> hosts, String baseUrl) {
return new Site(id, id, hosts, Locale.ENGLISH, List.of(Locale.ENGLISH), baseUrl, SiteStatus.ACTIVE, false,
null);
}
private RecoveryLinks links(String... consoleHosts) {
ConsoleHostProperties console = new ConsoleHostProperties();
console.setHosts(List.of(consoleHosts));
return new RecoveryLinks(sites, platform, console);
}
private static MockHttpServletRequest request(String scheme, String host, int port) {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/app/forgot-password");
request.setScheme(scheme);
request.setServerName(host);
request.setServerPort(port);
request.setSecure("https".equals(scheme));
return request;
}
@Test
void aSiteLinkIsTheSitesOwnAddressAndNeverTheRequests() {
RecoveryLinks links = links();
assertThat(links.siteBase(sites.find("main").orElseThrow())).contains("https://www.main.test");
assertThat(links.siteBase(sites.find("plain").orElseThrow())).contains("http://plain.test:8080");
assertThat(links.siteBase(sites.find("hostless").orElseThrow())).isEmpty();
}
@Test
void withoutConsoleHostsTheConsoleLinkIsTheDefaultSitesAddress() {
assertThat(links().appBase(request("https", "evil.example", 443))).isEmpty(); // no default site yet
platform.update(current -> current.withDefaultSiteId("main"));
assertThat(links().appBase(request("https", "evil.example", 443))).contains("https://www.main.test");
assertThat(links().appBase(request("http", "10.0.0.5", 8080))).contains("https://www.main.test");
platform.update(current -> current.withDefaultSiteId("hostless"));
assertThat(links().appBase(request("https", "evil.example", 443))).isEmpty();
}
@Test
void withConsoleHostsOnlyAListedHostMakesTheLink() {
RecoveryLinks links = links("https://Ops.Example.com/", "10.0.0.5");
assertThat(links.appBase(request("https", "ops.example.com", 443))).contains("https://ops.example.com");
assertThat(links.appBase(request("http", "10.0.0.5", 8080))).contains("http://10.0.0.5:8080");
assertThat(links.appBase(request("https", "evil.example", 443))).isEmpty();
platform.update(current -> current.withDefaultSiteId("main"));
assertThat(links.appBase(request("https", "evil.example", 443))).isEmpty(); // the list decides alone
}
@Test
void aLoopbackAddressIsNoAddressUnlessABaseUrlSaysSo() {
sites.save(site("default", List.of("localhost"), null)); // what the setup wizard leaves
sites.save(site("lab", List.of("127.0.0.1"), null));
sites.save(site("dev", List.of("localhost"), "http://localhost:8080")); // the operator's own word
RecoveryLinks links = links();
assertThat(links.siteBase(sites.find("default").orElseThrow())).isEmpty();
assertThat(links.siteBase(sites.find("lab").orElseThrow())).isEmpty();
assertThat(links.siteBase(sites.find("dev").orElseThrow())).contains("http://localhost:8080");
platform.update(current -> current.withDefaultSiteId("default"));
assertThat(links.appBase(request("https", "runway.example.com", 443))).isEmpty();
assertThat(RecoveryLinks.isLoopback("app.localhost")).isTrue();
assertThat(RecoveryLinks.isLoopback("localhost.example.com")).isFalse();
assertThat(RecoveryLinks.isLoopback("::1")).isTrue();
}
@Test
void aListedConsoleHostDecidesTheLinksSpellingAndAListedPortItsPort() {
RecoveryLinks links = links("ops.example.com", "admin.example.com:443", "[2001:db8::5]:8443");
assertThat(links.appBase(request("https", "Ops.Example.COM.", 443))).contains("https://ops.example.com");
// Without a listed port the request's stands (the client's Host header, or the proxy's).
assertThat(links.appBase(request("https", "ops.example.com", 8080))).contains("https://ops.example.com:8080");
assertThat(links.appBase(request("https", "admin.example.com", 8080))).contains("https://admin.example.com");
assertThat(links.appBase(request("https", "2001:db8::5", 9999))).contains("https://[2001:db8::5]:8443");
}
@Test
@SuppressWarnings("unchecked")
void theApplicationConsoleNeverMailsALinkToTheHostTheRequestNamed() {
platform.update(current -> current.withDefaultSiteId("main"));
PasswordRecoveryService recovery = Mockito.mock(PasswordRecoveryService.class);
AppRecoveryController controller = new AppRecoveryController(recovery, links());
controller.requestLink("root@example.com", Locale.ENGLISH, request("https", "evil.example", 443));
ArgumentCaptor<Function<String, String>> link = ArgumentCaptor.forClass(Function.class);
verify(recovery).requestApp(eq("root@example.com"), anyString(), link.capture(), any());
assertThat(link.getValue().apply("tok")).isEqualTo("https://www.main.test/app/reset?token=tok");
}
@Test
void withNoKnownAddressTheApplicationConsoleSendsNothing() {
PasswordRecoveryService recovery = Mockito.mock(PasswordRecoveryService.class);
AppRecoveryController controller = new AppRecoveryController(recovery, links("ops.example.com"));
String view = controller.requestLink("root@example.com", Locale.ENGLISH,
request("https", "evil.example", 443));
assertThat(view).isEqualTo("redirect:/app/forgot-password?sent"); // the same neutral answer
verify(recovery, never()).requestApp(anyString(), anyString(), any(), any());
}
@Test
@SuppressWarnings("unchecked")
void aSiteConsoleLinkPointsAtTheSiteItIsFor() {
PasswordRecoveryService recovery = Mockito.mock(PasswordRecoveryService.class);
SiteResolver resolver = new SiteResolver(sites, platform);
TenantRecoveryController controller = new TenantRecoveryController(recovery, resolver, links());
resolver.bind(sites.find("main").orElseThrow()); // an unknown host falls back to the default site
try {
controller.requestLink("editor@example.com", Locale.ENGLISH);
} finally {
resolver.clear();
}
ArgumentCaptor<Function<String, String>> link = ArgumentCaptor.forClass(Function.class);
verify(recovery).requestTenant(eq("main"), eq("editor@example.com"), anyString(), link.capture(), any());
assertThat(link.getValue().apply("tok")).isEqualTo("https://www.main.test/reset?token=tok");
resolver.bind(sites.find("hostless").orElseThrow());
try {
controller.requestLink("editor@example.com", Locale.ENGLISH);
} finally {
resolver.clear();
}
verify(recovery, never()).requestTenant(eq("hostless"), anyString(), anyString(), any(), any());
}
}
@@ -2,16 +2,20 @@ package mx.quest.runway.site;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
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.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.List;
import java.util.Locale;
import mx.quest.runway.storage.StorageLayout;
import mx.quest.runway.storage.StorageProperties;
import mx.quest.runway.storage.YamlStore;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -125,4 +129,28 @@ class SiteStoreTest {
assertFalse(loaded.maintenance(), "missing maintenance key defaults to off");
assertEquals(null, loaded.maintenanceMessage());
}
/**
* A site whose folder cannot be searched is "cannot tell", never "no such site": a plugin that takes a missing
* site for a deleted one would drop its data. A listing still goes on past it.
*/
@Test
void aSiteFolderThatCannotBeSearchedIsAnErrorNotAMissingSite(@TempDir Path tmp) throws IOException {
Assumptions.assumeTrue(!"root".equals(System.getProperty("user.name")), "root reads any folder");
SiteStore store = storeIn(tmp);
store.save(site("acme", "acme.test"));
store.save(site("beta", "beta.test"));
Path dir = tmp.resolve("sites").resolve("acme");
Files.setPosixFilePermissions(dir, PosixFilePermissions.fromString("rw-------"));
try {
store.evict("acme");
assertThrows(UncheckedIOException.class, () -> store.find("acme"));
assertEquals(List.of("beta"), store.findAll().stream().map(Site::id).toList());
assertTrue(store.find("gone").isEmpty(), "a site that is not there is still simply missing");
} finally {
Files.setPosixFilePermissions(dir, PosixFilePermissions.fromString("rwx------"));
}
store.evict("acme");
assertTrue(store.find("acme").isPresent());
}
}
@@ -0,0 +1,102 @@
package mx.quest.runway.web;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
/** The client is read from the right of the X-Forwarded-For chain, past the trusted proxies only. */
class ForwardedForTest {
private static final CidrSet PROXIES = CidrSet.of(List.of("10.0.0.0/8", "2001:db8:ffff::/48"));
private static ForwardedFor.Chain chain(String... lines) {
return ForwardedFor.chain(Collections.enumeration(List.of(lines)));
}
@Test
void anAppendingProxyCannotBeFooledByAClientWrittenEntry() {
// The client sent "X-Forwarded-For: 6.6.6.6"; the proxy appended the address it saw.
assertThat(ForwardedFor.client(chain("6.6.6.6, 203.0.113.7"), PROXIES, "10.0.0.9")).isEqualTo("203.0.113.7");
// Same, with the proxy adding a second header line instead of appending to the first.
assertThat(ForwardedFor.client(chain("6.6.6.6", "203.0.113.7"), PROXIES, "10.0.0.9")).isEqualTo("203.0.113.7");
}
@Test
void trustedHopsAreSkippedFromTheRight() {
assertThat(ForwardedFor.client(chain("6.6.6.6, 203.0.113.7, 10.1.1.1, 10.2.2.2"), PROXIES, "10.0.0.9"))
.isEqualTo("203.0.113.7");
assertThat(ForwardedFor.client(chain("203.0.113.7, [2001:db8:ffff::1]:443"), PROXIES, "10.0.0.9"))
.isEqualTo("203.0.113.7");
}
@Test
void aChainOfTrustedProxiesOnlyGivesItsLeftmostEntry() {
assertThat(ForwardedFor.client(chain("10.3.3.3, 10.1.1.1"), PROXIES, "10.0.0.9")).isEqualTo("10.3.3.3");
}
@Test
void noChainLeavesThePeer() {
assertThat(ForwardedFor.client(ForwardedFor.Chain.NONE, PROXIES, "10.0.0.9")).isEqualTo("10.0.0.9");
assertThat(ForwardedFor.client(chain(" , ,"), PROXIES, "10.0.0.9")).isEqualTo("10.0.0.9");
assertThat(ForwardedFor.chain(null)).isEqualTo(ForwardedFor.Chain.NONE);
}
@Test
void aDecidingEntryThatIsNotAnAddressFallsBackToThePeer() {
assertThat(ForwardedFor.client(chain("203.0.113.7, unknown"), PROXIES, "10.0.0.9")).isEqualTo("10.0.0.9");
assertThat(ForwardedFor.client(chain("203.0.113.7, example.com"), PROXIES, "10.0.0.9")).isEqualTo("10.0.0.9");
// An unreadable entry to the LEFT of the client does not matter: it is never reached.
assertThat(ForwardedFor.client(chain("garbage, 203.0.113.7"), PROXIES, "10.0.0.9")).isEqualTo("203.0.113.7");
}
@Test
void addressFormsAreNormalised() {
assertThat(ForwardedFor.address("192.0.2.1")).isEqualTo("192.0.2.1");
assertThat(ForwardedFor.address("192.0.2.1:8080")).isEqualTo("192.0.2.1");
assertThat(ForwardedFor.address("\"192.0.2.1\"")).isEqualTo("192.0.2.1");
assertThat(ForwardedFor.address("2001:db8::1")).isEqualTo("2001:db8::1");
assertThat(ForwardedFor.address("[2001:db8::1]")).isEqualTo("2001:db8::1");
assertThat(ForwardedFor.address("[2001:db8::1]:8080")).isEqualTo("2001:db8::1");
assertThat(ForwardedFor.address("\"[2001:db8::1]:8080\"")).isEqualTo("2001:db8::1");
}
@Test
void nonAddressesAreRefusedWithoutAnyLookup() {
assertThat(ForwardedFor.address(null)).isNull();
assertThat(ForwardedFor.address("")).isNull();
assertThat(ForwardedFor.address("unknown")).isNull();
assertThat(ForwardedFor.address("_hidden")).isNull();
assertThat(ForwardedFor.address("localhost")).isNull();
assertThat(ForwardedFor.address("192.0.2.1:http")).isNull();
assertThat(ForwardedFor.address("192.0.2.1:")).isNull();
assertThat(ForwardedFor.address("192.0.2.256")).isNull();
assertThat(ForwardedFor.address("[192.0.2.1]")).isNull();
assertThat(ForwardedFor.address("[2001:db8::1")).isNull();
assertThat(ForwardedFor.address("[2001:db8::1]x")).isNull();
assertThat(ForwardedFor.address("fe80::1%eth0")).isNull();
assertThat(ForwardedFor.address("1:2")).isNull();
assertThat(ForwardedFor.address("1".repeat(65))).isNull();
}
@Test
void aHugeChainKeepsOnlyItsRightmostEntries() {
String line = IntStream.range(0, 1000).mapToObj(i -> "6.6." + (i / 250) + "." + (i % 250))
.collect(Collectors.joining(", ")) + ", 203.0.113.7";
ForwardedFor.Chain chain = chain(line);
assertThat(chain.total()).isEqualTo(1001);
assertThat(chain.entries()).hasSize(ForwardedFor.MAX_ENTRIES).endsWith("203.0.113.7");
assertThat(chain.text()).startsWith("…, ").endsWith(", 203.0.113.7");
assertThat(ForwardedFor.client(chain, PROXIES, "10.0.0.9")).isEqualTo("203.0.113.7");
}
@Test
void aLongEntryIsCutForDisplayAndNeverTakenAsAnAddress() {
ForwardedFor.Chain chain = chain("x".repeat(500));
assertThat(chain.entries().getFirst()).hasSize(ForwardedFor.MAX_ENTRY_LENGTH + 1).endsWith("…");
assertThat(ForwardedFor.client(chain, PROXIES, "10.0.0.9")).isEqualTo("10.0.0.9");
}
}
@@ -0,0 +1,160 @@
package mx.quest.runway.web;
import static org.assertj.core.api.Assertions.assertThat;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import org.eclipse.jetty.ee11.servlet.ServletContextHandler;
import org.eclipse.jetty.ee11.servlet.ServletHolder;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.util.Map;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.MapConfigurationPropertySource;
import org.springframework.boot.jetty.JettyWebServer;
import org.springframework.boot.jetty.servlet.JettyServletWebServerFactory;
import org.springframework.boot.web.server.WebServer;
/**
* The minimum request data rate, against a real Jetty: a body trickled in is cut with {@code 408} instead of holding a
* request thread, and a server that is slow to start reading is not blamed for it. Guards the behaviour across Jetty
* upgrades, since the rate check is Jetty's.
*/
class SlowClientConfigTest {
/** The bean, as Spring binds and applies it: the property, the clamp, and every connector of Boot's own Jetty. */
@Test
void theBoundPropertyReachesEveryConnectorOfTheServerBootBuilds() throws Exception {
assertThat(rateOnBootsServer("1024")).containsOnly(1024L).isNotEmpty();
assertThat(rateOnBootsServer("-5")).as("a negative value is clamped to off").containsOnly(0L);
}
private java.util.List<Long> rateOnBootsServer(String configured) throws Exception {
SlowClientConfig.HttpLimitProperties properties = new Binder(new MapConfigurationPropertySource(
Map.of("runway.http.min-request-data-rate", configured)))
.bind("runway.http", SlowClientConfig.HttpLimitProperties.class).get();
JettyServletWebServerFactory factory = new JettyServletWebServerFactory(0);
new SlowClientConfig().slowClientJettyCustomizer(properties).customize(factory);
WebServer web = factory.getWebServer();
web.start();
try {
java.util.List<Long> rates = new java.util.ArrayList<>();
for (org.eclipse.jetty.server.Connector connector : ((JettyWebServer) web).getServer().getConnectors()) {
for (org.eclipse.jetty.server.ConnectionFactory f : connector.getConnectionFactories()) {
if (f instanceof org.eclipse.jetty.server.HttpConfiguration.ConnectionFactory http) {
rates.add(http.getHttpConfiguration().getMinRequestDataRate());
}
}
}
return rates;
} finally {
web.stop();
}
}
private Server server;
@AfterEach
void stop() throws Exception {
if (server != null) {
server.stop();
}
}
/** A server whose servlet reads the whole body after {@code pauseMillis}, with the rate applied by the config. */
private int start(long bytesPerSecond, long pauseMillis) throws Exception {
server = new Server();
ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory());
connector.setPort(0);
connector.setIdleTimeout(30_000);
server.addConnector(connector);
ServletContextHandler context = new ServletContextHandler();
context.addServlet(new ServletHolder(new HttpServlet() {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
Thread.sleep(pauseMillis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
response.getWriter().write("read " + request.getInputStream().readAllBytes().length);
}
}), "/*");
server.setHandler(context);
assertThat(SlowClientConfig.apply(server, bytesPerSecond)).isEqualTo(1);
server.start();
return connector.getLocalPort();
}
private static String statusLine(Socket socket) throws IOException {
socket.setSoTimeout(10_000);
String response = new String(socket.getInputStream().readAllBytes(), StandardCharsets.US_ASCII);
return response.isEmpty() ? "" : response.substring(0, response.indexOf("\r\n"));
}
@Test
void aTrickledBodyIsCutWithRequestTimeout() throws Exception {
int port = start(1024, 0);
long started = System.nanoTime();
try (Socket socket = new Socket("127.0.0.1", port)) {
OutputStream out = socket.getOutputStream();
out.write("POST / HTTP/1.1\r\nHost: x\r\nContent-Length: 1000\r\nConnection: close\r\n\r\n"
.getBytes(StandardCharsets.US_ASCII));
out.flush();
try {
for (int i = 0; i < 20; i++) { // one byte a second: far below 1 KiB/s
Thread.sleep(1000);
out.write('a');
out.flush();
}
} catch (IOException closedByServer) {
// expected: Jetty answered and closed while the client was still trickling
}
assertThat(statusLine(socket)).isEqualTo("HTTP/1.1 408 Request Timeout");
}
assertThat(Duration.ofNanos(System.nanoTime() - started)).isLessThan(Duration.ofSeconds(15));
}
@Test
void aServerSlowToReadIsNotBlamed() throws Exception {
int port = start(1024, 3000);
try (Socket socket = new Socket("127.0.0.1", port)) {
OutputStream out = socket.getOutputStream();
out.write(("POST / HTTP/1.1\r\nHost: x\r\nContent-Length: 100\r\nConnection: close\r\n\r\n"
+ "a".repeat(100)).getBytes(StandardCharsets.US_ASCII));
out.flush();
assertThat(statusLine(socket)).isEqualTo("HTTP/1.1 200 OK");
}
}
@Test
void theDefaultIsFourKilobytesPerSecond() {
assertThat(new SlowClientConfig.HttpLimitProperties().getMinRequestDataRate()).isEqualTo(4096);
}
@Test
void zeroTurnsTheCheckOff() throws Exception {
int port = start(0, 0);
try (Socket socket = new Socket("127.0.0.1", port)) {
OutputStream out = socket.getOutputStream();
out.write("POST / HTTP/1.1\r\nHost: x\r\nContent-Length: 3\r\nConnection: close\r\n\r\n"
.getBytes(StandardCharsets.US_ASCII));
out.flush();
for (int i = 0; i < 3; i++) { // one byte a second, accepted when the check is off
Thread.sleep(1000);
out.write('a');
out.flush();
}
assertThat(statusLine(socket)).isEqualTo("HTTP/1.1 200 OK");
}
}
}
@@ -89,4 +89,51 @@ class TrustedForwardedHeaderFilterTest {
assertNull(seen.getHeader("X-Forwarded-Host"), "forwarded handling off => always hide");
assertEquals("localhost", seen.getServerName());
}
@Test
void aClientWrittenLeftmostEntryDoesNotChooseTheAddress() throws Exception {
TrustedForwardedHeaderFilter filter = new TrustedForwardedHeaderFilter(CidrSet.of(List.of("10.0.0.0/8")), true);
MockHttpServletRequest request = behindProxy("10.0.0.9");
request.removeHeader("X-Forwarded-For");
request.addHeader("X-Forwarded-For", "6.6.6.6, 203.0.113.7"); // client sent 6.6.6.6, the proxy appended
HttpServletRequest seen = run(filter, request);
assertEquals("203.0.113.7", seen.getRemoteAddr(), "the address the trusted proxy saw, not the client's claim");
assertEquals("203.0.113.7", seen.getRemoteHost(), "never the leftmost, never a reverse lookup");
assertEquals("203.0.113.7", ClientIp.of(seen));
assertEquals("example.com", seen.getServerName(), "Spring still applies the forwarded host");
assertEquals("https", seen.getScheme(), "and the forwarded scheme");
}
@Test
void theStandardForwardedHeaderIsHiddenEvenFromATrustedPeer() throws Exception {
TrustedForwardedHeaderFilter filter = new TrustedForwardedHeaderFilter(CidrSet.of(List.of("10.0.0.0/8")), true);
MockHttpServletRequest request = behindProxy("10.0.0.9");
// A client-sent RFC 7239 header that a proxy managing X-Forwarded-* passed through untouched.
request.addHeader("Forwarded", "for=6.6.6.6;host=evil.example;proto=http");
HttpServletRequest seen = run(filter, request);
assertEquals("203.0.113.7", seen.getRemoteAddr());
assertEquals("example.com", seen.getServerName(), "Forwarded must not override X-Forwarded-Host");
assertEquals("https", seen.getScheme(), "Forwarded must not override X-Forwarded-Proto");
assertNull(seen.getHeader("Forwarded"));
}
@Test
void eachRequestRecordsHowItWasAttributed() throws Exception {
TrustedForwardedHeaderFilter filter = new TrustedForwardedHeaderFilter(CidrSet.of(List.of("10.0.0.0/8")), true);
MockHttpServletRequest viaProxy = behindProxy("10.0.0.9");
run(filter, viaProxy);
ProxyResolution trusted = ProxyResolution.of(viaProxy);
assertEquals(new ProxyResolution("10.0.0.9", true, true,
new ForwardedFor.Chain(List.of("203.0.113.7"), 1), "203.0.113.7"), trusted);
MockHttpServletRequest direct = behindProxy("198.51.100.9");
run(filter, direct);
ProxyResolution untrusted = ProxyResolution.of(direct);
assertEquals(new ProxyResolution("198.51.100.9", false, false,
new ForwardedFor.Chain(List.of("203.0.113.7"), 1), "198.51.100.9"), untrusted);
MockHttpServletRequest off = behindProxy("10.0.0.9");
run(new TrustedForwardedHeaderFilter(CidrSet.of(List.of("10.0.0.0/8")), false), off);
assertEquals(new ProxyResolution("10.0.0.9", true, false,
new ForwardedFor.Chain(List.of("203.0.113.7"), 1), "10.0.0.9"), ProxyResolution.of(off));
}
}