Runway 1.0.0
This commit is contained in:
commit
dcf819146b
1372 files changed
+188168
No files matched your search
@@ -0,0 +1,287 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway</artifactId>
|
||||
<version>1.0.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>runway-app</artifactId>
|
||||
<name>Runway App</name>
|
||||
<description>
|
||||
The Runway kernel: a Spring Boot (Jetty) multi-site web server + plugin host. Collects
|
||||
runway-spi implementations and plugin contributions; ships only the essential bytes,
|
||||
with domain features delivered as plugins.
|
||||
</description>
|
||||
|
||||
<dependencies>
|
||||
<!-- The extension API this kernel implements and exposes. -->
|
||||
<dependency>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-spi</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring Boot Web on Jetty (Tomcat excluded). The rest of the stack
|
||||
(Thymeleaf decoupled-logic, Security, validation, actuator, …) is
|
||||
added as the kernel is built out. -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-tomcat</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jetty</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Thymeleaf 3.1 (decoupled-logic) — the tenant-site render engine. -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring Security 7 (managed by the Boot 4 BOM) — the two never-crossing realm chains
|
||||
and the Argon2id password encoder. -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<!-- Argon2id needs BouncyCastle, which is NOT managed by the Spring Boot BOM — pin it. -->
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk18on</artifactId>
|
||||
<version>1.80</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Typed YAML stores. Jackson 3 (tools.jackson) is Spring Boot 4's default JSON/YAML
|
||||
engine; this adds the YAML dataformat on top of the managed jackson-databind. -->
|
||||
<dependency>
|
||||
<groupId>tools.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-yaml</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Jakarta Mail (Jakarta Mail API + the Angus reference implementation + Jakarta Activation) — the
|
||||
platform's OWN mail transport, used for APPLICATION-level messages only (password recovery, and any
|
||||
future operator notifications), NEVER for site-generated mail (a site's contact form keeps its own
|
||||
per-site SMTP). This is a CORE capability: the kernel sends platform mail directly through a small
|
||||
PlatformMailer (raw Session/MimeMessage/Transport), so the mail stack
|
||||
ships in the exec jar on the app classloader — one copy deployment-wide. Consumer plugins
|
||||
compile Jakarta Mail as `provided` and resolve THIS copy at runtime via parent-first delegation, so
|
||||
the former code-less `mail-provider` library plugin is retired. Versions pinned to match what that
|
||||
provider bundled (byte-identical). The kernel compiles only against the API; the Angus SMTP impl +
|
||||
Activation are runtime-only (discovered via META-INF/services). No spring.mail.host is set, so Spring
|
||||
Boot's JavaMailSender auto-configuration stays inert — PlatformMailer is the only mail bean. -->
|
||||
<dependency>
|
||||
<groupId>jakarta.mail</groupId>
|
||||
<artifactId>jakarta.mail-api</artifactId>
|
||||
<version>2.1.5</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.angus</groupId>
|
||||
<artifactId>angus-mail</artifactId>
|
||||
<version>2.0.5</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.angus</groupId>
|
||||
<artifactId>angus-activation</artifactId>
|
||||
<version>2.0.3</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jakarta.activation</groupId>
|
||||
<artifactId>jakarta.activation-api</artifactId>
|
||||
<version>2.1.4</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Bounded in-memory caches over the filesystem stores. -->
|
||||
<dependency>
|
||||
<groupId>com.github.ben-manes.caffeine</groupId>
|
||||
<artifactId>caffeine</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- HTML5 parsing for the page editor's re-seed structural merge (position-tracked, so untouched
|
||||
regions — notably the author's #content — are spliced byte-for-byte). MIT-licensed. -->
|
||||
<dependency>
|
||||
<groupId>org.jsoup</groupId>
|
||||
<artifactId>jsoup</artifactId>
|
||||
<version>1.18.3</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Pure-Java, zero-dependency SVG rasterizer (single ~500 KB jar) — used to GENERATE the raster
|
||||
icon slots (apple-touch / 192 / 512 PNG + favicon.ico) from one uploaded master SVG. Chosen over
|
||||
Batik for its lean footprint. It renders SVG into a BufferedImage (headless); it runs NO scripts
|
||||
and is loaded with external resources DENIED (no SSRF from a tenant-supplied SVG). MIT-licensed. -->
|
||||
<dependency>
|
||||
<groupId>com.github.weisj</groupId>
|
||||
<artifactId>jsvg</artifactId>
|
||||
<version>2.1.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Brotli HTTP response compression. The kernel's single CompressionFilter does gzip with the JDK's
|
||||
own GZIPOutputStream and brotli via brotli4j; Jetty's native gzip stays off so there is one
|
||||
compression decision. The brotli encoder is a native lib shipped as a per-platform artifact
|
||||
(linux-x86_64 covers typical servers, CI and development machines); on any platform without a matching
|
||||
native the filter probes at startup and cleanly falls back to gzip. -->
|
||||
<dependency>
|
||||
<groupId>com.aayushatharva.brotli4j</groupId>
|
||||
<artifactId>brotli4j</artifactId>
|
||||
<version>1.18.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.aayushatharva.brotli4j</groupId>
|
||||
<artifactId>native-linux-x86_64</artifactId>
|
||||
<version>1.18.0</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- OPT-IN clustering (runway.cluster.enabled=true; default OFF). Hazelcast provides the distributed
|
||||
session IMap + the cross-node event topic; spring-session-core provides the
|
||||
SessionRepository API over which the kernel hand-rolls a HazelcastSessionRepository. Both stay on
|
||||
the classpath unconditionally — ClusterConfig's class-level @ConditionalOnProperty is what keeps a
|
||||
single-node deployment from wiring any of it. Version PINNED for Hazelcast (unified jar — the client
|
||||
lives in it, so no separate hazelcast-client dependency); NOT hazelcast-spring or
|
||||
spring-session-hazelcast (the latter was dropped in Spring Session 4.x).
|
||||
spring-session-core is BOM-managed by the Boot 4 parent, so it stays unversioned. -->
|
||||
<dependency>
|
||||
<groupId>com.hazelcast</groupId>
|
||||
<artifactId>hazelcast</artifactId>
|
||||
<version>5.6.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.session</groupId>
|
||||
<artifactId>spring-session-core</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Health/metrics endpoints (the systemd health probe + the app-realm /actuator surface). -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Prometheus scrape format for /actuator/prometheus (version managed by the Spring Boot BOM). -->
|
||||
<dependency>
|
||||
<groupId>io.micrometer</groupId>
|
||||
<artifactId>micrometer-registry-prometheus</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Build-time metadata for @ConfigurationProperties (no runtime footprint). -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>${project.artifactId}-${project.version}</finalName>
|
||||
<!--
|
||||
Declaring <resources> replaces the inherited list, so the first two entries restate
|
||||
spring-boot-starter-parent's exactly (application*.yml/.yaml/.properties filtered with @..@, everything
|
||||
else copied as is). The third puts the license, the plugin permission and the third-party notices
|
||||
into the jar's META-INF, so the exec jar fetched on its own still carries its terms.
|
||||
-->
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>${basedir}/src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
<includes>
|
||||
<include>**/application*.yml</include>
|
||||
<include>**/application*.yaml</include>
|
||||
<include>**/application*.properties</include>
|
||||
</includes>
|
||||
</resource>
|
||||
<resource>
|
||||
<directory>${basedir}/src/main/resources</directory>
|
||||
<excludes>
|
||||
<exclude>**/application*.yml</exclude>
|
||||
<exclude>**/application*.yaml</exclude>
|
||||
<exclude>**/application*.properties</exclude>
|
||||
</excludes>
|
||||
</resource>
|
||||
<resource>
|
||||
<directory>${project.basedir}/..</directory>
|
||||
<includes>
|
||||
<include>LICENSE</include>
|
||||
<include>LICENSE-EXCEPTION</include>
|
||||
<include>THIRD-PARTY-NOTICES</include>
|
||||
</includes>
|
||||
<targetPath>META-INF</targetPath>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<!--
|
||||
Run the configuration processor. JDK 23+ no longer runs annotation processors found on the plain
|
||||
classpath implicitly, so the `optional` dependency above alone generated NOTHING: no
|
||||
META-INF/spring-configuration-metadata.json, no IDE completion, no documented runway.* keys. Naming it
|
||||
on the processor path (version from the Boot BOM) is the supported fix. The processor also merges
|
||||
src/main/resources/META-INF/additional-spring-configuration-metadata.json — the keys read via @Value or
|
||||
straight from the Environment, which no @ConfigurationProperties class describes.
|
||||
-->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
<annotationProcessorPathsUseDepMgmt>true</annotationProcessorPathsUseDepMgmt>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<!--
|
||||
Attach the executable (fat) jar under the `exec` classifier so the PLAIN thin
|
||||
jar stays runway-app's MAIN artifact. A reactor sibling that compiles `provided`
|
||||
against runway-app (runway-plugin-protection uses the kernel seams EdgeGuard /
|
||||
EdgeVerdict / CidrSet / LoginAttemptGate) then resolves real .class files, not a
|
||||
fat jar's BOOT-INF/classes/ — otherwise a full-reactor `mvn install` / building the
|
||||
plugin jar fails with "cannot find symbol". The launcher and the dist bundle the
|
||||
`-exec` jar; nothing depends on the thin jar at runtime.
|
||||
-->
|
||||
<classifier>exec</classifier>
|
||||
</configuration>
|
||||
<executions>
|
||||
<!--
|
||||
Generate META-INF/build-info.properties (version + build timestamp) so a BuildProperties
|
||||
bean is available at runtime — surfaced read-only on the app-realm "About Runway" screen.
|
||||
Merges with the parent's inherited `repackage` execution (matched by id); the repackage still
|
||||
runs and still produces the `-exec` jar.
|
||||
-->
|
||||
<execution>
|
||||
<id>build-info</id>
|
||||
<goals>
|
||||
<goal>build-info</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,30 @@
|
||||
package mx.quest.runway;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
/**
|
||||
* Entry point for the Runway kernel.
|
||||
*
|
||||
* <p>Plugin packages live OUTSIDE
|
||||
* this base package ({@code mx.quest.runway.plugins.*}) so the component scan never double-scans
|
||||
* them; they enter the context through their registered {@code @Configuration}.
|
||||
*/
|
||||
@SpringBootApplication
|
||||
public class RunwayApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
SpringApplication.run(RunwayApplication.class, args);
|
||||
} catch (Throwable failure) {
|
||||
// A startup failure that the wiring quarantine pinned on one plugin ends with the supervisor's relaunch
|
||||
// code: the marker it wrote makes the next boot load without that plugin. Anything else stays an
|
||||
// ordinary failure (Spring Boot has already reported it).
|
||||
java.util.OptionalInt relaunch = mx.quest.runway.plugin.PluginQuarantine.exitCodeAfterFailure();
|
||||
if (relaunch.isPresent()) {
|
||||
System.exit(relaunch.getAsInt());
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
package mx.quest.runway.authz;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.function.UnaryOperator;
|
||||
import java.util.regex.Pattern;
|
||||
import mx.quest.runway.security.AppUserStore;
|
||||
import mx.quest.runway.security.Roles;
|
||||
import mx.quest.runway.security.RunwaySecurityProperties;
|
||||
import mx.quest.runway.security.RunwayUserDetails;
|
||||
import mx.quest.runway.security.SiteUserStore;
|
||||
import mx.quest.runway.security.User;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* The authorization-management service — where an administrator defines roles and assigns roles/permissions
|
||||
* to users, with the <b>bounded-grant</b> rules enforced server-side: no one grants beyond their own
|
||||
* effective authority, the wildcard key is grantable only by the master or a wildcard admin, and the master
|
||||
* keys are never grantable in-app. Role definition itself is reserved to administrators (the wildcard tier
|
||||
* and above), and a custom role may hold only grantable permissions (never a master/wildcard-only one).
|
||||
*
|
||||
* <p>Operations take the acting principal and the resolved scope ({@code tenancyId} is {@code null} for the
|
||||
* application realm). All checks route through {@link AuthorizationService} so the precedence and tenancy
|
||||
* scoping are the same as at request time. Business logic lives here, never in a controller.
|
||||
*
|
||||
* <h2>Concurrency: one scope, one critical section</h2>
|
||||
* Every change runs under its scope's lock ({@link GrantStore#lock}), from the checks to the last write: the checks
|
||||
* read the role graph and the grants (does the role exist, may the actor grant it), and a write made between a check
|
||||
* and its write could make the check stale. So a role being deleted is never assigned at the same moment, and two
|
||||
* matrix writes to the same scope never lose each other. Grant-file changes go through {@link GrantStore}'s atomic
|
||||
* update. Scopes are the application realm and each site; different sites never wait for each other.
|
||||
*/
|
||||
@Service
|
||||
public class AuthorizationAdminService {
|
||||
|
||||
private final RoleStore roles;
|
||||
private final GrantStore grants;
|
||||
private final PermissionCatalog catalog;
|
||||
private final AuthorizationService authz;
|
||||
private final RunwaySecurityProperties security;
|
||||
private final AppUserStore appUsers;
|
||||
private final SiteUserStore siteUsers;
|
||||
|
||||
public AuthorizationAdminService(RoleStore roles, GrantStore grants, PermissionCatalog catalog,
|
||||
AuthorizationService authz, RunwaySecurityProperties security,
|
||||
AppUserStore appUsers, SiteUserStore siteUsers) {
|
||||
this.roles = Objects.requireNonNull(roles, "roles");
|
||||
this.grants = Objects.requireNonNull(grants, "grants");
|
||||
this.catalog = Objects.requireNonNull(catalog, "catalog");
|
||||
this.authz = Objects.requireNonNull(authz, "authz");
|
||||
this.security = Objects.requireNonNull(security, "security");
|
||||
this.appUsers = Objects.requireNonNull(appUsers, "appUsers");
|
||||
this.siteUsers = Objects.requireNonNull(siteUsers, "siteUsers");
|
||||
}
|
||||
|
||||
// --- role definition (administrators only) ----------------------------------------------
|
||||
|
||||
/**
|
||||
* The syntactic shape of a custom role name: 1–64 characters, upper/lower letters, digits, underscore and
|
||||
* hyphen only. Deliberately conservative — a role name is an identifier that travels into YAML files, grant
|
||||
* deltas and log lines, so it excludes whitespace, dots and slashes (path-safe by construction) and anything
|
||||
* that could collide with a delimiter or be mistaken for a traversal segment. It is <b>not</b> a filesystem
|
||||
* path (roles are stored as values inside a single per-scope role file), but keeping the vocabulary tight is
|
||||
* cheap defence and keeps names greppable.
|
||||
*/
|
||||
private static final Pattern ROLE_NAME = Pattern.compile("[A-Za-z0-9_-]{1,64}");
|
||||
|
||||
/**
|
||||
* Creates a <b>new</b> custom role with the given name, optional direct permissions and optional initial
|
||||
* inherit edges, failing fast if the name is malformed, reserved, already taken (as a custom role or a
|
||||
* predefined/reserved key), or if any edge/permission is invalid. Unlike {@link #saveRole} (which
|
||||
* create-<em>or</em>-replaces), this is strictly a create: a name clash is an error, never a silent
|
||||
* overwrite. Reserved to administrators (manage-roles). The {@link RoleStore} re-validates the resulting
|
||||
* graph (seal, unknown refs, cycle) before it is persisted, so the invariants cannot be bypassed here.
|
||||
*
|
||||
* @param actor the acting principal (its realm fixes the scope)
|
||||
* @param tenancyId the bound tenancy id, or {@code null} for the application realm
|
||||
* @param name the new role's name (validated against {@link #ROLE_NAME}, must be free)
|
||||
* @param permissions the permission keys granted directly by the role (grantable only; may be empty)
|
||||
* @param inherits the names of existing custom roles this role inherits (may be empty)
|
||||
* @throws IllegalArgumentException if the name is malformed, reserved or already in use, or a permission
|
||||
* is not grantable, or an inherited role does not exist
|
||||
* @throws org.springframework.security.access.AccessDeniedException if the actor may not manage roles
|
||||
*/
|
||||
public void createRole(RunwayUserDetails actor, String tenancyId, String name,
|
||||
Set<String> permissions, Set<String> inherits) {
|
||||
inScope(tenancyId, () -> {
|
||||
requireManageRoles(actor, tenancyId);
|
||||
String trimmed = name == null ? "" : name.trim();
|
||||
if (!ROLE_NAME.matcher(trimmed).matches()) {
|
||||
throw new IllegalArgumentException(
|
||||
"a role name must be 1–64 characters of letters, digits, '_' or '-'");
|
||||
}
|
||||
if (nameInUse(actor.realm(), tenancyId, trimmed)) {
|
||||
throw new IllegalArgumentException("a role named '" + trimmed + "' already exists");
|
||||
}
|
||||
Role role = new Role(trimmed, actor.realm(),
|
||||
permissions == null ? Set.of() : permissions,
|
||||
inherits == null ? Set.of() : inherits);
|
||||
saveRole(actor, tenancyId, role); // re-validates seal/permissions/refs/cycle before persisting
|
||||
});
|
||||
}
|
||||
|
||||
/** Creates or replaces a custom role (by name). Reserved to administrators; only grantable permissions. */
|
||||
public void saveRole(RunwayUserDetails actor, String tenancyId, Role role) {
|
||||
inScope(tenancyId, () -> {
|
||||
requireRealm(actor, role.realm());
|
||||
requireManageRoles(actor, tenancyId);
|
||||
if (ReservedRoles.isReserved(role.name())) {
|
||||
throw new IllegalArgumentException("'" + role.name() + "' is a reserved role name");
|
||||
}
|
||||
for (String key : role.permissions()) {
|
||||
if (catalog.find(key).filter(catalog::isGrantable).isEmpty()) {
|
||||
throw new IllegalArgumentException(
|
||||
"a role may only hold grantable permissions; '" + key + "' is not");
|
||||
}
|
||||
}
|
||||
List<Role> updated = new ArrayList<>();
|
||||
boolean replaced = false;
|
||||
for (Role existing : roleList(actor.realm(), tenancyId)) {
|
||||
if (existing.name().equals(role.name())) {
|
||||
updated.add(role);
|
||||
replaced = true;
|
||||
} else {
|
||||
updated.add(existing);
|
||||
}
|
||||
}
|
||||
if (!replaced) {
|
||||
updated.add(role);
|
||||
}
|
||||
saveRoles(actor.realm(), tenancyId, updated); // RoleStore re-validates seal/refs/cycle
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a custom role. Reserved/system role keys cannot be deleted (they are code-defined, not stored),
|
||||
* and the delete is rejected by the store's re-validation if another custom role still inherits the target
|
||||
* (removing it would leave a dangling inherit edge — an unknown-ref violation). Reserved to administrators.
|
||||
* The role is also removed from the grants file ({@link GrantFile#withoutRole}): its holders lose what it gave
|
||||
* them, and a role created later under the same name starts with no holders and no deltas.
|
||||
*
|
||||
* @throws IllegalArgumentException if {@code roleName} is a reserved key or is not a defined custom role
|
||||
* @throws IllegalStateException if another role still inherits it (the graph rejects the dangling edge);
|
||||
* nothing is written then
|
||||
* @throws org.springframework.security.access.AccessDeniedException if the actor may not manage roles
|
||||
*/
|
||||
public void deleteRole(RunwayUserDetails actor, String tenancyId, String roleName) {
|
||||
inScope(tenancyId, () -> {
|
||||
requireManageRoles(actor, tenancyId);
|
||||
if (ReservedRoles.isReserved(roleName)) {
|
||||
throw new IllegalArgumentException("'" + roleName + "' is a reserved role and cannot be deleted");
|
||||
}
|
||||
List<Role> current = roleList(actor.realm(), tenancyId);
|
||||
if (current.stream().noneMatch(role -> role.name().equals(roleName))) {
|
||||
throw new IllegalArgumentException("no such custom role: " + roleName);
|
||||
}
|
||||
List<Role> remaining = current.stream().filter(role -> !role.name().equals(roleName)).toList();
|
||||
RoleGraph.of(remaining); // rejects BEFORE any write if another role still inherits it (dangling ref)
|
||||
// Grants first, then roles: two files, two atomic writes, in one critical section (the scope's lock), so no
|
||||
// assignment of this role lands between them. A role name the graph no longer knows still resolves to
|
||||
// itself (built-in tiers rely on that), so a role gone from the graph but left on its holders keeps giving
|
||||
// them its console grants, and a retry finds no such role. In this order a failed roles write leaves the
|
||||
// role defined with no holders and no deltas (less access, never more), and the delete can simply be run
|
||||
// again.
|
||||
updateGrants(actor.realm(), tenancyId, file -> file.withoutRole(roleName));
|
||||
saveRoles(actor.realm(), tenancyId, remaining); // re-validates the same graph
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an inherit edge {@code roleName → parentName}: {@code roleName} gains {@code parentName}'s effective
|
||||
* permissions (the DAG accumulates downward, {@link RoleGraph}). Both must be existing custom roles of the
|
||||
* actor's realm; the resulting graph is re-validated by the {@link RoleStore}, so a <b>cycle</b> (or a seal
|
||||
* / unknown-ref violation) is rejected there — this method never bypasses the cycle check. Idempotent: adding
|
||||
* an edge that already exists is a no-op. Reserved to administrators.
|
||||
*
|
||||
* @throws IllegalArgumentException if either role is missing/reserved, they are the same, or the edge would
|
||||
* form a cycle (surfaced from {@link RoleGraph} via the store)
|
||||
* @throws org.springframework.security.access.AccessDeniedException if the actor may not manage roles
|
||||
*/
|
||||
public void addRoleInherit(RunwayUserDetails actor, String tenancyId, String roleName, String parentName) {
|
||||
inScope(tenancyId, () -> {
|
||||
requireManageRoles(actor, tenancyId);
|
||||
Role role = requireCustomRole(actor, tenancyId, roleName);
|
||||
requireCustomRole(actor, tenancyId, parentName); // the inherited role must exist too
|
||||
if (roleName.equals(parentName)) {
|
||||
throw new IllegalArgumentException("a role cannot inherit itself");
|
||||
}
|
||||
Set<String> edges = new LinkedHashSet<>(role.inherits());
|
||||
if (!edges.add(parentName)) {
|
||||
return; // already present — nothing to do
|
||||
}
|
||||
replaceRole(actor, tenancyId, new Role(role.name(), role.realm(), role.permissions(), edges));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the inherit edge {@code roleName → parentName} (idempotent — removing a missing edge is a no-op).
|
||||
* The trimmed graph is always valid (dropping an edge cannot create a cycle or a dangling ref), so this only
|
||||
* needs the role to exist. Reserved to administrators.
|
||||
*
|
||||
* @throws IllegalArgumentException if {@code roleName} is not a defined custom role
|
||||
* @throws org.springframework.security.access.AccessDeniedException if the actor may not manage roles
|
||||
*/
|
||||
public void removeRoleInherit(RunwayUserDetails actor, String tenancyId, String roleName, String parentName) {
|
||||
inScope(tenancyId, () -> {
|
||||
requireManageRoles(actor, tenancyId);
|
||||
Role role = requireCustomRole(actor, tenancyId, roleName);
|
||||
Set<String> edges = new LinkedHashSet<>(role.inherits());
|
||||
if (!edges.remove(parentName)) {
|
||||
return; // edge not present — nothing to do
|
||||
}
|
||||
replaceRole(actor, tenancyId, new Role(role.name(), role.realm(), role.permissions(), edges));
|
||||
});
|
||||
}
|
||||
|
||||
/** Looks up a defined custom role of the actor's realm/scope, or fails with a clean message. */
|
||||
private Role requireCustomRole(RunwayUserDetails actor, String tenancyId, String roleName) {
|
||||
return roleList(actor.realm(), tenancyId).stream()
|
||||
.filter(role -> role.name().equals(roleName)).findFirst()
|
||||
.orElseThrow(() -> new IllegalArgumentException("no such custom role: " + roleName));
|
||||
}
|
||||
|
||||
/** Replaces one existing custom role in place, re-validating the whole graph through the store. */
|
||||
private void replaceRole(RunwayUserDetails actor, String tenancyId, Role role) {
|
||||
List<Role> updated = roleList(actor.realm(), tenancyId).stream()
|
||||
.map(existing -> existing.name().equals(role.name()) ? role : existing).toList();
|
||||
saveRoles(actor.realm(), tenancyId, updated); // RoleStore re-validates seal/refs/cycle
|
||||
}
|
||||
|
||||
/** Whether {@code name} is already taken — as a reserved key, a predefined seed role, or a custom role. */
|
||||
private boolean nameInUse(Realm realm, String tenancyId, String name) {
|
||||
if (ReservedRoles.isReserved(name)) {
|
||||
return true;
|
||||
}
|
||||
boolean predefined = realm == Realm.APPLICATION
|
||||
? name.equals(Roles.SYSTEM_OPERATOR)
|
||||
: name.equals(Roles.OPERATOR);
|
||||
if (predefined) {
|
||||
return true;
|
||||
}
|
||||
return roleList(realm, tenancyId).stream().anyMatch(role -> role.name().equals(name));
|
||||
}
|
||||
|
||||
// --- user assignment --------------------------------------------------------------------
|
||||
|
||||
/** Assigns {@code roleName} to {@code targetId}, enforcing bounded-grant. */
|
||||
public void assignRole(RunwayUserDetails actor, String tenancyId, String targetId, String roleName) {
|
||||
inScope(tenancyId, () -> {
|
||||
requireNotMasterTarget(actor, targetId);
|
||||
requireRoleOfActorRealm(actor, roleName);
|
||||
if (!mayGrantRole(actor, roleName, tenancyId)) {
|
||||
throw new AccessDeniedException("not authorized to grant role '" + roleName + "'");
|
||||
}
|
||||
if (!ReservedRoles.isReserved(roleName) && !graph(actor.realm(), tenancyId).hasRole(roleName)) {
|
||||
throw new IllegalArgumentException("no such role: " + roleName);
|
||||
}
|
||||
updateGrants(actor.realm(), tenancyId, file -> file.withUserRole(targetId, roleName));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Revokes {@code roleName} from {@code targetId} (the actor must have grant authority over it). Removes the
|
||||
* grant-file role assignment (the channel {@link #assignRole} and the create form write custom roles to).
|
||||
*
|
||||
* <p>A role a user holds through their <b>own record</b> — their access tier ({@code OPERATOR}/{@code ADMIN})
|
||||
* — is <b>not</b> revocable here: it is the coarse console-access gate and the user's Spring authority
|
||||
* (removing it would lock them out), so it is managed on the Users screen, not the permissions matrix. Such
|
||||
* an attempt is rejected with a clear message rather than the old <i>silent no-op</i> (the grant-file delete
|
||||
* found nothing to remove, so the role stayed with no feedback).
|
||||
*/
|
||||
public void revokeRole(RunwayUserDetails actor, String tenancyId, String targetId, String roleName) {
|
||||
inScope(tenancyId, () -> {
|
||||
requireNotMasterTarget(actor, targetId);
|
||||
requireRoleOfActorRealm(actor, roleName);
|
||||
if (!mayGrantRole(actor, roleName, tenancyId)) {
|
||||
throw new AccessDeniedException("not authorized to revoke role '" + roleName + "'");
|
||||
}
|
||||
if (baseRecordRoles(actor.realm(), tenancyId, targetId).contains(roleName)) {
|
||||
throw new IllegalArgumentException("'" + roleName + "' is this user's access tier — set it on the "
|
||||
+ "Users screen; it cannot be revoked here");
|
||||
}
|
||||
updateGrants(actor.realm(), tenancyId, file -> file.withoutUserRole(targetId, roleName));
|
||||
});
|
||||
}
|
||||
|
||||
/** The roles held in {@code targetId}'s own user record (their access tier) — empty if no such user. */
|
||||
private Set<String> baseRecordRoles(Realm realm, String tenancyId, String targetId) {
|
||||
List<User> users = realm == Realm.APPLICATION ? appUsers.list() : siteUsers.list(tenancyId);
|
||||
return users.stream().filter(u -> u.principalId().equals(targetId)).findFirst()
|
||||
.map(User::roles).orElse(Set.of());
|
||||
}
|
||||
|
||||
/** Grants {@code permission} directly to {@code targetId}, enforcing grantable + bounded-grant. */
|
||||
public void grantPermission(RunwayUserDetails actor, String tenancyId, String targetId, Permission permission) {
|
||||
inScope(tenancyId, () -> {
|
||||
requireNotMasterTarget(actor, targetId);
|
||||
requireRealm(actor, permission.realm());
|
||||
if (!mayGrantPermission(actor, permission, tenancyId)) {
|
||||
throw new AccessDeniedException("not authorized to grant permission '" + permission.key() + "'");
|
||||
}
|
||||
updateGrants(actor.realm(), tenancyId, file -> file.withUserPermission(targetId, permission.key()));
|
||||
});
|
||||
}
|
||||
|
||||
/** Revokes a direct permission grant from {@code targetId}. */
|
||||
public void revokePermission(RunwayUserDetails actor, String tenancyId, String targetId, Permission permission) {
|
||||
inScope(tenancyId, () -> {
|
||||
requireNotMasterTarget(actor, targetId);
|
||||
requireRealm(actor, permission.realm());
|
||||
if (!mayGrantPermission(actor, permission, tenancyId)) {
|
||||
throw new AccessDeniedException("not authorized to revoke permission '" + permission.key() + "'");
|
||||
}
|
||||
updateGrants(actor.realm(), tenancyId, file -> file.withoutUserPermission(targetId, permission.key()));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Rejects a <b>reserved</b> role of the wrong realm before it can be written to a grant store. Non-reserved
|
||||
* roles are already realm-scoped: a custom role is looked up in the actor-realm graph, and a foreign seed
|
||||
* role (e.g. {@code SYSTEMOPERATOR} in a tenant) fails the existence check — only the reserved keys, which
|
||||
* bypass that check and whose {@code isReserved}/{@code isWildcard} tests are realm-agnostic, need this.
|
||||
*/
|
||||
private static void requireRoleOfActorRealm(RunwayUserDetails actor, String roleName) {
|
||||
if (ReservedRoles.isReserved(roleName) && !ReservedRoles.isReservedOfRealm(roleName, actor.realm())) {
|
||||
throw new IllegalArgumentException(
|
||||
"role '" + roleName + "' is not a role of the " + actor.realm() + " realm");
|
||||
}
|
||||
}
|
||||
|
||||
// --- role-level permission deltas --------------------------------------------
|
||||
|
||||
/**
|
||||
* Grants {@code permission} to {@code roleName} as a scope delta: if the permission is a declared default of
|
||||
* the role, the role's revoke-delta is cleared (the default applies again); otherwise it is added to the
|
||||
* role's grant-delta. Reserved to administrators (manage-roles), only for grantable permissions of the
|
||||
* actor's realm, and never on a master/wildcard tier (those pass everything — a delta would be inert).
|
||||
*/
|
||||
public void grantToRole(RunwayUserDetails actor, String tenancyId, String roleName, Permission permission) {
|
||||
inScope(tenancyId, () -> {
|
||||
requireManageRoles(actor, tenancyId);
|
||||
requireDeltaTarget(actor, roleName, permission);
|
||||
boolean held = heldWithoutDeltas(actor.realm(), tenancyId, roleName, permission);
|
||||
updateGrants(actor.realm(), tenancyId, file -> held
|
||||
? file.withoutRoleRevoke(roleName, permission.key()) // un-revoke a default or stored key
|
||||
: file.withRoleGrant(roleName, permission.key())); // add beyond what the role holds
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Revokes {@code permission} from {@code roleName} as a scope delta: a declared default is recorded in the
|
||||
* role's revoke-delta (so a later plugin default change does not silently re-grant it); a non-default simply
|
||||
* clears the grant-delta. Same authority and realm rules as {@link #grantToRole}.
|
||||
*/
|
||||
public void revokeFromRole(RunwayUserDetails actor, String tenancyId, String roleName, Permission permission) {
|
||||
inScope(tenancyId, () -> {
|
||||
requireManageRoles(actor, tenancyId);
|
||||
requireDeltaTarget(actor, roleName, permission);
|
||||
boolean held = heldWithoutDeltas(actor.realm(), tenancyId, roleName, permission);
|
||||
updateGrants(actor.realm(), tenancyId, file -> held
|
||||
? file.withoutRoleGrant(roleName, permission.key())
|
||||
.withRoleRevoke(roleName, permission.key()) // record the revoke of a default/stored key
|
||||
: file.withoutRoleGrant(roleName, permission.key())); // drop a grant beyond them
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code roleName} holds {@code permission} before any grant or revoke delta: as a plugin's declared
|
||||
* default, or stored on the role in the roles file. Only such a key needs a recorded revoke to take away;
|
||||
* until 1.0.0 a stored key was missed here, so revoking it from the console did nothing.
|
||||
*/
|
||||
private boolean heldWithoutDeltas(Realm realm, String tenancyId, String roleName, Permission permission) {
|
||||
return catalog.defaultsForRole(roleName).contains(permission.key())
|
||||
|| graph(realm, tenancyId).ownPermissionKeys(roleName).contains(permission.key());
|
||||
}
|
||||
|
||||
private void requireDeltaTarget(RunwayUserDetails actor, String roleName, Permission permission) {
|
||||
if (actor.realm() != permission.realm()) {
|
||||
throw new IllegalArgumentException("realm mismatch: actor is " + actor.realm()
|
||||
+ ", permission is " + permission.realm());
|
||||
}
|
||||
if (!catalog.isGrantable(permission)) {
|
||||
throw new IllegalArgumentException("a role may only hold grantable permissions; '"
|
||||
+ permission.key() + "' is master/wildcard-only");
|
||||
}
|
||||
if (ReservedRoles.isMaster(roleName) || ReservedRoles.isWildcard(roleName)) {
|
||||
throw new IllegalArgumentException("'" + roleName + "' is an admin tier — deltas on it are inert");
|
||||
}
|
||||
}
|
||||
|
||||
// --- bounded-grant authority ----------------------------------------------------
|
||||
|
||||
/** Whether {@code actor} may grant/revoke {@code roleName} in the scope. */
|
||||
public boolean mayGrantRole(RunwayUserDetails actor, String roleName, String tenancyId) {
|
||||
if (ReservedRoles.isMaster(roleName)) {
|
||||
return false; // master keys are never grantable in-app
|
||||
}
|
||||
if (ReservedRoles.isWildcard(roleName)) {
|
||||
return authz.isMaster(actor, tenancyId) || authz.isWildcard(actor, tenancyId);
|
||||
}
|
||||
return authz.isMaster(actor, tenancyId) || authz.isWildcard(actor, tenancyId)
|
||||
|| assignedRoleNames(actor, tenancyId).contains(roleName);
|
||||
}
|
||||
|
||||
/** Whether {@code actor} may grant/revoke {@code permission} in the scope (grantable + own authority). */
|
||||
public boolean mayGrantPermission(RunwayUserDetails actor, Permission permission, String tenancyId) {
|
||||
if (!catalog.isGrantable(permission)) {
|
||||
return false; // master/wildcard-only is never grantable
|
||||
}
|
||||
return authz.isMaster(actor, tenancyId) || authz.isWildcard(actor, tenancyId)
|
||||
|| authz.effectivePermissionKeys(actor, tenancyId).contains(permission.key());
|
||||
}
|
||||
|
||||
private void requireManageRoles(RunwayUserDetails actor, String tenancyId) {
|
||||
if (!authz.isMaster(actor, tenancyId) && !authz.isWildcard(actor, tenancyId)) {
|
||||
throw new AccessDeniedException("only administrators may manage roles");
|
||||
}
|
||||
}
|
||||
|
||||
private void requireNotMasterTarget(RunwayUserDetails actor, String targetId) {
|
||||
if (actor.realm() == Realm.APPLICATION) {
|
||||
String pin = security.getAppMasterId();
|
||||
if (pin != null && pin.equals(targetId)) {
|
||||
throw new AccessDeniedException("the application superadmin's authorization cannot be reassigned");
|
||||
}
|
||||
}
|
||||
// Tenant: the master short-circuits its own assignments, so editing them is inert; the master
|
||||
// *identity* is protected by the step-5 user-store guards.
|
||||
}
|
||||
|
||||
private static void requireRealm(RunwayUserDetails actor, Realm realm) {
|
||||
if (actor.realm() != realm) {
|
||||
throw new IllegalArgumentException("realm mismatch: actor is " + actor.realm() + ", target is " + realm);
|
||||
}
|
||||
}
|
||||
|
||||
private Set<String> assignedRoleNames(RunwayUserDetails actor, String tenancyId) {
|
||||
Set<String> names = new HashSet<>(actor.roles());
|
||||
names.addAll(grantsFor(actor.realm(), tenancyId).rolesOf(actor.principalId()));
|
||||
return names;
|
||||
}
|
||||
|
||||
private List<Role> roleList(Realm realm, String tenancyId) {
|
||||
return realm == Realm.APPLICATION ? roles.appRoleList() : roles.siteRoleList(tenancyId);
|
||||
}
|
||||
|
||||
private RoleGraph graph(Realm realm, String tenancyId) {
|
||||
return realm == Realm.APPLICATION ? roles.appRoles() : roles.siteRoles(tenancyId);
|
||||
}
|
||||
|
||||
private GrantFile grantsFor(Realm realm, String tenancyId) {
|
||||
return realm == Realm.APPLICATION ? grants.appGrants() : grants.siteGrants(tenancyId);
|
||||
}
|
||||
|
||||
private void saveRoles(Realm realm, String tenancyId, List<Role> list) {
|
||||
if (realm == Realm.APPLICATION) {
|
||||
roles.saveAppRoles(list);
|
||||
} else {
|
||||
roles.saveSiteRoles(tenancyId, list);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies {@code change} to the scope's latest grants in one atomic update. The base is the file as it is now, not
|
||||
* what was read for the checks; the checks stay valid because the caller holds the scope's lock.
|
||||
*/
|
||||
private void updateGrants(Realm realm, String tenancyId, UnaryOperator<GrantFile> change) {
|
||||
if (realm == Realm.APPLICATION) {
|
||||
grants.updateAppGrants(change);
|
||||
} else {
|
||||
grants.updateSiteGrants(tenancyId, change);
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs {@code work} under the lock of the scope ({@code null} = the application realm); see the class notes. */
|
||||
private void inScope(String tenancyId, Runnable work) {
|
||||
synchronized (grants.lock(GrantStore.scopeOf(tenancyId))) {
|
||||
work.run();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package mx.quest.runway.authz;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.security.RunwaySecurityProperties;
|
||||
import mx.quest.runway.security.RunwayUserDetails;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* The single authorization check — every guarded surface routes through {@link #mayAccess}. The
|
||||
* precedence is fixed and <b>fails closed</b>:
|
||||
*
|
||||
* <ol>
|
||||
* <li>the <b>master</b> (the pinned application principal, or a tenant-master assigned to the resolved
|
||||
* tenancy) passes everything;</li>
|
||||
* <li>a <b>wildcard admin</b> (holding the realm's reserved wildcard key) passes everything — the
|
||||
* master-<em>only</em> operations are a separate target-based guard, not a permission;</li>
|
||||
* <li>else the concrete permission must be in the principal's <b>effective set</b> (the union of every
|
||||
* assigned role's transitive downward closure, plus direct grants);</li>
|
||||
* <li>else <b>deny</b>. An undeclared permission, or one of the wrong realm, denies.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p>It re-reads the authoritative role/grant stores <b>per call</b> (never a cached session claim), and the
|
||||
* master/wildcard short-circuit passes <b>only for the resolved tenancy</b> — so a tenant-master assigned to
|
||||
* several tenancies gets no short-circuit on one it does not hold. The grant reason is logged for audit.
|
||||
*/
|
||||
@Service
|
||||
public class AuthorizationService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(AuthorizationService.class);
|
||||
|
||||
private final RoleStore roles;
|
||||
private final GrantStore grants;
|
||||
private final PermissionCatalog catalog;
|
||||
private final RunwaySecurityProperties security;
|
||||
|
||||
public AuthorizationService(RoleStore roles, GrantStore grants, PermissionCatalog catalog,
|
||||
RunwaySecurityProperties security) {
|
||||
this.roles = Objects.requireNonNull(roles, "roles");
|
||||
this.grants = Objects.requireNonNull(grants, "grants");
|
||||
this.catalog = Objects.requireNonNull(catalog, "catalog");
|
||||
this.security = Objects.requireNonNull(security, "security");
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code principal} may exercise {@code permission} in {@code tenancyId} (null/ignored for the
|
||||
* application realm). Fail-closed: an undeclared permission, a realm mismatch, a tenant permission with no
|
||||
* resolved tenancy, or no resolved grant denies.
|
||||
*/
|
||||
public boolean mayAccess(RunwayUserDetails principal, Permission permission, String tenancyId) {
|
||||
if (principal == null || permission == null) {
|
||||
return false;
|
||||
}
|
||||
if (principal.realm() != permission.realm()) {
|
||||
return false; // realms never cross
|
||||
}
|
||||
if (permission.realm() == Realm.TENANT && tenancyId == null) {
|
||||
return false; // a tenant permission requires a resolved tenancy — no tenancy, no access
|
||||
}
|
||||
if (!catalog.isDeclared(permission.key())) {
|
||||
return false; // an undeclared permission can never pass
|
||||
}
|
||||
if (isMaster(principal, tenancyId)) {
|
||||
return granted(principal, permission, "master");
|
||||
}
|
||||
if (isWildcard(principal, tenancyId)) {
|
||||
return granted(principal, permission, "wildcard");
|
||||
}
|
||||
if (effectivePermissionKeys(principal, tenancyId).contains(permission.key())) {
|
||||
return granted(principal, permission, "permission");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code principal} is the master for the scope — the pinned application principal, or a
|
||||
* tenant-master assigned to the resolved tenancy (the tenancy-scoped short-circuit).
|
||||
*/
|
||||
public boolean isMaster(RunwayUserDetails principal, String tenancyId) {
|
||||
if (principal.realm() == Realm.APPLICATION) {
|
||||
String pin = security.getAppMasterId();
|
||||
return pin != null && !pin.isBlank() && pin.equals(principal.principalId());
|
||||
}
|
||||
return principal.master() && tenancyId != null && principal.assignedTo(tenancyId);
|
||||
}
|
||||
|
||||
/** Whether {@code principal} holds the realm's wildcard role in the resolved scope. */
|
||||
public boolean isWildcard(RunwayUserDetails principal, String tenancyId) {
|
||||
return assignedRoleNames(principal, tenancyId).contains(ReservedRoles.wildcardKey(principal.realm()));
|
||||
}
|
||||
|
||||
/**
|
||||
* The principal's effective permission keys: direct grants, plus — over the closure of every assigned role
|
||||
* (the role and what it inherits), per role — {@code (stored ∪ declared defaults ∪ roleGrants) − roleRevokes}.
|
||||
* The role deltas realize the locked
|
||||
* "stored as DELTAS from the declared defaults" model: a plugin changing its {@code defaultRoles}
|
||||
* propagates wherever a scope has not explicitly overridden it.
|
||||
*/
|
||||
public Set<String> effectivePermissionKeys(RunwayUserDetails principal, String tenancyId) {
|
||||
RoleGraph graph = graphFor(principal.realm(), tenancyId);
|
||||
GrantFile grantFile = grantsFor(principal.realm(), tenancyId);
|
||||
|
||||
Set<String> keys = new HashSet<>(grantFile.permissionsOf(principal.principalId()));
|
||||
Set<String> roleClosure = new HashSet<>();
|
||||
for (String roleName : assignedRoleNames(principal, tenancyId)) {
|
||||
roleClosure.addAll(graph.effectiveRoleNames(roleName)); // role names in the closure (incl. predefined)
|
||||
}
|
||||
for (String roleName : roleClosure) {
|
||||
keys.addAll(rolePermissions(graph, grantFile, roleName));
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* One role's own contribution: {@code (stored ∪ declared defaults ∪ role grants) − role revokes}.
|
||||
*
|
||||
* <p>Revoke is applied LAST so a deny always wins over a grant of the same key on the same role (fail-closed),
|
||||
* even in a hand-edited grant file that names a key in both delta sets. It covers the permissions stored on
|
||||
* the role in the roles file too: until 1.0.0 those were added outside the revoke, so a key typed into the
|
||||
* file showed as granted and could not be revoked from the console.
|
||||
*/
|
||||
private Set<String> rolePermissions(RoleGraph graph, GrantFile grantFile, String roleName) {
|
||||
Set<String> rolePermissions = new HashSet<>(graph.ownPermissionKeys(roleName));
|
||||
rolePermissions.addAll(catalog.defaultsForRole(roleName));
|
||||
rolePermissions.addAll(grantFile.roleGrantsOf(roleName));
|
||||
rolePermissions.removeAll(grantFile.roleRevokesOf(roleName));
|
||||
return rolePermissions;
|
||||
}
|
||||
|
||||
/**
|
||||
* A single role's effective grantable permission keys in {@code scope} — the same fold {@link #mayAccess}
|
||||
* applies for a user holding <em>only</em> this role: per role in the closure,
|
||||
* {@code (stored ∪ declared defaults ∪ role grants) − role revokes}. The <b>wildcard</b> tier
|
||||
* ({@code ADMIN}/{@code SYSTEMADMIN}) and the <b>master</b> hold <em>every</em> grantable permission of the
|
||||
* realm — they pass by short-circuit, not by an explicit key set — so this reports the full grantable set
|
||||
* for them. The permissions matrix uses this to show each role's <b>true</b> reach (so the all-access
|
||||
* wildcard no longer renders as an empty row, and a role's granted core permissions appear).
|
||||
*
|
||||
* @param realm the realm the role belongs to (never {@code null})
|
||||
* @param tenancyId the bound tenancy for a tenant-realm role ({@code null} for the application realm)
|
||||
* @param roleName the role whose effective grantable keys to compute (never {@code null})
|
||||
* @return the grantable permission keys the role effectively holds (never {@code null})
|
||||
*/
|
||||
public Set<String> effectiveRolePermissionKeys(Realm realm, String tenancyId, String roleName) {
|
||||
if (ReservedRoles.isMaster(roleName) || ReservedRoles.isWildcard(roleName)) {
|
||||
Set<String> all = new HashSet<>();
|
||||
for (Permission permission : catalog.grantable(realm)) {
|
||||
all.add(permission.key());
|
||||
}
|
||||
return all;
|
||||
}
|
||||
RoleGraph graph = graphFor(realm, tenancyId);
|
||||
GrantFile grantFile = grantsFor(realm, tenancyId);
|
||||
Set<String> keys = new HashSet<>();
|
||||
for (String roleInClosure : graph.effectiveRoleNames(roleName)) {
|
||||
keys.addAll(rolePermissions(graph, grantFile, roleInClosure));
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
private Set<String> assignedRoleNames(RunwayUserDetails principal, String tenancyId) {
|
||||
Set<String> names = new HashSet<>(principal.roles());
|
||||
names.addAll(grantsFor(principal.realm(), tenancyId).rolesOf(principal.principalId()));
|
||||
return names;
|
||||
}
|
||||
|
||||
private RoleGraph graphFor(Realm realm, String tenancyId) {
|
||||
return realm == Realm.APPLICATION ? roles.appRoles() : roles.siteRoles(tenancyId);
|
||||
}
|
||||
|
||||
private GrantFile grantsFor(Realm realm, String tenancyId) {
|
||||
return realm == Realm.APPLICATION ? grants.appGrants() : grants.siteGrants(tenancyId);
|
||||
}
|
||||
|
||||
private static boolean granted(RunwayUserDetails principal, Permission permission, String reason) {
|
||||
log.debug("mayAccess granted: {} for '{}' on {} via {}",
|
||||
permission.key(), principal.getUsername(), permission.realm(), reason);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package mx.quest.runway.authz;
|
||||
|
||||
import java.util.Objects;
|
||||
import mx.quest.runway.security.RunwayUserDetails;
|
||||
import mx.quest.runway.site.Site;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import mx.quest.runway.spi.service.AccessCheck;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* The method-security expression root, registered as the bean {@code authz} so guarded methods can write
|
||||
* {@code @PreAuthorize("@authz.may('EDIT_PAGES')")}. It bridges Spring's per-method check to the single
|
||||
* {@link AuthorizationService#mayAccess} engine, resolving both halves of the call from request state:
|
||||
*
|
||||
* <ul>
|
||||
* <li>the <b>principal</b> from the active {@code SecurityContext} (the app or tenant context the matched
|
||||
* chain installed — only one is current per request, so this picks the right realm automatically);</li>
|
||||
* <li>the <b>tenancy</b> from {@link SiteResolver#current()} for a tenant-realm permission, or {@code null}
|
||||
* for an application-realm one (application permissions are not tenancy-scoped).</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>It is <b>fail-closed</b> end to end: no authentication, a non-{@link RunwayUserDetails} principal, or an
|
||||
* undeclared permission key all yield {@code false} before the engine is consulted. This is the
|
||||
* <em>per-operation</em> layer; it runs <em>behind</em> the realm/tenancy-entry gates in the security chains
|
||||
* (which establish that the principal legitimately belongs to the current realm and tenancy), so trusting the
|
||||
* principal's role claims here is sound.
|
||||
*
|
||||
* <p>It is also the kernel's implementation of the SPI {@link AccessCheck} (since SPI 0.5.0): a plugin injects
|
||||
* {@code AccessCheck} by type and gets this bean, so plugins use exactly the check the console uses. Off a request
|
||||
* thread there is no {@code SecurityContext}, so every check answers {@code false}; an anonymous endpoint route is
|
||||
* dispatched with an empty context for the same effect.
|
||||
*/
|
||||
@Component("authz")
|
||||
public class AuthzExpressions implements AccessCheck {
|
||||
|
||||
private final AuthorizationService authz;
|
||||
private final PermissionCatalog catalog;
|
||||
private final SiteResolver siteResolver;
|
||||
|
||||
public AuthzExpressions(AuthorizationService authz, PermissionCatalog catalog, SiteResolver siteResolver) {
|
||||
this.authz = Objects.requireNonNull(authz, "authz");
|
||||
this.catalog = Objects.requireNonNull(catalog, "catalog");
|
||||
this.siteResolver = Objects.requireNonNull(siteResolver, "siteResolver");
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the current principal may exercise the permission named {@code permissionKey} in the current
|
||||
* scope. The permission's realm is taken from the catalog (so the key alone is enough); an undeclared key
|
||||
* fails closed.
|
||||
*/
|
||||
@Override
|
||||
public boolean may(String permissionKey) {
|
||||
RunwayUserDetails principal = currentPrincipal();
|
||||
if (principal == null) {
|
||||
return false;
|
||||
}
|
||||
Permission permission = catalog.find(permissionKey).orElse(null);
|
||||
if (permission == null) {
|
||||
return false; // an undeclared key can never authorize
|
||||
}
|
||||
String tenancyId = permission.realm() == Realm.APPLICATION ? null : currentTenancyId();
|
||||
return authz.mayAccess(principal, permission, tenancyId);
|
||||
}
|
||||
|
||||
/** Whether the current principal may exercise {@code permissionKey} in an <b>explicitly named</b> tenancy. */
|
||||
public boolean mayInTenancy(String permissionKey, String tenancyId) {
|
||||
RunwayUserDetails principal = currentPrincipal();
|
||||
if (principal == null) {
|
||||
return false;
|
||||
}
|
||||
Permission permission = catalog.find(permissionKey).orElse(null);
|
||||
if (permission == null || permission.realm() == Realm.APPLICATION) {
|
||||
return false; // tenancy-scoped form is for tenant-realm permissions only
|
||||
}
|
||||
return authz.mayAccess(principal, permission, tenancyId);
|
||||
}
|
||||
|
||||
private static RunwayUserDetails currentPrincipal() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication == null || !authentication.isAuthenticated()) {
|
||||
return null;
|
||||
}
|
||||
return authentication.getPrincipal() instanceof RunwayUserDetails principal ? principal : null;
|
||||
}
|
||||
|
||||
private String currentTenancyId() {
|
||||
return siteResolver.current().map(Site::id).orElse(null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package mx.quest.runway.authz;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import mx.quest.runway.site.Site;
|
||||
import mx.quest.runway.site.SiteStore;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Validates the authorization role stores at startup, <b>fail-closed</b>, and holds the resulting tenancy
|
||||
* quarantine set. The role graphs are already validated lazily on first read ({@link RoleGraph#of} rejects a
|
||||
* duplicate name, the reserved-chain seal, an unknown inherited role, or a cycle), so a tampered file can
|
||||
* never yield a usable graph; this hook makes that check <b>eager</b> and routes the two realms differently:
|
||||
*
|
||||
* <ul>
|
||||
* <li><b>Application roles</b> ({@code app-roles.yml}) are part of the platform trusted computing base — an
|
||||
* invalid file <b>aborts context refresh</b> (the platform never boots with a broken/tampered app
|
||||
* authorization store), mirroring {@code RealmActivation} for the identity store.</li>
|
||||
* <li><b>Tenancy roles</b> ({@code sites/<id>/roles.yml}) follow <b>degrade-don't-crash</b>: a single
|
||||
* invalid file <b>quarantines that one tenancy</b> (its admin surface is short-circuited by
|
||||
* {@link QuarantinedSiteFilter}) and is logged for the operator, while the platform and every other
|
||||
* tenancy stay up.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Quarantine is a runtime safety state, not a persisted status — repairing the file and restarting clears
|
||||
* it (a failed graph load is never cached, so no stale graph lingers). Safe in every mode: absent stores read
|
||||
* as empty, which is valid, so first-run WIZARD boot is unaffected.
|
||||
*/
|
||||
@Component
|
||||
public class AuthzStoreIntegrity {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(AuthzStoreIntegrity.class);
|
||||
|
||||
private final RoleStore roles;
|
||||
private final SiteStore sites;
|
||||
private final Set<String> quarantined = ConcurrentHashMap.newKeySet();
|
||||
|
||||
public AuthzStoreIntegrity(RoleStore roles, SiteStore sites) {
|
||||
this.roles = roles;
|
||||
this.sites = sites;
|
||||
}
|
||||
|
||||
/** Validates the role stores; an invalid application store aborts startup, an invalid tenancy is quarantined. */
|
||||
@PostConstruct
|
||||
public void validateOnStartup() {
|
||||
try {
|
||||
roles.appRoles(); // RoleGraph.of validates: duplicate, seal, missing ref, cycle
|
||||
} catch (RuntimeException e) {
|
||||
throw new IllegalStateException(
|
||||
"application role store (app-roles.yml) is invalid; refusing to start: " + e.getMessage(), e);
|
||||
}
|
||||
for (Site site : sites.findAll()) {
|
||||
try {
|
||||
roles.siteRoles(site.id());
|
||||
} catch (RuntimeException e) {
|
||||
quarantined.add(site.id());
|
||||
log.error("Tenancy '{}' has an invalid role store (roles.yml); quarantining its admin surface "
|
||||
+ "until repaired and restarted: {}", site.id(), e.getMessage());
|
||||
}
|
||||
}
|
||||
log.info("Authorization role stores validated at startup ({} tenancy/tenancies quarantined).",
|
||||
quarantined.size());
|
||||
}
|
||||
|
||||
/** Whether {@code siteId}'s role store failed startup validation (its admin surface is held). */
|
||||
public boolean isQuarantined(String siteId) {
|
||||
return siteId != null && quarantined.contains(siteId);
|
||||
}
|
||||
|
||||
/** The ids of tenancies quarantined at startup (a snapshot). */
|
||||
public Set<String> quarantined() {
|
||||
return Set.copyOf(quarantined);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package mx.quest.runway.authz;
|
||||
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import mx.quest.runway.web.FilterOrder;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Registers the authorization servlet filter in the TENANT band of the kernel-wide ladder
|
||||
* ({@link FilterOrder}). {@link QuarantinedSiteFilter} sits at {@link FilterOrder#CORE_QUARANTINED_SITE} —
|
||||
* inner of the suspended-site short-circuit (the site is already bound) and outer of the security chain
|
||||
* ({@link FilterOrder#CORE_SECURITY}), so it can 503 a quarantined tenancy's admin surface before
|
||||
* authorization is attempted.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class AuthzWebConfig {
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean<QuarantinedSiteFilter> quarantinedSiteFilterRegistration(
|
||||
SiteResolver resolver, AuthzStoreIntegrity integrity) {
|
||||
FilterRegistrationBean<QuarantinedSiteFilter> registration =
|
||||
new FilterRegistrationBean<>(new QuarantinedSiteFilter(resolver, integrity));
|
||||
registration.setOrder(FilterOrder.CORE_QUARANTINED_SITE);
|
||||
registration.addUrlPatterns("/*");
|
||||
registration.setName("quarantinedSiteFilter");
|
||||
return registration;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package mx.quest.runway.authz;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* The on-disk shape of a grant store — per-principal role assignments and direct permission grants, plus the
|
||||
* <b>role-level deltas</b> from plugins' declared {@code defaultRoles}. These are the assignments that vary by
|
||||
* scope: the application file ({@code external/app-grants.yml}) and each tenancy's own file
|
||||
* ({@code sites/<id>/permissions.yml}, which travels in its backup). Keyed by stable principal id / role name;
|
||||
* values are role names / permission keys.
|
||||
*
|
||||
* <p>The role deltas realize the locked model "stored as DELTAS from the declared defaults, so plugin default
|
||||
* changes propagate where not overridden": {@code roleGrants} adds a (grantable) permission to a role beyond
|
||||
* its declared defaults; {@code roleRevokes} removes one a role would otherwise hold by default. The effective
|
||||
* set a role grants is then {@code (declared-defaults − roleRevokes) ∪ roleGrants} (see
|
||||
* {@link AuthorizationService#effectivePermissionKeys}).
|
||||
*
|
||||
* <p><b>Back-compatible:</b> a grant file written before role deltas existed simply omits the two new
|
||||
* sections; an absent map reads as empty (the 2-arg constructor and {@code null} handling guarantee it), so
|
||||
* old {@code app-grants.yml} / {@code permissions.yml} keep loading unchanged. Plaintext by design
|
||||
* (integrity, not confidentiality, is the guard).
|
||||
*
|
||||
* @param roles principal id → assigned role names (copied, unmodifiable; {@code null} → empty)
|
||||
* @param permissions principal id → directly-granted permission keys (copied, unmodifiable; {@code null} → empty)
|
||||
* @param roleGrants role name → permission keys added to that role (delta beyond declared defaults)
|
||||
* @param roleRevokes role name → permission keys removed from that role (delta from declared defaults)
|
||||
*/
|
||||
public record GrantFile(Map<String, Set<String>> roles, Map<String, Set<String>> permissions,
|
||||
Map<String, Set<String>> roleGrants, Map<String, Set<String>> roleRevokes) {
|
||||
|
||||
public GrantFile {
|
||||
roles = copy(roles);
|
||||
permissions = copy(permissions);
|
||||
roleGrants = copy(roleGrants);
|
||||
roleRevokes = copy(roleRevokes);
|
||||
}
|
||||
|
||||
/** Back-compatible constructor for a file with no role deltas (the shape before role deltas existed). */
|
||||
public GrantFile(Map<String, Set<String>> roles, Map<String, Set<String>> permissions) {
|
||||
this(roles, permissions, Map.of(), Map.of());
|
||||
}
|
||||
|
||||
/** An empty grant store (an absent file). */
|
||||
public static GrantFile empty() {
|
||||
return new GrantFile(Map.of(), Map.of(), Map.of(), Map.of());
|
||||
}
|
||||
|
||||
/** The role names assigned to {@code principalId} in this scope. */
|
||||
public Set<String> rolesOf(String principalId) {
|
||||
return roles.getOrDefault(principalId, Set.of());
|
||||
}
|
||||
|
||||
/** The permission keys granted directly to {@code principalId} in this scope. */
|
||||
public Set<String> permissionsOf(String principalId) {
|
||||
return permissions.getOrDefault(principalId, Set.of());
|
||||
}
|
||||
|
||||
/** The permission keys added to {@code roleName} beyond its declared defaults. */
|
||||
public Set<String> roleGrantsOf(String roleName) {
|
||||
return roleGrants.getOrDefault(roleName, Set.of());
|
||||
}
|
||||
|
||||
/** The permission keys removed from {@code roleName} relative to its declared defaults. */
|
||||
public Set<String> roleRevokesOf(String roleName) {
|
||||
return roleRevokes.getOrDefault(roleName, Set.of());
|
||||
}
|
||||
|
||||
/** This file with {@code roleName} added to {@code principalId}'s role assignments. */
|
||||
public GrantFile withUserRole(String principalId, String roleName) {
|
||||
return new GrantFile(plus(roles, principalId, roleName), permissions, roleGrants, roleRevokes);
|
||||
}
|
||||
|
||||
/** This file with {@code roleName} removed from {@code principalId}'s role assignments. */
|
||||
public GrantFile withoutUserRole(String principalId, String roleName) {
|
||||
return new GrantFile(minus(roles, principalId, roleName), permissions, roleGrants, roleRevokes);
|
||||
}
|
||||
|
||||
/** This file with {@code permissionKey} added to {@code principalId}'s direct grants. */
|
||||
public GrantFile withUserPermission(String principalId, String permissionKey) {
|
||||
return new GrantFile(roles, plus(permissions, principalId, permissionKey), roleGrants, roleRevokes);
|
||||
}
|
||||
|
||||
/** This file with {@code permissionKey} removed from {@code principalId}'s direct grants. */
|
||||
public GrantFile withoutUserPermission(String principalId, String permissionKey) {
|
||||
return new GrantFile(roles, minus(permissions, principalId, permissionKey), roleGrants, roleRevokes);
|
||||
}
|
||||
|
||||
/** This file with {@code permissionKey} added to {@code roleName}'s grant delta. */
|
||||
public GrantFile withRoleGrant(String roleName, String permissionKey) {
|
||||
return new GrantFile(roles, permissions, plus(roleGrants, roleName, permissionKey), roleRevokes);
|
||||
}
|
||||
|
||||
/** This file with {@code permissionKey} removed from {@code roleName}'s grant delta. */
|
||||
public GrantFile withoutRoleGrant(String roleName, String permissionKey) {
|
||||
return new GrantFile(roles, permissions, minus(roleGrants, roleName, permissionKey), roleRevokes);
|
||||
}
|
||||
|
||||
/** This file with {@code permissionKey} added to {@code roleName}'s revoke delta. */
|
||||
public GrantFile withRoleRevoke(String roleName, String permissionKey) {
|
||||
return new GrantFile(roles, permissions, roleGrants, plus(roleRevokes, roleName, permissionKey));
|
||||
}
|
||||
|
||||
/** This file with {@code permissionKey} removed from {@code roleName}'s revoke delta. */
|
||||
public GrantFile withoutRoleRevoke(String roleName, String permissionKey) {
|
||||
return new GrantFile(roles, permissions, roleGrants, minus(roleRevokes, roleName, permissionKey));
|
||||
}
|
||||
|
||||
/**
|
||||
* This file with every trace of {@code roleName} removed: it is taken off every principal that held it, and its
|
||||
* grant and revoke deltas are dropped. Used when a custom role is deleted, so its holders lose what it gave them
|
||||
* and a role created later under the same name starts clean.
|
||||
*/
|
||||
public GrantFile withoutRole(String roleName) {
|
||||
Map<String, Set<String>> held = new java.util.LinkedHashMap<>();
|
||||
roles.forEach((principal, names) -> {
|
||||
Set<String> kept = new java.util.LinkedHashSet<>(names);
|
||||
kept.remove(roleName);
|
||||
if (!kept.isEmpty()) {
|
||||
held.put(principal, kept);
|
||||
}
|
||||
});
|
||||
Map<String, Set<String>> grants = new java.util.LinkedHashMap<>(roleGrants);
|
||||
grants.remove(roleName);
|
||||
Map<String, Set<String>> revokes = new java.util.LinkedHashMap<>(roleRevokes);
|
||||
revokes.remove(roleName);
|
||||
return new GrantFile(held, permissions, grants, revokes);
|
||||
}
|
||||
|
||||
private static Map<String, Set<String>> plus(Map<String, Set<String>> base, String key, String value) {
|
||||
Map<String, Set<String>> out = new java.util.LinkedHashMap<>(base);
|
||||
Set<String> values = new java.util.LinkedHashSet<>(out.getOrDefault(key, Set.of()));
|
||||
values.add(value);
|
||||
out.put(key, values);
|
||||
return out;
|
||||
}
|
||||
|
||||
private static Map<String, Set<String>> minus(Map<String, Set<String>> base, String key, String value) {
|
||||
if (!base.containsKey(key)) {
|
||||
return base;
|
||||
}
|
||||
Map<String, Set<String>> out = new java.util.LinkedHashMap<>(base);
|
||||
Set<String> values = new java.util.LinkedHashSet<>(out.get(key));
|
||||
values.remove(value);
|
||||
if (values.isEmpty()) {
|
||||
out.remove(key);
|
||||
} else {
|
||||
out.put(key, values);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static Map<String, Set<String>> copy(Map<String, Set<String>> raw) {
|
||||
if (raw == null || raw.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<String, Set<String>> out = new java.util.LinkedHashMap<>();
|
||||
raw.forEach((key, value) -> out.put(key, value == null ? Set.of() : Set.copyOf(value)));
|
||||
return Map.copyOf(out);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package mx.quest.runway.authz;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.UnaryOperator;
|
||||
import mx.quest.runway.event.KernelEventOrder;
|
||||
import mx.quest.runway.site.SiteChangedEvent;
|
||||
import mx.quest.runway.storage.StorageLayout;
|
||||
import mx.quest.runway.storage.StoreCache;
|
||||
import mx.quest.runway.storage.YamlStore;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Reads and writes the per-scope grant files (role assignments + direct permission grants): the
|
||||
* application-wide {@code external/app-grants.yml} and each tenancy's {@code sites/<id>/permissions.yml}.
|
||||
* Cached per scope; part of the trusted computing base (external root / inside the tenant folder, never
|
||||
* web-served). An absent file is an {@linkplain GrantFile#empty() empty} grant set.
|
||||
*
|
||||
* <h2>One scope, one lock: a change goes through {@link #updateAppGrants} / {@link #updateSiteGrants}</h2>
|
||||
* Every console change to a grant file is a read-modify-write (assign a role, grant a permission, a role delta). Run
|
||||
* as {@code save(get().withX(..))}, two administrators writing the same scope at the same moment each read the old
|
||||
* file, and the second write silently drops the first. The update methods read the latest file from disk, apply the
|
||||
* change and write it under that scope's lock, so both survive. A scope is the application realm or one site; two
|
||||
* sites never wait for each other.
|
||||
*/
|
||||
@Component
|
||||
public class GrantStore {
|
||||
|
||||
private static final String APP_FILE = "app-grants.yml";
|
||||
private static final String SITE_FILE = "permissions.yml";
|
||||
private static final String APP_SCOPE = "app";
|
||||
|
||||
private final StorageLayout layout;
|
||||
private final YamlStore yaml;
|
||||
private final StoreCache<String, GrantFile> cache = new StoreCache<>(512);
|
||||
/** One monitor per scope ({@link #APP_SCOPE} or {@code site|<id>}), held across each read-modify-write. */
|
||||
private final ConcurrentHashMap<String, Object> locks = new ConcurrentHashMap<>();
|
||||
|
||||
public GrantStore(StorageLayout layout, YamlStore yaml) {
|
||||
this.layout = Objects.requireNonNull(layout, "layout");
|
||||
this.yaml = Objects.requireNonNull(yaml, "yaml");
|
||||
}
|
||||
|
||||
/** The application-realm grants. */
|
||||
public GrantFile appGrants() {
|
||||
return cache.get(APP_SCOPE, key -> read(appFile()));
|
||||
}
|
||||
|
||||
/** A tenancy's grants. */
|
||||
public GrantFile siteGrants(String siteId) {
|
||||
return cache.get(siteScope(siteId), key -> read(siteFile(siteId)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the application grants wholesale and evicts the cache (seeding, tests). A change to the current grants
|
||||
* goes through {@link #updateAppGrants}, which cannot lose another writer's change.
|
||||
*/
|
||||
public void saveAppGrants(GrantFile grants) {
|
||||
synchronized (lock(APP_SCOPE)) {
|
||||
write(appFile(), grants);
|
||||
cache.invalidate(APP_SCOPE);
|
||||
}
|
||||
}
|
||||
|
||||
/** Replaces a tenancy's grants wholesale and evicts the cache; see {@link #saveAppGrants}. */
|
||||
public void saveSiteGrants(String siteId, GrantFile grants) {
|
||||
synchronized (lock(siteScope(siteId))) {
|
||||
write(siteFile(siteId), grants);
|
||||
cache.invalidate(siteScope(siteId));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically changes the application grants: {@code change} receives the latest grants, read from disk, and returns
|
||||
* the new ones, which are written before the scope's lock is released. If it throws, nothing is written. Keep it
|
||||
* pure and cheap: it runs under the lock.
|
||||
*
|
||||
* @return the grants now in force
|
||||
*/
|
||||
public GrantFile updateAppGrants(UnaryOperator<GrantFile> change) {
|
||||
return update(APP_SCOPE, appFile(), change);
|
||||
}
|
||||
|
||||
/** Atomically changes a tenancy's grants; see {@link #updateAppGrants}. */
|
||||
public GrantFile updateSiteGrants(String siteId, UnaryOperator<GrantFile> change) {
|
||||
return update(siteScope(siteId), siteFile(siteId), change);
|
||||
}
|
||||
|
||||
/**
|
||||
* The read-modify-write of one scope. It reads the file, not the cache: a cached copy loaded before another
|
||||
* writer's change could otherwise be the base of this one.
|
||||
*/
|
||||
private GrantFile update(String scope, Path file, UnaryOperator<GrantFile> change) {
|
||||
Objects.requireNonNull(change, "change");
|
||||
synchronized (lock(scope)) {
|
||||
GrantFile current = read(file);
|
||||
GrantFile next = Objects.requireNonNull(change.apply(current), "change result");
|
||||
if (!next.equals(current)) {
|
||||
write(file, next);
|
||||
}
|
||||
cache.invalidate(scope);
|
||||
return next;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The monitor of {@code scope}, shared with {@link AuthorizationAdminService} so that a change spanning the roles
|
||||
* file and the grants file of one scope (deleting a role) is one critical section.
|
||||
*/
|
||||
Object lock(String scope) {
|
||||
return locks.computeIfAbsent(scope, key -> new Object());
|
||||
}
|
||||
|
||||
/** The scope key of the application realm ({@code tenancyId == null}) or of a tenancy, for {@link #lock}. */
|
||||
static String scopeOf(String tenancyId) {
|
||||
return tenancyId == null ? APP_SCOPE : siteScope(tenancyId);
|
||||
}
|
||||
|
||||
/** Drops a tenancy's cached grants (call when its folder changes out of band). */
|
||||
public void evictSite(String siteId) {
|
||||
cache.invalidate(siteScope(siteId));
|
||||
}
|
||||
|
||||
/** A site delete/restore rewrites its {@code permissions.yml} wholesale — drop its cached grants. */
|
||||
@EventListener
|
||||
@Order(KernelEventOrder.STORES)
|
||||
public void onSiteChanged(SiteChangedEvent event) {
|
||||
if (event.isWholesaleReplacement()) {
|
||||
evictSite(event.siteId());
|
||||
}
|
||||
}
|
||||
|
||||
private GrantFile read(Path file) {
|
||||
try {
|
||||
return yaml.read(file, GrantFile.class).orElseGet(GrantFile::empty);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("reading grant file " + file, e);
|
||||
}
|
||||
}
|
||||
|
||||
private void write(Path file, GrantFile grants) {
|
||||
try {
|
||||
yaml.write(file, grants);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("writing grant file " + file, e);
|
||||
}
|
||||
}
|
||||
|
||||
private Path appFile() {
|
||||
return layout.external().resolve(APP_FILE);
|
||||
}
|
||||
|
||||
private Path siteFile(String siteId) {
|
||||
return layout.siteDir(siteId).resolve(SITE_FILE); // siteDir validates the id
|
||||
}
|
||||
|
||||
private static String siteScope(String siteId) {
|
||||
return "site|" + siteId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package mx.quest.runway.authz;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
|
||||
/**
|
||||
* Turns on Spring's annotation-driven method security so service and controller methods can carry
|
||||
* {@code @PreAuthorize("@authz.may('…')")} (via {@link AuthzExpressions}). This is the per-operation
|
||||
* enforcement layer that complements the request-gate {@link PermissionAuthorizationManager}: business
|
||||
* operations declare the permission they require right at the method, and the check routes through the same
|
||||
* {@link AuthorizationService#mayAccess} engine.
|
||||
*
|
||||
* <p>It runs <em>behind</em> the realm/tenancy-entry gates in the {@code SecurityFilterChain}s — those
|
||||
* establish that the caller legitimately belongs to the current realm and tenancy; this decides what, within
|
||||
* that scope, the caller may do.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableMethodSecurity
|
||||
public class MethodSecurityConfig {
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package mx.quest.runway.authz;
|
||||
|
||||
import java.util.Objects;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
|
||||
/**
|
||||
* A realm-tagged authorization permission — the unit a role or user is granted. Permissions are
|
||||
* <b>programmatic and declared</b> (by the core, and contributed by plugins), never
|
||||
* user-created; each belongs to exactly one {@link Realm} and is meaningless outside it (the core never
|
||||
* offers a tenant permission to an application surface, or vice versa).
|
||||
*
|
||||
* <p>The {@link #key()} is the stable, persisted identifier (e.g. {@code EDIT_PAGES}); it is the
|
||||
* forward-compatible contract with stored grants, so the catalog can evolve and the permission can move
|
||||
* or be renamed in code without rewriting data. Two permissions are equal iff their key <em>and</em>
|
||||
* realm match.
|
||||
*
|
||||
* <p><b>Host-internal since SPI 0.4.0.</b> It used to live in {@code mx.quest.runway.spi.model}, but no plugin ever
|
||||
* constructed or received one: plugins <em>declare</em> permissions in {@code plugin.yml} and <em>check</em> them by
|
||||
* key string ({@code @authz.may('<id>|<perm>')}). Keeping an unused record in the frozen contract would have
|
||||
* frozen a host data shape for nothing, so it moved here.
|
||||
*
|
||||
* @param key the stable permission key (never {@code null}/blank)
|
||||
* @param realm the realm this permission belongs to (never {@code null})
|
||||
*/
|
||||
public record Permission(String key, Realm realm) {
|
||||
|
||||
public Permission {
|
||||
if (key == null || key.isBlank()) {
|
||||
throw new IllegalArgumentException("permission key is blank");
|
||||
}
|
||||
Objects.requireNonNull(realm, "realm");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package mx.quest.runway.authz;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.Supplier;
|
||||
import mx.quest.runway.security.RunwayUserDetails;
|
||||
import mx.quest.runway.site.Site;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import org.springframework.security.authorization.AuthorizationDecision;
|
||||
import org.springframework.security.authorization.AuthorizationManager;
|
||||
import org.springframework.security.authorization.AuthorizationResult;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
|
||||
|
||||
/**
|
||||
* A request-gate {@link AuthorizationManager} that authorizes a matched request against one fixed
|
||||
* {@link Permission} via {@link AuthorizationService#mayAccess} — the {@code .access(...)} counterpart of the
|
||||
* {@code @authz.may(...)} method-security expression, sharing the same engine, precedence and tenancy
|
||||
* scoping. Build one with {@link RequestAuthorizers#requirePermission(Permission)} and attach it to a chain
|
||||
* matcher; compose it with the realm/tenancy-entry gate (e.g. {@code AuthorizationManagers.allOf(...)}) when a
|
||||
* path needs both "belongs to this tenancy" and "holds this permission".
|
||||
*
|
||||
* <p>Fail-closed: no/anonymous authentication or a non-{@link RunwayUserDetails} principal denies before the
|
||||
* engine is consulted. The tenancy is resolved from {@link SiteResolver#current()} for a tenant-realm
|
||||
* permission, or {@code null} for an application-realm one.
|
||||
*/
|
||||
public final class PermissionAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {
|
||||
|
||||
private final Permission permission;
|
||||
private final AuthorizationService authz;
|
||||
private final SiteResolver siteResolver;
|
||||
|
||||
PermissionAuthorizationManager(Permission permission, AuthorizationService authz, SiteResolver siteResolver) {
|
||||
this.permission = Objects.requireNonNull(permission, "permission");
|
||||
this.authz = Objects.requireNonNull(authz, "authz");
|
||||
this.siteResolver = Objects.requireNonNull(siteResolver, "siteResolver");
|
||||
}
|
||||
|
||||
@Override
|
||||
public AuthorizationResult authorize(Supplier<? extends Authentication> authentication,
|
||||
RequestAuthorizationContext context) {
|
||||
Authentication auth = authentication.get();
|
||||
if (auth == null || !auth.isAuthenticated() || !(auth.getPrincipal() instanceof RunwayUserDetails principal)) {
|
||||
return new AuthorizationDecision(false);
|
||||
}
|
||||
String tenancyId = permission.realm() == Realm.APPLICATION
|
||||
? null
|
||||
: siteResolver.current().map(Site::id).orElse(null);
|
||||
return new AuthorizationDecision(authz.mayAccess(principal, permission, tenancyId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package mx.quest.runway.authz;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* The declared permission registry — the single source of truth for "does this permission exist" and
|
||||
* "may it be granted". Authorization is <b>fail-closed</b> on this catalog: an unknown permission key is
|
||||
* undeclared, so a check for it can never pass (the access check denies it).
|
||||
*
|
||||
* <p>Every declared permission is either <b>grantable</b> (assignable to roles/users — a holder passes a
|
||||
* check via the effective-permission union) or <b>privileged</b> (master/wildcard-only: declared and
|
||||
* recognized, but never assignable, so only the master or a wildcard admin passes it). The two sets are
|
||||
* disjoint; their union is every declared permission.
|
||||
*
|
||||
* <p>Plugins contribute further <em>grantable</em> permissions (namespaced {@code <pluginId>.<id>}); the
|
||||
* {@code @Autowired} constructor seeds the core baseline then merges them through the same fail-fast
|
||||
* {@link #declare} guard, so a plugin permission colliding with a core key (or another plugin's) <b>fails
|
||||
* startup</b>. {@code mayAccess} and the bounded-grant admin service are untouched. Thread-safe and immutable
|
||||
* after construction.
|
||||
*/
|
||||
@Component
|
||||
public class PermissionCatalog {
|
||||
|
||||
private final Map<String, Permission> byKey = new LinkedHashMap<>();
|
||||
private final Set<Permission> grantable = new LinkedHashSet<>();
|
||||
private final Set<Permission> privileged = new LinkedHashSet<>();
|
||||
private final Map<String, Set<String>> defaultsByRole;
|
||||
|
||||
/** Kernel-baseline only (used by tests and as the no-plugin default). */
|
||||
public PermissionCatalog() {
|
||||
seedKernelBaseline();
|
||||
this.defaultsByRole = Map.of();
|
||||
}
|
||||
|
||||
/** Kernel baseline plus the grantable permissions plugins declared (merged with the same dup-key guard). */
|
||||
@Autowired
|
||||
public PermissionCatalog(PluginPermissionContributions pluginPermissions) {
|
||||
seedKernelBaseline();
|
||||
for (Permission permission : pluginPermissions.grantable()) {
|
||||
grant(permission); // declare() fails fast on a collision with a core or another plugin's key
|
||||
}
|
||||
this.defaultsByRole = pluginPermissions.defaultsByRole();
|
||||
}
|
||||
|
||||
/**
|
||||
* Role key → the grantable plugin-permission keys that default to it. The {@code mayAccess} fold grants
|
||||
* these to a role unless a scope's {@code roleRevokes} delta removes them. Empty for a bare
|
||||
* kernel (no plugin declares a default).
|
||||
*/
|
||||
public Set<String> defaultsForRole(String roleName) {
|
||||
return defaultsByRole.getOrDefault(roleName, Set.of());
|
||||
}
|
||||
|
||||
/** Every role key that has at least one plugin-permission default (for the permissions matrix). */
|
||||
public Set<String> rolesWithDefaults() {
|
||||
return Set.copyOf(defaultsByRole.keySet());
|
||||
}
|
||||
|
||||
private void seedKernelBaseline() {
|
||||
grant(Permissions.EDIT_PAGES, Permissions.DISABLE_PAGES, Permissions.CONFIGURE_SITE,
|
||||
Permissions.MAINTENANCE_MODE, Permissions.MANAGE_USERS, Permissions.DELETE_USERS,
|
||||
Permissions.MANAGE_DOCUMENTS, Permissions.MANAGE_BACKUPS, Permissions.APPROVE_PAGES,
|
||||
Permissions.VIEW_SITE_INSIGHTS,
|
||||
Permissions.VIEW_APP_DASHBOARD, Permissions.VIEW_TENANCIES, Permissions.MANAGE_STYLES,
|
||||
Permissions.MANAGE_SITE_HOSTS, Permissions.VIEW_BANDWIDTH, Permissions.VIEW_AUDIT);
|
||||
reserve(Permissions.MANAGE_TENANCIES, Permissions.MANAGE_TENANT_MASTERS, Permissions.MANAGE_APP_USERS,
|
||||
Permissions.CONFIGURE_PLATFORM, Permissions.MANAGE_PLUGINS, Permissions.MANAGE_PROTECTION);
|
||||
}
|
||||
|
||||
/** The declared permission for {@code key}, or empty when undeclared (a check for it fails closed). */
|
||||
public Optional<Permission> find(String key) {
|
||||
return Optional.ofNullable(byKey.get(key));
|
||||
}
|
||||
|
||||
/** Whether {@code key} names a declared permission. */
|
||||
public boolean isDeclared(String key) {
|
||||
return byKey.containsKey(key);
|
||||
}
|
||||
|
||||
/** Whether {@code permission} may be assigned to a role or user (false for master/wildcard-only ones). */
|
||||
public boolean isGrantable(Permission permission) {
|
||||
return grantable.contains(permission);
|
||||
}
|
||||
|
||||
/** The grantable permissions in {@code realm} — the assignable set an admin can hand out. */
|
||||
public Set<Permission> grantable(Realm realm) {
|
||||
Set<Permission> inRealm = new LinkedHashSet<>();
|
||||
for (Permission permission : grantable) {
|
||||
if (permission.realm() == realm) {
|
||||
inRealm.add(permission);
|
||||
}
|
||||
}
|
||||
return inRealm;
|
||||
}
|
||||
|
||||
/** Every declared permission (grantable + master/wildcard-only). */
|
||||
public Set<Permission> all() {
|
||||
return Set.copyOf(byKey.values());
|
||||
}
|
||||
|
||||
private void grant(Permission... permissions) {
|
||||
for (Permission permission : permissions) {
|
||||
declare(permission);
|
||||
grantable.add(permission);
|
||||
}
|
||||
}
|
||||
|
||||
private void reserve(Permission... permissions) {
|
||||
for (Permission permission : permissions) {
|
||||
declare(permission);
|
||||
privileged.add(permission);
|
||||
}
|
||||
}
|
||||
|
||||
private void declare(Permission permission) {
|
||||
if (byKey.putIfAbsent(permission.key(), permission) != null) {
|
||||
throw new IllegalStateException("duplicate permission key: " + permission.key());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package mx.quest.runway.authz;
|
||||
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
|
||||
/**
|
||||
* The core (kernel-declared) permission keys — the baseline catalog the {@link PermissionCatalog} seeds.
|
||||
* Each is realm-tagged. Two classes (see the catalog for the distinction):
|
||||
*
|
||||
* <ul>
|
||||
* <li><b>Grantable</b> — assignable to roles and users (the tenant baseline + the application
|
||||
* grantable set); a holder passes a {@code mayAccess} check for it via the effective-permission
|
||||
* union.</li>
|
||||
* <li><b>Master/wildcard-only</b> — declared (so they are auditable and recognized) but <b>never
|
||||
* grantable</b>: an ordinary user can never be assigned them, so only the master or a wildcard
|
||||
* admin passes them (via the access-precedence short-circuit, not the union). They name the
|
||||
* privileged platform operations.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Plugins add further grantable permissions (control points); this is only the kernel seed.
|
||||
*/
|
||||
public final class Permissions {
|
||||
|
||||
// --- TENANT realm — grantable baseline ---
|
||||
public static final Permission EDIT_PAGES = tenant("EDIT_PAGES");
|
||||
public static final Permission DISABLE_PAGES = tenant("DISABLE_PAGES");
|
||||
public static final Permission CONFIGURE_SITE = tenant("CONFIGURE_SITE");
|
||||
public static final Permission MAINTENANCE_MODE = tenant("MAINTENANCE_MODE");
|
||||
public static final Permission MANAGE_USERS = tenant("MANAGE_USERS");
|
||||
public static final Permission DELETE_USERS = tenant("DELETE_USERS");
|
||||
public static final Permission MANAGE_DOCUMENTS = tenant("MANAGE_DOCUMENTS");
|
||||
/** Create / download / delete the site's backups. Restore is a separate, master-only destructive action. */
|
||||
public static final Permission MANAGE_BACKUPS = tenant("MANAGE_BACKUPS");
|
||||
/** Reviewer permission gating draft→review→publish when a site opts into the editorial workflow. */
|
||||
public static final Permission APPROVE_PAGES = tenant("APPROVE_PAGES");
|
||||
/**
|
||||
* Read the site's insights report ({@code /__admin/insights}: top 404s and most-visited pages, aggregated from
|
||||
* the access log). Grantable but default-granted to no role — like the logs screen, only the site's master and
|
||||
* wildcard admins see it until someone delegates it. The report is an aggregate of paths and counts; it never
|
||||
* exposes a client IP, which is why it can be delegated where the raw logs cannot.
|
||||
*/
|
||||
public static final Permission VIEW_SITE_INSIGHTS = tenant("VIEW_SITE_INSIGHTS");
|
||||
|
||||
// --- APPLICATION realm — grantable ---
|
||||
public static final Permission VIEW_APP_DASHBOARD = app("VIEW_APP_DASHBOARD");
|
||||
public static final Permission VIEW_TENANCIES = app("VIEW_TENANCIES");
|
||||
public static final Permission MANAGE_STYLES = app("MANAGE_STYLES");
|
||||
/**
|
||||
* Edit a site's routing hosts (the {@link mx.quest.runway.site.Site#hosts} set) from the app Sites screen.
|
||||
* Grantable — so an operator can delegate host management to a role or user without handing over the
|
||||
* master-only tenancy lifecycle (create / suspend / delete stay {@link #MANAGE_TENANCIES}). A host change is
|
||||
* a routing edit only; it can never move data or cross tenant isolation.
|
||||
*/
|
||||
public static final Permission MANAGE_SITE_HOSTS = app("MANAGE_SITE_HOSTS");
|
||||
public static final Permission VIEW_BANDWIDTH = app("VIEW_BANDWIDTH");
|
||||
public static final Permission VIEW_AUDIT = app("VIEW_AUDIT");
|
||||
|
||||
// --- APPLICATION realm — master/wildcard-only (declared, NOT grantable) ---
|
||||
public static final Permission MANAGE_TENANCIES = app("MANAGE_TENANCIES");
|
||||
public static final Permission MANAGE_TENANT_MASTERS = app("MANAGE_TENANT_MASTERS");
|
||||
public static final Permission MANAGE_APP_USERS = app("MANAGE_APP_USERS");
|
||||
public static final Permission CONFIGURE_PLATFORM = app("CONFIGURE_PLATFORM");
|
||||
public static final Permission MANAGE_PLUGINS = app("MANAGE_PLUGINS");
|
||||
public static final Permission MANAGE_PROTECTION = app("MANAGE_PROTECTION");
|
||||
|
||||
private Permissions() {
|
||||
}
|
||||
|
||||
private static Permission tenant(String key) {
|
||||
return new Permission(key, Realm.TENANT);
|
||||
}
|
||||
|
||||
private static Permission app(String key) {
|
||||
return new Permission(key, Realm.APPLICATION);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package mx.quest.runway.authz;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.plugin.LoadedPlugin;
|
||||
import mx.quest.runway.plugin.PluginRuntime;
|
||||
import mx.quest.runway.security.Roles;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import mx.quest.runway.storage.PathSafety;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Extracts the grantable permissions a plugin declares from the loaded plugins, <b>namespaced</b>
|
||||
* by plugin id ({@code <pluginId>.<declId>}) so two plugins both declaring (say) {@code settings} never collide.
|
||||
* A plugin contributes <b>permissions, never roles</b>; {@code defaultRoles} are validated here: a
|
||||
* reserved master/wildcard-chain key is a <b>hard fail</b> (a plugin must not default a permission to an admin
|
||||
* tier), while an unknown or cross-realm role is ignored with a warning. The {@link PermissionCatalog} merges
|
||||
* the result; {@code mayAccess} and the bounded-grant admin service are untouched (they key off the catalog by
|
||||
* string), so a plugin permission lights up authorization for free.
|
||||
*/
|
||||
@Component
|
||||
public class PluginPermissionContributions {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(PluginPermissionContributions.class);
|
||||
|
||||
private final List<Permission> grantable;
|
||||
private final Map<String, Set<String>> defaultsByRole;
|
||||
|
||||
/** Spring entry point — reads the plugins the initializer loaded. */
|
||||
@Autowired
|
||||
public PluginPermissionContributions(ObjectProvider<PluginRuntime> runtimeProvider) {
|
||||
this(runtimeProvider.getIfAvailable(() -> PluginRuntime.empty(
|
||||
PluginPermissionContributions.class.getClassLoader())).loaded());
|
||||
}
|
||||
|
||||
/** Core logic over an explicit loaded-plugin list (testable without a Spring context). */
|
||||
public PluginPermissionContributions(List<LoadedPlugin> loaded) {
|
||||
List<Permission> permissions = new ArrayList<>();
|
||||
Map<String, Set<String>> defaults = new LinkedHashMap<>();
|
||||
for (LoadedPlugin plugin : loaded) {
|
||||
for (var decl : plugin.descriptor().permissions()) {
|
||||
// both parts are safe ids (validated in the descriptor), so the '|' separator — which a safe id
|
||||
// can never contain — makes <pluginId>|<declId> injective (no two plugins can collide on a key).
|
||||
String key = PathSafety.compoundKey(plugin.id(), decl.id());
|
||||
collectDefaultRoles(plugin.id(), key, decl.realm(), decl.defaultRoles(), defaults);
|
||||
permissions.add(new Permission(key, decl.realm()));
|
||||
}
|
||||
}
|
||||
this.grantable = List.copyOf(permissions);
|
||||
defaults.replaceAll((role, keys) -> Set.copyOf(keys));
|
||||
this.defaultsByRole = Map.copyOf(defaults);
|
||||
}
|
||||
|
||||
/** The namespaced, grantable plugin permissions to merge into the catalog. */
|
||||
public List<Permission> grantable() {
|
||||
return grantable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Role key → the plugin-permission keys that default to it ({@code defaultRoles}). The fold in
|
||||
* {@link AuthorizationService#effectivePermissionKeys} grants these to a role unless a tenancy's
|
||||
* {@code roleRevokes} delta removes them. Only <b>valid</b> defaults are captured (a reserved tier is a
|
||||
* hard error at construction; an unknown/cross-realm role is dropped) — so this never names an admin tier.
|
||||
*/
|
||||
public Map<String, Set<String>> defaultsByRole() {
|
||||
return defaultsByRole;
|
||||
}
|
||||
|
||||
private static void collectDefaultRoles(String pluginId, String key, Realm realm, List<String> defaultRoles,
|
||||
Map<String, Set<String>> into) {
|
||||
for (String role : defaultRoles) {
|
||||
if (ReservedRoles.isReserved(role)) {
|
||||
throw new IllegalStateException("plugin '" + pluginId + "' permission '" + key
|
||||
+ "' defaults to reserved role '" + role + "' — a plugin may not grant an admin tier");
|
||||
}
|
||||
if (isSeedRoleFor(role, realm)) {
|
||||
into.computeIfAbsent(role, k -> new LinkedHashSet<>()).add(key);
|
||||
} else {
|
||||
log.warn("plugin '{}' permission '{}' defaultRoles names unknown/cross-realm role '{}' — ignoring",
|
||||
pluginId, key, role);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isSeedRoleFor(String role, Realm realm) {
|
||||
return realm == Realm.APPLICATION ? Roles.SYSTEM_OPERATOR.equals(role) : Roles.OPERATOR.equals(role);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package mx.quest.runway.authz;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import mx.quest.runway.site.Site;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import mx.quest.runway.web.AppRealmPaths;
|
||||
import mx.quest.runway.web.RequestPaths;
|
||||
import mx.quest.runway.web.TenantConsolePaths;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
/**
|
||||
* Short-circuits the <b>tenant admin surface</b> ({@code /__admin/**}) of a site whose role store failed
|
||||
* startup validation (see {@link AuthzStoreIntegrity}) with {@code 503 Service Unavailable}. Runs just after
|
||||
* the site is bound. The quarantine is surgical on purpose: a corrupt {@code roles.yml} compromises only the
|
||||
* tenant's <em>authorization</em> surface, so the admin console must not be served (authorization cannot be
|
||||
* evaluated — fail-closed), but the site's <b>public, anonymous pages</b> (which never consult authorization)
|
||||
* keep serving. The application realm is likewise untouched, so an operator can still reach the platform
|
||||
* console to repair the tenancy.
|
||||
*/
|
||||
public class QuarantinedSiteFilter extends OncePerRequestFilter {
|
||||
|
||||
private final SiteResolver resolver;
|
||||
private final AuthzStoreIntegrity integrity;
|
||||
|
||||
public QuarantinedSiteFilter(SiteResolver resolver, AuthzStoreIntegrity integrity) {
|
||||
this.resolver = resolver;
|
||||
this.integrity = integrity;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||
FilterChain chain) throws ServletException, IOException {
|
||||
Site site = resolver.current().orElse(null);
|
||||
if (site != null && integrity.isQuarantined(site.id())
|
||||
&& RequestPaths.eitherMatches(request, QuarantinedSiteFilter::isTenantAdmin)) {
|
||||
response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
|
||||
response.setContentType("text/plain;charset=UTF-8");
|
||||
response.getOutputStream().write(
|
||||
"This site's administration is temporarily unavailable.".getBytes(StandardCharsets.UTF_8));
|
||||
return;
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Only the tenant admin surface is held; public pages (no authorization) and the app realm pass. A hold is a
|
||||
* protection, so it applies when either spelling of the path is the admin surface ({@link RequestPaths}): an
|
||||
* encoded {@code /%5F%5Fadmin} reaches the admin console's handlers just like {@code /__admin}.
|
||||
*/
|
||||
private static boolean isTenantAdmin(String path) {
|
||||
return AppRealmPaths.inNamespace(path, TenantConsolePaths.ADMIN_PREFIX);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package mx.quest.runway.authz;
|
||||
|
||||
import java.util.Objects;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Factory for {@code mayAccess}-backed request gates, injected into a {@code SecurityFilterChain} bean so a
|
||||
* matcher can require a concrete {@link Permission}: {@code .requestMatchers("/__app/styles/**")
|
||||
* .access(requestAuthorizers.requirePermission(Permissions.MANAGE_STYLES))}. Centralizing
|
||||
* construction keeps the {@link AuthorizationService} / {@link SiteResolver} wiring in one place so chains
|
||||
* stay declarative.
|
||||
*/
|
||||
@Component
|
||||
public class RequestAuthorizers {
|
||||
|
||||
private final AuthorizationService authz;
|
||||
private final SiteResolver siteResolver;
|
||||
|
||||
public RequestAuthorizers(AuthorizationService authz, SiteResolver siteResolver) {
|
||||
this.authz = Objects.requireNonNull(authz, "authz");
|
||||
this.siteResolver = Objects.requireNonNull(siteResolver, "siteResolver");
|
||||
}
|
||||
|
||||
/** A request gate that passes only when the current principal {@code mayAccess} {@code permission}. */
|
||||
public PermissionAuthorizationManager requirePermission(Permission permission) {
|
||||
return new PermissionAuthorizationManager(permission, authz, siteResolver);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package mx.quest.runway.authz;
|
||||
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.security.Roles;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
|
||||
/**
|
||||
* The sealed reserved chain — the master and wildcard role keys, per realm. These are <b>code-defined</b>:
|
||||
* the master and wildcard tiers are recognized here, never read from a role file, so a hand-edit
|
||||
* can never invent or relocate them. A custom role may not bear a reserved key, nor inherit one (the seal,
|
||||
* enforced by {@link RoleGraph} on construction).
|
||||
*
|
||||
* <ul>
|
||||
* <li><b>Master</b> ({@code SYSTEMSUPERADMIN} / {@code SUPERADMIN}) — the immutable hierarchy top; the
|
||||
* authoritative master is the pinned principal id, the role key is only a label.</li>
|
||||
* <li><b>Wildcard</b> ({@code SYSTEMADMIN} / {@code ADMIN}) — full access except master-only operations;
|
||||
* the wildcard is derived from holding this key, never from a writable flag.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>The seed operator roles ({@code SYSTEMOPERATOR} / {@code OPERATOR}) are <b>not</b> reserved — they are
|
||||
* ordinary, editable roles that happen to be seeded.
|
||||
*/
|
||||
public final class ReservedRoles {
|
||||
|
||||
private static final Set<String> MASTER_KEYS = Set.of(Roles.SYSTEM_SUPERADMIN, Roles.SUPERADMIN);
|
||||
private static final Set<String> WILDCARD_KEYS = Set.of(Roles.SYSTEM_ADMIN, Roles.ADMIN);
|
||||
|
||||
private ReservedRoles() {
|
||||
}
|
||||
|
||||
/** Whether {@code roleName} is a reserved key (master or wildcard) — sealed from the custom-role graph. */
|
||||
public static boolean isReserved(String roleName) {
|
||||
return MASTER_KEYS.contains(roleName) || WILDCARD_KEYS.contains(roleName);
|
||||
}
|
||||
|
||||
/** Whether {@code roleName} is a wildcard key (full access except master-only). */
|
||||
public static boolean isWildcard(String roleName) {
|
||||
return WILDCARD_KEYS.contains(roleName);
|
||||
}
|
||||
|
||||
/** Whether {@code roleName} is a master key (the hierarchy top). */
|
||||
public static boolean isMaster(String roleName) {
|
||||
return MASTER_KEYS.contains(roleName);
|
||||
}
|
||||
|
||||
/** The wildcard key for {@code realm} ({@code SYSTEMADMIN} for application, {@code ADMIN} for tenant). */
|
||||
public static String wildcardKey(Realm realm) {
|
||||
return realm == Realm.APPLICATION ? Roles.SYSTEM_ADMIN : Roles.ADMIN;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code roleName} is a reserved key <b>of {@code realm}</b>. The reserved keys are realm-specific
|
||||
* ({@code SYSTEM*} for application, the plain forms for tenant), but {@link #isReserved}/{@link #isWildcard}
|
||||
* are realm-agnostic — so an assignment path must use this to reject the <em>other</em> realm's reserved key
|
||||
* (a tenant admin must not write {@code SYSTEMADMIN} into a tenant grant store, and vice versa).
|
||||
*/
|
||||
public static boolean isReservedOfRealm(String roleName, Realm realm) {
|
||||
return realm == Realm.APPLICATION
|
||||
? Roles.SYSTEM_SUPERADMIN.equals(roleName) || Roles.SYSTEM_ADMIN.equals(roleName)
|
||||
: Roles.SUPERADMIN.equals(roleName) || Roles.ADMIN.equals(roleName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package mx.quest.runway.authz;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
|
||||
/**
|
||||
* A custom role: a named bundle of granted permission keys plus a position in the role DAG. A role
|
||||
* {@link #inherits} the roles directly <b>beneath</b> it, so its effective permissions are its own plus
|
||||
* the transitive downward union of everything it inherits (computed by {@link RoleGraph}).
|
||||
*
|
||||
* <p>Roles live in the per-realm role files ({@code app-roles.yml}, {@code sites/<id>/roles.yml}); the
|
||||
* <b>reserved chain</b> (master > wildcard) is code-defined and never stored here — a custom role may
|
||||
* neither be named a {@linkplain ReservedRoles reserved key} nor inherit one (the seal, enforced by
|
||||
* {@link RoleGraph}). Permissions and inherited names are stored as <b>keys/names</b> (the
|
||||
* forward-compatible contract with the data); an undeclared permission key simply grants nothing.
|
||||
*
|
||||
* @param name the role's unique name within its realm/scope (never blank)
|
||||
* @param realm the realm this role belongs to (never {@code null})
|
||||
* @param permissions the permission keys granted directly by this role (copied, unmodifiable)
|
||||
* @param inherits the names of the roles directly beneath this one (copied, unmodifiable)
|
||||
*/
|
||||
public record Role(String name, Realm realm, Set<String> permissions, Set<String> inherits) {
|
||||
|
||||
public Role {
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new IllegalArgumentException("role name is blank");
|
||||
}
|
||||
name = name.trim();
|
||||
Objects.requireNonNull(realm, "realm");
|
||||
permissions = (permissions == null) ? Set.of() : Set.copyOf(permissions);
|
||||
inherits = (inherits == null) ? Set.of() : Set.copyOf(inherits);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package mx.quest.runway.authz;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The on-disk shape of a role store — a {@code roles:} list. A single top-level record (not a bare list)
|
||||
* keeps the YAML forward-compatible.
|
||||
*
|
||||
* @param roles the roles in this scope (copied, unmodifiable; {@code null} → empty)
|
||||
*/
|
||||
public record RoleFile(List<Role> roles) {
|
||||
|
||||
public RoleFile {
|
||||
roles = (roles == null) ? List.of() : List.copyOf(roles);
|
||||
}
|
||||
|
||||
/** An empty store (an absent file). */
|
||||
public static RoleFile empty() {
|
||||
return new RoleFile(List.of());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package mx.quest.runway.authz;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* An immutable, validated view of one realm/scope's custom-role DAG, with the effective-permission
|
||||
* resolver. Built (and validated) by {@link #of(Collection)}; a graph object is only ever a <em>valid</em>
|
||||
* graph — construction <b>fails closed</b> on any violation rather than silently dropping an edge:
|
||||
*
|
||||
* <ul>
|
||||
* <li>a duplicate role name;</li>
|
||||
* <li>the <b>seal</b>: a role named a {@linkplain ReservedRoles reserved key}, or inheriting one;</li>
|
||||
* <li>a role inheriting a role that does not exist; or</li>
|
||||
* <li>a cycle.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>{@link #effectivePermissionKeys(String)} returns a role's own permission keys plus the transitive
|
||||
* downward union of every role it inherits (parent accumulates descendants). The per-role closure is the
|
||||
* only thing cached. Thread-safe after construction.
|
||||
*/
|
||||
public final class RoleGraph {
|
||||
|
||||
private final Map<String, Role> byName;
|
||||
private final Map<String, Set<String>> closureCache = new HashMap<>();
|
||||
|
||||
private RoleGraph(Map<String, Role> byName) {
|
||||
this.byName = byName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds and validates the graph for {@code roles}.
|
||||
*
|
||||
* @throws IllegalStateException on a duplicate name, a seal violation, an unknown inherited role, or a cycle
|
||||
*/
|
||||
public static RoleGraph of(Collection<Role> roles) {
|
||||
Map<String, Role> byName = new LinkedHashMap<>();
|
||||
for (Role role : roles) {
|
||||
if (ReservedRoles.isReserved(role.name())) {
|
||||
throw new IllegalStateException("a custom role may not bear the reserved key '" + role.name() + "'");
|
||||
}
|
||||
if (byName.putIfAbsent(role.name(), role) != null) {
|
||||
throw new IllegalStateException("duplicate role name: " + role.name());
|
||||
}
|
||||
}
|
||||
for (Role role : byName.values()) {
|
||||
for (String inherited : role.inherits()) {
|
||||
if (ReservedRoles.isReserved(inherited)) {
|
||||
throw new IllegalStateException("role '" + role.name() + "' may not inherit the reserved key '" + inherited + "'");
|
||||
}
|
||||
if (!byName.containsKey(inherited)) {
|
||||
throw new IllegalStateException("role '" + role.name() + "' inherits unknown role '" + inherited + "'");
|
||||
}
|
||||
}
|
||||
}
|
||||
RoleGraph graph = new RoleGraph(byName);
|
||||
graph.requireAcyclic();
|
||||
return graph;
|
||||
}
|
||||
|
||||
/** A role's effective permission keys: its own plus the transitive downward union of what it inherits. */
|
||||
public Set<String> effectivePermissionKeys(String roleName) {
|
||||
if (!byName.containsKey(roleName)) {
|
||||
return Set.of(); // an unknown role grants nothing
|
||||
}
|
||||
return closureCache.computeIfAbsent(roleName, name -> {
|
||||
Set<String> keys = new HashSet<>();
|
||||
accumulate(name, keys, new HashSet<>());
|
||||
return Set.copyOf(keys);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The role-name closure of {@code roleName}: itself plus every role it transitively inherits. A name not in
|
||||
* the custom graph (e.g. a predefined seed role like {@code OPERATOR}) closes to <b>just itself</b>, so it
|
||||
* still participates in the plugin-permission-default fold ({@link AuthorizationService}). The dual of
|
||||
* {@link #effectivePermissionKeys} at the role level.
|
||||
*/
|
||||
public Set<String> effectiveRoleNames(String roleName) {
|
||||
if (!byName.containsKey(roleName)) {
|
||||
return Set.of(roleName);
|
||||
}
|
||||
Set<String> names = new HashSet<>();
|
||||
accumulateNames(roleName, names);
|
||||
return Set.copyOf(names);
|
||||
}
|
||||
|
||||
private void accumulateNames(String roleName, Set<String> names) {
|
||||
if (!names.add(roleName)) {
|
||||
return;
|
||||
}
|
||||
Role role = byName.get(roleName);
|
||||
if (role != null) {
|
||||
for (String inherited : role.inherits()) {
|
||||
accumulateNames(inherited, names);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The permission keys stored on {@code roleName} itself (its {@code permissions} in the roles file), without
|
||||
* what it inherits; empty for a name not in the graph. The authorization fold applies the role's revokes to
|
||||
* these per role, so a key typed into the file can be revoked from the console like any other.
|
||||
*/
|
||||
public Set<String> ownPermissionKeys(String roleName) {
|
||||
Role role = byName.get(roleName);
|
||||
return role == null ? Set.of() : Set.copyOf(role.permissions());
|
||||
}
|
||||
|
||||
/** Whether a role with this name exists in the graph. */
|
||||
public boolean hasRole(String name) {
|
||||
return byName.containsKey(name);
|
||||
}
|
||||
|
||||
/** Every role name in the graph. */
|
||||
public Set<String> roleNames() {
|
||||
return Set.copyOf(byName.keySet());
|
||||
}
|
||||
|
||||
private void accumulate(String roleName, Set<String> keys, Set<String> seen) {
|
||||
if (!seen.add(roleName)) {
|
||||
return;
|
||||
}
|
||||
Role role = byName.get(roleName);
|
||||
if (role == null) {
|
||||
return;
|
||||
}
|
||||
keys.addAll(role.permissions());
|
||||
for (String inherited : role.inherits()) {
|
||||
accumulate(inherited, keys, seen);
|
||||
}
|
||||
}
|
||||
|
||||
private void requireAcyclic() {
|
||||
Set<String> visited = new HashSet<>();
|
||||
Set<String> onStack = new HashSet<>();
|
||||
for (String name : byName.keySet()) {
|
||||
if (hasCycle(name, visited, onStack)) {
|
||||
throw new IllegalStateException("role hierarchy has a cycle through '" + name + "'");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasCycle(String name, Set<String> visited, Set<String> onStack) {
|
||||
if (onStack.contains(name)) {
|
||||
return true;
|
||||
}
|
||||
if (!visited.add(name)) {
|
||||
return false;
|
||||
}
|
||||
onStack.add(name);
|
||||
for (String inherited : byName.get(name).inherits()) {
|
||||
if (hasCycle(inherited, visited, onStack)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
onStack.remove(name);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package mx.quest.runway.authz;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import mx.quest.runway.event.KernelEventOrder;
|
||||
import mx.quest.runway.site.SiteChangedEvent;
|
||||
import mx.quest.runway.storage.StorageLayout;
|
||||
import mx.quest.runway.storage.StoreCache;
|
||||
import mx.quest.runway.storage.YamlStore;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Reads and writes the per-realm role files and exposes them as validated {@link RoleGraph}s:
|
||||
* {@code external/app-roles.yml} (the platform-wide application roles) and {@code sites/<id>/roles.yml}
|
||||
* (each tenancy's own roles, which travel in its backup and are invisible across tenancies). The graph is
|
||||
* cached per scope and rebuilt on save.
|
||||
*
|
||||
* <p>Loading a graph is <b>fail-closed</b>: {@link RoleGraph#of} validates the file (seal, missing refs,
|
||||
* cycles) and throws on any violation, so an invalid file cannot produce a usable graph. The store is part
|
||||
* of the trusted computing base — these files live under the external root / inside the tenant folder,
|
||||
* never under a web-served path.
|
||||
*/
|
||||
@Component
|
||||
public class RoleStore {
|
||||
|
||||
private static final String APP_FILE = "app-roles.yml";
|
||||
private static final String SITE_FILE = "roles.yml";
|
||||
private static final String APP_SCOPE = "app";
|
||||
|
||||
private final StorageLayout layout;
|
||||
private final YamlStore yaml;
|
||||
private final StoreCache<String, RoleGraph> graphs = new StoreCache<>(512);
|
||||
|
||||
public RoleStore(StorageLayout layout, YamlStore yaml) {
|
||||
this.layout = Objects.requireNonNull(layout, "layout");
|
||||
this.yaml = Objects.requireNonNull(yaml, "yaml");
|
||||
}
|
||||
|
||||
/** The application-realm role graph (validated; throws if the file is invalid). */
|
||||
public RoleGraph appRoles() {
|
||||
return graphs.get(APP_SCOPE, key -> RoleGraph.of(read(appFile())));
|
||||
}
|
||||
|
||||
/** The tenancy's role graph (validated; throws if the file is invalid or the id is unsafe). */
|
||||
public RoleGraph siteRoles(String siteId) {
|
||||
return graphs.get(siteScope(siteId), key -> RoleGraph.of(read(siteFile(siteId))));
|
||||
}
|
||||
|
||||
/** The raw application role list (for editing — the admin service reads, mutates, and re-saves it). */
|
||||
public List<Role> appRoleList() {
|
||||
return read(appFile());
|
||||
}
|
||||
|
||||
/** The raw role list for a tenancy (for editing). */
|
||||
public List<Role> siteRoleList(String siteId) {
|
||||
return read(siteFile(siteId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically replaces the application roles and rebuilds the cached graph. Validates first (rejected
|
||||
* on save as well as on load), so an invalid graph is never persisted.
|
||||
*
|
||||
* @throws IllegalStateException if the roles form an invalid graph (seal, missing ref, cycle)
|
||||
*/
|
||||
public void saveAppRoles(List<Role> roles) {
|
||||
RoleGraph.of(roles); // validate before persisting
|
||||
write(appFile(), roles);
|
||||
graphs.invalidate(APP_SCOPE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically replaces a tenancy's roles and rebuilds the cached graph (validated first).
|
||||
*
|
||||
* @throws IllegalStateException if the roles form an invalid graph
|
||||
*/
|
||||
public void saveSiteRoles(String siteId, List<Role> roles) {
|
||||
RoleGraph.of(roles); // validate before persisting
|
||||
write(siteFile(siteId), roles);
|
||||
graphs.invalidate(siteScope(siteId));
|
||||
}
|
||||
|
||||
/** Drops a tenancy's cached graph (call when its folder changes out of band). */
|
||||
public void evictSite(String siteId) {
|
||||
graphs.invalidate(siteScope(siteId));
|
||||
}
|
||||
|
||||
/** A site delete/restore rewrites its {@code roles.yml} wholesale — drop its cached role graph. */
|
||||
@EventListener
|
||||
@Order(KernelEventOrder.STORES)
|
||||
public void onSiteChanged(SiteChangedEvent event) {
|
||||
if (event.isWholesaleReplacement()) {
|
||||
evictSite(event.siteId());
|
||||
}
|
||||
}
|
||||
|
||||
private List<Role> read(Path file) {
|
||||
try {
|
||||
return yaml.read(file, RoleFile.class).orElseGet(RoleFile::empty).roles();
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("reading role file " + file, e);
|
||||
}
|
||||
}
|
||||
|
||||
private void write(Path file, List<Role> roles) {
|
||||
try {
|
||||
yaml.write(file, new RoleFile(roles));
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("writing role file " + file, e);
|
||||
}
|
||||
}
|
||||
|
||||
private Path appFile() {
|
||||
return layout.external().resolve(APP_FILE);
|
||||
}
|
||||
|
||||
private Path siteFile(String siteId) {
|
||||
return layout.siteDir(siteId).resolve(SITE_FILE); // siteDir validates the id
|
||||
}
|
||||
|
||||
private static String siteScope(String siteId) {
|
||||
return "site|" + siteId; // printable separator
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package mx.quest.runway.backup;
|
||||
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Enables {@link BackupProperties} so {@link BackupService} can apply the stored-backup retention policy.
|
||||
* {@link BackupService} itself is a {@code @Service}; this only publishes the bound properties bean.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableConfigurationProperties(BackupProperties.class)
|
||||
public class BackupConfig {
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package mx.quest.runway.backup;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The {@code manifest.yml} at the root of a site backup: what it is and what it contains. It travels with the
|
||||
* archive so a restore can identify the snapshot and know which {@link mx.quest.runway.spi.BackupParticipant}s
|
||||
* contributed data (a participant absent at restore time is tolerated — its data simply stays unrestored).
|
||||
*
|
||||
* @param siteId the site the backup was taken from (informational — a restore targets the current site)
|
||||
* @param spiVersion the SPI contract version at backup time (diagnostic only — restore never branches on it;
|
||||
* {@code formatVersion} is the field a restore checks)
|
||||
* @param createdAt ISO-8601 instant the backup was created
|
||||
* @param participants the participant keys whose data is present under {@code plugin-data/<key>/}
|
||||
* @param purpose {@code RESTORE} (complete) or {@code TRANSFER} (credentials, accounts and origin
|
||||
* hostnames removed) — see {@link BackupService.BackupPurpose}. Absent in archives
|
||||
* written before the distinction existed, which are always complete, so it reads as
|
||||
* {@code RESTORE}: an unmarked archive must never be mistaken for a sanitised one.
|
||||
* @param formatVersion the version of the archive <b>format</b> (entry layout + manifest shape). Absent in every
|
||||
* archive written before the field existed, which are all format {@code 1}, so it reads as
|
||||
* {@code 1}. A restore accepts any version up to {@link #SUPPORTED_FORMAT_VERSION} and refuses
|
||||
* a higher one ({@link UnsupportedBackupFormatException}) — an archive from a newer Runway
|
||||
* may hold data this build would silently drop. See
|
||||
* {@code docs/CONFIGURATION-AND-DATA-STABILITY.md}.
|
||||
* @param omitted what a {@code TRANSFER} copy deliberately left out as plugin personal data (SPI 0.5.0): each
|
||||
* declared {@code siteData.personal} path (for example {@code plugins/search/no-results.tsv};
|
||||
* a folder ends in {@code /}) and {@code plugins/<id>/} for each plugin that was not loaded.
|
||||
* Empty for a complete backup and in archives written before the key existed. An additive key:
|
||||
* older readers ignore it, so the format version is unchanged.
|
||||
*/
|
||||
public record BackupManifest(String siteId, String spiVersion, String createdAt, List<String> participants,
|
||||
String purpose, Integer formatVersion, List<String> omitted) {
|
||||
|
||||
/**
|
||||
* The archive format this build writes and the highest it restores. Raised only for a change an older reader
|
||||
* would misread (a new mandatory entry, a moved tree) — never for an additive manifest key, which older
|
||||
* readers ignore.
|
||||
*/
|
||||
public static final int SUPPORTED_FORMAT_VERSION = 1;
|
||||
|
||||
public BackupManifest {
|
||||
participants = participants == null ? List.of() : List.copyOf(participants);
|
||||
purpose = (purpose == null || purpose.isBlank())
|
||||
? BackupService.BackupPurpose.RESTORE.name() : purpose.trim();
|
||||
formatVersion = formatVersion == null ? 1 : formatVersion;
|
||||
omitted = omitted == null ? List.of() : List.copyOf(omitted);
|
||||
}
|
||||
|
||||
/** The pre-{@code omitted} 6-arg form: nothing omitted. */
|
||||
public BackupManifest(String siteId, String spiVersion, String createdAt, List<String> participants,
|
||||
String purpose, Integer formatVersion) {
|
||||
this(siteId, spiVersion, createdAt, participants, purpose, formatVersion, null);
|
||||
}
|
||||
|
||||
/** The pre-{@code formatVersion} 5-arg form: reads as format {@code 1}, like the archives written with it. */
|
||||
public BackupManifest(String siteId, String spiVersion, String createdAt, List<String> participants,
|
||||
String purpose) {
|
||||
this(siteId, spiVersion, createdAt, participants, purpose, null);
|
||||
}
|
||||
|
||||
/** The pre-{@code purpose} 4-arg form, kept so older call sites keep compiling as complete backups. */
|
||||
public BackupManifest(String siteId, String spiVersion, String createdAt, List<String> participants) {
|
||||
this(siteId, spiVersion, createdAt, participants, BackupService.BackupPurpose.RESTORE.name());
|
||||
}
|
||||
|
||||
/** Whether this archive was produced for handing to someone else, and so is deliberately incomplete. */
|
||||
public boolean isTransfer() {
|
||||
return BackupService.BackupPurpose.TRANSFER.name().equals(purpose);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package mx.quest.runway.backup;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import mx.quest.runway.plugin.ContributionGuard;
|
||||
import mx.quest.runway.spi.BackupParticipant;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Collects every {@link BackupParticipant} bean — core and plugin alike — indexed by its stable archive-namespace
|
||||
* {@code key()}, so a backup writes/reads each participant's slice under a collision-free namespace. A blank or
|
||||
* duplicate key among kernel participants fails startup; a plugin participant that collides or has a blank key is
|
||||
* refused and its plugin marked degraded. {@link BackupService} drives the participants: an
|
||||
* {@code export} failure fails the backup, an {@code importInto} failure is contained under {@link #guard()}.
|
||||
* Thread-safe and immutable.
|
||||
*/
|
||||
@Component
|
||||
public class BackupParticipantRegistry {
|
||||
|
||||
private final Map<String, BackupParticipant> byKey;
|
||||
private final ContributionGuard guard;
|
||||
|
||||
/** Unit-test form: every participant counts as kernel code, so a collision fails fast. */
|
||||
public BackupParticipantRegistry(List<BackupParticipant> participants) {
|
||||
this(participants, ContributionGuard.standalone());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param participants every {@link BackupParticipant} bean Spring discovered (possibly empty)
|
||||
* @param guard the plugin-contribution containment policy
|
||||
* @throws IllegalStateException if a <b>kernel</b> participant has a blank key or two kernel participants
|
||||
* share one
|
||||
*/
|
||||
@Autowired
|
||||
public BackupParticipantRegistry(List<BackupParticipant> participants, ContributionGuard guard) {
|
||||
List<BackupParticipant> ordered = new java.util.ArrayList<>(participants);
|
||||
AnnotationAwareOrderComparator.sort(ordered);
|
||||
this.guard = guard;
|
||||
this.byKey = Collections.unmodifiableMap(guard.index("BackupParticipant", ordered, BackupParticipant::key));
|
||||
}
|
||||
|
||||
/** The containment policy the restore path wraps {@code importInto} with. */
|
||||
public ContributionGuard guard() {
|
||||
return guard;
|
||||
}
|
||||
|
||||
/** Every registered participant, in order. */
|
||||
public Collection<BackupParticipant> all() {
|
||||
return byKey.values();
|
||||
}
|
||||
|
||||
/** The participant for an archive-namespace key, if any. */
|
||||
public Optional<BackupParticipant> find(String key) {
|
||||
return Optional.ofNullable(byKey.get(key));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package mx.quest.runway.backup;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.context.properties.NestedConfigurationProperty;
|
||||
|
||||
/**
|
||||
* Platform-level backup settings ({@code runway.backups.*}) — app-level, not tenant-editable (a
|
||||
* tenant-settable retention would let a tenant hoard disk or silently discard its own restore points).
|
||||
*
|
||||
* <p>This carries the {@link Retention} policy that auto-prunes stored backups after each new one is
|
||||
* written (so a site's {@code backups/<id>/} folder does not grow without bound), and the per-entry
|
||||
* decompression cap that defuses a zip-bomb archive on restore.
|
||||
*/
|
||||
@ConfigurationProperties("runway.backups")
|
||||
public class BackupProperties {
|
||||
|
||||
@NestedConfigurationProperty
|
||||
private final Retention retention = new Retention();
|
||||
|
||||
@NestedConfigurationProperty
|
||||
private final Schedule schedule = new Schedule();
|
||||
|
||||
/**
|
||||
* An optional <b>off-host</b> directory into which every newly-created stored backup is mirrored (organised
|
||||
* as {@code <offsite-dir>/<siteId>/<name>.zip}), so a copy survives loss of the deployment host. Point it at
|
||||
* a mounted remote share (NFS/SMB/rclone-mount) or a second disk. Blank (the default) disables mirroring —
|
||||
* backups then live only under the deployment-root {@code backups/}. The mirror is <b>best-effort</b>: if the
|
||||
* target is unwritable (share unmounted), the local backup still succeeds and a warning is logged. Off-host
|
||||
* copies are pruned by the same {@link Retention} policy as local ones.
|
||||
*/
|
||||
private String offsiteDir = "";
|
||||
|
||||
/** The default per-entry decompression cap when none (or a non-positive value) is configured: 256 MiB. */
|
||||
public static final long DEFAULT_MAX_ENTRY_BYTES = 256L * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* The maximum decompressed size of any <em>single</em> entry accepted while restoring (or cloning
|
||||
* from) a backup archive — the guard against a decompression bomb (a tiny, highly-compressible entry
|
||||
* that inflates to gigabytes) exhausting the heap or the staging disk. It bounds one entry, not the
|
||||
* whole archive, so a legitimate backup of many files is unaffected; only a pathologically large
|
||||
* single file trips it. Default: 256 MiB, generous for a real site asset (image/document/upload)
|
||||
* while still capping a bomb. Raise it if a site legitimately stores larger single files. A
|
||||
* <b>non-positive</b> value is treated as "unset" and falls back to {@link #DEFAULT_MAX_ENTRY_BYTES}
|
||||
* (a {@code 0} cap would otherwise reject every entry and break all restores).
|
||||
*/
|
||||
private long maxEntryBytes = DEFAULT_MAX_ENTRY_BYTES;
|
||||
|
||||
public Retention getRetention() {
|
||||
return retention;
|
||||
}
|
||||
|
||||
public Schedule getSchedule() {
|
||||
return schedule;
|
||||
}
|
||||
|
||||
public String getOffsiteDir() {
|
||||
return offsiteDir;
|
||||
}
|
||||
|
||||
public void setOffsiteDir(String offsiteDir) {
|
||||
this.offsiteDir = offsiteDir;
|
||||
}
|
||||
|
||||
public long getMaxEntryBytes() {
|
||||
return maxEntryBytes;
|
||||
}
|
||||
|
||||
public void setMaxEntryBytes(long maxEntryBytes) {
|
||||
this.maxEntryBytes = maxEntryBytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotation policy for the stored backups of a single site. Both limits apply independently and are
|
||||
* ANDed: a stored backup is pruned when it falls outside the newest {@code maxCount} <em>or</em> is
|
||||
* older than {@code maxAgeDays}. Either limit set to {@code 0} disables that dimension.
|
||||
*
|
||||
* <p>Pruning only ever removes a site's <em>own</em> stored backups (never another site's, never the
|
||||
* live site data). It runs after a successful {@code create}, so an explicit/manual backup is always
|
||||
* retained and the newest is never a pruning victim.
|
||||
*/
|
||||
public static class Retention {
|
||||
|
||||
/** Keep at most this many stored backups per site (newest kept); {@code 0} = unlimited. Default: 30. */
|
||||
private int maxCount = 30;
|
||||
|
||||
/** Prune stored backups older than this many days; {@code 0} = no age limit. Default: 0 (off). */
|
||||
private int maxAgeDays = 0;
|
||||
|
||||
public int getMaxCount() {
|
||||
return maxCount;
|
||||
}
|
||||
|
||||
public void setMaxCount(int maxCount) {
|
||||
this.maxCount = maxCount;
|
||||
}
|
||||
|
||||
public int getMaxAgeDays() {
|
||||
return maxAgeDays;
|
||||
}
|
||||
|
||||
public void setMaxAgeDays(int maxAgeDays) {
|
||||
this.maxAgeDays = maxAgeDays;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Automatic-backup schedule. When {@code enabled}, a scheduled task backs up <b>every</b> site on the
|
||||
* {@code cron} expression, each isolated so one site's failure does not stop the rest; the retention policy
|
||||
* then prunes as usual (and off-host mirroring applies if configured). Default OFF — automatic backups are
|
||||
* opt-in; a manual backup from the console is always available regardless.
|
||||
*/
|
||||
public static class Schedule {
|
||||
|
||||
/** Whether the scheduled all-sites backup runs. Default: {@code false} (opt-in). */
|
||||
private boolean enabled = false;
|
||||
|
||||
/**
|
||||
* The Spring cron expression (6 fields: {@code sec min hour day month weekday}) for the run. Default:
|
||||
* {@code 0 30 2 * * *} — 02:30 every day, a quiet hour. Only consulted when {@link #enabled}.
|
||||
*/
|
||||
private String cron = "0 30 2 * * *";
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public String getCron() {
|
||||
return cron;
|
||||
}
|
||||
|
||||
public void setCron(String cron) {
|
||||
this.cron = cron;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package mx.quest.runway.backup;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
import mx.quest.runway.storage.StorageLayout;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Recovers from a restore interrupted mid-swap (a crash / power loss between {@code siteDir → old} and
|
||||
* {@code staging → siteDir}). At that instant the live site is momentarily absent while its only copy sits in
|
||||
* {@code sites/.restore-work/<id>/old}; on the next boot this sweep <b>rolls the interrupted rollback
|
||||
* forward</b> — for any work dir whose site is missing, it moves {@code old} back into place — then clears the
|
||||
* leftover scratch. A work dir whose recovery move itself fails is left untouched (its {@code old} preserved
|
||||
* for manual recovery), never deleted.
|
||||
*
|
||||
* <p>The scratch lives under {@code sites/.restore-work/}, a hidden name {@link
|
||||
* mx.quest.runway.storage.PathSafety#isSafeId} rejects, so it is never mistaken for a tenant.
|
||||
*/
|
||||
@Component
|
||||
public class BackupRestoreRecovery {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(BackupRestoreRecovery.class);
|
||||
|
||||
private final StorageLayout layout;
|
||||
|
||||
public BackupRestoreRecovery(StorageLayout layout) {
|
||||
this.layout = layout;
|
||||
}
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void recover() {
|
||||
Path workRoot = layout.sites().resolve(BackupService.WORK_DIR);
|
||||
if (!Files.isDirectory(workRoot)) {
|
||||
return;
|
||||
}
|
||||
List<Path> workDirs;
|
||||
try (Stream<Path> ids = Files.list(workRoot)) {
|
||||
workDirs = ids.filter(Files::isDirectory).toList();
|
||||
} catch (IOException e) {
|
||||
log.warn("restore-recovery sweep could not list {}", workRoot, e);
|
||||
return;
|
||||
}
|
||||
for (Path workDir : workDirs) {
|
||||
String siteId = workDir.getFileName().toString();
|
||||
Path old = workDir.resolve("old");
|
||||
Path siteDir = layout.siteDir(siteId);
|
||||
if (Files.exists(old) && !Files.exists(siteDir)) {
|
||||
try {
|
||||
Files.move(old, siteDir);
|
||||
log.warn("recovered site '{}' from an interrupted restore", siteId);
|
||||
} catch (IOException e) {
|
||||
// Recovery failed — DO NOT delete this work dir; `old` is the only copy of the site.
|
||||
log.error("could not recover site '{}' automatically — its content is preserved at {}",
|
||||
siteId, old, e);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
BackupService.deleteRecursively(workDir); // recovered or not needed — the leftovers are safe to drop
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,25 @@
|
||||
package mx.quest.runway.backup;
|
||||
|
||||
import mx.quest.runway.site.SiteStore;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Wires the automatic-backup runner <b>only when opted in</b> ({@code runway.backups.schedule.enabled=true}). When
|
||||
* off (the default) the {@link ScheduledBackupRunner} does not exist, so no backup is ever scheduled — automatic
|
||||
* backups are strictly opt-in, and a manual console backup is always available regardless.
|
||||
*
|
||||
* <p>Scheduling itself is enabled platform-wide by {@link mx.quest.runway.platform.SchedulingConfig}; it used to be
|
||||
* enabled here, which left every other {@code @Scheduled} method (plugins' periodic work) dead unless automatic
|
||||
* backups were on.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnProperty(prefix = "runway.backups.schedule", name = "enabled", havingValue = "true")
|
||||
public class ScheduledBackupConfig {
|
||||
|
||||
@Bean
|
||||
public ScheduledBackupRunner scheduledBackupRunner(BackupService backups, SiteStore sites) {
|
||||
return new ScheduledBackupRunner(backups, sites);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package mx.quest.runway.backup;
|
||||
|
||||
import mx.quest.runway.site.Site;
|
||||
import mx.quest.runway.site.SiteStore;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
|
||||
/**
|
||||
* Runs the automatic all-sites backup on the configured cron ({@code runway.backups.schedule.cron}). Each site is
|
||||
* backed up <b>in isolation</b> — one site's failure is logged and does not stop the others — and the retention
|
||||
* policy + optional off-host mirror apply to each just as a manual backup does (this reuses
|
||||
* {@link BackupService#create(String)}). Created only when {@code runway.backups.schedule.enabled=true} (see
|
||||
* {@link ScheduledBackupConfig}), so no backup is scheduled when automatic backups are off. It runs on the
|
||||
* platform's shared scheduler pool ({@link mx.quest.runway.platform.SchedulingConfig}).
|
||||
*/
|
||||
public class ScheduledBackupRunner {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ScheduledBackupRunner.class);
|
||||
|
||||
private final BackupService backups;
|
||||
private final SiteStore sites;
|
||||
|
||||
public ScheduledBackupRunner(BackupService backups, SiteStore sites) {
|
||||
this.backups = backups;
|
||||
this.sites = sites;
|
||||
}
|
||||
|
||||
/**
|
||||
* Backs up every configured site. Invoked by Spring's scheduler on the cron; also callable directly (tests).
|
||||
*
|
||||
* @return the number of sites successfully backed up this run
|
||||
*/
|
||||
@Scheduled(cron = "${runway.backups.schedule.cron:0 30 2 * * *}")
|
||||
public int runAll() {
|
||||
java.util.List<Site> all = sites.findAll();
|
||||
int ok = 0;
|
||||
int failed = 0;
|
||||
for (Site site : all) {
|
||||
try {
|
||||
backups.create(site.id());
|
||||
ok++;
|
||||
} catch (Exception e) { // isolate: one site's failure must not stop the scheduled run
|
||||
failed++;
|
||||
log.warn("scheduled backup failed for site '{}': {}", site.id(), e.toString());
|
||||
}
|
||||
}
|
||||
log.info("scheduled backup run complete: {} succeeded, {} failed (of {} site(s))", ok, failed, all.size());
|
||||
return ok;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package mx.quest.runway.backup;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* A restore (or create-site-from-backup) refused because the archive's {@code manifest.yml} declares a
|
||||
* {@link BackupManifest#formatVersion() formatVersion} newer than this build reads — it was written by a later
|
||||
* Runway. Thrown <b>before</b> anything is swapped into place, so the live site is untouched. A subtype of
|
||||
* {@link IOException} so every caller that already handles "not a valid backup" still handles it; the consoles
|
||||
* catch it first to tell the operator what to do (upgrade, then restore).
|
||||
*/
|
||||
public final class UnsupportedBackupFormatException extends IOException {
|
||||
|
||||
private final int found;
|
||||
private final int supported;
|
||||
|
||||
public UnsupportedBackupFormatException(int found, int supported) {
|
||||
super("backup archive format " + found + " is newer than this Runway reads (up to " + supported
|
||||
+ ") — restore it on the Runway release that wrote it, or a later one");
|
||||
this.found = found;
|
||||
this.supported = supported;
|
||||
}
|
||||
|
||||
/** The format version the archive declares. */
|
||||
public int found() {
|
||||
return found;
|
||||
}
|
||||
|
||||
/** The highest format version this build restores. */
|
||||
public int supported() {
|
||||
return supported;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package mx.quest.runway.backup;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.FilterOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.Map;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
import mx.quest.runway.spi.model.BackupReader;
|
||||
import mx.quest.runway.spi.model.BackupWriter;
|
||||
|
||||
/**
|
||||
* The host-side {@link BackupWriter}/{@link BackupReader} implementations that scope a {@link
|
||||
* mx.quest.runway.spi.BackupParticipant}'s entries under {@code plugin-data/<key>/} inside a site archive.
|
||||
*
|
||||
* <p><b>Non-closing entry streams.</b> A participant writes each entry with
|
||||
* try-with-resources, so closing the per-entry stream must finalize <em>that entry</em> — not the whole
|
||||
* {@link ZipOutputStream}, which would truncate the archive after the first participant entry. {@link
|
||||
* Writer#put} therefore returns a stream whose {@code close()} calls {@code closeEntry()} and never touches
|
||||
* the underlying zip.
|
||||
*
|
||||
* <p><b>Entry names are checked</b> on both sides ({@link #requireSafeEntry}): a participant can neither write nor
|
||||
* look up a name outside its own namespace.
|
||||
*/
|
||||
final class ZipBackup {
|
||||
|
||||
private ZipBackup() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses an entry name that is not a plain relative path inside the participant's namespace:
|
||||
* blank, absolute ({@code /x}, {@code C:x}), containing a backslash or a NUL, or with an empty, {@code .} or
|
||||
* {@code ..} segment. Such a name would let one participant write outside {@code plugin-data/<key>/} in the
|
||||
* archive (and an extractor that trusts names would follow it on disk), so it is a participant bug, refused
|
||||
* loudly rather than normalised.
|
||||
*
|
||||
* @return {@code entry}, unchanged
|
||||
* @throws IllegalArgumentException if the name is unsafe
|
||||
*/
|
||||
static String requireSafeEntry(String entry) {
|
||||
if (entry == null || entry.isBlank() || entry.startsWith("/") || entry.indexOf('\\') >= 0
|
||||
|| entry.indexOf('\0') >= 0 || (entry.length() > 1 && entry.charAt(1) == ':')) {
|
||||
throw new IllegalArgumentException("unsafe backup entry name: '" + entry + "'");
|
||||
}
|
||||
for (String segment : entry.split("/", -1)) {
|
||||
if (segment.isEmpty() || segment.equals(".") || segment.equals("..")) {
|
||||
throw new IllegalArgumentException("unsafe backup entry name: '" + entry + "'");
|
||||
}
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
/** Writes a participant's entries under {@code plugin-data/<key>/} into the shared archive. */
|
||||
static final class Writer implements BackupWriter {
|
||||
|
||||
private final ZipOutputStream zip;
|
||||
private final String prefix;
|
||||
|
||||
Writer(ZipOutputStream zip, String participantKey) {
|
||||
this.zip = zip;
|
||||
this.prefix = "plugin-data/" + participantKey + "/";
|
||||
}
|
||||
|
||||
@Override
|
||||
public OutputStream put(String entry) throws IOException {
|
||||
zip.putNextEntry(new ZipEntry(prefix + requireSafeEntry(entry)));
|
||||
return new EntryStream(zip);
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads a participant's entries (pre-collected into memory, keyed by participant-relative name). */
|
||||
static final class Reader implements BackupReader {
|
||||
|
||||
private final Map<String, byte[]> entries;
|
||||
|
||||
Reader(Map<String, byte[]> entries) {
|
||||
this.entries = entries;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean has(String entry) {
|
||||
return entries.containsKey(requireSafeEntry(entry));
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream open(String entry) throws IOException {
|
||||
byte[] bytes = entries.get(requireSafeEntry(entry));
|
||||
if (bytes == null) {
|
||||
throw new IOException("backup entry not found: " + entry);
|
||||
}
|
||||
return new ByteArrayInputStream(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
/** A stream over one zip entry: {@code close()} finalizes the entry, never the underlying archive. */
|
||||
private static final class EntryStream extends FilterOutputStream {
|
||||
|
||||
private final ZipOutputStream zip;
|
||||
|
||||
EntryStream(ZipOutputStream zip) {
|
||||
super(zip);
|
||||
this.zip = zip;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(byte[] b, int off, int len) throws IOException {
|
||||
out.write(b, off, len); // FilterOutputStream's default is byte-by-byte — delegate the bulk write
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
flush();
|
||||
zip.closeEntry(); // finalize this entry only; the host owns the ZipOutputStream lifecycle
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package mx.quest.runway.bandwidth;
|
||||
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import mx.quest.runway.web.FilterOrder;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Registers {@link BandwidthFilter} at {@link FilterOrder#CORE_BANDWIDTH} (outside compression, inside the
|
||||
* forwarded-header gate) and enables {@link BandwidthProperties}.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableConfigurationProperties(BandwidthProperties.class)
|
||||
public class BandwidthConfig {
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean<BandwidthFilter> bandwidthFilterRegistration(SiteResolver siteResolver,
|
||||
BandwidthService bandwidth) {
|
||||
FilterRegistrationBean<BandwidthFilter> registration =
|
||||
new FilterRegistrationBean<>(new BandwidthFilter(siteResolver, bandwidth));
|
||||
registration.setOrder(FilterOrder.CORE_BANDWIDTH);
|
||||
registration.addUrlPatterns("/*");
|
||||
registration.setName("bandwidthFilter");
|
||||
return registration;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean<BandwidthLimitFilter> bandwidthLimitFilterRegistration(SiteResolver siteResolver,
|
||||
BandwidthService bandwidth) {
|
||||
FilterRegistrationBean<BandwidthLimitFilter> registration =
|
||||
new FilterRegistrationBean<>(new BandwidthLimitFilter(siteResolver, bandwidth));
|
||||
registration.setOrder(FilterOrder.CORE_BANDWIDTH_LIMIT);
|
||||
registration.addUrlPatterns("/*");
|
||||
registration.setName("bandwidthLimitFilter");
|
||||
return registration;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package mx.quest.runway.bandwidth;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import mx.quest.runway.site.Site;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import mx.quest.runway.web.RequestPaths;
|
||||
import mx.quest.runway.web.UnmeteredPaths;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
/**
|
||||
* Counts each request's on-the-wire bytes and attributes them to the host's site. It sits at
|
||||
* {@code FilterOrder.CORE_BANDWIDTH} — outside compression (so it counts the real transmitted size) and
|
||||
* inside the forwarded-header gate (so the host is settled). Because it wraps the site-context filter, the
|
||||
* request binding is already cleared in its post phase, so it re-resolves the site from the host directly.
|
||||
*
|
||||
* <p>App-realm and health traffic ({@code /__app}, {@code /app/…}, {@code /actuator}) is excluded — it is not
|
||||
* a tenant's bandwidth. Everything that resolves to a site (public pages, the tenant console, plugin assets)
|
||||
* is metered as aggregate byte counts only.
|
||||
*/
|
||||
public class BandwidthFilter extends OncePerRequestFilter {
|
||||
|
||||
private final SiteResolver siteResolver;
|
||||
private final BandwidthService bandwidth;
|
||||
|
||||
public BandwidthFilter(SiteResolver siteResolver, BandwidthService bandwidth) {
|
||||
this.siteResolver = siteResolver;
|
||||
this.bandwidth = bandwidth;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
if (isExcluded(RequestPaths.normalized(request))) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
CountingResponseWrapper counting = new CountingResponseWrapper(response);
|
||||
try {
|
||||
chain.doFilter(request, counting);
|
||||
} finally {
|
||||
counting.flushBuffer();
|
||||
Site site = siteResolver.resolve(request.getServerName()).orElse(null);
|
||||
if (site != null) {
|
||||
long in = Math.max(0, request.getContentLengthLong());
|
||||
bandwidth.record(site.id(), in, counting.bytesWritten());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Platform traffic, never charged to a tenant — the one shared authority (see {@link UnmeteredPaths}), asked of the
|
||||
* decoded path ({@link RequestPaths#normalized}) so an encoded console path is not charged to the host's site.
|
||||
*/
|
||||
private static boolean isExcluded(String path) {
|
||||
return UnmeteredPaths.isUnmetered(path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package mx.quest.runway.bandwidth;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import mx.quest.runway.site.Site;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import mx.quest.runway.web.AppRealmPaths;
|
||||
import mx.quest.runway.web.RequestPaths;
|
||||
import mx.quest.runway.web.TenantConsolePaths;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
/**
|
||||
* Short-circuits a site's <b>public</b> traffic with {@code 503 Service Unavailable} once it has exceeded its
|
||||
* configured rolling-30-day outbound bandwidth quota (see {@link BandwidthProperties.Quota}). Runs in the
|
||||
* tenant band after site binding; the over-quota decision is an O(1) cached-set lookup, so this adds nothing
|
||||
* measurable to the request path.
|
||||
*
|
||||
* <p>The application realm and the tenant <b>console</b> realm are exempt (same as maintenance mode): a
|
||||
* quota only throttles the abusive <em>public</em> load, never the operator or the site manager reaching the
|
||||
* console. When no quota is configured the cached set is empty and this filter is a straight pass-through.
|
||||
*/
|
||||
public class BandwidthLimitFilter extends OncePerRequestFilter {
|
||||
|
||||
private final SiteResolver siteResolver;
|
||||
private final BandwidthService bandwidth;
|
||||
|
||||
public BandwidthLimitFilter(SiteResolver siteResolver, BandwidthService bandwidth) {
|
||||
this.siteResolver = siteResolver;
|
||||
this.bandwidth = bandwidth;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||
FilterChain chain) throws ServletException, IOException {
|
||||
Site site = siteResolver.current().orElse(null);
|
||||
if (site != null && bandwidth.isOverQuota(site.id()) && !isExempt(RequestPaths.normalized(request))) {
|
||||
response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
|
||||
response.setHeader("Retry-After", "3600");
|
||||
response.setContentType("text/plain;charset=UTF-8");
|
||||
response.getOutputStream().write(
|
||||
"This site has reached its bandwidth allowance. Please try again later."
|
||||
.getBytes(StandardCharsets.UTF_8));
|
||||
return;
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Exempt: the application realm and the tenant console (sign-in and recovery included), so nobody is locked out
|
||||
* of lifting the block. Asked of the decoded path ({@link RequestPaths#normalized}), like every exemption.
|
||||
*/
|
||||
private static boolean isExempt(String path) {
|
||||
return AppRealmPaths.isAppRealm(path) || TenantConsolePaths.isConsole(path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package mx.quest.runway.bandwidth;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.context.properties.NestedConfigurationProperty;
|
||||
|
||||
/**
|
||||
* Platform-level bandwidth-metering settings ({@code runway.bandwidth.*}) — app-level, not tenant-editable
|
||||
* (a tenant-settable retention/path/quota would be an abuse lever). Metering is aggregate byte counts only.
|
||||
*/
|
||||
@ConfigurationProperties("runway.bandwidth")
|
||||
public class BandwidthProperties {
|
||||
|
||||
/** Whether per-site bandwidth metering runs at all. Default: on. */
|
||||
private boolean enabled = true;
|
||||
|
||||
/** How many days of hourly buckets to keep (older buckets are pruned from memory and the CSV). */
|
||||
private int retentionDays = 90;
|
||||
|
||||
/** How often the in-memory counters are snapshotted to disk. */
|
||||
private int snapshotSeconds = 60;
|
||||
|
||||
@NestedConfigurationProperty
|
||||
private final Quota quota = new Quota();
|
||||
|
||||
public Quota getQuota() {
|
||||
return quota;
|
||||
}
|
||||
|
||||
/**
|
||||
* Optional per-site rolling-30-day <em>outbound</em> bandwidth quota. When a site's last-30-day served
|
||||
* bytes exceed its effective quota, its <b>public</b> traffic is short-circuited with {@code 503} (the
|
||||
* console and login stay reachable). App-level and operator-set on purpose — a tenant raising its own cap
|
||||
* would defeat the point. Off by default (no cap). The check is O(1) at request time (a cached set,
|
||||
* recomputed on the metering snapshot cadence), so it never burdens the hot path.
|
||||
*/
|
||||
public static class Quota {
|
||||
|
||||
/** Default per-site monthly (rolling-30-day) outbound byte cap; {@code 0} = unlimited. */
|
||||
private long defaultMonthlyBytes = 0;
|
||||
|
||||
/** Per-site overrides of {@link #defaultMonthlyBytes}, keyed by site id ({@code 0} = unlimited). */
|
||||
private Map<String, Long> perSite = new LinkedHashMap<>();
|
||||
|
||||
public long getDefaultMonthlyBytes() {
|
||||
return defaultMonthlyBytes;
|
||||
}
|
||||
|
||||
public void setDefaultMonthlyBytes(long defaultMonthlyBytes) {
|
||||
this.defaultMonthlyBytes = defaultMonthlyBytes;
|
||||
}
|
||||
|
||||
public Map<String, Long> getPerSite() {
|
||||
return perSite;
|
||||
}
|
||||
|
||||
public void setPerSite(Map<String, Long> perSite) {
|
||||
this.perSite = (perSite == null) ? new LinkedHashMap<>() : perSite;
|
||||
}
|
||||
|
||||
/** The effective monthly cap for {@code siteId} — the per-site override if set, else the default. */
|
||||
public long effectiveFor(String siteId) {
|
||||
return perSite.getOrDefault(siteId, defaultMonthlyBytes);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public int getRetentionDays() {
|
||||
return retentionDays;
|
||||
}
|
||||
|
||||
public void setRetentionDays(int retentionDays) {
|
||||
this.retentionDays = retentionDays;
|
||||
}
|
||||
|
||||
public int getSnapshotSeconds() {
|
||||
return snapshotSeconds;
|
||||
}
|
||||
|
||||
public void setSnapshotSeconds(int snapshotSeconds) {
|
||||
this.snapshotSeconds = snapshotSeconds;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
package mx.quest.runway.bandwidth;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
import java.util.function.ToLongFunction;
|
||||
import java.util.stream.Stream;
|
||||
import mx.quest.runway.storage.AtomicFiles;
|
||||
import mx.quest.runway.storage.StorageLayout;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* Meters each site's bandwidth. {@link #record} is the hot path — it only bumps in-memory {@link LongAdder}s
|
||||
* keyed by site and UTC hour, doing no I/O. A single daemon thread snapshots the counters to
|
||||
* {@code sites/<id>/stats/bandwidth.csv} periodically (crash-survival; the CSV is reloaded at startup) and
|
||||
* prunes buckets past the retention window. Metering is <b>aggregate byte counts only</b> — never request
|
||||
* contents — which is what lets it (in aggregate) cross to the app realm without breaking tenant isolation.
|
||||
*/
|
||||
@Service
|
||||
public class BandwidthService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(BandwidthService.class);
|
||||
private static final long SECONDS_PER_HOUR = 3600;
|
||||
private static final DateTimeFormatter DAY_LABEL = DateTimeFormatter.ofPattern("MM-dd");
|
||||
private static final ZoneId ZONE = ZoneId.systemDefault();
|
||||
|
||||
/** Mutable per-hour counters. */
|
||||
private static final class Counters {
|
||||
final LongAdder in = new LongAdder();
|
||||
final LongAdder out = new LongAdder();
|
||||
final LongAdder requests = new LongAdder();
|
||||
}
|
||||
|
||||
/** One point in a report series. */
|
||||
public record BandPoint(String label, long bytesIn, long bytesOut) {
|
||||
public String inHuman() {
|
||||
return Bytes.human(bytesIn);
|
||||
}
|
||||
|
||||
public String outHuman() {
|
||||
return Bytes.human(bytesOut);
|
||||
}
|
||||
|
||||
/** The out-bytes bar width as a whole-number percent of {@code max} (for a CSS bar). */
|
||||
public long outBar(long max) {
|
||||
return max <= 0 ? 0 : Math.min(100, bytesOut * 100 / max);
|
||||
}
|
||||
}
|
||||
|
||||
/** A site's rolled-up totals, for the app-realm aggregate. */
|
||||
public record SiteBandwidth(String siteId, long bytesIn, long bytesOut) {
|
||||
public String inHuman() {
|
||||
return Bytes.human(bytesIn);
|
||||
}
|
||||
|
||||
public String outHuman() {
|
||||
return Bytes.human(bytesOut);
|
||||
}
|
||||
}
|
||||
|
||||
/** A tenant report: the daily series plus headline totals. */
|
||||
public record BandwidthReport(List<BandPoint> daily, long in24h, long out24h, long in7d, long out7d,
|
||||
long in30d, long out30d) {
|
||||
public long maxDaily() {
|
||||
return Math.max(1, daily.stream().mapToLong(BandPoint::bytesOut).max().orElse(1));
|
||||
}
|
||||
|
||||
public String in24hHuman() {
|
||||
return Bytes.human(in24h);
|
||||
}
|
||||
|
||||
public String out24hHuman() {
|
||||
return Bytes.human(out24h);
|
||||
}
|
||||
|
||||
public String out7dHuman() {
|
||||
return Bytes.human(out7d);
|
||||
}
|
||||
|
||||
public String out30dHuman() {
|
||||
return Bytes.human(out30d);
|
||||
}
|
||||
}
|
||||
|
||||
private final StorageLayout layout;
|
||||
private final BandwidthProperties props;
|
||||
private final Map<String, Map<Long, Counters>> counters = new ConcurrentHashMap<>();
|
||||
private volatile boolean running;
|
||||
private volatile LocalDate lastPrune;
|
||||
private volatile java.util.Set<String> overQuota = java.util.Set.of();
|
||||
private Thread worker;
|
||||
/** Each site's cap in bytes ({@code 0} = unlimited). */
|
||||
private final ToLongFunction<String> quotaFor;
|
||||
|
||||
/** With the caps bound from configuration only (tests). */
|
||||
public BandwidthService(StorageLayout layout, BandwidthProperties props) {
|
||||
this(layout, props, props.getQuota()::effectiveFor);
|
||||
}
|
||||
|
||||
/** With each site's cap from {@code quotas}: the host's, else the one set on the Sites screen, else the default. */
|
||||
@Autowired
|
||||
public BandwidthService(StorageLayout layout, BandwidthProperties props, SiteBandwidthQuotas quotas) {
|
||||
this(layout, props, quotas::bytesFor);
|
||||
}
|
||||
|
||||
private BandwidthService(StorageLayout layout, BandwidthProperties props, ToLongFunction<String> quotaFor) {
|
||||
this.layout = layout;
|
||||
this.props = props;
|
||||
this.quotaFor = quotaFor;
|
||||
}
|
||||
|
||||
/** Adds one request's byte counts to the current hour's bucket for {@code siteId}. Hot path — no I/O. */
|
||||
public void record(String siteId, long bytesIn, long bytesOut) {
|
||||
if (!props.isEnabled() || siteId == null) {
|
||||
return;
|
||||
}
|
||||
Counters c = counters.computeIfAbsent(siteId, k -> new ConcurrentHashMap<>())
|
||||
.computeIfAbsent(currentHour(), h -> new Counters());
|
||||
c.in.add(Math.max(0, bytesIn));
|
||||
c.out.add(Math.max(0, bytesOut));
|
||||
c.requests.increment();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code siteId} has exceeded its effective rolling-30-day outbound quota. O(1) — reads a set
|
||||
* that is recomputed on the snapshot cadence, so it never runs the 30-day sum on the request hot path.
|
||||
* Always {@code false} when no quota is configured, and when metering is off.
|
||||
*/
|
||||
public boolean isOverQuota(String siteId) {
|
||||
// A cap is measured by metering: with metering off (runway.bandwidth.enabled=false) nothing is counted, so the
|
||||
// set computed at startup from the saved totals would never change again and a site over its cap then would
|
||||
// answer 503 for good. No metering, no cap.
|
||||
return props.isEnabled() && siteId != null && overQuota.contains(siteId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Recomputes the over-quota set from the current 30-day outbound totals. Called once at startup and on
|
||||
* each snapshot cycle. A site with no configured cap (effective {@code 0}) is never included.
|
||||
*/
|
||||
void recomputeOverQuota() {
|
||||
java.util.Set<String> over = new java.util.HashSet<>();
|
||||
for (SiteBandwidth s : aggregate()) {
|
||||
long cap = quotaFor.applyAsLong(s.siteId());
|
||||
if (cap > 0 && s.bytesOut() > cap) {
|
||||
over.add(s.siteId());
|
||||
}
|
||||
}
|
||||
overQuota = over.isEmpty() ? java.util.Set.of() : java.util.Set.copyOf(over);
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-evaluates which sites are over their cap now, rather than at the next snapshot: after the operator changes a
|
||||
* site's cap, so raising it reopens the site at once.
|
||||
*/
|
||||
public void refreshQuotas() {
|
||||
recomputeOverQuota();
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
void start() {
|
||||
reloadAll();
|
||||
recomputeOverQuota();
|
||||
if (!props.isEnabled()) {
|
||||
return;
|
||||
}
|
||||
running = true;
|
||||
worker = new Thread(this::loop, "runway-bandwidth");
|
||||
worker.setDaemon(true);
|
||||
worker.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the daemon and takes a final snapshot. <b>Best-effort:</b> counts recorded by a {@code record()}
|
||||
* that lands after this final {@link #snapshotAll()} are lost — bandwidth metering is coarse telemetry and
|
||||
* the CSV snapshot is itself crash-safe, so a fully-quiesced count is not worth blocking the hot path for.
|
||||
*/
|
||||
@PreDestroy
|
||||
void stop() {
|
||||
running = false;
|
||||
if (worker != null) {
|
||||
worker.interrupt();
|
||||
try {
|
||||
worker.join(TimeUnit.SECONDS.toMillis(5));
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
snapshotAll(); // final flush after the worker exits (best-effort — see the method contract)
|
||||
}
|
||||
|
||||
/** The last-{@code days} daily series and 24h/7d/30d totals for one site. */
|
||||
public BandwidthReport report(String siteId, int days) {
|
||||
Map<Long, Counters> hours = counters.getOrDefault(siteId, Map.of());
|
||||
long nowHour = currentHour();
|
||||
LocalDate today = LocalDate.now(ZONE);
|
||||
|
||||
List<BandPoint> daily = new ArrayList<>();
|
||||
for (int d = days - 1; d >= 0; d--) {
|
||||
LocalDate day = today.minusDays(d);
|
||||
long in = 0;
|
||||
long out = 0;
|
||||
for (int h = 0; h < 24; h++) {
|
||||
long hourEpoch = day.atStartOfDay(ZONE).toEpochSecond() / SECONDS_PER_HOUR + h;
|
||||
Counters c = hours.get(hourEpoch);
|
||||
if (c != null) {
|
||||
in += c.in.sum();
|
||||
out += c.out.sum();
|
||||
}
|
||||
}
|
||||
daily.add(new BandPoint(DAY_LABEL.format(day), in, out));
|
||||
}
|
||||
return new BandwidthReport(daily,
|
||||
total(hours, nowHour - 23, nowHour, true), total(hours, nowHour - 23, nowHour, false),
|
||||
total(hours, nowHour - 24 * 7 + 1, nowHour, true), total(hours, nowHour - 24 * 7 + 1, nowHour, false),
|
||||
total(hours, nowHour - 24 * 30 + 1, nowHour, true), total(hours, nowHour - 24 * 30 + 1, nowHour, false));
|
||||
}
|
||||
|
||||
/** Per-site 30-day totals, busiest first — for the app-realm aggregate view. */
|
||||
public List<SiteBandwidth> aggregate() {
|
||||
long nowHour = currentHour();
|
||||
long from = nowHour - 24 * 30 + 1;
|
||||
List<SiteBandwidth> out = new ArrayList<>();
|
||||
for (Map.Entry<String, Map<Long, Counters>> site : counters.entrySet()) {
|
||||
out.add(new SiteBandwidth(site.getKey(),
|
||||
total(site.getValue(), from, nowHour, true), total(site.getValue(), from, nowHour, false)));
|
||||
}
|
||||
out.sort(Comparator.comparingLong((SiteBandwidth s) -> s.bytesOut()).reversed());
|
||||
return out;
|
||||
}
|
||||
|
||||
private static long total(Map<Long, Counters> hours, long fromHour, long toHour, boolean in) {
|
||||
long sum = 0;
|
||||
for (Map.Entry<Long, Counters> e : hours.entrySet()) {
|
||||
if (e.getKey() >= fromHour && e.getKey() <= toHour) {
|
||||
sum += in ? e.getValue().in.sum() : e.getValue().out.sum();
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
private static long currentHour() {
|
||||
return Instant.now().getEpochSecond() / SECONDS_PER_HOUR;
|
||||
}
|
||||
|
||||
private void loop() {
|
||||
while (running) {
|
||||
try {
|
||||
TimeUnit.SECONDS.sleep(Math.max(1, props.getSnapshotSeconds()));
|
||||
snapshotAll();
|
||||
pruneIfDue();
|
||||
recomputeOverQuota();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("bandwidth snapshot failed: {}", e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void snapshotAll() {
|
||||
long cutoff = currentHour() - (long) props.getRetentionDays() * 24;
|
||||
for (Map.Entry<String, Map<Long, Counters>> site : counters.entrySet()) {
|
||||
try {
|
||||
snapshotSite(site.getKey(), site.getValue(), cutoff);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
log.warn("bandwidth snapshot failed for '{}': {}", site.getKey(), e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void snapshotSite(String siteId, Map<Long, Counters> hours, long cutoff) throws IOException {
|
||||
StringBuilder csv = new StringBuilder();
|
||||
hours.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(e -> {
|
||||
if (e.getKey() >= cutoff) {
|
||||
Counters c = e.getValue();
|
||||
csv.append(e.getKey()).append(',').append(c.in.sum()).append(',').append(c.out.sum())
|
||||
.append(',').append(c.requests.sum()).append('\n');
|
||||
}
|
||||
});
|
||||
Path file = statsFile(siteId);
|
||||
if (file == null) {
|
||||
return;
|
||||
}
|
||||
AtomicFiles.write(file, csv.toString().getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
void reloadAll() {
|
||||
Path sites = layout.sites();
|
||||
if (!Files.isDirectory(sites)) {
|
||||
return;
|
||||
}
|
||||
try (Stream<Path> dirs = Files.list(sites)) {
|
||||
dirs.filter(Files::isDirectory).forEach(dir -> reloadSite(dir.getFileName().toString()));
|
||||
} catch (IOException e) {
|
||||
log.warn("bandwidth reload scan failed: {}", e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
private void reloadSite(String siteId) {
|
||||
Path file = statsFile(siteId);
|
||||
if (file == null || !Files.isRegularFile(file)) {
|
||||
return;
|
||||
}
|
||||
Map<Long, Counters> hours = new ConcurrentHashMap<>();
|
||||
try {
|
||||
for (String line : Files.readAllLines(file, java.nio.charset.StandardCharsets.UTF_8)) {
|
||||
String[] parts = line.split(",");
|
||||
if (parts.length >= 3) {
|
||||
Counters c = new Counters();
|
||||
c.in.add(Long.parseLong(parts[1].trim()));
|
||||
c.out.add(Long.parseLong(parts[2].trim()));
|
||||
if (parts.length >= 4) {
|
||||
c.requests.add(Long.parseLong(parts[3].trim()));
|
||||
}
|
||||
hours.put(Long.parseLong(parts[0].trim()), c);
|
||||
}
|
||||
}
|
||||
if (!hours.isEmpty()) {
|
||||
counters.put(siteId, hours);
|
||||
}
|
||||
} catch (IOException | RuntimeException e) {
|
||||
log.warn("could not reload bandwidth for '{}': {}", siteId, e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
private void pruneIfDue() {
|
||||
LocalDate today = LocalDate.now(ZONE);
|
||||
if (today.equals(lastPrune)) {
|
||||
return;
|
||||
}
|
||||
lastPrune = today;
|
||||
long cutoff = currentHour() - (long) props.getRetentionDays() * 24;
|
||||
counters.values().forEach(hours -> hours.keySet().removeIf(hour -> hour < cutoff));
|
||||
}
|
||||
|
||||
private Path statsFile(String siteId) {
|
||||
try {
|
||||
return layout.siteDir(siteId).resolve("stats").resolve("bandwidth.csv");
|
||||
} catch (IllegalArgumentException unsafe) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package mx.quest.runway.bandwidth;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/** Human-readable byte sizes (B / KB / MB / GB / TB, base-1024) for the bandwidth screens. */
|
||||
public final class Bytes {
|
||||
|
||||
private static final String[] UNITS = {"B", "KB", "MB", "GB", "TB", "PB"};
|
||||
|
||||
private Bytes() {
|
||||
}
|
||||
|
||||
/** Formats {@code bytes} with one decimal above 1 KB (e.g. {@code 1.5 MB}); {@code 0 B} for zero/negative. */
|
||||
public static String human(long bytes) {
|
||||
if (bytes <= 0) {
|
||||
return "0 B";
|
||||
}
|
||||
int unit = 0;
|
||||
double value = bytes;
|
||||
while (value >= 1024 && unit < UNITS.length - 1) {
|
||||
value /= 1024;
|
||||
unit++;
|
||||
}
|
||||
return unit == 0
|
||||
? bytes + " B"
|
||||
: String.format(Locale.ROOT, "%.1f %s", value, UNITS[unit]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package mx.quest.runway.bandwidth;
|
||||
|
||||
import jakarta.servlet.ServletOutputStream;
|
||||
import jakarta.servlet.WriteListener;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.http.HttpServletResponseWrapper;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* Wraps a response so every byte written to the client is counted. Sitting outside compression on the filter
|
||||
* ladder, the count is the real on-the-wire response size. The wrapper adds no buffering — it delegates and
|
||||
* only tallies — so it is safe on the hot path.
|
||||
*/
|
||||
public final class CountingResponseWrapper extends HttpServletResponseWrapper {
|
||||
|
||||
private long bytesWritten;
|
||||
private CountingOutputStream stream;
|
||||
private PrintWriter writer;
|
||||
|
||||
public CountingResponseWrapper(HttpServletResponse response) {
|
||||
super(response);
|
||||
}
|
||||
|
||||
/** The number of body bytes written to the client so far. */
|
||||
public long bytesWritten() {
|
||||
return bytesWritten;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServletOutputStream getOutputStream() throws IOException {
|
||||
if (writer != null) {
|
||||
return super.getOutputStream();
|
||||
}
|
||||
if (stream == null) {
|
||||
stream = new CountingOutputStream(super.getOutputStream());
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PrintWriter getWriter() throws IOException {
|
||||
if (stream != null) {
|
||||
return super.getWriter();
|
||||
}
|
||||
if (writer == null) {
|
||||
writer = new PrintWriter(new java.io.OutputStreamWriter(
|
||||
new CountingOutputStream(super.getOutputStream()), charset()), false);
|
||||
}
|
||||
return writer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flushBuffer() throws IOException {
|
||||
if (writer != null) {
|
||||
writer.flush();
|
||||
}
|
||||
super.flushBuffer();
|
||||
}
|
||||
|
||||
private java.nio.charset.Charset charset() {
|
||||
String name = getCharacterEncoding();
|
||||
try {
|
||||
return name == null ? StandardCharsets.UTF_8 : java.nio.charset.Charset.forName(name);
|
||||
} catch (RuntimeException e) {
|
||||
return StandardCharsets.UTF_8;
|
||||
}
|
||||
}
|
||||
|
||||
/** A pass-through {@link ServletOutputStream} that tallies every byte before delegating. */
|
||||
private final class CountingOutputStream extends ServletOutputStream {
|
||||
|
||||
private final ServletOutputStream delegate;
|
||||
|
||||
CountingOutputStream(ServletOutputStream delegate) {
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(int b) throws IOException {
|
||||
delegate.write(b);
|
||||
bytesWritten++;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(byte[] b, int off, int len) throws IOException {
|
||||
delegate.write(b, off, len);
|
||||
bytesWritten += len;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isReady() {
|
||||
return delegate.isReady();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setWriteListener(WriteListener listener) {
|
||||
delegate.setWriteListener(listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() throws IOException {
|
||||
delegate.flush();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
delegate.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package mx.quest.runway.bandwidth;
|
||||
|
||||
import java.util.Optional;
|
||||
import mx.quest.runway.platform.HostSettings;
|
||||
import mx.quest.runway.platform.PlatformSettingsStore;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Each site's monthly (rolling-30-day) outbound bandwidth cap, and where it comes from. The operator sets it per
|
||||
* site on the Sites screen, and the site sees
|
||||
* it read-only.
|
||||
*
|
||||
* <h2>Where a cap comes from, first match wins</h2>
|
||||
* <ol>
|
||||
* <li><b>The server</b> — {@code runway.bandwidth.quota.per-site.<id>} in the host's {@code application.yml} (or
|
||||
* an environment variable). One home per setting: the host's value wins and the Sites form shows the
|
||||
* field locked. Bound at startup.</li>
|
||||
* <li><b>The Sites screen</b> — {@code siteQuotas} in {@code external/platform.yml}. Read live, so a change takes
|
||||
* effect at the next over-quota check (the metering snapshot, once a minute by default) with no restart.</li>
|
||||
* <li><b>The platform default</b> — {@code runway.bandwidth.quota.default-monthly-bytes} (the Bandwidth settings
|
||||
* card or the host file). Bound at startup.</li>
|
||||
* </ol>
|
||||
* {@code 0} means unlimited at every level.
|
||||
*/
|
||||
@Component
|
||||
public class SiteBandwidthQuotas {
|
||||
|
||||
/** Where a site's cap comes from. */
|
||||
public enum Source {
|
||||
/** The host's configuration sets this site's cap. */
|
||||
HOST,
|
||||
/** The operator set this site's cap on the Sites screen. */
|
||||
SITE,
|
||||
/** No cap of its own: the platform default applies. */
|
||||
DEFAULT
|
||||
}
|
||||
|
||||
/**
|
||||
* A site's cap.
|
||||
*
|
||||
* @param bytes the cap in bytes; {@code 0} = unlimited
|
||||
* @param source where it comes from
|
||||
* @param origin for {@link Source#HOST}, where the host sets it ("external/application.yml", …); else {@code null}
|
||||
*/
|
||||
public record Quota(long bytes, Source source, String origin) {
|
||||
|
||||
/** Whether the site is capped at all. */
|
||||
public boolean limited() {
|
||||
return bytes > 0;
|
||||
}
|
||||
|
||||
/** The cap for people ("10 GiB"); "unlimited" is left to the caller's language. */
|
||||
public String human() {
|
||||
return Bytes.human(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
private final BandwidthProperties props;
|
||||
private final PlatformSettingsStore platform;
|
||||
private final HostSettings host;
|
||||
|
||||
public SiteBandwidthQuotas(BandwidthProperties props, PlatformSettingsStore platform, HostSettings host) {
|
||||
this.props = props;
|
||||
this.platform = platform;
|
||||
this.host = host;
|
||||
}
|
||||
|
||||
/** {@code siteId}'s cap and its source. */
|
||||
public Quota of(String siteId) {
|
||||
Long fromHost = props.getQuota().getPerSite().get(siteId);
|
||||
if (fromHost != null) {
|
||||
String origin = host.origin(PREFIX + siteId).orElse("the server's configuration");
|
||||
return new Quota(Math.max(0, fromHost), Source.HOST, origin);
|
||||
}
|
||||
Long own = platform.get().siteQuotas().get(siteId);
|
||||
if (own != null) {
|
||||
return new Quota(Math.max(0, own), Source.SITE, null);
|
||||
}
|
||||
return new Quota(Math.max(0, props.getQuota().getDefaultMonthlyBytes()), Source.DEFAULT, null);
|
||||
}
|
||||
|
||||
/** {@code siteId}'s cap in bytes, {@code 0} = unlimited. */
|
||||
public long bytesFor(String siteId) {
|
||||
return of(siteId).bytes();
|
||||
}
|
||||
|
||||
/** The platform default cap in bytes ({@code 0} = unlimited). */
|
||||
public long defaultBytes() {
|
||||
return Math.max(0, props.getQuota().getDefaultMonthlyBytes());
|
||||
}
|
||||
|
||||
/** Where the host sets {@code siteId}'s cap, when it does: the Sites form then shows the field locked. */
|
||||
public Optional<String> hostLock(String siteId) {
|
||||
Quota quota = of(siteId);
|
||||
return quota.source() == Source.HOST ? Optional.of(quota.origin()) : Optional.empty();
|
||||
}
|
||||
|
||||
private static final String PREFIX = "runway.bandwidth.quota.per-site.";
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package mx.quest.runway.cluster;
|
||||
|
||||
import com.hazelcast.client.HazelcastClient;
|
||||
import com.hazelcast.client.config.ClientConfig;
|
||||
import com.hazelcast.config.Config;
|
||||
import com.hazelcast.config.JoinConfig;
|
||||
import com.hazelcast.config.MapConfig;
|
||||
import com.hazelcast.config.NetworkConfig;
|
||||
import com.hazelcast.core.Hazelcast;
|
||||
import com.hazelcast.core.HazelcastInstance;
|
||||
import com.hazelcast.map.IMap;
|
||||
import java.time.Duration;
|
||||
import mx.quest.runway.wizard.ActiveModeCondition;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Conditional;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.session.MapSession;
|
||||
import org.springframework.session.SessionRepository;
|
||||
import org.springframework.session.config.annotation.web.http.EnableSpringHttpSession;
|
||||
|
||||
/**
|
||||
* Wires the Hazelcast layer and a Spring Session repository — but <b>only</b> when clustering is switched on and
|
||||
* the platform is running normally. Two gates, both class-level, so a single-node deployment carries none of
|
||||
* this:
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code @ConditionalOnProperty(runway.cluster.enabled=true)} — the master switch. With it off (the
|
||||
* default) this whole configuration is absent: no {@link HazelcastInstance}, no {@link SessionRepository},
|
||||
* and — because {@link EnableSpringHttpSession} never applies — no {@code springSessionRepositoryFilter}.
|
||||
* The container's own {@code HttpSession} is used exactly as today; there is provably zero clustering
|
||||
* overhead when off (guarded by a test).</li>
|
||||
* <li>{@link ActiveModeCondition} — clustering is meaningless during first-run setup, so this never activates
|
||||
* in WIZARD mode. In practice {@code runway.cluster.enabled=true} only ever lives in the external,
|
||||
* post-wizard {@code application.yml}; the mode gate makes that structural rather than a convention.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Hazelcast classes sit on the classpath unconditionally (a build-simplicity choice) — the
|
||||
* gating is done by the conditions above, not by keeping the jar off the path.
|
||||
*
|
||||
* <h2>Sessions</h2>
|
||||
* Backed by a Hazelcast {@code IMap<String, MapSession>} through the hand-rolled
|
||||
* {@link HazelcastSessionRepository} (the library {@code MapSessionRepository} is intentionally not used — see
|
||||
* that class). The map's {@code max-idle-seconds} is set from {@link RunwayClusterProperties#getSessionTtl()}
|
||||
* so Hazelcast evicts idle sessions itself.
|
||||
*
|
||||
* <p>The per-realm/per-site isolation is untouched: it lives as {@code HttpSession} attributes written by the
|
||||
* security layer's {@code HttpSession*} repositories, which a Hazelcast-backed session carries across the
|
||||
* cluster with no change to the security configuration.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnProperty(prefix = "runway.cluster", name = "enabled", havingValue = "true")
|
||||
@Conditional(ActiveModeCondition.class)
|
||||
@EnableConfigurationProperties(RunwayClusterProperties.class)
|
||||
@EnableSpringHttpSession
|
||||
public class ClusterConfig {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ClusterConfig.class);
|
||||
|
||||
/**
|
||||
* The Hazelcast instance for this node — an embedded member (default) or a client of an external cluster.
|
||||
* {@code destroyMethod="shutdown"} leaves the grid cleanly on context close.
|
||||
*/
|
||||
@Bean(destroyMethod = "shutdown")
|
||||
public HazelcastInstance hazelcastInstance(RunwayClusterProperties props) {
|
||||
return props.getTopology() == RunwayClusterProperties.Topology.CLIENT_SERVER
|
||||
? buildClient(props)
|
||||
: buildEmbedded(props);
|
||||
}
|
||||
|
||||
private HazelcastInstance buildEmbedded(RunwayClusterProperties props) {
|
||||
RunwayClusterProperties.Embedded embedded = props.getEmbedded();
|
||||
Config config = new Config().setClusterName(props.getClusterName());
|
||||
|
||||
NetworkConfig network = config.getNetworkConfig()
|
||||
.setPort(embedded.getPort())
|
||||
.setPortAutoIncrement(embedded.isPortAutoIncrement());
|
||||
JoinConfig join = network.getJoin();
|
||||
// Start from a clean slate — enable exactly the one requested mechanism.
|
||||
join.getAutoDetectionConfig().setEnabled(false);
|
||||
join.getMulticastConfig().setEnabled(false);
|
||||
join.getTcpIpConfig().setEnabled(false);
|
||||
switch (embedded.getDiscovery()) {
|
||||
case "tcp-ip" -> {
|
||||
join.getTcpIpConfig().setEnabled(true);
|
||||
embedded.getMembers().forEach(join.getTcpIpConfig()::addMember);
|
||||
}
|
||||
case "multicast" -> join.getMulticastConfig().setEnabled(true);
|
||||
default -> throw new IllegalArgumentException(
|
||||
"Unknown runway.cluster.embedded.discovery '" + embedded.getDiscovery()
|
||||
+ "' (expected 'tcp-ip' or 'multicast')");
|
||||
}
|
||||
|
||||
config.addMapConfig(sessionsMapConfig(props));
|
||||
log.info("Starting embedded Hazelcast member: cluster='{}', discovery={}, port={} (session TTL {})",
|
||||
props.getClusterName(), embedded.getDiscovery(), embedded.getPort(), props.getSessionTtl());
|
||||
return Hazelcast.newHazelcastInstance(config);
|
||||
}
|
||||
|
||||
private HazelcastInstance buildClient(RunwayClusterProperties props) {
|
||||
RunwayClusterProperties.Client client = props.getClient();
|
||||
if (client.getAddresses().isEmpty()) {
|
||||
throw new IllegalStateException(
|
||||
"runway.cluster.topology=CLIENT_SERVER requires runway.cluster.client.addresses to be non-empty");
|
||||
}
|
||||
ClientConfig config = new ClientConfig().setClusterName(props.getClusterName());
|
||||
config.getNetworkConfig().setSmartRouting(client.isSmartRouting());
|
||||
client.getAddresses().forEach(config.getNetworkConfig()::addAddress);
|
||||
log.info("Starting Hazelcast client: cluster='{}', addresses={} (session TTL {})",
|
||||
props.getClusterName(), client.getAddresses(), props.getSessionTtl());
|
||||
return HazelcastClient.newHazelcastClient(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* The sessions {@code IMap} config: {@code max-idle-seconds} = the configured session TTL (floored at 60s),
|
||||
* so Hazelcast evicts an idle session and the repository never sweeps. On a client this config is only a
|
||||
* hint unless the same map is declared server-side, so it is also applied to the embedded member above.
|
||||
*/
|
||||
private MapConfig sessionsMapConfig(RunwayClusterProperties props) {
|
||||
long ttlSeconds = Math.max(60, props.getSessionTtl().toSeconds());
|
||||
return new MapConfig(props.getSessionsMapName())
|
||||
.setMaxIdleSeconds((int) Math.min(ttlSeconds, Integer.MAX_VALUE));
|
||||
}
|
||||
|
||||
/**
|
||||
* The hand-rolled session repository over the distributed sessions map. {@link EnableSpringHttpSession}
|
||||
* wires the {@code springSessionRepositoryFilter} around it, at Spring Session's default order
|
||||
* ({@code Integer.MIN_VALUE + 50}) — inner of the kernel protection floor and outer of the security chain
|
||||
* (asserted by {@code FilterChainOrderTest}).
|
||||
*/
|
||||
@Bean
|
||||
public SessionRepository<MapSession> sessionRepository(HazelcastInstance hazelcast,
|
||||
RunwayClusterProperties props) {
|
||||
IMap<String, MapSession> sessions = hazelcast.getMap(props.getSessionsMapName());
|
||||
return new HazelcastSessionRepository(sessions, props.getSessionTtl());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package mx.quest.runway.cluster;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* The wire form of a cross-node cache-invalidation event, carried over the Hazelcast events topic by
|
||||
* {@link ClusterEventRelay}. One flat envelope covers all three relayed kinds — a site lifecycle change, a
|
||||
* per-tenant plugin-config change, and a page edit — so the topic carries a single {@code Serializable} type
|
||||
* with predictable round-trip.
|
||||
*
|
||||
* <p>Deliberately a hand-rolled POJO (no-arg constructor + getters/setters + a fixed {@code serialVersionUID}),
|
||||
* not a {@code record}: Hazelcast's default Java serializer round-trips a mutable JavaBean most predictably
|
||||
* across versions, and every field is a {@link String} or an enum for the same reason (the
|
||||
* {@code SiteChangedEvent.Kind} is carried as its {@link Enum#name() name} rather than the enum itself, so an
|
||||
* older node that lacks a newly-added kind fails to reconstruct that one event rather than to deserialize the
|
||||
* whole envelope). Only the fields relevant to a given {@link #getKind() kind} are set; the rest stay
|
||||
* {@code null}.
|
||||
*
|
||||
* <p>{@link #getOriginNodeId()} tags the node that first published the event, so the relay drops the
|
||||
* self-echo Hazelcast delivers back to the publisher (the mandatory loop guard).
|
||||
*/
|
||||
public class ClusterEventEnvelope implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* Which local {@code ApplicationEvent} this envelope carries across the cluster.
|
||||
*
|
||||
* <p><b>Rolling-upgrade note.</b> Adding a constant means an older node cannot deserialize <em>that
|
||||
* kind's</em> envelopes during a mixed-version window (Java enum deserialization is by name) — the
|
||||
* deserialization failure surfaces in <em>Hazelcast's</em> topic-listener machinery (logged there and the
|
||||
* message dropped; the relay's own malformed-envelope guard only covers envelopes that deserialized), and
|
||||
* the older node's caches converge via their TTLs. Acceptable pre-1.0 while clustering is opt-in and
|
||||
* default-OFF; upgrade all nodes of a cluster together.
|
||||
*/
|
||||
public enum Kind {
|
||||
/** A {@code site.SiteChangedEvent} — {@link #getSiteChangedKind()} + optional {@link #getTemplateId()}. */
|
||||
SITE_CHANGED,
|
||||
/** A {@code plugin.SitePluginConfigChangedEvent} — {@link #getSiteId()} + {@link #getPluginId()}. */
|
||||
SITE_PLUGIN_CONFIG_CHANGED,
|
||||
/** A {@code page.PageChangedEvent} — {@link #getSiteId()} + {@link #getSlug()} (slug nullable = whole site). */
|
||||
PAGE_CHANGED,
|
||||
/**
|
||||
* A {@code content.ContentChangedEvent} — {@link #getSiteId()} + {@link #getSourceKey()} +
|
||||
* {@link #getContentId()} (nullable ⇒ the source's whole corpus for the site).
|
||||
*/
|
||||
CONTENT_CHANGED
|
||||
}
|
||||
|
||||
private Kind kind;
|
||||
private String siteId;
|
||||
/** For {@link Kind#SITE_CHANGED}: the {@code SiteChangedEvent.Kind} name; otherwise {@code null}. */
|
||||
private String siteChangedKind;
|
||||
/** For {@link Kind#SITE_CHANGED}: the birth-only seed-template id (nullable); otherwise {@code null}. */
|
||||
private String templateId;
|
||||
/**
|
||||
* For {@link Kind#SITE_CHANGED}: whether a {@code CREATED} imports the site from a backup (so peers' birth-time
|
||||
* seeders stand down too — review m14a). Boxed on purpose: an envelope from a node that predates the field
|
||||
* deserializes with {@code null}, which reads as {@code false}; adding a field keeps Java serialization
|
||||
* compatible both ways, so the {@code serialVersionUID} is unchanged.
|
||||
*/
|
||||
private Boolean fromBackup;
|
||||
/** For {@link Kind#SITE_PLUGIN_CONFIG_CHANGED}: the plugin id; otherwise {@code null}. */
|
||||
private String pluginId;
|
||||
/** For {@link Kind#PAGE_CHANGED}: the page slug (nullable ⇒ whole site); otherwise {@code null}. */
|
||||
private String slug;
|
||||
/** For {@link Kind#CONTENT_CHANGED}: the content source's key; otherwise {@code null}. */
|
||||
private String sourceKey;
|
||||
/** For {@link Kind#CONTENT_CHANGED}: the content id (nullable ⇒ whole corpus); otherwise {@code null}. */
|
||||
private String contentId;
|
||||
/** The id of the node that first published this event — used to drop the self-echo. */
|
||||
private String originNodeId;
|
||||
|
||||
/** Required no-arg constructor for the Hazelcast Java serializer. */
|
||||
public ClusterEventEnvelope() {
|
||||
}
|
||||
|
||||
public ClusterEventEnvelope(Kind kind, String siteId, String siteChangedKind, String templateId,
|
||||
String pluginId, String slug, String originNodeId) {
|
||||
this.kind = kind;
|
||||
this.siteId = siteId;
|
||||
this.siteChangedKind = siteChangedKind;
|
||||
this.templateId = templateId;
|
||||
this.pluginId = pluginId;
|
||||
this.slug = slug;
|
||||
this.originNodeId = originNodeId;
|
||||
}
|
||||
|
||||
/** A {@link Kind#SITE_CHANGED} envelope that is not a backup import. */
|
||||
public static ClusterEventEnvelope siteChanged(String siteId, String siteChangedKind, String templateId,
|
||||
String originNodeId) {
|
||||
return siteChanged(siteId, siteChangedKind, templateId, false, originNodeId);
|
||||
}
|
||||
|
||||
/** A {@link Kind#SITE_CHANGED} envelope, carrying whether a {@code CREATED} imports the site from a backup. */
|
||||
public static ClusterEventEnvelope siteChanged(String siteId, String siteChangedKind, String templateId,
|
||||
boolean fromBackup, String originNodeId) {
|
||||
ClusterEventEnvelope env = new ClusterEventEnvelope(Kind.SITE_CHANGED, siteId, siteChangedKind, templateId,
|
||||
null, null, originNodeId);
|
||||
env.setFromBackup(fromBackup);
|
||||
return env;
|
||||
}
|
||||
|
||||
/** A {@link Kind#SITE_PLUGIN_CONFIG_CHANGED} envelope. */
|
||||
public static ClusterEventEnvelope sitePluginConfigChanged(String siteId, String pluginId,
|
||||
String originNodeId) {
|
||||
return new ClusterEventEnvelope(Kind.SITE_PLUGIN_CONFIG_CHANGED, siteId, null, null, pluginId, null,
|
||||
originNodeId);
|
||||
}
|
||||
|
||||
/** A {@link Kind#PAGE_CHANGED} envelope. */
|
||||
public static ClusterEventEnvelope pageChanged(String siteId, String slug, String originNodeId) {
|
||||
return new ClusterEventEnvelope(Kind.PAGE_CHANGED, siteId, null, null, null, slug, originNodeId);
|
||||
}
|
||||
|
||||
/** A {@link Kind#CONTENT_CHANGED} envelope ({@code contentId} nullable ⇒ the source's whole corpus). */
|
||||
public static ClusterEventEnvelope contentChanged(String siteId, String sourceKey, String contentId,
|
||||
String originNodeId) {
|
||||
ClusterEventEnvelope env = new ClusterEventEnvelope(Kind.CONTENT_CHANGED, siteId, null, null, null, null,
|
||||
originNodeId);
|
||||
env.setSourceKey(sourceKey);
|
||||
env.setContentId(contentId);
|
||||
return env;
|
||||
}
|
||||
|
||||
public Kind getKind() {
|
||||
return kind;
|
||||
}
|
||||
|
||||
public void setKind(Kind kind) {
|
||||
this.kind = kind;
|
||||
}
|
||||
|
||||
public String getSiteId() {
|
||||
return siteId;
|
||||
}
|
||||
|
||||
public void setSiteId(String siteId) {
|
||||
this.siteId = siteId;
|
||||
}
|
||||
|
||||
public String getSiteChangedKind() {
|
||||
return siteChangedKind;
|
||||
}
|
||||
|
||||
public void setSiteChangedKind(String siteChangedKind) {
|
||||
this.siteChangedKind = siteChangedKind;
|
||||
}
|
||||
|
||||
public String getTemplateId() {
|
||||
return templateId;
|
||||
}
|
||||
|
||||
public void setTemplateId(String templateId) {
|
||||
this.templateId = templateId;
|
||||
}
|
||||
|
||||
/** {@code null} on an envelope from a node that predates the field (read it as {@code false}). */
|
||||
public Boolean getFromBackup() {
|
||||
return fromBackup;
|
||||
}
|
||||
|
||||
public void setFromBackup(Boolean fromBackup) {
|
||||
this.fromBackup = fromBackup;
|
||||
}
|
||||
|
||||
public String getPluginId() {
|
||||
return pluginId;
|
||||
}
|
||||
|
||||
public void setPluginId(String pluginId) {
|
||||
this.pluginId = pluginId;
|
||||
}
|
||||
|
||||
public String getSlug() {
|
||||
return slug;
|
||||
}
|
||||
|
||||
public void setSlug(String slug) {
|
||||
this.slug = slug;
|
||||
}
|
||||
|
||||
public String getSourceKey() {
|
||||
return sourceKey;
|
||||
}
|
||||
|
||||
public void setSourceKey(String sourceKey) {
|
||||
this.sourceKey = sourceKey;
|
||||
}
|
||||
|
||||
public String getContentId() {
|
||||
return contentId;
|
||||
}
|
||||
|
||||
public void setContentId(String contentId) {
|
||||
this.contentId = contentId;
|
||||
}
|
||||
|
||||
public String getOriginNodeId() {
|
||||
return originNodeId;
|
||||
}
|
||||
|
||||
public void setOriginNodeId(String originNodeId) {
|
||||
this.originNodeId = originNodeId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package mx.quest.runway.cluster;
|
||||
|
||||
import com.hazelcast.core.HazelcastInstance;
|
||||
import com.hazelcast.topic.ITopic;
|
||||
import com.hazelcast.topic.Message;
|
||||
import com.hazelcast.topic.MessageListener;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import java.util.UUID;
|
||||
import mx.quest.runway.content.ContentChangedEvent;
|
||||
import mx.quest.runway.event.ClusterReplay;
|
||||
import mx.quest.runway.event.KernelEventOrder;
|
||||
import mx.quest.runway.page.PageChangedEvent;
|
||||
import mx.quest.runway.plugin.SitePluginConfigChangedEvent;
|
||||
import mx.quest.runway.site.SiteChangedEvent;
|
||||
import mx.quest.runway.wizard.ActiveModeCondition;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.context.annotation.Conditional;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* The bidirectional bridge that turns the kernel's <b>local</b> cache-invalidation events into <b>cluster-wide</b>
|
||||
* ones. Each node runs one relay:
|
||||
*
|
||||
* <ul>
|
||||
* <li>on a local {@link SiteChangedEvent} / {@link SitePluginConfigChangedEvent} / {@link PageChangedEvent} /
|
||||
* {@link ContentChangedEvent}, it publishes a tagged {@link ClusterEventEnvelope} to the Hazelcast events
|
||||
* topic;</li>
|
||||
* <li>on a topic message from <b>another</b> node, it re-fires the equivalent local event through the Spring
|
||||
* {@link ApplicationEventPublisher}, so every existing local {@code @EventListener} (per-site cache
|
||||
* evictors, host-index, message source, the page-cache listener, …) evicts on this node too.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Why a relay rather than a cluster-aware cache</h2>
|
||||
* The kernel's caches are deliberately plain per-JVM Caffeine/{@code StoreCache}s driven by Spring events; a
|
||||
* single-node deployment carries zero clustering machinery. Rather than replace those with distributed maps
|
||||
* (which would tax the common single-node case), clustering is added as an <em>edge</em>: this relay rebroadcasts
|
||||
* the same events across nodes and replays them locally. The eviction logic lives in exactly one place (the
|
||||
* local listeners) and is exercised identically whether the trigger was a local write or a peer's broadcast.
|
||||
*
|
||||
* <h2>Echo-loop guard (mandatory)</h2>
|
||||
* Hazelcast delivers a published message back to the publisher too. Two defences stop an infinite rebroadcast:
|
||||
* <ol>
|
||||
* <li>every envelope carries {@link ClusterEventEnvelope#getOriginNodeId() originNodeId}; a message whose
|
||||
* origin is this node is dropped on arrival (the primary guard);</li>
|
||||
* <li>when a <em>received</em> message is replayed locally, {@link ClusterReplay} marks the thread as replaying
|
||||
* a peer's event, so this relay's own {@code @EventListener}s see the replayed local event and do <b>not</b>
|
||||
* rebroadcast it (belt-and-braces, and it also covers the theoretical case of two nodes sharing an id). The
|
||||
* same mark is what plugin listeners receive as {@code local == false}.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <h2>Gating</h2>
|
||||
* The bean exists only when clustering is on and the platform is ACTIVE — the same two gates as
|
||||
* {@link ClusterConfig} (it depends on that config's {@link HazelcastInstance}). With clustering off (the
|
||||
* default) there is no relay: {@link PageChangedEvent} and the others still drive purely local eviction (correct
|
||||
* single-node behaviour) and nothing is broadcast.
|
||||
*/
|
||||
@Component
|
||||
@ConditionalOnProperty(prefix = "runway.cluster", name = "enabled", havingValue = "true")
|
||||
@Conditional(ActiveModeCondition.class)
|
||||
public class ClusterEventRelay {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ClusterEventRelay.class);
|
||||
|
||||
private final HazelcastInstance hz;
|
||||
private final ApplicationEventPublisher events;
|
||||
private final String eventsTopicName;
|
||||
private final String localNodeId;
|
||||
|
||||
private ITopic<ClusterEventEnvelope> topic;
|
||||
private UUID subscriptionId;
|
||||
|
||||
public ClusterEventRelay(HazelcastInstance hz, ApplicationEventPublisher events,
|
||||
RunwayClusterProperties props) {
|
||||
this.hz = hz;
|
||||
this.events = events;
|
||||
this.eventsTopicName = props.getEventsTopicName();
|
||||
this.localNodeId = hz.getLocalEndpoint().getUuid().toString();
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
void subscribe() {
|
||||
this.topic = hz.getTopic(eventsTopicName);
|
||||
this.subscriptionId = topic.addMessageListener(new TopicListener());
|
||||
log.info("Cluster event relay active: node={}, topic={}", localNodeId, eventsTopicName);
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
void unsubscribe() {
|
||||
if (topic != null && subscriptionId != null) {
|
||||
topic.removeMessageListener(subscriptionId);
|
||||
}
|
||||
}
|
||||
|
||||
// --- local event → topic (skip when the event is itself a replay of a received message) --------------
|
||||
|
||||
@EventListener
|
||||
@Order(KernelEventOrder.RELAY)
|
||||
public void onSiteChanged(SiteChangedEvent e) {
|
||||
if (ClusterReplay.active()) {
|
||||
return;
|
||||
}
|
||||
topic.publish(ClusterEventEnvelope.siteChanged(e.siteId(), e.kind().name(), e.templateId(), e.fromBackup(),
|
||||
localNodeId));
|
||||
}
|
||||
|
||||
@EventListener
|
||||
@Order(KernelEventOrder.RELAY)
|
||||
public void onSitePluginConfigChanged(SitePluginConfigChangedEvent e) {
|
||||
if (ClusterReplay.active()) {
|
||||
return;
|
||||
}
|
||||
topic.publish(ClusterEventEnvelope.sitePluginConfigChanged(e.siteId(), e.pluginId(), localNodeId));
|
||||
}
|
||||
|
||||
@EventListener
|
||||
@Order(KernelEventOrder.RELAY)
|
||||
public void onPageChanged(PageChangedEvent e) {
|
||||
if (ClusterReplay.active()) {
|
||||
return;
|
||||
}
|
||||
topic.publish(ClusterEventEnvelope.pageChanged(e.siteId(), e.slug(), localNodeId));
|
||||
}
|
||||
|
||||
@EventListener
|
||||
@Order(KernelEventOrder.RELAY)
|
||||
public void onContentChanged(ContentChangedEvent e) {
|
||||
if (ClusterReplay.active()) {
|
||||
return;
|
||||
}
|
||||
topic.publish(ClusterEventEnvelope.contentChanged(e.siteId(), e.sourceKey(), e.id(), localNodeId));
|
||||
}
|
||||
|
||||
// --- topic message → local event ---------------------------------------------------------------------
|
||||
|
||||
private final class TopicListener implements MessageListener<ClusterEventEnvelope> {
|
||||
@Override
|
||||
public void onMessage(Message<ClusterEventEnvelope> message) {
|
||||
handleClusterMessage(message.getMessageObject());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replays a received envelope as its local event so this node's listeners evict — unless it is our own echo.
|
||||
* Package-visible so a Mockito unit test can drive the receive path without a live Hazelcast grid.
|
||||
*
|
||||
* <p>The replay runs under {@link ClusterReplay} — set for the duration of the local re-publish and cleared in a
|
||||
* {@code finally} — so this relay's own {@code @EventListener}s (above) do not rebroadcast the replayed event, and
|
||||
* every plugin {@code SiteEventListener} receives it with {@code local == false}. A malformed envelope (e.g. an
|
||||
* unknown {@code SiteChangedEvent.Kind} name from a newer node) is logged and dropped rather than allowed to break
|
||||
* the topic listener. An envelope from a node that predates {@code fromBackup} carries {@code null} there, read
|
||||
* as {@code false}.
|
||||
*/
|
||||
void handleClusterMessage(ClusterEventEnvelope env) {
|
||||
if (localNodeId.equals(env.getOriginNodeId())) {
|
||||
return; // self-echo — the local listeners already evicted when the event was first published here
|
||||
}
|
||||
try {
|
||||
ClusterReplay.run(() -> replay(env));
|
||||
} catch (RuntimeException ex) {
|
||||
log.warn("Dropping malformed cluster event {} from node {}: {}", env.getKind(),
|
||||
env.getOriginNodeId(), ex.toString());
|
||||
}
|
||||
}
|
||||
|
||||
private void replay(ClusterEventEnvelope env) {
|
||||
switch (env.getKind()) {
|
||||
case SITE_CHANGED -> events.publishEvent(new SiteChangedEvent(env.getSiteId(),
|
||||
SiteChangedEvent.Kind.valueOf(env.getSiteChangedKind()), env.getTemplateId(),
|
||||
Boolean.TRUE.equals(env.getFromBackup())));
|
||||
case SITE_PLUGIN_CONFIG_CHANGED ->
|
||||
events.publishEvent(new SitePluginConfigChangedEvent(env.getSiteId(), env.getPluginId()));
|
||||
case PAGE_CHANGED -> events.publishEvent(new PageChangedEvent(env.getSiteId(), env.getSlug()));
|
||||
case CONTENT_CHANGED -> events.publishEvent(new ContentChangedEvent(env.getSiteId(),
|
||||
env.getSourceKey(), env.getContentId()));
|
||||
}
|
||||
}
|
||||
|
||||
/** Package-visible for unit tests. */
|
||||
String localNodeId() {
|
||||
return localNodeId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package mx.quest.runway.cluster;
|
||||
|
||||
import com.hazelcast.map.IMap;
|
||||
import java.time.Duration;
|
||||
import org.springframework.session.MapSession;
|
||||
import org.springframework.session.SessionRepository;
|
||||
|
||||
/**
|
||||
* A hand-rolled {@link SessionRepository} over a Hazelcast {@link IMap}{@code <String, MapSession>} — Spring
|
||||
* Session's persistence contract, backed by the distributed grid rather than one JVM's heap.
|
||||
*
|
||||
* <h2>Why hand-rolled</h2>
|
||||
* {@code spring-session-hazelcast} was dropped from Spring Session 4.x; the library's
|
||||
* own {@link org.springframework.session.MapSessionRepository} is deliberately <em>not</em> reused either,
|
||||
* because it is typed to a plain {@code Map<String, Session>} and its semantics (defensive copies, expiry
|
||||
* handling, id-change on {@code save}) are simple enough to own directly against the typed {@code IMap}. Keep
|
||||
* the Spring Session API, roll the repository — the pattern for any dropped backend.
|
||||
*
|
||||
* <h2>How a {@link MapSession} lives in the grid</h2>
|
||||
* {@link MapSession} is {@link java.io.Serializable}, so it round-trips through the {@code IMap}'s default Java
|
||||
* serializer with no custom {@code DataSerializable}/portable code. The attributes it carries — Spring
|
||||
* Security's {@code SecurityContext} and the CSRF token, written under the realm/site-scoped keys — must
|
||||
* therefore be serializable too; {@code security.User} and {@code security.RunwayUserDetails} are made
|
||||
* {@link java.io.Serializable} for exactly this reason (the rest of the chain — {@code SecurityContextImpl},
|
||||
* {@code UsernamePasswordAuthenticationToken}, {@code SimpleGrantedAuthority}, {@code DefaultCsrfToken} — is
|
||||
* already serializable).
|
||||
*
|
||||
* <h2>Semantics</h2>
|
||||
* <ul>
|
||||
* <li><b>Defensive copies.</b> {@link #save} stores a {@code new MapSession(session)} copy and {@link
|
||||
* #findById} returns one, so a caller mutating the object it holds never silently changes the stored
|
||||
* entry — only an explicit {@link #save} persists. (In EMBEDDED mode a get could otherwise hand back a
|
||||
* reference into local heap.)</li>
|
||||
* <li><b>Id change.</b> Spring Security rotates the session id on login (session-fixation defense); when the
|
||||
* id differs from the original, the old key is removed so the map is not left with a stale duplicate.</li>
|
||||
* <li><b>Expiry.</b> {@link #findById} treats an expired entry as absent — it deletes it and returns {@code
|
||||
* null}. Hazelcast also evicts idle entries via the map's {@code max-idle-seconds} (set from {@link
|
||||
* RunwayClusterProperties#getSessionTtl()} in {@link ClusterConfig}), so this is a belt-and-braces
|
||||
* read-time check, not the primary sweeper.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Wired only when {@code runway.cluster.enabled=true}; in the single-node default this class is never
|
||||
* instantiated and the container's {@code HttpSession} is used unchanged.
|
||||
*/
|
||||
final class HazelcastSessionRepository implements SessionRepository<MapSession> {
|
||||
|
||||
private final IMap<String, MapSession> sessions;
|
||||
private final Duration sessionTtl;
|
||||
|
||||
/**
|
||||
* @param sessions the distributed session map (never {@code null})
|
||||
* @param sessionTtl the default max-inactive-interval stamped onto a newly created session (never {@code
|
||||
* null}); the same value seeds the map's {@code max-idle-seconds} in {@link ClusterConfig}
|
||||
*/
|
||||
HazelcastSessionRepository(IMap<String, MapSession> sessions, Duration sessionTtl) {
|
||||
this.sessions = sessions;
|
||||
this.sessionTtl = sessionTtl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MapSession createSession() {
|
||||
MapSession created = new MapSession();
|
||||
created.setMaxInactiveInterval(sessionTtl);
|
||||
return created;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(MapSession session) {
|
||||
if (!session.getId().equals(session.getOriginalId())) {
|
||||
sessions.remove(session.getOriginalId());
|
||||
}
|
||||
sessions.put(session.getId(), new MapSession(session));
|
||||
}
|
||||
|
||||
@Override
|
||||
public MapSession findById(String id) {
|
||||
MapSession saved = sessions.get(id);
|
||||
if (saved == null) {
|
||||
return null;
|
||||
}
|
||||
if (saved.isExpired()) {
|
||||
deleteById(saved.getId());
|
||||
return null;
|
||||
}
|
||||
return new MapSession(saved);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteById(String id) {
|
||||
sessions.remove(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package mx.quest.runway.cluster;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.context.properties.NestedConfigurationProperty;
|
||||
|
||||
/**
|
||||
* Bound {@code runway.cluster.*} configuration — <b>opt-in horizontal clustering</b>. Default OFF, which is
|
||||
* today's single-node footprint exactly: with {@link #enabled} {@code false} no Hazelcast member starts, no
|
||||
* session repository is wired, and the container's own {@code HttpSession} is used — <b>zero overhead when
|
||||
* off</b> (see {@link ClusterConfig}, gated at the class level).
|
||||
*
|
||||
* <p>When enabled, sessions move into a Hazelcast {@code IMap<String, MapSession>} shared by every node, so a
|
||||
* request may be served by any node behind the load balancer and still see the same authenticated principal.
|
||||
* The per-realm / per-site isolation the kernel already implements needs <b>no</b> change: it lives as
|
||||
* {@code HttpSession} attributes written by Spring Security's {@code HttpSession*} repositories under custom
|
||||
* keys ({@code AppSecurityConfig} / {@code TenantSecurityConfig} / the {@code SiteScoped*} repositories), so a
|
||||
* Hazelcast-backed session carries those attributes across the cluster for free.
|
||||
*
|
||||
* <h2>Topology</h2>
|
||||
* <ul>
|
||||
* <li>{@link Topology#EMBEDDED} (default) — each Runway JVM is itself a Hazelcast member, joining via
|
||||
* {@link Embedded#getDiscovery()} (tcp-ip with an explicit member list is the recommended production
|
||||
* shape). No external process to run.</li>
|
||||
* <li>{@link Topology#CLIENT_SERVER} — Runway connects as a Hazelcast <em>client</em> to a separately-run
|
||||
* Hazelcast cluster at {@link Client#getAddresses()}. Chosen when the data grid is operated apart from
|
||||
* the app tier.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Session TTL</h2>
|
||||
* {@link #getSessionTtl()} (default 30 minutes — the same as today's container default, so enabling clustering
|
||||
* changes no timeout behaviour) feeds the sessions {@code IMap}'s {@code max-idle-seconds}, so Hazelcast evicts
|
||||
* an idle session itself and the repository never has to sweep. It should match
|
||||
* {@code server.servlet.session.timeout} in {@code application.yml}, which is the container's own view of the
|
||||
* same value.
|
||||
*/
|
||||
@ConfigurationProperties("runway.cluster")
|
||||
public class RunwayClusterProperties {
|
||||
|
||||
/** Discovery / connection topology for the Hazelcast layer. */
|
||||
public enum Topology {
|
||||
/** Each Runway JVM is a Hazelcast member (default — no external grid to run). */
|
||||
EMBEDDED,
|
||||
/** Runway is a Hazelcast client of a separately-operated cluster. */
|
||||
CLIENT_SERVER
|
||||
}
|
||||
|
||||
/**
|
||||
* Master switch. Default {@code false} — the single-node deployment: no Hazelcast, no Spring Session, the
|
||||
* container's {@code HttpSession} is used exactly as today. Only ever set {@code true} in the external,
|
||||
* post-wizard {@code application.yml} (clustering is meaningless in first-run WIZARD mode).
|
||||
*/
|
||||
private boolean enabled = false;
|
||||
|
||||
/** The Hazelcast cluster name — members/clients only join peers sharing it. Default {@code "runway"}. */
|
||||
private String clusterName = "runway";
|
||||
|
||||
/** The topology: {@link Topology#EMBEDDED} (default) or {@link Topology#CLIENT_SERVER}. */
|
||||
private Topology topology = Topology.EMBEDDED;
|
||||
|
||||
@NestedConfigurationProperty
|
||||
private final Embedded embedded = new Embedded();
|
||||
|
||||
@NestedConfigurationProperty
|
||||
private final Client client = new Client();
|
||||
|
||||
/** The name of the distributed map holding sessions. Default {@code "runway.sessions"}. */
|
||||
private String sessionsMapName = "runway.sessions";
|
||||
|
||||
/**
|
||||
* The name of the distributed topic used to relay cross-node cache-invalidation events. The
|
||||
* {@code cluster.ClusterEventRelay} subscribes to it and bridges local Spring {@code ApplicationEvent}s
|
||||
* ({@code SiteChangedEvent}, {@code SitePluginConfigChangedEvent}, {@code PageChangedEvent}) across the
|
||||
* cluster, so an edit on one node evicts the matching cache on every node. Default {@code "runway.events"}.
|
||||
*/
|
||||
private String eventsTopicName = "runway.events";
|
||||
|
||||
/**
|
||||
* The session time-to-live. Sourced onto the sessions {@code IMap}'s {@code max-idle-seconds} so an idle
|
||||
* session is evicted by Hazelcast. Default 30 minutes — matches today's container default, so enabling
|
||||
* clustering does not change session lifetime. Keep it in step with {@code server.servlet.session.timeout}.
|
||||
*/
|
||||
private Duration sessionTtl = Duration.ofMinutes(30);
|
||||
|
||||
/** Embedded-topology settings — how this JVM's Hazelcast member discovers its peers. */
|
||||
public static class Embedded {
|
||||
|
||||
/**
|
||||
* The member discovery mechanism. {@code "tcp-ip"} (default — an explicit {@link #members} list, the
|
||||
* recommended production shape) or {@code "multicast"} (convenient for a same-subnet dev cluster).
|
||||
*/
|
||||
private String discovery = "tcp-ip";
|
||||
|
||||
/** Explicit peer addresses for {@code tcp-ip} discovery, e.g. {@code ["10.0.0.1:5701","10.0.0.2:5701"]}. */
|
||||
private List<String> members = new ArrayList<>();
|
||||
|
||||
/** The port this member binds. Default 5701 (Hazelcast's default). */
|
||||
private int port = 5701;
|
||||
|
||||
/** Whether to try the next port when {@link #port} is taken (lets several members share one host). */
|
||||
private boolean portAutoIncrement = true;
|
||||
|
||||
public String getDiscovery() {
|
||||
return discovery;
|
||||
}
|
||||
|
||||
public void setDiscovery(String discovery) {
|
||||
this.discovery = discovery;
|
||||
}
|
||||
|
||||
public List<String> getMembers() {
|
||||
return members;
|
||||
}
|
||||
|
||||
public void setMembers(List<String> members) {
|
||||
this.members = members;
|
||||
}
|
||||
|
||||
public int getPort() {
|
||||
return port;
|
||||
}
|
||||
|
||||
public void setPort(int port) {
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
public boolean isPortAutoIncrement() {
|
||||
return portAutoIncrement;
|
||||
}
|
||||
|
||||
public void setPortAutoIncrement(boolean portAutoIncrement) {
|
||||
this.portAutoIncrement = portAutoIncrement;
|
||||
}
|
||||
}
|
||||
|
||||
/** Client-server-topology settings — how this JVM connects, as a client, to an external Hazelcast cluster. */
|
||||
public static class Client {
|
||||
|
||||
/** The cluster member addresses to connect to, e.g. {@code ["hz1.internal:5701","hz2.internal:5701"]}. */
|
||||
private List<String> addresses = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Whether the client routes each operation straight to the member owning the partition (smart routing,
|
||||
* the default and best throughput). Turn off only for a unisocket client behind a restrictive firewall.
|
||||
*/
|
||||
private boolean smartRouting = true;
|
||||
|
||||
public List<String> getAddresses() {
|
||||
return addresses;
|
||||
}
|
||||
|
||||
public void setAddresses(List<String> addresses) {
|
||||
this.addresses = addresses;
|
||||
}
|
||||
|
||||
public boolean isSmartRouting() {
|
||||
return smartRouting;
|
||||
}
|
||||
|
||||
public void setSmartRouting(boolean smartRouting) {
|
||||
this.smartRouting = smartRouting;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public String getClusterName() {
|
||||
return clusterName;
|
||||
}
|
||||
|
||||
public void setClusterName(String clusterName) {
|
||||
this.clusterName = clusterName;
|
||||
}
|
||||
|
||||
public Topology getTopology() {
|
||||
return topology;
|
||||
}
|
||||
|
||||
public void setTopology(Topology topology) {
|
||||
this.topology = topology;
|
||||
}
|
||||
|
||||
public Embedded getEmbedded() {
|
||||
return embedded;
|
||||
}
|
||||
|
||||
public Client getClient() {
|
||||
return client;
|
||||
}
|
||||
|
||||
public String getSessionsMapName() {
|
||||
return sessionsMapName;
|
||||
}
|
||||
|
||||
public void setSessionsMapName(String sessionsMapName) {
|
||||
this.sessionsMapName = sessionsMapName;
|
||||
}
|
||||
|
||||
public String getEventsTopicName() {
|
||||
return eventsTopicName;
|
||||
}
|
||||
|
||||
public void setEventsTopicName(String eventsTopicName) {
|
||||
this.eventsTopicName = eventsTopicName;
|
||||
}
|
||||
|
||||
public Duration getSessionTtl() {
|
||||
return sessionTtl;
|
||||
}
|
||||
|
||||
public void setSessionTtl(Duration sessionTtl) {
|
||||
this.sessionTtl = sessionTtl;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import mx.quest.runway.authz.AuthorizationAdminService;
|
||||
import mx.quest.runway.authz.Permission;
|
||||
import mx.quest.runway.authz.PermissionCatalog;
|
||||
import mx.quest.runway.security.RunwayUserDetails;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* The permissions-matrix surface, shared by both realms. The screen lists users with their roles + direct
|
||||
* grants and the assignable roles with their plugin-permission deltas; every write goes through
|
||||
* {@link AuthorizationAdminService} (bounded-grant), never the stores directly.
|
||||
*
|
||||
* <p><b>The matrix realm is fixed by the logged-in actor, not a path argument</b> (the load-bearing 9g
|
||||
* constraint). A subclass supplies its realm and scope: the tenant matrix ({@code /__admin/permissions}) is
|
||||
* driven by a TENANT principal over the bound tenancy; the application matrix ({@code /__app/permissions}) by an
|
||||
* APPLICATION principal with no tenancy. Because {@code AuthorizationAdminService} derives the store scope from
|
||||
* {@code actor.realm()}, and the two routes live on the two never-crossing security chains, an application
|
||||
* operator can <b>never</b> drive a tenant's matrix and vice versa — cross-realm editing is impossible by
|
||||
* construction.
|
||||
*/
|
||||
public abstract class AbstractPermissionsController {
|
||||
|
||||
protected final PermissionsMatrixService matrix;
|
||||
protected final AuthorizationAdminService admin;
|
||||
protected final PermissionCatalog catalog;
|
||||
|
||||
protected AbstractPermissionsController(PermissionsMatrixService matrix, AuthorizationAdminService admin,
|
||||
PermissionCatalog catalog) {
|
||||
this.matrix = matrix;
|
||||
this.admin = admin;
|
||||
this.catalog = catalog;
|
||||
}
|
||||
|
||||
/** The realm this controller serves (the same realm as its principals). */
|
||||
protected abstract Realm realm();
|
||||
|
||||
/** The bound tenancy id ({@code null} for the application realm). */
|
||||
protected abstract String tenancyId();
|
||||
|
||||
/** The route prefix (for redirects after an action). */
|
||||
protected abstract String basePath();
|
||||
|
||||
/** The content template name for the matrix screen. */
|
||||
protected abstract String contentTemplate();
|
||||
|
||||
/** The i18n title key. */
|
||||
protected abstract String titleKey();
|
||||
|
||||
/**
|
||||
* Fails closed unless the caller may administer this scope. The whole matrix (every user's roles + grants)
|
||||
* is sensitive, so the <b>read</b> view is gated too, not only the mutations — a read-mostly operator must
|
||||
* not enumerate the realm's authorization. The subclass supplies the realm-correct gate
|
||||
* ({@code PlatformAuthority} / {@code TenantAuthority}).
|
||||
*/
|
||||
protected abstract void requireAdmin(Authentication authentication);
|
||||
|
||||
@GetMapping
|
||||
public String view(Model model, Authentication authentication) {
|
||||
requireAdmin(authentication);
|
||||
model.addAttribute("matrix", matrix.build(realm(), tenancyId()));
|
||||
model.addAttribute("permBase", basePath()); // the realm-specific action prefix the forms post to
|
||||
model.addAttribute("contentTemplate", contentTemplate());
|
||||
model.addAttribute("pageTitleKey", titleKey());
|
||||
return "operator/op-layout";
|
||||
}
|
||||
|
||||
@PostMapping("/assign-role")
|
||||
public String assignRole(@RequestParam String targetId, @RequestParam String roleName,
|
||||
Authentication authentication, RedirectAttributes redirect) {
|
||||
return apply(redirect, "Assigned role '" + roleName + "'.",
|
||||
() -> admin.assignRole(actor(authentication), tenancyId(), targetId, roleName),
|
||||
authentication, "permissions.role-assigned", "user=" + targetId + " role=" + roleName);
|
||||
}
|
||||
|
||||
@PostMapping("/revoke-role")
|
||||
public String revokeRole(@RequestParam String targetId, @RequestParam String roleName,
|
||||
Authentication authentication, RedirectAttributes redirect) {
|
||||
return apply(redirect, "Revoked role '" + roleName + "'.",
|
||||
() -> admin.revokeRole(actor(authentication), tenancyId(), targetId, roleName),
|
||||
authentication, "permissions.role-revoked", "user=" + targetId + " role=" + roleName);
|
||||
}
|
||||
|
||||
@PostMapping("/grant-permission")
|
||||
public String grantPermission(@RequestParam String targetId, @RequestParam String permission,
|
||||
Authentication authentication, RedirectAttributes redirect) {
|
||||
Permission resolved = permission(permission);
|
||||
return apply(redirect, "Granted permission '" + resolved.key() + "'.",
|
||||
() -> admin.grantPermission(actor(authentication), tenancyId(), targetId, resolved),
|
||||
authentication, "permissions.permission-granted",
|
||||
"user=" + targetId + " permission=" + resolved.key());
|
||||
}
|
||||
|
||||
@PostMapping("/revoke-permission")
|
||||
public String revokePermission(@RequestParam String targetId, @RequestParam String permission,
|
||||
Authentication authentication, RedirectAttributes redirect) {
|
||||
Permission resolved = permission(permission);
|
||||
return apply(redirect, "Revoked permission '" + resolved.key() + "'.",
|
||||
() -> admin.revokePermission(actor(authentication), tenancyId(), targetId, resolved),
|
||||
authentication, "permissions.permission-revoked",
|
||||
"user=" + targetId + " permission=" + resolved.key());
|
||||
}
|
||||
|
||||
@PostMapping("/role-grant")
|
||||
public String roleGrant(@RequestParam String roleName, @RequestParam String permission,
|
||||
Authentication authentication, RedirectAttributes redirect) {
|
||||
Permission resolved = permission(permission);
|
||||
return apply(redirect, "Granted '" + resolved.key() + "' to role '" + roleName + "'.",
|
||||
() -> admin.grantToRole(actor(authentication), tenancyId(), roleName, resolved),
|
||||
authentication, "permissions.role-permission-granted",
|
||||
"role=" + roleName + " permission=" + resolved.key());
|
||||
}
|
||||
|
||||
@PostMapping("/role-revoke")
|
||||
public String roleRevoke(@RequestParam String roleName, @RequestParam String permission,
|
||||
Authentication authentication, RedirectAttributes redirect) {
|
||||
Permission resolved = permission(permission);
|
||||
return apply(redirect, "Revoked '" + resolved.key() + "' from role '" + roleName + "'.",
|
||||
() -> admin.revokeFromRole(actor(authentication), tenancyId(), roleName, resolved),
|
||||
authentication, "permissions.role-permission-revoked",
|
||||
"role=" + roleName + " permission=" + resolved.key());
|
||||
}
|
||||
|
||||
// --- custom-role definition + DAG hierarchy (administrators only) ------------------------
|
||||
|
||||
/**
|
||||
* Creates a custom role. {@code name} is required; {@code inherits} (repeatable) seeds optional initial
|
||||
* inherit edges to existing custom roles. Delegates to {@link AuthorizationAdminService#createRole}, which
|
||||
* validates the name (unique, well-formed, not reserved) and re-validates the graph (seal/refs/cycle) before
|
||||
* persisting — a malformed or clashing name comes back as a flash error, never a 500.
|
||||
*/
|
||||
@PostMapping("/create-role")
|
||||
public String createRole(@RequestParam String name,
|
||||
@RequestParam(name = "inherits", required = false) java.util.List<String> inherits,
|
||||
Authentication authentication, RedirectAttributes redirect) {
|
||||
requireAdmin(authentication); // gate the mutation at the request level (403), like the read view
|
||||
java.util.Set<String> parents = inherits == null ? java.util.Set.of() : new java.util.LinkedHashSet<>(inherits);
|
||||
return apply(redirect, "Created role '" + name + "'.",
|
||||
() -> admin.createRole(actor(authentication), tenancyId(), name, java.util.Set.of(), parents),
|
||||
authentication, "permissions.role-created",
|
||||
"role=" + name + (parents.isEmpty() ? "" : " inherits=" + String.join(",", parents)));
|
||||
}
|
||||
|
||||
/** Deletes a custom role (reserved roles and still-inherited roles are rejected by the service). */
|
||||
@PostMapping("/delete-role")
|
||||
public String deleteRole(@RequestParam String roleName,
|
||||
Authentication authentication, RedirectAttributes redirect) {
|
||||
requireAdmin(authentication);
|
||||
return apply(redirect, "Deleted role '" + roleName + "'.",
|
||||
() -> admin.deleteRole(actor(authentication), tenancyId(), roleName),
|
||||
authentication, "permissions.role-deleted", "role=" + roleName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an inherit edge {@code roleName → parentName} to the role DAG. The service re-validates through the
|
||||
* cycle-checked graph, so a would-be cycle is rejected with a clean flash message (never bypassed here).
|
||||
*/
|
||||
@PostMapping("/add-inherit")
|
||||
public String addInherit(@RequestParam String roleName, @RequestParam String parentName,
|
||||
Authentication authentication, RedirectAttributes redirect) {
|
||||
requireAdmin(authentication);
|
||||
return apply(redirect, "Added inherit '" + roleName + "' → '" + parentName + "'.",
|
||||
() -> admin.addRoleInherit(actor(authentication), tenancyId(), roleName, parentName),
|
||||
authentication, "permissions.role-inherit-added", "role=" + roleName + " inherits=" + parentName);
|
||||
}
|
||||
|
||||
/** Removes an inherit edge {@code roleName → parentName} from the role DAG (idempotent). */
|
||||
@PostMapping("/remove-inherit")
|
||||
public String removeInherit(@RequestParam String roleName, @RequestParam String parentName,
|
||||
Authentication authentication, RedirectAttributes redirect) {
|
||||
requireAdmin(authentication);
|
||||
return apply(redirect, "Removed inherit '" + roleName + "' → '" + parentName + "'.",
|
||||
() -> admin.removeRoleInherit(actor(authentication), tenancyId(), roleName, parentName),
|
||||
authentication, "permissions.role-inherit-removed",
|
||||
"role=" + roleName + " inherits=" + parentName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Records one <b>successful</b> matrix change to this realm's audit journal — the application activity log
|
||||
* for the application matrix, the bound site's audit log for a tenant matrix. Called after the change was
|
||||
* persisted, never for a rejected one (a refused grant changed nothing, and the actor already saw the error).
|
||||
*
|
||||
* @param actor the signed-in principal's username
|
||||
* @param action the stable {@code permissions.*} action key
|
||||
* @param detail the target (user principal id / role) and the role or permission involved
|
||||
*/
|
||||
protected abstract void audit(String actor, String action, String detail);
|
||||
|
||||
/**
|
||||
* Runs an admin action, confirming success with a {@code flash} message and turning a bounded-grant/
|
||||
* validation failure into a flash {@code error} (never a 500) — the op-layout shell renders both regions
|
||||
* (keyed {@code flash}/{@code error}). Every matrix mutation routes through here, so all confirm uniformly
|
||||
* and every successful one is {@linkplain #audit audited}.
|
||||
*/
|
||||
private String apply(RedirectAttributes redirect, String successMessage, Runnable action,
|
||||
Authentication authentication, String auditAction, String auditDetail) {
|
||||
try {
|
||||
action.run();
|
||||
audit(authentication == null ? "" : authentication.getName(), auditAction, auditDetail);
|
||||
redirect.addFlashAttribute("flash", successMessage);
|
||||
} catch (RuntimeException e) {
|
||||
redirect.addFlashAttribute("error", e.getMessage());
|
||||
}
|
||||
return "redirect:" + basePath();
|
||||
}
|
||||
|
||||
private RunwayUserDetails actor(Authentication authentication) {
|
||||
if (authentication != null && authentication.getPrincipal() instanceof RunwayUserDetails principal) {
|
||||
return principal;
|
||||
}
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "not authenticated in this realm");
|
||||
}
|
||||
|
||||
private Permission permission(String key) {
|
||||
return catalog.find(key)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "no such permission: " + key));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpSession;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
import mx.quest.runway.security.AccountStateFilter;
|
||||
import mx.quest.runway.security.LoginAttemptGate;
|
||||
import mx.quest.runway.security.RunwayUserDetails;
|
||||
import mx.quest.runway.security.User;
|
||||
import mx.quest.runway.web.ClientIp;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* Shared self-service logic for the app and tenant Account screens: a user changes only their <b>own</b> password,
|
||||
* display name and recovery email. Kept realm-agnostic (the caller supplies the loaded self, the store's save and
|
||||
* the realm's {@link Checks}) so the two realms share one set of rules.
|
||||
*
|
||||
* <h2>The current-password check is limited</h2>
|
||||
* Changing the password or the recovery email needs the current password. Without a limit, a borrowed or stolen
|
||||
* console session could guess it as fast as the server answers, and a hit gives away the credential or the place a
|
||||
* reset link goes. So every wrong guess:
|
||||
* <ul>
|
||||
* <li>counts against the signed-in account <b>in this session</b>; after {@link #MAX_WRONG_PASSWORDS} in a row the
|
||||
* session's sign-in for this realm is dropped and the person is sent to the sign-in page, so a borrowed session
|
||||
* is spent after a few guesses. This is the kernel's own floor and needs no plugin. A right password resets
|
||||
* the count. The count is reserved before the password is hashed ({@link WrongPasswordCounter}), so guesses
|
||||
* sent at the same moment cannot all slip under it: at most {@link #MAX_WRONG_PASSWORDS} are ever checked;</li>
|
||||
* <li>is reported to the {@link LoginAttemptGate} for the client's IP, as a failed sign-in is, so the protection
|
||||
* plugin's per-IP lockout covers these forms too; while that IP is locked the forms refuse before any
|
||||
* password is hashed;</li>
|
||||
* <li>is recorded in the realm's journal with the client's IP ({@link Checks#onWrongPassword}).</li>
|
||||
* </ul>
|
||||
* A blank current password is not a guess: it is refused with a prompt and not counted.
|
||||
*/
|
||||
final class AccountSupport {
|
||||
|
||||
/** Wrong current passwords in a row, in one session, before its sign-in is dropped (the login default). */
|
||||
static final int MAX_WRONG_PASSWORDS = 5;
|
||||
|
||||
/** The counter key prefix, followed by the session id, the realm and the principal id. */
|
||||
static final String WRONG_PASSWORDS_KEY = "runway.account.wrong-passwords|";
|
||||
|
||||
private AccountSupport() {
|
||||
}
|
||||
|
||||
/**
|
||||
* What a realm's account screen gives the shared rules.
|
||||
*
|
||||
* @param encoder the password encoder
|
||||
* @param gate the per-IP sign-in attempt gate (the kernel's permissive one, or the protection plugin's)
|
||||
* @param messages the operator message source, for the screen's messages in the console's language
|
||||
* @param screen the account screen's path, where every outcome but a sign-out returns
|
||||
* @param loginPath the realm's sign-in page, where a spent session is sent
|
||||
* @param counter the node's count of wrong current passwords per session and account
|
||||
* @param onWrongPassword records one wrong current password in the realm's journal; receives the client's IP
|
||||
*/
|
||||
record Checks(PasswordEncoder encoder, LoginAttemptGate gate, MessageSource messages, String screen,
|
||||
String loginPath, WrongPasswordCounter counter, Consumer<String> onWrongPassword) {
|
||||
Checks {
|
||||
Objects.requireNonNull(encoder, "encoder");
|
||||
Objects.requireNonNull(gate, "gate");
|
||||
Objects.requireNonNull(counter, "counter");
|
||||
Objects.requireNonNull(messages, "messages");
|
||||
Objects.requireNonNull(screen, "screen");
|
||||
Objects.requireNonNull(loginPath, "loginPath");
|
||||
Objects.requireNonNull(onWrongPassword, "onWrongPassword");
|
||||
}
|
||||
}
|
||||
|
||||
/** The signed-in principal as a {@link RunwayUserDetails}, or a 403 if there is none. */
|
||||
static RunwayUserDetails principal(Authentication authentication) {
|
||||
if (authentication != null && authentication.getPrincipal() instanceof RunwayUserDetails details) {
|
||||
return details;
|
||||
}
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "not authenticated");
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies {@code current} (limited, see the class comment), checks the new password is non-blank and matches
|
||||
* its confirmation, then saves {@code self} with the new hash — surfacing every failure as a flash error (never a
|
||||
* 500). Only the caller's own record is passed in, so this can never change another user.
|
||||
*
|
||||
* <p>After a successful save the <b>requesting</b> session is rebound to the new record
|
||||
* ({@link AccountStateFilter#rebindIfSelf}), so it stays signed in, while every other session of the account
|
||||
* ends on its next request ({@link AccountStateFilter} sees the hash change).
|
||||
*
|
||||
* @return the view to answer with: a redirect to the account screen, or to the sign-in page once the session's
|
||||
* sign-in was dropped for too many wrong passwords
|
||||
*/
|
||||
static String changePassword(User self, String current, String newPassword, String confirm, Checks checks,
|
||||
Consumer<User> save, RedirectAttributes redirect, HttpServletRequest request) {
|
||||
String refused = verifyCurrent(self, current, "op.account.error.currentNeeded",
|
||||
"Enter your current password.", checks, redirect, request);
|
||||
if (refused != null) {
|
||||
return refused;
|
||||
}
|
||||
if (newPassword == null || newPassword.isBlank()) {
|
||||
redirect.addFlashAttribute("error", message(checks, "op.account.error.newBlank",
|
||||
"The new password must not be blank."));
|
||||
return back(checks);
|
||||
}
|
||||
if (!newPassword.equals(confirm)) {
|
||||
redirect.addFlashAttribute("error", message(checks, "op.account.error.mismatch",
|
||||
"The new password and its confirmation do not match."));
|
||||
return back(checks);
|
||||
}
|
||||
User updated = self.withPasswordHash(checks.encoder().encode(newPassword));
|
||||
save.accept(updated);
|
||||
AccountStateFilter.rebindIfSelf(request, updated);
|
||||
redirect.addFlashAttribute("flash", message(checks, "op.account.passwordChanged",
|
||||
"Your password has been changed. Any other session signed in as you has been signed out."));
|
||||
return back(checks);
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves {@code self}'s own display name and recovery email, with the same rules as an administrator's edit
|
||||
* ({@link ConsoleUserService#withProfile}: a blank name falls back to the username, a non-blank email must be an
|
||||
* address). Changing the <b>recovery email</b> also needs the current password (limited, see the class
|
||||
* comment): it is where a password-reset link goes, so a borrowed or stolen session must not be able to point
|
||||
* it elsewhere. The name alone needs none. Every failure is a flash error; nothing is saved then.
|
||||
*
|
||||
* <p>After the save the requesting session is rebound to the new record, so the name in the top bar updates.
|
||||
*
|
||||
* @return the view to answer with, as for {@link #changePassword}
|
||||
*/
|
||||
static String changeProfile(User self, String displayName, String email, String current, Checks checks,
|
||||
Consumer<User> save, RedirectAttributes redirect, HttpServletRequest request) {
|
||||
User updated;
|
||||
try {
|
||||
updated = ConsoleUserService.withProfile(self, displayName, email);
|
||||
} catch (ConsoleUserService.UserEditException invalid) {
|
||||
redirect.addFlashAttribute("error", message(checks, "op.users.error." + invalid.code(),
|
||||
invalid.getMessage()));
|
||||
return back(checks);
|
||||
}
|
||||
if (!self.recoveryEmail().equals(updated.recoveryEmail())) {
|
||||
String refused = verifyCurrent(self, current, "op.account.profile.needsPassword",
|
||||
"Enter your current password to change your recovery email.", checks, redirect, request);
|
||||
if (refused != null) {
|
||||
return refused;
|
||||
}
|
||||
}
|
||||
save.accept(updated);
|
||||
AccountStateFilter.rebindIfSelf(request, updated);
|
||||
redirect.addFlashAttribute("flash", message(checks, "op.account.profile.saved",
|
||||
"Your profile has been saved."));
|
||||
return back(checks);
|
||||
}
|
||||
|
||||
/**
|
||||
* The limited current-password check. A blank {@code current} is answered with {@code blankKey}'s message and
|
||||
* not counted; a wrong one with "The current password is incorrect."
|
||||
*
|
||||
* @return {@code null} when {@code current} is right; otherwise the view to answer with, the flash already set
|
||||
*/
|
||||
private static String verifyCurrent(User self, String current, String blankKey, String blankFallback,
|
||||
Checks checks, RedirectAttributes redirect, HttpServletRequest request) {
|
||||
if (current == null || current.isEmpty()) {
|
||||
redirect.addFlashAttribute("error", message(checks, blankKey, blankFallback));
|
||||
return back(checks);
|
||||
}
|
||||
String ip = ClientIp.of(request);
|
||||
if (checks.gate().isLocked(ip)) {
|
||||
redirect.addFlashAttribute("error", message(checks, "op.login.locked",
|
||||
"Too many failed sign-in attempts from your network. Wait a few minutes, then try again."));
|
||||
return back(checks);
|
||||
}
|
||||
// The guess's number is reserved before the password is hashed: guesses sent at the same moment each get
|
||||
// their own, so the ones past the limit are refused unhashed instead of all reading the same count.
|
||||
HttpSession session = request.getSession(false);
|
||||
String key = WRONG_PASSWORDS_KEY + (session == null ? "-" : session.getId()) + "|" + self.realm() + "|"
|
||||
+ self.principalId();
|
||||
int attempt = checks.counter().reserve(key);
|
||||
if (attempt > MAX_WRONG_PASSWORDS) {
|
||||
AccountStateFilter.signOutIfSelf(request, self); // spent: this one is not checked at all
|
||||
return "redirect:" + checks.loginPath() + "?reverify";
|
||||
}
|
||||
if (checks.encoder().matches(current, self.passwordHash())) {
|
||||
checks.counter().reset(key);
|
||||
return null;
|
||||
}
|
||||
checks.gate().recordFailure(ip);
|
||||
checks.onWrongPassword().accept(ip);
|
||||
if (attempt == MAX_WRONG_PASSWORDS) {
|
||||
// No reset here: a guess still in flight must find the count spent, not start again at 1. The key carries
|
||||
// the session id, and the sign-out ends that session, so the entry is never used again and expires.
|
||||
AccountStateFilter.signOutIfSelf(request, self);
|
||||
return "redirect:" + checks.loginPath() + "?reverify";
|
||||
}
|
||||
redirect.addFlashAttribute("error", message(checks, "op.account.error.currentIncorrect",
|
||||
"The current password is incorrect."));
|
||||
return back(checks);
|
||||
}
|
||||
|
||||
private static String back(Checks checks) {
|
||||
return "redirect:" + checks.screen();
|
||||
}
|
||||
|
||||
private static String message(Checks checks, String key, String fallback) {
|
||||
return checks.messages().getMessage(key, null, fallback, LocaleContextHolder.getLocale());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import mx.quest.runway.page.PageStore;
|
||||
import mx.quest.runway.security.RunwayUserDetails;
|
||||
import mx.quest.runway.security.SiteUserStore;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
/**
|
||||
* The tenant-realm operator home ({@code /__admin}) — a dashboard for the bound tenancy: counts (pages, users)
|
||||
* over the tenant stores, rendered through the same {@code op-layout} shell but with the admin topbar and
|
||||
* tenant i18n ({@link OperatorModelAdvice} selects them by path). Counts are zero when no tenancy is bound.
|
||||
*/
|
||||
@Controller
|
||||
public class AdminHomeController {
|
||||
|
||||
private final PageStore pages;
|
||||
private final SiteUserStore siteUsers;
|
||||
private final SiteResolver siteResolver;
|
||||
private final DashboardCardRegistry cards;
|
||||
|
||||
public AdminHomeController(PageStore pages, SiteUserStore siteUsers, SiteResolver siteResolver,
|
||||
DashboardCardRegistry cards) {
|
||||
this.pages = pages;
|
||||
this.siteUsers = siteUsers;
|
||||
this.siteResolver = siteResolver;
|
||||
this.cards = cards;
|
||||
}
|
||||
|
||||
@GetMapping({"/__admin", "/__admin/"})
|
||||
public String home(Authentication authentication, Model model) {
|
||||
String tenancyId = siteResolver.current().map(site -> site.id()).orElse(null);
|
||||
RunwayUserDetails principal = authentication != null
|
||||
&& authentication.getPrincipal() instanceof RunwayUserDetails details ? details : null;
|
||||
model.addAttribute("countPages", tenancyId == null ? 0 : pages.findAll(tenancyId).size());
|
||||
model.addAttribute("countUsers", tenancyId == null ? 0 : siteUsers.list(tenancyId).size());
|
||||
model.addAttribute("dashboardCards", cards.cardsFor(Realm.TENANT, principal, tenancyId));
|
||||
model.addAttribute("contentTemplate", "operator/admin/home");
|
||||
model.addAttribute("pageTitleKey", "op.admin.home.title");
|
||||
return "operator/op-layout";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
/**
|
||||
* The application-realm <b>About Runway</b> screen ({@code /__app/about}) — a read-only view of the running
|
||||
* platform: the version, the curated effective configuration, and the runtime environment of the node serving
|
||||
* the request. Rendered through the {@code op-layout} operator shell.
|
||||
*
|
||||
* <p>Unlike the sibling <b>Platform settings</b> page ({@link AppSettingsController}), About mutates nothing and
|
||||
* exposes no secret, so it carries <b>no platform-admin gate</b>: the {@code /__app/**} security chain already
|
||||
* restricts it to authenticated application operators, which is exactly the intended audience. All values come
|
||||
* from {@link RuntimeInfoService} (the controller stays free of business logic).
|
||||
*/
|
||||
@Controller
|
||||
public class AppAboutController {
|
||||
|
||||
private final RuntimeInfoService info;
|
||||
|
||||
public AppAboutController(RuntimeInfoService info) {
|
||||
this.info = info;
|
||||
}
|
||||
|
||||
@GetMapping("/__app/about")
|
||||
public String about(Model model) {
|
||||
model.addAttribute("appVersion", info.version());
|
||||
model.addAttribute("buildTime", info.buildTime());
|
||||
model.addAttribute("effectiveConfig", info.effectiveConfig());
|
||||
model.addAttribute("runtimeInfo", info.runtime());
|
||||
model.addAttribute("componentInfo", info.components());
|
||||
model.addAttribute("contentTemplate", "operator/app/about");
|
||||
model.addAttribute("pageTitleKey", "op.about.title");
|
||||
return "operator/op-layout";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import mx.quest.runway.log.AppActivityLog;
|
||||
import mx.quest.runway.security.AppUserStore;
|
||||
import mx.quest.runway.security.LoginAttemptGate;
|
||||
import mx.quest.runway.security.RunwayUserDetails;
|
||||
import mx.quest.runway.security.User;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* The application operator's own <b>Account</b> ({@code /__app/account}): your display name and recovery email, and
|
||||
* your password. No admin
|
||||
* gate — every authenticated app user may change their <em>own</em> credential — but the current password must
|
||||
* verify first, and it only ever touches the signed-in principal's own record ({@link AppUserStore}). Wrong current
|
||||
* passwords are limited and journaled ({@link AccountSupport}). Shares the {@code operator/account} form template
|
||||
* with the tenant account.
|
||||
*/
|
||||
@Controller
|
||||
public class AppAccountController {
|
||||
|
||||
private final AppUserStore users;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final AppActivityLog activity;
|
||||
private final LoginAttemptGate loginGate;
|
||||
private final MessageSource messages;
|
||||
private final WrongPasswordCounter wrongPasswords;
|
||||
|
||||
public AppAccountController(AppUserStore users, PasswordEncoder passwordEncoder, AppActivityLog activity,
|
||||
LoginAttemptGate loginGate,
|
||||
@Qualifier("operatorAwareMessageSource") MessageSource messages,
|
||||
WrongPasswordCounter wrongPasswords) {
|
||||
this.wrongPasswords = wrongPasswords;
|
||||
this.users = users;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.activity = activity;
|
||||
this.loginGate = loginGate;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
@GetMapping("/__app/account")
|
||||
public String form(Authentication authentication, Model model) {
|
||||
model.addAttribute("self", self(authentication));
|
||||
model.addAttribute("accountAction", "/__app/account");
|
||||
model.addAttribute("contentTemplate", "operator/account");
|
||||
model.addAttribute("pageTitleKey", "op.account.title");
|
||||
return "operator/op-layout";
|
||||
}
|
||||
|
||||
@PostMapping("/__app/account")
|
||||
public String change(@RequestParam String currentPassword, @RequestParam String newPassword,
|
||||
@RequestParam String confirmPassword, Authentication authentication,
|
||||
RedirectAttributes redirect, HttpServletRequest request) {
|
||||
User self = self(authentication);
|
||||
// The save consumer fires only on a successful change, so recording inside it audits success only.
|
||||
return AccountSupport.changePassword(self, currentPassword, newPassword, confirmPassword, checks(self),
|
||||
updated -> {
|
||||
users.save(updated);
|
||||
activity.record(self.username(), "account.password-changed", "");
|
||||
}, redirect, request);
|
||||
}
|
||||
|
||||
/** Saves your own display name and recovery email ({@link AccountSupport#changeProfile}). */
|
||||
@PostMapping("/__app/account/profile")
|
||||
public String profile(@RequestParam(required = false) String displayName,
|
||||
@RequestParam(required = false) String recoveryEmail,
|
||||
@RequestParam(required = false) String currentPassword, Authentication authentication,
|
||||
RedirectAttributes redirect, HttpServletRequest request) {
|
||||
User self = self(authentication);
|
||||
return AccountSupport.changeProfile(self, displayName, recoveryEmail, currentPassword, checks(self),
|
||||
updated -> {
|
||||
users.save(updated);
|
||||
activity.record(self.username(), "account.profile-changed", "");
|
||||
}, redirect, request);
|
||||
}
|
||||
|
||||
private AccountSupport.Checks checks(User self) {
|
||||
return new AccountSupport.Checks(passwordEncoder, loginGate, messages, "/__app/account", "/app/login",
|
||||
wrongPasswords, ip -> activity.record(self.username(), "account.password-check-failed", "ip=" + ip));
|
||||
}
|
||||
|
||||
private User self(Authentication authentication) {
|
||||
RunwayUserDetails principal = AccountSupport.principal(authentication);
|
||||
return users.findByPrincipalId(principal.principalId())
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.FORBIDDEN, "no account"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import mx.quest.runway.backup.BackupService;
|
||||
import mx.quest.runway.backup.BackupService.StoredBackup;
|
||||
import mx.quest.runway.backup.UnsupportedBackupFormatException;
|
||||
import mx.quest.runway.log.AppActivityLog;
|
||||
import mx.quest.runway.site.Site;
|
||||
import mx.quest.runway.site.SiteHosts;
|
||||
import mx.quest.runway.site.SiteStore;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* The application console's backups screen ({@code /__app/backups}): the operator can back up, download and
|
||||
* restore <b>any</b> site (not just its own), and <b>create a new site from an uploaded backup</b> (cloning or
|
||||
* migrating). Gated to platform superadmins via {@link PlatformAuthority} — these are cross-tenant operations.
|
||||
*/
|
||||
@Controller
|
||||
public class AppBackupsController {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(AppBackupsController.class);
|
||||
|
||||
private final SiteStore sites;
|
||||
private final BackupService backups;
|
||||
private final PlatformAuthority platformAuthority;
|
||||
private final MessageSource messages;
|
||||
private final AppActivityLog activity;
|
||||
|
||||
private final mx.quest.runway.backup.BackupProperties policy;
|
||||
|
||||
public AppBackupsController(SiteStore sites, BackupService backups, PlatformAuthority platformAuthority,
|
||||
@Qualifier("operatorAwareMessageSource") MessageSource messages,
|
||||
AppActivityLog activity, mx.quest.runway.backup.BackupProperties policy) {
|
||||
this.policy = policy;
|
||||
this.sites = sites;
|
||||
this.backups = backups;
|
||||
this.platformAuthority = platformAuthority;
|
||||
this.messages = messages;
|
||||
this.activity = activity;
|
||||
}
|
||||
|
||||
/** One site row: its id and the backups stored for it on the server. */
|
||||
public record SiteBackups(String siteId, List<StoredBackup> stored) {
|
||||
}
|
||||
|
||||
@GetMapping("/__app/backups")
|
||||
public String view(Authentication authentication, Model model) {
|
||||
platformAuthority.require(authentication);
|
||||
List<SiteBackups> rows = new ArrayList<>();
|
||||
for (Site site : sites.findAll()) {
|
||||
rows.add(new SiteBackups(site.id(), backups.list(site.id())));
|
||||
}
|
||||
model.addAttribute("rows", rows);
|
||||
// Shown, not edited: a server folder that receives every site's archives is the host's (settings-homes.yml).
|
||||
String offsite = policy.getOffsiteDir();
|
||||
model.addAttribute("offsiteDir", offsite == null || offsite.isBlank() ? null : offsite.trim());
|
||||
model.addAttribute("contentTemplate", "operator/app/backups");
|
||||
model.addAttribute("pageTitleKey", "op.appbackups.title");
|
||||
return "operator/op-layout";
|
||||
}
|
||||
|
||||
/** Stream a fresh backup of any site. */
|
||||
@GetMapping("/__app/backups/{siteId}/download")
|
||||
public void download(@PathVariable String siteId, Authentication authentication, HttpServletResponse response)
|
||||
throws IOException {
|
||||
platformAuthority.require(authentication);
|
||||
if (!sites.exists(siteId)) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no such site");
|
||||
}
|
||||
response.setContentType("application/zip");
|
||||
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
|
||||
"attachment; filename=\"" + siteId + "-backup-" + LocalDate.now() + ".zip\"");
|
||||
backups.backup(siteId, response.getOutputStream());
|
||||
}
|
||||
|
||||
/** Stream a <b>transfer</b> archive of any site — no credentials, accounts or origin hostnames. */
|
||||
@GetMapping("/__app/backups/{siteId}/download-transfer")
|
||||
public void downloadForTransfer(@PathVariable String siteId, Authentication authentication,
|
||||
HttpServletResponse response) throws IOException {
|
||||
platformAuthority.require(authentication);
|
||||
if (!sites.exists(siteId)) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no such site");
|
||||
}
|
||||
response.setContentType("application/zip");
|
||||
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
|
||||
"attachment; filename=\"" + siteId + "-transfer-" + LocalDate.now() + ".zip\"");
|
||||
backups.backup(siteId, response.getOutputStream(), BackupService.BackupPurpose.TRANSFER);
|
||||
}
|
||||
|
||||
/** Save a stored backup of any site on the server. */
|
||||
@PostMapping("/__app/backups/{siteId}/save")
|
||||
public String save(@PathVariable String siteId, Authentication authentication, RedirectAttributes redirect) {
|
||||
platformAuthority.require(authentication);
|
||||
try {
|
||||
String name = backups.create(siteId);
|
||||
activity.record(authentication.getName(), "backup.saved", siteId + "/" + name);
|
||||
redirect.addFlashAttribute("flash", message("op.appbackups.saved", "Backup saved.") + " " + name);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
redirect.addFlashAttribute("error", message("op.appbackups.failed", "Backup failed."));
|
||||
}
|
||||
return "redirect:/__app/backups";
|
||||
}
|
||||
|
||||
/** Restore any site from an uploaded backup (replaces that site). */
|
||||
@PostMapping("/__app/backups/{siteId}/restore")
|
||||
public String restoreUpload(@PathVariable String siteId, @RequestParam("file") MultipartFile file,
|
||||
Authentication authentication, RedirectAttributes redirect) {
|
||||
platformAuthority.require(authentication);
|
||||
if (file == null || file.isEmpty()) {
|
||||
redirect.addFlashAttribute("error", message("op.appbackups.noFile", "Choose a backup file."));
|
||||
return "redirect:/__app/backups";
|
||||
}
|
||||
try (InputStream in = file.getInputStream()) {
|
||||
backups.restore(siteId, in);
|
||||
activity.record(authentication.getName(), "site.restored", siteId + " (upload)");
|
||||
redirect.addFlashAttribute("flash", message("op.appbackups.restored", "Site restored."));
|
||||
} catch (UnsupportedBackupFormatException e) {
|
||||
redirect.addFlashAttribute("error", newerFormat(e));
|
||||
} catch (IOException | RuntimeException e) {
|
||||
log.warn("app-realm restore-from-upload failed for {}", siteId, e);
|
||||
redirect.addFlashAttribute("error", message("op.appbackups.restoreFailed", "Restore failed."));
|
||||
}
|
||||
return "redirect:/__app/backups";
|
||||
}
|
||||
|
||||
/** Restore a site from one of its stored backups. */
|
||||
@PostMapping("/__app/backups/{siteId}/{name}/restore")
|
||||
public String restoreStored(@PathVariable String siteId, @PathVariable String name,
|
||||
Authentication authentication, RedirectAttributes redirect) {
|
||||
platformAuthority.require(authentication);
|
||||
try {
|
||||
backups.restoreStored(siteId, name);
|
||||
activity.record(authentication.getName(), "site.restored", siteId + "/" + name);
|
||||
redirect.addFlashAttribute("flash", message("op.appbackups.restored", "Site restored."));
|
||||
} catch (UnsupportedBackupFormatException e) {
|
||||
redirect.addFlashAttribute("error", newerFormat(e));
|
||||
} catch (IOException | RuntimeException e) {
|
||||
redirect.addFlashAttribute("error", message("op.appbackups.restoreFailed", "Restore failed."));
|
||||
}
|
||||
return "redirect:/__app/backups";
|
||||
}
|
||||
|
||||
/** Delete a stored backup. */
|
||||
@PostMapping("/__app/backups/{siteId}/{name}/delete")
|
||||
public String deleteStored(@PathVariable String siteId, @PathVariable String name,
|
||||
Authentication authentication, RedirectAttributes redirect) {
|
||||
platformAuthority.require(authentication);
|
||||
backups.delete(siteId, name);
|
||||
activity.record(authentication.getName(), "backup.deleted", siteId + "/" + name);
|
||||
redirect.addFlashAttribute("flash", message("op.appbackups.deleted", "Backup deleted."));
|
||||
return "redirect:/__app/backups";
|
||||
}
|
||||
|
||||
/** Create a NEW site from an uploaded backup — cloning or migrating a site under a new identity. */
|
||||
@PostMapping("/__app/backups/create-site")
|
||||
public String createSite(@RequestParam String newId, @RequestParam(required = false) String name,
|
||||
@RequestParam(required = false) String hosts, @RequestParam("file") MultipartFile file,
|
||||
Authentication authentication, RedirectAttributes redirect) {
|
||||
platformAuthority.require(authentication);
|
||||
if (file == null || file.isEmpty()) {
|
||||
redirect.addFlashAttribute("error", message("op.appbackups.noFile", "Choose a backup file."));
|
||||
return "redirect:/__app/backups";
|
||||
}
|
||||
try {
|
||||
// Checked here first so a bad or claimed host is reported as such, not as an unusable site id (the
|
||||
// service checks again under the host lock when it saves).
|
||||
SiteHosts.requireUnclaimed(sites, newId.strip(), SiteHosts.normalize(splitHosts(hosts)));
|
||||
} catch (IllegalArgumentException badHost) {
|
||||
redirect.addFlashAttribute("error", message("op.appbackups.badHosts", "Those hosts cannot be used:")
|
||||
+ " " + badHost.getMessage());
|
||||
return "redirect:/__app/backups";
|
||||
}
|
||||
try (InputStream in = file.getInputStream()) {
|
||||
backups.createFromBackup(newId.strip(), name, splitHosts(hosts), in);
|
||||
activity.record(authentication.getName(), "site.created-from-backup", newId.strip());
|
||||
redirect.addFlashAttribute("flash", message("op.appbackups.created", "Site created from backup."));
|
||||
} catch (UnsupportedBackupFormatException e) {
|
||||
redirect.addFlashAttribute("error", newerFormat(e));
|
||||
} catch (IllegalStateException e) {
|
||||
redirect.addFlashAttribute("error", message("op.appbackups.exists", "A site with that id already exists."));
|
||||
} catch (IllegalArgumentException e) {
|
||||
redirect.addFlashAttribute("error", message("op.appbackups.badId", "That site id cannot be used."));
|
||||
} catch (IOException | RuntimeException e) {
|
||||
log.warn("create-site-from-backup failed for {}", newId, e);
|
||||
redirect.addFlashAttribute("error", message("op.appbackups.createFailed", "Could not create the site."));
|
||||
}
|
||||
return "redirect:/__app/backups";
|
||||
}
|
||||
|
||||
private static List<String> splitHosts(String hosts) {
|
||||
if (hosts == null || hosts.isBlank()) {
|
||||
return List.of();
|
||||
}
|
||||
return Arrays.stream(hosts.split("[,\\s]+")).map(String::strip).filter(h -> !h.isEmpty()).toList();
|
||||
}
|
||||
|
||||
private String message(String key, String fallback) {
|
||||
return messages.getMessage(key, null, fallback, LocaleContextHolder.getLocale());
|
||||
}
|
||||
|
||||
/** The operator-facing refusal for an archive written by a newer Runway: what it is, and what to do. */
|
||||
private String newerFormat(UnsupportedBackupFormatException e) {
|
||||
return messages.getMessage("op.appbackups.newerFormat", new Object[] {e.found(), e.supported()},
|
||||
"This backup was made by a newer version of Runway. Upgrade Runway, then restore it.",
|
||||
LocaleContextHolder.getLocale());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import mx.quest.runway.bandwidth.BandwidthService;
|
||||
import mx.quest.runway.bandwidth.BandwidthService.SiteBandwidth;
|
||||
import mx.quest.runway.bandwidth.Bytes;
|
||||
import java.util.List;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
/**
|
||||
* The application console's bandwidth screen ({@code /__app/bandwidth}): a 30-day aggregate across <b>all</b>
|
||||
* sites, busiest first, plus platform totals. This is the one deliberate exception to tenant→app isolation —
|
||||
* but it exposes only <b>aggregate byte counts</b> (never log entries or content), which is why it is allowed
|
||||
* to cross realms. Gated by the grantable {@code VIEW_BANDWIDTH} application permission.
|
||||
*/
|
||||
@Controller
|
||||
public class AppBandwidthController {
|
||||
|
||||
private final BandwidthService bandwidth;
|
||||
|
||||
public AppBandwidthController(BandwidthService bandwidth) {
|
||||
this.bandwidth = bandwidth;
|
||||
}
|
||||
|
||||
@GetMapping("/__app/bandwidth")
|
||||
@PreAuthorize("@authz.may('VIEW_BANDWIDTH')")
|
||||
public String view(Model model) {
|
||||
List<SiteBandwidth> sites = bandwidth.aggregate();
|
||||
model.addAttribute("sites", sites);
|
||||
model.addAttribute("totalIn", Bytes.human(sites.stream().mapToLong(SiteBandwidth::bytesIn).sum()));
|
||||
model.addAttribute("totalOut", Bytes.human(sites.stream().mapToLong(SiteBandwidth::bytesOut).sum()));
|
||||
model.addAttribute("contentTemplate", "operator/app/bandwidth");
|
||||
model.addAttribute("pageTitleKey", "op.appbandwidth.title");
|
||||
return "operator/op-layout";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.log.AppActivityLog;
|
||||
import mx.quest.runway.platform.EmbedHostService;
|
||||
import mx.quest.runway.platform.PlatformSettings.EmbedHost;
|
||||
import mx.quest.runway.site.Site;
|
||||
import mx.quest.runway.site.SiteCspService;
|
||||
import mx.quest.runway.site.SiteStore;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* Settings → <b>Embed hosts</b> ({@code /__app/embed-hosts}): the third-party hosts the operator approves for sites to
|
||||
* add to their own public pages' Content Security Policy, each limited to the directives chosen here
|
||||
* ({@link EmbedHostService}). A site then switches on the ones it needs on its Site config. A platform operation,
|
||||
* gated to the master and wildcard admins like the other Settings screens; every change applies on the next page.
|
||||
*/
|
||||
@Controller
|
||||
public class AppEmbedHostsController {
|
||||
|
||||
private static final String SCREEN = "/__app/embed-hosts";
|
||||
|
||||
private final EmbedHostService hosts;
|
||||
private final PlatformAuthority platformAuthority;
|
||||
private final SiteStore sites;
|
||||
private final SiteCspService siteCsp;
|
||||
private final AppActivityLog activity;
|
||||
private final MessageSource messages;
|
||||
|
||||
public AppEmbedHostsController(EmbedHostService hosts, PlatformAuthority platformAuthority, SiteStore sites,
|
||||
SiteCspService siteCsp, AppActivityLog activity,
|
||||
@Qualifier("operatorAwareMessageSource") MessageSource messages) {
|
||||
this.hosts = hosts;
|
||||
this.platformAuthority = platformAuthority;
|
||||
this.sites = sites;
|
||||
this.siteCsp = siteCsp;
|
||||
this.activity = activity;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
@GetMapping(SCREEN)
|
||||
public String list(Authentication authentication, Model model) {
|
||||
platformAuthority.require(authentication);
|
||||
Map<String, Integer> usage = new LinkedHashMap<>();
|
||||
for (Site site : sites.findAll()) {
|
||||
for (String id : siteCsp.chosen(site.id())) {
|
||||
usage.merge(id, 1, Integer::sum);
|
||||
}
|
||||
}
|
||||
model.addAttribute("hosts", hosts.list());
|
||||
model.addAttribute("usage", usage);
|
||||
model.addAttribute("directives", EmbedHostService.DIRECTIVES);
|
||||
model.addAttribute("contentTemplate", "operator/app/embed-hosts");
|
||||
model.addAttribute("pageTitleKey", "op.embed.title");
|
||||
return "operator/op-layout";
|
||||
}
|
||||
|
||||
/** Approves a host, or replaces the entry with the same id. */
|
||||
@PostMapping(SCREEN)
|
||||
public String save(@RequestParam(required = false) String id, @RequestParam(required = false) String label,
|
||||
@RequestParam(required = false) String source,
|
||||
@RequestParam(name = "directives", required = false) List<String> directives,
|
||||
Authentication authentication, RedirectAttributes redirect) {
|
||||
platformAuthority.require(authentication);
|
||||
try {
|
||||
EmbedHost saved = hosts.save(id, label, source, directives);
|
||||
activity.record(authentication.getName(), "platform.embed-host-saved",
|
||||
saved.id() + " " + saved.source() + " " + String.join(",", saved.directives()));
|
||||
redirect.addFlashAttribute("flash", messages.getMessage("op.embed.saved", new Object[] {saved.label()},
|
||||
"Saved.", LocaleContextHolder.getLocale()));
|
||||
} catch (EmbedHostService.Invalid invalid) {
|
||||
redirect.addFlashAttribute("error", message("op.embed.invalid." + invalid.code(), invalid.getMessage()));
|
||||
}
|
||||
return "redirect:" + SCREEN;
|
||||
}
|
||||
|
||||
/** Withdraws approval; the sites that had switched it on lose it on their next page. */
|
||||
@PostMapping(SCREEN + "/remove")
|
||||
public String remove(@RequestParam String id, Authentication authentication, RedirectAttributes redirect) {
|
||||
platformAuthority.require(authentication);
|
||||
if (hosts.remove(id)) {
|
||||
activity.record(authentication.getName(), "platform.embed-host-removed", id);
|
||||
redirect.addFlashAttribute("flash", message("op.embed.removed", "Removed."));
|
||||
}
|
||||
return "redirect:" + SCREEN;
|
||||
}
|
||||
|
||||
private String message(String key, String fallback) {
|
||||
return messages.getMessage(key, null, fallback, LocaleContextHolder.getLocale());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.util.List;
|
||||
import mx.quest.runway.authz.AuthorizationService;
|
||||
import mx.quest.runway.authz.Permissions;
|
||||
import mx.quest.runway.plugin.RunningPlugins;
|
||||
import mx.quest.runway.security.AppUserStore;
|
||||
import mx.quest.runway.security.RunwayUserDetails;
|
||||
import mx.quest.runway.site.SiteStore;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
/**
|
||||
* The application-realm operator home ({@code /__app}) — a dashboard rendered through the {@code op-layout}
|
||||
* shell: at-a-glance counts (sites, application users, loaded plugins) over the already-tested stores, plus the
|
||||
* plugin dashboard-card host. {@link OperatorModelAdvice} supplies the chrome (app topbar, plugin menu).
|
||||
*
|
||||
* <p><b>Gate.</b> The dashboard content — the counts <em>and</em> the plugin cards — needs
|
||||
* {@link Permissions#VIEW_APP_DASHBOARD}. The route itself does not: it is where every application sign-in lands,
|
||||
* so an operator without the permission gets a minimal landing (a heading and a pointer to the menu) instead of a
|
||||
* {@code 403} after a successful login. The application superadmin and {@code SYSTEMADMIN} pass as always; a
|
||||
* {@code SYSTEMOPERATOR} sees the dashboard once the permission is granted to them or one of their roles. A plugin
|
||||
* card that declares its own permission still needs it as well.
|
||||
*/
|
||||
@Controller
|
||||
public class AppHomeController {
|
||||
|
||||
private final SiteStore sites;
|
||||
private final AppUserStore appUsers;
|
||||
private final RunningPlugins runningPlugins;
|
||||
private final DashboardCardRegistry cards;
|
||||
private final AuthorizationService authorization;
|
||||
|
||||
public AppHomeController(SiteStore sites, AppUserStore appUsers, RunningPlugins runningPlugins,
|
||||
DashboardCardRegistry cards, AuthorizationService authorization) {
|
||||
this.sites = sites;
|
||||
this.appUsers = appUsers;
|
||||
this.runningPlugins = runningPlugins;
|
||||
this.cards = cards;
|
||||
this.authorization = authorization;
|
||||
}
|
||||
|
||||
@GetMapping({"/__app", "/__app/"})
|
||||
public String home(Authentication authentication, Model model) {
|
||||
RunwayUserDetails principal = authentication != null
|
||||
&& authentication.getPrincipal() instanceof RunwayUserDetails details ? details : null;
|
||||
boolean dashboard = principal != null
|
||||
&& authorization.mayAccess(principal, Permissions.VIEW_APP_DASHBOARD, null);
|
||||
model.addAttribute("canViewDashboard", dashboard);
|
||||
if (dashboard) {
|
||||
model.addAttribute("countSites", sites.findAll().size());
|
||||
model.addAttribute("countUsers", appUsers.list().size());
|
||||
model.addAttribute("countPlugins", runningPlugins.installed().size());
|
||||
}
|
||||
model.addAttribute("dashboardCards",
|
||||
dashboard ? cards.cardsFor(Realm.APPLICATION, principal, null) : List.of());
|
||||
model.addAttribute("contentTemplate", "operator/app/home");
|
||||
model.addAttribute("pageTitleKey", "op.app.home.title");
|
||||
return "operator/op-layout";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import mx.quest.runway.log.AppActivityLog;
|
||||
import mx.quest.runway.platform.LogLevelService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* Activity → Logs → <b>Log levels</b> ({@code /__app/logs/levels}): how much each logger writes to the server log,
|
||||
* changed at once and kept across restarts ({@link LogLevelService}). Platform administrators only, and every change
|
||||
* is recorded in the activity log, because DEBUG and TRACE can write request details to the server log.
|
||||
*/
|
||||
@Controller
|
||||
public class AppLogLevelsController {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(AppLogLevelsController.class);
|
||||
|
||||
private static final String SCREEN = "/__app/logs/levels";
|
||||
|
||||
private final LogLevelService levels;
|
||||
private final PlatformAuthority platformAuthority;
|
||||
private final AppActivityLog activity;
|
||||
private final MessageSource messages;
|
||||
|
||||
public AppLogLevelsController(LogLevelService levels, PlatformAuthority platformAuthority,
|
||||
AppActivityLog activity,
|
||||
@Qualifier("operatorAwareMessageSource") MessageSource messages) {
|
||||
this.levels = levels;
|
||||
this.platformAuthority = platformAuthority;
|
||||
this.activity = activity;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
@GetMapping(SCREEN)
|
||||
public String list(Authentication authentication, Model model) {
|
||||
platformAuthority.require(authentication);
|
||||
model.addAttribute("rows", levels.rows());
|
||||
model.addAttribute("levels", LogLevelService.LEVELS);
|
||||
model.addAttribute("contentTemplate", "operator/app/log-levels");
|
||||
model.addAttribute("pageTitleKey", "op.loglevels.title");
|
||||
return "operator/op-layout";
|
||||
}
|
||||
|
||||
/** Sets one logger's level ({@code level} blank: back to Default). */
|
||||
@PostMapping(SCREEN)
|
||||
public String set(@RequestParam(required = false) String logger, @RequestParam(required = false) String level,
|
||||
Authentication authentication, RedirectAttributes redirect) {
|
||||
platformAuthority.require(authentication);
|
||||
try {
|
||||
levels.set(logger, level);
|
||||
String shown = level == null || level.isBlank() ? "default" : level.strip().toUpperCase();
|
||||
activity.record(authentication.getName(), "platform.log-level-changed", logger.strip() + " " + shown);
|
||||
redirect.addFlashAttribute("flash", messages.getMessage("op.loglevels.saved",
|
||||
new Object[] {logger.strip(), shown}, "Saved.", LocaleContextHolder.getLocale()));
|
||||
} catch (LogLevelService.Invalid invalid) {
|
||||
redirect.addFlashAttribute("error", messages.getMessage("op.loglevels.invalid." + invalid.code(), null,
|
||||
invalid.getMessage(), LocaleContextHolder.getLocale()));
|
||||
} catch (RuntimeException failed) {
|
||||
// The logging system or the settings file refused: say so instead of a 500.
|
||||
log.warn("could not set the log level of {} to {}: {}", logger, level, failed.toString());
|
||||
redirect.addFlashAttribute("error", messages.getMessage("op.loglevels.failed", null,
|
||||
"The log level could not be set. The server log says why.", LocaleContextHolder.getLocale()));
|
||||
}
|
||||
return "redirect:" + SCREEN;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import mx.quest.runway.mail.PlatformMailer;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
/**
|
||||
* Serves the application-realm sign-in page ({@code GET /app/login}) on the operator chrome — a standalone,
|
||||
* menu-less Thymeleaf page (the login layout deliberately omits the topbar/menu but keeps the chrome and the
|
||||
* messages area). The {@code POST /app/login} is handled by Spring Security's form-login filter
|
||||
* ({@code AppSecurityConfig}), not a controller; the {@code ?error} / {@code ?logout} flags drive the page's
|
||||
* alerts. Replaces the interim {@code @ResponseBody} login that {@code AppConsoleController} used to serve.
|
||||
*
|
||||
* <p>The {@code recoveryEnabled} flag drives the "Forgot your password?" link: it is shown only when the
|
||||
* platform mail account is configured (there is no way to email a reset link otherwise).
|
||||
*/
|
||||
@Controller
|
||||
public class AppLoginController {
|
||||
|
||||
private final PlatformMailer mailer;
|
||||
|
||||
public AppLoginController(PlatformMailer mailer) {
|
||||
this.mailer = mailer;
|
||||
}
|
||||
|
||||
@GetMapping("/app/login")
|
||||
public String login(Model model) {
|
||||
model.addAttribute("recoveryEnabled", mailer.isConfigured());
|
||||
return "operator/login-app";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import mx.quest.runway.log.AppActivityLog;
|
||||
import mx.quest.runway.log.AuditPage;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
/**
|
||||
* The application console's <b>Activity → Logs</b> screen ({@code /__app/logs}) — the operator audit journal
|
||||
* from {@link AppActivityLog} (sign-ins, password recovery, sign-outs, and every platform mutation including
|
||||
* role and permission changes). Read-only.
|
||||
*
|
||||
* <p>The journal is parsed into rows (time, actor, action, detail) and can be filtered by a date range, an actor
|
||||
* and an action (both case-insensitive substrings), paged newest-first through the <b>whole retention window</b>,
|
||||
* and downloaded as CSV ({@code /__app/logs/export.csv}, at most {@link AuditView#MAX_EXPORT_ROWS} rows). Every
|
||||
* request reads within {@link mx.quest.runway.log.AuditJournal.Limits#DEFAULT}; when that budget ends a search
|
||||
* early the screen says so.
|
||||
*
|
||||
* <p><b>Gate:</b> both routes require the grantable {@code VIEW_AUDIT} application permission, enforced in
|
||||
* {@code AppSecurityConfig} (the master and wildcard administrators pass; an ordinary operator only once granted
|
||||
* it). The journal names who did what to every site and account, so the coarse operator role band is not enough.
|
||||
* Retention is a platform setting ({@code runway.app-activity.retention-days}), not editable here.
|
||||
*/
|
||||
@Controller
|
||||
public class AppLogsController {
|
||||
|
||||
private final AppActivityLog activity;
|
||||
private final MessageSource messages;
|
||||
|
||||
public AppLogsController(AppActivityLog activity,
|
||||
@Qualifier("operatorAwareMessageSource") MessageSource messages) {
|
||||
this.activity = activity;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
@GetMapping("/__app/logs")
|
||||
public String view(@RequestParam(required = false) String from, @RequestParam(required = false) String to,
|
||||
@RequestParam(required = false) String actor, @RequestParam(required = false) String action,
|
||||
@RequestParam(required = false) Integer page, Model model) {
|
||||
AuditView.Filter filter = AuditView.filter(from, to, actor, action, page);
|
||||
AuditPage result = activity.query(filter.query(), filter.page() * AuditView.PAGE_SIZE, AuditView.PAGE_SIZE);
|
||||
AuditView.populate(model, result, filter, "/__app/logs", "/__app/logs/export.csv",
|
||||
"op.applog.audit", "runway.app.audit", messages,
|
||||
LocaleContextHolder.getLocale());
|
||||
model.addAttribute("contentTemplate", "operator/app/logs");
|
||||
model.addAttribute("pageTitleKey", "op.applog.title");
|
||||
return "operator/op-layout";
|
||||
}
|
||||
|
||||
@GetMapping("/__app/logs/export.csv")
|
||||
public ResponseEntity<byte[]> export(@RequestParam(required = false) String from,
|
||||
@RequestParam(required = false) String to,
|
||||
@RequestParam(required = false) String actor,
|
||||
@RequestParam(required = false) String action) {
|
||||
AuditView.Filter filter = AuditView.filter(from, to, actor, action, 0);
|
||||
AuditPage result = activity.query(filter.query(), 0, AuditView.MAX_EXPORT_ROWS);
|
||||
return AuditView.csv(result, "runway-activity-" + LocalDate.now() + ".csv", messages,
|
||||
LocaleContextHolder.getLocale());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import mx.quest.runway.authz.AuthorizationAdminService;
|
||||
import mx.quest.runway.authz.PermissionCatalog;
|
||||
import mx.quest.runway.log.AppActivityLog;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
/**
|
||||
* The <b>application-realm</b> permissions matrix ({@code /__app/permissions}): an APPLICATION principal edits
|
||||
* application users' roles/grants and the application roles' deltas, with no tenancy. The realm is APPLICATION
|
||||
* by construction (this route only sits on the application security chain), so the scope is the app stores.
|
||||
* Every successful change is recorded to the application activity log ({@link AppActivityLog}).
|
||||
*/
|
||||
@Controller
|
||||
@RequestMapping("/__app/permissions")
|
||||
public class AppPermissionsController extends AbstractPermissionsController {
|
||||
|
||||
private final PlatformAuthority platformAuthority;
|
||||
private final AppActivityLog activity;
|
||||
|
||||
public AppPermissionsController(PermissionsMatrixService matrix, AuthorizationAdminService admin,
|
||||
PermissionCatalog catalog, PlatformAuthority platformAuthority,
|
||||
AppActivityLog activity) {
|
||||
super(matrix, admin, catalog);
|
||||
this.platformAuthority = platformAuthority;
|
||||
this.activity = activity;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void audit(String actor, String action, String detail) {
|
||||
activity.record(actor, action, detail);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void requireAdmin(Authentication authentication) {
|
||||
platformAuthority.require(authentication); // master / wildcard of the application realm
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Realm realm() {
|
||||
return Realm.APPLICATION;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String tenancyId() {
|
||||
return null; // the application realm has no tenancy
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String basePath() {
|
||||
return "/__app/permissions";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String contentTemplate() {
|
||||
return "operator/permissions";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String titleKey() {
|
||||
return "op.permissions.title";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Locale;
|
||||
import java.util.function.Function;
|
||||
import mx.quest.runway.recovery.PasswordRecoveryService;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
|
||||
|
||||
/**
|
||||
* The <b>application-realm</b> password-recovery flow — {@code /app/forgot-password} and {@code /app/reset},
|
||||
* the self-service counterpart to {@code /app/login}. A user requests a link by email; the platform mails a
|
||||
* time-limited, single-use link back; opening it sets a new password. All logic lives in
|
||||
* {@link PasswordRecoveryService}; this controller only renders the two standalone pages and threads the
|
||||
* realm-specific chrome (brand, accent, URLs).
|
||||
*
|
||||
* <p>The request path is deliberately <b>non-enumerating</b>: a POST always shows the same neutral
|
||||
* confirmation, whether or not any account matched.
|
||||
*/
|
||||
@Controller
|
||||
public class AppRecoveryController {
|
||||
|
||||
private static final String BRAND = "Runway";
|
||||
private static final int MIN_PASSWORD_LENGTH = 8;
|
||||
|
||||
private final PasswordRecoveryService recovery;
|
||||
|
||||
public AppRecoveryController(PasswordRecoveryService recovery) {
|
||||
this.recovery = recovery;
|
||||
}
|
||||
|
||||
@GetMapping("/app/forgot-password")
|
||||
public String forgot(@RequestParam(required = false) String sent, Model model) {
|
||||
chrome(model, "/app/forgot-password");
|
||||
model.addAttribute("sent", sent != null);
|
||||
return "operator/recovery-forgot";
|
||||
}
|
||||
|
||||
@PostMapping("/app/forgot-password")
|
||||
public String requestLink(@RequestParam(required = false) String email, Locale locale) {
|
||||
String base = ServletUriComponentsBuilder.fromCurrentContextPath().build().toUriString();
|
||||
Function<String, String> linkFor =
|
||||
token -> base + "/app/reset?token=" + URLEncoder.encode(token, StandardCharsets.UTF_8);
|
||||
recovery.requestApp(email, BRAND, linkFor, locale);
|
||||
// Post-redirect-get to the neutral confirmation (no account enumeration, no form re-submit).
|
||||
return "redirect:/app/forgot-password?sent";
|
||||
}
|
||||
|
||||
@GetMapping("/app/reset")
|
||||
public String resetForm(@RequestParam(required = false) String token, Model model) {
|
||||
chrome(model, "/app/reset");
|
||||
recovery.validateApp(token).ifPresentOrElse(
|
||||
grant -> {
|
||||
model.addAttribute("valid", true);
|
||||
model.addAttribute("token", token);
|
||||
model.addAttribute("username", grant.username());
|
||||
},
|
||||
() -> model.addAttribute("valid", false));
|
||||
return "operator/recovery-reset";
|
||||
}
|
||||
|
||||
@PostMapping("/app/reset")
|
||||
public String doReset(@RequestParam(required = false) String token,
|
||||
@RequestParam(required = false) String password,
|
||||
@RequestParam(required = false) String confirm, Model model) {
|
||||
String error = passwordError(password, confirm);
|
||||
if (error != null) {
|
||||
chrome(model, "/app/reset");
|
||||
model.addAttribute("valid", true);
|
||||
model.addAttribute("token", token);
|
||||
model.addAttribute("error", error);
|
||||
return "operator/recovery-reset";
|
||||
}
|
||||
if (recovery.resetApp(token, password) == PasswordRecoveryService.ResetOutcome.OK) {
|
||||
return "redirect:/app/login?reset";
|
||||
}
|
||||
chrome(model, "/app/reset");
|
||||
model.addAttribute("valid", false); // unknown/expired/already-used link, or the account is gone
|
||||
return "operator/recovery-reset";
|
||||
}
|
||||
|
||||
/** The realm-specific chrome the shared recovery templates bind (brand, accent, form + back-link URLs). */
|
||||
private void chrome(Model model, String postUrl) {
|
||||
model.addAttribute("brand", BRAND);
|
||||
model.addAttribute("accentBorder", "border-primary");
|
||||
model.addAttribute("accentBtn", "btn-primary");
|
||||
model.addAttribute("loginUrl", "/app/login");
|
||||
model.addAttribute("postUrl", postUrl);
|
||||
}
|
||||
|
||||
/** Returns a message-key suffix for an invalid new password, or {@code null} when it is acceptable. */
|
||||
private static String passwordError(String password, String confirm) {
|
||||
if (password == null || password.length() < MIN_PASSWORD_LENGTH) {
|
||||
return "weak";
|
||||
}
|
||||
if (!password.equals(confirm)) {
|
||||
return "mismatch";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import jakarta.mail.MessagingException;
|
||||
import java.util.Locale;
|
||||
import mx.quest.runway.crypto.SecretCipher;
|
||||
import mx.quest.runway.log.AppActivityLog;
|
||||
import mx.quest.runway.mail.PlatformMailer;
|
||||
import mx.quest.runway.platform.HostSettings;
|
||||
import mx.quest.runway.platform.PlatformSettings;
|
||||
import mx.quest.runway.platform.PlatformSettingsStore;
|
||||
import mx.quest.runway.security.PasswordStrength;
|
||||
import mx.quest.runway.security.RunwaySecurityProperties;
|
||||
import mx.quest.runway.site.SiteStore;
|
||||
import mx.quest.runway.web.CompressionFilter;
|
||||
import mx.quest.runway.web.TemplateCacheService;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* The application-realm <b>Settings</b> screen ({@code /__app/settings}) — platform-wide operator settings
|
||||
* held in {@code external/platform.yml} ({@link PlatformSettingsStore}), not per-tenant and outside every
|
||||
* tenant folder. A <b>platform</b> operation, gated to the master/wildcard admin via {@link PlatformAuthority}.
|
||||
*
|
||||
* <p>The settings:
|
||||
* <ul>
|
||||
* <li><b>Default site</b> — the catch-all that answers requests whose Host isn't bound to another site.
|
||||
* Applies immediately (site resolution reads it live).</li>
|
||||
* <li><b>Password strength</b> — the Argon2id memory-cost profile. Applies to <b>new</b> hashes on the next
|
||||
* restart (existing PHC hashes verify regardless).</li>
|
||||
* <li><b>Node name</b> — a human-friendly identity for this node, shown on About. Blank defers to the
|
||||
* {@code runway.node.name} config, else the host name. Applies immediately.</li>
|
||||
* <li><b>Response compression</b> — a master switch plus per-encoding Brotli / gzip switches. Applies
|
||||
* immediately: {@link CompressionFilter} resolves them live per request.</li>
|
||||
* <li><b>Platform mail (SMTP)</b> — the account used for application-level messages (password recovery, and
|
||||
* any future operator notifications) for BOTH realms; never for site-generated mail. The password is
|
||||
* stored {@code ENC(...)}-encrypted ({@link SecretCipher}) and masked on the form (a blank field on save
|
||||
* keeps the stored secret). A "Send test email" action verifies the account. Applies immediately.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Plus one maintenance action, <b>Clear template cache</b> ({@link #clearTemplateCache}). It sits here rather
|
||||
* than on the read-only About page because it mutates server state and needs this screen's platform-admin gate.
|
||||
*/
|
||||
@Controller
|
||||
public class AppSettingsController {
|
||||
|
||||
private final PlatformSettingsStore platform;
|
||||
private final SiteStore sites;
|
||||
private final RunwaySecurityProperties security;
|
||||
private final PlatformAuthority platformAuthority;
|
||||
private final CompressionFilter compression;
|
||||
private final SecretCipher cipher;
|
||||
private final PlatformMailer mailer;
|
||||
private final AppActivityLog activity;
|
||||
private final TemplateCacheService templateCache;
|
||||
private final MessageSource messages;
|
||||
private final HostSettings host;
|
||||
|
||||
private static final String COMPRESSION_ENABLED = "runway.compression.enabled";
|
||||
private static final String BROTLI_ENABLED = "runway.compression.brotli.enabled";
|
||||
private static final String GZIP_ENABLED = "runway.compression.gzip.enabled";
|
||||
|
||||
public AppSettingsController(PlatformSettingsStore platform, SiteStore sites,
|
||||
RunwaySecurityProperties security, PlatformAuthority platformAuthority,
|
||||
CompressionFilter compression, SecretCipher cipher, PlatformMailer mailer,
|
||||
AppActivityLog activity, TemplateCacheService templateCache,
|
||||
@Qualifier("operatorAwareMessageSource") MessageSource messages,
|
||||
HostSettings host) {
|
||||
this.host = host;
|
||||
this.templateCache = templateCache;
|
||||
this.messages = messages;
|
||||
this.platform = platform;
|
||||
this.sites = sites;
|
||||
this.security = security;
|
||||
this.platformAuthority = platformAuthority;
|
||||
this.compression = compression;
|
||||
this.cipher = cipher;
|
||||
this.mailer = mailer;
|
||||
this.activity = activity;
|
||||
}
|
||||
|
||||
@GetMapping("/__app/settings")
|
||||
public String form(Authentication authentication, Model model) {
|
||||
platformAuthority.require(authentication);
|
||||
populate(model, platform.get());
|
||||
model.addAttribute("contentTemplate", "operator/app/settings");
|
||||
model.addAttribute("pageTitleKey", "op.settings.platform.title");
|
||||
return "operator/op-layout";
|
||||
}
|
||||
|
||||
@PostMapping("/__app/settings")
|
||||
public String save(@RequestParam(required = false) String defaultSiteId,
|
||||
@RequestParam(required = false) String passwordStrength,
|
||||
@RequestParam(required = false) String nodeName,
|
||||
@RequestParam(name = "compressionEnabled", defaultValue = "false") boolean compressionEnabled,
|
||||
@RequestParam(name = "brotliEnabled", defaultValue = "false") boolean brotliEnabled,
|
||||
@RequestParam(name = "gzipEnabled", defaultValue = "false") boolean gzipEnabled,
|
||||
@RequestParam(required = false) String smtpHost,
|
||||
@RequestParam(required = false) String smtpPort,
|
||||
@RequestParam(name = "smtpAuth", defaultValue = "false") boolean smtpAuth,
|
||||
@RequestParam(required = false) String smtpUsername,
|
||||
@RequestParam(required = false) String smtpPassword,
|
||||
@RequestParam(required = false) String smtpFrom,
|
||||
@RequestParam(name = "smtpStarttls", defaultValue = "false") boolean smtpStarttls,
|
||||
@RequestParam(name = "smtpSsl", defaultValue = "false") boolean smtpSsl,
|
||||
Authentication authentication, RedirectAttributes redirect) {
|
||||
platformAuthority.require(authentication);
|
||||
try {
|
||||
String site = normalize(defaultSiteId);
|
||||
String strength = normalize(passwordStrength);
|
||||
if (strength != null) {
|
||||
// Validate against the enum so a bad value never reaches the encoder factory at startup.
|
||||
PasswordStrength.valueOf(strength.toUpperCase(Locale.ROOT));
|
||||
strength = strength.toUpperCase(Locale.ROOT);
|
||||
}
|
||||
String level = strength;
|
||||
// A checkbox submits nothing when unchecked (→ the false default) and its value when checked; so the
|
||||
// three compression flags are always explicit here — stored as an override the live filter reads.
|
||||
// A switch the server itself sets is not stored: the host's value wins (one home per setting).
|
||||
Boolean compressionOverride = host.setOnHost(COMPRESSION_ENABLED) ? null : compressionEnabled;
|
||||
Boolean brotliOverride = host.setOnHost(BROTLI_ENABLED) ? null : brotliEnabled;
|
||||
Boolean gzipOverride = host.setOnHost(GZIP_ENABLED) ? null : gzipEnabled;
|
||||
// One atomic change against the latest settings: the SMTP block keeps the stored password on a blank
|
||||
// field, and every field this screen does not own (kernel settings, quotas, embed hosts, log levels)
|
||||
// is carried over as it is now, not as it was when this request started.
|
||||
// The site's existence is checked inside the change: a site deleted while this saves cannot become the
|
||||
// default after its deletion cleared the pointer (the deletion's own change waits for this one).
|
||||
platform.update(current -> {
|
||||
if (site != null && !sites.exists(site)) {
|
||||
throw new IllegalArgumentException("no such site: " + site);
|
||||
}
|
||||
return new PlatformSettings(site, level, normalize(nodeName),
|
||||
compressionOverride, brotliOverride, gzipOverride,
|
||||
smtp(current.smtp(), smtpHost, smtpPort, smtpAuth, smtpUsername, smtpPassword, smtpFrom,
|
||||
smtpStarttls, smtpSsl),
|
||||
current.settings(), current.siteQuotas(), current.embedHosts(), current.logLevels(),
|
||||
current.siteStorageCeilings());
|
||||
});
|
||||
activity.record(authentication.getName(), "platform.settings-changed", "");
|
||||
redirect.addFlashAttribute("flash", "Platform settings saved.");
|
||||
} catch (IllegalArgumentException invalid) {
|
||||
redirect.addFlashAttribute("error", invalid.getMessage());
|
||||
}
|
||||
return "redirect:/__app/settings";
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a diagnostic message through the platform relay to verify the SMTP account from the console. The
|
||||
* recipient defaults to the configured From address when {@code testTo} is blank.
|
||||
*/
|
||||
@PostMapping("/__app/settings/test-email")
|
||||
public String testEmail(@RequestParam(required = false) String testTo,
|
||||
Authentication authentication, RedirectAttributes redirect) {
|
||||
platformAuthority.require(authentication);
|
||||
PlatformSettings.Smtp smtp = platform.get().smtp();
|
||||
if (smtp == null || !smtp.isConfigured()) {
|
||||
redirect.addFlashAttribute("error", "Configure and save the platform mail account first.");
|
||||
return "redirect:/__app/settings";
|
||||
}
|
||||
String to = normalize(testTo) != null ? normalize(testTo) : smtp.from();
|
||||
try {
|
||||
mailer.send(to, "Runway platform mail test",
|
||||
"This is a test message from Runway.\n\n"
|
||||
+ "If you received it, the platform mail account is configured correctly and can be "
|
||||
+ "used for password recovery and other application messages.");
|
||||
activity.record(authentication.getName(), "platform.test-email", to);
|
||||
redirect.addFlashAttribute("flash", "Test email sent to " + to + ".");
|
||||
} catch (MessagingException e) {
|
||||
redirect.addFlashAttribute("error", "Test email failed: " + rootMessage(e));
|
||||
}
|
||||
return "redirect:/__app/settings";
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the parsed-template cache ({@link TemplateCacheService#evictAll()}). Runway runs the Thymeleaf cache
|
||||
* ON, evicts precisely on every console edit, and re-reads a template whose file changed on disk on its next use
|
||||
* ({@code FileStampValidity}), so this is not needed in normal use; it is a backstop (e.g. a file system whose
|
||||
* timestamps cannot be trusted). It affects <b>this node only</b> — on a cluster, run it on
|
||||
* each node. Harmless: the next request of each page re-parses its template. Platform-admin gated like the
|
||||
* rest of this screen, and recorded in the activity log.
|
||||
*/
|
||||
@PostMapping("/__app/settings/clear-template-cache")
|
||||
public String clearTemplateCache(Authentication authentication, RedirectAttributes redirect) {
|
||||
platformAuthority.require(authentication);
|
||||
templateCache.evictAll();
|
||||
activity.record(authentication.getName(), "platform.template-cache-cleared", "");
|
||||
redirect.addFlashAttribute("flash", messages.getMessage("op.settings.platform.cache.cleared", null,
|
||||
"Template cache cleared.", LocaleContextHolder.getLocale()));
|
||||
return "redirect:/__app/settings";
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the SMTP block from the submitted form, encrypting a newly-entered password and <b>preserving</b>
|
||||
* the stored secret when the password field is left blank (the masked-secret convention). Returns
|
||||
* {@code null} when nothing is set, so an untouched form does not litter {@code platform.yml} with an
|
||||
* all-blank block.
|
||||
*/
|
||||
private PlatformSettings.Smtp smtp(PlatformSettings.Smtp current, String host, String port, boolean auth,
|
||||
String username, String password, String from, boolean starttls,
|
||||
boolean ssl) {
|
||||
String h = normalize(host);
|
||||
String u = normalize(username);
|
||||
String f = normalize(from);
|
||||
Integer p = port(port);
|
||||
String stored = current != null ? current.password() : null;
|
||||
String secret;
|
||||
if (normalize(password) == null) {
|
||||
secret = stored; // blank field ⇒ keep the stored (encrypted) secret
|
||||
} else {
|
||||
if (!cipher.isAvailable()) {
|
||||
throw new IllegalArgumentException("Cannot store an SMTP password: no encryption key is "
|
||||
+ "configured (set runway.security.secret-key).");
|
||||
}
|
||||
secret = cipher.encrypt(password.trim());
|
||||
}
|
||||
boolean empty = h == null && f == null && u == null
|
||||
&& (secret == null || secret.isBlank()) && !auth && !starttls && !ssl && p == null;
|
||||
if (empty) {
|
||||
return null;
|
||||
}
|
||||
return new PlatformSettings.Smtp(h, p, auth, u, secret, f, starttls, ssl);
|
||||
}
|
||||
|
||||
private void populate(Model model, PlatformSettings current) {
|
||||
model.addAttribute("sites", sites.findAll());
|
||||
model.addAttribute("currentDefaultSiteId", current.defaultSite().orElse(""));
|
||||
model.addAttribute("passwordStrengths", PasswordStrength.values());
|
||||
model.addAttribute("currentPasswordStrength", current.strength().orElse(""));
|
||||
// The profile in force when no override is set (the config default) — shown as the effective baseline.
|
||||
model.addAttribute("configDefaultStrength", security.getPasswordStrength().name());
|
||||
model.addAttribute("currentNodeName", current.node().orElse(""));
|
||||
// Compression switches seed from the EFFECTIVE current state (platform override, else config default),
|
||||
// read from the filter so the form and the running behaviour never disagree.
|
||||
model.addAttribute("compressionEnabled", compression.enabled());
|
||||
model.addAttribute("brotliEnabled", compression.brotliOn());
|
||||
model.addAttribute("gzipEnabled", compression.gzipOn());
|
||||
// A switch the server itself sets is shown locked, with where it is set.
|
||||
model.addAttribute("compLock", host.origin(COMPRESSION_ENABLED).orElse(null));
|
||||
model.addAttribute("brotliLock", host.origin(BROTLI_ENABLED).orElse(null));
|
||||
model.addAttribute("gzipLock", host.origin(GZIP_ENABLED).orElse(null));
|
||||
model.addAttribute("brotliNativeAvailable", compression.brotliNativeAvailable());
|
||||
// Platform mail: seed the visible fields; the secret is NEVER sent to the form — only a "configured" flag.
|
||||
PlatformSettings.Smtp smtp = current.smtp();
|
||||
model.addAttribute("smtpHost", smtp != null ? orEmpty(smtp.host()) : "");
|
||||
model.addAttribute("smtpPort", smtp != null ? smtp.port() : null);
|
||||
model.addAttribute("smtpAuth", smtp != null && Boolean.TRUE.equals(smtp.auth()));
|
||||
model.addAttribute("smtpUsername", smtp != null ? orEmpty(smtp.username()) : "");
|
||||
model.addAttribute("smtpFrom", smtp != null ? orEmpty(smtp.from()) : "");
|
||||
model.addAttribute("smtpStarttls", smtp != null && Boolean.TRUE.equals(smtp.starttls()));
|
||||
model.addAttribute("smtpSsl", smtp != null && Boolean.TRUE.equals(smtp.ssl()));
|
||||
model.addAttribute("smtpPasswordConfigured",
|
||||
smtp != null && smtp.password() != null && !smtp.password().isBlank());
|
||||
model.addAttribute("smtpConfigured", smtp != null && smtp.isConfigured());
|
||||
}
|
||||
|
||||
/** Trims and maps blank to {@code null} (blank = "unset this setting"). */
|
||||
private static String normalize(String value) {
|
||||
return (value == null || value.isBlank()) ? null : value.trim();
|
||||
}
|
||||
|
||||
private static String orEmpty(String value) {
|
||||
return value == null ? "" : value;
|
||||
}
|
||||
|
||||
/** Parses the port field: blank ⇒ {@code null} (use the default); otherwise validated to 1..65535. */
|
||||
private static Integer port(String raw) {
|
||||
String v = normalize(raw);
|
||||
if (v == null) {
|
||||
return null;
|
||||
}
|
||||
int port;
|
||||
try {
|
||||
port = Integer.parseInt(v);
|
||||
} catch (NumberFormatException e) {
|
||||
throw new IllegalArgumentException("SMTP port must be a number (1..65535).");
|
||||
}
|
||||
if (port < 1 || port > 65535) {
|
||||
throw new IllegalArgumentException("SMTP port must be in 1..65535.");
|
||||
}
|
||||
return port;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import mx.quest.runway.authz.AuthorizationAdminService;
|
||||
import mx.quest.runway.authz.Role;
|
||||
import mx.quest.runway.authz.RoleStore;
|
||||
import mx.quest.runway.log.AppActivityLog;
|
||||
import mx.quest.runway.security.AppUserStore;
|
||||
import mx.quest.runway.security.Roles;
|
||||
import mx.quest.runway.security.RunwaySecurityProperties;
|
||||
import mx.quest.runway.security.RunwayUserDetails;
|
||||
import mx.quest.runway.security.User;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* The application-realm <b>App users</b> screen ({@code /__app/users}): the platform operators. List, create
|
||||
* (as {@code SYSTEMADMIN} or {@code SYSTEMOPERATOR} — never a second superadmin, which the store's fail-closed
|
||||
* validation forbids), edit (display name, recovery email, access tier), suspend / resume, reset a password, and
|
||||
* delete. Thin wiring of {@link AppUserStore} and {@link ConsoleUserService}; a platform operation gated to the
|
||||
* master/wildcard admin. The <b>pinned application superadmin</b> can never be deleted, suspended or have its tier
|
||||
* changed here (the undeletable-last-master rule) — its identity is guarded structurally; only its profile
|
||||
* (display name, email) is editable.
|
||||
*/
|
||||
@Controller
|
||||
@RequestMapping("/__app/users")
|
||||
public class AppUsersController {
|
||||
|
||||
private final AppUserStore users;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final RunwaySecurityProperties security;
|
||||
private final PlatformAuthority platformAuthority;
|
||||
private final AppActivityLog activity;
|
||||
private final RoleStore roleStore;
|
||||
private final AuthorizationAdminService admin;
|
||||
private final ConsoleUserService userService;
|
||||
private final MessageSource messages;
|
||||
|
||||
public AppUsersController(AppUserStore users, PasswordEncoder passwordEncoder,
|
||||
RunwaySecurityProperties security, PlatformAuthority platformAuthority,
|
||||
AppActivityLog activity, RoleStore roleStore, AuthorizationAdminService admin,
|
||||
ConsoleUserService userService,
|
||||
@Qualifier("operatorAwareMessageSource") MessageSource messages) {
|
||||
this.users = users;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.security = security;
|
||||
this.platformAuthority = platformAuthority;
|
||||
this.activity = activity;
|
||||
this.roleStore = roleStore;
|
||||
this.admin = admin;
|
||||
this.userService = userService;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String list(Model model, Authentication authentication) {
|
||||
model.addAttribute("users", users.list());
|
||||
model.addAttribute("masterId", security.getAppMasterId());
|
||||
// The signed-in operator's own row offers no Suspend and no tier change (the service refuses both).
|
||||
model.addAttribute("selfId", authentication != null
|
||||
&& authentication.getPrincipal() instanceof RunwayUserDetails self ? self.principalId() : "");
|
||||
model.addAttribute("customRoles", roleStore.appRoleList().stream().map(Role::name).toList());
|
||||
model.addAttribute("contentTemplate", "operator/app/users");
|
||||
model.addAttribute("pageTitleKey", "op.users.title");
|
||||
return "operator/op-layout";
|
||||
}
|
||||
|
||||
@PostMapping("/create")
|
||||
public String create(@RequestParam String username, @RequestParam String password,
|
||||
@RequestParam(required = false) String displayName, @RequestParam(required = false) String email,
|
||||
@RequestParam String tier, @RequestParam(name = "roles", required = false) List<String> roles,
|
||||
Authentication authentication, RedirectAttributes redirect) {
|
||||
platformAuthority.require(authentication);
|
||||
try {
|
||||
if (!Roles.SYSTEM_ADMIN.equals(tier) && !Roles.SYSTEM_OPERATOR.equals(tier)) {
|
||||
throw new IllegalArgumentException("invalid access tier '" + tier + "'");
|
||||
}
|
||||
Set<String> customNames = roleStore.appRoleList().stream().map(Role::name)
|
||||
.collect(java.util.stream.Collectors.toSet());
|
||||
List<String> requested = new ArrayList<>();
|
||||
if (roles != null) {
|
||||
for (String r : roles) {
|
||||
if (r != null && !r.isBlank() && !requested.contains(r)) {
|
||||
if (!customNames.contains(r)) {
|
||||
throw new IllegalArgumentException("no such custom role '" + r + "'");
|
||||
}
|
||||
requested.add(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
String newId = UUID.randomUUID().toString();
|
||||
users.save(new User(newId, username.trim(), passwordEncoder.encode(password),
|
||||
orBlank(displayName, username.trim()), orBlank(email, ""), true, false, Realm.APPLICATION,
|
||||
Set.of(tier), java.util.List.of()));
|
||||
RunwayUserDetails actor = actor(authentication);
|
||||
List<String> assigned = new ArrayList<>();
|
||||
for (String r : requested) {
|
||||
try {
|
||||
admin.assignRole(actor, null, newId, r); // app-realm grant file; bounded-grant enforced
|
||||
assigned.add(r);
|
||||
} catch (RuntimeException ex) {
|
||||
// Roll back COMPLETELY: strip grant-file roles written so far, then delete the user.
|
||||
for (String done : assigned) {
|
||||
try {
|
||||
admin.revokeRole(actor, null, newId, done);
|
||||
} catch (RuntimeException ignored) {
|
||||
// best-effort cleanup; the user delete below removes the principal regardless
|
||||
}
|
||||
}
|
||||
users.delete(newId);
|
||||
throw new IllegalArgumentException("could not assign role '" + r + "': " + ex.getMessage());
|
||||
}
|
||||
}
|
||||
activity.record(authentication.getName(), "appuser.created", username.trim() + " (" + tier + ")");
|
||||
redirect.addFlashAttribute("flash", "Created application user '" + username.trim() + "'"
|
||||
+ (requested.isEmpty() ? "." : " with role(s): " + String.join(", ", requested) + "."));
|
||||
} catch (mx.quest.runway.security.UsernameTakenException e) {
|
||||
// Held by another application user or the pinned superadmin (the store checks, under its lock).
|
||||
// Before this check a duplicate was written and the NEXT start refused the app realm.
|
||||
redirect.addFlashAttribute("error", message("op.users.error.usernameTaken", e.username()));
|
||||
} catch (RuntimeException e) {
|
||||
redirect.addFlashAttribute("error", e.getMessage());
|
||||
}
|
||||
return "redirect:/__app/users";
|
||||
}
|
||||
|
||||
private RunwayUserDetails actor(Authentication authentication) {
|
||||
if (authentication != null && authentication.getPrincipal() instanceof RunwayUserDetails principal) {
|
||||
return principal;
|
||||
}
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "not authenticated in this realm");
|
||||
}
|
||||
|
||||
/**
|
||||
* Edits an application user's display name, recovery email and — except for the pinned superadmin and the
|
||||
* operator's own account — access tier. Guards live in {@link ConsoleUserService}; a refusal is a flash error.
|
||||
*/
|
||||
@PostMapping("/{principalId}/edit")
|
||||
public String edit(@PathVariable String principalId, @RequestParam(required = false) String displayName,
|
||||
@RequestParam(required = false) String email, @RequestParam(required = false) String tier,
|
||||
Authentication authentication, RedirectAttributes redirect) {
|
||||
platformAuthority.require(authentication);
|
||||
try {
|
||||
User updated = userService.updateAppUser(actor(authentication), principalId, displayName, email, tier);
|
||||
activity.record(authentication.getName(), "appuser.updated",
|
||||
updated.username() + " (" + String.join(",", new java.util.TreeSet<>(updated.roles())) + ")");
|
||||
redirect.addFlashAttribute("flash", message("op.users.edit.saved", updated.username()));
|
||||
} catch (ConsoleUserService.UserEditException e) {
|
||||
redirect.addFlashAttribute("error", error(e));
|
||||
} catch (IllegalStateException | java.io.UncheckedIOException e) {
|
||||
redirect.addFlashAttribute("error", e.getMessage()); // a store guard or a failed write: never a 500
|
||||
}
|
||||
return "redirect:/__app/users";
|
||||
}
|
||||
|
||||
/** Suspends an application user: sign-in refused, and an open session is dropped on its next request. */
|
||||
@PostMapping("/{principalId}/suspend")
|
||||
public String suspend(@PathVariable String principalId, Authentication authentication,
|
||||
RedirectAttributes redirect) {
|
||||
return setEnabled(principalId, false, authentication, redirect);
|
||||
}
|
||||
|
||||
/** Resumes a suspended application user (sign-in allowed again; the password is unchanged). */
|
||||
@PostMapping("/{principalId}/resume")
|
||||
public String resume(@PathVariable String principalId, Authentication authentication,
|
||||
RedirectAttributes redirect) {
|
||||
return setEnabled(principalId, true, authentication, redirect);
|
||||
}
|
||||
|
||||
private String setEnabled(String principalId, boolean enabled, Authentication authentication,
|
||||
RedirectAttributes redirect) {
|
||||
platformAuthority.require(authentication);
|
||||
try {
|
||||
User updated = userService.setAppUserEnabled(actor(authentication), principalId, enabled);
|
||||
activity.record(authentication.getName(), enabled ? "appuser.resumed" : "appuser.suspended",
|
||||
updated.username());
|
||||
redirect.addFlashAttribute("flash",
|
||||
message(enabled ? "op.users.resumed" : "op.users.suspended", updated.username()));
|
||||
} catch (ConsoleUserService.UserEditException e) {
|
||||
redirect.addFlashAttribute("error", error(e));
|
||||
} catch (IllegalStateException | java.io.UncheckedIOException e) {
|
||||
redirect.addFlashAttribute("error", e.getMessage()); // a store guard or a failed write: never a 500
|
||||
}
|
||||
return "redirect:/__app/users";
|
||||
}
|
||||
|
||||
private String message(String key, Object arg) {
|
||||
return messages.getMessage(key, new Object[] {arg}, key, LocaleContextHolder.getLocale());
|
||||
}
|
||||
|
||||
private String error(ConsoleUserService.UserEditException e) {
|
||||
return messages.getMessage("op.users.error." + e.code(), null, e.getMessage(),
|
||||
LocaleContextHolder.getLocale());
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets another user's password. Every open session of that user ends on its next request
|
||||
* ({@code AccountStateFilter} sees the hash change); an administrator resetting their OWN password here keeps
|
||||
* this session, like the Account screen.
|
||||
*/
|
||||
@PostMapping("/reset-password")
|
||||
public String resetPassword(@RequestParam String principalId, @RequestParam String password,
|
||||
Authentication authentication, RedirectAttributes redirect,
|
||||
jakarta.servlet.http.HttpServletRequest request) {
|
||||
platformAuthority.require(authentication);
|
||||
try {
|
||||
User user = users.findByPrincipalId(principalId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("no such user"));
|
||||
User updated = user.withPasswordHash(passwordEncoder.encode(password));
|
||||
users.save(updated);
|
||||
mx.quest.runway.security.AccountStateFilter.rebindIfSelf(request, updated);
|
||||
activity.record(authentication.getName(), "appuser.password-reset", user.username());
|
||||
redirect.addFlashAttribute("flash", "Reset the password for '" + user.username() + "'.");
|
||||
} catch (RuntimeException e) {
|
||||
redirect.addFlashAttribute("error", e.getMessage());
|
||||
}
|
||||
return "redirect:/__app/users";
|
||||
}
|
||||
|
||||
@PostMapping("/{principalId}/delete")
|
||||
public String delete(@PathVariable String principalId,
|
||||
Authentication authentication, RedirectAttributes redirect) {
|
||||
platformAuthority.require(authentication);
|
||||
if (principalId.equals(security.getAppMasterId())) {
|
||||
redirect.addFlashAttribute("error", "The application superadmin cannot be deleted.");
|
||||
return "redirect:/__app/users";
|
||||
}
|
||||
try {
|
||||
// Read the record first: once deleted, only the opaque principal id would be left to journal, and the
|
||||
// journal names people by username like every other entry. The id follows in brackets, so a later
|
||||
// user re-created under the same name stays distinguishable from this one.
|
||||
String username = users.findByPrincipalId(principalId).map(User::username).orElse(principalId);
|
||||
boolean deleted = users.delete(principalId);
|
||||
if (deleted) {
|
||||
activity.record(authentication.getName(), "appuser.deleted", username + " (id " + principalId + ")");
|
||||
}
|
||||
redirect.addFlashAttribute(deleted ? "flash" : "error", deleted ? "Deleted the user." : "No such user.");
|
||||
} catch (RuntimeException e) {
|
||||
redirect.addFlashAttribute("error", e.getMessage());
|
||||
}
|
||||
return "redirect:/__app/users";
|
||||
}
|
||||
|
||||
private static String orBlank(String value, String fallback) {
|
||||
return value == null || value.isBlank() ? fallback : value.trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.web.RequestPaths;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
|
||||
/**
|
||||
* The {@code Cache-Control} policy of the self-hosted console assets ({@code /__assets/**}), chosen per request:
|
||||
*
|
||||
* <ul>
|
||||
* <li><b>Versioned</b> ({@code ?v=<token>}, see {@link AssetVersion}) — {@value #VERSIONED}: the URL changes with
|
||||
* every release, so a day without revalidation can never serve a stale file.</li>
|
||||
* <li><b>Unversioned</b> — {@value #UNVERSIONED}: the browser may keep the file but must revalidate it before
|
||||
* each use ({@code Last-Modified} makes that a cheap {@code 304} while nothing changed). Any reference that
|
||||
* forgot its {@code ?v=} — including one in a plugin's own template — is therefore correct-but-slower after
|
||||
* an upgrade, never stale for a day. (Before this policy every asset was cached for a day regardless, and the
|
||||
* page editor kept running the previous release's script after an upgrade.)</li>
|
||||
* <li><b>Fonts</b> (woff2, woff, ttf, otf, eot) — {@value #VERSIONED} even without {@code ?v=}: a font is reached
|
||||
* through a <em>relative</em> {@code url(../webfonts/…)} inside a stylesheet, which can never carry the token,
|
||||
* so forcing revalidation would make every console page re-ask for every font. This is the long-standing
|
||||
* one-day policy, kept unchanged on purpose.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Runs as an MVC interceptor on the asset handler's mapping, <b>before</b> the handler: the
|
||||
* {@code ResourceHttpRequestHandler} is registered with no cache period, so it never overwrites the header set
|
||||
* here.
|
||||
*
|
||||
* <p><b>What counts as versioned:</b> a {@code v} made of digits only — the shape every {@link AssetVersion} token
|
||||
* has. Anything else counts as unversioned, notably {@code v=} (blank) and {@code v=null}, which is what a template
|
||||
* renders when its model lacks {@code assetVersion}: caching such a URL for a day would pin it to whatever file
|
||||
* was current, across every later release, because the URL never changes.
|
||||
*/
|
||||
public class AssetCachePolicy implements HandlerInterceptor {
|
||||
|
||||
/** The policy for a versioned request (and for fonts). */
|
||||
public static final String VERSIONED = "max-age=86400";
|
||||
/** The policy for an unversioned request: store, but revalidate before every use. */
|
||||
public static final String UNVERSIONED = "no-cache";
|
||||
|
||||
private static final Set<String> FONT_TYPES = Set.of("woff2", "woff", "ttf", "otf", "eot");
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
|
||||
response.setHeader(HttpHeaders.CACHE_CONTROL, cacheControlFor(request));
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The {@code Cache-Control} value for an asset request (see the class contract). */
|
||||
static String cacheControlFor(HttpServletRequest request) {
|
||||
String version = request.getParameter(AssetVersion.PARAM);
|
||||
if (isToken(version)) {
|
||||
return VERSIONED;
|
||||
}
|
||||
return isFont(RequestPaths.normalized(request)) ? VERSIONED : UNVERSIONED;
|
||||
}
|
||||
|
||||
/** Whether {@code v} has the shape of an {@link AssetVersion} token: non-empty, ASCII digits only. */
|
||||
private static boolean isToken(String v) {
|
||||
if (v == null || v.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < v.length(); i++) {
|
||||
char c = v.charAt(i);
|
||||
if (c < '0' || c > '9') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean isFont(String uri) {
|
||||
if (uri == null) {
|
||||
return false;
|
||||
}
|
||||
int dot = uri.lastIndexOf('.');
|
||||
return dot >= 0 && dot > uri.lastIndexOf('/')
|
||||
&& FONT_TYPES.contains(uri.substring(dot + 1).toLowerCase(Locale.ROOT));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.util.Objects;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.info.BuildProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* The single source of the cache-busting token that every first-party {@code /__assets/**} reference carries as
|
||||
* {@code ?v=<token>} — templates read it as the {@code assetVersion} model attribute, Java code that emits asset
|
||||
* URLs (the wizard, the preview window, the protection plugin's CAPTCHA widget) calls {@link #url(String)}.
|
||||
*
|
||||
* <p><b>Why every reference is versioned.</b> {@code /__assets/**} answers a versioned request with a one-day
|
||||
* {@code max-age} (see {@link AssetCachePolicy}), so a browser does not even ask again for a day. A new release
|
||||
* must therefore be served from a <em>new URL</em>, or a browser keeps running the previous release's script after
|
||||
* an upgrade — which is exactly what happened to {@code page-editor.js} before this existed. An unversioned
|
||||
* request is still answered correctly, only less efficiently ({@code no-cache}: revalidate every time).
|
||||
*
|
||||
* <p><b>The token.</b> The build timestamp from build-info when present — the reproducible-build
|
||||
* {@code outputTimestamp}, stable across restarts of one jar and different for every release cut — else the time
|
||||
* this class was loaded (a dev/IDE run without build-info: different on every restart). The fallback is a
|
||||
* process-wide constant, so {@link OperatorShellModel} (which derives it the same way through {@link #of}) and
|
||||
* this bean always agree within one JVM. <b>Dev caveat:</b> two SNAPSHOT builds share the pinned timestamp, so a
|
||||
* developer testing one build over another must hard-reload.
|
||||
*
|
||||
* <p>Immutable and thread-safe.
|
||||
*/
|
||||
@Component
|
||||
public class AssetVersion {
|
||||
|
||||
/** The query parameter that marks a versioned asset request. */
|
||||
public static final String PARAM = "v";
|
||||
|
||||
/** The fallback token: when this class was loaded, i.e. process start (one value per JVM). */
|
||||
private static final String PROCESS_START = Long.toString(System.currentTimeMillis());
|
||||
|
||||
private final String value;
|
||||
|
||||
/** The bean: derived from build-info when present (see {@link #of}). */
|
||||
@Autowired
|
||||
public AssetVersion(ObjectProvider<BuildProperties> buildProperties) {
|
||||
this(of(buildProperties.getIfAvailable()));
|
||||
}
|
||||
|
||||
private AssetVersion(String value) {
|
||||
this.value = Objects.requireNonNull(value, "value");
|
||||
}
|
||||
|
||||
/** A fixed token — for tests and for callers that already hold the value. */
|
||||
public static AssetVersion fixed(String value) {
|
||||
return new AssetVersion(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* The token for {@code build}: its build time in epoch milliseconds, or the process-start fallback when
|
||||
* {@code build} (or its time) is {@code null}. Never {@code null}, always digits.
|
||||
*/
|
||||
public static String of(BuildProperties build) {
|
||||
return (build != null && build.getTime() != null)
|
||||
? Long.toString(build.getTime().toEpochMilli())
|
||||
: PROCESS_START;
|
||||
}
|
||||
|
||||
/** The token itself (digits only — safe to embed in an attribute or URL unescaped). */
|
||||
public String value() {
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code path} with {@code v=<token>} appended — {@code ?v=} or, when {@code path} already has a query,
|
||||
* {@code &v=}. {@code path} is expected to be an {@code /__assets/...} path; it is not escaped.
|
||||
*/
|
||||
public String url(String path) {
|
||||
return path + (path.indexOf('?') < 0 ? '?' : '&') + PARAM + '=' + value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import mx.quest.runway.log.AuditEntry;
|
||||
import mx.quest.runway.log.AuditPage;
|
||||
import mx.quest.runway.log.AuditQuery;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.http.ContentDisposition;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
/**
|
||||
* The presentation half of the two audit-journal screens — the application Activity log ({@code /__app/logs})
|
||||
* and the per-site audit view on {@code /__admin/logs}. Both show the same thing (a {@link AuditPage} of
|
||||
* {@link AuditEntry} rows with date/actor/action filters, paging and a CSV download), so the request parsing, the
|
||||
* row shaping, the localized action labels and the CSV encoding live here once. The data side is
|
||||
* {@link mx.quest.runway.log.AuditJournal}; gating is each controller's (and its realm's security chain's) job.
|
||||
*
|
||||
* <h2>Labels</h2>
|
||||
* An action key {@code a.b} is shown as the operator message {@code op.audit.action.a.b} in the viewer's
|
||||
* language, falling back to the raw key for an action nothing declares (a plugin's, or one added later) — the raw
|
||||
* key is always shown too, because it is what the action filter matches. A legacy key carrying a suffix after
|
||||
* {@code :} (older {@code master.assigned:<site>} lines) is labelled by its part before the colon.
|
||||
*
|
||||
* <h2>CSV</h2>
|
||||
* RFC 4180 (every cell quoted, quotes doubled, CRLF rows) with a UTF-8 BOM so spreadsheet tools read accents
|
||||
* correctly. Spreadsheet-formula injection is neutralized: a cell beginning with {@code = + - @}, a tab or a CR is
|
||||
* prefixed with a single quote, so a crafted username or detail can never execute as a formula when an
|
||||
* auditor opens the export.
|
||||
*/
|
||||
final class AuditView {
|
||||
|
||||
/** Rows per screen page. */
|
||||
static final int PAGE_SIZE = 100;
|
||||
/** The most rows a CSV download carries. */
|
||||
static final int MAX_EXPORT_ROWS = 10_000;
|
||||
/** The highest page index accepted (the scan budget ends far sooner; this only bounds the arithmetic). */
|
||||
private static final int MAX_PAGE = 10_000;
|
||||
/** Free-text filters are clipped to this length (a filter is a substring, never a pattern). */
|
||||
private static final int MAX_FILTER_LENGTH = 100;
|
||||
|
||||
private static final DateTimeFormatter SHOWN_WITH_OFFSET = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss xxx");
|
||||
private static final DateTimeFormatter SHOWN_LEGACY = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
private static final DateTimeFormatter CSV_TIME = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
|
||||
|
||||
/** One row as the template binds it (every value already a display string). */
|
||||
record Row(String time, String sortKey, String actor, String action, String label, String detail) {
|
||||
}
|
||||
|
||||
/** The parsed filter of one request, echoed back into the form. */
|
||||
record Filter(String from, String to, String actor, String action, int page) {
|
||||
|
||||
AuditQuery query() {
|
||||
return new AuditQuery(date(from), date(to), actor, action);
|
||||
}
|
||||
}
|
||||
|
||||
private AuditView() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the request's filter parameters. A malformed date is dropped (treated as no bound) rather than
|
||||
* rejected; text filters are stripped and clipped; the page index is clamped to {@code [0, MAX_PAGE]}.
|
||||
*/
|
||||
static Filter filter(String from, String to, String actor, String action, Integer page) {
|
||||
LocalDate fromDay = date(from);
|
||||
LocalDate toDay = date(to);
|
||||
if (fromDay != null && toDay != null && toDay.isBefore(fromDay)) {
|
||||
LocalDate swap = fromDay; // an inverted range is almost always a slip — read it the obvious way
|
||||
fromDay = toDay;
|
||||
toDay = swap;
|
||||
}
|
||||
int p = page == null ? 0 : Math.max(0, Math.min(MAX_PAGE, page));
|
||||
return new Filter(fromDay == null ? "" : fromDay.toString(), toDay == null ? "" : toDay.toString(),
|
||||
clip(actor), clip(action), p);
|
||||
}
|
||||
|
||||
private static LocalDate date(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return LocalDate.parse(value.strip());
|
||||
} catch (DateTimeParseException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String clip(String value) {
|
||||
if (value == null) {
|
||||
return "";
|
||||
}
|
||||
String s = value.strip();
|
||||
return s.length() > MAX_FILTER_LENGTH ? s.substring(0, MAX_FILTER_LENGTH) : s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fills the model attributes both audit templates bind: {@code auditRows}, the echoed filter
|
||||
* ({@code auditFilter}), paging links ({@code auditPrevUrl} / {@code auditNextUrl}, absent when there is no
|
||||
* such page), {@code auditCsvUrl}, {@code auditTruncated} / {@code auditScanned}, and the bound constants.
|
||||
*
|
||||
* @param basePath the screen's path (paging links)
|
||||
* @param csvPath the CSV download's path
|
||||
* @param titleKey the operator message key of the card title
|
||||
* @param tableKey the listing-table layout key (unique per screen, so the two realms keep separate layouts)
|
||||
*/
|
||||
static void populate(Model model, AuditPage page, Filter filter, String basePath, String csvPath,
|
||||
String titleKey, String tableKey, MessageSource messages, Locale locale) {
|
||||
model.addAttribute("auditTitleKey", titleKey);
|
||||
model.addAttribute("auditTableKey", tableKey);
|
||||
model.addAttribute("auditRows", rows(page.rows(), messages, locale));
|
||||
model.addAttribute("auditFilter", filter);
|
||||
model.addAttribute("auditPageNumber", filter.page() + 1);
|
||||
model.addAttribute("auditPrevUrl", filter.page() > 0 ? url(basePath, filter, filter.page() - 1) : null);
|
||||
model.addAttribute("auditNextUrl", page.hasMore() ? url(basePath, filter, filter.page() + 1) : null);
|
||||
model.addAttribute("auditCsvUrl", url(csvPath, filter, -1));
|
||||
model.addAttribute("auditResetUrl", basePath);
|
||||
model.addAttribute("auditTruncated", page.truncated());
|
||||
model.addAttribute("auditScanned", page.scanned());
|
||||
model.addAttribute("auditPageSize", PAGE_SIZE);
|
||||
model.addAttribute("auditMaxExport", MAX_EXPORT_ROWS);
|
||||
}
|
||||
|
||||
static List<Row> rows(List<AuditEntry> entries, MessageSource messages, Locale locale) {
|
||||
List<Row> rows = new ArrayList<>(entries.size());
|
||||
for (AuditEntry e : entries) {
|
||||
String shown = (e.offsetKnown() ? SHOWN_WITH_OFFSET : SHOWN_LEGACY).format(e.time());
|
||||
rows.add(new Row(shown, CSV_TIME.format(e.time()), e.actor(), e.action(),
|
||||
label(e.action(), messages, locale), e.detail()));
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** The localized label of an action key, or the raw key when no message declares it. */
|
||||
static String label(String action, MessageSource messages, Locale locale) {
|
||||
if (action == null || action.isBlank()) {
|
||||
return "";
|
||||
}
|
||||
int colon = action.indexOf(':');
|
||||
String base = colon > 0 ? action.substring(0, colon) : action;
|
||||
return messages.getMessage("op.audit.action." + base, null, action, locale);
|
||||
}
|
||||
|
||||
/** The screen/CSV URL for {@code filter} at {@code page} ({@code -1} = no page parameter), URL-encoded. */
|
||||
private static String url(String path, Filter filter, int page) {
|
||||
UriComponentsBuilder b = UriComponentsBuilder.fromPath(path);
|
||||
if (!filter.from().isEmpty()) {
|
||||
b.queryParam("from", filter.from());
|
||||
}
|
||||
if (!filter.to().isEmpty()) {
|
||||
b.queryParam("to", filter.to());
|
||||
}
|
||||
if (!filter.actor().isEmpty()) {
|
||||
b.queryParam("actor", filter.actor());
|
||||
}
|
||||
if (!filter.action().isEmpty()) {
|
||||
b.queryParam("action", filter.action());
|
||||
}
|
||||
if (page > 0) {
|
||||
b.queryParam("page", page);
|
||||
}
|
||||
return b.encode().build().toUriString();
|
||||
}
|
||||
|
||||
/**
|
||||
* The CSV download of {@code page}'s rows (time ISO-8601 with offset, actor, raw action key, localized label,
|
||||
* detail). Sent {@code no-store} — an audit export must not linger in a shared cache.
|
||||
*
|
||||
* @param filename the attachment filename (ASCII, no path)
|
||||
*/
|
||||
static ResponseEntity<byte[]> csv(AuditPage page, String filename, MessageSource messages, Locale locale) {
|
||||
StringBuilder out = new StringBuilder(64 + page.rows().size() * 96);
|
||||
out.append('');
|
||||
appendRow(out, "time", "actor", "action", "label", "detail");
|
||||
for (AuditEntry e : page.rows()) {
|
||||
appendRow(out, CSV_TIME.format(e.time()), e.actor(), e.action(), label(e.action(), messages, locale),
|
||||
e.detail());
|
||||
}
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(new MediaType("text", "csv", StandardCharsets.UTF_8));
|
||||
headers.setContentDisposition(ContentDisposition.attachment().filename(filename).build());
|
||||
headers.setCacheControl("no-store");
|
||||
if (page.hasMore() || page.truncated()) {
|
||||
// The file holds fewer rows than match (row cap or scan budget) — say so to a scripted consumer.
|
||||
headers.add("X-Runway-Audit-Incomplete", "true");
|
||||
}
|
||||
return ResponseEntity.ok().headers(headers).body(out.toString().getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static void appendRow(StringBuilder out, String... cells) {
|
||||
for (int i = 0; i < cells.length; i++) {
|
||||
if (i > 0) {
|
||||
out.append(',');
|
||||
}
|
||||
out.append('"').append(csvSafe(cells[i]).replace("\"", "\"\"")).append('"');
|
||||
}
|
||||
out.append("\r\n");
|
||||
}
|
||||
|
||||
/** Neutralizes a cell a spreadsheet would evaluate as a formula (OWASP CSV-injection guidance). */
|
||||
static String csvSafe(String cell) {
|
||||
if (cell == null || cell.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
char first = cell.charAt(0);
|
||||
if (first == '=' || first == '+' || first == '-' || first == '@' || first == '\t' || first == '\r') {
|
||||
return "'" + cell;
|
||||
}
|
||||
return cell;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import mx.quest.runway.bandwidth.BandwidthService;
|
||||
import mx.quest.runway.bandwidth.SiteBandwidthQuotas;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
/**
|
||||
* The tenant console's bandwidth screen ({@code /__admin/bandwidth}): a 30-day chart of the site's own data
|
||||
* transfer plus 24h/7d/30d totals. Gated to the site's administrators via {@link TenantAuthority} — a tenant
|
||||
* sees only its own numbers, and its monthly cap read-only (the operator sets it on the Sites screen). (Aggregate metering across all sites is an operator view at {@code /__app/bandwidth}.)
|
||||
*/
|
||||
@Controller
|
||||
public class BandwidthController {
|
||||
|
||||
private static final int DAYS = 30;
|
||||
|
||||
private final SiteResolver siteResolver;
|
||||
private final BandwidthService bandwidth;
|
||||
private final TenantAuthority tenantAuthority;
|
||||
private final SiteBandwidthQuotas quotas;
|
||||
|
||||
public BandwidthController(SiteResolver siteResolver, BandwidthService bandwidth, TenantAuthority tenantAuthority,
|
||||
SiteBandwidthQuotas quotas) {
|
||||
this.quotas = quotas;
|
||||
this.siteResolver = siteResolver;
|
||||
this.bandwidth = bandwidth;
|
||||
this.tenantAuthority = tenantAuthority;
|
||||
}
|
||||
|
||||
@GetMapping("/__admin/bandwidth")
|
||||
public String view(Authentication authentication, Model model) {
|
||||
String siteId = siteResolver.current()
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "no bound tenancy"))
|
||||
.id();
|
||||
tenantAuthority.require(authentication, siteId);
|
||||
model.addAttribute("report", bandwidth.report(siteId, DAYS));
|
||||
model.addAttribute("quota", quotas.of(siteId));
|
||||
model.addAttribute("overQuota", bandwidth.isOverQuota(siteId));
|
||||
model.addAttribute("contentTemplate", "operator/admin/bandwidth");
|
||||
model.addAttribute("pageTitleKey", "op.bandwidth.title");
|
||||
return "operator/op-layout";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.authz.AuthorizationService;
|
||||
import mx.quest.runway.authz.Permission;
|
||||
import mx.quest.runway.authz.Permissions;
|
||||
import mx.quest.runway.security.RunwayUserDetails;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Which of the <b>kernel's own</b> topbar entries the signed-in operator may see, so the console never offers a
|
||||
* link that answers {@code 403}. Plugin entries already work this way ({@link MenuRegistry} hides an entry whose
|
||||
* declared {@code permission} fails); this does the same for the kernel's fixed menu.
|
||||
*
|
||||
* <h2>One gate per entry — the same check its route makes</h2>
|
||||
* Each entry names the check the route behind it enforces, and is evaluated with the same code: a grantable
|
||||
* permission through {@link AuthorizationService#mayAccess} (application permissions without a tenancy, tenant
|
||||
* permissions in the bound site — exactly what {@code @authz.may('…')} does), the platform gate through
|
||||
* {@link PlatformAuthority#isPlatformAdmin}, the site-administrator gate through
|
||||
* {@link TenantAuthority#isTenantAdmin}. Entries whose route only requires the realm's sign-in are always shown.
|
||||
* When a route's gate changes, its row here must change with it; {@code ConsoleNavigationVisibilityTest}
|
||||
* requests every route as an under-privileged operator and fails if a visible entry answers {@code 403} or a
|
||||
* hidden one does not.
|
||||
*
|
||||
* <h2>Groups</h2>
|
||||
* A dropdown group is shown when at least one of its kernel entries is visible <em>or</em> a plugin contributes an
|
||||
* entry to it — an empty dropdown would be a dead control.
|
||||
*
|
||||
* <p>UX only: hiding an entry grants or removes nothing; the route still enforces its own gate.
|
||||
*/
|
||||
@Component
|
||||
public class ConsoleNavigation {
|
||||
|
||||
/** How an entry's route is gated. */
|
||||
enum Gate { SIGNED_IN, PLATFORM_ADMIN, TENANT_ADMIN, PERMISSION }
|
||||
|
||||
/**
|
||||
* One kernel menu entry.
|
||||
*
|
||||
* @param key the model key the topbar reads ({@code nav['key']})
|
||||
* @param group the dropdown group it sits in, or {@code null} for a top-level item
|
||||
* @param path the route it links to (for the consistency test and for readers)
|
||||
* @param gate how the route is gated
|
||||
* @param anyOf for {@link Gate#PERMISSION}: the permissions, any one of which opens the route
|
||||
*/
|
||||
record Entry(String key, String group, String path, Gate gate, List<Permission> anyOf) {
|
||||
|
||||
static Entry open(String key, String group, String path) {
|
||||
return new Entry(key, group, path, Gate.SIGNED_IN, List.of());
|
||||
}
|
||||
|
||||
static Entry gated(String key, String group, String path, Gate gate) {
|
||||
return new Entry(key, group, path, gate, List.of());
|
||||
}
|
||||
|
||||
static Entry permission(String key, String group, String path, Permission... anyOf) {
|
||||
return new Entry(key, group, path, Gate.PERMISSION, List.of(anyOf));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The application console's topbar ({@code app-topbar}). The dashboard is always offered: without
|
||||
* {@code VIEW_APP_DASHBOARD} it renders a minimal landing rather than answering {@code 403}, because it is where
|
||||
* sign-in lands. The Sites list opens with {@code VIEW_TENANCIES} or {@code MANAGE_SITE_HOSTS} (editing a
|
||||
* site's hosts happens on that list).
|
||||
*/
|
||||
static final List<Entry> APP = List.of(
|
||||
Entry.open("dashboard", null, "/__app"),
|
||||
Entry.permission("sites", "sites", "/__app/sites", Permissions.VIEW_TENANCIES,
|
||||
Permissions.MANAGE_SITE_HOSTS),
|
||||
Entry.gated("backups", "sites", "/__app/backups", Gate.PLATFORM_ADMIN),
|
||||
Entry.permission("site-templates", "sites", "/__app/site-templates", Permissions.MANAGE_STYLES),
|
||||
Entry.open("masters", "sites", "/__app/masters"),
|
||||
Entry.open("users", "access", "/__app/users"),
|
||||
Entry.gated("permissions", "access", "/__app/permissions", Gate.PLATFORM_ADMIN),
|
||||
Entry.permission("bandwidth", "activity", "/__app/bandwidth", Permissions.VIEW_BANDWIDTH),
|
||||
Entry.permission("logs", "activity", "/__app/logs", Permissions.VIEW_AUDIT),
|
||||
Entry.open("plugins", null, "/__app/plugins"),
|
||||
Entry.gated("settings", "settings", "/__app/settings", Gate.PLATFORM_ADMIN),
|
||||
Entry.gated("server-settings", "settings", "/__app/config/server", Gate.PLATFORM_ADMIN),
|
||||
Entry.gated("embed-hosts", "settings", "/__app/embed-hosts", Gate.PLATFORM_ADMIN),
|
||||
Entry.open("about", "settings", "/__app/about"));
|
||||
|
||||
/** A site's console topbar ({@code admin-topbar}). */
|
||||
static final List<Entry> TENANT = List.of(
|
||||
Entry.open("dashboard", null, "/__admin"),
|
||||
Entry.permission("pages", "resources", "/__admin/pages", Permissions.EDIT_PAGES, Permissions.DISABLE_PAGES),
|
||||
Entry.permission("review", "resources", "/__admin/review", Permissions.APPROVE_PAGES),
|
||||
Entry.permission("fragments", "resources", "/__admin/fragments", Permissions.CONFIGURE_SITE),
|
||||
Entry.permission("widgets", "resources", "/__admin/widgets", Permissions.CONFIGURE_SITE),
|
||||
Entry.permission("documents", "resources", "/__admin/documents", Permissions.MANAGE_DOCUMENTS),
|
||||
Entry.permission("static", "resources", "/__admin/static", Permissions.CONFIGURE_SITE),
|
||||
Entry.permission("messages", "resources", "/__admin/messages", Permissions.CONFIGURE_SITE),
|
||||
Entry.permission("users", "access", "/__admin/users", Permissions.MANAGE_USERS, Permissions.DELETE_USERS),
|
||||
Entry.gated("permissions", "access", "/__admin/permissions", Gate.TENANT_ADMIN),
|
||||
Entry.permission("insights", "activity", "/__admin/insights", Permissions.VIEW_SITE_INSIGHTS),
|
||||
Entry.gated("bandwidth", "activity", "/__admin/bandwidth", Gate.TENANT_ADMIN),
|
||||
Entry.gated("logs", "activity", "/__admin/logs", Gate.TENANT_ADMIN),
|
||||
Entry.permission("config", "settings", "/__admin/config", Permissions.CONFIGURE_SITE),
|
||||
Entry.permission("seo", "settings", "/__admin/seo", Permissions.CONFIGURE_SITE),
|
||||
Entry.permission("icons", "settings", "/__admin/icons", Permissions.CONFIGURE_SITE),
|
||||
Entry.permission("manifest", "settings", "/__admin/manifest", Permissions.CONFIGURE_SITE),
|
||||
Entry.permission("backups", "settings", "/__admin/backups", Permissions.MANAGE_BACKUPS),
|
||||
Entry.permission("maintenance", "settings", "/__admin/maintenance", Permissions.MAINTENANCE_MODE));
|
||||
|
||||
private final AuthorizationService authorization;
|
||||
private final PlatformAuthority platformAuthority;
|
||||
private final TenantAuthority tenantAuthority;
|
||||
|
||||
public ConsoleNavigation(AuthorizationService authorization, PlatformAuthority platformAuthority,
|
||||
TenantAuthority tenantAuthority) {
|
||||
this.authorization = Objects.requireNonNull(authorization, "authorization");
|
||||
this.platformAuthority = Objects.requireNonNull(platformAuthority, "platformAuthority");
|
||||
this.tenantAuthority = Objects.requireNonNull(tenantAuthority, "tenantAuthority");
|
||||
}
|
||||
|
||||
/**
|
||||
* The visibility map the topbar reads: one boolean per entry key, plus {@code grp.<group>} per dropdown group.
|
||||
* Every key of the realm's table is present, so a template lookup never sees {@code null}.
|
||||
*
|
||||
* @param realm which console is rendering
|
||||
* @param authentication the signed-in operator ({@code null} ⇒ only {@link Gate#SIGNED_IN} entries)
|
||||
* @param tenancyId the bound site on the tenant console ({@code null} on the application console)
|
||||
* @param groupsWithPluginEntries the groups a plugin contributes at least one visible entry to
|
||||
*/
|
||||
public Map<String, Boolean> visibility(Realm realm, Authentication authentication, String tenancyId,
|
||||
Set<String> groupsWithPluginEntries) {
|
||||
List<Entry> entries = realm == Realm.APPLICATION ? APP : TENANT;
|
||||
RunwayUserDetails principal = authentication != null
|
||||
&& authentication.getPrincipal() instanceof RunwayUserDetails details ? details : null;
|
||||
Map<String, Boolean> visible = new LinkedHashMap<>();
|
||||
for (Entry entry : entries) {
|
||||
boolean shown = allows(entry, authentication, principal, tenancyId);
|
||||
visible.put(entry.key(), shown);
|
||||
if (entry.group() != null) {
|
||||
visible.merge("grp." + entry.group(), shown, Boolean::logicalOr);
|
||||
}
|
||||
}
|
||||
for (String group : groupsWithPluginEntries) {
|
||||
if (visible.containsKey("grp." + group)) {
|
||||
visible.put("grp." + group, true);
|
||||
}
|
||||
}
|
||||
return visible;
|
||||
}
|
||||
|
||||
private boolean allows(Entry entry, Authentication authentication, RunwayUserDetails principal,
|
||||
String tenancyId) {
|
||||
return switch (entry.gate()) {
|
||||
case SIGNED_IN -> true;
|
||||
case PLATFORM_ADMIN -> platformAuthority.isPlatformAdmin(authentication);
|
||||
case TENANT_ADMIN -> tenancyId != null && tenantAuthority.isTenantAdmin(authentication, tenancyId);
|
||||
case PERMISSION -> principal != null && entry.anyOf().stream().anyMatch(permission ->
|
||||
authorization.mayAccess(principal, permission,
|
||||
permission.realm() == Realm.APPLICATION ? null : tenancyId));
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import mx.quest.runway.spi.service.ConsoleScreen;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
|
||||
/**
|
||||
* Fills the operator shell's model for every controller annotated {@link ConsoleScreen} — the SPI way for a plugin
|
||||
* screen to render inside {@code op-layout}. It delegates to the same {@link OperatorShellModel} the
|
||||
* kernel's own {@link OperatorModelAdvice} uses, so a plugin screen and a kernel screen get exactly the same chrome.
|
||||
*
|
||||
* <p>It replaced the per-plugin {@code @ControllerAdvice} that injected {@code OperatorShellModel} (a host class,
|
||||
* which a plugin may not link from SPI 1.0.0). {@code populate} is idempotent, so a controller that some other advice
|
||||
* also covers still gets the same attributes.
|
||||
*/
|
||||
@ControllerAdvice(annotations = ConsoleScreen.class)
|
||||
public class ConsoleScreenAdvice {
|
||||
|
||||
private final OperatorShellModel shellModel;
|
||||
|
||||
public ConsoleScreenAdvice(OperatorShellModel shellModel) {
|
||||
this.shellModel = shellModel;
|
||||
}
|
||||
|
||||
@ModelAttribute
|
||||
public void consoleScreenShell(Model model, HttpServletRequest request, Authentication authentication) {
|
||||
shellModel.populate(model, request, authentication);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
import mx.quest.runway.authz.AuthorizationAdminService;
|
||||
import mx.quest.runway.security.AppUserStore;
|
||||
import mx.quest.runway.security.Roles;
|
||||
import mx.quest.runway.security.RunwaySecurityProperties;
|
||||
import mx.quest.runway.security.RunwayUserDetails;
|
||||
import mx.quest.runway.security.SiteUserStore;
|
||||
import mx.quest.runway.security.TenantMasterStore;
|
||||
import mx.quest.runway.security.User;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* Edits and suspends console users after they were created — the operations the two Users screens
|
||||
* ({@code /__app/users}, {@code /__admin/users}) and the application console's Site masters screen
|
||||
* ({@code /__app/masters}, suspend / resume only) call. It changes a user's <b>profile</b> (display name, recovery
|
||||
* email), <b>access tier</b>, and <b>enabled</b> flag; it never changes the username (the login name), the
|
||||
* password (the separate reset action) or custom roles (the permissions matrix).
|
||||
*
|
||||
* <h2>Guards, all enforced here, server-side</h2>
|
||||
* <ul>
|
||||
* <li><b>The pinned application superadmin</b> may have its profile edited, but never its tier changed and never
|
||||
* be suspended. {@link AppUserStore#save} enforces the same rule structurally (it throws on any role or
|
||||
* enabled change to the pin); this service refuses first, with a clear reason.</li>
|
||||
* <li><b>Not yourself:</b> an operator cannot suspend their own account or change their own tier. Either would
|
||||
* lock them out of the screen they are using — and a self-demotion cannot be undone by the same person.</li>
|
||||
* <li><b>Bounded grant:</b> changing a tier both revokes the old tier key and grants the new one, so the actor
|
||||
* must be allowed to grant <em>both</em> ({@link AuthorizationAdminService#mayGrantRole}) — the same rule the
|
||||
* permissions matrix applies, so nobody raises or lowers a user beyond their own authority.</li>
|
||||
* <li><b>Tenant scope:</b> a tenant edit reads and writes only the bound tenancy's {@code users.yml}; the tenant
|
||||
* superadmin lives in a different store (the tenant-master store) and is out of reach by construction. A
|
||||
* record that nevertheless carries the master flag or a master key (a hand-edited file) is refused.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Suspension is the record's existing {@code enabled} flag: a suspended user cannot sign in (Spring's provider
|
||||
* honours {@link RunwayUserDetails#isEnabled()}), cannot use password recovery (it mails enabled accounts only),
|
||||
* and a session already open is dropped on its next request by {@code AccountStateFilter}.
|
||||
*
|
||||
* <p>Failures throw {@link UserEditException} carrying a stable {@code code} the controllers localize.
|
||||
*/
|
||||
@Service
|
||||
public class ConsoleUserService {
|
||||
|
||||
/** Longest accepted display name — a label, not a document. */
|
||||
static final int MAX_DISPLAY_NAME = 128;
|
||||
/** Longest accepted recovery email (the RFC 5321 path limit). */
|
||||
static final int MAX_EMAIL = 254;
|
||||
/** Deliberately loose: one {@code @}, something on each side, no whitespace. Delivery is the real test. */
|
||||
private static final Pattern EMAIL = Pattern.compile("[^@\\s]+@[^@\\s]+");
|
||||
|
||||
private static final Set<String> APP_TIERS = Set.of(Roles.SYSTEM_ADMIN, Roles.SYSTEM_OPERATOR);
|
||||
private static final Set<String> SITE_TIERS = Set.of(Roles.ADMIN, Roles.OPERATOR);
|
||||
|
||||
private final AppUserStore appUsers;
|
||||
private final SiteUserStore siteUsers;
|
||||
private final RunwaySecurityProperties security;
|
||||
private final AuthorizationAdminService admin;
|
||||
private final TenantMasterStore masters;
|
||||
|
||||
public ConsoleUserService(AppUserStore appUsers, SiteUserStore siteUsers, RunwaySecurityProperties security,
|
||||
AuthorizationAdminService admin, TenantMasterStore masters) {
|
||||
this.appUsers = Objects.requireNonNull(appUsers, "appUsers");
|
||||
this.siteUsers = Objects.requireNonNull(siteUsers, "siteUsers");
|
||||
this.security = Objects.requireNonNull(security, "security");
|
||||
this.admin = Objects.requireNonNull(admin, "admin");
|
||||
this.masters = Objects.requireNonNull(masters, "masters");
|
||||
}
|
||||
|
||||
/** A refused edit, with a stable {@code code} ({@code op.users.error.<code>}) for the localized message. */
|
||||
public static final class UserEditException extends IllegalArgumentException {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private final String code;
|
||||
|
||||
UserEditException(String code, String message) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String code() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
// --- application realm ------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Updates an application user's display name, recovery email and tier.
|
||||
*
|
||||
* @param tier {@code SYSTEMADMIN} or {@code SYSTEMOPERATOR}; {@code null}/blank keeps the current tier (the
|
||||
* pinned superadmin's form sends none)
|
||||
* @return the saved record
|
||||
* @throws UserEditException on an unknown user, invalid input, or a guard refusal
|
||||
*/
|
||||
public User updateAppUser(RunwayUserDetails actor, String principalId, String displayName, String email,
|
||||
String tier) {
|
||||
User target = appUsers.findByPrincipalId(principalId)
|
||||
.orElseThrow(() -> new UserEditException("noSuchUser", "no such user"));
|
||||
User updated = withProfile(target, displayName, email);
|
||||
String newTier = blank(tier) ? null : tier.trim();
|
||||
if (newTier != null && !target.hasRole(newTier)) {
|
||||
if (isAppPin(principalId)) {
|
||||
throw new UserEditException("pinnedTier", "the application superadmin's tier cannot be changed");
|
||||
}
|
||||
updated = withTier(updated, newTier, APP_TIERS, actor, null);
|
||||
}
|
||||
appUsers.save(updated); // the store re-checks the pin structurally
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Suspends ({@code enabled=false}) or resumes an application user.
|
||||
*
|
||||
* @return the saved record
|
||||
* @throws UserEditException on an unknown user, the pinned superadmin, or the actor's own account
|
||||
*/
|
||||
public User setAppUserEnabled(RunwayUserDetails actor, String principalId, boolean enabled) {
|
||||
User target = appUsers.findByPrincipalId(principalId)
|
||||
.orElseThrow(() -> new UserEditException("noSuchUser", "no such user"));
|
||||
if (!enabled && isAppPin(principalId)) {
|
||||
throw new UserEditException("pinnedSuspend", "the application superadmin cannot be suspended");
|
||||
}
|
||||
requireNotSelf(actor, principalId, enabled);
|
||||
User updated = target.withEnabled(enabled);
|
||||
appUsers.save(updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
// --- tenant realm -----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Updates one of {@code tenancyId}'s sub-users: display name, recovery email and tier ({@code ADMIN} or
|
||||
* {@code OPERATOR}; blank keeps the current tier).
|
||||
*
|
||||
* @return the saved record
|
||||
* @throws UserEditException on an unknown user (in THIS tenancy), invalid input, or a guard refusal
|
||||
*/
|
||||
public User updateSiteUser(RunwayUserDetails actor, String tenancyId, String principalId, String displayName,
|
||||
String email, String tier) {
|
||||
User target = siteUser(tenancyId, principalId);
|
||||
User updated = withProfile(target, displayName, email);
|
||||
String newTier = blank(tier) ? null : tier.trim();
|
||||
if (newTier != null && !target.hasRole(newTier)) {
|
||||
updated = withTier(updated, newTier, SITE_TIERS, actor, tenancyId);
|
||||
}
|
||||
siteUsers.save(tenancyId, updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Suspends or resumes one of {@code tenancyId}'s sub-users.
|
||||
*
|
||||
* @return the saved record
|
||||
* @throws UserEditException on an unknown user (in THIS tenancy) or the actor's own account
|
||||
*/
|
||||
public User setSiteUserEnabled(RunwayUserDetails actor, String tenancyId, String principalId, boolean enabled) {
|
||||
User target = siteUser(tenancyId, principalId);
|
||||
requireNotSelf(actor, principalId, enabled);
|
||||
User updated = target.withEnabled(enabled);
|
||||
siteUsers.save(tenancyId, updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
// --- tenant superadmins (application-managed) --------------------------------------------
|
||||
|
||||
/**
|
||||
* Suspends ({@code enabled=false}) or resumes a tenant superadmin — the global identity in the tenant-master
|
||||
* store, managed from the application console. A suspended superadmin cannot sign in to any of its sites, and
|
||||
* every open session of it ends on its next request ({@code AccountStateFilter}); the password, the site
|
||||
* assignments and the record itself are kept, so Resume restores exactly what was there.
|
||||
*
|
||||
* <p>The same guards as an application user's suspension, applied to this store: never the pinned
|
||||
* application superadmin's identity, never the actor's own identity. Both are structurally unlikely (the actor
|
||||
* is an application user, a tenant superadmin a tenant identity) and are refused anyway rather than relied on.
|
||||
* Suspending a site's only superadmin is allowed: unlike deletion it is undone with one click, and locking a
|
||||
* site's management out is a legitimate reason to suspend.
|
||||
*
|
||||
* @return the saved record
|
||||
* @throws UserEditException on an unknown superadmin, the pinned identity, or the actor's own identity
|
||||
*/
|
||||
public User setTenantMasterEnabled(RunwayUserDetails actor, String principalId, boolean enabled) {
|
||||
User target = masters.findByPrincipalId(principalId)
|
||||
.orElseThrow(() -> new UserEditException("noSuchUser", "no such user"));
|
||||
if (!enabled && isAppPin(principalId)) {
|
||||
throw new UserEditException("pinnedSuspend", "the application superadmin cannot be suspended");
|
||||
}
|
||||
requireNotSelf(actor, principalId, enabled);
|
||||
User updated = target.withEnabled(enabled);
|
||||
masters.save(updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
// --- shared -----------------------------------------------------------------------------
|
||||
|
||||
private User siteUser(String tenancyId, String principalId) {
|
||||
User target = siteUsers.findByPrincipalId(tenancyId, principalId)
|
||||
.orElseThrow(() -> new UserEditException("noSuchUser", "no such user"));
|
||||
if (target.master() || target.hasRole(Roles.SUPERADMIN) || target.realm() != Realm.TENANT) {
|
||||
// Never in a well-formed users.yml (the tenant superadmin lives in the tenant-master store).
|
||||
throw new UserEditException("protected", "this account cannot be edited here");
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code target} with a new display name (blank ⇒ the username) and recovery email (blank ⇒ none), after the
|
||||
* checks every console profile edit shares. Package-visible for the site-masters screen.
|
||||
*
|
||||
* @throws UserEditException when the name is too long or the email is not an address
|
||||
*/
|
||||
static User withProfile(User target, String displayName, String email) {
|
||||
String name = blank(displayName) ? target.username() : displayName.trim();
|
||||
if (name.length() > MAX_DISPLAY_NAME) {
|
||||
throw new UserEditException("displayNameTooLong",
|
||||
"the display name is longer than " + MAX_DISPLAY_NAME + " characters");
|
||||
}
|
||||
return target.withProfile(name, recoveryEmail(email));
|
||||
}
|
||||
|
||||
/**
|
||||
* A recovery email as stored: trimmed, or {@code ""} for none.
|
||||
*
|
||||
* @throws UserEditException when a non-blank value is not an address
|
||||
*/
|
||||
static String recoveryEmail(String email) {
|
||||
String mail = blank(email) ? "" : email.trim();
|
||||
if (!mail.isEmpty() && (mail.length() > MAX_EMAIL || !EMAIL.matcher(mail).matches())) {
|
||||
throw new UserEditException("invalidEmail", "'" + mail + "' is not a valid email address");
|
||||
}
|
||||
return mail;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the realm tier key in {@code user}'s roles with {@code newTier}, after checking the tier is valid,
|
||||
* the actor is not changing their own tier, and the actor may grant both the old and the new key.
|
||||
*/
|
||||
private User withTier(User user, String newTier, Set<String> realmTiers, RunwayUserDetails actor,
|
||||
String tenancyId) {
|
||||
if (!realmTiers.contains(newTier)) {
|
||||
throw new UserEditException("invalidTier", "invalid access tier '" + newTier + "'");
|
||||
}
|
||||
if (actor.principalId().equals(user.principalId())) {
|
||||
throw new UserEditException("selfTier", "you cannot change your own access tier");
|
||||
}
|
||||
Set<String> roles = new HashSet<>(user.roles());
|
||||
for (String old : realmTiers) {
|
||||
if (roles.contains(old) && !admin.mayGrantRole(actor, old, tenancyId)) {
|
||||
throw new UserEditException("tierNotAllowed", "not authorized to revoke the '" + old + "' tier");
|
||||
}
|
||||
}
|
||||
if (!admin.mayGrantRole(actor, newTier, tenancyId)) {
|
||||
throw new UserEditException("tierNotAllowed", "not authorized to grant the '" + newTier + "' tier");
|
||||
}
|
||||
roles.removeAll(realmTiers);
|
||||
roles.add(newTier);
|
||||
return user.withRoles(roles);
|
||||
}
|
||||
|
||||
private static void requireNotSelf(RunwayUserDetails actor, String principalId, boolean enabling) {
|
||||
if (!enabling && actor.principalId().equals(principalId)) {
|
||||
throw new UserEditException("selfSuspend", "you cannot suspend your own account");
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isAppPin(String principalId) {
|
||||
String pin = security.getAppMasterId();
|
||||
return pin != null && !pin.isBlank() && pin.equals(principalId);
|
||||
}
|
||||
|
||||
private static boolean blank(String value) {
|
||||
return value == null || value.isBlank();
|
||||
}
|
||||
|
||||
/** The tier key a record holds in {@code realm} (for the edit form's preselection), or empty. */
|
||||
static String tierOf(User user) {
|
||||
Set<String> tiers = user.realm() == Realm.APPLICATION ? APP_TIERS : SITE_TIERS;
|
||||
return user.roles().stream().filter(tiers::contains).findFirst().orElse("");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import mx.quest.runway.authz.AuthorizationService;
|
||||
import mx.quest.runway.authz.Permission;
|
||||
import mx.quest.runway.authz.PermissionCatalog;
|
||||
import mx.quest.runway.plugin.LoadedPlugin;
|
||||
import mx.quest.runway.plugin.PluginCardDecl;
|
||||
import mx.quest.runway.plugin.RunningPlugins;
|
||||
import mx.quest.runway.security.RunwayUserDetails;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Collects the dashboard cards plugins contribute ({@code dashboardCards:} in the descriptor) for a realm and
|
||||
* principal, resolving each to its {@code __plugin__/<id>/<fragment>} template so the console dashboard can pull
|
||||
* it (via {@link PluginTemplateResolver}). Realm-filtered, ordered ({@code order} → plugin id), and
|
||||
* permission-gated exactly like {@link MenuRegistry} — a card naming a permission the principal lacks is
|
||||
* hidden; UX only (the fragment's own data still comes from the plugin's beans).
|
||||
*/
|
||||
@Component
|
||||
public class DashboardCardRegistry {
|
||||
|
||||
private final RunningPlugins runningPlugins;
|
||||
private final AuthorizationService authorization;
|
||||
private final PermissionCatalog catalog;
|
||||
|
||||
public DashboardCardRegistry(RunningPlugins runningPlugins, AuthorizationService authorization,
|
||||
PermissionCatalog catalog) {
|
||||
this.runningPlugins = runningPlugins;
|
||||
this.authorization = authorization;
|
||||
this.catalog = catalog;
|
||||
}
|
||||
|
||||
/** A resolved card: the template the dashboard pulls, its order, and the contributing plugin. */
|
||||
public record Card(String template, int order, String pluginId) {
|
||||
}
|
||||
|
||||
/** The visible dashboard cards for {@code principal} in {@code realm} (+ bound {@code tenancyId}). */
|
||||
public List<Card> cardsFor(Realm realm, RunwayUserDetails principal, String tenancyId) {
|
||||
List<Card> cards = new ArrayList<>();
|
||||
for (LoadedPlugin plugin : runningPlugins.installed()) {
|
||||
for (PluginCardDecl decl : plugin.descriptor().dashboardCards()) {
|
||||
if (decl.realm() != realm || !visible(decl, principal, tenancyId)) {
|
||||
continue;
|
||||
}
|
||||
cards.add(new Card(PluginTemplateResolver.PREFIX + plugin.id() + "/" + decl.fragment(),
|
||||
decl.order(), plugin.id()));
|
||||
}
|
||||
}
|
||||
cards.sort(Comparator.comparingInt(Card::order).thenComparing(Card::pluginId));
|
||||
return List.copyOf(cards);
|
||||
}
|
||||
|
||||
private boolean visible(PluginCardDecl decl, RunwayUserDetails principal, String tenancyId) {
|
||||
if (decl.permission() == null || decl.permission().isBlank()) {
|
||||
return true;
|
||||
}
|
||||
if (principal == null || principal.realm() != decl.realm()) {
|
||||
return false;
|
||||
}
|
||||
Permission permission = catalog.find(decl.permission()).orElse(null);
|
||||
return permission != null && authorization.mayAccess(principal, permission, tenancyId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import mx.quest.runway.document.DocumentService;
|
||||
import mx.quest.runway.document.DocumentService.DocumentEntry;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* The tenant console's documents screen ({@code /__admin/documents}): a site manager uploads, lists, deletes,
|
||||
* and enables/disables the site's downloadable files (its {@code static/doc/} area). Gated by the grantable
|
||||
* {@code MANAGE_DOCUMENTS} permission (narrower than {@code CONFIGURE_SITE}). Documents are served publicly as
|
||||
* {@code nosniff} attachments; a <em>disabled</em> document is withheld (404) without being deleted.
|
||||
*/
|
||||
@Controller
|
||||
public class DocumentsController {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(DocumentsController.class);
|
||||
|
||||
private final SiteResolver siteResolver;
|
||||
private final DocumentService documents;
|
||||
private final MessageSource messages;
|
||||
|
||||
public DocumentsController(SiteResolver siteResolver, DocumentService documents,
|
||||
@Qualifier("operatorAwareMessageSource") MessageSource messages) {
|
||||
this.siteResolver = siteResolver;
|
||||
this.documents = documents;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
@GetMapping("/__admin/documents")
|
||||
@PreAuthorize("@authz.may('MANAGE_DOCUMENTS')")
|
||||
public String list(Model model) {
|
||||
String siteId = currentSiteId();
|
||||
List<DocumentEntry> docs;
|
||||
try {
|
||||
docs = documents.list(siteId);
|
||||
} catch (IOException e) {
|
||||
log.warn("could not list documents for {}", siteId, e);
|
||||
docs = List.of();
|
||||
model.addAttribute("error", message("op.documents.listFailed", "Could not list documents."));
|
||||
}
|
||||
model.addAttribute("documents", docs);
|
||||
model.addAttribute("maxMb", DocumentService.MAX_DOC_BYTES / (1024 * 1024));
|
||||
model.addAttribute("contentTemplate", "operator/admin/documents");
|
||||
model.addAttribute("pageTitleKey", "op.documents.title");
|
||||
return "operator/op-layout";
|
||||
}
|
||||
|
||||
@PostMapping("/__admin/documents/upload")
|
||||
@PreAuthorize("@authz.may('MANAGE_DOCUMENTS')")
|
||||
public String upload(@RequestParam("file") MultipartFile file, RedirectAttributes redirect) {
|
||||
if (file == null || file.isEmpty()) {
|
||||
redirect.addFlashAttribute("error", message("op.documents.noFile", "Choose a file."));
|
||||
return "redirect:/__admin/documents";
|
||||
}
|
||||
if (file.getSize() > DocumentService.MAX_DOC_BYTES) {
|
||||
redirect.addFlashAttribute("error", message("op.documents.tooLarge", "The document is too large."));
|
||||
return "redirect:/__admin/documents";
|
||||
}
|
||||
try {
|
||||
documents.add(currentSiteId(), file.getOriginalFilename(), file.getBytes());
|
||||
redirect.addFlashAttribute("flash", message("op.documents.uploaded", "Document uploaded."));
|
||||
} catch (mx.quest.runway.site.SiteStorageCeilings.OverCeiling over) {
|
||||
redirect.addFlashAttribute("error", message("op.documents.overCeiling",
|
||||
"Not uploaded: the site's files would go over their storage limit."));
|
||||
} catch (IllegalArgumentException e) {
|
||||
redirect.addFlashAttribute("error", message("op.documents.badName", "That file name cannot be used."));
|
||||
} catch (IOException e) {
|
||||
redirect.addFlashAttribute("error", message("op.documents.failed", "Could not save the document."));
|
||||
}
|
||||
return "redirect:/__admin/documents";
|
||||
}
|
||||
|
||||
@PostMapping("/__admin/documents/delete")
|
||||
@PreAuthorize("@authz.may('MANAGE_DOCUMENTS')")
|
||||
public String delete(@RequestParam String path, RedirectAttributes redirect) {
|
||||
try {
|
||||
documents.delete(currentSiteId(), path);
|
||||
redirect.addFlashAttribute("flash", message("op.documents.deleted", "Document deleted."));
|
||||
} catch (IllegalArgumentException | IOException e) {
|
||||
redirect.addFlashAttribute("error", message("op.documents.failed", "Could not delete the document."));
|
||||
}
|
||||
return "redirect:/__admin/documents";
|
||||
}
|
||||
|
||||
@PostMapping("/__admin/documents/toggle")
|
||||
@PreAuthorize("@authz.may('MANAGE_DOCUMENTS')")
|
||||
public String toggle(@RequestParam String path, @RequestParam(defaultValue = "false") boolean disable,
|
||||
RedirectAttributes redirect) {
|
||||
try {
|
||||
documents.setDisabled(currentSiteId(), path, disable);
|
||||
redirect.addFlashAttribute("flash", disable
|
||||
? message("op.documents.disabledMsg", "Document disabled.")
|
||||
: message("op.documents.enabledMsg", "Document enabled."));
|
||||
} catch (IllegalArgumentException | IOException e) {
|
||||
redirect.addFlashAttribute("error", message("op.documents.failed", "Could not update the document."));
|
||||
}
|
||||
return "redirect:/__admin/documents";
|
||||
}
|
||||
|
||||
private String currentSiteId() {
|
||||
return siteResolver.current()
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "no bound tenancy"))
|
||||
.id();
|
||||
}
|
||||
|
||||
private String message(String key, String fallback) {
|
||||
return messages.getMessage(key, null, fallback, LocaleContextHolder.getLocale());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The accepted values of the site fields that end up in every page's head or in the Web App Manifest: a value a
|
||||
* browser or a social network does not understand is ignored by it silently, so the console refuses it with the
|
||||
* reason instead. Blank always means "not set" (the platform's automatic choice).
|
||||
*/
|
||||
final class HeadFieldRules {
|
||||
|
||||
/** The Twitter/X card types that exist. */
|
||||
static final List<String> TWITTER_CARDS = List.of("summary", "summary_large_image");
|
||||
/** The manifest {@code display} modes browsers know, most to least app-like. */
|
||||
static final List<String> DISPLAY_MODES = List.of("fullscreen", "standalone", "minimal-ui", "browser");
|
||||
|
||||
/** A CSS hex colour: {@code #rgb}, {@code #rgba}, {@code #rrggbb} or {@code #rrggbbaa}. */
|
||||
private static final Pattern HEX_COLOUR = Pattern.compile("#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})");
|
||||
/** An Open Graph type: {@code website}, {@code article}, {@code video.movie}, {@code music.song}, … */
|
||||
private static final Pattern OG_TYPE = Pattern.compile("[a-z][a-z0-9_]*(?:[.:][a-z][a-z0-9_]*)?");
|
||||
|
||||
private HeadFieldRules() {
|
||||
}
|
||||
|
||||
static String twitterCard(String value) {
|
||||
return oneOf(value, TWITTER_CARDS, "op.rules.twitterCard",
|
||||
"The Twitter card must be summary or summary_large_image, or empty for automatic.");
|
||||
}
|
||||
|
||||
static String display(String value) {
|
||||
return oneOf(value, DISPLAY_MODES, "op.rules.display",
|
||||
"Display must be fullscreen, standalone, minimal-ui or browser, or empty.");
|
||||
}
|
||||
|
||||
static String ogType(String value) {
|
||||
String v = blankToNull(value);
|
||||
if (v != null && (v.length() > 40 || !OG_TYPE.matcher(v.toLowerCase(Locale.ROOT)).matches())) {
|
||||
throw new SiteConfigInput.Invalid("op.rules.ogType",
|
||||
"The content type must be an Open Graph type such as website or article.");
|
||||
}
|
||||
return v == null ? null : v.toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
static String colour(String value) {
|
||||
String v = blankToNull(value);
|
||||
if (v != null && !HEX_COLOUR.matcher(v).matches()) {
|
||||
throw new SiteConfigInput.Invalid("op.rules.colour", "A colour must be written as #rrggbb, such as #0d6efd.");
|
||||
}
|
||||
return v == null ? null : v.toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
static String language(String value) {
|
||||
String v = blankToNull(value);
|
||||
if (v != null) {
|
||||
Locale locale = Locale.forLanguageTag(v);
|
||||
// Two or three letters for the language itself (ISO 639): Java also accepts 5-8 letters ("english").
|
||||
if (locale.getLanguage().length() < 2 || locale.getLanguage().length() > 3
|
||||
|| !locale.toLanguageTag().equalsIgnoreCase(v)) {
|
||||
throw new SiteConfigInput.Invalid("op.rules.language",
|
||||
"The language must be a language tag such as en, es or pt-BR.");
|
||||
}
|
||||
return locale.toLanguageTag();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String oneOf(String value, List<String> allowed, String key, String fallback) {
|
||||
String v = blankToNull(value);
|
||||
if (v == null) {
|
||||
return null;
|
||||
}
|
||||
String lower = v.toLowerCase(Locale.ROOT);
|
||||
if (!allowed.contains(lower)) {
|
||||
throw new SiteConfigInput.Invalid(key, fallback);
|
||||
}
|
||||
return lower;
|
||||
}
|
||||
|
||||
private static String blankToNull(String value) {
|
||||
return (value == null || value.isBlank()) ? null : value.strip();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.icon.IconGenerationService;
|
||||
import mx.quest.runway.icon.IconRasterizer.IconRenderException;
|
||||
import mx.quest.runway.icon.SiteIcon;
|
||||
import mx.quest.runway.icon.SiteIconService;
|
||||
import mx.quest.runway.icon.SiteManifest;
|
||||
import mx.quest.runway.icon.SiteManifestService;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* The tenant console's icon & manifest screens. {@code /__admin/icons} uploads/removes the fixed icon slots
|
||||
* (favicons, apple-touch, PWA icons); {@code /__admin/manifest} edits the Web App Manifest fields — two separate
|
||||
* menu entries over the same site config. A manager can upload each slot manually, or <b>generate the whole
|
||||
* raster set (apple-touch / 192 / 512 PNG + favicon.ico) plus the SVG favicon from one uploaded SVG</b> (see
|
||||
* {@link IconGenerationService}). Both screens gated by {@code CONFIGURE_SITE}; a slot is always resolved through
|
||||
* the closed {@link SiteIcon} enum, so no request ever names a file on disk.
|
||||
*/
|
||||
@Controller
|
||||
public class IconsController {
|
||||
|
||||
private final SiteResolver siteResolver;
|
||||
private final SiteIconService icons;
|
||||
private final SiteManifestService manifests;
|
||||
private final IconGenerationService generation;
|
||||
private final MessageSource messages;
|
||||
|
||||
public IconsController(SiteResolver siteResolver, SiteIconService icons, SiteManifestService manifests,
|
||||
IconGenerationService generation,
|
||||
@Qualifier("operatorAwareMessageSource") MessageSource messages) {
|
||||
this.siteResolver = siteResolver;
|
||||
this.icons = icons;
|
||||
this.manifests = manifests;
|
||||
this.generation = generation;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
/** A slot's state for the screen: its stable key, public URL, and whether the site has provided it. */
|
||||
public record IconSlotView(String key, String url, boolean present) {
|
||||
}
|
||||
|
||||
@GetMapping("/__admin/icons")
|
||||
@PreAuthorize("@authz.may('CONFIGURE_SITE')")
|
||||
public String page(Model model) {
|
||||
String siteId = currentSiteId();
|
||||
Set<SiteIcon> present = icons.presentSlots(siteId);
|
||||
List<IconSlotView> slots = Arrays.stream(SiteIcon.values())
|
||||
.map(icon -> new IconSlotView(icon.key(), icon.url(), present.contains(icon)))
|
||||
.toList();
|
||||
model.addAttribute("slots", slots);
|
||||
model.addAttribute("maxKb", icons.maxBytes() / 1024);
|
||||
model.addAttribute("cb", System.currentTimeMillis()); // preview cache-buster so a re-upload shows at once
|
||||
model.addAttribute("contentTemplate", "operator/admin/icons");
|
||||
model.addAttribute("pageTitleKey", "op.icons.title");
|
||||
return "operator/op-layout";
|
||||
}
|
||||
|
||||
@GetMapping("/__admin/manifest")
|
||||
@PreAuthorize("@authz.may('CONFIGURE_SITE')")
|
||||
public String manifestPage(Model model) {
|
||||
model.addAttribute("manifest", manifests.get(currentSiteId()));
|
||||
model.addAttribute("contentTemplate", "operator/admin/web-manifest");
|
||||
model.addAttribute("pageTitleKey", "op.manifest.title");
|
||||
return "operator/op-layout";
|
||||
}
|
||||
|
||||
@PostMapping("/__admin/icons/{slot}/upload")
|
||||
@PreAuthorize("@authz.may('CONFIGURE_SITE')")
|
||||
public String upload(@PathVariable String slot, @RequestParam("file") MultipartFile file,
|
||||
RedirectAttributes redirect) {
|
||||
SiteIcon icon = SiteIcon.fromKey(slot).orElse(null);
|
||||
if (icon == null) {
|
||||
redirect.addFlashAttribute("error", message("op.icons.unknownSlot", "Unknown icon."));
|
||||
return "redirect:/__admin/icons";
|
||||
}
|
||||
if (file == null || file.isEmpty()) {
|
||||
redirect.addFlashAttribute("error", message("op.icons.noFile", "Choose a file."));
|
||||
return "redirect:/__admin/icons";
|
||||
}
|
||||
if (file.getSize() > icons.maxBytes()) {
|
||||
redirect.addFlashAttribute("error", message("op.icons.tooLarge", "The icon is too large."));
|
||||
return "redirect:/__admin/icons";
|
||||
}
|
||||
try {
|
||||
icons.store(currentSiteId(), icon, file.getBytes());
|
||||
redirect.addFlashAttribute("flash", message("op.icons.uploaded", "Icon updated."));
|
||||
} catch (IOException | IllegalArgumentException e) {
|
||||
redirect.addFlashAttribute("error", message("op.icons.failed", "Could not save the icon."));
|
||||
}
|
||||
return "redirect:/__admin/icons";
|
||||
}
|
||||
|
||||
@PostMapping("/__admin/icons/generate")
|
||||
@PreAuthorize("@authz.may('CONFIGURE_SITE')")
|
||||
public String generate(@RequestParam("svg") MultipartFile svg, RedirectAttributes redirect) {
|
||||
if (svg == null || svg.isEmpty()) {
|
||||
redirect.addFlashAttribute("error", message("op.icons.noFile", "Choose an SVG file."));
|
||||
return "redirect:/__admin/icons";
|
||||
}
|
||||
if (svg.getSize() > icons.maxBytes()) {
|
||||
redirect.addFlashAttribute("error", message("op.icons.tooLarge", "The SVG is too large."));
|
||||
return "redirect:/__admin/icons";
|
||||
}
|
||||
try {
|
||||
Set<SiteIcon> written = generation.generateFrom(currentSiteId(), svg.getBytes());
|
||||
redirect.addFlashAttribute("flash", messages.getMessage("op.icons.generated",
|
||||
new Object[]{written.size()}, "Generated " + written.size() + " icons from the SVG.",
|
||||
LocaleContextHolder.getLocale()));
|
||||
} catch (IconRenderException e) {
|
||||
// Content-based rejection: the file isn't a usable SVG (parse/render failed) — nothing was written.
|
||||
redirect.addFlashAttribute("error",
|
||||
message("op.icons.badSvg", "That file could not be read as an SVG image."));
|
||||
} catch (IOException | IllegalArgumentException e) {
|
||||
redirect.addFlashAttribute("error", message("op.icons.failed", "Could not save the icons."));
|
||||
}
|
||||
return "redirect:/__admin/icons";
|
||||
}
|
||||
|
||||
@PostMapping("/__admin/icons/{slot}/delete")
|
||||
@PreAuthorize("@authz.may('CONFIGURE_SITE')")
|
||||
public String delete(@PathVariable String slot, RedirectAttributes redirect) {
|
||||
SiteIcon icon = SiteIcon.fromKey(slot).orElse(null);
|
||||
if (icon != null) {
|
||||
try {
|
||||
icons.remove(currentSiteId(), icon);
|
||||
redirect.addFlashAttribute("flash", message("op.icons.removed", "Icon removed."));
|
||||
} catch (IOException e) {
|
||||
redirect.addFlashAttribute("error", message("op.icons.failed", "Could not remove the icon."));
|
||||
}
|
||||
}
|
||||
return "redirect:/__admin/icons";
|
||||
}
|
||||
|
||||
@PostMapping("/__admin/manifest")
|
||||
@PreAuthorize("@authz.may('CONFIGURE_SITE')")
|
||||
public String saveManifest(@RequestParam(required = false) String name,
|
||||
@RequestParam(required = false) String shortName,
|
||||
@RequestParam(required = false) String description,
|
||||
@RequestParam(required = false) String themeColor,
|
||||
@RequestParam(required = false) String backgroundColor,
|
||||
@RequestParam(required = false) String display,
|
||||
@RequestParam(required = false) String lang,
|
||||
RedirectAttributes redirect) {
|
||||
try {
|
||||
manifests.save(currentSiteId(), new SiteManifest(blankToNull(name), blankToNull(shortName),
|
||||
blankToNull(description), HeadFieldRules.colour(themeColor), HeadFieldRules.colour(backgroundColor),
|
||||
HeadFieldRules.display(display), HeadFieldRules.language(lang)));
|
||||
redirect.addFlashAttribute("flash", message("op.icons.manifestSaved", "Manifest saved."));
|
||||
} catch (SiteConfigInput.Invalid invalid) {
|
||||
redirect.addFlashAttribute("error", message(invalid.messageKey(), invalid.getMessage()));
|
||||
} catch (IOException e) {
|
||||
redirect.addFlashAttribute("error", message("op.icons.failed", "Could not save the manifest."));
|
||||
}
|
||||
return "redirect:/__admin/manifest";
|
||||
}
|
||||
|
||||
private String currentSiteId() {
|
||||
return siteResolver.current()
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "no bound tenancy"))
|
||||
.id();
|
||||
}
|
||||
|
||||
private String message(String key, String fallback) {
|
||||
return messages.getMessage(key, null, fallback, LocaleContextHolder.getLocale());
|
||||
}
|
||||
|
||||
private static String blankToNull(String value) {
|
||||
return (value == null || value.isBlank()) ? null : value.strip();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.log.AppActivityLog;
|
||||
import mx.quest.runway.log.SiteLogConfigService;
|
||||
import mx.quest.runway.platform.KernelSettings;
|
||||
import mx.quest.runway.platform.KernelSettingsService;
|
||||
import mx.quest.runway.plugin.PluginSettingDef;
|
||||
import mx.quest.runway.plugin.SettingType;
|
||||
import mx.quest.runway.plugin.SettingValidationException;
|
||||
import mx.quest.runway.site.SiteStore;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* The kernel's own settings forms ({@code /__app/config/{screen}}): Settings → Server settings, and the policy cards
|
||||
* of Backups, Bandwidth, Activity → Logs and Plugins. The same settings form as a plugin's (sections, help, Advanced,
|
||||
* show-when), over {@link KernelSettings}; a field the server itself sets is shown locked with where it is set.
|
||||
* A platform operation: gated to the master and wildcard admins ({@link PlatformAuthority}), like Platform settings.
|
||||
*/
|
||||
@Controller
|
||||
public class KernelSettingsController {
|
||||
|
||||
private final KernelSettingsService settings;
|
||||
private final PlatformAuthority platformAuthority;
|
||||
private final AppActivityLog activity;
|
||||
private final SiteStore sites;
|
||||
private final SiteLogConfigService siteLogs;
|
||||
private final MessageSource messages;
|
||||
|
||||
public KernelSettingsController(KernelSettingsService settings, PlatformAuthority platformAuthority,
|
||||
AppActivityLog activity, SiteStore sites, SiteLogConfigService siteLogs,
|
||||
@Qualifier("operatorAwareMessageSource") MessageSource messages) {
|
||||
this.messages = messages;
|
||||
this.sites = sites;
|
||||
this.siteLogs = siteLogs;
|
||||
this.settings = settings;
|
||||
this.platformAuthority = platformAuthority;
|
||||
this.activity = activity;
|
||||
}
|
||||
|
||||
@GetMapping("/__app/config/{screen}")
|
||||
public String form(@PathVariable String screen, Authentication authentication, Model model) {
|
||||
platformAuthority.require(authentication);
|
||||
requireScreen(screen);
|
||||
Map<String, String> locks = settings.locks(screen);
|
||||
Map<String, KernelSettingsService.LockState> states = settings.lockStates(screen);
|
||||
List<SettingSection> sections = new ArrayList<>();
|
||||
for (SettingSection section : SettingsForm.build(settings.render(screen), KernelSettings.descriptor(),
|
||||
key -> null)) {
|
||||
sections.add(new SettingSection(section.label(), section.help(), section.helpLink(),
|
||||
locked(section.fields(), locks, states), locked(section.advanced(), locks, states),
|
||||
section.advancedOpen(),
|
||||
section.advancedShowWhen(), section.advancedHidden()));
|
||||
}
|
||||
model.addAttribute("pluginName", null);
|
||||
model.addAttribute("settingsTitleKey", "op.config." + screen + ".title");
|
||||
model.addAttribute("sections", sections);
|
||||
model.addAttribute("fields", sections.stream().flatMap(s -> s.fields().stream()).toList());
|
||||
model.addAttribute("pendingKeys", settings.pendingKeys(screen));
|
||||
model.addAttribute("strayKeys", List.of());
|
||||
model.addAttribute("settingsAction", "/__app/config/" + screen);
|
||||
model.addAttribute("adoptAction", locks.isEmpty() ? null : "/__app/config/" + screen + "/adopt");
|
||||
model.addAttribute("settingsBack", backOf(screen));
|
||||
model.addAttribute("settingsScope", "app");
|
||||
model.addAttribute("contentTemplate", "operator/plugin-settings");
|
||||
model.addAttribute("pageTitleKey", "op.config." + screen + ".title");
|
||||
return "operator/op-layout";
|
||||
}
|
||||
|
||||
@PostMapping("/__app/config/{screen}")
|
||||
public String save(@PathVariable String screen, HttpServletRequest request, Authentication authentication,
|
||||
RedirectAttributes redirect) {
|
||||
platformAuthority.require(authentication);
|
||||
requireScreen(screen);
|
||||
Map<String, String> submitted = new LinkedHashMap<>();
|
||||
for (PluginSettingDef def : KernelSettings.forScreen(screen)) {
|
||||
String value = request.getParameter(def.key());
|
||||
// An unchecked checkbox submits nothing: that is "false", not "the default".
|
||||
if (value == null && SettingType.of(def.type()) == SettingType.BOOLEAN) {
|
||||
value = "false";
|
||||
}
|
||||
submitted.put(def.key(), value);
|
||||
}
|
||||
try {
|
||||
settings.save(screen, submitted);
|
||||
activity.record(authentication.getName(), "platform.kernel-settings-changed", screen);
|
||||
redirect.addFlashAttribute("flash", messages.getMessage("op.config.kernel.saved", null,
|
||||
"Saved. The changes apply after the next restart.", LocaleContextHolder.getLocale())
|
||||
+ sitesAboveLogCeiling());
|
||||
} catch (KernelSettingsService.PlaceholderRefused refused) {
|
||||
var locale = LocaleContextHolder.getLocale();
|
||||
String label = messages.getMessage("op.ks." + refused.key(), null, refused.key(), locale);
|
||||
redirect.addFlashAttribute("error", messages.getMessage("op.config.error.placeholder",
|
||||
new Object[] {label}, label + ": " + refused.getMessage(), locale));
|
||||
} catch (SettingValidationException invalid) {
|
||||
redirect.addFlashAttribute("error", refusal(invalid));
|
||||
}
|
||||
return "redirect:/__app/config/" + screen;
|
||||
}
|
||||
|
||||
/**
|
||||
* "Use the file's value" on a locked field: copies the value the server runs with for {@code key} into the
|
||||
* console's store ({@link KernelSettingsService#adopt}), so the operator can then remove the host's line and
|
||||
* restart once with nothing changing. Same gate and CSRF protection as a save, and recorded in the activity log
|
||||
* by key (never the value). The field stays locked: the host's value still wins until its line is removed.
|
||||
*/
|
||||
@PostMapping("/__app/config/{screen}/adopt")
|
||||
public String adopt(@PathVariable String screen, @RequestParam("key") String key, Authentication authentication,
|
||||
RedirectAttributes redirect) {
|
||||
platformAuthority.require(authentication);
|
||||
requireScreen(screen);
|
||||
if (KernelSettings.forScreen(screen).stream().noneMatch(def -> def.key().equals(key))) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no such setting on this screen");
|
||||
}
|
||||
var locale = LocaleContextHolder.getLocale();
|
||||
String label = messages.getMessage("op.ks." + key, null, key, locale);
|
||||
String origin = settings.locks(screen).getOrDefault(key, "");
|
||||
try {
|
||||
KernelSettingsService.Adopted adopted = settings.adopt(key);
|
||||
activity.record(authentication.getName(), "platform.kernel-setting-adopted", key);
|
||||
String code = adopted == KernelSettingsService.Adopted.STORED ? "op.config.adopt.stored"
|
||||
: "op.config.adopt.default";
|
||||
redirect.addFlashAttribute("flash", messages.getMessage(code, new Object[] {label, origin},
|
||||
label + ": copied.", locale));
|
||||
} catch (KernelSettingsService.PlaceholderRefused refused) {
|
||||
redirect.addFlashAttribute("error", messages.getMessage("op.config.error.placeholder",
|
||||
new Object[] {label}, label + ": " + refused.getMessage(), locale));
|
||||
} catch (SettingValidationException invalid) {
|
||||
redirect.addFlashAttribute("error", refusal(invalid));
|
||||
}
|
||||
return "redirect:/__app/config/" + screen;
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a value was refused, in the operator's language: the field's label, then the detail from the refusal's
|
||||
* message code ({@code op.config.invalid.*}). A refusal without a code, or a code with no message, shows its
|
||||
* English text, so the operator always learns which field and why.
|
||||
*/
|
||||
private String refusal(SettingValidationException invalid) {
|
||||
var locale = LocaleContextHolder.getLocale();
|
||||
String label = messages.getMessage("op.ks." + invalid.key(), null, invalid.key(), locale);
|
||||
String detail = invalid.code() == null ? invalid.getMessage()
|
||||
: messages.getMessage(invalid.code(), invalid.args(), invalid.getMessage(), locale);
|
||||
return messages.getMessage("op.config.kernel.invalid", new Object[] {label, detail}, label + ": " + detail,
|
||||
locale);
|
||||
}
|
||||
|
||||
/**
|
||||
* When the sites' log retention ceiling is below what some sites chose, says how many: they keep their value and
|
||||
* are held to the ceiling, and each sees a note on its own Logs screen (a ceiling warns,
|
||||
* clamps and never deletes on the save itself).
|
||||
*/
|
||||
private String sitesAboveLogCeiling() {
|
||||
int ceiling;
|
||||
try {
|
||||
ceiling = Integer.parseInt(String.valueOf(settings.upcoming("runway.logs.max-retention-days")).trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return "";
|
||||
}
|
||||
long above = sites.findAll().stream()
|
||||
.map(site -> siteLogs.get(site.id()).retentionDays())
|
||||
.filter(days -> days != null && days > ceiling)
|
||||
.count();
|
||||
return above == 0 ? "" : " " + messages.getMessage("op.config.kernel.logCeiling",
|
||||
new Object[] {above, String.valueOf(ceiling)}, "Some sites keep logs longer than the ceiling.",
|
||||
LocaleContextHolder.getLocale());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code fields} with the host-set ones locked: each says where the host sets it and what removing that would do,
|
||||
* and, when removing it would change something, offers to copy the server's value into the console first.
|
||||
*/
|
||||
private static List<SettingField> locked(List<SettingField> fields, Map<String, String> locks,
|
||||
Map<String, KernelSettingsService.LockState> states) {
|
||||
List<SettingField> out = new ArrayList<>(fields.size());
|
||||
for (SettingField field : fields) {
|
||||
String origin = locks.get(field.key());
|
||||
if (origin == null) {
|
||||
out.add(field);
|
||||
continue;
|
||||
}
|
||||
KernelSettingsService.LockState state = states.get(field.key());
|
||||
boolean offer = state == KernelSettingsService.LockState.NONE
|
||||
|| state == KernelSettingsService.LockState.DIFFERS;
|
||||
String button = !offer ? null
|
||||
: HOST_FILE.equals(origin) ? "op.settings.adopt.file" : "op.settings.adopt.server";
|
||||
out.add(field.lockedBy(origin, state == null ? null : state.key(), button));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** How {@code HostSettings} names the host's own file; any other origin is "the server". */
|
||||
private static final String HOST_FILE = "external/application.yml";
|
||||
|
||||
private static void requireScreen(String screen) {
|
||||
if (!KernelSettings.screens().contains(screen)) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no such settings screen");
|
||||
}
|
||||
}
|
||||
|
||||
/** Where the form's Back link goes: the screen the card belongs to. */
|
||||
private static String backOf(String screen) {
|
||||
return switch (screen) {
|
||||
case "backups" -> "/__app/backups";
|
||||
case "bandwidth" -> "/__app/bandwidth";
|
||||
case "activity" -> "/__app/logs";
|
||||
case "plugins" -> "/__app/plugins";
|
||||
default -> "/__app/settings";
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDate;
|
||||
import mx.quest.runway.log.AuditPage;
|
||||
import mx.quest.runway.log.LogKind;
|
||||
import mx.quest.runway.log.LogProperties;
|
||||
import mx.quest.runway.log.SiteLogConfig;
|
||||
import mx.quest.runway.log.SiteLogConfigService;
|
||||
import mx.quest.runway.log.SiteLogService;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* The tenant console's logs screen ({@code /__admin/logs}): tails the site's access log, shows the site's
|
||||
* <b>audit journal</b> as a filtered, paged listing (date range / actor / action, newest first, across the whole
|
||||
* retention window — the same {@link AuditView} card as the application Activity log) with a CSV download
|
||||
* ({@code /__admin/logs/audit.csv}), and edits the log settings (IP anonymization, retention). A change to those
|
||||
* settings is itself recorded in the audit journal.
|
||||
*
|
||||
* <p>Logs are strictly tenant-private, so every route is gated to the site's own administrators via
|
||||
* {@link TenantAuthority} — there is no grantable "view logs" permission and no app-realm surface that reads a
|
||||
* tenant's logs. The journal read is bounded ({@link mx.quest.runway.log.AuditJournal.Limits#DEFAULT}).
|
||||
*/
|
||||
@Controller
|
||||
public class LogsController {
|
||||
|
||||
private static final int TAIL_LINES = 200;
|
||||
|
||||
private final SiteResolver siteResolver;
|
||||
private final SiteLogService logs;
|
||||
private final SiteLogConfigService configs;
|
||||
private final LogProperties props;
|
||||
private final TenantAuthority tenantAuthority;
|
||||
private final MessageSource messages;
|
||||
|
||||
public LogsController(SiteResolver siteResolver, SiteLogService logs, SiteLogConfigService configs,
|
||||
LogProperties props, TenantAuthority tenantAuthority,
|
||||
@Qualifier("operatorAwareMessageSource") MessageSource messages) {
|
||||
this.siteResolver = siteResolver;
|
||||
this.logs = logs;
|
||||
this.configs = configs;
|
||||
this.props = props;
|
||||
this.tenantAuthority = tenantAuthority;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
@GetMapping("/__admin/logs")
|
||||
public String view(Authentication authentication,
|
||||
@RequestParam(required = false) String from, @RequestParam(required = false) String to,
|
||||
@RequestParam(required = false) String actor, @RequestParam(required = false) String action,
|
||||
@RequestParam(required = false) Integer page, Model model) {
|
||||
String siteId = currentSiteId();
|
||||
tenantAuthority.require(authentication, siteId);
|
||||
|
||||
SiteLogConfig cfg = configs.get(siteId);
|
||||
model.addAttribute("accessLines", String.join("\n", logs.tail(siteId, LogKind.ACCESS, TAIL_LINES)));
|
||||
AuditView.Filter filter = AuditView.filter(from, to, actor, action, page);
|
||||
AuditPage audit = logs.queryAudit(siteId, filter.query(), filter.page() * AuditView.PAGE_SIZE,
|
||||
AuditView.PAGE_SIZE);
|
||||
AuditView.populate(model, audit, filter, "/__admin/logs", "/__admin/logs/audit.csv", "op.logs.audit",
|
||||
"runway.site.audit", messages, LocaleContextHolder.getLocale());
|
||||
model.addAttribute("anonymize", cfg.anonymize());
|
||||
model.addAttribute("retentionDays", cfg.effectiveRetentionDays(props.getMaxRetentionDays()));
|
||||
model.addAttribute("maxRetention", props.getMaxRetentionDays());
|
||||
// Set above the platform's maximum (the operator lowered it since): say so instead of clamping silently.
|
||||
model.addAttribute("retentionClamped", cfg.retentionDays() != null
|
||||
&& cfg.retentionDays() > props.getMaxRetentionDays() ? cfg.retentionDays() : null);
|
||||
model.addAttribute("dropped", logs.droppedCount());
|
||||
model.addAttribute("contentTemplate", "operator/admin/logs");
|
||||
model.addAttribute("pageTitleKey", "op.logs.title");
|
||||
return "operator/op-layout";
|
||||
}
|
||||
|
||||
/** The site's audit journal as CSV (the screen's filters, at most {@link AuditView#MAX_EXPORT_ROWS} rows). */
|
||||
@GetMapping("/__admin/logs/audit.csv")
|
||||
public ResponseEntity<byte[]> exportAudit(Authentication authentication,
|
||||
@RequestParam(required = false) String from,
|
||||
@RequestParam(required = false) String to,
|
||||
@RequestParam(required = false) String actor,
|
||||
@RequestParam(required = false) String action) {
|
||||
String siteId = currentSiteId();
|
||||
tenantAuthority.require(authentication, siteId);
|
||||
AuditView.Filter filter = AuditView.filter(from, to, actor, action, 0);
|
||||
AuditPage audit = logs.queryAudit(siteId, filter.query(), 0, AuditView.MAX_EXPORT_ROWS);
|
||||
return AuditView.csv(audit, siteId + "-audit-" + LocalDate.now() + ".csv", messages,
|
||||
LocaleContextHolder.getLocale());
|
||||
}
|
||||
|
||||
@PostMapping("/__admin/logs")
|
||||
public String save(Authentication authentication,
|
||||
@RequestParam(defaultValue = "false") boolean anonymize,
|
||||
@RequestParam(defaultValue = "30") int retentionDays, RedirectAttributes redirect) {
|
||||
String siteId = currentSiteId();
|
||||
tenantAuthority.require(authentication, siteId);
|
||||
try {
|
||||
int retention = Math.max(1, retentionDays);
|
||||
if (retention > props.getMaxRetentionDays()) {
|
||||
// A ceiling refuses, never clamps silently.
|
||||
redirect.addFlashAttribute("error", message("op.logs.retention.aboveMax",
|
||||
"The platform keeps logs at most {0} days.", props.getMaxRetentionDays()));
|
||||
return "redirect:/__admin/logs";
|
||||
}
|
||||
configs.save(siteId, new SiteLogConfig(anonymize, retention));
|
||||
logs.audit(siteId, authentication.getName(), "logs.settings-changed",
|
||||
"anonymize=" + anonymize + " retentionDays=" + retention);
|
||||
redirect.addFlashAttribute("flash", message("op.logs.saved", "Log settings saved."));
|
||||
} catch (IOException e) {
|
||||
redirect.addFlashAttribute("error", message("op.logs.failed", "Could not save log settings."));
|
||||
}
|
||||
return "redirect:/__admin/logs";
|
||||
}
|
||||
|
||||
private String currentSiteId() {
|
||||
return siteResolver.current()
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "no bound tenancy"))
|
||||
.id();
|
||||
}
|
||||
|
||||
private String message(String key, String fallback, Object... args) {
|
||||
return messages.getMessage(key, args.length == 0 ? null : args, fallback, LocaleContextHolder.getLocale());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import mx.quest.runway.site.Site;
|
||||
import mx.quest.runway.site.SiteLifecycleService;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* The tenant console's <b>Maintenance</b> screen ({@code /__admin/maintenance}) — a site manager takes the
|
||||
* <em>public</em> site offline for maintenance (visitors see a 503 page with an optional message) while the
|
||||
* console and login stay reachable, then brings it back.
|
||||
*
|
||||
* <p>Gated by the grantable {@code MAINTENANCE_MODE} permission. Bound-tenancy only — a manager can only ever
|
||||
* toggle maintenance on its own site. The enforcement (the public 503) is {@code MaintenanceSiteFilter}; this
|
||||
* controller only flips the stored flag.
|
||||
*/
|
||||
@Controller
|
||||
public class MaintenanceController {
|
||||
|
||||
private final SiteResolver siteResolver;
|
||||
private final SiteLifecycleService lifecycle;
|
||||
private final MessageSource messages;
|
||||
|
||||
public MaintenanceController(SiteResolver siteResolver, SiteLifecycleService lifecycle,
|
||||
@org.springframework.beans.factory.annotation.Qualifier("operatorAwareMessageSource")
|
||||
MessageSource messages) {
|
||||
this.siteResolver = siteResolver;
|
||||
this.lifecycle = lifecycle;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
@GetMapping("/__admin/maintenance")
|
||||
@PreAuthorize("@authz.may('MAINTENANCE_MODE')")
|
||||
public String view(Model model) {
|
||||
Site site = boundTenancy();
|
||||
model.addAttribute("maintenance", site.maintenance());
|
||||
model.addAttribute("maintenanceMessage", site.maintenanceMessage() == null ? "" : site.maintenanceMessage());
|
||||
model.addAttribute("pageTitleKey", "op.maint.title");
|
||||
model.addAttribute("contentTemplate", "operator/admin/maintenance");
|
||||
return "operator/op-layout";
|
||||
}
|
||||
|
||||
@PostMapping("/__admin/maintenance")
|
||||
@PreAuthorize("@authz.may('MAINTENANCE_MODE')")
|
||||
public String toggle(@RequestParam(value = "enabled", defaultValue = "false") boolean enabled,
|
||||
@RequestParam(value = "message", required = false) String message,
|
||||
RedirectAttributes redirect) {
|
||||
Site site = boundTenancy();
|
||||
lifecycle.setMaintenance(site.id(), enabled, message);
|
||||
String key = enabled ? "op.maint.flash.on" : "op.maint.flash.off";
|
||||
redirect.addFlashAttribute("flash", message(key, enabled ? "Maintenance mode is on." : "Site is live again."));
|
||||
return "redirect:/__admin/maintenance";
|
||||
}
|
||||
|
||||
private String message(String code, String fallback) {
|
||||
return messages.getMessage(code, null, fallback, LocaleContextHolder.getLocale());
|
||||
}
|
||||
|
||||
private Site boundTenancy() {
|
||||
return siteResolver.current()
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "no bound tenancy"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import mx.quest.runway.authz.AuthorizationService;
|
||||
import mx.quest.runway.authz.Permission;
|
||||
import mx.quest.runway.authz.PermissionCatalog;
|
||||
import mx.quest.runway.plugin.LoadedPlugin;
|
||||
import mx.quest.runway.plugin.PluginMenuDecl;
|
||||
import mx.quest.runway.plugin.RunningPlugins;
|
||||
import mx.quest.runway.security.RunwayUserDetails;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Collects the admin-menu links plugins contribute (a plugin never builds its own admin page — it declares a
|
||||
* {@code menu:} entry in its descriptor) and hands the operator console the ones a given principal
|
||||
* may see. The kernel knows only this generic collection point; there is zero plugin-specific code in the
|
||||
* chrome.
|
||||
*
|
||||
* <p>Filtered by <b>realm</b> (an application menu never shows in the tenant console or vice versa) and by
|
||||
* <b>region</b> (the topbar group a plugin targets: {@code menu} = top-level nav, {@code settings} /
|
||||
* {@code activity} = the matching dropdown), ordered ({@code order} → plugin id → declaration order), and gated by
|
||||
* <b>permission visibility</b>: an entry naming a permission is hidden from a principal who fails {@code mayAccess}
|
||||
* on it (an undeclared permission fails closed). This is UX only — the plugin's own controller still enforces;
|
||||
* hiding merely declutters.
|
||||
*/
|
||||
@Component
|
||||
public class MenuRegistry {
|
||||
|
||||
/** The default region for a menu declaration that leaves {@code region} unset — the top-level nav bar. */
|
||||
static final String DEFAULT_REGION = "menu";
|
||||
|
||||
private final RunningPlugins runningPlugins;
|
||||
private final AuthorizationService authorization;
|
||||
private final PermissionCatalog catalog;
|
||||
|
||||
public MenuRegistry(RunningPlugins runningPlugins, AuthorizationService authorization, PermissionCatalog catalog) {
|
||||
this.runningPlugins = runningPlugins;
|
||||
this.authorization = authorization;
|
||||
this.catalog = catalog;
|
||||
}
|
||||
|
||||
/** The Font Awesome class a plugin menu entry falls back to when it declares no {@code icon}. */
|
||||
static final String DEFAULT_MENU_ICON = "fa-solid fa-puzzle-piece";
|
||||
|
||||
/** One resolved menu link for the topbar. {@code icon} is always a non-blank Font Awesome class. */
|
||||
public record MenuEntry(String label, String path, int order, String pluginId, String icon) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The visible <b>top-level</b> ({@code region: menu}) menu entries for {@code principal} in {@code realm}
|
||||
* (+ bound {@code tenancyId} for tenant). Shorthand for {@link #menuFor(Realm, String, RunwayUserDetails, String)}
|
||||
* with the default region. A {@code null} principal (or one whose realm differs) sees none of the
|
||||
* permission-gated entries.
|
||||
*/
|
||||
public List<MenuEntry> menuFor(Realm realm, RunwayUserDetails principal, String tenancyId) {
|
||||
return menuFor(realm, DEFAULT_REGION, principal, tenancyId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The visible menu entries a plugin targets at {@code region} for {@code principal} in {@code realm} (+ bound
|
||||
* {@code tenancyId} for tenant). The region is the topbar group the entry renders into: {@code menu}
|
||||
* for the top-level nav, {@code settings} / {@code activity} for the matching dropdown, so a plugin can drop its
|
||||
* own console screen into a group instead of adding a top-level item. A declaration that leaves {@code region}
|
||||
* blank defaults to {@link #DEFAULT_REGION} — a plugin authored before region targeting keeps its top-level
|
||||
* placement. Filtered by realm + region, gated by permission visibility, and ordered ({@code order} → plugin id).
|
||||
*/
|
||||
public List<MenuEntry> menuFor(Realm realm, String region, RunwayUserDetails principal, String tenancyId) {
|
||||
String target = normalizeRegion(region);
|
||||
List<MenuEntry> entries = new ArrayList<>();
|
||||
for (LoadedPlugin plugin : runningPlugins.installed()) {
|
||||
for (PluginMenuDecl decl : plugin.descriptor().menu()) {
|
||||
if (decl.realm() != realm || !normalizeRegion(decl.region()).equals(target)) {
|
||||
continue;
|
||||
}
|
||||
if (!visible(decl, principal, tenancyId)) {
|
||||
continue;
|
||||
}
|
||||
// The label is resolved as an i18n key in the topbar (#{label}); coalesce a null/blank label to
|
||||
// the plugin id so a mis-authored menu entry degrades to a harmless literal instead of a render error.
|
||||
String label = (decl.label() == null || decl.label().isBlank()) ? plugin.id() : decl.label();
|
||||
String icon = (decl.icon() == null || decl.icon().isBlank()) ? DEFAULT_MENU_ICON : decl.icon().strip();
|
||||
entries.add(new MenuEntry(label, decl.path(), decl.order(), plugin.id(), icon));
|
||||
}
|
||||
}
|
||||
entries.sort(Comparator.comparingInt(MenuEntry::order).thenComparing(MenuEntry::pluginId));
|
||||
return List.copyOf(entries);
|
||||
}
|
||||
|
||||
/** A blank/null region coalesces to {@link #DEFAULT_REGION} so an unset region means the top-level nav. */
|
||||
private static String normalizeRegion(String region) {
|
||||
return (region == null || region.isBlank()) ? DEFAULT_REGION : region;
|
||||
}
|
||||
|
||||
private boolean visible(PluginMenuDecl decl, RunwayUserDetails principal, String tenancyId) {
|
||||
if (decl.permission() == null || decl.permission().isBlank()) {
|
||||
return true; // no gate → always visible
|
||||
}
|
||||
if (principal == null || principal.realm() != decl.realm()) {
|
||||
return false;
|
||||
}
|
||||
Permission permission = catalog.find(decl.permission()).orElse(null);
|
||||
return permission != null && authorization.mayAccess(principal, permission, tenancyId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The plugin <b>settings</b> entries for the console's Settings menu — one per running plugin that declares a
|
||||
* settings schema for {@code realm} ({@code siteSettings:} for TENANT, {@code settings:} for APPLICATION),
|
||||
* each linking to the kernel's generic settings form ({@code /__admin/plugins/<id>/settings} or
|
||||
* {@code /__app/plugins/<id>/settings}). The {@link MenuEntry#label()} is the plugin's <b>name</b> (a literal,
|
||||
* rendered as plain text — not an i18n key like {@link #menuFor}'s). Gated by the plugin's reserved
|
||||
* {@code settings} control point when it declares one (undeclared ⇒ visible; the controller still enforces),
|
||||
* then ordered by name. This replaces the old standalone "Site settings" landing page.
|
||||
*/
|
||||
public List<MenuEntry> settingsFor(Realm realm, RunwayUserDetails principal, String tenancyId) {
|
||||
String prefix = realm == Realm.APPLICATION ? "/__app/plugins/" : "/__admin/plugins/";
|
||||
List<MenuEntry> entries = new ArrayList<>();
|
||||
for (LoadedPlugin plugin : runningPlugins.installed()) {
|
||||
boolean hasSchema = realm == Realm.APPLICATION
|
||||
? !plugin.descriptor().settings().isEmpty()
|
||||
: !plugin.descriptor().siteSettings().isEmpty();
|
||||
if (!hasSchema || !settingsVisible(plugin.id(), realm, principal, tenancyId)) {
|
||||
continue;
|
||||
}
|
||||
String name = plugin.descriptor().name();
|
||||
String label = (name == null || name.isBlank()) ? plugin.id() : name;
|
||||
entries.add(new MenuEntry(label, prefix + plugin.id() + "/settings", 0, plugin.id(), DEFAULT_MENU_ICON));
|
||||
}
|
||||
entries.sort(Comparator.comparing(MenuEntry::label, String.CASE_INSENSITIVE_ORDER).thenComparing(MenuEntry::pluginId));
|
||||
return List.copyOf(entries);
|
||||
}
|
||||
|
||||
private boolean settingsVisible(String pluginId, Realm realm, RunwayUserDetails principal, String tenancyId) {
|
||||
Permission permission = catalog.find(mx.quest.runway.storage.PathSafety.compoundKey(pluginId, "settings")).orElse(null);
|
||||
if (permission == null) {
|
||||
return true; // the plugin declares no settings control point → visible (the controller enforces)
|
||||
}
|
||||
if (principal == null || principal.realm() != realm) {
|
||||
return false;
|
||||
}
|
||||
return authorization.mayAccess(principal, permission, tenancyId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
/**
|
||||
* Serves the operator console's <b>self-hosted</b> chrome assets from the classpath at {@code /__assets/**} —
|
||||
* the vendor bundles (Tabler/Bootstrap, FontAwesome, HTMX, Alpine, Chart.js) and Runway's own
|
||||
* {@code runway-chrome.css/js}. Self-hosting (not a CDN) is the locked decision: offline/air-gapped capability,
|
||||
* pinned reproducible versions, a tight CSP, and no runtime outbound call.
|
||||
*
|
||||
* <p>These are <b>classpath-only</b> (in the jar), never the external tree, so an accidental on-disk copy can
|
||||
* never shadow the jar's and serve stale chrome after an upgrade (per-tenant {@code /static/**} and per-plugin
|
||||
* {@code /__plugin/<id>/static/**} stay external — those <em>are</em> tenant/plugin-editable). The handler is
|
||||
* registered at {@link Ordered#HIGHEST_PRECEDENCE} mirroring {@code PluginStaticResourceConfig}; because
|
||||
* {@code spring.web.resources.add-mappings} is already {@code false}, raising it cannot pull Boot's default
|
||||
* {@code /**} handler ahead of the page/operator controllers (the handler-ordering trap is structurally avoided). The
|
||||
* {@code /__assets} prefix is unreachable as a public page path — every {@code /__} path is blocked by
|
||||
* {@code PathSafety}/{@code PageController} — so no tenant page can claim it.
|
||||
*
|
||||
* <p><b>Caching</b> is decided per request by {@link AssetCachePolicy} (one day for a {@code ?v=}-versioned URL,
|
||||
* revalidate-every-time for an unversioned one), so the handler itself is given <b>no</b> cache period — it would
|
||||
* otherwise overwrite the policy's header with one fixed value for every request.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class OperatorAssetsConfig implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/__assets/**")
|
||||
.addResourceLocations("classpath:/static/")
|
||||
.resourceChain(true);
|
||||
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(new AssetCachePolicy()).addPathPatterns("/__assets/**");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.util.Locale;
|
||||
import mx.quest.runway.i18n.SiteAwareMessageSource;
|
||||
import mx.quest.runway.web.RequestPaths;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.MessageSourceResolvable;
|
||||
import org.springframework.context.NoSuchMessageException;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
/**
|
||||
* The single {@link MessageSource} installed on the Thymeleaf engine: it routes {@code #{}} resolution by the
|
||||
* current request. An <b>operator</b> request ({@link OperatorPaths#isOperatorRequest}) resolves against the
|
||||
* {@link OperatorMessageSource}; everything else (tenant pages) keeps resolving against the per-site
|
||||
* {@link SiteAwareMessageSource}. One engine, one message source, but the two realms' string namespaces never
|
||||
* cross — the i18n half of the realm-isolation law.
|
||||
*
|
||||
* <p>The discriminator is the request URI (via {@link RequestContextHolder}), not whether a site is bound:
|
||||
* {@code /__admin} chrome must use operator strings even though a tenant is the subject. With no request bound
|
||||
* (e.g. a background render) it falls through to the site source, which itself no-ops without a bound site.
|
||||
*/
|
||||
@Component
|
||||
public class OperatorAwareMessageSource implements MessageSource {
|
||||
|
||||
/**
|
||||
* Request attribute a <b>tenant-page render</b> sets to force resolution against the SITE strings even when
|
||||
* it is served under a console path. The page editor's live preview / quality run
|
||||
* ({@code DraftRenderer}) render a tenant's own page — full of the site's {@code #{}} keys — from a
|
||||
* {@code /__admin/**} URL; without this the URI-based routing below would hand them the console's operator
|
||||
* strings and every site key would echo as its bare code. Set by the render choke point, honoured here.
|
||||
*/
|
||||
public static final String SITE_MESSAGES_ATTRIBUTE = "mx.quest.runway.render.siteMessages";
|
||||
|
||||
private final OperatorMessageSource operatorMessages;
|
||||
private final SiteAwareMessageSource siteMessages;
|
||||
|
||||
public OperatorAwareMessageSource(OperatorMessageSource operatorMessages, SiteAwareMessageSource siteMessages) {
|
||||
this.operatorMessages = operatorMessages;
|
||||
this.siteMessages = siteMessages;
|
||||
}
|
||||
|
||||
private MessageSource current() {
|
||||
return isOperatorRequest() ? operatorMessages : siteMessages;
|
||||
}
|
||||
|
||||
private static boolean isOperatorRequest() {
|
||||
if (!(RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attributes)) {
|
||||
return false;
|
||||
}
|
||||
HttpServletRequest request = attributes.getRequest();
|
||||
// A tenant-page render served under a console path (editor preview / quality) opts into SITE strings.
|
||||
if (Boolean.TRUE.equals(request.getAttribute(SITE_MESSAGES_ATTRIBUTE))) {
|
||||
return false;
|
||||
}
|
||||
return OperatorPaths.isOperatorRequest(RequestPaths.normalized(request));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage(String code, Object[] args, String defaultMessage, Locale locale) {
|
||||
return current().getMessage(code, args, defaultMessage, locale);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException {
|
||||
return current().getMessage(code, args, locale);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException {
|
||||
return current().getMessage(resolvable, locale);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.LocaleResolver;
|
||||
|
||||
/**
|
||||
* Wires the operator console's language switching: binds {@link OperatorProperties} and registers the
|
||||
* {@link OperatorLocaleResolver} as the DispatcherServlet's {@code localeResolver} (the bean NAME is
|
||||
* load-bearing — it displaces Spring Boot's default {@code AcceptHeaderLocaleResolver}). Only operator
|
||||
* requests are affected; public tenant sites keep their own locale pipeline.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableConfigurationProperties(OperatorProperties.class)
|
||||
public class OperatorI18nConfig {
|
||||
|
||||
/** Must be named {@code localeResolver}: the DispatcherServlet resolves the locale via this exact bean name. */
|
||||
@Bean
|
||||
public LocaleResolver localeResolver(OperatorProperties operator) {
|
||||
return new OperatorLocaleResolver(operator.getUiLanguages(), operator.getDefaultLanguage());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.util.Locale;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.servlet.LocaleResolver;
|
||||
|
||||
/**
|
||||
* The operator-console language switch endpoint ({@code GET /__ui-lang?lang=xx&to=/path}). It sets the operator
|
||||
* UI-language cookie (via the {@link OperatorLocaleResolver}) and redirects back to the page the operator was on.
|
||||
*
|
||||
* <p>GET is deliberate — switching the display language is not a sensitive state change, carries no CSRF token,
|
||||
* and must work from any console page. The {@code lang} is honored only if it is one of the offered
|
||||
* {@link OperatorProperties#getUiLanguages() UI languages} (an unknown value is ignored, not an error). The
|
||||
* {@code to} target is guarded to a same-origin local path, so the parameter can never drive an open redirect.
|
||||
*/
|
||||
@Controller
|
||||
public class OperatorLocaleController {
|
||||
|
||||
private final OperatorProperties operator;
|
||||
private final LocaleResolver localeResolver;
|
||||
|
||||
public OperatorLocaleController(OperatorProperties operator, LocaleResolver localeResolver) {
|
||||
this.operator = operator;
|
||||
this.localeResolver = localeResolver;
|
||||
}
|
||||
|
||||
@GetMapping("/__ui-lang")
|
||||
public String switchLanguage(@RequestParam String lang,
|
||||
@RequestParam(required = false) String to,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
if (operator.getUiLanguages().contains(lang)) {
|
||||
localeResolver.setLocale(request, response, Locale.forLanguageTag(lang));
|
||||
}
|
||||
return "redirect:" + safeLocalPath(to);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduces {@code to} to a safe same-origin path, defaulting to the app console. Only a value that begins with
|
||||
* a single {@code /} and contains no scheme, backslash, space or control character is honored — so a crafted
|
||||
* {@code ?to=} can never redirect off-site or inject a header.
|
||||
*/
|
||||
private static String safeLocalPath(String to) {
|
||||
if (to == null || to.isBlank() || !to.startsWith("/") || to.startsWith("//") || to.contains("://")) {
|
||||
return "/__app";
|
||||
}
|
||||
for (int i = 0; i < to.length(); i++) {
|
||||
char c = to.charAt(i);
|
||||
if (c < 0x20 || c == '\\' || c == ' ') {
|
||||
return "/__app";
|
||||
}
|
||||
}
|
||||
return to;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import mx.quest.runway.web.RequestPaths;
|
||||
import org.springframework.web.servlet.LocaleResolver;
|
||||
|
||||
/**
|
||||
* The DispatcherServlet's {@code localeResolver}, made <b>realm-aware</b> so the operator console gets a
|
||||
* switchable, remembered UI language WITHOUT disturbing the public tenant sites.
|
||||
*
|
||||
* <ul>
|
||||
* <li><b>Operator requests</b> ({@link OperatorPaths#isOperatorRequest} — the {@code /__app} and
|
||||
* {@code /__admin} consoles, their logins, and the {@code /__ui-lang} switch endpoint): the language is a
|
||||
* cookie ({@value #COOKIE}) the operator sets from the topbar switcher, falling back to the best offered
|
||||
* {@code Accept-Language} match, then the configured default. Only offered languages are ever returned.</li>
|
||||
* <li><b>Every other request</b> (the public per-tenant sites): behaves exactly like the default
|
||||
* Accept-Language resolver ({@code request.getLocale()}). The tenant sites run their OWN per-site locale
|
||||
* negotiation downstream; this resolver deliberately does not touch it, keeping the two realms isolated.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Registered under the bean name {@code localeResolver} (the name the DispatcherServlet looks up), which
|
||||
* displaces Spring Boot's default {@code AcceptHeaderLocaleResolver}. Being cookie-backed (no HTTP session
|
||||
* attribute), the operator language never collides across the two realms sharing one session.
|
||||
*/
|
||||
public class OperatorLocaleResolver implements LocaleResolver {
|
||||
|
||||
/** The cookie the operator console remembers its chosen UI language in — never shared with any per-site cookie. */
|
||||
static final String COOKIE = "runway-op-lang";
|
||||
|
||||
private static final int ONE_YEAR_SECONDS = 365 * 24 * 60 * 60;
|
||||
|
||||
private final List<Locale> supported;
|
||||
private final Locale fallback;
|
||||
|
||||
/**
|
||||
* @param uiLanguages the offered BCP-47 language codes (order irrelevant here); an empty list disables
|
||||
* switching (only the fallback and Accept-Language remain, matching nothing offered)
|
||||
* @param defaultLanguage the fallback language code when the browser requests none offered
|
||||
*/
|
||||
public OperatorLocaleResolver(List<String> uiLanguages, String defaultLanguage) {
|
||||
this.supported = uiLanguages.stream().map(Locale::forLanguageTag).toList();
|
||||
this.fallback = Locale.forLanguageTag(defaultLanguage);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Locale resolveLocale(HttpServletRequest request) {
|
||||
if (!OperatorPaths.isOperatorRequest(RequestPaths.normalized(request))) {
|
||||
// Public tenant-site request: preserve the default Accept-Language behavior untouched.
|
||||
return request.getLocale();
|
||||
}
|
||||
Locale fromCookie = fromCookie(request);
|
||||
if (fromCookie != null) {
|
||||
return fromCookie;
|
||||
}
|
||||
Locale fromAccept = bestAccept(request);
|
||||
return fromAccept != null ? fromAccept : fallback;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
|
||||
Cookie cookie = new Cookie(COOKIE, locale == null ? "" : locale.toLanguageTag());
|
||||
cookie.setPath("/");
|
||||
cookie.setHttpOnly(true);
|
||||
cookie.setSecure(request.isSecure());
|
||||
cookie.setMaxAge(locale == null ? 0 : ONE_YEAR_SECONDS);
|
||||
response.addCookie(cookie);
|
||||
}
|
||||
|
||||
/** The offered locale named by the cookie, or {@code null} if there is no cookie or it names an unoffered one. */
|
||||
private Locale fromCookie(HttpServletRequest request) {
|
||||
if (request.getCookies() == null) {
|
||||
return null;
|
||||
}
|
||||
for (Cookie c : request.getCookies()) {
|
||||
if (COOKIE.equals(c.getName())) {
|
||||
return match(Locale.forLanguageTag(c.getValue()));
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The best offered locale by browser preference order, or {@code null} if none is offered. */
|
||||
private Locale bestAccept(HttpServletRequest request) {
|
||||
Enumeration<Locale> requested = request.getLocales();
|
||||
while (requested.hasMoreElements()) {
|
||||
Locale hit = match(requested.nextElement());
|
||||
if (hit != null) {
|
||||
return hit;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The offered locale whose language equals {@code candidate}'s, or {@code null} — so only offered ones return. */
|
||||
private Locale match(Locale candidate) {
|
||||
if (candidate == null) {
|
||||
return null;
|
||||
}
|
||||
for (Locale s : supported) {
|
||||
if (s.getLanguage().equals(candidate.getLanguage())) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import mx.quest.runway.i18n.I18nProperties;
|
||||
import mx.quest.runway.plugin.LoadedPlugin;
|
||||
import mx.quest.runway.plugin.PluginRuntime;
|
||||
import mx.quest.runway.storage.StorageLayout;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* The operator console's own i18n bundle — entirely separate from the per-tenant {@code SiteAwareMessageSource},
|
||||
* so an operator request never resolves a {@code #{}} key against a tenant's site strings. The classpath bundle
|
||||
* ({@code i18n/operator-messages[_xx].properties}, shipped in the jar) is the default; an external override
|
||||
* ({@code external/i18n/operator-messages[_xx].properties}) takes precedence, so an operator can re-translate
|
||||
* or correct the console copy without a rebuild. Reloadable on the same cadence as tenant i18n
|
||||
* ({@code runway.i18n.cache-seconds}).
|
||||
*
|
||||
* <p><b>Plugin bundles.</b> Each loaded plugin that ships an {@code i18n/messages[_xx].properties} bundle in its
|
||||
* install folder contributes it to the console — appended <b>last</b>, so a plugin may <b>add</b> keys (its own
|
||||
* permission / settings / menu / card labels, rendered by the generic console via {@code #{...}}) but can
|
||||
* <b>never override</b> a core key (basenames are consulted in order; the first match wins, and core comes
|
||||
* first). Two plugins declaring the same key resolve deterministically by load order. This is the i18n arm of
|
||||
* the plugin resource seams (alongside {@code /__plugin/<id>/static/**} and the {@code __plugin__/<id>}
|
||||
* templates): a plugin's strings live <b>with the plugin</b>, never in core.
|
||||
*/
|
||||
@Component
|
||||
public class OperatorMessageSource extends ReloadableResourceBundleMessageSource {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(OperatorMessageSource.class);
|
||||
|
||||
public OperatorMessageSource(StorageLayout layout, I18nProperties properties,
|
||||
ObjectProvider<PluginRuntime> pluginRuntime) {
|
||||
List<String> basenames = new ArrayList<>();
|
||||
// CORE first (the first basename that has a code wins): external override, then the classpath default.
|
||||
basenames.add("file:" + layout.external().resolve("i18n").resolve("operator-messages"));
|
||||
basenames.add("classpath:i18n/operator-messages");
|
||||
// PLUGINS last — add-only, never overriding core.
|
||||
appendPluginBundles(basenames, pluginRuntime);
|
||||
|
||||
setBasenames(basenames.toArray(String[]::new));
|
||||
setDefaultEncoding("UTF-8");
|
||||
setCacheMillis(Math.max(0, properties.getCacheSeconds()) * 1000L);
|
||||
setFallbackToSystemLocale(false); // an unset locale falls back to the default bundle, not the host's
|
||||
setUseCodeAsDefaultMessage(true); // a missing key renders the code, never throws mid-render
|
||||
}
|
||||
|
||||
private static void appendPluginBundles(List<String> basenames, ObjectProvider<PluginRuntime> pluginRuntime) {
|
||||
PluginRuntime runtime = pluginRuntime.getIfAvailable(
|
||||
() -> PluginRuntime.empty(OperatorMessageSource.class.getClassLoader()));
|
||||
int added = 0;
|
||||
for (LoadedPlugin plugin : runtime.loaded()) {
|
||||
Path i18nDir = plugin.installDir().resolve("i18n");
|
||||
if (Files.isDirectory(i18nDir)) {
|
||||
basenames.add("file:" + i18nDir.resolve("messages"));
|
||||
added++;
|
||||
}
|
||||
}
|
||||
if (added > 0) {
|
||||
log.info("appended {} plugin i18n bundle(s) to the operator message source", added);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
|
||||
/**
|
||||
* Supplies the model attributes the {@code op-layout} shell needs on <b>every</b> kernel operator page, so each
|
||||
* controller only sets its {@code contentTemplate} + {@code pageTitleKey}. Scoped to the {@code console}
|
||||
* package, so it never touches the tenant {@code PageController} — and, deliberately, so it does <b>not</b> fire
|
||||
* for a plugin's operator controller (which lives outside {@code mx.quest.runway.console}). A plugin that renders
|
||||
* a full operator screen annotates its controller with the SPI's {@code @ConsoleScreen}, which
|
||||
* {@link ConsoleScreenAdvice} serves from the same {@link OperatorShellModel} bean.
|
||||
*
|
||||
* <p>All population logic lives in {@link OperatorShellModel}; this advice is only the kernel-scoped trigger that
|
||||
* delegates to it.
|
||||
*/
|
||||
@ControllerAdvice(basePackages = "mx.quest.runway.console")
|
||||
public class OperatorModelAdvice {
|
||||
|
||||
private final OperatorShellModel shellModel;
|
||||
|
||||
public OperatorModelAdvice(OperatorShellModel shellModel) {
|
||||
this.shellModel = shellModel;
|
||||
}
|
||||
|
||||
@ModelAttribute
|
||||
public void shellModel(Model model, HttpServletRequest request, Authentication authentication) {
|
||||
shellModel.populate(model, request, authentication);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import mx.quest.runway.web.AppRealmPaths;
|
||||
import mx.quest.runway.web.TenantConsolePaths;
|
||||
|
||||
/**
|
||||
* The single predicate for "is this request an <b>operator-console</b> request" — the two operator realms'
|
||||
* surfaces ({@code /__app/**} + {@code /app/login|logout}, and {@code /__admin/**} + {@code /login|logout}), their
|
||||
* login endpoints, and their pre-auth <b>password-recovery</b> pages ({@code /app/forgot-password|reset} and the
|
||||
* reserved bare {@code /forgot-password|reset}). It decides i18n routing ({@link OperatorAwareMessageSource}):
|
||||
* every operator-rendered page resolves {@code #{}} against the operator bundle, <b>never</b> a bound tenant's
|
||||
* site strings — even on {@code /__admin}, where a tenant <em>is</em> the subject but the chrome is still platform
|
||||
* copy. Omitting the recovery pages here made them resolve against the site bundle, rendering their labels as
|
||||
* {@code ??op.recovery.*??}.
|
||||
*
|
||||
* <p>Exact matches (not loose {@code startsWith}) for the bare, login and recovery paths, matching the realm
|
||||
* chains, so a public tenant path can never be mistaken for operator chrome. The recovery paths are reserved
|
||||
* platform routes (like {@code /login}); a tenant page can no more sit at {@code /forgot-password} than at
|
||||
* {@code /login}.
|
||||
*/
|
||||
public final class OperatorPaths {
|
||||
|
||||
private OperatorPaths() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the decoded, context-stripped {@code path} ({@link mx.quest.runway.web.RequestPaths#normalized}) is
|
||||
* served by the operator console: the application console ({@link AppRealmPaths#isOperatorConsole}) or a page of
|
||||
* a tenant console ({@link TenantConsolePaths#isConsolePage}). Built from those two, so the sets cannot drift.
|
||||
*/
|
||||
public static boolean isOperatorRequest(String path) {
|
||||
return AppRealmPaths.isOperatorConsole(path) || TenantConsolePaths.isConsolePage(path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.util.List;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
/**
|
||||
* Operator-console UI settings, bound from {@code runway.operator.*}. Today this is the set of UI languages the
|
||||
* console's language switcher offers and the fallback language. It is a <b>platform</b> concern (the operator
|
||||
* console is platform chrome), not a per-tenant one.
|
||||
*/
|
||||
@ConfigurationProperties("runway.operator")
|
||||
public class OperatorProperties {
|
||||
|
||||
/**
|
||||
* The UI languages the operator console offers in its language switcher, as BCP-47 language codes, in the
|
||||
* order shown. Each needs a matching {@code operator-messages[_xx].properties} bundle and an
|
||||
* {@code op.lang.<code>} label. Default: {@code [en, es]} (Runway ships both operator bundles).
|
||||
*/
|
||||
private List<String> uiLanguages = List.of("en", "es");
|
||||
|
||||
/** The fallback UI language when the browser requests none of the offered ones. Default: {@code en}. */
|
||||
private String defaultLanguage = "en";
|
||||
|
||||
public List<String> getUiLanguages() {
|
||||
return uiLanguages;
|
||||
}
|
||||
|
||||
public void setUiLanguages(List<String> uiLanguages) {
|
||||
this.uiLanguages = uiLanguages;
|
||||
}
|
||||
|
||||
public String getDefaultLanguage() {
|
||||
return defaultLanguage;
|
||||
}
|
||||
|
||||
public void setDefaultLanguage(String defaultLanguage) {
|
||||
this.defaultLanguage = defaultLanguage;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.crypto.SecretCipher;
|
||||
import mx.quest.runway.mail.PlatformMailer;
|
||||
import mx.quest.runway.security.RunwayUserDetails;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import mx.quest.runway.web.AppRealmPaths;
|
||||
import mx.quest.runway.web.RequestPaths;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.boot.info.BuildProperties;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.ui.Model;
|
||||
|
||||
/**
|
||||
* Populates the model attributes the {@code op-layout} shell (topbar / nav / locale switcher / footer) needs on
|
||||
* <b>every</b> operator page, so a controller only has to set its {@code contentTemplate} + {@code pageTitleKey}.
|
||||
*
|
||||
* <p>This is the kernel seam for the operator chrome. Its callers:
|
||||
* <ul>
|
||||
* <li>{@link OperatorModelAdvice} — a {@code @ControllerAdvice} scoped to {@code mx.quest.runway.console} that
|
||||
* fires for every <b>kernel</b> console controller and delegates here.</li>
|
||||
* <li>{@link ConsoleScreenAdvice} — fires for every controller annotated with the SPI's
|
||||
* {@link mx.quest.runway.spi.service.ConsoleScreen}: how a <b>plugin</b> renders a full operator screen inside
|
||||
* {@code op-layout} (SPI 0.6.0). The plugin returns {@code "operator/op-layout"} with its own
|
||||
* {@code contentTemplate} (a {@code __plugin__/<id>/<name>} template — {@link PluginTemplateResolver}) and
|
||||
* needs no host class.</li>
|
||||
* </ul>
|
||||
* This class is kernel-internal: no plugin may inject it (a plugin that links a host class is refused from SPI
|
||||
* 1.0.0). The essential plugin, too, reaches the shell through {@code @ConsoleScreen}.
|
||||
*
|
||||
* <p>Extracting this from {@code OperatorModelAdvice} is behaviour-preserving: the advice now delegates and the
|
||||
* exact same attributes are set, so kernel screens are unaffected.
|
||||
*/
|
||||
@Component
|
||||
public class OperatorShellModel {
|
||||
|
||||
private final MenuRegistry menuRegistry;
|
||||
private final SiteResolver siteResolver;
|
||||
private final OperatorProperties operator;
|
||||
private final SecretCipher cipher;
|
||||
private final PlatformMailer mailer;
|
||||
|
||||
/**
|
||||
* The cache-busting token appended to every {@code /__assets/**} reference ({@code ?v=…}) so a redeploy is
|
||||
* served from a fresh URL and the 1-day asset cache is bypassed — computed ONCE per process, never bumped by
|
||||
* hand, and identical to the {@link AssetVersion} bean's (both come from {@link AssetVersion#of}): the build
|
||||
* timestamp when build-info is present (stable across restarts of one jar, distinct per release), else the
|
||||
* process start time (dev / no build-info: distinct per restart).
|
||||
*/
|
||||
private final String assetVersion;
|
||||
/** The running instance version for the console footer — from build-info, else {@code "dev"} (matches the
|
||||
* About screen's {@code RuntimeInfoService.version()} primary path; a dev/IDE run with no build-info shows
|
||||
* {@code "dev"} in both). */
|
||||
private final String appVersion;
|
||||
|
||||
/** Which kernel menu entries the operator may see; {@code null} (the legacy constructor) shows them all. */
|
||||
private final ConsoleNavigation navigation;
|
||||
|
||||
/** Without kernel-menu filtering (every kernel entry shown) — kept for callers built before it existed. */
|
||||
public OperatorShellModel(MenuRegistry menuRegistry, SiteResolver siteResolver, OperatorProperties operator,
|
||||
SecretCipher cipher, PlatformMailer mailer,
|
||||
ObjectProvider<BuildProperties> buildProperties) {
|
||||
this(menuRegistry, siteResolver, operator, cipher, mailer, buildProperties, null);
|
||||
}
|
||||
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
public OperatorShellModel(MenuRegistry menuRegistry, SiteResolver siteResolver, OperatorProperties operator,
|
||||
SecretCipher cipher, PlatformMailer mailer,
|
||||
ObjectProvider<BuildProperties> buildProperties, ConsoleNavigation navigation) {
|
||||
this.navigation = navigation;
|
||||
this.menuRegistry = menuRegistry;
|
||||
this.siteResolver = siteResolver;
|
||||
this.operator = operator;
|
||||
this.cipher = cipher;
|
||||
this.mailer = mailer;
|
||||
BuildProperties bp = buildProperties.getIfAvailable();
|
||||
this.assetVersion = AssetVersion.of(bp); // the same token the AssetVersion bean holds
|
||||
this.appVersion = (bp != null && bp.getVersion() != null && !bp.getVersion().isBlank())
|
||||
? bp.getVersion()
|
||||
: "dev";
|
||||
}
|
||||
|
||||
/** The asset cache-busting token this shell puts in the model as {@code assetVersion}. */
|
||||
public String assetVersion() {
|
||||
return assetVersion;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds every {@code op-layout} shell attribute to {@code model}, choosing the realm chrome from the request
|
||||
* path ({@link AppRealmPaths}: the application realm gets the app topbar/menu, everything else — the
|
||||
* {@code /__admin} tenant console — the admin topbar/menu). Idempotent and side-effect-free beyond the model;
|
||||
* safe to call from either advice.
|
||||
*
|
||||
* <p>The set is exactly what {@code op-layout.th.xml} reads: {@code currentPath}, {@code appPath}/
|
||||
* {@code adminPath} (the realm-prefix-stripped path used for active-nav, kept split to dodge the
|
||||
* {@code __…__} preprocessing trap), {@code operatorRealm}, {@code topbarFragment},
|
||||
* {@code principalName}, {@code appName}, {@code appVersion}, {@code tenantSiteId}, {@code titleSuffix}
|
||||
* (the browser-tab title suffix: the site id on the tenant console, the platform name on the app realm),
|
||||
* {@code assetVersion}, {@code operatorLanguages}, {@code uiLocale}, {@code pluginMenu}, {@code pluginSettings},
|
||||
* {@code pluginSettingsMenu}, {@code pluginActivityMenu}, and {@code nav} — which kernel menu entries and
|
||||
* dropdown groups the operator may see ({@link ConsoleNavigation}).
|
||||
*
|
||||
* @param model the view model to populate (never {@code null})
|
||||
* @param request the current request, used to classify the realm and the active-nav path
|
||||
* @param authentication the signed-in operator (may be {@code null} on an unauthenticated shell render)
|
||||
*/
|
||||
public void populate(Model model, HttpServletRequest request, Authentication authentication) {
|
||||
// The decoded path the page was routed on (RequestPaths): /%5F%5Fapp/sites is the application console, with
|
||||
// its own topbar and active entry, exactly like /__app/sites.
|
||||
String path = RequestPaths.normalized(request);
|
||||
boolean appRealm = AppRealmPaths.isAppRealm(path);
|
||||
Realm realm = appRealm ? Realm.APPLICATION : Realm.TENANT;
|
||||
String tenancyId = appRealm ? null : siteResolver.current().map(site -> site.id()).orElse(null);
|
||||
RunwayUserDetails principal = authentication != null
|
||||
&& authentication.getPrincipal() instanceof RunwayUserDetails details ? details : null;
|
||||
|
||||
// The language switcher returns to the page as the browser addressed it (still encoded), not the decoded path.
|
||||
model.addAttribute("currentPath", request.getRequestURI());
|
||||
// The tenant path with the "/__admin" prefix stripped (e.g. "/pages", "" for the dashboard). The grouped
|
||||
// admin topbar tests active-nav against THIS, never the full path: an expression that names two or more
|
||||
// "/__admin/…" literals would otherwise pair their leading "__" as Thymeleaf's __…__ preprocessing
|
||||
// delimiters and fail to parse. Null on the application realm.
|
||||
model.addAttribute("adminPath",
|
||||
(!appRealm && path.startsWith("/__admin")) ? path.substring("/__admin".length()) : path);
|
||||
// The mirror for the application realm's grouped topbar: the path with "/__app" stripped (e.g. "/sites",
|
||||
// "" for the dashboard). Same reason as adminPath — two "/__app/…" literals in one active-nav expression
|
||||
// would otherwise pair their leading "__" as Thymeleaf __…__ preprocessing.
|
||||
model.addAttribute("appPath",
|
||||
(appRealm && path.startsWith("/__app")) ? path.substring("/__app".length()) : path);
|
||||
model.addAttribute("operatorRealm", appRealm ? "application" : "tenant");
|
||||
model.addAttribute("topbarFragment",
|
||||
appRealm ? "operator/fragments/app-topbar" : "operator/fragments/admin-topbar");
|
||||
model.addAttribute("principalName", authentication == null ? "" : authentication.getName());
|
||||
String appName = "Runway";
|
||||
model.addAttribute("appName", appName);
|
||||
model.addAttribute("appVersion", appVersion);
|
||||
// The bound tenant's id, for the admin topbar's "<id> site management" badge (null on the app realm).
|
||||
model.addAttribute("tenantSiteId", tenancyId);
|
||||
// The browser-tab title suffix (op-layout renders "<page> · <suffix>"). On the TENANT console it is the
|
||||
// bound site id, so an operator with several sites' consoles open in separate tabs can tell them apart at
|
||||
// a glance ("Backups · northbeam" vs "Backups · nocturne"); on the APPLICATION realm it stays the platform
|
||||
// name. Falls back to the platform name if a tenant page ever renders without a resolved site.
|
||||
model.addAttribute("titleSuffix", (!appRealm && tenancyId != null) ? tenancyId : appName);
|
||||
model.addAttribute("assetVersion", assetVersion);
|
||||
// The topbar language switcher: the offered languages and the one currently in force (the language code
|
||||
// only, e.g. "en"/"es", so it keys the op.lang.* labels and the active highlight regardless of country).
|
||||
model.addAttribute("operatorLanguages", operator.getUiLanguages());
|
||||
model.addAttribute("uiLocale", LocaleContextHolder.getLocale().getLanguage());
|
||||
// Plugin-contributed TOP-LEVEL menu links for this realm/principal (region: menu; empty when none).
|
||||
model.addAttribute("pluginMenu", menuRegistry.menuFor(realm, principal, tenancyId));
|
||||
// Plugin settings entries for the console's Settings dropdown, generated from each plugin's settings SCHEMA
|
||||
// and linking to the kernel's generic settings form (empty when no plugin declares a schema).
|
||||
List<?> pluginSettings = menuRegistry.settingsFor(realm, principal, tenancyId);
|
||||
model.addAttribute("pluginSettings", pluginSettings);
|
||||
// Plugin screens a plugin targets at a topbar GROUP via region targeting — its OWN console
|
||||
// screen rendered under Settings or Activity instead of a top-level item (empty unless a plugin declares
|
||||
// one). Distinct from pluginSettings: those are the auto-generated generic-form links; these are the
|
||||
// plugin's own custom screens (e.g. the essential protection plugin's login-protection + DoS screens).
|
||||
List<?> pluginSettingsMenu = menuRegistry.menuFor(realm, "settings", principal, tenancyId);
|
||||
List<?> pluginActivityMenu = menuRegistry.menuFor(realm, "activity", principal, tenancyId);
|
||||
model.addAttribute("pluginSettingsMenu", pluginSettingsMenu);
|
||||
model.addAttribute("pluginActivityMenu", pluginActivityMenu);
|
||||
// Kernel menu entries the operator may open (the same gate as each route), plus whether each dropdown
|
||||
// group has anything left to show once the plugin entries targeted at it are counted. The topbar reads
|
||||
// nav['<key>'] / nav['grp.<group>']; absent (legacy constructor) means "show everything".
|
||||
if (navigation != null) {
|
||||
Set<String> pluginGroups = new HashSet<>();
|
||||
if (!pluginSettings.isEmpty() || !pluginSettingsMenu.isEmpty()) {
|
||||
pluginGroups.add("settings");
|
||||
}
|
||||
if (!pluginActivityMenu.isEmpty()) {
|
||||
pluginGroups.add("activity");
|
||||
}
|
||||
model.addAttribute("nav", navigation.visibility(realm, authentication, tenancyId, pluginGroups));
|
||||
}
|
||||
// Persistent platform-misconfiguration warnings, surfaced on EVERY application-realm console page (the
|
||||
// designated messages area) so the application operator — the one who can fix them — notices promptly:
|
||||
// • no secret-encryption key ⇒ NO secret (SMTP/CAPTCHA/plugin) setting can be stored at all;
|
||||
// • no platform mail account ⇒ password recovery cannot send a link.
|
||||
// App realm only: a tenant manager can act on neither (both are platform config the operator owns).
|
||||
model.addAttribute("secretKeyMissing", appRealm && !cipher.isAvailable());
|
||||
model.addAttribute("smtpMissing", appRealm && !mailer.isConfigured());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.plugin.RunningPlugins;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.thymeleaf.templatemode.TemplateMode;
|
||||
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
|
||||
|
||||
/**
|
||||
* Resolves the <b>operator-console</b> templates, which — unlike tenant pages — are <b>kernel-owned</b> and
|
||||
* live on the classpath ({@code templates/operator/**}), never in the tenant-editable external tree. This is a
|
||||
* conscious, documented divergence from "templates live in external": that rule governs <em>tenant</em>
|
||||
* presentation; operator chrome is platform code and must not be operator-editable (nor able to be shadowed by
|
||||
* a stale on-disk copy after an upgrade).
|
||||
*
|
||||
* <p>Like the tenant resolver it uses <b>decoupled logic</b> (zero Thymeleaf in the {@code .html}; the
|
||||
* {@code th:*} lives in a sibling {@code .th.xml}) and keeps the cache <b>on</b> (dev/production parity). It is
|
||||
* ordered <b>after</b> {@link mx.quest.runway.web.SiteTemplateResolver} (order 1) and only claims the
|
||||
* {@code operator/*} name space (so every other name falls through to Boot's default classpath resolver); a
|
||||
* view name like {@code operator/op-layout} maps to {@code classpath:/templates/operator/op-layout.html}.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class OperatorTemplatingConfig {
|
||||
|
||||
/** The classpath resolver for {@code operator/*} templates (decoupled logic, cache on, order 2). */
|
||||
@Bean
|
||||
public ClassLoaderTemplateResolver operatorTemplateResolver() {
|
||||
ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
|
||||
resolver.setPrefix("templates/");
|
||||
resolver.setSuffix(".html");
|
||||
resolver.setResolvablePatterns(Set.of("operator/*"));
|
||||
resolver.setTemplateMode(TemplateMode.HTML);
|
||||
resolver.setCharacterEncoding("UTF-8");
|
||||
resolver.setUseDecoupledLogic(true);
|
||||
resolver.setCacheable(true);
|
||||
resolver.setOrder(2);
|
||||
return resolver;
|
||||
}
|
||||
|
||||
/** Resolves {@code __plugin__/<id>/<name>} to a loaded plugin's own {@code templates/} (dashboard cards,
|
||||
* admin fragments) — ordered 3, after the site and operator resolvers. */
|
||||
@Bean
|
||||
public PluginTemplateResolver pluginTemplateResolver(RunningPlugins runningPlugins) {
|
||||
return new PluginTemplateResolver(runningPlugins);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.page.Page;
|
||||
|
||||
/**
|
||||
* The page-editor's form-backing command. Spring binds the scalar fields plus the per-locale maps (form
|
||||
* inputs named {@code title[en]}, {@code description[es]}, {@code localizedPath[fr]}) and the multi-valued
|
||||
* {@code locales} checkboxes. {@link #toPage(String, boolean)} assembles a {@link Page} from it, dropping
|
||||
* blank per-locale entries (an empty title input must not persist an empty title) — the {@code Page}
|
||||
* constructor then sanitizes the localized paths and normalizes the rest.
|
||||
*
|
||||
* <p>The {@code draft} flag is <b>not</b> a form field: editing content is {@code EDIT_PAGES}, but changing a
|
||||
* page's published/draft visibility is {@code DISABLE_PAGES} (the disable/enable actions), so a save
|
||||
* preserves the page's current draft state — the caller passes it in.
|
||||
*
|
||||
* <p>Per-page template {@code params} bind as two <b>parallel arrays</b> ({@code paramKey[]} /
|
||||
* {@code paramValue[]}) rather than an indexed map: the key of a param row is itself editable (unlike the
|
||||
* fixed {@code title[en]} locale keys), so a fixed-key input name could not carry a renamed or newly-added
|
||||
* key. {@link #toPage(String, boolean)} zips the two lists positionally, trims keys, drops blank-keyed rows,
|
||||
* and keeps the last value on a duplicate key.
|
||||
*/
|
||||
public class PageForm {
|
||||
|
||||
private String path = "";
|
||||
private String template = "";
|
||||
private String activeNav = "";
|
||||
private String author = "";
|
||||
private String publishedAt = "";
|
||||
private String canonical = "";
|
||||
private String cacheControl = "";
|
||||
private boolean noindex;
|
||||
private boolean nosnippet;
|
||||
private boolean gone;
|
||||
private String html = "";
|
||||
private String thxml = "";
|
||||
private Map<String, String> title = new LinkedHashMap<>();
|
||||
private Map<String, String> description = new LinkedHashMap<>();
|
||||
private Map<String, String> localizedPath = new LinkedHashMap<>();
|
||||
private List<String> locales = new ArrayList<>();
|
||||
private List<String> paramKey = new ArrayList<>();
|
||||
private List<String> paramValue = new ArrayList<>();
|
||||
|
||||
/** Builds the {@link Page} to persist: the given slug + draft state, this form's metadata, blanks dropped. */
|
||||
public Page toPage(String slug, boolean draft) {
|
||||
String cleanPath = (path == null || path.isBlank()) ? null : path.trim();
|
||||
String cleanTemplate = (template == null || template.isBlank()) ? null : template.trim();
|
||||
List<Locale> localeList = locales.stream()
|
||||
.filter(code -> code != null && !code.isBlank())
|
||||
.map(Locale::forLanguageTag)
|
||||
.toList();
|
||||
// The Page constructor normalizes a blank canonical / cacheControl to null (no override); noindex is a
|
||||
// plain flag (an unchecked checkbox binds to false — the site default: indexable). It also sanitizes
|
||||
// the zipped params map (trims keys, drops blank keys), so this only needs to pair the two arrays.
|
||||
return new Page(slug, cleanPath, nonBlank(localizedPath), localeList,
|
||||
nonBlank(title), nonBlank(description),
|
||||
activeNav == null ? "" : activeNav.trim(), cleanTemplate, draft, noindex, canonical, cacheControl,
|
||||
zipParams(), author, parsePublishedAt(), nosnippet, gone);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the {@code publishedAt} field (an HTML {@code <input type="date">}, so {@code yyyy-MM-dd}) into an
|
||||
* instant at <b>midnight UTC</b> on that day.
|
||||
*
|
||||
* <p>A date rather than a timestamp because publication date is an editorial fact at day granularity — what
|
||||
* a byline shows and what {@code datePublished} means to a consumer. Fixing a typo at 4pm must not move it.
|
||||
*
|
||||
* <p>An unparseable value yields {@code null} (no date) rather than throwing: this field is optional
|
||||
* metadata, and a malformed date must never block saving a page's content. A wrong-but-parseable date is the
|
||||
* author's to correct; an absent one asserts nothing, which is the safe failure.
|
||||
*/
|
||||
private java.time.Instant parsePublishedAt() {
|
||||
if (publishedAt == null || publishedAt.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return java.time.LocalDate.parse(publishedAt.trim())
|
||||
.atStartOfDay(java.time.ZoneOffset.UTC).toInstant();
|
||||
} catch (java.time.format.DateTimeParseException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pairs the {@code paramKey[]} / {@code paramValue[]} arrays positionally into a map: a row with a
|
||||
* blank/null key is dropped (its value cannot be addressed), a missing value at an index becomes empty,
|
||||
* and the last value wins on a duplicate key. The {@link Page} constructor trims and re-validates keys,
|
||||
* so this stays deliberately thin.
|
||||
*/
|
||||
private Map<String, String> zipParams() {
|
||||
Map<String, String> params = new LinkedHashMap<>();
|
||||
for (int i = 0; i < paramKey.size(); i++) {
|
||||
String key = paramKey.get(i);
|
||||
if (key == null || key.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
String value = i < paramValue.size() && paramValue.get(i) != null ? paramValue.get(i) : "";
|
||||
params.put(key.trim(), value);
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
/** A copy of {@code raw} with blank (or null) values removed, keys trimmed of empties. */
|
||||
private static Map<String, String> nonBlank(Map<String, String> raw) {
|
||||
Map<String, String> clean = new LinkedHashMap<>();
|
||||
raw.forEach((key, value) -> {
|
||||
if (key != null && value != null && !value.isBlank()) {
|
||||
clean.put(key, value.trim());
|
||||
}
|
||||
});
|
||||
return clean;
|
||||
}
|
||||
|
||||
public String getPath() {
|
||||
return path;
|
||||
}
|
||||
|
||||
public void setPath(String path) {
|
||||
this.path = path;
|
||||
}
|
||||
|
||||
public String getTemplate() {
|
||||
return template;
|
||||
}
|
||||
|
||||
public void setTemplate(String template) {
|
||||
this.template = template;
|
||||
}
|
||||
|
||||
public String getActiveNav() {
|
||||
return activeNav;
|
||||
}
|
||||
|
||||
public void setActiveNav(String activeNav) {
|
||||
this.activeNav = activeNav;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public void setAuthor(String author) {
|
||||
this.author = author;
|
||||
}
|
||||
|
||||
public String getPublishedAt() {
|
||||
return publishedAt;
|
||||
}
|
||||
|
||||
public void setPublishedAt(String publishedAt) {
|
||||
this.publishedAt = publishedAt;
|
||||
}
|
||||
|
||||
public String getCanonical() {
|
||||
return canonical;
|
||||
}
|
||||
|
||||
public void setCanonical(String canonical) {
|
||||
this.canonical = canonical;
|
||||
}
|
||||
|
||||
public String getCacheControl() {
|
||||
return cacheControl;
|
||||
}
|
||||
|
||||
public void setCacheControl(String cacheControl) {
|
||||
this.cacheControl = cacheControl;
|
||||
}
|
||||
|
||||
public boolean isNosnippet() {
|
||||
return nosnippet;
|
||||
}
|
||||
|
||||
public void setNosnippet(boolean nosnippet) {
|
||||
this.nosnippet = nosnippet;
|
||||
}
|
||||
|
||||
public boolean isGone() {
|
||||
return gone;
|
||||
}
|
||||
|
||||
public void setGone(boolean gone) {
|
||||
this.gone = gone;
|
||||
}
|
||||
|
||||
public boolean isNoindex() {
|
||||
return noindex;
|
||||
}
|
||||
|
||||
public void setNoindex(boolean noindex) {
|
||||
this.noindex = noindex;
|
||||
}
|
||||
|
||||
public String getHtml() {
|
||||
return html;
|
||||
}
|
||||
|
||||
public void setHtml(String html) {
|
||||
this.html = html;
|
||||
}
|
||||
|
||||
public String getThxml() {
|
||||
return thxml;
|
||||
}
|
||||
|
||||
public void setThxml(String thxml) {
|
||||
this.thxml = thxml;
|
||||
}
|
||||
|
||||
public Map<String, String> getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(Map<String, String> title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public Map<String, String> getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(Map<String, String> description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public Map<String, String> getLocalizedPath() {
|
||||
return localizedPath;
|
||||
}
|
||||
|
||||
public void setLocalizedPath(Map<String, String> localizedPath) {
|
||||
this.localizedPath = localizedPath;
|
||||
}
|
||||
|
||||
public List<String> getLocales() {
|
||||
return locales;
|
||||
}
|
||||
|
||||
public void setLocales(List<String> locales) {
|
||||
this.locales = locales;
|
||||
}
|
||||
|
||||
public List<String> getParamKey() {
|
||||
return paramKey;
|
||||
}
|
||||
|
||||
public void setParamKey(List<String> paramKey) {
|
||||
this.paramKey = paramKey;
|
||||
}
|
||||
|
||||
public List<String> getParamValue() {
|
||||
return paramValue;
|
||||
}
|
||||
|
||||
public void setParamValue(List<String> paramValue) {
|
||||
this.paramValue = paramValue;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import mx.quest.runway.plugin.LoadedPlugin;
|
||||
import mx.quest.runway.plugin.PluginRuntime;
|
||||
import mx.quest.runway.storage.PathSafety;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Resolves a grantable-permission <b>key</b> to a human display <b>label</b> for the permissions matrix. The
|
||||
* label key is the permission's declared i18n key — a plugin permission's {@code plugin.yml} {@code label}, or
|
||||
* for a core permission the {@code op.perm.<KEY>} convention — resolved through the operator console's
|
||||
* {@link OperatorMessageSource} (which already carries plugin bundles). An unresolved key falls back to the
|
||||
* raw permission key, so the matrix is always readable even for a plugin that ships no i18n bundle.
|
||||
*
|
||||
* <p>Called directly from the matrix template ({@code ${@permissionLabelResolver.label(p.key(), #locale)}}),
|
||||
* so no controller wiring changes.
|
||||
*/
|
||||
@Component("permissionLabelResolver")
|
||||
public class PermissionLabelResolver {
|
||||
|
||||
private final OperatorMessageSource messages;
|
||||
private final Map<String, String> pluginLabelKeys; // permission key -> plugin.yml label (message) key
|
||||
|
||||
public PermissionLabelResolver(OperatorMessageSource messages, ObjectProvider<PluginRuntime> pluginRuntime) {
|
||||
this.messages = messages;
|
||||
this.pluginLabelKeys = buildPluginLabelKeys(pluginRuntime);
|
||||
}
|
||||
|
||||
private static Map<String, String> buildPluginLabelKeys(ObjectProvider<PluginRuntime> pluginRuntime) {
|
||||
PluginRuntime runtime = pluginRuntime.getIfAvailable(
|
||||
() -> PluginRuntime.empty(PermissionLabelResolver.class.getClassLoader()));
|
||||
Map<String, String> map = new HashMap<>();
|
||||
for (LoadedPlugin plugin : runtime.loaded()) {
|
||||
for (var decl : plugin.descriptor().permissions()) {
|
||||
if (decl.label() != null && !decl.label().isBlank()) {
|
||||
map.put(PathSafety.compoundKey(plugin.id(), decl.id()), decl.label());
|
||||
}
|
||||
}
|
||||
}
|
||||
return Map.copyOf(map);
|
||||
}
|
||||
|
||||
/** The resolved display label for one permission key (falls back to the key itself). */
|
||||
public String label(String permissionKey, Locale locale) {
|
||||
String labelKey = pluginLabelKeys.getOrDefault(permissionKey, "op.perm." + permissionKey);
|
||||
return messages.getMessage(labelKey, null, permissionKey, locale);
|
||||
}
|
||||
|
||||
/** The resolved, comma-joined labels for a role's held permission keys (an em-dash when none). */
|
||||
public String joinHeld(List<String> heldKeys, Locale locale) {
|
||||
if (heldKeys == null || heldKeys.isEmpty()) {
|
||||
return "—";
|
||||
}
|
||||
return heldKeys.stream().map(key -> label(key, locale)).collect(Collectors.joining(", "));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import mx.quest.runway.authz.GrantFile;
|
||||
import mx.quest.runway.authz.GrantStore;
|
||||
import mx.quest.runway.authz.Permission;
|
||||
import mx.quest.runway.authz.PermissionCatalog;
|
||||
import mx.quest.runway.authz.ReservedRoles;
|
||||
import mx.quest.runway.authz.Role;
|
||||
import mx.quest.runway.authz.RoleStore;
|
||||
import mx.quest.runway.security.AppUserStore;
|
||||
import mx.quest.runway.security.Roles;
|
||||
import mx.quest.runway.security.SiteUserStore;
|
||||
import mx.quest.runway.security.User;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* Builds the read model for the permissions matrix — users with their assigned roles + direct grants, the
|
||||
* assignable roles, the grantable permissions, and each role's <b>true effective</b> permission set (via
|
||||
* {@link mx.quest.runway.authz.AuthorizationService#effectiveRolePermissionKeys} — the full grantable set for
|
||||
* the wildcard Administrator tier). The scope is given by the caller's realm + (for the tenant
|
||||
* realm) the bound tenancy; the controllers always pass the realm of the <b>logged-in actor</b>, so the matrix
|
||||
* a tenant manager sees and edits is their own tenancy's and never crosses into the application realm.
|
||||
*
|
||||
* <p>Pure read model; all <b>writes</b> go through {@code AuthorizationAdminService} (bounded-grant), never
|
||||
* this service or the stores directly.
|
||||
*/
|
||||
@Service
|
||||
public class PermissionsMatrixService {
|
||||
|
||||
private final AppUserStore appUsers;
|
||||
private final SiteUserStore siteUsers;
|
||||
private final RoleStore roles;
|
||||
private final GrantStore grants;
|
||||
private final PermissionCatalog catalog;
|
||||
private final mx.quest.runway.authz.AuthorizationService authz;
|
||||
|
||||
public PermissionsMatrixService(AppUserStore appUsers, SiteUserStore siteUsers, RoleStore roles,
|
||||
GrantStore grants, PermissionCatalog catalog,
|
||||
mx.quest.runway.authz.AuthorizationService authz) {
|
||||
this.appUsers = appUsers;
|
||||
this.siteUsers = siteUsers;
|
||||
this.roles = roles;
|
||||
this.grants = grants;
|
||||
this.catalog = catalog;
|
||||
this.authz = authz;
|
||||
}
|
||||
|
||||
/** A user row: identity plus the roles and direct permissions it holds in this scope. */
|
||||
public record UserRow(String principalId, String username, String displayName, boolean master,
|
||||
List<String> roles, List<String> directPermissions) {
|
||||
}
|
||||
|
||||
/**
|
||||
* A role row: the role, whether it is the all-access {@code wildcard} tier (Administrator), the grantable
|
||||
* permission keys it <b>effectively</b> holds (stored + granted + defaults − revokes over its closure; the
|
||||
* <em>full</em> grantable set for the wildcard), and — for a <b>custom</b> role — the names of the roles it
|
||||
* directly inherits (its outgoing DAG edges). Predefined roles never carry inherit edges ({@code inherits}
|
||||
* is empty), so the hierarchy UI only offers edges on custom rows.
|
||||
*/
|
||||
public record RoleRow(String name, boolean custom, boolean wildcard, List<String> heldPermissions,
|
||||
List<String> inherits) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The whole matrix for a scope. {@code customRoles} is the subset of role names that are editable custom
|
||||
* roles (the delete + hierarchy affordances apply only to these); it is the eligible set for both ends of an
|
||||
* inherit edge.
|
||||
*/
|
||||
public record Matrix(Realm realm, String tenancyId, List<UserRow> users, List<String> assignableRoles,
|
||||
List<Permission> grantablePermissions, List<RoleRow> roles, List<String> customRoles) {
|
||||
}
|
||||
|
||||
/** Builds the matrix for {@code realm} (+ bound {@code tenancyId} for the tenant realm). */
|
||||
public Matrix build(Realm realm, String tenancyId) {
|
||||
GrantFile grantFile = realm == Realm.APPLICATION ? grants.appGrants() : grants.siteGrants(tenancyId);
|
||||
List<User> users = realm == Realm.APPLICATION ? appUsers.list() : siteUsers.list(tenancyId);
|
||||
|
||||
List<UserRow> userRows = new ArrayList<>();
|
||||
for (User user : users) {
|
||||
Set<String> assigned = new TreeSet<>(user.roles());
|
||||
assigned.addAll(grantFile.rolesOf(user.principalId()));
|
||||
userRows.add(new UserRow(user.principalId(), user.username(), user.displayName(), user.master(),
|
||||
List.copyOf(assigned), new ArrayList<>(new TreeSet<>(grantFile.permissionsOf(user.principalId())))));
|
||||
}
|
||||
|
||||
List<String> assignableRoles = assignableRoles(realm, tenancyId);
|
||||
List<Permission> grantable = new ArrayList<>(catalog.grantable(realm));
|
||||
|
||||
// Inherit edges by role name, read from the raw custom-role list (predefined roles have none).
|
||||
Map<String, List<String>> inheritsByRole = new HashMap<>();
|
||||
List<String> customRoles = new ArrayList<>();
|
||||
for (Role role : (realm == Realm.APPLICATION ? roles.appRoleList() : roles.siteRoleList(tenancyId))) {
|
||||
customRoles.add(role.name());
|
||||
inheritsByRole.put(role.name(), new ArrayList<>(new TreeSet<>(role.inherits())));
|
||||
}
|
||||
|
||||
List<RoleRow> roleRows = new ArrayList<>();
|
||||
for (String roleName : assignableRoles) {
|
||||
// The role's TRUE effective reach (the same fold mayAccess applies): stored + granted + defaults −
|
||||
// revokes over its closure, and the FULL grantable set for the wildcard tier. This is why the
|
||||
// all-access Administrator no longer renders as an empty row and a role's granted core permissions
|
||||
// show — the old display listed only plugin-default control points, inverting apparent role power.
|
||||
Set<String> held = new TreeSet<>(authz.effectiveRolePermissionKeys(realm, tenancyId, roleName));
|
||||
boolean custom = !isPredefined(roleName, realm);
|
||||
boolean wildcard = ReservedRoles.isWildcard(roleName);
|
||||
roleRows.add(new RoleRow(roleName, custom, wildcard, List.copyOf(held),
|
||||
inheritsByRole.getOrDefault(roleName, List.of())));
|
||||
}
|
||||
return new Matrix(realm, tenancyId, userRows, assignableRoles, grantable, roleRows, List.copyOf(customRoles));
|
||||
}
|
||||
|
||||
/** Assignable roles: the realm's ordinary predefined roles (never the master) plus every custom role. */
|
||||
private List<String> assignableRoles(Realm realm, String tenancyId) {
|
||||
Set<String> names = new LinkedHashSet<>(predefinedAssignable(realm));
|
||||
for (Role role : (realm == Realm.APPLICATION ? roles.appRoleList() : roles.siteRoleList(tenancyId))) {
|
||||
names.add(role.name());
|
||||
}
|
||||
return List.copyOf(names);
|
||||
}
|
||||
|
||||
private static List<String> predefinedAssignable(Realm realm) {
|
||||
// The master tier is never assignable in-app; the wildcard + operator tiers are.
|
||||
return realm == Realm.APPLICATION
|
||||
? List.of(Roles.SYSTEM_ADMIN, Roles.SYSTEM_OPERATOR)
|
||||
: List.of(Roles.ADMIN, Roles.OPERATOR);
|
||||
}
|
||||
|
||||
private static boolean isPredefined(String roleName, Realm realm) {
|
||||
return ReservedRoles.isReserved(roleName) || predefinedAssignable(realm).contains(roleName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import mx.quest.runway.security.RunwayUserDetails;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
|
||||
/**
|
||||
* Puts {@code platformAdmin} in every console model: whether the signed-in operator may change platform settings,
|
||||
* so a screen shows its Settings button (Backups, Bandwidth, Logs, Plugins → the kernel settings card of that
|
||||
* screen) only to someone it would not answer with 403.
|
||||
*/
|
||||
@ControllerAdvice(basePackages = "mx.quest.runway.console")
|
||||
public class PlatformAdminModelAdvice {
|
||||
|
||||
private final PlatformAuthority platformAuthority;
|
||||
|
||||
public PlatformAdminModelAdvice(PlatformAuthority platformAuthority) {
|
||||
this.platformAuthority = platformAuthority;
|
||||
}
|
||||
|
||||
/** Only an application-realm operator can be one; a site user never is (and is never asked about). */
|
||||
@ModelAttribute("platformAdmin")
|
||||
public boolean platformAdmin(Authentication authentication) {
|
||||
return authentication != null
|
||||
&& authentication.getPrincipal() instanceof RunwayUserDetails principal
|
||||
&& principal.realm() == Realm.APPLICATION
|
||||
&& platformAuthority.isPlatformAdmin(authentication);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import mx.quest.runway.authz.AuthorizationService;
|
||||
import mx.quest.runway.security.RunwayUserDetails;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
/**
|
||||
* The one place the operator console asks "may this caller perform a <b>platform</b> operation?" — plugin
|
||||
* management, app-level plugin settings, the restart, application configuration. These are reserved to the
|
||||
* application <b>master</b> or a <b>wildcard</b> admin and checked through {@link AuthorizationService}
|
||||
* ({@code isMaster}/{@code isWildcard}, application realm with no tenancy) — <b>not</b> a grantable permission
|
||||
* (the master-only operations are a target-based guard). Controllers call {@link #require} on every such
|
||||
* mutation so the gate can't be forgotten; it fails closed with {@code 403}.
|
||||
*/
|
||||
@Component
|
||||
public class PlatformAuthority {
|
||||
|
||||
private final AuthorizationService authorization;
|
||||
|
||||
public PlatformAuthority(AuthorizationService authorization) {
|
||||
this.authorization = authorization;
|
||||
}
|
||||
|
||||
/** Whether {@code authentication} is the application master or a wildcard admin. */
|
||||
public boolean isPlatformAdmin(Authentication authentication) {
|
||||
return authentication != null
|
||||
&& authentication.getPrincipal() instanceof RunwayUserDetails principal
|
||||
&& (authorization.isMaster(principal, null) || authorization.isWildcard(principal, null));
|
||||
}
|
||||
|
||||
/**
|
||||
* Fails closed with {@code 403} unless the caller is a platform admin. A {@link ResponseStatusException} so
|
||||
* the status is clean in every harness (mapped by the dispatcher, not only the security access-denied path).
|
||||
*/
|
||||
public void require(Authentication authentication) {
|
||||
if (!isPlatformAdmin(authentication)) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN,
|
||||
"this operation is restricted to the application master or a wildcard administrator");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import mx.quest.runway.log.AppActivityLog;
|
||||
import mx.quest.runway.plugin.PluginAdminService;
|
||||
import mx.quest.runway.plugin.PluginDescriptor;
|
||||
import mx.quest.runway.wizard.Restarter;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* The plugin-management screen (the operator console's headline) and its actions, app-realm only
|
||||
* ({@code /__app/plugins}). The screen lists every install folder with its drift badge and the restart-required
|
||||
* banner, each plugin's health this boot (contained failures, refused contributions, compliance warnings, the
|
||||
* "uses host internals" badge); the actions install (upload), enable/disable, retry a quarantined plugin,
|
||||
* uninstall, and restart-to-apply.
|
||||
*
|
||||
* <p><b>Authority.</b> Plugin management is a <b>platform operation</b> reserved to the application master or a
|
||||
* wildcard admin — checked here through {@link PlatformAuthority} (the shared master/wildcard gate), <b>not</b>
|
||||
* a grantable permission (the master-only ops are a target-based guard, not a permission anyone can be
|
||||
* granted). The read-only listing is open to any authenticated app operator (the chain already restricts to
|
||||
* {@code SYSTEM_*}); every <b>mutation</b> (and the restart) re-checks the gate and answers {@code 403}
|
||||
* otherwise — proven by test.
|
||||
*
|
||||
* <p>Mutations change only the {@code external/plugins} tree and apply on the <b>next restart</b> (the locked
|
||||
* restart-to-install decision); the restart action triggers the supervised relaunch ({@link Restarter}) and
|
||||
* returns a standalone interstitial that meta-refreshes to the console once the fresh JVM is up.
|
||||
*/
|
||||
@Controller
|
||||
@RequestMapping("/__app/plugins")
|
||||
public class PluginAdminController {
|
||||
|
||||
private final PluginAdminService plugins;
|
||||
private final PlatformAuthority platformAuthority;
|
||||
private final Restarter restarter;
|
||||
private final AppActivityLog activity;
|
||||
|
||||
public PluginAdminController(PluginAdminService plugins, PlatformAuthority platformAuthority,
|
||||
Restarter restarter, AppActivityLog activity) {
|
||||
this.plugins = plugins;
|
||||
this.platformAuthority = platformAuthority;
|
||||
this.restarter = restarter;
|
||||
this.activity = activity;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String list(Model model) {
|
||||
model.addAttribute("plugins", plugins.list());
|
||||
model.addAttribute("restartRequired", plugins.restartRequired());
|
||||
model.addAttribute("contentTemplate", "operator/app/plugins");
|
||||
model.addAttribute("pageTitleKey", "op.plugins.title");
|
||||
return "operator/op-layout";
|
||||
}
|
||||
|
||||
@PostMapping("/upload")
|
||||
public String upload(@RequestParam("file") MultipartFile file, Authentication authentication,
|
||||
RedirectAttributes redirect) {
|
||||
platformAuthority.require(authentication);
|
||||
if (file == null || file.isEmpty()) {
|
||||
redirect.addFlashAttribute("error", "No file was uploaded.");
|
||||
return "redirect:/__app/plugins";
|
||||
}
|
||||
try (InputStream in = file.getInputStream()) {
|
||||
PluginDescriptor descriptor = plugins.install(in);
|
||||
activity.record(authentication.getName(), "plugin.installed", descriptor.id() + " v" + descriptor.version());
|
||||
redirect.addFlashAttribute("flash",
|
||||
"Installed " + descriptor.id() + " v" + descriptor.version() + " — restart to apply.");
|
||||
} catch (IOException | RuntimeException e) {
|
||||
redirect.addFlashAttribute("error", "Install failed: " + rootMessage(e));
|
||||
}
|
||||
return "redirect:/__app/plugins";
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/enable")
|
||||
public String enable(@PathVariable String id, Authentication authentication, RedirectAttributes redirect) {
|
||||
return setEnabled(id, true, authentication, redirect);
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/disable")
|
||||
public String disable(@PathVariable String id, Authentication authentication, RedirectAttributes redirect) {
|
||||
return setEnabled(id, false, authentication, redirect);
|
||||
}
|
||||
|
||||
private String setEnabled(String id, boolean enabled, Authentication authentication, RedirectAttributes redirect) {
|
||||
platformAuthority.require(authentication);
|
||||
try {
|
||||
plugins.setEnabled(id, enabled);
|
||||
activity.record(authentication.getName(), enabled ? "plugin.enabled" : "plugin.disabled", id);
|
||||
redirect.addFlashAttribute("flash",
|
||||
"Plugin '" + id + "' " + (enabled ? "enabled" : "disabled") + " — restart to apply.");
|
||||
} catch (RuntimeException e) {
|
||||
redirect.addFlashAttribute("error", rootMessage(e));
|
||||
}
|
||||
return "redirect:/__app/plugins";
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears a quarantined plugin's marker so the next boot tries it again. A platform
|
||||
* operation like every other mutation here; applies on restart.
|
||||
*/
|
||||
@PostMapping("/{id}/retry")
|
||||
public String retry(@PathVariable String id, Authentication authentication, RedirectAttributes redirect) {
|
||||
platformAuthority.require(authentication);
|
||||
try {
|
||||
if (plugins.retry(id)) {
|
||||
activity.record(authentication.getName(), "plugin.retried", id);
|
||||
redirect.addFlashAttribute("flash", "Quarantine cleared for '" + id
|
||||
+ "' — it will be tried again on the next restart.");
|
||||
} else {
|
||||
redirect.addFlashAttribute("flash", "'" + id + "' was not quarantined.");
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
redirect.addFlashAttribute("error", rootMessage(e));
|
||||
}
|
||||
return "redirect:/__app/plugins";
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/uninstall")
|
||||
public String uninstall(@PathVariable String id, Authentication authentication, RedirectAttributes redirect) {
|
||||
platformAuthority.require(authentication);
|
||||
try {
|
||||
plugins.uninstall(id);
|
||||
activity.record(authentication.getName(), "plugin.uninstalled", id);
|
||||
redirect.addFlashAttribute("flash", "Uninstalled '" + id + "' — restart to apply.");
|
||||
} catch (RuntimeException e) {
|
||||
redirect.addFlashAttribute("error", rootMessage(e));
|
||||
}
|
||||
return "redirect:/__app/plugins";
|
||||
}
|
||||
|
||||
@PostMapping("/restart")
|
||||
public String restart(Authentication authentication, Model model) {
|
||||
platformAuthority.require(authentication);
|
||||
activity.record(authentication.getName(), "platform.restart", "");
|
||||
restarter.restart(); // schedules a supervised relaunch on a background thread after this response flushes
|
||||
model.addAttribute("pageTitleKey", "op.plugins.restart.title");
|
||||
return "operator/restarting";
|
||||
}
|
||||
|
||||
private static String rootMessage(Throwable t) {
|
||||
Throwable root = t;
|
||||
while (root.getCause() != null && root.getCause() != root) {
|
||||
root = root.getCause();
|
||||
}
|
||||
return root.getMessage() == null ? root.toString() : root.getMessage();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.authz.AuthorizationService;
|
||||
import mx.quest.runway.authz.Permission;
|
||||
import mx.quest.runway.authz.PermissionCatalog;
|
||||
import mx.quest.runway.log.AppActivityLog;
|
||||
import mx.quest.runway.plugin.PluginAdminService;
|
||||
import mx.quest.runway.plugin.PluginDescriptor;
|
||||
import mx.quest.runway.plugin.PluginSettingDef;
|
||||
import mx.quest.runway.plugin.PluginSettingsService;
|
||||
import mx.quest.runway.plugin.SettingValidationException;
|
||||
import mx.quest.runway.plugin.SitePluginConfigService;
|
||||
import mx.quest.runway.site.SiteStore;
|
||||
import mx.quest.runway.security.RunwayUserDetails;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import mx.quest.runway.storage.PathSafety;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* The <b>app-level</b> plugin settings form ({@code /__app/plugins/{id}/settings}) — the kernel renders,
|
||||
* validates and persists a plugin's declared {@code settings:} schema generically through
|
||||
* {@link PluginSettingsService}; the plugin never sees the form. A <b>platform</b> operation (app-level
|
||||
* settings are platform config): gated by the plugin's app-realm {@code <id>|settings} permission when it declares
|
||||
* one, else to the master/wildcard admin via {@link PlatformAuthority} — see {@code requireSettingsAccess}.
|
||||
*
|
||||
* <p>Checkbox semantics are translated here (the form layer): an unchecked boolean sends no parameter, so the
|
||||
* controller writes an explicit {@code false} for every boolean key, keeping the service's coercion generic. A
|
||||
* bad value comes back as a field error (never a 500). Changes apply on the next restart;
|
||||
* {@link PluginSettingsService#pendingRestartKeys} and {@code strayKeys} feed the drift warnings.
|
||||
*/
|
||||
@Controller
|
||||
public class PluginSettingsController {
|
||||
|
||||
private final SettingRefusals refusals;
|
||||
private final PluginAdminService plugins;
|
||||
private final PluginSettingsService settings;
|
||||
private final PlatformAuthority platformAuthority;
|
||||
private final Environment environment;
|
||||
private final AppActivityLog activity;
|
||||
private final PermissionCatalog catalog;
|
||||
private final AuthorizationService authorization;
|
||||
private final SiteStore sites;
|
||||
private final SitePluginConfigService sitePluginConfig;
|
||||
|
||||
public PluginSettingsController(PluginAdminService plugins, PluginSettingsService settings,
|
||||
PlatformAuthority platformAuthority, Environment environment,
|
||||
AppActivityLog activity, PermissionCatalog catalog,
|
||||
AuthorizationService authorization, SiteStore sites,
|
||||
SitePluginConfigService sitePluginConfig, SettingRefusals refusals) {
|
||||
this.refusals = refusals;
|
||||
this.sites = sites;
|
||||
this.sitePluginConfig = sitePluginConfig;
|
||||
this.catalog = catalog;
|
||||
this.authorization = authorization;
|
||||
this.plugins = plugins;
|
||||
this.settings = settings;
|
||||
this.platformAuthority = platformAuthority;
|
||||
this.environment = environment;
|
||||
this.activity = activity;
|
||||
}
|
||||
|
||||
/**
|
||||
* The gate for one plugin's app-level settings. When the plugin declares the app-realm {@code settings}
|
||||
* permission point ({@code <id>|settings}), holding it opens the form, as it already opens the plugin's own
|
||||
* screens and its Settings-menu entry; the master and wildcard admins hold every permission. Until 1.0.0 the
|
||||
* form was master/wildcard-only regardless, so an operator granted {@code protection|settings} could save
|
||||
* protection's login panel but not open the page it sits on. A plugin that declares no such point keeps the
|
||||
* master/wildcard gate.
|
||||
*/
|
||||
private void requireSettingsAccess(Authentication authentication, String pluginId) {
|
||||
if (!PathSafety.isSafeId(pluginId)) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no such plugin");
|
||||
}
|
||||
Permission declared = catalog.find(PathSafety.compoundKey(pluginId, "settings"))
|
||||
.filter(permission -> permission.realm() == Realm.APPLICATION)
|
||||
.orElse(null);
|
||||
if (declared == null) {
|
||||
platformAuthority.require(authentication);
|
||||
return;
|
||||
}
|
||||
boolean allowed = authentication != null
|
||||
&& authentication.getPrincipal() instanceof RunwayUserDetails principal
|
||||
&& principal.realm() == Realm.APPLICATION
|
||||
&& authorization.mayAccess(principal, declared, null);
|
||||
if (!allowed) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN,
|
||||
"this operation needs the '" + declared.key() + "' permission");
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/__app/plugins/{id}/settings")
|
||||
public String form(@PathVariable String id, Authentication authentication, Model model) {
|
||||
requireSettingsAccess(authentication, id);
|
||||
PluginDescriptor descriptor = descriptorOrThrow(id);
|
||||
populate(model, id, descriptor);
|
||||
// A plugin's optional APP-realm panel, rendered below the generic form from its own namespace. Realm-scoped
|
||||
// (admin-app.html, not the tenant-oriented admin.html) so a per-tenant panel never leaks into this console —
|
||||
// the reference is the protection plugin's login-protection panel. Reference: TenantPluginSettingsController.
|
||||
if (plugins.hasAppAdminFragment(id)) {
|
||||
model.addAttribute("adminFragment", "__plugin__/" + id + "/admin-app");
|
||||
}
|
||||
model.addAttribute("settingsAction", "/__app/plugins/" + id + "/settings");
|
||||
model.addAttribute("settingsBack", "/__app/plugins");
|
||||
model.addAttribute("settingsScope", "app");
|
||||
model.addAttribute("contentTemplate", "operator/plugin-settings");
|
||||
model.addAttribute("pageTitleKey", "op.settings.title");
|
||||
return "operator/op-layout";
|
||||
}
|
||||
|
||||
@PostMapping("/__app/plugins/{id}/settings")
|
||||
public String save(@PathVariable String id, HttpServletRequest request, Authentication authentication,
|
||||
RedirectAttributes redirect) {
|
||||
requireSettingsAccess(authentication, id);
|
||||
PluginDescriptor descriptor = descriptorOrThrow(id);
|
||||
List<PluginSettingDef> schema = descriptor.settings();
|
||||
try {
|
||||
List<String> dropped = settings.save(id, schema, submittedValues(request, schema));
|
||||
activity.record(authentication.getName(), "plugin.settings-changed",
|
||||
dropped.isEmpty() ? id : id + " (cleared " + String.join(", ", dropped) + ")");
|
||||
redirect.addFlashAttribute("flash", "Settings saved for '" + id + "' — restart to apply.");
|
||||
if (!dropped.isEmpty()) {
|
||||
// A secret removed because a setting it is bound to changed (PluginSettingDef.secretBoundTo).
|
||||
redirect.addFlashAttribute("secretsDropped", String.join(", ", dropped));
|
||||
}
|
||||
} catch (SettingValidationException invalid) {
|
||||
redirect.addFlashAttribute("error", refusals.describe(invalid));
|
||||
} catch (RuntimeException e) {
|
||||
redirect.addFlashAttribute("error", e.getMessage());
|
||||
}
|
||||
return "redirect:/__app/plugins/" + id + "/settings";
|
||||
}
|
||||
|
||||
/** Builds the submitted map; an unchecked boolean (no param) becomes an explicit {@code false}. */
|
||||
static Map<String, String> submittedValues(HttpServletRequest request, List<PluginSettingDef> schema) {
|
||||
Map<String, String> submitted = new LinkedHashMap<>();
|
||||
for (PluginSettingDef def : schema) {
|
||||
String[] values = request.getParameterValues(def.key());
|
||||
boolean present = values != null && values.length > 0;
|
||||
if ("boolean".equalsIgnoreCase(def.type())) {
|
||||
submitted.put(def.key(), present && !"false".equalsIgnoreCase(values[values.length - 1]) ? "true" : "false");
|
||||
} else if (present) {
|
||||
submitted.put(def.key(), values[values.length - 1]);
|
||||
}
|
||||
}
|
||||
return submitted;
|
||||
}
|
||||
|
||||
private void populate(Model model, String id, PluginDescriptor descriptor) {
|
||||
List<PluginSettingDef> schema = descriptor.settings();
|
||||
model.addAttribute("pluginId", id);
|
||||
model.addAttribute("pluginName", descriptor.name() != null ? descriptor.name() : id);
|
||||
var rendered = settings.render(id, schema);
|
||||
model.addAttribute("fields", rendered.stream().map(SettingField::of).toList());
|
||||
model.addAttribute("sections", SettingsForm.build(rendered, descriptor,
|
||||
SettingsForm.appValues(descriptor, environment)));
|
||||
model.addAttribute("strayKeys", settings.strayKeys(id, schema));
|
||||
model.addAttribute("pendingKeys", settings.pendingRestartKeys(id, schema, environment::getProperty));
|
||||
model.addAttribute("siteOverrides", siteOverrides(id, descriptor));
|
||||
}
|
||||
|
||||
/**
|
||||
* One line per per-site setting that inherits an app-level one ({@code inheritsFrom: app:<key>}) and that some
|
||||
* sites set to their own value: those sites keep it when the app-level default changes (an
|
||||
* informational note, nothing is changed for them).
|
||||
*
|
||||
* @param label the per-site setting's label key (the plugin's message)
|
||||
* @param count how many sites set their own value
|
||||
*/
|
||||
public record SiteOverride(String label, long count) {
|
||||
}
|
||||
|
||||
private List<SiteOverride> siteOverrides(String pluginId, PluginDescriptor descriptor) {
|
||||
List<SiteOverride> out = new java.util.ArrayList<>();
|
||||
for (PluginSettingDef siteDef : descriptor.siteSettings()) {
|
||||
String from = siteDef.inheritsFrom();
|
||||
if (from == null || !from.startsWith("app:")) {
|
||||
continue;
|
||||
}
|
||||
long count = sites.findAll().stream()
|
||||
.map(site -> sitePluginConfig.config(site.id(), pluginId).get(siteDef.key()))
|
||||
.filter(value -> value != null && !String.valueOf(value).isBlank()
|
||||
&& !"inherit".equals(String.valueOf(value)))
|
||||
.count();
|
||||
if (count > 0) {
|
||||
out.add(new SiteOverride(siteDef.label() != null ? siteDef.label() : siteDef.key(), count));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private PluginDescriptor descriptorOrThrow(String id) {
|
||||
return plugins.descriptor(id).orElseThrow(() ->
|
||||
new ResponseStatusException(org.springframework.http.HttpStatus.NOT_FOUND, "no such plugin: " + id));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.plugin.LoadedPlugin;
|
||||
import mx.quest.runway.plugin.RunningPlugins;
|
||||
import mx.quest.runway.storage.PathSafety;
|
||||
import mx.quest.runway.web.FileStampValidity;
|
||||
import org.thymeleaf.IEngineConfiguration;
|
||||
import org.thymeleaf.cache.ICacheEntryValidity;
|
||||
import org.thymeleaf.templatemode.TemplateMode;
|
||||
import org.thymeleaf.templateresolver.FileTemplateResolver;
|
||||
import org.thymeleaf.templateresource.FileTemplateResource;
|
||||
import org.thymeleaf.templateresource.ITemplateResource;
|
||||
|
||||
/**
|
||||
* Resolves a plugin-contributed template named {@code __plugin__/<id>/<name>} to the file
|
||||
* {@code <installDir>/templates/<name>.html} (with its paired {@code .th.xml}), so a plugin can ship dashboard
|
||||
* cards, admin-fragment panels, and any presentation-time templates from <b>its own namespace</b> — the plugin
|
||||
* self-containment rule (assets served from the plugin, never copied into tenants). The kernel knows only this
|
||||
* generic seam; there is zero plugin-specific code in the chrome.
|
||||
*
|
||||
* <p>Two safeguards, mirroring {@code SiteTemplateResolver}: the {@code __plugin__/<id>/} prefix makes the
|
||||
* cached template name plugin-unique (Thymeleaf caches by name), and the id must name a
|
||||
* <b>loaded</b> plugin while the name is confined under that plugin's {@code templates/} directory (traversal
|
||||
* can never escape it). Decoupled logic on, cache on (each parse valid while its files are unchanged); ordered
|
||||
* after the site (1) and operator (2) resolvers.
|
||||
*/
|
||||
public class PluginTemplateResolver extends FileTemplateResolver {
|
||||
|
||||
/** The reserved name prefix for plugin templates. */
|
||||
public static final String PREFIX = "__plugin__/";
|
||||
|
||||
private static final String TEMPLATES_DIR = "templates";
|
||||
private static final String SUFFIX = ".html";
|
||||
|
||||
private final RunningPlugins runningPlugins;
|
||||
|
||||
public PluginTemplateResolver(RunningPlugins runningPlugins) {
|
||||
this.runningPlugins = runningPlugins;
|
||||
setName("pluginTemplateResolver");
|
||||
setTemplateMode(TemplateMode.HTML);
|
||||
setUseDecoupledLogic(true);
|
||||
// Cache on; a parse stays valid only while its files are unchanged on disk (computeValidity). Plugin
|
||||
// templates are operator-editable install-dir files that no event evicts by name, and a virtual render's
|
||||
// ETag folds their bytes — so the parse must follow the file, not a timer (the former 30 s TTL served
|
||||
// the old parse under the new ETag for up to 30 s).
|
||||
setCacheable(true);
|
||||
setCharacterEncoding("UTF-8");
|
||||
setCheckExistence(true);
|
||||
setOrder(3);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean computeResolvable(IEngineConfiguration configuration, String ownerTemplate,
|
||||
String template, Map<String, Object> templateResolutionAttributes) {
|
||||
return template != null && template.startsWith(PREFIX);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ITemplateResource computeTemplateResource(IEngineConfiguration configuration, String ownerTemplate,
|
||||
String template, String resourceName, String characterEncoding,
|
||||
Map<String, Object> templateResolutionAttributes) {
|
||||
return new FileTemplateResource(resolveFile(template).toString(), characterEncoding);
|
||||
}
|
||||
|
||||
/** A cached parse stays valid while its {@code .html}/{@code .th.xml} are unchanged ({@link FileStampValidity}). */
|
||||
@Override
|
||||
protected ICacheEntryValidity computeValidity(IEngineConfiguration configuration, String ownerTemplate,
|
||||
String template, Map<String, Object> templateResolutionAttributes) {
|
||||
return FileStampValidity.forTemplate(resolveFile(template));
|
||||
}
|
||||
|
||||
/** Maps {@code __plugin__/<id>/<name>} to the absolute {@code .html} file under the loaded plugin's dir. */
|
||||
private Path resolveFile(String template) {
|
||||
String rest = template.substring(PREFIX.length());
|
||||
int slash = rest.indexOf('/');
|
||||
if (slash <= 0 || slash == rest.length() - 1) {
|
||||
throw new IllegalArgumentException("template name must be " + PREFIX + "<id>/<name>: " + template);
|
||||
}
|
||||
String pluginId = rest.substring(0, slash);
|
||||
String name = rest.substring(slash + 1);
|
||||
Path installDir = installDirOf(pluginId);
|
||||
return PathSafety.resolveConfined(installDir.resolve(TEMPLATES_DIR), name + SUFFIX);
|
||||
}
|
||||
|
||||
/** The install dir of a currently-loaded plugin; only a running plugin can contribute a template. */
|
||||
private Path installDirOf(String pluginId) {
|
||||
for (LoadedPlugin plugin : runningPlugins.installed()) {
|
||||
if (plugin.id().equals(pluginId)) {
|
||||
return plugin.installDir();
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("no loaded plugin '" + pluginId + "' to resolve its template");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.lang.management.RuntimeMXBean;
|
||||
import java.net.InetAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.FileStore;
|
||||
import java.nio.file.Files;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import mx.quest.runway.backup.BackupProperties;
|
||||
import mx.quest.runway.crypto.SecretCipher;
|
||||
import mx.quest.runway.i18n.I18nProperties;
|
||||
import mx.quest.runway.platform.PlatformSettingsStore;
|
||||
import mx.quest.runway.security.ActivePasswordStrength;
|
||||
import mx.quest.runway.storage.StorageLayout;
|
||||
import mx.quest.runway.web.CompressionFilter;
|
||||
import mx.quest.runway.web.RunwayProxyProperties;
|
||||
import mx.quest.runway.web.RunwayTlsProperties;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.boot.SpringBootVersion;
|
||||
import org.springframework.boot.info.BuildProperties;
|
||||
import org.springframework.core.SpringVersion;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* A read-only snapshot of the effective configuration and the runtime environment, for the app-realm
|
||||
* <b>About Runway</b> screen ({@link AppAboutController}). It is a pure query bean — it computes but never
|
||||
* mutates, holds no state, and touches no tenant data.
|
||||
*
|
||||
* <p><b>Secret hygiene.</b> The "effective configuration" is a <em>curated whitelist</em> of non-secret,
|
||||
* operator-relevant settings read off the bound {@code @ConfigurationProperties} beans — never a dump of the
|
||||
* Spring {@code Environment}'s property sources. Nothing that carries a secret (the TLS keystore password, the
|
||||
* metrics scrape token, the {@code runway.security.secret-key}, plugin secret settings) is ever surfaced;
|
||||
* secret-adjacent state is shown only as a boolean "configured / not configured" (e.g. via
|
||||
* {@link SecretCipher#isAvailable()}), following the platform's "render whether it is set, never its value"
|
||||
* rule. Because the list is curated, no masking/redaction is needed.
|
||||
*
|
||||
* <p>Everything under "runtime environment" describes <b>the node serving the request</b> (PID, uptime, heap,
|
||||
* host name, active profiles) — relevant when more than one node runs the platform.
|
||||
*/
|
||||
@Service
|
||||
public class RuntimeInfoService {
|
||||
|
||||
/** A single labelled row of the About tables. {@code name} is a message key (config/runtime rows) or a
|
||||
* literal product name (component rows); {@code value} is a display-ready string. */
|
||||
public record NameValue(String name, String value) {}
|
||||
|
||||
private static final long MIB = 1024L * 1024L;
|
||||
private static final DateTimeFormatter TS =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm z").withZone(ZoneId.systemDefault());
|
||||
/** Matches a trailing {@code -<version>} on a jar file name (used when a package has no Implementation-Version). */
|
||||
private static final Pattern JAR_VERSION = Pattern.compile("-(\\d[\\w.+-]*)$");
|
||||
|
||||
private final ActivePasswordStrength activeStrength;
|
||||
private final ObjectProvider<BuildProperties> buildProperties;
|
||||
private final Environment environment;
|
||||
private final RunwayTlsProperties tls;
|
||||
private final RunwayProxyProperties proxy;
|
||||
private final BackupProperties backups;
|
||||
private final I18nProperties i18n;
|
||||
private final StorageLayout layout;
|
||||
private final SecretCipher secretCipher;
|
||||
private final CompressionFilter compression;
|
||||
private final PlatformSettingsStore platform;
|
||||
|
||||
public RuntimeInfoService(ObjectProvider<BuildProperties> buildProperties, Environment environment,
|
||||
RunwayTlsProperties tls,
|
||||
RunwayProxyProperties proxy, BackupProperties backups, I18nProperties i18n,
|
||||
StorageLayout layout, SecretCipher secretCipher,
|
||||
CompressionFilter compression, PlatformSettingsStore platform,
|
||||
ActivePasswordStrength activeStrength) {
|
||||
this.activeStrength = activeStrength;
|
||||
this.buildProperties = buildProperties;
|
||||
this.environment = environment;
|
||||
this.tls = tls;
|
||||
this.proxy = proxy;
|
||||
this.backups = backups;
|
||||
this.i18n = i18n;
|
||||
this.layout = layout;
|
||||
this.secretCipher = secretCipher;
|
||||
this.compression = compression;
|
||||
this.platform = platform;
|
||||
}
|
||||
|
||||
/** The running application version — from the build-info bean, else the jar manifest, else {@code "dev"}. */
|
||||
public String version() {
|
||||
BuildProperties bp = buildProperties.getIfAvailable();
|
||||
if (bp != null && bp.getVersion() != null && !bp.getVersion().isBlank()) {
|
||||
return bp.getVersion();
|
||||
}
|
||||
String impl = getClass().getPackage() == null ? null : getClass().getPackage().getImplementationVersion();
|
||||
return impl != null && !impl.isBlank() ? impl : "dev";
|
||||
}
|
||||
|
||||
/** The build timestamp from the build-info bean, formatted; {@code "—"} when build-info is absent. */
|
||||
public String buildTime() {
|
||||
BuildProperties bp = buildProperties.getIfAvailable();
|
||||
return bp != null && bp.getTime() != null ? TS.format(bp.getTime()) : "—";
|
||||
}
|
||||
|
||||
/**
|
||||
* The curated, non-secret effective configuration. Each row's {@code name} is a message key
|
||||
* ({@code op.about.cfg.*}); values are formatted for display and deliberately exclude every secret.
|
||||
*/
|
||||
public List<NameValue> effectiveConfig() {
|
||||
List<NameValue> rows = new ArrayList<>();
|
||||
rows.add(new NameValue("op.about.cfg.tls",
|
||||
tls.isEnabled() ? "terminated here (embedded)" : "at the reverse proxy"));
|
||||
rows.add(new NameValue("op.about.cfg.port", serverPort()));
|
||||
rows.add(new NameValue("op.about.cfg.proxy", proxySummary()));
|
||||
rows.add(new NameValue("op.about.cfg.compression", compression.summary()));
|
||||
rows.add(new NameValue("op.about.cfg.pw", passwordSummary()));
|
||||
rows.add(new NameValue("op.about.cfg.secret", secretCipher.isAvailable() ? "configured" : "not configured"));
|
||||
rows.add(new NameValue("op.about.cfg.dataDir", pathSummary(layout.external())));
|
||||
rows.add(new NameValue("op.about.cfg.backupsDir", pathSummary(layout.backups())));
|
||||
rows.add(new NameValue("op.about.cfg.schedule", scheduleSummary()));
|
||||
rows.add(new NameValue("op.about.cfg.retention", retentionSummary()));
|
||||
rows.add(new NameValue("op.about.cfg.offsite",
|
||||
backups.getOffsiteDir().isBlank() ? "off" : backups.getOffsiteDir()));
|
||||
rows.add(new NameValue("op.about.cfg.i18n",
|
||||
"public pages: every request · other: "
|
||||
+ (i18n.getCacheSeconds() == 0 ? "every access" : "every " + i18n.getCacheSeconds() + " s")));
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* The profile new passwords are hashed with now, and the saved Platform settings choice when it differs
|
||||
* (it applies on the next launch). Until 1.0.0 this row showed the {@code application.yml} default even when
|
||||
* Platform settings had changed it.
|
||||
*/
|
||||
String passwordSummary() {
|
||||
String inForce = activeStrength.strength().name();
|
||||
String saved = platform.get().strength().map(v -> v.trim().toUpperCase(java.util.Locale.ROOT)).orElse(null);
|
||||
if (saved != null && !saved.equals(inForce)) {
|
||||
return "Argon2id · " + inForce + " (" + saved + " is saved and applies after the next restart)";
|
||||
}
|
||||
return "Argon2id · " + inForce;
|
||||
}
|
||||
|
||||
/**
|
||||
* A data path as configured, followed by where it really is when that differs (an installed release reaches
|
||||
* {@code /opt/runway-data} through links under {@code /opt/runway-<version>}).
|
||||
*/
|
||||
static String pathSummary(java.nio.file.Path configured) {
|
||||
try {
|
||||
java.nio.file.Path real = configured.toRealPath();
|
||||
return real.equals(configured.toAbsolutePath().normalize())
|
||||
? configured.toString() : configured + " → " + real;
|
||||
} catch (java.io.IOException | SecurityException unresolved) {
|
||||
return configured.toString();
|
||||
}
|
||||
}
|
||||
|
||||
/** The "Host & JVM" table describing the node serving the request. Row names are {@code op.about.rt.*} keys. */
|
||||
public List<NameValue> runtime() {
|
||||
RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean();
|
||||
Runtime rt = Runtime.getRuntime();
|
||||
String[] profiles = environment.getActiveProfiles();
|
||||
List<NameValue> rows = new ArrayList<>();
|
||||
rows.add(new NameValue("op.about.rt.node", nodeName()));
|
||||
rows.add(new NameValue("op.about.rt.profiles", profiles.length == 0 ? "default" : String.join(", ", profiles)));
|
||||
rows.add(new NameValue("op.about.rt.java", prop("java.version") + " (" + prop("java.vendor") + ")"));
|
||||
rows.add(new NameValue("op.about.rt.jvm", prop("java.vm.name") + " " + prop("java.vm.version")));
|
||||
rows.add(new NameValue("op.about.rt.os",
|
||||
prop("os.name") + " " + prop("os.version") + " (" + prop("os.arch") + ")"));
|
||||
rows.add(new NameValue("op.about.rt.cpus", Integer.toString(rt.availableProcessors())));
|
||||
rows.add(new NameValue("op.about.rt.heap",
|
||||
(rt.totalMemory() - rt.freeMemory()) / MIB + " MiB used / " + rt.maxMemory() / MIB + " MiB max"));
|
||||
rows.add(new NameValue("op.about.rt.disk", diskSummary()));
|
||||
rows.add(new NameValue("op.about.rt.uptime", humanDuration(rb.getUptime())));
|
||||
rows.add(new NameValue("op.about.rt.started", TS.format(Instant.ofEpochMilli(rb.getStartTime()))));
|
||||
rows.add(new NameValue("op.about.rt.pid", Long.toString(ProcessHandle.current().pid())));
|
||||
rows.add(new NameValue("op.about.rt.host", hostName()));
|
||||
rows.add(new NameValue("op.about.rt.timezone", ZoneId.systemDefault().getId()));
|
||||
rows.add(new NameValue("op.about.rt.locale", Locale.getDefault().toLanguageTag()));
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* The "Bundled components" table — the <b>notable</b> third-party libraries and their versions (a curated
|
||||
* set, not the full ~100-jar transitive closure). Row names are literal product names (not translated). A
|
||||
* library whose version cannot be resolved is silently omitted (a missing optional dependency must never
|
||||
* break the page). Grouped: platform/web, data, observability, crypto/cache, rendering, logging.
|
||||
*/
|
||||
public List<NameValue> components() {
|
||||
List<NameValue> rows = new ArrayList<>();
|
||||
addIf(rows, "Runway", version());
|
||||
addIf(rows, "Spring Boot", SpringBootVersion.getVersion());
|
||||
addIf(rows, "Spring Framework", SpringVersion.getVersion());
|
||||
addIf(rows, "Spring Security", versionOf("org.springframework.security.core.SpringSecurityCoreVersion"));
|
||||
addIf(rows, "Jetty", versionOf("org.eclipse.jetty.server.Server"));
|
||||
addIf(rows, "Thymeleaf", versionOf("org.thymeleaf.TemplateEngine"));
|
||||
addIf(rows, "attoparser", versionOf("org.attoparser.MarkupParser"));
|
||||
addIf(rows, "unbescape", versionOf("org.unbescape.html.HtmlEscape"));
|
||||
addIf(rows, "Jackson", versionOf("tools.jackson.databind.ObjectMapper"));
|
||||
addIf(rows, "SnakeYAML", versionOf("org.yaml.snakeyaml.Yaml"));
|
||||
addIf(rows, "Micrometer", versionOf("io.micrometer.core.instrument.MeterRegistry"));
|
||||
addIf(rows, "Prometheus", versionOf("io.prometheus.metrics.core.metrics.Counter"));
|
||||
addIf(rows, "BouncyCastle", versionOf("org.bouncycastle.jce.provider.BouncyCastleProvider"));
|
||||
addIf(rows, "Caffeine", versionOf("com.github.benmanes.caffeine.cache.Caffeine"));
|
||||
addIf(rows, "jsoup", versionOf("org.jsoup.Jsoup"));
|
||||
addIf(rows, "jsvg", versionOf("com.github.weisj.jsvg.SVGDocument"));
|
||||
addIf(rows, "brotli4j", versionOf("com.aayushatharva.brotli4j.Brotli4jLoader"));
|
||||
addIf(rows, "CodeMirror", classpathVersion("codemirror.version"));
|
||||
addIf(rows, "SLF4J", versionOf("org.slf4j.LoggerFactory"));
|
||||
addIf(rows, "Logback", versionOf("ch.qos.logback.classic.LoggerContext"));
|
||||
return rows;
|
||||
}
|
||||
|
||||
// ---- helpers -------------------------------------------------------------------------------------------
|
||||
|
||||
/** The effective HTTP port — the actually-bound port when known ({@code local.server.port}), else configured. */
|
||||
private String serverPort() {
|
||||
String bound = environment.getProperty("local.server.port");
|
||||
if (bound != null && !bound.isBlank()) {
|
||||
return bound;
|
||||
}
|
||||
return environment.getProperty("server.port", "8080");
|
||||
}
|
||||
|
||||
private String proxySummary() {
|
||||
if (!proxy.isForwardedHeaders()) {
|
||||
return "forwarded headers ignored";
|
||||
}
|
||||
int n = proxy.getTrustedCidrs() == null ? 0 : proxy.getTrustedCidrs().size();
|
||||
return n == 0 ? "direct connection only" : n + " trusted CIDR(s)";
|
||||
}
|
||||
|
||||
private String scheduleSummary() {
|
||||
BackupProperties.Schedule s = backups.getSchedule();
|
||||
return s.isEnabled() ? "enabled · " + s.getCron() : "off (manual only)";
|
||||
}
|
||||
|
||||
private String retentionSummary() {
|
||||
BackupProperties.Retention r = backups.getRetention();
|
||||
String count = r.getMaxCount() > 0 ? r.getMaxCount() + " newest" : "unlimited";
|
||||
return r.getMaxAgeDays() > 0 ? count + " · " + r.getMaxAgeDays() + "d" : count;
|
||||
}
|
||||
|
||||
private String diskSummary() {
|
||||
try {
|
||||
FileStore fs = Files.getFileStore(layout.external());
|
||||
return humanBytes(fs.getUsableSpace()) + " free of " + humanBytes(fs.getTotalSpace());
|
||||
} catch (Exception unavailable) {
|
||||
return "?";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The logical node name — the configured {@code runway.node.name}, or the OS host name when that is blank.
|
||||
* A human-friendly identity for the node serving the request, distinct from the raw {@code os host name}
|
||||
* and worth setting when several nodes run the platform behind a load balancer (so a page/log can be traced
|
||||
* to a specific node). Read straight off the {@link Environment} — it is a display-only value.
|
||||
*/
|
||||
private String nodeName() {
|
||||
Optional<String> override = platform.get().node(); // Platform settings takes precedence, applied live
|
||||
if (override.isPresent()) {
|
||||
return override.get();
|
||||
}
|
||||
String configured = environment.getProperty("runway.node.name");
|
||||
return configured != null && !configured.isBlank() ? configured.trim() : hostName();
|
||||
}
|
||||
|
||||
private static String hostName() {
|
||||
try {
|
||||
return InetAddress.getLocalHost().getHostName();
|
||||
} catch (Exception unknown) {
|
||||
return "?";
|
||||
}
|
||||
}
|
||||
|
||||
private static String prop(String key) {
|
||||
String v = System.getProperty(key);
|
||||
return v != null ? v : "?";
|
||||
}
|
||||
|
||||
private static void addIf(List<NameValue> rows, String name, String value) {
|
||||
if (value != null && !value.isBlank()) {
|
||||
rows.add(new NameValue(name, value));
|
||||
}
|
||||
}
|
||||
|
||||
/** Formats a byte count as GiB (≥ 1 GiB) or MiB, with one decimal — for human-readable disk sizes. */
|
||||
private static String humanBytes(long bytes) {
|
||||
double gib = bytes / (double) (MIB * 1024);
|
||||
if (gib >= 1.0) {
|
||||
return String.format(Locale.ROOT, "%.1f GiB", gib);
|
||||
}
|
||||
return String.format(Locale.ROOT, "%.0f MiB", bytes / (double) MIB);
|
||||
}
|
||||
|
||||
/** Compacts a millisecond duration to at most three coarse units (e.g. {@code "3d 4h 12m"}, {@code "5m 8s"}). */
|
||||
private static String humanDuration(long millis) {
|
||||
Duration d = Duration.ofMillis(millis);
|
||||
long days = d.toDays();
|
||||
int hours = d.toHoursPart();
|
||||
int mins = d.toMinutesPart();
|
||||
int secs = d.toSecondsPart();
|
||||
if (days > 0) {
|
||||
return days + "d " + hours + "h " + mins + "m";
|
||||
}
|
||||
if (hours > 0) {
|
||||
return hours + "h " + mins + "m " + secs + "s";
|
||||
}
|
||||
if (mins > 0) {
|
||||
return mins + "m " + secs + "s";
|
||||
}
|
||||
return secs + "s";
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort version of a library, identified by a representative class name. Tries the package's
|
||||
* {@code Implementation-Version} first; if that is absent or the sentinel {@code "None"} (some jars — e.g.
|
||||
* BouncyCastle — ship that, or only a {@code Bundle-Version}), parses the version out of the source jar's
|
||||
* file name. Returns {@code null} — never throws — when the class is absent or nothing usable is found, so
|
||||
* an optional dependency never breaks the About page.
|
||||
*/
|
||||
static String versionOf(String className) {
|
||||
try {
|
||||
Class<?> c = Class.forName(className);
|
||||
String v = c.getPackage() == null ? null : c.getPackage().getImplementationVersion();
|
||||
if (v != null && !v.isBlank() && !"None".equalsIgnoreCase(v)) {
|
||||
return v;
|
||||
}
|
||||
var source = c.getProtectionDomain().getCodeSource();
|
||||
return source == null || source.getLocation() == null ? null
|
||||
: versionFromJarName(source.getLocation().toString());
|
||||
} catch (Throwable absentOrUnreadable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts a version from a code-source location URL by parsing the source jar's file name. Handles a
|
||||
* Spring Boot <b>nested</b> jar URL — which terminates the inner jar with {@code "!/"}, e.g.
|
||||
* {@code jar:nested:/opt/app.jar/!BOOT-INF/lib/bcprov-jdk18on-1.80.jar!/} — as well as a plain
|
||||
* {@code file:.../bcprov-jdk18on-1.80.jar}. (The earlier form was the bug: leaving the trailing {@code "!/"}
|
||||
* on made the parsed file name empty, so every jar lacking an {@code Implementation-Version} — BouncyCastle,
|
||||
* Prometheus — silently dropped out of the packaged jar while resolving fine in exploded test runs.) Returns
|
||||
* {@code null} for an exploded class directory or a name with no {@code -<version>} suffix. Package-private
|
||||
* for testing.
|
||||
*/
|
||||
static String versionFromJarName(String location) {
|
||||
if (location == null) {
|
||||
return null;
|
||||
}
|
||||
String path = location;
|
||||
// A nested-jar URL ends with "!/" (or "!"); trim trailing separators so the jar file name comes last.
|
||||
while (path.endsWith("/") || path.endsWith("!")) {
|
||||
path = path.substring(0, path.length() - 1);
|
||||
}
|
||||
int cut = Math.max(path.lastIndexOf('/'), path.lastIndexOf('!'));
|
||||
String file = cut >= 0 ? path.substring(cut + 1) : path;
|
||||
if (file.endsWith(".jar")) {
|
||||
file = file.substring(0, file.length() - 4);
|
||||
}
|
||||
Matcher m = JAR_VERSION.matcher(file);
|
||||
return m.find() ? m.group(1) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A version read from a small UTF-8 classpath text resource — for a bundled asset (a JS bundle like
|
||||
* CodeMirror) that has no class to introspect. Returns {@code null} if the resource is absent or blank.
|
||||
*/
|
||||
private static String classpathVersion(String resource) {
|
||||
try (var in = RuntimeInfoService.class.getClassLoader().getResourceAsStream(resource)) {
|
||||
if (in == null) {
|
||||
return null;
|
||||
}
|
||||
String v = new String(in.readAllBytes(), StandardCharsets.UTF_8).trim();
|
||||
return v.isBlank() ? null : v;
|
||||
} catch (Exception unreadable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.io.IOException;
|
||||
import mx.quest.runway.seo.SeoConfigService;
|
||||
import mx.quest.runway.seo.SiteSeoConfig;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* The tenant console's SEO screen ({@code /__admin/seo}): a site manager edits the site's core social-card
|
||||
* hints, search-engine verification tokens, and a verbatim extra-{@code <head>} block. These are the lean
|
||||
* kernel fields — the platform already emits canonical URLs, {@code hreflang} alternates and {@code robots}
|
||||
* for free, and richer concerns (analytics, consent, GEO) are contributed by plugins. Gated by the grantable
|
||||
* {@code CONFIGURE_SITE} permission; the bound tenancy is taken from the host, never a parameter.
|
||||
*/
|
||||
@Controller
|
||||
public class SeoController {
|
||||
|
||||
private final SiteResolver siteResolver;
|
||||
private final SeoConfigService seo;
|
||||
private final MessageSource messages;
|
||||
|
||||
public SeoController(SiteResolver siteResolver, SeoConfigService seo,
|
||||
@Qualifier("operatorAwareMessageSource") MessageSource messages) {
|
||||
this.siteResolver = siteResolver;
|
||||
this.seo = seo;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
@GetMapping("/__admin/seo")
|
||||
@PreAuthorize("@authz.may('CONFIGURE_SITE')")
|
||||
public String form(Model model) {
|
||||
model.addAttribute("seo", seo.get(currentSiteId()));
|
||||
model.addAttribute("contentTemplate", "operator/admin/seo");
|
||||
model.addAttribute("pageTitleKey", "op.seo.title");
|
||||
return "operator/op-layout";
|
||||
}
|
||||
|
||||
@PostMapping("/__admin/seo")
|
||||
@PreAuthorize("@authz.may('CONFIGURE_SITE')")
|
||||
public String save(@RequestParam(required = false) String ogImage,
|
||||
@RequestParam(required = false) String ogType,
|
||||
@RequestParam(required = false) String twitterCard,
|
||||
@RequestParam(required = false) String twitterSite,
|
||||
@RequestParam(required = false) String googleVerification,
|
||||
@RequestParam(required = false) String bingVerification,
|
||||
@RequestParam(required = false) String extraHead,
|
||||
@RequestParam(defaultValue = "false") boolean documentsNoindex,
|
||||
RedirectAttributes redirect) {
|
||||
try {
|
||||
seo.save(currentSiteId(), new SiteSeoConfig(blankToNull(ogImage), HeadFieldRules.ogType(ogType),
|
||||
HeadFieldRules.twitterCard(twitterCard), blankToNull(twitterSite), blankToNull(googleVerification),
|
||||
blankToNull(bingVerification), blankToNull(extraHead), documentsNoindex));
|
||||
redirect.addFlashAttribute("flash", message("op.seo.saved", "SEO settings saved."));
|
||||
} catch (SiteConfigInput.Invalid invalid) {
|
||||
redirect.addFlashAttribute("error", message(invalid.messageKey(), invalid.getMessage()));
|
||||
} catch (IOException e) {
|
||||
redirect.addFlashAttribute("error", message("op.seo.failed", "Could not save SEO settings."));
|
||||
}
|
||||
return "redirect:/__admin/seo";
|
||||
}
|
||||
|
||||
private String currentSiteId() {
|
||||
return siteResolver.current()
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "no bound tenancy"))
|
||||
.id();
|
||||
}
|
||||
|
||||
private String message(String key, String fallback) {
|
||||
return messages.getMessage(key, null, fallback, LocaleContextHolder.getLocale());
|
||||
}
|
||||
|
||||
private static String blankToNull(String value) {
|
||||
return (value == null || value.isBlank()) ? null : value.strip();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import mx.quest.runway.plugin.PluginSettingDef;
|
||||
import mx.quest.runway.plugin.PluginSettingsService;
|
||||
|
||||
/**
|
||||
* A presentation view of one plugin setting for the (app-level or per-tenant) settings form: the declared type
|
||||
* is normalized to one of five <b>input kinds</b> ({@code text}/{@code area}/{@code secret}/{@code bool}/
|
||||
* {@code select}) so the decoupled template branches on a single value instead of re-deriving the type in SpEL.
|
||||
* A secret's {@code value} is always blank (never echoed); {@code secretSet} says whether one is stored.
|
||||
*
|
||||
* <p>{@code label} and {@code help} are the declared {@code plugin.yml} keys — i18n <b>message keys</b> resolved
|
||||
* (in the template) against the plugin's own bundle; the label defaults to the setting {@code key} when the
|
||||
* plugin declares none, so the form always shows either a resolved human label or the key itself.
|
||||
*
|
||||
* <p>The facts line under a field is composed in the template (so it localizes) from {@code type},
|
||||
* {@code range} and {@code defaultValue}. {@code hint} is the older, English-only one-string summary that the
|
||||
* widget-instance form still shows.
|
||||
*
|
||||
* @param key the setting key — the input's {@code name}
|
||||
* @param label the label message key
|
||||
* @param inputKind {@code text|area|secret|bool|select}
|
||||
* @param value the current value (blank for a secret)
|
||||
* @param secretSet whether a secret is stored
|
||||
* @param hint the English one-line type/range/default summary (widget form)
|
||||
* @param type the normalized declared type
|
||||
* @param range the declared range, or {@code null}
|
||||
* @param defaultValue the declared default as text, or {@code null} (always {@code null} for a secret)
|
||||
* @param help the help-line message key, or {@code null}
|
||||
* @param helpLink the resolved "Learn more" URL, or {@code null}
|
||||
* @param showWhen the key of the boolean switch this field depends on, or {@code null}
|
||||
* @param hidden whether the field starts hidden (its switch is off when the page renders)
|
||||
* @param options the choices of a {@code select} field, in order; empty otherwise
|
||||
* @param platformOff whether a platform-level switch this field needs is off (the form says so)
|
||||
* @param lockedBy where the server itself sets this value, when it does ({@code null}: editable here)
|
||||
* @param lockState for a locked field, what removing the server's line would do, as the suffix of its message key
|
||||
* {@code op.settings.locked.<state>} ({@code same}, {@code default}, {@code differs},
|
||||
* {@code none}); {@code null} when not locked or not known
|
||||
* @param adoptLabel for a locked field the console can take over, the message key of the button that copies the
|
||||
* server's value into the console; {@code null}: no button
|
||||
*/
|
||||
public record SettingField(String key, String label, String inputKind, String value, boolean secretSet,
|
||||
String hint, String type, String range, String defaultValue, String help,
|
||||
String helpLink, String showWhen, boolean hidden, List<SettingOption> options,
|
||||
boolean platformOff, String lockedBy, String lockState, String adoptLabel) {
|
||||
|
||||
public SettingField {
|
||||
options = options == null ? List.of() : List.copyOf(options);
|
||||
}
|
||||
|
||||
/** The form before {@code lockedBy}: an editable field. */
|
||||
public SettingField(String key, String label, String inputKind, String value, boolean secretSet, String hint,
|
||||
String type, String range, String defaultValue, String help, String helpLink,
|
||||
String showWhen, boolean hidden, List<SettingOption> options, boolean platformOff) {
|
||||
this(key, label, inputKind, value, secretSet, hint, type, range, defaultValue, help, helpLink, showWhen,
|
||||
hidden, options, platformOff, null, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* This field locked because the server itself sets it ({@code lockedBy} names where: the host's
|
||||
* {@code application.yml}, an environment variable, a command-line argument). The form shows it disabled with
|
||||
* that origin, and a save leaves it alone: one home per setting, and the host's wins.
|
||||
*/
|
||||
public SettingField lockedBy(String origin) {
|
||||
return lockedBy(origin, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link #lockedBy(String)}, also saying what removing the server's line would do ({@code state}, see
|
||||
* {@link #lockState()}) and, when the console can take the value over, offering the button that copies it
|
||||
* ({@code adoptLabel}, see {@link #adoptLabel()}).
|
||||
*/
|
||||
public SettingField lockedBy(String origin, String state, String adoptLabel) {
|
||||
return new SettingField(key, label, inputKind, value, secretSet, hint, type, range, defaultValue, help,
|
||||
helpLink, showWhen, hidden, options, platformOff, origin, state, adoptLabel);
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a rendered setting (value + secret-set, from either settings engine) to its plain form view: the help
|
||||
* line, but no select, no links, no dependency — the rest of the presentation keys are applied by
|
||||
* {@link SettingsForm}.
|
||||
*/
|
||||
public static SettingField of(PluginSettingsService.RenderedSetting rendered) {
|
||||
PluginSettingDef def = rendered.def();
|
||||
String type = typeOf(def);
|
||||
String kind = switch (type) {
|
||||
case "secret" -> "secret";
|
||||
case "boolean" -> "bool";
|
||||
case "text", "list" -> "area";
|
||||
default -> "text";
|
||||
};
|
||||
String label = (def.label() != null && !def.label().isBlank()) ? def.label() : def.key();
|
||||
String defaultText = def.defaultValue() == null || "secret".equals(type) ? null : String.valueOf(def.defaultValue());
|
||||
String range = def.range() == null || def.range().isBlank() ? null : def.range();
|
||||
return new SettingField(def.key(), label, kind, rendered.value(), rendered.secretSet(), hint(def, type),
|
||||
type, range, defaultText, def.help() == null || def.help().isBlank() ? null : def.help(), null, null,
|
||||
false, List.of(), false);
|
||||
}
|
||||
|
||||
/** This field with the presentation keys applied (see {@link SettingsForm}). */
|
||||
SettingField present(String inputKind, String help, String helpLink, String showWhen, boolean hidden,
|
||||
List<SettingOption> options, boolean platformOff) {
|
||||
return new SettingField(key, label, inputKind, value, secretSet, hint, type, range, defaultValue, help,
|
||||
helpLink, showWhen, hidden, options, platformOff);
|
||||
}
|
||||
|
||||
/** Whether the facts line shows the declared range (a select already lists its choices). */
|
||||
public boolean showsRange() {
|
||||
return range != null && !"select".equals(inputKind);
|
||||
}
|
||||
|
||||
/** Whether the facts line shows the default (a checkbox's default reads as noise; a blank one says nothing). */
|
||||
public boolean showsDefault() {
|
||||
return defaultValue != null && !defaultValue.isBlank() && !"bool".equals(inputKind);
|
||||
}
|
||||
|
||||
static String typeOf(PluginSettingDef def) {
|
||||
return def.type() == null ? "string" : def.type().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private static String hint(PluginSettingDef def, String type) {
|
||||
StringBuilder hint = new StringBuilder(type);
|
||||
if (def.range() != null && !def.range().isBlank()) {
|
||||
hint.append(" · ").append(def.range());
|
||||
}
|
||||
if (def.defaultValue() != null && !"secret".equals(type)) {
|
||||
hint.append(" · default: ").append(def.defaultValue());
|
||||
}
|
||||
return hint.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
/**
|
||||
* One choice of an enum setting rendered as a {@code <select>}.
|
||||
*
|
||||
* @param value the stored value (also the visible text)
|
||||
* @param selected whether it is the current value
|
||||
* @param inherited for the {@code inherit} choice of a field that declares {@code inheritsFrom}: the value it
|
||||
* resolves to right now, shown as "Inherit (currently: …)"; {@code null} otherwise or when the
|
||||
* source cannot be resolved
|
||||
*/
|
||||
public record SettingOption(String value, boolean selected, String inherited) {
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import mx.quest.runway.plugin.SettingValidationException;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Why a settings value was refused, in the operator's language: the field, then the reason from the refusal's
|
||||
* message code ({@code op.config.invalid.*}). A refusal without a code, or a code with no message, falls back to its
|
||||
* English text, so the operator always learns which field and why. Used by the plugin settings forms (app level and
|
||||
* per site) and the widget settings; Server settings resolves its own field labels.
|
||||
*/
|
||||
@Component
|
||||
public class SettingRefusals {
|
||||
|
||||
private final MessageSource messages;
|
||||
|
||||
public SettingRefusals(@Qualifier("operatorAwareMessageSource") MessageSource messages) {
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
/** The refusal for the form's flash: {@code <field>: <reason>}, the reason localized when it carries a code. */
|
||||
public String describe(SettingValidationException invalid) {
|
||||
var locale = LocaleContextHolder.getLocale();
|
||||
String field = invalid.key();
|
||||
String detail = invalid.code() == null ? invalid.getMessage()
|
||||
: messages.getMessage(invalid.code(), invalid.args(), invalid.getMessage(), locale);
|
||||
return messages.getMessage("op.config.kernel.invalid", new Object[] {field, detail}, field + ": " + detail,
|
||||
locale);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 1372 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user