castle

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 16 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

castle-go

An unofficial Go SDK for Castle. Requires Go 1.27.3 or later.

Request models, response models, and endpoint calls are generated from Castle's official OpenAPI definition, with shared authentication, configuration, and error handling.

Install

go get github.com/fchimpan/castle-go@latest

Use the client

Set CASTLE_API_SECRET to your API secret. This example fetches your lists and prints their IDs and names:

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	castle "github.com/fchimpan/castle-go"
)

func main() {
	client, err := castle.NewClient(os.Getenv("CASTLE_API_SECRET"), castle.Config{})
	if err != nil {
		log.Fatal(err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	result, err := client.GetLists(ctx)
	if err != nil {
		log.Fatal(err)
	}
	for _, list := range *result.JSON200 {
		fmt.Println(list.Id, list.Name)
	}
}

Save the code as main.go in your application and run go run .. Reuse the client across requests in a long-running application. Methods follow the OpenAPI operation names with an initial capital. Request and response types live in the api package. See the generated client for available methods and the generated models for their types.

For an assessment example with request models, context headers, and policy handling, see the executable example. Supply the request token from Castle's client SDK and context from the originating request. The generated models do not apply server defaults or validate every schema constraint.

Read responses

Each method returns a generated response envelope. Read JSON200 or JSON201 for the typed payload, Body for the original response bytes, and StatusCode() for the status. For Risk and Filter, use result.JSON201.ValueByDiscriminator() or result.JSON201.AsLoginResponse() to read an assessment. Check whether Scores is present before reading a score. An absent score is different from a score of zero. The response union preserves unknown JSON fields; a typed projection can discard fields outside its schema.

Bodyless successes return an envelope with the status and headers.

QueryEventsWithBody(ctx, "text/csv", reader) supports the documented CSV mode. The official example sends a JSON query with that content type. Read the CSV result from Body; JSON200 is nil for CSV responses. Other WithBody variants accept a content type and reader and use the same client policies.

GetLatestIpDatasetExportMetadata sends HEAD and returns typed metadata in Headers200. DownloadIpDatasetExport returns the documented 302 response and presigned URL in Headers302.Location. Fetch that URL separately with an HTTP client that does not attach the Castle API secret. The SDK does not follow the redirect or download the dataset automatically.

Configure requests and handle failures

castle.Config accepts a BaseURL and an HTTPClient. Empty configuration uses https://api.castle.io/v1. The SDK copies the HTTP client and disables redirects on the copy. It uses HTTP Basic authentication with an empty username and the secret as the password. Custom transports remain responsible for their own behavior.

The default HTTP client has no timeout. Set a context deadline or configure HTTPClient.Timeout to bound the request duration. Successful response bodies are limited to 4 MiB by default. Set Config.MaxResponseBytes to a positive byte limit for larger responses, such as Events queries or CSV exports.

The root client accepts each operation's documented success statuses and content types. JSON responses must declare application/json; a missing or unexpected content type is an error. The SDK adds no retries and does not replace API failures with an allow decision. Use errors.As to inspect *castle.APIError.StatusCode. HTTP status is available even for empty or malformed error bodies. Error messages exclude response bodies, request data, and API secrets. Use errors.Is with context.Canceled and context.DeadlineExceeded to detect cancellation.

Set SkipRequestTokenValidation: new(true) or SkipContextValidation: new(true) only when the corresponding data is unavailable. These flags allow the corresponding fields to be omitted. Skipping request token validation prevents risk scores from being calculated.

Custom-event status and nullable changeset fields use github.com/oapi-codegen/nullable. Use an explicit null value when sending JSON null; leave an optional nullable field unspecified to omit it. Request Properties has an extra object level compared with response Properties, as declared in the official schema.

The generated api.Client and api.ClientWithResponses are low-level clients. Use the root castle.Client for the authentication, redirect, and error behavior described here.

Verify webhooks

Use the exact raw request body and the X-Castle-Signature header before parsing or processing a webhook:

err := castle.VerifyWebhookSignature(rawBody, r.Header.Get("X-Castle-Signature"), apiSecret)
if errors.Is(err, castle.ErrWebhookVerification) {
    http.Error(w, "Invalid webhook signature", http.StatusBadRequest)
    return
}

Read rawBody with a bounded reader such as http.MaxBytesReader, and reject read errors before verification. Use the API secret selected for webhook signing in Castle. Do not reserialize JSON before checking the signature. Following Castle's webhook specification, verification compares the standard Base64 HMAC-SHA256 signature in constant time. Empty secrets and missing, malformed, or mismatched signatures return ErrWebhookVerification, without including sensitive values. Verification does not parse the payload or prevent replay of a previously signed delivery.

Regenerate and test

go generate ./...
go test -race -count=1 ./...
go vet ./...

Generation uses the checked-in schema and pinned oapi-codegen version. It does not fetch a newer schema or select a newer tool version. Tests use synthetic data and local HTTP servers, without Castle credentials. CI also checks for stale generated code in a separate job. Tests run with the race detector enabled, and go vet runs in its own job. Read the testing guide for test design and the generation guide before updating the snapshot.

Local HTTP fixtures check requests and decoded responses against the checked-in specification. These tests do not verify live Castle accounts or service behavior.

Migration from the unreleased Risk-only prototype

Client.Risk now returns *api.RiskResponse, matching every other operation's response envelope. Change result.AsLoginResponse() to result.JSON201.AsLoginResponse() and similarly move other assessment access through JSON201. Request models remain generated. Some newly named component types replace anonymous nested schemas; regenerate and compile callers when updating the specification.

Releases remain in the v0.x.y series. New features and breaking public API changes use a minor version increment; backward-compatible fixes use a patch increment.

Documentation

Overview

Package castle provides a client for the Castle API.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrWebhookVerification = errors.New("castle: webhook signature verification failed")

ErrWebhookVerification indicates a missing or invalid webhook signature or secret.

Functions

func VerifyWebhookSignature

func VerifyWebhookSignature(body []byte, signature, apiSecret string) error

VerifyWebhookSignature verifies the X-Castle-Signature header against the exact request body bytes using the API secret selected for webhook signing in Castle. Call it before parsing or processing the body. It returns ErrWebhookVerification for an empty secret, missing or malformed signature, or signature mismatch.

Types

type APIError

type APIError struct{ StatusCode int }

APIError reports a non-success HTTP status without exposing response data.

func (*APIError) Error

func (e *APIError) Error() string

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client calls Castle's generated API operations. It is safe for concurrent use.

func NewClient

func NewClient(apiSecret string, config Config) (*Client, error)

NewClient constructs a client using apiSecret as the Basic authentication password.

func (*Client) ArchiveListItem

func (c *Client) ArchiveListItem(ctx context.Context, listId string, id string) (*api.ArchiveListItemResponse, error)

ArchiveListItem calls DELETE /lists/{list_id}/items/{id}/archive with the shared client policy.

func (*Client) CountListItems

CountListItems calls POST /lists/{list_id}/items/count with the shared client policy.

func (*Client) CountListItemsWithBody

func (c *Client) CountListItemsWithBody(ctx context.Context, listId string, contentType string, body io.Reader) (*api.CountListItemsResponse, error)

CountListItemsWithBody calls POST /lists/{list_id}/items/count with the shared client policy.

func (*Client) CreateList

CreateList calls POST /lists with the shared client policy.

func (*Client) CreateListItem

CreateListItem calls POST /lists/{list_id}/items with the shared client policy.

func (*Client) CreateListItemWithBody

func (c *Client) CreateListItemWithBody(ctx context.Context, listId string, contentType string, body io.Reader) (*api.CreateListItemResponse, error)

CreateListItemWithBody calls POST /lists/{list_id}/items with the shared client policy.

func (*Client) CreateListWithBody

func (c *Client) CreateListWithBody(ctx context.Context, contentType string, body io.Reader) (*api.CreateListResponse, error)

CreateListWithBody calls POST /lists with the shared client policy.

func (*Client) CreateOrUpdateBatchListItems

CreateOrUpdateBatchListItems calls POST /lists/{list_id}/items/batch with the shared client policy.

func (*Client) CreateOrUpdateBatchListItemsWithBody

func (c *Client) CreateOrUpdateBatchListItemsWithBody(ctx context.Context, listId string, contentType string, body io.Reader) (*api.CreateOrUpdateBatchListItemsResponse, error)

CreateOrUpdateBatchListItemsWithBody calls POST /lists/{list_id}/items/batch with the shared client policy.

func (*Client) DeleteList

func (c *Client) DeleteList(ctx context.Context, id string) (*api.DeleteListResponse, error)

DeleteList calls DELETE /lists/{id} with the shared client policy.

func (*Client) DeleteUserPrivacy

DeleteUserPrivacy calls DELETE /privacy/users with the shared client policy.

func (*Client) DeleteUserPrivacyDeprecated

func (c *Client) DeleteUserPrivacyDeprecated(ctx context.Context, id string) (*api.DeleteUserPrivacyDeprecatedResponse, error)

DeleteUserPrivacyDeprecated calls DELETE /privacy/users/{id} with the shared client policy. Deprecated: This operation is deprecated in Castle's API specification.

func (*Client) DeleteUserPrivacyWithBody

func (c *Client) DeleteUserPrivacyWithBody(ctx context.Context, contentType string, body io.Reader) (*api.DeleteUserPrivacyResponse, error)

DeleteUserPrivacyWithBody calls DELETE /privacy/users with the shared client policy.

func (*Client) DownloadIpDatasetExport

func (c *Client) DownloadIpDatasetExport(ctx context.Context, dataset string, window string, format string) (*api.DownloadIpDatasetExportResponse, error)

DownloadIpDatasetExport calls GET /ips/downloads/{dataset}/{window}.{format}.gz with the shared client policy.

func (*Client) Filter

Filter calls POST /filter with the shared client policy.

func (*Client) FilterWithBody

func (c *Client) FilterWithBody(ctx context.Context, contentType string, body io.Reader) (*api.FilterResponse, error)

FilterWithBody calls POST /filter with the shared client policy.

func (*Client) GetEventSchema

func (c *Client) GetEventSchema(ctx context.Context) (*api.GetEventSchemaResponse, error)

GetEventSchema calls GET /events/schema with the shared client policy.

func (*Client) GetLatestIpDatasetExportMetadata

func (c *Client) GetLatestIpDatasetExportMetadata(ctx context.Context, dataset string, window string, format string) (*api.GetLatestIpDatasetExportMetadataResponse, error)

GetLatestIpDatasetExportMetadata calls HEAD /ips/downloads/{dataset}/{window}.{format}.gz with the shared client policy.

func (*Client) GetList

func (c *Client) GetList(ctx context.Context, id string, params *api.GetListParams) (*api.GetListResponse, error)

GetList calls GET /lists/{id} with the shared client policy.

func (*Client) GetListItem

func (c *Client) GetListItem(ctx context.Context, listId string, id string) (*api.GetListItemResponse, error)

GetListItem calls GET /lists/{list_id}/items/{id} with the shared client policy.

func (*Client) GetLists

func (c *Client) GetLists(ctx context.Context) (*api.GetListsResponse, error)

GetLists calls GET /lists with the shared client policy.

func (*Client) GetUserPrivacy

GetUserPrivacy calls POST /privacy/users with the shared client policy.

func (*Client) GetUserPrivacyDeprecated

func (c *Client) GetUserPrivacyDeprecated(ctx context.Context, id string) (*api.GetUserPrivacyDeprecatedResponse, error)

GetUserPrivacyDeprecated calls POST /privacy/users/{id} with the shared client policy. Deprecated: This operation is deprecated in Castle's API specification.

func (*Client) GetUserPrivacyWithBody

func (c *Client) GetUserPrivacyWithBody(ctx context.Context, contentType string, body io.Reader) (*api.GetUserPrivacyResponse, error)

GetUserPrivacyWithBody calls POST /privacy/users with the shared client policy.

func (*Client) GroupEvents

GroupEvents calls POST /events/group with the shared client policy.

func (*Client) GroupEventsWithBody

func (c *Client) GroupEventsWithBody(ctx context.Context, contentType string, body io.Reader) (*api.GroupEventsResponse, error)

GroupEventsWithBody calls POST /events/group with the shared client policy.

func (*Client) IpsLookupBatch

IpsLookupBatch calls POST /ips/query with the shared client policy.

func (*Client) IpsLookupBatchWithBody

func (c *Client) IpsLookupBatchWithBody(ctx context.Context, contentType string, body io.Reader) (*api.IpsLookupBatchResponse, error)

IpsLookupBatchWithBody calls POST /ips/query with the shared client policy.

func (*Client) IpsLookupSingle

func (c *Client) IpsLookupSingle(ctx context.Context, value string) (*api.IpsLookupSingleResponse, error)

IpsLookupSingle calls GET /ips/{value} with the shared client policy.

func (*Client) QueryEvents

QueryEvents calls POST /events/query with the shared client policy.

func (*Client) QueryEventsWithBody

func (c *Client) QueryEventsWithBody(ctx context.Context, contentType string, body io.Reader) (*api.QueryEventsResponse, error)

QueryEventsWithBody calls POST /events/query with the shared client policy.

func (*Client) QueryListItems

QueryListItems calls POST /lists/{list_id}/items/query with the shared client policy.

func (*Client) QueryListItemsWithBody

func (c *Client) QueryListItemsWithBody(ctx context.Context, listId string, contentType string, body io.Reader) (*api.QueryListItemsResponse, error)

QueryListItemsWithBody calls POST /lists/{list_id}/items/query with the shared client policy.

func (*Client) QueryLists

QueryLists calls POST /lists/query with the shared client policy.

func (*Client) QueryListsWithBody

func (c *Client) QueryListsWithBody(ctx context.Context, contentType string, body io.Reader) (*api.QueryListsResponse, error)

QueryListsWithBody calls POST /lists/query with the shared client policy.

func (*Client) Risk

Risk calls POST /risk with the shared client policy.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"

	castle "github.com/fchimpan/castle-go"
	"github.com/fchimpan/castle-go/api"
)

func main() {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusCreated)
		io.WriteString(w, `{"type":"$login","policy":{"action":"challenge","name":null,"id":null,"revision_id":null},"signals":{},"device":{"fingerprint":null}}`)
	}))
	defer server.Close()
	client, err := castle.NewClient("synthetic-secret", castle.Config{
		BaseURL: server.URL,
	})
	if err != nil {
		panic(err)
	}
	var name, value api.Context_Headers_Item
	if err := name.FromContextHeaders0("User-Agent"); err != nil {
		panic(err)
	}
	if err := value.FromContextHeaders0("ExampleBrowser/1"); err != nil {
		panic(err)
	}
	var request api.Risk
	if err := request.FromLoginRiskRequest(api.LoginRiskRequest{
		Status:       api.LoginRiskRequestStatusSucceeded,
		RequestToken: new("synthetic-request-token"),
		Context: &api.Context{
			Ip:      "192.0.2.1",
			Headers: [][]api.Context_Headers_Item{{name, value}},
		},
		User: api.UserForMonitorAndRisk{
			Id: "user-123",
		},
	}); err != nil {
		panic(err)
	}
	result, err := client.Risk(context.Background(), request)
	if err != nil {
		panic(err)
	}
	login, err := result.JSON201.AsLoginResponse()
	if err != nil {
		panic(err)
	}
	action, err := login.Policy.Action.Get()
	if err != nil {
		panic(err)
	}
	fmt.Println(action)
	fmt.Println(login.Scores == nil)
}
Output:
challenge
true

