admiralty

package module
v0.0.0-...-65155a5 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2026 License: GPL-2.0 Imports: 40 Imported by: 0

README

trust

TPM-anchored trust store and PKI authority for Sovereignite nodes. Extracted from github.com/sovereignite/sovereignite (internal/trust + cmd/trust).

The root package trust maintains a persistent, cryptographically self-describing store of node identities and their authorization state: it derives a stable peer identity from a TPM 2.0 key, issues and verifies identity records and authorization grants with domain-separated signatures, runs a CA over the node's trust domain, enforces mTLS and role policies, and records relationships and uncertain-revocation events to disk with strict directory-permission checks. The cmd/trust binary exposes the store as a long-lived gRPC service backed by the sibling keymanager for TPM key/certificate management.

Sibling modules github.com/sovereignite/armory, github.com/sovereignite/hull, github.com/sovereignite/anchor, and github.com/sovereignite/signal are resolved via local replace directives until they are published.

Build & test

go build ./...
go test ./...

Note: the test suite's directory-permission checks assume a standard umask (0022). With a group-writable umask (e.g. 0007), Go 1.26's t.TempDir() creates group-writable temp directories and the security checks reject them.

Deploy

  • kubernetes/sovereignite.io/trust/ — kustomize manifests (DaemonSet, namespace, service account).
  • .ko.yaml — ko build entry (main: ./cmd/trust, static, CGO_ENABLED=0).
  • os/systemd/sovereignite-admiralty.service — systemd unit.

License

GPL-2.0-only. See LICENSE.

Documentation

Overview

Package trust owns Sovereignite SPIFFE identity, adoption, ownership, certificate, revocation, federation, and public trust-state publication.

Index

Constants

View Source
const (
	// PathSPIFFEBundle is the exact public SPIFFE bundle path named by v5.
	PathSPIFFEBundle = "/spiffe-bundle.json"
	// PathOpenIDConfiguration is the exact public OIDC discovery mirror path.
	PathOpenIDConfiguration = "/.well-known/openid-configuration"
	// PathDeviceDocument is the exact public device metadata path.
	PathDeviceDocument = "/.well-known/sovereignite/device"
	// PathFederationDocument is the exact public federation metadata path.
	PathFederationDocument = "/.well-known/sovereignite/federation"
	// PathUpdateManifest is the exact public update manifest path.
	PathUpdateManifest = "/updates/manifest.json"
)
View Source
const (
	// DeviceSPIFFEPathPrefix is the only SPIFFE subject namespace fixed by the
	// Phase 2 domain core. Additional subject namespaces require an authorized
	// certificate hierarchy and profile decision.
	DeviceSPIFFEPathPrefix = "/device/"
)
View Source
const (
	// StateVersion is the sole durable trust-state schema understood here.
	StateVersion = 1
)

Variables

View Source
var (
	// ErrAuthorizationUnavailable means no authority-approved policy was
	// injected. The operation must remain disabled.
	ErrAuthorizationUnavailable = errors.New("trust authorization policy is unavailable")
	// ErrPublicationUnavailable means no public-only publication boundary was
	// injected.
	ErrPublicationUnavailable = errors.New("public trust-state publisher is unavailable")
	// ErrPublicationSchemaUnavailable means authoritative public protocol
	// document rendering remains unresolved.
	ErrPublicationSchemaUnavailable = errors.New("public trust-state schema builder is unavailable")
	// ErrRevisionConflict means another writer committed state first.
	ErrRevisionConflict = errors.New("trust state revision conflict")
	// ErrStateRollback means durable state predates or differs from its
	// monotonic revision anchor.
	ErrStateRollback = errors.New("trust state rollback detected")
	// ErrStaleGeneration means a caller or policy acted on older state.
	ErrStaleGeneration = errors.New("stale trust state generation")
	// ErrReplay means an authorization grant or publication was already used.
	ErrReplay = errors.New("trust operation replay rejected")
	// ErrNotAuthorized means the authenticated peer has no current authority.
	ErrNotAuthorized = errors.New("authenticated peer is not authorized")
	// ErrUnsupportedStateVersion means durable state was written by an
	// unsupported schema version.
	ErrUnsupportedStateVersion = errors.New("unsupported trust state version")
	// ErrMismatchedPublicKey means the supplied public key does not derive
	// the expected peer ID.
	ErrMismatchedPublicKey = errors.New("public key does not match the expected peer ID")
	// ErrMismatchedPeerID means the record peer ID does not match the local
	// device peer ID.
	ErrMismatchedPeerID = errors.New("identity record peer ID does not match the local device")
	// ErrMismatchedSPIFFEID means the SPIFFE ID is not correctly derived from
	// the trust domain and peer ID.
	ErrMismatchedSPIFFEID = errors.New("SPIFFE ID does not match the expected derivation")
	// ErrUnknownHandle means the TPM persistent handle is not a locally-known
	// handle.
	ErrUnknownHandle = errors.New("TPM persistent handle is unknown or foreign")
	// ErrInvalidPhaseTransition means the requested identity phase transition
	// is not permitted.
	ErrInvalidPhaseTransition = errors.New("identity phase transition is not permitted")
	// ErrIdentityAlreadyRevoked means the identity is already in the revoked
	// phase.
	ErrIdentityAlreadyRevoked = errors.New("identity is already revoked")
	// ErrStalePeerRecordEnvelope means the peer record envelope sequence is
	// older than the current record.
	ErrStalePeerRecordEnvelope = errors.New("peer record envelope sequence is stale")
)

Functions

func CRLPath

func CRLPath(timestamp time.Time) (string, error)

CRLPath constructs the sole public CRL path form using a canonical UTC second. The protocol authority and retention policy remain behind D-011.

func DeviceIdentityPath

func DeviceIdentityPath(canonicalPeerID string) (string, error)

DeviceIdentityPath constructs the sole per-device identity path.

func IdentityRecordToProto

func IdentityRecordToProto(record IdentityRecord) map[string]any

IdentityRecordToProto converts an internal IdentityRecord to the proto DeviceIdentity message.

func OCSPPath

func OCSPPath(statusID string) (string, error)

OCSPPath constructs the sole public OCSP path form. Status IDs are lowercase SHA-256 values: issued-certificate fingerprints or deterministic locators for serials whose post-sign outcome is uncertain.

func TrustDomainFromIPNS

func TrustDomainFromIPNS(canonicalIPNS string) (string, error)

TrustDomainFromIPNS validates and returns a canonical CIDv1/base36 IPNS identifier suitable for the SPIFFE trust-domain authority component.

func ValidateHandleOwnership

func ValidateHandleOwnership(record IdentityRecord, localHandle uint32) error

ValidateHandleOwnership verifies that the given handle is a locally-known TPM persistent handle, not a foreign or unknown handle.

func ValidateIdentityRecord

func ValidateIdentityRecord(record IdentityRecord, localPeerID string) error

ValidateIdentityRecord checks internal consistency of the identity record without external state.

func ValidatePublicKeyPeerIDConsistency

func ValidatePublicKeyPeerIDConsistency(
	publicKey libp2pcrypto.PubKey,
	expectedPeerID string,
) error

ValidatePublicKeyPeerIDConsistency verifies that a libp2p public key derives the expected peer ID.

func ValidateSPIFFEDerivation

func ValidateSPIFFEDerivation(record IdentityRecord) error

ValidateSPIFFEDerivation proves the SPIFFE ID is correctly derived from the trust domain and peer ID in the identity record.

Types

type AppliedGrant

type AppliedGrant struct {
	Digest    string    `json:"digest"`
	Operation Operation `json:"operation"`
	AppliedAt time.Time `json:"applied_at"`
}

AppliedGrant retains only a domain-separated digest for replay rejection.

type AuthorizationGrant

type AuthorizationGrant struct {
	GrantID              string
	ExpectedRevision     uint64
	ExpiresAt            time.Time
	OwnershipRole        OwnershipRole
	RelationshipPhase    RelationshipPhase
	RelatedRelationship  string
	LocalFederationRole  FederationRole
	RemoteFederationRole FederationRole
	SourceGeneration     uint64
	CertificateNotBefore time.Time
	CertificateNotAfter  time.Time
}

AuthorizationGrant is the smallest fail-closed result consumed by the domain core. GrantID is treated as sensitive approval material: only its domain-separated digest is persisted.

type AuthorizationIntent

type AuthorizationIntent struct {
	Operation         Operation
	Peer              VerifiedMTLSPeer
	LocalIdentity     DeviceIdentity
	TargetPeerID      string
	RelationshipID    string
	CertificateID     string
	RemoteTrustDomain string
	CurrentRevision   uint64
}

AuthorizationIntent is public-only input to the injected policy. The policy must bind any external approval transcript and proof of possession to this authenticated peer and the exact current revision.

type AuthorizationPolicy

type AuthorizationPolicy interface {
	Authorize(context.Context, AuthorizationIntent) (AuthorizationGrant, error)
}

AuthorizationPolicy supplies first-trust and all subsequent mutation authorization. A nil or typed-nil policy always denies every mutation.

The unresolved v5 first-trust transcript, issuer hierarchy, and federation topology decisions belong behind this boundary; implementations must never weaken mTLS to satisfy them.

type AuthorizationPolicyFunc

type AuthorizationPolicyFunc func(
	context.Context,
	AuthorizationIntent,
) (AuthorizationGrant, error)

AuthorizationPolicyFunc adapts a function to AuthorizationPolicy.

func (AuthorizationPolicyFunc) Authorize

Authorize implements AuthorizationPolicy.

type CertificateKeyManager

type CertificateKeyManager interface {
	Metadata(context.Context, armory.Role) (armory.KeyMetadata, error)
	IssueCertificate(context.Context, armory.CertificateRequest) ([]byte, error)
}

CertificateKeyManager is the narrow TPM-backed certificate boundary. The Trust service never receives a crypto.Signer or private-key bytes.

type CertificateRecord

type CertificateRecord struct {
	ID                  string            `json:"id"`
	RelationshipID      string            `json:"relationship_id,omitempty"`
	SPIFFEID            string            `json:"spiffe_id"`
	Serial              string            `json:"serial"`
	DER                 []byte            `json:"der"`
	SubjectPublicKeyDER []byte            `json:"subject_public_key_der"`
	NotBefore           time.Time         `json:"not_before"`
	NotAfter            time.Time         `json:"not_after"`
	Status              CertificateStatus `json:"status"`
	IssuedAt            time.Time         `json:"issued_at"`
	RevokedAt           time.Time         `json:"revoked_at,omitempty"`
}

CertificateRecord contains a public certificate and its local status.

type CertificateStatus

type CertificateStatus string

CertificateStatus is the local enforcement status of a public certificate.

const (
	CertificateStatusActive  CertificateStatus = "active"
	CertificateStatusRevoked CertificateStatus = "revoked"
)

type Clock

type Clock interface {
	Now() time.Time
}

Clock makes persisted transition times deterministic in tests.

type DeviceIdentity

type DeviceIdentity struct {
	CanonicalIPNS string `json:"canonical_ipns"`
	PeerID        string `json:"peer_id"`
	TrustDomain   string `json:"trust_domain"`
	SPIFFEID      string `json:"spiffe_id"`
}

DeviceIdentity is the immutable public binding between the canonical IPNS name, its canonical libp2p peer ID, and the corresponding SPIFFE ID.

func DeriveDeviceIdentity

func DeriveDeviceIdentity(
	canonicalIPNS string,
	canonicalPeerID string,
) (DeviceIdentity, error)

DeriveDeviceIdentity constructs the sole device SPIFFE form authorized by the bounded v5 interpretation:

spiffe://<canonical-IPNS-trust-domain>/device/<canonical-peer-id>

The CIDv1/base36 IPNS name and peer ID must encode the same libp2p identity.

func ParseDeviceSPIFFEID

func ParseDeviceSPIFFEID(raw string) (DeviceIdentity, error)

ParseDeviceSPIFFEID strictly parses the sole device subject namespace and proves that its trust domain and peer path encode the same identity.

type FederationMaterial

type FederationMaterial struct {
	RemoteCACertificateDER []byte
	SourceGeneration       uint64
}

FederationMaterial contains verified public remote CA input supplied by the unresolved authority-approved exchange. It contains no trust direction; direction remains an explicit policy grant and durable edge.

type FederationMaterialProvider

type FederationMaterialProvider interface {
	Fetch(
		context.Context,
		DeviceIdentity,
		string,
		VerifiedMTLSPeer,
	) (FederationMaterial, error)
}

FederationMaterialProvider supplies remote public CA input without adding a public RPC or inferring discovery data as authorization.

type FederationMaterialProviderFunc

type FederationMaterialProviderFunc func(
	context.Context,
	DeviceIdentity,
	string,
	VerifiedMTLSPeer,
) (FederationMaterial, error)

FederationMaterialProviderFunc adapts a function to the public-material provider seam.

func (FederationMaterialProviderFunc) Fetch

Fetch implements FederationMaterialProvider.

type FederationRecord

