# Java

> A complete integration with Java's built-in HttpClient. One class that calls the API with a timeout and fails open, one method that turns the answer into a decision, and a Spring Boot sign-up handler.

This guide needs Java 17 or later (records, `java.net.http`). The client has one dependency, Jackson, to read JSON; most Java web apps already have it.

```xml title="pom.xml"
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.23.0</version>
</dependency>
```

## 1. Call the API

`Heimdal.check` returns Heimdal's answer, or `Optional.empty()` when there is none: a timeout, a network error, or an error status. Empty means "no opinion", and the caller lets the sign-up through.

```java title="Heimdal.java"

public final class Heimdal {
    private static final Logger LOG = Logger.getLogger(Heimdal.class.getName());
    private static final URI CHECK_URL = URI.create("https://heimdal.codebrewerz.com/api/v1/check");
    private static final Duration TIMEOUT = Duration.ofSeconds(2);

    private final HttpClient client = HttpClient.newBuilder()
        .connectTimeout(TIMEOUT)
        .build();
    private final ObjectMapper json = new ObjectMapper();
    private final String apiKey;

    public Heimdal(String apiKey) {
        if (apiKey == null || apiKey.isBlank()) {
            throw new IllegalArgumentException("Set HEIMDAL_API_KEY");
        }
        this.apiKey = apiKey;
    }

    public static Heimdal fromEnv() {
        return new Heimdal(System.getenv("HEIMDAL_API_KEY"));
    }

    /** Heimdal's answer, or empty when the check could not be made. */
    public Optional<JsonNode> check(String ip, String email) {
        Map<String, String> body = new LinkedHashMap<>();
        // An address that is not valid would fail the whole request: leave it out.
        if (isIp(ip)) body.put("ip", ip);
        if (email != null) body.put("email", email);
        try {
            HttpRequest request = HttpRequest.newBuilder(CHECK_URL)
                .timeout(TIMEOUT)
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(json.writeValueAsString(body)))
                .build();
            HttpResponse<String> response =
                client.send(request, HttpResponse.BodyHandlers.ofString());
            JsonNode answer = json.readTree(response.body());
            if (response.statusCode() != 200) {
                JsonNode error = answer.path("error");
                LOG.warning("Heimdal " + response.statusCode() + " "
                    + error.path("code").asText() + ": " + error.path("message").asText());
                return Optional.empty();
            }
            return Optional.of(answer);
        } catch (IOException e) {
            LOG.warning("Heimdal check failed, sign-up allowed: " + e);
            return Optional.empty();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return Optional.empty();
        }
    }

    /** Literal IPv4 or IPv6 only: never resolves a host name. */
    static boolean isIp(String value) {
        if (value == null || value.isBlank()) return false;
        if (!value.matches("[0-9.]+|[0-9a-fA-F:.]*:[0-9a-fA-F:.]*")) return false;
        try {
            InetAddress.getByName(value);
            return true;
        } catch (IOException e) {
            return false;
        }
    }
}
```

`HttpClient` is thread-safe: create one `Heimdal` and share it, for example as a Spring bean.

## 2. Decide

Keep the policy in one method, apart from the HTTP call. This one refuses disposable email, Tor, open proxies and custom-list hits. VPN and hosting networks pass.

```java title="SignupPolicy.java"

public final class SignupPolicy {
    /** The message that refuses this sign-up, or empty to let it through. */
    public static Optional<String> refusalFor(Optional<JsonNode> result) {
        if (result.isEmpty()) return Optional.empty();
        JsonNode answer = result.get();
        if (answer.path("email").path("disposable").asBoolean(false)) {
            return Optional.of("Disposable email addresses can't be used to sign up.");
        }
        JsonNode ip = answer.path("ip");
        if (ip.path("tor").asBoolean(false) || ip.path("proxy").asBoolean(false)) {
            return Optional.of(
                "Sign-ups from this network aren't allowed. Contact support if this is a mistake.");
        }
        if (answer.path("custom").path("matched").size() > 0) {
            return Optional.of(
                "This sign-up can't be completed. Contact support if this is a mistake.");
        }
        return Optional.empty();
    }
}
```

To use the strict policy instead, refuse whenever `answer.path("block").asBoolean()` is true. [Best practices](https://heimdal.codebrewerz.com/docs/guides/best-practices/#choose-a-policy) explains the trade-off.

## 3. Use it in your sign-up handler

The example uses Spring Boot. The two calls are the same in any framework: Jakarta Servlet, Micronaut, Quarkus or Javalin.

```java title="SignupController.java"

@RestController
public class SignupController {
    private final Heimdal heimdal = Heimdal.fromEnv();

    record SignupRequest(String email, String password) {}

    @PostMapping("/signup")
    public ResponseEntity<?> signup(@RequestBody SignupRequest body, HttpServletRequest http) {
        // Behind a proxy, set server.forward-headers-strategy=native so this is
        // the client's address, not the proxy's.
        var result = heimdal.check(http.getRemoteAddr(), body.email());
        var refusal = SignupPolicy.refusalFor(result);
        if (refusal.isPresent()) {
            return ResponseEntity.badRequest().body(Map.of("error", refusal.get()));
        }

        // Create the user as you do today.
        return ResponseEntity.status(201).build();
    }
}
```

## What this gets right

- **It fails open.** No answer from Heimdal never blocks a sign-up.
- **It has a timeout.** Connect and response are both capped at two seconds.
- **It sends the visitor's address**, and only when it is a literal IP address.
- **It keeps the key on the server**, in `HEIMDAL_API_KEY`, and refuses to start without it.
- **It reads errors**: every non-200 answer is `{"error":{"code","message"}}` and is logged with its code.

## Test it

```sh
curl -X POST "http://localhost:8080/signup" \
  -H "Content-Type: application/json" \
  -d '{"email": "test@mailinator.com", "password": "Correct-horse-9"}'
```

```json
{ "error": "Disposable email addresses can't be used to sign up." }
```
