Documentation
¶
Overview ¶
Package modulekit is the scaffolding every Kiban module service needs and used to copy: bearer verification, the small HTTP/pg helpers, and thin clients for org's member facts, authz's effective-access/grants API and notification's targeted-events API. Every constructor takes the module key, which prefixes error strings ("<moduleKey>: ...") and, where the platform wire carries it, is sent as moduleKey/sourceModule. Modules never treat JWT roles as authority — the verifier answers "who is the caller" (kcSub only), never "what may they do".
Index ¶
- Constants
- Variables
- func BearerFromHeader(v string) string
- func ClampPage(page, pageSize int) (int, int)
- func DecodeJSON(w http.ResponseWriter, r *http.Request, v any) bool
- func IsUniqueViolation(err error) bool
- func PageParams(r *http.Request) (int, int)
- func ParsePathUUID(w http.ResponseWriter, r *http.Request, name string) (uuid.UUID, bool)
- func WritePage[T any, W any](w http.ResponseWriter, items []T, total, page, pageSize int, toWire func(T) W)
- type AuthzClient
- func (c *AuthzClient) AnchorTuple(objectType, objectID, companyID string) Tuple
- func (c *AuthzClient) Can(ctx context.Context, rawBearer, featureKey, companyID, relation string) (allowed bool, reason string, err error)
- func (c *AuthzClient) CompanyModuleObjectID(companyID string) string
- func (c *AuthzClient) DoCan(ctx context.Context, rawBearer string, req CanRequest) (allowed bool, reason string, err error)
- func (c *AuthzClient) GrantOrRevoke(ctx context.Context, rawBearer, companyID, op string, tuples []Tuple, ...) error
- func (c *AuthzClient) ModuleKey() string
- func (c *AuthzClient) PostJSON(ctx context.Context, rawBearer, path, what string, in, out any) error
- type CanRequest
- type CanResponse
- type Decision
- type GrantsRequest
- type MuxHandleFunc
- type NotificationClient
- type ObjectRef
- type OrgClient
- func (c *OrgClient) GetJSON(ctx context.Context, path, what string, out any, notFound error) error
- func (c *OrgClient) GetMember(ctx context.Context, memberID string) (OrgMember, error)
- func (c *OrgClient) MemberByKcSub(ctx context.Context, companyID, kcSub string) (memberID string, isMember, isActive bool, err error)
- type OrgMember
- type SendEventRequest
- type TokenVerifier
- type Tuple
Constants ¶
const DefaultJWKSRefreshInterval = 10 * time.Minute
DefaultJWKSRefreshInterval matches the gateway's own periodic refresh cadence, so a key rotated at the IdP is picked up without a process restart.
Variables ¶
var ErrOrgMemberNotFound = errors.New("org member not found")
ErrOrgMemberNotFound is GetMember's 404, returned wrapped as "<moduleKey>: org member not found"; match with errors.Is.
var ErrTokenInvalid = errors.New("bearer token invalid")
ErrTokenInvalid covers any bearer validation failure (missing, malformed, expired, wrong issuer/audience, bad signature). Verify returns it wrapped as "<moduleKey>: bearer token invalid"; match with errors.Is.
Functions ¶
func BearerFromHeader ¶
BearerFromHeader returns the token half of a "Bearer <token>" Authorization header value (scheme matched case-insensitively), or "" when the value is not a bearer credential.
func ClampPage ¶
ClampPage normalises pagination: page >= 1, pageSize in [1, 100] with 25 as the default.
func DecodeJSON ¶
DecodeJSON decodes the request body into v, writing the 400 envelope on a missing body or malformed JSON.
func IsUniqueViolation ¶
IsUniqueViolation reports whether err is a Postgres unique_violation (SQLSTATE 23505).
func PageParams ¶
PageParams reads ?page and ?pageSize (unparseable values read as 0; ClampPage normalises).
func ParsePathUUID ¶
ParsePathUUID parses the named path value as a UUID, writing the 400 envelope on failure.
Types ¶
type AuthzClient ¶
type AuthzClient struct {
// contains filtered or unexported fields
}
AuthzClient calls authz's POST /internal/authz/effective-access/can (per-operation decisions) and POST /internal/authz/grants (op:"grant"|"revoke") — a module's ONLY path to reading or writing authz tuples (modules never touch authz.* tables directly). rawBearer is always the acting caller's own bearer, forwarded verbatim (never a caller-supplied header, never re-derived); the grants endpoint binds every tuple to the request's company and gates the write on the bearer's access to that (module, company) — see GrantsRequest.
func NewAuthzClient ¶
func NewAuthzClient(client *http.Client, baseURL, moduleKey string) *AuthzClient
NewAuthzClient returns a client whose requests carry moduleKey and whose errors are prefixed with it.
func (*AuthzClient) AnchorTuple ¶
func (c *AuthzClient) AnchorTuple(objectType, objectID, companyID string) Tuple
AnchorTuple is the `<objectType>:<objectID>#company_module @ company_module:<companyId>/<moduleKey>` tuple every module object must carry (module contract §3): the decision layer binds a company-scope object check to the request's company through it, so an object without one is denied for everyone. Grant it in the same request as the object's owner tuple on create.
func (*AuthzClient) Can ¶
func (c *AuthzClient) Can(ctx context.Context, rawBearer, featureKey, companyID, relation string) (allowed bool, reason string, err error)
Can asks authz's effective-access decision for featureKey at company scope: the ordered decision's steps 1-6 (subject/Keycloak/lifecycle/company-active/membership/module-enabled) PLUS, when relation is non-empty, step 7's company_module#<relation> object-relation leg. Returns (allowed, reason, nil) on a well-formed response; any transport, non-200, or decode failure returns a non-nil error — callers must fail closed, never treat an error as allow.
func (*AuthzClient) CompanyModuleObjectID ¶
func (c *AuthzClient) CompanyModuleObjectID(companyID string) string
CompanyModuleObjectID builds the object id half of the company_module object-relation leg — the platform's object-id encoding "<companyId>/<moduleKey>".
func (*AuthzClient) DoCan ¶
func (c *AuthzClient) DoCan(ctx context.Context, rawBearer string, req CanRequest) (allowed bool, reason string, err error)
DoCan sends an arbitrary can request — the object-mode check on a module's own object type, or a position/group holder check.
func (*AuthzClient) GrantOrRevoke ¶
func (c *AuthzClient) GrantOrRevoke(ctx context.Context, rawBearer, companyID, op string, tuples []Tuple, correlationID string) error
GrantOrRevoke writes (op "grant") or removes (op "revoke") tuples through authz's grants API, bound to companyID (the request's company).
func (*AuthzClient) ModuleKey ¶
func (c *AuthzClient) ModuleKey() string
ModuleKey is the key given to NewAuthzClient.
func (*AuthzClient) PostJSON ¶
func (c *AuthzClient) PostJSON(ctx context.Context, rawBearer, path, what string, in, out any) error
PostJSON posts in to baseURL+path with the bearer, requiring 200 and decoding into out when non-nil; what names the call in error strings ("<moduleKey>: <what> request: HTTP 500").
type CanRequest ¶
type CanRequest struct {
FeatureKey string `json:"featureKey"`
ModuleKey string `json:"moduleKey"`
Scope string `json:"scope"`
CompanyID string `json:"companyId"`
Object ObjectRef `json:"object,omitempty"`
Relation string `json:"relation,omitempty"`
}
CanRequest is the effective-access/can request body.
type CanResponse ¶
type CanResponse struct {
Data Decision `json:"data"`
}
CanResponse is the effective-access/can response envelope.
type GrantsRequest ¶
type GrantsRequest struct {
Op string `json:"op"`
CompanyID string `json:"companyId"`
Tuples []Tuple `json:"tuples"`
CorrelationID string `json:"correlationId"`
}
GrantsRequest is the /internal/authz/grants request body. CompanyID is the company every tuple is bound to: authz refuses a tuple whose object is not this company's module object or a module object anchored to it, and gates the write on the bearer's access to (module, company) — a company_module tuple additionally needs the bearer to hold its admin relation.
type MuxHandleFunc ¶
type MuxHandleFunc interface {
HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))
}
MuxHandleFunc is the minimal surface a module's route mounter needs from a mux — *http.ServeMux satisfies it structurally, and so does a route recorder in tests.
type NotificationClient ¶
type NotificationClient struct {
// contains filtered or unexported fields
}
NotificationClient calls notification's S2S targeted-events endpoint (POST /internal/notification/v1/companies/{companyId}/events). Returns an error only on a genuine transport/non-200 failure — callers decide independently whether to log-and-continue (notification must never be a hard dependency for a module's own writes).
func NewNotificationClient ¶
func NewNotificationClient(client *http.Client, baseURL, moduleKey string) *NotificationClient
NewNotificationClient returns a client whose events carry moduleKey as sourceModule and whose errors are prefixed with it.
type OrgClient ¶
type OrgClient struct {
// contains filtered or unexported fields
}
OrgClient calls org's internal, unauthenticated-at-that-layer member-facts endpoints (modules consume the foundation's facts through APIs only — never a direct join into org's schema).
func NewOrgClient ¶
NewOrgClient returns a client whose errors are prefixed with moduleKey.
func (*OrgClient) GetJSON ¶
GetJSON reads baseURL+path into out, requiring 200; a 404 returns notFound when non-nil. what names the call in error strings ("<moduleKey>: <what>: HTTP 500").
type OrgMember ¶
type OrgMember struct {
ID string
CompanyID string
DisplayName string
IsActive bool
KcSub string // "" if the member has no linked user account
}
OrgMember is a member's own facts as org's GET /internal/org/members/{id} reports them.
type SendEventRequest ¶
type SendEventRequest struct {
RecipientKcSubs []string `json:"recipientKcSubs"`
SubjectLine string `json:"subjectLine"`
Body string `json:"body"`
SourceModule string `json:"sourceModule"`
}
SendEventRequest is the targeted-events request body.
type TokenVerifier ¶
type TokenVerifier struct {
// contains filtered or unexported fields
}
TokenVerifier validates bearer tokens against a JWKS (lestrrat-go/jwx/v3).
func NewTokenVerifier ¶
func NewTokenVerifier(ctx context.Context, jwksURL, issuer, audience, moduleKey string) (*TokenVerifier, error)
NewTokenVerifier fetches the JWKS once at construction, failing loudly if that fails.
func NewTokenVerifierHTTP ¶
func NewTokenVerifierHTTP(ctx context.Context, httpClient *http.Client, jwksURL, issuer, audience, moduleKey string) (*TokenVerifier, error)
NewTokenVerifierHTTP is NewTokenVerifier with the HTTP client the JWKS is fetched with (nil means http.DefaultClient) — a gateway behind a private CA or a test's self-signed cert.
func (*TokenVerifier) Refresh ¶
func (v *TokenVerifier) Refresh(ctx context.Context) error
Refresh forces a JWKS re-fetch regardless of cache age — wired to a periodic background goroutine (RefreshPeriodically) and also called once, inline, by Verify itself on an unknown-kid failure.
func (*TokenVerifier) RefreshPeriodically ¶
func (v *TokenVerifier) RefreshPeriodically(ctx context.Context, logger *slog.Logger, interval time.Duration)
RefreshPeriodically re-fetches the JWKS on a fixed interval until ctx is done. A failed refresh is logged and the previous key set keeps serving.
func (*TokenVerifier) Verify ¶
Verify returns the validated subject (kcSub). azp is never treated as an audience fallback (it would widen the accepted-token set). On a kid the cached JWKS doesn't recognize — the signal a key rotation just happened at the IdP — Verify refetches ONCE and retries the parse before giving up. Any other failure (expired, bad signature, wrong issuer/audience) is never retried.
type Tuple ¶
type Tuple struct {
ObjectType string `json:"objectType"`
ObjectID string `json:"objectId"`
Relation string `json:"relation"`
SubjectType string `json:"subjectType"`
SubjectID string `json:"subjectId"`
SubjectRelation string `json:"subjectRelation,omitempty"`
}
Tuple is one relation tuple on the grants wire.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package kittest is the test JWKS issuer a module's tests use to mint bearers for modulekit.TokenVerifier: an RSA key pair, an httptest JWKS server and a signer.
|
Package kittest is the test JWKS issuer a module's tests use to mint bearers for modulekit.TokenVerifier: an RSA key pair, an httptest JWKS server and a signer. |