type FederationRecord struct {
	SourceDomain           string         `json:"source_domain"`
	TargetDomain           string         `json:"target_domain"`
	LocalRole              FederationRole `json:"local_role"`
	RemoteRole             FederationRole `json:"remote_role"`
	SourceGeneration       uint64         `json:"source_generation"`
	RemoteCACertificate    []byte         `json:"remote_ca_certificate"`
	CrossCertificate       []byte         `json:"cross_certificate,omitempty"`
	CrossCertificateID     string         `json:"cross_certificate_id,omitempty"`
	CrossCertificateSerial string         `json:"cross_certificate_serial,omitempty"`
	EstablishedAt          time.Time      `json:"established_at"`
	UpdatedAt              time.Time      `json:"updated_at"`
}

FederationRecord is one explicit directed edge. It never implies a reverse, transitive, or spoke-to-spoke edge.

type FederationRole

type FederationRole string

FederationRole records explicit hub-and-spoke membership. A directed edge is still required; membership never implies a reverse or spoke-to-spoke edge.

const (
	FederationRoleHub   FederationRole = "hub"
	FederationRoleSpoke FederationRole = "spoke"
)

type FileStore

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

FileStore persists one owner-only, bounded JSON snapshot and a monotonic digest/revision anchor using same-directory temporary files, fsync, atomic rename, and directory fsync. An advisory lock plus revision comparison serializes cooperating processes. The anchor detects restoration of an older state file; deployment storage must independently protect whole-directory rollback.

func NewFileStore

func NewFileStore(path string) (*FileStore, error)

NewFileStore constructs a durable trust store at an absolute or resolvable path. No state is read or written until Load or Commit.

func (*FileStore) Commit

func (s *FileStore) Commit(expectedRevision uint64, next Snapshot) error

Commit atomically replaces the complete snapshot only when the durable revision equals expectedRevision and next advances it by exactly one.

func (*FileStore) Load

func (s *FileStore) Load() (Snapshot, error)

Load returns a validated deep copy. A missing state file is the canonical revision-zero state; an unknown version is never rewritten.

type IdentityCondition

type IdentityCondition struct {
	Type               string    `json:"type"`
	Status             string    `json:"status"`
	Reason             string    `json:"reason"`
	Message            string    `json:"message"`
	LastTransitionTime time.Time `json:"last_transition_time"`
}

IdentityCondition records one observed property of the identity.

type IdentityEnvelope

type IdentityEnvelope struct {
	AddrInfo  peer.AddrInfo `json:"addr_info"`
	Sequence  uint64        `json:"sequence"`
	Addresses []string      `json:"addresses"`
}

IdentityEnvelope wraps a peer.PeerRecord with its canonical address info.

type IdentityPhase

type IdentityPhase string

IdentityPhase is the lifecycle state of a device identity record.

const (
	IdentityPhasePending IdentityPhase = "pending"
	IdentityPhaseActive  IdentityPhase = "active"
	IdentityPhaseRevoked IdentityPhase = "revoked"
)

type IdentityRecord

type IdentityRecord struct {
	PeerID             string              `json:"peer_id"`
	Addrs              []string            `json:"addrs"`
	Keys               []IdentityRecordKey `json:"keys"`
	Handle             uint32              `json:"handle"`
	Phase              IdentityPhase       `json:"phase"`
	PeerRecordSequence uint64              `json:"peer_record_sequence"`
	SPIFFEID           string              `json:"spiffe_id"`
	X509SVID           *X509SVID           `json:"x509_svid,omitempty"`
	Conditions         []IdentityCondition `json:"conditions"`
	Generation         uint64              `json:"generation"`
	ObservedGeneration uint64              `json:"observed_generation"`
}

IdentityRecord is the versioned internal Trust record that maps from libp2p peer.AddrInfo to a structured device identity. It never contains private keys, CRDs, or exportable key material.

func MapAddrInfoToIdentityRecord

func MapAddrInfoToIdentityRecord(
	addrInfo peer.AddrInfo,
	publicKey libp2pcrypto.PubKey,
	handle uint32,
	spiffeID string,
) (IdentityRecord, error)

MapAddrInfoToIdentityRecord maps a libp2p peer.AddrInfo to an internal IdentityRecord. It never copies private keys.

func MapPeerRecordToIdentityRecord

func MapPeerRecordToIdentityRecord(
	record IdentityRecord,
	envelope IdentityEnvelope,
) (IdentityRecord, error)

MapPeerRecordToIdentityRecord applies a signed peer.PeerRecord envelope to an existing identity record. The envelope sequence must be greater than or equal to the record's current peer record sequence.

func TransitionIdentityPhase

func TransitionIdentityPhase(
	record IdentityRecord,
	targetPhase IdentityPhase,
	now time.Time,
) (IdentityRecord, error)

TransitionIdentityPhase validates and applies a phase transition. Only authorized transitions are permitted: pending→active, active→revoked.

func ValidateX509SVID

func ValidateX509SVID(record IdentityRecord, certChain [][]byte) (IdentityRecord, error)

ValidateX509SVID maps and validates an X.509 certificate chain into the identity record's SVID field. It rejects private-key PEM blocks.

type IdentityRecordKey

type IdentityRecordKey struct {
	Type      string `json:"type"`
	RawBase64 string `json:"raw_base64"`
	TPMHandle string `json:"tpm_handle"`
}

IdentityRecordKey contains only public key material and a reference to the TPM persistent handle. It never contains private key bytes.

type Operation

type Operation string

Operation identifies one mutation that requires an explicit authorization decision. It is an internal domain value and does not add a public RPC.

const (
	OperationAdopt                Operation = "adopt"
	OperationRevokeRelationship   Operation = "revoke-relationship"
	OperationInitializeCA         Operation = "initialize-ca"
	OperationIssueMTLSCertificate Operation = "issue-mtls-certificate"
	OperationRevokeCertificate    Operation = "revoke-certificate"
	OperationFederate             Operation = "federate"
)

type OwnershipRole

type OwnershipRole string

OwnershipRole is the explicit authority held by one adopted principal.

const (
	OwnershipRoleOwner       OwnershipRole = "owner"
	OwnershipRoleBackupAdmin OwnershipRole = "backup-admin"
)

type PendingCertificate

type PendingCertificate struct {
	ID                  string    `json:"id"`
	GrantDigest         string    `json:"grant_digest"`
	Operation           Operation `json:"operation"`
	RelationshipID      string    `json:"relationship_id,omitempty"`
	RemoteTrustDomain   string    `json:"remote_trust_domain,omitempty"`
	SPIFFEID            string    `json:"spiffe_id"`
	Serial              string    `json:"serial"`
	SubjectPublicKeyDER []byte    `json:"subject_public_key_der"`
	NotBefore           time.Time `json:"not_before"`
	NotAfter            time.Time `json:"not_after"`
	CreatedAt           time.Time `json:"created_at"`
}

PendingCertificate reserves a serial before the TPM-backed issuer is called. A failed or uncertain operation is removed only after its serial is burned.

type PublicCertificate

type PublicCertificate struct {
	ID        string
	SPIFFEID  string
	Serial    string
	DER       []byte
	NotBefore time.Time
	NotAfter  time.Time
	Status    CertificateStatus
}

PublicCertificate is the public certificate subset available to a builder.

type PublicDocument

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

PublicDocument is an immutable public-only document whose path belongs to the mechanically closed v5 allowlist.

func NewPublicDocument

func NewPublicDocument(
	path string,
	mediaType string,
	content []byte,
) (PublicDocument, error)

NewPublicDocument validates one complete public document. Dynamic path components must already be in their canonical forms produced by OCSPPath, CRLPath, or DeviceIdentityPath.

func (PublicDocument) Content

func (d PublicDocument) Content() []byte

Content returns a copy of the public bytes.

func (PublicDocument) MarshalJSON

func (d PublicDocument) MarshalJSON() ([]byte, error)

MarshalJSON persists only the validated public representation.

func (PublicDocument) MediaType

func (d PublicDocument) MediaType() string

MediaType returns the exact media type required for this path family.

func (PublicDocument) Path

func (d PublicDocument) Path() string

Path returns the canonical public path.

func (*PublicDocument) UnmarshalJSON

func (d *PublicDocument) UnmarshalJSON(encoded []byte) error

UnmarshalJSON validates durable public bytes before accepting them.

type PublicFederation

type PublicFederation struct {
	SourceDomain           string
	TargetDomain           string
	SourceGeneration       uint64
	RemoteCACertificateDER []byte
	CrossCertificateDER    []byte
	EstablishedAt          time.Time
}

PublicFederation is one explicit directed, domain-keyed public edge.

type PublicRevocation

type PublicRevocation struct {
	StatusID       string
	CertificateID  string
	Serial         string
	Kind           RevocationKind
	CertificateDER []byte
	RevokedAt      time.Time
}

PublicRevocation is the public revocation subset available to a builder.

type PublicSnapshotBuilder

type PublicSnapshotBuilder interface {
	Build(context.Context, PublicStateView) ([]PublicDocument, error)
}

PublicSnapshotBuilder renders authority-approved protocol bytes. D-011 keeps production builders disabled until each protocol document's semantics are fixed. Every returned document is independently revalidated by Service.

type PublicStateView

type PublicStateView struct {
	Revision               uint64
	LocalIdentity          DeviceIdentity
	ActiveCACertificateDER []byte
	Certificates           []PublicCertificate
	Revocations            []PublicRevocation
	Federations            []PublicFederation
}

PublicStateView contains only state classified as public. Builders must not receive ownership principals, authorization grants, cluster state, or any private key material.

type Publication

type Publication struct {
	ID            string           `json:"id"`
	StateRevision uint64           `json:"state_revision"`
	IPNSName      string           `json:"ipns_name"`
	Digest        string           `json:"digest"`
	Documents     []PublicDocument `json:"documents"`
	CreatedAt     time.Time        `json:"created_at"`
}

Publication is one immutable, digest-bound public-only outbox item.

func (Publication) Clone

func (p Publication) Clone() Publication

Clone returns a deep copy safe for an injected publisher to retain.

func (Publication) Validate

func (p Publication) Validate() error

Validate independently proves the closed path allowlist, public-only document constraints, canonical IPNS name, deterministic ordering, ID, and digest. Publisher adapters should call it before importing any bytes.

type PublicationReceipt

type PublicationReceipt struct {
	PublicationID string
	Digest        string
	IPNSName      string
	RootCID       string
	IPNSSequence  uint64
}

PublicationReceipt proves what the publisher advanced. The service accepts it only when its identity, content digest, IPNS name, CID, and sequence match the pending item and current monotonic publication state.

type PublishedRecord

type PublishedRecord struct {
	Digest       string    `json:"digest"`
	RootCID      string    `json:"root_cid"`
	IPNSSequence uint64    `json:"ipns_sequence"`
	CompletedAt  time.Time `json:"completed_at"`
}

PublishedRecord binds a completed outbox item to its immutable CID and monotonic IPNS sequence.

type Publisher

type Publisher interface {
	Publish(context.Context, Publication) (PublicationReceipt, error)
}

Publisher atomically imports and publishes one immutable public snapshot. Repeated calls with the same Publication ID and digest must be idempotent.

type RelationshipPhase

type RelationshipPhase string

RelationshipPhase is the durable adoption/ownership state.

const (
	RelationshipPhaseProvisional RelationshipPhase = "provisional"
	RelationshipPhaseAuthorized  RelationshipPhase = "authorized"
	RelationshipPhaseRevoked     RelationshipPhase = "revoked"
)

type RelationshipRecord

type RelationshipRecord struct {
	ID                       string            `json:"id"`
	TargetPeerID             string            `json:"target_peer_id"`
	PrincipalSPIFFEID        string            `json:"principal_spiffe_id"`
	PrincipalCertificateHash string            `json:"principal_certificate_sha256"`
	Role                     OwnershipRole     `json:"role"`
	Phase                    RelationshipPhase `json:"phase"`
	Generation               uint64            `json:"generation"`
	EstablishedAt            time.Time         `json:"established_at"`
	UpdatedAt                time.Time         `json:"updated_at"`
}

RelationshipRecord is a durable ownership/adoption relationship. Approval protocol material is not persisted.

type RevocationKind

type RevocationKind string

RevocationKind distinguishes issued leaf certificates, retired federation cross-certificates, and serials whose post-sign outcome is uncertain.

const (
	RevocationKindMTLS      RevocationKind = "mtls"
	RevocationKindCross     RevocationKind = "cross-certificate"
	RevocationKindUncertain RevocationKind = "uncertain-serial"
)

type RevocationRecord

type RevocationRecord struct {
	CertificateID  string         `json:"certificate_id"`
	Serial         string         `json:"serial"`
	Kind           RevocationKind `json:"kind"`
	CertificateDER []byte         `json:"certificate_der"`
	RevokedAt      time.Time      `json:"revoked_at"`
}

RevocationRecord contains only public local revocation status.

type Service

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

Service owns the durable Trust domain core.

func NewService

func NewService(config ServiceConfig) (*Service, error)

NewService validates immutable identity and safety bounds without performing I/O. Missing policy/builder/publisher/issuer seams are retained so read-only startup can explain the exact fail-closed gate.

func (*Service) AdoptDevice

func (s *Service) AdoptDevice(
	ctx context.Context,
	state tls.ConnectionState,
	targetPeerID string,
) (RelationshipRecord, error)

AdoptDevice applies an injected authorization grant to the exact local target selected by the committed RPC. The caller is derived exclusively from a verified mutual-TLS client certificate.

func (*Service) DrainOutbox

func (s *Service) DrainOutbox(ctx context.Context) error

DrainOutbox publishes pending immutable snapshots serially. A publisher failure leaves the item durable; a post-publish commit failure causes replay of the same ID and digest, which Publisher must handle idempotently.

func (*Service) Federate

func (s *Service) Federate(
	ctx context.Context,
	state tls.ConnectionState,
	remoteTrustDomain string,
) (FederationRecord, error)

Federate creates exactly one directed local-to-remote hub/spoke edge and a TPM-signed cross-certificate. No reverse, transitive, authorization, or route edge is inferred.

func (*Service) GetFederations

func (s *Service) GetFederations() ([]FederationRecord, error)

GetFederations returns explicit directed edges sorted by target domain.

func (*Service) GetTrustRelationships

func (s *Service) GetTrustRelationships() ([]RelationshipRecord, error)

GetTrustRelationships returns only currently authorized relationships. Provisional and revoked records remain internal because the committed proto has no phase field for them.

func (*Service) InitializeLocalCA

func (s *Service) InitializeLocalCA(ctx context.Context) ([]byte, error)

InitializeLocalCA creates the device-local CA only through the TPM-backed Key Manager boundary. It remains disabled unless the injected policy and public schema builder authorize the unresolved production hierarchy.

func (*Service) IssueLocalMTLSCertificate

func (s *Service) IssueLocalMTLSCertificate(ctx context.Context) ([]byte, error)

IssueLocalMTLSCertificate issues only the canonical local device identity. Mobile/client subject namespaces and enrollment remain blocked by D-004 and are not generalized here.

func (*Service) Open

func (s *Service) Open(ctx context.Context) error

Open loads and validates durable state. First open atomically binds the state root to the configured lifetime identity.

func (*Service) RevokeCertificate

func (s *Service) RevokeCertificate(
	ctx context.Context,
	state tls.ConnectionState,
	certificateID string,
) error

RevokeCertificate enforces local revocation before its outbox is drained.

func (*Service) RevokeTrust

func (s *Service) RevokeTrust(
	ctx context.Context,
	state tls.ConnectionState,
	relationshipID string,
) error

RevokeTrust atomically revokes one relationship and every certificate bound to it before public publication is attempted.

func (*Service) Snapshot

func (s *Service) Snapshot() (Snapshot, error)

Snapshot returns a validated deep copy for internal inspection and tests.

type ServiceConfig

type ServiceConfig struct {
	Identity                   DeviceIdentity
	Store                      Store
	KeyManager                 CertificateKeyManager
	Policy                     AuthorizationPolicy
	FederationMaterial         FederationMaterialProvider
	PublicSnapshotBuilder      PublicSnapshotBuilder
	Publisher                  Publisher
	Clock                      Clock
	MaximumGrantLifetime       time.Duration
	MaximumCertificateLifetime time.Duration
}

ServiceConfig contains only internal dependencies and fixed limits. It does not define a listener or extend the sovereignite.v1 API.

type Snapshot

type Snapshot struct {
	Version             int                           `json:"version"`
	Revision            uint64                        `json:"revision"`
	Identity            DeviceIdentity                `json:"identity"`
	NextSerial          uint64                        `json:"next_serial"`
	ActiveCACertificate []byte                        `json:"active_ca_certificate,omitempty"`
	ActiveCAID          string                        `json:"active_ca_id,omitempty"`
	Relationships       map[string]RelationshipRecord `json:"relationships"`
	Certificates        map[string]CertificateRecord  `json:"certificates"`
	PendingCertificates map[string]PendingCertificate `json:"pending_certificates"`
	BurnedSerials       map[string]time.Time          `json:"burned_serials"`
	Revocations         map[string]RevocationRecord   `json:"revocations"`
	Federations         map[string]FederationRecord   `json:"federations"`
	Bundles             map[string]TrustBundleRecord  `json:"bundles"`
	AppliedGrants       map[string]AppliedGrant       `json:"applied_grants"`
	Outbox              map[string]Publication        `json:"outbox"`
	Published           map[string]PublishedRecord    `json:"published"`
	LastIPNSSequence    uint64                        `json:"last_ipns_sequence"`
	LastPublishedRoot   string                        `json:"last_published_root,omitempty"`
}

