jpegtrust

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 30, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package jpegtrust implements parsing and validation for JPEG Trust metadata as defined in ISO/IEC 21617 (JPEG Trust).

JPEG Trust provides a standardized framework for content authenticity, provenance, and integrity verification in JPEG images. It is designed to work with all JPEG family formats and leverages JUMBF (ISO/IEC 19566-5) as its container format for trust metadata.

Core Concepts

The package supports three main types of trust metadata:

  • Provenance Records: Track the history of image creation and modifications, including actors, timestamps, software used, and actions performed.

  • Authenticity Assertions: Claims about the image content, including whether it was AI-generated, human-created, or edited.

  • Integrity Hashes: Cryptographic hashes that allow verification that the image content has not been tampered with.

Trust Chain

JPEG Trust supports building a chain of trust from the original creator through subsequent editors to the current state of the image. The TrustChain type represents this chain and allows verification of the complete history.

Security Considerations

The parser enforces security limits from security/limits.go:

  • MaxMetadataSize: Maximum trust metadata size (default: 64 MB)
  • MaxJUMBFBoxDepth: Maximum nesting depth for trust boxes (default: 32)

Usage Example

data := readJPEGFile("photo.jpg")
validator := jpegtrust.NewValidator()
manifest, err := validator.ValidateTrust(data)
if err != nil {
    log.Printf("Trust validation failed: %v", err)
    return
}
if manifest.IsAIContent {
    fmt.Println("This image was marked as AI-generated")
}

Provenance Checking

To extract and examine the provenance chain:

checker := jpegtrust.NewProvenanceChecker()
records, err := checker.GetProvenance(data)
if err != nil {
    log.Fatal(err)
}
for _, record := range records {
    fmt.Printf("%s by %s at %d\n", record.Action, record.Actor, record.Timestamp)
}

Anti-Deepfake Markers

JPEG Trust includes specific support for marking and detecting AI-generated content, which is crucial for combating deepfakes:

manifest, _ := validator.ValidateTrust(data)
if manifest.IsAIContent {
    fmt.Println("Warning: This image is marked as AI-generated")
}

Integration with JUMBF

JPEG Trust metadata is stored in JUMBF boxes within the JPEG file. This package integrates with the jumbf package for container parsing.

Note on Signature Verification

This package provides parsing and structure validation for trust metadata. Full cryptographic signature verification requires an external crypto backend and is provided as an interface (SignatureVerifier) that can be implemented by the application.

References

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidManifest indicates the trust manifest structure is invalid.
	ErrInvalidManifest = errors.New("invalid trust manifest")

	// ErrProvenanceError indicates an error parsing provenance records.
	ErrProvenanceError = errors.New("provenance record error")

	// ErrAuthenticityError indicates an error parsing authenticity assertions.
	ErrAuthenticityError = errors.New("authenticity assertion error")

	// ErrHashError indicates an error with integrity hash data.
	ErrHashError = errors.New("integrity hash error")

	// ErrVerificationFailed indicates trust verification failed.
	ErrVerificationFailed = errors.New("trust verification failed")

	// ErrChainBroken indicates the provenance chain has a break.
	ErrChainBroken = errors.New("provenance chain broken")

	// ErrEmptyProvenance indicates no provenance records were found.
	ErrEmptyProvenance = errors.New("no provenance records found")

	// ErrNoTrustData indicates no trust metadata was found in the image.
	ErrNoTrustData = errors.New("no trust metadata found")

	// ErrSignatureInvalid indicates the digital signature is invalid.
	ErrSignatureInvalid = errors.New("invalid digital signature")

	// ErrCertificateExpired indicates the signing certificate has expired.
	ErrCertificateExpired = errors.New("signing certificate expired")

	// ErrCertificateRevoked indicates the signing certificate was revoked.
	ErrCertificateRevoked = errors.New("signing certificate revoked")

	// ErrNoSignatureVerifier indicates no signature verifier was configured.
	ErrNoSignatureVerifier = errors.New("no signature verifier configured")

	// ErrHashMismatch indicates the content hash does not match.
	ErrHashMismatch = errors.New("content hash mismatch")

	// ErrUnsupportedHashAlgorithm indicates the hash algorithm is not supported.
	ErrUnsupportedHashAlgorithm = errors.New("unsupported hash algorithm")

	// ErrTruncatedData indicates the trust data is truncated.
	ErrTruncatedData = errors.New("truncated trust data")

	// ErrNilData indicates nil input data was provided.
	ErrNilData = errors.New("nil data provided")

	// ErrEmptyData indicates empty input data was provided.
	ErrEmptyData = errors.New("empty data provided")

	// ErrTooManyRecords wraps the security error for too many provenance records.
	ErrTooManyRecords = errors.New("too many provenance records")

	// ErrTooManyAssertions wraps the security error for too many assertions.
	ErrTooManyAssertions = errors.New("too many assertions")

	// ErrMetadataTooLarge wraps the security error for metadata size.
	ErrMetadataTooLarge = security.ErrMetadataTooLarge
)

