gw

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2026 License: Apache-2.0 Imports: 45 Imported by: 0

README

varwof-gateway-core

Shared security engine library — unified mTLS, CRL, OCSP, TSA, RBAC, audit, metrics, and decision capabilities for gateway-tcp/http/udp.

⚠️ Preview — Not for production use. APIs and features may change before official release.

License Go Reference

中文

What is varwof-gateway-core?

Shared security engine library providing unified mTLS, CRL, OCSP, TSA, RBAC, audit, metrics, decision, and short-lived certificate capabilities for gateway-tcp/http/udp. Pure Go, zero external dependencies.

Quick Start

import gw "github.com/varwof/gateway-core"

// CRL cache
caCert, _ := gw.LoadCACert("ca.pem")
crlCache := gw.NewCRLCache(caCert, "http://crl.example.com/ca.crl", 1800, nil, "zh")

// RBAC
roles := gw.ExtractRoles(cert)
if !gw.CheckRole(roles, []string{"gateway:admin"}) {
    // reject
}

// Audit log
audit, _ := gw.NewAuditLogger("/var/log/pki/audit.log", nil, 100*1024*1024, 3)
audit.Log(gw.AuditEntry{Action: "connection_allowed", ClientCN: "user@example.com"})

Installation

go get github.com/varwof/gateway-core@v0.1.0

Core Modules

Module Description
CRL/OCSP Cache Certificate revocation list + online status query
TSA Client RFC 3161 timestamp request and verification
RBAC Role extraction from certificate OU
Audit Log JSON Lines + Merkle hash chain
Metrics Prometheus Counter/Gauge/Histogram
Unified Pipeline CRL → OCSP → RBAC → AIC → constraints → plugins
Policy Versioning Monotonic version + history + branch control

Ecosystem

graph TB
    subgraph varwof["varwof Ecosystem"]
        core["core"]
        tcp["gateway-tcp"]
        http["gateway-http"]
        udp["gateway-udp"]
        gwcore["gateway-core<br/>Security Engine"]
    end
    tcp --> gwcore
    http --> gwcore
    udp --> gwcore
    gwcore -->|mTLS API| core

gateway-core is the shared security engine layer for the three gateways. This project is a member of the Open Invention Network.

Homepage https://varwof.com
Community https://varwof.org
IETF Draft draft-wei-aic-identity-cert
License Apache-2.0
Member Open Invention Network

Documentation

Overview

Package gw provides the shared security engine for varwof gateways.

Capability plugin types (CapabilityPlugin, PluginContext, PluginResult, PluginDecision, HTTPFacts, PluginRegistry) are defined in the types module and re-exported here for backward compatibility.

Package gw provides the shared gateway core library for the varwof project.

Index

Constants

View Source
const (
	// SM2ReasonParseCert 证书/链 DER 解析失败(含截断、非证书内容)。
	SM2ReasonParseCert = "sm2_verify_parse_certificate"
	// SM2ReasonNotSM2Cert 证书签名算法不是 SM2-with-SM3(OID 501)。
	SM2ReasonNotSM2Cert = "sm2_verify_not_sm2_certificate"
	// SM2ReasonParsePublicKey 公钥 DER 解析失败。
	SM2ReasonParsePublicKey = "sm2_verify_parse_public_key"
	// SM2ReasonPublicKeyType 公钥不是 SM2 曲线(拒绝,不静默放行)。
	SM2ReasonPublicKeyType = "sm2_verify_unsupported_public_key"
	// SM2ReasonSignature 单签名验证失败或入参为空。
	SM2ReasonSignature = "sm2_verify_signature"
	// SM2ReasonChainBuild 链构建失败(超深/成环,防证书风暴)。
	SM2ReasonChainBuild = "sm2_verify_chain_not_built"
	// SM2ReasonChainSignature 链上某级签名验签失败。
	SM2ReasonChainSignature = "sm2_verify_chain_signature"
	// SM2ReasonChainUntrusted 链无法终止于受信根(找不到签发者/不受信)。
	SM2ReasonChainUntrusted = "sm2_verify_chain_untrusted"
	// SM2ReasonMixedChain 链中出现非国密成员(叶子/中间件非 501 签名或根非
	// SM2 密钥)。
	SM2ReasonMixedChain = "sm2_verify_mixed_chain"
	// SM2ReasonChainValidity 证书有效期校验失败(未生效/已过期)。
	SM2ReasonChainValidity = "sm2_verify_chain_validity"
	// SM2ReasonMissingAIC 要求携带 AIC 扩展但缺失。
	SM2ReasonMissingAIC = "sm2_verify_missing_aic"
	// SM2ReasonNotSupported 当前构建未启用 gmsm(stub 专用)。
	SM2ReasonNotSupported = "sm2_verify_not_supported"
)

SM2 验证核心的稳定原因码。原因码是稳定的 snake_case 标识(与网关既有 拒绝原因风格一致),可原样写入审计 deny_reason 或 Admin 上报;适配层不得 依赖错误文案,只依赖原因码。

View Source
const (
	// Transport protocols (layer 4)
	ProtocolTCP  = "tcp"  // TCP transparent proxy
	ProtocolUDP  = "udp"  // UDP packet forwarder
	ProtocolQUIC = "quic" // QUIC transport (UDP-based, built-in TLS 1.3)

	// Application protocols over TCP (layer 7)
	ProtocolHTTP1 = "http1" // HTTP/1.1
	ProtocolHTTP2 = "http2" // HTTP/2 (TLS)
	ProtocolH2C   = "h2c"   // HTTP/2 cleartext (no TLS)
	ProtocolGRPC  = "grpc"  // gRPC (HTTP/2 + proto)
	ProtocolWS    = "ws"    // WebSocket (HTTP upgrade)
	ProtocolWSS   = "wss"   // WebSocket over TLS

	// Application protocols over UDP (layer 7)
	ProtocolDTLS = "dtls" // DTLS (Datagram TLS)
	ProtocolH3   = "h3"   // HTTP/3 (QUIC + HTTP/2 framing)
)
View Source
const (
	TLSModeNone   = "none"   // No TLS (plaintext)
	TLSModeServer = "server" // Server certificate only (one-way)
	TLSModeMTLS   = "mtls"   // Mutual TLS (two-way)
)
View Source
const (
	OCSPFallbackAllow = "allow"
	OCSPFallbackDeny  = "deny"
	OCSPFallbackCRL   = "crl"
)

OCSPFallbackAllow/Deny/CRL are OCSP fallback policy constants.

View Source
const (
	PluginTypeAllowlist = "allowlist"
	PluginTypeDenylist  = "denylist"
	PluginTypeRBAC      = "rbac"
	PluginTypeWebhook   = "webhook"
)

PluginTypeAllowlist/Denylist/RBAC/Webhook are built-in plugin type names.

View Source
const (
	RoleAdmin  = "gateway:admin"
	RoleOps    = "gateway:ops"
	RoleAudit  = "gateway:audit"
	RoleDeploy = "gateway:deploy"
	RoleRead   = "gateway:read"
	RoleWild   = "gateway:*"
)

RoleAdmin/Ops/Audit/Deploy/Read/Wild are role constants.

View Source
const CompletedHeaderValue = "completed"

CompletedHeaderValue is the value of the task completion signal.

View Source
const ConstraintAuditRequiredKey = "op:audit:required"

ConstraintAuditRequiredKey is the capabilityId for audit-required operation constraint.

View Source
const ConstraintCIDRKey = "network:cidr"

ConstraintCIDRKey is the capabilityId for IP network range constraint.

View Source
const ConstraintConcurrentKey = "session:max-concurrent"

ConstraintConcurrentKey is the capabilityId for max concurrent connections constraint.

View Source
const ConstraintGeoFenceKey = "geo-fence"

ConstraintGeoFenceKey is the capabilityId for geo fence constraint.

View Source
const ConstraintHardTimeoutKey = "session:hard-timeout"

ConstraintHardTimeoutKey is the capabilityId for session hard timeout constraint.

View Source
const ConstraintIdleTimeoutKey = "session:idle-timeout"

ConstraintIdleTimeoutKey is the capabilityId for session idle timeout constraint.

View Source
const ConstraintReadOnlyKey = "op:readonly"

ConstraintReadOnlyKey is the capabilityId for read-only operation constraint.

View Source
const ConstraintTimeWindowKey = "time:window"

ConstraintTimeWindowKey is the capabilityId for time window constraint.

View Source
const DefaultConnExpiryCheckInterval = 5 * time.Second

DefaultConnExpiryCheckInterval is the default polling interval for the expiry check goroutine (P2-A-14: 5 seconds).

View Source
const DefaultDAAgeMax = 30 * time.Second

DefaultDAAgeMax is the default value for the DelegationAuthorization.timestamp freshness window (specification P1-B-13 / dev-docs/aic/06-delegation-auth.md §validation flow ①: |now - timestamp| ≤ 30s).

View Source
const DefaultMaskRune = '*'

DefaultMaskRune is the character used to replace sensitive content.

View Source
const DefaultMaxChainLength = 8

DefaultMaxChainLength is the default upper bound for maximum delegation chain length (anti-certificate-bomb, P1-B-15). Chains exceeding this are rejected (specification maxDepth is set by the top Principal; this serves as the gateway-side hard limit). Real-world Agent delegation depths are typically 2–3 levels; default 8 provides ample margin.

View Source
const DefaultRenewInterval = 30 * time.Second

DefaultRenewInterval is the default renewal check interval.

View Source
const DefaultRenewPct = 0.10

DefaultRenewPct is the renewal threshold percentage (spec P2-A-11 / P2-D-02: renewal is triggered when remaining validity falls below 10% of total validity).

View Source
const DefaultRenewWindow = 2 * time.Minute

DefaultRenewWindow is the default renewal window (minutes before expiry).

View Source
const DefaultRenewalConfirmTimeout = 24 * time.Hour

DefaultRenewalConfirmTimeout is the default timeout for confirmed renewal awaiting responsible party confirmation (24 hours). After timeout, the request automatically transitions to Rejected, preventing state machine deadlock.

View Source
const HardTimeoutMax = 86400

HardTimeoutMax is the maximum value for session:hard-timeout (seconds).

View Source
const HardTimeoutMin = 60

HardTimeoutMin is the minimum value for session:hard-timeout (seconds).

View Source
const HeaderTaskID = "X-AIC-Task-Id"

HeaderTaskID is the header name for identifying the task ID in requests (A3).

View Source
const HeaderTaskStatus = "X-AIC-Task-Status"

HeaderTaskStatus is the header name for carrying the task completion signal in requests (A4).

View Source
const IdleTimeoutMax = 3600

IdleTimeoutMax is the maximum value for session:idle-timeout (seconds).

View Source
const IdleTimeoutMin = 30

IdleTimeoutMin is the minimum value for session:idle-timeout (seconds).

View Source
const MaxAmplificationDefault = 16

MaxAmplificationDefault is the default response amplification factor applied when UDPExtra.MaxAmplification is unset. See UDPExtra.MaxAmplification.

View Source
const MaxConcurrentMax = 1024

MaxConcurrentMax is the maximum value for the max parameter of the max-concurrent constraint (patent P1-A-29).

View Source
const MaxConcurrentMin = 1

MaxConcurrentMin is the minimum value for the max parameter of the max-concurrent constraint (patent P1-A-29).

View Source
const MaxPostingsPerKey = 1000

MaxPostingsPerKey caps the number of hash postings kept under a single by_cn / by_serial / by_word key (finding 23). Without a bound these postings lists grow forever on high-activity keys (common CN, common word).

View Source
const OfflineLifetimeLimit = time.Hour

OfflineLifetimeLimit is the maximum remaining certificate validity enforced in offline mode (G2(b): ≤1h).

View Source
const RolePrefix = "gateway:"

RolePrefix is the gateway role OU prefix.

Variables

View Source
var (
	OIDSigECDSAWithSHA256  = pki.OIDSigECDSAWithSHA256
	OIDSigECDSAWithSHA384  = pki.OIDSigECDSAWithSHA384
	OIDSigECDSAWithSHA512  = pki.OIDSigECDSAWithSHA512
	OIDSigRSAWithSHA256    = pki.OIDSigRSAWithSHA256
	OIDSigRSAWithSHA384    = pki.OIDSigRSAWithSHA384
	OIDSigRSAWithSHA512    = pki.OIDSigRSAWithSHA512
	OIDSigRSAPSSWithSHA256 = pki.OIDSigRSAPSSWithSHA256
	OIDSigEd25519          = pki.OIDSigEd25519
	OIDSHA256              = pki.OIDSHA256
	OIDSHA384              = pki.OIDSHA384
	OIDSHA512              = pki.OIDSHA512
)

OID re-exports — signature algorithm OIDs.

View Source
var (
	// OIDSM3 是 SM3 杂凑算法 OID(GM/T 0004)。
	OIDSM3 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 401}
	// OIDSM2Curve 是 SM2 椭圆曲线(推荐参数 sm2p256v1)OID(GM/T 0003)。
	OIDSM2Curve = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 301}
	// OIDSM2WithSM3 是纯 SM2-with-SM3 签名算法 OID,X.509 证书与 CMS 中为国密
	// 证书链/主体签名标注(GM/T 0003.5 §A.2)。
	OIDSM2WithSM3 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 501}
)

国密对象标识符(GB/T 15629 / GM/T 0003 / SM 系列标准)。

View Source
var (
	MetricAICAdmissionTotal    = NewMetricCounter("aic_admission_total", "Total AIC admission checks", "decision")
	MetricAICActiveAgents      = NewMetricGauge("aic_active_agents", "Currently active AIC agents")
	MetricAICCertIssuedTotal   = NewMetricCounter("aic_cert_issued_total", "Total AIC certificates issued")
	MetricAICCertRevokedTotal  = NewMetricCounter("aic_cert_revoked_total", "Total AIC certificates revoked")
	MetricAICRenewalTotal      = NewMetricCounter("aic_renewal_total", "Total AIC certificate renewals")
	MetricAICAdmissionDuration = NewMetricHistogram("aic_admission_duration_ms", "AIC admission check duration in milliseconds", []string{}, 1, 5, 10, 25, 50, 100, 250, 500, 1000)
	MetricAICBufferQueueDepth  = NewMetricGauge("aic_buffer_queue_depth", "Current AIC capability buffer queue depth")
)

AIC metric declarations (spec §6.4).

View Source
var (
	AIAOID  = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 1}
	OCSPOID = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
)

AIAOID is the Authority Information Access method OID. OCSPOID is the OCSP responder OID.

View Source
var ErrNoTask = fmt.Errorf("task not found")

ErrNoTask is returned by complete-by-serial lookups when the task is unknown.

View Source
var ErrSM2NotSupported = errors.New("SM2 not supported: build with -tags gmsm")

ErrSM2NotSupported 是默认构建(无 -tags gmsm)下所有国密入口返回的哨兵错误, 与 core 仓库 gmsm_stub 的文案保持一致,保证 fail-closed。

View Source
var OIDRenewalToken = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 66257, 1, 6}

OIDRenewalToken is the OID for the RenewalToken extension (1.3.6.1.4.1.66257.1.6).

SecureCipherSuites is the list of secure cipher suites (GCM/CHACHA).

View Source
var Version = "0.1.0"

Version is the package version, set via -ldflags -X github.com/varwof/gateway-core.Version=x.y.z.

Functions

func AICFingerprint

func AICFingerprint(cert *x509.Certificate) string

AICFingerprint computes the SHA-256 hex fingerprint of the AIC extension DER encoding in the certificate. Returns empty string if the certificate has no AIC extension (audit field uses omitempty, keeping old entries readable).

func ApplyJSONConfig

func ApplyJSONConfig[T any](target *T) func([]byte) error

ApplyJSONConfig is a generic configuration application function for updating configuration objects after JSON deserialization. Usage example:

var cfg MyConfig
watcher := NewConfigWatcher(url, tlsCfg, 30*time.Second, ApplyJSONConfig(&cfg))

func ArchiveAuditFile

func ArchiveAuditFile(path string) error

ArchiveAuditFile archives (compress-rotates) the audit log file.

func AuditDuration

func AuditDuration(start time.Time, entry *AuditEntry)

AuditDuration computes and sets the duration of an audit entry.

func BaseTLSConfig

func BaseTLSConfig(cipherSuites []string, minTLSVersion string) *tls.Config

BaseTLSConfig creates a base TLS configuration.

func BuildCipherSuites

func BuildCipherSuites(names []string) []uint16

BuildCipherSuites builds a cipher suite list from name strings.

func BuildPluginsFromConfig

func BuildPluginsFromConfig(reg *PluginRegistry, cfgs PluginConfigs) error

BuildPluginsFromConfig builds plugins from configuration and registers them to the registry. Resets first then registers all, ensuring a complete rebuild after config changes.

func CheckAuthorizationConstraints

func CheckAuthorizationConstraints(constraints []Capability, clientIP string) error

CheckAuthorizationConstraints performs offline validation of authorizationConstraints. Supports: network:cidr (requires ClientIP), time:window, geo-fence (requires ClientIP), session:max-concurrent, session:hard-timeout, session:idle-timeout, op:readonly, op:audit:required. Unknown constraint types are ignored by default (forward compatible); the caller logs audit warnings; after registering a custom constraint executor (RegisterConstraint), it will be recognized and executed.

func CheckAuthorizationConstraintsAt

func CheckAuthorizationConstraintsAt(constraints []Capability, clientIP, timeHHMM string) error

CheckAuthorizationConstraintsAt is the same as CheckAuthorizationConstraints, but evaluates time-window constraints at a specified UTC time (HH:MM), useful for testing and offline decision demonstrations. When timeHHMM is empty, uses the current time. The tz field in time-window is converted to the corresponding timezone during evaluation.

func CheckDAFreshness

func CheckDAFreshness(ts time.Time, now time.Time, maxAge time.Duration) error

CheckDAFreshness validates that DelegationAuthorization.timestamp is within the freshness window. When now is nil, uses time.Now(); when maxAge <= 0, uses DefaultDAAgeMax. Zero-value timestamp (never set) is treated as expired.

func CheckDelegatedAgentCert

func CheckDelegatedAgentCert(cert *x509.Certificate) string

CheckDelegatedAgentCert validates the legitimacy of a Delegated-Agent certificate (for non-HTTP protocols like TCP). Returns empty string on success, non-empty rejection reason on failure.

A certificate that merely carries the "Delegated-Agent" OU is not legitimate on its own (finding 17): the OU is a plaintext subject attribute anyone can mint, so a Delegated-Agent cert must additionally be core-signed (carry a valid AIC extension) and be within its validity window. Certificates without the OU are not delegated-agent certs and pass through.

func CheckDelegatedAgentHeaders deprecated

func CheckDelegatedAgentHeaders(cert *x509.Certificate, r *http.Request) string

Deprecated: CheckDelegatedAgentHeaders validates the X-Agent-User/X-Agent-TTL headers of a Delegated-Agent certificate (B1 username delegation path). The username cannot be cryptographically bound to the certificate; identity propagation has been changed to B2 (X-Client-Cert-DER certificate passthrough). This function is kept for legacy client compatibility only. Certificates without Delegated-Agent OU pass through directly. Returns empty string on success, non-empty rejection reason on failure.

Security note (G4): The client's X-Agent-User / X-Agent-TTL headers are entirely controlled by the requestor and must never be trusted as the true identity of the proxied user. This function only performs "declarative" validation (prompting ops to configure the delegation channel). The real delegation identity is derived by DelegatedAgentServerIdentity from the core-signed AIC/GatewaySession, and the gateway overwrites X-Agent-User / X-Agent-TTL headers before forwarding.

func CheckRole

func CheckRole(roles []string, allowed []string) bool

CheckRole checks whether the role list contains an allowed role.

func ClientTLSConfig

func ClientTLSConfig(caCertFile, certFile, keyFile string, cipherSuites []string, minTLSVersion string) (*tls.Config, error)

ClientTLSConfig creates an mTLS client-side configuration.

func ConstraintRecheckLoop

func ConstraintRecheckLoop(aicConstraints, paConstraints []Capability, clientIP string, interval time.Duration, done <-chan struct{}, onViolation func(reason string))

ConstraintRecheckLoop periodically re-evaluates authorizationConstraints (G3: constraint timing consistency).

Constraints on long-lived data plane connections like TCP are only checked once at handshake; time-window / revocation constraints that expire over time cease to be effective after crossing the window — for example, a "weekdays 9-18 only" connection established during the night window remains active during the day. This function re-evaluates the authorizationConstraints of both AIC and PrincipalAuthorization at the given interval (using the current time), calling onViolation when a constraint is no longer met (gateway disconnects and audits accordingly). Stops when done is closed (idempotent).

Any single constraint evaluation failure is treated as a violation; a and pa may both be nil/empty (skipping the corresponding set). Callers should ensure onViolation is non-nil (nil internally only logs, no actual action).

func DAHash

func DAHash(cert *x509.Certificate) string

DAHash computes the SHA-256 hex hash of the DelegationAuthorization signatureValue in the AIC (authorization evidence fingerprint). Returns empty string if AIC is missing or has no DA signature.

func DAHashFromAIC

func DAHashFromAIC(aic *AIC) string

DAHashFromAIC computes the SHA-256 hash of the DelegationAuthorization signatureValue for a parsed AIC. Returns empty string if no DA signature is present.

func DecodeBase64

func DecodeBase64(s string) ([]byte, error)

DecodeBase64 performs Base64 decoding.

func DelegatedAgentServerIdentity

func DelegatedAgentServerIdentity(cert *x509.Certificate, principal string) (user string, expiry time.Time, reason string)

DelegatedAgentServerIdentity derives the server-asserted delegation identity from the core-signed certificate extension (AIC), preventing G4 identity spoofing: never trust client-supplied plaintext headers. Returns:

  • user: the server-asserted proxied subject (from AIC.PrincipalUid or cert CN/OU fallback)
  • expiry: delegation validity deadline (zero time.Time{} when no hard-timeout constraint)
  • reason: non-empty rejection reason (illegal conditions other than missing Delegated-Agent OU)

func EffectiveDelegationCapabilities

func EffectiveDelegationCapabilities(chain []*x509.Certificate, principalCaps []pki.Capability, maxChainLen int) ([]pki.Capability, error)

EffectiveDelegationCapabilities validates per-level capability subsets and computes the intersection along the delegation chain (P1-B-16/17).

chain goes top-down: chain[0]=topmost delegated Agent, chain[len-1]=bottom Agent. principalCaps is the effective capabilities P of the original principal (top Principal). Returns C_eff = P ∩ C_1 ∩ … ∩ C_n.

