notification

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: Apache-2.0, Apache-2.0 Imports: 28 Imported by: 0

Documentation

Overview

notification's per-operation authorization goes through authz's real effective-access decision (POST /internal/authz/effective-access/can), with the fragment's own object-relation leg (step 7 of the ordered decision) for the two tiers that need it. `channels.manage`/`messages.send` anchor on `company_module#admin` (authz.fragment.json's own accessRulePayload), resolvable because every (company, module) pair gets a default `company_module:<companyId>/<moduleKey>#system @ system:platform` structural tuple. `inbox.view` carries NO relation leg: its fragment anchors on `company_module#member`, which does not exist on the base model's `company_module` type (internal/authz/engine/model.json only defines system/company/admin/editor/submitter/approver/viewer) — wiring it literally would engine-error (UNKNOWN_RELATION) for every caller. inbox.view is therefore gated by the ordered decision's steps 1-6 (company-membership-based), never relation-gated.

OrgClient reads org's membership-fact endpoint (modules consume the foundation's facts through APIs only — never a direct join into org's schema) to confirm a targeted event's RECIPIENT kcSubs are active company members before any recipient_state row is ever written for them.

Package notification implements the notification module service: channels, subscriptions, messages/inbox, and leased background delivery jobs, built solely against the platform's Go "SDK" packages (internal/errenv, internal/audit, internal/httpx, internal/obs, internal/config) plus HTTP calls to org's company-facts API — never by reaching into any foundation schema.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrConflict          = errors.New("notification: conflict")
	ErrChannelNotFound   = errors.New("notification: channel not found")
	ErrMessageNotFound   = errors.New("notification: message not found")
	ErrRecipientNotFound = errors.New("notification: recipient state not found")
)
View Source
var ErrIdempotencyConflict = errors.New("notification: idempotency key reused with a different payload")

ErrIdempotencyConflict: idempotency keys are payload-bound (409 on conflicting reuse) — the same Idempotency-Key was reused on this channel with a DIFFERENT subjectLine/body, so reject instead of silently replaying the first request's message, which would mask exactly this class of client bug.

View Source
var ErrLeaseLost = errors.New("notification: lease lost (job reclaimed by another worker or already settled)")

ErrLeaseLost is returned by CompleteJob/FailJob/FailJobPermanent when the fencing UPDATE affects zero rows — the caller's lease_token no longer matches the row (it expired and was reclaimed by another worker, or the job already left 'pending'). Callers log and drop; they must never retry with a different token or otherwise overwrite state a newer claim owns. ExtendLeaseBatch reports the same condition per-token, via its returned map, rather than this error (a batch call must not fail wholesale just because one job's lease in the batch was lost).

View Source
var ErrNonRetryableDelivery = errors.New("notification: non-retryable delivery failure")

ErrNonRetryableDelivery marks a delivery failure the worker must never retry — currently only a delivery-time WebhookPolicy rejection (retrying a target the policy just rejected can never succeed). Wrapped (errors.Is still matches) so the worker can distinguish it from an ordinary transient delivery error without either side needing to know the concrete error type.

Functions

func CheckMigrationsApplied

func CheckMigrationsApplied(ctx context.Context, pool *pgxpool.Pool) error

CheckMigrationsApplied verifies migrations have been run — it never runs them itself (ARCH-004: no runtime DDL, ever; migrations are applied out-of-band by `make migrate- notification`, as the kiban owner role) — same pattern as every other service's Store.

func NewTokenVerifier

func NewTokenVerifier(ctx context.Context, jwksURL, issuer, audience string) (*modulekit.TokenVerifier, error)

NewTokenVerifier wires modulekit's bearer verifier under this module's error prefix.

Types

type AuthzClient

type AuthzClient struct {
	*modulekit.AuthzClient
}

AuthzClient is modulekit's authz client plus this module's feature -> relation-leg mapping.

func NewAuthzClient

func NewAuthzClient(client *http.Client, baseURL string) *AuthzClient

func (*AuthzClient) Can

