canonical

package
v0.3.3 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Overview

Package canonical owns DKIM2 canonical byte transformations and digest result containers for the draft-ietf-dkim-dkim2-spec-09 baseline.

This package is the library-internal source of truth for Section 6.1 body hash input, Section 6.2 header hash input, and Section 12.8 signature input. Later builders consume immutable rawmsg, instance, and signature parser views instead of reparsing raw RFC 5322 messages or DKIM2 tag lists.

Section 6.1 body input is MIME-agnostic and works on parser-owned body octets. Section 6.2 header input excludes the draft-defined header classes, including Delivered-To under Section 4, lowercases field names, applies header-hash whitespace rules, and sorts deterministically. Section 12.8 signature input signs only DKIM2 protocol fields and uses its own all-WSP deletion rule. These transformations are intentionally distinct so later code cannot apply header hash rules to signature input or signature rules to header hashes.

The package also owns fixed-length SHA-256 and SHA-512 Message-Instance digest containers while keeping signature-input SHA-256 separate. Hash calculation helpers build on immutable canonical byte and digest accessors, restrictive limits, domain-named options, and structured secret-safe diagnostics. It also provides the immutable Section 4 and Section 6.2 signed-header relevance classifier consumed through recipe's narrow interface, keeping the exclusion rules in one canonical owner without introducing a package cycle.

Debug metadata is bounded by design. It may carry canonicalization kind, draft version, safe algorithm names, counts, lengths, and allowlisted excluded-header counters. It must not carry raw message bodies, raw header values, full DKIM2 fields, decoded envelope paths, recipients, nonces, signatures, private keys, tokens, or protected configuration values.

Recipe parsing, application, and generation remain recipe-owned. Cryptographic verification, DNS lookup, policy, datasource behavior, daemon behavior, Milter integration, OpenAPI mapping, concrete logging, metrics, tracing, and public facade APIs remain outside this package.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsErrorCode

func IsErrorCode(err error, code ErrorCode) bool

IsErrorCode reports whether err contains a canonicalization Error with code.

Types

type BodyTerminalAction

type BodyTerminalAction string

BodyTerminalAction records how Section 6.1 terminal CRLF handling behaved.

const (
	// BodyTerminalActionUnspecified records no body terminal action.
	BodyTerminalActionUnspecified BodyTerminalAction = ""
	// BodyTerminalActionPreserved records an existing single terminal CRLF.
	BodyTerminalActionPreserved BodyTerminalAction = "preserved"
	// BodyTerminalActionAppended records that one terminal CRLF was appended.
	BodyTerminalActionAppended BodyTerminalAction = "appended"
	// BodyTerminalActionCollapsed records that trailing empty lines collapsed to one CRLF.
	BodyTerminalActionCollapsed BodyTerminalAction = "collapsed"
)

type ByteInput

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

ByteInput stores immutable canonical byte output and bounded metadata.

func NewCanonicalBytes

func NewCanonicalBytes(kind Kind, input []byte, metadata Metadata) (ByteInput, error)

NewCanonicalBytes constructs immutable canonical byte output.

func (ByteInput) Bytes

func (c ByteInput) Bytes() []byte

Bytes returns a copy of the canonical byte output.

func (ByteInput) Kind

func (c ByteInput) Kind() Kind

Kind returns the canonical byte stream kind.

func (ByteInput) Len

func (c ByteInput) Len() int

Len returns the canonical byte length.

func (ByteInput) Metadata

func (c ByteInput) Metadata() Metadata

Metadata returns bounded debug metadata by value.

type Canonicalizer

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

Canonicalizer carries validated options for canonical byte builders.

func NewCanonicalizer

func NewCanonicalizer(options ...Option) (Canonicalizer, error)

NewCanonicalizer constructs a canonicalizer with validated options.

func (Canonicalizer) BodyHash

func (c Canonicalizer) BodyHash(body rawmsg.Body) (Result, error)

BodyHash calculates the selected Message-Instance digest over Section 6.1 input.

func (Canonicalizer) BodyHashFromMessage

func (c Canonicalizer) BodyHashFromMessage(message rawmsg.Message) (Result, error)

BodyHashFromMessage calculates the selected body digest from a raw message.

func (Canonicalizer) BodyHashInput

func (c Canonicalizer) BodyHashInput(body rawmsg.Body) (ByteInput, error)

BodyHashInput builds DKIM2 Section 6.1 canonical body hash input.

func (Canonicalizer) BodyHashInputFromMessage

func (c Canonicalizer) BodyHashInputFromMessage(message rawmsg.Message) (ByteInput, error)

BodyHashInputFromMessage builds Section 6.1 body input from a raw message.

func (Canonicalizer) Digest

func (c Canonicalizer) Digest(input ByteInput) (Digest, error)

Digest calculates the selected supported Message-Instance digest over canonical bytes.

func (Canonicalizer) HeaderHash

func (c Canonicalizer) HeaderHash(headers rawmsg.HeaderBlock) (Result, error)

HeaderHash calculates the selected Message-Instance digest over Section 6.2 input.

func (Canonicalizer) HeaderHashFromMessage

func (c Canonicalizer) HeaderHashFromMessage(message rawmsg.Message) (Result, error)

HeaderHashFromMessage calculates the selected header digest from a raw message.

func (Canonicalizer) HeaderHashInput

func (c Canonicalizer) HeaderHashInput(headers rawmsg.HeaderBlock) (ByteInput, error)

HeaderHashInput builds DKIM2 Section 6.2 canonical header hash input.

func (Canonicalizer) HeaderHashInputFromMessage

func (c Canonicalizer) HeaderHashInputFromMessage(message rawmsg.Message) (ByteInput, error)

HeaderHashInputFromMessage builds Section 6.2 header input from a raw message.

func (Canonicalizer) Options

func (c Canonicalizer) Options() Options

Options returns a copy of the canonicalizer configuration.

func (Canonicalizer) SHA256Digest

func (c Canonicalizer) SHA256Digest(input ByteInput) (Digest, error)

SHA256Digest calculates the fixed Section 12.8 signature-input SHA-256 digest.

func (Canonicalizer) SignatureInput

func (c Canonicalizer) SignatureInput(selection SignatureInputSelection) (ByteInput, error)

SignatureInput builds DKIM2 Section 12.8 canonical signature input.

func (Canonicalizer) SignatureInputFromMessage

func (c Canonicalizer) SignatureInputFromMessage(message rawmsg.Message, targetSequence uint64) (ByteInput, error)

SignatureInputFromMessage builds Section 12.8 input from parser-owned headers.

func (Canonicalizer) SigningInput

func (c Canonicalizer) SigningInput(selection SigningInputSelection) (ByteInput, error)

SigningInput builds Section 12.8 input without inserting an incomplete field into a message.

type Digest

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

Digest stores immutable digest bytes and padded base64 text.

func NewDigest

func NewDigest(algorithm HashAlgorithm, digest []byte) (Digest, error)

NewDigest constructs an immutable supported Message-Instance digest container.

func NewSHA256Digest

func NewSHA256Digest(digest []byte) (Digest, error)

NewSHA256Digest constructs an immutable SHA-256 digest container.

func NewSHA512Digest

func NewSHA512Digest(digest []byte) (Digest, error)

NewSHA512Digest constructs an immutable SHA-512 digest container.

func (Digest) Algorithm

func (d Digest) Algorithm() HashAlgorithm

Algorithm returns the digest algorithm name.

func (Digest) Base64

func (d Digest) Base64() string

Base64 returns padded RFC 4648 digest text.

func (Digest) Bytes

func (d Digest) Bytes() []byte

Bytes returns a copy of the digest bytes.

func (Digest) Len

func (d Digest) Len() int

Len returns the digest byte length.

type Error

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

Error is a typed, secret-safe canonicalization error.

func (*Error) Algorithm

func (e *Error) Algorithm() HashAlgorithm

Algorithm returns the safe algorithm name associated with the error.

func (*Error) Class

func (e *Error) Class() ErrorClass

Class returns the stable operational error class.

func (*Error) Code

func (e *Error) Code() ErrorCode

Code returns the stable canonicalization error code.

func (*Error) Count

func (e *Error) Count() int

