Aller au contenu principal

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​

PackagePurposeUsed by
arnParse and match resource identifiers (atl:...)audit, authz, events, files, inventory, members
auditAudit record type (no PII) and topicall Go services
authzclientAsk the authz service for decisionsaudit, events, files, gateway, inventory, members
catalogDeclaration of every platform permissionauthz, files
cloudeventCloudEvents 1.0 JSON envelopeauthz, events, files, gateway, inventory, members
configEnv var loader and common settingsall Go services
cryptoxEnvelope encryption, per-subject keys, crypto-shreddingmembers (borrowing in progress)
cryptox/barbicanLoad the KEK from OpenStack Barbicanmembers
csvxTyped CSV import/exportinventory, members (borrowing in progress)
eventstoreLightweight event sourcing on MongoDBauthz, events, inventory, members
gen/authz/v1 (+ authzv1connect)Generated protobuf / Connect code of the authz RPCauthz, gateway (and indirectly authzclient)
httpxGin server bootstrap, middlewares, problem renderingall Go services
idsULID generationall Go services
kafkax (+ kafkatest)Kafka producer/consumer on franz-goall Go services
leaseMongoDB lease for single-replica background jobsevents, files, inventory, members
loggingJSON slog loggers with trace contextall Go services
mongox (+ mongotest)MongoDB driver conventions and helpersauthz, events, files, inventory, members
outboxTransactional outbox and relay to Kafkaauthz, events, files, gateway, inventory, members
paginationOpaque cursor paginationaudit, authz, events, files, inventory, members
principalSigned principal token between gateway and servicesall Go services
problemRFC 9457 problem details errorsall Go services
s3xS3 client with presigned URLsfiles (borrowing in progress)
telemetryOpenTelemetry tracing and Prometheus metrics setupall 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().

APINotes
(*Loader).String(key, def string) stringValue or default.
(*Loader).Require(key string) stringRecords an error if missing.
Int, Bool, Duration, ListTyped variants with a default; List splits on commas.
(*Loader).Err() errorEvery error recorded so far.
LoadCommon(l *Loader, service string) CommonSettings shared by every service.
(Common).IsProduction() boolEnv == "production".

Env vars read by LoadCommon (see environment variables):

VariableDefaultField
APP_ENVproductionEnv — must be development, test or production
HTTP_ADDR:8080HTTPAddr
METRICS_ADDR:9090MetricsAddr
LOG_LEVELinfoLogLevel
OTEL_EXPORTER_OTLP_ENDPOINTemptyOTLPEndpoint

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.

APINotes
New(cfg config.Common, log *slog.Logger) *ServerServer.Engine is the *gin.Engine.
(*Server).AddCheck(name string, fn Check)Readiness check, Check is func(ctx) error.
(*Server).TrustProxies(cidrs []string) errorCIDRs allowed to set X-Forwarded-For.
(*Server).Run(ctx) errorServe, 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) boolDecode 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.

APINotes
PrincipalID, Kind, OwnerKind, OwnerID, AdminMode, ACR, AuthTime, IP, RequestID.
Kindanonymous, user, api_key, service. OwnerKind: user, project.
(Principal).UserID() stringHuman user behind the principal (owner for user API keys).
(Principal).SteppedUp(acr, maxAge, now) boolSession 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.HandlerFuncNo header means anonymous; an invalid token is rejected.
RequireAuth() gin.HandlerFuncRejects 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).

APINotes
ARNService, Site, Path []Segment, Descendants (trailing /*).
New(service, site string, typeIDs ...string) ARNAlternating type/id values.
Parse(s string) (ARN, error)Returns ErrInvalid on malformed input.
(ARN).Matches(r ARN) boolWhether 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.

APINotes
PermissionName, 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).

APINotes
New(baseURL string) *ClientNewWithRPC(rpc) wraps an existing client (tests).
(*Client).Check(ctx, permission string, target arn.ARN, parents ...arn.ARN) errornil 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.
ScopeAll, 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.

APINotes
New(client *mongo.Client, db *mongo.Database, service string) *StoreEvents 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.
CommitAggregateType, AggregateID, Site, ExpectedVersion, Changes, State, StateColl, Audit, Additional.
ChangeType (<service>.<aggregate>.<event>) and Data.
Event, Meta, (Event).Decode(dst)Stored event and its actor metadata.
NewID() stringNew 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.

APINotes
New(db) *Outbox, (*Outbox).Add(ctx, msgs ...Message) errorCall Add with a transaction context.
MessageID, Topic, Key, Value, CreatedAt.
FromEvent(e cloudevent.Event)Keyed by the event subject.
FromAudit(r audit.Record)Keyed by the actor.
TopicOf(eventType string) stringmembers.member.created gives members.member.v1.
PublisherPublish(ctx, msgs) error, returns once all are acknowledged (kafkax.Producer implements it).
NewRelay(db, pub, log) *RelayRun(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.

APINotes
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) errorUnmarshal Data.
(Event).Context(ctx) context.Contextctx 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).

APINotes
RecordID, Time, Service, Action, Resource, Outcome, actor, owner, AdminMode, IP, RequestID, TraceID, Refs.
Outcomesuccess, denied, failure.
New(ctx, service, action, resource string, outcome Outcome) RecordPrincipal and trace taken from ctx.
(Record).WithRef(key, id string) RecordAdd 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).

APINotes
ConfigBrokers []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.
Handlerfunc(ctx, rec *kgo.Record) error; an error retries the record.
Consumer.MaxRetries, Consumer.BackoffDefaults 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.

APINotes
Connect(ctx, cfg Config) (*mongo.Client, *mongo.Database, error)Config: URI, Database. Majority writes, secondary-preferred reads.
Primary(c *mongo.Collection) *mongo.CollectionReads from the primary (read-after-write paths).
WithTransaction(ctx, client, fn) errorRetries transient errors.
EnsureIndexes(ctx, c, models...) error
AfterID(filter, after string) bson.DAscending cursor pagination on _id.
NotDeleted(filter bson.D) bson.DSoft-delete exclusion (deleted_at is null).
IsDuplicate(err), IsNotFound(err)Error classification.
Ping(client) func(context.Context) errorReadiness 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.

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

APINotes
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) errorNo 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) errorReadiness check.
VariableDefault
S3_ENDPOINTrequired
S3_REGIONgarage
S3_ACCESS_KEY, S3_SECRET_KEYrequired
S3_PUBLIC_ENDPOINTS3_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.

APINotes
KEKInterface: 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, OpenStringEmpty strings stay empty.
Shred(ctx, subject) errorDestroys the subject key; later reads fail with ErrShredded.
LoadKEKSettings(l *config.Loader) KEKSettingsReads the CRYPTO_* variables below.
VariableWhenNotes
CRYPTO_KEK_SOURCEalwaysenv (default) or barbican
CRYPTO_KEKsource envbase64 32-byte key, required
OS_AUTH_URL, OS_APPLICATION_CREDENTIAL_ID, OS_APPLICATION_CREDENTIAL_SECRETsource barbicanrequired
OS_REGION_NAMEsource barbicanoptional
CRYPTO_KEK_BARBICAN_SECRET_IDsource barbicanrequired

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.

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

APINotes
Parse(limit, cursor string) (Params, error)Validates raw query values; Params has Limit and After *Cursor.
CursorID 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.

APINotes
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) errorHeader plus one line per row.
LineErrorLine, Column, Message; ErrTooManyRows beyond maxRows.