Package-specific errors for JPEG Trust parsing and validation.

View Source
var ErrNotJUMBFTrust = errors.New("jpegtrust: no JUMBF Trust manifest found")

ErrNotJUMBFTrust indicates the input does not contain an ISO/IEC 21617 JUMBF Trust manifest.

Functions

This section is empty.

Types

type ActionType

type ActionType string

ActionType represents the type of action in a provenance record.

const (
	// ActionCreated indicates the content was created.
	ActionCreated ActionType = "c2pa.created"

	// ActionEdited indicates the content was edited.
	ActionEdited ActionType = "c2pa.edited"

	// ActionConverted indicates the content was converted to another format.
	ActionConverted ActionType = "c2pa.converted"

	// ActionCropped indicates the content was cropped.
	ActionCropped ActionType = "c2pa.cropped"

	// ActionResized indicates the content was resized.
	ActionResized ActionType = "c2pa.resized"

	// ActionFiltered indicates a filter was applied.
	ActionFiltered ActionType = "c2pa.filtered"

	// ActionPublished indicates the content was published.
	ActionPublished ActionType = "c2pa.published"

	// ActionSigned indicates the content was digitally signed.
	ActionSigned ActionType = "c2pa.signed"
)

type AuthenticityAssertion

type AuthenticityAssertion struct {
	// Type identifies the assertion type (e.g., "c2pa.created", "c2pa.edited").
	Type string

	// Label is a human-readable label for the assertion.
	Label string

	// Value contains the assertion value (type depends on assertion type).
	Value interface{}

	// WhenAsserted is the timestamp when this assertion was made.
	WhenAsserted int64

	// AssertedBy identifies who made this assertion.
	AssertedBy string

	// IsAIGenerated indicates if the content was generated by AI.
	IsAIGenerated bool

	// AIModel specifies the AI model used, if IsAIGenerated is true.
	AIModel string

	// IsHumanCreated indicates if the content was created by a human.
	IsHumanCreated bool

	// IsEdited indicates if the content has been edited.
	IsEdited bool

	// EditActions lists the types of edits performed.
	EditActions []string

	// Metadata contains any additional key-value metadata.
	Metadata map[string]string
}

AuthenticityAssertion represents a claim about the image content. These assertions provide information about how the content was created and whether it has been modified.

type ByteRange

type ByteRange struct {
	Start int64
	End   int64
}

ByteRange represents a range of bytes.

type ChainBuilder

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

ChainBuilder builds trust chains from provenance records.

func DefaultChainBuilder

func DefaultChainBuilder() *ChainBuilder

DefaultChainBuilder returns a new ChainBuilder with default configuration. This is the recommended way to create a ChainBuilder for basic use.

func NewChainBuilder

func NewChainBuilder() *ChainBuilder

NewChainBuilder creates a new ChainBuilder.

func (*ChainBuilder) BuildChain

func (b *ChainBuilder) BuildChain(data []byte) (*TrustChain, error)

BuildChain builds a trust chain from image data.

Chain-integrity semantics per ISO/IEC 21617: only the origin record is permitted to have an absent ParentHash. Any non-origin record missing either its own Hash or its ParentHash is treated as a broken link with BreakReason = "missing hash" — the previous implementation silently skipped the linkage check when either side was nil, letting malformed chains report IsComplete=true. See doc/DEFERRED-AUDITS.md §3 T3.

type ChainError

type ChainError struct {
	// RecordIndex is the index of the record where the error occurred.
	RecordIndex int

	// Message describes the error.
	Message string

	// Cause is the underlying error.
	Cause error
}

