Documentation
¶
Overview ¶
Package arcjet provides the Go SDK for Arcjet, the runtime security platform for AI code.
Use NewClient for request protection in net/http handlers and any router that exposes *http.Request. Always include Shield as a base rule, then layer route-specific rules with Client.WithRule, which returns a copy of the client without mutating the base. WithRule validates and pre-builds the rule's wire form, so it returns an error if the rule is misconfigured; keep the call near startup rather than on the hot path. Call Protect inside each handler — once per request — not in generic middleware that runs on every path.
Use NewGuardClient for non-HTTP entry points: AI agent tool calls, MCP servers, queue consumers, and background jobs. Create the GuardClient and each rule once at package scope so per-rule result accessors have a stable reference. Call GuardClient.Guard at the specific operation with a hardcoded Label such as "tools.get-weather" — never an interpolated string like fmt.Sprintf("tools.%s", name), which defeats dashboard grouping. Each rate-limit rule needs an explicit Key at call time; when there is no user context (e.g. a stdio MCP server), pick a stable identifier such as the deployment name rather than an empty string.
Arcjet is designed to fail open: if the service is unavailable, Protect and Guard return an error and the caller should continue serving.
Index ¶
- Constants
- Variables
- func SetRateLimitHeaders(w http.ResponseWriter, d Decision)
- type ArcjetError
- type BotOptions
- type BotReason
- type Client
- func (c *Client) Close(ctx context.Context) error
- func (c *Client) Protect(ctx context.Context, r *http.Request, opts ...ProtectOption) (Decision, error)
- func (c *Client) ProtectDetails(ctx context.Context, details ProtectDetails, opts ...ProtectOption) (Decision, error)
- func (c *Client) WithRule(rule Rule) (*Client, error)
- type Conclusion
- type Config
- type Decision
- type EmailOptions
- type EmailReason
- type EmailType
- type EntityType
- type ExperimentalGuardModerateContentOptions
- type ExperimentalGuardModerateContentRule
- func (r *ExperimentalGuardModerateContentRule) DeniedResult(d GuardDecision) *GuardModerateContentResult
- func (r *ExperimentalGuardModerateContentRule) ErrorResult(d GuardDecision) *ArcjetError
- func (r *ExperimentalGuardModerateContentRule) Result(d GuardDecision) *GuardModerateContentResult
- func (r *ExperimentalGuardModerateContentRule) Text(text string) GuardRuleInput
- type FilterOptions
- type FilterReason
- type FixedWindowOptions
- type GuardClient
- type GuardConfig
- type GuardCustomFunc
- type GuardCustomOptions
- type GuardCustomResult
- type GuardCustomRule
- type GuardDecision
- type GuardFixedWindowOptions
- type GuardFixedWindowResult
- type GuardFixedWindowRule
- func (r *GuardFixedWindowRule) DeniedResult(d GuardDecision) *GuardFixedWindowResult
- func (r *GuardFixedWindowRule) ErrorResult(d GuardDecision) *ArcjetError
- func (r *GuardFixedWindowRule) Key(key string, requested int) GuardRuleInput
- func (r *GuardFixedWindowRule) Result(d GuardDecision) *GuardFixedWindowResult
- type GuardLocalCustomResult
- type GuardModerateContentResult
- type GuardPromptInjectionOptions
- type GuardPromptInjectionRule
- func (r *GuardPromptInjectionRule) DeniedResult(d GuardDecision) *GuardPromptResult
- func (r *GuardPromptInjectionRule) ErrorResult(d GuardDecision) *ArcjetError
- func (r *GuardPromptInjectionRule) Result(d GuardDecision) *GuardPromptResult
- func (r *GuardPromptInjectionRule) Text(text string) GuardRuleInput
- type GuardPromptResult
- type GuardRequest
- type GuardRuleInput
- type GuardRuleResult
- type GuardRuleType
- type GuardSensitiveInfoOptions
- type GuardSensitiveInfoResult
- type GuardSensitiveInfoRule
- func (r *GuardSensitiveInfoRule) DeniedResult(d GuardDecision) *GuardSensitiveInfoResult
- func (r *GuardSensitiveInfoRule) ErrorResult(d GuardDecision) *ArcjetError
- func (r *GuardSensitiveInfoRule) Result(d GuardDecision) *GuardSensitiveInfoResult
- func (r *GuardSensitiveInfoRule) Text(text string) GuardRuleInput
- type GuardSlidingWindowOptions
- type GuardSlidingWindowResult
- type GuardSlidingWindowRule
- func (r *GuardSlidingWindowRule) DeniedResult(d GuardDecision) *GuardSlidingWindowResult
- func (r *GuardSlidingWindowRule) ErrorResult(d GuardDecision) *ArcjetError
- func (r *GuardSlidingWindowRule) Key(key string, requested int) GuardRuleInput
- func (r *GuardSlidingWindowRule) Result(d GuardDecision) *GuardSlidingWindowResult
- type GuardTokenBucketOptions
- type GuardTokenBucketResult
- type GuardTokenBucketRule
- func (r *GuardTokenBucketRule) DeniedResult(d GuardDecision) *GuardTokenBucketResult
- func (r *GuardTokenBucketRule) ErrorResult(d GuardDecision) *ArcjetError
- func (r *GuardTokenBucketRule) Key(key string, requested int) GuardRuleInput
- func (r *GuardTokenBucketRule) Result(d GuardDecision) *GuardTokenBucketResult
- type IPDetails
- type IdentifiedEntity
- type Mode
- type Platform
- type PromptInjectionOptions
- type PromptInjectionReason
- type ProtectDetails
- type ProtectOption
- func WithBody(body []byte) ProtectOption
- func WithCharacteristic(key, value string) ProtectOption
- func WithCharacteristics(values map[string]string) ProtectOption
- func WithCorrelationId(id string) ProtectOption
- func WithDetectPromptInjectionMessage(s string) ProtectOption
- func WithEmail(email string) ProtectOption
- func WithExtra(extra map[string]string) ProtectOption
- func WithFilterLocal(fields map[string]string) ProtectOption
- func WithIPSrc(ip string) ProtectOption
- func WithRequested(n int) ProtectOption
- func WithSensitiveInfoValue(s string) ProtectOption
- type ProtectOptions
- type ProtectSignupOptions
- type RateLimitReason
- type Reason
- type ReasonType
- type Rule
- func DetectBot(opts BotOptions) Rule
- func DetectPromptInjection(opts PromptInjectionOptions) Rule
- func Filter(opts FilterOptions) Rule
- func FixedWindow(opts FixedWindowOptions) Rule
- func ProtectSignup(opts ProtectSignupOptions) []Rule
- func SensitiveInfo(opts SensitiveInfoOptions) Rule
- func Shield(opts ShieldOptions) Rule
- func SlidingWindow(opts SlidingWindowOptions) Rule
- func TokenBucket(opts TokenBucketOptions) Rule
- func ValidateEmail(opts EmailOptions) Rule
- type RuleResult
- type RuleState
- type SensitiveInfoDetect
- type SensitiveInfoOptions
- type SensitiveInfoReason
- type ShieldOptions
- type ShieldReason
- type SlidingWindowOptions
- type TokenBucketOptions
- type Warning
- type WasmModule
Constants ¶
const ( BotCategoryAcademic = "CATEGORY:ACADEMIC" BotCategoryAdvertising = "CATEGORY:ADVERTISING" BotCategoryAI = "CATEGORY:AI" BotCategoryAmazon = "CATEGORY:AMAZON" BotCategoryArchive = "CATEGORY:ARCHIVE" BotCategoryBotnet = "CATEGORY:BOTNET" BotCategoryFeedFetcher = "CATEGORY:FEEDFETCHER" BotCategoryGoogle = "CATEGORY:GOOGLE" BotCategoryMeta = "CATEGORY:META" BotCategoryMicrosoft = "CATEGORY:MICROSOFT" BotCategoryMonitor = "CATEGORY:MONITOR" BotCategoryOptimizer = "CATEGORY:OPTIMIZER" BotCategoryPreview = "CATEGORY:PREVIEW" BotCategoryProgrammatic = "CATEGORY:PROGRAMMATIC" BotCategorySearchEngine = "CATEGORY:SEARCH_ENGINE" BotCategorySlack = "CATEGORY:SLACK" BotCategorySocial = "CATEGORY:SOCIAL" BotCategoryTool = "CATEGORY:TOOL" BotCategoryUnknown = "CATEGORY:UNKNOWN" BotCategoryVercel = "CATEGORY:VERCEL" BotCategoryYahoo = "CATEGORY:YAHOO" )
Bot category identifiers for use with BotOptions.Allow and BotOptions.Deny.
Categories group well-known bots so a single entry covers many user agents. Pass these alongside any specific bot identifiers from https://arcjet.com/bot-list. Strings are still accepted; these constants exist for autocomplete and to catch typos at compile time.
const Version = "0.1.0"
Version is the Arcjet Go SDK version sent with Decide and Guard requests.
Variables ¶
var ( // ErrMissingKey is returned when no Arcjet site key is configured. ErrMissingKey = errors.New("site key required (set Config.Key or ARCJET_KEY)") // ErrNilClient is returned when a method is called on a nil Client or // GuardClient. ErrNilClient = errors.New("client is nil") // ErrNilRequest is returned when Client.Protect is called with a nil // *http.Request. ErrNilRequest = errors.New("request is nil") // ErrNilRule is returned when a rule input is nil. ErrNilRule = errors.New("rule is nil") // ErrInvalidMode is returned when a Mode value is unrecognized. ErrInvalidMode = errors.New("invalid mode") // ErrAllowDenyConflict is returned when a rule sets both Allow and Deny. ErrAllowDenyConflict = errors.New("allow and deny are mutually exclusive") // ErrInvalidProxy is returned when a trusted proxy IP or CIDR is invalid. ErrInvalidProxy = errors.New("invalid trusted proxy") // ErrInvalidPlatform is returned when Config.Platform is not a recognized // Platform value. ErrInvalidPlatform = errors.New("invalid platform") // ErrInvalidLabel is returned when a Guard label fails validation. ErrInvalidLabel = errors.New("invalid guard label") // ErrInvalidRateLimit is returned when rate-limit options are invalid. ErrInvalidRateLimit = errors.New("invalid rate limit configuration") // ErrEmptyKey is returned when a Guard rate-limit key is empty. ErrEmptyKey = errors.New("rate limit key required") // ErrMissingFunc is returned when a custom rule has no evaluation // function. ErrMissingFunc = errors.New("custom rule function required") // ErrInvalidWasm is returned when a Wasm module is empty or invalid. ErrInvalidWasm = errors.New("invalid wasm module") // ErrWasmClosed is returned when a Wasm module method is called after // Close. ErrWasmClosed = errors.New("wasm module is closed") // ErrWasmExportNotFound is returned when a Wasm function export is // missing. ErrWasmExportNotFound = errors.New("wasm export not found") // ErrEmptyResponse is returned when Arcjet returns an empty decision // response. ErrEmptyResponse = errors.New("empty response") )
Sentinel errors returned by configuration and validation paths. Wrap them with fmt.Errorf("...: %w", Err...) when adding context so callers can detect the underlying cause via errors.Is.
Remote errors and per-rule errors are surfaced as ArcjetError values.
Functions ¶
func SetRateLimitHeaders ¶
func SetRateLimitHeaders(w http.ResponseWriter, d Decision)
SetRateLimitHeaders writes rate limit headers describing the decision onto w, following the IETF "RateLimit header fields for HTTP" draft. It sets:
- RateLimit: limit=<max>, remaining=<remaining>, reset=<seconds>
- RateLimit-Policy: <max>;w=<window>[, <max>;w=<window>...]
When the decision ran multiple rate limit rules, RateLimit reports the limit nearest to being exhausted (lowest remaining, then soonest reset, then smallest max) while RateLimit-Policy lists every policy. SetRateLimitHeaders is a no-op when the decision carries no rate limit reason, so it is safe to call unconditionally. Mirrors setRateLimitHeaders from @arcjet/decorate in arcjet-js.
Types ¶
type ArcjetError ¶
type ArcjetError struct {
Code string `json:"code,omitempty"`
Message string `json:"message,omitempty"`
}
ArcjetError describes an error returned by Arcjet or a local guard rule.
func (ArcjetError) Error ¶
func (e ArcjetError) Error() string
Error formats an Arcjet error as a Go error string.
func (ArcjetError) Is ¶
func (e ArcjetError) Is(target error) bool
Is reports whether target is an ArcjetError with the same, non-empty Code. Use it with errors.Is to detect specific Arcjet error codes:
if errors.Is(err, ArcjetError{Code: "AJ1100"}) { ... }
A target with an empty Code matches nothing, so ArcjetError{} is not a wildcard for "any Arcjet error" — use errors.As for that. This matters because Decision.Err returns a code-less ArcjetError.
type BotOptions ¶
type BotOptions struct {
// Mode controls whether the rule enforces denials or only reports them.
Mode Mode
// Allow lists allowed bot categories or identifiers.
Allow []string
// Deny lists denied bot categories or identifiers.
Deny []string
}
BotOptions configures bot detection.
Allow and Deny are mutually exclusive. An empty Allow list blocks all detected bots.
type BotReason ¶
type BotReason struct {
Allowed []string `json:"allowed,omitempty"`
Denied []string `json:"denied,omitempty"`
Verified bool `json:"verified,omitempty"`
Spoofed bool `json:"spoofed,omitempty"`
}
BotReason contains details for a bot detection decision.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client evaluates HTTP requests with Arcjet request protection rules.
A Client is safe for concurrent use and should be created once at startup and reused across handlers.
The cache field is shared by clients derived via WithRule — derivatives shallow-copy the parent and alias the pointer so per-rule cache entries outlive each route-specific clone. All other fields are owned per-client.
func NewClient ¶
NewClient creates a reusable request protection client.
If Config.Key is empty, NewClient reads ARCJET_KEY from the environment.
func (*Client) Protect ¶
func (c *Client) Protect(ctx context.Context, r *http.Request, opts ...ProtectOption) (Decision, error)
Protect evaluates an HTTP request with the client's configured rules.
func (*Client) ProtectDetails ¶
func (c *Client) ProtectDetails(ctx context.Context, details ProtectDetails, opts ...ProtectOption) (Decision, error)
ProtectDetails evaluates explicit request details with the client's rules.
type Conclusion ¶
type Conclusion string
Conclusion is the top-level Arcjet decision outcome.
Conclusion values are normalized when JSON-decoded: both the bare wire strings ("DENY", "ALLOW", "CHALLENGE", "ERROR") and the prefixed forms ("CONCLUSION_DENY", "GUARD_CONCLUSION_DENY", etc.) are mapped to the canonical constants below.
const ( // ConclusionAllow means Arcjet allowed the request or guard call. ConclusionAllow Conclusion = "ALLOW" // ConclusionDeny means Arcjet denied the request or guard call. ConclusionDeny Conclusion = "DENY" // ConclusionChallenge means Arcjet returned a challenge decision. ConclusionChallenge Conclusion = "CHALLENGE" // ConclusionError means Arcjet or a local rule produced an error result. ConclusionError Conclusion = "ERROR" )
func (Conclusion) LogValue ¶
func (c Conclusion) LogValue() slog.Value
LogValue implements slog.LogValuer so Conclusion logs as its string form.
func (*Conclusion) UnmarshalJSON ¶
func (c *Conclusion) UnmarshalJSON(data []byte) error
UnmarshalJSON normalizes wire-format conclusion strings to canonical Conclusion constants. Single source of truth is parseConclusion.
type Config ¶
type Config struct {
// Key is the Arcjet site key. If empty, ARCJET_KEY is used.
Key string
// Rules are the request protection rules evaluated for each request.
Rules []Rule
// Characteristics are global rate-limit characteristic keys.
Characteristics []string
// HTTPClient is the client used for Arcjet RPCs. If nil, http.DefaultClient
// is used, which honors the standard HTTP_PROXY, HTTPS_PROXY, and NO_PROXY
// environment variables via http.ProxyFromEnvironment. Supply a custom
// client only if you need different behavior; set its Transport's Proxy to
// http.ProxyFromEnvironment to preserve outbound proxy support.
HTTPClient *http.Client
// BaseURL overrides the Arcjet Decide API base URL.
BaseURL string
// SDKVersion overrides the version reported to Arcjet.
SDKVersion string
// Proxies are trusted proxy IPs or CIDRs used to trust X-Forwarded-For.
Proxies []string
// Platform selects a managed hosting platform explicitly, overriding the
// environment auto-detection. Set it when running behind a platform whose
// environment variables aren't present — most importantly a Go service
// behind the Cloudflare CDN. Leave empty to auto-detect.
Platform Platform
// SensitiveInfoDetect, if set, classifies tokens the bundled analyzer
// didn't recognise. Shared across every SensitiveInfo rule on this
// Client — the same callback model as arcjet-py's
// `ImportCallbacks.sensitive_info_detect` and arcjet-js's analyzer
// `detect` hook.
SensitiveInfoDetect SensitiveInfoDetect
}
Config configures a request protection Client.
type Decision ¶
type Decision struct {
ID string `json:"id,omitempty"`
Conclusion Conclusion `json:"conclusion,omitempty"`
Reason Reason `json:"reason"`
Results []RuleResult
// TTL is the number of seconds the decision can be cached.
TTL int
IP IPDetails
Raw json.RawMessage
}
Decision is the result of evaluating request protection rules.
func (Decision) Err ¶
Err returns the decision's terminal error, or nil if the decision did not error. The returned error is an ArcjetError carrying the Reason message when available.
func (Decision) IsChallenged ¶
IsChallenged reports whether Arcjet returned a challenge decision.
func (Decision) IsMissingUserAgent ¶
IsMissingUserAgent reports whether a bot rule denied the request because it had no User-Agent header. A missing User-Agent is a common indicator of an automated client, since IETF HTTP Semantics (RFC 9110) recommends sending one. Mirrors @arcjet/inspect's isMissingUserAgent in arcjet-js.
func (Decision) IsSpoofedBot ¶
IsSpoofedBot reports whether a bot rule detected a spoofed verified bot — one claiming to be a well-known crawler but originating from an IP outside that crawler's published ranges.
func (Decision) IsVerifiedBot ¶
IsVerifiedBot reports whether a bot rule confirmed the request came from a verified bot (for example a search engine crawler whose IP matches its published ranges). You may want to allow such requests even when other signals would otherwise deny them.
type EmailOptions ¶
type EmailOptions struct {
// Mode controls whether the rule enforces denials or only reports them.
Mode Mode
// Allow lists allowed email types.
Allow []EmailType
// Deny lists denied email types.
Deny []EmailType
// RequireTopLevelDomain requires a top-level domain in the address when true.
RequireTopLevelDomain *bool
// AllowDomainLiteral allows domain literals such as user@[192.0.2.1] when true.
AllowDomainLiteral *bool
}
EmailOptions configures email validation.
type EmailReason ¶
type EmailReason struct {
Types []EmailType `json:"types,omitempty"`
}
EmailReason contains details for an email validation decision.
type EmailType ¶
type EmailType string
EmailType classifies an email address for ValidateEmail rules.
Values are stored in their canonical form (without the "EMAIL_TYPE_" wire prefix). UnmarshalJSON strips the prefix when decoding responses. See constants.go for the supported constants.
const ( EmailTypeDisposable EmailType = "DISPOSABLE" EmailTypeFree EmailType = "FREE" EmailTypeInvalid EmailType = "INVALID" EmailTypeNoMXRecords EmailType = "NO_MX_RECORDS" EmailTypeNoGravatar EmailType = "NO_GRAVATAR" )
Email type identifiers for use with EmailOptions.Allow and EmailOptions.Deny.
func (EmailType) LogValue ¶
LogValue implements slog.LogValuer so EmailType logs as its string form.
func (*EmailType) UnmarshalJSON ¶
UnmarshalJSON strips the wire "EMAIL_TYPE_" prefix when present so values match the EmailType constants.
type EntityType ¶
type EntityType string
EntityType classifies a sensitive-information entity. See constants.go for the supported constants.
const ( SensitiveInfoEmail EntityType = "EMAIL" SensitiveInfoPhoneNumber EntityType = "PHONE_NUMBER" SensitiveInfoIPAddress EntityType = "IP_ADDRESS" SensitiveInfoCreditCardNumber EntityType = "CREDIT_CARD_NUMBER" )
Sensitive information entity type identifiers for use with SensitiveInfoOptions.Allow, SensitiveInfoOptions.Deny, GuardSensitiveInfoOptions.Allow, and GuardSensitiveInfoOptions.Deny.
func (EntityType) LogValue ¶
func (e EntityType) LogValue() slog.Value
LogValue implements slog.LogValuer so EntityType logs as its string form.
type ExperimentalGuardModerateContentOptions ¶
type ExperimentalGuardModerateContentOptions struct {
// Mode controls whether the rule enforces denials or only reports them.
Mode Mode
// Label identifies this rule in the Arcjet dashboard.
Label string
// Metadata is recorded with every invocation of this rule.
Metadata map[string]string
}
ExperimentalGuardModerateContentOptions configures a Guard content moderation rule.
Experimental: the rule name and result shape may change. This functionality may not be available yet, so while this rule is experimental a call may simply return an error result. Errors are fail open, so the decision reports an error while the conclusion stays ALLOW. Check the latest version of this SDK to see whether the rule is now stable.
type ExperimentalGuardModerateContentRule ¶
type ExperimentalGuardModerateContentRule struct {
// contains filtered or unexported fields
}
ExperimentalGuardModerateContentRule is a configured Guard content moderation rule.
Experimental: see ExperimentalGuardModerateContent.
func ExperimentalGuardModerateContent ¶
func ExperimentalGuardModerateContent(opts ExperimentalGuardModerateContentOptions) (*ExperimentalGuardModerateContentRule, error)
ExperimentalGuardModerateContent creates a Guard content moderation rule.
Experimental: the rule name and result shape may change, and the name is deliberately prefixed to make that clear. This functionality may not be available yet, so while this rule is experimental a call may simply return an error result. Errors are fail open, so the conclusion stays ALLOW and GuardDecision.HasFailedOpen reports true (inspect the errored result with GuardDecision.ErrorResults). Check the latest version of this SDK to see whether the rule is now stable.
func (*ExperimentalGuardModerateContentRule) DeniedResult ¶
func (r *ExperimentalGuardModerateContentRule) DeniedResult(d GuardDecision) *GuardModerateContentResult
DeniedResult returns this rule's content moderation result if it denied the Guard call, or nil otherwise.
func (*ExperimentalGuardModerateContentRule) ErrorResult ¶
func (r *ExperimentalGuardModerateContentRule) ErrorResult(d GuardDecision) *ArcjetError
ErrorResult returns this rule's error if it failed to evaluate, or nil otherwise. Errors are fail-open, so an errored rule never surfaces through Result or DeniedResult — this is the only accessor that returns it. While this rule is experimental a call may simply return an error result.
func (*ExperimentalGuardModerateContentRule) Result ¶
func (r *ExperimentalGuardModerateContentRule) Result(d GuardDecision) *GuardModerateContentResult
Result returns this rule's content moderation result from the given Guard decision, or nil if the rule did not produce one.
func (*ExperimentalGuardModerateContentRule) Text ¶
func (r *ExperimentalGuardModerateContentRule) Text(text string) GuardRuleInput
Text binds text to moderate for one Guard call.
type FilterOptions ¶
type FilterOptions struct {
// Mode controls whether the rule enforces denials or only reports them.
Mode Mode
// Allow expressions allow matching requests and deny non-matching requests.
Allow []string
// Deny expressions deny matching requests.
Deny []string
}
FilterOptions configures request filters.
Allow and Deny expressions are mutually exclusive.
type FilterReason ¶
type FilterReason struct {
MatchedExpressions []string `json:"matchedExpressions,omitempty"`
UndeterminedExpressions []string `json:"undeterminedExpressions,omitempty"`
}
FilterReason contains request filter match results.
type FixedWindowOptions ¶
type FixedWindowOptions struct {
// Mode controls whether the rule enforces denials or only reports them.
Mode Mode
// Characteristics are rate-limit keys such as "userId".
Characteristics []string
// Window is the fixed window duration.
Window time.Duration
// MaxRequests is the maximum number of requests per window.
MaxRequests int
}
FixedWindowOptions configures a fixed window rate limit rule.
type GuardClient ¶
type GuardClient struct {
// contains filtered or unexported fields
}
GuardClient evaluates non-HTTP inputs such as tool calls, jobs, and queues.
A GuardClient is safe for concurrent use and should be created once at startup.
func NewGuardClient ¶
func NewGuardClient(cfg GuardConfig) (*GuardClient, error)
NewGuardClient creates a reusable Guard client.
If GuardConfig.Key is empty, NewGuardClient reads ARCJET_KEY from the environment.
func (*GuardClient) Close ¶
func (c *GuardClient) Close(ctx context.Context) error
Close releases the locally-compiled wasm factory, if any. Safe to call even if no local Guard rule was ever used.
func (*GuardClient) Guard ¶
func (c *GuardClient) Guard(ctx context.Context, req GuardRequest) (GuardDecision, error)
Guard evaluates bound guard rule inputs.
Programmer errors (nil client, invalid label, nil rule, or a rule that cannot be encoded) return the zero-value decision and a non-nil error — callers must handle the error. These are not fail-open: they reflect misuse or misconfiguration, not runtime degradation.
Runtime degradation — a transport failure reaching the Decide service — is fail-open: the returned decision is a usable ALLOW carrying a synthetic errored result (code TRANSPORT_ERROR) alongside the non-nil error. A caller that ignores the error still gets a decision where GuardDecision.HasFailedOpen reports true and GuardDecision.ErrorResults surfaces the failure, so a fail-closed policy stays honest. A missing or malformed response is also fail-open (synthesized by guardDecisionFromProto), but returns a nil error.
type GuardConfig ¶
type GuardConfig struct {
// Key is the Arcjet site key. If empty, ARCJET_KEY is used.
Key string
// HTTPClient is the client used for Arcjet RPCs. If nil, http.DefaultClient
// is used, which honors the standard HTTP_PROXY, HTTPS_PROXY, and NO_PROXY
// environment variables via http.ProxyFromEnvironment. Supply a custom
// client only if you need different behavior; set its Transport's Proxy to
// http.ProxyFromEnvironment to preserve outbound proxy support.
HTTPClient *http.Client
// BaseURL overrides the Arcjet Guard API base URL.
BaseURL string
// SDKVersion overrides the version reported to Arcjet.
SDKVersion string
// SensitiveInfoDetect, if set, classifies tokens the bundled analyzer
// didn't recognise. Shared across every GuardSensitiveInfo rule on
// this client.
SensitiveInfoDetect SensitiveInfoDetect
}
GuardConfig configures a GuardClient.
type GuardCustomFunc ¶
GuardCustomFunc evaluates one custom local Guard rule input.
type GuardCustomOptions ¶
type GuardCustomOptions struct {
// Mode controls whether the rule enforces denials or only reports them.
Mode Mode
// Config is the rule configuration recorded with each invocation.
Config map[string]string
// Func is the local evaluation function. Required.
Func GuardCustomFunc
// Label identifies this rule in the Arcjet dashboard.
Label string
// Metadata is recorded with every invocation of this rule.
Metadata map[string]string
}
GuardCustomOptions configures a custom local Guard rule.
type GuardCustomResult ¶
type GuardCustomResult struct {
// Conclusion is the custom rule conclusion.
Conclusion Conclusion
// Data is optional result data recorded with the custom rule result.
Data map[string]string
}
GuardCustomResult is the result returned by a custom local Guard rule.
type GuardCustomRule ¶
type GuardCustomRule struct {
// contains filtered or unexported fields
}
GuardCustomRule is a configured custom local Guard rule.
func GuardCustom ¶
func GuardCustom(opts GuardCustomOptions) (*GuardCustomRule, error)
GuardCustom creates a custom local Guard rule.
func (*GuardCustomRule) DeniedResult ¶
func (r *GuardCustomRule) DeniedResult(d GuardDecision) *GuardLocalCustomResult
DeniedResult returns this rule's custom result if it denied the Guard call, or nil otherwise.
func (*GuardCustomRule) ErrorResult ¶
func (r *GuardCustomRule) ErrorResult(d GuardDecision) *ArcjetError
ErrorResult returns this rule's error if it failed to evaluate, or nil otherwise. Errors are fail-open, so an errored rule never surfaces through Result or DeniedResult — this is the only accessor that returns it.
func (*GuardCustomRule) Input ¶
func (r *GuardCustomRule) Input(data map[string]string) GuardRuleInput
Input binds custom rule input data for one Guard call.
func (*GuardCustomRule) Result ¶
func (r *GuardCustomRule) Result(d GuardDecision) *GuardLocalCustomResult
Result returns this rule's custom result from the given Guard decision, or nil if the rule did not produce one.
type GuardDecision ¶
type GuardDecision struct {
ID string
Conclusion Conclusion
Reason ReasonType
Results []GuardRuleResult
// Warnings are decision-level diagnostics from request validation (e.g. an
// invalid metadata key that was stripped). The decision is still valid;
// warnings never change the conclusion.
Warnings []Warning
}
GuardDecision is the result of a Guard evaluation.
func (GuardDecision) Err ¶
func (d GuardDecision) Err() error
Err returns the first per-rule ArcjetError carried by this decision, or nil if no rule errored. Warnings are not errors and are not returned here. Useful with errors.Is / errors.As when bubbling up Arcjet errors to handlers.
func (GuardDecision) ErrorResults ¶
func (d GuardDecision) ErrorResults() []GuardRuleResult
ErrorResults returns the rule results that errored — rules (or the decision itself) that could not be processed. Empty when nothing errored. Each carries its *ArcjetError in Error; correlate one to a rule via ConfigID/InputID. Arcjet fails open, so an errored result is still ALLOW.
func (GuardDecision) HasFailedOpen ¶
func (d GuardDecision) HasFailedOpen() bool
HasFailedOpen reports whether this decision returned ALLOW only because a rule or the decision could not be processed — i.e. it failed open. Gate a fail-closed policy on this:
if decision.HasFailedOpen() {
return deny()
}
"Failed open" describes an outcome of this decision, not the policy configuration.
func (GuardDecision) IsAllowed ¶
func (d GuardDecision) IsAllowed() bool
IsAllowed reports whether Arcjet allowed the Guard call.
func (GuardDecision) IsDenied ¶
func (d GuardDecision) IsDenied() bool
IsDenied reports whether Arcjet denied the Guard call.
type GuardFixedWindowOptions ¶
type GuardFixedWindowOptions struct {
// Mode controls whether the rule enforces denials or only reports them.
Mode Mode
// Window is the fixed window duration.
Window time.Duration
// MaxRequests is the maximum number of requests per window.
MaxRequests int
// Bucket groups counters for this rule.
Bucket string
// Label identifies this rule in the Arcjet dashboard.
Label string
// Metadata is recorded with every invocation of this rule.
Metadata map[string]string
}
GuardFixedWindowOptions configures a Guard fixed window rule.
type GuardFixedWindowResult ¶
type GuardFixedWindowResult struct {
Conclusion Conclusion `json:"conclusion"`
RemainingRequests int `json:"remainingRequests"`
MaxRequests int `json:"maxRequests"`
ResetAtUnixSeconds int64 `json:"resetAtUnixSeconds"`
WindowSeconds int `json:"windowSeconds"`
}
GuardFixedWindowResult contains Guard fixed window result details.
type GuardFixedWindowRule ¶
type GuardFixedWindowRule struct {
// contains filtered or unexported fields
}
GuardFixedWindowRule is a configured Guard fixed window rule.
func GuardFixedWindow ¶
func GuardFixedWindow(opts GuardFixedWindowOptions) (*GuardFixedWindowRule, error)
GuardFixedWindow creates a Guard fixed window rule.
func (*GuardFixedWindowRule) DeniedResult ¶
func (r *GuardFixedWindowRule) DeniedResult(d GuardDecision) *GuardFixedWindowResult
DeniedResult returns this rule's fixed window result if it denied the Guard call, or nil otherwise.
func (*GuardFixedWindowRule) ErrorResult ¶
func (r *GuardFixedWindowRule) ErrorResult(d GuardDecision) *ArcjetError
ErrorResult returns this rule's error if it failed to evaluate, or nil otherwise. Errors are fail-open, so an errored rule never surfaces through Result or DeniedResult — this is the only accessor that returns it.
func (*GuardFixedWindowRule) Key ¶
func (r *GuardFixedWindowRule) Key(key string, requested int) GuardRuleInput
Key binds a fixed window key and requested count for one Guard call.
func (*GuardFixedWindowRule) Result ¶
func (r *GuardFixedWindowRule) Result(d GuardDecision) *GuardFixedWindowResult
Result returns this rule's fixed window result from the given Guard decision, or nil if the rule did not produce one.
type GuardLocalCustomResult ¶
type GuardLocalCustomResult struct {
Conclusion Conclusion `json:"conclusion"`
Data map[string]string `json:"data,omitempty"`
}
GuardLocalCustomResult contains custom local Guard result details.
type GuardModerateContentResult ¶
type GuardModerateContentResult struct {
Conclusion Conclusion `json:"conclusion"`
Detected bool `json:"detected"`
}
GuardModerateContentResult contains Guard content moderation result details.
type GuardPromptInjectionOptions ¶
type GuardPromptInjectionOptions struct {
// Mode controls whether the rule enforces denials or only reports them.
Mode Mode
// Label identifies this rule in the Arcjet dashboard.
Label string
// Metadata is recorded with every invocation of this rule.
Metadata map[string]string
}
GuardPromptInjectionOptions configures a Guard prompt injection rule.
type GuardPromptInjectionRule ¶
type GuardPromptInjectionRule struct {
// contains filtered or unexported fields
}
GuardPromptInjectionRule is a configured Guard prompt injection rule.
func GuardPromptInjection ¶
func GuardPromptInjection(opts GuardPromptInjectionOptions) (*GuardPromptInjectionRule, error)
GuardPromptInjection creates a Guard prompt injection rule.
func (*GuardPromptInjectionRule) DeniedResult ¶
func (r *GuardPromptInjectionRule) DeniedResult(d GuardDecision) *GuardPromptResult
DeniedResult returns this rule's prompt injection result if it denied the Guard call, or nil otherwise.
func (*GuardPromptInjectionRule) ErrorResult ¶
func (r *GuardPromptInjectionRule) ErrorResult(d GuardDecision) *ArcjetError
ErrorResult returns this rule's error if it failed to evaluate, or nil otherwise. Errors are fail-open, so an errored rule never surfaces through Result or DeniedResult — this is the only accessor that returns it.
func (*GuardPromptInjectionRule) Result ¶
func (r *GuardPromptInjectionRule) Result(d GuardDecision) *GuardPromptResult
Result returns this rule's prompt injection result from the given Guard decision, or nil if the rule did not produce one.
func (*GuardPromptInjectionRule) Text ¶
func (r *GuardPromptInjectionRule) Text(text string) GuardRuleInput
Text binds text to scan for one Guard call.
type GuardPromptResult ¶
type GuardPromptResult struct {
Conclusion Conclusion `json:"conclusion"`
Detected bool `json:"detected"`
}
GuardPromptResult contains Guard prompt injection result details.
type GuardRequest ¶
type GuardRequest struct {
// Label identifies this Guard call.
Label string
// Metadata is optional key-value metadata for this Guard call.
Metadata map[string]string
// CorrelationId is an optional, caller-supplied opaque identifier used to
// correlate this Guard call with other Guard and Protect calls that belong
// to the same workflow, agent run, or multi-step task. Unlike Metadata it
// is a dedicated, indexable field; it does not affect the decision. Bounded
// server-side to 256 bytes of printable ASCII; invalid values are dropped.
CorrelationId string
// Rules are bound rule inputs evaluated by Guard.
Rules []GuardRuleInput
}
GuardRequest is a single Guard evaluation request.
type GuardRuleInput ¶
type GuardRuleInput interface {
// contains filtered or unexported methods
}
GuardRuleInput is a rule bound to runtime input for a Guard call.
The unexported `guardSubmission` method seals the interface so external types can't implement it; SDK-provided rules use it to build the wire submission, optionally running locally via the shared evaluator.
type GuardRuleResult ¶
type GuardRuleResult struct {
ResultID string
ConfigID string
InputID string
Type GuardRuleType
Conclusion Conclusion
Reason ReasonType
TokenBucket *GuardTokenBucketResult
FixedWindow *GuardFixedWindowResult
SlidingWindow *GuardSlidingWindowResult
PromptInjection *GuardPromptResult
ModerateContent *GuardModerateContentResult
LocalSensitiveInfo *GuardSensitiveInfoResult
LocalCustom *GuardLocalCustomResult
Error *ArcjetError
NotRun bool
// Warnings are per-rule diagnostics: this rule was processed correctly
// (the result is trustworthy) but something about it should be fixed.
// Informational; never changes the rule's conclusion. Empty until the
// Decide service emits per-rule diagnostics.
Warnings []Warning
}
GuardRuleResult is the per-rule result included in a Guard decision.
func (GuardRuleResult) IsDenied ¶
func (r GuardRuleResult) IsDenied() bool
IsDenied reports whether this Guard rule result denied the Guard call.
func (GuardRuleResult) IsErrored ¶
func (r GuardRuleResult) IsErrored() bool
IsErrored reports whether this Guard rule result contains an error.
type GuardRuleType ¶
type GuardRuleType string
GuardRuleType identifies a Guard rule family in a GuardRuleResult.
const ( // GuardRuleTypeUnknown is used when a Guard rule type is unrecognized. GuardRuleTypeUnknown GuardRuleType = "" // GuardRuleTypeTokenBucket identifies a Guard token bucket rule. GuardRuleTypeTokenBucket GuardRuleType = "TOKEN_BUCKET" // GuardRuleTypeFixedWindow identifies a Guard fixed window rule. GuardRuleTypeFixedWindow GuardRuleType = "FIXED_WINDOW" // GuardRuleTypeSlidingWindow identifies a Guard sliding window rule. GuardRuleTypeSlidingWindow GuardRuleType = "SLIDING_WINDOW" // GuardRuleTypePromptInjection identifies a Guard prompt injection rule. GuardRuleTypePromptInjection GuardRuleType = "PROMPT_INJECTION" // GuardRuleTypeModerateContent identifies a Guard content moderation rule. GuardRuleTypeModerateContent GuardRuleType = "MODERATE_CONTENT" // GuardRuleTypeLocalSensitiveInfo identifies a local sensitive info Guard rule. GuardRuleTypeLocalSensitiveInfo GuardRuleType = "LOCAL_SENSITIVE_INFO" // GuardRuleTypeLocalCustom identifies a custom local Guard rule. GuardRuleTypeLocalCustom GuardRuleType = "LOCAL_CUSTOM" )
func (GuardRuleType) LogValue ¶
func (g GuardRuleType) LogValue() slog.Value
LogValue implements slog.LogValuer so GuardRuleType logs as its string form.
type GuardSensitiveInfoOptions ¶
type GuardSensitiveInfoOptions struct {
// Mode controls whether the rule enforces denials or only reports them.
Mode Mode
// Allow lists entity types allowed in scanned text.
Allow []EntityType
// Deny lists entity types denied in scanned text.
Deny []EntityType
// Label identifies this rule in the Arcjet dashboard.
Label string
// Metadata is recorded with every invocation of this rule.
Metadata map[string]string
}
GuardSensitiveInfoOptions configures local Guard sensitive information detection.
type GuardSensitiveInfoResult ¶
type GuardSensitiveInfoResult struct {
Conclusion Conclusion `json:"conclusion"`
Detected bool `json:"detected"`
DetectedEntityTypes []EntityType `json:"detectedEntityTypes"`
}
GuardSensitiveInfoResult contains Guard sensitive information result details.
type GuardSensitiveInfoRule ¶
type GuardSensitiveInfoRule struct {
// contains filtered or unexported fields
}
GuardSensitiveInfoRule is a configured local Guard sensitive information rule.
func GuardSensitiveInfo ¶
func GuardSensitiveInfo(opts GuardSensitiveInfoOptions) (*GuardSensitiveInfoRule, error)
GuardSensitiveInfo creates a local Guard sensitive information rule.
func (*GuardSensitiveInfoRule) DeniedResult ¶
func (r *GuardSensitiveInfoRule) DeniedResult(d GuardDecision) *GuardSensitiveInfoResult
DeniedResult returns this rule's sensitive information result if it denied the Guard call, or nil otherwise.
func (*GuardSensitiveInfoRule) ErrorResult ¶
func (r *GuardSensitiveInfoRule) ErrorResult(d GuardDecision) *ArcjetError
ErrorResult returns this rule's error if it failed to evaluate, or nil otherwise. Errors are fail-open, so an errored rule never surfaces through Result or DeniedResult — this is the only accessor that returns it.
func (*GuardSensitiveInfoRule) Result ¶
func (r *GuardSensitiveInfoRule) Result(d GuardDecision) *GuardSensitiveInfoResult
Result returns this rule's sensitive information result from the given Guard decision, or nil if the rule did not produce one.
func (*GuardSensitiveInfoRule) Text ¶
func (r *GuardSensitiveInfoRule) Text(text string) GuardRuleInput
Text binds text to scan for one Guard call.
Detection runs locally via the bundled WebAssembly analyzer (the same `arcjet_analyze_js_req` component used by arcjet-js and arcjet-py); the text never leaves the SDK. The submission carries a SHA-256 hash of the text alongside the locally-computed result so the server can correlate inputs without seeing the raw value.
type GuardSlidingWindowOptions ¶
type GuardSlidingWindowOptions struct {
// Mode controls whether the rule enforces denials or only reports them.
Mode Mode
// Interval is the sliding window interval.
Interval time.Duration
// MaxRequests is the maximum number of requests per interval.
MaxRequests int
// Bucket groups counters for this rule.
Bucket string
// Label identifies this rule in the Arcjet dashboard.
Label string
// Metadata is recorded with every invocation of this rule.
Metadata map[string]string
}
GuardSlidingWindowOptions configures a Guard sliding window rule.
type GuardSlidingWindowResult ¶
type GuardSlidingWindowResult struct {
Conclusion Conclusion `json:"conclusion"`
RemainingRequests int `json:"remainingRequests"`
MaxRequests int `json:"maxRequests"`
ResetAtUnixSeconds int64 `json:"resetAtUnixSeconds"`
IntervalSeconds int `json:"intervalSeconds"`
}
GuardSlidingWindowResult contains Guard sliding window result details.
type GuardSlidingWindowRule ¶
type GuardSlidingWindowRule struct {
// contains filtered or unexported fields
}
GuardSlidingWindowRule is a configured Guard sliding window rule.
func GuardSlidingWindow ¶
func GuardSlidingWindow(opts GuardSlidingWindowOptions) (*GuardSlidingWindowRule, error)
GuardSlidingWindow creates a Guard sliding window rule.
func (*GuardSlidingWindowRule) DeniedResult ¶
func (r *GuardSlidingWindowRule) DeniedResult(d GuardDecision) *GuardSlidingWindowResult
DeniedResult returns this rule's sliding window result if it denied the Guard call, or nil otherwise.
func (*GuardSlidingWindowRule) ErrorResult ¶
func (r *GuardSlidingWindowRule) ErrorResult(d GuardDecision) *ArcjetError
ErrorResult returns this rule's error if it failed to evaluate, or nil otherwise. Errors are fail-open, so an errored rule never surfaces through Result or DeniedResult — this is the only accessor that returns it.
func (*GuardSlidingWindowRule) Key ¶
func (r *GuardSlidingWindowRule) Key(key string, requested int) GuardRuleInput
Key binds a sliding window key and requested count for one Guard call.
func (*GuardSlidingWindowRule) Result ¶
func (r *GuardSlidingWindowRule) Result(d GuardDecision) *GuardSlidingWindowResult
Result returns this rule's sliding window result from the given Guard decision, or nil if the rule did not produce one.
type GuardTokenBucketOptions ¶
type GuardTokenBucketOptions struct {
// Mode controls whether the rule enforces denials or only reports them.
Mode Mode
// RefillRate is the number of tokens added per interval.
RefillRate int
// Interval is the token refill interval.
Interval time.Duration
// Capacity is the maximum bucket size.
Capacity int
// Bucket groups counters for this rule.
Bucket string
// Label identifies this rule in the Arcjet dashboard.
Label string
// Metadata is recorded with every invocation of this rule.
Metadata map[string]string
}
GuardTokenBucketOptions configures a Guard token bucket rule.
type GuardTokenBucketResult ¶
type GuardTokenBucketResult struct {
Conclusion Conclusion `json:"conclusion"`
RemainingTokens int `json:"remainingTokens"`
MaxTokens int `json:"maxTokens"`
ResetAtUnixSeconds int64 `json:"resetAtUnixSeconds"`
RefillRate int `json:"refillRate"`
RefillIntervalSeconds int `json:"refillIntervalSeconds"`
}
GuardTokenBucketResult contains Guard token bucket result details.
type GuardTokenBucketRule ¶
type GuardTokenBucketRule struct {
// contains filtered or unexported fields
}
GuardTokenBucketRule is a configured Guard token bucket rule.
func GuardTokenBucket ¶
func GuardTokenBucket(opts GuardTokenBucketOptions) (*GuardTokenBucketRule, error)
GuardTokenBucket creates a Guard token bucket rule.
func (*GuardTokenBucketRule) DeniedResult ¶
func (r *GuardTokenBucketRule) DeniedResult(d GuardDecision) *GuardTokenBucketResult
DeniedResult returns this rule's token bucket result if it denied the Guard call, or nil otherwise. Useful for reading reset and remaining-token information when returning a "rate limited" response to the caller.
func (*GuardTokenBucketRule) ErrorResult ¶
func (r *GuardTokenBucketRule) ErrorResult(d GuardDecision) *ArcjetError
ErrorResult returns this rule's error if it failed to evaluate, or nil otherwise. Errors are fail-open (the conclusion stays ALLOW), so an errored rule never surfaces through Result or DeniedResult — this is the only accessor that returns it. Correlated by ConfigID like the other accessors.
func (*GuardTokenBucketRule) Key ¶
func (r *GuardTokenBucketRule) Key(key string, requested int) GuardRuleInput
Key binds a token bucket key and requested token count for one Guard call.
func (*GuardTokenBucketRule) Result ¶
func (r *GuardTokenBucketRule) Result(d GuardDecision) *GuardTokenBucketResult
Result returns this rule's token bucket result from the given Guard decision, or nil if the rule did not produce one.
type IPDetails ¶
type IPDetails struct {
Latitude float64 `json:"latitude,omitempty"`
Longitude float64 `json:"longitude,omitempty"`
AccuracyRadius int32 `json:"accuracyRadius,omitempty"`
Timezone string `json:"timezone,omitempty"`
PostalCode string `json:"postalCode,omitempty"`
City string `json:"city,omitempty"`
Region string `json:"region,omitempty"`
Country string `json:"country,omitempty"`
CountryName string `json:"countryName,omitempty"`
Continent string `json:"continent,omitempty"`
ContinentName string `json:"continentName,omitempty"`
ASN string `json:"asn,omitempty"`
ASNName string `json:"asnName,omitempty"`
ASNDomain string `json:"asnDomain,omitempty"`
ASNType string `json:"asnType,omitempty"`
ASNCountry string `json:"asnCountry,omitempty"`
Service string `json:"service,omitempty"`
IsHosting bool `json:"isHosting,omitempty"`
IsVPN bool `json:"isVpn,omitempty"`
IsProxy bool `json:"isProxy,omitempty"`
IsTor bool `json:"isTor,omitempty"`
IsRelay bool `json:"isRelay,omitempty"`
IsAbuser bool `json:"isAbuser,omitempty"`
Bots map[string]string `json:"bots,omitempty"`
}
IPDetails contains geolocation, network, and reputation details for a request IP.
type IdentifiedEntity ¶
type IdentifiedEntity struct {
Type EntityType `json:"identifiedType,omitempty"`
Start int `json:"start,omitempty"`
End int `json:"end,omitempty"`
}
IdentifiedEntity describes a sensitive information entity found in text.
type Platform ¶
type Platform string
Platform names a managed hosting platform whose proxy headers Arcjet can trust to determine the client IP. Set Config.Platform to one of these to select a platform explicitly when its environment isn't auto-detected — most importantly a Go service behind the Cloudflare CDN, which does not set the CF_PAGES variable detectPlatform looks for. The names mirror the platform values accepted by arcjet-js's @arcjet/ip.
type PromptInjectionOptions ¶
type PromptInjectionOptions struct {
// Mode controls whether the rule enforces denials or only reports them.
Mode Mode
}
PromptInjectionOptions configures prompt injection detection.
Arcjet no longer exposes a prompt injection threshold; use Mode to enforce or dry-run the rule.
type PromptInjectionReason ¶
type PromptInjectionReason struct {
Detected bool `json:"injectionDetected,omitempty"`
TotalTokens int `json:"totalTokens,omitempty"`
}
PromptInjectionReason contains prompt injection detection results.
type ProtectDetails ¶
type ProtectDetails struct {
// IP is the request source IP address.
IP string
// Method is the HTTP method.
Method string
// Protocol is the HTTP protocol string.
Protocol string
// Host is the request host.
Host string
// Path is the URL path.
Path string
// Headers are request headers keyed by lowercase header name.
Headers map[string]string
// Body is an optional request body override.
Body []byte
// Email is the email address used by ValidateEmail.
Email string
// Cookies is the raw Cookie header.
Cookies string
// Query is the raw URL query, with or without a leading question mark.
Query string
// Extra contains additional string fields sent to Arcjet.
Extra map[string]string
// CorrelationId is an optional, caller-supplied opaque identifier used to
// correlate this request with other Protect and Guard calls that belong to
// the same workflow, agent run, or multi-step task. It does not affect the
// decision and is excluded from the decision cache key; it is stored
// alongside the recorded decision so a chain of actions can be
// reconstructed. Bounded server-side to 256 bytes of printable ASCII;
// invalid values are dropped, not truncated.
CorrelationId string
}
ProtectDetails is the request data Arcjet evaluates.
Use DetailsFromRequest or Client.Protect for ordinary HTTP handlers. Construct ProtectDetails directly when protecting a non-standard request source.
func DetailsFromRequest ¶
func DetailsFromRequest(r *http.Request) ProtectDetails
DetailsFromRequest extracts Arcjet request details from an HTTP request.
It uses Request.RemoteAddr for the source IP. Configure Config.Proxies and use Client.Protect when Arcjet should trust X-Forwarded-For from known proxies, or when running on a supported hosting platform (Fly.io, Vercel, Render, Firebase, Railway) where Client.Protect reads the platform's signed headers.
type ProtectOption ¶
type ProtectOption func(*ProtectOptions)
ProtectOption configures a single Client.Protect or Client.ProtectDetails call.
func WithBody ¶
func WithBody(body []byte) ProtectOption
WithBody overrides the request body sent to Arcjet.
func WithCharacteristic ¶
func WithCharacteristic(key, value string) ProtectOption
WithCharacteristic sets a single rate-limit characteristic value. It merges with any prior WithCharacteristic or WithCharacteristics call.
func WithCharacteristics ¶
func WithCharacteristics(values map[string]string) ProtectOption
WithCharacteristics sets values for rate-limit characteristics declared by rules.
func WithCorrelationId ¶
func WithCorrelationId(id string) ProtectOption
WithCorrelationId sets an optional, caller-supplied opaque identifier used to correlate this request with other Protect and Guard calls in the same workflow or agent run. It does not affect the decision and is excluded from the decision cache key.
func WithDetectPromptInjectionMessage ¶
func WithDetectPromptInjectionMessage(s string) ProtectOption
WithDetectPromptInjectionMessage sets the text scanned by prompt injection detection.
func WithEmail ¶
func WithEmail(email string) ProtectOption
WithEmail sets the email address scanned by email validation.
func WithExtra ¶
func WithExtra(extra map[string]string) ProtectOption
WithExtra sets additional string fields sent to Arcjet with the request.
func WithFilterLocal ¶
func WithFilterLocal(fields map[string]string) ProtectOption
WithFilterLocal sets local-only values available to Filter expressions.
Values are evaluated by local WebAssembly and are not sent to Arcjet Cloud.
func WithIPSrc ¶
func WithIPSrc(ip string) ProtectOption
WithIPSrc overrides the request source IP sent to Arcjet.
func WithRequested ¶
func WithRequested(n int) ProtectOption
WithRequested sets the token or request cost consumed by this request.
func WithSensitiveInfoValue ¶
func WithSensitiveInfoValue(s string) ProtectOption
WithSensitiveInfoValue sets the text scanned by sensitive information detection. Pair with SensitiveInfo; the value is evaluated locally and never leaves the SDK.
type ProtectOptions ¶
type ProtectOptions struct {
// Requested is the token or request cost consumed by this request.
Requested int
// Characteristics are per-request rate-limit characteristic values.
Characteristics map[string]string
// DetectPromptInjectionMessage is text scanned by prompt injection detection.
DetectPromptInjectionMessage string
// SensitiveInfoValue is text scanned by sensitive information detection.
SensitiveInfoValue string
// Email is the email address scanned by ValidateEmail.
Email string
// IPSrc overrides the request source IP.
IPSrc string
// FilterLocal contains local-only fields for Filter expressions.
FilterLocal map[string]string
// Extra contains additional string fields sent to Arcjet.
Extra map[string]string
// Body overrides the request body sent to Arcjet.
Body []byte
// CorrelationId is an optional, caller-supplied opaque identifier used to
// correlate this request with other Protect and Guard calls in the same
// workflow or agent run. It does not affect the decision and is excluded
// from the decision cache key.
CorrelationId string
}
ProtectOptions contains per-request inputs used by specific rules.
Most callers set these with ProtectOption helpers such as WithRequested and WithEmail.
type ProtectSignupOptions ¶
type ProtectSignupOptions struct {
// RateLimit configures the sliding-window rate limit applied to the signup
// form, typically keyed on the source IP.
RateLimit SlidingWindowOptions
// Bots configures bot detection for the signup form.
Bots BotOptions
// Email configures validation of the submitted email address.
Email EmailOptions
}
ProtectSignupOptions configures the ProtectSignup composite rule.
type RateLimitReason ¶
type RateLimitReason struct {
Max int `json:"max,omitempty"`
Remaining int `json:"remaining,omitempty"`
ResetInSeconds int `json:"resetInSeconds,omitempty"`
WindowInSeconds int `json:"windowInSeconds,omitempty"`
}
RateLimitReason contains details for a rate limit decision.
type Reason ¶
type Reason struct {
Type ReasonType
Message string
RateLimit *RateLimitReason
Bot *BotReason
Shield *ShieldReason
Email *EmailReason
SensitiveInfo *SensitiveInfoReason
PromptInjection *PromptInjectionReason
Filter *FilterReason
}
Reason contains typed details about why Arcjet reached a decision.
func (Reason) IsPromptInjection ¶
IsPromptInjection reports whether prompt injection detection drove this reason.
func (Reason) IsRateLimit ¶
IsRateLimit reports whether a rate limit rule drove this reason.
func (Reason) IsSensitiveInfo ¶
IsSensitiveInfo reports whether sensitive info detection drove this reason.
type ReasonType ¶
type ReasonType string
ReasonType identifies the rule family or condition behind a decision.
const ( // ReasonUnknown is used when a response does not include a known reason. ReasonUnknown ReasonType = "" // ReasonRateLimit means a rate limit rule determined the result. ReasonRateLimit ReasonType = "RATE_LIMIT" // ReasonBot means a bot detection rule determined the result. ReasonBot ReasonType = "BOT" // ReasonShield means Shield determined the result. ReasonShield ReasonType = "SHIELD" // ReasonEmail means an email validation rule determined the result. ReasonEmail ReasonType = "EMAIL" // ReasonSensitiveInfo means a sensitive information rule determined the result. ReasonSensitiveInfo ReasonType = "SENSITIVE_INFO" // ReasonPromptInjection means a prompt injection rule determined the result. ReasonPromptInjection ReasonType = "PROMPT_INJECTION" // ReasonModerateContent means a content moderation rule determined the result. ReasonModerateContent ReasonType = "MODERATE_CONTENT" // ReasonFilter means a request filter rule determined the result. ReasonFilter ReasonType = "FILTER" // ReasonError means the decision contains an error. ReasonError ReasonType = "ERROR" // ReasonNotRun means a guard rule did not run. ReasonNotRun ReasonType = "NOT_RUN" // ReasonCustom means a custom guard rule determined the result. ReasonCustom ReasonType = "CUSTOM" )
func (ReasonType) LogValue ¶
func (r ReasonType) LogValue() slog.Value
LogValue implements slog.LogValuer so ReasonType logs as its string form.
type Rule ¶
type Rule interface {
// contains filtered or unexported methods
}
Rule is a request protection rule evaluated by Client.Protect.
func DetectPromptInjection ¶
func DetectPromptInjection(opts PromptInjectionOptions) Rule
DetectPromptInjection creates a prompt injection detection rule.
func Filter ¶
func Filter(opts FilterOptions) Rule
Filter creates a request filter rule.
Local filter values passed with WithFilterLocal are available to expressions as local["name"].
func FixedWindow ¶
func FixedWindow(opts FixedWindowOptions) Rule
FixedWindow creates a fixed window rate limit rule.
func ProtectSignup ¶
func ProtectSignup(opts ProtectSignupOptions) []Rule
ProtectSignup bundles the rules commonly used to protect a signup form: a sliding-window rate limit, bot detection, and email validation. It is sugar over SlidingWindow, DetectBot, and ValidateEmail; the returned rules can be passed directly to Client.Protect alongside any others. Mirrors protectSignup in arcjet-js.
func SensitiveInfo ¶
func SensitiveInfo(opts SensitiveInfoOptions) Rule
SensitiveInfo creates a sensitive information detection rule. The text to scan comes from WithSensitiveInfoValue on each Protect call.
Detection runs locally via the bundled WebAssembly analyzer (the same `arcjet_analyze_js_req` component used by the JavaScript and Python SDKs) — the text never leaves the SDK.
func Shield ¶
func Shield(opts ShieldOptions) Rule
Shield creates a rule that protects against common web attacks.
func SlidingWindow ¶
func SlidingWindow(opts SlidingWindowOptions) Rule
SlidingWindow creates a sliding window rate limit rule.
func TokenBucket ¶
func TokenBucket(opts TokenBucketOptions) Rule
TokenBucket creates a token bucket rate limit rule.
Token buckets are useful for AI token budgets because callers can pass the consumed token count with WithRequested.
func ValidateEmail ¶
func ValidateEmail(opts EmailOptions) Rule
ValidateEmail creates an email validation rule.
type RuleResult ¶
type RuleResult struct {
RuleID string
State RuleState
Conclusion Conclusion
Reason Reason
// TTL is the number of seconds the per-rule result can be cached.
TTL int
Fingerprint string
}
RuleResult is the per-rule result included in a request decision.
type RuleState ¶
type RuleState string
RuleState is the lifecycle state of a per-rule evaluation in a Decision.
const ( // RuleStateUnspecified means no rule state was provided. RuleStateUnspecified RuleState = "" // RuleStateRun means the rule was evaluated this request. RuleStateRun RuleState = "RULE_STATE_RUN" // RuleStateDryRun means the rule was evaluated but not enforced. RuleStateDryRun RuleState = "RULE_STATE_DRY_RUN" // RuleStateNotRun means the rule did not run. RuleStateNotRun RuleState = "RULE_STATE_NOT_RUN" // RuleStateCached means the rule result was served from cache. RuleStateCached RuleState = "RULE_STATE_CACHED" )
type SensitiveInfoDetect ¶
type SensitiveInfoDetect func(ctx context.Context, tokens []string) []EntityType
SensitiveInfoDetect classifies tokens that the bundled wasm analyzer didn't recognise. The returned slice must have one entry per input token; an empty EntityType leaves the token unclassified, otherwise the value is recorded — either a built-in constant (SensitiveInfoEmail, SensitiveInfoPhoneNumber, …) or any custom label.
type SensitiveInfoOptions ¶
type SensitiveInfoOptions struct {
// Mode controls whether the rule enforces denials or only reports them.
Mode Mode
// Allow lists entity types allowed in scanned text.
Allow []EntityType
// Deny lists entity types denied in scanned text.
Deny []EntityType
}
SensitiveInfoOptions configures request sensitive information detection.
Allow and Deny are mutually exclusive. Pass text for each request with WithSensitiveInfoValue.
type SensitiveInfoReason ¶
type SensitiveInfoReason struct {
Allowed []IdentifiedEntity `json:"allowed,omitempty"`
Denied []IdentifiedEntity `json:"denied,omitempty"`
}
SensitiveInfoReason contains sensitive information detection results.
type ShieldOptions ¶
type ShieldOptions struct {
// Mode controls whether the rule enforces denials or only reports them.
Mode Mode
// Characteristics are optional keys associated with Shield evaluation.
Characteristics []string
}
ShieldOptions configures Arcjet Shield.
type ShieldReason ¶
type ShieldReason struct {
Triggered bool `json:"shieldTriggered,omitempty"`
Suspicious bool `json:"suspicious,omitempty"`
}
ShieldReason contains details for a Shield decision.
type SlidingWindowOptions ¶
type SlidingWindowOptions struct {
// Mode controls whether the rule enforces denials or only reports them.
Mode Mode
// Characteristics are rate-limit keys such as "userId".
Characteristics []string
// Interval is the sliding window interval.
Interval time.Duration
// MaxRequests is the maximum number of requests per interval.
MaxRequests int
}
SlidingWindowOptions configures a sliding window rate limit rule.
type TokenBucketOptions ¶
type TokenBucketOptions struct {
// Mode controls whether the rule enforces denials or only reports them.
Mode Mode
// Characteristics are rate-limit keys such as "userId".
Characteristics []string
// RefillRate is the number of tokens added per interval.
RefillRate int
// Interval is the token refill interval.
Interval time.Duration
// Capacity is the maximum bucket size.
Capacity int
}
TokenBucketOptions configures a token bucket rate limit rule.
type Warning ¶
type Warning struct {
Code string `json:"code,omitempty"`
Message string `json:"message,omitempty"`
}
Warning is a diagnostic on a Guard decision or rule result. A warning means the decision (or rule) was processed correctly — the result is trustworthy — but something should be fixed (e.g. an invalid metadata key that was stripped). Contrast with a per-rule error (GuardRuleResult.Error), which means a rule or the decision could not be processed and the security signal is degraded.
type WasmModule ¶
type WasmModule struct {
// contains filtered or unexported fields
}
WasmModule is a small helper for executing raw WebAssembly modules with wazero.
Most applications do not need this type; request rules use the SDK's bundled analyzers directly.
func NewWasmModule ¶
func NewWasmModule(ctx context.Context, wasm []byte) (*WasmModule, error)
NewWasmModule instantiates a raw WebAssembly module.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
Package redact detects and redacts sensitive information — emails, phone numbers, IP addresses, credit card numbers, and custom entities — in arbitrary text.
|
Package redact detects and redacts sensitive information — emails, phone numbers, IP addresses, credit card numbers, and custom entities — in arbitrary text. |
|
sensitiveinfo
|
|
|
rampart
module
|