diff --git a/backend/internal/rest/errors.go b/backend/internal/rest/errors.go index f44e8c6..d65ec24 100644 --- a/backend/internal/rest/errors.go +++ b/backend/internal/rest/errors.go @@ -22,7 +22,8 @@ func statusFor(err error) int { return http.StatusUnauthorized case errors.Is(err, invite.ErrInvalid), errors.Is(err, user.ErrUnsupportedFormat), - errors.Is(err, user.ErrExceedDimensions): + errors.Is(err, user.ErrExceedDimensions), + errors.Is(err, user.ErrImageTooLarge): return http.StatusBadRequest case errors.Is(err, auth.ErrCanceled): return http.StatusRequestTimeout diff --git a/backend/internal/rest/handler_config.go b/backend/internal/rest/handler_config.go new file mode 100644 index 0000000..dea5874 --- /dev/null +++ b/backend/internal/rest/handler_config.go @@ -0,0 +1,35 @@ +package rest + +import ( + "net/http" + + "goAuth/internal/user" +) + +// avatarLimitsResponse describes the constraints applied to avatar uploads so +// the frontend can mirror them (file picker filter, size hint and client-side +// pre-validation) without hardcoding values. +type avatarLimitsResponse struct { + MaxSizeBytes int `json:"maxSizeBytes"` + MaxWidth int `json:"maxWidth"` + MaxHeight int `json:"maxHeight"` + AllowedMimeTypes []string `json:"allowedMimeTypes"` +} + +type configResponse struct { + Avatar avatarLimitsResponse `json:"avatar"` +} + +// getConfig exposes public, non-secret limits used by the frontend. It is +// served on the public chain so the CSRF cookie is seeded on this GET request +// as well. +func (h *Handler) getConfig(w http.ResponseWriter, r *http.Request) { + writeJson(w, http.StatusOK, configResponse{ + Avatar: avatarLimitsResponse{ + MaxSizeBytes: user.MaxImageSize, + MaxWidth: user.MaxImageWidth, + MaxHeight: user.MaxImageHeight, + AllowedMimeTypes: user.AllowedAvatarMIMETypes(), + }, + }) +} diff --git a/backend/internal/rest/handler_profile.go b/backend/internal/rest/handler_profile.go index bb5f58c..f8a4e9b 100644 --- a/backend/internal/rest/handler_profile.go +++ b/backend/internal/rest/handler_profile.go @@ -141,14 +141,27 @@ func readAvatarUpload(r *http.Request) ([]byte, error) { contentType := r.Header.Get("Content-Type") const multipart = "multipart/form-data" + // Read at most one byte more than allowed so an oversized upload is + // detected and rejected instead of silently truncated. + const limit = user.MaxImageSize + 1 + + var reader io.Reader = r.Body if len(contentType) >= len(multipart) && contentType[:len(multipart)] == multipart { file, _, err := r.FormFile("avatar") if err != nil { return nil, err } defer file.Close() - return io.ReadAll(io.LimitReader(file, maxRequestBody)) + reader = file } - return io.ReadAll(io.LimitReader(r.Body, maxRequestBody)) + data, err := io.ReadAll(io.LimitReader(reader, limit)) + if err != nil { + return nil, err + } + if len(data) > user.MaxImageSize { + return nil, user.ErrImageTooLarge + } + + return data, nil } diff --git a/backend/internal/rest/routes.go b/backend/internal/rest/routes.go index fb5500a..305046d 100644 --- a/backend/internal/rest/routes.go +++ b/backend/internal/rest/routes.go @@ -17,6 +17,8 @@ func (h *Handler) registerRoutes(mux *http.ServeMux) { userChain := middleware.MiddlewareChain{corsMw, csrfMw, sessionMw} superuserChain := middleware.MiddlewareChain{corsMw, csrfMw, sessionMw, h.superuser} + mux.Handle("GET /api/config", publicChain.ThenFunc(h.getConfig)) + mux.Handle("POST /api/auth/signup", publicChain.ThenFunc(h.signup)) mux.Handle("POST /api/auth/signin", publicChain.ThenFunc(h.signin)) mux.Handle("POST /api/auth/signout", userChain.ThenFunc(h.signout)) diff --git a/backend/internal/user/errors.go b/backend/internal/user/errors.go index aca9ce7..69c982c 100644 --- a/backend/internal/user/errors.go +++ b/backend/internal/user/errors.go @@ -7,5 +7,6 @@ var ( ErrNotFound = errors.New("user not found") ErrUnsupportedFormat = errors.New("not supported format") ErrExceedDimensions = errors.New("image exceeds max dimenstions") + ErrImageTooLarge = errors.New("image exceeds max size") ErrInvalidPassword = errors.New("invalid password") ) diff --git a/backend/internal/user/service.go b/backend/internal/user/service.go index 0cf3499..afa69db 100644 --- a/backend/internal/user/service.go +++ b/backend/internal/user/service.go @@ -9,9 +9,14 @@ import ( ) const ( - MaxImageWidth = 1024 - MaxImageHeight = 1024 - PasswordCost = 14 + // MaxImageWidth and MaxImageHeight cap the dimensions of an uploaded + // avatar. + MaxImageWidth = 2048 + MaxImageHeight = 2048 + // MaxImageSize is the maximum accepted avatar upload size in bytes + // (4 MiB). + MaxImageSize = 4 << 20 + PasswordCost = 14 ) type Service struct { diff --git a/backend/internal/user/validator.go b/backend/internal/user/validator.go index 0f00986..41f7be9 100644 --- a/backend/internal/user/validator.go +++ b/backend/internal/user/validator.go @@ -10,6 +10,22 @@ import ( "strings" ) +// allowedImageFormats maps the image formats returned by image.DecodeConfig +// (derived from the file content, not the extension) to the MIME types the +// frontend advertises in the file picker. JPEG files may carry either a .jpg +// or a .jpeg extension; both decode to the "jpeg" format and are accepted. +var allowedImageFormats = map[string]string{ + "jpeg": "image/jpeg", + "png": "image/png", +} + +// AllowedAvatarMIMETypes returns the MIME types accepted for avatars. The +// "image/jpg" alias is included so file pickers that treat ".jpg" as a +// distinct type still allow the upload. +func AllowedAvatarMIMETypes() []string { + return []string{"image/jpeg", "image/jpg", "image/png"} +} + type Validator struct { emailRegex *regexp.Regexp loginRegex *regexp.Regexp @@ -50,6 +66,10 @@ func (v *Validator) VerifyPassword(password string) bool { } func (v *Validator) VerifyImage(data []byte) error { + if len(data) > MaxImageSize { + return ErrImageTooLarge + } + r := bytes.NewReader(data) cfg, format, err := image.DecodeConfig(r) if err != nil { @@ -57,9 +77,7 @@ func (v *Validator) VerifyImage(data []byte) error { return err } - switch format { - case "jpeg", "png": - default: + if _, ok := allowedImageFormats[format]; !ok { return ErrUnsupportedFormat } diff --git a/docker/nginx.conf b/docker/nginx.conf index 796a4c8..d096a01 100644 --- a/docker/nginx.conf +++ b/docker/nginx.conf @@ -11,6 +11,11 @@ server { # The SPA handles the API itself; don't announce the server version. server_tokens off; + # Avatar uploads are capped at 4 MiB by the backend; allow a little extra + # for multipart form overhead. Without this nginx would reject them with + # 413 Request Entity Too Large at its default 1m limit. + client_max_body_size 5m; + # SPA fallback: unknown paths render the app, so client-side routes like # /rooms/daily-standup work on refresh and deep links. location / { diff --git a/frontend/nginx.conf.example b/frontend/nginx.conf.example index 3ed0c99..d4544d9 100644 --- a/frontend/nginx.conf.example +++ b/frontend/nginx.conf.example @@ -15,6 +15,11 @@ server { root /srv/gochat/dist; index index.html; + # Avatar uploads are capped at 4 MiB by the backend; allow a little extra + # for multipart form overhead. Without this nginx would reject them with + # 413 Request Entity Too Large at its default 1m limit. + client_max_body_size 5m; + # Hashed/static bundles can be cached aggressively; index.html must not be. location / { try_files $uri $uri/ /index.html; diff --git a/frontend/src/api.js b/frontend/src/api.js index 08552ef..ce8b523 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -86,6 +86,9 @@ export async function request(method, path, body, options = {}) { } export const api = { + // public configuration (avatar limits, etc.) + getConfig: () => request('GET', '/api/config'), + // auth signup: (payload) => request('POST', '/api/auth/signup', payload), signin: (payload) => request('POST', '/api/auth/signin', payload), diff --git a/frontend/src/pages/ProfilePage.jsx b/frontend/src/pages/ProfilePage.jsx index 0ac4c54..3a3483a 100644 --- a/frontend/src/pages/ProfilePage.jsx +++ b/frontend/src/pages/ProfilePage.jsx @@ -1,6 +1,52 @@ -import React, { useRef, useState } from 'react' +import React, { useEffect, useRef, useState } from 'react' import { api } from '../api.js' +// Fallback used until GET /api/config answers. Kept in sync with the backend +// defaults (user.MaxImageSize and the accepted image formats). +const DEFAULT_AVATAR_LIMITS = { + maxSizeBytes: 4 << 20, + maxWidth: 2048, + maxHeight: 2048, + allowedMimeTypes: ['image/jpeg', 'image/jpg', 'image/png'], +} + +// Builds the file picker `accept` value. MIME types cover the common case, +// the explicit extensions make sure both ".jpg" and ".jpeg" are offered even +// on pickers that do not recognise "image/jpg". +function buildAccept(mimeTypes) { + const types = mimeTypes?.length ? mimeTypes : DEFAULT_AVATAR_LIMITS.allowedMimeTypes + const extensions = ['.jpg', '.jpeg', '.png'] + return [...types, ...extensions].join(',') +} + +function formatBytes(bytes) { + if (!bytes || bytes <= 0) return '0 B' + const units = ['B', 'KB', 'MB', 'GB'] + let value = bytes + let unit = 0 + while (value >= 1024 && unit < units.length - 1) { + value /= 1024 + unit += 1 + } + const rounded = Number.isInteger(value) ? value : value.toFixed(1) + return `${rounded} ${units[unit]}` +} + +// Maps accepted MIME types to a short human readable label (e.g. "JPEG, PNG"). +function formatTypes(mimeTypes) { + const known = { + 'image/jpeg': 'JPEG', + 'image/jpg': 'JPEG', + 'image/png': 'PNG', + } + const labels = [] + for (const type of mimeTypes || []) { + const label = known[type] || type + if (!labels.includes(label)) labels.push(label) + } + return labels.join(', ') +} + export default function ProfilePage({ user, onUserChange }) { const [fullName, setFullName] = useState(user.fullName || '') const [email, setEmail] = useState(user.email || '') @@ -12,8 +58,37 @@ export default function ProfilePage({ user, onUserChange }) { const [avatarMsg, setAvatarMsg] = useState(null) const [avatarVersion, setAvatarVersion] = useState(Date.now()) const [avatarError, setAvatarError] = useState(false) + const [avatarLimits, setAvatarLimits] = useState(DEFAULT_AVATAR_LIMITS) const fileRef = useRef(null) + // Query the backend for the avatar limits instead of hardcoding them, so the + // file picker, the size hint and the client-side check always match what the + // server enforces. + useEffect(() => { + let active = true + api + .getConfig() + .then((config) => { + if (active && config?.avatar) { + setAvatarLimits({ + maxSizeBytes: config.avatar.maxSizeBytes ?? DEFAULT_AVATAR_LIMITS.maxSizeBytes, + maxWidth: config.avatar.maxWidth ?? DEFAULT_AVATAR_LIMITS.maxWidth, + maxHeight: config.avatar.maxHeight ?? DEFAULT_AVATAR_LIMITS.maxHeight, + allowedMimeTypes: + config.avatar.allowedMimeTypes?.length + ? config.avatar.allowedMimeTypes + : DEFAULT_AVATAR_LIMITS.allowedMimeTypes, + }) + } + }) + .catch(() => { + // Keep the hardcoded defaults when the config endpoint is unavailable. + }) + return () => { + active = false + } + }, []) + const initials = (user.fullName || user.login || '?').trim().charAt(0).toUpperCase() const hasAvatar = Boolean(user.hasAvatar) && !avatarError @@ -45,6 +120,18 @@ export default function ProfilePage({ user, onUserChange }) { const file = event.target.files?.[0] if (!file) return setAvatarMsg(null) + + if (file.size > avatarLimits.maxSizeBytes) { + setAvatarMsg({ + type: 'error', + text: `File is too large (${formatBytes(file.size)}). Maximum size is ${formatBytes( + avatarLimits.maxSizeBytes, + )}.`, + }) + if (fileRef.current) fileRef.current.value = '' + return + } + try { await api.uploadAvatar(file) const profile = await api.getProfile() @@ -94,10 +181,15 @@ export default function ProfilePage({ user, onUserChange }) { -

PNG or JPEG.

+

+ {formatTypes(avatarLimits.allowedMimeTypes)}. Max {formatBytes(avatarLimits.maxSizeBytes)} + {avatarLimits.maxWidth && avatarLimits.maxHeight + ? `, up to ${avatarLimits.maxWidth}\u00d7${avatarLimits.maxHeight} px.` + : '.'} +

{user.hasAvatar && (