credential

package
v0.27.0 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: AGPL-3.0 Imports: 51 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package credential defines credential schemas, issuers, consumer slots and their go-plugin transport. Importing it links the same strict codec as importing pkg/sdk. Programs that need only metadata negotiation should import pkg/credential/protocol; that leaf does not install a codec. A plugin module outside this SDK must also select the SDK's gRPC fork with a replace directive, which Go does not inherit; see docs/resource-v2-api.md, "Source-session transport".

The server checks callback results against declared types, schemas, limits and TTLs, keeps discovery metadata-only, and sanitizes callback errors. Protected replies must still meet the original call's contract after plugin middleware and synchronous telemetry. The host independently admits the reply bytes against its negotiated roles and pinned declarations.

Index

Constants

View Source
const (
	TypeBearer        = cw.Bearer
	TypeBasic         = cw.Basic
	TypeX509          = cw.X509
	TypeSSHKey        = cw.SSHKey
	TypeSSHCert       = cw.SSHCert
	TypeOAuthTokenSet = cw.OAuthTokenSet
	TypeOpaque        = cw.Opaque
)

Exact canonical type IDs. Only the SDK owns the core namespace.

View Source
const PluginID = "credential"

PluginID identifies the credential capability in the lifecycle inventory.

Variables

View Source
var ErrInvalidMaterial = errors.New("invalid credential material")

ErrInvalidMaterial rejects a schema value or import document without naming it.

Functions

func OneCandidate

func OneCandidate(key string, metadata Metadata) func(context.Context) ([]Candidate, error)

OneCandidate builds a Discover callback for a fixed candidate. Set metadata.Type to the issuer's exact output type and supply the actual target claims, if any. Neither the caller nor a discovery result can mutate the snapshot.

func ProviderError

func ProviderError(err error) error

ProviderError discards the native error and all its text and details. It preserves cancellation, deadlines and non-OK gRPC classes. Unclassified provider failures become Internal. Nil remains nil.

func ReadBasic

func ReadBasic(m Material) ([]byte, []byte, error)

ReadBasic returns the username first and the password second.

func ReadBearer

func ReadBearer(m Material) ([]byte, error)

ReadBearer reads the token field, never an OAuth token set's access_token.

func ReadOAuthTokenSet

func ReadOAuthTokenSet(m Material) ([]byte, []byte, []byte, error)

ReadOAuthTokenSet returns the access token, refresh token, and token type in that order. An absent refresh token is returned as nil.

func ReadOpaque

func ReadOpaque(m Material) ([]byte, error)

ReadOpaque reads only the opaque value field, not arbitrary material.

func ReadSSHCert

func ReadSSHCert(m Material) ([]byte, []byte, error)

ReadSSHCert returns the user certificate followed by the private key.

func ReadSSHKey

func ReadSSHKey(m Material) ([]byte, error)

ReadSSHKey reads the OpenSSH private key.

func ReadX509

func ReadX509(m Material) ([]byte, []byte, error)

ReadX509 returns the leaf-first certificate chain followed by the private key.

func RegisterPlugin

func RegisterPlugin(p *sdk.Plugin, opts PluginOpts) error

RegisterPlugin validates and snapshots declarations before installing any transport. Register once before Serve. Registration neither binds a channel nor grants authority to exchange material.

Types

type ApprovalPendingPrompt

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

ApprovalPendingPrompt indicates outstanding approval without disclosing a ticket.

func (ApprovalPendingPrompt) Format

func (ApprovalPendingPrompt) Format(s fmt.State, _ rune)

func (ApprovalPendingPrompt) GoString

func (ApprovalPendingPrompt) GoString() string

func (ApprovalPendingPrompt) GobEncode

func (ApprovalPendingPrompt) GobEncode() ([]byte, error)

GobEncode refuses to serialize protected requests and results.

func (ApprovalPendingPrompt) MarshalJSON

func (ApprovalPendingPrompt) MarshalJSON() ([]byte, error)

func (ApprovalPendingPrompt) String

func (ApprovalPendingPrompt) String() string

type Candidate

type Candidate struct {
	Key      string
	Metadata Metadata
}

Candidate identifies one issuable credential within its issuer, without material.

type Claim

type Claim struct {
	Kind  string
	Value string
}

Claim describes a target for host review. It is not proof of identity or authorization.

type ConnectionDraft

type ConnectionDraft struct {
	Plugin   string
	Label    string
	Endpoint string
	Slots    map[string]string
}

ConnectionDraft proposes a connection and maps consumer slot names to credential draft keys in the same result. It never starts a native client.

type CredentialDraft

type CredentialDraft struct {
	Key      string
	Metadata Metadata
	Material Material `json:"-"`
	// contains filtered or unexported fields
}

CredentialDraft carries protected material. Key is local to this import result.

func (CredentialDraft) Format

func (CredentialDraft) Format(s fmt.State, _ rune)

func (CredentialDraft) GoString

func (CredentialDraft) GoString() string

func (CredentialDraft) GobEncode

func (CredentialDraft) GobEncode() ([]byte, error)

GobEncode refuses to serialize protected requests and results.

func (CredentialDraft) MarshalJSON

func (CredentialDraft) MarshalJSON() ([]byte, error)

func (CredentialDraft) String

func (CredentialDraft) String() string

type DeviceCodePrompt

type DeviceCodePrompt struct {
	VerificationURI string `json:"-"`
	UserCode        string `json:"-"`
	// contains filtered or unexported fields
}

DeviceCodePrompt contains the user-facing code, never the issuer's polling secret.

func (DeviceCodePrompt) Format

func (DeviceCodePrompt) Format(s fmt.State, _ rune)

func (DeviceCodePrompt) GoString

func (DeviceCodePrompt) GoString() string

func (DeviceCodePrompt) GobEncode

func (DeviceCodePrompt) GobEncode() ([]byte, error)

GobEncode refuses to serialize protected requests and results.

func (DeviceCodePrompt) MarshalJSON

func (DeviceCodePrompt) MarshalJSON() ([]byte, error)

func (DeviceCodePrompt) String

func (DeviceCodePrompt) String() string

type Expiry

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

Expiry selects one of three distinct lease expiry models. Its zero value is unspecified and invalid in a result. None of the models proves remote validity.

