All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.tryfinch.api.services.async.WebhookServiceAsyncImpl.kt Maven / Gradle / Ivy

Go to download

The Finch HRIS API provides a unified way to connect to a multitide of HRIS systems. The API requires an access token issued by Finch. By default, Organization and Payroll requests use Finch's [Data Syncs](/developer-resources/Data-Syncs). If a request is made before the initial sync has completed, Finch will request data live from the provider. The latency on live requests may range from seconds to minutes depending on the provider and batch size. For automated integrations, Deductions requests (both read and write) are always made live to the provider. Latencies may range from seconds to minutes depending on the provider and batch size. Employer products are specified by the product parameter, a space-separated list of products that your application requests from an employer authenticating through Finch Connect. Valid product names are— - `company`: Read basic company data - `directory`: Read company directory and organization structure - `individual`: Read individual data, excluding income and employment data - `employment`: Read individual employment and income data - `payment`: Read payroll and contractor related payments by the company - `pay_statement`: Read detailed pay statements for each individual - `benefits`: Create and manage deductions and contributions and enrollment for an employer [![Open in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/21027137-08db0929-883d-4094-a9ce-dbf5a9bee4a4?action=collection%2Ffork&collection-url=entityId%3D21027137-08db0929-883d-4094-a9ce-dbf5a9bee4a4%26entityType%3Dcollection%26workspaceId%3D1edf19bc-e0a8-41e9-ac55-481a4b50790b)

There is a newer version: 1.11.0
Show newest version
// File generated from our OpenAPI spec by Stainless.

package com.tryfinch.api.services.async

import com.fasterxml.jackson.core.JsonProcessingException
import com.google.common.collect.ListMultimap
import com.tryfinch.api.core.ClientOptions
import com.tryfinch.api.core.getRequiredHeader
import com.tryfinch.api.core.http.HttpResponse.Handler
import com.tryfinch.api.errors.FinchError
import com.tryfinch.api.errors.FinchException
import com.tryfinch.api.models.WebhookEvent
import com.tryfinch.api.services.errorHandler
import java.security.MessageDigest
import java.time.Duration
import java.time.Instant
import java.util.Base64
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

class WebhookServiceAsyncImpl
constructor(
    private val clientOptions: ClientOptions,
) : WebhookServiceAsync {

    private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper)

    override fun unwrap(
        payload: String,
        headers: ListMultimap,
        secret: String?
    ): WebhookEvent {
        verifySignature(payload, headers, secret)
        return try {
            clientOptions.jsonMapper.readValue(payload, WebhookEvent::class.java)
        } catch (e: JsonProcessingException) {
            throw FinchException("Invalid event payload", e)
        }
    }

    override fun verifySignature(
        payload: String,
        headers: ListMultimap,
        secret: String?
    ) {
        val webhookSecret =
            secret
                ?: clientOptions.webhookSecret
                ?: throw FinchException(
                    "The webhook secret must either be set using the env var, FINCH_WEBHOOK_SECRET, on the client class, or passed to this method"
                )

        val parsedSecret =
            try {
                Base64.getDecoder().decode(webhookSecret)
            } catch (e: RuntimeException) {
                throw FinchException("Invalid webhook secret")
            }

        val eventId = headers.getRequiredHeader("finch-event-id")
        val msgSignature = headers.getRequiredHeader("finch-signature")
        val msgTimestamp = headers.getRequiredHeader("finch-timestamp")

        val timestamp =
            try {
                Instant.ofEpochSecond(msgTimestamp.toLong())
            } catch (e: RuntimeException) {
                throw FinchException("Invalid timestamp header: $msgTimestamp", e)
            }
        val now = Instant.now(clientOptions.clock)

        if (timestamp.isBefore(now.minus(Duration.ofMinutes(5)))) {
            throw FinchException("Webhook timestamp too old")
        }
        if (timestamp.isAfter(now.plus(Duration.ofMinutes(5)))) {
            throw FinchException("Webhook timestamp too new")
        }

        val mac = Mac.getInstance("HmacSHA256")
        mac.init(SecretKeySpec(parsedSecret, "HmacSHA256"))
        val expectedSignature =
            mac.doFinal("$eventId.${timestamp.epochSecond}.$payload".toByteArray())

        msgSignature.splitToSequence(" ").forEach {
            val parts = it.split(",")
            if (parts.size != 2) {
                return@forEach
            }

            if (parts[0] != "v1") {
                return@forEach
            }

            if (MessageDigest.isEqual(Base64.getDecoder().decode(parts[1]), expectedSignature)) {
                return
            }
        }

        throw FinchException("None of the given webhook signatures match the expected signature")
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy