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
- Variables
- func OneCandidate(key string, metadata Metadata) func(context.Context) ([]Candidate, error)
- func ProviderError(err error) error
- func ReadBasic(m Material) ([]byte, []byte, error)
- func ReadBearer(m Material) ([]byte, error)
- func ReadOAuthTokenSet(m Material) ([]byte, []byte, []byte, error)
- func ReadOpaque(m Material) ([]byte, error)
- func ReadSSHCert(m Material) ([]byte, []byte, error)
- func ReadSSHKey(m Material) ([]byte, error)
- func ReadX509(m Material) ([]byte, []byte, error)
- func RegisterPlugin(p *sdk.Plugin, opts PluginOpts) error
- type ApprovalPendingPrompt
- type Candidate
- type Claim
- type ConnectionDraft
- type CredentialDraft
- type DeviceCodePrompt
- type Expiry
- type FailureError
- type Field
- type FormPrompt
- type HostService
- type ImportRequest
- type ImportResult
- type Inventory
- type IssueRequest
- func (IssueRequest) Format(s fmt.State, _ rune)
- func (IssueRequest) GoString() string
- func (IssueRequest) GobEncode() ([]byte, error)
- func (r IssueRequest) Input(ctx context.Context, name string) (Lease, error)
- func (IssueRequest) MarshalJSON() ([]byte, error)
- func (r IssueRequest) Prompt(ctx context.Context, p Prompt) (PromptDisposition, error)
- func (IssueRequest) String() string
- type IssueResult
- type IssuedLease
- type Issuer
- type IssuerDeclaration
- type IssuerRef
- type Lease
- type LeaseOperation
- func (LeaseOperation) Format(s fmt.State, _ rune)
- func (LeaseOperation) GoString() string
- func (LeaseOperation) GobEncode() ([]byte, error)
- func (r LeaseOperation) Input(ctx context.Context, name string) (Lease, error)
- func (LeaseOperation) MarshalJSON() ([]byte, error)
- func (r LeaseOperation) Prompt(ctx context.Context, p Prompt) (PromptDisposition, error)
- func (LeaseOperation) String() string
- type Manager
- type Material
- func Basic(username, password []byte) Material
- func Bearer(token []byte) Material
- func OAuthTokenSet(accessToken, refreshToken, tokenType []byte) Material
- func Opaque(value []byte) Material
- func SSHCert(certificate, privateKey []byte) Material
- func SSHKey(privateKey []byte) Material
- func X509(certificateChain, privateKey []byte) Material
- type Metadata
- type Observation
- type ObservationOutcome
- type OpenURLPrompt
- type Pending
- type Plugin
- type PluginClient
- func (p *PluginClient) AttachSources(ctx context.Context, connection string, revision uint64, sources []SourceRef) (err error)
- func (p *PluginClient) Declarations(ctx context.Context, owner string) (Inventory, error)
- func (p *PluginClient) Describe(ctx context.Context, id string, material Material) (Metadata, error)
- func (p *PluginClient) Discover(ctx context.Context, issuer string) ([]Candidate, error)
- func (p *PluginClient) Import(ctx context.Context, r ImportRequest) (ImportResult, error)
- func (p *PluginClient) Issue(ctx context.Context, r IssueRequest) (IssueResult, error)
- func (p *PluginClient) Negotiate(ctx context.Context, supported []protocol.Feature) ([]protocol.Feature, error)
- func (p *PluginClient) Observe(ctx context.Context, op LeaseOperation) (Observation, error)
- func (p *PluginClient) Renew(ctx context.Context, op LeaseOperation) (IssueResult, error)
- func (p *PluginClient) Revoke(ctx context.Context, op LeaseOperation) (Observation, error)
- func (p *PluginClient) ServeCredentials(ctx context.Context, service HostService) (func(), error)
- func (p *PluginClient) Validate(ctx context.Context, id string, material Material) error
- type PluginOpts
- type PrivilegeTier
- type Prompt
- type PromptDisposition
- type PromptKind
- type RejectionReason
- type Replacement
- type ReplacementStatus
- type ReplacementStream
- type RequirementError
- type RevocationClass
- type Slot
- type Source
- type SourceError
- type SourceRef
- type Type
- type TypeDeclaration
Constants ¶
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.
const PluginID = "credential"
PluginID identifies the credential capability in the lifecycle inventory.
Variables ¶
var ErrInvalidMaterial = errors.New("invalid credential material")
ErrInvalidMaterial rejects a schema value or import document without naming it.
Functions ¶
func OneCandidate ¶
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 ¶
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 ReadBearer ¶
ReadBearer reads the token field, never an OAuth token set's access_token.
func ReadOAuthTokenSet ¶
ReadOAuthTokenSet returns the access token, refresh token, and token type in that order. An absent refresh token is returned as nil.
func ReadOpaque ¶
ReadOpaque reads only the opaque value field, not arbitrary material.
func ReadSSHCert ¶
ReadSSHCert returns the user certificate followed by the private key.
func ReadSSHKey ¶
ReadSSHKey reads the OpenSSH 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) GobEncode ¶
GobEncode refuses to serialize protected requests and results.
func (ApprovalPendingPrompt) MarshalJSON ¶
type Claim ¶
Claim describes a target for host review. It is not proof of identity or authorization.
type ConnectionDraft ¶
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) MarshalJSON ¶
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) MarshalJSON ¶
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 ¶
Until sets an absolute upper bound on delivery. Even time.Time{} selects a timestamp, not static or unknown expiry.
func (Expiry) ExpiresAt ¶
ExpiresAt returns the deadline only when Until selected an absolute timestamp.
func (Expiry) IsUnknownUntilRejected ¶
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 ¶
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) MarshalJSON ¶
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.
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) MarshalJSON ¶
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) MarshalJSON ¶
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) Input ¶
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) Prompt ¶
func (r IssueRequest) Prompt(ctx context.Context, p Prompt) (PromptDisposition, error)
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.
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) MarshalJSON ¶
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 Get caller. Keep handles, parents and all material off logs, profiles and UI paths. See Material for rendering limits.
func (Lease) MarshalJSON ¶
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) Input ¶
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) Prompt ¶
func (r LeaseOperation) Prompt(ctx context.Context, p Prompt) (PromptDisposition, error)
Prompt has the same contract as IssueRequest.Prompt during Renew. Revoke and Observe cannot prompt.
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 ¶
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 OAuthTokenSet ¶
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 (Material) MarshalJSON ¶
MarshalJSON returns only a fixed redaction. JSON is not a material transport.
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 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) MarshalJSON ¶
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) MarshalJSON ¶
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 ¶
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 ¶
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) Declarations ¶
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 ¶
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) Import ¶
func (p *PluginClient) Import(ctx context.Context, r ImportRequest) (ImportResult, error)
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 ¶
func (p *PluginClient) Issue(ctx context.Context, r IssueRequest) (IssueResult, error)
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 ¶
func (p *PluginClient) Observe(ctx context.Context, op LeaseOperation) (Observation, error)
Observe asks the issuer about upstream state, never the host's lease cache.
func (*PluginClient) Renew ¶
func (p *PluginClient) Renew(ctx context.Context, op LeaseOperation) (IssueResult, error)
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 ¶
func (p *PluginClient) Revoke(ctx context.Context, op LeaseOperation) (Observation, error)
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. Call the idempotent stop at process retirement. 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.
type PluginOpts ¶
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 ¶
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 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.
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) 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) MarshalJSON ¶
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.
Source Files
¶
- binding_channel.go
- binding_generation.go
- binding_host.go
- binding_plugin.go
- callback_scopes.go
- delivery.go
- errors.go
- host_client.go
- host_server.go
- host_types.go
- intercepted_reply.go
- issuer_callbacks.go
- manager.go
- manager_declarations.go
- manager_schema.go
- material.go
- messages.go
- plugin.go
- plugin_client.go
- plugin_server.go
- receiver_refs.go
- rpc_context.go
- source.go
- source_attach.go
- source_http.go
- types.go
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. |