Count returns the observed resource count or size associated with the error.

func (*Error) Error

func (e *Error) Error() string

Error returns a bounded diagnostic without canonical bytes or raw fields.

func (*Error) Is

func (e *Error) Is(target error) bool

Is matches canonicalization errors by code for errors.Is.

func (*Error) Limit

func (e *Error) Limit() int

Limit returns the configured resource limit associated with the error.

func (*Error) LimitName

func (e *Error) LimitName() string

LimitName returns the resource limit name for structured callers only.

func (*Error) Location

func (e *Error) Location() ErrorLocation

Location returns bounded canonicalization location metadata.

func (*Error) TargetName

func (e *Error) TargetName() string

TargetName returns the allowlisted target class associated with the error.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the structured lower-level cause when one exists.

type ErrorClass

type ErrorClass string

ErrorClass groups canonicalization failures for stable callers.

const (
	// ErrorClassAlgorithm classifies unsupported algorithm selection.
	ErrorClassAlgorithm ErrorClass = "algorithm"
	// ErrorClassInvariant classifies invalid options or internal invariants.
	ErrorClassInvariant ErrorClass = "invariant"
	// ErrorClassLimit classifies configured resource-limit failures.
	ErrorClassLimit ErrorClass = "limit"
	// ErrorClassMalformed classifies malformed parser-owned state.
	ErrorClassMalformed ErrorClass = "malformed"
	// ErrorClassAmbiguous classifies ambiguous target or input selection.
	ErrorClassAmbiguous ErrorClass = "ambiguous"
	// ErrorClassMissing classifies omitted required targets.
	ErrorClassMissing ErrorClass = "missing"
	// ErrorClassDuplicate classifies duplicate target identifiers.
	ErrorClassDuplicate ErrorClass = "duplicate"
	// ErrorClassInternal classifies package misuse that should not depend on message input.
	ErrorClassInternal ErrorClass = "internal"
)

type ErrorCode

type ErrorCode string

ErrorCode identifies a bounded canonicalization failure.

const (
	// ErrorCodeUnsupportedAlgorithm reports a hash or signature algorithm outside the allowlist.
	ErrorCodeUnsupportedAlgorithm ErrorCode = "unsupported_algorithm"
	// ErrorCodeInvalidOptions reports unsafe canonicalization options.
	ErrorCodeInvalidOptions ErrorCode = "invalid_options"
	// ErrorCodeLimitExceeded reports a canonicalization resource-limit violation.
	ErrorCodeLimitExceeded ErrorCode = "limit_exceeded"
	// ErrorCodeMalformedState reports invalid parser-owned state consumed by canonicalization.
	ErrorCodeMalformedState ErrorCode = "malformed_state"
	// ErrorCodeAmbiguousSelection reports ambiguous canonical input selection.
	ErrorCodeAmbiguousSelection ErrorCode = "ambiguous_selection"
	// ErrorCodeMissingTarget reports a missing target field or digest.
	ErrorCodeMissingTarget ErrorCode = "missing_target"
	// ErrorCodeDuplicateTarget reports repeated target identifiers.
	ErrorCodeDuplicateTarget ErrorCode = "duplicate_target"
	// ErrorCodeInternalMisuse reports invalid internal canonicalization API use.
	ErrorCodeInternalMisuse ErrorCode = "internal_misuse"
)

type ErrorDetails

type ErrorDetails struct {
	// Class records the stable operational class for the error.
	Class ErrorClass
	// Algorithm records a safe hash or signature algorithm name.
	Algorithm HashAlgorithm
	// LimitName records the resource limit identifier for structured callers.
	LimitName string
	// Limit records the configured limit when relevant.
	Limit int
	// Count records the observed count or size when relevant.
	Count int
	// TargetName records an allowlisted target class such as message_instance.
	TargetName string
}

ErrorDetails carries bounded metadata for Error.

type ErrorLocation

type ErrorLocation struct {
	// Kind records the canonicalization byte stream when known.
	Kind Kind
	// FieldIndex records a raw header occurrence index when relevant.
	FieldIndex int
	// TargetNumber records an m= or i= target number when relevant.
	TargetNumber uint64
}

