Skip to content

Latest commit

 

History

History
195 lines (175 loc) · 10.9 KB

AGENTS.md

File metadata and controls

195 lines (175 loc) · 10.9 KB

AGENTS.md — teamusers

Standalone Go identity & access microservice for the Nekostick service fleet. Single source of truth for users, teams, groups, roles, permissions, credentials, sessions, and audit; issues EdDSA JWTs and serves JWKS for the rest of the fleet. API-only (no UI), deployed as a Nekostick-supervised child process behind a route prefix such as /iam/.

Repository layout

cmd/teamusers/          entrypoint: run / status / doctor / bootstrap-admin
cmd/genspec/            OpenAPI generator (routes + doc.go metadata -> YAML)
internal/
  config/               env + flag loading, secret redaction
  domain/               permission grammar, wildcard matcher, resolver (deny > allow)
  store/                pgx queries, goose migrations (embedded), session reaper
  authn/                argon2id, TOTP, passkeys, token issue/rotate, JWKS, self-service
  authz/                effective-set resolver, ABAC expr eval, /authz/check
  httpapi/              chi routers: runtime plane, /me plane, admin plane, middleware
  events/               outbox relay -> NATS JetStream; notify.* -> HMAC HTTP
  audit/                append-only audit writer
  apidocsgen/           teamusers-side wiring for spec generation (builders, fake store)
migrations/             goose SQL, numbered NNNN_name.sql, Up/Down mandatory
apidocs/go/             standalone Go module (github.com/crazy4chicken/nsc-teamusers/apidocs/go):
                        chi route walking, route<->metadata pairing, OpenAPI emission;
                        distributed via apidocs/go/vX.Y.Z tags
apidocs/vitepress/      npm package teamusers-apidocs-vitepress (API reference renderer)
sdk/go|ts|python/       local-verification SDKs (JWKS cache, perm cache, middleware)
test/                   end-to-end integration tests (TEAMUSERS_TEST_PG-gated)
docs/                   VitePress site; api/reference + public/openapi.yaml generated
PLAN.md                 backlog of UNFINISHED work only (see "Planning docs" below)

Commands

go run ./cmd/teamusers run          # needs TEAMUSERS_CONNECTION_STRING etc.
go run ./cmd/teamusers doctor       # diagnose config/DB/keys
go run ./cmd/genspec                # regenerate docs/public/openapi.yaml
pnpm docs:dev / docs:build          # docs site (predocs hooks run genspec)
TEAMUSERS_TEST_PG='postgres://...' go test ./test/   # integration suite

Integration tests require a real PostgreSQL and skip when TEAMUSERS_TEST_PG is unset. No in-memory substitute is accepted.

Architecture invariants (do not break)

  • Tokens prove identity only. Permissions are NEVER embedded in JWTs. Claims contract consumed by all three SDKs: iss, aud, sub, team, kind, perm_ver, iat, exp, jti, auth_time, amr; impersonation tokens add act ({sub: admin id}) + imp=true and force auth_time=0. Additive-only; changing existing claim names/shapes is a breaking cross-repo change.
  • Effective set = direct bindings U group bindings -> roles -> permission keys, minus failed ABAC conditions, expired bindings, disabled users. Explicit deny (! prefix) always beats allow; wildcards match within one segment only. Precedence rules live in internal/domain/resolve.go and have a dedicated test matrix — extend the matrix when changing rules.
  • Every authz-relevant mutation runs in one transaction that also: writes an audit row, writes an outbox row, and bumps perm_ver of every affected user. Skipping any of the three silently breaks SDK caches.
  • Audit log is append-only. No UPDATE/DELETE anywhere, ever.
  • Admin plane dogfoods the permission engine. Every admin route is gated by an iam:* permission; new admin routes must register their key and check it.
  • Revocation semantics: disable/revoke propagates within min(access_token_TTL, cache_TTL), narrowed to seconds by events; /authz/check is always immediate. Document behavior honestly against this, never promise instant revocation.
  • Trust boundary: the service binds loopback/leased port and trusts X-Forwarded-For/X-Real-IP only from loopback or configured TEAMUSERS_TRUSTED_PROXIES. Never widen this by default.
  • Outbox topics are a contract with SDK subscribers: perm.changed, user.disabled, role.updated, key.rotated, user.created, user.updated, user.deleted, team.created, team.updated (-> iam.* subjects) plus notify.* and audit.forward (-> HMAC-signed HTTP). Consumers are idempotent by event id; keep payloads additive-only.

Rules for changes

  1. New/changed route -> register handler AND add/update its Operation metadata in internal/httpapi/doc.go. apidocs/go/collect.go enforces bidirectional pairing: go run ./cmd/genspec fails if a walked route lacks metadata or metadata matches no route. Never hand-edit docs/public/openapi.yaml or docs/api/reference/ (generated).
  2. Schema change -> new migrations/NNNN_name.sql (next number, Up and Down), embedded via migrations/embed.go. Migrations run at startup behind an advisory lock; keep them idempotent-safe.
  3. New POST endpoints must honor Idempotency-Key (24 h store) and return RFC 9457 problem+json errors.
  4. REST collection pagination MUST follow the canonical REST pagination guide for the request/response contract and exceptions. Preserve the current authorization scope and ordering, and keep internal full-list callers required by authentication and export.
  5. Permission keys are data validated against [!]resource:action:scope at write time; scope is own|team|any|*.
  6. SDK parity: authz semantics, claim shapes, event payloads, or endpoint behavior changes must be mirrored in sdk/go, sdk/ts, sdk/python (each has its own tests/CI publish workflow); version bumps follow the ## SDK versioning rules below.
  7. Secrets: never log credentials/tokens/keys; extend config redaction when adding secret-bearing config. Passwords stay argon2id.
  8. Tests: behavior changes ship with integration coverage in test/ against real Postgres; unit-test pure logic (matcher, expr sandbox, rotation state machine) next to the code.
  9. Events: new authz-affecting mutation -> new/updated outbox topic + relay mapping + SDK handler. notify.* topics are notification-service directives, not fleet events; don't mix the two channels.

