Aller au contenu principal

files

Status: implemented (cmd/files, tests). Runs in the apps profile of docker-compose.yml on port 8084 (S3 = Garage, presigned URLs signed for http://localhost:3900) and is reached through the gateway thanks to the compose GATEWAY_ROUTES entry /v1/files; the gateway built-in default routes do not include it.

Role: generic attachment storage for every module. A file belongs to an owner resource ARN (e.g. atl:inventory:paris:item/01J…); the service sniffs, converts or sanitises the upload, stores its variants in S3, keeps the metadata in MongoDB and hands out short-lived presigned download URLs.

Limits: no business meaning of attachments (owners reference file IDs themselves) and no identity documents (borrowing stores those encrypted in its own bucket, see borrowing). No antivirus scan. Files are not encrypted at application level.

Access control​

Permissions are derived from the owner ARN, then checked through authz (deny by default, see authorization):

OperationPermission on the owner
list, metadata, download URL<service>.<type>.read (projects: projects.file.read)
upload, delete<service>.<type>.update (projects: projects.file.write)

<service> and <type> come from the owner ARN service and leaf type. A permission absent from the catalogue answers 403 (files cannot be attached to this resource). Owner rules: valid ARN, not a pattern, not a files ARN, ID segments [A-Za-z0-9._-]{1,128}. The owner site atl:settings:<site>:site/<site> is always added as a parent; up to 4 extra parents are accepted, only that site or a project of the same site (atl:projects:<site>:project/<id>). Parents are stored with the file and reused for later checks.

Delegated authorization​

Some owners carry business rules authz cannot express (a borrower on their own sheet, the reporter of an inventory issue). When the derived check is denied (403; authz errors and anonymous callers are never delegated) and the owner service has a delegate in FILES_DELEGATES, files calls POST <delegate>/internal/v1/attachments/authorize with {"owner": "<ARN>", "parents": [...], "action": "read" | "write"} and the caller X-Atl-Principal token (timeout FILES_DELEGATE_TIMEOUT, no caching):

Delegate answerFiles answer
204allowed
401, 403, 404403 (the original problem)
anything else, timeout503
DelegateOwnerRules
borrowingatl:borrowing:<site>:sheet/<id>read: sheet read rule; write: member borrower / creator while the sheet is not returned or cancelled, else borrowing.sheet.update
inventoryatl:inventory:<site>:issue/<id>read: reporter or inventory.item.read on the item; write: reporter, inventory.issue.handle, or inventory.issue.report while open

/internal/... routes require a principal token and are never routed by the gateway (it only proxies /v1/...).

Upload pipeline​

  1. Body limits (in memory, no temporary files): body up to FILES_MAX_BYTES + 64 KiB, at most 16 parts, form fields up to 1 KiB, exactly one file part; unknown fields answer 422.

  2. Validation: owner and parents (above), purpose matches ^[a-z][a-z0-9_]{0,31}$, permission check, non-empty file within FILES_MAX_BYTES.

  3. Detection from the bytes (the client content type is ignored); the extension is only used for formats without a reliable magic number:

    FormatDetectionStored as
    jpeg, png, gif, webp, heicmagic number / ftyp brandwebp original + webp thumb
    svgXML whose root element is svgsanitised svg (thumb serves the original)
    pdf%PDF-as is
    csv, txtextension + valid UTF-8 plain text (no NUL, sniffed text/plain)as is
    pes, dstextension + #PES / LA: prefixas is
    jef, expextension + opaque binaryas is

    Anything else answers 415.

  4. Conversion (media.Process, at most FILES_CONVERT_WORKERS at once): raster images are rejected above FILES_MAX_PIXELS before decoding (413), decoded (decoder panics become 422), scaled so the longest side is at most FILES_MAX_IMAGE_DIMENSION (thumbnail: FILES_THUMB_DIMENSION), JPEG EXIF orientation applied, then re-encoded as lossy webp (quality 82), which drops EXIF and every other metadata. GIF keeps its first frame only.

  5. SVG sanitising: re-serialised with an element and attribute allow-list; script, style elements, foreignObject, a, animations, event handlers, comments, DOCTYPE / entities are dropped; values with javascript:, expression(, @import... or url() pointing outside the document are removed; image only keeps inline data:image/(png|jpeg|gif|webp);base64 hrefs, other hrefs must be # fragments. Depth is capped at 128.

  6. Storage: every variant is put in S3 with its content type and Content-Disposition (images inline, everything else attachment, sanitised name). Then one Mongo transaction inserts the metadata, the audit record and the files.file.uploaded event in the outbox. If S3 or Mongo fails, the uploaded objects are removed (leftovers are logged).

The stored name is sanitised (no path, control or reserved characters, max 120 runes) and its extension is the stored format (.webp for converted images). size, content_type and sha256 describe the stored original.

Downloads, deletion and purge​

  • GET /v1/files/{id}/url?variant=original|thumb presigns a GET for FILES_URL_TTL against S3_PUBLIC_ENDPOINT, forcing content type, disposition and Cache-Control: private, max-age=300; the JSON response is no-store. Non-image files have no thumbnail (404 variant_not_found).
  • DELETE /v1/files/{id} soft-deletes (deleted_at, purge_at = now + FILES_PURGE_DELAY); deleted files answer 404.
  • Owner erasure: on members.member.erased, every live file owned by atl:members:*:member/<id> is soft-deleted (batches of 200, service principal, no permission check).
  • Purge job: every FILES_PURGE_INTERVAL, a single replica (lease files-purge in locks) deletes the S3 objects of files whose purge_at has passed, then their document, with a files.file.purge audit record.

Dependencies​

  • Services: authz (Check through authzclient); delegates from FILES_DELEGATES (borrowing, inventory).
  • Infrastructure: MongoDB (replica set, transactions), Kafka, S3 (Garage locally).
  • Libraries: authzclient, httpx, kafkax, outbox, lease, mongox, s3x (config only), audit, cloudevent, catalog, arn, ids, pagination, principal, problem, config, logging, telemetry (see libraries).

Container builds​

The shared services/Dockerfile and make build use CGO_ENABLED=0 go build -tags nodynamic. This selects the bundled HEIC (WASM) and WebP (transpiled Go) codecs. Without nodynamic, their optional purego bindings introduce a dynamic loader dependency even with CGO disabled. An Alpine-built binary then fails in the distroless static image with exec /app: no such file or directory because /lib/ld-musl-…so.1 is missing, although /app exists.

After updating the build configuration, rebuild and recreate the service:

docker compose build files
docker compose up -d --no-deps --force-recreate files
docker compose logs --tail=50 files

Inputs and outputs​

KindNameNotes
HTTPPOST/GET /v1/files, GET/DELETE /v1/files/{id}, GET /v1/files/{id}/urlAPI reference; authenticated principals only; list requires owner (optional parents, max 4), cursor paginated
RPC outauthz.v1.AuthzService/Checkpermission derived from the owner
HTTP outPOST <delegate>/internal/v1/attachments/authorizedelegated authorization (see above)
Kafka outfiles.file.v1files.file.uploaded (id, owner, site, content type, size, purpose, variant names; no file name), files.file.deleted (id, owner, site, purge time); key = file ID, CloudEvents site set except for global owners
Kafka outaudit.records.v1files.file.upload, files.file.delete, files.file.purge (resource atl:files:<site>:file/<id>, ref owner)
Kafka inmembers.member.v1members.member.erased only, other types ignored (group files)
Kafka outmembers.member.v1.dlqerasure events still failing after 5 attempts

Data​

MongoDB database files:

CollectionContentIndexes
filesmetadata: owner, parents, site, name, content type, size, SHA-256, variants (name, key, type, size, width, height), purpose, uploaded by, created / deleted / purge times(owner, deleted_at, _id); purge_at (partial, dates only)
outboxpending events and audit recordssee Kafka
lockspurge job lease

S3 bucket FILES_BUCKET (default atelier-files, private), object keys <service>/<site>/<type>/<owner id>/<file id>/<variant>, where <site> is global for owners with a * site and <variant> is original or thumb.

Not implemented yet​

  • Erasure / deletion events of other owners (only members.member.erased is consumed); deleting an owner resource in another service leaves its files in place.
  • No antivirus scan, no application-level encryption (see the limits above).
  • No web screen uploads or displays files yet.

Configuration​

VariableDefaultDescription
HTTP_ADDR, METRICS_ADDR:8084, :9184Listen addresses
PRINCIPAL_PUBLIC_KEYrequiredBase64 Ed25519 public key verifying X-Atl-Principal
AUTHZ_URLhttp://localhost:8081authz ConnectRPC endpoint
KAFKA_BROKERSlocalhost:19092Outbox relay and consumer
MONGO_URI, MONGO_DATABASEmongodb://localhost:27017/?directConnection=true, filesMongoDB
S3_ENDPOINT, S3_ACCESS_KEY, S3_SECRET_KEYrequiredS3 API
S3_REGIONgarageS3 region
S3_PUBLIC_ENDPOINTS3_ENDPOINTHost used to sign URLs handed to browsers
FILES_BUCKETatelier-filesBucket
FILES_MAX_BYTES20971520Max upload size (20 MiB)
FILES_MAX_IMAGE_DIMENSION, FILES_THUMB_DIMENSION2560, 320Longest side of stored image / thumbnail (thumb not larger than max)
FILES_MAX_PIXELS50000000Decompression bomb guard
FILES_CONVERT_WORKERS2Concurrent conversions
FILES_URL_TTL5mPresigned URL lifetime (1 s to 7 days)
FILES_PURGE_DELAY24hSoft delete to purge delay
FILES_PURGE_INTERVAL15mPurge job period
FILES_DELEGATESemptyservice=url,... delegates of attachment authorization (compose: borrowing=http://borrowing:8087,inventory=http://inventory:8085)
FILES_DELEGATE_TIMEOUT3sDelegate call timeout (up to 1 m)

Plus the common APP_ENV, LOG_LEVEL, OTEL_EXPORTER_OTLP_ENDPOINT (see environment variables).