rawmsg

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

Documentation

Overview

Package rawmsg owns the raw RFC 5322 message representation used by DKIM2 protocol code.

Values in this package are byte-oriented and immutable after construction. Constructors copy caller-owned slices, and accessors return fresh copies so later canonicalization, recipe, and signature code cannot accidentally observe mutated protocol state.

The parser contract is strict by default. Raw messages are expected to use CRLF line endings, bounded header and body sizes, and explicit metadata for any future compatibility normalization. Structured errors report typed, bounded context only; they must not include raw message bodies, full header values, recipients, credentials, or other secret-bearing data.

Index

Constants

View Source
const HardMaxBodyLines = 2_097_152

HardMaxBodyLines is the closed ceiling for parser-owned body-line metadata.

View Source
const HardMaxMessageBytes = 128 << 20

HardMaxMessageBytes bounds supported SMTP-sized raw messages across the library.

Variables

This section is empty.

Functions

func CanonicalHeaderName

func CanonicalHeaderName(name string) (string, bool)

CanonicalHeaderName validates an RFC 5322 field name and returns its ASCII lowercase form.

func IsParserErrorCode

func IsParserErrorCode(err error, code ErrorCode) bool

IsParserErrorCode reports whether err contains a ParserError with code.

Types

type Body

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

Body stores immutable parser-owned body bytes and their line index.

func NewBody

func NewBody(data []byte, lines BodyLineIndex) (Body, error)

NewBody constructs an immutable body from bytes and a validated line index.

func NewReconstructedBody

func NewReconstructedBody(data []byte, options ParserOptions) (Body, error)

NewReconstructedBody validates detached body bytes and rebuilds their line index.

func (Body) Bytes

func (b Body) Bytes() []byte

Bytes returns the parser-owned body bytes.

func (Body) Equal

func (b Body) Equal(other Body) bool

Equal reports exact body-byte equality without exposing or cloning storage.

func (Body) Initialized

func (b Body) Initialized() bool

Initialized reports whether the body was constructed through rawmsg validation.

func (Body) Len

func (b Body) Len() int

Len returns the number of parser-owned body bytes.

func (Body) LineBytes

func (b Body) LineBytes(index int) ([]byte, bool)

LineBytes returns one detached encoded line including its original terminator.

func (Body) LineCount

func (b Body) LineCount() int

LineCount returns the validated body-line count without cloning the index.

func (Body) LineEncodedLen

func (b Body) LineEncodedLen(index int) (int, bool)

LineEncodedLen returns one line's byte size including its original terminator.

func (Body) Lines

func (b Body) Lines() BodyLineIndex

Lines returns the immutable body line index.

func (Body) VisitLines

func (b Body) VisitLines(visit func(BodyLineView) error) error

VisitLines visits immutable line views in top-down message order.

type BodyLine

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

BodyLine describes one body line span without rewriting body bytes.

func NewBodyLine

func NewBodyLine(index int, startOffset int, endOffset int, lineEndingWidth int) (BodyLine, error)

NewBodyLine constructs an immutable body line span.

func (BodyLine) EndOffset

func (l BodyLine) EndOffset() int

EndOffset returns the exclusive body byte offset before the line ending.

func (BodyLine) Index

func (l BodyLine) Index() int

Index returns the zero-based body line index.

func (BodyLine) LineEndingWidth

func (l BodyLine) LineEndingWidth() int

LineEndingWidth returns the byte width of the line ending after the line.

func (BodyLine) StartOffset

func (l BodyLine) StartOffset() int

StartOffset returns the inclusive body byte offset where the line begins.

type BodyLineIndex

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

BodyLineIndex stores immutable body line spans in byte order.

func NewBodyLineIndex

func NewBodyLineIndex(lines []BodyLine) (BodyLineIndex, error)

NewBodyLineIndex constructs an immutable body line index.

func (BodyLineIndex) Len

func (i BodyLineIndex) Len() int

Len returns the number of indexed body lines.

func (BodyLineIndex) Line

func (i BodyLineIndex) Line(index int) (BodyLine, bool)

