diff --git a/doc/distributed.md b/doc/distributed.md index c8a1522..0d6392b 100644 --- a/doc/distributed.md +++ b/doc/distributed.md @@ -28,7 +28,23 @@ Every instance runs the same image, in one of three modes set by `wombat.mode` ( | `aggregator` | | its database | ✓ | | `worker` | ✓ | the aggregator | | -Outside of the aggregator mode, `POST /api/workers/{worker}/metrics` and `PUT /api/workers/{worker}/environments` answer `404`. +### Features + +The mode also sets which functionalities an instance serves: + +| Feature | Serves | `standalone` | `aggregator` | `worker` | +|-------------|--------------------------------------------------------------------------------|--------------|--------------|----------| +| `ui` | the web UI and its dashboards, `GET /api/app` | ✓ | ✓ | | +| `api-read` | `/api/impact`, `/api/simulation`, `/api/environments`, `/api/modules` | ✓ | ✓ | | +| `api-write` | `POST /api/workers/{worker}/metrics`, `PUT /api/workers/{worker}/environments` | | ✓ | | +| `admin` | `/api/users`, `/api/keys`, `/api/secrets` | ✓ | ✓ | | + +`api-write` only covers what workers push, so only an aggregator serves it. The endpoints managing an instance (users, +API keys, secrets) write too, but fall under `admin`, so that a standalone instance can still be administered. + +The endpoints of a disabled feature are not registered: they answer `404` and are left out of the OpenAPI document +(`/api/openapi`). `/q/*` is never gated: a worker serves nothing else, so it needs no authentication. The features are +resolved once at startup and logged. ## Aggregator diff --git a/src/main/java/tech/illuin/wombat/commons/NodeMode.java b/src/main/java/tech/illuin/wombat/commons/NodeMode.java index 210ad72..f24c2e1 100644 --- a/src/main/java/tech/illuin/wombat/commons/NodeMode.java +++ b/src/main/java/tech/illuin/wombat/commons/NodeMode.java @@ -8,4 +8,10 @@ public enum NodeMode aggregator, /** Samples its environments and pushes the metrics to an aggregator instead of its own database. */ worker, + ; + + public static NodeMode parse(String mode) + { + return NodeMode.valueOf(mode.trim().replace('-', '_').toLowerCase()); + } } diff --git a/src/main/java/tech/illuin/wombat/commons/NodeModeConfigSourceFactory.java b/src/main/java/tech/illuin/wombat/commons/NodeModeConfigSourceFactory.java index 0882df1..ccc2cb1 100644 --- a/src/main/java/tech/illuin/wombat/commons/NodeModeConfigSourceFactory.java +++ b/src/main/java/tech/illuin/wombat/commons/NodeModeConfigSourceFactory.java @@ -18,7 +18,6 @@ @StaticInitSafe public class NodeModeConfigSourceFactory implements ConfigSourceFactory { - public static final String AGGREGATOR_CONFIG_KEY = "_internal.aggregator"; private static final String WORKER_DB_KIND = "sqlite"; private static final String WORKER_JDBC_URL = "jdbc:sqlite::memory:"; @@ -28,11 +27,9 @@ public class NodeModeConfigSourceFactory implements ConfigSourceFactory public Iterable getConfigSources(ConfigSourceContext context) { ConfigValue value = context.getValue("wombat.mode"); - NodeMode mode = value.getValue() == null ? null : parse(value.getValue()); + NodeMode mode = value.getValue() == null ? null : NodeMode.parse(value.getValue()); Map properties = new HashMap<>(); - properties.put(AGGREGATOR_CONFIG_KEY, String.valueOf(mode == NodeMode.aggregator)); - if (mode == NodeMode.worker) { String backend = context.getValue(ACTIVE_BACKEND_CONFIG_KEY).getValue(); @@ -52,9 +49,4 @@ public Iterable getConfigSources(ConfigSourceContext context) Integer.MAX_VALUE )); } - - private static NodeMode parse(String mode) - { - return NodeMode.valueOf(mode.trim().replace('-', '_').toLowerCase()); - } } diff --git a/src/main/java/tech/illuin/wombat/endpoint/AppController.java b/src/main/java/tech/illuin/wombat/endpoint/AppController.java index 034bbff..dcc2eaa 100644 --- a/src/main/java/tech/illuin/wombat/endpoint/AppController.java +++ b/src/main/java/tech/illuin/wombat/endpoint/AppController.java @@ -1,5 +1,6 @@ package tech.illuin.wombat.endpoint; +import io.quarkus.resteasy.reactive.server.EndpointDisabled; import io.quarkus.security.identity.SecurityIdentity; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; @@ -9,15 +10,15 @@ import org.eclipse.microprofile.openapi.annotations.media.Schema; import org.eclipse.microprofile.openapi.annotations.media.SchemaProperty; import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; -import tech.illuin.wombat.commons.WombatProperties; import tech.illuin.wombat.endpoint.response.Response; import tech.illuin.wombat.endpoint.response.Status; +import tech.illuin.wombat.feature.Feature; import tech.illuin.wombat.security.AuthProperties; -import tech.illuin.wombat.endpoint.UIProperties; import java.util.Locale; @Path("api/app") +@EndpointDisabled(name = Feature.Keys.UI, stringValue = "false") public class AppController { private final SecurityIdentity identity; diff --git a/src/main/java/tech/illuin/wombat/endpoint/EnvironmentController.java b/src/main/java/tech/illuin/wombat/endpoint/EnvironmentController.java index 6878606..cddb1d9 100644 --- a/src/main/java/tech/illuin/wombat/endpoint/EnvironmentController.java +++ b/src/main/java/tech/illuin/wombat/endpoint/EnvironmentController.java @@ -1,5 +1,6 @@ package tech.illuin.wombat.endpoint; +import io.quarkus.resteasy.reactive.server.EndpointDisabled; import io.quarkus.security.PermissionsAllowed; import jakarta.ws.rs.*; import jakarta.ws.rs.core.MediaType; @@ -16,6 +17,7 @@ import tech.illuin.wombat.engine.context.persistence.AssetRepository; import tech.illuin.wombat.engine.context.persistence.EnvironmentEntity; import tech.illuin.wombat.engine.context.persistence.EnvironmentRepository; +import tech.illuin.wombat.feature.Feature; import tech.illuin.wombat.security.Permission; import java.util.List; @@ -26,6 +28,7 @@ * this controller exposes the current state and the per-asset change history but never mutates config. */ @Path("api/environments") +@EndpointDisabled(name = Feature.Keys.API_READ, stringValue = "false") @PermissionsAllowed(Permission.Names.API_ENVIRONMENT_READ) public class EnvironmentController { diff --git a/src/main/java/tech/illuin/wombat/endpoint/ImpactController.java b/src/main/java/tech/illuin/wombat/endpoint/ImpactController.java index 8fe0e54..bf3e6c5 100644 --- a/src/main/java/tech/illuin/wombat/endpoint/ImpactController.java +++ b/src/main/java/tech/illuin/wombat/endpoint/ImpactController.java @@ -1,5 +1,6 @@ package tech.illuin.wombat.endpoint; +import io.quarkus.resteasy.reactive.server.EndpointDisabled; import io.quarkus.security.PermissionsAllowed; import jakarta.validation.Valid; import jakarta.ws.rs.*; @@ -21,6 +22,7 @@ import tech.illuin.wombat.engine.impact.timeline.TimelineStep; import tech.illuin.wombat.endpoint.response.Response; import tech.illuin.wombat.endpoint.response.Status; +import tech.illuin.wombat.feature.Feature; import tech.illuin.wombat.security.Permission; import java.time.Duration; @@ -33,6 +35,7 @@ import java.util.stream.Collectors; @Path("api/impact") +@EndpointDisabled(name = Feature.Keys.API_READ, stringValue = "false") @PermissionsAllowed(Permission.Names.API_IMPACT_READ) public class ImpactController { diff --git a/src/main/java/tech/illuin/wombat/endpoint/MetricController.java b/src/main/java/tech/illuin/wombat/endpoint/MetricController.java index 2d3def3..36f9729 100644 --- a/src/main/java/tech/illuin/wombat/endpoint/MetricController.java +++ b/src/main/java/tech/illuin/wombat/endpoint/MetricController.java @@ -14,13 +14,13 @@ import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import tech.illuin.wombat.commons.NodeModeConfigSourceFactory; import tech.illuin.wombat.core.asset.AssetIdentity; import tech.illuin.wombat.core.source.data.MetricData; import tech.illuin.wombat.endpoint.response.Response; import tech.illuin.wombat.endpoint.response.Status; import tech.illuin.wombat.engine.module.registry.ModuleMetadata; import tech.illuin.wombat.engine.module.registry.ModuleRegistry; +import tech.illuin.wombat.feature.Feature; import tech.illuin.wombat.persistence.backend.push.PushBackendConfig; import tech.illuin.wombat.persistence.backend.api.store.MetricSample; import tech.illuin.wombat.persistence.backend.api.store.MetricStoreContainer; @@ -33,15 +33,15 @@ import java.util.Map; /** - * Receives metrics sampled by workers, see {@link tech.illuin.wombat.persistence.backend.push.PushBackendConfig}. Only - * an {@link NodeMode#AGGREGATOR} serves it. Each worker already aggregated its metrics over its sampling window, so they + * Receives metrics sampled by workers, see {@link tech.illuin.wombat.persistence.backend.push.PushBackendConfig}. Served + * with the {@link Feature#API_WRITE}, by an aggregator by default. Each worker already aggregated its metrics over its sampling window, so they * are saved to the database as they are, at the start of the worker's window, for the asset {@code workerId.assetId}, see * {@link WorkerController}. A sample for an asset type without an active module, or of a service family without a store, * is skipped and reported in the response status, under {@code errors}, with the asset id the worker knows; the others * are saved. */ @Path("api/workers/{worker}/metrics") -@EndpointDisabled(name = NodeModeConfigSourceFactory.AGGREGATOR_CONFIG_KEY, stringValue = "false") +@EndpointDisabled(name = Feature.Keys.API_WRITE, stringValue = "false") @PermissionsAllowed(Permission.Names.API_METRIC_WRITE) public class MetricController { diff --git a/src/main/java/tech/illuin/wombat/endpoint/ModuleController.java b/src/main/java/tech/illuin/wombat/endpoint/ModuleController.java index 8281af4..5badea9 100644 --- a/src/main/java/tech/illuin/wombat/endpoint/ModuleController.java +++ b/src/main/java/tech/illuin/wombat/endpoint/ModuleController.java @@ -1,5 +1,6 @@ package tech.illuin.wombat.endpoint; +import io.quarkus.resteasy.reactive.server.EndpointDisabled; import io.quarkus.security.PermissionsAllowed; import jakarta.ws.rs.*; import jakarta.ws.rs.core.MediaType; @@ -13,12 +14,14 @@ import tech.illuin.wombat.engine.module.registry.ModuleMetadata; import tech.illuin.wombat.engine.module.registry.ModuleRegistry; import tech.illuin.wombat.engine.module.registry.schema.AssetSchemaRegistry; +import tech.illuin.wombat.feature.Feature; import tech.illuin.wombat.security.Permission; import com.fasterxml.jackson.databind.JsonNode; import java.util.List; @Path("api/modules") +@EndpointDisabled(name = Feature.Keys.API_READ, stringValue = "false") @PermissionsAllowed(Permission.Names.API_MODULE_READ) public class ModuleController { diff --git a/src/main/java/tech/illuin/wombat/endpoint/SimulationController.java b/src/main/java/tech/illuin/wombat/endpoint/SimulationController.java index d61c53f..b2eac53 100644 --- a/src/main/java/tech/illuin/wombat/endpoint/SimulationController.java +++ b/src/main/java/tech/illuin/wombat/endpoint/SimulationController.java @@ -1,5 +1,6 @@ package tech.illuin.wombat.endpoint; +import io.quarkus.resteasy.reactive.server.EndpointDisabled; import io.quarkus.security.PermissionsAllowed; import jakarta.validation.Valid; import jakarta.ws.rs.*; @@ -16,6 +17,7 @@ import tech.illuin.wombat.core.evaluation.AssetEvaluator; import tech.illuin.wombat.core.evaluation.WombatEvaluationException; import tech.illuin.wombat.endpoint.response.Status; +import tech.illuin.wombat.feature.Feature; import tech.illuin.wombat.security.Permission; import java.util.ArrayList; @@ -25,6 +27,7 @@ import static tech.illuin.wombat.endpoint.SimulationRequest.Scope.IMPACT; @Path("api/simulation") +@EndpointDisabled(name = Feature.Keys.API_READ, stringValue = "false") @PermissionsAllowed(Permission.Names.API_SIMULATION_READ) public class SimulationController { diff --git a/src/main/java/tech/illuin/wombat/endpoint/WorkerController.java b/src/main/java/tech/illuin/wombat/endpoint/WorkerController.java index e920e88..3858c86 100644 --- a/src/main/java/tech/illuin/wombat/endpoint/WorkerController.java +++ b/src/main/java/tech/illuin/wombat/endpoint/WorkerController.java @@ -16,7 +16,6 @@ import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import tech.illuin.wombat.commons.NodeModeConfigSourceFactory; import tech.illuin.wombat.core.asset.Asset; import tech.illuin.wombat.core.asset.Environment; import tech.illuin.wombat.core.source.Monitorable; @@ -28,6 +27,7 @@ import tech.illuin.wombat.engine.module.registry.ModuleMetadata; import tech.illuin.wombat.engine.module.registry.ModuleRegistry; import tech.illuin.wombat.engine.monitor.MonitoredEnvironments; +import tech.illuin.wombat.feature.Feature; import tech.illuin.wombat.persistence.backend.push.PushBackendConfig; import tech.illuin.wombat.security.Permission; @@ -37,10 +37,11 @@ /** * Receives the environments declared by workers, so an aggregator evaluates their assets without declaring them itself. * Each worker owns the assets it declares, see {@link EnvironmentReconciler}, identified as {@code workerId.assetId}, so - * two workers declaring the same asset id declare two assets. Only an {@link NodeMode#AGGREGATOR} serves it. + * two workers declaring the same asset id declare two assets. + * Served with the {@link Feature#API_WRITE}, by an aggregator by default. */ @Path("api/workers") -@EndpointDisabled(name = NodeModeConfigSourceFactory.AGGREGATOR_CONFIG_KEY, stringValue = "false") +@EndpointDisabled(name = Feature.Keys.API_WRITE, stringValue = "false") public class WorkerController { private final EnvironmentReconciler reconciler; diff --git a/src/main/java/tech/illuin/wombat/endpoint/access/ApiKeyController.java b/src/main/java/tech/illuin/wombat/endpoint/access/ApiKeyController.java index 7e4b00e..fa7d9dd 100644 --- a/src/main/java/tech/illuin/wombat/endpoint/access/ApiKeyController.java +++ b/src/main/java/tech/illuin/wombat/endpoint/access/ApiKeyController.java @@ -1,5 +1,6 @@ package tech.illuin.wombat.endpoint.access; +import io.quarkus.resteasy.reactive.server.EndpointDisabled; import io.quarkus.security.PermissionsAllowed; import io.quarkus.security.identity.SecurityIdentity; import jakarta.ws.rs.*; @@ -11,6 +12,7 @@ import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; import tech.illuin.wombat.endpoint.response.Response; import tech.illuin.wombat.endpoint.response.Status; +import tech.illuin.wombat.feature.Feature; import tech.illuin.wombat.security.AuthProperties; import tech.illuin.wombat.security.Caller; import tech.illuin.wombat.security.Permission; @@ -20,6 +22,7 @@ /** Users manage their own API keys; admins also list ({@code ?all=true}) and revoke everyone's. */ @Path("api/keys") +@EndpointDisabled(name = Feature.Keys.ADMIN, stringValue = "false") @PermissionsAllowed(Permission.Names.API_APIKEY_MANAGE) public class ApiKeyController { diff --git a/src/main/java/tech/illuin/wombat/endpoint/access/UserController.java b/src/main/java/tech/illuin/wombat/endpoint/access/UserController.java index d8b8ae0..b18eca3 100644 --- a/src/main/java/tech/illuin/wombat/endpoint/access/UserController.java +++ b/src/main/java/tech/illuin/wombat/endpoint/access/UserController.java @@ -1,5 +1,6 @@ package tech.illuin.wombat.endpoint.access; +import io.quarkus.resteasy.reactive.server.EndpointDisabled; import io.quarkus.security.PermissionsAllowed; import io.quarkus.security.identity.SecurityIdentity; import jakarta.ws.rs.GET; @@ -14,6 +15,7 @@ import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; import tech.illuin.wombat.endpoint.response.Response; import tech.illuin.wombat.endpoint.response.Status; +import tech.illuin.wombat.feature.Feature; import tech.illuin.wombat.security.AuthProperties; import tech.illuin.wombat.security.Caller; import tech.illuin.wombat.security.Permission; @@ -29,6 +31,7 @@ import java.util.stream.Collectors; @Path("api/users") +@EndpointDisabled(name = Feature.Keys.ADMIN, stringValue = "false") @PermissionsAllowed(Permission.Names.API_USER_READ) public class UserController { diff --git a/src/main/java/tech/illuin/wombat/endpoint/access/UserRoleController.java b/src/main/java/tech/illuin/wombat/endpoint/access/UserRoleController.java index 0b4de92..f3395c5 100644 --- a/src/main/java/tech/illuin/wombat/endpoint/access/UserRoleController.java +++ b/src/main/java/tech/illuin/wombat/endpoint/access/UserRoleController.java @@ -1,5 +1,6 @@ package tech.illuin.wombat.endpoint.access; +import io.quarkus.resteasy.reactive.server.EndpointDisabled; import io.quarkus.security.PermissionsAllowed; import io.quarkus.security.identity.SecurityIdentity; import jakarta.ws.rs.*; @@ -10,6 +11,7 @@ import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; import tech.illuin.wombat.endpoint.response.Response; import tech.illuin.wombat.endpoint.response.Status; +import tech.illuin.wombat.feature.Feature; import tech.illuin.wombat.security.AuthProperties; import tech.illuin.wombat.security.Caller; import tech.illuin.wombat.security.Permission; @@ -17,6 +19,7 @@ /** Admin-only: grants and removes Wombat roles held on top of the identity provider's (see the users page). */ @Path("api/users/{userId}/roles/{role}") +@EndpointDisabled(name = Feature.Keys.ADMIN, stringValue = "false") @PermissionsAllowed(Permission.Names.API_USER_MANAGE) public class UserRoleController { diff --git a/src/main/java/tech/illuin/wombat/engine/secret/SecretController.java b/src/main/java/tech/illuin/wombat/engine/secret/SecretController.java index c388654..e841dc4 100644 --- a/src/main/java/tech/illuin/wombat/engine/secret/SecretController.java +++ b/src/main/java/tech/illuin/wombat/engine/secret/SecretController.java @@ -17,13 +17,14 @@ import tech.illuin.wombat.core.secret.SecretWriter; import tech.illuin.wombat.endpoint.response.Response; import tech.illuin.wombat.endpoint.response.Status; +import tech.illuin.wombat.feature.Feature; import tech.illuin.wombat.security.Permission; import java.util.List; @ApplicationScoped @Path("api/secrets") -@EndpointDisabled(name = "wombat.secret.write-mode", stringValue = "DISABLED", disableIfMissing = true) +@EndpointDisabled(name = Feature.Keys.ADMIN_SECRETS, stringValue = "false") @PermissionsAllowed(Permission.Names.API_SECRET_MANAGE) @Blocking public class SecretController diff --git a/src/main/java/tech/illuin/wombat/engine/secret/database/DatabaseSecretController.java b/src/main/java/tech/illuin/wombat/engine/secret/database/DatabaseSecretController.java index d610cf1..e551693 100644 --- a/src/main/java/tech/illuin/wombat/engine/secret/database/DatabaseSecretController.java +++ b/src/main/java/tech/illuin/wombat/engine/secret/database/DatabaseSecretController.java @@ -16,11 +16,12 @@ import tech.illuin.wombat.endpoint.response.Status; import tech.illuin.wombat.engine.secret.database.crypto.SecretRewrap; import tech.illuin.wombat.engine.secret.database.crypto.SecretRewrapService; +import tech.illuin.wombat.feature.Feature; import tech.illuin.wombat.security.Permission; @ApplicationScoped @Path("api/secrets/database") -@EndpointDisabled(name = "wombat.secret.write-mode", stringValue = "DISABLED", disableIfMissing = true) +@EndpointDisabled(name = Feature.Keys.ADMIN_SECRETS, stringValue = "false") @PermissionsAllowed(Permission.Names.API_SECRET_MANAGE) @Blocking public class DatabaseSecretController diff --git a/src/main/java/tech/illuin/wombat/feature/Feature.java b/src/main/java/tech/illuin/wombat/feature/Feature.java new file mode 100644 index 0000000..d3f4a64 --- /dev/null +++ b/src/main/java/tech/illuin/wombat/feature/Feature.java @@ -0,0 +1,57 @@ +package tech.illuin.wombat.feature; + +import tech.illuin.wombat.commons.NodeMode; + +import java.util.function.Predicate; + +public enum Feature +{ + UI("ui", mode -> mode != NodeMode.worker), + API_READ("api-read", mode -> mode != NodeMode.worker), + API_WRITE("api-write", mode -> mode == NodeMode.aggregator), + ADMIN("admin", mode -> mode != NodeMode.worker), + ; + + private final String flag; + private final Predicate enabled; + + Feature(String flag, Predicate enabled) + { + this.flag = flag; + this.enabled = enabled; + } + + public String flag() + { + return this.flag; + } + + public boolean enabledIn(NodeMode mode) + { + return this.enabled.test(mode); + } + + public String configKey() + { + return Keys.PREFIX + this.flag; + } + + /** + * Config keys set to whether a feature is enabled, see {@link FeatureConfigSourceFactory}. Endpoints are gated with + * {@link io.quarkus.resteasy.reactive.server.EndpointDisabled} on them, so a disabled endpoint is neither served nor + * listed in the OpenAPI document. + */ + public static final class Keys + { + static final String PREFIX = "_internal.feature."; + + public static final String UI = PREFIX + "ui"; + public static final String API_READ = PREFIX + "api-read"; + public static final String API_WRITE = PREFIX + "api-write"; + public static final String ADMIN = PREFIX + "admin"; + /** The {@link #ADMIN} feature with a secret write mode: {@code @EndpointDisabled} only takes a single key. */ + public static final String ADMIN_SECRETS = PREFIX + "admin-secrets"; + + private Keys() {} + } +} diff --git a/src/main/java/tech/illuin/wombat/feature/FeatureConfigSourceFactory.java b/src/main/java/tech/illuin/wombat/feature/FeatureConfigSourceFactory.java new file mode 100644 index 0000000..8fe6b37 --- /dev/null +++ b/src/main/java/tech/illuin/wombat/feature/FeatureConfigSourceFactory.java @@ -0,0 +1,41 @@ +package tech.illuin.wombat.feature; + +import io.quarkus.runtime.annotations.StaticInitSafe; +import io.smallrye.config.ConfigSourceContext; +import io.smallrye.config.ConfigSourceFactory; +import io.smallrye.config.PropertiesConfigSource; +import org.eclipse.microprofile.config.spi.ConfigSource; +import tech.illuin.wombat.commons.NodeMode; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** Sets the {@link Feature.Keys} from the node mode, so endpoints are gated before the application starts. */ +@StaticInitSafe +public class FeatureConfigSourceFactory implements ConfigSourceFactory +{ + static final String SECRET_WRITE_MODE = "wombat.secret.write-mode"; + private static final String SECRET_WRITE_DISABLED = "DISABLED"; + + @Override + public Iterable getConfigSources(ConfigSourceContext context) + { + String value = context.getValue("wombat.mode").getValue(); + NodeMode mode = value == null ? NodeMode.standalone : NodeMode.parse(value); + + Map properties = new HashMap<>(); + for (Feature feature : Feature.values()) + properties.put(feature.configKey(), String.valueOf(feature.enabledIn(mode))); + + String writeMode = context.getValue(SECRET_WRITE_MODE).getValue(); + boolean secretsWritable = writeMode != null && !writeMode.equals(SECRET_WRITE_DISABLED); + properties.put(Feature.Keys.ADMIN_SECRETS, String.valueOf(Feature.ADMIN.enabledIn(mode) && secretsWritable)); + + return List.of(new PropertiesConfigSource( + properties, + FeatureConfigSourceFactory.class.getSimpleName(), + Integer.MAX_VALUE + )); + } +} diff --git a/src/main/java/tech/illuin/wombat/feature/FeatureFlags.java b/src/main/java/tech/illuin/wombat/feature/FeatureFlags.java new file mode 100644 index 0000000..5d9e73c --- /dev/null +++ b/src/main/java/tech/illuin/wombat/feature/FeatureFlags.java @@ -0,0 +1,39 @@ +package tech.illuin.wombat.feature; + +import io.quarkus.runtime.StartupEvent; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import tech.illuin.wombat.commons.NodeMode; +import tech.illuin.wombat.commons.WombatProperties; + +import java.util.Arrays; +import java.util.stream.Collectors; + +/** The features served by this instance, set by its mode. REST endpoints are gated on {@link Feature.Keys} instead. */ +@ApplicationScoped +public class FeatureFlags +{ + private static final Logger logger = LoggerFactory.getLogger(FeatureFlags.class); + + private final NodeMode mode; + + public FeatureFlags(WombatProperties wombat) + { + this.mode = wombat.mode(); + } + + public boolean isEnabled(Feature feature) + { + return feature.enabledIn(this.mode); + } + + void logFeatures(@Observes StartupEvent event) + { + String features = Arrays.stream(Feature.values()) + .map(feature -> feature.flag() + "=" + this.isEnabled(feature)) + .collect(Collectors.joining(", ")); + logger.info("Features: {}", features); + } +} diff --git a/src/main/java/tech/illuin/wombat/feature/UiFeatureFilter.java b/src/main/java/tech/illuin/wombat/feature/UiFeatureFilter.java new file mode 100644 index 0000000..f2c0cfb --- /dev/null +++ b/src/main/java/tech/illuin/wombat/feature/UiFeatureFilter.java @@ -0,0 +1,44 @@ +package tech.illuin.wombat.feature; + +import io.quarkus.vertx.http.runtime.filters.Filters; +import io.quarkus.vertx.http.runtime.security.SecurityHandlerPriorities; +import io.vertx.ext.web.RoutingContext; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; + +@ApplicationScoped +public class UiFeatureFilter +{ + static final int PRIORITY = (SecurityHandlerPriorities.CORS + SecurityHandlerPriorities.AUTHENTICATION) / 2; + + private final FeatureFlags features; + + public UiFeatureFilter(FeatureFlags features) + { + this.features = features; + } + + void register(@Observes Filters filters) + { + filters.register(this::filter, PRIORITY); + } + + private void filter(RoutingContext context) + { + if (!isUiPath(context.normalizedPath())) + { + context.next(); + return; + } + + if (this.features.isEnabled(Feature.UI)) + context.next(); + else + context.response().setStatusCode(404).end(); + } + + static boolean isUiPath(String path) + { + return !path.startsWith("/api/") && !path.startsWith("/q/"); + } +} diff --git a/src/main/java/tech/illuin/wombat/ui/SessionController.java b/src/main/java/tech/illuin/wombat/ui/SessionController.java index 1032010..3a59243 100644 --- a/src/main/java/tech/illuin/wombat/ui/SessionController.java +++ b/src/main/java/tech/illuin/wombat/ui/SessionController.java @@ -3,6 +3,7 @@ import io.quarkus.oidc.IdTokenCredential; import io.quarkus.oidc.OidcConfigurationMetadata; import io.quarkus.oidc.OidcSession; +import io.quarkus.resteasy.reactive.server.EndpointDisabled; import io.quarkus.security.identity.SecurityIdentity; import io.smallrye.mutiny.Uni; import jakarta.ws.rs.GET; @@ -12,12 +13,14 @@ import jakarta.ws.rs.core.UriBuilder; import jakarta.ws.rs.core.UriInfo; import org.eclipse.microprofile.config.inject.ConfigProperty; +import tech.illuin.wombat.feature.Feature; import tech.illuin.wombat.security.AuthProperties; import java.net.URI; import java.util.Optional; @Path("logout") +@EndpointDisabled(name = Feature.Keys.UI, stringValue = "false") public class SessionController { /** {@code io.quarkus.oidc.runtime.OidcUtils#CONFIG_METADATA_ATTRIBUTE} */ diff --git a/src/main/resources/META-INF/services/io.smallrye.config.ConfigSourceFactory b/src/main/resources/META-INF/services/io.smallrye.config.ConfigSourceFactory index e4799b4..b4dbb6f 100644 --- a/src/main/resources/META-INF/services/io.smallrye.config.ConfigSourceFactory +++ b/src/main/resources/META-INF/services/io.smallrye.config.ConfigSourceFactory @@ -1 +1,2 @@ tech.illuin.wombat.commons.NodeModeConfigSourceFactory +tech.illuin.wombat.feature.FeatureConfigSourceFactory diff --git a/src/test/java/tech/illuin/wombat/endpoint/MetricControllerStandaloneTest.java b/src/test/java/tech/illuin/wombat/endpoint/MetricControllerStandaloneTest.java index d66501e..9e53439 100644 --- a/src/test/java/tech/illuin/wombat/endpoint/MetricControllerStandaloneTest.java +++ b/src/test/java/tech/illuin/wombat/endpoint/MetricControllerStandaloneTest.java @@ -5,6 +5,8 @@ import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.not; /** Runs in the default standalone mode, which accepts no pushed metrics. */ @QuarkusTest @@ -25,4 +27,15 @@ void declare_isNotServedOutsideOfTheAggregatorMode() .when().put("/api/workers/east/environments") .then().statusCode(404); } + + @Test + void openApi_listsNoWorkerEndpoint_butTheReadApi() + { + given().queryParam("format", "json") + .when().get("/api/openapi") + .then().statusCode(200) + .body("paths", not(hasKey("/api/workers/{worker}/metrics"))) + .body("paths", not(hasKey("/api/workers/{worker}/environments"))) + .body("paths", hasKey("/api/environments")); + } } diff --git a/src/test/java/tech/illuin/wombat/endpoint/MetricControllerTest.java b/src/test/java/tech/illuin/wombat/endpoint/MetricControllerTest.java index 03c5d5d..ca70f25 100644 --- a/src/test/java/tech/illuin/wombat/endpoint/MetricControllerTest.java +++ b/src/test/java/tech/illuin/wombat/endpoint/MetricControllerTest.java @@ -13,6 +13,7 @@ import java.util.List; import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; @@ -35,6 +36,16 @@ void setUp() QuarkusTransaction.requiringNew().run(() -> this.llm.delete("assetId in ?1", List.of("east.pushed-llm", "east.a"))); } + @Test + void openApi_listsTheWorkerEndpoints() + { + given().queryParam("format", "json") + .when().get("/api/openapi") + .then().statusCode(200) + .body("paths", hasKey("/api/workers/{worker}/metrics")) + .body("paths", hasKey("/api/workers/{worker}/environments")); + } + @Test void push_savesEverySample_atTheStartOfTheWorkersWindow() { diff --git a/src/test/java/tech/illuin/wombat/feature/FeatureTest.java b/src/test/java/tech/illuin/wombat/feature/FeatureTest.java new file mode 100644 index 0000000..8d9aa79 --- /dev/null +++ b/src/test/java/tech/illuin/wombat/feature/FeatureTest.java @@ -0,0 +1,47 @@ +package tech.illuin.wombat.feature; + +import org.junit.jupiter.api.Test; +import tech.illuin.wombat.commons.NodeMode; + +import java.util.Arrays; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class FeatureTest +{ + @Test + void standaloneServesTheUiTheReadApiAndTheAdministration() + { + assertEquals(Set.of(Feature.UI, Feature.API_READ, Feature.ADMIN), enabled(NodeMode.standalone)); + } + + @Test + void aggregatorServesEveryFeature() + { + assertEquals(Set.of(Feature.values()), enabled(NodeMode.aggregator)); + } + + @Test + void workerServesNoFeature() + { + assertEquals(Set.of(), enabled(NodeMode.worker)); + } + + @Test + void configKeysMatchTheConstants() + { + assertEquals(Feature.Keys.UI, Feature.UI.configKey()); + assertEquals(Feature.Keys.API_READ, Feature.API_READ.configKey()); + assertEquals(Feature.Keys.API_WRITE, Feature.API_WRITE.configKey()); + assertEquals(Feature.Keys.ADMIN, Feature.ADMIN.configKey()); + } + + private static Set enabled(NodeMode mode) + { + return Arrays.stream(Feature.values()) + .filter(feature -> feature.enabledIn(mode)) + .collect(Collectors.toSet()); + } +} diff --git a/src/test/java/tech/illuin/wombat/feature/WorkerFeaturesTest.java b/src/test/java/tech/illuin/wombat/feature/WorkerFeaturesTest.java new file mode 100644 index 0000000..25eed51 --- /dev/null +++ b/src/test/java/tech/illuin/wombat/feature/WorkerFeaturesTest.java @@ -0,0 +1,95 @@ +package tech.illuin.wombat.feature; + +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import io.restassured.http.ContentType; +import jakarta.inject.Inject; +import org.eclipse.microprofile.config.ConfigProvider; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.anEmptyMap; +import static org.junit.jupiter.api.Assertions.assertFalse; + +/** A worker serves none of the features, only {@code /q/*}. */ +@QuarkusTest +@TestProfile(WorkerFeaturesTest.WorkerProfile.class) +class WorkerFeaturesTest +{ + @Inject + FeatureFlags features; + + @Test + void featuresAreAllDisabled() + { + Arrays.stream(Feature.values()).forEach(feature -> { + assertFalse(this.features.isEnabled(feature), feature.flag()); + assertFalse(ConfigProvider.getConfig().getValue(feature.configKey(), Boolean.class), feature.configKey()); + }); + } + + @Test + void uiIsNotServed() + { + given().when().get("/api/app").then().statusCode(404); + given().redirects().follow(false).when().get("/logout").then().statusCode(404); + } + + @Test + void readApiIsNotServed() + { + given().when().get("/api/environments").then().statusCode(404); + given().when().get("/api/impact/environments").then().statusCode(404); + given().when().get("/api/modules").then().statusCode(404); + } + + @Test + void writeApiIsNotServed() + { + given().contentType(ContentType.JSON).body("[]").when().post("/api/workers/east/metrics").then().statusCode(404); + } + + @Test + void administrationIsNotServed() + { + // Served to anonymous callers without authentication, when the feature is enabled + given().when().get("/api/secrets").then().statusCode(404); + given().when().post("/api/secrets/database/rewrap").then().statusCode(404); + } + + @Test + void openApiListsNoEndpoint() + { + given().queryParam("format", "json").when().get("/api/openapi").then().statusCode(200).body("paths", anEmptyMap()); + } + + @Test + void healthIsServed() + { + given().when().get("/q/health/live").then().statusCode(200); + } + + public static class WorkerProfile implements QuarkusTestProfile + { + @Override + public Map getConfigOverrides() + { + String kek = Base64.getEncoder().encodeToString("01234567890123456789012345678901".getBytes(StandardCharsets.UTF_8)); + return Map.of( + "wombat.mode", "worker", + "wombat.worker.id", "test-worker", + "wombat.worker.aggregator.url", "http://localhost:0", + "wombat.worker.aggregator.api-key", "unused", + "wombat.secret.write-mode", "DATABASE", + "wombat.secret.database.active-kek-id", "test", + "wombat.secret.database.kek.test", kek + ); + } + } +}