func (c *AuthzClient) Can(ctx context.Context, rawBearer, featureKey, companyID string) (allowed bool, reason string, err error)

Can asks authz's effective-access decision for featureKey at company scope, adding the company_module relation leg relationLeg declares for it. rawBearer is forwarded verbatim (the SAME bearer withAuth already verified itself). Any transport, non-200, or decode failure returns a non-nil error — callers must fail closed, never treat an error as allow.

func (*AuthzClient) GrantChannelAnchor

func (c *AuthzClient) GrantChannelAnchor(ctx context.Context, rawBearer, companyID, channelID string) error

GrantChannelAnchor writes `notification_channel:<channelID>#company_module @ company_module:<companyID>/notification` on channel create — the anchor the fragment's `notification_channel.company_module` relation declares and the decision layer binds object checks through.

type Channel

type Channel struct {
	ID        uuid.UUID
	CompanyID uuid.UUID
	Key       string
	Label     string
	Kind      string
	Target    *string
	CreatedAt time.Time
}

type Deliverer

type Deliverer interface {
	Deliver(ctx context.Context, d JobDelivery) error
}

Deliverer sends one job (email via net/smtp to mailpit, webhook via signed HTTP POST).

type DeliveryJob

type DeliveryJob struct {
	ID          uuid.UUID
	MessageID   uuid.UUID
	Kind        string // "email" | "webhook"
	Target      string
	Status      string // "pending" | "done" | "dead"
	Attempts    int
	LeasedUntil *time.Time
	LastError   *string
	// LeaseToken is the fencing token this specific claim holds. Every Complete/Fail call must
	// present the token it was handed by ClaimJobs (and
	// every token passed to ExtendLeaseBatch) — a stale token (the lease already expired and a
	// second worker reclaimed the row) affects zero rows instead of overwriting the second
	// worker's state. Never the zero UUID for a freshly claimed job.
	LeaseToken uuid.UUID
}

DeliveryJob is one leased background delivery.

type JobDelivery

type JobDelivery struct {
	Job         DeliveryJob
	SubjectLine string
	Body        string
}

JobTarget resolves a delivery job's recipient-facing metadata the deliverer needs beyond DeliveryJob itself (message subject/body) — a small join, kept out of ClaimJobs's own RETURNING clause because most callers (list/inspect) never need the message body.

type Mailer

type Mailer struct {
	Host string
	Port string
	From string
	// Timeout bounds the dial + the SMTP conversation. Zero uses defaultSMTPTimeout.
	Timeout time.Duration
}

Mailer delivers a job via net/smtp to a mailpit container (dev), never a vendor SDK. No auth (mailpit accepts anonymous SMTP on 1025 by default).

func NewMailer

func NewMailer(host, port, from string) *Mailer

func (*Mailer) Deliver

func (m *Mailer) Deliver(ctx context.Context, d JobDelivery) error

Deliver dials with a context deadline (net/smtp.SendMail cannot time out on its own — it has no context parameter and no dial-timeout option — so this reimplements SendMail's steps by hand: dial via (&net.Dialer{}).DialContext against a deadline, then feed the resulting conn to smtp.NewClient, matching every other step SendMail itself performs).

type MembershipChecker

type MembershipChecker interface {
	IsActiveMember(ctx context.Context, companyID, kcSub string) (bool, error)
}

MembershipChecker is the seam SendTargetedEvent uses to confirm each recipient kcSub is an ACTIVE member of companyID before a recipient_state row is ever written for them — satisfied by OrgClient in production (orgclient.go), faked in tests. A non-nil error is treated IDENTICALLY to "not a member": the recipient is skipped, never delivered to on an unconfirmed membership (fail-closed — recipients that are not members are skipped, not errors, and that extends to "recipients we couldn't confirm," which is not the same as "confirmed member").

type Message

type Message struct {
	ID          uuid.UUID
	CompanyID   uuid.UUID
	ChannelID   uuid.UUID
	SubjectLine string
	Body        string
	CreatedBy   string
	CreatedAt   time.Time
	ReadAt      *time.Time
}

type OrgClient

type OrgClient struct {
	*modulekit.OrgClient
}

func NewOrgClient

func NewOrgClient(client *http.Client, baseURL string) *OrgClient

func (*OrgClient) IsActiveMember

func (c *OrgClient) IsActiveMember(ctx context.Context, companyID, kcSub string) (bool, error)

IsActiveMember reports whether kcSub is an ACTIVE member of companyID, per org's own membership fact endpoint. A transport/decode/non-200 failure returns a non-nil error — SendTargetedEvent treats that identically to "not a member" (skip, never deliver on an unconfirmed recipient).

type ResolvedWebhookTarget

type ResolvedWebhookTarget struct {
	URL  *url.URL
	Port string
	IPs  []netip.Addr
}

ResolvedWebhookTarget is a validated webhook target — the parsed URL plus the exact IPs its host resolved to at validation time, so the caller can dial those IPs directly (closing the DNS-rebinding window between validation and connect: a second lookup at dial time could return a different, unvalidated answer).

type Service

type Service struct {
	Store    *Store
	Verifier *modulekit.TokenVerifier
	Authz    *AuthzClient
	// Org is the membership-confirmation dependency (OrgClient, orgclient.go). May be
	// nil in tests that never exercise handleSendEvent — every other route is unaffected.
	Org MembershipChecker
}

Service wires the notification module's HTTP surface: bearer verification (own JWKS copy — backend modules verify the bearer themselves; JWT roles are never authority) + a per-operation authz effective-access decision (see authzclient.go's header comment and withAuth's own doc comment below for exactly what this checks and what it deliberately does NOT differentiate).

func NewService

func NewService(store *Store, verifier *modulekit.TokenVerifier, authz *AuthzClient) *Service

func (*Service) Routes

func (svc *Service) Routes() http.Handler

type Store

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

Store is the notification service's data access layer: a pgx pool (connected as kiban_notification) plus the audit writer for "audit.notification__events". No sqlc codegen: every query is hand-written SQL against notification's own schema only.

func NewStore

func NewStore(pool *pgxpool.Pool, auditWriter *audit.Writer, claimGroup string, webhookPolicy *WebhookPolicy) *Store

NewStore builds a Store bound to one claim_group and one webhook SSRF policy (the policy CreateChannel validates webhook targets against — cmd/main.go hands the same instance to the worker's WebhookSender so the create-time check and the delivery-time re-check agree; tests inject one with a custom Resolver). Claim group: every delivery_job this Store enqueues (SendMessage) and claims (ClaimJobs) is scoped to claimGroup, so a Store's worker only ever competes with other Stores/workers sharing its own group. Production always uses "default" (cmd/main.go's KIBAN_NOTIFICATION_CLAIM_GROUP, defaulted there); a module's own test suite uses a unique per-run group (dbtest_env_test.go) so it never races the live kiban-notification compose container's worker, which only ever polls "default".

func (*Store) ClaimJobs

func (s *Store) ClaimJobs(ctx context.Context, lease time.Duration, limit int) ([]DeliveryJob, error)

ClaimJobs claims up to limit jobs: UPDATE ... leased_until=now()+lease, attempts=attempts+1 WHERE status='pending' AND (leased_until IS NULL OR leased_until<now()) ORDER BY created_at LIMIT n FOR UPDATE SKIP LOCKED RETURNING *. lease is a parameter (not a fixed 30s) so tests can use a short lease to prove crash-reclaim without a 30s sleep; the worker's own production loop (Worker.leaseDuration) uses 30s. The claim is also scoped to s.claimGroup — this Store only ever claims jobs it (or another Store sharing its group) enqueued, so a module's own test suite's Store, bound to its own per-run group, never races the live kiban-notification container's worker Store, bound to "default".

func (*Store) CompleteJob

func (s *Store) CompleteJob(ctx context.Context, id, leaseToken uuid.UUID) error

CompleteJob marks a job done, fenced by leaseToken: a worker whose lease already expired and got reclaimed affects zero rows here instead of clobbering the reclaiming worker's state — see ErrLeaseLost.

func (*Store) CountJobsByState

func (s *Store) CountJobsByState(ctx context.Context) (map[string]int, error)

CountJobsByState returns this Store's own claim_group's delivery_job count per status ("pending"/"done"/"dead") — the kiban_delivery_jobs{state} gauge source. A single grouped COUNT query, called periodically by the worker (Worker.reportJobCounts), never on every state transition.

func (*Store) CreateChannel

func (s *Store) CreateChannel(ctx context.Context, actor string, companyID uuid.UUID, key, label, kind string, target *string) (Channel, error)

func (*Store) DeleteChannel

func (s *Store) DeleteChannel(ctx context.Context, actor string, companyID, channelID uuid.UUID) error

func (*Store) ExtendLeaseBatch

func (s *Store) ExtendLeaseBatch(ctx context.Context, tokens []uuid.UUID, lease time.Duration) (map[uuid.UUID]bool, error)

ExtendLeaseBatch heartbeats every job in a claimed batch, not only the one currently being delivered: otherwise a slow first delivery lets every LATER job in that same batch expire behind it and be reclaimed by another worker, causing a duplicate external send once the slow delivery finally finished and the original worker resumed its own stale copy of the later job. Extending every job in the claimed batch in one UPDATE (keeping the single-round-trip batch claim) closes that window: as long as this worker is still alive and ticking, no job it holds can be reclaimed, whether or not delivery of it has started yet. Scoped to status='pending' like ExtendLease, so a token whose job already left 'pending' (this worker's own Complete/Fail already ran, in a concurrent goroutine — not a competing worker) is silently excluded rather than misreported as lost; the RETURNING set tells the caller exactly which tokens are still genuinely held.

func (*Store) FailJob

func (s *Store) FailJob(ctx context.Context, id, leaseToken uuid.UUID, attempts int, deliverErr error) error

FailJob records a delivery failure (back to pending, or dead once attempts reach maxAttempts), fenced by leaseToken. attempts was already incremented by ClaimJobs; leased_until is set to now()+retryBackoff(attempts) so the claim predicate (leased_until < now()) holds the job back for the backoff — an outbound outage no longer burns every attempt in a few seconds.

func (*Store) FailJobPermanent

func (s *Store) FailJobPermanent(ctx context.Context, id, leaseToken uuid.UUID, deliverErr error) error

FailJobPermanent marks a job dead immediately, without going through the normal retry ladder (a delivery-time SSRF policy violation is non-retryable — retrying a target the policy just rejected can never succeed, so it isn't given the remaining attempts budget). attempts is recorded as -1 in the audit payload to distinguish a policy-forced dead-letter from one that genuinely exhausted maxAttempts.

func (*Store) GetChannel

func (s *Store) GetChannel(ctx context.Context, companyID, channelID uuid.UUID) (Channel, error)

func (*Store) ListChannels

func (s *Store) ListChannels(ctx context.Context, companyID uuid.UUID, page, pageSize int) ([]Channel, int, error)

func (*Store) ListInbox

func (s *Store) ListInbox(ctx context.Context, companyID uuid.UUID, subject string, page, pageSize int) ([]Message, int, error)

ListInbox returns the caller's own messages (recipient_state.subject = subject), newest first — v1 is poll-only (Out of scope: "in-app real-time").

func (*Store) LoadJobDelivery

func (s *Store) LoadJobDelivery(ctx context.Context, job DeliveryJob) (JobDelivery, error)

func (*Store) MarkRead

func (s *Store) MarkRead(ctx context.Context, actor string, companyID, messageID uuid.UUID, subject string) (Message, error)

MarkRead sets recipient_state.read_at=now() for (messageId, subject) — the caller may only ever mark THEIR OWN recipient row read (subject is always the validated bearer, never a request field), scoped to companyID so a message from another company 404s instead of leaking existence.

func (*Store) Pool

func (s *Store) Pool() *pgxpool.Pool

func (*Store) SendMessage

func (s *Store) SendMessage(ctx context.Context, actor string, companyID, channelID uuid.UUID, subjectLine, body, idempotencyKey string) (Message, bool, error)

func (*Store) SendTargetedEvent

func (s *Store) SendTargetedEvent(ctx context.Context, checker MembershipChecker, actor string, companyID uuid.UUID, sourceModule, subjectLine, body string, recipientKcSubs []string) (sent, skipped int, err error)

SendTargetedEvent is the S2S delivery primitive: another module ("your doc was shared", "ticket assigned to you") targets SPECIFIC recipient kcSubs, bypassing the normal self-subscription fan-out SendMessage uses. It auto-provisions ONE per-company system channel per sourceModule (key "events-<sourceModule>", kind in_app, created lazily on first use via an upsert — "admin-owned by convention," i.e. no end-user ever manages it through the channels.manage API, but this module writes no authz tuple for it either: a system channel has no natural owner subject, and nothing reads notification_channel-scoped authz for it since recipient_state is written directly here, never through the subscribe/publish path that authz-gates real channels) and writes notification.recipient_state rows DIRECTLY for every CONFIRMED recipient (checker.IsActiveMember) — an unconfirmed/non-member recipient is silently skipped, counted, never an error for the whole call. actor is the acting end user (the bearer http.go's handler already validated + authorized as an active company member) — recorded as the message's created_by and the audit event's Actor, same convention SendMessage uses.

func (*Store) Subscribe

func (s *Store) Subscribe(ctx context.Context, actor string, companyID, channelID uuid.UUID, subject string, email *string) error

func (*Store) Unsubscribe

func (s *Store) Unsubscribe(ctx context.Context, actor string, companyID, channelID uuid.UUID, subject string) error

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

func (*ValidationError) Error

func (e *ValidationError) Error() string

type WebhookPolicy

type WebhookPolicy struct {
	AllowHTTP    bool
	AllowedHosts map[string]struct{} // lower-cased hostnames; nil/empty = no allowlist restriction
	Resolver     *net.Resolver       // nil = net.DefaultResolver
}

WebhookPolicy enforces the webhook target rules, applied identically at CREATE time (webhook channel target) and at DELIVERY time (re-resolve — DNS can change between create and delivery/each delivery, so a validated hostname is re-checked, never cached past one resolution):

  • scheme must be https, UNLESS the KIBAN_WEBHOOK_ALLOW_HTTP dev opt-in env is "true" (default false — plaintext webhook delivery is off by default);
  • every resolved IP must be a routable, non-internal unicast address: loopback, RFC1918, link-local (incl. the 169.254.169.254 cloud metadata address), IPv6 unique-local/site-local, multicast, and unspecified are all rejected;
  • an optional operator egress allowlist, KIBAN_WEBHOOK_ALLOWED_HOSTS (comma-separated hostnames, case-insensitive) — empty/unset means policy-only (no allowlist restriction beyond the address-class checks above).

func NewWebhookPolicyFromEnv

func NewWebhookPolicyFromEnv() *WebhookPolicy

NewWebhookPolicyFromEnv builds the policy the production worker/HTTP layer uses, reading KIBAN_WEBHOOK_ALLOW_HTTP and KIBAN_WEBHOOK_ALLOWED_HOSTS directly (both optional — no config.Load Required entry, so a deployment that never sets them gets the safe https-only, policy-only-no-allowlist default).

func (*WebhookPolicy) Validate

func (p *WebhookPolicy) Validate(ctx context.Context, rawURL string) (ResolvedWebhookTarget, error)

Validate parses rawURL, enforces the scheme rule, resolves the host (or accepts a literal IP with no DNS lookup), and rejects the target if ANY resolved address falls in a disallowed class or (when set) the host isn't on the operator allowlist. Called both at webhook-channel CREATE time and again immediately before every delivery attempt.

type WebhookPolicyError

type WebhookPolicyError struct {
	Message string
}

WebhookPolicyError marks a webhook target rejected by the SSRF guard — distinct from ValidationError because it maps to the shared errenv.CodeValidationFailed code (VALIDATION_FAILED) rather than the field-shape errenv.CodeValidationError, and because a delivery-time rejection is a non-retryable delivery failure, not a request-shape problem.

func (*WebhookPolicyError) Error

func (e *WebhookPolicyError) Error() string

type WebhookSender

type WebhookSender struct {
	Policy     *WebhookPolicy
	HMACSecret string
	Timeout    time.Duration
	// contains filtered or unexported fields
}

WebhookSender delivers a job via a signed HTTP POST. The signature is HMAC-SHA256 over the raw JSON body, hex-encoded, in X-Notification-Signature — a receiver verifies by recomputing over the exact bytes received.

Every delivery re-validates the target through Policy (DNS can change between channel-create time and delivery time, and between one delivery attempt and the next, so the CREATE-time check alone is not enough) and dials only the IPs that validation just approved (pinnedDialContext) — never the transport's own independent DNS lookup, which would reopen the rebinding window Validate just closed.

One http.Transport per sender (built by NewWebhookSender, reused by every Deliver): a fresh transport per delivery leaked its keep-alive connection and loop goroutines until the remote closed them. The per-delivery pin survives the sharing: Deliver stores the validated target in the request context and the transport's single DialContext dials only that target's IPs. A pooled idle connection is one a previous delivery dialed to an address the policy approved then; it is never re-resolved, and a target the policy now rejects never reaches the transport.

func NewWebhookSender

func NewWebhookSender(policy *WebhookPolicy, hmacSecret string) *WebhookSender

NewWebhookSender builds a sender bound to policy (nil = NewWebhookPolicyFromEnv, the production default).

func (*WebhookSender) Deliver

func (w *WebhookSender) Deliver(ctx context.Context, d JobDelivery) error

type Worker

type Worker struct {
	Store         *Store
	Mailer        Deliverer
	Webhook       Deliverer
	Logger        *slog.Logger
	PollInterval  time.Duration
	LeaseDuration time.Duration
	BatchSize     int

	// Metrics records kiban_delivery_jobs{state} (a periodic re-count, see reportJobCounts —
	// a periodic re-count is cheaper than updating the gauge on
	// every individual state transition) and kiban_delivery_attempts_total{kind,outcome} (updated
	// inline, once per attempt: deliverLeased/failJob). Nil-safe (every Registry method on a nil
	// *metrics.Registry is a documented no-op) — left unset by every existing test's NewWorker
	// call, so nothing here changes their behavior.
	Metrics *metrics.Registry
	// MetricsInterval controls how often reportJobCounts re-counts delivery_job by state.
	// Defaults to 15s (NewWorker) — independent of PollInterval so a fast test poll interval
	// doesn't turn this into a per-second COUNT query.
	MetricsInterval time.Duration
}

Worker is the leased delivery loop: poll -> claim -> deliver -> complete/fail, heartbeating the lease while delivery is in flight. One Worker instance is one "worker" for crash-reclaim purposes — stopping it (ctx cancel) mid-lease, with no complete/fail ever recorded, is exactly the "kill worker mid-lease" scenario the mandatory test drives.

func NewWorker

func NewWorker(store *Store, mailer, webhook Deliverer, logger *slog.Logger) *Worker

func (*Worker) Run

func (w *Worker) Run(ctx context.Context)

Run polls until ctx is cancelled. It never returns an error — delivery failures are per-job (FailJob), not process-fatal (Design: "fail=>pending", retried, never crashes the worker).

Directories

Path Synopsis
Command notification runs kiban-notification: the notification module service — channels/subscriptions/messages/inbox HTTP API plus the leased delivery worker, in one process (the module manifest names one service.port; the worker is an in-process background loop, not a second binary).
Command notification runs kiban-notification: the notification module service — channels/subscriptions/messages/inbox HTTP API plus the leased delivery worker, in one process (the module manifest names one service.port; the worker is an in-process background loop, not a second binary).

Jump to

Keyboard shortcuts

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