Snapshot is the complete public/state-only durable trust document.

type Store

type Store interface {
	Load() (Snapshot, error)
	Commit(expectedRevision uint64, next Snapshot) error
}

Store provides revision-checked atomic persistence. Implementations must reject a stale expected revision instead of overwriting a concurrent writer.

type TrustBundleRecord

type TrustBundleRecord struct {
	TrustDomain    string    `json:"trust_domain"`
	Generation     uint64    `json:"generation"`
	CACertificates [][]byte  `json:"ca_certificates"`
	UpdatedAt      time.Time `json:"updated_at"`
}

TrustBundleRecord keeps every authority keyed by its trust domain. Bundles are never merged into an undifferentiated CA pool.

type TrustServer

type TrustServer struct {
	pb.UnimplementedTrustServer
	// contains filtered or unexported fields
}

TrustServer implements the sovereignite.v1.Trust gRPC service by delegating to the trust domain Service. Every mutating RPC extracts the mTLS peer from the gRPC transport credentials and forwards it to the domain layer.

func NewTrustServer

func NewTrustServer(svc *Service) *TrustServer

NewTrustServer wraps a pre-configured trust Service for gRPC exposure.

func (*TrustServer) AdoptDevice

func (s *TrustServer) AdoptDevice(
	ctx context.Context,
	req *pb.AdoptDeviceRequest,
) (*pb.AdoptDeviceResponse, error)

AdoptDevice accepts an mTLS-authenticated adoption request and creates or transitions a trust relationship.

func (*TrustServer) Federate

func (s *TrustServer) Federate(
	ctx context.Context,
	req *pb.FederateRequest,
) (*pb.FederateResponse, error)

Federate creates one directed local-to-remote hub/spoke federation edge.

func (*TrustServer) GetTrustRelationships

func (s *TrustServer) GetTrustRelationships(
	ctx context.Context,
	_ *emptypb.Empty,
) (*pb.TrustRelationshipsResponse, error)

GetTrustRelationships returns every currently authorized relationship and federation edge.

func (*TrustServer) RevokeTrust

func (s *TrustServer) RevokeTrust(
	ctx context.Context,
	req *pb.RevokeTrustRequest,
) (*emptypb.Empty, error)

RevokeTrust atomically revokes one relationship and every certificate bound to it.

type VerifiedMTLSPeer

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

VerifiedMTLSPeer is immutable evidence extracted from a TLS 1.3 connection whose client certificate has a verified chain. It intentionally contains no private key or authorization decision.

func VerifyMutualTLSPeer

func VerifyMutualTLSPeer(
	state tls.ConnectionState,
	now time.Time,
) (VerifiedMTLSPeer, error)

VerifyMutualTLSPeer rejects plaintext, server-authentication-only, unverified, expired, CA, wrong-usage, or noncanonical peer certificates. First-trust authorization is a separate mandatory injected policy decision.

func (VerifiedMTLSPeer) CertificateDER

func (p VerifiedMTLSPeer) CertificateDER() []byte

CertificateDER returns a copy of the authenticated leaf certificate.

func (VerifiedMTLSPeer) CertificateSHA256

func (p VerifiedMTLSPeer) CertificateSHA256() [sha256.Size]byte

CertificateSHA256 returns the authenticated leaf certificate fingerprint.

func (VerifiedMTLSPeer) Identity

func (p VerifiedMTLSPeer) Identity() DeviceIdentity

Identity returns the authenticated canonical device identity.

func (VerifiedMTLSPeer) NotAfter

func (p VerifiedMTLSPeer) NotAfter() time.Time

NotAfter returns the authenticated leaf validity end.

func (VerifiedMTLSPeer) NotBefore

func (p VerifiedMTLSPeer) NotBefore() time.Time

NotBefore returns the authenticated leaf validity start.

func (VerifiedMTLSPeer) SubjectPublicKeySHA256

func (p VerifiedMTLSPeer) SubjectPublicKeySHA256() [sha256.Size]byte

SubjectPublicKeySHA256 returns the leaf SubjectPublicKeyInfo fingerprint.

type X509SVID

type X509SVID struct {
	CertificateChain [][]byte  `json:"certificate_chain"`
	Expiry           time.Time `json:"expiry"`
}

X509SVID contains public X.509 certificate chain material.

Directories

Path Synopsis
cmd
admiralty command

Jump to

Keyboard shortcuts

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