instance

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: 9 Imported by: 0

Documentation

Overview

Package instance parses Message-Instance header fields for the DKIM2 draft baseline draft-ietf-dkim-dkim2-spec-09.

The parser consumes immutable raw message header fields, accepts only Message-Instance fields, and validates the field-local `m=`, `h=`, and optional `r=` tags. Every header tag must have its draft-required semicolon terminator. Shared DKIM2 tag-list scanning, duplicate tag detection, extension tag validation, and base64string parsing remain owned by internal/tagvalue so parser behavior stays DRY across protocol packages.

Collection helpers extract Message-Instance fields from a full raw message in RFC 5322 occurrence order and validate that m= numbers are contiguous from origin value 1. This package owns strict recipe base64 decoding and immutable decoded-byte storage but intentionally does not parse recipe JSON or apply a reconstruction plan; those semantics belong to internal/recipe. Hash selection exposes supported SHA-256 and SHA-512 tuples in wire order. Syntactically valid unknown extension tuples remain preserved but unselected, and duplicate names are rejected case-insensitively across both groups. Canonical hash calculation and authenticated comparison remain outside this package.

Diagnostics are structured and bounded. Errors may expose stable codes, small allowlisted tag names, indexes, and resource-limit metadata, but must not include raw header values, hash bytes, recipe bytes, or other message-derived secret material.

Index

Constants

View Source
const (
	// HeaderName is the lowercase rawmsg name for Message-Instance fields.
	HeaderName = "message-instance"
	// HashAlgorithmSHA256 is the supported SHA-256 Message-Instance hash name.
	HashAlgorithmSHA256 = "sha256"
	// HashAlgorithmSHA512 is the supported SHA-512 Message-Instance hash name.
	HashAlgorithmSHA512 = "sha512"
)

Variables

This section is empty.

Functions

func IsErrorCode

func IsErrorCode(err error, code ErrorCode) bool

IsErrorCode reports whether err contains an instance Error with code.

func PreflightSigningField

func PreflightSigningField(number uint64, recipeBytes int, recipePresent bool, limits RenderLimits) (int, error)

PreflightSigningField returns the exact rendered size without allocating field bytes.

func ValidateSequence

func ValidateSequence(instances []MessageInstance) error

ValidateSequence validates contiguous Message-Instance m= numbers from origin.

Types

type Collection

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

Collection owns one immutable contiguous Message-Instance sequence.

func NewCollection

func NewCollection(items []MessageInstance) (Collection, error)

NewCollection validates and clones one nonempty contiguous sequence.

func (Collection) ByNumber

func (c Collection) ByNumber(number uint64) (MessageInstance, bool)

ByNumber returns one detached instance by m= number.

func (Collection) HighestNumber

func (c Collection) HighestNumber() uint64

HighestNumber returns the greatest retained m= number.

func (Collection) Len

func (c Collection) Len() int

Len returns the retained instance count.

func (Collection) Valid

func (c Collection) Valid() bool

Valid reports whether the collection is initialized and contiguous.

type Error

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

Error is a typed, secret-safe Message-Instance parser 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 parser 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 raw hashes or recipe bytes.

func (*Error) ExpectedNumber

func (e *Error) ExpectedNumber() uint64

ExpectedNumber returns the required sequence number for validation errors.

func (*Error) Format

func (e *Error) Format(state fmt.State, _ rune)

Format routes every fmt form through the secret-safe diagnostic.

func (*Error) GoString

func (e *Error) GoString() string

GoString returns the same secret-safe diagnostic for Go-syntax formatting.

func (*Error) Is

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

Is matches parser 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 parser location metadata.

func (*Error) ObservedNumber

func (e *Error) ObservedNumber() uint64

ObservedNumber returns the observed sequence number for validation errors.

func (*Error) TagName

func (e *Error) TagName() string

TagName returns the allowlisted tag name 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 Message-Instance parser failures for stable callers.

