docs

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: 16 Imported by: 0

Documentation

Overview

AuthzClient talks to authz's real effective-access decision (POST /internal/authz/ effective-access/can and /batch-can, the pattern every module uses) plus the grants S2S surface (POST /internal/authz/grants, op:"grant"|"revoke") — this module's ONLY path to writing/removing authz tuples (modules never write authz.* tables directly). The can/batch-can wire shape supports an explicit object-mode check (Object+Relation), which this module uses as its primary access decision (docs_document owner/editor/viewer), together with op:"revoke" for share removal.

Package docs implements the DocShare module service: per-document sharing with fine-grained authorization (owner/editor/viewer via Zanzibar tuples; a document nobody shared stays unreadable even to the superadmin). Built solely against the platform's Go "SDK" packages (internal/errenv, internal/audit, internal/httpx, internal/obs, internal/config, modulekit) plus HTTP calls to org's company-facts API, authz's effective-access/grants API, and notification's targeted-events API — never by reaching into any foundation schema.

Store is the docs service's data access layer: a pgx pool (connected as kiban_docs, the module's own DB role) plus the audit writer for "audit.docs__events". Hand-written SQL against docs's own schema only — no sqlc codegen, same accepted v1 pattern notification's/timesheet's own Store use.

AUTHORIZATION NEVER LIVES HERE (the index is NEVER authoritative). Every method in this file is a plain read/write of docs's own tables; the caller (http.go) is responsible for asking AuthzClient first and for calling the authz grants API BEFORE the corresponding Store write, mirroring timesheet's own store_approvers.go convention exactly (authorize, THEN persist the local read-side index row — never the reverse, so a failed grant never leaves a local row implying access that was never actually granted).

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrDocumentNotFound = errors.New("docs: document not found")
	ErrShareNotFound    = errors.New("docs: share not found")
)
View Source
var ErrIdempotencyConflict = errors.New("docs: idempotency key reused with a different payload")

ErrIdempotencyConflict means the same Idempotency-Key was reused with a DIFFERENT payload (same idempotency_key_hash approach as notification's) — reject instead of silently replaying the first request's result.

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

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 AuditEvent

type AuditEvent struct {
	OccurredAt time.Time
	Actor      string
	Action     string
	Subject    string
	Payload    map[string]any
}

type AuthzClient

type AuthzClient struct {
	*modulekit.AuthzClient
}

AuthzClient is modulekit's authz client plus this module's feature -> relation-leg mapping, its docs_document object-mode checks and its share grants.

func NewAuthzClient

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

func (*AuthzClient) BatchCanObject

func (c *AuthzClient) BatchCanObject(ctx context.Context, rawBearer, companyID string, docIDs []string, relation string) (map[string]bool, error)

BatchCanObject verifies, in one round trip, whether the bearer holds `relation` on each of docIDs (docs_document) — used by listDocuments (belt and braces, the engine is the source of truth; the read-side share index is NEVER authoritative on its own). Returns a docID->allowed map; docIDs the response doesn't cover (should not happen on a well-formed response) are treated as denied — fail closed.

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 a FEATURE-ONLY check (docs.manage / docs.create) — the ordered decision's steps 1-6 plus, for docs.manage, step 7's company_module#admin leg. rawBearer is forwarded verbatim (never a caller-supplied header, never re-derived).

func (*AuthzClient) CanObject

func (c *AuthzClient) CanObject(ctx context.Context, rawBearer, companyID, docID, relation string) (allowed bool, reason string, err error)

CanObject asks authz's effective-access decision for docs's OWN object type (docs_document): "may THIS caller (the bearer) act as `relation` on docs_document:<docID>?" — the object-mode check, this module's primary access decision for every document read/write. The featureKey carried on the wire is informational only (audit-log labeling on a deny — see internal/authz/http.go's auditDenial); it never gates anything itself once Object+Relation are present.

func (*AuthzClient) GrantDocumentOwner

func (c *AuthzClient) GrantDocumentOwner(ctx context.Context, rawBearer, companyID, docID, creatorKcSub, correlationID string) error

GrantDocumentOwner writes `docs_document:<docID>#owner @ user:<creatorKcSub>` PLUS the `company_module` anchor tuple, both on document create (authz accepts the owner tuple only because the anchor arrives in the same request). rawBearer is the ACTING caller's own bearer; authz binds the write to companyID and gates it on the bearer's docs access there.

func (*AuthzClient) GrantShare

func (c *AuthzClient) GrantShare(ctx context.Context, rawBearer, companyID, docID, relation, kcSub, correlationID string) error

GrantShare writes `docs_document:<docID>#relation @ user:<kcSub>` (relation is "viewer" or "editor"); authz refuses it unless the document is anchored to companyID.

func (*AuthzClient) RevokeShare

func (c *AuthzClient) RevokeShare(ctx context.Context, rawBearer, companyID, docID, relation, kcSub, correlationID string) error

RevokeShare removes `docs_document:<docID>#relation @ user:<kcSub>` — through authz's op:"revoke".

type Document

type Document struct {
	ID         uuid.UUID
	CompanyID  uuid.UUID
	Title      string
	Body       string
	OwnerKcSub string
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

type NotificationClient

type NotificationClient = modulekit.NotificationClient

NotificationClient delivers "<name> shared '<title>' with you" / "your access to '<title>' was revoked" notices through notification's S2S targeted-events endpoint. Non-fatal if notification is down: every call site in store.go treats a SendEvent error as log-and-continue, never a share/revoke failure.

func NewNotificationClient

func NewNotificationClient(client *http.Client, baseURL string) *NotificationClient

type OrgClient

type OrgClient = modulekit.OrgClient

OrgClient reads org's member facts (modules consume the foundation's facts through APIs only — never a direct join into org's schema): the caller's OWN member id (docs.share is keyed by member_id) and a share target's memberId resolved to its linked user's kcSub (422 if none).

func NewOrgClient

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

type Service

type Service struct {
	Store        *Store
	Verifier     *modulekit.TokenVerifier
	Authz        *AuthzClient
	Org          *OrgClient
	Notification *NotificationClient
}

Service wires the docs module's HTTP surface: bearer verification + per-operation authz decision — company-scoped feature checks (docs.create/docs.manage) for the two routes that need them, and the OBJECT-mode check (docs_document owner/editor/viewer) for every per-document route. This is the module's central authorization boundary: the read-side share index (store.go) is NEVER consulted for an allow/deny decision, only for listing.

func NewService

func NewService(store *Store, verifier *modulekit.TokenVerifier, authz *AuthzClient, org *OrgClient, notif *NotificationClient) *Service

func (*Service) Routes

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

type Share

type Share struct {
	ID         uuid.UUID
	DocumentID uuid.UUID
	MemberID   uuid.UUID
	Relation   string
	GrantedBy  string
	CreatedAt  time.Time
}

type Store

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

func NewStore

func NewStore(pool *pgxpool.Pool, auditWriter *audit.Writer) *Store

func (*Store) CreateDocument

func (s *Store) CreateDocument(ctx context.Context, docID uuid.UUID, actor string, companyID uuid.UUID, title, body, idempotencyKey string) (Document, error)

CreateDocument persists a new document row at the given docID — the caller (handler) MUST already have generated docID and successfully granted `docs_document:<docID>#owner @ user:<creatorKcSub>` (plus the company_module pointer tuple) through AuthzClient .GrantDocumentOwner BEFORE calling this, so a document row never exists without its owner tuple already in place. idempotencyKey (may be "") is persisted alongside its payload hash for future replay detection via FindDocumentByIdempotencyKey — this method itself does not replay/conflict-check (the handler already did, via FindDocumentByIdempotencyKey, before generating docID and granting the owner tuple).

func (*Store) DeleteDocument

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

func (*Store) DocumentAudit

func (s *Store) DocumentAudit(ctx context.Context, docID uuid.UUID) ([]AuditEvent, error)

DocumentAudit returns every audit event whose subject is exactly this document (shares, revokes, edits, create) — the per-doc audit panel.

func (*Store) FindDocumentByIdempotencyKey

func (s *Store) FindDocumentByIdempotencyKey(ctx context.Context, companyID uuid.UUID, ownerKcSub, idempotencyKey string) (Document, string, bool, error)

FindDocumentByIdempotencyKey looks up a previously created document by (companyID, ownerKcSub, idempotencyKey) — the handler calls this BEFORE granting the owner authz tuple, so a replayed create-document request never issues a second (orphaned) grant. Returns the stored payload hash (empty string for a row stored without a hash) alongside the document so the caller can distinguish a genuine replay from a payload conflict.

func (*Store) FindShareByIdempotencyKey

func (s *Store) FindShareByIdempotencyKey(ctx context.Context, docID uuid.UUID, idempotencyKey string) (Share, string, bool, error)

FindShareByIdempotencyKey looks up a previously recorded share by (docID, idempotencyKey) — the handler calls this BEFORE granting the authz relation tuple, so a replayed create-share request never issues a second (orphaned) grant. Returns the stored payload hash (empty string for a share recorded before this key existed) alongside the share.

func (*Store) GetDocument

func (s *Store) GetDocument(ctx context.Context, companyID, docID uuid.UUID) (Document, error)

func (*Store) GetDocumentsByIDs

func (s *Store) GetDocumentsByIDs(ctx context.Context, companyID uuid.UUID, docIDs []uuid.UUID) ([]Document, error)

func (*Store) GetShare

func (s *Store) GetShare(ctx context.Context, docID, memberID uuid.UUID) (Share, error)

func (*Store) ListOwnedDocuments

func (s *Store) ListOwnedDocuments(ctx context.Context, companyID uuid.UUID, ownerKcSub string) ([]Document, error)

ListOwnedDocuments returns every document companyID/ownerKcSub created — never verified via authz (the owner tuple was granted atomically at create time; nothing revokes an owner's own relation in this module), matching the "owned" half of GET /documents.

func (*Store) ListShares

func (s *Store) ListShares(ctx context.Context, docID uuid.UUID) ([]Share, error)

func (*Store) ModuleAudit

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

ModuleAudit returns a page of the company's docs__events rows (module-wide admin view — deliberately includes titles/actions but NEVER document body content, since this table is never written with body text). Every event carries its company in payload.companyId; rows without one belong to no company's view.

func (*Store) Pool

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

func (*Store) RecordShare

func (s *Store) RecordShare(ctx context.Context, actor string, companyID, docID, memberID uuid.UUID, relation, grantedByKcSub, idempotencyKey string) (Share, error)

RecordShare upserts the local index row. Caller MUST have already granted `docs_document:<docID>#relation @ user:<targetKcSub>` through AuthzClient.GrantShare before calling this (store_approvers.go's own established ordering). idempotencyKey (may be "") is persisted alongside its payload hash for future replay detection via FindShareByIdempotencyKey — this method itself does not replay/conflict-check (the handler already did, before granting the relation tuple). NOTE: docs.share's own UNIQUE(document_id, member_id) upsert-in-place semantics are UNCHANGED by this — a second share of the SAME member always still updates that one row regardless of idempotency key; the key only gates whether the FIRST call for a given key is treated as a fresh grant or a replay.

func (*Store) RemoveShare

func (s *Store) RemoveShare(ctx context.Context, actor string, companyID, docID, memberID uuid.UUID) error

RemoveShare deletes the local index row. Caller MUST have already revoked the corresponding authz tuple via AuthzClient.RevokeShare before calling this.

func (*Store) SharedDocumentIDsForMember

func (s *Store) SharedDocumentIDsForMember(ctx context.Context, companyID, memberID uuid.UUID) ([]uuid.UUID, error)

SharedDocumentIDsForMember returns the document ids docs.share currently lists as shared with memberID, in ANY relation — the CANDIDATE list for the "shared with me" half of GET /documents. Never authoritative on its own: the caller MUST batch-verify each id via AuthzClient.BatchCanObject before returning it (belt and braces: the engine is the source of truth).

func (*Store) UpdateDocument

func (s *Store) UpdateDocument(ctx context.Context, actor string, companyID, docID uuid.UUID, title, body string) (Document, error)

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

func (*ValidationError) Error

func (e *ValidationError) Error() string

Directories

Path Synopsis
Command docs runs kiban-docs: the DocShare module service's HTTP API (fine-grained, per-document sharing).
Command docs runs kiban-docs: the DocShare module service's HTTP API (fine-grained, per-document sharing).

Jump to

Keyboard shortcuts

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