ChainError provides detailed context for provenance chain errors.

func NewChainError

func NewChainError(recordIndex int, message string, cause error) *ChainError

NewChainError creates a new ChainError with the given details.

func (*ChainError) Error

func (e *ChainError) Error() string

Error implements the error interface.

func (*ChainError) Unwrap

func (e *ChainError) Unwrap() error

Unwrap returns the underlying error.

type ContentOrigin

type ContentOrigin int

ContentOrigin represents how content was originally created.

const (
	// OriginUnknown indicates the origin is not specified.
	OriginUnknown ContentOrigin = iota

	// OriginHumanCreated indicates content was created by a human.
	OriginHumanCreated

	// OriginAIGenerated indicates content was generated by AI.
	OriginAIGenerated

	// OriginMixed indicates content has both human and AI elements.
	OriginMixed

	// OriginCaptured indicates content was captured from real world (camera).
	OriginCaptured
)

func (ContentOrigin) String

func (o ContentOrigin) String() string

String returns a string representation of the content origin.

type IntegrityHash

type IntegrityHash struct {
	// Algorithm specifies the hash algorithm (e.g., "SHA-256", "SHA-384", "SHA-512").
	Algorithm string

	// Value is the hash value bytes.
	Value []byte

	// Scope indicates what the hash covers (e.g., "full", "content", "metadata").
	Scope string

	// ComputedAt is the timestamp when the hash was computed.
	ComputedAt int64

	// ExcludedRanges lists byte ranges excluded from the hash calculation.
	// Used for self-referential hashes where the hash itself must be excluded.
	ExcludedRanges []ByteRange
}

IntegrityHash represents a cryptographic hash for content verification.

type ParseError

type ParseError struct {
	// Offset is the byte position where the error occurred.
	Offset int64

	// Field describes which field was being parsed.
	Field string

	// Message describes the error.
	Message string

	// Cause is the underlying error.
	Cause error
}

ParseError provides detailed context for parsing errors.

func NewParseError

func NewParseError(offset int64, field, message string, cause error) *ParseError

NewParseError creates a new ParseError with the given details.

func (*ParseError) Error

func (e *ParseError) Error() string

Error implements the error interface.

func (*ParseError) Unwrap

func (e *ParseError) Unwrap() error

Unwrap returns the underlying error.

type Parser

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

Parser parses JPEG Trust metadata from byte data.

func DefaultParser

func DefaultParser() *Parser

DefaultParser returns a new Parser with default configuration. This is the recommended way to create a Parser for basic use.

func NewParser

func NewParser() *Parser

NewParser creates a new Parser with default configuration.

func NewParserWithConfig

func NewParserWithConfig(config *ValidatorConfig) *Parser

NewParserWithConfig creates a new Parser with the specified configuration.

func (*Parser) Parse

func (p *Parser) Parse(data []byte) (*TrustManifest, error)

Parse parses trust metadata from byte data.

Detection order (matches ISO/IEC 21617 + 19566-5 routing requirements):

  1. Legacy 6-byte "JTRUST" magic — pre-ISO binary format retained for backwards compatibility with existing fixtures.
  2. JUMBF superbox ("jumb") prefix — routes through the JUMBF reader's superbox dispatch (internal/jpegsystems/jumbf) and detects the JPEG-Trust UUID or a C2PA UUID in the description box.

type ProvenanceCheckerImpl

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

ProvenanceCheckerImpl implements the ProvenanceChecker interface.

func DefaultProvenanceChecker

func DefaultProvenanceChecker() *ProvenanceCheckerImpl

DefaultProvenanceChecker returns a new ProvenanceChecker with default configuration. This is the recommended way to create a ProvenanceChecker for basic use.

func NewProvenanceChecker

func NewProvenanceChecker() *ProvenanceCheckerImpl

NewProvenanceChecker creates a new ProvenanceChecker.

func (*ProvenanceCheckerImpl) GetProvenance

func (c *ProvenanceCheckerImpl) GetProvenance(data []byte) ([]ProvenanceRecord, error)

GetProvenance extracts the provenance chain from image data.

func (*ProvenanceCheckerImpl) HasProvenance

func (c *ProvenanceCheckerImpl) HasProvenance(data []byte) bool

HasProvenance checks if provenance data exists.