func Static

func Static() Expiry

Static marks material with no time-based deadline, such as a pasted secret.

func UnknownUntilRejected

func UnknownUntilRejected() Expiry

UnknownUntilRejected marks a lease whose expiry time is not known.

func Until

func Until(at time.Time) Expiry

Until sets an absolute upper bound on delivery. Even time.Time{} selects a timestamp, not static or unknown expiry.

func (Expiry) ExpiresAt

func (e Expiry) ExpiresAt() (time.Time, bool)

ExpiresAt returns the deadline only when Until selected an absolute timestamp.

func (Expiry) IsStatic

func (e Expiry) IsStatic() bool

IsStatic reports whether the issuer explicitly selected static expiry.

func (Expiry) IsUnknownUntilRejected

func (e Expiry) IsUnknownUntilRejected() bool

IsUnknownUntilRejected reports whether the issuer explicitly selected unknown expiry.

type FailureError

type FailureError struct {
	Kind            RequirementError
	Slot            string
	SuggestedIssuer *IssuerRef
}

FailureError carries only a reviewed reason. A named slot must be an input in the affected issuer's Requires declaration. An undeclared slot makes the whole detail inadmissible; it never redirects the failure to the issuer itself. Only ErrAccessRequired may suggest an issuer; that suggestion is not authority. Never place provider text, material or opaque handles here.

func (*FailureError) Error

func (e *FailureError) Error() string

Error returns only the fixed reason.

func (*FailureError) GRPCStatus

func (e *FailureError) GRPCStatus() *status.Status

GRPCStatus reports only the admitted class. Peer text is never retained.

func (*FailureError) Unwrap

func (e *FailureError) Unwrap() error

Unwrap allows errors.Is to match the reason even when a slot is present.

type Field

type Field struct {
	Name      string
	Secret    bool
	Required  bool
	Format    string
	Multiline bool
}

Field describes a material field, not its value. Even nonsecret fields stay on the protected channel. Multiline is a presentation hint.

type FormPrompt

type FormPrompt struct {
	Fields []Field `json:"-"`
	// contains filtered or unexported fields
}

FormPrompt describes trusted-entry fields. It carries no defaults or answers.

func (FormPrompt) Format

func (FormPrompt) Format(s fmt.State, _ rune)

func (FormPrompt) GoString

func (FormPrompt) GoString() string

func (FormPrompt) GobEncode

func (FormPrompt) GobEncode() ([]byte, error)

GobEncode refuses to serialize protected requests and results.

func (FormPrompt) MarshalJSON

func (FormPrompt) MarshalJSON() ([]byte, error)

func (FormPrompt) String

func (FormPrompt) String() string

type HostService

type HostService interface {
	// Get returns the current authorized projection, not issuer-private state.
	// Its handle and each parent handle must differ from every active source
	// reference on this bind. A lease cannot be its own parent. A replacement
	// with a different handle or status requires a new revision. The returned
	// value stays the host's: the SDK reads it, sends copies and never retains,
	// mutates or wipes it, so a host may return bytes it still serves from a
	// cache. Implement LeaseReleaser to learn when the SDK has finished with it.
	Get(ctx context.Context, sourceRef []byte) (Lease, error)
	// Invalidate reports exactly the presented handle and revision. A stale
	// rejection must not evict a replacement. Never accept target response text.
	Invalidate(ctx context.Context, sourceRef, leaseHandle []byte, revision uint64, reason RejectionReason) error
	// Watch atomically subscribes and snapshots the current revision/status.
	// Return that snapshot separately from subsequent, strictly newer updates.
	// Recheck live authorization for each update. Replacing or withdrawing the
	// source cancels its subscription: end it with a gRPC PermissionDenied status.
	// The adapter forwards the class it is given, so ErrSourceRetired would reach
	// the plugin as FailedPrecondition, outside the pair its Source documents.
	// Both context cancellation and closing the returned stream must unblock Recv.
	// The SDK buffers at most eight waiting updates. Overflow stops upstream work and ends the RPC with
	// ResourceExhausted once any in-flight send unblocks. Resubscribe for a
	// new snapshot and Get the current material.
	Watch(ctx context.Context, sourceRef []byte) (Replacement, ReplacementStream, error)
	// Prompt presents a challenge only for this authorized interactive issue or
	// renewal. Constrain destinations and verify loopback state at presentation.
	// The host must mint a never-reused operation ID per attempt, including a resume.
	// Return a disposition, never answers, polling secrets or proof of sign-in.
	Prompt(ctx context.Context, operationID string, prompt Prompt) (PromptDisposition, error)
}

HostService implements the protected callbacks on one bound plugin channel. Callbacks can run concurrently, including while the host awaits an outbound call to the same plugin. Never hold a lock needed by a callback across such a call. Authorize the process, binding, target and dependencies at each use; recheck after upstream work. The SDK's reference check is not a grant. Before exposing profile removal or replacement, revoke its refs and deny Get, Invalidate and Watch for them. Mint fresh reference bytes for every new installation, even for the same slot on the same bind. The SDK checks live references, not their history; it cannot enforce this host requirement. Contexts carry cancellation, deadlines and trace identity, not ambient values. Keep returned lease data immutable; the SDK detaches it before delivery.

type ImportRequest

type ImportRequest struct {
	Type     string
	Document []byte `json:"-"`
	// contains filtered or unexported fields
}

ImportRequest carries a protected foreign document, including on parse failure. Do not log it, execute helpers, or resolve external secret paths.

func (ImportRequest) Format

func (ImportRequest) Format(s fmt.State, _ rune)

func (ImportRequest) GoString

func (ImportRequest) GoString() string

func (ImportRequest) GobEncode

func (ImportRequest) GobEncode() ([]byte, error)

GobEncode refuses to serialize protected requests and results.

func (ImportRequest) MarshalJSON

func (ImportRequest) MarshalJSON() ([]byte, error)

func (ImportRequest) String

func (ImportRequest) String() string

type ImportResult

type ImportResult struct {
	Credentials []CredentialDraft `json:"-"`
	Connections []ConnectionDraft
	// contains filtered or unexported fields
}

ImportResult proposes drafts to the trusted host. The host separates reviewed metadata from material before preview; returning drafts does not create a binding.

func (ImportResult) Format

func (ImportResult) Format(s fmt.State, _ rune)

func (ImportResult) GoString

func (ImportResult) GoString() string

func (ImportResult) GobEncode

func (ImportResult) GobEncode() ([]byte, error)

GobEncode refuses to serialize protected requests and results.

func (ImportResult) MarshalJSON

func (ImportResult) MarshalJSON() ([]byte, error)

func (ImportResult) String

func (ImportResult) String() string

type Inventory

type Inventory struct {
	Types   []TypeDeclaration
	Issuers []IssuerDeclaration
	Slots   []Slot
}

Inventory lists the plugin's declarations in registration order. It contains neither callbacks nor credential instances. A declaration is not a grant.

type IssueRequest

type IssueRequest struct {
	IssuerID     string
	CandidateKey string
	// OperationID identifies this attempt. The host must mint a fresh ID
	// for every Issue, including a resume. PendingHandle carries continuity.
	OperationID   string
	Silent        bool
	PendingHandle []byte `json:"-"`
	Target        []Claim
	MaxTTL        time.Duration

	Inputs                []SourceRef `json:"-"`
	ProtectedPromptAnswer []byte      `json:"-"`
	// contains filtered or unexported fields
}

IssueRequest asks the issuer to issue or resume one selected candidate. Silent forbids interaction. A positive MaxTTL bounds expiry from request receipt at the plugin, before issuer work. Zero means the bound was not supplied, not an unlimited grant. Honor a positive bound before issuing upstream, or fail without issuing; the SDK rejects an overlong lease rather than shortening it. Inputs is host-side only: issuer callbacks receive a nil Inputs slice and use IssueRequest.Input to obtain an authorized input lease. A nonempty ProtectedPromptAnswer is secret and belongs only to this authorized resume.

func (IssueRequest) Format

func (IssueRequest) Format(s fmt.State, _ rune)

func (IssueRequest) GoString

func (IssueRequest) GoString() string

func (IssueRequest) GobEncode

func (IssueRequest) GobEncode() ([]byte, error)

GobEncode refuses to serialize protected requests and results.

func (IssueRequest) Input

func (r IssueRequest) Input(ctx context.Context, name string) (Lease, error)

Input gets the current authorized lease for one declared issuer input. A missing binding returns ErrCredentialRequired naming that input; an unknown name returns ErrUnknownSlot locally. A finite lease that expires before delivery returns ErrLeaseExpired. Access ends with the original Issue call.

func (IssueRequest) MarshalJSON

func (IssueRequest) MarshalJSON() ([]byte, error)

func (IssueRequest) Prompt

Prompt asks the host to present a declared challenge for this issue or resume. Silent operations return ErrInteractionRequired without contacting the host. Even a presented prompt does not grant permission to issue.

func (IssueRequest) String

func (IssueRequest) String() string

type IssueResult

type IssueResult interface {
	// contains filtered or unexported methods
}

IssueResult is an issued lease or a pending continuation, never both.

type IssuedLease

type IssuedLease struct {
	Material           Material `json:"-"`
	Expiry             Expiry
	RenewAfter         time.Time
	Renewable          bool
	IssuerPrivateState []byte `json:"-"`
	MaxTTL             time.Duration
	// contains filtered or unexported fields
}

IssuedLease returns material to the trusted host, not directly to a consumer. IssuerPrivateState never enters the consumer lease. RenewAfter and MaxTTL are optional; their zero values mean absent. A positive MaxTTL bounds expiry from request receipt at the plugin and cannot exceed a positive requested MaxTTL. The host checks remaining TTL on response receipt.

func Issued

func Issued(m Material, e Expiry) IssuedLease

Issued packages material with its explicit expiry without copying the bytes.

func (IssuedLease) Format

func (IssuedLease) Format(s fmt.State, _ rune)

func (IssuedLease) GoString

func (IssuedLease) GoString() string

func (IssuedLease) GobEncode

func (IssuedLease) GobEncode() ([]byte, error)

GobEncode refuses to serialize protected requests and results.

func (IssuedLease) MarshalJSON

func (IssuedLease) MarshalJSON() ([]byte, error)

func (IssuedLease) String

func (IssuedLease) String() string

type Issuer

type Issuer struct {
	ID          string
	Produces    string
	Requires    []Slot
	Revocation  RevocationClass
	Interaction []PromptKind
	Discover    func(context.Context) ([]Candidate, error)
	Issue       func(context.Context, IssueRequest) (IssueResult, error)
	Renew       func(context.Context, LeaseOperation) (IssueResult, error)
	Revoke      func(context.Context, LeaseOperation) (Observation, error)
	Observe     func(context.Context, LeaseOperation) (Observation, error)
}

Issuer produces leases of exactly one type. Discover returns only metadata; Issue and Renew return either material or a private continuation. Explicit and verified revocation require Revoke; verified also requires Observe. The SDK checks issued and renewed material against the declared schema, but does not run native Validate. Success does not prove key validity, target identity, or authorization to deliver the material.

type IssuerDeclaration

type IssuerDeclaration struct {
	ID          string
	Produces    string
	Requires    []Slot
	Revocation  RevocationClass
	Interaction []PromptKind
	Renews      bool
	Revokes     bool
	Observes    bool
}

IssuerDeclaration describes one issuer, not a candidate or an issued lease. Renews advertises extension of an existing grant, not re-issue.

type IssuerRef

type IssuerRef struct{ Plugin, Issuer string }

IssuerRef suggests a declared issuer. Both names are public identifiers; the host must verify the suggestion independently before presenting it.

type Lease

type Lease struct {
	Type         string
	Issuer       IssuerRef
	Handle       []byte `json:"-"`
	Revision     uint64
	Expiry       Expiry
	RenewAfter   time.Time
	Renewable    bool
	MaxTTL       time.Duration
	Revocation   RevocationClass
	ParentLeases [][]byte `json:"-"`
	Material     Material `json:"-"`
	// contains filtered or unexported fields
}

Lease is the host-authorized material projection for a single revision. Its bytes belong to the caller of Source.Get; a lease that a HostService returns from Get stays the host's (see LeaseReleaser). Keep handles, parents and all material off logs, profiles and UI paths. See Material for rendering limits.

func (Lease) Format

func (Lease) Format(s fmt.State, _ rune)

func (Lease) GoString

func (Lease) GoString() string

func (Lease) GobEncode

func (Lease) GobEncode() ([]byte, error)

GobEncode refuses to serialize protected requests and results.

func (Lease) MarshalJSON

func (Lease) MarshalJSON() ([]byte, error)

func (Lease) String

func (Lease) String() string

func (*Lease) Wipe

func (l *Lease) Wipe()

Wipe clears the visible material, handle and parent bytes in place and resets the lease, including its source provenance. Use only after all borrowers finish. Independent copies cannot be erased by this method.

type LeaseOperation

type LeaseOperation struct {
	IssuerID string
	// OperationID is fresh for every Renew attempt, including a resume.
	// Use PendingHandle, not a previous ID, to continue pending work.
	OperationID        string
	LeaseHandle        []byte `json:"-"`
	IssuerPrivateState []byte `json:"-"`
	PendingHandle      []byte `json:"-"`
	Revision           uint64
	Silent             bool
	MaxTTL             time.Duration

	Inputs                []SourceRef `json:"-"`
	ProtectedPromptAnswer []byte      `json:"-"`
	// contains filtered or unexported fields
}

LeaseOperation addresses an exact lease revision for renewal, revocation, or observation. Only the originating issuer may receive its sealed state. On renewal, MaxTTL has the same meaning as in IssueRequest. Inputs is host-side only and nil in native callbacks; call LeaseOperation.Input during Renew. Inputs and ProtectedPromptAnswer are refused on Revoke and Observe.

func (LeaseOperation) Format

func (LeaseOperation) Format(s fmt.State, _ rune)

func (LeaseOperation) GoString

func (LeaseOperation) GoString() string

func (LeaseOperation) GobEncode

func (LeaseOperation) GobEncode() ([]byte, error)

GobEncode refuses to serialize protected requests and results.

func (LeaseOperation) Input

func (r LeaseOperation) Input(ctx context.Context, name string) (Lease, error)

Input has the same contract as IssueRequest.Input during Renew. Revoke and Observe receive no input authority, even for an issuer that declares inputs.

func (LeaseOperation) MarshalJSON

func (LeaseOperation) MarshalJSON() ([]byte, error)

func (LeaseOperation) Prompt

Prompt has the same contract as IssueRequest.Prompt during Renew. Revoke and Observe cannot prompt.

func (LeaseOperation) String

func (LeaseOperation) String() string

type LeaseReleaser added in v0.26.0

type LeaseReleaser interface {
	ReleaseLease(lease Lease)
}

LeaseReleaser is an optional interface of a HostService. It tells the host when the SDK has finished with a Lease that Get returned. The SDK cannot wipe that value itself: the host may have returned bytes it still serves from a cache, and a host cannot otherwise tell when the SDK is done with it.

ReleaseLease is called exactly once for each Get that returned a nil error, with the Lease value Get returned (the same backing bytes), after the SDK's last read of it. The SDK has copied what it needs by then, so releasing, wiping or reusing the value changes nothing that is delivered. Every path ends in that one call: the reply is delivered, refused because the SDK does not accept the lease, withheld because the bind was fenced or the source was withdrawn while the handler ran, or the SDK fails internally. It runs before the reply is published, so a host cannot learn from it that delivery happened.

A Get that returned an error is never released, and neither is a callback that was refused before it reached Get: the SDK took no value from the host. Wipe the value if Get returned a private copy; drop a pin or reference if it returned shared bytes. ReleaseLease runs on the goroutine that serves Get, with no lock of the SDK held, and may run concurrently with other callbacks. A panic in it fails the callback with an internal-class error, and the SDK withholds the reply and wipes its own copy.

The SDK finds the hook by a type assertion on the value given to ServeCredentials. A wrapper around the service, such as a logging, metrics or authorization decorator, must implement ReleaseLease and forward it to the service it wraps; otherwise the hook is never called.

type Manager

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

Manager holds a validated, immutable declaration snapshot and, on the plugin side only, the author callbacks. Build it before serving requests.

func NewManager

func NewManager(owner string, opts PluginOpts) (*Manager, error)

NewManager validates declarations against the installed plugin ID. It does not register a transport, invoke callbacks, or retain caller-owned slices. Registration diagnostics identify declaration indices, never rejected data.

type Material

type Material map[string][]byte

Material holds the protected bytes of an authorized schema projection. Every value is protected, even a username or certificate. Constructors and readers share byte slices with their caller; they neither copy nor normalize data.

Canonical fields and format identifiers (all required unless noted):

Type                Field: format
core.bearer/v1      token: bearer-token (secret)
core.basic/v1       username: text; password: text (secret)
core.x509/v1        certificate_chain: pem-certificate-chain; private_key: pem-private-key (secret)
core.ssh-key/v1     private_key: openssh-private-key (secret)
core.ssh-cert/v1    certificate: openssh-user-certificate; private_key: openssh-private-key (secret)
core.oauth-token-set/v1  access_token: oauth-token (secret); refresh_token: oauth-token (optional, secret);
                         token_type: oauth-token-type
core.opaque/v1      value: bytes (secret)

Read helpers require the nonempty canonical fields but allow subtype fields. They do not determine a material's type, validate cryptographic encodings, verify a key pair, or authorize its use. Use the known type and adapter.

Material and the SDK's protected requests and results redact ordinary fmt verbs (such as %v, %+v, %#v, %s and %q) and encoding/json output. The stock slog handlers and the SDK's hclog backend redact these values in rendered text and JSON. Gob encoding is refused.

Rendering is not a confidentiality boundary. %p, invalid operands (such as %w on a non-error), and fmt on unexported fields can bypass Format. Reflection-based serializers need not honor these methods. Structured log sinks receive the live value, not its rendering. Do not send protected values to arbitrary loggers or serializers, convert Material to an unnamed map for output, or log extracted keys, byte slices, handles or state.

func Basic

func Basic(username, password []byte) Material

Basic packages a username and password. Both values stay protected.

func Bearer

func Bearer(token []byte) Material

Bearer packages bearer text without interpreting it as a JWT.

func OAuthTokenSet

func OAuthTokenSet(accessToken, refreshToken, tokenType []byte) Material

