Profile picture API (/v1/me/avatar)
Lets a signed-in user upload, show, replace and remove their own profile picture (display picture) from the profile settings page. Built for both the Flutter app and the web console.
The image is stored in a private S3 bucket. The API never sends or receives image bytes. You upload straight to S3 with a short-lived signed URL, and you read the picture through another short-lived signed URL.
:::info Deployment status
Committed 2026-11-11 to cse-http-be; not deployed yet. The routes go live
on dev at the next npm run deploy:dev, which updates the cse-http-be-dev-data
stack (new bucket lifecycle rule) and the cse-http-be-dev-api-account stack
(four new routes and the S3 grant). No call has been captured. Every example
below is an illustrative example built from the Zod schemas in
packages/core/src/schemas.ts and the handler packages/api/src/handlers/me-avatar.ts.
None is a real response.
:::
How it works
- Ask for an upload URL:
POST /v1/me/avatar/uploads. - Upload the file to S3:
PUTthe raw bytes toupload.urlwithupload.headers, exactly as given. - Set it as your picture:
PUT /v1/me/avatarwith theuploadId. The server checks the file, saves it, and deletes your previous picture. - Show it: use
avatar.urlfromPUT /v1/me/avatar,GET /v1/me/avatarorGET /v1/me/settings(account.avatar).
Common to all four routes
| Aspect | Value |
|---|---|
| Auth | Cognito JWT (Authorization: Bearer <token>). Never public |
| AuthZ | Self only. Every route acts on the caller's own account (sub from the token). There is no user ID in the path or body, so nobody can read or change another user's picture |
| Headers | Authorization (required). Content-Type: application/json on bodies (else 415). X-Org-Id optional: if sent, it must be one of your ACTIVE memberships, else 403 FORBIDDEN. X-Correlation-Id optional |
| Bodies | Strict: unknown keys → 422 VALIDATION_FAILED. Invalid JSON → 400 MALFORMED_REQUEST |
| Query params | None. Any query parameter → 400 VALIDATION_FAILED |
| Errors | { "error": { "code", "message", "details"?, "requestId" } } |
| Common errors | 401 gateway (bare {"message":"Unauthorized"}) · 401 SESSION_REVOKED · 403 FORBIDDEN · 500 INTERNAL · 503 DEPENDENCY_UNAVAILABLE (also when the bucket is not configured) |
Accepted images: PNG, JPEG or WebP, up to 2 MiB (2,097,152 bytes). SVG is refused (it can carry script). HEIC is refused (browsers cannot show it).
POST /v1/me/avatar/uploads: get an upload URL
Body (CreateAvatarUploadInput):
| Field | Type | Validation |
|---|---|---|
contentType | string | image/png, image/jpeg or image/webp |
sizeBytes | integer | 1 to 2,097,152. Must be the exact byte length of the file you will upload |
Limit: 20 upload URLs per user per hour. Past that → 429 RATE_LIMITED
with Retry-After.
Response 201 (illustrative example):
{
"uploadId": "01JCF6Z3M5W8Z0XK9R4T6V1AA0",
"upload": {
"url": "https://cse-http-be-dev-service-files.s3.us-east-1.amazonaws.com/avatar-pending/<sub>/01JCF6Z3M5W8Z0XK9R4T6V1AA0?X-Amz-Algorithm=…&X-Amz-Signature=…",
"method": "PUT",
"headers": {
"Content-Type": "image/jpeg",
"Content-Length": "48213",
"x-amz-server-side-encryption": "AES256"
},
"expiresAt": "2026-11-11T10:15:00.000Z"
}
}
upload.urlis valid for 15 minutes.Content-Type,Content-Lengthandx-amz-server-side-encryptionare part of the signature. Send all three headers with these exact values, or S3 answers403 SignatureDoesNotMatch. A file of a different size or type is refused by S3 itself.- Nothing changes on your profile yet. An upload that is never set as the picture is deleted automatically after 1 day.
| Status | Code | When |
|---|---|---|
| 201 | — | upload URL created |
| 422 | VALIDATION_FAILED | type not PNG/JPEG/WebP, size out of range, unknown field |
| 429 | RATE_LIMITED | more than 20 per hour |
| 400 / 401 / 403 / 415 / 500 / 503 | common | — |
Upload the file to S3
Send the image bytes as the raw request body (not multipart, not base64)
to upload.url, with upload.headers. S3 answers 200 with an empty body.
This request goes to S3, not to the API, so do not add the
Authorization header.
curl -X PUT "<upload.url>" \
-H "Content-Type: image/jpeg" \
-H "Content-Length: 48213" \
-H "x-amz-server-side-encryption: AES256" \
--data-binary @avatar.jpg
Web (the bucket's CORS allows PUT and GET from the configured
webOrigins; on dev the default is http://localhost:5173):
// Browsers set Content-Length themselves from the body; it must equal sizeBytes.
const { 'Content-Length': _len, ...headers } = upload.headers;
await fetch(upload.url, { method: 'PUT', headers, body: file });
PUT /v1/me/avatar: set the uploaded image as your picture
Body (SetAvatarInput):
| Field | Type | Validation |
|---|---|---|
uploadId | string | the ULID from POST /v1/me/avatar/uploads |
What the server checks before it accepts the image:
- The file was uploaded (else
409 INVALID_STATE,details.reason: OBJECT_MISSING). - Its stored type is PNG, JPEG or WebP and its size is at most 2 MiB.
- Its first bytes really are that image type (magic bytes). A renamed
HTML or PDF file is refused even if it was uploaded with
Content-Type: image/png.
If a check in 2 or 3 fails, the upload is deleted. Start again with a new
POST /v1/me/avatar/uploads.
On success the image becomes your picture, your previous picture is deleted
from S3, and the profile version (the ETag of PATCH /v1/me/profile)
goes up by 1.
Safe to retry: sending the same uploadId again after it succeeded
returns the current picture, with no further change.
Response 200 (illustrative example):
{
"avatar": {
"avatarId": "01JCF6Z3M5W8Z0XK9R4T6V1AA0",
"contentType": "image/jpeg",
"sizeBytes": 48213,
"updatedAt": "2026-11-11T10:01:12.000Z",
"url": "https://cse-http-be-dev-service-files.s3.us-east-1.amazonaws.com/avatars/<sub>/01JCF6Z3M5W8Z0XK9R4T6V1AA0?X-Amz-Algorithm=…&X-Amz-Signature=…",
"expiresAt": "2026-11-11T10:06:12.000Z"
}
}
| Status | Code | When |
|---|---|---|
| 200 | — | picture set (or already set with this uploadId) |
| 409 | INVALID_STATE | details.reason: OBJECT_MISSING: nothing uploaded for this uploadId, or the upload expired (1 day) |
| 422 | VALIDATION_FAILED | uploadId is not a ULID; or details.reason is TYPE_MISMATCH, SIZE_MISMATCH or NOT_AN_IMAGE |
| 400 / 401 / 403 / 415 / 500 / 503 | common | — |
GET /v1/me/avatar: read your picture
Response 200: { "avatar": AvatarView } as above, or, when no picture
is set:
{ "avatar": null }
The same avatar object (or null) is also returned in:
GET /v1/me/settings→account.avatar, so the settings page needs no extra call (Account settings);PATCH /v1/me/profile→account.avatar.
It is not part of the legacy mobile GET /v1/me response. That shape is
a shipped contract and stays unchanged. Use GET /v1/me/avatar (or
/v1/me/settings) in the app header.
DELETE /v1/me/avatar: remove your picture
No body. Removes the picture and deletes the image from S3. Answers 204 No Content, also when no picture was set. Show the initials
(account.initials) afterwards.
Showing the picture: signed URLs and caching
avatar.urlis a signed S3 URL, valid for 5 minutes (expiresAt). Load it with a plainGET, with noAuthorizationheader. S3 serves it inline with the storedContent-Type.- The URL is different on every read, so don't use it as a cache key.
Use
avatarId: it changes only when a new picture is set.- Flutter (
cached_network_image):CachedNetworkImage(imageUrl: avatar.url, cacheKey: avatar.avatarId). - Web: keep the image in memory keyed by
avatarId. If an<img>gets a403(URL expired), callGET /v1/me/avataragain for a fresh URL.
- Flutter (
- When
avatarisnull, or the image fails to load, showaccount.initials. - Don't store the URL long term (for example in local storage). Store
avatarIdand ask the API for a new URL.
Client checklist (Flutter and web)
- Let the user pick or take a photo.
- Crop and re-encode it on the device to a square, at most 512×512, JPEG (quality ~85) or PNG. This keeps it well under 2 MiB and removes EXIF metadata such as GPS location (the server does not strip it, see Security). Convert HEIC (iPhone) to JPEG.
POST /v1/me/avatar/uploadswith the exactcontentTypeand byte length.PUTthe bytes toupload.urlwithupload.headersunchanged, within 15 minutes.PUT /v1/me/avatarwithuploadId. On a network error, retry the same call (it is safe).- Show
avatar.urlfrom the response, cached byavatarId.
Error handling:
| You get | Do |
|---|---|
403 from S3 on upload | Headers changed or the URL expired: start again at step 3 |
409 OBJECT_MISSING | The S3 upload didn't finish or is older than 1 day: start again at step 3 |
422 NOT_AN_IMAGE / TYPE_MISMATCH / SIZE_MISMATCH | The file is not a real PNG/JPEG/WebP of that size: re-encode and start again |
429 RATE_LIMITED | Wait Retry-After seconds |
403 from S3 on display | URL expired: call GET /v1/me/avatar |
Security
| Concern | How it is handled |
|---|---|
| Public access | The bucket blocks all public access, requires TLS and encrypts every object (SSE-S3). Images are only reachable through signed URLs |
| Reading someone else's picture | Keys are built by the server from the token's sub and a server-made ID. The client never sends a key, and no route takes a user ID |
| Signed URL lifetime | Upload: 15 minutes. Download: 5 minutes |
| Wrong file type or size | Type and size are signed into the upload URL (S3 refuses others), then checked again on PUT /v1/me/avatar together with the file's magic bytes |
| Script in images (XSS) | SVG is refused. Downloads are served with the confirmed image Content-Type |
| Abuse | 20 upload URLs per user per hour; unused uploads are deleted after 1 day; a replaced or removed picture is deleted |
| Lambda permissions | The settings Lambdas can read, write and delete only avatars/* and avatar-pending/* in the bucket. No list permission, no other prefix |
| Logs | Signed URLs are never logged |
| Image metadata | Not stripped by the server. JPEG EXIF (GPS, camera) stays in the file unless the client re-encodes it. See KI-50 |
Storage
| What | Where |
|---|---|
| Picture reference | DynamoDB USER#<sub> / PROFILE, attribute avatar = { avatarId, contentType, sizeBytes, updatedAt } (never returned as is) |
| Pending upload | s3://cse-http-be-<stage>-service-files/avatar-pending/<sub>/<uploadId>, deleted after 1 day by a lifecycle rule |
| Current picture | s3://cse-http-be-<stage>-service-files/avatars/<sub>/<avatarId> |
Source: packages/core/src/services/avatar.ts, packages/api/src/handlers/me-avatar.ts,
lib/routes.ts (avatars), lib/route-family.ts, lib/data-stack.ts, docs/openapi.yaml.