SDK versioning

SDK versions live in sdk/ts/package.json, sdk/python/pyproject.toml, and annotated sdk/go/vX.Y.Z git tags for the Go module. The extracted docs tooling follows the same scheme in its own namespaces: the apidocs/go module ships via annotated apidocs/go/vX.Y.Z tags (the root go.mod uses a replace to ./apidocs/go, so tag versions matter only for external consumers) and the apidocs/vitepress npm package teamusers-apidocs-vitepress versions in apidocs/vitepress/package.json with publish automation in .github/workflows/apidocs_publish_npm.yml. Bumps follow semver strictly (breaking -> major, additive -> minor, fix -> patch). Unless the user explicitly requests a version bump, only advance the -preview.N pre-release suffix (e.g. 0.3.0-preview.1 -> 0.3.0-preview.2); previews never hang off an already-released stable version. When the current version is a stable release (no suffix), the first preview of the next release follows semver against the pending changes: additive -> x.y.z to x.(y+1).0-preview.1, breaking -> (x+1).0.0-preview.1. User-invisible changes and small bug fixes do NOT open a new preview cycle: bump PATCH directly (x.y.z -> x.y.(z+1)); on an existing preview line they keep advancing -preview.N. ANY major/minor/patch movement — including a PATCH bump for a small fix — MUST be confirmed with the user before the final commit; it is never taken unilaterally.

Configuration surface

Env + flags, precedence: CLI > TEAMUSERS_* > PORT/HOST (Nekostick injected) > defaults. Current env vars: TEAMUSERS_CONNECTION_STRING, TEAMUSERS_DB_SCHEMA (optional; when set to a valid identifier the schema is created if missing, every connection uses it as search_path, and the goose version table lives inside it — needs database-level CREATE privilege the first time), TEAMUSERS_LISTEN_ADDRESS, TEAMUSERS_LISTEN_PORT, TEAMUSERS_KEY_DIR, TEAMUSERS_NATS_URL, TEAMUSERS_NODE_ID, TEAMUSERS_NOTIFICATION_ENDPOINTS, TEAMUSERS_NOTIFICATION_SECRET, TEAMUSERS_REGISTRATION_MODE, TEAMUSERS_TOKEN_AUDIENCE, TEAMUSERS_TRUSTED_PROXIES, TEAMUSERS_WEBAUTHN_ORIGIN, TEAMUSERS_LOCKOUT_DURATION, TEAMUSERS_LOG_LEVEL, TEAMUSERS_ACCESS_TOKEN_TTL, TEAMUSERS_REFRESH_TOKEN_TTL, TEAMUSERS_SESSION_FAMILY_TTL (defaults 10m/720h/2160h; family >= refresh), TEAMUSERS_AUDIT_RETENTION_DAYS (default 0 = keep forever), TEAMUSERS_AUDIT_FORWARD_ENDPOINTS, TEAMUSERS_AUDIT_FORWARD_SECRET, TEAMUSERS_LOGIN_ACTIVITY_RETENTION_DAYS (default 90), TEAMUSERS_PWNED_PASSWORDS_ENABLED (HIBP breach screening, default off), TEAMUSERS_OIDC_ISSUER, TEAMUSERS_OIDC_CLIENT_ID, TEAMUSERS_OIDC_CLIENT_SECRET, TEAMUSERS_OIDC_REDIRECT_URL (OIDC off when issuer unset), TEAMUSERS_OIDC_TRUST_UPSTREAM_MFA, TEAMUSERS_OIDC_MFA_ACR_VALUES, TEAMUSERS_SCIM_BEARER_TOKEN (SCIM off when empty), TEAMUSERS_SCIM_RATE_LIMIT (SCIM requests per second and burst as rps/burst; a plain number sets burst to twice the rate; default 10/30, 0 disables).

Signing-key rotation: POST /keys/rotate (admin plane, iam:keys:any). Retired keys stay in JWKS until rotated_at + 2*max(access, mfa, password-change TTL); multi-replica procedure is one POST + rolling restart (see docs/guide/operations.md).

Planning docs

PLAN.md records unfinished work only (backlog with evidence pointers). When an item ships, delete it from PLAN.md and document the shipped behavior in docs/ if user-visible. Current design and architecture live in this file and docs/ — do not re-add design prose to PLAN.md.

Deployment

Static binary (CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build ./cmd/teamusers), no Dockerfile/systemd: Nekostick owns the process lifecycle, injects HOST/PORT, supervises GET /healthz; /readyz gates on DB writability; SIGTERM drains in 10 s. Nekostick service Environment is plaintext in its PG config — treat Host Config API read access as high-sensitivity.

Release assets are consumed by svchost's release source and MUST follow the svchost publishing contract: 4-segment ZIP names teamusers_<version>_<platform>_<arch>.zip (e.g. teamusers_1.2.3_linux_x64.zip; the version segment strips the tag's v prefix — svchost compares SemVer identity, platform is linux/windows/macos/freebsd, arch is x64/arm64/arm/x86), with the entry binary named teamusers at the ZIP root. .github/workflows/release.yml enforces this; update it when the contract changes. .github/workflows/release.yml builds linux/windows/macos × x64/arm64 (Windows entry is teamusers.exe); freebsd is not built.