ErrorLocation identifies bounded canonicalization context.

type ExcludedHeaderCounts

type ExcludedHeaderCounts struct {
	// Received counts excluded Received fields.
	Received int
	// ReturnPath counts excluded Return-Path fields.
	ReturnPath int
	// DeliveredTo counts excluded Delivered-To fields.
	DeliveredTo int
	// AuthenticationResults counts excluded Authentication-Results fields.
	AuthenticationResults int
	// XHeader counts excluded X-* fields.
	XHeader int
	// DKIMSignature counts excluded DKIM-Signature fields.
	DKIMSignature int
	// ExactUnsigned counts the six exact Draft-09 registered exclusions.
	ExactUnsigned int
	// ARC counts the three exact excluded ARC fields.
	ARC int
	// MessageInstance counts excluded Message-Instance fields.
	MessageInstance int
	// DKIM2Signature counts excluded DKIM2-Signature fields.
	DKIM2Signature int
}

ExcludedHeaderCounts stores allowlisted Section 6.2 exclusion counters.

func (ExcludedHeaderCounts) Total

func (c ExcludedHeaderCounts) Total() int

Total returns the total excluded-header count.

type HashAlgorithm

type HashAlgorithm string

HashAlgorithm identifies a safe canonicalization hash algorithm name.

const (
	// DraftBaseline identifies the active DKIM2 canonicalization draft.
	DraftBaseline = "draft-ietf-dkim-dkim2-spec-09"
	// HashAlgorithmSHA256 identifies the supported SHA-256 Message-Instance hash.
	HashAlgorithmSHA256 HashAlgorithm = "sha256"
	// HashAlgorithmSHA512 identifies the supported SHA-512 Message-Instance hash.
	HashAlgorithmSHA512 HashAlgorithm = "sha512"
)

func (HashAlgorithm) Known

func (a HashAlgorithm) Known() bool

Known reports whether the algorithm is a supported Message-Instance digest.

type HeaderRelevance

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

HeaderRelevance is the immutable Draft-09 signed-header relevance classifier.

func NewHeaderRelevance

func NewHeaderRelevance() HeaderRelevance

NewHeaderRelevance constructs the canonical-owned production classifier.

func (HeaderRelevance) IsRelevantHeader

func (r HeaderRelevance) IsRelevantHeader(nameLower string) (bool, error)

IsRelevantHeader classifies one validated canonical lowercase ASCII field name.

func (HeaderRelevance) Validate

func (r HeaderRelevance) Validate() error

Validate rejects a zero classifier before it crosses a consumer boundary.

type Kind

type Kind string

Kind identifies one DKIM2 canonicalization byte stream.

const (
	// KindBodyHashInput identifies Section 6.1 body hash input.
	KindBodyHashInput Kind = "body_hash_input"
	// KindHeaderHashInput identifies Section 6.2 header hash input.
	KindHeaderHashInput Kind = "header_hash_input"
	// KindSignatureInput identifies Section 12.8 signature input.
	KindSignatureInput Kind = "signature_input"
)

type Limits

type Limits struct {
	// MaxBodyInputBytes bounds Section 6.1 canonical body input bytes.
	MaxBodyInputBytes int
	// MaxHeaderInputBytes bounds Section 6.2 canonical header input bytes.
	MaxHeaderInputBytes int
	// MaxSignatureInputBytes bounds Section 12.8 canonical signature input bytes.
	MaxSignatureInputBytes int
	// MaxFieldBytes bounds one canonicalized header or protocol field.
	MaxFieldBytes int
	// MaxFieldCount bounds fields considered by header or signature builders.
	MaxFieldCount int
	// MaxExcludedHeaderCounters bounds allowlisted debug exclusion counters.
	MaxExcludedHeaderCounters int
}

Limits contains fail-closed canonicalization resource settings.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns restrictive canonicalization defaults.

func (Limits) Validate

func (l Limits) Validate() error

Validate rejects unsafe canonicalization limit values.

type Metadata