func (*Client) RiskWithBody

func (c *Client) RiskWithBody(ctx context.Context, contentType string, body io.Reader) (*api.RiskResponse, error)

RiskWithBody calls POST /risk with the shared client policy.

func (*Client) UnarchiveListItem

UnarchiveListItem calls PUT /lists/{list_id}/items/{id}/unarchive with the shared client policy.

func (*Client) UnarchiveListItemWithBody

func (c *Client) UnarchiveListItemWithBody(ctx context.Context, listId string, id string, contentType string, body io.Reader) (*api.UnarchiveListItemResponse, error)

UnarchiveListItemWithBody calls PUT /lists/{list_id}/items/{id}/unarchive with the shared client policy.

func (*Client) UpdateList

UpdateList calls PUT /lists/{id} with the shared client policy.

func (*Client) UpdateListItem

func (c *Client) UpdateListItem(ctx context.Context, listId string, id string, body api.UpdateListItemJSONRequestBody) (*api.UpdateListItemResponse, error)

UpdateListItem calls PUT /lists/{list_id}/items/{id} with the shared client policy.

func (*Client) UpdateListItemWithBody

func (c *Client) UpdateListItemWithBody(ctx context.Context, listId string, id string, contentType string, body io.Reader) (*api.UpdateListItemResponse, error)

UpdateListItemWithBody calls PUT /lists/{list_id}/items/{id} with the shared client policy.

func (*Client) UpdateListWithBody

func (c *Client) UpdateListWithBody(ctx context.Context, id string, contentType string, body io.Reader) (*api.UpdateListResponse, error)

UpdateListWithBody calls PUT /lists/{id} with the shared client policy.

type Config

type Config struct {
	// BaseURL includes the API version path. Empty uses https://api.castle.io/v1.
	BaseURL string
	// HTTPClient is copied before use. Nil uses a client without a timeout.
	HTTPClient *http.Client
	// MaxResponseBytes bounds response bodies. Zero uses 4 MiB.
	MaxResponseBytes int64
}

Config configures the client. Its zero value uses Castle's production API.

Directories

Path Synopsis
Package api provides primitives to interact with the openapi HTTP API.
Package api provides primitives to interact with the openapi HTTP API.
internal
cmd/generateclient command
Command generateclient wraps generated endpoint calls in the shared SDK policy.
Command generateclient wraps generated endpoint calls in the shared SDK policy.
cmd/prepareapi command
Command prepareapi applies documented generation-only adaptations to the snapshot.
Command prepareapi applies documented generation-only adaptations to the snapshot.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL