gnap

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 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 runs go test ./... in golang:1.27. GitHub Actions uses that command. Do not run the Go toolchain on the host. The demo image does not run the suite.

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. The nightly workflow runs the unit suite and this script at 07:14 UTC.

Module path: github.com/rcbj/gnap-caep-risc-go. A proxy or GitHub publish is not set up.

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.

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.

Demo

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. 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.

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 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 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

New returns a client for an already resolved configuration.

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) 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
}

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 {
	Stream map[string]any
	// contains filtered or unexported fields
}

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

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) 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) Track

func (r *SignalsReceiver) Track(session TrackedSession)

Track remembers a local session.

func (*SignalsReceiver) Untrack

func (r *SignalsReceiver) Untrack(localID string)

Untrack forgets a local session.

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