type ProvenanceCheckerInterface

type ProvenanceCheckerInterface interface {
	// GetProvenance extracts the provenance chain from image data.
	GetProvenance(data []byte) ([]ProvenanceRecord, error)

	// HasProvenance checks if provenance data exists.
	HasProvenance(data []byte) bool
}

ProvenanceCheckerInterface defines the interface for provenance checking. This matches the ProvenanceChecker interface defined in interfaces.go.

type ProvenanceRecord

type ProvenanceRecord struct {
	// Action describes what was done (e.g., "created", "edited", "exported", "signed").
	Action string

	// Actor identifies who performed the action (person, organization, or software).
	Actor string

	// Timestamp is the Unix timestamp when the action occurred.
	Timestamp int64

	// Software identifies the application or tool used.
	Software string

	// SoftwareVersion is the version of the software used.
	SoftwareVersion string

	// Description provides a human-readable description of the action.
	Description string

	// Hash is the integrity hash after this action was performed.
	Hash []byte

	// HashAlgorithm specifies the algorithm used for the hash (e.g., "SHA-256").
	HashAlgorithm string

	// ParentHash links to the previous record in the chain.
	ParentHash []byte

	// Metadata contains any additional key-value metadata for the action.
	Metadata map[string]string
}

ProvenanceRecord represents a single entry in the provenance chain. Each record documents an action taken on the image by a specific actor.

func (*ProvenanceRecord) Time

func (p *ProvenanceRecord) Time() time.Time

Time returns the Timestamp as a time.Time value.

type SignatureVerification

type SignatureVerification struct {
	// IsValid indicates if the signature is valid.
	IsValid bool

	// VerifiedAt is the timestamp when verification was performed.
	VerifiedAt int64

	// SignerIdentity is the identity extracted from the certificate.
	SignerIdentity string

	// CertificateChain contains the certificate chain used for verification.
	CertificateChain [][]byte

	// CertificateExpiry is when the signing certificate expires.
	CertificateExpiry int64

	// IsCertificateExpired indicates if the certificate has expired.
	IsCertificateExpired bool

	// IsCertificateRevoked indicates if the certificate was revoked.
	IsCertificateRevoked bool

	// TrustAnchor identifies the root of trust for the certificate.
	TrustAnchor string

	// Error contains any error that occurred during verification.
	Error error
}

SignatureVerification represents the result of verifying a digital signature.

type SignatureVerifier

type SignatureVerifier interface {
	// Verify verifies a digital signature.
	// data is the signed data, signature is the signature bytes,
	// and certificate is the signer's certificate.
	Verify(data, signature, certificate []byte) (*SignatureVerification, error)
}

SignatureVerifier is an interface for external signature verification. Implementations should verify cryptographic signatures using appropriate certificate infrastructure.

type TrustChain

type TrustChain struct {
	// Records contains all provenance records in chronological order.
	Records []ProvenanceRecord

	// IsComplete indicates if the chain is complete from origin.
	IsComplete bool

	// BrokenAt indicates the index where the chain is broken (-1 if complete).
	BrokenAt int

	// BreakReason describes why the chain is broken, if applicable.
	BreakReason string

	// OriginRecord is the first record in the chain (creation).
	OriginRecord *ProvenanceRecord

	// LatestRecord is the most recent record in the chain.
	LatestRecord *ProvenanceRecord
}

TrustChain represents the complete chain of trust from creation to current state.

func (*TrustChain) Len

func (tc *TrustChain) Len() int

Len returns the number of records in the chain.

func (*TrustChain) Validate

func (tc *TrustChain) Validate() error

Validate checks if the chain is internally consistent.

Chain-integrity semantics per ISO/IEC 21617: only the origin record (index 0) may have an absent ParentHash. Any non-origin record with a missing ParentHash, missing own Hash, or mismatched parent linkage is rejected with ErrChainBroken. See doc/DEFERRED-AUDITS.md §3 T3.

type TrustManifest