OAuthTokenSet packages an access token, optional refresh token, and token type. A nil or empty refresh token is omitted. No bearer projection is implied.

func Opaque

func Opaque(value []byte) Material

Opaque packages uninterpreted bytes. This type is not a wildcard.

func SSHCert

func SSHCert(certificate, privateKey []byte) Material

SSHCert packages an OpenSSH user certificate and its matching private key.

func SSHKey

func SSHKey(privateKey []byte) Material

SSHKey packages an OpenSSH private key.

func X509

func X509(certificateChain, privateKey []byte) Material

X509 packages a leaf-first PEM certificate chain and its matching PEM private key.

func (Material) Format

func (Material) Format(s fmt.State, verb rune)

Format redacts material when fmt calls the formatter for the given verb.

func (Material) GoString

func (Material) GoString() string

GoString redacts material in Go-syntax diagnostics.

func (Material) GobEncode

func (Material) GobEncode() ([]byte, error)

GobEncode refuses to serialize material, including field names.

func (Material) MarshalJSON

func (Material) MarshalJSON() ([]byte, error)

MarshalJSON returns only a fixed redaction. JSON is not a material transport.

func (Material) String

func (Material) String() string

String redacts field names and values.

func (Material) Wipe

func (m Material) Wipe()

Wipe clears each visible byte slice in place and removes all map entries. Aliases of the map and of those bytes observe the changes. Call only after every user has finished. Wipe cannot erase independent copies, strings, bytes outside each slice's length, or separately held handles or issuer state.

type Metadata

type Metadata struct {
	Type          string
	IdentityLabel string
	Provenance    string
	PrivilegeTier *PrivilegeTier
	TargetClaims  []Claim
}

Metadata is the credential description offered for host review. Never copy material or unchecked provider output into labels, provenance, or claims.

type Observation

type Observation struct {
	Outcome    ObservationOutcome
	ObservedAt time.Time
}

Observation reports the upstream lease state at ObservedAt, not cache or client readiness.

type ObservationOutcome

type ObservationOutcome string

ObservationOutcome is the issuer's observation, not authorization to deliver a lease.

const (
	// ObservationActive reports an upstream grant observed to be active.
	ObservationActive ObservationOutcome = cw.Active
	// ObservationRevoked reports an upstream revocation confirmed by the issuer.
	ObservationRevoked ObservationOutcome = cw.Revoked
	// ObservationUnknown means the issuer cannot determine the state.
	ObservationUnknown ObservationOutcome = cw.Unknown
	// ObservationUnavailable means the upstream observation is unavailable.
	ObservationUnavailable ObservationOutcome = cw.Unavailable
)

type OpenURLPrompt

type OpenURLPrompt struct {
	AuthorizationURI string `json:"-"`
	LoopbackSession  string `json:"-"`
	// contains filtered or unexported fields
}

OpenURLPrompt binds sign-in at an authorized HTTPS origin to a host loopback session.

func (OpenURLPrompt) Format

func (OpenURLPrompt) Format(s fmt.State, _ rune)

func (OpenURLPrompt) GoString

func (OpenURLPrompt) GoString() string

func (OpenURLPrompt) GobEncode

func (OpenURLPrompt) GobEncode() ([]byte, error)

GobEncode refuses to serialize protected requests and results.

func (OpenURLPrompt) MarshalJSON

func (OpenURLPrompt) MarshalJSON() ([]byte, error)

func (OpenURLPrompt) String

func (OpenURLPrompt) String() string

type Pending

type Pending struct {
	Handle     []byte `json:"-"`
	RetryAfter time.Duration
	// contains filtered or unexported fields
}

Pending returns protected continuation state and a positive retry hint. A continuation is not material and does not imply that approval succeeded.

func (Pending) Format

func (Pending) Format(s fmt.State, _ rune)

func (Pending) GoString

func (Pending) GoString() string

func (Pending) GobEncode

func (Pending) GobEncode() ([]byte, error)

GobEncode refuses to serialize protected requests and results.

func (Pending) MarshalJSON

func (Pending) MarshalJSON() ([]byte, error)

func (Pending) String

func (Pending) String() string

type Plugin

type Plugin struct {
	plugin.NetRPCUnsupportedPlugin

	Impl *Manager
	// contains filtered or unexported fields
}

Plugin exposes an immutable manager through go-plugin. On the host, use one instance per process and install its GRPCDialOption before dialing. Do not copy or reuse an instance after use.

func (*Plugin) Close

func (p *Plugin) Close() error

Close permanently retires the plugin's credential binding. SDK Serve calls it at process shutdown; a closed or uncertain binding is never replaced.

func (*Plugin) GRPCClient

func (p *Plugin) GRPCClient(lifetime context.Context, broker *plugin.GRPCBroker, c *grpc.ClientConn) (any, error)

GRPCClient returns the host-side client for this connection. Negotiate and read Declarations using the expected installed owner before invoking a role.

func (*Plugin) GRPCDialOption

func (p *Plugin) GRPCDialOption() grpc.DialOption

GRPCDialOption observes the lifetime of this process's primary connection. Add it to the go-plugin client's standard dial options on the host. Without the matching observer the credential bind fails closed. Other services, including their tracing and metrics, are unaffected.

func (*Plugin) GRPCServer

func (p *Plugin) GRPCServer(broker *plugin.GRPCBroker, s *grpc.Server) error

GRPCServer installs the credential service and its one-time binding on the primary go-plugin connection. Both check the transport before decoding. The server validates and sanitizes author callbacks inside the interceptor chain, then checks protected replies against the original request at delivery. The host independently admits the bytes it receives and checks the contract.

type PluginClient

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

PluginClient calls a single plugin process over its go-plugin connection. It is safe for concurrent calls. Negotiate first, then pin Declarations to the expected installed plugin ID. No bytes are sent by a protected method without an authenticated bind. Returned material and private bytes belong to the caller, never to a logger, UI, profile or second lease cache. The host admits raw replies and checks them against the original call and pinned declarations; it does not rely on prior checks inside the plugin. A gRPC frame-limit status can report numeric sizes but never payload or provider text; PluginClient returns only its ResourceExhausted class.

func (*PluginClient) AttachSources

func (p *PluginClient) AttachSources(
	ctx context.Context, connection string, revision uint64, sources []SourceRef,
) (err error)