Process: eff = P; for each level C_i, first verify C_i ⊆ eff (permissions only decrease, escalation is rejected), then eff = filterCovered(C_i, eff) (retain this level's capabilities that are authorized by eff).

Note: This function only performs capability semantic validation; signature verification is handled separately by Verify.

func EffectiveDelegationCapabilitiesFromAIC

func EffectiveDelegationCapabilitiesFromAIC(chain []*x509.Certificate, topPrincipal *x509.Certificate, maxChainLen int) ([]pki.Capability, error)

EffectiveDelegationCapabilitiesFromAIC is a convenience entry point: extracts AIC.capabilities from the top Principal certificate as P, then recursively computes the intersection. Chain signature verification is performed separately by the caller.

func EncodeBase64

func EncodeBase64(data []byte) string

EncodeBase64 performs Base64 encoding.

func ExtractOCSPURL

func ExtractOCSPURL(cert *x509.Certificate) string

ExtractOCSPURL extracts the OCSP URL from the certificate's AIA extension.

func ExtractPolicyRoles

func ExtractPolicyRoles(cert *x509.Certificate) []string

ExtractPolicyRoles extracts policy roles from the certificate OU. Uses the global authorization policy's (if set) OU→role mapping to resolve role names; when no policy is set, falls back to the hardcoded ExtractRoles (only identifies gateway: prefix OUs). Returned role names include both policy role names and original gateway:* OUs (if present), for compatibility with both configuration styles.

func ExtractRoles

func ExtractRoles(cert *x509.Certificate) []string

ExtractRoles extracts the gateway role list from the certificate OU.

func ExtractSPIFFEIDFromCert

func ExtractSPIFFEIDFromCert(cert *x509.Certificate) string

ExtractSPIFFEIDFromCert extracts a SPIFFE ID from a certificate's SAN URIs. Returns "" if no SPIFFE URI is found.

func FetchOCSPResponseRaw

func FetchOCSPResponseRaw(cert, issuer *x509.Certificate, ocspURL string) ([]byte, error)

FetchOCSPResponseRaw fetches the raw OCSP response bytes.

func FilterAuditFile

func FilterAuditFile(file string, since time.Time, action string, cn, serial, mapping string) error

FilterAuditFile filters the audit file by conditions and prints matching entries.

func FindStartOffsetByTime

func FindStartOffsetByTime(file string, target time.Time) (int64, error)

FindStartOffsetByTime binary-searches for the file offset corresponding to a given time.

func HasAIC

func HasAIC(cert *x509.Certificate) bool

HasAIC reports whether the certificate carries a valid AIC extension (G2: short-lived certificate identification). Malformed AIC returns false (such certificates are denied in the admission pipeline and will not enter the data plane).

func HasDelegatedAgentOU

func HasDelegatedAgentOU(cert *x509.Certificate) bool

HasDelegatedAgentOU is the exported wrapper of hasDelegatedAgentOU, for gateways to check delegation identity before forwarding.

func HashLeaf

func HashLeaf(data []byte) []byte

HashLeaf computes the SHA256 hash of a Merkle tree leaf node. Finding 22: the leaf is domain-separated (prefix 0x00) from internal node hashes so a leaf hash can never be presented as an internal node hash or vice versa.

func HashNode

func HashNode(left, right []byte) []byte

HashNode computes the SHA256 hash of a Merkle tree internal node. Finding 22: internal nodes use a distinct domain prefix (0x01) so lone-leaf roots (HashLeaf, 0x00) cannot collide with node hashes.

func IsAdminOU

func IsAdminOU(ou string) bool

IsAdminOU checks whether the OU is an admin role (compatible with gateway:admin and bare admin).

func IsReloadSignal

func IsReloadSignal(sig os.Signal) bool

IsReloadSignal checks whether the signal is SIGHUP hot-reload.

func IsSM2Certificate added in v0.5.0

func IsSM2Certificate(der []byte) bool

IsSM2Certificate 默认构建下报告 false(无法识别即失败,fail-closed)。

func KeyHashHex

func KeyHashHex(cert *x509.Certificate) string

KeyHashHex returns the certificate SPKI SHA-256 hash (hex), used for AIC PrincipalUid.KeyHash cross-validation.

func LoadCA

func LoadCA(caCertFile string) (*x509.CertPool, error)

LoadCA loads a CA certificate pool and validates that every certificate in the bundle is a CA.

func LoadCACert

func LoadCACert(caCertFile string) (*x509.Certificate, error)

LoadCACert loads and parses a single CA certificate (first PEM block).

func LoadCAFromFile

func LoadCAFromFile(path string) (*x509.CertPool, error)

LoadCAFromFile loads a PEM CA chain into a CertPool.

func LoadCert

func LoadCert(certFile, keyFile string) (*tls.Certificate, error)

LoadCert loads a TLS certificate key pair.

func LoadGatewayPolicy

func LoadGatewayPolicy(policyPath, sigSuffix string, opts *PolicyVerifyOptions, require bool) error

LoadGatewayPolicy loads and sets the gateway authorization policy. If authorization_file is configured, loads it (with signature verification); opts=nil skips signature verification. On successful load, sets the global policy via SetAuthorizationPolicy. On failure, if require=true returns an error; otherwise degrades by keeping the existing policy.

func LogAdmission

func LogAdmission(result AdmissionResult, clientIP string, logger *slog.Logger)

LogAdmission records the admission decision log.

func LogPluginDecision

func LogPluginDecision(logger *AuditLogger, entry PluginAuditEntry)

LogPluginDecision writes a plugin decision event to the audit log. Deny and execution errors are logged as WARN, allow as INFO (spec P2-A-28). When entry.Level is empty, it is inferred from Decision ("allow"→INFO, others→WARN).

func MTLSServerConfig

func MTLSServerConfig(caCertFile string, cert *tls.Certificate, cipherSuites []string, minTLSVersion string) (*tls.Config, error)

MTLSServerConfig creates an mTLS server-side configuration.

func MakeConfirmedRenewalConfirmHandler

func MakeConfirmedRenewalConfirmHandler(m *ConfirmedRenewalManager, tr Translator, lang string) http.HandlerFunc

MakeConfirmedRenewalConfirmHandler returns a handler for responsible-party renewal confirmation (POST /api/v1/gateway/renewal/confirm, RoleOps/RoleAdmin). Request body: {session_id, principal_cert_pem, da{...}} — DA is re-signed by the responsible party using their private key via SignRenewalDA (new nonce/timestamp/requestedLifetime). Gateway verifies DA signature + permission recheck (capabilities ⊆ PA grants), rejecting renewal on escalation (P2-A-17).

func MakeConfirmedRenewalRejectHandler

func MakeConfirmedRenewalRejectHandler(m *ConfirmedRenewalManager, tr Translator, lang string) http.HandlerFunc

MakeConfirmedRenewalRejectHandler returns a handler for rejecting renewal (POST /api/v1/gateway/renewal/reject, RoleAdmin).

func MakeConfirmedRenewalRequestHandler

func MakeConfirmedRenewalRequestHandler(m *ConfirmedRenewalManager, tr Translator, lang string) http.HandlerFunc

MakeConfirmedRenewalRequestHandler returns a handler for initiating confirmed renewal (POST /api/v1/gateway/renewal/request, RoleOps/RoleAdmin). Request body: {session_id, ca, cn, san, agent_id, principal_uid, old_serial, validity, profile, capabilities[]} After triggering renewal, enters "awaiting responsible party confirmation" state (P2-A-12).

func MakeConfirmedRenewalStatusHandler

func MakeConfirmedRenewalStatusHandler(m *ConfirmedRenewalManager, tr Translator, lang string) http.HandlerFunc

MakeConfirmedRenewalStatusHandler returns a handler for querying confirmed renewal status (GET /api/v1/gateway/renewal/status, RoleOps/RoleAdmin).

func MakeDisconnectByAgentHandler

func MakeDisconnectByAgentHandler(registry *ConnRegistry, tr Translator, lang string) http.HandlerFunc

MakeDisconnectByAgentHandler returns an HTTP handler that disconnects all connections for a given agent_id. Request: POST with JSON body {"agent_id": "..."}.

func MakeDisconnectByUserHandler

func MakeDisconnectByUserHandler(registry *ConnRegistry, tr Translator, lang string) http.HandlerFunc

MakeDisconnectByUserHandler returns an HTTP handler that disconnects all connections for a given principalUid. Request: POST with JSON body {"principal_uid": "..."}.

func MarshalTSARequest

func MarshalTSARequest(req TimeStampReq) ([]byte, error)

MarshalTSARequest serializes a TSA request to DER.

func MaskCertSerial

func MaskCertSerial(serial string) string

MaskCertSerial masks a certificate serial number, keeping only the last 4 hex chars. Example: "A1:B2:C3:D4:E5:F6" → "**********E5:F6"

func MaskEmail

func MaskEmail(email string) string

MaskEmail masks an email address, keeping domain visible. Example: "alice@example.com" → "a***e@example.com"

func MaskFilePath

func MaskFilePath(path string) string

MaskFilePath masks the filename portion of a path, keeping the directory. Example: "/etc/pki/certs/secret.pem" → "/etc/pki/certs/********.pem"

func MaskString

func MaskString(s string, visible int) string

MaskString replaces all but the last `visible` characters with the mask rune. If the input is shorter than visible, it returns the input unchanged. If visible is 0, the entire string is masked. Returns empty string unchanged.

func MaskToken

func MaskToken(token string) string

MaskToken masks an API token or key, keeping only first and last 4 chars for long tokens, and proportionally fewer for short tokens so that at least half of the token is always masked (finding 21: a 9-char token must not reveal 8 chars). Example: "sk-abc123def456ghi789" → "sk-a*******i789"

func MatchCapability

func MatchCapability(id, pattern string) bool

MatchCapability checks whether a capability matches a pattern (supports * and a:b:* prefix).

func MatchCapabilityPriority

func MatchCapabilityPriority(id, pattern string) int

MatchCapabilityPriority checks whether id matches pattern and returns a five-level priority (pki.MatchPriorityExact .. MatchPriorityGlobal, 0 means no match). Semantics: capabilityId is segmented by ':', '*' matches a single segment, '**' crosses segments, priority: exact(5) > single-segment(4) > multi-segment(3) > scheme(2) > global(1).

func MatchCapabilityRules

func MatchCapabilityRules(id string, rules []pki.CapabilityRule) pki.CapabilityRuleMatch

MatchCapabilityRules makes a decision within a rule set (allow + deny) by priority: takes the highest-priority matching rule; at equal priority, deny takes precedence over allow. Returns Matched=false when no rule matches.

func MustVerifyCurrentExecutable

func MustVerifyCurrentExecutable(roots *x509.CertPool)

MustVerifyCurrentExecutable is like VerifyCurrentExecutable, but prints the error and terminates the process (os.Exit(1)) on verification failure. Typical usage is to call it as the first line in main():

gw.MustVerifyCurrentExecutable(roots)

If the target program has not deployed a <self-path>.p7s signature file, it will fail to start (fail-closed).

func NeedRenew

func NeedRenew(cert *x509.Certificate, renewalWindow time.Duration) bool

NeedRenew checks whether a certificate is within the renewal window.

func NeedRenewPct

func NeedRenewPct(cert *x509.Certificate, pct float64) bool

NeedRenewPct checks whether a certificate has entered the renewal window, taking the earlier of two triggers (concurrent semantics, spec P2-A-11):

  • Percentage threshold: remaining validity ≤ total validity × pct (pct<=0 uses DefaultRenewPct)
  • Fixed window fallback: remaining validity ≤ DefaultRenewWindow (2 minutes, prevents ultra-short validity certificates from never triggering at the 10% threshold)

Falls back to the fixed window when NotBefore is missing.

func NeedRevoke

func NeedRevoke(cert *x509.Certificate) bool

NeedRevoke checks whether a certificate needs proactive revocation.

func NewChainHTTPClient

func NewChainHTTPClient(tlsConfig *tls.Config) *http.Client

NewChainHTTPClient creates an HTTP client for chain reference synchronization based on mTLS configuration. Falls back to a default client when tlsConfig is nil.

func NewReplayNonceStore added in v0.4.0

func NewReplayNonceStore(ttl time.Duration, max int) *memReplayStore

NewReplayNonceStore returns a process-local replay-protection store. Nonces are retained for ttl (default 24h) and at most max entries (default 4096); beyond that the oldest are evicted. The store is intended for single-node gateways; multi-node deployments should share a distributed nonce store instead.

func NormalizeSerial

func NormalizeSerial(serial *big.Int) string

NormalizeSerial converts a certificate serial number to standard hex format (uppercase, no 0x prefix, zero-padded to 40 characters).

func OfflineLifetimeFor

func OfflineLifetimeFor(ocspFallback string) time.Duration

OfflineLifetimeFor returns the enforced offline limit based on the OCSP fallback policy. OCSPFallbackAllow (fail-open) and OCSPFallbackCRL (crl data can lag a recent revocation) → 1h cap; deny/disabled → 0 (not enforced; deny is fail-closed). Called by the gateway when constructing PipelineConfig.OfflineMaxCertLifetime.

func PEMRootPool

func PEMRootPool(pemData []byte) (*x509.CertPool, error)

PEMRootPool builds a CertPool from PEM-encoded CA certificates.

func ParseCertPEM

func ParseCertPEM(data []byte) (*x509.Certificate, error)

ParseCertPEM parses the first certificate from PEM bytes.

func ParseCertPEMFile

func ParseCertPEMFile(path string) (*x509.Certificate, error)

ParseCertPEMFile reads and parses a PEM certificate file.

func ParsePEMCert

func ParsePEMCert(data []byte) (*x509.Certificate, error)

ParsePEMCert parses a PEM-encoded certificate.

func ParsePrivateKeyPEM

func ParsePrivateKeyPEM(data []byte) (crypto.Signer, error)

ParsePrivateKeyPEM parses a PEM private key (PKCS#1/PKCS#8/EC/RSA).

func ParsePrivateKeyPEMFile

func ParsePrivateKeyPEMFile(path string) (crypto.Signer, error)

ParsePrivateKeyPEMFile reads and parses a PEM private key file.

func ParseSM2Certificate added in v0.5.0

func ParseSM2Certificate(der []byte) (*x509.Certificate, error)

ParseSM2Certificate 默认构建下不可用。

func PeerCertRoles

func PeerCertRoles(r *http.Request) []string

PeerCertRoles extracts roles from the first peer certificate in the request's TLS connection. Returns nil if the request has no TLS or no peer certs.

func PluginTypeName

func PluginTypeName(p CapabilityPlugin) string

PluginTypeName returns the human-readable type name of a plugin.

func RegisterConstraint

func RegisterConstraint(ev ConstraintEvaluator) error

RegisterConstraint registers a constraint evaluator in the global registry (extension point).

func RegisterCounter

func RegisterCounter(m *MetricCounter)

RegisterCounter registers a counter in the global metric registry.

func RegisterGauge

func RegisterGauge(m *MetricGauge)

RegisterGauge registers a gauge in the global metric registry.

func RegisterGeoResolver

func RegisterGeoResolver(name string, fn GeoResolver)

RegisterGeoResolver registers a custom geographic resolver (extension point) for use in the geo-fence resolver mode (e.g. third-party geographic databases like ip2region).

func RegisterHistogram

func RegisterHistogram(m *MetricHistogram)

RegisterHistogram registers a histogram in the global metric registry.

func RegisterParameterValidator

func RegisterParameterValidator(v ParameterValidator) error

RegisterParameterValidator registers a validator in the built-in parameter boundary validator registry.

func RegisterPlugin

func RegisterPlugin(p CapabilityPlugin) error

RegisterPlugin registers a plugin in the global registry.

func RegisterReloadSignal

func RegisterReloadSignal(sigCh chan os.Signal)

RegisterReloadSignal registers the SIGHUP hot-reload signal.

func RenderMetrics

func RenderMetrics(buildInfo string) string

RenderMetrics outputs metrics in Prometheus text format.

func RenewalLoop

func RenewalLoop(cfg *IssueConfig, cn, san string, certFile, keyFile string, renewWindow, checkInterval time.Duration, stopCh <-chan struct{}, onRenew func())

RenewalLoop periodically checks and automatically renews short-lived certificates.

func ReplaceConstraint

func ReplaceConstraint(ev ConstraintEvaluator) error

ReplaceConstraint replaces an evaluator in the global registry (hot update extension point).

func RequireRoles

func RequireRoles(r *http.Request, allowedRoles []string) bool

RequireRoles checks whether the mTLS peer certificate in the request carries at least one of the given allowedRoles. It is a convenience wrapper around PeerCertRoles + CheckRole for HTTP handler middleware.

func ResetConstraints

func ResetConstraints()

ResetConstraints clears the global registry and re-registers built-in types (for testing only).

func ResetParameterValidators

func ResetParameterValidators()

ResetParameterValidators clears the built-in parameter boundary validator registry (testing only).

func ResetPlugins

func ResetPlugins()

ResetPlugins clears the global registry (testing only).

func SanitizeString

func SanitizeString(s string) string

SanitizeString removes non-printable characters and trims whitespace. Useful for sanitizing user input before logging.

func ServerTLSConfig

func ServerTLSConfig(cert *tls.Certificate, cipherSuites []string, minTLSVersion string) *tls.Config

ServerTLSConfig creates a server-side TLS configuration.

func SetAuthorizationPolicy

func SetAuthorizationPolicy(p *AuthorizationPolicy)

SetAuthorizationPolicy sets the global authorization policy.

func SetGlobalCapabilityRegistry

func SetGlobalCapabilityRegistry(cr CapabilityRegistry)

SetGlobalCapabilityRegistry sets the package-level default capability registry. Passing nil clears it (disables capability registration validation).

func SignPolicy

func SignPolicy(policyData []byte, cert *x509.Certificate, signer crypto.Signer) ([]byte, error)

SignPolicy uses an admin identity to create a PKCS#7 detached signature (SHA-256) for policy data, returning .sig DER. signer must be a crypto.Signer (supports RSA/ECDSA/Ed25519).

func SignerHasAdminOU

func SignerHasAdminOU(cert *x509.Certificate) bool

SignerHasAdminOU checks whether the signer certificate carries the admin OU.

func StartOCSPStapling

func StartOCSPStapling(tlsCert *tls.Certificate, cfg *tls.Config, caCertFile string, stopCh <-chan struct{}, translator Translator, lang string)

StartOCSPStapling starts the OCSP stapling background refresh.

func SynthesizeCertFromJWT added in v0.3.0

func SynthesizeCertFromJWT(outer *aicjwt.OuterClaims) (*x509.Certificate, error)

SynthesizeCertFromJWT builds an X.509 certificate carrying the AIC claims of an AIC-JWT, so downstream certificate-based pipeline stages (CheckAdmission, capability matching, audit) work unchanged.

func TLSVersionFromString

func TLSVersionFromString(s string) uint16

TLSVersionFromString converts a version string to a TLS version number.

func TaskCompletedFromHeader

func TaskCompletedFromHeader(h func(string) string, fallbackID string) (string, bool)

TaskCompletedFromHeader detects whether a request carries a task completion signal (HeaderTaskStatus == completed). Returns the taskID and whether it is completed. taskID prefers the explicit HeaderTaskID; when absent, falls back to fallbackID (for simple scenarios without task IDs, revoking directly by certificate).

func TaskIDFromHeader

func TaskIDFromHeader(h func(string) string) string

TaskIDFromHeader extracts the task ID (HeaderTaskID) from a request; returns "" if absent.

func TrackDuration

func TrackDuration(start time.Time, d *DurationTracker)

TrackDuration computes elapsed time from a start point and records it.

func ValidateAIC

func ValidateAIC(aic *AIC) error

ValidateAIC delegates to pki-types.

func VerifyAuditEntry

func VerifyAuditEntry(data []byte, tsaClient *TSAClient) error

VerifyAuditEntry verifies the TSA timestamp signature of an audit entry.

func VerifyBelongTo

func VerifyBelongTo(handshake, auth *x509.Certificate, roots *x509.CertPool) error

VerifyBelongTo verifies that the handshake certificate and authorization certificate are strongly bound to the same Agent (G4).

Parameters:

  • handshake: the handshake certificate presented at the TLS layer (its chain has already been verified by the gateway trust roots during the handshake);
  • auth: the authorization certificate presented at the application layer (full AIC);
  • roots: the gateway trust root pool (same as used for verifying the handshake certificate chain); when nil, chain verification is skipped, but SPKI and same-CA checks are still enforced.

Returns an error if any assertion fails (Fail-Close). AgentId extraction is only used for logging and does not participate in the decision.

func VerifyBundle

func VerifyBundle(bundle *CredentialBundle, roots *x509.CertPool) error

VerifyBundle verifies the credential bundle dual chain (P1-B-29):

  • Agent chain → trust root (default client authentication EKU);
  • Principal chain → same trust root;
  • keyHash match: AIC.PrincipalUid.KeyHash == SHA256(Principal SPKI).

roots is the trust root pool; if empty, falls back to bundle.CACerts. Returns an error if any verification step fails.

func VerifyCurrentExecutable

func VerifyCurrentExecutable(roots *x509.CertPool) error

VerifyCurrentExecutable verifies the currently running executable. Uses os.Executable() to locate itself; the signature file defaults to exePath+".p7s". Suitable for calling at program startup: returns nil on success, detailed error on failure.

func VerifyDelegationAuth

func VerifyDelegationAuth(aic *AIC, userCert *x509.Certificate, agentCert *x509.Certificate) error

VerifyDelegationAuth verifies the validity of a DelegationAuthorization signature. aic must contain a non-empty DelegationAuthorization; userCert is the authorizing user's certificate; agentCert is the certificate carrying the AIC, whose SPKI the DA version 2 agentKeyBinding covers. The signed content is the DelegationAuthTBS DER encoding (a specific subset, not the entire AIC).

func VerifyDelegationChain

func VerifyDelegationChain(chain []*x509.Certificate, topPrincipal *x509.Certificate, maxDepth int) error

VerifyDelegationChain is a convenience entry point: creates a default verifier and verifies the chain. chain goes from top to bottom: chain[0]=top-level delegating Agent, chain[len-1]=bottom-level Agent. maxDepth is set by the top Principal.

func VerifyDelegationChainWithCaps

func VerifyDelegationChainWithCaps(chain []*x509.Certificate, topPrincipal *x509.Certificate, principalCaps []pki.Capability, maxDepth, maxChainLen int) ([]pki.Capability, error)

VerifyDelegationChainWithCaps verifies a multi-level delegation chain and computes the effective capability intersection:

  • Basic signature verification (bottom-up per level) and depth limits;
  • Anti-cycle (serial number deduplication within chain);
  • Anti-certificate-bomb (chain length upper bound);
  • Per-level capability subset validation + C_eff recursive intersection.

maxDepth is set by the top Principal (≤0 means no limit); maxChainLen is the gateway-side hard upper bound (≤0 uses DefaultMaxChainLength). Returns C_eff = P ∩ C_1 ∩ … ∩ C_n.

func VerifyLayer2

func VerifyLayer2(chain []*x509.Certificate, cfg *PipelineConfig, roles []string) (AdmissionResult, *Layer2Result)

VerifyLayer2 performs Layer 2 representation verification: AIC parsing + PA parsing + delegation representation check (completed within CheckAdmission). Returns AdmissionResult and Layer2Result.

func VerifyPrincipalKeyHash

func VerifyPrincipalKeyHash(agent, principal *x509.Certificate) error

VerifyPrincipalKeyHash verifies that AIC.PrincipalUid.KeyHash matches the SHA-256 of the principal certificate's SPKI. Returns an error (fail-close) if keyHash is missing or empty.

func VerifyProof

func VerifyProof(leaf []byte, proof []ProofStep, root []byte) bool

VerifyProof verifies a Merkle audit proof.

func VerifyProofBounded added in v0.4.0

func VerifyProofBounded(leaf []byte, proof []ProofStep, root []byte, maxProofLen int) bool

VerifyProofBounded is like VerifyProof but enforces a maximum proof length (finding 22): a proof for a tree with n leaves has at most ceil(log2 n) steps, so any longer proof is rejected regardless of hash match.

func VerifySM2CertificateChain added in v0.5.0

func VerifySM2CertificateChain(leafDER []byte, intermediates, roots [][]byte, nows ...time.Time) (*x509.Certificate, error)

VerifySM2CertificateChain 默认构建下不可用。

func VerifySM2Signature added in v0.5.0

func VerifySM2Signature(pub, digest, sig []byte) error

VerifySM2Signature 默认构建下不可用。

func VerifySPIFFESAN

func VerifySPIFFESAN(cert *x509.Certificate, expectedID string) bool

VerifySPIFFESAN validates that a certificate carries the expected SPIFFE ID in its SAN URIs. Because SPIFFE trust domains are case-insensitive (RFC 7555 §2.1), both the certificate value and the expected ID are compared in canonical form: trust domain lowercased, path compared verbatim.

func VerifySelf

func VerifySelf(exePath string, roots *x509.CertPool) (*x509.Certificate, error)

VerifySelf verifies the detached signature of the executable itself. exePath is the path to the binary to verify; the signature file defaults to exePath+".p7s". On success, returns the signer certificate for further OU/validity checks by the caller.

func VerifySelfWithOptions

func VerifySelfWithOptions(exePath string, opts SelfVerifyOptions) (*x509.Certificate, error)

VerifySelfWithOptions is the extended version of VerifySelf, supporting custom signature file paths.

func VerifySignedBinary

func VerifySignedBinary(data, sig []byte, roots *x509.CertPool) (*x509.Certificate, error)

VerifySignedBinary verifies a PKCS#7 detached signature over binary data. On success, returns the signer certificate; when roots is non-nil, performs additional chain validation.

func VerifySignedPolicy

func VerifySignedPolicy(sigDER, policyData []byte, roots *x509.CertPool, requireAdminOU bool) (*x509.Certificate, error)

VerifySignedPolicy verifies a PKCS#7 detached signature (policyData is the raw policy bytes). Returns the signer certificate on success, for further OU/status checks by the caller.

func WriteMgmtError

func WriteMgmtError(w http.ResponseWriter, status int, message string)

WriteMgmtError writes a management API JSON error response.

func WriteMgmtJSON

func WriteMgmtJSON(w http.ResponseWriter, status int, v interface{})

WriteMgmtJSON writes a management API JSON success response.

Types

type AIC

type AIC = pki.AIC

── Type aliases ──

func ParseAIC

func ParseAIC(cert *x509.Certificate) (*AIC, error)

ParseAIC delegates to pki-types.

type AdmissionConfig

type AdmissionConfig struct {
	// RequireAIC when set to true rejects connections without AIC extension.
	RequireAIC bool
	// RequiredProtocol requires the Agent to have the specified protocol capability (empty = no check).
	RequiredProtocol string
	// RequiredRuleId requires the Agent to have the specified CapabilityId permission (empty = no check).
	RequiredRuleId string
	// RequiredCapabilities requires the Agent to have all specified CapabilityIds (empty = no check).
	RequiredCapabilities []string
	// DisallowRepresentative when set to true rejects DelegationRepresentative mode connections.
	DisallowRepresentative bool
	// RequireUserPermission when set to true rejects connections without UserPermission extension.
	RequireUserPermission bool
	// RejectOverflow when set to true rejects AIC containing CapabilityIds not authorized by UserPermission.
	RejectOverflow bool
	// RequireUserAuth when set to true requires DelegationAuthorization signature verification in the AIC.
	RequireUserAuth bool
	// EnforceCapSizeConstraints when set to true validates Capability field lengths (schemeId 1-128, capabilityId 1-256, parameters 0-4096).
	EnforceCapSizeConstraints bool
	// NonceCache is used for DelegationAuthorization nonce replay protection.
	// nil means skip nonce replay check (not recommended).
	NonceCache *NonceCache
	// EnforceSize32 when set to true validates Nonce is exactly 32 bytes.
	EnforceSize32 bool
	// UserCert is the authorized user's certificate for verifying DelegationAuthorization signatures.
	// When nil, if UserCertResolver is not nil, resolves via KeyHash from varwof-core;
	// otherwise falls back to the connection peer certificate (only agent == user can verify).
	UserCert *x509.Certificate
	// UserCertResolver resolves user certificates based on PrincipalUid.KeyHash (via varwof-core API).
	// Automatically called when UserCert is nil and RequireUserAuth is true.
	UserCertResolver func(keyHash []byte) (*x509.Certificate, error)
	// EnforceConstraints when set to true enforces authorizationConstraints (CIDR/time window/concurrency).
	EnforceConstraints bool
	// StrictConstraints when set to true directly rejects connections with unregistered constraint types
	// in authorizationConstraints (unknown capabilityId under constraint/constraint-v1 scheme),
	// fail-closed. Default false only logs audit warnings for unknown constraints and ignores them
	// (forward compatible, specification P1-B-23 strict mode).
	StrictConstraints bool
	// ClientIP is used for authorizationConstraints allowed-cidr checks.
	ClientIP string
	// AuditLogger is used for authorization decision audit logging. When non-nil, logs warnings
	// for unknown constraint types, etc.
	AuditLogger *AuditLogger
	// CheckDAAge when set to true validates DelegationAuthorization.timestamp freshness
	// (|now - timestamp| ≤ DAAgeMax). Default off — specification delegates lifecycle validation
	// to X.509 NotAfter (dev-docs/aic/06-delegation-auth.md §validation flow (gateway runtime));
	// deployments requiring stricter time window defense (specification P1-B-13) can enable this.
	CheckDAAge bool
	// DAAgeMax is the DA timestamp freshness window (|now - timestamp| ≤ DAAgeMax).
	// Only effective when CheckDAAge=true; <=0 uses DefaultDAAgeMax (30 seconds).
	DAAgeMax time.Duration
	// CredentialBundle is the client-submitted credential bundle (P1-B-27/P1-B-29/P2-A-01).
	// When RequireUserAuth is true and UserCert is nil, prioritizes the Principal certificate
	// from the credential bundle for DA signature verification (including keyHash cross-validation);
	// falls back to UserCertResolver when missing.
	CredentialBundle *CredentialBundle
}

AdmissionConfig is the configuration for the admission engine.

func (AdmissionConfig) Validate

func (c AdmissionConfig) Validate() error

Validate checks the configuration for conflicting options.

type AdmissionResult

type AdmissionResult struct {
	Decision               DecisionResult
	Reason                 string
	AIC                    *AIC
	PrincipalAuthorization *PrincipalAuthorization
	PrincipalUid           string
	// EffectiveCaps is the P∩C (AIC declarations ∩ PA grants) intersection result,
	// preserving full Capability (including SchemeId/Parameters). When no PA is present,
	// equals the full AIC declarations. Phase two plugin evaluation only acts on this set
	// — declarations outside the intersection (including unrelated schemes) do not participate
	// in decisions or block connections (P2-A-06/P2-A-07 operation-level mapping).
	EffectiveCaps []Capability
}

AdmissionResult contains the complete admission check result.

func CheckAdmission

func CheckAdmission(cert *x509.Certificate, cfg AdmissionConfig) AdmissionResult
  1. Parse GatewaySession extension
  2. Verify AgentType is in the allowed list
  3. Check protocol capability match
  4. Check RuleId permission
  5. Check required capability subset
  6. Check delegation mode
  7. Parse UserPermission extension
  8. Check merge with UserPermission

Returns AdmissionResult; caller decides whether to allow based on the Decision field.

type AggregateSource

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

AggregateSource is an aggregated metric data source that manages multiple sub-metrics.

func NewAggregateSource

func NewAggregateSource() *AggregateSource

NewAggregateSource creates an aggregated metric data source.

func (*AggregateSource) Name

func (a *AggregateSource) Name() string

Name returns the aggregate source name.

func (*AggregateSource) Set

func (a *AggregateSource) Set(name string, val float64)

Set sets or updates the value of a sub-metric.

func (*AggregateSource) Value

func (a *AggregateSource) Value() (float64, bool)

Value returns the aggregate source value (always returns false).

type AlarmClient

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

AlarmClient is the alarm client that periodically checks rules and sends notifications.

func NewAlarmClient

func NewAlarmClient(cfg *AlarmConfig) *AlarmClient

NewAlarmClient creates an AlarmClient instance.

func (*AlarmClient) AddSource

func (a *AlarmClient) AddSource(s AlarmSource)

AddSource registers an alarm data source.

func (*AlarmClient) Start

func (a *AlarmClient) Start(stopCh chan struct{})

Start starts the alarm check loop.

func (*AlarmClient) Stop

func (a *AlarmClient) Stop()

Stop stops the alarm check loop.

type AlarmConfig

type AlarmConfig struct {
	// Rules is the list of alarm rules.
	Rules []AlarmRule `json:"rules"`
	// Receivers is the list of alarm receivers.
	Receivers []AlarmReceiver `json:"receivers"`
	// Interval is the alarm check interval.
	Interval int `json:"interval_sec,omitempty"`
}

AlarmConfig is the alarm configuration.

type AlarmReceiver

type AlarmReceiver struct {
	// Name is the receiver name.
	Name string `json:"name"`
	// Type is the notification type (e.g., webhook).
	Type string `json:"type"`
	// Webhook is the webhook callback URL.
	Webhook string `json:"webhook"`
	// Secret is the webhook signing secret (masked).
	Secret string `json:"secret,omitempty"`
}

AlarmReceiver defines an alarm receiver.

type AlarmRule

type AlarmRule struct {
	// Name is the rule name.
	Name string `json:"name"`
	// Metric is the monitoring metric name.
	Metric string `json:"metric"`
	// Operator is the threshold comparison operator (> / < / >= / <=).
	Operator string `json:"operator"`
	// Threshold is the alarm threshold value.
	Threshold float64 `json:"threshold"`
	// Cooldown is the alarm cooldown duration.
	Cooldown int `json:"cooldown_sec,omitempty"`
	// Receiver is the alarm receiver name.
	Receiver string `json:"receiver"`
}

AlarmRule defines a single alarm rule.

type AlarmSource

type AlarmSource interface {
	Name() string
	Value() (float64, bool)
}

AlarmSource is the alarm data source interface that provides metric names and values.

type AlgorithmIdentifier

type AlgorithmIdentifier = pki.AlgorithmIdentifier

── Type aliases ──

type AuditAction

type AuditAction string

AuditAction represents the action type of an audit event.

const (
	// ActionConnected indicates the client has connected.
	ActionConnected AuditAction = "connected"
	// ActionDisconnected indicates the client has disconnected.
	ActionDisconnected AuditAction = "disconnected"
	// ActionDenied indicates the connection was rejected.
	ActionDenied AuditAction = "denied"
	// ActionRevoked indicates the certificate has been revoked.
	ActionRevoked AuditAction = "revoked"
	// ActionProxied indicates the proxy forwarding has been established.
	ActionProxied AuditAction = "proxied"
	// ActionCompleted indicates the proxy forwarding has completed.
	ActionCompleted AuditAction = "completed"
	// ActionNoRoute indicates no matching route was found.
	ActionNoRoute AuditAction = "no_route"
	// ActionWSConnect indicates a WebSocket has been connected.
	ActionWSConnect AuditAction = "ws_connect"
	// ActionWSClose indicates a WebSocket has been closed.
	ActionWSClose AuditAction = "ws_close"
	// ActionPluginDecision indicates a plugin decision has been executed.
	ActionPluginDecision AuditAction = "plugin_decision"
	// ActionUnknownConstraint indicates an unknown constraint type was ignored (forward compatibility).
	ActionUnknownConstraint AuditAction = "unknown_constraint"
)

type AuditChain

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

AuditChain manages a sequence of Merkle tree batches for audit trail integrity.

func NewAuditChain

func NewAuditChain(batchSize int, onSeal func(root []byte)) *AuditChain

NewAuditChain creates an audit chain.

func (*AuditChain) BatchCount

func (c *AuditChain) BatchCount() int

BatchCount returns the number of sealed batches.

func (*AuditChain) Dump

func (c *AuditChain) Dump() string

Dump exports a text summary of all batches.

func (*AuditChain) GetTree

func (c *AuditChain) GetTree(batchNumber int) *SealedTree

GetTree returns the sealed tree for a given batch number.

func (*AuditChain) LatestRoot

func (c *AuditChain) LatestRoot() string

LatestRoot returns the root hash (hex) of the most recent batch.

func (*AuditChain) LatestRootBytes

func (c *AuditChain) LatestRootBytes() []byte

LatestRootBytes returns the root hash (raw bytes) of the most recent batch.

func (*AuditChain) Seal

func (c *AuditChain) Seal(entries [][]byte, previousRoot string) *SealedTree

Seal seals a batch of audit entries into a Merkle tree.

func (*AuditChain) SealChecked added in v0.4.0

func (c *AuditChain) SealChecked(entries [][]byte, previousRoot string) (*SealedTree, error)

SealChecked seals a batch like Seal but enforces chain continuity (finding 8): when the chain is non-empty, previousRoot must equal the latest root; passing an empty previousRoot for a non-empty chain is refused. Tamper-evidence is only meaningful if every batch links to its predecessor.

func (*AuditChain) Verify

func (c *AuditChain) Verify(batchNumber int, leaf []byte, proof []ProofStep) (bool, error)

Verify verifies the audit proof for a given batch.

func (*AuditChain) VerifyContinuity added in v0.4.0

func (c *AuditChain) VerifyContinuity() error

VerifyContinuity checks that every batch (after the first) links to its predecessor's root, so a reordered/inserted/deleted batch is detected (finding 8).

func (*AuditChain) VerifyJSON

func (c *AuditChain) VerifyJSON(req *VerifyRequest) *VerifyResponse

VerifyJSON verifies an audit proof based on a JSON request.

type AuditEntry

type AuditEntry struct {
	Time           string   `json:"time"`
	Action         string   `json:"action"`
	SrcIP          string   `json:"src_ip"`
	ClientCN       string   `json:"client_cn,omitempty"`
	ClientSerial   string   `json:"client_serial,omitempty"`
	Roles          []string `json:"roles,omitempty"`
	Mapping        string   `json:"mapping"`
	Target         string   `json:"target"`
	TargetID       string   `json:"target_id,omitempty"`
	Duration       string   `json:"duration,omitempty"`
	DenyReason     string   `json:"deny_reason,omitempty"`
	BytesIn        int64    `json:"bytes_in,omitempty"`
	BytesOut       int64    `json:"bytes_out,omitempty"`
	TraceId        string   `json:"trace_id,omitempty"`
	SessionId      string   `json:"session_id,omitempty"`
	GatewayId      string   `json:"gateway_id,omitempty"`
	Protocol       string   `json:"protocol,omitempty"`
	AgentId        string   `json:"agent_id,omitempty"`
	SPIFFEID       string   `json:"spiffe_id,omitempty"`
	PrincipalUid   string   `json:"principal_uid,omitempty"`
	DelegationMode int      `json:"delegation_mode,omitempty"`
	Decision       string   `json:"decision,omitempty"`
	Capabilities   []string `json:"capabilities,omitempty"`
	// Level is the audit entry level (INFO/WARN/ERROR). Plugin decisions: allow=INFO,
	// deny/execution error=WARN (spec P2-A-28).
	Level string `json:"level,omitempty"`
	// DaHash is the SHA-256 hex hash of the DelegationAuthorization signatureValue
	// (authorization evidence fingerprint, Task 4: binding authorization evidence to action records).
	DaHash string `json:"da_hash,omitempty"`
	// AICFingerprint is the SHA-256 hex of the AIC extension DER encoding (Task 4).
	AICFingerprint string `json:"aic_fingerprint,omitempty"`
	// PolicyVersion is the policy version effective at decision time (Task 5a: binding decision records to policy version).
	// 0 when PolicyManager is not enabled (omitempty omits from output).
	PolicyVersion uint64 `json:"policy_version,omitempty"`
}

AuditEntry is an audit log entry that records connection or decision events.

func NewAuditEntryDenied

func NewAuditEntryDenied(srcIP, mappingName, target, reason string, cert *x509.Certificate) AuditEntry

NewAuditEntryDenied creates an audit entry for a denied connection.

func NewAuditEntryFromConn

func NewAuditEntryFromConn(srcIP, mappingName, target string, cert *x509.Certificate) AuditEntry

NewAuditEntryFromConn creates an audit entry from connection information.

func ReadAuditEntries

func ReadAuditEntries(file string, filter AuditFilter) ([]AuditEntry, error)

ReadAuditEntries reads audit entries by filter.

func (*AuditEntry) SetV12Fields

func (e *AuditEntry) SetV12Fields(protocol, gatewayId, traceId, sessionId, decision string)

SetV12Fields sets the v1.2 spec extension fields for the audit log.

func (*AuditEntry) WithEvidenceFingerprints

func (e *AuditEntry) WithEvidenceFingerprints(cert *x509.Certificate) *AuditEntry

WithEvidenceFingerprints populates the audit entry's authorization evidence fingerprint fields (Task 4). Returns the original entry for method chaining.

type AuditFilter

type AuditFilter struct {
	Since    time.Time
	Until    time.Time
	Limit    int
	Offset   int
	Sort     string
	Action   string
	ClientCN string
	Serial   string
	Mapping  string
}

AuditFilter is the audit log query filter.

type AuditIndex

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

AuditIndex is the audit log index, a hash-chain index based on bbolt.

func NewAuditIndex

func NewAuditIndex(path string) (*AuditIndex, error)

NewAuditIndex creates an audit index instance.

func (*AuditIndex) Close

func (idx *AuditIndex) Close() error

Close closes the audit index database.

func (*AuditIndex) DBPath

func (idx *AuditIndex) DBPath() string

DBPath returns the underlying database file path for external inspection.

func (*AuditIndex) Drop

func (idx *AuditIndex) Drop() error

Drop clears all index data.

func (*AuditIndex) Index

func (idx *AuditIndex) Index(entry *AuditEntry) error

Index indexes a single audit entry.

func (*AuditIndex) IndexFTS

func (idx *AuditIndex) IndexFTS(entry *AuditEntry) error

IndexFTS indexes the text fields of an audit entry as searchable word tokens. Typically called automatically by Index(), but can also be used standalone.

func (*AuditIndex) Search

func (idx *AuditIndex) Search(q *AuditIndexQuery) ([]AuditIndexEntry, error)

Search searches the audit index by query criteria.

func (*AuditIndex) SearchFTS

func (idx *AuditIndex) SearchFTS(query string, limit int) ([]AuditIndexEntry, error)

SearchFTS executes a full-text search query, returning matching audit index entries. Multiple words in the query are ANDed together. Results are sorted by time descending.

func (*AuditIndex) Size

func (idx *AuditIndex) Size() (int64, error)

Size returns the index database size.

type AuditIndexEntry

type AuditIndexEntry struct {
	Hash     string `json:"hash"`
	CN       string `json:"cn,omitempty"`
	Serial   string `json:"serial,omitempty"`
	Action   string `json:"action"`
	Target   string `json:"target,omitempty"`
	Time     int64  `json:"time"`
	RawEntry string `json:"raw_entry,omitempty"`
}

AuditIndexEntry is an audit index entry containing hash and metadata.

type AuditIndexQuery

type AuditIndexQuery struct {
	CN     string `json:"cn,omitempty"`
	Serial string `json:"serial,omitempty"`
	Since  int64  `json:"since,omitempty"`
	Until  int64  `json:"until,omitempty"`
	Limit  int    `json:"limit,omitempty"`
	Offset int    `json:"offset,omitempty"`
}

AuditIndexQuery is the audit index query parameters.

type AuditLogger

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

AuditLogger is the audit log writer that writes in JSON Lines format.

func NewAuditLogger

func NewAuditLogger(file string, tsa *TSAClient, maxSize int64, maxBak int) (*AuditLogger, error)

NewAuditLogger creates an audit log writer (returns nil if file is empty).

func (*AuditLogger) Close

func (l *AuditLogger) Close() error

Close closes the audit log writer, draining buffered entries.

func (*AuditLogger) Dropped

func (l *AuditLogger) Dropped() int64

Dropped returns the number of audit entries discarded because the buffer was full (M6). Data-plane Log calls must never block, so overflow is dropped and counted rather than stalling the caller.

func (*AuditLogger) File

func (l *AuditLogger) File() string

File returns the audit log file path.

func (*AuditLogger) Log

func (l *AuditLogger) Log(entry AuditEntry)

Log enqueues an audit entry. It never blocks the caller (M6): if the buffer is full the entry is dropped and counted. This prevents a slow audit sink (e.g. TSA) from stalling the data plane. Security-critical entries (WARN/ERROR, revocation/denial actions) are never dropped on the fast path: Log waits up to a bounded timeout for them so an attacker flooding the log cannot evict the evidence of its own activity (finding 15).

type AuditVerifier

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

AuditVerifier verifies audit log entries via TSA timestamps.

type AuthorizationPolicy

type AuthorizationPolicy struct {
	Version           string                     `json:"version"`
	Roles             map[string]PolicyRole      `json:"roles"`
	OUMapping         map[string]string          `json:"ou_mapping"`
	GatewayNamespaces map[string]PolicyNamespace `json:"gateway_namespaces"`
	// CapabilityParameters is the parameter default values map derived by gen-authz from
	// capability.json. Key is "scheme:capability_id" (e.g., "varwof/gateway:admin:config").
	CapabilityParameters map[string]map[string]any `json:"capability_parameters,omitempty"`
}

AuthorizationPolicy is the runtime model for the gateway authorization policy (authz.json). Structurally identical to varwof-core auth/policy.go, but kept as an independent implementation to maintain lib's zero new external dependency policy.

func GetAuthorizationPolicy

func GetAuthorizationPolicy() *AuthorizationPolicy

GetAuthorizationPolicy returns the current global authorization policy (may be nil).

func LoadAuthorizationPolicy

func LoadAuthorizationPolicy(policyPath, sigSuffix string, opts *PolicyVerifyOptions) (*AuthorizationPolicy, error)

LoadAuthorizationPolicy loads the authorization policy from a file. If opts is non-nil and the signature file (policyPath+sigSuffix) exists, signature verification is performed first.

func ParseAuthorizationPolicy

func ParseAuthorizationPolicy(data []byte) (*AuthorizationPolicy, error)

ParseAuthorizationPolicy parses the policy JSON.

func (*AuthorizationPolicy) HasGrant

func (p *AuthorizationPolicy) HasGrant(role, capability string) bool

HasGrant checks whether a role has a given capability (supports wildcards).

func (*AuthorizationPolicy) HasParamDefault

func (p *AuthorizationPolicy) HasParamDefault(scheme, capID, param string) (any, bool)

HasParamDefault checks whether a parameter has a default value (for overflow validation).

func (*AuthorizationPolicy) IntersectGrants

func (p *AuthorizationPolicy) IntersectGrants(roles []string, aicCapIds []string) []string

IntersectGrants returns the subset of aicCapIds that matches any role grants.

func (*AuthorizationPolicy) ParamDefaults

func (p *AuthorizationPolicy) ParamDefaults(scheme, capID string) map[string]any

ParamDefaults returns the parameter defaults for a given scheme:capability_id (gen-authz derived). Returns nil if not found.

func (*AuthorizationPolicy) RoleByOU

func (p *AuthorizationPolicy) RoleByOU(ou string) string

RoleByOU maps a certificate OU to a role name.

func (*AuthorizationPolicy) RoleGrants

func (p *AuthorizationPolicy) RoleGrants(role string) []string

RoleGrants returns the grants list for a role.

type AutoIssueResult

type AutoIssueResult struct {
	CertFile string
	KeyFile  string
	CN       string
	Result   *IssueResult
}

AutoIssueResult is the auto-issuance result (including temp file paths).

func AutoIssueCert

func AutoIssueCert(cfg *IssueConfig, cn, san string) (*AutoIssueResult, error)

AutoIssueCert issues a certificate with one call and writes it to temp PEM files.

type CRLCache

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

CRLCache is a CRL cache that supports periodic refresh and forced reload.

func NewCRLCache

func NewCRLCache(caCert *x509.Certificate, url string, refreshSec int, translator Translator, lang string) *CRLCache

NewCRLCache creates a CRL cache instance.

func (*CRLCache) ForceRefresh

func (c *CRLCache) ForceRefresh() error

ForceRefresh forces an immediate CRL cache refresh.

func (*CRLCache) IsRevoked

func (c *CRLCache) IsRevoked(caDN string, serial *big.Int) (bool, error)

IsRevoked checks whether a given certificate serial number has been revoked.

func (*CRLCache) IsRevokedCert added in v0.4.0

func (c *CRLCache) IsRevokedCert(cert *x509.Certificate) (bool, error)

IsRevokedCert checks whether the given certificate is revoked, matching the certificate's issuer against this cache's CA robustly (finding 13): the raw issuer bytes are compared first, falling back to a structural RDN comparison that tolerates RDN ordering/formatting differences. A certificate not issued by this cache's CA is not covered by it and returns not-revoked.

func (*CRLCache) LastRefresh

func (c *CRLCache) LastRefresh() time.Time

LastRefresh returns the time of the last successful refresh.

func (*CRLCache) Start

func (c *CRLCache) Start(stop <-chan struct{})

Start starts the CRL periodic refresh loop.

func (*CRLCache) Stats

func (c *CRLCache) Stats() (int, time.Time, time.Time)

Stats returns CRL cache statistics (revocation count, this update, next update).

type CRLRevokedFunc added in v0.4.0

type CRLRevokedFunc func(caDN string, serial *big.Int) (bool, error)

CRLRevokedFunc reports whether the certificate serial has been revoked by the CA identified by caDN. An error must fail closed (the OCSP crl fallback cannot prove the certificate valid when the CRL cannot be consulted).

type Capability

type Capability = pki.Capability

── Type aliases ──

type CapabilityPlugin

type CapabilityPlugin = pki.CapabilityPlugin

CapabilityPlugin is the interface for all capability plugins.

type CapabilityRegistry

type CapabilityRegistry interface {
	// ValidateCapability validates the full identifier "scheme:capability_id".
	ValidateCapability(formatted string) error
	// Enabled reports whether the registry has been loaded.
	Enabled() bool
}

CapabilityRegistry is the capability registration validation interface (single source of truth). Gateway data plane validates AIC-declared capabilities against the registry during admission pipeline (RunAccessPipeline) phase one: unregistered scheme/capability is treated as an illegal declaration.

Injected by gateways (gateway-*/protocol modules): internally holds a register.Registry (embedded + disk override), atomically replaced after SIGHUP hot reload.

Returns nil when the capability is registered; returns an error when unregistered (caller rejects the connection).

func GetGlobalCapabilityRegistry

func GetGlobalCapabilityRegistry() CapabilityRegistry

GetGlobalCapabilityRegistry returns the current package-level capability registry (may be nil).

type ChainPeerConfig

type ChainPeerConfig struct {
	// Name is the peer gateway name.
	Name string `json:"name"`
	// URL is the peer gateway management API base URL, e.g. https://gw2:9443.
	// The synchronizer will request <URL>/api/v1/gateway/audit/chain.
	URL string `json:"url"`
	// TLSConfig is the peer gateway mTLS client configuration (reuses the gateway management API client).
	TLSConfig *tls.Config `json:"-"`
}

ChainPeerConfig is the configuration for a cross-gateway audit chain reference peer node.

type ChainRef

type ChainRef struct {
	// Peer is the peer gateway name.
	Peer string `json:"peer"`
	// BatchNumber is the remote's latest sealed batch number.
	BatchNumber int `json:"batch"`
	// Root is the remote's latest batch root hash (hex).
	Root string `json:"root"`
	// Previous is the remote batch's predecessor root hash (hex).
	Previous string `json:"previous_root"`
	// Size is the number of entries in the remote batch.
	Size int `json:"size"`
	// Timestamp is the remote batch timestamp (Unix seconds).
	Timestamp string `json:"timestamp"`
	// CapturedAt is the local time this reference was captured (Unix seconds).
	CapturedAt int64 `json:"captured_at"`
}

ChainRef is a peer gateway audit chain reference snapshot (DAG horizontal anchoring). Each gateway locally maintains an AuditChain (vertical hash chain), and periodically syncs its local chain head to peer gateways. Peers record received chain heads as ChainRefs. During verification, the peer's self-exposed chain head is compared against the locally recorded reference (hash anchoring), forming a cross-gateway audit evidence DAG — proving that each gateway's chain is temporally anchored to others without consensus ordering, and any unilateral tampering would break reference consistency.

type ChainRefStore

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

ChainRefStore stores cross-gateway audit chain references. Thread-safe, stores the latest chain head reference per peer gateway name.

func NewChainRefStore

func NewChainRefStore() *ChainRefStore

NewChainRefStore creates a cross-gateway audit chain reference store.

func (*ChainRefStore) CompareRef

func (s *ChainRefStore) CompareRef(peer string, theirs *SealedTree) (bool, ChainRef, string)

CompareRef compares the locally recorded remote reference against the remote's actual exposed chain head. Returns (match, remote chain head, difference description). When the remote batch number is less than or equal to the local reference batch number, their root hashes are compared directly; a newer batch number is treated as consistent (normal remote advancement) and updates the local record.

func (*ChainRefStore) Len

func (s *ChainRefStore) Len() int

Len returns the number of recorded peer gateways. Safe on nil receiver.

func (*ChainRefStore) PeerRefs

func (s *ChainRefStore) PeerRefs() []ChainRef

PeerRefs returns a snapshot of all peer gateway references (sorted by peer name). Safe on nil receiver (returns nil)。

func (*ChainRefStore) Record

func (s *ChainRefStore) Record(ref ChainRef)

Record records the latest chain head reference for a peer gateway. Only the latest batch is kept per peer. Safe on nil receiver (no-op)。

type ChainSyncClient

type ChainSyncClient struct {
	// Peer is the peer gateway name (for local record keeping).
	Peer string
	// URL is the remote management endpoint, e.g. https://host:9443/api/v1/gateway/audit/chain.
	URL string
	// HTTPClient is the HTTP client with mTLS certificates.
	HTTPClient *http.Client
	// Timeout is the per-fetch timeout (default 5s).
	Timeout time.Duration
}

ChainSyncClient fetches chain head references from a peer gateway management API. Reuses an mTLS HTTP client to GET /api/v1/gateway/audit/chain from the remote peer.

func (*ChainSyncClient) Fetch

func (c *ChainSyncClient) Fetch() (*SealedTree, error)

Fetch retrieves the remote chain head and returns it.

type ChainSyncer

type ChainSyncer struct {
	Store    *ChainRefStore
	Peers    []ChainSyncClient
	Interval time.Duration
	// contains filtered or unexported fields
}

ChainSyncer periodically synchronizes peer gateway audit chain references. After Start, it polls all peers at Interval and writes the latest chain heads to the store.

func NewChainSyncer

func NewChainSyncer(store *ChainRefStore, peers []ChainSyncClient, interval time.Duration) *ChainSyncer

NewChainSyncer creates a chain reference synchronizer.

func (*ChainSyncer) Start

func (s *ChainSyncer) Start()

Start starts the background synchronization loop.

func (*ChainSyncer) Stop

func (s *ChainSyncer) Stop()

Stop stops the background synchronization loop.

type CloseFunc

type CloseFunc func()

CloseFunc is a function that closes a single connection.

type ConfigWatcher

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

ConfigWatcher polls a remote endpoint for configuration changes. Suitable for scenarios where varwof-core pushes configuration.

func ConfigWatcherFromCLI

func ConfigWatcherFromCLI(url string, tlsConfig *tls.Config, onChange func([]byte) error) *ConfigWatcher

ConfigWatcherFromCLI creates a ConfigWatcher from CLI arguments (if applicable). Returns nil when url is empty, indicating dynamic configuration is not enabled.

func NewConfigWatcher

func NewConfigWatcher(url string, tlsConfig *tls.Config, interval time.Duration, onChange func([]byte) error) *ConfigWatcher

NewConfigWatcher creates a configuration watcher. url: configuration API endpoint (e.g. https://varwof-core:4433/api/v1/gateway/config) tlsConfig: mTLS client certificate (for gateway→core authentication) interval: polling interval onChange: callback when configuration changes, parameter is the full configuration JSON

func (*ConfigWatcher) Start

func (w *ConfigWatcher) Start()

Start begins polling for configuration.

func (*ConfigWatcher) Stop

func (w *ConfigWatcher) Stop()

Stop stops polling.

type ConfirmedRenewalManager

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

ConfirmedRenewalManager manages the confirmed renewal state machine. Thread-safe; only one in-progress renewal request is allowed at a time (single certificate rotation semantics).

func NewConfirmedRenewalManager

func NewConfirmedRenewalManager(issueCfg *IssueConfig, registry *ConnExpiryRegistry, onIssued func(newCert *x509.Certificate)) *ConfirmedRenewalManager

NewConfirmedRenewalManager creates a confirmed renewal manager.

  • issueCfg is used to issue new certificates from CA (may be nil: registration/confirmation semantics only, no actual issuance, for testing);
  • registry, when non-nil, calls UpdateCert on the old certificate after successful issuance to mark the transition;
  • onIssued, when non-nil, is called after successful issuance (gateway atomic certificate switch entry point).

func (*ConfirmedRenewalManager) Confirm

Confirm confirms the renewal by the responsible party (P2-A-12/17):

  1. Verifies sessionID match and AwaitingConfirmation state;
  2. Verifies responsible party certificate is non-empty + DA signature (signed by responsible party's private key);
  3. Permission recheck: new capabilities ⊆ responsible party PA grants (capabilitySubset), out of bounds → Rejected (permissions reduced, P2-A-17);
  4. Issues new certificate to CA (when issueCfg is non-nil);
  5. Marks old certificate for transition: registry.UpdateCert(oldSerial, newCert);
  6. onIssued callback (gateway atomic switch).

func (*ConfirmedRenewalManager) CurrentSessionID

func (m *ConfirmedRenewalManager) CurrentSessionID() string

CurrentSessionID returns the sessionID of the in-progress renewal request.

func (*ConfirmedRenewalManager) Issued

func (m *ConfirmedRenewalManager) Issued() *IssueResult

Issued returns the certificate result issued for the current renewal request (available after Confirmed).

func (*ConfirmedRenewalManager) Reason

func (m *ConfirmedRenewalManager) Reason() string

Reason returns the rejection/reason information for the current renewal request.

func (*ConfirmedRenewalManager) Reject

func (m *ConfirmedRenewalManager) Reject(reason string)

Reject explicitly rejects the renewal (responsible party refused or gateway found permissions reduced).

func (*ConfirmedRenewalManager) RequestRenewal

func (m *ConfirmedRenewalManager) RequestRenewal(req *RenewalRequest) error

RequestRenewal initiates a renewal request and enters the AwaitingConfirmation state. Returns an error if a request is already in progress and has not timed out.

func (*ConfirmedRenewalManager) Reset

func (m *ConfirmedRenewalManager) Reset()

Reset clears the current renewal request (reverts to Idle, for testing/reuse).

func (*ConfirmedRenewalManager) SetOldCertVerifier added in v0.4.0

func (m *ConfirmedRenewalManager) SetOldCertVerifier(fn func(serial string, oldCert *x509.Certificate) error)

SetOldCertVerifier installs the old-certificate revocation verifier invoked by Confirm before a renewal is issued. It must confirm the old certificate is still valid/unrevoked; Confirm fails closed when issuance is configured but no verifier is installed (finding 4).

func (*ConfirmedRenewalManager) SetPrincipalCertVerifier added in v0.4.0

func (m *ConfirmedRenewalManager) SetPrincipalCertVerifier(fn func(*x509.Certificate) error)

SetPrincipalCertVerifier installs the responsible-party certificate verifier. The verifier must chain the presented certificate to a trusted identity anchor (and may additionally check revocation/OU policy). It is invoked by Confirm before the renewal DA is accepted. Deployments that issue new certificates must configure one; Confirm fails closed otherwise (finding 1).

func (*ConfirmedRenewalManager) SetRenewalDAFreshness added in v0.4.0

func (m *ConfirmedRenewalManager) SetRenewalDAFreshness(maxAge time.Duration)

SetRenewalDAFreshness overrides the maximum acceptable age of the renewal DA timestamp (finding 10). Ages older than this are rejected.

func (*ConfirmedRenewalManager) SetRenewalNonceStore added in v0.4.0

func (m *ConfirmedRenewalManager) SetRenewalNonceStore(s *memReplayStore)

SetRenewalNonceStore replaces the renewal DA replay store (finding 10). Pass nil to disable replay protection (not recommended).

func (*ConfirmedRenewalManager) SetTimeout

func (m *ConfirmedRenewalManager) SetTimeout(d time.Duration)

SetTimeout overrides the confirmation timeout (for testing).

func (*ConfirmedRenewalManager) State

State returns the current renewal state.

type ConnExpiryRegistry

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

ConnExpiryRegistry tracks active connection certificate validity and renewal flags keyed by certificate serial number. Thread-safe (sync.RWMutex protects the map; certificate and renewal flag are atomic reads/writes).

func NewConnExpiryRegistry

func NewConnExpiryRegistry() *ConnExpiryRegistry

NewConnExpiryRegistry creates an empty ConnExpiryRegistry.

func (*ConnExpiryRegistry) Certificate

func (r *ConnExpiryRegistry) Certificate(serial string) *x509.Certificate

Certificate reads the current certificate for a serial number (atomic pointer, may be nil).

func (*ConnExpiryRegistry) Connections

func (r *ConnExpiryRegistry) Connections(serial string) int64

Connections returns the current active connection count for a serial number (P2-A-16 transitional state concurrent count inheritance).

func (*ConnExpiryRegistry) Len

func (r *ConnExpiryRegistry) Len() int

Len returns the number of tracked serial numbers.

func (*ConnExpiryRegistry) Register

func (r *ConnExpiryRegistry) Register(serial string, cert *x509.Certificate) func()

Register records an active connection (serial is the normalized hex serial number) and returns a deregistration function to be called when the connection closes. Multiple Register calls for the same serial increment the concurrent count; the renewal flag is not reset by new connection registration. A nil receiver returns a no-op deregistration function.

func (*ConnExpiryRegistry) Renewed

func (r *ConnExpiryRegistry) Renewed(serial string) bool

Renewed queries the renewal flag for a serial number.

func (*ConnExpiryRegistry) SerialNumbers

func (r *ConnExpiryRegistry) SerialNumbers() []string

SerialNumbers returns all tracked serial numbers (for testing/metrics).

func (*ConnExpiryRegistry) ShouldSkipRevoke

func (r *ConnExpiryRegistry) ShouldSkipRevoke(serial string) bool

ShouldSkipRevoke reads the renewal flag and certificate validity during connection-closure revocation evaluation (P2-A-15): renewal flag true or certificate already expired → skip revocation; otherwise returns false. Untracked serial numbers return false (maintaining default revocation behavior).

func (*ConnExpiryRegistry) StartExpiryLoop

func (r *ConnExpiryRegistry) StartExpiryLoop(interval time.Duration, stopCh <-chan struct{}) func()

StartExpiryLoop starts the expiry check goroutine, polling every interval (<=0 uses default 5 seconds), cleaning up expired entries with no active connections (transitional certificates expire naturally, no explicit revocation). Returns a callable stop function (can also be stopped via external stopCh).

func (*ConnExpiryRegistry) Unregister

func (r *ConnExpiryRegistry) Unregister(serial string)

Unregister forcefully removes a serial number entry (P2-A-14 Unregister()).

func (*ConnExpiryRegistry) UpdateCert

func (r *ConnExpiryRegistry) UpdateCert(serial string, cert *x509.Certificate) bool

UpdateCert updates the certificate and sets the renewal flag to true after successful renewal (P2-A-15). Returns false if the serial number is not tracked.

type ConnRegistry

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

ConnRegistry maps agent_id and principalUid to close functions. It is safe for concurrent use and designed for gateway disconnect APIs.

func NewConnRegistry

func NewConnRegistry() *ConnRegistry

NewConnRegistry creates a new ConnRegistry.

func (*ConnRegistry) DisconnectByAgentId

func (r *ConnRegistry) DisconnectByAgentId(agentId string) int

DisconnectByAgentId closes all connections for the given agentId. Returns the number of connections closed. Safe on nil receiver.

func (*ConnRegistry) DisconnectByPrincipalUid

func (r *ConnRegistry) DisconnectByPrincipalUid(principalUid string) int

DisconnectByPrincipalUid closes all connections for the given principalUid. Returns the number of connections closed. Safe on nil receiver.

func (*ConnRegistry) ListByAgentId

func (r *ConnRegistry) ListByAgentId() map[string]int

ListByAgentId returns agentId → count for all tracked agents.

func (*ConnRegistry) ListByIP

func (r *ConnRegistry) ListByIP() map[string]int

ListByIP returns connection counts aggregated by source IP. Safe on nil receiver.

func (*ConnRegistry) ListConnections

func (r *ConnRegistry) ListConnections() []ConnectionInfo

ListConnections returns a snapshot of all active connection details. Safe on nil receiver.

func (*ConnRegistry) Register

func (r *ConnRegistry) Register(agentId, principalUid string, close CloseFunc) func()

Register adds a close function associated with the given agentId and principalUid. Returns a RemoveFunc that should be called on disconnect. Safe to call on a nil receiver (returns noop).

func (*ConnRegistry) RegisterConn

func (r *ConnRegistry) RegisterConn(agentId, principalUid, srcIP, protocol, serial string, close CloseFunc) func()

RegisterConn adds a close function associated with the given identity and connection metadata (source IP, protocol, certificate serial). Returns a RemoveFunc that should be called on disconnect. Safe on a nil receiver.

func (*ConnRegistry) Stats

func (r *ConnRegistry) Stats() (total int)

Stats returns the number of tracked connections. Safe on nil receiver.

type ConnectionInfo

type ConnectionInfo struct {
	// ID is the internal connection registry ID.
	ID uint64 `json:"id"`
	// AgentId is the associated agent identifier.
	AgentId string `json:"agent_id,omitempty"`
	// PrincipalUid is the associated responsible party identifier.
	PrincipalUid string `json:"principal_uid,omitempty"`
	// SrcIP is the connection source IP.
	SrcIP string `json:"src_ip,omitempty"`
	// Protocol is the transport protocol (tcp/http/udp/dtls/quic).
	Protocol string `json:"protocol,omitempty"`
	// Serial is the client certificate serial number.
	Serial string `json:"serial,omitempty"`
	// Established is the connection establishment time (Unix seconds).
	Established int64 `json:"established,omitempty"`
}

ConnectionInfo is a detailed connection entry (real-time traffic/IP access point/agent directory query).

type ConnectionTracker

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

ConnectionTracker tracks active connection counts by certificate serial number.

func NewConnectionTracker

func NewConnectionTracker() *ConnectionTracker

NewConnectionTracker creates a connection tracker.

func (*ConnectionTracker) Add

func (t *ConnectionTracker) Add(serial string, max int64) bool

Add increments the connection count; returns false if the limit is exceeded.

func (*ConnectionTracker) Count

func (t *ConnectionTracker) Count(serial string) int64

Count returns the active connection count for a given certificate.

func (*ConnectionTracker) Remove

func (t *ConnectionTracker) Remove(serial string)

Remove decrements the connection count.

func (*ConnectionTracker) Render

func (t *ConnectionTracker) Render() string

Render outputs connection counts in Prometheus format.

func (*ConnectionTracker) Snapshot

func (t *ConnectionTracker) Snapshot() map[string]int64

Snapshot returns a snapshot of the current connections.

func (*ConnectionTracker) Total

func (t *ConnectionTracker) Total() int64

Total returns the total active connection count across all certificates.

type ConstraintContext

type ConstraintContext struct {
	// ClientIP is used for source-address-based constraints such as allowed-cidr / geo-fence.
	ClientIP string
	// Now is the evaluation time; defaults to current UTC time. Can be injected for testing and offline decisions.
	Now time.Time
}

ConstraintContext is the runtime context provided during constraint evaluation.

type ConstraintEvaluator

type ConstraintEvaluator interface {
	// CapabilityId returns the constraint type identifier handled by this evaluator.
	CapabilityId() string
	// Evaluate evaluates a single constraint. The cap's SchemeId has already been filtered
	// to constraint / constraint-v1 by the caller.
	Evaluate(cap *Capability, ctx *ConstraintContext) error
}

ConstraintEvaluator evaluates a single constraint from authorizationConstraints. Returns a non-nil error if the constraint is not satisfied; the gateway denies the connection.

type ConstraintRegistry

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

ConstraintRegistry registers/looks up constraint evaluators by capabilityId. It provides an extensible constraint type registration mechanism: when adding a new constraint type, only the corresponding evaluator needs to be registered without modifying the certificate ASN.1 structure or gateway core routing code.

func NewConstraintRegistry

func NewConstraintRegistry() *ConstraintRegistry

NewConstraintRegistry creates an empty registry.

func (*ConstraintRegistry) Find

func (r *ConstraintRegistry) Find(capabilityId string) (ConstraintEvaluator, error)

Find looks up an evaluator by capabilityId.

func (*ConstraintRegistry) Keys

func (r *ConstraintRegistry) Keys() []string

Keys returns the list of registered capabilityIds (for metrics/audit).

func (*ConstraintRegistry) Len

func (r *ConstraintRegistry) Len() int

Len returns the number of registered constraint evaluators.

func (*ConstraintRegistry) Register

Register registers a constraint evaluator. Returns an error if the same capabilityId is registered twice.

func (*ConstraintRegistry) Remove

func (r *ConstraintRegistry) Remove(capabilityId string)

Remove removes an evaluator. After removal, unknown types revert to the "unknown constraint" semantics (ignored by default).

func (*ConstraintRegistry) Replace

Replace atomically replaces a registered evaluator (for hot updates). Registers the evaluator if not already registered.

func (*ConstraintRegistry) Reset

func (r *ConstraintRegistry) Reset()

Reset clears the registry (for testing only).

type ContentInfo

type ContentInfo struct {
	ContentType asn1.ObjectIdentifier
	Content     asn1.RawValue `asn1:"explicit,tag:0"`
}

ContentInfo is CMS content information.

type ControlHandler

type ControlHandler func(msg ControlMessage) error

ControlHandler is a callback for handling mesh control plane messages, wired by the gateway for revocation evaluation/session management. When it returns an error, MeshManager only logs the error and does not block message dispatch.

type ControlMessage

type ControlMessage struct {
	// Type is the message type (revoke / disconnect / peer_sync).
	Type ControlMessageType `json:"type"`
	// Source is the name of the originating gateway.
	Source string `json:"source"`
	// MsgID is the unique message ID (source + sequence), used for dedup and loop prevention.
	MsgID string `json:"msg_id"`
	// Timestamp is the message timestamp (Unix milliseconds).
	Timestamp int64 `json:"timestamp"`
	// Serial is the certificate serial number (optional for revoke).
	Serial string `json:"serial,omitempty"`
	// KeyHash is the SPKI hash (optional for revoke).
	KeyHash string `json:"key_hash,omitempty"`
	// AgentId is the agent identifier (revoke/disconnect).
	AgentId string `json:"agent_id,omitempty"`
	// Reason is the action reason (disconnect payload).
	Reason string `json:"reason,omitempty"`
	// Version is the state summary version number (peer_sync payload).
	Version uint64 `json:"version,omitempty"`
}

ControlMessage is a control plane message between mesh nodes. The channel reuses inter-node mTLS; message integrity and authenticity are guaranteed by the TLS channel.

type ControlMessageType

type ControlMessageType string

ControlMessageType is a control plane message type.

const (
	// ControlRevoke is a revocation notification: payload contains certificate serial or keyHash/agentId.
	ControlRevoke ControlMessageType = "revoke"
	// ControlDisconnect is a kick notification: payload contains agentId, reason, and source gateway.
	ControlDisconnect ControlMessageType = "disconnect"
	// ControlPeerSync is a state summary sync on peer join (revocation/disconnect record version).
	ControlPeerSync ControlMessageType = "peer_sync"
	// ControlDedupWindow is the control message dedup window (default 5 minutes).
	ControlDedupWindow = 5 * time.Minute
)

type CredentialBundle

type CredentialBundle struct {
	// AgentChain is the agent certificate chain containing AIC.
	// chain[0]=Agent, subsequent entries are intermediate/root CAs.
	AgentChain []*x509.Certificate
	// PrincipalChain is the principal certificate chain containing PA.
	// chain[0]=Principal (independently issued, not in the agent chain),
	// subsequent entries are intermediate CAs (optional).
	PrincipalChain []*x509.Certificate
	// CACerts are optional CA certs carried in the bundle for informational
	// purposes. They are never used as trust anchors (finding 20): callers must
	// supply operator-configured roots via VerifyBundle.
	CACerts []*x509.Certificate
}

CredentialBundle is the credential bundle submitted by the client (Agent certificate chain + Principal certificate chain + CA).

func NewCredentialBundle

func NewCredentialBundle(agentChain, principalChain, caCerts []*x509.Certificate) (*CredentialBundle, error)

NewCredentialBundle constructs a credential bundle. Returns an error if either chain is empty.

func ParseCredentialBundlePEM

func ParseCredentialBundlePEM(data []byte) (*CredentialBundle, error)

ParseCredentialBundlePEM parses a credential bundle from PEM data (P2-A-01 order: Agent chain first, Principal second, CA chain last). Certificates are classified by extensions: AIC-containing → Agent chain, PA-containing → Principal chain, rest → CA. The parsed result must be verified via VerifyBundle before use.

func (*CredentialBundle) Agent

func (b *CredentialBundle) Agent() *x509.Certificate

Agent returns the Agent certificate (contains AIC, chain[0]).

func (*CredentialBundle) Principal

func (b *CredentialBundle) Principal() *x509.Certificate

Principal returns the Principal certificate (contains PA, chain[0]).

type DecisionResult

type DecisionResult int

DecisionResult is the result of a connection admission decision.

const (
	// DecisionAllow means admission is allowed.
	DecisionAllow DecisionResult = iota
	// DecisionDeny means admission is denied.
	DecisionDeny DecisionResult = iota
	// DecisionNeedAuth means additional authentication is required.
	DecisionNeedAuth
)

type DelegationAuthTBS

type DelegationAuthTBS = pki.DelegationAuthTBS

── Type aliases ──

type DelegationAuthorization

type DelegationAuthorization = pki.DelegationAuthorization

── Type aliases ──

func SignRenewalDA

func SignRenewalDA(req *RenewalRequest, key crypto.Signer, nonce []byte, ts time.Time, lifetime int, reasonCode, reasonDesc string) (DelegationAuthorization, error)

SignRenewalDA has the responsible party re-sign DelegationAuthorization with its private key (P2-A-12): generates a DA with new nonce/timestamp/requestedLifetime, signing the DelegationAuthTBS DER content. The responsible party client calls this and passes the result + responsible party certificate to the gateway's Confirm().

type DelegationChainVerifier

type DelegationChainVerifier struct {
	// MaxDepth is the maximum delegation depth allowed by the top Principal (including intermediate Agent B etc.).
	MaxDepth int
	// MaxChainLength is the hard upper limit to prevent certificate bomb attacks (P1-B-15):
	// ≤0 means no extra limit (only constrained by MaxDepth).
	MaxChainLength int
}

DelegationChainVerifier verifies multi-level delegation chains (Zhang→Scheduler-A→Worker-B→…).

Multi-level delegation reuses the same DelegationAuthorization structure (spec dev-docs/aic/06-delegation-auth.md §Multi-level delegation chain, FUTURE reserved): each Agent's AIC contains a DelegationAuthorization signed by the previous level (delegator) certificate's private key. Verification proceeds bottom-up:

chain[i].AIC.DA signed by chain[i-1].cert → chain[i-1].AIC.DA signed by chain[i-2].cert
→ … → chain[0].AIC.DA signed by topPrincipal certificate

chainDepth is the number of delegation certificates in the chain (excluding the top Principal); maxDepth is set by the top Principal; exceeding it results in rejection. No new ASN.1 types needed; the entire chain is verifiable offline.

func (*DelegationChainVerifier) Verify

func (v *DelegationChainVerifier) Verify(chain []*x509.Certificate, topPrincipal *x509.Certificate) error

Verify verifies the delegation chain bottom-up starting from workerCert. chain is the certificate list from top to bottom: chain[0]=Scheduler-A (top-level delegating Agent), chain[len-1]=Worker-B (bottom-level Agent). Each level's AIC.DA is signed by the previous level's certificate.

Verification steps:

  1. Each certificate must contain an AIC with non-empty DA;
  2. Each level's AIC.DA signer = previous certificate (SPKI hash cross-validation);
  3. Top-level chain[0].AIC.DA signer = topPrincipal certificate;
  4. Chain depth (len(chain)) must ≤ MaxDepth;
  5. Entire chain verified offline, no external service dependency.

type DelegationMode

type DelegationMode = pki.DelegationMode

── Type aliases ──

const (
	DelegationAuthorized     DelegationMode = 0
	DelegationRepresentative DelegationMode = 1
)

DelegationMode values.

type DelegationPolicy

type DelegationPolicy = pki.DelegationPolicy

── Type aliases ──

type DurationTracker

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

DurationTracker tracks durations for latency aggregation.

func (*DurationTracker) Add

func (d *DurationTracker) Add(dur time.Duration)

Add records a single duration observation.

type ExtField

type ExtField = pki.ExtField

── Type aliases ──

type ExternalPolicyRef

type ExternalPolicyRef = pki.ExternalPolicyRef

── Type aliases ──

type GeoResolver

type GeoResolver func(ip string) (string, error)

GeoResolver resolves a geographic region identifier (e.g. "CN-SHA") from a source IP. Registered with the geo-fence evaluator to make region resolution pluggable (built-in inline table; third-party databases like ip2region can self-register).

type HTTPExtra

type HTTPExtra struct {
	// ForwardClientCert specifies whether to forward client certificates to the backend.
	ForwardClientCert *bool `json:"forward_client_cert,omitempty"`

	// ForwardClientCertDER specifies whether to pass the client certificate
	// to the backend via X-Client-Cert-DER header.
	ForwardClientCertDER *bool `json:"forward_client_cert_der,omitempty"`

	// ReadHeaderTimeoutSec is the request header read timeout in seconds (default 30).
	ReadHeaderTimeoutSec int `json:"read_header_timeout_sec,omitempty"`

	// WriteTimeoutSec is the response write timeout in seconds (default 300).
	WriteTimeoutSec int `json:"write_timeout_sec,omitempty"`

	// TLSTermination specifies whether TLS is terminated at the gateway.
	TLSTermination *bool `json:"tls_termination,omitempty"`
}

func (*HTTPExtra) ForwardClientCertDEREnabled

func (h *HTTPExtra) ForwardClientCertDEREnabled() bool

func (*HTTPExtra) ForwardClientCertEnabled

func (h *HTTPExtra) ForwardClientCertEnabled() bool

func (*HTTPExtra) ReadHeaderTimeout

func (h *HTTPExtra) ReadHeaderTimeout() time.Duration

func (*HTTPExtra) TLSTerminationEnabled

func (h *HTTPExtra) TLSTerminationEnabled() bool

func (*HTTPExtra) WriteTimeout

func (h *HTTPExtra) WriteTimeout() time.Duration

type HTTPFacts

type HTTPFacts = pki.HTTPFacts

HTTPFacts carries per-request HTTP facts for capability plugins.

type IssueClient

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

IssueClient is the short-lived certificate issuance client.

func NewIssueClient

func NewIssueClient(cfg IssueConfig) (*IssueClient, error)

NewIssueClient creates a short-lived certificate issuance client.

func (*IssueClient) Issue

func (c *IssueClient) Issue(req *IssueRequest) (*IssueResult, error)

Issue sends a short-lived certificate issuance request.

type IssueConfig

type IssueConfig struct {
	// CoreURL is the Varwof Core service address (e.g. https://varwof-core:4433).
	CoreURL string `json:"core_url"`
	// CertFile is the mTLS client certificate file path.
	CertFile string `json:"cert_file"`
	// KeyFile is the mTLS client private key file path.
	KeyFile string `json:"key_file"`
	// CACertFile is the CA certificate file path (for server verification).
	CACertFile string `json:"ca_cert_file,omitempty"`
	// DefaultCA is the default issuance CA name.
	DefaultCA string `json:"default_ca,omitempty"`
	// DefaultKeyType is the default key type (e.g. ecdsa-p256).
	DefaultKeyType string `json:"default_key_type,omitempty"`
	// DefaultValidity is the default issuance validity period (days), 0 = caller defaults (W38).
	DefaultValidity int `json:"default_validity,omitempty"`
	// Timeout is the HTTP request timeout.
	Timeout time.Duration `json:"timeout,omitempty"`
	// RetryCount is the number of retries on failure.
	RetryCount int `json:"retry_count,omitempty"`
	// RenewalIntervalSec is the certificate renewal polling interval (seconds), 0 = default 30s (W38).
	RenewalIntervalSec int `json:"renewal_interval_sec,omitempty"`
}

IssueConfig is the configuration for the short-lived certificate issuance client.

func (*IssueConfig) RenewalInterval

func (c *IssueConfig) RenewalInterval() time.Duration

RenewalInterval returns the certificate renewal polling interval (W38: configurable, default 30s).

type IssueRequest

type IssueRequest struct {
	CA             string `json:"ca"`
	CN             string `json:"cn"`
	SAN            string `json:"san,omitempty"`
	Profile        string `json:"profile,omitempty"`
	KeyType        string `json:"key_type,omitempty"`
	Validity       int    `json:"validity,omitempty"`
	AgentType      *int   `json:"agent_type,omitempty"`
	AgentId        string `json:"agent_id,omitempty"`
	MarketAccessId string `json:"market_access_id,omitempty"`
	// OldSerial, when non-empty, records the certificate serial being renewed so
	// the issuer can carry a linkage back to the original (finding 4). A renewed
	// certificate is then traceable to its predecessor for revocation purposes.
	OldSerial string `json:"old_serial,omitempty"`
}

IssueRequest is a short-lived certificate issuance request.

type IssueResult

type IssueResult struct {
	SerialNumber string `json:"serial_number"`
	CommonName   string `json:"common_name"`
	CertPEM      string `json:"cert_pem"`
	KeyPEM       string `json:"key_pem"`
	CA           string `json:"ca"`
	// contains filtered or unexported fields
}

IssueResult is the result of a short-lived certificate issuance.

func (*IssueResult) Certificate

func (r *IssueResult) Certificate() (*x509.Certificate, error)

Certificate parses and returns the x509.Certificate (cached).

type JWTVerifier added in v0.3.0

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

JWTVerifier verifies AIC-JWT bearer tokens against a trust root built from CA certificates (same kid convention as the X.509 carrier: base64url SHA-256 of the certificate SPKI). On success it returns a synthesized X.509 certificate carrying the token's AIC extension, so the existing pipeline (RunAccessPipeline / CheckAdmission) admits a bearer request exactly like a certificate-authenticated one.

A bare NewJWTVerifier only verifies the token signature/expiry. For production use the gateway must call SetBearerPolicy (issuer/audience binding + replay protection) and pass per-request proof-of-possession via VerifyBearer options; without those the bearer is replayable until exp by any holder (finding 5).

func LoadJWTVerifier added in v0.3.0

func LoadJWTVerifier(caFiles ...string) (*JWTVerifier, error)

LoadJWTVerifier reads one or more PEM CA certificate files (comma or space separated paths) and builds a JWT verifier from them. An empty spec returns a nil verifier (bearer auth disabled).

func NewJWTVerifier added in v0.3.0

func NewJWTVerifier(cas []*x509.Certificate) *JWTVerifier

NewJWTVerifier builds a verifier from CA certificates. kid for each CA is base64url(SHA-256(SubjectPublicKeyInfo)) — the same binding core publishes on /.well-known/jwks.json.

func (*JWTVerifier) SetBearerPolicy added in v0.4.0

func (v *JWTVerifier) SetBearerPolicy(expectedIssuer string, expectedAudience []string, nonces aicjwt.NonceStore)

SetBearerPolicy installs the static bearer-token policy applied to every verification: the expected issuer, acceptable audiences, and a replay nonce store. Configure all three for production; leaving issuer/audience empty or the nonce store nil keeps those checks off (finding 5).

func (*JWTVerifier) VerifyBearer added in v0.3.0

func (v *JWTVerifier) VerifyBearer(token string, now time.Time, opts ...JWTVerifyOptions) (*x509.Certificate, *aicjwt.OuterClaims, error)

VerifyBearer validates a Bearer AIC-JWT and returns a synthesized certificate carrying the AIC claims, plus the raw outer claims. opts carry per-request checks (proof-of-possession, revocation); the verifier's static policy (issuer/audience/replay) is always applied.

type JWTVerifyOptions added in v0.4.0

type JWTVerifyOptions struct {
	// ExpectedIssuer, when non-empty, requires outer.iss == ExpectedIssuer.
	ExpectedIssuer string
	// ExpectedAudience, when non-empty, requires the token aud to include one.
	ExpectedAudience []string
	// PresenterKey, when non-nil, enforces cnf proof-of-possession: the token
	// must be bound to this public key (e.g. the mTLS peer cert key).
	PresenterKey crypto.PublicKey
	// NonceStore, when non-nil, provides one-time-use replay protection on the
	// DA nonce (finding 5).
	NonceStore aicjwt.NonceStore
	// RequireJtiNonceMatch requires outer.jti == DA nonce.
	RequireJtiNonceMatch bool
	// StatusChecker, when non-nil, checks issuer/principal for revocation.
	StatusChecker aicjwt.StatusChecker
}

JWTVerifyOptions carries the runtime verification parameters for a single bearer token. These activate the checks Validate supports but that a bare call leaves unset (finding 5).

type Layer1Result

type Layer1Result struct {
	Verified bool
	Reason   string
	Roles    []string
}

Layer1Result is the Layer 1 identity verification result (Agent Cert + CA Chain + RBAC).

func VerifyLayer1

func VerifyLayer1(chain []*x509.Certificate, cfg *PipelineConfig) *Layer1Result

VerifyLayer1 performs Layer 1 identity verification: certificate chain validity (validity period) + RBAC roles (AllowRoles matching). Cryptographic certificate chain verification is done by the TLS layer (VerifyPeerCertificate); this layer performs application-level identity checks (validity period + roles). Returns roles for use by subsequent layers.

type Layer2Result

type Layer2Result struct {
	Verified               bool
	Reason                 string
	AIC                    *AIC
	PrincipalAuthorization *PrincipalAuthorization
	PrincipalUid           string
}

Layer2Result is the Layer 2 representation verification result (+ Principal Cert + PA).

type Layer3Result

type Layer3Result struct {
	Verified bool
	Reason   string
}

Layer3Result is the Layer 3 online authorization verification result (OCSP/CRL/Policy Server).

func VerifyLayer3

func VerifyLayer3(chain []*x509.Certificate, cfg *PipelineConfig) *Layer3Result

VerifyLayer3 performs Layer 3 online authorization verification: CRL/OCSP revocation freshness check + optional PolicyServer online policy check.

type ManagementServer

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

ManagementServer is the unified management API server, supporting mTLS + RBAC.

func NewManagementServer

func NewManagementServer(cfg ManagementServerConfig) *ManagementServer

NewManagementServer creates a management API server instance.

func (*ManagementServer) RegisterHandler

func (ms *ManagementServer) RegisterHandler(pattern string, handler http.HandlerFunc, allowedRoles ...string)

RegisterHandler registers a management route with RBAC role protection.

func (*ManagementServer) RegisterRawHandler

func (ms *ManagementServer) RegisterRawHandler(pattern string, handler http.HandlerFunc)

RegisterRawHandler registers a raw management route without RBAC checks.

func (*ManagementServer) SetConfirmedRenewalManager

func (ms *ManagementServer) SetConfirmedRenewalManager(m *ConfirmedRenewalManager)

SetConfirmedRenewalManager sets the confirmed renewal manager reference (for hot reload).

func (*ManagementServer) SetPolicyManager

func (ms *ManagementServer) SetPolicyManager(pm *PolicyManager)

SetPolicyManager updates the policy versioning manager reference (for hot reload).

func (*ManagementServer) Start

func (ms *ManagementServer) Start() error

Start starts the management API HTTP service.

func (*ManagementServer) Stop

func (ms *ManagementServer) Stop()

Stop gracefully shuts down the management API service.

func (*ManagementServer) UpdatePluginRegistry

func (ms *ManagementServer) UpdatePluginRegistry(reg *PluginRegistry)

UpdatePluginRegistry updates the plugin registry reference on the management server (for hot reload).

type ManagementServerConfig

type ManagementServerConfig struct {
	// Listen is the management API listen address (e.g. :9443).
	Listen string
	// TLSConfig is the mTLS server-side TLS configuration.
	TLSConfig *tls.Config
	// BuildInfo contains build information (version, build time, etc.).
	BuildInfo string
	// AuditLogger is the audit logger instance.
	AuditLogger *AuditLogger
	// AuditChain is the audit Merkle hash chain instance.
	AuditChain *AuditChain
	// Translator is the i18n translator instance.
	Translator Translator
	// Lang is the current language code (e.g. zh, en).
	Lang string
	// PluginRegistry is the capability plugin registry.
	PluginRegistry *PluginRegistry
	// PolicyManager is the policy versioning manager (task 5a: versioning/rollback/audit).
	// When nil, PUT /plugins degrades to unversioned direct rebuild, GET /policies/* returns 404.
	PolicyManager *PolicyManager
	// ConfirmedRenewalManager is the confirmed renewal state machine (P0-2, P2-A-12/17).
	ConfirmedRenewalManager *ConfirmedRenewalManager
	// AuditIndex is the audit FTS index (monitoring presentation: full-text search). Returns 404 when nil.
	AuditIndex *AuditIndex
	// ConnRegistry is the active connection registry (monitoring: real-time traffic/IP access points/agent directory).
	// Returns empty list when nil.
	ConnRegistry *ConnRegistry
	// ChainRefs is the cross-gateway audit chain reference store (DAG horizontal anchoring).
	// Returns empty peers when nil, but still returns the local chain head.
	ChainRefs *ChainRefStore
}

ManagementServerConfig is the management API server configuration.

type MerkleTree

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

MerkleTree is a Merkle hash tree used for tamper-proof audit chains.

func NewMerkleTree

func NewMerkleTree(leaves [][]byte) *MerkleTree

NewMerkleTree creates a Merkle tree from leaf data.

func (*MerkleTree) Proof

func (m *MerkleTree) Proof(leafIndex int) ([]ProofStep, error)

Proof computes the audit proof path for a given leaf index.

func (*MerkleTree) Root

func (m *MerkleTree) Root() []byte

Root returns the Merkle tree root hash.

func (*MerkleTree) RootHex

func (m *MerkleTree) RootHex() string

RootHex returns the root hash as a hex-encoded string.

type MeshConfig

type MeshConfig struct {
	// LocalName is the name of this node.
	LocalName string `json:"local_name"`
	// TLSConfig is the mTLS configuration for inter-node communication.
	TLSConfig *tls.Config `json:"-"`
	// Peers is the list of peer node addresses.
	Peers []MeshPeer `json:"peers"`
	// DialTimeout is the connection timeout.
	DialTimeout time.Duration `json:"-"`
	// PingInterval is the health check interval for peers.
	PingInterval time.Duration `json:"-"`
}

MeshConfig defines the mesh configuration.

type MeshManager

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

MeshManager manages mesh peer connections and forwarding.

func NewMeshManager

func NewMeshManager(cfg MeshConfig) *MeshManager

NewMeshManager creates a mesh manager.

func (*MeshManager) Broadcast

func (m *MeshManager) Broadcast(msg ControlMessage) error

Broadcast sends a control message to all healthy peers. Each message is sent over an independent short-lived mTLS connection (separate from the data plane forwarding channel), parsed by HandleControlMessage on the remote side. A single peer send failure does not block other nodes; the first error is returned.

func (*MeshManager) BroadcastDisconnect

func (m *MeshManager) BroadcastDisconnect(agentId, reason string) error

BroadcastDisconnect broadcasts a kick notification to all healthy peers. The remote side matches agentId and disconnects all active sessions.

func (*MeshManager) BroadcastPeerSync

func (m *MeshManager) BroadcastPeerSync(version uint64) error

BroadcastPeerSync broadcasts a state summary version number to all healthy peers (peer join sync).

func (*MeshManager) BroadcastRevoke

func (m *MeshManager) BroadcastRevoke(serial, keyHash string) error

BroadcastRevoke broadcasts a revocation notification to all healthy peers. At least one of serial or keyHash must be provided for the remote side to locate the certificate.

func (*MeshManager) Forward

func (m *MeshManager) Forward(peerName string, conn net.Conn) error

Forward opens a new mTLS connection to the target peer and pipes data.

func (*MeshManager) HandleControlMessage

func (m *MeshManager) HandleControlMessage(conn io.ReadWriter) error

HandleControlMessage parses and processes a control plane message (receiver side). Returns nil if processed or deduplicated; returns an error if frame parsing fails. Messages are deduplicated by MsgID before processing; messages originating from this node are ignored (loop prevention).

func (*MeshManager) HealthyPeers

func (m *MeshManager) HealthyPeers() []MeshPeer

HealthyPeers returns the list of currently healthy peer connections.

func (*MeshManager) NewControlMessage

func (m *MeshManager) NewControlMessage(typ ControlMessageType) ControlMessage

NewControlMessage constructs a control message, automatically populating source and timestamp.

func (*MeshManager) SelectPeer

func (m *MeshManager) SelectPeer(tags map[string]string) *MeshPeer

SelectPeer randomly selects a healthy peer by weight.

func (*MeshManager) SendControl

func (m *MeshManager) SendControl(peerName string, msg ControlMessage) error

SendControl sends a single control message to a specified peer.

func (*MeshManager) ServeControlListener

func (m *MeshManager) ServeControlListener(l net.Listener)

ServeControlListener continuously accepts and processes control connections on a listener (receiver entry point). Called by the gateway in the control listening goroutine; returns when the listener is closed or Stop is called. H3 fix: each control connection's peer certificate must carry an admin role — otherwise trust-domain members cannot inject revoke/disconnect messages to kick other agents laterally.

func (*MeshManager) SetControlHandler

func (m *MeshManager) SetControlHandler(fn ControlHandler)

SetControlHandler registers the control plane message callback. Messages from the same source are deduplicated by MsgID, so the handler is not called more than once per message (default dedup window is 5 minutes, see ControlDedupWindow).

func (*MeshManager) Start

func (m *MeshManager) Start() error

Start connects to all peer nodes and starts the health check loop.

func (*MeshManager) StartDedupCleanup

func (m *MeshManager) StartDedupCleanup(interval time.Duration)

StartDedupCleanup periodically cleans up message IDs in the dedup table that exceed the window. Exits with Stop after being called. Uses ControlDedupWindow if interval <= 0.

func (*MeshManager) Stop

func (m *MeshManager) Stop()

Stop closes all mesh connections.

type MeshPeer

type MeshPeer struct {
	Name    string            `json:"name"`
	Address string            `json:"address"`
	Weight  int               `json:"weight,omitempty"`
	Tags    map[string]string `json:"tags,omitempty"`
}

MeshPeer represents a peer gateway node in the mesh.

type MessageImprint

type MessageImprint struct {
	HashAlgorithm AlgorithmIdentifier
	HashedMessage []byte
}

MessageImprint is a message digest imprint.

type MetricCounter

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

MetricCounter is a counter metric.

func NewMetricCounter

func NewMetricCounter(name, help string, labels ...string) *MetricCounter

NewMetricCounter creates a counter metric.

func (*MetricCounter) Add

func (c *MetricCounter) Add(n uint64, labelValues ...string)

Add increments the counter by the specified value.

func (*MetricCounter) Count

func (c *MetricCounter) Count(labelValues ...string) uint64

Count returns the current count for the given label combination (for testing/observation).

func (*MetricCounter) Inc

func (c *MetricCounter) Inc(labelValues ...string)

Inc increments the counter by one.

type MetricGauge

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

MetricGauge is a gauge metric.

func NewMetricGauge

func NewMetricGauge(name, help string, labels ...string) *MetricGauge

NewMetricGauge creates a gauge metric.

func (*MetricGauge) Add

func (g *MetricGauge) Add(delta int64, labelValues ...string)

Add increments the gauge by the specified delta.

func (*MetricGauge) Set

func (g *MetricGauge) Set(n int64, labelValues ...string)

Set sets the gauge value.

func (*MetricGauge) Value

func (g *MetricGauge) Value(labelValues ...string) int64

Value returns the current value for the given label combination (for testing/observation). Returns 0 if not set.

type MetricHistogram

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

MetricHistogram is a histogram metric.

func NewMetricHistogram

func NewMetricHistogram(name, help string, labels []string, bounds ...float64) *MetricHistogram

NewMetricHistogram creates a histogram metric.

func (*MetricHistogram) Observe

func (h *MetricHistogram) Observe(v float64, labelValues ...string)

Observe records a histogram observation.

type MetricSource

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

MetricSource is a simple metric data source that stores a single name and value.

func NewMetricSource

func NewMetricSource(name string, val float64) *MetricSource

NewMetricSource creates a simple metric data source.

func (*MetricSource) Name

func (m *MetricSource) Name() string

Name returns the metric name.

func (*MetricSource) Value

func (m *MetricSource) Value() (float64, bool)

Value returns the metric value.

type MuxStream

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

MuxStream implements net.Conn over a multiplexed mTLS connection.

func (*MuxStream) Close

func (s *MuxStream) Close() error

Close closes the stream (implements net.Conn).

func (*MuxStream) LocalAddr

func (s *MuxStream) LocalAddr() net.Addr

LocalAddr returns the local address (implements net.Conn).

func (*MuxStream) LocalID

func (s *MuxStream) LocalID() uint32

LocalID returns the locally-assigned stream identifier.

func (*MuxStream) Read

func (s *MuxStream) Read(b []byte) (int, error)

Read reads data from the stream (implements net.Conn).

func (*MuxStream) RemoteAddr

func (s *MuxStream) RemoteAddr() net.Addr

RemoteAddr returns the remote address (implements net.Conn).

func (*MuxStream) RemoteID

func (s *MuxStream) RemoteID() uint32

RemoteID returns the remote-assigned stream identifier, or 0 if unknown.

func (*MuxStream) SetDeadline

func (s *MuxStream) SetDeadline(t time.Time) error

SetDeadline sets the deadline (implements net.Conn, currently a no-op).

func (*MuxStream) SetReadDeadline

func (s *MuxStream) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline (implements net.Conn, currently a no-op).

func (*MuxStream) SetWriteDeadline

func (s *MuxStream) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline (implements net.Conn, currently a no-op).

func (*MuxStream) Write

func (s *MuxStream) Write(b []byte) (int, error)

Write writes data to the stream (implements net.Conn).

type NonceCache

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

NonceCache provides a nonce replay protection cache (v1.4 §3.2). Thread-safe with automatic cleanup of expired entries.

func NewNonceCache

func NewNonceCache() *NonceCache

NewNonceCache creates a NonceCache and starts automatic cleanup (hourly, retaining entries within 24h).

func (*NonceCache) CheckAndAdd

func (nc *NonceCache) CheckAndAdd(scope string, nonce []byte) bool

CheckAndAdd checks whether a nonce has been replayed by a different certificate (DA replay attack detection). scope is the certificate identity (issuer/serial), used to distinguish "same cert replaying the same nonce" (normal) from "DA evidence copied into a different cert" (attack). Returns true to allow.

func (*NonceCache) Len

func (nc *NonceCache) Len() int

Len returns the current number of nonces in the cache (for testing and monitoring only).

func (*NonceCache) Stop

func (nc *NonceCache) Stop()

Stop stops the background cleanup goroutine.

type OCSPCache

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

OCSPCache is an OCSP response cache with request coalescing.

func NewOCSPCache

func NewOCSPCache(ttl time.Duration, fallback string, translator Translator, lang string) *OCSPCache

NewOCSPCache creates an OCSP cache instance.

func (*OCSPCache) Check

func (c *OCSPCache) Check(cert, issuer *x509.Certificate) error

Check queries the OCSP responder and caches the result.

func (*OCSPCache) Flush

func (c *OCSPCache) Flush()

Flush clears the OCSP cache.

func (*OCSPCache) SetCRLChecker added in v0.4.0

func (c *OCSPCache) SetCRLChecker(fn CRLRevokedFunc)

SetCRLChecker installs the CRL revocation lookup used by the "crl" OCSP fallback. It must be set for OCSPFallbackCRL to fail closed instead of silently allowing (finding 3).

func (*OCSPCache) Stats

func (c *OCSPCache) Stats() (int, int)

Stats returns the count of good/revoked entries in the OCSP cache.

type OfflineRBAC

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

OfflineRBAC provides offline RBAC decision capability for degraded scenarios where the core is unreachable. Injected with a role list extracted from certificates or configuration at construction time via NewOfflineRBAC.

func NewOfflineRBAC

func NewOfflineRBAC(roles []string) *OfflineRBAC

NewOfflineRBAC creates an offline RBAC instance storing the specified roles.

func NewOfflineRBACFromCert

func NewOfflineRBACFromCert(cert *x509.Certificate) *OfflineRBAC

NewOfflineRBACFromCert creates an offline RBAC instance by extracting roles from a certificate's OU.

func (*OfflineRBAC) CheckRole

func (r *OfflineRBAC) CheckRole(allowed []string) bool

CheckRole checks whether roles contains at least one role from allowed. If roles contains gateway:*, it passes immediately. Supports gateway:* wildcard in allowed.

type PKIStatusInfo

type PKIStatusInfo struct {
	Status int
}

PKIStatusInfo is PKI status information.

type ParameterValidator

type ParameterValidator interface {
	// Scheme returns the schemeId associated with this validator.
	Scheme() string
	// Validate checks whether declared (agent/certificate declaration) falls within
	// granted (principal authorization boundary). Returns a non-nil error if out of bounds
	// (includes the specific parameter name and boundary).
	Validate(granted, declared Capability) error
}

ParameterValidator validates whether a capability declaration's parameters fall within the authorized boundary. Implemented per schemeId (one Scheme → one validator).

var MaxRowsValidator ParameterValidator = maxRowsValidator{}

MaxRowsValidator is an exported instance of the max_rows parameter boundary validator (for registration: NewParameterValidatorRegistry().Register(MaxRowsValidator)).

type ParameterValidatorRegistry

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

ParameterValidatorRegistry manages registration and lookup of parameter boundary validators.

func BuiltinParameterValidators

func BuiltinParameterValidators() *ParameterValidatorRegistry

BuiltinParameterValidators returns the built-in parameter boundary validator registry.

func NewParameterValidatorRegistry

func NewParameterValidatorRegistry() *ParameterValidatorRegistry

NewParameterValidatorRegistry creates an empty parameter boundary validator registry.

func (*ParameterValidatorRegistry) Find

Find looks up the parameter boundary validator for the given schemeId.

func (*ParameterValidatorRegistry) Keys

func (r *ParameterValidatorRegistry) Keys() []string

Keys returns all registered scheme IDs.

func (*ParameterValidatorRegistry) Len

Len returns the number of registered validators.

func (*ParameterValidatorRegistry) Register

Register registers a parameter boundary validator.

func (*ParameterValidatorRegistry) Reset

func (r *ParameterValidatorRegistry) Reset()

Reset clears the registry.

func (*ParameterValidatorRegistry) ValidateCapability

func (r *ParameterValidatorRegistry) ValidateCapability(granted, declared Capability) error

ValidateCapability validates a capability declaration against the authorized boundary using the given registry. Unregistered schemes are allowed (no parameter boundary rules; capability-level intersection was already performed upstream).

type PermissionDef

type PermissionDef = pki.PermissionDef

── Type aliases ──

type PermissionLevel

type PermissionLevel = pki.PermissionLevel

── Type aliases ──

const (
	PermissionAuto             PermissionLevel = 0
	PermissionRequiresApproval PermissionLevel = 1
)

PermissionLevel constants.

type PipelineCheck

type PipelineCheck int

PipelineCheck is the certificate chain check scope type.

const (
	CheckFullChain PipelineCheck = iota
	CheckLeafOnly
)

CheckFullChain/CheckLeafOnly are certificate chain check scope constants.

type PipelineConfig

type PipelineConfig struct {
	// CRLCache is the CRL cache instance.
	CRLCache *CRLCache
	// OCSPCache is the OCSP cache instance.
	OCSPCache *OCSPCache
	// AllowRoles is the list of allowed RBAC roles.
	AllowRoles []string
	// CheckScope controls the CA scope check mode.
	CheckScope PipelineCheck
	// MaxConnsPerCert is the maximum connections per certificate.
	MaxConnsPerCert int
	// RequireAIC requires the client to hold an AIC certificate.
	RequireAIC bool
	// RequireSPIFFE requires the client certificate to carry a SPIFFE ID
	// SAN URI. When set, connections without a SPIFFE ID are rejected.
	RequireSPIFFE bool
	// AllowedSPIFFEIDs is an optional exact-match allowlist of SPIFFE IDs.
	// Empty means no allowlist restriction.
	AllowedSPIFFEIDs []string
	// SPIFFETrustDomain when non-empty requires the client SPIFFE ID to
	// belong to this trust domain (e.g. "varwof.com").
	SPIFFETrustDomain string
	// RequiredProtocol is the transport protocol required by the client.
	RequiredProtocol string
	// RequiredRuleId is the required matching route rule ID.
	RequiredRuleId string
	// RequiredCapabilities is the list of capabilities the client must possess.
	RequiredCapabilities []string
	// DisallowRepresentative disallows delegated representative mode.
	DisallowRepresentative bool
	// RequireUserPermission requires user authorization signature.
	RequireUserPermission bool
	// RejectOverflow rejects when connection limit is exceeded.
	RejectOverflow bool
	// RequireUserAuth requires user authentication.
	RequireUserAuth bool
	// EnforceCapSizeConstraints enforces capability size constraints.
	EnforceCapSizeConstraints bool
	// EnforceSize32 enforces the 32-byte size constraint.
	EnforceSize32 bool
	// CapabilityPluginRegistry is the capability plugin registry.
	CapabilityPluginRegistry *PluginRegistry
	// CapabilityRegistry is the capability registration validation (single source of truth).
	// When non-nil, phase one performs registration validation on AIC-declared capabilities:
	// unregistered → reject connection.
	// nil means disabled (backward compatible).
	CapabilityRegistry CapabilityRegistry
	// CapabilityPluginResolver selects a capability plugin registry by agent identifier
	// (task 5b: branch control/canary).
	// When non-nil, it takes precedence over CapabilityPluginRegistry: the returned registry
	// is used for phase one plugin evaluation, and the returned version number (if non-zero)
	// overrides PolicyVersion for audit binding. Agents matching a branch use the branch
	// version policy; others fall back to the currently active version.
	CapabilityPluginResolver func(agentID string) (version uint64, reg *PluginRegistry)
	// AuditLogger is the audit log recorder.
	AuditLogger *AuditLogger
	// NonceCache is the anti-replay nonce cache.
	NonceCache *NonceCache
	// ClientIP is the client IP address for authorization constraint checks.
	ClientIP string
	// UserCert is the authorized user's certificate, used for DelegationAuthorization
	// signature verification.
	UserCert *x509.Certificate
	// UserCertResolver resolves a user certificate by PrincipalUid.KeyHash
	// (fetched via varwof-core API). Automatically called when UserCert is nil.
	UserCertResolver func(keyHash []byte) (*x509.Certificate, error)
	// EnforceConstraints, when true, enforces authorizationConstraints.
	EnforceConstraints bool
	// StrictConstraints, when true, fails-closed on unknown constraint types (patent spec P1-B-23).
	StrictConstraints bool
	// ParameterValidators is the parameter boundary validator registry
	// (patent spec P1-B-11/P2-B-05).
	// When non-nil, after the P∩C intersection, parameters of AIC declarations and PA
	// authorizations are compared one by one against the boundary; out-of-bounds → reject.
	ParameterValidators *ParameterValidatorRegistry
	// PolicyServer is the Layer 3 online authorization policy server (patent spec P2-A-02).
	// Called by VerifyLayer3/VerifyTrustLayers; not used by RunAccessPipeline.
	PolicyServer PolicyServer
	// CredentialBundle is the client-submitted credential bundle (P1-B-27/P1-B-29/P2-A-01).
	// When RequireUserAuth is enabled, the Principal certificate is preferentially extracted
	// from the credential bundle for DA signature verification.
	CredentialBundle *CredentialBundle
	// PolicyVersion is the policy version effective at decision time (task 5a: decision
	// records bound to policy version).
	// Filled by the gateway from PolicyManager.CurrentVersion() when constructing PipelineConfig;
	// when 0, the audit entry omits this field.
	PolicyVersion uint64
	// RiskMonitor is the high-risk behavior monitor (2026-08-15). When non-nil, the pipeline
	// automatically records violation signals at behavioral rejection points (parameter overflow /
	// plugin deny / CIDR out-of-bounds); once a rule threshold is reached, the gateway's
	// injected OnAction callback executes kick + revocation.
	RiskMonitor *RiskMonitor
	// OfflineMaxCertLifetime is the maximum remaining certificate validity enforced in offline
	// mode (G2(b)).
	// When >0 (e.g., 1h): revocation checks use fail-open (OCSP fallback=allow / CRL unreachable)
	// in offline scenarios; client certificates with remaining validity exceeding this value are
	// rejected — prevents offline fail-open windows from diluting "short-lived certificate"
	// semantics with long-lived certificates. 0 = not enforced.
	OfflineMaxCertLifetime time.Duration
	// HTTPFacts carries per-request HTTP facts (method/path/query/
	// headers) that are copied into the PluginContext for capability
	// plugins. nil means no HTTP facts (TCP/TLS admission path).
	HTTPFacts *HTTPFacts
}

PipelineConfig is the unified admission pipeline configuration.

type PipelineResult

type PipelineResult struct {
	Granted    bool
	DenyReason string
	Roles      []string
	Principal  string
	Serial     string
	AgentId    string
	// SPIFFEID is the SPIFFE ID extracted from the client certificate SAN
	// URI (empty when the certificate carries no SPIFFE URI).
	SPIFFEID string
	// AIC is the AIC extension carried by the admitted connection (parsed result). G3 long-lived
	// connection periodic review requires its AuthorizationConstraints.
	AIC *AIC
	// PrincipalAuthorization is the principal authorization extension carried by the connection
	// (source of the P∩C intersection).
	PrincipalAuthorization *PrincipalAuthorization
}

PipelineResult is the admission pipeline execution result.

func RunAccessPipeline

func RunAccessPipeline(chain []*x509.Certificate, cfg *PipelineConfig) *PipelineResult

RunAccessPipeline executes the unified admission pipeline (CRL→OCSP→RBAC→decision engine).

func VerifyTrustLayers

func VerifyTrustLayers(chain []*x509.Certificate, cfg *PipelineConfig) *PipelineResult

VerifyTrustLayers executes three-layer trust verification in combination (L1 → L2 → L3), equivalent to the explicit layered entry point of RunAccessPipeline. Returns denial on any layer failure.

type PluginAuditEntry

type PluginAuditEntry struct {
	Scheme       string `json:"scheme"`
	CapabilityID string `json:"capability_id"`
	Decision     string `json:"decision"`
	Reason       string `json:"reason"`
	ClientCN     string `json:"client_cn,omitempty"`
	Principal    string `json:"principal,omitempty"`
	// Level is the audit level (INFO/WARN). Allow→INFO, deny/execution error→WARN (spec P2-A-28).
	// Empty value defaults to INFO.
	Level string `json:"level,omitempty"`
	// DaHash is the SHA-256 hash of the DelegationAuthorization signatureValue
	// (Task 4: plugin decision entries also bind authorization evidence fingerprints).
	DaHash string `json:"da_hash,omitempty"`
	// PolicyVersion is the policy version effective at decision time (Task 5a).
	PolicyVersion uint64 `json:"policy_version,omitempty"`
}

PluginAuditEntry records audit fields for plugin decision events.

type PluginConfig

type PluginConfig struct {
	// Type is the plugin type: allowlist / denylist / rbac / webhook.
	Type string `json:"type"`
	// Config is the plugin-specific configuration (JSON serializable).
	Config map[string]interface{} `json:"config"`
}

PluginConfig defines the plugin configuration for a single scheme (JSON serializable).

type PluginConfigs

type PluginConfigs map[string]*PluginConfig

PluginConfigs is a schemeId-keyed plugin configuration map, supporting JSON hot reload.

type PluginContext

type PluginContext = pki.PluginContext

PluginContext is the context during plugin execution.

type PluginDecision

type PluginDecision = pki.PluginDecision

PluginDecision represents the decision result after plugin execution.

const (
	PluginAllow  PluginDecision = pki.PluginAllow
	PluginDeny   PluginDecision = pki.PluginDeny
	PluginBypass PluginDecision = pki.PluginBypass
)

PluginAllow/Deny/Bypass are plugin decision constants.

type PluginRegistry

type PluginRegistry = pki.PluginRegistry

PluginRegistry manages plugin registration and lookup.

func NewPluginRegistry

func NewPluginRegistry() *PluginRegistry

NewPluginRegistry creates a new empty registry.

type PluginResult

type PluginResult = pki.PluginResult

PluginResult is the return result after plugin execution.

func CheckOperationCapability

func CheckOperationCapability(reg *PluginRegistry, cap *Capability, ctx *PluginContext) (*PluginResult, error)

CheckOperationCapability executes phase two (operation layer) plugin decisions (P2-A-06/P2-A-07). Called by the gateway before processing a specific operation (e.g., HTTP route, TCP tunnel, UDP target), making decisions only for the capability corresponding to that operation:

  • Operation scheme has no plugin → fail-closed reject (gateway declares service but no decision rule configured; cannot allow uncontrolled operations);
  • Plugin deny → reject;
  • Plugin allow/bypass → allow.

Complementary to phase one (P∩C intersection + scheme alignment inside RunAccessPipeline): phase one ignores unrelated schemes to allow connections; phase two is fail-closed for operations that will actually be executed.

Returns (PluginResult, error): error indicates only internal execution errors (e.g., webhook call failure); Decision==PluginDeny means the operation is rejected, and the caller should block the operation and record an audit entry accordingly.

func ExecutePlugin

func ExecutePlugin(schemeID string, cap *pki.Capability, ctx *PluginContext) (*PluginResult, error)

ExecutePlugin is a convenience wrapper for findPlugin + Execute.

type PluginSummary

type PluginSummary struct {
	Scheme string `json:"scheme"`
	Type   string `json:"type"`
}

PluginSummary is the plugin summary returned by the management API.

type PolicyBranch

type PolicyBranch struct {
	// ID is the unique branch identifier (e.g., "canary-agent-x").
	ID string `json:"id"`
	// AgentID is the match pattern: exact "a-123" / prefix "a-*" / wildcard "*".
	AgentID string `json:"agent_id"`
	// Version is the policy version number effective when this branch is matched (must be published).
	Version uint64 `json:"version"`
	// Priority determines match order (higher wins); default 0.
	Priority int `json:"priority"`
	// Comment describes the branch (canary scope, rollback plan, etc.).
	Comment string `json:"comment,omitempty"`
}

PolicyBranch defines policy branch rules (task 5b: branch control/canary). Routes specific agents to designated policy versions by agent identifier, enabling canary deployments and multi-policy lines.

type PolicyManager

type PolicyManager struct {

	// MaxHistory is the maximum number of historical snapshots retained (default 64).
	MaxHistory int
	// MinRollbackVersion prevents rollback to versions earlier than this (0=disabled).
	MinRollbackVersion uint64
	// contains filtered or unexported fields
}

PolicyManager manages the versioned lifecycle of the entire policy bundle (PluginConfigs): monotonically increasing version numbers, historical snapshots (configurable limit), rollback (generates new version numbers), branch control (select version by agent identifier, task 5b), and effective version query at decision time (task 5a). Compared to LEE US12676749B1 policy epoch, kept lightweight (does not enable "prevent rollback to before X" by default).

func NewPolicyManager

func NewPolicyManager(registry *PluginRegistry) *PolicyManager

NewPolicyManager creates a policy manager, binding to the target registry.

func (*PolicyManager) ActiveSnapshot

func (pm *PolicyManager) ActiveSnapshot() *PolicySnapshot

ActiveSnapshot returns the currently active version snapshot.

func (*PolicyManager) Branches

func (pm *PolicyManager) Branches() []PolicyBranch

Branches returns the current branch rules (copy).

func (*PolicyManager) ClearBranches

func (pm *PolicyManager) ClearBranches()

ClearBranches clears all branch rules (reverts to using the currently active version for all).

func (*PolicyManager) CurrentVersion

func (pm *PolicyManager) CurrentVersion() uint64

CurrentVersion returns the currently active policy version number.

func (*PolicyManager) History

func (pm *PolicyManager) History() []*PolicySnapshot

History returns historical snapshots (including current, ascending order).

func (*PolicyManager) Publish

func (pm *PolicyManager) Publish(configs PluginConfigs, source, operator string) (uint64, error)

Publish publishes a new version and applies it to the registry (shared by PUT /plugins and SIGHUP). source is "api" or "sighup"; operator is the API operator CN (may be empty for SIGHUP). Returns the new version number.

func (*PolicyManager) Registry

func (pm *PolicyManager) Registry() *PluginRegistry

Registry returns the bound registry.

func (*PolicyManager) Reset

func (pm *PolicyManager) Reset()

Reset resets to an empty policy (clears all version history, branches, and registry). For testing and full rebuild.

func (*PolicyManager) Rollback

func (pm *PolicyManager) Rollback(version uint64, source, operator string) (uint64, error)

Rollback rolls back to a specified version (generates a new version number, does not decrease the version number itself). Applies the snapshot of the specified version to rebuild the registry and records the rollback source.

func (*PolicyManager) SelectRegistry

func (pm *PolicyManager) SelectRegistry(agentID string) (uint64, *PluginRegistry)

SelectRegistry selects the effective policy version and corresponding plugin registry by agent identifier (task 5b). Rules are matched in descending Priority order: a matching branch returns that version's registry and version number; no match returns the currently active version. version=0 means the current version.

func (*PolicyManager) SetBranches

func (pm *PolicyManager) SetBranches(branches []PolicyBranch) error

SetBranches fully replaces branch rules (task 5b: branch control/canary). Validates: ID uniqueness, non-empty AgentID, referenced version must be published. Any invalid entry causes the entire operation to be rejected.

type PolicyNamespace

type PolicyNamespace struct {
	DisplayName string   `json:"display_name"`
	Prefix      string   `json:"prefix"`
	Grants      []string `json:"grants"`
}

PolicyNamespace defines the grants for a gateway namespace.

type PolicyRole

type PolicyRole struct {
	DisplayName string   `json:"display_name"`
	Profiles    []string `json:"profiles"`
	Grants      []string `json:"grants"`
	Scope       []string `json:"scope,omitempty"`
}

PolicyRole defines a single role's display name, profiles, grants, and scope.

type PolicyServer

type PolicyServer interface {
	// Name returns the policy server name (for auditing).
	Name() string
	// CheckOnline checks online authorization (leaf certificate + parsed AIC).
	// Returns nil for authorization granted; non-nil for denial (with reason).
	CheckOnline(leaf *x509.Certificate, aic *AIC) error
}

PolicyServer is the Layer 3 online authorization policy server interface (spec P2-A-02 Layer 3). Online authorization verification includes revocation freshness (OCSP/CRL, handled by PipelineConfig's cache instances) and policy server policy checks (if configured).

type PolicySigningConfig

type PolicySigningConfig struct {
	// Enabled enables policy signature verification.
	Enabled bool `json:"enabled,omitempty"`
	// CAFile is the trusted CA chain PEM (defaults to tls_client_ca).
	CAFile string `json:"ca_file,omitempty"`
	// RequireAdminOU requires the signer to have admin OU (nil=defaults to true).
	RequireAdminOU *bool `json:"require_admin_ou,omitempty"`
	// Require: true=reject if signature is missing; false=degrade with warning if missing.
	Require bool `json:"require,omitempty"`
	// SigSuffix is the signature file suffix (default ".sig").
	SigSuffix string `json:"sig_suffix,omitempty"`
}

PolicySigningConfig configures PKCS#7 detached signature verification for the gateway authz.json policy file. Structurally identical to varwof-core's policy_signing configuration.

func (*PolicySigningConfig) BuildPolicyVerifyOptions

func (ps *PolicySigningConfig) BuildPolicyVerifyOptions(tlsClientCA string) (*PolicyVerifyOptions, error)

BuildPolicyVerifyOptions builds signature verification parameters from PolicySigningConfig. Returns nil if signature verification is not enabled (signing disabled). tlsClientCA is used as the default fallback when CAFile is empty.

type PolicySigningIdentity

type PolicySigningIdentity struct {
	Cert *x509.Certificate
	Key  crypto.Signer
}

PolicySigningIdentity describes the admin identity used to sign the policy file.

func LoadPolicySigningIdentity

func LoadPolicySigningIdentity(certPEM, keyPEM string) (*PolicySigningIdentity, error)

LoadPolicySigningIdentity loads the signer certificate and private key from PEM files.

type PolicySnapshot

type PolicySnapshot struct {
	// Version is the policy version number (monotonically increasing, never decreases).
	Version uint64 `json:"version"`
	// Source is the origin: SIGHUP / API.
	Source string `json:"source"`
	// Operator is the operator (for API, it is the client certificate CN).
	Operator string `json:"operator,omitempty"`
	// RolledBackFrom records which version this rollback was initiated from (if applicable).
	RolledBackFrom uint64 `json:"rolled_back_from,omitempty"`
	// Timestamp is the creation time (RFC3339).
	Timestamp time.Time `json:"timestamp"`
	// Configs is the plugin configuration for this version (full snapshot, rebuildable on rollback).
	Configs PluginConfigs `json:"configs"`
}

PolicySnapshot is a policy version snapshot (task 5a: policy config versioning + anti-rollback).

func (*PolicySnapshot) SnapshotJSON

func (s *PolicySnapshot) SnapshotJSON() map[string]interface{}

SnapshotJSON returns the JSON representation of a version snapshot (for management API).

type PolicyVerifyOptions

type PolicyVerifyOptions struct {
	// Roots is the trusted CA chain (Issuing CA + Root CA) for verifying the signer certificate.
	Roots *x509.CertPool
	// RequireAdminOU, when true, requires the signer certificate OU to contain the admin role.
	RequireAdminOU bool
}

PolicyVerifyOptions describes the external parameters needed for signature verification.

type PrincipalAuthorization

type PrincipalAuthorization = pki.PrincipalAuthorization

── Type aliases ──

func ParseUserPermissionExtension

func ParseUserPermissionExtension(cert *x509.Certificate) (*PrincipalAuthorization, error)

ParseUserPermissionExtension delegates to pki-types.

type PrincipalUid

type PrincipalUid = pki.PrincipalUid

── Type aliases ──

func MakePrincipalUidFromCert

func MakePrincipalUidFromCert(realm, identifier string, certDER []byte) PrincipalUid

MakePrincipalUidFromCert constructs a PrincipalUid from a certificate DER (KeyHash = SPKI SHA-256, per spec §PrincipalUid).

func ParsePrincipalUid

func ParsePrincipalUid(s string) (PrincipalUid, error)

ParsePrincipalUid delegates to pki-types.

type ProofStep

type ProofStep struct {
	Sibling []byte `json:"sibling"`
	Left    bool   `json:"left"`
}

ProofStep is a single step in a Merkle audit proof, containing a sibling hash and direction.

type ProofStepJSON

type ProofStepJSON struct {
	Sibling string `json:"sibling"`
	Left    bool   `json:"left"`
}

ProofStepJSON is the JSON representation of an audit proof step.

type Reason

type Reason = pki.Reason

── Type aliases ──

type RenewalConfirmation

type RenewalConfirmation struct {
	// SessionID matches RenewalRequest.SessionID.
	SessionID string
	// DA is the DelegationAuthorization re-signed by the responsible party (output of SignRenewalDA).
	DA DelegationAuthorization
	// PrincipalCert is the responsible party certificate (basis for signature verification + permission recheck).
	PrincipalCert *x509.Certificate
	// KeyHash is the responsible party SPKI hash (for cross-validation with AIC PrincipalUid.KeyHash, optional).
	KeyHash []byte
}

RenewalConfirmation is the information after responsible party confirmation (Confirm input).

type RenewalDAPayload

type RenewalDAPayload struct {
	ReasonCode         string `json:"reason_code"`
	ReasonDesc         string `json:"reason_description,omitempty"`
	RequestedLifetime  int    `json:"requested_lifetime"`
	Timestamp          string `json:"timestamp"`
	Nonce              []byte `json:"nonce"`
	SignatureAlgorithm string `json:"signature_algorithm"`
	SignatureValue     []byte `json:"signature_value"`
}

RenewalDAPayload is the JSON carrier for the responsible party's re-signed DA (SignRenewalDA output → management API).

func DAToPayload

DAToPayload serializes the DelegationAuthorization re-signed by the responsible party into a management API JSON payload. The responsible party client obtains the DA via SignRenewalDA, calls this function to pack it, and POSTs to /api/v1/gateway/renewal/confirm.

type RenewalRequest

type RenewalRequest struct {
	// SessionID is the original session identifier carried by the renewal request (P2-A-12, not written to cert).
	SessionID string `json:"session_id"`
	// CA is the target issuing CA name.
	CA string `json:"ca,omitempty"`
	// CN is the certificate common name.
	CN string `json:"cn"`
	// SAN is the certificate SAN (optional).
	SAN string `json:"san,omitempty"`
	// AgentId is the retained agentId.
	AgentId string `json:"agent_id,omitempty"`
	// PrincipalUid is the responsible party UID.
	PrincipalUid string `json:"principal_uid,omitempty"`
	// Capabilities are the capabilities to retain in the new cert (for new ⊆ responsible party PA grants check).
	Capabilities []Capability `json:"capabilities,omitempty"`
	// OldSerial is the old certificate serial number (for transition marking).
	OldSerial string `json:"old_serial,omitempty"`
	// OldCert is the old certificate (for transition marking, contains NotAfter).
	OldCert *x509.Certificate `json:"-"`
	// RequesterKeyHash is the SPKI SHA-256 hash of the authenticated entity that
	// triggered the renewal request (captured server-side from the management
	// mTLS peer, not decoded from JSON). Confirm rejects when the confirming
	// responsible party is the same entity (two-party control, finding 2).
	RequesterKeyHash string `json:"-"`
	// Validity is the new certificate validity (days).
	Validity int `json:"validity,omitempty"`
	// Profile is the issuance profile.
	Profile string `json:"profile,omitempty"`
}

RenewalRequest is the registration information for a renewal request (input for entering the awaiting confirmation state).

type RenewalState

type RenewalState int

RenewalState is the state of the confirmed renewal state machine.

const (
	// RenewalIdle indicates no in-progress renewal request.
	RenewalIdle RenewalState = iota
	// RenewalAwaitingConfirmation means renewal was triggered and awaits responsible party confirmation (P2-A-12).
	RenewalAwaitingConfirmation
	// RenewalConfirmed means the responsible party confirmed, new cert issued successfully, old cert marked for transition.
	RenewalConfirmed
	// RenewalRejected means the renewal was rejected (permissions reduced or responsible party refused).
	RenewalRejected
)

RenewalState values.

func (RenewalState) String

func (s RenewalState) String() string

String returns the human-readable name of the state.

type RenewalTokenExt

type RenewalTokenExt struct {
	Version        int          `asn1:"default:1"`
	PrincipalUid   PrincipalUid `asn1:"optional,contextspecific,tag:0"`
	OldCertSerial  []byte       `asn1:"octet"`
	NewKeyHash     []byte       `asn1:"octet"`
	Timestamp      time.Time    `asn1:"generalized"`
	Nonce          []byte       `asn1:"octet"` // SIZE(16)
	ValidityPeriod int          `asn1:"default:300"`
}

RenewalTokenExt is the ASN.1 serialization structure for RenewalToken (I-D §6). The spec defines 7 fields: version, principalUid, oldCertSerial, newKeyHash, timestamp, nonce, validityPeriod.

func ParseRenewalToken

func ParseRenewalToken(exts []pkix.Extension) (*RenewalTokenExt, error)

ParseRenewalToken parses a RenewalToken from certificate extensions.

func (*RenewalTokenExt) IsExpired

func (r *RenewalTokenExt) IsExpired() bool

IsExpired checks whether the RenewalToken has expired.

func (*RenewalTokenExt) ValidateConstraints

func (r *RenewalTokenExt) ValidateConstraints() error

ValidateConstraints validates the RenewalToken constraints (spec §6).

func (*RenewalTokenExt) VerifyNonce

func (r *RenewalTokenExt) VerifyNonce() bool

VerifyNonce verifies that the nonce is 16 bytes long (spec §6: SIZE(16)).

type ResourceScope

type ResourceScope = pki.ResourceScope

── Type aliases ──

type RevokeRequest

type RevokeRequest struct {
	Reason string `json:"reason,omitempty"`
}

RevokeRequest is the JSON body of a revocation request.

type Revoker

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

Revoker handles certificate revocation.

func NewRevoker

func NewRevoker(cfg RevokerConfig) (*Revoker, error)

NewRevoker creates a revocation client. Returns an error if the mTLS certificate fails to load.

func (*Revoker) Registry

func (r *Revoker) Registry() *ConnExpiryRegistry

Registry returns the associated ConnExpiryRegistry (may be nil).

func (*Revoker) RevokeClientCert

func (r *Revoker) RevokeClientCert(cert *x509.Certificate, audit *AuditLogger)

RevokeClientCert conditionally revokes the given client certificate. Condition: only revokes certificates that have not expired (expired certs don't need revocation, wasting an API call). If a ConnExpiryRegistry is associated and the serial number has been renewed (P2-A-15), revocation is also skipped. Extracts Issuer.CommonName from the certificate, maps it to the CA internal name via ca_map, then calls the varwof-core revoke API. Retries on failure and logs audit entries.

func (*Revoker) RevokeClientCertForced

func (r *Revoker) RevokeClientCertForced(cert *x509.Certificate, audit *AuditLogger)

RevokeClientCertForced forcefully revokes the given client certificate (G2(c)). Unlike RevokeClientCert: bypasses the ConnExpiryRegistry renewal-marker skip (renewed-skip only applies to "passive disconnection revocation", i.e., the connection close revocation when a certificate is superseded by renewal; security-triggered active revocation—risk monitor kick, task completion revocation, admin kick—must not be allowed through by the renewed flag, otherwise an attacker could mark a certificate as renewed to permanently escape revocation). Other conditions (not-expired, ca_map, retry, audit) remain unchanged.

func (*Revoker) SetConnRegistry

func (r *Revoker) SetConnRegistry(reg *ConnExpiryRegistry)

SetConnRegistry associates a ConnExpiryRegistry (P2-A-15 renewal marker linkage). If the registry determines a certificate should be skipped (renewed or expired), no revocation is initiated.

type RevokerConfig

type RevokerConfig struct {
	// CoreURL is the base URL of the varwof-core API, e.g. "https://core.varwof.com:4433/api/v1".
	CoreURL string `json:"core_url"`
	// MTLSCertFile and MTLSKeyFile are the gateway's own mTLS client certificate,
	// which must have revocation privileges (gateway:revoker role).
	MTLSCertFile string `json:"mtls_cert_file"`
	// MTLSKeyFile is the path to the mTLS client private key.
	MTLSKeyFile string `json:"mtls_key_file"`
	// CAMap maps certificate Issuer.CommonName to varwof-core's internal CA name.
	// Example: {"Varwof Issuing CA": "issuing", "Varwof Client CA": "client"}
	CAMap map[string]string `json:"ca_map"`
	// Timeout is the HTTP request timeout, default 10 seconds.
	Timeout time.Duration `json:"timeout,omitempty"`
	// RetryCount is the number of retries on revocation failure, default 2.
	RetryCount int `json:"retry_count,omitempty"`
}

RevokerConfig is the configuration for the certificate revoker.

type RiskMonitor

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

RiskMonitor maintains per-agent violation counts and enforces rules automatically. Thread-safe; nil receiver methods are no-ops (safe to call when gateway is not configured).

func NewRiskMonitor

func NewRiskMonitor(cfg RiskMonitorConfig) *RiskMonitor

NewRiskMonitor creates a risk monitor.

func (*RiskMonitor) RecordViolation

func (m *RiskMonitor) RecordViolation(v RiskViolation) bool

RecordViolation records a behavioral violation and evaluates rules; triggers the enforcement callback when the threshold is reached. Returns whether enforcement was triggered. Returns false for nil receiver.

func (*RiskMonitor) Rules

func (m *RiskMonitor) Rules() []RiskRule

Rules returns a copy of the current rule list.

func (*RiskMonitor) SetRules

func (m *RiskMonitor) SetRules(rules []RiskRule)

SetRules hot-swaps the rule set (called during SIGHUP hot-reload).

func (*RiskMonitor) Violations

func (m *RiskMonitor) Violations(agentId string) int

Violations returns the cumulative violation count for an agent within the window (used for monitoring display when no enforcement has been triggered). Returns 0 for nil receiver.

type RiskMonitorConfig

type RiskMonitorConfig struct {
	// Rules is the list of risk rules.
	Rules []RiskRule `json:"rules"`
	// OnAction is the enforcement callback (gateway injects: execute disconnect + revoke).
	// When nil, only logging is performed.
	OnAction func(agentId, action, reason string)
	// Logger is the structured logger; uses slog.Default() when nil.
	Logger *slog.Logger
}

RiskMonitorConfig is the configuration for RiskMonitor.

type RiskRule

type RiskRule struct {
	// Name is the rule name.
	Name string `json:"name"`
	// Signals is the list of behavioral signal types that trigger the rule (any hit counts).
	Signals []string `json:"signals"`
	// Threshold is the violation count threshold within the window; reaching it triggers enforcement.
	Threshold int `json:"threshold"`
	// WindowSeconds is the counting window in seconds, default 60.
	WindowSeconds int `json:"window_seconds,omitempty"`
	// Action is the enforcement action: disconnect (kick) or revoke (kick + revoke).
	Action string `json:"action"`
	// Reason is the risk reason description for audit records.
	Reason string `json:"reason"`
}

RiskRule is a single risk rule.

type RiskViolation

type RiskViolation struct {
	// AgentId is the violating agent.
	AgentId string `json:"agent_id,omitempty"`
	// Signal is the risk signal type (e.g. cap_overflow / abnormal_rate / out_of_window).
	Signal string `json:"signal"`
	// CapabilityId is the associated capability identifier (optional).
	CapabilityId string `json:"capability_id,omitempty"`
	// Details provides supplementary description.
	Details string `json:"details,omitempty"`
	// At is the violation time (Unix seconds).
	At int64 `json:"at"`
}

RiskViolation describes a recorded behavioral violation (risk signal).

type RoleDef

type RoleDef = pki.RoleDef

── Type aliases ──

type RotatingFile

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

RotatingFile is an auto-rotating file that supports size-based rotation and backup count limits.

func NewRotatingFile

func NewRotatingFile(path string, maxSize int64, maxBak int) (*RotatingFile, error)

NewRotatingFile creates an auto-rotating file instance.

func (*RotatingFile) Close

func (r *RotatingFile) Close() error

Close closes the rotating file.

func (*RotatingFile) Write

func (r *RotatingFile) Write(p []byte) (int, error)

Write implements io.Writer with automatic rotation.

type SM2BundleInput added in v0.5.0

type SM2BundleInput struct {
	// LeafDER 是客户端叶子证书 DER(SM2 签发)。
	LeafDER []byte
	// Intermediates 是可选的中间 CA 证书 DER。
	Intermediates [][]byte
	// Roots 是受信根 CA 证书 DER 集合(链必须终止于其中之一)。
	Roots [][]byte
	// Data 是待验签数据(由叶子证书持有者密钥签名的原文)。
	// 仅当 Signature 非空时参与验证。
	Data []byte
	// Signature 是 SM2 签名(ASN.1 DER 编码 r||s),由叶子证书持有者密钥生成。
	// 空值表示本入口只做链验证与 AIC 提取,不要求主体签名。
	Signature []byte
	// RequireAIC 为 true 时,叶子证书必须携带可解析的 AIC 扩展,否则拒绝。
	RequireAIC bool
	// AuditLogger 非空时,验证失败会写一条 denied 审计记录(原因码嵌入
	// deny_reason)。nil 表示不写审计(由适配层自行处理)。
	AuditLogger *AuditLogger
	// SrcIP / MappingName / Target 透传给审计记录(可选)。
	SrcIP       string
	MappingName string
	Target      string
	// Now 是链有效期校验的基准时刻;零值表示使用实时时间(time.Now())。
	// 供测试注入固定时刻,生产调用保持默认即可。
	Now time.Time
}

SM2BundleInput 是 SM2 验证核心的最小公共验证入口入参,与具体传输解耦: 适配层(自终止 TLS 自定义验证 / 透传证书链头)只需把原始字节填入本结构并 调用 VerifySM2Bundle。

type SM2BundleResult added in v0.5.0

type SM2BundleResult struct {
	// Cert 是解析后的叶子证书(stdlib *x509.Certificate,可复用 ParseAIC /
	// ExtractRoles 等既有提取逻辑)。
	Cert *x509.Certificate
	// AIC 是叶子证书携带的 AIC 扩展解析结果;证书无 AIC 扩展时为 nil。
	AIC *AIC
}

SM2BundleResult 是验证成功后的结果。

func VerifySM2Bundle added in v0.5.0

func VerifySM2Bundle(in SM2BundleInput) (*SM2BundleResult, error)

VerifySM2Bundle 默认构建下不可用。

type SM2VerifyError added in v0.5.0

type SM2VerifyError struct {
	// Code 是稳定原因码(见 SM2Reason* 常量)。
	Code string
	// Detail 是供人读的详细描述。
	Detail string
}

SM2VerifyError 是国密验证核心返回的错误,携带稳定原因码。 适配层(审计/上报)应读取 Code 而非解析 Error() 文案。

func (*SM2VerifyError) Error added in v0.5.0

func (e *SM2VerifyError) Error() string

type SPIFFEID

type SPIFFEID struct {
	TrustDomain string
	Path        string
}

SPIFFEID represents a parsed SPIFFE identity.

func ExtractSPIFFEID

func ExtractSPIFFEID(cert *x509.Certificate) *SPIFFEID

ExtractSPIFFEID extracts a parsed SPIFFE ID from a certificate's SAN URIs. Returns nil if no valid SPIFFE URI is found.

func ParseSPIFFEID

func ParseSPIFFEID(id string) (*SPIFFEID, error)

ParseSPIFFEID parses a SPIFFE ID string into its components (trust domain, path).

Per RFC 7555 §2.1 a trust domain is case-insensitive, so the parsed trust domain is canonicalized to lowercase and validated against the trust-domain character set [a-z0-9-._] (at least one dot). The path is preserved verbatim (path segments are case-sensitive).

func (*SPIFFEID) Equal

func (s *SPIFFEID) Equal(other *SPIFFEID) bool

Equal checks whether two SPIFFEID values are identical.

func (*SPIFFEID) String

func (s *SPIFFEID) String() string

String returns the SPIFFE ID in URI format.

type SealedTree

type SealedTree struct {
	BatchNumber int    `json:"batch"`
	Timestamp   string `json:"timestamp"`
	Previous    string `json:"previous_root"`
	Root        string `json:"root"`
	Size        int    `json:"size"`
}

SealedTree is a sealed Merkle tree batch with root hash and predecessor link.

type SelfVerifyOptions

type SelfVerifyOptions struct {
	// SigPath is the path to the detached signature file (PKCS#7 .p7s).
	// Defaults to exePath+".p7s" when empty.
	SigPath string
	// Roots is the trusted CA pool for verifying the signer certificate chain.
	// When nil, only the signature is verified without chain validation.
	Roots *x509.CertPool
	// RequireExecutable checks that exePath falls within the expected location
	// for executables (prevents accidentally passing a config file path as the target program).
	RequireExecutable bool
}

SelfVerifyOptions describes the parameters required for binary self-verification.

type SignedAuditEntry

type SignedAuditEntry struct {
	Entry AuditEntry `json:"entry"`
	TST   string     `json:"tst,omitempty"`
}

SignedAuditEntry is an audit entry with TSA timestamp signature.

type SnapshotSource

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

SnapshotSource is a snapshot metric data source that retrieves metric values via a callback function.

func NewSnapshotSource

func NewSnapshotSource(fn func() map[string]float64) *SnapshotSource

NewSnapshotSource creates a snapshot metric data source.

func (*SnapshotSource) Name

func (s *SnapshotSource) Name() string

Name returns the snapshot source name.

func (*SnapshotSource) Value

func (s *SnapshotSource) Value() (float64, bool)

Value returns the connection metric value from the snapshot source.

type StopGuard

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

StopGuard is a unified idempotent shutdown guard.

func NewStopGuard

func NewStopGuard() *StopGuard

NewStopGuard creates a stop guard.

func (*StopGuard) IsStopped

func (s *StopGuard) IsStopped() bool

IsStopped checks whether shutdown has been triggered.

func (*StopGuard) Reset

func (s *StopGuard) Reset()

Reset resets the stopped state (for testing or post-renewal use only).

func (*StopGuard) Stop

func (s *StopGuard) Stop() bool

Stop triggers shutdown (idempotent, returns whether it was the first call).

func (*StopGuard) StopChan

func (s *StopGuard) StopChan() <-chan struct{}

StopChan returns the stop signal channel.

type StreamMux

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

StreamMux manages multiple virtual streams over a single net.Conn.

func NewStreamMux

func NewStreamMux(conn net.Conn) *StreamMux

NewStreamMux creates a multiplexer over an existing connection.

func (*StreamMux) Accept

func (m *StreamMux) Accept() (*MuxStream, error)

Accept waits for and returns the next incoming virtual stream.

func (*StreamMux) Close

func (m *StreamMux) Close() error

Close shuts down the multiplexer and all its active streams.

func (*StreamMux) Open

func (m *StreamMux) Open() (*MuxStream, error)

Open opens a new virtual stream. Blocks until the remote accepts.

type TCPExtra

type TCPExtra struct {
	// RequireDelegation whether dual-certificate delegation mode is required (Agent + User).
	RequireDelegation *bool `json:"require_delegation,omitempty"`

	// MaxConnectionDurationSec is the max connection duration in seconds (0=unlimited).
	MaxConnectionDurationSec int `json:"max_connection_duration_sec,omitempty"`

	// SessionTimeoutSec is the session validity period in seconds (0=unlimited).
	SessionTimeoutSec int `json:"session_timeout_sec,omitempty"`

	// ConstraintRecheckSec is the periodic recheck interval for authorizationConstraints
	// in long-lived connections (0=disabled).
	ConstraintRecheckSec int `json:"constraint_recheck_sec,omitempty"`

	// HealthCheckSec is the backend health check interval in seconds (0=no check).
	HealthCheckSec int `json:"health_check_sec,omitempty"`

	// HealthCheckURL is the health check URL (HTTP mode).
	HealthCheckURL string `json:"health_check_url,omitempty"`

	// DialTimeoutSec is the backend dial timeout in seconds (default 10).
	DialTimeoutSec int `json:"dial_timeout_sec,omitempty"`

	// RenewalEnabled whether to enable auto-renewal.
	RenewalEnabled *bool `json:"renewal_enabled,omitempty"`

	// RenewalWindowSec is the renewal advance window in seconds.
	RenewalWindowSec int `json:"renewal_window_sec,omitempty"`
}

func (*TCPExtra) ConstraintRecheckInterval

func (t *TCPExtra) ConstraintRecheckInterval() time.Duration

func (*TCPExtra) DialTimeout

func (t *TCPExtra) DialTimeout() time.Duration

func (*TCPExtra) HealthCheckInterval

func (t *TCPExtra) HealthCheckInterval() time.Duration

func (*TCPExtra) MaxConnectionDuration

func (t *TCPExtra) MaxConnectionDuration() time.Duration

func (*TCPExtra) RenewalEnabledOrDefault

func (t *TCPExtra) RenewalEnabledOrDefault() bool

func (*TCPExtra) RenewalWindow

func (t *TCPExtra) RenewalWindow() time.Duration

func (*TCPExtra) RequireDelegationEnabled

func (t *TCPExtra) RequireDelegationEnabled() bool

func (*TCPExtra) SessionTimeout

func (t *TCPExtra) SessionTimeout() time.Duration

type TLSConfig

type TLSConfig struct {
	// Mode is the TLS authentication mode: none / server / mtls.
	Mode string `json:"mode,omitempty"`

	// CACertFile is the CA certificate file path (required for mtls mode, used to verify clients).
	CACertFile string `json:"ca_cert_file,omitempty"`

	// JWTCAFile is an optional CA certificate file for verifying AIC-JWT
	// bearer tokens (HTTP only). When set, requests without an mTLS client
	// certificate may authenticate via Authorization: Bearer <AIC-JWT>,
	// verified against this trust root (same kid convention as the X.509
	// carrier). Empty disables bearer authentication.
	JWTCAFile string `json:"jwt_ca_file,omitempty"`

	// JWTIssuer is the expected iss claim for bearer tokens. When empty the
	// issuer is not checked; set it to bind bearers to a specific issuer
	// (finding 5).
	JWTIssuer string `json:"jwt_issuer,omitempty"`

	// JWTAudience lists the acceptable aud claims for bearer tokens. When empty
	// the audience is not checked; set it to prevent audience confusion
	// (finding 5).
	JWTAudience []string `json:"jwt_audience,omitempty"`

	// JWTReplayProtection enables one-time-use jti/DA-nonce replay protection
	// for bearer tokens (process-local store). Default true when JWTCAFile is
	// set; multi-node deployments should supply a shared nonce store instead
	// (finding 5).
	JWTReplayProtection *bool `json:"jwt_replay_protection,omitempty"`

	// CertFile is the server certificate file path (required for server/mtls modes).
	CertFile string `json:"cert_file,omitempty"`

	// KeyFile is the server private key file path (required for server/mtls modes).
	KeyFile string `json:"key_file,omitempty"`

	// MinTLSVersion is the minimum TLS version (e.g. "1.2", "1.3").
	MinTLSVersion string `json:"min_tls_version,omitempty"`

	// CipherSuites is the list of TLS cipher suite names.
	CipherSuites []string `json:"cipher_suites,omitempty"`

	// CRLURL is the CRL distribution point URL.
	CRLURL string `json:"crl_url,omitempty"`

	// CRLRefreshSec is the CRL cache refresh interval in seconds (default 300).
	CRLRefreshSec int `json:"crl_refresh_sec,omitempty"`

	// OCSPCacheTTLSec is the OCSP response cache TTL in seconds (default 300).
	OCSPCacheTTLSec int `json:"ocsp_cache_ttl_sec,omitempty"`

	// OCSPFallback is the OCSP degradation policy when unavailable: deny / allow.
	OCSPFallback string `json:"ocsp_fallback,omitempty"`

	// TSAURL is the TSA timestamp service URL.
	TSAURL string `json:"tsa_url,omitempty"`

	// TSACertFile is the TSA certificate file path.
	TSACertFile string `json:"tsa_cert_file,omitempty"`

	// AuditFile is the audit log output file path.
	AuditFile string `json:"audit_file,omitempty"`

	// AuditMaxSizeMB is the max audit log file size in MB (default 100).
	AuditMaxSizeMB int `json:"audit_max_size_mb,omitempty"`

	// AuditMaxBackups is the max number of audit log backup files to retain (default 3).
	AuditMaxBackups int `json:"audit_max_backups,omitempty"`

	// MaxConnsPerIP is the max connections per IP (0=unlimited).
	MaxConnsPerIP int `json:"max_conns_per_ip,omitempty"`

	// MaxConnsPerCert is the max connections per certificate (0=unlimited).
	MaxConnsPerCert int `json:"max_conns_per_cert,omitempty"`

	// MaxTotalConns is the global max connections (0=unlimited).
	MaxTotalConns int `json:"max_total_conns,omitempty"`

	// IdleTimeoutSec is the idle timeout in seconds (0=unlimited).
	IdleTimeoutSec int `json:"idle_timeout_sec,omitempty"`

	// RequireAIC specifies whether clients must hold an AIC certificate.
	RequireAIC *bool `json:"require_aic,omitempty"`

	// DisallowRepresentative prohibits the delegated representative mode.
	DisallowRepresentative *bool `json:"disallow_representative,omitempty"`

	// RequireUserAuth specifies whether user authentication is required.
	RequireUserAuth *bool `json:"require_user_auth,omitempty"`

	// RequireSPIFFE requires the client certificate to carry a SPIFFE ID
	// SAN URI; connections without one are rejected.
	RequireSPIFFE *bool `json:"require_spiffe,omitempty"`

	// AllowedSPIFFEIDs is an optional exact-match allowlist of SPIFFE IDs.
	AllowedSPIFFEIDs []string `json:"allowed_spiffe_ids,omitempty"`

	// SPIFFETrustDomain when non-empty requires the client SPIFFE ID to
	// belong to this trust domain (e.g. "varwof.com").
	SPIFFETrustDomain string `json:"spiffe_trust_domain,omitempty"`

	// DisconnectOnExpiry auto-disconnects when certificate expires (default true).
	DisconnectOnExpiry *bool `json:"disconnect_on_expiry,omitempty"`

	// AllowRoles is the list of allowed RBAC roles.
	AllowRoles []string `json:"allow_roles,omitempty"`

	// RequiredCapabilities is the list of capabilities the client must have.
	RequiredCapabilities []string `json:"required_capabilities,omitempty"`

	// CapabilityScheme is the capability scheme ID.
	CapabilityScheme string `json:"capability_scheme,omitempty"`
}

func (*TLSConfig) AuditMaxBackupCount

func (t *TLSConfig) AuditMaxBackupCount() int

func (*TLSConfig) AuditMaxSize

func (t *TLSConfig) AuditMaxSize() int64

func (*TLSConfig) CRLRefreshDuration

func (t *TLSConfig) CRLRefreshDuration() time.Duration

func (*TLSConfig) DisallowRepresentativeEnabled

func (t *TLSConfig) DisallowRepresentativeEnabled() bool

func (*TLSConfig) DisconnectOnExpiryEnabled

func (t *TLSConfig) DisconnectOnExpiryEnabled() bool

func (*TLSConfig) IdleTimeout

func (t *TLSConfig) IdleTimeout() time.Duration

func (*TLSConfig) RequireAICEnabled

func (t *TLSConfig) RequireAICEnabled() bool

func (*TLSConfig) RequireSPIFFEEnabled

func (t *TLSConfig) RequireSPIFFEEnabled() bool

func (*TLSConfig) RequireUserAuthEnabled

func (t *TLSConfig) RequireUserAuthEnabled() bool

func (*TLSConfig) ToGoTLSConfig

func (t *TLSConfig) ToGoTLSConfig() *tls.Config

ToGoTLSConfig converts the TLSConfig to a Go tls.Config for the server side. This is a helper for gateways that need to build tls.Config from the JSON config.

type TSAClient

type TSAClient struct {
	// URL is the TSA service address.
	URL string
	// CACert is the CA certificate (for verifying TSA response signatures).
	CACert *x509.Certificate
	// HTTPClient is the HTTP client.
	HTTPClient *http.Client
	// SignFunc is a custom signing function (replaces HTTP calls).
	SignFunc func(data []byte) ([]byte, error)
	// contains filtered or unexported fields
}

TSAClient is an RFC 3161 timestamp client.

func NewTSAClient

func NewTSAClient(url string) *TSAClient

NewTSAClient creates a timestamp client.

func (*TSAClient) SetCACert

func (t *TSAClient) SetCACert(certFile string) error

SetCACert sets the TSA CA certificate.

func (*TSAClient) SetMaxTSTAge

func (t *TSAClient) SetMaxTSTAge(d time.Duration)

SetMaxTSTAge overrides the accepted TST age window. Defaults to 1h.

func (*TSAClient) Sign

func (t *TSAClient) Sign(data []byte) (tstDER []byte, err error)

Sign performs an RFC 3161 timestamp signature on data.

func (*TSAClient) Verify

func (t *TSAClient) Verify(entryJSON, tstDER []byte) error

Verify verifies a timestamp token.

type TSAProofEntry

type TSAProofEntry struct {
	Time  string `json:"time"`
	Root  string `json:"root"`
	TST   string `json:"tst"`
	Batch int    `json:"batch"`
}

TSAProofEntry is a TSA audit proof entry.

type TSAProofLogger

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

TSAProofLogger is the TSA audit proof logger.

func NewTSAProofLogger

func NewTSAProofLogger(path string, tsa *TSAClient, chain *AuditChain, intervalSec int) *TSAProofLogger

NewTSAProofLogger creates a TSA audit proof logger.

func (*TSAProofLogger) Close

func (l *TSAProofLogger) Close() error

Close closes the TSA proof log file.

func (*TSAProofLogger) SetAuditChain

func (l *TSAProofLogger) SetAuditChain(chain *AuditChain)

SetAuditChain sets the audit chain reference (runtime replacement).

func (*TSAProofLogger) Start

func (l *TSAProofLogger) Start(stopCh chan struct{})

Start starts the TSA audit proof periodic recording loop.

func (*TSAProofLogger) Stop

func (l *TSAProofLogger) Stop()

Stop stops the TSA proof logger.

type TSTInfo

type TSTInfo struct {
	Version        int
	Policy         asn1.ObjectIdentifier
	MessageImprint MessageImprint
	SerialNumber   int
	GenTime        time.Time
	Accuracy       asn1.RawValue `asn1:"optional"`
	Ordering       bool          `asn1:"optional,default:false"`
	Nonce          *int          `asn1:"optional"`
	TSA            asn1.RawValue `asn1:"optional,explicit,tag:0"`
}

TSTInfo is the timestamp token information.

func UnmarshalTimestampToken

func UnmarshalTimestampToken(data []byte) (*TSTInfo, error)

UnmarshalTimestampToken parses a timestamp token from DER.

type TaskRecord

type TaskRecord struct {
	TaskID   string     `json:"task_id"`
	Serial   string     `json:"serial"`
	AgentID  string     `json:"agent_id,omitempty"`
	Status   TaskStatus `json:"status"`
	Created  int64      `json:"created"`
	Note     string     `json:"note,omitempty"`
	Revoked  bool       `json:"revoked"`
	RevokeAt int64      `json:"revoke_at,omitempty"`
}

TaskRecord is a single record in the task registry.

type TaskRegistry

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

TaskRegistry tracks task → certificate serial number mappings keyed by task ID, used to trigger conditional revocation via completion signals. Thread-safe.

func NewTaskRegistry

func NewTaskRegistry() *TaskRegistry

NewTaskRegistry creates an empty task registry.

func (*TaskRegistry) Complete

func (r *TaskRegistry) Complete(taskID string, now int64) *TaskRecord

Complete marks a task as completed and returns its associated certificate serial number (for the caller to trigger revocation). Returns an empty string for unregistered tasks.

func (*TaskRegistry) Len

func (r *TaskRegistry) Len() int

Len returns the number of currently active tasks.

func (*TaskRegistry) List

func (r *TaskRegistry) List() []TaskRecord

List returns a snapshot of all task records (sorted by creation time descending).

func (*TaskRegistry) Lookup

func (r *TaskRegistry) Lookup(taskID string) *TaskRecord

Lookup queries a task record (read-only).

func (*TaskRegistry) Register

func (r *TaskRegistry) Register(taskID, serial, agentID, note string, now int64) *TaskRecord

Register registers a new task and returns the previous record (if one with the same ID already existed, it is overwritten and the old one is returned). Does not register if taskID is empty (returns nil).

func (*TaskRegistry) Unregister

func (r *TaskRegistry) Unregister(taskID string) *TaskRecord

Unregister removes a task record. Returns the removed record (may be nil).

type TaskStatus

type TaskStatus string

TaskStatus represents the completion status of a task.

const (
	// TaskActive indicates the task is in progress.
	TaskActive TaskStatus = "active"
	// TaskCompleted indicates the task is completed (triggers revocation).
	TaskCompleted TaskStatus = "completed"
)

type TimeStampReq

type TimeStampReq struct {
	Version        int
	MessageImprint MessageImprint
	ReqPolicy      asn1.ObjectIdentifier `asn1:"optional"`
	Nonce          *int                  `asn1:"optional"`
	CertReq        bool                  `asn1:"optional,default:false"`
	Extensions     []asn1.RawValue       `asn1:"optional,set"`
}

TimeStampReq is an RFC 3161 timestamp request.

type TimeStampResp

type TimeStampResp struct {
	Status         PKIStatusInfo
	TimeStampToken asn1.RawValue `asn1:"optional"`
}

TimeStampResp is an RFC 3161 timestamp response.

type TokenBucket

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

TokenBucket is a token bucket rate limiter with dynamic parameter adjustment.

func NewTokenBucket

func NewTokenBucket(rate float64, burst int64) *TokenBucket

NewTokenBucket creates a token bucket rate limiter.

func (*TokenBucket) Allow

func (tb *TokenBucket) Allow(n int) bool

Allow checks whether n tokens can be consumed (non-blocking).

func (*TokenBucket) SetBurst

func (tb *TokenBucket) SetBurst(burst int64)

SetBurst sets the token bucket capacity.

func (*TokenBucket) SetRate

func (tb *TokenBucket) SetRate(rate float64)

SetRate sets the token refill rate.

func (*TokenBucket) WaitN

func (tb *TokenBucket) WaitN(n int)

WaitN blocks until enough tokens are available.

type Translator

type Translator interface {
	T(lang, key string, args ...any) string
}

Translator is the internationalization translation interface.

type TrustLayer

type TrustLayer int

TrustLayer represents a layer in the three-layer trust model.

const (
	Layer1Identity TrustLayer = iota
	Layer2Representation
	Layer3OnlineAuthorization
)

Layer1/2/3 three-layer trust model layer constants.

func (TrustLayer) String

func (l TrustLayer) String() string

String returns the layer name.

type UDPExtra

type UDPExtra struct {
	// RequireDelegation whether dual-certificate delegation mode is required.
	RequireDelegation *bool `json:"require_delegation,omitempty"`

	// MaxPktsPerIP is the max packets per IP per second (0=unlimited).
	MaxPktsPerIP int `json:"max_pkts_per_ip,omitempty"`

	// MaxTotalPkts is the global max total packet count (0=unlimited).
	MaxTotalPkts int `json:"max_total_pkts,omitempty"`

	// ConnectionBPS is per-connection byte-level rate limiting in bps (0=unlimited).
	ConnectionBPS int64 `json:"connection_bps,omitempty"`

	// ConnectionBurst is the token bucket burst capacity in bytes.
	ConnectionBurst int64 `json:"connection_burst,omitempty"`

	// DisconnectOnExpirySec is automatic disconnect delay on certificate expiry in seconds.
	DisconnectOnExpirySec int `json:"disconnect_on_expiry_sec,omitempty"`

	// MaxAmplification caps the relayed response size relative to the request
	// size (0 = default factor). Plaintext UDP relays are otherwise reflection
	// amplifiers: a small spoofed-source query can elicit a large response
	// sent to the victim. The response is dropped when it exceeds
	// len(request) * factor (with a small floor), bounding amplification.
	MaxAmplification int `json:"max_amplification,omitempty"`

	// RequirePlaintextRelayRateLimit forces per-IP rate limiting on plaintext
	// (unauthenticated) UDP listeners even when max_pkts_per_ip is unset. When
	// true and the listener is plaintext, a default per-IP cap is applied so
	// an unauthenticated relay cannot be used for sustained amplification.
	// Default false (operator opt-in keeps legacy configs working); the
	// per-IP rate limiting of a plaintext relay is strongly recommended.
	RequirePlaintextRelayRateLimit *bool `json:"require_plaintext_relay_rate_limit,omitempty"`
}

func (*UDPExtra) DisconnectOnExpiryEnabled

func (u *UDPExtra) DisconnectOnExpiryEnabled() bool

func (*UDPExtra) MaxAmplificationFactor added in v0.4.0

func (u *UDPExtra) MaxAmplificationFactor() int

MaxAmplificationFactor returns the effective response amplification factor, defaulting to MaxAmplificationDefault when unset or <= 0.

func (*UDPExtra) RequireDelegationEnabled

func (u *UDPExtra) RequireDelegationEnabled() bool

func (*UDPExtra) RequirePlaintextRelayRateLimitEnabled added in v0.4.0

func (u *UDPExtra) RequirePlaintextRelayRateLimitEnabled() bool

RequirePlaintextRelayRateLimitEnabled reports whether plaintext UDP listeners must apply default per-IP rate limiting.

type UserPermission

type UserPermission = pki.UserPermission

── Type aliases ──

type VerifyRequest

type VerifyRequest struct {
	Batch int             `json:"batch"`
	Leaf  string          `json:"leaf"`
	Proof []ProofStepJSON `json:"proof"`
}

VerifyRequest is an audit verification request.

type VerifyResponse

type VerifyResponse struct {
	Valid bool   `json:"valid"`
	Error string `json:"error,omitempty"`
}

VerifyResponse is an audit verification response.

Jump to

Keyboard shortcuts

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