type TrustManifest struct {
	// Version is the manifest format version (e.g., "1.0", "2.0").
	Version string

	// Issuer identifies the entity that created this manifest.
	Issuer string

	// IssuerURL is the URL for the issuer's public information.
	IssuerURL string

	// Title is an optional human-readable title for the manifest.
	Title string

	// CreatedAt is the timestamp when the manifest was created.
	CreatedAt int64

	// ProvenanceRecords contains the provenance chain.
	ProvenanceRecords []ProvenanceRecord

	// Assertions contains authenticity assertions.
	Assertions []AuthenticityAssertion

	// ContentHash is the primary integrity hash for the image content.
	ContentHash *IntegrityHash

	// MetadataHash is the integrity hash for the metadata portion.
	MetadataHash *IntegrityHash

	// Signature is the digital signature over the manifest (if present).
	Signature []byte

	// SignatureAlgorithm identifies the signature algorithm used.
	SignatureAlgorithm string

	// SignerCertificate is the X.509 certificate of the signer (if present).
	SignerCertificate []byte

	// IsAIContent indicates if any assertion marks this as AI-generated content.
	IsAIContent bool

	// ClaimGeneratorInfo describes the software that generated the claims.
	ClaimGeneratorInfo string
}

TrustManifest represents the complete trust metadata for an image. It aggregates provenance records, assertions, and integrity information.

type TrustValidationResult

type TrustValidationResult struct {
	// Manifest is the parsed trust manifest.
	Manifest *TrustManifest

	// Chain is the verified provenance chain.
	Chain *TrustChain

	// SignatureVerification contains signature verification results.
	SignatureVerification *SignatureVerification

	// HashVerification indicates if the content hash was verified.
	HashVerification bool

	// Warnings contains any non-fatal issues found during validation.
	Warnings []string

	// IsFullyVerified indicates if all checks passed.
	IsFullyVerified bool
}

TrustValidationResult represents the complete result of trust validation.

type TrustValidatorInterface

type TrustValidatorInterface interface {
	// ValidateTrust validates the trust metadata in image data.
	// Returns the manifest and any validation errors.
	ValidateTrust(data []byte) (*TrustManifest, error)
}

TrustValidatorInterface defines the interface for trust validation. This matches the TrustValidator interface defined in interfaces.go.

type ValidationError

type ValidationError struct {
	// Step describes which validation step failed.
	Step string

	// Expected describes what was expected.
	Expected string

	// Actual describes what was found.
	Actual string

	// Message describes the error.
	Message string

	// Cause is the underlying error.
	Cause error
}

ValidationError provides detailed context for validation errors.

func NewValidationError

func NewValidationError(step, expected, actual, message string, cause error) *ValidationError

NewValidationError creates a new ValidationError with the given details.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface.

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

Unwrap returns the underlying error.

type Validator

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

Validator validates JPEG Trust metadata.

func DefaultValidator

func DefaultValidator() *Validator

DefaultValidator returns a new Validator with default configuration. This is the recommended way to create a TrustValidator for basic use.

func NewValidator

func NewValidator() *Validator

NewValidator creates a new Validator with default configuration.

func NewValidatorWithConfig

func NewValidatorWithConfig(config *ValidatorConfig) *Validator

NewValidatorWithConfig creates a new Validator with the specified configuration.

func (*Validator) SetSignatureVerifier

func (v *Validator) SetSignatureVerifier(verifier SignatureVerifier)

SetSignatureVerifier sets the signature verifier for cryptographic verification.

func (*Validator) ValidateTrust

func (v *Validator) ValidateTrust(data []byte) (*TrustManifest, error)

ValidateTrust validates the trust metadata in image data.

type ValidatorConfig

type ValidatorConfig struct {
	// VerifySignatures enables signature verification.
	// Requires a SignatureVerifier to be configured.
	VerifySignatures bool

	// VerifyHashes enables content hash verification.
	VerifyHashes bool

	// RequireProvenance requires at least one provenance record.
	RequireProvenance bool

	// RequireAssertions requires at least one authenticity assertion.
	RequireAssertions bool

	// MaxProvenanceRecords limits the number of provenance records.
	MaxProvenanceRecords int

	// MaxAssertions limits the number of assertions.
	MaxAssertions int

	// AllowExpiredCertificates allows validation with expired certificates.
	AllowExpiredCertificates bool
}

ValidatorConfig contains configuration options for the TrustValidator.

func DefaultValidatorConfig

func DefaultValidatorConfig() *ValidatorConfig

DefaultValidatorConfig returns a ValidatorConfig with sensible defaults.

Jump to

Keyboard shortcuts

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