type Metadata struct {
	// Kind records the canonicalization byte stream.
	Kind Kind
	// Draft records the active DKIM2 draft baseline.
	Draft string
	// Algorithm records a safe hash algorithm name when relevant.
	Algorithm HashAlgorithm
	// InputBytes records the parser-owned input size.
	InputBytes int
	// OutputBytes records the canonical output size.
	OutputBytes int
	// IncludedFields records canonicalized field count when relevant.
	IncludedFields int
	// ExcludedFields records excluded field count when relevant.
	ExcludedFields int
	// ExcludedHeaderCounts records allowlisted Section 6.2 exclusion reasons.
	ExcludedHeaderCounts ExcludedHeaderCounts
	// BodyTrailingEmptyLines records collapsed terminal empty body lines.
	BodyTrailingEmptyLines int
	// BodyTerminalAction records terminal CRLF handling for body input.
	BodyTerminalAction BodyTerminalAction
}

Metadata carries bounded canonicalization debug facts.

type Option

type Option func(*Options)

Option mutates canonicalization options before validation.

func WithHashAlgorithm

func WithHashAlgorithm(algorithm HashAlgorithm) Option

WithHashAlgorithm replaces the canonicalization digest algorithm.

func WithLimits

func WithLimits(limits Limits) Option

WithLimits replaces canonicalization resource limits.

type Options

type Options struct {
	// Limits bounds canonical byte builders and debug metadata.
	Limits Limits
	// HashAlgorithm selects the supported canonicalization digest algorithm.
	HashAlgorithm HashAlgorithm
}

Options contains domain-named canonicalization settings.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns fail-closed canonicalization defaults.

func (Options) Validate

func (o Options) Validate() error

Validate rejects unsafe canonicalization options before builders run.

type Result

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

Result stores canonical bytes and an optional digest result.

func NewResult

func NewResult(canonical ByteInput, digest Digest) Result

NewResult constructs a canonicalization result with a digest.

func NewResultWithoutDigest

func NewResultWithoutDigest(canonical ByteInput) Result

NewResultWithoutDigest constructs a canonicalization result without a digest.

func (Result) CanonicalBytes

func (r Result) CanonicalBytes() ByteInput

CanonicalBytes returns the immutable canonical bytes container.

func (Result) Digest

func (r Result) Digest() (Digest, bool)

Digest returns the immutable digest container when present.

type SignatureInputSelection

type SignatureInputSelection struct {
	// Headers is the sole authority for protocol field parsing and rendering.
	Headers rawmsg.HeaderBlock
	// TargetSequence selects the DKIM2-Signature i= value rendered incomplete.
	TargetSequence uint64
}

SignatureInputSelection identifies the immutable header source and target for Section 12.8 input.

func (SignatureInputSelection) Format

func (s SignatureInputSelection) Format(state fmt.State, _ rune)

Format routes every selection formatting form through the redacted summary.

func (SignatureInputSelection) GoString

func (s SignatureInputSelection) GoString() string

GoString returns the constant protected-input Go representation.

func (SignatureInputSelection) String

func (s SignatureInputSelection) String() string

String returns a constant protected-input summary.

type SigningInputSelection

type SigningInputSelection struct {
	// Headers is the sole authority for inherited complete protocol fields.
	Headers rawmsg.HeaderBlock
	// GeneratedInstance is the optional next Message-Instance model.
	GeneratedInstance instance.MessageInstance
	// GeneratedInstanceField is the exact planner-owned rendering of GeneratedInstance.
	GeneratedInstanceField []byte
	// HasGeneratedInstance distinguishes an absent model from an invalid supplied model.
	HasGeneratedInstance bool
	// Target is the structured new DKIM2-Signature with every s= value empty.
	Target signature.UnsignedTarget
}

SigningInputSelection identifies structured existing and newly generated Section 12.8 input.

func (SigningInputSelection) Format

func (s SigningInputSelection) Format(state fmt.State, _ rune)

Format routes every signing selection formatting form through the redacted summary.

func (SigningInputSelection) GoString

func (s SigningInputSelection) GoString() string

GoString returns the constant protected signing-input Go representation.

func (SigningInputSelection) String

func (s SigningInputSelection) String() string

String returns a constant protected signing-input summary.

Jump to

Keyboard shortcuts

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