Shared libraries
Every Go service depends on one shared module, github.com/Atelier-Epita/intranet/pkg (directory pkg/,
Go 1.27). It holds the cross-cutting plumbing: configuration, HTTP bootstrap, identity, authorization
client, event sourcing, outbox, Kafka, MongoDB, S3, encryption and observability. Services keep only their
domain code. Run go doc -all ./<package> from pkg/ for the full API.
Overview
| Package | Purpose | Used by |
|---|---|---|
arn | Parse and match resource identifiers (atl:...) | audit, authz, events, files, inventory, members |
audit | Audit record type (no PII) and topic | all Go services |
authzclient | Ask the authz service for decisions | audit, events, files, gateway, inventory, members |
catalog | Declaration of every platform permission | authz, files |
cloudevent | CloudEvents 1.0 JSON envelope | authz, events, files, gateway, inventory, members |
config | Env var loader and common settings | all Go services |
cryptox | Envelope encryption, per-subject keys, crypto-shredding | members (borrowing in progress) |
cryptox/barbican | Load the KEK from OpenStack Barbican | members |
csvx | Typed CSV import/export | inventory, members (borrowing in progress) |
eventstore | Lightweight event sourcing on MongoDB | authz, events, inventory, members |
gen/authz/v1 (+ authzv1connect) | Generated protobuf / Connect code of the authz RPC | authz, gateway (and indirectly authzclient) |
httpx | Gin server bootstrap, middlewares, problem rendering | all Go services |
ids | ULID generation | all Go services |
kafkax (+ kafkatest) | Kafka producer/consumer on franz-go | all Go services |
lease | MongoDB lease for single-replica background jobs | events, files, inventory, members |
logging | JSON slog loggers with trace context | all Go services |
mongox (+ mongotest) | MongoDB driver conventions and helpers | authz, events, files, inventory, members |
outbox | Transactional outbox and relay to Kafka | authz, events, files, gateway, inventory, members |
pagination | Opaque cursor pagination | audit, authz, events, files, inventory, members |
principal | Signed principal token between gateway and services | all Go services |
problem | RFC 9457 problem details errors | all Go services |
s3x | S3 client with presigned URLs | files (borrowing in progress) |
telemetry | OpenTelemetry tracing and Prometheus metrics setup | all Go services |
"All Go services" means audit, authz, events, files, gateway, inventory and members. borrowing is being
finished (it already uses the same libraries plus cryptox and s3x); vision is a Python service.
Configuration and bootstrap
config
Loads service configuration from environment variables only. A Loader reads typed values and
accumulates parsing errors, so a service reports every bad variable at once through Err().
| API | Notes |
|---|---|
(*Loader).String(key, def string) string | Value or default. |
(*Loader).Require(key string) string | Records an error if missing. |
Int, Bool, Duration, List | Typed variants with a default; List splits on commas. |
(*Loader).Err() error | Every error recorded so far. |
LoadCommon(l *Loader, service string) Common | Settings shared by every service. |
(Common).IsProduction() bool | Env == "production". |
Env vars read by LoadCommon (see environment variables):
| Variable | Default | Field |
|---|---|---|
APP_ENV | production | Env — must be development, test or production |
HTTP_ADDR | :8080 | HTTPAddr |
METRICS_ADDR | :9090 | MetricsAddr |
LOG_LEVEL | info | LogLevel |
OTEL_EXPORTER_OTLP_ENDPOINT | empty | OTLPEndpoint |
httpx
Bootstraps Gin HTTP servers with the project middlewares. New returns a server with recovery, request ID,
tracing, access log and problem middlewares, plus /healthz (liveness) and /readyz (runs the registered
checks). Run serves until the context is cancelled and shuts down gracefully; metrics are served on
MetricsAddr when set.
| API | Notes |
|---|---|
New(cfg config.Common, log *slog.Logger) *Server | Server.Engine is the *gin.Engine. |
(*Server).AddCheck(name string, fn Check) | Readiness check, Check is func(ctx) error. |
(*Server).TrustProxies(cidrs []string) error | CIDRs allowed to set X-Forwarded-For. |
(*Server).Run(ctx) error | Serve, then graceful shutdown. |
Fail(c *gin.Context, err error) | Attach an error, set its status and abort; Problems renders it. |
BindJSON(c, dst) bool, BindQuery(c, dst) bool | Decode and validate, failing the request on error. |
RequestID(), Problems(log) | Middlewares (installed by New). Header X-Request-Id. |
logging
Builds JSON structured slog loggers enriched with trace context.
New(service, level string) *slog.Logger writes to stdout; NewWithWriter(w, service, level) writes to w.
telemetry
Configures OpenTelemetry tracing and Prometheus metrics.
Setup(ctx, cfg config.Common) (func(context.Context) error, error) installs the global tracer and meter
providers and returns a shutdown function. Traces are exported over OTLP only when
OTEL_EXPORTER_OTLP_ENDPOINT is set. See observability.
Typical main wiring, taken from services/members/cmd/members/main.go (shortened):
cfg, err := config.Load() // service config built on pkg/config
log := logging.New(cfg.Service, cfg.LogLevel)
shutdown, err := telemetry.Setup(ctx, cfg.Common)
defer func() { _ = shutdown(context.Background()) }()
client, db, err := mongox.Connect(ctx, mongox.Config{URI: cfg.MongoURI, Database: cfg.MongoDatabase})
verifier, err := principal.NewVerifier(cfg.PrincipalKey)
producer, err := kafkax.NewProducer(kafkax.Config{Brokers: cfg.KafkaBrokers, ClientID: cfg.Service})
srv := httpx.New(cfg.Common, log)
srv.AddCheck("mongo", mongox.Ping(client))
srv.AddCheck("kafka", producer.Ping)
srv.Engine.Use(principal.Middleware(verifier))
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error { return srv.Run(ctx) })
g.Go(func() error { return outbox.NewRelay(db, producer, log).Run(ctx) })
Identity and authorization
principal
Carries the authenticated identity between the gateway and services. The gateway authenticates the caller
and forwards a short-lived Ed25519-signed token (lifetime TokenTTL = 2 minutes) in the X-Atl-Principal
header. Services verify it and never trust any other client-provided identity header.
See identity.
| API | Notes |
|---|---|
Principal | ID, Kind, OwnerKind, OwnerID, AdminMode, ACR, AuthTime, IP, RequestID. |
Kind | anonymous, user, api_key, service. OwnerKind: user, project. |
(Principal).UserID() string | Human user behind the principal (owner for user API keys). |
(Principal).SteppedUp(acr, maxAge, now) bool | Session validated with that ACR within maxAge. |
NewSigner(b64), (*Signer).Sign(p) | Gateway side; base64 Ed25519 seed or private key. |
NewVerifier(b64), (*Verifier).Verify(token) | Service side; base64 Ed25519 public key. |
Middleware(v *Verifier) gin.HandlerFunc | No header means anonymous; an invalid token is rejected. |
RequireAuth() gin.HandlerFunc | Rejects anonymous requests. |
FromContext(ctx) Principal, WithContext(ctx, p) | Anonymous when absent. |
TokenFromContext(ctx), WithToken(ctx, token) | Raw token, to forward it to internal services. |
arn
Parses and matches resource identifiers of the form atl:<service>:<site|*>:<type>/<id>[/<type>/<id>...][/*].
A pattern may use * for the site, as the last id (every resource of that type) or as a trailing segment
(the resource and all its sub-resources).
| API | Notes |
|---|---|
ARN | Service, Site, Path []Segment, Descendants (trailing /*). |
New(service, site string, typeIDs ...string) ARN | Alternating type/id values. |
Parse(s string) (ARN, error) | Returns ErrInvalid on malformed input. |
(ARN).Matches(r ARN) bool | Whether pattern a covers concrete resource r. |
(ARN).IsPattern(), Leaf(), String() |
catalog
Declares every permission of the platform (in permissions.go). Names follow
<service>.<resource>.<action>. The authz service generates the Permify schema from this catalogue; roles are
dynamic and grant catalogue permissions on resource nodes. See authorization.
| API | Notes |
|---|---|
Permission | Name, Scope (global or project), Elevated (admin mode only), Sensitive (recent passkey step-up). |
All() []Permission, Get(name) (Permission, bool) | Sorted by name. |
ResourceTypes(), ProjectResourceTypes() | Distinct resource types (the latter: with at least one project permission). |
(Permission).Service(), ResourceType(), Action(), Relation() | ResourceType is <service>_<resource> (Permify entity), Relation is svc_res_action. |
authzclient
The client services use to ask the authz service for decisions over its internal Connect RPC (see authz RPC).
| API | Notes |
|---|---|
New(baseURL string) *Client | NewWithRPC(rpc) wraps an existing client (tests). |
(*Client).Check(ctx, permission string, target arn.ARN, parents ...arn.ARN) error | nil when allowed, otherwise a problem describing the denial. |
(*Client).Allowed(...) (bool, error) | Check as a boolean; dependency errors are returned. |
(*Client).Lookup(ctx, permission) (Scope, error) | Scope on which the principal holds the permission. |
Scope | All, Sites, Projects, IDs; Empty() when nothing is granted. |
From services/members/internal/api/api.go:
func (h *Handler) check(c *gin.Context, perm string, target arn.ARN, parents ...arn.ARN) bool {
if err := h.Authz.Check(c.Request.Context(), perm, target, parents...); err != nil {
httpx.Fail(c, err)
return false
}
return true
}
gen/authz/v1
Generated protobuf messages (authzv1) and Connect client/handler (authzv1connect) from
proto/authz/v1/authz.proto: AuthzService with Check, CheckMany, LookupResources,
EffectivePermissions and AuthenticateAPIKey. Do not edit; regenerate from the proto.
Events, audit and messaging
eventstore
Lightweight event sourcing on MongoDB. A commit atomically appends events, updates the aggregate current-state document (the snapshot used by queries) and enqueues events and audit records in the outbox. See CQRS.
| API | Notes |
|---|---|
New(client *mongo.Client, db *mongo.Database, service string) *Store | Events go to the events collection. |
(*Store).EnsureIndexes(ctx) error | |
(*Store).Save(ctx, c Commit) (int64, error) | Returns the new version; ErrConcurrency if the aggregate changed. |
(*Store).Load(ctx, aggregateID string, after int64) ([]Event, error) | Events with version greater than after. |
Commit | AggregateType, AggregateID, Site, ExpectedVersion, Changes, State, StateColl, Audit, Additional. |
Change | Type (<service>.<aggregate>.<event>) and Data. |
Event, Meta, (Event).Decode(dst) | Stored event and its actor metadata. |
NewID() string | New aggregate identifier. |
State must not contain a version field; pass nil to skip the state update. From
services/members/internal/member/service.go:
v, err := s.Store.Events.Save(ctx, eventstore.Commit{
AggregateType: "member", AggregateID: m.ID, Site: site, ExpectedVersion: expected, Changes: changes,
State: m, StateColl: s.Store.Members,
Audit: []audit.Record{store.Record(ctx, "members.member."+action, ARN(m.ID).String())},
})
if errors.Is(err, eventstore.ErrConcurrency) {
return problem.Conflict("concurrent_modification", "member was modified concurrently, retry")
}
outbox
Transactional outbox on MongoDB. Messages are written in the same transaction as the business data (the
outbox collection), then a single leader Relay per service publishes them to Kafka in insertion order.
See Kafka.
| API | Notes |
|---|---|
New(db) *Outbox, (*Outbox).Add(ctx, msgs ...Message) error | Call Add with a transaction context. |
Message | ID, Topic, Key, Value, CreatedAt. |
FromEvent(e cloudevent.Event) | Keyed by the event subject. |
FromAudit(r audit.Record) | Keyed by the actor. |
TopicOf(eventType string) string | members.member.created gives members.member.v1. |
Publisher | Publish(ctx, msgs) error, returns once all are acknowledged (kafkax.Producer implements it). |
NewRelay(db, pub, log) *Relay | Run(ctx) publishes while holding a lease; Flush(ctx) sends one batch. |
Relay defaults: Interval 250 ms, Lease 15 s, batches of 200 messages.
cloudevent
The CloudEvents 1.0 structured-mode JSON envelope used on Kafka. Extension attributes carry the actor
(atlactorkind, atlactorid), the site (atlsite), the aggregate version (atlversion) and the W3C
traceparent.
| API | Notes |
|---|---|
New(ctx, source, typ, subject string, data any) (Event, error) | Fills principal and trace from ctx; typ is <service>.<aggregate>.<event>. |
(Event).Decode(dst any) error | Unmarshal Data. |
(Event).Context(ctx) context.Context | ctx enriched with the event trace parent. |
audit
Defines audit records. Records never contain PII, only identifiers (Refs holds IDs or ARNs only, never
names or free text). Every record goes to the audit.records.v1 topic (audit.Topic).
| API | Notes |
|---|---|
Record | ID, Time, Service, Action, Resource, Outcome, actor, owner, AdminMode, IP, RequestID, TraceID, Refs. |
Outcome | success, denied, failure. |
New(ctx, service, action, resource string, outcome Outcome) Record | Principal and trace taken from ctx. |
(Record).WithRef(key, id string) Record | Add a related identifier. |
kafkax
Wraps franz-go for publishing and consuming project topics. Brokers are passed in Config; the package
reads no env var itself (services load their brokers list through config).
| API | Notes |
|---|---|
Config | Brokers []string, ClientID string. |
NewProducer(cfg) (*Producer, error) | Acks from all in-sync replicas. Publish, Ping, Close. |
NewConsumer(cfg, group string, topics []string, h Handler, log) (*Consumer, error) | Commits after success. |
Handler | func(ctx, rec *kgo.Record) error; an error retries the record. |
Consumer.MaxRetries, Consumer.Backoff | Defaults 5 and 500 ms; then the record goes to <topic>.dlq. |
kafkax/kafkatest.Start(t testing.TB) []string starts a single-node KRaft broker (apache/kafka:4.3.1) for
integration tests, or uses KAFKA_TEST_BROKERS; it skips in -short mode.
Storage
mongox
Wraps the MongoDB driver with the project conventions.
| API | Notes |
|---|---|
Connect(ctx, cfg Config) (*mongo.Client, *mongo.Database, error) | Config: URI, Database. Majority writes, secondary-preferred reads. |
Primary(c *mongo.Collection) *mongo.Collection | Reads from the primary (read-after-write paths). |
WithTransaction(ctx, client, fn) error | Retries transient errors. |
EnsureIndexes(ctx, c, models...) error | |
AfterID(filter, after string) bson.D | Ascending cursor pagination on _id. |
NotDeleted(filter bson.D) bson.D | Soft-delete exclusion (deleted_at is null). |
IsDuplicate(err), IsNotFound(err) | Error classification. |
Ping(client) func(context.Context) error | Readiness check for httpx. |
mongox/mongotest.Start(t testing.TB) (*mongo.Client, *mongo.Database) starts a single-node replica set
(ghcr.io/hadkaz/psmdb-no-avx:8.0.38-16) for integration tests, or uses MONGO_TEST_URI, and returns a fresh database; it skips in
-short mode. mongotest.URI(t) returns the connection string of that shared instance (for code that opens its
own client).
lease
MongoDB-backed lease (collection locks) so that only one replica runs a background job.
| API | Notes |
|---|---|
New(db, name string, ttl time.Duration) *Lease | |
(*Lease).Acquire(ctx) (bool, error) | Takes or renews; reports whether this process holds it. |
(*Lease).Release(ctx) error | Gives it up if held. |
RunEvery(ctx, l *Lease, interval, log, job) | Runs job every interval while holding the lease; errors are logged, not fatal. |
lease.RunEvery(ctx, lease.New(db, "members-purge", 2*cfg.PurgeInterval), cfg.PurgeInterval, log,
func(ctx context.Context) error {
_, err := mem.PurgeDue(ctx)
return err
})
s3x
Wraps the S3 API (Ceph RGW in production, Garage locally) with presigned URLs.
| API | Notes |
|---|---|
LoadConfig(l *config.Loader) Config, New(cfg) *Client | |
Put(ctx, bucket, key, contentType string, body io.Reader, size int64) error | |
Get(ctx, bucket, key) (io.ReadCloser, error) | ErrNotFound when missing; caller closes the body. |
Delete(ctx, bucket, key) error | No error if missing. |
PresignGet(ctx, bucket, key, ttl), PresignPut(ctx, bucket, key, contentType, ttl) | Short-lived URLs; PUT is bound to a content type. |
Ping(bucket) func(context.Context) error | Readiness check. |
| Variable | Default |
|---|---|
S3_ENDPOINT | required |
S3_REGION | garage |
S3_ACCESS_KEY, S3_SECRET_KEY | required |
S3_PUBLIC_ENDPOINT | S3_ENDPOINT — used to sign URLs handed to browsers |
cryptox
Envelope encryption with per-subject data keys. Each subject (user, external person, ...) gets its own data
encryption key (DEK), wrapped by a key encryption key (KEK) and stored in the data_keys collection.
Deleting the wrapped DEK makes the subject data unreadable (crypto-shredding). See
encryption.
| API | Notes |
|---|---|
KEK | Interface: ID(), Wrap(dek), Unwrap(wrapped). |
NewAESKEK(key []byte), NewAESKEKFromBase64(s) | 256-bit AES-GCM KEK in memory. |
NewKeyring(db, kek) *Keyring | |
Seal(ctx, subject, plaintext), Open(ctx, subject, sealed) | Creates the subject key on first seal. |
SealString, OpenString | Empty strings stay empty. |
Shred(ctx, subject) error | Destroys the subject key; later reads fail with ErrShredded. |
LoadKEKSettings(l *config.Loader) KEKSettings | Reads the CRYPTO_* variables below. |
| Variable | When | Notes |
|---|---|---|
CRYPTO_KEK_SOURCE | always | env (default) or barbican |
CRYPTO_KEK | source env | base64 32-byte key, required |
OS_AUTH_URL, OS_APPLICATION_CREDENTIAL_ID, OS_APPLICATION_CREDENTIAL_SECRET | source barbican | required |
OS_REGION_NAME | source barbican | optional |
CRYPTO_KEK_BARBICAN_SECRET_ID | source barbican | required |
cryptox/barbican loads the KEK from OpenStack Barbican with Keystone application credentials:
LoadKEK(ctx, cfg Config) (*cryptox.AESKEK, error) fetches the 32-byte payload, and
Load(ctx, s cryptox.KEKSettings) picks env or barbican from the settings.
API helpers
problem
RFC 9457 problem details errors, rendered as application/problem+json by httpx. Problem carries
Type, Title, Status, Code (machine-readable), Detail, Instance and Fields.
| Constructor | Status |
|---|---|
BadRequest(code, detail) | 400 |
Validation(fields map[string]string) | 422, code validation_failed |
Unauthorized(detail) | 401 |
Forbidden(detail) | 403 |
NotFound(code, detail) | 404 |
Conflict(code, detail) | 409 |
PayloadTooLarge(detail) | 413 |
UnsupportedMediaType(detail) | 415 |
TooManyRequests() | 429 |
Internal(err) | 500, cause kept for logs only |
BadGateway(detail), Unavailable(detail), GatewayTimeout(detail) | 502, 503, 504 |
From(err) converts any error, (*Problem).Wrap(err) attaches an internal cause never exposed to clients and
WithCode(code) returns a copy with another code.
pagination
Opaque cursor-based pagination (every list endpoint uses it). DefaultLimit is 25, MaxLimit 200.
| API | Notes |
|---|---|
Parse(limit, cursor string) (Params, error) | Validates raw query values; Params has Limit and After *Cursor. |
Cursor | ID and optional Key (sort value when not sorting on the ID); Encode(), Decode(s). |
NewPage[T](items []T, limit int, cursorOf func(T) Cursor) Page[T] | Pass up to limit+1 items; the extra one signals a next page. |
Page[T] | JSON items and next_cursor. |
From services/files/internal/file/query.go:
filter := mongox.NotDeleted(bson.D{{Key: "owner", Value: a.Owner.String()}})
items, err := store.Find[File](ctx, s.Store.Files, filter, after, p.Limit+1)
// ...
return pagination.NewPage(items, p.Limit, func(f File) pagination.Cursor { return pagination.Cursor{ID: f.ID} }), nil
ids
Sortable unique identifiers (ULID, used for every non-user ID). New() is strictly increasing within the
process, NewAt(t) builds one for a given time and Valid(s) checks the format.
csvx
Reads and writes CSV files for bulk import and export. Columns are declared once per type and drive both
directions. Reading accepts , or ; separators and a UTF-8 BOM; writing adds a BOM and neutralises formula
injection. See CSV formats.
| API | Notes |
|---|---|
Column[T] | Name, Required, Get func(T) string (export, nil = import-only), Set func(*T, string) error (import, nil = export-only). |
Read[T](r, cols, maxRows) ([]T, []LineError, error) | Line errors do not stop parsing; invalid rows are skipped. |
ReadRows[T](...) | Same, keeping each row's 1-based line number (Row[T]). |
Write[T](w, cols, rows) error | Header plus one line per row. |
LineError | Line, Column, Message; ErrTooManyRows beyond maxRows. |