Line returns an indexed body line by zero-based index.

func (BodyLineIndex) Lines

func (i BodyLineIndex) Lines() []BodyLine

Lines returns copies of all indexed body line spans.

type BodyLineView

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

BodyLineView provides read-only bounded traversal without cloning body storage.

func (BodyLineView) ContentLen

func (v BodyLineView) ContentLen() int

ContentLen returns line bytes excluding the validated original terminator.

func (BodyLineView) EncodedCopy

func (v BodyLineView) EncodedCopy() []byte

EncodedCopy returns detached exact content and terminator bytes.

func (BodyLineView) EncodedLen

func (v BodyLineView) EncodedLen() int

EncodedLen returns content plus the validated original terminator width.

func (BodyLineView) Terminated

func (v BodyLineView) Terminated() bool

Terminated reports whether the line ended with CRLF in the parsed body.

type ErrorCode

type ErrorCode string

ErrorCode identifies a bounded raw-message parser or invariant failure.

const (
	// ErrorCodeBareLF reports a bare LF rejected by strict CRLF policy.
	ErrorCodeBareLF ErrorCode = "bare_lf"
	// ErrorCodeBareCR reports a bare CR rejected by strict CRLF policy.
	ErrorCodeBareCR ErrorCode = "bare_cr"
	// ErrorCodeMixedLineEndings reports incompatible line endings in one input.
	ErrorCodeMixedLineEndings ErrorCode = "mixed_line_endings"
	// ErrorCodeMissingDelimiter reports a missing header/body delimiter.
	ErrorCodeMissingDelimiter ErrorCode = "missing_header_body_delimiter"
	// ErrorCodeMalformedHeader reports malformed header syntax.
	ErrorCodeMalformedHeader ErrorCode = "malformed_header"
	// ErrorCodeLimitExceeded reports a configured resource limit violation.
	ErrorCodeLimitExceeded ErrorCode = "limit_exceeded"
	// ErrorCodeUnsupportedPolicy reports an unknown parser policy value.
	ErrorCodeUnsupportedPolicy ErrorCode = "unsupported_policy"
	// ErrorCodeInvalidTransportForm reports missing or unsupported signing transport metadata.
	ErrorCodeInvalidTransportForm ErrorCode = "invalid_transport_form"
	// ErrorCodeInvalidInvariant reports an invalid type-construction invariant.
	ErrorCodeInvalidInvariant ErrorCode = "invalid_invariant"
)

type ErrorLocation

type ErrorLocation struct {
	// Offset records a zero-based byte offset when known.
	Offset int
	// Line records a one-based input line number when known.
	Line int
	// Column records a one-based input column number when known.
	Column int
}

ErrorLocation identifies bounded byte and line context for a parser error.

type ErrorReasonClass

type ErrorReasonClass string

ErrorReasonClass groups parser failures into stable operational classes.

const (
	// ErrorReasonMalformed classifies syntactically malformed message input.
	ErrorReasonMalformed ErrorReasonClass = "malformed"
	// ErrorReasonPolicy classifies input rejected by an explicit parser policy.
	ErrorReasonPolicy ErrorReasonClass = "policy"
	// ErrorReasonLimit classifies input rejected by resource limits.
	ErrorReasonLimit ErrorReasonClass = "limit"
	// ErrorReasonInvariant classifies invalid internal domain construction.
	ErrorReasonInvariant ErrorReasonClass = "invariant"
)

type HeaderBlock

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

HeaderBlock stores immutable header fields in RFC 5322 occurrence order.

func NewHeaderBlock

func NewHeaderBlock(fields []HeaderField, originalBytes []byte) (HeaderBlock, error)

NewHeaderBlock constructs an immutable header block from validated fields.

func NewReconstructedHeaderBlock

func NewReconstructedHeaderBlock(fieldBytes [][]byte, options ParserOptions) (HeaderBlock, error)

NewReconstructedHeaderBlock validates detached logical header-field bytes for recipe output.

func (HeaderBlock) Field

func (h HeaderBlock) Field(index int) (HeaderField, bool)

Field returns the header field at index when it exists.

func (HeaderBlock) Fields

func (h HeaderBlock) Fields() []HeaderField

Fields returns immutable copies of the header field sequence.

func (HeaderBlock) FieldsByName

func (h HeaderBlock) FieldsByName(name string) []HeaderField

FieldsByName returns header occurrences matching a lowercase ASCII name.

func (HeaderBlock) Initialized

func (h HeaderBlock) Initialized() bool

Initialized reports whether the block was constructed through rawmsg validation.

func (HeaderBlock) LastFieldByName

func (h HeaderBlock) LastFieldByName(name string) (HeaderField, bool)

LastFieldByName returns the last matching header occurrence.

func (HeaderBlock) Len

func (h HeaderBlock) Len() int

Len returns the number of header fields in occurrence order.

func (HeaderBlock) OriginalByteLen

func (h HeaderBlock) OriginalByteLen() int

OriginalByteLen returns the validated raw header-block size without cloning bytes.

func (HeaderBlock) OriginalBytes

func (h HeaderBlock) OriginalBytes() []byte

OriginalBytes returns the parser-owned raw header bytes.

func (HeaderBlock) VisitFieldsReverse

func (h HeaderBlock) VisitFieldsReverse(visit func(HeaderFieldView) error) error

VisitFieldsReverse visits immutable field views from the bottom header upward.

type HeaderField

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

HeaderField stores one immutable RFC 5322 header occurrence.

func NewHeaderField

func NewHeaderField(index int, rawName []byte, rawValue []byte, unfoldedValue []byte, originalBytes []byte) (HeaderField, error)

NewHeaderField constructs an immutable header field and canonical name view.

func (HeaderField) Index

func (f HeaderField) Index() int

Index returns the zero-based header occurrence index.

func (HeaderField) NameLower

func (f HeaderField) NameLower() string

NameLower returns the lowercase ASCII field name for matching.

func (HeaderField) OriginalBytes

func (f HeaderField) OriginalBytes() []byte

OriginalBytes returns the original field bytes including its line ending.

func (HeaderField) RawName

func (f HeaderField) RawName() []byte

RawName returns the field name bytes exactly as captured by the parser.

func (HeaderField) RawValue

func (f HeaderField) RawValue() []byte

RawValue returns the field value bytes without the field name or line ending.

func (HeaderField) UnfoldedValue

func (f HeaderField) UnfoldedValue() []byte

UnfoldedValue returns a parser-owned unfolded value copy.

type HeaderFieldView

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

HeaderFieldView provides read-only bounded traversal without deep-cloning a field.

func (HeaderFieldView) MaximumPhysicalLineBytes

func (v HeaderFieldView) MaximumPhysicalLineBytes() int

MaximumPhysicalLineBytes scans the encoded field and returns its longest line excluding CRLF.

func (HeaderFieldView) NameLower

func (v HeaderFieldView) NameLower() string

NameLower returns the immutable canonical lowercase name without allocation.

func (HeaderFieldView) OriginalByteLen

func (v HeaderFieldView) OriginalByteLen() int

OriginalByteLen returns the encoded field size without copying bytes.

func (HeaderFieldView) UnfoldedValueCopy

func (v HeaderFieldView) UnfoldedValueCopy() []byte

UnfoldedValueCopy returns one detached exact unfolded value.

func (HeaderFieldView) UnfoldedValueLen

func (v HeaderFieldView) UnfoldedValueLen() int

UnfoldedValueLen returns the exact unfolded value size without copying bytes.

type InsertionRequest

type InsertionRequest struct {
	// Message is the immutable authoritative RFC 5322 source.
	Message Message
	// TransportForm declares that all local transformations except dot-stuffing are complete.
	TransportForm TransportForm
	// Fields contains one or more ordered, complete RFC 5322 header fields.
	Fields [][]byte
	// Options narrows parser and output limits without widening hard defaults.
	Options ParserOptions
}

InsertionRequest carries ordered complete fields and exact validated source bytes.

func (InsertionRequest) Format

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

Format routes every insertion-request formatting form through the redacted summary.

func (InsertionRequest) GoString

func (r InsertionRequest) GoString() string

GoString returns the constant secret-safe insertion-request Go representation.

func (InsertionRequest) String

func (r InsertionRequest) String() string

String returns a constant secret-safe insertion-request summary.

type LineEndingPolicy

type LineEndingPolicy string

LineEndingPolicy identifies the parser's line-ending handling mode.

const (
	// LineEndingPolicyStrictCRLF accepts only CRLF-delimited protocol input.
	LineEndingPolicyStrictCRLF LineEndingPolicy = "strict-crlf"
	// LineEndingPolicyNormalizeLF is reserved and rejected until normalization is implemented.
	LineEndingPolicyNormalizeLF LineEndingPolicy = "normalize-lf"
)

type Message

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

Message stores immutable raw RFC 5322 message bytes and controlled views.

func NewMessage

func NewMessage(rawBytes []byte, headers HeaderBlock, body Body, metadata ParserMetadata) (Message, error)

NewMessage constructs an immutable message from parser-owned components.

func NewReconstructedMessage

func NewReconstructedMessage(headers HeaderBlock, body Body, options ParserOptions) (Message, error)

NewReconstructedMessage materializes validated reconstructed components with an RFC 5322 separator.

func NewReconstructedMessageWithFraming

func NewReconstructedMessageWithFraming(headers HeaderBlock, body Body, options ParserOptions, framing MessageFraming) (Message, error)

NewReconstructedMessageWithFraming materializes components under explicit validated framing.

func Parse

func Parse(data []byte) (Message, error)

Parse parses raw RFC 5322 bytes with restrictive default parser options.

func ParseWithOptions

func ParseWithOptions(data []byte, options ParserOptions) (Message, error)

ParseWithOptions parses raw RFC 5322 bytes with explicit parser options.

func PrependValidatedFields

func PrependValidatedFields(request InsertionRequest) (Message, error)

PrependValidatedFields places ordered complete fields as one block at the top of the header block without rewriting inherited bytes. Message-Instance and DKIM2-Signature are trace fields (Draft-09 Sections 9 and 10), and RFC 5322 Section 3.6 says trace fields SHOULD be kept in blocks prepended to the message, so the block lands above the previous top field in request order. This is the single library owner of whole-message trace-block placement.

func (Message) Body

func (m Message) Body() Body

Body returns the immutable message body.

func (Message) Framing

func (m Message) Framing() MessageFraming

Framing returns the validated raw message's header/body separator form.

func (Message) Headers

func (m Message) Headers() HeaderBlock

Headers returns the immutable header block.

func (Message) Initialized

func (m Message) Initialized() bool

Initialized reports whether the message was constructed through rawmsg validation.

func (Message) Metadata

func (m Message) Metadata() ParserMetadata

Metadata returns bounded parser metadata for the message.

func (Message) RawBytes

func (m Message) RawBytes() []byte

RawBytes returns the parser-owned full message bytes.

type MessageFraming

type MessageFraming string

MessageFraming identifies whether an empty body used an explicit header/body separator.

const (
	// MessageFramingHeaderOnly identifies header bytes without a separator or body.
	MessageFramingHeaderOnly MessageFraming = "header_only"
	// MessageFramingDelimited identifies an explicit CRLF header/body separator.
	MessageFramingDelimited MessageFraming = "delimited"
)

func (MessageFraming) Known

func (f MessageFraming) Known() bool

Known reports whether framing belongs to the closed raw-message vocabulary.

type ParserError

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

ParserError is a typed, secret-safe raw-message parser error.

func NewParserError

func NewParserError(code ErrorCode, location ErrorLocation, details ParserErrorDetails) *ParserError

NewParserError constructs a bounded parser error for classification.

func (*ParserError) Code

func (e *ParserError) Code() ErrorCode

Code returns the stable parser error code.

func (*ParserError) Error

func (e *ParserError) Error() string