const (
	// ErrorClassMalformed classifies malformed Message-Instance syntax.
	ErrorClassMalformed ErrorClass = "malformed"
	// ErrorClassMissing classifies omitted required tags.
	ErrorClassMissing ErrorClass = "missing"
	// ErrorClassDuplicate classifies duplicate semantic names.
	ErrorClassDuplicate ErrorClass = "duplicate"
	// ErrorClassLimit classifies configured resource-limit failures.
	ErrorClassLimit ErrorClass = "limit"
	// ErrorClassInvariant classifies invalid parser configuration.
	ErrorClassInvariant ErrorClass = "invariant"
)

func (ErrorClass) Known

func (c ErrorClass) Known() bool

Known reports whether class belongs to the closed Message-Instance vocabulary.

type ErrorCode

type ErrorCode string

ErrorCode identifies a bounded Message-Instance parser failure.

const (
	// ErrorCodeWrongHeaderField reports a non Message-Instance header field.
	ErrorCodeWrongHeaderField ErrorCode = "wrong_header_field"
	// ErrorCodeMissingRequiredTag reports an omitted required Message-Instance tag.
	ErrorCodeMissingRequiredTag ErrorCode = "missing_required_tag"
	// ErrorCodeInvalidNumber reports malformed, zero, or overflowing m= syntax.
	ErrorCodeInvalidNumber ErrorCode = "invalid_number"
	// ErrorCodeMalformedHashSet reports an h= entry without exactly three parts.
	ErrorCodeMalformedHashSet ErrorCode = "malformed_hash_set"
	// ErrorCodeDuplicateHashName reports a duplicate algorithm name inside h=.
	ErrorCodeDuplicateHashName ErrorCode = "duplicate_hash_name"
	// ErrorCodeInvalidHashBase64 reports malformed Base64 in a supported or
	// extension hash tuple.
	ErrorCodeInvalidHashBase64 ErrorCode = "invalid_hash_base64"
	// ErrorCodeInvalidHashLength reports a supported SHA-256 or SHA-512 hash
	// with the wrong decoded size.
	ErrorCodeInvalidHashLength ErrorCode = "invalid_hash_length"
	// ErrorCodeInvalidRecipeBase64 reports malformed r= base64string syntax.
	ErrorCodeInvalidRecipeBase64 ErrorCode = "invalid_recipe_base64"
	// ErrorCodeLimitExceeded reports a Message-Instance resource-limit violation.
	ErrorCodeLimitExceeded ErrorCode = "limit_exceeded"
	// ErrorCodeInvalidOptions reports unsafe Message-Instance parser options.
	ErrorCodeInvalidOptions ErrorCode = "invalid_options"
	// ErrorCodeMissingOrigin reports a collection without m=1.
	ErrorCodeMissingOrigin ErrorCode = "missing_origin"
	// ErrorCodeDuplicateNumber reports repeated Message-Instance m= numbers.
	ErrorCodeDuplicateNumber ErrorCode = "duplicate_number"
	// ErrorCodeSequenceGap reports a missing Message-Instance m= number.
	ErrorCodeSequenceGap ErrorCode = "sequence_gap"
	// ErrorCodeInvalidConstruction reports an invalid generated instance model.
	ErrorCodeInvalidConstruction ErrorCode = "invalid_construction"
	// ErrorCodeRenderInvariant reports internal deterministic-render disagreement.
	ErrorCodeRenderInvariant ErrorCode = "render_invariant"
)

func (ErrorCode) Known

func (c ErrorCode) Known() bool

Known reports whether code belongs to the closed Message-Instance vocabulary.

type ErrorDetails

type ErrorDetails struct {
	// Class records the stable operational class for the error.
	Class ErrorClass
	// TagName records an allowlisted Message-Instance tag when relevant.
	TagName TagName
	// LimitName records the resource limit identifier for structured callers.
	LimitName LimitName
	// Limit records the configured limit when relevant.
	Limit int
	// Count records the observed count or size when relevant.
	Count int
	// ExpectedNumber records the sequence number required by validation.
	ExpectedNumber uint64
	// ObservedNumber records the sequence number found by validation.
	ObservedNumber uint64
}

