|
| 1 | +/* |
| 2 | + * Copyright © 2021-present Arcade Data Ltd ([email protected]) |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + * |
| 16 | + * SPDX-FileCopyrightText: 2021-present Arcade Data Ltd ([email protected]) |
| 17 | + * SPDX-License-Identifier: Apache-2.0 |
| 18 | + */ |
| 19 | +package com.arcadedb.server.ai; |
| 20 | + |
| 21 | +import com.arcadedb.Constants; |
| 22 | +import com.arcadedb.log.LogManager; |
| 23 | +import com.arcadedb.serializer.json.JSONObject; |
| 24 | +import com.arcadedb.server.http.HttpServer; |
| 25 | +import com.arcadedb.server.http.handler.AbstractServerHttpHandler; |
| 26 | +import com.arcadedb.server.http.handler.ExecutionResponse; |
| 27 | +import com.arcadedb.server.security.ServerSecurityUser; |
| 28 | +import io.undertow.server.HttpServerExchange; |
| 29 | + |
| 30 | +import java.net.InetAddress; |
| 31 | +import java.net.NetworkInterface; |
| 32 | +import java.net.URI; |
| 33 | +import java.net.http.HttpClient; |
| 34 | +import java.net.http.HttpRequest; |
| 35 | +import java.net.http.HttpResponse; |
| 36 | +import java.security.MessageDigest; |
| 37 | +import java.time.Duration; |
| 38 | +import java.util.Enumeration; |
| 39 | +import java.util.logging.Level; |
| 40 | + |
| 41 | +/** |
| 42 | + * POST /api/v1/ai/activate - Activates an AI subscription. |
| 43 | + * Collects hardware fingerprint, validates the key against the gateway, and saves to config/ai.json. |
| 44 | + */ |
| 45 | +public class AiActivateHandler extends AbstractServerHttpHandler { |
| 46 | + private final AiConfiguration config; |
| 47 | + private final HttpClient httpClient; |
| 48 | + |
| 49 | + public AiActivateHandler(final HttpServer httpServer, final AiConfiguration config) { |
| 50 | + super(httpServer); |
| 51 | + this.config = config; |
| 52 | + this.httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build(); |
| 53 | + } |
| 54 | + |
| 55 | + @Override |
| 56 | + protected boolean mustExecuteOnWorkerThread() { |
| 57 | + return true; |
| 58 | + } |
| 59 | + |
| 60 | + @Override |
| 61 | + protected ExecutionResponse execute(final HttpServerExchange exchange, final ServerSecurityUser user, final JSONObject payload) { |
| 62 | + if (payload == null) |
| 63 | + return new ExecutionResponse(400, errorJson("Request body is required")); |
| 64 | + |
| 65 | + final String subscriptionKey = payload.getString("subscriptionKey", ""); |
| 66 | + if (subscriptionKey.isEmpty()) |
| 67 | + return new ExecutionResponse(400, errorJson("Subscription key is required")); |
| 68 | + |
| 69 | + try { |
| 70 | + final String serverVersion = Constants.getVersion(); |
| 71 | + final String hardwareId = getHardwareId(); |
| 72 | + final String clientIp = getClientIp(exchange); |
| 73 | + |
| 74 | + // Validate the key against the gateway |
| 75 | + final JSONObject activationRequest = new JSONObject(); |
| 76 | + activationRequest.put("subscriptionKey", subscriptionKey); |
| 77 | + activationRequest.put("serverVersion", serverVersion); |
| 78 | + activationRequest.put("hardwareId", hardwareId); |
| 79 | + |
| 80 | + final HttpRequest request = HttpRequest.newBuilder()// |
| 81 | + .uri(URI.create(config.getGatewayUrl() + "/api/activate"))// |
| 82 | + .header("Content-Type", "application/json")// |
| 83 | + .POST(HttpRequest.BodyPublishers.ofString(activationRequest.toString()))// |
| 84 | + .timeout(Duration.ofSeconds(15))// |
| 85 | + .build(); |
| 86 | + |
| 87 | + final HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); |
| 88 | + |
| 89 | + if (response.statusCode() != 200) { |
| 90 | + String errorMsg = "Activation failed"; |
| 91 | + try { |
| 92 | + final JSONObject errBody = new JSONObject(response.body()); |
| 93 | + errorMsg = errBody.getString("error", errorMsg); |
| 94 | + } catch (final Exception ignored) { |
| 95 | + } |
| 96 | + return new ExecutionResponse(response.statusCode(), errorJson(errorMsg)); |
| 97 | + } |
| 98 | + |
| 99 | + // Activation successful - save to config/ai.json |
| 100 | + config.activate(subscriptionKey, clientIp, hardwareId, serverVersion); |
| 101 | + |
| 102 | + LogManager.instance().log(this, Level.INFO, "AI subscription activated (user=%s, ip=%s)", user.getName(), clientIp); |
| 103 | + |
| 104 | + return new ExecutionResponse(200, new JSONObject().put("activated", true).toString()); |
| 105 | + |
| 106 | + } catch (final Exception e) { |
| 107 | + LogManager.instance().log(this, Level.WARNING, "AI activation error: %s", e.getMessage()); |
| 108 | + return new ExecutionResponse(500, errorJson("Activation failed: " + e.getMessage())); |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + /** |
| 113 | + * Generates a hardware fingerprint by hashing MAC addresses + hostname. |
| 114 | + * This provides a stable identifier for the server without exposing raw MAC addresses. |
| 115 | + */ |
| 116 | + static String getHardwareId() { |
| 117 | + try { |
| 118 | + final StringBuilder raw = new StringBuilder(); |
| 119 | + |
| 120 | + // Collect all non-loopback MAC addresses |
| 121 | + final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); |
| 122 | + while (interfaces.hasMoreElements()) { |
| 123 | + final NetworkInterface ni = interfaces.nextElement(); |
| 124 | + if (ni.isLoopback() || ni.isVirtual()) |
| 125 | + continue; |
| 126 | + final byte[] mac = ni.getHardwareAddress(); |
| 127 | + if (mac != null) { |
| 128 | + for (final byte b : mac) |
| 129 | + raw.append(String.format("%02x", b)); |
| 130 | + raw.append("|"); |
| 131 | + } |
| 132 | + } |
| 133 | + |
| 134 | + // Add hostname for extra uniqueness |
| 135 | + raw.append(InetAddress.getLocalHost().getHostName()); |
| 136 | + |
| 137 | + // Hash it to produce a stable, non-reversible fingerprint |
| 138 | + final MessageDigest digest = MessageDigest.getInstance("SHA-256"); |
| 139 | + final byte[] hash = digest.digest(raw.toString().getBytes()); |
| 140 | + final StringBuilder hex = new StringBuilder(); |
| 141 | + for (int i = 0; i < 16; i++) // Use first 16 bytes (128 bits) for a shorter ID |
| 142 | + hex.append(String.format("%02x", hash[i])); |
| 143 | + return hex.toString(); |
| 144 | + } catch (final Exception e) { |
| 145 | + LogManager.instance().log(AiActivateHandler.class, Level.FINE, "Could not generate hardware ID: %s", e.getMessage()); |
| 146 | + return "unknown"; |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + private static String getClientIp(final HttpServerExchange exchange) { |
| 151 | + // Check for X-Forwarded-For (reverse proxy) |
| 152 | + final String forwarded = exchange.getRequestHeaders().getFirst("X-Forwarded-For"); |
| 153 | + if (forwarded != null && !forwarded.isEmpty()) |
| 154 | + return forwarded.split(",")[0].trim(); |
| 155 | + return exchange.getSourceAddress().getAddress().getHostAddress(); |
| 156 | + } |
| 157 | + |
| 158 | + private static String errorJson(final String message) { |
| 159 | + return new JSONObject().put("error", message).toString(); |
| 160 | + } |
| 161 | +} |
0 commit comments