Error returns a bounded diagnostic without raw message-derived values.

func (*ParserError) Is

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

Is matches parser errors by code for errors.Is.

func (*ParserError) Limit

func (e *ParserError) Limit() int

Limit returns the numeric resource limit associated with the error.

func (*ParserError) LimitName

func (e *ParserError) LimitName() string

LimitName returns the resource limit name for structured callers only.

func (*ParserError) Location

func (e *ParserError) Location() ErrorLocation

Location returns bounded byte and line context for the error.

func (*ParserError) PolicyName

func (e *ParserError) PolicyName() string

PolicyName returns the bounded parser policy name associated with the error.

func (*ParserError) ReasonClass

func (e *ParserError) ReasonClass() ErrorReasonClass

ReasonClass returns the stable operational error class.

type ParserErrorDetails

type ParserErrorDetails struct {
	// Reason records the stable operational class for the error.
	Reason ErrorReasonClass
	// PolicyName records a bounded parser policy name when relevant.
	PolicyName string
	// LimitName records the resource limit identifier for structured callers.
	LimitName string
	// Limit records the numeric resource limit when relevant.
	Limit int
}

ParserErrorDetails carries bounded classification metadata for ParserError.

type ParserMetadata

type ParserMetadata struct {
	// LineEndingPolicy records the policy used for parser-owned bytes.
	LineEndingPolicy LineEndingPolicy
	// NormalizedInput records whether explicit compatibility normalization occurred.
	NormalizedInput bool
	// OriginalBytes records the caller input size before normalization.
	OriginalBytes int
	// StoredBytes records the parser-owned raw message size.
	StoredBytes int
	// HeaderBytes records the parser-owned header block size.
	HeaderBytes int
	// HeaderFields records the number of parsed header occurrences.
	HeaderFields int
	// BodyBytes records the parser-owned body size.
	BodyBytes int
}

ParserMetadata records bounded facts about parser-owned message bytes.

func NewParserMetadata

func NewParserMetadata(policy LineEndingPolicy, normalized bool, originalBytes int, storedBytes int, headerBytes int, headerFields int, bodyBytes int) ParserMetadata

NewParserMetadata constructs bounded parser metadata from byte counts.

type ParserOptions

type ParserOptions struct {
	// MaxMessageBytes bounds the full raw message accepted by the parser.
	MaxMessageBytes int
	// MaxHeaderBytes bounds the raw header block accepted by the parser.
	MaxHeaderBytes int
	// MaxHeaderFields bounds the number of parsed header occurrences.
	MaxHeaderFields int
	// MaxHeaderFieldBytes bounds one header field including continuations.
	MaxHeaderFieldBytes int
	// MaxHeaderLineBytes bounds one physical header line excluding CRLF.
	MaxHeaderLineBytes int
	// MaxBodyLineBytes bounds the body line size recorded for indexing.
	MaxBodyLineBytes int
	// MaxBodyLines bounds the number of body lines recorded for indexing.
	MaxBodyLines int
	// LineEndingPolicy controls strict CRLF handling; compatibility modes are reserved.
	LineEndingPolicy LineEndingPolicy
	// RecordNormalizedInput is reserved and rejected until normalization is implemented.
	RecordNormalizedInput bool
}

ParserOptions contains fail-closed parser resource and policy settings.

func DefaultParserOptions

func DefaultParserOptions() ParserOptions

DefaultParserOptions returns the restrictive raw-message parser defaults.

func (ParserOptions) Validate

func (o ParserOptions) Validate() error

Validate rejects unsafe parser option values before parsing begins.

type TransportForm

type TransportForm string

TransportForm identifies the caller-declared transport state of signable bytes.

const (
	// TransportFormFinalNetworkPreDotStuffing declares final network bytes before SMTP dot-stuffing.
	TransportFormFinalNetworkPreDotStuffing TransportForm = "final_network_form_pre_dot_stuffing"
)

func (TransportForm) Known

func (f TransportForm) Known() bool

Known reports whether the form is the sole signable transport declaration.

Jump to

Keyboard shortcuts

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