XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEServerManager

【Java】我的世界XFE服务器管理器

公开
关注 0 Fork 0 Star 0
UTF-8
package com.xfestudio.xfeservermanager.infra.webhook;

import com.xfestudio.xfeservermanager.api.event.ManagementEvent;
import com.xfestudio.xfeservermanager.api.spi.ManagementEventSink;
import com.xfestudio.xfeservermanager.infra.http.JsonCodec;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HexFormat;
import java.util.Objects;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/** Bounded, signed outbound webhook sink. Delivery never runs on the Minecraft tick thread. */
public final class HmacWebhookEventSink implements ManagementEventSink, AutoCloseable {
    private final URI endpoint;
    private final byte[] secret;
    private final JsonCodec json;
    private final ThreadPoolExecutor executor;
    private volatile HttpClient client;
    private final java.util.Set<CompletableFuture<Void>> pending = ConcurrentHashMap.newKeySet();
    private final AtomicBoolean closed = new AtomicBoolean();

    public HmacWebhookEventSink(URI endpoint, byte[] secret, int queueCapacity) {
        this.endpoint = validateEndpoint(endpoint);
        if (secret == null || secret.length < 32) {
            throw new IllegalArgumentException("webhook secret must contain at least 256 bits");
        }
        if (queueCapacity < 1 || queueCapacity > 65_536) {
            throw new IllegalArgumentException("invalid webhook queue capacity");
        }
        this.secret = secret.clone();
        this.json = new JsonCodec();
        this.executor = new ThreadPoolExecutor(
                1,
                2,
                30,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(queueCapacity),
                runnable -> {
                    Thread thread = new Thread(runnable, "xfesm-webhook");
                    thread.setDaemon(true);
                    return thread;
                },
                new ThreadPoolExecutor.AbortPolicy());
    }

    @Override
    public CompletionStage<Void> publish(ManagementEvent event) {
        Objects.requireNonNull(event, "event");
        CompletableFuture<Void> completion = new CompletableFuture<>();
        if (closed.get()) {
            completion.completeExceptionally(new WebhookDeliveryException("webhook sink is closed"));
            return completion;
        }
        pending.add(completion);
        try {
            executor.execute(() -> {
                try {
                    deliver(event, completion);
                } finally {
                    pending.remove(completion);
                }
            });
        } catch (RejectedExecutionException exception) {
            pending.remove(completion);
            completion.completeExceptionally(new WebhookDeliveryException(
                    "webhook queue is saturated", exception));
        }
        return completion;
    }

    private void deliver(ManagementEvent event, CompletableFuture<Void> completion) {
        byte[] body = json.writeBytes(event);
        long timestamp = event.timestamp().getEpochSecond();
        String signature = signature(secret, timestamp, body);
        HttpRequest request = HttpRequest.newBuilder(endpoint)
                .timeout(Duration.ofSeconds(5))
                .header("Content-Type", "application/json; charset=utf-8")
                .header("User-Agent", "XFEServerManager/1")
                .header("X-XFESM-Event-ID", event.eventId().toString())
                .header("X-XFESM-Timestamp", Long.toString(timestamp))
                .header("X-XFESM-Signature", "v1=" + signature)
                .POST(HttpRequest.BodyPublishers.ofByteArray(body))
                .build();
        try {
            HttpResponse<Void> response = client().send(request, HttpResponse.BodyHandlers.discarding());
            if (response.statusCode() < 200 || response.statusCode() >= 300) {
                throw new WebhookDeliveryException(
                        "webhook returned HTTP " + response.statusCode());
            }
            completion.complete(null);
        } catch (InterruptedException exception) {
            Thread.currentThread().interrupt();
            completion.completeExceptionally(new WebhookDeliveryException(
                    "webhook delivery was interrupted", exception));
        } catch (Exception exception) {
            completion.completeExceptionally(exception instanceof WebhookDeliveryException
                    ? exception
                    : new WebhookDeliveryException("webhook delivery failed", exception));
        }
    }

    static String signature(byte[] secret, long timestamp, byte[] body) {
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret, "HmacSHA256"));
            mac.update(Long.toString(timestamp).getBytes(StandardCharsets.US_ASCII));
            mac.update((byte) '.');
            return HexFormat.of().formatHex(mac.doFinal(body));
        } catch (java.security.GeneralSecurityException impossible) {
            throw new IllegalStateException("HmacSHA256 is unavailable", impossible);
        }
    }

    private HttpClient client() {
        HttpClient current = client;
        if (current != null) {
            return current;
        }
        synchronized (this) {
            if (client == null) {
                client = HttpClient.newBuilder()
                        .connectTimeout(Duration.ofSeconds(3))
                        .followRedirects(HttpClient.Redirect.NEVER)
                        .build();
            }
            return client;
        }
    }

    private static URI validateEndpoint(URI endpoint) {
        Objects.requireNonNull(endpoint, "endpoint");
        String scheme = endpoint.getScheme();
        String host = endpoint.getHost();
        if (host == null || endpoint.getUserInfo() != null
                || !("https".equalsIgnoreCase(scheme) || "http".equalsIgnoreCase(scheme))) {
            throw new IllegalArgumentException("webhook endpoint must be an HTTP(S) URL without credentials");
        }
        if (host.startsWith("[") && host.endsWith("]")) {
            host = host.substring(1, host.length() - 1);
        }
        if ("http".equalsIgnoreCase(scheme)
                && !("localhost".equalsIgnoreCase(host)
                        || "127.0.0.1".equals(host)
                        || "::1".equals(host))) {
            throw new IllegalArgumentException("remote webhook endpoints must use HTTPS");
        }
        return endpoint;
    }

    @Override
    public void close() {
        if (!closed.compareAndSet(false, true)) {
            return;
        }
        executor.shutdownNow();
        WebhookDeliveryException failure = new WebhookDeliveryException("webhook sink was closed");
        pending.forEach(future -> future.completeExceptionally(failure));
        try {
            executor.awaitTermination(2, TimeUnit.SECONDS);
        } catch (InterruptedException interrupted) {
            Thread.currentThread().interrupt();
        }
        pending.clear();
        java.util.Arrays.fill(secret, (byte) 0);
    }

    public static final class WebhookDeliveryException extends RuntimeException {
        private static final long serialVersionUID = 1L;

        public WebhookDeliveryException(String message) {
            super(message);
        }

        public WebhookDeliveryException(String message, Throwable cause) {
            super(message, cause);
        }
    }
}