gnap

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: MIT Imports: 31 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.

README

gnap-caep-risc

A server-side GNAP client. The key is registered by value and proved with mutual TLS, an HTTP message signature, or a detached JWS. Access tokens are key-bound; a bearer token is refused. One Shared Signals poll stream carries CAEP and RISC events.

The private key stays in this process. The same gnap.json shape as the Python and Node libraries loads: the JSON keys are identical.

Build and tests

docker build --target test .

The test stage and the demo build stage each copy go.mod and go.sum and run go mod download with GOPROXY=https://proxy.golang.org,direct, so github.com/rcbj/iya-pep-go is fetched from the module proxy. The test stage then runs go test -race ./... and go test -race -tags iyapep ./... in golang:1.27, and the demo is built with -tags iyapep. GitHub Actions uses that command. Do not run the Go toolchain on the host. The demo image does not run the suite. The final image is debian:bookworm-slim and includes openssl, which makes the client key and can make a PEP key.

python3 scripts/live_iya_sts.py is the live half. It starts a fresh iya-sts from its main branch in memory mode when IYA_STS_URL is unset (IYA_STS_IMAGE names an iya-sts image to start instead of building one). It copies this checkout to a scratch build context, makes the client key and its self-signed certificate there with openssl in the demo image, and runs the install script scripts/configure_iya_sts.py (standard-library Python on the host), which registers the demo and writes the tlsCa chain. Then it rebuilds the demo image, checks the image carries that chain and no key, starts it with only the key and certificate mounted, no CA mount and TLS_CA_REFRESH=0, signs in, and requires a credential-change event and a session-revoked event on GET /live-status. The second event ends the local session. LIVE_STS_PORT (default 18560) and LIVE_DEMO_PORT (default 18660) choose the ports. It never binds port 3000 or 8081, and it runs no Go on the host. --pep (or LIVE_PEP=1) passes --pep central to the install script, mounts generated/pep-key.pem after that image check, and requires pep.mode central on the signed-in status. The nightly workflow runs the unit suite and this script without --pep at 07:14 UTC.

concurrency_test.go and cmd/demo/concurrency_test.go (TestConcurrency…) start goroutines together and repeat: sixteen users getting grants at once and each finishing only their own, one finish continued once, rotation once per grant, Track while the receiver starts, track and untrack of one person against a transmitter, a session-revoked for one user ending only theirs, poll against stop, the demo's /live-status for eight users, its receiver started once by concurrent first sign-ins, and its gsid cookie over https.

Module path: github.com/rcbj/gnap-caep-risc-go. A release happens when the library's files changed since the last release's tag: release.yml takes one patch above the highest published version, publishes it, and creates the matching tag and GitHub Release. A change to tests, the demo, or the docs releases nothing. To choose a version or start a new minor, raise VERSION; the version is stamped in CI and is not committed, so the manifests can trail what is published.

The iya-sts trust chain (tlsCa)

tlsCa in demo/gnap.json names the iya-sts TLS listener CA trust chain the library trusts. The default is generated/idp-ca.pem, relative to demo/. The value may also be file:<path>, env:<NAME>, or the PEM itself. The library takes every certificate in it: the presented leaf is accepted when it is one of them, and otherwise the presented chain must verify to any of them. The host name is checked against the leaf's subjectAltName either way (a DNS name, or an IP literal against an IP SAN). A leaf that is not in the file is never accepted because some other presented certificate is. trust_chain_test.go holds all of that.

scripts/configure_iya_sts.py, the install script, writes that file. It saves the whole chain iya-sts publishes at GET /tls/server-certificate (leaf, TLS Issuing CA, Intermediate, Root), or the chain from the TLS handshake when that path does not answer. It prints the path, the trust anchor's subject and its SHA-256 fingerprint. Compare the anchor with the Root CA on iya-sts's PKI page.

The demo image build copies that file into the image at /app/demo/generated/idp-ca.pem, so the image trusts that iya-sts with no bind mount and no fetch. Run the install script before you build the image. Rebuild the image after running the install script against a different iya-sts. .dockerignore admits only that file from demo/generated. The client key and certificate stay out of the image; compose mounts demo/generated for them. A build with no chain file yet (a fresh clone, CI) still succeeds; the image then has no tlsCa file.

The mechanism is COPY demo demo plus .dockerignore's demo/generated/* and !demo/generated/idp-ca.pem. Do not replace it with a COPY that names the file or globs for it: when the file is absent, BuildKit fails on the missing demo/generated and the classic builder fails with "no source files were specified". A directory COPY of demo/ (which always exists) succeeds in both. The build stage copies only the Go sources, so a new chain does not rebuild the binary.

The container also refreshes the file from the authorization server at start, because a development iya-sts makes a new CA when it restarts. A failed refresh keeps the file from the build. TLS_CA_REFRESH=0 turns the refresh off. python3 scripts/trust_chain.py --config demo/gnap.json refreshes it by hand.

Three calls

gnapClient, err := gnap.FromFile("gnap.json")
started, err := gnapClient.RequestGrant()
done, err := gnapClient.FinishRedirect(query, []string{started.Pending.ID})

RequestGrant returns a redirect and a pending grant. FinishRedirect checks the interaction hash against grants this process started, then continues the grant with the key proof. Pass the pending ids this browser was given.

Resolve loads the same document without starting a grant.

Goroutine safety

  • Share one *gnap.Client across every request goroutine. RequestGrant, RequestClientGrant, FinishRedirect, FinishPush, AuthorizationHeaders, Call, Rotate, EnsureFresh and Revoke may run at once. A finish is matched, its pending grant taken and its hash recorded in one step under the client's lock, so the same finish delivered twice continues the grant once.
  • Rotation is once per grant. Concurrent Rotate or EnsureFresh calls for one grant (its manage URI) wait for one rotation and share its result; a caller still holding the grant that was just rotated gets the new one. Keep the grant each call returns: the old access token is spent.
  • A Grant is a value. Rotation returns a new one and never changes the one it was given.
  • client.Config is read-only after New or FromFile.
  • Share one *gnap.SignalsReceiver. Track, Untrack, PollOnce, Stream, Verify and Stop may run at once with Start and the background poll; the transmitter configuration and the stream are written and read under the receiver's lock, and Stream() returns a copy. Track and Untrack of one person are serialised under that person's lock, so the transmitter's last word about them is Add Subject exactly while a session of theirs is tracked.
  • Configure before Start. SetAddSubjects, On and UsePep are called before Start. onEndSessions and the handlers run on the poll goroutine; take your own lock for state they share with request handlers.
  • A receiver authenticates as the application. RequestClientGrant asks for a client-only grant (no interaction, no subject); the demo polls with that, rotated with EnsureFresh, never with a person's grant. iya-sts issues one only to an application with gnapSkipInteraction TRUE, which the install script sets.

Signals

signals omitted or true keeps CAEP and RISC on. The resolved configuration omits the key, fills ssf from ssf.transmitter or transmitterIssuer, and asks for ssf.read and ssf.manage when access does not say otherwise.

signals: false does not start the Shared Signals receiver, does not require transmitter metadata, and drops ssf.read and ssf.manage from the GNAP access. The resolved configuration includes signals: false. If those two rights were the only ones, configuration fails and asks for another right the authorization server grants. Any other value fails with signals must be true or false.

ssf.pollIntervalMs is the poll interval in milliseconds. ssf.addSubjects defaults to true and is stored on the resolved configuration beside ssf, not inside it. false turns Add Subject and Remove Subject off. Anything else fails with ssf.addSubjects must be true or false. With signals off, the default stays true and a value in the file is not read.

Embedded PEP

A pep section asks iya-sts whether the person a grant names may do something. The engine is iya-pep-go, package pep. It is optional, compiled only with the iyapep build tag (go build -tags iyapep), as Rust's library has an optional pep feature: without the tag nothing links iya-pep-go, and a configuration with a pep section is refused at load (pep is configured, and this build has no embedded PEP: build with -tags iyapep (github.com/rcbj/iya-pep-go)). go.mod pins the module to one commit. Resolve loads it and does not start it. New and FromFile start it. docs/remote-pep.md is the setup.

pdpUrl defaults to the grant endpoint's realm (https://sts/realm/acme/gnap gives https://sts/realm/acme), not idTokenIssuer. The assertion key is compared with the client instance key by PEMThumbprint. The same key is refused: pep.assertionKey is the GNAP client instance key (privateKey); the PEP needs a key of its own.

Decide and DecideGrant do not return an error. Decision.HTTPStatus is 200 for a permit and 403 for a deny and for unavailable. A signed-out 401 is the caller's question, asked before the PEP.

In local mode, and in central mode with permitCacheMs, the receiver asks for pep-policies-changed, adds the application as an opaque subject when it starts, and never removes that subject. It adds the person at sign-in and removes them when their last sign-in ends. A refusal is logged once and does not fail the sign-in.

ADMIN_API_CLIENT_SECRET=… python scripts/configure_iya_sts.py --config demo/gnap.json --pep central

--pep without a mode is local. Generate the client key first; a configuration with no pep section still loads. When the realm checks GNAP mutual TLS by PKI, the same script still issues the client's certificate and replaces the generated key. The certificate's name is readable. It is not CN=localhost.

With a pep section the demo's signed-in pages link GET /attribute-protected (permitted when directory attr1 is abc123) and GET /orders/42 (a read permitted when the sign-in has an acr). POST /orders/42 is a write. Any other method on those paths is 404. Both pages are 401 while signed out. The signed-in home page shows the username. The catalogue row subject.acr maps to urn:example:acr.

Demo

The signed-in home page has three tabs: Identity, CAEP & RISC events (Ask for a verification event), and Policy enforcement (four panes: Decisions, Cached policy, The PEP, and Control plane). docs/remote-pep.md describes them.

docker compose up --build

PORT defaults to 3000 and is the bind port. Loopback finish and display URLs follow PORT. Any other host is left as written. PUBLIC_URL or --public-url replaces the origin and keeps the path. GET /healthz returns ok. Each browser has its own session: several people may be signed in at once, a session-revoked ends only the sessions of the person it names, and every signed-in person sees every event. The gsid cookie is Secure when the demo is served over https. GET /live-status is JSON for the sign-in in this browser and the Shared Signals events the demo has accepted: signedIn, subject, receiver, and events of type and jti. It does not include tokens. The home page has a sign-in control; /login starts a grant, /callback finishes it, and POST /logout signs out.

The shipped demo/gnap.json leaves signals on by omitting the key. Key material is file: or env: and is not in the tree. Register the application with:

ADMIN_API_CLIENT_SECRET=… python scripts/configure_iya_sts.py --config demo/gnap.json
docker compose up --build

The build bakes in the trust chain the install script saved. A test user password the script generates goes to demo/generated/<user>.password (mode 0600); it is never printed.

--dry-run prints the admin API calls and sends nothing. When the gnap-demo container is running, its PORT wins over the shell PORT.

License

MIT. Copyright (c) 2026 Iya CyberSecurity Solutions, LLC.

Documentation

Index

Constants

View Source
const (
	CAEP = "https://schemas.openid.net/secevent/caep/event-type/"
	RISC = "https://schemas.openid.net/secevent/risc/event-type/"
	SSF  = "https://schemas.openid.net/secevent/ssf/event-type/"
)

CAEP, RISC, and SSF event type prefixes.

View Source
const (
	EventSessionRevoked                  = CAEP + "session-revoked"
	EventTokenClaimsChange               = CAEP + "token-claims-change"
	EventCredentialChange                = CAEP + "credential-change"
	EventAssuranceLevelChange            = CAEP + "assurance-level-change"
	EventDeviceComplianceChange          = CAEP + "device-compliance-change"
	EventSessionEstablished              = CAEP + "session-established"
	EventSessionPresented                = CAEP + "session-presented"
	EventRiskLevelChange                 = CAEP + "risk-level-change"
	EventAccountCredentialChangeRequired = RISC + "account-credential-change-required"
	EventAccountPurged                   = RISC + "account-purged"
	EventAccountDisabled                 = RISC + "account-disabled"
	EventAccountEnabled                  = RISC + "account-enabled"
	EventIdentifierChanged               = RISC + "identifier-changed"
	EventIdentifierRecycled              = RISC + "identifier-recycled"
	EventCredentialCompromise            = RISC + "credential-compromise"
	EventOptIn                           = RISC + "opt-in"
	EventOptOutInitiated                 = RISC + "opt-out-initiated"
	EventOptOutCancelled                 = RISC + "opt-out-cancelled"
	EventOptOutEffective                 = RISC + "opt-out-effective"
	EventRecoveryActivated               = RISC + "recovery-activated"
	EventRecoveryInformationChanged      = RISC + "recovery-information-changed"
	EventSessionsRevoked                 = RISC + "sessions-revoked"
	EventVerification                    = SSF + "verification"
	EventStreamUpdated                   = SSF + "stream-updated"
)

Shared Signals event types this receiver understands.

View Source
const SameKeyMessage = "pep.assertionKey is the GNAP client instance key (privateKey); the PEP needs a key of its own"

SameKeyMessage is the refusal when pep.assertionKey is this client's instance key.

Variables

DefaultEndingEvents end local sessions that match the subject.

DefaultEventsRequested is the set a new stream asks for.

Functions

func AsFloat

func AsFloat(value any) (float64, bool)

func AsList

func AsList(value any) ([]any, bool)

func AsMap

func AsMap(value any) (map[string]any, bool)

func AsString

func AsString(value any) (string, bool)

func B64Std

func B64Std(data []byte) string

func B64URL

func B64URL(data []byte) string

func B64URLDecode

func B64URLDecode(value string) ([]byte, error)

func ContentDigest

func ContentDigest(body string) string

func DecodeJSON

func DecodeJSON(text string) (any, error)

func DefaultPDPURL added in v0.1.1

func DefaultPDPURL(grantEndpoint string) string

DefaultPDPURL is the iya-sts base a GNAP grant endpoint belongs to, realm prefix kept. https://sts/realm/acme/gnap and https://sts/realm/acme/as/gnap both give https://sts/realm/acme. https://sts/gnap gives https://sts. An unparseable URL gives "".

func DetachedJWS

func DetachedJWS(key *ClientKey, method, rawURL string, body *string, token string) (string, error)

func Dump

func Dump(value any) (string, error)

func Fingerprint256

func Fingerprint256(cert *x509.Certificate) string

func HashEqual

func HashEqual(a, b string) bool

func Href

func Href(raw string) (string, error)

func InteractionHash

func InteractionHash(clientNonce, serverNonce, interactRef, grantEndpoint string) string

InteractionHash is base64url(SHA-256(clientNonce, serverNonce, interact_ref, grant endpoint)) separated by newlines.

func IsLoopback

func IsLoopback(raw string) bool

func IsNumber

func IsNumber(value any) bool

func Origin

func Origin(raw string) (string, error)

func PublicKeyFromJWK

func PublicKeyFromJWK(jwk map[string]any) (crypto.PublicKey, error)

func PublicKeyObject

func PublicKeyObject(key *ClientKey) (map[string]any, error)

func ReadTrust

func ReadTrust(raw, base string) string

ReadTrust returns PEM trust material. A missing file is empty, not an error.

func SHA256

func SHA256(data []byte) []byte

func SignRaw

func SignRaw(key *ClientKey, data []byte) ([]byte, error)

func SignRequest

func SignRequest(key *ClientKey, method, rawURL string, headers map[string]string, body *string) (map[string]string, error)

func SubjectID added in v0.1.1

func SubjectID(person *Person) string

SubjectID is the id iya-sts's PIP resolves: a non-empty account uid, else the assertion's username claim, else preferred_username, else sub (kept even when empty).

func SubjectOf

func SubjectOf(subID any, issuer string) map[string]string

SubjectOf names the person, email, and provider session an event is about.

func TimingEqual

func TimingEqual(a, b string) bool

func UIDFromAccount

func UIDFromAccount(uri string) *string

UIDFromAccount returns the user part of an acct: URI. Invalid percent-encoding is kept as written.

func VerifyRaw

func VerifyRaw(public crypto.PublicKey, alg string, data, signature []byte) bool

func WellKnown

func WellKnown(issuer, suffix string) ([]string, error)

Types

type Answer

type Answer struct {
	Status      int
	ContentType string
	Body        string
}

Answer is one HTTP response. Body is capped at 2 MiB.

func Send

func Send(rawURL, method string, headers map[string]string, body *string, tlsOpt TLSOpt, code string) (*Answer, error)

type Client

type Client struct {
	Config *Config
	// contains filtered or unexported fields
}

Client is a server-side GNAP client. The private key stays in this process.

func FromFile

func FromFile(path string) (*Client, error)

FromFile loads gnap.json and returns a client.

func New

func New(cfg *Config) (*Client, error)

New returns a client for an already resolved configuration. It starts the embedded PEP when the configuration has one. Resolve does not.

func (*Client) AuthorizationHeaders

func (c *Client) AuthorizationHeaders(grant *Grant, method, rawURL string, body *string) (map[string]string, error)

AuthorizationHeaders are the key proof for one request that carries this grant's access token.

func (*Client) Call

func (c *Client) Call(grant *Grant, rawURL, method string, headers map[string]string, body *string) (*Answer, error)

Call sends a key-bound request.

func (*Client) EnsureFresh

func (c *Client) EnsureFresh(grant *Grant) (*Grant, error)

EnsureFresh rotates when the access token expires within 60 seconds. now is milliseconds.

func (*Client) FinishPush

func (c *Client) FinishPush(body any) (*Finished, error)

FinishPush completes a back-channel interaction finish.

func (*Client) FinishRedirect

func (c *Client) FinishRedirect(query any, allowedIDs []string) (*Finished, error)

FinishRedirect completes a redirect interaction. allowedIDs are the pending ids this browser was given.

func (*Client) RememberRevoked added in v0.1.1

func (c *Client) RememberRevoked(uri string)

RememberRevoked records a continuation URI DecideGrant treats as revoked. The ring keeps 10000 URIs and forgets the oldest.

func (*Client) RequestClientGrant added in v0.1.1

func (c *Client) RequestClientGrant(access []any) (*Grant, error)

RequestClientGrant asks for a client-only grant (RFC 9635 section 1.6.2): access for the client acting as itself, such as a Shared Signals receiver, with no interaction and no subject information. The authorization server must issue it at once; one that asks for an interaction is refused. With iya-sts the application needs gnapSkipInteraction TRUE.

func (*Client) RequestGrant

func (c *Client) RequestGrant() (*GrantResult, error)

RequestGrant asks for the configured access and returns the redirect the browser should open.

func (*Client) RequestGrantAccess

func (c *Client) RequestGrantAccess(access []any, expectedSub string, user any) (*GrantResult, error)

RequestGrantAccess asks for access, or the configured rights when access is nil. expectedSub is optional.

func (*Client) Revoke

func (c *Client) Revoke(grant *Grant) error

Revoke deletes the grant.

func (*Client) Rotate

func (c *Client) Rotate(grant *Grant) (*Grant, error)

Rotate asks the authorization server for a new access token.

func (*Client) TLS

func (c *Client) TLS() (TLSOpt, error)

TLS is the back-channel trust material, including the mutual TLS chain when that proof is in use.

type ClientKey

type ClientKey struct {
	Proof    string
	Private  any
	Thumb    string
	Alg      string
	Kid      string
	JWK      map[string]string
	CertPEM  string
	ChainPEM string
}

ClientKey is the one key this process proves. The private half is not sent.

func LoadClientKey

func LoadClientKey(privatePEM, certificatePEM, proof string) (*ClientKey, error)

func (*ClientKey) PrivatePEM

func (k *ClientKey) PrivatePEM() (string, error)

type Config

type Config struct {
	GrantEndpoint      string
	IDTokenIssuer      string
	Application        string
	ClassID            string
	Display            *Display
	Access             []any
	Signals            *bool
	SubIDFormats       []string
	AssertionFormats   []string
	Key                *ClientKey
	FinishURI          string
	FinishMethod       string
	InteractionStart   []string
	HashMethod         string
	RequireBoundTokens bool
	UseInstanceID      bool
	TLSCA              string
	AllowInsecure      bool
	ClockToleranceSec  float64
	MaxWaitSec         float64
	TransactionTTLSec  float64
	SSF                *SSFConfig
	// AddSubjects is Add Subject and Remove Subject on the receiver. It defaults
	// to true and is not a member of SSF. signals: false leaves it true.
	AddSubjects bool
	// contains filtered or unexported fields
}

Config is a resolved gnap.json. Signals is nil when CAEP and RISC stay on, and false when they are off.

func ReadConfigFile

func ReadConfigFile(path string) (*Config, error)

ReadConfigFile loads gnap.json from path.

func Resolve

func Resolve(raw map[string]any, baseDir string) (*Config, error)

Resolve checks raw gnap.json and returns the configuration the client uses.

type Continuation

type Continuation struct {
	URI         string
	AccessToken string
	Wait        *float64
}

Continuation is a GNAP continue or manage handle. The token is key-bound.

type Display

type Display struct {
	Name string
	URI  string
}

Display is the client name and URI shown to the resource owner.

type Error

type Error struct {
	Code    string
	Msg     string
	Gnap    string
	Context any
	Cont    *Continuation
	Cause   error
}

Error is a config, discovery, protocol, validation, signature, or ssf failure.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type Finished

type Finished struct {
	Grant   *Grant
	Context any
}

Finished is a grant completed from a redirect or a push.

type Grant

type Grant struct {
	AccessToken  string
	Bearer       bool
	Access       any
	ExpiresIn    *float64
	ExpiresAt    *float64
	Manage       *Continuation
	Continuation *Continuation
	InstanceID   string
	Subject      *Person
	GrantID      string
}

Grant is an access token and the subject it was issued for.

type GrantResult

type GrantResult struct {
	RedirectURL string
	Pending     *Pending
	Grant       *Grant
}

GrantResult is either a redirect the browser must follow or a grant that needed no interaction.

type GrantServer

type GrantServer struct {
	GrantRequestEndpoint string
	InteractionStart     []string
	InteractionFinish    []string
	KeyProofs            []string
	SubIDFormats         []string
	AssertionFormats     []string
}

GrantServer is the metadata from OPTIONS on the grant endpoint.

func DiscoverGrantServer

func DiscoverGrantServer(grantEndpoint string, tlsOpt TLSOpt) (*GrantServer, error)

func ValidateGrantServer

func ValidateGrantServer(raw any, grantEndpoint string) (*GrantServer, error)

type IDCheck

type IDCheck struct {
	Issuer    string
	Audiences []string
	Skew      float64
	Keys      func() ([]map[string]any, error)
}

IDCheck is how an id_token is judged.

type JWS

type JWS struct {
	Header  map[string]any
	Payload map[string]any
}

JWS is a verified compact JWS header and payload.

func VerifyCompactJWS

func VerifyCompactJWS(token string, keys []map[string]any) (*JWS, error)

VerifyCompactJWS checks a Security Event Token or an ID token. none and HMAC are refused.

type KeyPair

type KeyPair struct {
	PrivateKeyPEM  string
	CertificatePEM string
	Fingerprint    string
	Certificate    *x509.Certificate
	Private        *ecdsa.PrivateKey
}

KeyPair is a self-signed P-256 key and certificate kept in this process.

func CreateSelfSignedKeyPair

func CreateSelfSignedKeyPair(commonName string, dns []string, ips []string) (*KeyPair, error)

CreateSelfSignedKeyPair builds a P-256 certificate whose only key usage is digitalSignature.

type Logger

type Logger interface {
	Info(string)
	Warn(string)
	Error(string)
}

Logger receives receiver progress. A nil logger prints.

type OpenID

type OpenID struct {
	Issuer  string
	JWKSURI string
}

OpenID is the issuer and its jwks_uri.

func DiscoverOpenID

func DiscoverOpenID(issuer string, tlsOpt TLSOpt) (*OpenID, error)

type Pending

type Pending struct {
	ID                string
	ClientNonce       string
	ServerNonce       string
	HashMethod        string
	Continuation      *Continuation
	ContinueNotBefore float64
	GrantEndpoint     string
	CreatedAt         float64
	Context           any
	InstanceID        string
	ExpectedSub       string
}

Pending is a grant whose browser interaction has not finished.

type Person

type Person struct {
	Sub               string
	Claims            map[string]any
	AssertionVerified bool
	Iss               string
	Uid               *string
	Email             string
	Name              string
	PreferredUsername string
	Sid               string
	Acr               string
	Amr               []string
}

Person is the subject of a grant. Uid is nil when the grant has no account identifier.

func PersonFrom

func PersonFrom(subject any, check IDCheck) (*Person, error)

PersonFrom reads a GNAP subject. An id_token is checked when one is present.

type ReceiverOpt

type ReceiverOpt struct {
	TLS             TLSOpt
	Headers         func(SSFRequest) map[string]string
	EventsRequested []string
	EndOn           []string
	Description     string
	PollIntervalMs  int
	MaxEvents       int
	Log             Logger
}

ReceiverOpt tunes one poll receiver.

type SSFConfig

type SSFConfig struct {
	Transmitter    string
	PollIntervalMs int
}

SSFConfig is the transmitter the receiver polls. It is absent when signals are off.

type SSFRequest

type SSFRequest struct {
	Method string
	URL    string
	Body   string
}

SSFRequest is one transmitter call. Body is set when the call has one.

type SignalEvent

type SignalEvent struct {
	Type     string
	Payload  any
	Subject  map[string]string
	JTI      string
	Sessions []string
	Ended    bool
	IAT      *float64
	Txn      string
}

SignalEvent is one event from a Security Event Token.

type SignalsReceiver

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

SignalsReceiver polls one Shared Signals stream. Stop waits until the poll Start already had in flight has finished.

Its transmitter configuration and stream are written by Start and read by every poll, Track, Untrack and Verify, always under mu.

func NewSignalsReceiver

func NewSignalsReceiver(transmitter string, onEnd func([]string, *SignalEvent), opt ReceiverOpt) (*SignalsReceiver, error)

NewSignalsReceiver builds a receiver. onEndSessions is required. The transmitter is an http(s) URL.

func (*SignalsReceiver) On

func (r *SignalsReceiver) On(eventType string, handler func(*SignalEvent)) *SignalsReceiver

On registers a handler for one event type, or "*" for every event.

func (*SignalsReceiver) PollOnce

func (r *SignalsReceiver) PollOnce() (bool, error)

PollOnce fetches one batch. A caller that arrives while a poll is running waits for that poll.

func (*SignalsReceiver) SetAddSubjects added in v0.1.1

func (r *SignalsReceiver) SetAddSubjects(add bool)

SetAddSubjects turns Add Subject and Remove Subject on or off. The default is on. Set it before Start.

func (*SignalsReceiver) Start

func (r *SignalsReceiver) Start() error

Start discovers the transmitter, opens one poll stream, and polls in the background.

func (*SignalsReceiver) Stop

func (r *SignalsReceiver) Stop()

Stop waits until the background poll has finished, so the next poll is a new one.

func (*SignalsReceiver) Stream

func (r *SignalsReceiver) Stream() map[string]any

Stream is a copy of the poll stream, once Start has found or created it.

func (*SignalsReceiver) Track

func (r *SignalsReceiver) Track(session TrackedSession)

Track remembers a local session and, when Add Subject is on, names the person on the stream.

func (*SignalsReceiver) Untrack

func (r *SignalsReceiver) Untrack(localID string)

Untrack forgets a local session and removes its subject when no other sign-in maps to it.

func (*SignalsReceiver) Verify

func (r *SignalsReceiver) Verify(state string) error

Verify asks the transmitter to send a verification event.

type TLSOpt

type TLSOpt struct {
	CA       string
	Cert     string
	Key      string
	Insecure bool
}

TLSOpt is the back-channel trust material. CA pins the authorization server. Cert and Key are the mutual TLS client.

type TrackedSession

type TrackedSession struct {
	LocalID    string
	Person     string
	Email      string
	IDPSession string
	ExpiresAt  *float64
}

TrackedSession is one local session that a signal can end.

func TrackedFromPerson

func TrackedFromPerson(localID string, person *Person, expiresAt *float64) TrackedSession

TrackedFromPerson copies the identifiers a grant subject can be found by.

Directories

Path Synopsis
cmd
demo command

Jump to

Keyboard shortcuts

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