swt

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2025 License: MIT Imports: 15 Imported by: 0

README

SecureWebhookToken (SWT)

GitHub Tag Go Report Card GitHub go.mod Go version Coverage Go Reference

SecureWebhookToken is an Internet-Draft for sending secure Webhooks, based on the JWT standard. See Documentation for more details.

Install

go get github.com/SecureWebhookToken/swt

Examples

Client / Server

package main

import (
	"fmt"
	"log/slog"
	"net/http"

	"github.com/SecureWebhookToken/swt"
)

const (
	issuer = "https://example.com"
	url    = "http://localhost:8080/webhook"
)

var secretKey = []byte("test")

func main() {
	go startServer()

	req, err := swt.BuildRequest(url, "issuer", "send.stars", []byte(`{"username": "me", "stars": "567"}`), secretKey)
	if err != nil {
		slog.Error(fmt.Errorf("error building request: %w", err).Error())
		return
	}

	httpClient := &http.Client{}
	res, err := httpClient.Do(req)
	if err != nil {
		slog.Error("Error executing request", "error", err)
		return
	}
	slog.Info("Successfully executed request", "status", res.StatusCode)
}

func startServer() {
	http.Handle("/webhook", swt.NewHandlerFunc(secretKey, func(token *swt.SecureWebhookToken) error {
		slog.Info("Successfully received token: " + token.String())
		return nil
	}, nil))

	slog.Error("Server error", "error", http.ListenAndServe(":8080", nil))
}

Documentation

Overview