AttachSources replaces the complete binding for the next native generation. Empty sources clears it. Revisions must increase; references must be fresh. The host still owns authorization, fencing and the native stop/restart. No resource configuration or existing client's source is silently changed. Stopping and restarting an unchanged connection preserves its binding and observed lease revisions. Never reset a connection ID's revision during the bind. Revoke refs before removing/replacing the profile and wait for the fresh set's acknowledgement before starting. An unknown result may have applied: revoke those refs and send a higher revision, even for a recreated profile.

func (*PluginClient) BindDone added in v0.26.0

func (p *PluginClient) BindDone() <-chan struct{}

BindDone returns a channel that is closed when the bind that a successful ServeCredentials established has ended, for any reason: the host called Fence or the returned stop, either original connection of the bound pair ended as the host side observed it, a negotiation refusal or renegotiation retired the agreement, or the plugin process was retired. An idle bind is otherwise silent: protected calls on a dead bind are refused inside the SDK and never reach the HostService. A host that sees the channel close MUST retire the plugin process and not reuse it; the bind cannot be replaced.

The channel is closed only after the SDK's own fence is in effect: any protected call, in either direction, that starts after the close is refused. Ordinary call failures never close it. It carries no reason and no peer text.

Call it after ServeCredentials has returned a nil error. Before that, and after a ServeCredentials that failed, it returns nil. A nil channel never becomes ready, so a client that was never bound cannot be read as one that lost its bind; the failed call's own error already told the host that the bind is terminal. A PluginClient binds at most once (a second ServeCredentials is refused), so the signal is one-shot: once closed it stays closed.

Every call returns the same channel. It is safe for concurrent use, takes no lock and starts no goroutine.

func (*PluginClient) Declarations

func (p *PluginClient) Declarations(ctx context.Context, owner string) (Inventory, error)

Declarations pins and returns an independent copy of the immutable inventory. owner is the expected plugin ID from the host's installation, not peer input.

func (*PluginClient) Describe

func (p *PluginClient) Describe(ctx context.Context, id string, material Material) (Metadata, error)

Describe obtains only metadata for the named declared type. Review it before display. Describe checks the material's schema without running native Validate. Success does not establish target identity or authorize use.

func (*PluginClient) Discover

func (p *PluginClient) Discover(ctx context.Context, issuer string) ([]Candidate, error)

Discover returns one bounded, metadata-only snapshot; it neither selects nor issues. The host checks the wire candidates it receives, not their representation in the plugin. Keys are opaque to the host and meaningful only to the requested issuer. The host cannot detect substitution by another issuer producing the same type and must return a key only to the issuer it requested.

func (*PluginClient) Fence added in v0.26.0

func (p *PluginClient) Fence()

Fence retires the bind synchronously, ahead of the slow teardown that the stop function returned by ServeCredentials performs.