ErrorDetails carries bounded parser metadata for Error.

type ErrorLocation

type ErrorLocation struct {
	// FieldIndex records the rawmsg header occurrence index when known.
	FieldIndex int
	// HashIndex records the zero-based h= hash-set index when relevant.
	HashIndex int
}

ErrorLocation identifies bounded Message-Instance parser context.

type HashSelectionStatus

type HashSelectionStatus string

HashSelectionStatus identifies supported Message-Instance hash selection state.

const (
	// HashSelectionStatusSelected reports at least one usable supported tuple.
	HashSelectionStatusSelected HashSelectionStatus = "selected"
	// HashSelectionStatusMissing reports an empty or incoherent instance value.
	HashSelectionStatusMissing HashSelectionStatus = "missing"
	// HashSelectionStatusUnsupported reports only unknown hash algorithms.
	HashSelectionStatusUnsupported HashSelectionStatus = "unsupported"
)

func (HashSelectionStatus) Known

func (s HashSelectionStatus) Known() bool

Known reports whether status belongs to the closed selection vocabulary.

type HashSet

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

HashSet stores one immutable h= algorithm/header/body hash tuple.

func (HashSet) BodyHash

func (h HashSet) BodyHash() (tagvalue.Base64String, bool)

BodyHash returns the decoded body hash container for known algorithms.

func (HashSet) BodyHashValue

func (h HashSet) BodyHashValue() []byte

BodyHashValue returns the parser-owned body hash component bytes.

func (HashSet) Format

func (h HashSet) Format(state fmt.State, _ rune)

Format routes every fmt form through the secret-safe hash-set summary.

func (HashSet) GoString

func (h HashSet) GoString() string

GoString returns a secret-safe hash-set Go representation.

func (HashSet) HeaderHash

func (h HashSet) HeaderHash() (tagvalue.Base64String, bool)

HeaderHash returns the decoded header hash container for known algorithms.

func (HashSet) HeaderHashValue

func (h HashSet) HeaderHashValue() []byte

HeaderHashValue returns the parser-owned header hash component bytes.

func (HashSet) Known

func (h HashSet) Known() bool

Known reports whether this hash set uses a parser-known algorithm.

func (HashSet) Name

func (h HashSet) Name() string

Name returns the canonical lowercase hash algorithm name.

func (HashSet) String

func (h HashSet) String() string

String returns a secret-safe hash-set summary.

type LimitName

type LimitName string

LimitName identifies one closed Message-Instance limit name.

const (
	LimitNameMaxHashSets     LimitName = "max_hash_sets"
	LimitNameMaxInstances    LimitName = "max_instances"
	LimitNameMaxFieldBytes   LimitName = "max_field_bytes"
	LimitNameMaxLineBytes    LimitName = "max_line_bytes"
	LimitNameMaxRecipeBytes  LimitName = "max_recipe_bytes"
	LimitNameRenderCoherence LimitName = "render_limit_coherence"
)

Message-Instance limit names form the closed resource vocabulary.

func (LimitName) Known

func (n LimitName) Known() bool

Known reports whether name belongs to the closed Message-Instance limit vocabulary.

type Limits

type Limits struct {
	// TagLimits bounds shared DKIM2 tag-list and base64string parsing.
	TagLimits tagvalue.Limits
	// MaxHashSets bounds h= hash sets counted across all groups.
	MaxHashSets int
	// MaxInstances bounds Message-Instance fields in one message.
	MaxInstances int
}

Limits contains fail-closed Message-Instance parser resource settings.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns restrictive Message-Instance parser defaults.

func (Limits) Validate

func (l Limits) Validate() error

Validate rejects unsafe Message-Instance parser limit values.

type MessageInstance

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

MessageInstance stores one immutable parsed Message-Instance field.

func Extract

func Extract(msg rawmsg.Message) ([]MessageInstance, error)

Extract parses all Message-Instance fields from msg with default limits.

func NewForSigning

func NewForSigning(request SigningRequest) (MessageInstance, error)