Package swt implements the [Secure Webhook Token (SWT)](https://datatracker.ietf.org/doc/draft-knauer-secure-webhook-token/) an Internet-Draft for standardized webhook request.

Index

Constants

View Source
const (
	HeadMaxDataSize = 6 << 10
	// Supported hash algorithms
	SHA256   = "SHA-256"
	SHA384   = "SHA-384"
	SHA512   = "SHA-512"
	SHA3_256 = "SHA3-256"
	SHA3_384 = "SHA3-384"
	SHA3_512 = "SHA3-512"
)

Variables

View Source
var (
	ErrInvalidToken             = errors.New("invalid token - please use New or NewWithClaims to properly initialize token")
	ErrMissingClaims            = errors.New("missing claims")
	ErrInvalidOption            = errors.New("invalid option")
	ErrInvalidJSON              = errors.New("invalid json data")
	ErrInvalidData              = errors.New("invalid data")
	ErrInvalidTokenHandler      = errors.New("invalid token handler function")
	ErrUnsupportedHashAlgorithm = errors.New("unsupported hash algorithm")
)

Functions

func HashSum

func HashSum(hashAlg string, body []byte) (string, error)

HashSum computes the hash sum for a given hashAlg and the body to be sent via http.MethodPost request.

func NewHandlerFunc

func NewHandlerFunc(secret []byte, handleFn func(*SecureWebhookToken) error, opts *HandlerOptions) http.HandlerFunc

NewHandlerFunc Creates a new http.HandlerFunc which will process an incoming webhook request and pass the token, if valid, to the given handleFn.

Types

type Claims

type Claims interface {
	GetID() (string, error)
	GetWebhook() (Webhook, error)

	jwt.Claims
	// contains filtered or unexported methods
}

type HandlerOptions

type HandlerOptions struct {
	MaxBodySize int64
}

type Option

type Option func(swt *SecureWebhookToken)

func WithAudience

func WithAudience(ids ...string) Option

WithAudience overrides the aud claim. The Audience claim is optional and is nil by default. It can consist of zero or more recipients containing a StringOrURI value.

func WithExpiresAt

func WithExpiresAt(t time.Time) Option

WithExpiresAt overrides the default exp claim.

func WithID

func WithID(id string) Option

WithID overrides the jti claim with a given id. Should be a UUID or similar unique id.

func WithNotBefore

func WithNotBefore(t time.Time) Option

WithNotBefore overrides the default nbf claim.

func WithSigningMethod

func WithSigningMethod(method *jwt.SigningMethodHMAC) Option

WithSigningMethod allows overriding the default signing method HS256. For the convenience of SecureHookTokens usage, only symmetrical signatures are supported. (HS256, HS384 and HS512)

func WithSubject

func WithSubject(s string) Option

WithSubject overrides the default sub claim.

type Request added in v0.2.0

type Request struct {
	URL     string // Target URL for the webhook request
	Issuer  string // JWT issuer claim (iss) - typically the service sending the webhook
	Event   string // Event name following EVENT_NAME.ACTIVITY format (e.g., "user.created")
	HashAlg string // Hash algorithm for POST requests (SHA-256, SHA3-256, etc.). Defaults to SHA3-256 if empty
	Data    []byte // Payload data to be sent with the request
}

Request represents a webhook request configuration for creating SecureWebhookTokens. It contains all the necessary information to build HTTP requests with embedded tokens.

func (*Request) Build added in v0.2.0

func (r *Request) Build(key any, opts ...Option) (*http.Request, error)

Build can be used to create an http.Request for creating and sending a SecureWebhookToken via HEAD or POST request, depending on the size and value of the provided data.

func (*Request) BuildHead added in v0.2.0

func (r *Request) BuildHead(key any, opts ...Option) (*http.Request, error)

BuildHead creates an http.Request with http.MethodHead independently of data length. Should only be used if you've good reasons not to stick to the suggested HeadMaxDataSize as depicted in the SecureWebhookToken draft.

func (*Request) BuildPost added in v0.2.0

func (r *Request) BuildPost(key any, opts ...Option) (*http.Request, error)

BuildPost creates an http.Request with http.MethodPost independently of data length. Can be used e.g., when creating and sending a SecureWebhookToken with data of a type which differs from JSON or a data size less than the HeadMaxDataSize.

type SecureWebhookToken

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

SecureWebhookToken is a structure for secure webhook tokens. Currently, it implements symmetrical signatures based on HMAC-SHA for example purposes only. If the Internet-Draft is accepted, other methods will be implemented in the future.

func New

func New(issuer, event string, data any, opts ...Option) *SecureWebhookToken

New creates a SecureWebhookToken with the given issuer, event name, and data. Can be further customized with additional Option parameters. See Option for available functional parameters.

func NewWithClaims

func NewWithClaims(c Claims, opts ...Option) *SecureWebhookToken

NewWithClaims creates a new SecureWebhookToken with the given Claims object. Must be a pointer to an instance of WebhookClaims or a custom Claims instance, which embeds the WebhookClaims.

func Parse

func Parse(tokenStr string, key any) (*SecureWebhookToken, error)

Parse parses a given token string, verifies it and returns a SecureWebhookToken if successful.

func ParseWithClaims

func ParseWithClaims(tokenStr string, claims Claims, key any) (*SecureWebhookToken, error)

ParseWithClaims parses a given token string and given claims, verifies it and returns a SecureWebhookToken if successful.

func (*SecureWebhookToken) Algorithm

func (swt *SecureWebhookToken) Algorithm() string

Algorithm returns the used SigningMethod algorithm.

func (*SecureWebhookToken) Claims

func (swt *SecureWebhookToken) Claims() Claims

Claims return all token Claims. If no custom WebhookClaims have been set with NewWithClaims(), then the underlying type will be *WebhookClaims.

func (*SecureWebhookToken) ID

func (swt *SecureWebhookToken) ID() string

ID convenient method for accessing the ID of the SecureWebhookToken.

func (*SecureWebhookToken) Issuer

func (swt *SecureWebhookToken) Issuer() string

Issuer convenient method for accessing the Issuer claim of the SecureWebhookToken.

func (*SecureWebhookToken) SignedString

func (swt *SecureWebhookToken) SignedString(key any) (string, error)

SignedString returns the encoded and signed SecureWebhookToken as a JWT string.

func (*SecureWebhookToken) String

func (swt *SecureWebhookToken) String() string

String implements the Stringer interface for returning the SecureWebhookToken as a JSON string.

func (*SecureWebhookToken) Valid

func (swt *SecureWebhookToken) Valid() bool

Valid returns true only if the SecureWebhookToken has been created via Parse method and successfully been validated.

func (*SecureWebhookToken) Validate

func (swt *SecureWebhookToken) Validate() error

Validate validates the Claims of the SecureWebhookToken.

func (*SecureWebhookToken) Webhook

func (swt *SecureWebhookToken) Webhook() Webhook

Webhook convenient method for accessing the Webhook claim of the SecureWebhookToken.

type Webhook

type Webhook struct {
	Event string `json:"event"` // Event name. Should have the form EVENT_NAME.ACTIVITY (e.g., user.created or pull_request.merged)
	Data  any    `json:"data,omitempty"`
}

type WebhookClaims

type WebhookClaims struct {
	Webhook Webhook `json:"webhook"`
	jwt.RegisteredClaims
}

func NewWebhookClaims

func NewWebhookClaims(issuer, event string, data any) WebhookClaims

NewWebhookClaims creates WebhookClaims with a given issuer, event name and data, and the default registered claims.

func (*WebhookClaims) GetID

func (wc *WebhookClaims) GetID() (string, error)

the `jti` (JWT ID) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.7

func (*WebhookClaims) MapClaims

func (wc *WebhookClaims) MapClaims() jwt.MapClaims

MapClaims will convert a WebhookClaims object into jwt.MapClaims Can easily be used with the golang-jwt package for creating JWTs directly if desired.

func (*WebhookClaims) Validate

func (wc *WebhookClaims) Validate() error

Validate implements the jwt.ClaimsValidator interface to perform further required validation on specific claims.

type WebhookData

type WebhookData struct {
	Hash    string `json:"hash"`              // Hash string produced by the used HashAlg or sha3-256 by default
	HashAlg string `json:"hashAlg,omitempty"` // Hash algorithm is used to verify data integrity
	Size    int64  `json:"size"`              // Size of the payload in bytes
}

Directories

Path Synopsis
examples
client command
custom_claims command

Jump to

Keyboard shortcuts

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