Each protected result and request has a last check before it leaves. A result, in either direction (a HostService reply, a Watch notification, the plugin's result of a host call), has the SDK's final check, the last one before the SDK publishes it. A request that the host sends to the plugin has the send check, which gRPC runs on the selected connection just before it writes the call's headers. The guarantee ends at those checks. After Fence returns the host can rely on this:

  • nothing that has not yet passed its last check leaves or is delivered. That includes a HostService reply that the host's handler already returned but the SDK has not yet published: the SDK refuses it and wipes the bytes it holds for it, never a lease the host returned (see LeaseReleaser);
  • no new protected call is admitted: a callback that arrives afterwards never reaches the host's handler, and no new call to the plugin starts;
  • if a bind had been established, BindDone is closed. A client that was fenced before its bind went live never binds, and BindDone stays nil.

What has already passed its last check is not recalled, in either direction: a reply, a Watch notification or a request may still be written after Fence returns, with the material it carries. Each check runs under a lock that Fence also takes, so each result or request either passed before Fence took effect or is refused. Treat one that passed as delivered. A callback that passed its entry check just before Fence can also enter the host's handler after Fence has returned: its result is refused, but its side effects, such as an Invalidate or a Prompt, happen.

Fence only changes state under the client's own locks and cancels contexts. It does not wait for the peer, the network, an in-flight HostService handler (its context is canceled, asynchronously, but the handler may keep running) or the teardown. The SDK also starts that teardown in the background, as for any other retirement; calling stop afterwards, even concurrently, is correct and idempotent, and returns at once when a teardown is already under way.

Call Fence at the moment the host decides to retire the bind, before closing or revoking host state that its handlers consult. A reply that is delivered after that point passed the final check while that state was still in place. A fenced bind cannot be replaced; retire the plugin process, as after any lost bind.

Fence on a client that has not started to bind makes a later ServeCredentials fail: a fenced client never binds. Fence on a client whose bind is still being established ends that attempt: ServeCredentials returns an error, but the plugin may already have accepted the bind, so retire the process, as after any uncertain bind. It is safe for concurrent use, idempotent, safe from inside a HostService callback and a no-op on a nil client.

func (*PluginClient) Import

Import sends a protected document to its declared importer. Drafts are not a UI preview, a stored credential, a live connection or an authorized binding. The SDK checks draft material against its schema without running native Validate. Success does not authorize storage or delivery.

func (*PluginClient) Issue

Issue obtains an issued result or a private continuation from a declared issuer. Issued material conforms to the declared schema; the SDK does not run native Validate. Success neither verifies the target nor authorizes delivery. The host checks remaining TTL on receipt, independently of the plugin's local bound from request receipt.

func (*PluginClient) Negotiate

func (p *PluginClient) Negotiate(ctx context.Context, supported []protocol.Feature) ([]protocol.Feature, error)

Negotiate offers the host-supported subset of this cohort's implemented roles; material is required. It returns the mutually supported set, not a grant. The host drops unoffered roles from the peer's full advertisement; a refusal clears both the agreement and the inventory pin.

func (*PluginClient) Observe

Observe asks the issuer about upstream state, never the host's lease cache.

func (*PluginClient) Renew

Renew extends the identified lease revision, not a replacement grant. As with Issue, the host checks remaining TTL on receipt and checks returned material against the schema without native Validate. Success does not authorize continued delivery.

func (*PluginClient) Revoke

Revoke asks the issuer to revoke this lease. An uncertain result is not confirmation.

func (*PluginClient) ServeCredentials

func (p *PluginClient) ServeCredentials(ctx context.Context, service HostService) (func(), error)

ServeCredentials binds the dedicated host callback after negotiation and an installed-owner declaration pin. Both ends must verify mutual TLS on both exact connections. Binding authorizes no source, lease or prompt.

The context bounds the handshake, not the callback service. To retire the bind, call Fence first (synchronous, cheap) and the idempotent stop after it, on its own goroutine: stop may wait for the peer. Once binding starts, any failure is terminal: the plugin may have accepted even when its reply was lost. Stop using and retire that plugin process; do not retry, re-dispense or reuse it after an uncertain bind, connection loss or invalidated agreement.

func (*PluginClient) Validate

func (p *PluginClient) Validate(ctx context.Context, id string, material Material) error

Validate checks material against a declared type and its base schemas.

type PluginOpts

type PluginOpts struct {
	Types   []Type
	Issuers []Issuer
	Slots   []Slot
}

PluginOpts declares a plugin's credential types, issuers, and consumer slots. At least one role must be nonempty. A declaration is not a grant. Register before serving. The SDK snapshots declaration slices; it does not clone callback state. Callbacks may run concurrently, borrow their input for one call and transfer their result to the SDK. Do not retain inputs, mutate returned bytes or put any protected content in metadata or errors. Callbacks receive cancellation, a deadline if supplied, and trace linkage; no ambient plugin context or gRPC metadata. Protected request and result values share Material's rendering limits: never pass them to log sinks.

type PrivilegeTier

type PrivilegeTier struct {
	Scale   string
	Ordinal uint32
}

PrivilegeTier orders candidates only within one issuer's named scale. Zero is a valid ordinal. A tier is never an authorization input.

type Prompt

type Prompt interface {
	// contains filtered or unexported methods
}

Prompt is one of the four v1 host challenges. Only a trusted host surface may present the permitted fields. Never log or serialize the challenge.

type PromptDisposition

type PromptDisposition string

PromptDisposition acknowledges presentation only. No disposition grants authority.

const (
	PromptPresented PromptDisposition = "presented"
	PromptDenied    PromptDisposition = "denied"
	PromptCancelled PromptDisposition = "cancelled"
)

The complete v1 prompt dispositions. Denial and cancellation are not success.

type PromptKind

type PromptKind string

PromptKind declares a supported interaction, not permission to prompt.

const (
	// KindDeviceCode identifies a device-code sign-in.
	KindDeviceCode PromptKind = cw.DeviceCode
	// KindOpenURL identifies an HTTPS sign-in with a host-bound loopback response.
	KindOpenURL PromptKind = cw.OpenURL
	// KindFormMFA identifies a protected form or MFA challenge.
	KindFormMFA PromptKind = cw.FormMFA
	// KindApprovalPending identifies an external approval in progress.
	KindApprovalPending PromptKind = cw.ApprovalPending
)

type RejectionReason

type RejectionReason string

RejectionReason classifies evidence that the admitted target rejected this lease.

const TargetRejected RejectionReason = "target-rejected"

TargetRejected means the target rejected the presented credential, not a network failure, anonymous challenge or resource authorization denial.

type Replacement

type Replacement struct {
	Revision uint64
	Status   ReplacementStatus
}

Replacement is a material-free notification. A revision change requires a new Get.

type ReplacementStatus

type ReplacementStatus string

ReplacementStatus describes a credential binding, not native connection readiness.

const (
	StatusUnbound          ReplacementStatus = "UNBOUND"
	StatusIssuing          ReplacementStatus = "ISSUING"
	StatusActive           ReplacementStatus = "ACTIVE"
	StatusNeedsInteraction ReplacementStatus = "NEEDS_INTERACTION"
	StatusPendingApproval  ReplacementStatus = "PENDING_APPROVAL"
	StatusRefreshing       ReplacementStatus = "REFRESHING"
	StatusExpired          ReplacementStatus = "EXPIRED"
	StatusRevoking         ReplacementStatus = "REVOKING"
	StatusRevoked          ReplacementStatus = "REVOKED"
	StatusRevokeUnverified ReplacementStatus = "REVOKE_UNVERIFIED"
)

The complete v1 replacement status vocabulary. Unverified is not revoked.

type ReplacementStream

type ReplacementStream interface {
	Recv() (Replacement, error)
	Close() error
}

ReplacementStream yields ordered notifications to one reader. Recv returns io.EOF only on clean completion. Close is idempotent, safe concurrently with Recv, and releases the subscription even if the reader stopped early.

type RequirementError

type RequirementError uint8

RequirementError is an actionable credential failure, never provider prose. Use errors.Is on a host error. Use FailureError when a slot or suggestion is needed.

const (
	// ErrInteractionRequired requests sign-in; no slot means the issuer itself.
	ErrInteractionRequired RequirementError = iota + 1
	// ErrCredentialRequired requires an eligible binding. Always name its slot in FailureError.
	ErrCredentialRequired
	// ErrAccessRequired means a grant or approval is needed. A suggestion grants nothing.
	ErrAccessRequired
)

func (RequirementError) Error

func (k RequirementError) Error() string

Error returns the fixed credential reason, never a provider message.

type RevocationClass

type RevocationClass string

RevocationClass is the assurance an issuer can provide about upstream revocation.

const (
	// TTLBound means the issuer has no remote kill switch.
	TTLBound RevocationClass = cw.TTLBound
	// Explicit means the issuer can ask the upstream service to revoke a lease.
	Explicit RevocationClass = cw.Explicit
	// Verified means the issuer can also observe authoritative confirmation.
	Verified RevocationClass = cw.Verified
)

type Slot

type Slot struct {
	Name    string
	Accepts []string
}

Slot names one consumer or issuer input and the exact types it accepts.

type Source

type Source interface {
	// Get retrieves the current authorized lease from the host. Concurrent
	// calls are independent; the host owns caching and refresh coalescing.
	// The caller owns the lease bytes and should Wipe them after their last use.
	// A finite lease that expires before delivery returns ErrLeaseExpired.
	Get(context.Context) (Lease, error)
	// Invalidate reports the exact lease this source delivered and the closed
	// reason the target rejected it. Identical in-flight reports share one RPC.
	// The first caller's deadline bounds the shared RPC. Each caller can stop
	// waiting independently; the last departure cancels the RPC.
	Invalidate(context.Context, Lease, RejectionReason) error
	// Watch subscribes to material-free revisions, starting with current status.
	// Recv skips ordered notifications overtaken by a Get or another Watch.
	// A duplicate or decreasing stream revision, or contradictory facts at the
	// same current revision, end the stream with DataLoss. Watch never sends
	// a deadline to its host. Caller cancellation, deadline or retirement still
	// end it locally. A successful acquisition sheds its temporary deadline.
	// A call which races the host's revocation or rebinding of the source ends
	// with ErrSourceRetired or a gRPC PermissionDenied status: a Recv parked on
	// the stream, and a Get, Invalidate or Watch begun before the plugin applied
	// the change (a Watch reports it at its first Recv). Loss of the bind is
	// Unauthenticated. See SourceError. Each means the source is gone: do not
	// subscribe again on it.
	Watch(context.Context) (ReplacementStream, error)
}

Source is a live credential slot of one native client generation. Keep the source, not a cached lease. Replacement of its binding or retirement of its generation permanently disables it. Methods are safe for concurrent use. The SDK retains the scoped reference and non-material revision, status and lease identity facts, never a second material snapshot.

func SourceFor

func SourceFor(ctx context.Context, slot string) (Source, error)

SourceFor returns the named slot snapshotted for CreateClient and OnStart. A declared but unattached slot returns ErrCredentialRequired with its name; discovery, ordinary RPC contexts and undeclared names cannot select a source.

type SourceError

type SourceError uint8

SourceError classifies a local source lookup or lifetime failure. It carries no rejected name, reference, peer text or material. Match with errors.Is.

A source can permanently lose its authority in two ways, and the caller sees a different error for each. Removal of its profile or a rebind retires the generation and the host revokes the source's reference. A call begun after the plugin applied that change, and an open HTTP response, fail with ErrSourceRetired. A call which races the change can end differently: a Recv parked on an open Watch, and a Get, Invalidate or the first Recv of a Watch begun before the plugin applied it, can fail with a gRPC PermissionDenied status instead. The host's revocation of the reference and the plugin's retirement of the generation reach the call separately, a caller cannot know which came first, and PermissionDenied is the more common outcome for a parked Recv. A caller which matches only ErrSourceRetired misses that case: check status.Code as well. Loss of the authenticated bind itself (the host retiring the pair, or either original transport ending) is never ErrSourceRetired: every such call, parked or started afterwards, fails with a gRPC Unauthenticated status, which errors.Is does not match to this type; use status.Code. Each of these means the source is gone. None is retryable on the same source, and a caller must not subscribe again on it: take a new Source from SourceFor in the next generation.

const (
	// ErrNoSourceContext means SourceFor was called outside a credential-enabled generation.
	ErrNoSourceContext SourceError = iota + 1
	// ErrUnknownSlot means the name is not a declared consumer slot or issuer input.
	ErrUnknownSlot
	// ErrSourceRetired means this source's generation was retired by removal of its profile or a
	// rebind. A call which raced that change, or a Recv parked on the host at that moment, can
	// instead end with a gRPC PermissionDenied status, and loss of the authenticated bind is
	// reported as Unauthenticated: see SourceError.
	ErrSourceRetired
	// ErrLeaseExpired means a finite lease reached its expiry before local delivery.
	ErrLeaseExpired
)

func (SourceError) Error

func (e SourceError) Error() string

Error returns a fixed diagnostic.

func (SourceError) GRPCStatus

func (e SourceError) GRPCStatus() *status.Status

GRPCStatus reports a class only, never an actionable instruction about a different slot.

type SourceRef

type SourceRef struct {
	Slot string
	Ref  []byte `json:"-"`
	// contains filtered or unexported fields
}

SourceRef names one binding of one profile incarnation or one issuer input of one attempt. Never reuse, persist or render Ref. Revoke it before making profile replacement visible. Callers must not mutate Ref during an RPC.

func (SourceRef) Format

func (SourceRef) Format(s fmt.State, _ rune)

func (SourceRef) GoString

func (SourceRef) GoString() string

func (SourceRef) GobEncode

func (SourceRef) GobEncode() ([]byte, error)

GobEncode refuses to serialize protected requests and results.

func (SourceRef) MarshalJSON

func (SourceRef) MarshalJSON() ([]byte, error)

func (SourceRef) String

func (SourceRef) String() string

type Type

type Type struct {
	ID       string
	Extends  string
	Fields   []Field
	Validate func(context.Context, Material) error
	Import   func(context.Context, ImportRequest) (ImportResult, error)
	Describe func(context.Context, Material) (Metadata, error)
}

Type declares a plugin-owned schema. Extends, when set, names an exact base type. The explicit Validate operation checks the effective schema, then runs native validators base first. Describe and Import are optional; neither may put material into metadata. The SDK checks Describe inputs and imported drafts structurally without running Validate or authorizing their use.

type TypeDeclaration

type TypeDeclaration struct {
	ID        string
	Extends   string
	Fields    []Field
	Imports   bool
	Describes bool
}

TypeDeclaration describes a type's own fields. Its exact base supplies the inherited fields. Imports and Describes advertise optional implementations.

Directories

Path Synopsis
Package credentialhttp authenticates requests to one explicit HTTPS origin using a live SDK credential source.
Package credentialhttp authenticates requests to one explicit HTTPS origin using a live SDK credential source.
Package credentialtest exercises plugin credential providers and consumers without installing a host.
Package credentialtest exercises plugin credential providers and consumers without installing a host.
internal
httplifetime
Package httplifetime links the SDK's HTTP exchange to its source.
Package httplifetime links the SDK's HTTP exchange to its source.
instanceclock
Package instanceclock selects time for one credential transport before serving.
Package instanceclock selects time for one credential transport before serving.
testbroker
Package testbroker runs real go-plugin transports in-process for credential tests.
Package testbroker runs real go-plugin transports in-process for credential tests.
Package protocol defines credential wire versions and feature negotiation.
Package protocol defines credential wire versions and feature negotiation.

Jump to

Keyboard shortcuts

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