GHSA-RCRW-PG2V-J9XG
Service-role metadata worker can overwrite another tenant's image object
Ciclo de vida de la vulnerabilidad
| Fecha | Fase | Evento | Detalle |
|---|---|---|---|
| Divulgación | Publicada | GHSA-RCRW-PG2V-J9XG divulgada | |
| Monitoreo | Detectada | Ingresó al índice | |
| Monitoreo | Verificada | Última verificación contra las fuentes |
Cross-tenant image overwrite through the metadata-cleaning worker
Executive Summary
Capgo's asynchronous image metadata cleaner trusts an image object key copied
from a mutable application, organization, or user database row. An
authenticated actor can place the exact key of another tenant's image in a row
they are allowed to update. The resulting database trigger queues an internal
job, and a service-role worker downloads, sanitizes, and upserts that victim
object without checking that the key belongs to the updated entity.
This is a cross-tenant integrity issue. The overwrite is constrained: the
attacker must know an existing key, the object must be a recognized JPEG or PNG
containing removable metadata, and the resulting bytes are chosen by the
sanitizer rather than by the attacker. The expected visual pixels remain
unchanged. I therefore assess the issue as Medium severity, rather than an
arbitrary-file-write or visible-defacement primitive.
I reviewed vulnerable revision
`255357ca7277c95737c5148b20e43391efe858b8` directly and executed the original
path normalizer and metadata cleaner in an isolated Node.js harness with an
in-memory storage double. I observed the worker download a victim key and
upsert changed bytes to that same key. I did not contact Capgo production,
Supabase, or any real tenant, and I did not execute the full asynchronous queue
flow against a deployed stack.
Background
Capgo stores images in the Supabase `images` bucket. Application icons,
organization logos, and user avatars are represented in database rows as text
paths. Public update paths authorize access to the row. For example, the
application update handler checks `app.update_settings`, normalizes the
caller-provided icon, and stores it:
// supabase/functions/_backend/public/app/put.ts:28-38,57-70
if (!(await checkPermission(c, 'app.update_settings', { appId }))) {
throw quickError(401, 'cannot_access_app', 'You can\'t access this app')
}
const normalizedIcon = normalizeImagePath(body.icon)
// ...
.update({
name: body.name,
icon_url: normalizedIcon ?? body.icon,
})The organization path similarly checks `org.update_settings` and then assigns
`normalizeImagePath(body.logo) ?? body.logo` in
`supabase/functions/_backend/public/organization/put.ts:179-200,231-239`.
Authenticated users also have an owner-only UPDATE policy over their own
`users` row, but the policy does not constrain `image_url`
(`supabase/migrations/20260708000000_prod_baseline.sql:20666`).
These controls establish which *row* we may change. The intended storage
boundary is separate: ordinary authenticated storage updates are restricted by
folder ownership policies. That boundary becomes important because the
background cleaner does not use the caller's storage privileges. It constructs
a Supabase client with `SUPABASE_SERVICE_ROLE_KEY` in
`supabase/functions/_backend/utils/supabase.ts:114-125`.
Updates to `apps.icon_url`, `orgs.logo`, and `users` invoke
`trigger_http_queue_post_to_function`, which places the old and new records
into PGMQ. The high-frequency queue consumer includes `on_app_update`,
`on_org_update`, and `on_user_update`. Direct trigger routes require the
internal API secret, but an external actor need not call them: an authorized
row update is the queue producer.
Vulnerability Details
The problem begins with normalization. `normalizeImagePath` unwraps a signed or
public storage URL, removes an `images/` prefix or leading slashes, and returns
the resulting key:
// supabase/functions/_backend/utils/storage.ts:5-26
const STORAGE_URL_REGEX =
/\/storage\/v1\/object(?:\/(public|sign))?\/images\/(.+)$/
export function normalizeImagePath(raw?: string | null) {
if (!raw)
return null
const trimmed = raw.trim()
// ...
const url = new URL(trimmed)
const match = url.pathname.match(STORAGE_URL_REGEX)
if (match?.[2])
return decodeURIComponent(match[2])
// ...
return trimmed.replace(/^images\//, '').replace(/^\/+/, '')
}Normalization is deliberately syntactic. It never receives an expected user,
application, or organization identifier, so it cannot verify ownership. If we
store a value naming
`org/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/logo/victim.jpg`, that exact
cross-tenant key survives normalization.
The database triggers at baseline lines 19848, 19868, and 19884 then enqueue
the updated record. Each internal handler carries the mutable field directly
into the shared cleaner. The application handler is representative:
// supabase/functions/_backend/triggers/on_app_update.ts:10-20
app.post('/', middlewareAPISecret, triggerValidator('apps', 'UPDATE'), async (c) => {
const record = c.get('webhookBody')
// ...
if (record.icon_url) {
await cleanStoredImageMetadata(c, record.icon_url)
}
})The organization handler uses `record.logo`, while the user handler uses
`record.image_url`. None passes the immutable identity of the row's owner into
the cleaner. We therefore arrive at the privileged sink with only an
attacker-influenced string:
// supabase/functions/_backend/utils/image.ts:163-198
const normalizedPath = normalizeImagePath(rawImagePath)
const supabase = supabaseAdmin(c)
const { data: fileBlob } =
await supabase.storage.from('images').download(normalizedPath)
const original = new Uint8Array(await fileBlob.arrayBuffer())
const sanitized = stripMetadataBytes(original)
if (!sanitized || isSameBytes(sanitized, original))
return
await supabase.storage.from('images').upload(normalizedPath, sanitized, {
upsert: true,
...(contentType ? { contentType } : {}),
})We can now state the missing invariant precisely: a key derived from an
application row must belong to that application or its owning organization; a
key derived from an organization row must belong to that organization; and a
key derived from a user row must belong to that user. The worker checks none of
those relationships. Because its service-role client bypasses ordinary storage
RLS, the row-level authorization is converted into a write to an unrelated
tenant's object.
Exploitability Analysis
The simplest route is the user's own profile row. An authenticated user may
update that row under the owner policy, so no application or organization
administrative role is required. The attacker places a known victim object key
in `image_url`; the user-update trigger notices the new path and invokes the
cleaner asynchronously. Administrators of an application or organization have
equivalent routes through `icon_url` and `logo`.
This primitive has meaningful constraints:
- The exact victim key must already be known. This finding does not establish
- The object must parse as JPEG or PNG and contain metadata the cleaner removes.
- The attacker cannot choose arbitrary replacement bytes. The transformation
- The expected pixel content remains unchanged because the worker removes
- Processing is asynchronous, so timing depends on the queue consumer.
These constraints rule out claims of arbitrary content replacement, direct
code execution, or guaranteed visible defacement. They do not remove the
cross-tenant boundary violation: object bytes, hash, ETag, and embedded
metadata are changed by a tenant that lacks update permission for the object.
Metadata may include provenance, copyright, color-profile, or workflow data,
so silent removal can matter even when the rendered image is unchanged.
A signed image URL is a convenient way to express the key because the
normalizer unwraps it, but a valid signature is not necessary for the worker;
it uses only the URL path. A raw `images/<key>` or `/<key>` value reaches the
same normalized key. Conversely, directly invoking the trigger route is an
unhelpful route because `middlewareAPISecret` protects it. The authorized
database update followed by the internal queue is the confused-deputy path.
Proof of Concept
The supplied PoC safely executes the original normalizer and cleaner from a
checkout of the vulnerable revision. It replaces only the Supabase client with
an in-memory double. The input JPEG contains an APP1/EXIF segment; the harness
asserts that the worker removes the segment and upserts the changed bytes to the
same victim key. It also confirms that a clean JPEG and an unsupported GIF do
not trigger uploads.
Requirements are Node.js 22.6 or newer and a checkout at the vulnerable
revision. From this report directory:
cd poc
node metadata_worker_harness.mjs /path/to/capgo-checkoutRepresentative output:
Isolated metadata-worker harness
Result: PASS
normalized victim key: org/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/logo/victim.jpg
download key: org/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/logo/victim.jpg
upload key: org/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/logo/victim.jpg
original bytes: ff d8 ff e1 00 08 45 78 69 66 00 00 ff d9
sanitized bytes: ff d8 ff d9
upsert: true
clean JPEG uploads: 0
unsupported GIF uploads: 0
production or Supabase storage contacted: falseThe harness is non-destructive and needs no cleanup because all object data is
held in memory. It proves the key-preserving privileged rewrite and its format
constraints. It does not claim that I exercised a real queue, live storage
bucket, or cross-tenant account.
Remediation
The worker must derive or validate its target from trusted ownership data, not
solely from mutable row text. The strongest design is to generate canonical
object keys server-side and enqueue a structured job containing the immutable
entity type and ID. Before download or upload, a server-side function should
reconstruct the only permitted prefix and reject any mismatch.
A minimal shape is:
function assertOwnedImagePath(
path: string,
ownerType: 'user' | 'org' | 'app',
ownerId: string,
): string {
const normalized = normalizeImagePath(path)
if (!normalized)
throw new Error('invalid image path')
const expectedPrefix = `${ownerType}/${ownerId}/`
if (!normalized.startsWith(expectedPrefix))
throw new Error('image path does not belong to queued entity')
return normalized
}The precise prefixes should follow Capgo's canonical storage schema; a
`startsWith` check is appropriate only after strict normalization and delimiter
handling. Prefer a scoped database RPC that rechecks object ownership at the
write boundary, even when invoked with service credentials. Reject absolute
and signed URLs in persisted image fields, and store structured ownership
metadata rather than treating a path string as authority.
Regression tests should cover all three triggers:
- same-owner canonical paths are cleaned;
- cross-user, cross-organization, and cross-application paths are rejected;
- similarly prefixed identifiers cannot bypass delimiter checks;
- encoded separators and signed/public URL wrappers cannot change ownership;
- unsupported and already-clean files remain no-ops;
- a rejected job never downloads or uploads the referenced object.
Summary
Capgo correctly authorizes the database row an actor may update, but the
metadata worker later treats a path stored in that row as authorization to
rewrite a storage object. We followed that value through normalization,
database-triggered queue processing, and the service-role download/upsert
sink. The isolated PoC executed the original transformation and demonstrated a
same-key overwrite of a metadata-bearing JPEG without contacting external
systems.
The practical result is a constrained but genuine cross-tenant integrity
violation. Binding every queued image key to the immutable identity of its
source entity, then enforcing that invariant again at the privileged storage
boundary, removes the confused-deputy condition. The same path-to-owner review
should be applied to other service-role image operations and any background
job that consumes mutable storage keys.
dc026-poc.zip https://github.com/user-attachments/files/30302240/dc026-poc.zip
<!-- private-maintainer-note -->
Private maintainer note: related hardening in merged PR https://github.com/Cap-go/capgo.app/pull/3083 (cleanStoredImageMetadata ownership gate). Reporter: please re-test cross-tenant overwrite on latest main; if still reproducible, comment with updated PoC.
Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.
Estado del parche por paquete
La fuente no informa paquetes ni versiones corregidas.
Arsenal público
Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.
https://github.com/Cap-go/capgo.app/security/advisories/GHSA-rcrw-pg2v-j9xgLas referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.
