diff --git a/README.md b/README.md index 4d3bfff..547cb5c 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,7 @@ VotingPlugin Control is designed to manage and troubleshoot a VotingPlugin netwo - Run guided setup for standalone and proxy/backend networks. - Configure common settings through searchable presets. +- Use Codex CLI or a compatible local stdio MCP client to read and preview a named backend vote site or automatic site-creation policy for up to ten explicit backends through opt-in local MCP, then review and apply it in Control. Separately grant agents scoped topology, Network Doctor checks, proxy routing previews, non-vote transport checks, and typed General Settings, Vote Sites, and Rewards editor previews. Network grants can include coordinated proxy-method previews and guided common settings, VoteLog, and Vote Party v2. See [agent setup](docs/agent-setup.md). - Set up or synchronize Vote Sites while preserving existing rewards and sensitive values. - Configure automatic Vote Site creation. - Configure VoteLogging and retention. diff --git a/docs/agent-setup.md b/docs/agent-setup.md new file mode 100644 index 0000000..b85bbe6 --- /dev/null +++ b/docs/agent-setup.md @@ -0,0 +1,169 @@ +# Configure a vote site with an MCP agent + +VotingPlugin Control provides a local stdio MCP connection. The packaged adapter has been exercised through Codex CLI App Server. Claude Code configuration is documented below, and its runtime compatibility remains unverified. The agent can discover authorized enrolled nodes, read one named vote site on a Bukkit backend, preview a change and track the result. The owner reviews and applies the preview in Control. The backend uses existing managed-file and quick-setup capabilities over the current task protocol. + +## Enable MCP management + +Control disables the agent API by default. Set `CONTROL_MCP_ENABLED=true` on the Control server and restart that service to enable it. The client adapter cannot enable server access. Remove the setting or set it to `false` and restart Control to disable it. See the [management coverage matrix](mcp-network-coverage.md) for supported tools. + +## Connect a client + +1. Install VotingPlugin and enroll the backend as an administrator. Check that Control reports the backend online with both accepted capabilities, `config.files.v1` and `config.quick-setup.v1`. +2. Open **Access → Agent access** in Control. Enter exact node IDs or enter one online proxy ID to grant its enrolled network. Choose the actions and lifetime. Issue the credential and copy it when displayed. Control keeps only its verifier in memory. Grants expire after the chosen lifetime (up to 24 hours), can be revoked immediately, and are invalidated when Control restarts. Revocation prevents new requests and prevents approval of pending previews. A write the owner already approved can still complete. A proxy grant covers the proxy and the enrolled Bukkit nodes in its reported snapshot at issuance. Removing a member or disconnecting the proxy drops current access. A new proxy session or newly reported backend requires a fresh grant. The grant list shows the selected proxy and node count. Control uses the latest reported snapshot for that live proxy session. A heartbeat does not certify the age or accuracy of its topology. +3. Supply `VP_CONTROL_MCP_ORIGIN` and `VP_CONTROL_MCP_TOKEN` in the local client environment. Use a verified HTTPS origin or literal loopback HTTP such as `http://127.0.0.1:8080`. Use the actual Control port. Keep the token out of tool arguments, command-line arguments, agent prompts and checked-in files. +4. Configure the client to launch the Control all-in-one JAR with its `mcp` subcommand. Use an absolute path to the JAR. + +### Codex CLI + +Add the following to your local Codex configuration: + +```toml +[mcp_servers.votingplugin-control] +command = "java" +args = ["-jar", "/absolute/path/votingplugin-control-all.jar", "mcp"] +env_vars = ["VP_CONTROL_MCP_ORIGIN", "VP_CONTROL_MCP_TOKEN"] +``` + +Verify that the server is configured with `codex mcp list`. [Codex MCP configuration](https://learn.chatgpt.com/docs/extend/mcp?surface=cli) + +### Claude Code + +Launch Claude Code with the two environment variables available to the process. Register the stdio command in local scope: + +```sh +claude mcp add --transport stdio --scope local votingplugin-control -- java -jar /absolute/path/votingplugin-control-all.jar mcp +``` + +Check the connection in Claude Code with `/mcp`. [Claude Code MCP configuration](https://code.claude.com/docs/en/mcp) + +## Review and apply + +Ask the agent to choose an authorized node, read the exact site name and prepare a preview. The agent returns a review path on the configured Control origin. You can also open **Activity → Review agent preview**. The review lists the agent grant, target, changed configuration paths and effective proposed values. Control reads the redacted main `VoteSites.yml` through its managed-file service and extracts only the named site's typed values. It discards the full document after extraction. The review shows the preset's proposed display item amount of one and the prior value when present. Control blocks approval if the file has an ambiguous structure or the node's changed paths do not match the revision-bound typed diff. Split VoteSites files are outside this setup flow. The URL must use HTTP(S) and omit userinfo, query and fragment. Only put public vote-site information in the guided fields. + +Approve in the browser to queue the exact preview. The agent can poll the preview operation for the resulting apply ID and then track the apply. A changed file revision, changed session, lost capability, expired grant or incomplete diff requires a new eligible preview. Use these tools for the guided named-site workflow: + +| Tool | Arguments | +|---|---| +| `list_nodes` | Optional `offset`, starting at zero. Returns up to 50 authorized nodes and `nextOffset` when there are more positions to check. | +| `read_setup` | `nodeId`, `name`. | +| `preview_setup` | `nodeId`, `readOperationId`, `options`. Options require `name`, `serviceSite` and `voteUrl` and may include `enabled`, `displayName`, `priority`, `hidden`, `voteDelay` and `material`. | +| `get_operation` | `operationId`. Only operations from the current grant are visible. | + +The guided named-site workflow targets one enrolled backend per operation. Deployment, enrollment, restarts and raw file editing use their existing administrator workflows. + +## Optional topology and diagnostics + +Select **Topology and diagnostics** when issuing a grant to enable `get_topology`, `get_network_health` and +`refresh_node_health`. The other actions do not enable these tools. + +- `get_topology` accepts an optional page offset. It reports only authorized nodes and links. Each proxy row shows when + Control received its last topology snapshot and whether it is less than five minutes old. Links may be truncated. +- `refresh_node_health` queues the existing read-only Network Doctor inspection for one authorized, capable node. + Wait at least two seconds between requests on the same grant. Control coalesces queued or recent observations + and reserves shared inspection capacity for browser and administrator requests. +- `get_network_health` accepts 1–25 exact authorized node IDs. It returns bounded check IDs, statuses, affected node IDs + and restart-required flags. Missing, stale or unsupported evidence remains unknown. A truncated report is incomplete. + +These tools do not expose raw inspection data, player lookup, vote logs, health evidence values, or restart controls. + +## Optional proxy routing + +Select **Read and preview proxy routing** to enable `read_proxy_routing` and `preview_proxy_routing`. The grant +also needs **Track operations** to retrieve READ results and apply status. Routing targets one enrolled proxy with +`config.proxy-routing.v1`. Preview takes the current routing READ ID, an explicit `sendVotesToAllServers` Boolean +and the complete `blockedServers` list. The proxy must report the same revision and exact changes. Apply uses the +browser review and the existing proxy reload and rollback workflow. Long diffs and server identifiers outside +the bounded MCP schema require the Control browser editor. + +## Optional transport check + +Select **Run non-vote transport checks** and **Track operations** to run `check_transport` and retrieve its result. +The request names one authorized proxy and one authorized enrolled backend on a fresh reported link. Both must be +online, and the proxy must negotiate `config.transport-test.v1`. The existing status probe sends no vote and changes +no configuration. Results are scoped to the two node sessions and contain status codes rather than raw probe messages. + +## Optional automatic vote-site creation policy + +Select **Read and preview automatic vote-site creation** and **Track operations** to use `read_site_policy` and +`preview_site_policy` on an authorized Bukkit backend with `config.quick-setup.v1`. Preview takes the operation ID +from the current policy read and an explicit Boolean `enabled`. Control requires the same file revision and a diff +limited to `AutoCreateVoteSites`. The prior value is the backend’s effective value, including its default where applicable. +The operator reviews and applies the change in the browser. + +### Batch proposal + +Grant **Preview automatic vote-site creation across multiple backends** separately to use `preview_site_policy_batch`. +Obtain a current policy read for each target with the same grant. Pass one Boolean `enabled` and 1–10 explicit +`targets`, each with `nodeId` and `readOperationId`. Offline, unsupported, unchanged, or missing targets prevent +queueing the batch. Any failed or stale preview blocks approval for the entire batch. The browser lists each prior +value and revision. An approved apply can still fail on individual nodes. Inspect each node's outcome and rollback +indicator before taking further action. + +## Optional typed General Settings + +Grant **Read and preview typed General Settings** and **Track operations**. Use `read_general_settings` on one +authorized backend or proxy, then pass its current read ID and typed `overrides` to `preview_general_settings`. +The tool selects the fixed file for the target role and uses Control's curated General Settings schema. It returns +available typed fields, while redacted documents stay within Control's existing bounded retention. The node must +return the same current revision, redacted document, and expected changed paths before browser approval. A successful +proxy-file apply reports `restartRequired`; the operator restarts through the existing owner workflow. + + +## Optional typed Vote Sites editor + +Grant **Read and preview typed Vote Sites edits** and **Track operations** to use `read_vote_site_editor` +and `preview_vote_site_editor` on one Bukkit backend with `config.files.v1`. Read an exact `siteKey`, then preview +`ADD`, `EDIT`, or `REMOVE` with that read operation ID. Add requires all nine schema fields; edit requires one or +more changed fields. Remove takes no fields. A site with inline Rewards or unreviewable fields needs the browser editor. +The proposal preserves unrelated sites and sections. Control checks the current redacted source and complete changed +paths against the reviewed proposal before making browser approval available. MCP returns typed fields and a Rewards +presence indicator, and omits raw documents and approval material. + + +## Optional typed Rewards editor + +Grant **Read and preview typed Reward fields** and **Track operations** to use `read_reward_field` +and `preview_reward_field` on one Bukkit backend. Select an exact `siteKey` for an inline reward with +`config.files.v1`, or an exact `rewardName` for an enrolled named reward file with `config.reward-files.v1`. +Select an existing money, chance, player or broadcast message, or named item material or amount field. +Preview uses that read operation ID and one replacement scalar. Control checks the source, revision and exact +changed path before browser approval. Command payloads, reward creation or removal, raw files, and execution +are outside this tool surface. + + +## Coordinated network proposals + +**Read and preview coordinated proxy method changes** and **Track operations** allow +`read_proxy_method` and `preview_proxy_method`. Read each peer using the intended method to select its capability, +then submit the exact proxy and every backend in its fresh reported topology, with one read ID per peer. +The total limit is ten nodes. HTTP requires `config.proxy-method.v2`; legacy methods require +`config.proxy-method.v1`. Backends also require `config.quick-setup.v1`. +Control binds the preview to the exact participants, node sessions and per-target revisions. +The proxy revision covers the method enum. Changes to other proxy transport settings are outside that revision. +Control applies backends first and waits for their durable success before issuing work to the proxy. +Per-peer status distinguishes reported persistence, rollback, and unconfirmed persistence. +Proxy acknowledgement can trigger the existing connector’s runtime replacement, but runtime readiness remains unknown. +A partial rollout requires a fresh review and can leave some backends changed. + + +## Guided common settings, VoteLog, and Vote Party + +Grant the individual preset action and **Track operations** to use `read_guided_settings` and +`preview_guided_settings`. On each explicit backend, read the preset twice with `PRESET` and `PRESENCE` +as the evidence selector. The presence read is an internal masked managed-file read. Its raw document stays in Control. +Preview requires both successful read IDs from the same grant, session and file revision. A mismatched revision requires +both reads again. This matches file revisions from two independent reads. + +A proposal accepts up to four explicit targets. Each must accept the same typed proposal, including the values +retained from its preset read. If the targets need different proposals, preview them separately. An absent key is +shown with its effective default. Approval stays unavailable if an unselected key would be materialized or a node +cannot return the complete expected diff. Each node applies its own revision and reports its result separately. + +- **Common settings** edits reward processing, the extra all-sites check, and the missing-service message setting. + Automatic site creation, fake-vote counting and update checking keep their existing tools. +- **VoteLog** edits enablement and purge retention. Retention is `-1` to disable automatic purging or 1–3650 days. + Database selection and connection settings remain administrator-managed in the browser. A change to logging + enablement requires a VotingPlugin restart, which this tool does not initiate. +- **Vote Party** requires both quick-setup versions and a typed v2 READ with an explicit enabled value. + It edits enablement, threshold, recipient flags and a nonblank broadcast. Legacy v1-only connectors and + inconsistent READ replies are unavailable for this agent workflow. Reward commands remain browser-managed. diff --git a/docs/control-management.md b/docs/control-management.md index fdbbca2..872f475 100644 --- a/docs/control-management.md +++ b/docs/control-management.md @@ -60,6 +60,14 @@ Do not infer support from plugin version strings. Check `acceptedCapabilities` f Deploy the paired VotingPlugin connector change before enabling Control features that require a new capability. During a mixed-version rollout, older nodes remain connected but are excluded from v2 HTTP previews and applies. +## Local agent setup + +The packaged stdio MCP adapter calls Control's scoped agent API. The browser owner issues and revokes +short-lived grants after the administrator sets `CONTROL_MCP_ENABLED=true` on Control. A grant covers exact node IDs or an enrolled proxy network and explicitly selected discovery, read, preview or status actions. +Agent previews bind a successful named-site projection from the redacted managed VoteSites.yml read to the same node session and file revision. Control's +browser-only approval route uses the normal configuration operation engine without returning its approval token. +Existing node capability negotiation and the node task protocol are unchanged. See [agent setup](agent-setup.md). + ## WebUI feature map The dependency-free WebUI is an API client, not a privileged implementation path. Every write below still uses the same diff --git a/docs/mcp-network-coverage.md b/docs/mcp-network-coverage.md new file mode 100644 index 0000000..273dec7 --- /dev/null +++ b/docs/mcp-network-coverage.md @@ -0,0 +1,41 @@ +# MCP coverage for an enrolled proxy network + +A proxy-network grant limits where an agent may use MCP. The negotiated node capability and available typed tools still determine what the agent can do. + +| Existing Control management | Current MCP coverage | Increment after network scoping | +| --- | --- | --- | +| Enrolled identity, liveness, accepted capabilities, proxy/backend presence and topology | Bounded discovery and topology, with proxy snapshot freshness and truncation indicators | Extend large-network link pagination | +| Network Doctor, overview, diagnostics, vote-site health, vote-log summary/search/trace, exact player lookup, site resolution, reward simulation | Network Doctor status and read-only observation refresh with a separate health action | Further diagnostic projections. Player and log data need separate projections and access decisions | +| Bukkit managed YAML, split VoteSites, named reward files, supported file comments, General Settings, typed Vote Sites and Rewards | Typed backend and proxy General Settings, plus a named-site guided preview and typed Vote Sites and scalar Rewards editors | Add typed editor tools using their existing validators, per-target revisions, and bounded results | +| Quick setup v1/v2, standalone/proxy setup, common settings, auto-create, vote logging, Vote Party, rewards and VoteSites sync | Named-site, automatic site creation, common settings, VoteLog and Vote Party v2 | Standalone and proxy-backend setup remain in the browser | +| Proxy routing, fixed proxy YAML, coordinated proxy-method v1/v2 and transport tests | Typed routing and coordinated method proposals with browser approval, plus a non-vote transport check | Add further curated proxy projections | +| Configuration review, apply, status, retries, durable operation history, snapshots and drift | Token-free, per-target status for operations from the same grant. Browser-only Apply. Automatic site policy supports 1–10 explicit backends with immutable revisions | Extend bounded multi-node review and partial-failure reporting to other safe typed operations | +| Plugin staging, artifact source, admin enrollment, credentials and restart coordination | Owner-only workflows | Keep separate owner gates | + +Control already has typed management services in both roles. MCP coverage is currently narrower than those services. Control has no general command, SQL, or filesystem API, and cannot restart a remote process through these tools. An enrolled server on another proxy is outside a grant for the selected proxy unless the administrator explicitly grants that node or the selected proxy reports it as a member at issue time. + +MCP uses an opt-in server boundary, proxy-network grants, bounded discovery and a separately scoped read-only health projection. It makes no connector protocol change. Multi-node previews use bounded explicit targets and immutable revisions, reject unavailable peers, preserve one-time browser approval, and report results per target. + +## Acceptance checklist + +| Surface | State | Acceptance evidence or remaining work | +| --- | --- | --- | +| Server gate and exact or proxy grants | Implemented and tested | Disabled API denial, grant expiry/revoke, proxy session replacement, membership removal and isolated discovery | +| Scoped topology and health | Implemented and tested | MCP frames, aged topology independent of heartbeat, capability gating, bounded inspection admission and projection | +| Single named vote site, proxy routing, automatic site policy | Implemented and tested | Typed prior reads, scoped preview, exact diff and revision, browser-only approval, token-free status | +| Existing non-vote transport probe | Implemented and tested | Both peers in grant; fresh reported relation and current sessions required | +| Batch site policy | Implemented and tested | Explicit unique targets, separate batch permission, revision per backend, all previews successful before approval, per-target terminal results | +| Typed General Settings | Implemented and tested | Both node roles use the curated editor, scoped reads, exact revision and diff, and browser approval. Proxy applies report restart required | +| Typed Vote Sites editor | Implemented and tested | Exact-site read, typed add/edit, and removal for reviewable sites without inline Rewards. Revision, masked source and leaf changes checked before browser approval | +| Typed Rewards editor | Implemented and tested for supported scalar fields | Inline and named-file reward reads, exact same-scope scalar previews and browser approval. Command payloads and whole-scope edits stay in administrator workflows | +| Coordinated proxy method | Implemented and tested | Full fresh topology, exact method capability, per-peer revision, backend-first apply and explicit partial persistence. Runtime readiness and other proxy transport settings are outside the revision contract | +| VoteSites sync | Browser only pending complete diff proof | The connector can replace a destination scalar or list with a mapping while omitting the removed value from its change paths. Agent approval needs revision-matched source and destination shape evidence and a typed source projection | +| Guided common settings, VoteLog and Vote Party v2 | Implemented and tested | Both same-session READs agree on revision, key presence is reviewed, and approval checks every target's exact diff. Up to four explicit targets. Vote Party v1 and database selection stay in the browser | +| Remaining guided presets and fixed proxy-file projections | Browser workflows | Standalone, proxy-backend connection setup and advanced file settings require separately reviewable projections. Proxy-backend HTTP depends on its connector contract | +| Other multi-node proposals, typed retries and snapshot or drift projections | Remaining | Add bounded per-target reads, target-specific proposal data and clear validation/partial failure handling | +| Player and vote-log inspections | Separately gated | Require distinct grants and purpose-specific redacted results before exposure | +| Enrollment, credential administration, artifact staging and restart | Owner-only | Maintain established non-MCP gates | +| Arbitrary command, SQL, filesystem and new connector features | Outside supported scope | Any new protocol requires its own design and decision | +| Client verification | Packaged protocol and Codex App Server exercised | A disposable two-node fixture covered discovery, reads, preview, browser-session review and approval, and mixed terminal apply status. Codex CLI 0.169.0 mediated the MCP calls through App Server with process-local settings. Model-driven interaction, browser rendering and Claude Code runtime remain unverified | + +Completion means supported typed rows are implemented and have permission, revision, failure and client evidence, or have a documented product decision to remain gated. Check the browser and agent boundaries for every write operation. diff --git a/src/main/java/com/bencodez/votingplugin/control/ControlApplication.java b/src/main/java/com/bencodez/votingplugin/control/ControlApplication.java index 0726aed..4945356 100644 --- a/src/main/java/com/bencodez/votingplugin/control/ControlApplication.java +++ b/src/main/java/com/bencodez/votingplugin/control/ControlApplication.java @@ -42,7 +42,10 @@ private ControlApplication() { } public static void main(String[] args) { try { - if (args.length > 0) { + if (args.length == 1 && "mcp".equals(args[0])) { + new com.bencodez.votingplugin.control.mcp.StdioAdapter(System.getenv("VP_CONTROL_MCP_ORIGIN"), + System.getenv("VP_CONTROL_MCP_TOKEN")).run(System.in, System.out); + } else if (args.length > 0) { runOwnerCommand(args); } else { runServer(System.getenv()); @@ -169,7 +172,7 @@ static void runServer(Map environment) throws Exception { configuration.dataDirectory(), clock); ControlHttpServer server = new ControlHttpServer(configuration.address(), registry, identity, credentials, operations, inspections, snapshots, artifacts, deployments, configuration.secureCookies(), - configuration.trustedProxyAddresses(), configuration.launchId()); + configuration.trustedProxyAddresses(), configuration.launchId(), configuration.agentEnabled()); ProcessHandle parent = parentProcess(configuration.parentPid()); CountDownLatch shutdown = new CountDownLatch(1); Runtime.getRuntime().addShutdownHook(new Thread(() -> { @@ -267,7 +270,7 @@ private static ProcessHandle parentProcess(Long parentPid) { record Configuration(InetSocketAddress address, Path dataDirectory, Duration offlineTimeout, int requestTimeoutSeconds, boolean secureCookies, Set trustedProxyAddresses, - String launchId, Long parentPid) { + String launchId, Long parentPid, boolean agentEnabled) { static Configuration from(Map environment) throws IOException { String host = environment.getOrDefault("CONTROL_HOST", "127.0.0.1").trim(); if (host.isEmpty()) { @@ -288,7 +291,8 @@ static Configuration from(Map environment) throws IOException { return new Configuration(new InetSocketAddress(resolved, port), requirePath(environment.getOrDefault("CONTROL_DATA_DIR", "data")), Duration.ofSeconds(offlineSeconds), requestSeconds, secureCookies, trustedProxies, launchId, - parentPid); + parentPid, strictBoolean(environment.getOrDefault("CONTROL_MCP_ENABLED", "false"), + "MCP management")); } private static String launchId(String value) { diff --git a/src/main/java/com/bencodez/votingplugin/control/domain/AgentHealth.java b/src/main/java/com/bencodez/votingplugin/control/domain/AgentHealth.java new file mode 100644 index 0000000..e0b1bae --- /dev/null +++ b/src/main/java/com/bencodez/votingplugin/control/domain/AgentHealth.java @@ -0,0 +1,60 @@ +package com.bencodez.votingplugin.control.domain; + +import com.bencodez.votingplugin.control.protocol.BackendServerIdentity; +import com.bencodez.votingplugin.control.protocol.NodeStatus; +import java.time.Duration; +import java.time.Instant; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +public final class AgentHealth { + private static final Duration TOPOLOGY_MAX_AGE = Duration.ofMinutes(5); + private static final int MAX_CHECKS = 75; + private static final int MAX_LINKS = 6; + + private AgentHealth() { } + + static Node topologyRow(NodeRegistry registry, NodeStatus node, Set allowed, Instant now) { + Instant observedAt = registry.topologyObservedAt(node.nodeId()); + boolean current = fresh(node, observedAt, now); + var links = current ? node.backends().stream().map(BackendServerIdentity::backendId) + .filter(allowed::contains).limit(MAX_LINKS + 1L).toList() : List.of(); + return new Node(node.nodeId(), node.platform(), node.online(), observedAt == null ? null : observedAt.toString(), + current, links.stream().limit(MAX_LINKS).toList(), links.size() > MAX_LINKS); + } + + static Report report(NodeRegistry registry, InspectionOperations inspections, List requested, Instant now) { + Set included = new LinkedHashSet<>(requested); + var nodes = requested.stream().map(registry::find).filter(java.util.Objects::nonNull).toList(); + boolean incomplete = nodes.size() != requested.size() || nodes.stream().anyMatch(node -> + !"BUKKIT".equals(node.platform()) && (!fresh(node, registry.topologyObservedAt(node.nodeId()), now) + || node.backends().stream().anyMatch(backend -> !included.contains(backend.backendId())))); + var projected = nodes.stream().map(node -> new NodeStatus(node.nodeId(), node.sessionId(), node.displayName(), + node.platform(), node.pluginVersion(), node.protocolVersion(), node.advertisedCapabilities(), + node.acceptedCapabilities(), node.detectedPlugins(), + fresh(node, registry.topologyObservedAt(node.nodeId()), now) ? node.backends().stream() + .filter(backend -> included.contains(backend.backendId())).toList() : List.of(), + node.snapshotSequence(), node.lastSeen(), node.lastAuthenticatedUpdate(), node.online())).toList(); + var evidence = inspections.networkEvidence(projected.stream() + .filter(node -> "BUKKIT".equals(node.platform()) + || fresh(node, registry.topologyObservedAt(node.nodeId()), now)).toList()); + var evaluation = NetworkDoctor.evaluate(projected, evidence, now, incomplete); + var checks = evaluation.checks().stream().filter(check -> included.containsAll(check.affectedNodes())) + .limit(MAX_CHECKS).map(check -> new Check(check.id(), check.status().name(), check.affectedNodes().stream().limit(3).toList(), + check.restartRequired())).toList(); + return new Report(now.toString(), evaluation.truncated() || evaluation.checks().size() > checks.size() + || evaluation.checks().stream().anyMatch(check -> check.affectedNodes().size() > 3), checks); + } + + static boolean fresh(NodeStatus node, Instant observed, Instant now) { + return node.online() && node.acceptedCapabilities().contains("presence.snapshot") && observed != null + && !observed.isAfter(now) && observed.isAfter(now.minus(TOPOLOGY_MAX_AGE)); + } + + public record Node(String nodeId, String platform, boolean online, String topologyObservedAt, + boolean topologyFresh, List backendIds, boolean linksTruncated) { } + public record Topology(List items, Integer nextOffset) { } + public record Check(String id, String status, List affectedNodes, boolean restartRequired) { } + public record Report(String generatedAt, boolean truncated, List checks) { } +} diff --git a/src/main/java/com/bencodez/votingplugin/control/domain/AgentOperations.java b/src/main/java/com/bencodez/votingplugin/control/domain/AgentOperations.java new file mode 100644 index 0000000..3f82774 --- /dev/null +++ b/src/main/java/com/bencodez/votingplugin/control/domain/AgentOperations.java @@ -0,0 +1,595 @@ +package com.bencodez.votingplugin.control.domain; + +import com.bencodez.votingplugin.control.protocol.ManagedConfiguration; +import com.bencodez.votingplugin.control.protocol.NodeStatus; +import com.bencodez.votingplugin.control.protocol.ProxyRoutingConfiguration; +import java.util.HashSet; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Instant; +import java.util.Base64; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.Supplier; + +public final class AgentOperations { + private static final Set ACTIONS = Set.of("discover", "read", "preview", "status", "health", "routing", "transport", "site-policy", "site-policy-batch", "general-settings", "vote-sites-editor", "rewards-editor", "proxy-method", "common-settings", "vote-logging", "vote-party"); + private final Map grants = new HashMap<>(); + private final Map healthRefreshes = new HashMap<>(); + private final NodeRegistry registry; + private final ConfigurationOperations operations; + private final Clock clock; + private final InspectionOperations inspections; + private final SecureRandom random = new SecureRandom(); + + public AgentOperations(NodeRegistry registry, ConfigurationOperations operations, Clock clock) { + this(registry, operations, new InspectionOperations(registry, clock), clock); + } + + public AgentOperations(NodeRegistry registry, ConfigurationOperations operations, + InspectionOperations inspections, Clock clock) { + this.registry = registry; + this.operations = operations; + this.inspections = inspections; + this.clock = clock; + } + + public synchronized Issued issue(Issue request) { + grants.values().removeIf(grant -> !clock.instant().isBefore(grant.expiresAt())); + healthRefreshes.keySet().retainAll(grants.keySet()); + if (request == null || request.actions() == null || request.actions().isEmpty() + || request.actions().size() > ACTIONS.size() + || request.actions().stream().anyMatch(action -> action == null || !ACTIONS.contains(action)) + || request.minutes() == null || request.minutes() < 1 || request.minutes() > 1440 + || grants.size() >= 64) throw invalid("Invalid agent grant or grant limit reached"); + NodeStatus root = null; + Set nodes; + if (request.proxyNodeId() != null) { + if (request.nodeIds() != null && !request.nodeIds().isEmpty()) throw invalid("Choose one scope"); + validateNodeId(request.proxyNodeId()); + root = registry.find(request.proxyNodeId()); + if (!onlineProxy(root) || root.snapshotSequence() < 0) { + throw invalid("An online enrolled proxy with a topology snapshot is required"); + } + nodes = new HashSet<>(); + nodes.add(root.nodeId()); + for (var backend : root.backends()) { + NodeStatus member = registry.find(backend.backendId()); + if (member != null && "BUKKIT".equals(member.platform())) nodes.add(member.nodeId()); + } + } else { + if (request.nodeIds() == null || request.nodeIds().isEmpty() || request.nodeIds().size() > 50) { + throw invalid("Node scope requires 1 to 50 exact node IDs"); + } + request.nodeIds().forEach(AgentOperations::validateNodeId); + nodes = Set.copyOf(request.nodeIds()); + } + UUID id = UUID.randomUUID(); + byte[] secret = new byte[32]; + random.nextBytes(secret); + String token = "vp-agent-" + id + "." + Base64.getUrlEncoder().withoutPadding().encodeToString(secret); + Instant expiry = clock.instant().plusSeconds(60L * request.minutes()); + operations.auditAgentGrant(id, root == null ? "ISSUED" : "NETWORK_ISSUED"); + grants.put(id, new Grant(id, nodes.stream().sorted().toList(), Set.copyOf(request.actions()), + expiry, digest(token), root == null ? null : root.nodeId(), root == null ? null : root.sessionId())); + return new Issued(id, token, expiry); + } + + public synchronized List list() { + return grants.values().stream().filter(grant -> clock.instant().isBefore(grant.expiresAt())) + .map(grant -> new GrantView(grant.id(), grant.proxyNodeId() == null ? grant.nodes() : List.of(), + grant.actions(), grant.expiresAt(), grant.proxyNodeId(), grant.nodes().size())).toList(); + } + + public synchronized void revoke(UUID id) { + operations.auditAgentGrant(id, "REVOKED"); + operations.revokeCoordinatedAgent(id); + grants.remove(id); + healthRefreshes.remove(id); + } + + public synchronized void requireAccess(String token, String action) { + authorize(token, action); + } + + public synchronized Object discover(String token, Discovery request) { + Grant grant = authorize(token, "discover"); + int offset = request.offset() == null ? 0 : request.offset(); + if (offset < 0 || offset > grant.nodes().size()) throw invalid("Invalid discovery offset"); + int end = Math.min(offset + 50, grant.nodes().size()); + return withStableScope(grant, () -> { + Set permitted = permittedNodes(grant); + if (permitted.isEmpty()) return Map.of("items", List.of()); + var results = new LinkedHashMap(); + results.put("items", grant.nodes().subList(offset, end).stream().filter(permitted::contains) + .map(registry::find).filter(java.util.Objects::nonNull) + .map(node -> Map.of("nodeId", node.nodeId(), "platform", node.platform(), "online", node.online(), + "acceptedCapabilities", node.acceptedCapabilities())).toList()); + if (end < grant.nodes().size()) results.put("nextOffset", end); + return results; + }); + } + + public synchronized AgentHealth.Topology topology(String token, Discovery request) { + Grant grant = authorize(token, "health"); + return registry.withStableTopology(() -> { + List scope = grant.nodes(); + int offset = request.offset() == null ? 0 : request.offset(); + if (offset < 0 || offset > scope.size()) throw invalid("Invalid topology offset"); + int end = Math.min(offset + 50, scope.size()); + Set allowed = permittedNodes(grant); + var rows = scope.subList(offset, end).stream().filter(allowed::contains).map(registry::find) + .filter(java.util.Objects::nonNull).map(node -> AgentHealth.topologyRow( + registry, node, allowed, clock.instant())).toList(); + return new AgentHealth.Topology(rows, !allowed.isEmpty() && end < scope.size() ? end : null); + }); + } + + public synchronized AgentHealth.Report health(String token, HealthRequest request) { + Grant grant = authorize(token, "health"); + List requested = request.nodeIds(); + if (requested == null || requested.isEmpty() || requested.size() > 25 + || new HashSet<>(requested).size() != requested.size()) { + throw invalid("Health requires 1 to 25 distinct target nodes"); + } + requested.forEach(AgentOperations::validateNodeId); + synchronized (inspections) { + return registry.withStableTopology(() -> { + Set allowed = permittedNodes(grant); + if (!allowed.containsAll(requested)) denied(); + return AgentHealth.report(registry, inspections, requested, clock.instant()); + }); + } + } + + public synchronized Map refreshHealth(String token, RefreshHealth request) { + Grant grant = authorize(token, "health"); + synchronized (inspections) { + return registry.withStableTopology(() -> { + requireNode(grant, request.nodeId()); + Instant now = clock.instant(); + Instant last = healthRefreshes.get(grant.id()); + if (last != null && now.isBefore(last.plusSeconds(2))) throw invalid("Wait before refreshing another node"); + var observation = inspections.refreshAgentHealth(request.nodeId()); + healthRefreshes.put(grant.id(), now); + return Map.of("nodeId", request.nodeId(), "state", observation.state()); + }); + } + } + + public synchronized void requireGuidedAccess(String token) { + if (authorize(token, null).actions().stream().noneMatch(Set.of("common-settings", "vote-logging", "vote-party")::contains)) { + denied(); + } + } + + public synchronized Object readGuided(String token, GuidedRead request) { + var preset = GuidedSettings.select(request.preset()); + Grant grant = authorize(token, preset.action()); + if (!List.of("PRESET", "PRESENCE").contains(request.evidence() == null ? "" : request.evidence())) { + throw invalid("Choose PRESET or PRESENCE evidence"); + } + return withStableTopology(() -> { + requireNode(grant, request.nodeId()); + return project(operations.readAgentGuided(grant.id(), request.nodeId(), preset, "PRESENCE".equals(request.evidence()))); + }); + } + + public synchronized Object previewGuided(String token, GuidedPreview request) { + var preset = GuidedSettings.select(request.preset()); + Grant grant = authorize(token, preset.action()); + if (request.targets() == null || request.targets().isEmpty() || request.targets().size() > 4) { + throw invalid("Supply 1 to 4 explicit targets"); + } + return withStableTopology(() -> { + Map reads = new LinkedHashMap<>(); + for (var target : request.targets()) { + if (target == null) throw invalid("Invalid target"); + requireNode(grant, target.nodeId()); + var ids = new GuidedReadIds(parseId(target.presetReadId()), parseId(target.presenceReadId())); + if (reads.putIfAbsent(target.nodeId(), ids) != null) throw invalid("Targets must be unique"); + } + return project(operations.previewAgentGuided(grant.id(), preset, reads, request.overrides())); + }); + } + + public synchronized Object readProxyMethod(String token, ProxyMethodRead request) { + Grant grant = authorize(token, "proxy-method"); + return withStableTopology(() -> { + requireNode(grant, request.nodeId()); + return project(operations.readAgentProxyMethod(grant.id(), request.nodeId(), request.method())); + }); + } + + public synchronized Object previewProxyMethod(String token, ProxyMethodPreview request) { + Grant grant = authorize(token, "proxy-method"); + if (request.targets() == null || request.targets().size() < 2 + || request.targets().size() > ConfigurationOperations.MAX_AGENT_TARGETS) { + throw invalid("An explicit proxy and 2 to 10 targets are required"); + } + return withStableTopology(() -> { + requireNode(grant, request.proxyNodeId()); + Map reads = new LinkedHashMap<>(); + for (SitePolicyTarget target : request.targets()) { + if (target == null) throw invalid("Invalid target"); + requireNode(grant, target.nodeId()); + if (reads.putIfAbsent(target.nodeId(), parseId(target.readOperationId())) != null) { + throw invalid("Targets must be unique"); + } + } + return project(operations.previewAgentProxyMethod(grant.id(), request.proxyNodeId(), request.method(), + reads, grant.expiresAt())); + }); + } + + public synchronized Object readReward(String token, RewardRead request) { + Grant grant = authorize(token, "rewards-editor"); + return withStableTopology(() -> { + requireNode(grant, request.nodeId()); + return project(operations.readAgentReward(grant.id(), request.nodeId(), + AgentSetup.RewardField.select(request.siteKey(), request.rewardName(), request.field()))); + }); + } + + public synchronized Object previewReward(String token, RewardPreview request) { + Grant grant = authorize(token, "rewards-editor"); + return withStableTopology(() -> { + requireNode(grant, request.nodeId()); + return project(operations.previewAgentReward(grant.id(), request.nodeId(), + parseId(request.readOperationId()), request.value())); + }); + } + + public synchronized Object readVoteSitesEditor(String token, VoteSitesEditorRead request) { + Grant grant = authorize(token, "vote-sites-editor"); + return withStableTopology(() -> { + requireNode(grant, request.nodeId()); + return project(operations.readAgentVoteSitesEditor(grant.id(), request.nodeId(), request.siteKey())); + }); + } + + public synchronized Object previewVoteSitesEditor(String token, VoteSitesEditorPreview request) { + Grant grant = authorize(token, "vote-sites-editor"); + return withStableTopology(() -> { + requireNode(grant, request.nodeId()); + return project(operations.previewAgentVoteSitesEditor(grant.id(), request.nodeId(), + parseId(request.readOperationId()), request.action(), request.siteKey(), request.fields())); + }); + } + + public synchronized Object readGeneralSettings(String token, GeneralSettingsRead request) { + Grant grant = authorize(token, "general-settings"); + return withStableTopology(() -> { + requireNode(grant, request.nodeId()); + return project(operations.readAgentGeneralSettings(grant.id(), request.nodeId())); + }); + } + + public synchronized Object previewGeneralSettings(String token, GeneralSettingsPreview request) { + Grant grant = authorize(token, "general-settings"); + return withStableTopology(() -> { + requireNode(grant, request.nodeId()); + return project(operations.previewAgentGeneralSettings(grant.id(), request.nodeId(), + parseId(request.readOperationId()), request.overrides())); + }); + } + + public synchronized Object readSitePolicy(String token, SitePolicyRead request) { + Grant grant = authorize(token, "site-policy"); + return withStableScope(grant, () -> { + requireNode(grant, request.nodeId()); + return project(operations.createAgentSitePolicy(grant.id(), request.nodeId(), null, null)); + }); + } + + public synchronized Object previewSitePolicy(String token, SitePolicyPreview request) { + Grant grant = authorize(token, "site-policy"); + if (request.enabled() == null) throw invalid("An explicit enabled value is required"); + return withStableScope(grant, () -> { + requireNode(grant, request.nodeId()); + return project(operations.createAgentSitePolicy(grant.id(), request.nodeId(), request.enabled(), + parseId(request.readOperationId()))); + }); + } + + public synchronized Object previewSitePolicyBatch(String token, SitePolicyBatch request) { + Grant grant = authorize(token, "site-policy-batch"); + if (request.enabled() == null || request.targets() == null || request.targets().isEmpty() + || request.targets().size() > ConfigurationOperations.MAX_AGENT_TARGETS) { + throw invalid("Explicit site policy and 1 to 10 targets are required"); + } + return withStableTopology(() -> { + Map reads = new LinkedHashMap<>(); + for (SitePolicyTarget target : request.targets()) { + if (target == null) throw invalid("Invalid target"); + requireNode(grant, target.nodeId()); + if (reads.putIfAbsent(target.nodeId(), parseId(target.readOperationId())) != null) { + throw invalid("Targets must be unique"); + } + } + return project(operations.createAgentSitePolicyBatch(grant.id(), reads, request.enabled())); + }); + } + + public synchronized Object checkTransport(String token, TransportRequest request) { + Grant grant = authorize(token, "transport"); + return withStableTopology(() -> { + requireNode(grant, request.proxyNodeId()); + requireNode(grant, request.backendNodeId()); + return project(operations.createAgentTransportCheck(grant.id(), request.proxyNodeId(), request.backendNodeId())); + }); + } + + public synchronized Object readRouting(String token, RoutingRead request) { + Grant grant = authorize(token, "routing"); + return withStableScope(grant, () -> { + requireNode(grant, request.nodeId()); + return project(operations.createAgentProxyRouting(grant.id(), request.nodeId(), null, null)); + }); + } + + public synchronized Object previewRouting(String token, RoutingPreview request) { + Grant grant = authorize(token, "routing"); + if (request.sendVotesToAllServers() == null || request.blockedServers() == null + || request.blockedServers().size() > 256) throw invalid("Complete routing settings are required"); + request.blockedServers().forEach(AgentOperations::validateNodeId); + var proposal = new ProxyRoutingConfiguration(request.sendVotesToAllServers(), request.blockedServers()); + return withStableScope(grant, () -> { + requireNode(grant, request.nodeId()); + return project(operations.createAgentProxyRouting(grant.id(), request.nodeId(), proposal, + parseId(request.readOperationId()))); + }); + } + + public synchronized Object read(String token, Read request) { + Grant grant = authorize(token, "read"); + siteName(request.name()); + return withStableScope(grant, () -> { + requireNode(grant, request.nodeId()); + return project(operations.createAgentVoteSite(grant.id(), request.nodeId(), + configuration(Map.of("name", request.name())), null)); + }); + } + + public synchronized Object preview(String token, Preview request) { + Grant grant = authorize(token, "preview"); + if (request.readOperationId() == null || request.options() == null) throw invalid("Read and options are required"); + Site site = request.options(); + siteName(site.name()); + Map values = new LinkedHashMap<>(); + values.put("name", site.name()); + values.put("serviceSite", bounded(site.serviceSite(), 200)); + if (!AgentSetup.safeUrl(site.voteUrl())) throw invalid("Invalid vote URL"); + values.put("voteUrl", site.voteUrl()); + put(values, "displayName", site.displayName()); + put(values, "voteDelay", site.voteDelay()); + put(values, "material", site.material()); + if (site.enabled() != null) values.put("enabled", site.enabled().toString()); + if (site.hidden() != null) values.put("hidden", site.hidden().toString()); + if (site.priority() != null) { + if (site.priority() < 0 || site.priority() > 100) throw invalid("Invalid priority"); + values.put("priority", site.priority().toString()); + } + return withStableScope(grant, () -> { + requireNode(grant, request.nodeId()); + return project(operations.createAgentVoteSite(grant.id(), request.nodeId(), configuration(values), + parseId(request.readOperationId()))); + }); + } + + public synchronized Object status(String token, UUID id) { + Grant grant = authorize(token, "status"); + return withStableTopology(() -> { + var operation = operations.getAgentOperation(grant.id(), id); + operation.nodeStates().keySet().forEach(nodeId -> requireNode(grant, nodeId)); + var projected = project(operation, operations.agentVoteLogRestartTargets(grant.id(), id)); + if (ManagedConfiguration.COMMUNICATION_TEST.equals(operation.configuration().preset())) { + String backend = operation.configuration().options().get("server"); + requireNode(grant, backend); + if (!operations.agentTransportCurrent(grant.id(), id)) { + String proxy = operation.nodeStates().keySet().iterator().next(); + projected.put("state", "COMPLETED_WITH_ERRORS"); + projected.put("nodes", Map.of(proxy, "COMPLETE")); + projected.put("results", Map.of(proxy, + Map.of("code", "TARGET_CHANGED", "success", false, "reloaded", false, "rolledBack", false))); + } + return projected; + } + if ("READ".equals(operation.type()) && "SUCCEEDED".equals(operation.state())) { + projected.put("values", operations.agentReadValues(grant.id(), id)); + } + if ("PREVIEW".equals(operation.type())) { + UUID applyId = operations.agentApplyId(grant.id(), id); + if (applyId != null) projected.put("applyOperationId", applyId); + } + return projected; + }); + } + + public synchronized ConfigurationOperations.OperationView approve(UUID id) { + var preview = operations.get(id); + Grant grant = grants.get(preview.agentId()); + if (grant == null || !clock.instant().isBefore(grant.expiresAt())) throw invalid("Agent grant is unavailable"); + return withStableTopology(() -> { + if (!permittedNodes(grant).containsAll(preview.nodeStates().keySet())) { + throw invalid("Preview target is outside the current grant scope"); + } + return operations.approveAgentPreview(id); + }); + } + + private T withStableScope(Grant grant, Supplier action) { + return grant.proxyNodeId() == null ? action.get() : withStableTopology(action); + } + + private T withStableTopology(Supplier action) { + // Configuration claims and completions already acquire the operations + // monitor before entering the registry. Preserve that order. + synchronized (operations) { + return registry.withStableTopology(action); + } + } + + private static Map project(ConfigurationOperations.OperationView operation) { + return project(operation, Set.of()); + } + + private static Map project(ConfigurationOperations.OperationView operation, Set restartTargets) { + Map result = new LinkedHashMap<>(); + result.put("operationId", operation.operationId()); + result.put("type", operation.type()); + result.put("state", operation.state()); + result.put("nodes", operation.nodeStates()); + result.put("browserReviewReady", operation.browserReviewReady()); + if ("PREVIEW".equals(operation.type())) result.put("reviewPath", "/#agent-review/" + operation.operationId()); + Map results = new LinkedHashMap<>(); + operation.results().forEach((node, value) -> { + Map item = new LinkedHashMap<>(); + item.put("code", value.code()); + item.put("success", value.success()); + item.put("rolledBack", value.rolledBack()); + item.put("reloaded", value.reloaded()); + if ("APPLY".equals(operation.type()) && value.success() && operation.configuration() != null + && ("bungeeconfig.yml".equals(operation.configuration().fileName()) + || restartTargets.contains(node))) { + item.put("restartRequired", true); + } + if ("APPLY".equals(operation.type()) && ManagedConfiguration.PROXY_METHOD.equals(operation.configuration().preset())) { + item.put("persistence", value.success() ? "REPORTED_PERSISTED" + : value.rolledBack() ? "ROLLED_BACK" : "UNCONFIRMED"); + if (value.success() && !value.reloaded()) { + item.put("restartAfterAcknowledgement", true); + item.put("runtimeReadiness", "UNKNOWN"); + } + } + results.put(node, item); + }); + result.put("results", results); + return result; + } + + private Grant authorize(String token, String action) { + if (token == null || !token.matches("vp-agent-[0-9a-f-]{36}\\.[A-Za-z0-9_-]{43}")) return denied(); + UUID id; + try { + id = UUID.fromString(token.substring(9, 45)); + } catch (IllegalArgumentException e) { + return denied(); + } + Grant grant = grants.get(id); + if (grant == null || !clock.instant().isBefore(grant.expiresAt()) + || !MessageDigest.isEqual(grant.verifier(), digest(token)) || action != null && !grant.actions().contains(action)) { + return denied(); + } + return grant; + } + + private static Grant denied() { + throw new SecurityException("Agent access denied"); + } + + private void requireNode(Grant grant, String id) { + validateNodeId(id); + if (!permittedNodes(grant).contains(id)) denied(); + } + + private Set permittedNodes(Grant grant) { + if (grant.proxyNodeId() == null) return Set.copyOf(grant.nodes()); + NodeStatus proxy = registry.find(grant.proxyNodeId()); + if (!onlineProxy(proxy) || !grant.proxySession().equals(proxy.sessionId())) return Set.of(); + Set current = new HashSet<>(); + current.add(proxy.nodeId()); + for (var backend : proxy.backends()) { + NodeStatus member = registry.find(backend.backendId()); + if (member != null && "BUKKIT".equals(member.platform())) current.add(member.nodeId()); + } + current.retainAll(grant.nodes()); + return current; + } + + private static boolean onlineProxy(NodeStatus node) { + return node != null && node.online() && Set.of("BUNGEECORD", "VELOCITY").contains(node.platform()); + } + + public static UUID parseId(String id) { + if (id == null || !id.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) { + throw invalid("Invalid operation ID"); + } + return UUID.fromString(id); + } + + private static void validateNodeId(String id) { + if (id == null || !id.matches("[A-Za-z0-9][A-Za-z0-9._-]{0,63}")) throw invalid("Invalid node ID"); + } + + private static void siteName(String name) { + if (name == null || !name.matches("[A-Za-z0-9_-]{1,64}")) throw invalid("Invalid site name"); + } + + private static String bounded(String value, int max) { + if (value == null || value.isBlank() || value.length() > max + || value.codePoints().anyMatch(Character::isISOControl)) throw invalid("Invalid site option"); + return value; + } + + private static void put(Map values, String field, String value) { + if (value != null) values.put(field, bounded(value, 200)); + } + + private static ManagedConfiguration configuration(Map options) { + return new ManagedConfiguration("quick-setup", null, List.of(), null, null, "vote-site", options); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static byte[] digest(String token) { + try { + return MessageDigest.getInstance("SHA-256").digest(token.getBytes(StandardCharsets.US_ASCII)); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + public record Issue(List nodeIds, List actions, Integer minutes, String proxyNodeId) { } + public record Discovery(Integer offset) { } + public record HealthRequest(List nodeIds) { } + public record RefreshHealth(String nodeId) { } + public record GuidedRead(String nodeId, String preset, String evidence) { } + public record GuidedTarget(String nodeId, String presetReadId, String presenceReadId) { } + public record GuidedPreview(String preset, List targets, Map overrides) { } + record GuidedReadIds(UUID typed, UUID presence) { } + public record ProxyMethodRead(String nodeId, String method) { } + public record ProxyMethodPreview(String proxyNodeId, String method, List targets) { } + public record RewardRead(String nodeId, String siteKey, String rewardName, String field) { } + public record RewardPreview(String nodeId, String readOperationId, Object value) { } + public record VoteSitesEditorRead(String nodeId, String siteKey) { } + public record VoteSitesEditorPreview(String nodeId, String siteKey, String readOperationId, + String action, Map fields) { } + public record GeneralSettingsRead(String nodeId) { } + public record GeneralSettingsPreview(String nodeId, String readOperationId, Map overrides) { } + public record SitePolicyRead(String nodeId) { } + public record SitePolicyPreview(String nodeId, String readOperationId, Boolean enabled) { } + public record SitePolicyTarget(String nodeId, String readOperationId) { } + public record SitePolicyBatch(List targets, Boolean enabled) { } + public record RoutingRead(String nodeId) { } + public record TransportRequest(String proxyNodeId, String backendNodeId) { } + public record RoutingPreview(String nodeId, String readOperationId, Boolean sendVotesToAllServers, + List blockedServers) { } + public record Issued(UUID id, String token, Instant expiresAt) { } + public record GrantView(UUID id, List nodeIds, Set actions, Instant expiresAt, String proxyNodeId, int nodeCount) { } + public record Read(String nodeId, String name) { } + public record Preview(String nodeId, String readOperationId, Site options) { } + public record Site(String name, String serviceSite, String voteUrl, Boolean enabled, String displayName, + Integer priority, Boolean hidden, String voteDelay, String material) { } + private record Grant(UUID id, List nodes, Set actions, Instant expiresAt, byte[] verifier, + String proxyNodeId, UUID proxySession) { } +} diff --git a/src/main/java/com/bencodez/votingplugin/control/domain/AgentSetup.java b/src/main/java/com/bencodez/votingplugin/control/domain/AgentSetup.java new file mode 100644 index 0000000..5cac4d5 --- /dev/null +++ b/src/main/java/com/bencodez/votingplugin/control/domain/AgentSetup.java @@ -0,0 +1,214 @@ +package com.bencodez.votingplugin.control.domain; + +import com.bencodez.votingplugin.control.protocol.ManagedConfiguration; +import java.net.URI; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.HashSet; +import java.util.Set; + +final class AgentSetup { + private static final Map DEFAULTS = Map.of( + "enabled", "true", "priority", "5", "hidden", "false", "voteDelay", "24h", "material", "DIAMOND"); + private static final Map PATHS = Map.of( + "enabled", "Enabled", "displayName", "Name", "priority", "Priority", "hidden", "Hidden", + "serviceSite", "ServiceSite", "voteUrl", "VoteURL", "voteDelay", "VoteDelay", + "material", "DisplayItem.Material", "displayItem.amount", "DisplayItem.Amount"); + + private AgentSetup() { } + + static ManagedConfiguration proposal(Map current, ManagedConfiguration requested) { + Map values = new LinkedHashMap<>(DEFAULTS); + String name = requested.options().get("name"); + values.put("displayName", name); + if (current == null || !name.equals(current.get("name")) + || !List.of("true", "false").contains(current.getOrDefault("exists", ""))) { + throw new IllegalArgumentException("Read did not return the requested site"); + } + if ("true".equals(current.get("exists"))) { + for (String field : List.of("enabled", "priority", "hidden", "voteDelay", "material", "displayName")) { + String value = current.get(field); + if (value != null) values.put(field, value); + } + } + values.putAll(requested.options()); + if (!safeUrl(values.get("voteUrl"))) throw new IllegalArgumentException("Use a public-facing HTTP(S) vote URL without credentials, query or fragment"); + return new ManagedConfiguration("quick-setup", null, List.of(), null, null, "vote-site", values); + } + + static Map readSite(String name, ManagedConfiguration document) { + if (document == null || document.content() == null) throw new IllegalArgumentException("Missing VoteSites read"); + Map values = new LinkedHashMap<>(); + values.put("name", name); + var sites = VoteSitesDocument.inventory(document.content()).sites(); + var site = sites.stream().filter(item -> name.equalsIgnoreCase(item.key())).findFirst().orElse(null); + values.put("exists", Boolean.toString(site != null)); + if (site == null) return Map.copyOf(values); + if (!site.editable() || !name.equals(site.key())) throw new IllegalArgumentException("Ambiguous site name"); + PATHS.forEach((key, path) -> { + var field = site.fields().get(path); + if (field.status() == VoteSitesDocument.Status.UNSUPPORTED) { + throw new IllegalArgumentException("Site contains unsupported field"); + } + if (field.status() == VoteSitesDocument.Status.AVAILABLE) { + String value = field.value().toString(); + if ("voteUrl".equals(key) && !safeUrl(value)) { + throw new IllegalArgumentException("Existing site URL cannot be reviewed"); + } + values.put(key, value); + } + }); + return Map.copyOf(values); + } + + static boolean safeUrl(String value) { + if (value == null || value.length() > 500) return false; + try { + URI uri = URI.create(value); + return ("https".equalsIgnoreCase(uri.getScheme()) || "http".equalsIgnoreCase(uri.getScheme())) + && uri.getHost() != null && uri.getRawUserInfo() == null + && uri.getRawQuery() == null && uri.getRawFragment() == null; + } catch (IllegalArgumentException e) { + return false; + } + } + + static Map editorSiteValues(String key, String document) { + var values = new LinkedHashMap(); + values.put("siteKey", key); + var site = VoteSitesDocument.inventory(document).sites().stream() + .filter(row -> key.equalsIgnoreCase(row.key())).findFirst().orElse(null); + values.put("exists", Boolean.toString(site != null)); + if (site == null) return Map.copyOf(values); + if (!site.editable() || !key.equals(site.key())) throw new IllegalArgumentException("Ambiguous site"); + site.fields().forEach((path, field) -> { + if (field.status() == VoteSitesDocument.Status.UNSUPPORTED + || field.status() == VoteSitesDocument.Status.AVAILABLE + && "VoteURL".equals(path) && !safeUrl(field.value().toString())) { + throw new IllegalArgumentException("Site contains a field that cannot be reviewed safely"); + } + if (field.status() == VoteSitesDocument.Status.AVAILABLE) values.put(path, field.value().toString()); + }); + values.put("rewardsConfigured", Boolean.toString(site.rewardsConfigured())); + return Map.copyOf(values); + } + + record RewardField(String file, String scope, String field) { + static RewardField select(String siteKey, String rewardName, String field) { + if ((siteKey == null) == (rewardName == null) || field == null + || !field.matches("Money|Chance|Messages[.](Player|Broadcast)|Items[.][A-Za-z0-9_-]{1,64}[.](Material|Amount)")) { + throw new IllegalArgumentException("Select one reward and one supported scalar field"); + } + if (siteKey != null && siteKey.matches("[A-Za-z0-9_-]{1,64}")) { + return new RewardField("VoteSites.yml", "VoteSites." + siteKey + ".Rewards", field); + } + if (rewardName != null && rewardName.matches("[A-Za-z0-9][A-Za-z0-9_-]{0,99}")) { + return new RewardField("Rewards/" + rewardName + ".yml", "$", field); + } + throw new IllegalArgumentException("Invalid reward selector"); + } + + String changePath() { + return "$".equals(scope) ? field : scope + "." + field; + } + + Map values(String content) { + var selected = RewardsDocument.inventory(content, file).stream() + .filter(row -> scope.equals(row.path())).findFirst().orElseThrow(IllegalArgumentException::new); + if (!selected.editable() || !List.of("PRESENT", "EMPTY").contains(selected.status())) { + throw new IllegalArgumentException("Reward scope is missing or unsupported"); + } + Object value = selected.fields().get(field); + if (!(value instanceof String text) || text.length() > 500) { + throw new IllegalArgumentException("Reward field must already be a reviewable scalar"); + } + return Map.of("rewardField", field, "rewardValue", text); + } + } + + static Map settingsValues(Map fields) { + Map values = new LinkedHashMap<>(); + fields.forEach((key, field) -> { + if (field.status() == GeneralSettingsDocument.Status.AVAILABLE) values.put(key, field.value().toString()); + }); + return Map.copyOf(values); + } + + static String documentDigest(String document) { + try { + return java.util.HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256") + .digest(document.getBytes(java.nio.charset.StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException failure) { + throw new IllegalStateException(failure); + } + } + + static ManagedConfiguration proxyMethod(String method) { + var configuration = new ManagedConfiguration(ManagedConfiguration.QUICK_SETUP, null, List.of(), null, null, + ManagedConfiguration.PROXY_METHOD, method == null ? Map.of() : Map.of("method", method)); + configuration.validateProposal(); + return configuration; + } + + static Map proxyMethodValues(ManagedConfiguration configuration, boolean backend) { + if (configuration == null) throw new IllegalArgumentException("Missing method read"); + String method = configuration.options().get("method"); + proxyMethod(method); + if (!backend) return Map.of("method", method); + String enabled = configuration.options().getOrDefault("useBungeecord", ""); + if (!List.of("true", "false").contains(enabled)) throw new IllegalArgumentException("Missing backend state"); + return Map.of("method", method, "useBungeecord", enabled); + } + + static Set proxyMethodChanges(Map before, String method) { + var paths = new HashSet(); + boolean backend = before.containsKey("useBungeecord"); + if (!before.get("method").equals(method)) { + paths.add(backend ? "changed BungeeMethod" : "change proxy method from " + before.get("method") + " to " + method); + } + if (backend && !"true".equals(before.get("useBungeecord"))) paths.add("changed UseBungeecord"); + return Set.copyOf(paths); + } + + static final String SITE_POLICY = "auto-create-vote-sites"; + + static ManagedConfiguration sitePolicy(Boolean enabled) { + return new ManagedConfiguration(ManagedConfiguration.QUICK_SETUP, null, List.of(), null, null, SITE_POLICY, + enabled == null ? Map.of() : Map.of("enabled", enabled.toString())); + } + + static Map sitePolicyValues(ManagedConfiguration configuration) { + if (configuration == null || !SITE_POLICY.equals(configuration.preset()) + || !Set.of(Map.of("enabled", "true"), Map.of("enabled", "false")).contains(configuration.options())) { + throw new IllegalArgumentException("Expected the explicit vote-site creation policy"); + } + return configuration.options(); + } + + static Map routingValues(ManagedConfiguration configuration) { + if (configuration == null || !ManagedConfiguration.PROXY_ROUTING.equals(configuration.domain()) + || configuration.blockedServers().stream().anyMatch(id -> !id.matches("[A-Za-z0-9][A-Za-z0-9._-]{0,63}"))) { + throw new IllegalArgumentException("Routing must contain exact server identifiers"); + } + return Map.of("sendVotesToAllServers", configuration.sendVotesToAllServers().toString(), + "blockedServers", configuration.blockedServers().toString()); + } + + static List routingChanges(Map before, Map after) { + return List.of("sendVotesToAllServers", "blockedServers").stream() + .filter(key -> !before.get(key).equals(after.get(key))) + .map(key -> key + ": " + before.get(key) + " -> " + after.get(key)).toList(); + } + + static boolean reviewableChanges(ManagedConfiguration configuration, Map before, + List changes) { + String root = "changed VoteSites." + configuration.options().get("name") + "."; + var expected = new HashSet(); + PATHS.forEach((key, path) -> { + String next = "displayItem.amount".equals(key) ? "1" : configuration.options().get(key); + if (!next.equals(before.get(key))) expected.add(root + path); + }); + return changes.size() == expected.size() && expected.equals(new HashSet<>(changes)); + } +} diff --git a/src/main/java/com/bencodez/votingplugin/control/domain/ConfigurationOperations.java b/src/main/java/com/bencodez/votingplugin/control/domain/ConfigurationOperations.java index 7d0af56..fe08df6 100644 --- a/src/main/java/com/bencodez/votingplugin/control/domain/ConfigurationOperations.java +++ b/src/main/java/com/bencodez/votingplugin/control/domain/ConfigurationOperations.java @@ -26,6 +26,7 @@ /** In-memory, bounded coordinator for outbound node configuration tasks. */ public final class ConfigurationOperations implements AutoCloseable { + public static final int MAX_AGENT_TARGETS = 10; public static final String CAPABILITY = "config.proxy-routing.v1"; public static final String FILE_CAPABILITY = "config.files.v1"; public static final String PROXY_FILE_CAPABILITY = "config.proxy-files.v1"; @@ -38,6 +39,8 @@ public final class ConfigurationOperations implements AutoCloseable { private static final int MAX_OPERATIONS = 1000; private static final int MAX_LISTED_OPERATIONS = 100; private static final int MAX_FILE_OPERATIONS = 16; + private static final int MAX_AGENT_FILE_READS_AND_PREVIEWS = 6; + private static final int MAX_AGENT_FILE_APPLIES = 4; static final int MAX_RETAINED_CHANGE_BYTES = 256 * 1024; static final int MAX_RETAINED_MESSAGE_BYTES = 256 * 1024; static final int MAX_RETAINED_FILE_BYTES = 8 * 1024 * 1024; @@ -105,7 +108,452 @@ public synchronized OperationView createPreview(List nodeIds, ManagedCon Base64.getUrlEncoder().withoutPadding().encodeToString(token)); } + public synchronized void auditAgentGrant(UUID agent, String outcome) { + audit.append("AGENT_GRANT", agent, null, outcome); + } + + public synchronized OperationView createAgentVoteSite(UUID agent, String nodeId, + ManagedConfiguration configuration, UUID readId) { + prune(); + if (!"vote-site".equals(configuration.preset())) throw invalid("Unsupported agent preset"); + configuration.validateProposal(); + ValidatedTargets targets = validateTargets(List.of(nodeId), QUICK_SETUP_CAPABILITY); + if (!"BUKKIT".equalsIgnoreCase(targets.platforms().get(nodeId))) throw invalid("Agent setup requires a Bukkit node"); + validateConfigurationTargets(targets, configuration); + requireAgentCapacity(agent); + if (readId == null) { + var selector = ManagedConfiguration.file("VoteSites.yml", null); + ValidatedTargets readTargets = validateTargets(List.of(nodeId), FILE_CAPABILITY); + validateConfigurationTargets(readTargets, selector); + OperationView view = create("READ", readTargets, selector, null, Map.of(), agent); + operations.get(view.operationId()).agentSite = configuration.options().get("name"); + return view; + } + StoredOperation read = agentOperation(agent, readId); + ConfigurationTaskResult result = read.results.get(nodeId); + if (!"READ".equals(read.type) || result == null || !result.success() + || !Objects.equals(read.agentSite, configuration.options().get("name")) + || !Objects.equals(result.sessionId(), targets.sessions().get(nodeId))) { + throw invalid("A successful READ of this site in the current node session is required"); + } + ManagedConfiguration proposal = AgentSetup.proposal(read.agentBefore, configuration); + byte[] token = new byte[32]; + random.nextBytes(token); + OperationView preview = create("PREVIEW", targets, proposal, + Base64.getUrlEncoder().withoutPadding().encodeToString(token), + Map.of(nodeId, result.revision()), agent); + operations.get(preview.operationId()).agentBefore = read.agentBefore; + return preview; + } + + synchronized OperationView createAgentProxyRouting(UUID agent, String nodeId, + ProxyRoutingConfiguration routing, UUID readId) { + prune(); + requireAgentCapacity(agent); + ValidatedTargets targets = validateTargets(List.of(nodeId), CAPABILITY); + if ("BUKKIT".equals(targets.platforms().get(nodeId))) throw invalid("Routing requires a proxy node"); + if (readId == null) { + return create("READ", targets, ManagedConfiguration.proxy(new ProxyRoutingConfiguration(false, List.of())), + null, Map.of(), agent); + } + StoredOperation read = agentOperation(agent, readId); + ConfigurationTaskResult result = read.results.get(nodeId); + if (!"READ".equals(read.type) || !ManagedConfiguration.PROXY_ROUTING.equals(read.configuration.domain()) + || result == null || !result.success() + || !Objects.equals(result.sessionId(), targets.sessions().get(nodeId))) { + throw invalid("A successful routing READ in the current proxy session is required"); + } + Map requested = AgentSetup.routingValues(ManagedConfiguration.proxy(routing)); + if (AgentSetup.routingChanges(read.agentBefore, requested).stream().anyMatch(change -> change.length() > 500)) { + throw invalid("Routing diff exceeds the review limit"); + } + byte[] token = new byte[32]; + random.nextBytes(token); + OperationView preview = create("PREVIEW", targets, ManagedConfiguration.proxy(routing), + Base64.getUrlEncoder().withoutPadding().encodeToString(token), + Map.of(nodeId, result.revision()), agent); + operations.get(preview.operationId()).agentBefore = read.agentBefore; + return preview; + } + + synchronized OperationView createAgentSitePolicy(UUID agent, String nodeId, Boolean enabled, UUID readId) { + prune(); + requireAgentCapacity(agent); + ValidatedTargets targets = validateTargets(List.of(nodeId), QUICK_SETUP_CAPABILITY); + if (!"BUKKIT".equals(targets.platforms().get(nodeId))) throw invalid("Site policy requires a Bukkit backend"); + var configuration = AgentSetup.sitePolicy(enabled); + if (readId == null) return create("READ", targets, configuration, null, Map.of(), agent); + return createAgentSitePolicyBatch(agent, Map.of(nodeId, readId), enabled); + } + + synchronized OperationView createAgentSitePolicyBatch(UUID agent, Map readIds, boolean enabled) { + prune(); + requireAgentCapacity(agent); + if (readIds.isEmpty() || readIds.size() > MAX_AGENT_TARGETS) throw invalid("Invalid agent target count"); + var configuration = AgentSetup.sitePolicy(enabled); + ValidatedTargets targets = validateTargets(new ArrayList<>(readIds.keySet()), QUICK_SETUP_CAPABILITY); + Map revisions = new LinkedHashMap<>(); + Map> before = new LinkedHashMap<>(); + for (var target : readIds.entrySet()) { + String nodeId = target.getKey(); + StoredOperation read = agentOperation(agent, target.getValue()); + ConfigurationTaskResult current = read.results.get(nodeId); + if (!"BUKKIT".equals(targets.platforms().get(nodeId)) || !"READ".equals(read.type) + || !AgentSetup.SITE_POLICY.equals(read.configuration.preset()) || current == null + || !current.success() || !Objects.equals(current.sessionId(), targets.sessions().get(nodeId))) { + throw new ValidationException("READ_REQUIRED", "A current successful site-policy read is required", List.of(nodeId)); + } + if (read.agentBefore.equals(configuration.options())) { + throw new ValidationException("NO_CHANGE", "Site policy is already set to the requested value", List.of(nodeId)); + } + before.put(nodeId, read.agentBefore); + revisions.put(nodeId, current.revision()); + } + byte[] token = new byte[32]; + random.nextBytes(token); + OperationView preview = create("PREVIEW", targets, configuration, + Base64.getUrlEncoder().withoutPadding().encodeToString(token), revisions, agent); + StoredOperation stored = operations.get(preview.operationId()); + stored.agentBeforeByNode = Map.copyOf(before); + if (before.size() == 1) stored.agentBefore = before.values().iterator().next(); + return preview; + } + + synchronized OperationView createAgentTransportCheck(UUID agent, String proxyId, String backendId) { + prune(); + requireAgentCapacity(agent); + ValidatedTargets targets = validateTargets(List.of(proxyId), TRANSPORT_TEST_CAPABILITY); + NodeStatus proxy = registry.find(proxyId); + NodeStatus backend = registry.find(backendId); + if (!transportPeerAvailable(proxy, backend)) { + throw new ValidationException("NODE_UNAVAILABLE", "A live, reported proxy/backend relationship is required", List.of()); + } + var selector = new ManagedConfiguration(ManagedConfiguration.QUICK_SETUP, null, List.of(), null, null, + ManagedConfiguration.COMMUNICATION_TEST, Map.of("server", backendId)); + selector.validateProposal(); + OperationView view = create("READ", targets, selector, null, Map.of(), agent); + operations.get(view.operationId()).agentPeerSession = backend.sessionId(); + return view; + } + + private boolean transportPeerAvailable(NodeStatus proxy, NodeStatus backend) { + return proxy != null && !"BUKKIT".equals(proxy.platform()) && backend != null && backend.online() + && "BUKKIT".equals(backend.platform()) + && AgentHealth.fresh(proxy, registry.topologyObservedAt(proxy.nodeId()), clock.instant()) + && proxy.backends().stream().anyMatch(member -> member.backendId().equals(backend.nodeId())); + } + + synchronized boolean agentTransportCurrent(UUID agent, UUID id) { + StoredOperation operation = agentOperation(agent, id); + String proxyId = operation.states.keySet().iterator().next(); + NodeStatus proxy = registry.find(proxyId); + return proxy != null && Objects.equals(operation.targetSessions.get(proxyId), proxy.sessionId()) + && agentTransportPeerCurrent(operation, proxy); + } + + private boolean agentTransportPeerCurrent(StoredOperation operation, NodeStatus proxy) { + NodeStatus backend = registry.find(operation.configuration.options().get("server")); + return transportPeerAvailable(proxy, backend) && operation.agentPeerSession.equals(backend.sessionId()); + } + + synchronized OperationView readAgentGeneralSettings(UUID agent, String nodeId) { + prune(); + requireAgentCapacity(agent); + NodeStatus node = registry.find(nodeId); + if (node == null) throw new ValidationException("NODE_UNAVAILABLE", "Node cannot accept configuration operations", List.of(nodeId)); + var profile = "BUKKIT".equals(node.platform()) ? GeneralSettingsDocument.Profile.BACKEND : GeneralSettingsDocument.Profile.PROXY; + var selector = ManagedConfiguration.file(GeneralSettingsDocument.fileName(profile), null); + ValidatedTargets targets = validateTargets(List.of(nodeId), selector.capability()); + validateConfigurationTargets(targets, selector); + OperationView read = create("READ", targets, selector, null, Map.of(), agent); + operations.get(read.operationId()).agentGeneralSettings = true; + return read; + } + + synchronized OperationView previewAgentGeneralSettings(UUID agent, String nodeId, UUID readId, + Map overrides) { + prune(); + requireAgentCapacity(agent); + if (!agentOperation(agent, readId).agentGeneralSettings) throw invalid("A General Settings read is required"); + return createGeneralSettingsPreview(readId, nodeId, overrides, agent); + } + + synchronized OperationView readAgentVoteSitesEditor(UUID agent, String nodeId, String siteKey) { + prune(); + requireAgentCapacity(agent); + if (siteKey == null || !siteKey.matches("[A-Za-z0-9_-]{1,64}")) throw invalid("Invalid site key"); + var selector = ManagedConfiguration.file("VoteSites.yml", null); + ValidatedTargets targets = validateTargets(List.of(nodeId), selector.capability()); + validateConfigurationTargets(targets, selector); + OperationView read = create("READ", targets, selector, null, Map.of(), agent); + operations.get(read.operationId()).agentEditorSite = siteKey; + return read; + } + + synchronized OperationView previewAgentVoteSitesEditor(UUID agent, String nodeId, UUID readId, + String action, String siteKey, Map fields) { + prune(); + requireAgentCapacity(agent); + if (siteKey == null || !siteKey.equals(agentOperation(agent, readId).agentEditorSite)) { + throw invalid("A current editor read of this exact site is required"); + } + return createVoteSitesPreview(readId, nodeId, action, siteKey, fields, agent); + } + + synchronized OperationView readAgentReward(UUID agent, String nodeId, AgentSetup.RewardField field) { + prune(); + requireAgentCapacity(agent); + var selector = ManagedConfiguration.file(field.file(), null); + ValidatedTargets targets = validateTargets(List.of(nodeId), selector.capability()); + validateConfigurationTargets(targets, selector); + var read = create("READ", targets, selector, null, Map.of(), agent); + operations.get(read.operationId()).agentRewardField = field; + return read; + } + + synchronized OperationView previewAgentReward(UUID agent, String nodeId, UUID readId, Object value) { + prune(); + requireAgentCapacity(agent); + var field = agentOperation(agent, readId).agentRewardField; + if (field == null) throw invalid("A typed reward field read is required"); + return createRewardsPreview(readId, nodeId, field.file(), field.scope(), "SET_SCALAR", + field.field(), value, agent, field); + } + + synchronized OperationView readAgentGuided(UUID agent, String nodeId, GuidedSettings preset, boolean presence) { + prune(); + requireAgentCapacity(agent); + var targets = validateTargets(List.of(nodeId), preset.capability()); + validateTargets(List.of(nodeId), QUICK_SETUP_CAPABILITY); + validateTargets(List.of(nodeId), FILE_CAPABILITY); + if (!"BUKKIT".equals(targets.platforms().get(nodeId))) throw invalid("Guided setup requires a Bukkit backend"); + var selector = presence ? ManagedConfiguration.file(preset.file(), null) : preset.selector(); + var read = create("READ", targets, selector, null, Map.of(), agent); + operations.get(read.operationId()).agentGuidedRead = preset; + return read; + } + + synchronized OperationView previewAgentGuided(UUID agent, GuidedSettings preset, + Map ids, Map overrides) { + prune(); + requireAgentCapacity(agent); + var targets = validateTargets(new ArrayList<>(ids.keySet()), preset.capability()); + validateTargets(new ArrayList<>(ids.keySet()), QUICK_SETUP_CAPABILITY); + var revisions = new LinkedHashMap(); + var before = new LinkedHashMap>(); + Map proposal = null; + var after = new LinkedHashMap(); + for (var entry : ids.entrySet()) { + String nodeId = entry.getKey(); + var read = agentOperation(agent, entry.getValue().typed()); + var fileRead = agentOperation(agent, entry.getValue().presence()); + var typed = read.results.get(nodeId); + if (!"READ".equals(read.type) || read.agentGuidedRead != preset + || !ManagedConfiguration.QUICK_SETUP.equals(read.configuration.domain()) + || fileRead.agentGuidedRead != preset || typed == null || !typed.success() + || !Objects.equals(typed.sessionId(), targets.sessions().get(nodeId))) { + throw new ValidationException("READ_REQUIRED", "Read the typed preset and managed file again", List.of(nodeId)); + } + var snapshot = fileSnapshot(fileRead.id, nodeId, preset.file()); + if (!snapshot.sessionId().equals(typed.sessionId()) || !snapshot.revision().equals(typed.revision())) { + throw new ValidationException("STALE_REVISION", "Preset and file must agree on revision; repeat both reads", List.of(nodeId)); + } + GuidedSettings.Evidence evidence; + try { + evidence = preset.evidence(snapshot.configuration().content(), read.agentBefore, overrides); + } catch (IllegalArgumentException unsupported) { + throw new ValidationException("GUIDED_EVIDENCE_UNAVAILABLE", unsupported.getMessage(), List.of(nodeId)); + } + if (evidence.after().isEmpty()) throw new ValidationException("NO_CHANGE", "No reviewable change on this target", List.of(nodeId)); + if (proposal != null && !proposal.equals(evidence.options())) { + throw new ValidationException("INCOMPATIBLE_TARGETS", "Use separate previews for differing retained settings", List.of(nodeId)); + } + proposal = evidence.options(); + before.put(nodeId, evidence.before()); + after.putAll(evidence.after()); + revisions.put(nodeId, snapshot.revision()); + } + byte[] token = new byte[32]; + random.nextBytes(token); + var preview = create("PREVIEW", targets, preset.configuration(proposal), + Base64.getUrlEncoder().withoutPadding().encodeToString(token), revisions, agent); + var stored = operations.get(preview.operationId()); + stored.agentGuidedPreview = preset; + stored.agentBeforeByNode = Map.copyOf(before); + if (before.size() == 1) stored.agentBefore = before.values().iterator().next(); + stored.agentAfter = Map.copyOf(after); + return preview; + } + + synchronized OperationView readAgentProxyMethod(UUID agent, String nodeId, String method) { + prune(); + requireAgentCapacity(agent); + var proposal = AgentSetup.proxyMethod(method); + var targets = validateTargets(List.of(nodeId), proposal.capability()); + boolean backend = "BUKKIT".equals(targets.platforms().get(nodeId)); + ManagedConfiguration selector = proposal; + if (backend) { + validateTargets(List.of(nodeId), QUICK_SETUP_CAPABILITY); + selector = new ManagedConfiguration(ManagedConfiguration.QUICK_SETUP, null, List.of(), null, null, + "proxy-backend", "HTTP".equals(method) ? Map.of("method", "HTTP") : Map.of()); + } + var read = create("READ", targets, selector, null, Map.of(), agent); + operations.get(read.operationId()).agentMethodReadCapability = proposal.capability(); + return read; + } + + synchronized OperationView previewAgentProxyMethod(UUID agent, String proxyId, String method, + Map readIds, Instant expiresAt) { + prune(); + requireAgentCapacity(agent); + if (readIds.size() < 2 || readIds.size() > MAX_AGENT_TARGETS) throw invalid("Invalid proxy method target count"); + var configuration = AgentSetup.proxyMethod(method); + var targets = validateTargets(new ArrayList<>(readIds.keySet()), configuration.capability()); + validateProxyMethodTargets(targets, configuration); + var scope = new AgentProxyRollout(proxyId, expiresAt); + if (!currentProxyRollout(scope, configuration, targets.sessions(), targets.platforms())) { + throw invalid("A fresh, complete, available proxy network is required"); + } + Map revisions = new LinkedHashMap<>(); + Map> before = new LinkedHashMap<>(); + boolean anyChange = false; + for (var entry : readIds.entrySet()) { + String node = entry.getKey(); + var read = agentOperation(agent, entry.getValue()); + var result = read.results.get(node); + if (!"READ".equals(read.type) || !configuration.capability().equals(read.agentMethodReadCapability) + || result == null || !result.success() || !Objects.equals(result.sessionId(), targets.sessions().get(node))) { + throw new ValidationException("READ_REQUIRED", "A current method read for the required capability is needed", List.of(node)); + } + anyChange |= !AgentSetup.proxyMethodChanges(read.agentBefore, method).isEmpty(); + before.put(node, read.agentBefore); + revisions.put(node, result.revision()); + } + if (!anyChange) throw invalid("The requested proxy method is already set on every target"); + byte[] token = new byte[32]; + random.nextBytes(token); + var view = create("PREVIEW", targets, configuration, Base64.getUrlEncoder().withoutPadding().encodeToString(token), + revisions, agent); + var stored = operations.get(view.operationId()); + stored.agentBeforeByNode = Map.copyOf(before); + stored.agentProxyRollout = scope; + return view; + } + + private boolean currentProxyRollout(AgentProxyRollout scope, ManagedConfiguration configuration, + Map sessions, Map platforms) { + if (scope.revoked || !clock.instant().isBefore(scope.expiresAt)) return false; + NodeStatus proxy = registry.find(scope.proxyId); + if (proxy == null || "BUKKIT".equals(proxy.platform()) + || !AgentHealth.fresh(proxy, registry.topologyObservedAt(scope.proxyId), clock.instant()) + || proxy.backends().size() + 1 != sessions.size() || !sessions.containsKey(scope.proxyId) + || proxy.backends().stream().anyMatch(row -> !sessions.containsKey(row.backendId()))) return false; + for (var entry : sessions.entrySet()) { + NodeStatus node = registry.find(entry.getKey()); + if (node == null || !node.online() || !entry.getValue().equals(node.sessionId()) + || !platforms.get(entry.getKey()).equals(node.platform()) + || !node.acceptedCapabilities().contains(configuration.capability()) + || "BUKKIT".equals(node.platform()) && !node.acceptedCapabilities().contains(QUICK_SETUP_CAPABILITY)) { + return false; + } + } + return true; + } + + synchronized void revokeCoordinatedAgent(UUID agent) { + operations.values().stream().filter(operation -> agent.equals(operation.agent)) + .map(operation -> operation.agentProxyRollout).filter(Objects::nonNull) + .forEach(scope -> scope.revoked = true); + } + + private boolean currentAgentCoordination(StoredOperation operation) { + return operation.agentProxyRollout == null || currentProxyRollout(operation.agentProxyRollout, + operation.configuration, operation.targetSessions, operation.targetPlatforms); + } + + private boolean cancelChangedAgentCoordination(StoredOperation operation) { + if (currentAgentCoordination(operation)) return false; + for (var entry : operation.states.entrySet()) { + Instant leased = operation.leasedAt.get(entry.getKey()); + if ("QUEUED".equals(entry.getValue()) || "IN_PROGRESS".equals(entry.getValue()) && leased != null + && !clock.instant().isBefore(leased.plus(LEASE))) { + automaticCancellation(operation, entry.getKey(), operation.targetSessions.get(entry.getKey()), + "TARGET_CHANGED", "Coordinated operation scope, grant or topology changed", "TARGET_CHANGED"); + } + } + operation.approvalUsed = true; + return true; + } + + private void requireAgentCapacity(UUID agent) { + var retained = operations.values().stream().filter(op -> agent.equals(op.agent)).toList(); + if (retained.size() >= 48 || retained.stream().filter(op -> !op.complete()).count() >= 4) { + throw invalid("Agent operation limit reached"); + } + } + + public synchronized AgentReview getAgentReview(UUID id) { + prune(); + StoredOperation operation = operations.get(id); + if (operation == null || operation.agent == null || !"PREVIEW".equals(operation.type)) { + throw new ValidationException("OPERATION_NOT_FOUND", "Agent preview was not found", List.of()); + } + return new AgentReview(view(operation), operation.agentBefore, operation.agentBeforeByNode, operation.agentAfter); + } + + public synchronized OperationView getAgentOperation(UUID agent, UUID id) { + prune(); + return view(agentOperation(agent, id)); + } + + synchronized Map agentReadValues(UUID agent, UUID id) { + StoredOperation operation = agentOperation(agent, id); + return "READ".equals(operation.type) ? operation.agentBefore : Map.of(); + } + + synchronized Set agentVoteLogRestartTargets(UUID agent, UUID id) { + return agentOperation(agent, id).agentVoteLogRestartTargets; + } + + synchronized UUID agentApplyId(UUID agent, UUID previewId) { + return operations.values().stream().filter(op -> agent.equals(op.agent) && "APPLY".equals(op.type) + && previewId.equals(op.sourceOperationId)).map(op -> op.id).findFirst().orElse(null); + } + + private StoredOperation agentOperation(UUID agent, UUID id) { + StoredOperation operation = operations.get(id); + if (operation == null || !agent.equals(operation.agent)) { + throw new ValidationException("OPERATION_NOT_FOUND", "Operation was not found", List.of()); + } + return operation; + } + + public synchronized OperationView approveAgentPreview(UUID id) { + prune(); + StoredOperation preview = operations.get(id); + if (preview == null || !agentReviewReady(preview)) { + if (preview != null && !preview.approvalUsed && !currentAgentCoordination(preview)) { + audit.append("AGENT_PREVIEW_INVALIDATED", preview.id, null, "SCOPE_CHANGED"); + preview.approvalUsed = true; + } + throw invalid("Preview is unavailable for browser approval"); + } + return createApply(id, preview.approvalToken, true); + } + + private boolean agentReviewReady(StoredOperation operation) { + return operation.agent != null && "PREVIEW".equals(operation.type) + && !operation.approvalUsed && operation.complete() + && currentAgentCoordination(operation) + && operation.results.values().stream().allMatch(ConfigurationTaskResult::success) + && clock.instant().isBefore(operation.createdAt.plus(ACTIVE_RETENTION)); + } + public synchronized OperationView createApply(UUID previewId, String approvalToken) { + return createApply(previewId, approvalToken, false); + } + + private OperationView createApply(UUID previewId, String approvalToken, boolean browserAgentReview) { prune(); LinkedHashMap priorOperations = new LinkedHashMap<>(operations); long priorChanges = retainedChangeBytes; @@ -113,6 +561,7 @@ public synchronized OperationView createApply(UUID previewId, String approvalTok long priorFiles = retainedFileBytes; StoredOperation preview = operations.get(previewId); if (preview == null || !"PREVIEW".equals(preview.type)) throw invalid("preview operation was not found"); + if ((preview.agent != null) != browserAgentReview) throw invalid("Preview requires its original approval route"); if (!preview.complete() || preview.results.values().stream().anyMatch(result -> !result.success())) { throw new ValidationException("PREVIEW_INCOMPLETE", "Every node must pass preview before apply", List.of()); } @@ -124,6 +573,7 @@ public synchronized OperationView createApply(UUID previewId, String approvalTok ValidatedTargets targets = validateTargets(new ArrayList<>(preview.states.keySet()), preview.configuration.capability()); validateApprovedTargets(preview, targets); + if (preview.agentGuidedPreview != null) validateTargets(targets.nodeIds(), QUICK_SETUP_CAPABILITY); validateConfigurationTargets(targets, preview.configuration); validateProxyMethodTargets(targets, preview.configuration); rejectOverlappingProxyMethodApply(targets, preview.configuration); @@ -132,10 +582,22 @@ public synchronized OperationView createApply(UUID previewId, String approvalTok preview.results.forEach((node, result) -> revisions.put(node, result.revision())); boolean priorApprovalUsed = preview.approvalUsed; StoredOperation apply = store("APPLY", targets, preview.configuration, - null, revisions, preview.id); + null, revisions, preview.id, preview.agent); + apply.agentProxyRollout = preview.agentProxyRollout; + apply.agentGuidedPreview = preview.agentGuidedPreview; + if (preview.agentGuidedPreview == GuidedSettings.LOG) { + apply.agentVoteLogRestartTargets = preview.agentBeforeByNode.entrySet().stream() + .filter(row -> row.getValue().containsKey("VoteLogging.Enabled")).map(Map.Entry::getKey) + .collect(java.util.stream.Collectors.toUnmodifiableSet()); + } preview.approvalUsed = true; try { - audit.append("APPLY_APPROVED", apply.id, null, "QUEUED"); + if (browserAgentReview) { + audit.append("AGENT_APPLY_APPROVED", apply.id, targets.nodeIds().size() == 1 ? targets.nodeIds().get(0) : null, + preview.id.toString()); + } else { + audit.append("APPLY_APPROVED", apply.id, null, "QUEUED"); + } persist(); } catch (RuntimeException e) { operations.clear(); @@ -163,6 +625,13 @@ public synchronized SettingsState generalSettingsState(UUID readId, String nodeI public synchronized OperationView createGeneralSettingsPreview(UUID readId, String nodeId, Map overrides) { + StoredOperation read = operations.get(readId); + if (read != null && read.agent != null) throw invalid("Agent reads require the agent editor"); + return createGeneralSettingsPreview(readId, nodeId, overrides, null); + } + + private OperationView createGeneralSettingsPreview(UUID readId, String nodeId, + Map overrides, UUID agent) { SettingsSnapshot source = settingsSnapshot(readId, nodeId); ConfigurationTaskResult snapshot = source.result(); if (overrides == null || overrides.isEmpty() @@ -180,8 +649,26 @@ public synchronized OperationView createGeneralSettingsPreview(UUID readId, Stri validateConfigurationTargets(targets, configuration); byte[] token = new byte[32]; random.nextBytes(token); - return create("PREVIEW", targets, configuration, - Base64.getUrlEncoder().withoutPadding().encodeToString(token), Map.of(nodeId, snapshot.revision())); + if (agent == null) { + return create("PREVIEW", targets, configuration, + Base64.getUrlEncoder().withoutPadding().encodeToString(token), Map.of(nodeId, snapshot.revision())); + } + String current = snapshot.configuration().content(); + var before = GeneralSettingsDocument.fields(current, source.profile()); + var after = GeneralSettingsDocument.fields(proposal, source.profile()); + List diff = GeneralSettingsDocument.reviewedChangedPaths(source.profile(), before, after); + if (diff.isEmpty()) throw invalid("General Settings values are already set"); + var preview = create("PREVIEW", targets, configuration, + Base64.getUrlEncoder().withoutPadding().encodeToString(token), Map.of(nodeId, snapshot.revision()), agent); + StoredOperation stored = operations.get(preview.operationId()); + stored.agentGeneralSettings = true; + stored.agentBefore = AgentSetup.settingsValues(before); + var proposed = new LinkedHashMap<>(AgentSetup.settingsValues(after)); + proposed.entrySet().removeIf(entry -> entry.getValue().equals(stored.agentBefore.get(entry.getKey()))); + stored.agentAfter = Map.copyOf(proposed); + stored.agentDocumentDigest = AgentSetup.documentDigest(current); + stored.agentExpectedChanges = Set.copyOf(diff); + return preview; } private SettingsSnapshot settingsSnapshot(UUID readId, String nodeId) { @@ -250,6 +737,13 @@ public synchronized VoteSitesState voteSitesState(UUID readId, String nodeId) { /** Creates one revision-bound preview for one exact typed site action on one target. */ public synchronized OperationView createVoteSitesPreview(UUID readId, String nodeId, String action, String siteKey, Map fields) { + StoredOperation read = operations.get(readId); + if (read != null && read.agent != null) throw invalid("Agent reads require the agent editor"); + return createVoteSitesPreview(readId, nodeId, action, siteKey, fields, null); + } + + private OperationView createVoteSitesPreview(UUID readId, String nodeId, String action, String siteKey, + Map fields, UUID agent) { ConfigurationTaskResult snapshot = fileSnapshot(readId, nodeId, "VoteSites.yml"); String proposal; try { @@ -258,6 +752,7 @@ public synchronized OperationView createVoteSitesPreview(UUID readId, String nod case "EDIT" -> VoteSitesDocument.edit(snapshot.configuration().content(), siteKey, fields); case "REMOVE" -> { if (fields != null && !fields.isEmpty()) throw new IllegalArgumentException(); + if (agent != null) VoteSitesDocument.requireReviewableRemoval(snapshot.configuration().content(), siteKey); yield VoteSitesDocument.remove(snapshot.configuration().content(), siteKey); } default -> throw new IllegalArgumentException(); @@ -273,8 +768,40 @@ public synchronized OperationView createVoteSitesPreview(UUID readId, String nod validateConfigurationTargets(targets, configuration); byte[] token = new byte[32]; random.nextBytes(token); - return create("PREVIEW", targets, configuration, - Base64.getUrlEncoder().withoutPadding().encodeToString(token), Map.of(nodeId, snapshot.revision())); + String approval = Base64.getUrlEncoder().withoutPadding().encodeToString(token); + var revisions = Map.of(nodeId, snapshot.revision()); + if (agent == null) return create("PREVIEW", targets, configuration, approval, revisions); + Map before; + Map after; + try { + before = AgentSetup.editorSiteValues(siteKey, snapshot.configuration().content()); + after = AgentSetup.editorSiteValues(siteKey, proposal); + } catch (IllegalArgumentException unsafe) { + throw invalid("Site values cannot be reviewed safely"); + } + var changes = new LinkedHashMap(); + var prior = new LinkedHashMap(); + var paths = new java.util.HashSet(); + for (String key : VoteSitesDocument.editableKeys()) { + if (Objects.equals(before.get(key), after.get(key))) continue; + String path = "VoteSites." + siteKey + "." + key; + if (before.containsKey(key)) prior.put(path, before.get(key)); + changes.put(path, after.getOrDefault(key, "(removed)")); + paths.add("changed " + path); + } + if (paths.isEmpty()) throw invalid("Site action has no reviewable changes"); + if (!before.get("exists").equals(after.get("exists"))) { + String path = "VoteSites." + siteKey + " exists"; + prior.put(path, before.get("exists")); + changes.put(path, after.get("exists")); + } + var preview = create("PREVIEW", targets, configuration, approval, revisions, agent); + StoredOperation stored = operations.get(preview.operationId()); + stored.agentBefore = Map.copyOf(prior); + stored.agentAfter = Map.copyOf(changes); + stored.agentDocumentDigest = AgentSetup.documentDigest(snapshot.configuration().content()); + stored.agentExpectedChanges = Set.copyOf(paths); + return preview; } public record VoteSitesState(UUID readOperationId, String nodeId, UUID sessionId, String revision, @@ -304,6 +831,13 @@ public synchronized RewardsState rewardsState(UUID readId, String nodeId, String /** Source-preserving one-target reward edit, approved through the existing PREVIEW/APPLY path. */ public synchronized OperationView createRewardsPreview(UUID readId, String nodeId, String fileName, String rewardPath, String action, String field, Object value) { + StoredOperation read = operations.get(readId); + if (read != null && read.agent != null) throw invalid("Agent reads require the agent editor"); + return createRewardsPreview(readId, nodeId, fileName, rewardPath, action, field, value, null, null); + } + + private OperationView createRewardsPreview(UUID readId, String nodeId, String fileName, + String rewardPath, String action, String field, Object value, UUID agent, AgentSetup.RewardField agentField) { if (!"VoteSites.yml".equals(fileName) && !isNamedRewardFile(fileName)) throw invalid("This reward scope is advanced-only"); ConfigurationTaskResult snapshot = fileSnapshot(readId, nodeId, fileName); @@ -320,8 +854,27 @@ public synchronized OperationView createRewardsPreview(UUID readId, String nodeI validateConfigurationTargets(targets, configuration); byte[] token = new byte[32]; random.nextBytes(token); - return create("PREVIEW", targets, configuration, - Base64.getUrlEncoder().withoutPadding().encodeToString(token), Map.of(nodeId, snapshot.revision())); + String approval = Base64.getUrlEncoder().withoutPadding().encodeToString(token); + var revisions = Map.of(nodeId, snapshot.revision()); + if (agent == null) return create("PREVIEW", targets, configuration, approval, revisions); + String prior; + String next; + try { + prior = agentField.values(snapshot.configuration().content()).get("rewardValue"); + next = agentField.values(proposal).get("rewardValue"); + } catch (IllegalArgumentException unsupported) { + throw invalid("Reward field cannot be reviewed safely"); + } + if (prior.equals(next)) throw invalid("Reward field has no reviewable change"); + var preview = create("PREVIEW", targets, configuration, approval, revisions, agent); + var stored = operations.get(preview.operationId()); + String path = agentField.changePath(); + String label = fileName + " / " + path; + stored.agentBefore = Map.of(label, prior); + stored.agentAfter = Map.of(label, next); + stored.agentDocumentDigest = AgentSetup.documentDigest(snapshot.configuration().content()); + stored.agentExpectedChanges = Set.of("changed " + path); + return preview; } public record RewardsState(UUID readOperationId, String nodeId, String fileName, UUID sessionId, String revision, @@ -343,7 +896,7 @@ public synchronized OperationView discardVoteSitesPreview(UUID id, String token) private OperationView discardVisualPreview(UUID id, String token, String source) { prune(); StoredOperation preview = operations.get(id); - if (preview == null || !"PREVIEW".equals(preview.type) || preview.expectedRevisions.isEmpty() + if (preview == null || preview.agent != null || !"PREVIEW".equals(preview.type) || preview.expectedRevisions.isEmpty() || token == null || token.length() > 128 || preview.approvalToken == null || !MessageDigest.isEqual(token.getBytes(java.nio.charset.StandardCharsets.UTF_8), preview.approvalToken.getBytes(java.nio.charset.StandardCharsets.UTF_8))) { @@ -382,7 +935,7 @@ public synchronized OperationView retry(UUID id) { prune(); StoredOperation original = operations.get(id); if (original == null) throw new ValidationException("OPERATION_NOT_FOUND", "Operation was not found", List.of()); - if (original.recovered) { + if (original.recovered || original.agent != null) { throw new ValidationException("RETRY_REQUIRES_INPUT", "Recovered operations are history only; start a fresh read or preview", List.of()); } @@ -423,7 +976,7 @@ public synchronized OperationView retry(UUID id) { long priorChanges = retainedChangeBytes; long priorMessages = retainedMessageBytes; long priorFiles = retainedFileBytes; - StoredOperation retry = store(original.type, targets, original.configuration, token, revisions, original.id); + StoredOperation retry = store(original.type, targets, original.configuration, token, revisions, original.id, null); try { audit.append("OPERATION_RETRIED", retry.id, null, original.id.toString()); persist(); @@ -439,7 +992,8 @@ public synchronized OperationView retry(UUID id) { } public synchronized ConfigurationTask claim(String nodeId, UUID sessionId) { - return registry.withSession(nodeId, sessionId, node -> claimCurrentSession(nodeId, node)); + return registry.withStableTopology(() -> registry.withSession(nodeId, sessionId, + node -> claimCurrentSession(nodeId, node))); } private ConfigurationTask claimCurrentSession(String nodeId, NodeStatus node) { @@ -450,8 +1004,8 @@ private ConfigurationTask claimCurrentSession(String nodeId, NodeStatus node) { Instant leased = operation.leasedAt.get(nodeId); if ("QUEUED".equals(state) || ("IN_PROGRESS".equals(state) && leased != null && !now.isBefore(leased.plus(LEASE)))) { - if (cancelChangedFileRole(operation, node)) continue; - if (cancelChangedBackendSetupRole(operation, node)) continue; + if (cancelChangedAgentCoordination(operation) || cancelChangedFileRole(operation, node)) continue; + if (cancelChangedAgentTarget(operation, node) || cancelChangedBackendSetupRole(operation, node)) continue; if (cancelChangedProxyMethodRole(operation, node)) continue; if (deferProxyMethodApply(operation, node)) continue; if (cancelLostCapability(operation, node)) continue; @@ -589,6 +1143,15 @@ private boolean cancelChangedFileRole(StoredOperation operation, NodeStatus node return true; } + private boolean cancelChangedAgentTarget(StoredOperation operation, NodeStatus node) { + if (operation.agent == null || (Objects.equals(operation.targetPlatforms.get(node.nodeId()), node.platform()) + && Objects.equals(operation.targetSessions.get(node.nodeId()), node.sessionId()) + && (operation.agentPeerSession == null || agentTransportPeerCurrent(operation, node)))) return false; + automaticCancellation(operation, node.nodeId(), node.sessionId(), "TARGET_CHANGED", + "Agent operation target reconnected or changed role", "TARGET_CHANGED"); + return true; + } + private boolean cancelChangedBackendSetupRole(StoredOperation operation, NodeStatus node) { if (!ManagedConfiguration.QUICK_SETUP.equals(operation.configuration.domain()) || !"proxy-backend".equals(operation.configuration.preset())) return false; @@ -600,7 +1163,14 @@ private boolean cancelChangedBackendSetupRole(StoredOperation operation, NodeSta } private boolean cancelLostCapability(StoredOperation operation, NodeStatus node) { - if (node.online() && node.acceptedCapabilities().contains(operation.configuration.capability())) return false; + if (node.online() && node.acceptedCapabilities().contains(operation.configuration.capability()) + && (operation.agentGuidedRead == null + || node.acceptedCapabilities().containsAll(Set.copyOf(List.of(QUICK_SETUP_CAPABILITY, + operation.agentGuidedRead.capability(), FILE_CAPABILITY)))) + && (operation.agentGuidedPreview == null || node.acceptedCapabilities().contains(QUICK_SETUP_CAPABILITY)) + && (operation.agentMethodReadCapability == null + || node.acceptedCapabilities().contains(operation.agentMethodReadCapability) + && (!"BUKKIT".equals(node.platform()) || node.acceptedCapabilities().contains(QUICK_SETUP_CAPABILITY)))) return false; automaticCancellation(operation, node.nodeId(), sessionId(node), "CAPABILITY_LOST", "Node no longer accepts this configuration capability", "CAPABILITY_LOST"); return true; @@ -757,6 +1327,42 @@ private static UUID sessionId(NodeStatus node) { return node.sessionId(); } + private static boolean agentPreviewReviewable(StoredOperation operation, String nodeId, ConfigurationTaskResult result) { + if (operation.agentGuidedPreview != null) { + var changes = operation.agentBeforeByNode.get(nodeId).keySet().stream() + .map(path -> "changed " + path).collect(java.util.stream.Collectors.toSet()); + return operation.configuration.equals(result.configuration()) + && changes.size() == result.changes().size() && changes.equals(Set.copyOf(result.changes())); + } + if (operation.agentProxyRollout != null) { + var changes = AgentSetup.proxyMethodChanges(operation.agentBeforeByNode.get(nodeId), + operation.configuration.options().get("method")); + return operation.configuration.equals(result.configuration()) + && changes.size() == result.changes().size() && changes.equals(Set.copyOf(result.changes())); + } + if (operation.agentDocumentDigest != null) { + return result.configuration() != null && result.configuration().content() != null + && operation.agentDocumentDigest.equals(AgentSetup.documentDigest(result.configuration().content())) + && result.changes().size() == operation.agentExpectedChanges.size() + && operation.agentExpectedChanges.equals(Set.copyOf(result.changes())); + } + if (AgentSetup.SITE_POLICY.equals(operation.configuration.preset())) { + return operation.configuration.equals(result.configuration()) + && result.changes().equals(List.of("changed AutoCreateVoteSites")); + } + if (!ManagedConfiguration.PROXY_ROUTING.equals(operation.configuration.domain())) { + return operation.configuration.equals(result.configuration()) + && AgentSetup.reviewableChanges(operation.configuration, operation.agentBefore, result.changes()); + } + try { + return operation.agentBefore.equals(AgentSetup.routingValues(result.configuration())) + && AgentSetup.routingChanges(operation.agentBefore, + AgentSetup.routingValues(operation.configuration)).equals(result.changes()); + } catch (IllegalArgumentException unsafe) { + return false; + } + } + private OperationView completeCurrentSession(UUID operationId, String nodeId, ConfigurationTaskResult result, NodeStatus node) { StoredOperation operation = operations.get(operationId); @@ -778,12 +1384,22 @@ private OperationView completeCurrentSession(UUID operationId, String nodeId, Co if (!Objects.equals(operation.claimSessions.get(nodeId), result.sessionId())) { throw new ValidationException("SESSION_MISMATCH", "Operation task belongs to another node session", List.of()); } - if (cancelChangedFileRole(operation, node) || cancelChangedBackendSetupRole(operation, node) + if (cancelChangedAgentTarget(operation, node) || cancelChangedFileRole(operation, node) + || cancelChangedBackendSetupRole(operation, node) || cancelChangedProxyMethodRole(operation, node) || cancelLostCapability(operation, node)) { return view(operation); } - validateResultConfiguration(operation, result, node); + try { + validateResultConfiguration(operation, result, node); + } catch (ValidationException incompatible) { + if (operation.agentGuidedRead == null || !ManagedConfiguration.QUICK_SETUP.equals(operation.configuration.domain())) { + throw incompatible; + } + result = new ConfigurationTaskResult(result.sessionId(), false, "UNSUPPORTED", + "The connector did not return the required versioned preset READ", null, + (ManagedConfiguration) null, List.of(), false, false, result.attemptId()); + } if ("PREVIEW".equals(operation.type) && result.success() && operation.expectedRevisions.containsKey(nodeId) && !Objects.equals(operation.expectedRevisions.get(nodeId), result.revision())) { @@ -791,6 +1407,69 @@ private OperationView completeCurrentSession(UUID operationId, String nodeId, Co "Configuration changed since READ; read and preview again", null, (ManagedConfiguration) null, List.of(), false, false, result.attemptId()); } + if (operation.agent != null && "PREVIEW".equals(operation.type) && result.success() + && (result.changes().size() >= 20 || result.changes().contains("additional changes omitted") + || retainedChangeBytes + result.changes().stream().mapToLong( + change -> change.getBytes(StandardCharsets.UTF_8).length).sum() > MAX_RETAINED_CHANGE_BYTES + || !agentPreviewReviewable(operation, nodeId, result))) { + result = new ConfigurationTaskResult(result.sessionId(), false, "DIFF_UNAVAILABLE", + "Preview changes cannot be reviewed completely", null, (ManagedConfiguration) null, + List.of(), false, false, result.attemptId()); + } + Map agentRead = Map.of(); + if (operation.agent != null && operation.agentPeerSession == null + && "READ".equals(operation.type) && result.success()) { + try { + if (operation.agentGuidedRead != null) { + if (ManagedConfiguration.FILE.equals(operation.configuration.domain())) { + if (result.configuration() == null || result.configuration().content() == null) { + throw new IllegalArgumentException("Missing masked presence evidence"); + } + } else { + agentRead = operation.agentGuidedRead.effectiveValues(result.configuration()); + result = new ConfigurationTaskResult(result.sessionId(), true, "OK", "Scoped configuration read", + result.revision(), (ManagedConfiguration) null, List.of(), false, false, result.attemptId()); + } + } else if (operation.agentGeneralSettings) { + if (result.configuration() == null || result.configuration().content() == null) { + throw new IllegalArgumentException("Missing redacted settings"); + } + agentRead = AgentSetup.settingsValues(GeneralSettingsDocument.fields(result.configuration().content(), + GeneralSettingsDocument.profileForFile(operation.configuration.fileName()))); + } else if (operation.agentMethodReadCapability != null) { + boolean backend = "proxy-backend".equals(operation.configuration.preset()); + agentRead = AgentSetup.proxyMethodValues(result.configuration(), backend); + if (!backend && !AgentSetup.documentDigest(agentRead.get("method")).equals(result.revision())) { + throw new IllegalArgumentException("Unreviewable proxy method revision"); + } + result = new ConfigurationTaskResult(result.sessionId(), true, "OK", "Scoped configuration read", + result.revision(), (ManagedConfiguration) null, List.of(), false, false, result.attemptId()); + } else if (operation.agentRewardField != null) { + if (result.configuration() == null || result.configuration().content() == null) { + throw new IllegalArgumentException("Missing redacted reward source"); + } + agentRead = operation.agentRewardField.values(result.configuration().content()); + } else if (operation.agentEditorSite != null) { + if (result.configuration() == null || result.configuration().content() == null) { + throw new IllegalArgumentException("Missing redacted VoteSites source"); + } + agentRead = AgentSetup.editorSiteValues(operation.agentEditorSite, result.configuration().content()); + } else { + agentRead = ManagedConfiguration.PROXY_ROUTING.equals(operation.configuration.domain()) + ? AgentSetup.routingValues(result.configuration()) + : AgentSetup.SITE_POLICY.equals(operation.configuration.preset()) + ? AgentSetup.sitePolicyValues(result.configuration()) + : AgentSetup.readSite(operation.agentSite, result.configuration()); + result = new ConfigurationTaskResult(result.sessionId(), true, "OK", "Scoped configuration read", + result.revision(), (ManagedConfiguration) null, List.of(), false, false, result.attemptId()); + } + } catch (IllegalArgumentException unreviewable) { + result = new ConfigurationTaskResult(result.sessionId(), false, + operation.agentGuidedRead == null ? "DIFF_UNAVAILABLE" : "GUIDED_EVIDENCE_UNAVAILABLE", + "The requested configuration cannot be represented safely", null, + (ManagedConfiguration) null, List.of(), false, false, result.attemptId()); + } + } String priorState = operation.states.get(nodeId); ConfigurationTaskResult priorResult = operation.results.get(nodeId); Instant priorLease = operation.leasedAt.get(nodeId); @@ -805,7 +1484,7 @@ private OperationView completeCurrentSession(UUID operationId, String nodeId, Co if ("APPLY".equals(operation.type) && result.success()) { configurationGeneration++; } - if (requiresVoteLoggingRestart(operation, result)) { + if (requiresVoteLoggingRestart(operation, nodeId, result)) { reclaimStaleRestartSessions(nodeId); voteLoggingRestartSessions.remove(nodeId); voteLoggingRestartSessions.put(nodeId, result.sessionId()); @@ -815,6 +1494,7 @@ private OperationView completeCurrentSession(UUID operationId, String nodeId, Co operation.attemptIds.remove(nodeId); persist(); audit.append("TASK_COMPLETED", operation.id, nodeId, result.success() ? "SUCCESS" : result.code()); + if (!agentRead.isEmpty()) operation.agentBefore = agentRead; } catch (RuntimeException failure) { restoreTransition(operation, nodeId, priorState, priorResult, priorLease, priorAttempt, priorChanges, priorMessages, priorFiles, priorConfigurationGeneration, @@ -830,13 +1510,20 @@ private OperationView create(String type, ValidatedTargets targets, ManagedConfi private OperationView create(String type, ValidatedTargets targets, ManagedConfiguration config, String token, Map revisions) { + return create(type, targets, config, token, revisions, null); + } + + private OperationView create(String type, ValidatedTargets targets, ManagedConfiguration config, String token, + Map revisions, UUID agent) { LinkedHashMap priorOperations = new LinkedHashMap<>(operations); long priorChanges = retainedChangeBytes; long priorMessages = retainedMessageBytes; long priorFiles = retainedFileBytes; - StoredOperation operation = store(type, targets, config, token, revisions, null); + StoredOperation operation = store(type, targets, config, token, revisions, null, agent); try { - audit.append("OPERATION_CREATED", operation.id, null, type); + if (agent == null) audit.append("OPERATION_CREATED", operation.id, null, type); + else audit.append("AGENT_" + type + "_CREATED", operation.id, + targets.nodeIds().size() == 1 ? targets.nodeIds().get(0) : null, agent.toString()); persist(); } catch (RuntimeException e) { operations.clear(); @@ -850,9 +1537,17 @@ private OperationView create(String type, ValidatedTargets targets, ManagedConfi } private StoredOperation store(String type, ValidatedTargets targets, ManagedConfiguration config, - String token, Map revisions, UUID protectedOperation) { + String token, Map revisions, UUID protectedOperation, UUID agent) { prune(); - ensureFileCapacity(config, protectedOperation); + if (config != null && largeContentOperation(config)) { + if (agent != null) { + boolean apply = "APPLY".equals(type); + ensureFileCapacity(protectedOperation, + candidate -> candidate.agent != null && "APPLY".equals(candidate.type) == apply, + apply ? MAX_AGENT_FILE_APPLIES : MAX_AGENT_FILE_READS_AND_PREVIEWS); + } + ensureFileCapacity(protectedOperation, candidate -> true, MAX_FILE_OPERATIONS); + } if (operations.size() >= MAX_OPERATIONS) throw new ValidationException("OPERATION_LIMIT", "Too many retained operations", List.of()); UUID id = UUID.randomUUID(); @@ -862,20 +1557,21 @@ private StoredOperation store(String type, ValidatedTargets targets, ManagedConf new LinkedHashMap<>(), new LinkedHashMap<>(), new LinkedHashMap<>(), new LinkedHashMap<>(revisions), new LinkedHashMap<>(targets.platforms()), new LinkedHashMap<>(targets.sessions()), protectedOperation, false); + result.agent = agent; operations.put(id, result); return result; } - private void ensureFileCapacity(ManagedConfiguration config, UUID protectedOperation) { - if (config == null || !largeContentOperation(config)) return; - long retained = operations.values().stream().filter(StoredOperation::fileOperation).count(); + private void ensureFileCapacity(UUID protectedOperation, + java.util.function.Predicate inLane, int limit) { + long retained = operations.values().stream().filter(StoredOperation::fileOperation).filter(inLane).count(); Iterator> iterator = operations.entrySet().iterator(); - while (retained >= MAX_FILE_OPERATIONS && iterator.hasNext()) { + while (retained >= limit && iterator.hasNext()) { StoredOperation candidate = iterator.next().getValue(); boolean boundApprovalPending = "PREVIEW".equals(candidate.type) && !candidate.expectedRevisions.isEmpty() && !candidate.approvalUsed && candidate.createdAt.plus(ACTIVE_RETENTION).isAfter(clock.instant()) && candidate.results.values().stream().allMatch(ConfigurationTaskResult::success); - if (candidate.fileOperation() && candidate.complete() && !candidate.id.equals(protectedOperation) + if (candidate.fileOperation() && inLane.test(candidate) && candidate.complete() && !candidate.id.equals(protectedOperation) && !boundApprovalPending) { audit.append("OPERATION_EVICTED", candidate.id, null, "FILE_RETENTION_LIMIT"); releaseResultDetails(candidate); @@ -883,7 +1579,7 @@ private void ensureFileCapacity(ManagedConfiguration config, UUID protectedOpera retained--; } } - if (retained >= MAX_FILE_OPERATIONS) { + if (retained >= limit) { throw new ValidationException("OPERATION_LIMIT", "Too many active file operations", List.of()); } } @@ -916,12 +1612,12 @@ private ConfigurationTaskResult boundedResult(StoredOperation operation, Configu result.revision(), configuration, changes, result.reloaded(), result.rolledBack(), result.attemptId()); } - private static boolean requiresVoteLoggingRestart(StoredOperation operation, ConfigurationTaskResult result) { + private static boolean requiresVoteLoggingRestart(StoredOperation operation, String nodeId, ConfigurationTaskResult result) { return result.success() && "APPLY".equals(operation.type) && ManagedConfiguration.QUICK_SETUP.equals(operation.configuration.domain()) && "vote-logging".equals(operation.configuration.preset()) - && result.changes().stream() - .anyMatch(change -> change.matches(".*VoteLogging\\.(Enabled|UseMainMySQL)\\b.*")); + && (operation.agentVoteLogRestartTargets.contains(nodeId) || result.changes().stream() + .anyMatch(change -> change.matches(".*VoteLogging\\.(Enabled|UseMainMySQL)\\b.*"))); } private void reclaimStaleRestartSessions(String incomingNodeId) { @@ -1062,7 +1758,7 @@ private OperationView view(StoredOperation operation, boolean includeRetainedCon ? "SUCCEEDED" : "COMPLETED_WITH_ERRORS") : "RUNNING"; String approval = "PREVIEW".equals(operation.type) && operation.complete() && operation.results.values().stream().allMatch(ConfigurationTaskResult::success) - && !operation.approvalUsed ? operation.approvalToken : null; + && !operation.approvalUsed && operation.agent == null ? operation.approvalToken : null; Map results = operation.results; if (!includeRetainedContent) { LinkedHashMap summaries = new LinkedHashMap<>(); @@ -1076,11 +1772,11 @@ private OperationView view(StoredOperation operation, boolean includeRetainedCon return new OperationView(operation.id, operation.type, state, operation.createdAt, operation.configuration == null ? null : operation.configuration.publicView(), Map.copyOf(operation.states), Map.copyOf(results), approval, operation.sourceOperationId, - operation.recovered, retryable(operation)); + operation.recovered, retryable(operation), operation.agent, agentReviewReady(operation)); } private static boolean retryable(StoredOperation operation) { - if (operation.recovered || !operation.complete() + if (operation.recovered || operation.agent != null || !operation.complete() || operation.results.values().stream().allMatch(ConfigurationTaskResult::success)) return false; if ("PREVIEW".equals(operation.type) && !operation.expectedRevisions.isEmpty()) return false; return !("APPLY".equals(operation.type) @@ -1206,7 +1902,18 @@ public void close() throws java.io.IOException { public record OperationView(UUID operationId, String type, String state, Instant createdAt, ManagedConfiguration configuration, Map nodeStates, Map results, String approvalToken, - UUID sourceOperationId, boolean recovered, boolean retryable) { } + UUID sourceOperationId, boolean recovered, boolean retryable, UUID agentId, boolean browserReviewReady) { + public OperationView(UUID operationId, String type, String state, Instant createdAt, + ManagedConfiguration configuration, Map nodeStates, + Map results, String approvalToken, + UUID sourceOperationId, boolean recovered, boolean retryable) { + this(operationId, type, state, createdAt, configuration, nodeStates, results, approvalToken, + sourceOperationId, recovered, retryable, null, false); + } + } + + public record AgentReview(OperationView operation, Map before, + Map> beforeByNode, Map after) { } public record OperationListView(List items, Map voteLoggingRestartSessions, long configurationGeneration) { @@ -1218,6 +1925,17 @@ public OperationListView(List items, Map voteLoggin private record ValidatedTargets(List nodeIds, Map platforms, Map sessions) { } + private static final class AgentProxyRollout { + private final String proxyId; + private final Instant expiresAt; + private boolean revoked; + + private AgentProxyRollout(String proxyId, Instant expiresAt) { + this.proxyId = proxyId; + this.expiresAt = expiresAt; + } + } + private static final class StoredOperation { private final UUID id; private final String type; @@ -1235,6 +1953,22 @@ private static final class StoredOperation { private final UUID sourceOperationId; private final boolean recovered; private boolean approvalUsed; + private UUID agent; + private String agentSite; + private String agentEditorSite; + private AgentSetup.RewardField agentRewardField; + private boolean agentGeneralSettings; + private GuidedSettings agentGuidedRead; + private GuidedSettings agentGuidedPreview; + private Set agentVoteLogRestartTargets = Set.of(); + private String agentDocumentDigest; + private Set agentExpectedChanges = Set.of(); + private Map agentAfter = Map.of(); + private UUID agentPeerSession; + private String agentMethodReadCapability; + private AgentProxyRollout agentProxyRollout; + private Map agentBefore = Map.of(); + private Map> agentBeforeByNode = Map.of(); private StoredOperation(UUID id, String type, ManagedConfiguration configuration, String approvalToken, Instant createdAt, LinkedHashMap states, diff --git a/src/main/java/com/bencodez/votingplugin/control/domain/GeneralSettingsDocument.java b/src/main/java/com/bencodez/votingplugin/control/domain/GeneralSettingsDocument.java index 7f00578..f4562dc 100644 --- a/src/main/java/com/bencodez/votingplugin/control/domain/GeneralSettingsDocument.java +++ b/src/main/java/com/bencodez/votingplugin/control/domain/GeneralSettingsDocument.java @@ -107,6 +107,18 @@ public static String patch(String content, Profile profile, Map overr return patched.toString(); } + public static Set editableKeys() { + Set keys = new java.util.TreeSet<>(); + BACKEND_SPECS.forEach(spec -> keys.add(spec.key())); + PROXY_SPECS.forEach(spec -> keys.add(spec.key())); + return Collections.unmodifiableSet(keys); + } + + static List reviewedChangedPaths(Profile profile, Map before, Map after) { + return specs(profile).stream().filter(spec -> !before.get(spec.key()).equals(after.get(spec.key()))) + .map(spec -> "changed " + spec.rawKey()).toList(); + } + public static Profile profileForFile(String fileName) { if ("Config.yml".equals(fileName)) return Profile.BACKEND; if ("bungeeconfig.yml".equals(fileName)) return Profile.PROXY; diff --git a/src/main/java/com/bencodez/votingplugin/control/domain/GuidedSettings.java b/src/main/java/com/bencodez/votingplugin/control/domain/GuidedSettings.java new file mode 100644 index 0000000..5d3a92c --- /dev/null +++ b/src/main/java/com/bencodez/votingplugin/control/domain/GuidedSettings.java @@ -0,0 +1,183 @@ +package com.bencodez.votingplugin.control.domain; + +import com.bencodez.votingplugin.control.protocol.ManagedConfiguration; +import java.io.StringReader; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.nodes.MappingNode; +import org.yaml.snakeyaml.nodes.Node; +import org.yaml.snakeyaml.nodes.ScalarNode; +import org.yaml.snakeyaml.nodes.Tag; + +/** Typed preset values and presence evidence from an existing masked managed-file READ. */ +public enum GuidedSettings { + COMMON("common-settings", "Config.yml", List.of( + new Field("processRewards", "ProcessRewards", "true", Kind.FLAG, true), + new Field("autoCreateVoteSites", "AutoCreateVoteSites", "true", Kind.FLAG, false), + new Field("extraAllSitesCheck", "ExtraAllSitesCheck", "false", Kind.FLAG, true), + new Field("countFakeVotes", "CountFakeVotes", "true", Kind.FLAG, false), + new Field("disableNoServiceSiteMessage", "DisableNoServiceSiteMessage", "false", Kind.FLAG, true), + new Field("disableUpdateChecking", "DisableUpdateChecking", "false", Kind.FLAG, false))), + LOG("vote-logging", "Config.yml", List.of( + new Field("enabled", "VoteLogging.Enabled", "false", Kind.FLAG, true), + new Field("purgeDays", "VoteLogging.PurgeDays", "30", Kind.RETENTION, true), + new Field("useMainMySQL", "VoteLogging.UseMainMySQL", "true", Kind.FLAG, false))), + PARTY("vote-party", "SpecialRewards.yml", List.of( + new Field("enabled", "VoteParty.Enabled", "false", Kind.FLAG, true), + new Field("votesRequired", "VoteParty.VotesRequired", "20", Kind.THRESHOLD, true), + new Field("giveAllPlayers", "VoteParty.GiveAllPlayers", "false", Kind.FLAG, true), + new Field("onlineOnly", "VoteParty.GiveOnlinePlayersOnly", "true", Kind.FLAG, true), + new Field("broadcast", "VoteParty.Broadcast", "", Kind.TEXT, true))); + + private final String preset; + private final String file; + private final List fields; + + GuidedSettings(String preset, String file, List fields) { + this.preset = preset; + this.file = file; + this.fields = fields; + } + + public static GuidedSettings select(String preset) { + for (var entry : values()) if (entry.preset.equals(preset)) return entry; + throw new IllegalArgumentException("Select a supported guided setup preset"); + } + + public String action() { return preset; } + String file() { return file; } + String capability() { return selector().capability(); } + + ManagedConfiguration selector() { + return configuration(this == PARTY ? Map.of("enabled", "false") : Map.of()); + } + + ManagedConfiguration configuration(Map options) { + var value = new ManagedConfiguration(ManagedConfiguration.QUICK_SETUP, null, List.of(), null, null, preset, options); + value.validateProposal(); + return value; + } + + public static Set resultKeys() { + return Set.of("processRewards", "autoCreateVoteSites", "extraAllSitesCheck", "countFakeVotes", + "disableNoServiceSiteMessage", "disableUpdateChecking", "enabled", "purgeDays", + "useMainMySQL", "votesRequired", "giveAllPlayers", "onlineOnly", "broadcast"); + } + + Map effectiveValues(ManagedConfiguration result) { + if (result == null) throw new IllegalArgumentException("Missing typed preset response"); + var values = new LinkedHashMap(); + for (var field : fields) { + String value = result.options().get(field.key()); + if (!field.kind().valid(value)) throw new IllegalArgumentException("Unsupported preset READ result"); + values.put(field.key(), value); + } + return Map.copyOf(values); + } + + Evidence evidence(String content, Map effective, Map overrides) { + if (content == null || overrides == null || overrides.isEmpty() || overrides.size() > fields.size()) { + throw new IllegalArgumentException("Guided setup requires at least one typed change"); + } + for (String key : overrides.keySet()) { + if (fields.stream().noneMatch(field -> field.editable() && field.key().equals(key))) { + throw new IllegalArgumentException("This field is managed in a different Control editor"); + } + } + LoaderOptions options = new LoaderOptions(); + options.setAllowDuplicateKeys(false); + options.setAllowRecursiveKeys(false); + options.setNestingDepthLimit(32); + options.setMaxAliasesForCollections(0); + options.setCodePointLimit(ManagedConfiguration.MAX_CONTENT); + Node root; + try { + root = new Yaml(new SafeConstructor(options)).compose(new StringReader(content)); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Managed file is ambiguous", invalid); + } + if (!(root instanceof MappingNode)) throw new IllegalArgumentException("Managed file requires a mapping"); + var proposal = new LinkedHashMap(); + var before = new LinkedHashMap(); + var after = new LinkedHashMap(); + for (var field : fields) { + String typed = effective.get(field.key()); + String actual = readField(root, field); + if (!field.kind().valid(typed) || !typed.equals(actual == null ? field.defaultValue() : actual)) { + throw new IllegalArgumentException("Preset and managed-file values disagree"); + } + boolean override = overrides.containsKey(field.key()); + if (field.kind() == Kind.TEXT && !override) continue; + String proposed = override ? field.kind().request(overrides.get(field.key())) : typed; + proposal.put(field.key(), proposed); + if (actual != null && actual.equals(proposed)) continue; + if (!override) throw new IllegalArgumentException("Preset would materialize an unselected key"); + before.put(field.path(), actual == null ? "(absent; effective " + typed + ")" : actual); + after.put(field.path(), proposed); + } + return new Evidence(Map.copyOf(proposal), Map.copyOf(before), Map.copyOf(after)); + } + + private static String readField(Node root, Field field) { + Node current = root; + for (String part : field.path().split("[.]")) { + if (!(current instanceof MappingNode mapping) || current.getAnchor() != null + || !Tag.MAP.equals(current.getTag())) throw new IllegalArgumentException("Unsupported key parent"); + Node match = null; + for (var tuple : mapping.getValue()) { + if (!(tuple.getKeyNode() instanceof ScalarNode scalar) || !Tag.STR.equals(scalar.getTag()) + || scalar.getValue().indexOf('.') >= 0) throw new IllegalArgumentException("Ambiguous mapping"); + if (!part.equalsIgnoreCase(scalar.getValue())) continue; + if (match != null || !part.equals(scalar.getValue())) throw new IllegalArgumentException("Ambiguous key"); + match = tuple.getValueNode(); + } + if (match == null) return null; + current = match; + } + if (!(current instanceof ScalarNode scalar) || scalar.getAnchor() != null + || !field.kind().tag.equals(scalar.getTag()) || !field.kind().valid(scalar.getValue())) { + throw new IllegalArgumentException("Unsupported managed value"); + } + return scalar.getValue(); + } + + record Evidence(Map options, Map before, Map after) { } + + private record Field(String key, String path, String defaultValue, Kind kind, boolean editable) { } + + private enum Kind { + FLAG(Tag.BOOL), RETENTION(Tag.INT), THRESHOLD(Tag.INT), TEXT(Tag.STR); + + private final Tag tag; + Kind(Tag tag) { this.tag = tag; } + + boolean valid(String value) { + if (value == null) return false; + return switch (this) { + case FLAG -> "true".equals(value) || "false".equals(value); + case RETENTION -> "-1".equals(value) || integer(value, 3650); + case THRESHOLD -> integer(value, 100000); + case TEXT -> value.length() <= 500 && value.codePoints().noneMatch(Character::isISOControl); + }; + } + + private static boolean integer(String value, int max) { + return value.matches("[1-9][0-9]{0,5}") && Integer.parseInt(value) <= max; + } + + String request(Object value) { + boolean correctType = switch (this) { + case FLAG -> value instanceof Boolean; + case RETENTION, THRESHOLD -> value instanceof Integer; + case TEXT -> value instanceof String text && !text.isBlank(); + }; + if (!correctType || !valid(value.toString())) throw new IllegalArgumentException("Invalid guided field value"); + return value.toString(); + } + } +} diff --git a/src/main/java/com/bencodez/votingplugin/control/domain/InMemoryNodeRegistry.java b/src/main/java/com/bencodez/votingplugin/control/domain/InMemoryNodeRegistry.java index 6dbb768..47e3406 100644 --- a/src/main/java/com/bencodez/votingplugin/control/domain/InMemoryNodeRegistry.java +++ b/src/main/java/com/bencodez/votingplugin/control/domain/InMemoryNodeRegistry.java @@ -98,7 +98,8 @@ public synchronized RegistrationResult register(NodeRegistration registration) { StoredNode replacement = new StoredNode(registration.nodeId(), registration.sessionId(), registration.displayName().trim(), registration.platform(), registration.pluginVersion().trim(), registration.protocolVersion(), registration.capabilities(), accepted(registration.capabilities()), - registration.detectedPlugins(), backends, sequence, now, now); + registration.detectedPlugins(), backends, sequence, now, now, + sequence < 0 ? null : existing.topologyObservedAt); result.set(replacement); return replacement; }); @@ -123,7 +124,7 @@ public NodeStatus heartbeat(String nodeId, Heartbeat heartbeat) { StoredNode updated = new StoredNode(existing.nodeId, existing.sessionId, existing.displayName, existing.platform, existing.pluginVersion, existing.protocolVersion, heartbeat.capabilities(), accepted(heartbeat.capabilities()), existing.detectedPlugins, existing.backends, - existing.snapshotSequence, now, now); + existing.snapshotSequence, now, now, existing.topologyObservedAt); result.set(updated); return updated; }); @@ -157,7 +158,7 @@ public synchronized SnapshotResult replacePresence(String nodeId, PresenceSnapsh StoredNode updated = new StoredNode(existing.nodeId, existing.sessionId, existing.displayName, existing.platform, existing.pluginVersion, existing.protocolVersion, existing.advertisedCapabilities, existing.acceptedCapabilities, existing.detectedPlugins, - sorted, snapshot.sequence(), now, now); + sorted, snapshot.sequence(), now, now, now); applied.set(true); retainedBackends = replacementTotal; result.set(updated); @@ -203,6 +204,12 @@ public void requireSession(String nodeId, UUID sessionId) { requireSession(node, sessionId); } + @Override + public Instant topologyObservedAt(String nodeId) { + StoredNode node = nodes.get(nodeId); + return node == null ? null : node.topologyObservedAt; + } + /** Runs one task mutation while replacement registration for this node is excluded. */ @Override public T withSession(String nodeId, UUID sessionId, @@ -361,7 +368,7 @@ private record StoredNode(String nodeId, UUID sessionId, String displayName, Str String pluginVersion, int protocolVersion, Set advertisedCapabilities, Set acceptedCapabilities, Set detectedPlugins, List backends, - long snapshotSequence, Instant lastSeen, Instant lastAuthenticatedUpdate) { + long snapshotSequence, Instant lastSeen, Instant lastAuthenticatedUpdate, Instant topologyObservedAt) { private StoredNode { advertisedCapabilities = Set.copyOf(advertisedCapabilities); acceptedCapabilities = Set.copyOf(acceptedCapabilities); diff --git a/src/main/java/com/bencodez/votingplugin/control/domain/InspectionOperations.java b/src/main/java/com/bencodez/votingplugin/control/domain/InspectionOperations.java index 3a068df..d51d37f 100644 --- a/src/main/java/com/bencodez/votingplugin/control/domain/InspectionOperations.java +++ b/src/main/java/com/bencodez/votingplugin/control/domain/InspectionOperations.java @@ -65,7 +65,17 @@ public InspectionOperations(NodeRegistry registry, Clock clock) { this(registry, null, clock); } + private static final int MAX_AGENT_HEALTH = 12; + public synchronized InspectionView create(String nodeId, InspectionQuery query) { + return create(nodeId, query, false); + } + + synchronized InspectionView refreshAgentHealth(String nodeId) { + return create(nodeId, new InspectionQuery("network-health", Map.of()), true); + } + + private InspectionView create(String nodeId, InspectionQuery query, boolean agentHealth) { prune(); if (query == null) throw invalid("inspection query is required"); if (nodeId == null || !NODE_ID.matcher(nodeId).matches()) throw invalid("nodeId is invalid"); @@ -76,12 +86,28 @@ public synchronized InspectionView create(String nodeId, InspectionQuery query) || query.requiresRewardFiles() && !node.acceptedCapabilities().contains(InspectionQuery.REWARD_FILE_CAPABILITY)) { throw new ValidationException("NODE_UNAVAILABLE", "Node cannot answer inspection queries", List.of(nodeId)); } + if (agentHealth) { + var last = inspections.values().stream().filter(item -> item.nodeId.equals(nodeId) + && item.query.requiresNetworkHealth() && item.targetSession.equals(node.sessionId())) + .reduce((first, second) -> second).orElse(null); + if (last != null && (!"COMPLETE".equals(last.state) + || last.createdAt.isAfter(clock.instant().minusSeconds(30)))) return view(last); + if (inspections.values().stream().filter(item -> item.agentHealth).count() >= MAX_AGENT_HEALTH) { + var evictable = inspections.values().stream() + .filter(item -> item.agentHealth && "COMPLETE".equals(item.state)).findFirst().orElse(null); + if (evictable == null) throw new ValidationException("OPERATION_LIMIT", + "Agent health observation limit reached", List.of()); + append("INSPECTION_EVICTED", evictable.id, evictable.nodeId, evictable.query.kind()); + inspections.remove(evictable.id); + } + } evictOldestCompletedAtCapacity(); if (inspections.size() >= MAX_INSPECTIONS) { throw new ValidationException("OPERATION_LIMIT", "Too many retained inspections", List.of()); } UUID id = UUID.randomUUID(); StoredInspection stored = new StoredInspection(id, nodeId, node.sessionId(), query, clock.instant()); + stored.agentHealth = agentHealth; inspections.put(id, stored); try { // Deliberately record only the query type. Player names and filter values are not audit metadata. @@ -521,7 +547,7 @@ private void evictOldestCompletedAtCapacity() { Iterator> iterator = inspections.entrySet().iterator(); while (iterator.hasNext()) { StoredInspection stored = iterator.next().getValue(); - if (!"COMPLETE".equals(stored.state) || !stored.terminalResultObserved) continue; + if (!"COMPLETE".equals(stored.state) || !(stored.agentHealth || stored.terminalResultObserved)) continue; append("INSPECTION_EVICTED", stored.id, stored.nodeId, stored.query.kind()); iterator.remove(); return; @@ -550,6 +576,7 @@ private static final class StoredInspection { private UUID attemptId; private InspectionTaskResult result; private boolean terminalResultObserved; + private boolean agentHealth; private StoredInspection(UUID id, String nodeId, UUID targetSession, InspectionQuery query, Instant createdAt) { this.id = id; diff --git a/src/main/java/com/bencodez/votingplugin/control/domain/NodeRegistry.java b/src/main/java/com/bencodez/votingplugin/control/domain/NodeRegistry.java index 11b3c17..d0c68de 100644 --- a/src/main/java/com/bencodez/votingplugin/control/domain/NodeRegistry.java +++ b/src/main/java/com/bencodez/votingplugin/control/domain/NodeRegistry.java @@ -13,10 +13,18 @@ public interface NodeRegistry { List list(int offset, int limit); RegistryPage page(int offset, int limit, Long expectedRevision); NodeStatus find(String nodeId); + default java.time.Instant topologyObservedAt(String nodeId) { return null; } void requireSession(String nodeId, java.util.UUID sessionId); T withSession(String nodeId, java.util.UUID sessionId, java.util.function.Function action); + /** Topology writers and registration synchronize on this registry during authorization and queue creation. */ + default T withStableTopology(java.util.function.Supplier action) { + synchronized (this) { + return action.get(); + } + } + record RegistrationResult(NodeStatus node, boolean created) { } record SnapshotResult(NodeStatus node, boolean applied) { } record RegistryPage(List items, long revision, int total) { } diff --git a/src/main/java/com/bencodez/votingplugin/control/domain/VoteSitesDocument.java b/src/main/java/com/bencodez/votingplugin/control/domain/VoteSitesDocument.java index 1a9dcae..5ea8714 100644 --- a/src/main/java/com/bencodez/votingplugin/control/domain/VoteSitesDocument.java +++ b/src/main/java/com/bencodez/votingplugin/control/domain/VoteSitesDocument.java @@ -55,6 +55,23 @@ public static Inventory inventory(String content) { return new Inventory(Collections.unmodifiableList(sites)); } + public static List editableKeys() { + return FIELDS; + } + + static void requireReviewableRemoval(String content, String key) { + SiteInfo site = parse(content).byKey().get(key); + if (site == null) throw invalidOperation(); + for (String property : site.properties().keySet()) { + if (FIELD_SET.contains(property) && !property.startsWith("DisplayItem.")) continue; + if ("DisplayItem".equals(property) + && site.properties().get(property).getValueNode() instanceof MappingNode display + && !properties(display).isEmpty() + && Set.of("Material", "Amount").containsAll(properties(display).keySet())) continue; + throw invalidOperation(); + } + } + /** Adds one safe, absent site with all nine typed fields. */ public static String add(String content, String siteKey, Map fields) { Parsed parsed = parse(content); diff --git a/src/main/java/com/bencodez/votingplugin/control/http/ControlHttpServer.java b/src/main/java/com/bencodez/votingplugin/control/http/ControlHttpServer.java index e3b936f..4d79866 100644 --- a/src/main/java/com/bencodez/votingplugin/control/http/ControlHttpServer.java +++ b/src/main/java/com/bencodez/votingplugin/control/http/ControlHttpServer.java @@ -5,6 +5,7 @@ import com.bencodez.votingplugin.control.artifact.ArtifactStore; import com.bencodez.votingplugin.control.artifact.JenkinsVotingPluginSource; import com.bencodez.votingplugin.control.artifact.ArtifactStore.ArtifactException; +import com.bencodez.votingplugin.control.domain.AgentOperations; import com.bencodez.votingplugin.control.domain.NodeRegistry; import com.bencodez.votingplugin.control.domain.RegistrySnapshot; import com.bencodez.votingplugin.control.domain.ConfigurationOperations; @@ -112,6 +113,12 @@ public final class ControlHttpServer implements AutoCloseable { private static final int MAX_BACKENDS_PER_NODE_SUMMARY = 256; private static final long ARTIFACT_TRANSFER_TIMEOUT_SECONDS = 120; + private static final String AGENT_API = "/api/v1/agent/"; + private static final String AGENT_OWNER = "/api/v1/agent-admin/"; + private static final int AGENT_REQUEST_BYTES = 16 * 1024; + private final AgentOperations agentOperations; + private final boolean agentEnabled; + private final ObjectMapper agentJson; private final HttpServer server; private final ObjectMapper json; private final NodeRegistry registry; @@ -142,10 +149,15 @@ public ControlHttpServer(InetSocketAddress address, NodeRegistry registry, Contr public ControlHttpServer(InetSocketAddress address, NodeRegistry registry, ControlIdentity identity, CredentialStore credentials, String launchId) throws IOException { + this(address, registry, identity, credentials, launchId, false); + } + + public ControlHttpServer(InetSocketAddress address, NodeRegistry registry, ControlIdentity identity, + CredentialStore credentials, String launchId, boolean agentEnabled) throws IOException { this(address, registry, identity, credentials, new ConfigurationOperations(registry, new com.bencodez.votingplugin.control.domain.ConfigurationAuditLog( java.nio.file.Files.createTempDirectory("votingplugin-control-test-audit"), Clock.systemUTC()), - Clock.systemUTC()), Clock.systemUTC(), System::nanoTime, false, Set.of(), launchId); + Clock.systemUTC()), agentEnabled, launchId); } public ControlHttpServer(InetSocketAddress address, NodeRegistry registry, ControlIdentity identity, @@ -207,6 +219,26 @@ public ControlHttpServer(InetSocketAddress address, NodeRegistry registry, Contr secureCookies, trustedProxyAddresses, launchId); } + public ControlHttpServer(InetSocketAddress address, NodeRegistry registry, ControlIdentity identity, + CredentialStore credentials, ConfigurationOperations configurationOperations, + InspectionOperations inspectionOperations, ConfigurationSnapshots configurationSnapshots, + ArtifactStore artifactStore, DeploymentOperations deploymentOperations, + boolean secureCookies, Set trustedProxyAddresses, String launchId, + boolean agentEnabled) throws IOException { + this(address, registry, identity, credentials, configurationOperations, inspectionOperations, + configurationSnapshots, artifactStore, deploymentOperations, Clock.systemUTC(), System::nanoTime, + secureCookies, trustedProxyAddresses, launchId, agentEnabled); + } + + private ControlHttpServer(InetSocketAddress address, NodeRegistry registry, ControlIdentity identity, + CredentialStore credentials, ConfigurationOperations operations, + boolean agentEnabled, String launchId) throws IOException { + this(address, registry, identity, credentials, operations, + new InspectionOperations(registry, Clock.systemUTC()), temporarySnapshots(), temporaryArtifactStore(), + new DeploymentOperations(registry, Clock.systemUTC()), Clock.systemUTC(), System::nanoTime, + false, Set.of(), launchId, agentEnabled); + } + ControlHttpServer(InetSocketAddress address, NodeRegistry registry, ControlIdentity identity, CredentialStore credentials, ConfigurationOperations configurationOperations, Clock clock, java.util.function.LongSupplier nanoTime, boolean secureCookies, @@ -233,6 +265,18 @@ public ControlHttpServer(InetSocketAddress address, NodeRegistry registry, Contr ArtifactStore artifactStore, DeploymentOperations deploymentOperations, Clock clock, java.util.function.LongSupplier nanoTime, boolean secureCookies, Set trustedProxyAddresses, String launchId) throws IOException { + this(address, registry, identity, credentials, configurationOperations, inspectionOperations, + configurationSnapshots, artifactStore, deploymentOperations, clock, nanoTime, secureCookies, + trustedProxyAddresses, launchId, false); + } + + private ControlHttpServer(InetSocketAddress address, NodeRegistry registry, ControlIdentity identity, + CredentialStore credentials, ConfigurationOperations configurationOperations, + InspectionOperations inspectionOperations, ConfigurationSnapshots configurationSnapshots, + ArtifactStore artifactStore, DeploymentOperations deploymentOperations, + Clock clock, java.util.function.LongSupplier nanoTime, boolean secureCookies, + Set trustedProxyAddresses, String launchId, boolean agentEnabled) throws IOException { + this.agentEnabled = agentEnabled; this.registry = Objects.requireNonNull(registry, "registry"); this.identity = Objects.requireNonNull(identity, "identity"); this.credentials = Objects.requireNonNull(credentials, "credentials"); @@ -254,6 +298,17 @@ public ControlHttpServer(InetSocketAddress address, NodeRegistry registry, Contr json.getFactory().setStreamReadConstraints(StreamReadConstraints.builder() .maxNestingDepth(20).maxStringLength(ManagedConfiguration.MAX_CONTENT + 4096) .maxNumberLength(64).build()); + agentOperations = new AgentOperations(registry, configurationOperations, inspectionOperations, clock); + agentJson = json.copy().enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .disable(com.fasterxml.jackson.databind.MapperFeature.ALLOW_COERCION_OF_SCALARS) + .disable(DeserializationFeature.ACCEPT_FLOAT_AS_INT); + agentJson.coercionConfigFor(com.fasterxml.jackson.databind.type.LogicalType.Textual) + .setCoercion(com.fasterxml.jackson.databind.cfg.CoercionInputShape.Integer, + com.fasterxml.jackson.databind.cfg.CoercionAction.Fail) + .setCoercion(com.fasterxml.jackson.databind.cfg.CoercionInputShape.Float, + com.fasterxml.jackson.databind.cfg.CoercionAction.Fail) + .setCoercion(com.fasterxml.jackson.databind.cfg.CoercionInputShape.Boolean, + com.fasterxml.jackson.databind.cfg.CoercionAction.Fail); authLimiter = new AuthFailureLimiter(nanoTime, MAX_AUTH_FAILURES_PER_MINUTE, TimeUnit.MINUTES.toNanos(1)); passwordFailureLimiter = new PasswordFailureLimiter(nanoTime, MAX_PASSWORD_FAILURES_PER_CLIENT, TimeUnit.MINUTES.toNanos(1), MAX_PASSWORD_FAILURE_CLIENTS); @@ -390,6 +445,10 @@ private void route(HttpExchange exchange) throws IOException { send(exchange, 200, health); return; } + if (path != null && (path.startsWith(AGENT_API) || path.startsWith(AGENT_OWNER))) { + routeAgent(exchange, path); + return; + } if (AUTH_SETUP.equals(path)) { if ("GET".equals(exchange.getRequestMethod())) { send(exchange, 200, Map.of("required", !credentials.hasWebPassword(), @@ -1027,9 +1086,127 @@ static BackendPage boundedNodePage(List nodes) { return new BackendPage(List.copyOf(items), returned, truncated, List.copyOf(truncatedNodeIds)); } + private void routeAgent(HttpExchange exchange, String path) throws IOException { + if (!agentEnabled) { + error(exchange, 403, "AGENT_DISABLED", "MCP management is disabled on this Control instance", List.of()); + return; + } + if (exchange.getRequestURI().getRawQuery() != null + || !path.equals(exchange.getRequestURI().getRawPath())) { + throw new IllegalArgumentException("Invalid agent route"); + } + if (path.startsWith(AGENT_OWNER)) { + switch (path.substring(AGENT_OWNER.length())) { + case "grants" -> { + requireMethod(exchange, "GET"); + authenticateWebSession(exchange, false); + send(exchange, 200, agentOperations.list()); + } + case "issue" -> { + requireMethod(exchange, "POST"); + authenticateWebSession(exchange, true); + send(exchange, 201, agentOperations.issue(read(exchange, AgentOperations.Issue.class, true))); + } + case "revoke" -> { + requireMethod(exchange, "POST"); + authenticateWebSession(exchange, true); + agentOperations.revoke(readAgentId(exchange)); + send(exchange, 200, Map.of("revoked", true)); + } + case "review" -> { + requireMethod(exchange, "POST"); + authenticateWebSession(exchange, true); + send(exchange, 200, configurationOperations.getAgentReview(readAgentId(exchange))); + } + case "approve" -> { + requireMethod(exchange, "POST"); + authenticateWebSession(exchange, true); + send(exchange, 202, agentOperations.approve(readAgentId(exchange))); + } + default -> error(exchange, 404, "NOT_FOUND", "Route not found", List.of()); + } + return; + } + requireMethod(exchange, "POST"); + String token = bearer(exchange); + String route = path.substring(AGENT_API.length()); + String action = switch (route) { + case "nodes" -> "discover"; + case "topology", "health", "health-refresh" -> "health"; + case "routing-read", "routing-preview" -> "routing"; + case "transport" -> "transport"; + case "site-policy-read", "site-policy-preview" -> "site-policy"; + case "site-policy-batch" -> "site-policy-batch"; + case "guided-read", "guided-preview" -> "guided"; + case "proxy-method-read", "proxy-method-preview" -> "proxy-method"; + case "reward-read", "reward-preview" -> "rewards-editor"; + case "vote-sites-editor-read", "vote-sites-editor-preview" -> "vote-sites-editor"; + case "settings-read", "settings-preview" -> "general-settings"; + case "read", "preview", "status" -> route; + default -> null; + }; + if (action == null) { + error(exchange, 404, "NOT_FOUND", "Route not found", List.of()); + return; + } + try { + if ("guided".equals(action)) agentOperations.requireGuidedAccess(token); + else agentOperations.requireAccess(token, action); + Object result = switch (route) { + case "nodes" -> { + yield agentOperations.discover(token, read(exchange, AgentOperations.Discovery.class, true)); + } + case "topology" -> agentOperations.topology(token, read(exchange, AgentOperations.Discovery.class, true)); + case "health" -> agentOperations.health(token, read(exchange, AgentOperations.HealthRequest.class, true)); + case "health-refresh" -> agentOperations.refreshHealth(token, read(exchange, AgentOperations.RefreshHealth.class, true)); + case "guided-read" -> agentOperations.readGuided(token, read(exchange, AgentOperations.GuidedRead.class, true)); + case "guided-preview" -> agentOperations.previewGuided(token, read(exchange, AgentOperations.GuidedPreview.class, true)); + case "proxy-method-read" -> agentOperations.readProxyMethod(token, read(exchange, AgentOperations.ProxyMethodRead.class, true)); + case "proxy-method-preview" -> agentOperations.previewProxyMethod(token, read(exchange, AgentOperations.ProxyMethodPreview.class, true)); + case "reward-read" -> agentOperations.readReward(token, read(exchange, AgentOperations.RewardRead.class, true)); + case "reward-preview" -> agentOperations.previewReward(token, read(exchange, AgentOperations.RewardPreview.class, true)); + case "vote-sites-editor-read" -> agentOperations.readVoteSitesEditor(token, + read(exchange, AgentOperations.VoteSitesEditorRead.class, true)); + case "vote-sites-editor-preview" -> agentOperations.previewVoteSitesEditor(token, + read(exchange, AgentOperations.VoteSitesEditorPreview.class, true)); + case "settings-read" -> agentOperations.readGeneralSettings(token, read(exchange, AgentOperations.GeneralSettingsRead.class, true)); + case "settings-preview" -> agentOperations.previewGeneralSettings(token, read(exchange, AgentOperations.GeneralSettingsPreview.class, true)); + case "site-policy-read" -> agentOperations.readSitePolicy(token, read(exchange, AgentOperations.SitePolicyRead.class, true)); + case "site-policy-batch" -> agentOperations.previewSitePolicyBatch(token, read(exchange, AgentOperations.SitePolicyBatch.class, true)); + case "site-policy-preview" -> agentOperations.previewSitePolicy(token, read(exchange, AgentOperations.SitePolicyPreview.class, true)); + case "transport" -> agentOperations.checkTransport(token, read(exchange, AgentOperations.TransportRequest.class, true)); + case "routing-read" -> agentOperations.readRouting(token, read(exchange, AgentOperations.RoutingRead.class, true)); + case "routing-preview" -> agentOperations.previewRouting(token, read(exchange, AgentOperations.RoutingPreview.class, true)); + case "read" -> agentOperations.read(token, read(exchange, AgentOperations.Read.class, true)); + case "preview" -> agentOperations.preview(token, read(exchange, AgentOperations.Preview.class, true)); + case "status" -> agentOperations.status(token, readAgentId(exchange)); + default -> throw new IllegalStateException("Unhandled agent route"); + }; + byte[] bytes = agentJson.writeValueAsBytes(result); + if (bytes.length > 32 * 1024) throw new IllegalArgumentException("Agent result exceeds limit"); + sendBytes(exchange, 200, "application/json; charset=utf-8", bytes); + } catch (SecurityException denied) { + authenticationFailed(); + } + } + + private UUID readAgentId(HttpExchange exchange) throws IOException { + AgentId request = read(exchange, AgentId.class, true); + return AgentOperations.parseId(request.operationId()); + } + + private record AgentId(String operationId) { } + private T read(HttpExchange exchange, Class type) throws IOException { - String contentType = exchange.getRequestHeaders().getFirst("Content-Type"); - if (contentType == null || !contentType.toLowerCase(Locale.ROOT).startsWith("application/json")) { + return read(exchange, type, false); + } + + private T read(HttpExchange exchange, Class type, boolean agent) throws IOException { + int maximum = agent ? AGENT_REQUEST_BYTES : MAX_REQUEST_BYTES; + String contentType = agent ? singleHeader(exchange, "Content-Type") + : exchange.getRequestHeaders().getFirst("Content-Type"); + if (contentType == null || (agent ? !"application/json".equalsIgnoreCase(contentType.split(";", 2)[0].trim()) + : !contentType.toLowerCase(Locale.ROOT).startsWith("application/json"))) { throw new ValidationException("UNSUPPORTED_MEDIA_TYPE", "Content-Type must be application/json", List.of()); } List lengths = exchange.getRequestHeaders().get("Content-Length"); @@ -1046,8 +1223,8 @@ private T read(HttpExchange exchange, Class type) throws IOException { if (length < 0) { throw new IllegalArgumentException("Invalid Content-Length"); } - if (length > MAX_REQUEST_BYTES) { - throw new RequestTooLargeException(MAX_REQUEST_BYTES); + if (length > maximum) { + throw new RequestTooLargeException(maximum); } } byte[] bytes; @@ -1057,8 +1234,8 @@ private T read(HttpExchange exchange, Class type) throws IOException { int count; while ((count = input.read(buffer)) != -1) { total += count; - if (total > MAX_REQUEST_BYTES) { - throw new RequestTooLargeException(MAX_REQUEST_BYTES); + if (total > maximum) { + throw new RequestTooLargeException(maximum); } output.write(buffer, 0, count); } @@ -1067,6 +1244,11 @@ private T read(HttpExchange exchange, Class type) throws IOException { String text = StandardCharsets.UTF_8.newDecoder() .onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT) .decode(ByteBuffer.wrap(bytes)).toString(); + if (agent) { + T value = agentJson.readValue(text, type); + requireRequest(value); + return value; + } if (type == ConfigurationRequests.SettingsState.class || type == ConfigurationRequests.SettingsPreview.class || type == ConfigurationRequests.SettingsDiscard.class || type == ConfigurationRequests.VoteSitesState.class || type == ConfigurationRequests.VoteSitesPreview.class || type == ConfigurationRequests.VoteSitesDiscard.class diff --git a/src/main/java/com/bencodez/votingplugin/control/mcp/StdioAdapter.java b/src/main/java/com/bencodez/votingplugin/control/mcp/StdioAdapter.java new file mode 100644 index 0000000..fd6ece3 --- /dev/null +++ b/src/main/java/com/bencodez/votingplugin/control/mcp/StdioAdapter.java @@ -0,0 +1,487 @@ +package com.bencodez.votingplugin.control.mcp; + +import com.bencodez.votingplugin.control.domain.GeneralSettingsDocument; +import com.bencodez.votingplugin.control.domain.GuidedSettings; +import com.bencodez.votingplugin.control.domain.VoteSitesDocument; + +import com.fasterxml.jackson.core.StreamReadConstraints; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.json.JsonMapper; +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Flow; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +public final class StdioAdapter { + private static final int MAX_REQUEST = 16 * 1024; + private static final int MAX_RESULT = 32 * 1024; + private static final List VERSIONS = List.of("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"); + private static final ObjectMapper JSON = JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS).build(); + static { + JSON.getFactory().setStreamReadConstraints(StreamReadConstraints.builder() + .maxNestingDepth(16).maxStringLength(MAX_RESULT).maxNumberLength(64).build()); + } + private static final Map TOOLS = tools(); + + private final URI origin; + private final String token; + private final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)) + .followRedirects(HttpClient.Redirect.NEVER).build(); + private String version; + private boolean ready; + + public StdioAdapter(String origin, String token) { + if (origin == null || token == null || !token.matches("vp-agent-[0-9a-f-]{36}\\.[A-Za-z0-9_-]{43}")) { + throw new IllegalArgumentException("Configure the Control origin and scoped credential"); + } + this.origin = URI.create(origin); + String host = this.origin.getHost(); + if (host == null || this.origin.getRawUserInfo() != null || this.origin.getRawQuery() != null + || this.origin.getRawFragment() != null || !Set.of("", "/").contains(this.origin.getRawPath()) + || !("https".equals(this.origin.getScheme()) || ("http".equals(this.origin.getScheme()) + && Set.of("127.0.0.1", "[::1]").contains(host)))) { + throw new IllegalArgumentException("Use an HTTPS Control origin or a literal loopback HTTP origin"); + } + this.token = token; + } + + public void run(InputStream source, OutputStream output) throws IOException, InterruptedException { + BufferedInputStream input = new BufferedInputStream(source); + byte[] line; + while ((line = readFrame(input)) != null) { + Object reply = dispatch(line); + if (reply == null) continue; + output.write(JSON.writeValueAsBytes(reply)); + output.write('\n'); + output.flush(); + } + } + + private Object dispatch(byte[] line) throws InterruptedException { + JsonNode request; + try { + request = JSON.readTree(StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(line)).toString()); + } catch (IOException failure) { + return error(JSON.nullNode(), -32700, "Invalid JSON"); + } + JsonNode id = request == null ? JSON.nullNode() : request.path("id"); + if (request == null || !request.isObject() || !"2.0".equals(request.path("jsonrpc").asText()) + || !request.path("method").isTextual() + || !(id.isMissingNode() || id.isTextual() || id.isIntegralNumber())) { + return error(JSON.nullNode(), -32600, "Invalid request"); + } + String method = request.path("method").asText(); + if (id.isMissingNode()) { + if (version != null && "notifications/initialized".equals(method)) ready = true; + return null; + } + JsonNode params = request.path("params"); + return switch (method) { + case "initialize" -> initialize(id, params); + case "ping" -> reply(id, "result", Map.of()); + case "tools/list" -> ready ? reply(id, "result", Map.of("tools", + TOOLS.values().stream().map(Tool::descriptionJson).toList())) + : error(id, -32002, "Initialize MCP first"); + case "tools/call" -> ready ? call(id, params) : error(id, -32002, "Initialize MCP first"); + default -> error(id, -32601, "Method not found"); + }; + } + + private Object initialize(JsonNode id, JsonNode params) { + if (version != null || !params.path("protocolVersion").isTextual()) { + return error(id, -32602, "Invalid initialization"); + } + String requested = params.path("protocolVersion").asText(); + version = VERSIONS.contains(requested) ? requested : VERSIONS.get(0); + return reply(id, "result", Map.of( + "protocolVersion", version, + "capabilities", Map.of("tools", Map.of()), + "serverInfo", Map.of("name", "votingplugin-control", "version", "1.0.0"))); + } + + private Object call(JsonNode id, JsonNode params) throws InterruptedException { + Tool tool = TOOLS.get(params.path("name").asText()); + if (tool == null) return error(id, -32602, "Unknown tool"); + JsonNode arguments = params.has("arguments") ? params.get("arguments") : JSON.createObjectNode(); + if (!arguments.isObject()) return error(id, -32602, "Invalid arguments"); + try { + HttpRequest request = HttpRequest.newBuilder(origin.resolve("/api/v1/agent/" + tool.route())) + .timeout(Duration.ofSeconds(8)) + .header("Authorization", "Bearer " + token).header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofByteArray(JSON.writeValueAsBytes(arguments))).build(); + HttpResponse response = request(request); + if (response.statusCode() != 200) { + String code = JSON.readTree(response.body()).path("error").path("code").asText(""); + return toolError(id, "Control rejected the request (" + response.statusCode() + + (code.matches("[A-Z_]{1,48}") ? ", " + code : "") + ")."); + } + JsonNode result = JSON.readTree(response.body()); + if (!validResult(tool.route(), result)) return toolError(id, "Invalid Control response."); + Map body = new LinkedHashMap<>(); + body.put("content", List.of(Map.of("type", "text", "text", JSON.writeValueAsString(result)))); + if (version.compareTo("2025-06-18") >= 0) body.put("structuredContent", result); + return reply(id, "result", body); + } catch (IOException | RuntimeException failure) { + return toolError(id, "Control request failed. Check the configured origin and operation status."); + } + } + + private static boolean validResult(String route, JsonNode result) { + if ("topology".equals(route)) return validTopology(result); + if ("health".equals(route)) return validHealth(result); + if ("health-refresh".equals(route)) { + return fields(result, Set.of("nodeId", "state")) && nodeId(result.path("nodeId")) + && Set.of("RUNNING", "SUCCEEDED", "FAILED").contains(result.path("state").asText()); + } + if ("nodes".equals(route)) { + JsonNode items = result.path("items"); + if (!fields(result, Set.of("items", "nextOffset")) || !items.isArray() || items.size() > 50) return false; + if (result.has("nextOffset") && (!result.path("nextOffset").isIntegralNumber() + || !result.path("nextOffset").canConvertToInt() || result.path("nextOffset").intValue() < 1 + || result.path("nextOffset").intValue() > 4097)) return false; + for (JsonNode node : items) { + if (!fields(node, Set.of("nodeId", "platform", "online", "acceptedCapabilities")) + || !node.path("nodeId").asText().matches("[A-Za-z0-9][A-Za-z0-9._-]{0,63}") + || !node.path("nodeId").isTextual() || !node.path("platform").isTextual() + || !node.path("online").isBoolean() || !node.path("acceptedCapabilities").isArray()) { + return false; + } + for (JsonNode capability : node.path("acceptedCapabilities")) { + if (!capability.isTextual()) return false; + } + } + return true; + } + if (!fields(result, Set.of("operationId", "applyOperationId", "type", "state", "nodes", + "browserReviewReady", "reviewPath", "results", "values")) + || !canonicalId(result.path("operationId")) + || !Set.of("READ", "PREVIEW", "APPLY").contains(result.path("type").asText()) + || !Set.of("RUNNING", "SUCCEEDED", "COMPLETED_WITH_ERRORS").contains(result.path("state").asText()) + || !result.path("browserReviewReady").isBoolean() + || !result.path("nodes").isObject() || result.path("nodes").isEmpty() + || result.path("nodes").size() > com.bencodez.votingplugin.control.domain.ConfigurationOperations.MAX_AGENT_TARGETS + || !result.path("results").isObject() || result.path("results").size() > result.path("nodes").size()) return false; + if (result.has("applyOperationId") && !canonicalId(result.path("applyOperationId"))) return false; + if (result.has("reviewPath") && !result.path("reviewPath").asText().equals( + "/#agent-review/" + result.path("operationId").asText())) return false; + var nodes = result.path("nodes").fields(); + while (nodes.hasNext()) { + var node = nodes.next(); + if (!node.getKey().matches("[A-Za-z0-9][A-Za-z0-9._-]{0,63}") + || !Set.of("QUEUED", "IN_PROGRESS", "COMPLETE").contains(node.getValue().asText())) return false; + } + if (result.has("values") && !validValues(result)) return false; + var results = result.path("results").fields(); + while (results.hasNext()) { + var row = results.next(); + JsonNode details = row.getValue(); + if (!result.path("nodes").has(row.getKey()) + || !fields(details, Set.of("code", "success", "rolledBack", "reloaded", "restartRequired", + "persistence", "restartAfterAcknowledgement", "runtimeReadiness")) + || !details.path("code").asText().matches("[A-Z][A-Z0-9_]{0,63}") + || !details.path("success").isBoolean() || !details.path("rolledBack").isBoolean() + || !details.path("reloaded").isBoolean() + || details.has("restartRequired") && !details.path("restartRequired").isBoolean() + || details.has("persistence") && !Set.of("REPORTED_PERSISTED", "ROLLED_BACK", "UNCONFIRMED") + .contains(details.path("persistence").asText()) + || details.has("restartAfterAcknowledgement") && !details.path("restartAfterAcknowledgement").isBoolean() + || details.has("runtimeReadiness") && !"UNKNOWN".equals(details.path("runtimeReadiness").asText())) return false; + } + return true; + } + + private static boolean validTopology(JsonNode result) { + JsonNode items = result.path("items"); + if (!fields(result, Set.of("items", "nextOffset")) || !items.isArray() || items.size() > 50) return false; + if (result.hasNonNull("nextOffset") && (!result.path("nextOffset").isIntegralNumber() + || !result.path("nextOffset").canConvertToInt() || result.path("nextOffset").intValue() < 1 + || result.path("nextOffset").intValue() > 4097)) return false; + for (JsonNode row : items) { + if (!fields(row, Set.of("nodeId", "platform", "online", "topologyObservedAt", "topologyFresh", + "backendIds", "linksTruncated")) || !nodeId(row.path("nodeId")) + || !Set.of("VELOCITY", "BUNGEECORD", "BUKKIT").contains(row.path("platform").asText()) + || !row.path("online").isBoolean() || !row.path("topologyFresh").isBoolean() + || !row.path("linksTruncated").isBoolean() + || row.hasNonNull("topologyObservedAt") && !timestamp(row.path("topologyObservedAt")) + || !nodeList(row.path("backendIds"), 6)) return false; + } + return true; + } + + private static boolean validHealth(JsonNode result) { + JsonNode checks = result.path("checks"); + if (!fields(result, Set.of("generatedAt", "truncated", "checks")) || !timestamp(result.path("generatedAt")) + || !result.path("truncated").isBoolean() || !checks.isArray() || checks.size() > 75) return false; + for (JsonNode check : checks) { + if (!fields(check, Set.of("id", "status", "affectedNodes", "restartRequired")) + || !check.path("id").asText().matches("[a-zA-Z][a-zA-Z0-9.-]{0,95}") + || !Set.of("PASS", "WARNING", "FAIL", "UNKNOWN", "INFO").contains(check.path("status").asText()) + || !check.path("restartRequired").isBoolean() || !nodeList(check.path("affectedNodes"), 3)) return false; + } + return true; + } + + private static boolean nodeList(JsonNode nodes, int maximum) { + if (!nodes.isArray() || nodes.size() > maximum) return false; + for (JsonNode node : nodes) if (!nodeId(node)) return false; + return true; + } + + private static boolean nodeId(JsonNode node) { + return node.isTextual() && node.asText().matches("[A-Za-z0-9][A-Za-z0-9._-]{0,63}"); + } + + private static boolean timestamp(JsonNode node) { + if (!node.isTextual() || node.asText().length() > 40) return false; + try { + java.time.Instant.parse(node.asText()); + return true; + } catch (java.time.format.DateTimeParseException failure) { + return false; + } + } + + private static boolean validValues(JsonNode result) { + JsonNode values = result.path("values"); + Set keys = new java.util.HashSet<>(GeneralSettingsDocument.editableKeys()); + keys.addAll(VoteSitesDocument.editableKeys()); + keys.addAll(GuidedSettings.resultKeys()); + keys.addAll(Set.of("siteKey", "rewardsConfigured", "rewardField", "rewardValue", "method", "useBungeecord")); + keys.addAll(Set.of("name", "exists", "serviceSite", "voteUrl", "enabled", "displayName", "priority", + "hidden", "voteDelay", "material", "displayItem.amount", "sendVotesToAllServers", "blockedServers")); + if (!"READ".equals(result.path("type").asText()) || !fields(values, keys)) return false; + for (JsonNode value : values) if (!value.isTextual()) return false; + return true; + } + + private static boolean fields(JsonNode object, Set permitted) { + if (!object.isObject()) return false; + var fields = object.fieldNames(); + while (fields.hasNext()) { + if (!permitted.contains(fields.next())) return false; + } + return true; + } + + private static boolean canonicalId(JsonNode id) { + return id.isTextual() && id.asText().matches( + "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + } + + private HttpResponse request(HttpRequest request) throws IOException, InterruptedException { + var pending = client.sendAsync(request, ignored -> new BoundedBody()); + try { + return pending.get(8, TimeUnit.SECONDS); + } catch (ExecutionException | TimeoutException failure) { + throw new IOException("Control request failed", failure); + } finally { + if (!pending.isDone()) pending.cancel(true); + } + } + + private static byte[] readFrame(InputStream input) throws IOException { + ByteArrayOutputStream frame = new ByteArrayOutputStream(); + int next; + while ((next = input.read()) != -1 && next != '\n') { + if (frame.size() == MAX_REQUEST) throw new IOException("MCP frame exceeds the input limit"); + frame.write(next); + } + if (next == -1) return null; + return frame.toByteArray(); + } + + private static Object toolError(JsonNode id, String text) { + return reply(id, "result", Map.of("isError", true, "content", List.of(Map.of("type", "text", "text", text)))); + } + + private static Object error(JsonNode id, int code, String message) { + return reply(id, "error", Map.of("code", code, "message", message)); + } + + private static Object reply(JsonNode id, String field, Object body) { + return Map.of("jsonrpc", "2.0", "id", id, field, body); + } + + private static Map tools() { + Map tools = new LinkedHashMap<>(); + Map node = Map.of("type", "string", "pattern", "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$"); + Map name = Map.of("type", "string", "pattern", "^[A-Za-z0-9_-]{1,64}$"); + Map id = Map.of("type", "string", "pattern", + "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"); + Map flag = Map.of("type", "boolean"); + Map text = Map.of("type", "string", "minLength", 1, "maxLength", 200); + tools.put("list_nodes", new Tool("list_nodes", "nodes", "List authorized enrolled Control nodes.", + object(Map.of("offset", Map.of("type", "integer", "minimum", 0, "maximum", 4097)), List.of()))); + tools.put("get_topology", new Tool("get_topology", "topology", "Read scoped node topology and observation freshness.", + object(Map.of("offset", Map.of("type", "integer", "minimum", 0, "maximum", 4097)), List.of()))); + tools.put("get_network_health", new Tool("get_network_health", "health", "Read scoped Network Doctor checks from current evidence.", + object(Map.of("nodeIds", Map.of("type", "array", "items", node, "minItems", 1, + "maxItems", 25, "uniqueItems", true)), List.of("nodeIds")))); + tools.put("refresh_node_health", new Tool("refresh_node_health", "health-refresh", + "Queue the read-only Network Doctor observation for an authorized node.", + object(Map.of("nodeId", node), List.of("nodeId")))); + var guidedPreset = Map.of("type", "string", "enum", List.of("common-settings", "vote-logging", "vote-party")); + var guidedTarget = object(Map.of("nodeId", node, "presetReadId", id, "presenceReadId", id), + List.of("nodeId", "presetReadId", "presenceReadId")); + var guidedOverrides = object(Map.of("processRewards", flag, "extraAllSitesCheck", flag, + "disableNoServiceSiteMessage", flag, "enabled", flag, "giveAllPlayers", flag, "onlineOnly", flag, + "purgeDays", Map.of("anyOf", List.of(Map.of("const", -1), Map.of("type", "integer", "minimum", 1, "maximum", 3650))), + "votesRequired", Map.of("type", "integer", "minimum", 1, "maximum", 100000), + "broadcast", Map.of("type", "string", "minLength", 1, "maxLength", 500)), List.of()); + tools.put("read_guided_settings", new Tool("read_guided_settings", "guided-read", + "Collect one typed preset read or a non-exported masked key-presence read. Both must match to preview.", + object(Map.of("nodeId", node, "preset", guidedPreset, "evidence", + Map.of("enum", List.of("PRESET", "PRESENCE"))), List.of("nodeId", "preset", "evidence")))); + tools.put("preview_guided_settings", new Tool("preview_guided_settings", "guided-preview", + "Preview common settings, VoteLog or Vote Party with both READ ids per target and browser approval.", + object(Map.of("preset", guidedPreset, "targets", Map.of("type", "array", + "items", guidedTarget, "minItems", 1, "maxItems", 4), "overrides", guidedOverrides), + List.of("preset", "targets", "overrides")))); + var method = Map.of("type", "string", "enum", List.of("PLUGINMESSAGING", "REDIS", "MQTT", "SOCKETS", "MYSQL", "HTTP")); + var rolloutTarget = object(Map.of("nodeId", node, "readOperationId", id), List.of("nodeId", "readOperationId")); + tools.put("read_proxy_method", new Tool("read_proxy_method", "proxy-method-read", + "Read the current method on an authorized node for a proposed transport capability.", + object(Map.of("nodeId", node, "method", method), List.of("nodeId", "method")))); + tools.put("preview_proxy_method", new Tool("preview_proxy_method", "proxy-method-preview", + "Preview one method for an authorized proxy and all its reported backends. Browser approval is required.", + object(Map.of("proxyNodeId", node, "method", method, "targets", Map.of("type", "array", + "minItems", 2, "maxItems", 10, "items", rolloutTarget)), List.of("proxyNodeId", "method", "targets")))); + var rewardFields = Map.of( + "type", "string", "pattern", "^(Money|Chance|Messages[.](Player|Broadcast)|Items[.][A-Za-z0-9_-]{1,64}[.](Material|Amount))$"); + var rewardSelector = new LinkedHashMap<>(object(Map.of("nodeId", node, "siteKey", name, + "rewardName", Map.of("type", "string", "pattern", "^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$"), + "field", rewardFields), List.of("nodeId", "field"))); + rewardSelector.put("oneOf", List.of(Map.of("required", List.of("siteKey")), Map.of("required", List.of("rewardName")))); + tools.put("read_reward_field", new Tool("read_reward_field", "reward-read", + "Read one supported scalar field from an inline vote-site reward or one named reward.", + rewardSelector)); + tools.put("preview_reward_field", new Tool("preview_reward_field", "reward-preview", + "Preview replacing the exact scalar selected by a current reward read. Browser approval is required.", + object(Map.of("nodeId", node, "readOperationId", id, "value", + Map.of("oneOf", List.of(Map.of("type", "number", "minimum", 0), + Map.of("type", "string", "maxLength", 500)))), + List.of("nodeId", "readOperationId", "value")))); + Map editorFields = Map.of( + "Enabled", flag, "Hidden", flag, "Name", Map.of("type", "string", "maxLength", 200), + "ServiceSite", Map.of("type", "string", "minLength", 1, "maxLength", 2048), + "VoteURL", Map.of("type", "string", "minLength", 1, "maxLength", 500), + "VoteDelay", Map.of("type", "string", "minLength", 1, "maxLength", 64), + "Priority", Map.of("type", "integer", "minimum", Integer.MIN_VALUE, "maximum", Integer.MAX_VALUE), + "DisplayItem.Material", Map.of("type", "string", "pattern", "^[A-Za-z0-9_:-]{1,100}$"), + "DisplayItem.Amount", Map.of("type", "integer", "minimum", 1, "maximum", 64)); + tools.put("read_vote_site_editor", new Tool("read_vote_site_editor", "vote-sites-editor-read", + "Read the typed editor fields for one exact site on an authorized backend.", + object(Map.of("nodeId", node, "siteKey", name), List.of("nodeId", "siteKey")))); + tools.put("preview_vote_site_editor", new Tool("preview_vote_site_editor", "vote-sites-editor-preview", + "Preview adding, editing, or removing a named site for review in Control. Removal requires a site with only reviewable fields.", + object(Map.of("nodeId", node, "siteKey", name, "readOperationId", id, + "action", Map.of("type", "string", "enum", List.of("ADD", "EDIT", "REMOVE")), + "fields", object(editorFields, List.of())), + List.of("nodeId", "siteKey", "readOperationId", "action")))); + Map settings = new LinkedHashMap<>(); + for (String key : GeneralSettingsDocument.editableKeys()) { + settings.put(key, Map.of("oneOf", List.of(flag, Map.of("type", "string", "maxLength", 32)))); + } + tools.put("read_general_settings", new Tool("read_general_settings", "settings-read", + "Read curated settings for one authorized backend or proxy.", + object(Map.of("nodeId", node), List.of("nodeId")))); + tools.put("preview_general_settings", new Tool("preview_general_settings", "settings-preview", + "Preview typed General Settings changes for browser approval.", + object(Map.of("nodeId", node, "readOperationId", id, "overrides", object(settings, List.of())), + List.of("nodeId", "readOperationId", "overrides")))); + tools.put("read_site_policy", new Tool("read_site_policy", "site-policy-read", + "Read automatic vote-site creation policy on one authorized backend.", + object(Map.of("nodeId", node), List.of("nodeId")))); + tools.put("preview_site_policy_batch", new Tool("preview_site_policy_batch", "site-policy-batch", + "Preview one policy change on an explicit set of at most ten authorized backends.", + object(Map.of("targets", Map.of("type", "array", "minItems", 1, "maxItems", 10, "items", + object(Map.of("nodeId", node, "readOperationId", id), List.of("nodeId", "readOperationId"))), + "enabled", flag), List.of("targets", "enabled")))); + tools.put("preview_site_policy", new Tool("preview_site_policy", "site-policy-preview", + "Preview automatic vote-site creation policy for browser approval.", + object(Map.of("nodeId", node, "readOperationId", id, "enabled", flag), + List.of("nodeId", "readOperationId", "enabled")))); + tools.put("check_transport", new Tool("check_transport", "transport", + "Run a non-vote status probe between an authorized proxy and backend.", + object(Map.of("proxyNodeId", node, "backendNodeId", node), List.of("proxyNodeId", "backendNodeId")))); + tools.put("read_proxy_routing", new Tool("read_proxy_routing", "routing-read", + "Read routing settings on one authorized proxy.", + object(Map.of("nodeId", node), List.of("nodeId")))); + tools.put("preview_proxy_routing", new Tool("preview_proxy_routing", "routing-preview", + "Preview routing settings for browser approval on one authorized proxy.", + object(Map.of("nodeId", node, "readOperationId", id, "sendVotesToAllServers", flag, + "blockedServers", Map.of("type", "array", "items", node, "maxItems", 256, "uniqueItems", true)), + List.of("nodeId", "readOperationId", "sendVotesToAllServers", "blockedServers")))); + tools.put("read_setup", new Tool("read_setup", "read", "Read one named backend vote site.", + object(Map.of("nodeId", node, "name", name), List.of("nodeId", "name")))); + tools.put("preview_setup", new Tool("preview_setup", "preview", + "Preview a named backend vote site. The operator reviews and applies in Control.", + object(Map.of("nodeId", node, "readOperationId", id, "options", object(Map.of( + "name", name, "serviceSite", text, "voteUrl", Map.of("type", "string", "maxLength", 500), + "enabled", flag, "displayName", text, "priority", Map.of("type", "integer", + "minimum", 0, "maximum", 100), "hidden", flag, "voteDelay", text, "material", text), + List.of("name", "serviceSite", "voteUrl"))), List.of("nodeId", "readOperationId", "options")))); + tools.put("get_operation", new Tool("get_operation", "status", "Track a scoped setup operation.", + object(Map.of("operationId", id), List.of("operationId")))); + return java.util.Collections.unmodifiableMap(tools); + } + + private static Map object(Map properties, List required) { + return Map.of("type", "object", "properties", properties, "required", required, "additionalProperties", false); + } + + private record Tool(String name, String route, String description, Map schema) { + Map descriptionJson() { + return Map.of("name", name, "description", description, "inputSchema", schema); + } + } + + private static final class BoundedBody implements HttpResponse.BodySubscriber { + private final HttpResponse.BodySubscriber delegate = HttpResponse.BodySubscribers.ofByteArray(); + private Flow.Subscription subscription; + private long size; + + public CompletionStage getBody() { return delegate.getBody(); } + + public void onSubscribe(Flow.Subscription subscription) { + this.subscription = subscription; + delegate.onSubscribe(subscription); + } + + public void onNext(List buffers) { + size += buffers.stream().mapToLong(ByteBuffer::remaining).sum(); + if (size > MAX_RESULT) { + subscription.cancel(); + delegate.onError(new IOException("Control response exceeds the result limit")); + return; + } + delegate.onNext(buffers); + } + + public void onError(Throwable failure) { delegate.onError(failure); } + + public void onComplete() { delegate.onComplete(); } + } +} diff --git a/src/main/resources/web/app.js b/src/main/resources/web/app.js index fd8b859..3fcbb6c 100644 --- a/src/main/resources/web/app.js +++ b/src/main/resources/web/app.js @@ -1062,6 +1062,141 @@ function rememberOperation(operation) { renderOperationHistory(); } +const agentGrantForm = document.querySelector('#agent-grant-form'); +const agentGrantStatus = document.querySelector('#agent-grant-status'); +const agentCredentialOutput = document.querySelector('#agent-credential-output'); +const agentGrants = document.querySelector('#agent-grants'); +const agentReview = document.querySelector('#agent-review'); +const agentReviewDetail = document.querySelector('#agent-review-detail'); +const agentReviewStatus = document.querySelector('#agent-review-status'); +const agentReviewApply = document.querySelector('#agent-review-apply'); +let agentReviewId = null; + +function agentAdmin(action, body) { + return authorized('/api/v1/agent-admin/' + action, body === undefined ? {} : { + method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(body) + }); +} + +function clearAgentCredential() { + agentCredentialOutput.querySelector('input').value = ''; + agentCredentialOutput.hidden = true; +} + +async function loadAgentGrants() { + const grants = await agentAdmin('grants'); + agentGrants.replaceChildren(...grants.map(grant => { + const row = document.createElement('p'); + const scope = grant.proxyNodeId ? `Proxy ${grant.proxyNodeId} · ${grant.nodeCount} enrolled nodes` + : grant.nodeIds.join(', '); + const label = document.createTextNode(`${grant.id} · ${scope} · ${grant.actions.join(', ')} · ${grant.expiresAt} `); + const revoke = text(document.createElement('button'), 'Revoke'); + revoke.type = 'button'; + revoke.addEventListener('click', async () => { + revoke.disabled = true; + clearAgentCredential(); + try { + await agentAdmin('revoke', {operationId: grant.id}); + await loadAgentGrants(); + } catch (error) { text(agentGrantStatus, error.message); } + finally { revoke.disabled = false; } + }); + row.append(label, revoke); + return row; + })); +} + +agentGrantForm.addEventListener('submit', async event => { + event.preventDefault(); + clearAgentCredential(); + const button = event.submitter; + button.disabled = true; + try { + const form = new FormData(agentGrantForm); + const grant = await agentAdmin('issue', { + nodeIds: form.get('nodes').split(',').map(id => id.trim()).filter(Boolean), + proxyNodeId: form.get('proxy').trim() || null, + actions: form.getAll('actions'), + minutes: Number(form.get('minutes')) + }); + agentCredentialOutput.querySelector('input').value = grant.token; + agentCredentialOutput.hidden = false; + text(agentGrantStatus, `Grant expires at ${grant.expiresAt}.`); + await loadAgentGrants(); + } catch (error) { text(agentGrantStatus, error.message); } + finally { button.disabled = false; } +}); + +document.querySelector('#agent-grant-refresh').addEventListener('click', () => { + loadAgentGrants().catch(error => text(agentGrantStatus, error.message)); +}); + +async function reviewAgentPreview(operationId) { + agentReviewId = operationId; + agentReviewApply.disabled = true; + text(agentReviewDetail, ''); + text(agentReviewStatus, 'Loading preview…'); + if (!agentReview.open) agentReview.showModal(); + try { + const {operation, before, beforeByNode, after} = await agentAdmin('review', {operationId}); + if (agentReviewId !== operationId || !agentReview.open) return; + const configuration = operation.configuration; + const routing = configuration.domain === 'proxy-routing'; + const guided = Boolean(after && Object.keys(after).length) && ['common-settings', 'vote-logging', 'vote-party'].includes(configuration.preset); + const fields = routing ? [ + ['sendVotesToAllServers', String(configuration.sendVotesToAllServers)], + ['blockedServers', `[${configuration.blockedServers.join(', ')}]`] + ] : Object.entries(configuration.domain === 'file' || guided ? (after || {}) : configuration.options); + if (configuration.preset === 'vote-site') fields.push(['displayItem.amount', '1']); + const methodRollout = configuration.preset === 'proxy-method'; + const fieldDetails = prior => [...fields, ...(methodRollout && Object.hasOwn(prior, 'useBungeecord') + ? [['useBungeecord', 'true']] : [])].filter(([key]) => !guided || Object.hasOwn(prior, key)).map(([key, value]) => + `${configuration.preset === 'auto-create-vote-sites' ? 'enabled (current effective value)' : key}: ${(configuration.preset !== 'vote-site' || prior.exists === 'true') && Object.hasOwn(prior, key) + ? JSON.stringify(prior[key]) : '(absent)'} → ${JSON.stringify(value)}`).join('\n'); + const targets = Object.entries(beforeByNode || {}); + const details = targets.length > 1 ? targets.map(([nodeId, prior]) => + `${nodeId} · revision ${operation.results?.[nodeId]?.revision || '(pending)'}\n${fieldDetails(prior)}`).join('\n\n') + : fieldDetails(before); + const rolloutNote = methodRollout + ? '\nBackends persist and reload first. Partial persistence is possible. Proxy runtime replacement follows acknowledgement. Proxy revision covers the method only.' + : ''; + text(agentReviewDetail, `Agent ${operation.agentId} +${operationSummary(operation)} + +Proposed settings +${details}${rolloutNote}`); + text(agentReviewStatus, operation.browserReviewReady ? 'Review the listed changes before applying.' + : 'This preview is not ready for approval. Refresh Activity to check again.'); + agentReviewApply.disabled = !operation.browserReviewReady; + } catch (error) { + if (agentReviewId === operationId && agentReview.open) text(agentReviewStatus, error.message); + } +} + +agentReviewApply.addEventListener('click', async () => { + const operationId = agentReviewId; + agentReviewApply.disabled = true; + try { + const operation = await agentAdmin('approve', {operationId}); + if (agentReviewId !== operationId || !agentReview.open) return; + text(agentReviewStatus, `Apply queued · ${operation.operationId}`); + await loadOperationHistory(); + } catch (error) { + if (agentReviewId === operationId && agentReview.open) text(agentReviewStatus, error.message); + } +}); + +agentReview.addEventListener('close', () => { + agentReviewId = null; + agentReviewApply.disabled = true; + text(agentReviewDetail, ''); + text(agentReviewStatus, ''); +}); + +function agentReviewFromHash() { + return /^#agent-review\/([0-9a-f-]{36})$/.exec(window.location.hash)?.[1]; +} + function renderOperationHistory() { operationHistory.replaceChildren(); if (operationHistoryItems.length === 0 && deploymentHistoryItems.length === 0) { @@ -1110,6 +1245,12 @@ function renderOperationHistory() { }); actions.append(retry); } + if (operation.type === 'PREVIEW' && operation.agentId) { + const review = text(document.createElement('button'), 'Review agent preview'); + review.type = 'button'; + review.addEventListener('click', () => void reviewAgentPreview(operation.operationId)); + actions.append(review); + } if (operation.type === 'PREVIEW' && operation.state === 'SUCCEEDED' && operation.approvalToken && operation.configuration?.domain === 'quick-setup' && !['proxy-method', 'reward-builder', 'sync-vote-sites'].includes(operation.configuration?.preset)) { @@ -1365,6 +1506,7 @@ async function loadSetupState() { } function applyAuthenticatedSession(body) { + const agentPreview = agentReviewFromHash(); configurationTargetNodeId = null; settingsEditor?.clear(); settingsHealthReader?.clear(); @@ -1376,6 +1518,7 @@ function applyAuthenticatedSession(body) { window.history.replaceState(null, '', '#home'); authenticated = true; csrfToken = body.csrfToken; + if (agentPreview) void reviewAgentPreview(agentPreview); approvedPreview = null; approvedFilePreview = null; approvedQuickPreview = null; @@ -1751,6 +1894,12 @@ function enterGlobalWorkspace() { function applyNavigationRoute() { if (!authenticated) return; + const agentPreview = agentReviewFromHash(); + if (agentPreview) { + window.history.replaceState(null, '', activeNavigationHash || '#home'); + void reviewAgentPreview(agentPreview); + return; + } const route = ControlWorkspace.parseRoute(window.location.hash); const cancelNavigation = () => window.history.replaceState(null, '', activeNavigationHash); if (route.scope === 'GLOBAL' && workspace.managementScope !== 'GLOBAL') { @@ -3754,6 +3903,11 @@ async function waitForDeployment(operation, generation) { } function discardAuthenticationState(reason) { + clearAgentCredential(); + agentGrantForm.reset(); + agentGrants.replaceChildren(); + text(agentGrantStatus, ''); + if (agentReview.open) agentReview.close(); settingsEditor?.clear(); settingsHealthReader?.clear(); voteSitesEditor?.clear(); diff --git a/src/main/resources/web/index.html b/src/main/resources/web/index.html index 6790fba..c68b8db 100644 --- a/src/main/resources/web/index.html +++ b/src/main/resources/web/index.html @@ -706,6 +706,14 @@

Setup

Safe service-site test

Resolve a service name and report whether it would match or auto-create. No fake vote is submitted and no reward runs.

No service tested.
+ +

Review agent configuration preview

+

+        

+ +
+
+