NewForSigning constructs one immutable generated Message-Instance model.

func Parse

func Parse(field rawmsg.HeaderField) (MessageInstance, error)

Parse parses one Message-Instance field with default limits.

func (MessageInstance) Format

func (m MessageInstance) Format(state fmt.State, _ rune)

Format routes every fmt form through the secret-safe summary.

func (MessageInstance) GoString

func (m MessageInstance) GoString() string

GoString returns a secret-safe Message-Instance Go representation.

func (MessageInstance) HashLayout

func (m MessageInstance) HashLayout() combine.Layout

HashLayout returns the Draft-09 Section 9.3 hash-any/hash-all group structure of HashSets.

func (MessageInstance) HashSets

func (m MessageInstance) HashSets() []HashSet

HashSets returns immutable copies of h= hash sets in field order.

func (MessageInstance) HeaderIndex

func (m MessageInstance) HeaderIndex() int

HeaderIndex returns the raw header occurrence index.

func (MessageInstance) Number

func (m MessageInstance) Number() uint64

Number returns the parsed m= Message-Instance number.

func (MessageInstance) Recipe

func (m MessageInstance) Recipe() (tagvalue.Base64String, bool)

Recipe returns the parsed r= base64 container when present.

func (MessageInstance) Render

func (m MessageInstance) Render(limits RenderLimits) ([]byte, error)

Render emits the deterministic complete Message-Instance field.

func (MessageInstance) SHA256HashSet

func (m MessageInstance) SHA256HashSet() (HashSet, HashSelectionStatus)

SHA256HashSet selects the supported SHA-256 tuple for compatibility callers.

func (MessageInstance) String

func (m MessageInstance) String() string

String returns a secret-safe Message-Instance summary.

func (MessageInstance) SupportedHashSets

func (m MessageInstance) SupportedHashSets() ([]HashSet, HashSelectionStatus)

SupportedHashSets returns every supported tuple in wire order.

type Parser

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

Parser parses Message-Instance fields with immutable output.

func NewParser

func NewParser(limits Limits) (Parser, error)

NewParser constructs a Message-Instance parser with restrictive defaults.

func (Parser) Extract

func (p Parser) Extract(msg rawmsg.Message) ([]MessageInstance, error)

Extract parses Message-Instance fields from msg in raw header occurrence order.

func (Parser) ParseField

func (p Parser) ParseField(field rawmsg.HeaderField) (MessageInstance, error)

ParseField parses one rawmsg header field as a Message-Instance.

type RenderLimits

type RenderLimits struct {
	MaxFieldBytes  int
	MaxLineBytes   int
	MaxRecipeBytes int
}

RenderLimits bounds deterministic Message-Instance rendering.

func DefaultRenderLimits

func DefaultRenderLimits() RenderLimits

DefaultRenderLimits returns the exact signing field hard limits.

func (RenderLimits) Validate

func (l RenderLimits) Validate() error

Validate rejects widening, nonpositive, or incoherent render limits.

type SigningRequest

type SigningRequest struct {
	Number        uint64
	HeaderHash    []byte
	BodyHash      []byte
	Recipe        []byte
	RecipePresent bool
}

SigningRequest contains immutable input for one generated Message-Instance.

func (SigningRequest) Format

func (r SigningRequest) Format(state fmt.State, _ rune)

Format routes every fmt form through the secret-safe summary.

func (SigningRequest) GoString

func (r SigningRequest) GoString() string

GoString returns a secret-safe signing-request Go representation.

func (SigningRequest) String

func (r SigningRequest) String() string

String returns a secret-safe signing-request summary.

type TagName

type TagName string

TagName identifies one closed Message-Instance tag name.

const (
	TagNameNumber TagName = "m"
	TagNameHashes TagName = "h"
	TagNameRecipe TagName = "r"
)

Message-Instance tag names form the closed diagnostic vocabulary.

func (TagName) Known

func (n TagName) Known() bool

Known reports whether name belongs to the closed Message-Instance tag vocabulary.

Jump to

Keyboard shortcuts

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