Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .fernignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ src/main/java/com/schematic/api/logger/SchematicLogger.java
src/main/java/com/schematic/api/resources/accounts/AccountsClient.java
src/main/java/com/schematic/api/resources/companies/CompaniesClient.java
src/main/java/com/schematic/api/resources/entitlements/EntitlementsClient.java
src/main/java/com/schematic/webhook/
src/test/java/com/schematic/api/TestCache.java
src/test/java/com/schematic/api/TestEventBuffer.java
src/test/java/com/schematic/api/TestLogger.java
src/test/java/com/schematic/api/TestOfflineMode.java
src/test/java/com/schematic/api/TestReadme.java
src/test/java/com/schematic/api/TestSchematic.java
src/test/java/com/schematic/webhook/
64 changes: 64 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,70 @@ user.put("user_id", "your-user-id");
boolean flagValue = schematic.checkFlag("some-flag-key", company, user);
```

## Webhook Verification

Schematic can send webhooks to notify your application of events. To ensure the security of these webhooks, Schematic signs each request using HMAC-SHA256. The Java SDK provides utility functions to verify these signatures.

### Verifying Webhook Signatures

When your application receives a webhook request from Schematic, you should verify its signature to ensure it's authentic:

```java
import com.schematic.webhook.WebhookVerifier;
import com.schematic.webhook.WebhookSignatureException;
import java.util.Map;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.IOException;

// In your webhook endpoint handler:
public void handleWebhook(HttpServletRequest request, HttpServletResponse response) throws IOException {
// Read the request body
String body = request.getReader().lines().collect(Collectors.joining("\n"));

// Get the required headers
Map<String, String> headers = new HashMap<>();
headers.put(WebhookVerifier.WEBHOOK_SIGNATURE_HEADER,
request.getHeader(WebhookVerifier.WEBHOOK_SIGNATURE_HEADER));
headers.put(WebhookVerifier.WEBHOOK_TIMESTAMP_HEADER,
request.getHeader(WebhookVerifier.WEBHOOK_TIMESTAMP_HEADER));

String webhookSecret = "your-webhook-secret";

try {
// Verify the webhook signature
WebhookVerifier.verifyWebhookSignature(body, headers, webhookSecret);

// Process the webhook payload
// ...

response.setStatus(HttpServletResponse.SC_OK);
} catch (WebhookSignatureException e) {
// Handle signature verification failure
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write("Invalid signature: " + e.getMessage());
}
}
```

### Verifying Signatures Manually

If you need to verify a webhook signature outside of the context of a servlet request, you can use the `verifySignature` method:

```java
import com.schematic.webhook.WebhookVerifier;
import com.schematic.webhook.WebhookSignatureException;

public void verifyWebhookManually(String body, String signature, String timestamp, String secret) {
try {
WebhookVerifier.verifySignature(body, signature, timestamp, secret);
System.out.println("Signature verification successful!");
} catch (WebhookSignatureException e) {
System.out.println("Signature verification failed: " + e.getMessage());
}
}
```

## Configuration Options

There are a number of configuration options that can be specified using the builder when instantiating the Schematic client.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.schematic.webhook;

/**
* Exception thrown when webhook signature verification fails.
*/
public class WebhookSignatureException extends RuntimeException {

/**
* Constructs a new WebhookSignatureException with the specified detail message.
*
* @param message the detail message
*/
public WebhookSignatureException(String message) {
super(message);
}

/**
* Constructs a new WebhookSignatureException with the specified detail message and cause.
*
* @param message the detail message
* @param cause the cause
*/
public WebhookSignatureException(String message, Throwable cause) {
super(message, cause);
}
}
179 changes: 179 additions & 0 deletions src/main/java/com/schematic/webhook/WebhookVerifier.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
package com.schematic.webhook;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
* Utilities for verifying the signatures of Schematic webhooks.
* <p>
* Schematic signs webhook payloads using HMAC-SHA256. This class provides methods
* to verify these signatures.
*/
public class WebhookVerifier {

/**
* Header containing the webhook signature.
*/
public static final String WEBHOOK_SIGNATURE_HEADER = "X-Schematic-Webhook-Signature";

/**
* Header containing the webhook timestamp.
*/
public static final String WEBHOOK_TIMESTAMP_HEADER = "X-Schematic-Webhook-Timestamp";

private static final String HMAC_SHA256 = "HmacSHA256";

/**
* Verifies the signature of a webhook request.
*
* @param body The request body as a string
* @param headers Map of HTTP headers
* @param secret The webhook secret
* @throws WebhookSignatureException if the signature is invalid
*/
public static void verifyWebhookSignature(String body, Map<String, String> headers, String secret)
throws WebhookSignatureException {

// Extract signature and timestamp headers
String signature = headers.get(WEBHOOK_SIGNATURE_HEADER);
String timestamp = headers.get(WEBHOOK_TIMESTAMP_HEADER);

// Verify signature
verifySignature(body, signature, timestamp, secret);
}

/**
* Verifies the signature of a webhook payload.
*
* @param body The webhook payload
* @param signature The signature header value
* @param timestamp The timestamp header value
* @param secret The webhook secret
* @throws WebhookSignatureException if the signature is invalid
*/
public static void verifySignature(String body, String signature, String timestamp, String secret)
throws WebhookSignatureException {

if (signature == null || signature.isEmpty()) {
throw new WebhookSignatureException("Missing webhook signature");
}

if (timestamp == null || timestamp.isEmpty()) {
throw new WebhookSignatureException("Missing webhook timestamp");
}

// Compute expected signature
String expectedSignature = computeHexSignature(body, timestamp, secret);

// Compare signatures using constant-time comparison
if (!constantTimeEquals(hexToBytes(expectedSignature), hexToBytes(signature))) {
throw new WebhookSignatureException("Invalid signature");
}
}

/**
* Computes the hex-encoded HMAC-SHA256 signature for a webhook payload.
*
* @param body The webhook payload
* @param timestamp The timestamp
* @param secret The webhook secret
* @return The hex-encoded signature
* @throws WebhookSignatureException if an error occurs during signature computation
*/
public static String computeHexSignature(String body, String timestamp, String secret)
throws WebhookSignatureException {

byte[] signature = computeSignature(body, timestamp, secret);
return bytesToHex(signature);
}

/**
* Computes the HMAC-SHA256 signature for a webhook payload.
*
* @param body The webhook payload
* @param timestamp The timestamp
* @param secret The webhook secret
* @return The signature bytes
* @throws WebhookSignatureException if an error occurs during signature computation
*/
public static byte[] computeSignature(String body, String timestamp, String secret)
throws WebhookSignatureException {

try {
// Create message by concatenating body and timestamp
String message = body + "+" + timestamp;
byte[] messageBytes = message.getBytes(StandardCharsets.UTF_8);

// Create HMAC-SHA256 instance
SecretKeySpec keySpec = new SecretKeySpec(
secret.getBytes(StandardCharsets.UTF_8),
HMAC_SHA256
);
Mac mac = Mac.getInstance(HMAC_SHA256);
mac.init(keySpec);

// Compute and return signature
return mac.doFinal(messageBytes);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new WebhookSignatureException("Error computing signature", e);
}
}

/**
* Converts a byte array to a hex string.
*
* @param bytes The byte array
* @return The hex string
*/
private static String bytesToHex(byte[] bytes) {
StringBuilder result = new StringBuilder();
for (byte b : bytes) {
result.append(String.format("%02x", b));
}
return result.toString();
}

/**
* Converts a hex string to a byte array.
*
* @param hex The hex string
* @return The byte array
* @throws WebhookSignatureException if the hex string is invalid
*/
private static byte[] hexToBytes(String hex) throws WebhookSignatureException {
Copy link

Copilot AI Mar 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be beneficial to validate that the hex string has an even length before processing, as an odd-length string would indicate an invalid format.

Suggested change
private static byte[] hexToBytes(String hex) throws WebhookSignatureException {
private static byte[] hexToBytes(String hex) throws WebhookSignatureException {
if (hex.length() % 2 != 0) {
throw new WebhookSignatureException("Invalid hex string format: length must be even");
}

Copilot uses AI. Check for mistakes.
try {
int len = hex.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
+ Character.digit(hex.charAt(i + 1), 16));
}
return data;
} catch (Exception e) {
throw new WebhookSignatureException("Invalid signature format", e);
}
}

/**
* Compares two byte arrays in constant time to prevent timing attacks.
*
* @param a First byte array
* @param b Second byte array
* @return true if the arrays are equal, false otherwise
*/
private static boolean constantTimeEquals(byte[] a, byte[] b) {
if (a.length != b.length) {
return false;
}

int result = 0;
for (int i = 0; i < a.length; i++) {
result |= a[i] ^ b[i];
}
return result == 0;
}
}
Loading