omi icon indicating copy to clipboard operation
omi copied to clipboard

Tighten WebSocket auth close codes

Open tianmind-studio opened this issue 5 months ago • 2 comments

Summary

  • distinguish WebSocket auth failures so clients can refresh expired/certificate-stale tokens or force re-login for revoked tokens
  • keep generic invalid auth on policy violation code 1008
  • add client-side socket close-code labels for 1008, 4001, and 4004
  • add backend coverage for expired, revoked, certificate-key, and certificate-fetch auth failures

Verification

  • python -m pytest tests\unit\test_ws_auth_handshake.py -q
    • 23 passed, 1 warning
  • python -m black utils\other\endpoints.py tests\unit\test_ws_auth_handshake.py --check
    • 2 files would be left unchanged
  • python -m py_compile utils\other\endpoints.py tests\unit\test_ws_auth_handshake.py
  • git diff --check origin/main..HEAD

Not run

  • Dart/Flutter formatting or tests: dart and flutter are not installed on this Windows host.

tianmind-studio avatar Jun 06 '26 09:06 tianmind-studio

Greptile Summary

This PR differentiates WebSocket authentication close codes by mapping Firebase auth errors to 4001 (token refresh needed), 4004 (re-login required), and 1008 (generic failure), and adds matching telemetry labels on the Dart client side.

  • Backend (endpoints.py): A new _get_ws_auth_close helper uses isinstance checks for ExpiredIdTokenError/RevokedIdTokenError/CertificateFetchError, then falls back to substring matching. The CertificateFetchError isinstance branch is unreachable because that class inherits from UnknownError, not InvalidIdTokenError.
  • Tests (test_ws_auth_handshake.py): New tests cover expired/revoked token paths, but the certificate-error test uses InvalidIdTokenError('Certificate key not found') rather than an actual CertificateFetchError, leaving the dead isinstance branch undetected.
  • Dart (pure_socket.dart): Adds human-readable labels for 1008, 4001, and 4004 in _getCloseCodeReason for telemetry only; no reconnect behavior changes.

Confidence Score: 3/5

Safe for the happy-path and string-fallback cases, but a real CertificateFetchError silently returns 1008 instead of the intended 4001, so clients will not know to refresh their token in that scenario.

The core logic routing ExpiredIdTokenError to 4001 and RevokedIdTokenError to 4004 is correct and tested. However, CertificateFetchError inherits from UnknownError not InvalidIdTokenError, making its isinstance branch dead code. The test that appears to cover this path exercises a completely different branch via string matching, masking the gap.

backend/utils/other/endpoints.py — the _verify_ws_auth and _get_ws_auth_close functions need attention for the unreachable CertificateFetchError branch.

Important Files Changed

Filename Overview
backend/utils/other/endpoints.py Introduces _get_ws_auth_close to map Firebase auth errors to distinct WS close codes; contains a dead isinstance(CertificateFetchError) check because that class does not inherit from InvalidIdTokenError, and an overly broad 'key' substring match in the fallback.
backend/tests/unit/test_ws_auth_handshake.py Adds tests for 4001/4004 close codes; the CertificateFetchError test case exercises the string-matching fallback rather than an actual CertificateFetchError instance, leaving the dead isinstance branch untested.
app/lib/services/sockets/pure_socket.dart Adds telemetry labels for close codes 1008, 4001, and 4004 in _getCloseCodeReason; straightforward and correct for its stated purpose.

Sequence Diagram

sequenceDiagram
    participant Client as Flutter Client
    participant Auth as _verify_ws_auth
    participant Close as _get_ws_auth_close
    participant FB as firebase_admin

    Client->>Auth: WS connect (Authorization header)
    alt No or malformed header
        Auth-->>Client: close 1008
    else Valid format
        Auth->>FB: verify_token(token)
        alt RevokedIdTokenError (subclass of InvalidIdTokenError)
            FB-->>Auth: raises RevokedIdTokenError
            Auth->>Close: _get_ws_auth_close(e)
            Close-->>Auth: 4004
            Auth-->>Client: close 4004 (re-login required)
        else ExpiredIdTokenError (subclass of InvalidIdTokenError)
            FB-->>Auth: raises ExpiredIdTokenError
            Auth->>Close: _get_ws_auth_close(e)
            Close-->>Auth: 4001
            Auth-->>Client: close 4001 (token refresh)
        else Generic InvalidIdTokenError
            FB-->>Auth: raises InvalidIdTokenError
            Auth->>Close: _get_ws_auth_close(e)
            Close-->>Auth: 1008 or 4001 via string match
            Auth-->>Client: close 1008 or 4001
        else CertificateFetchError (NOT subclass of InvalidIdTokenError)
            FB-->>Auth: raises CertificateFetchError
            Note over Auth: Caught by except Exception, not InvalidIdTokenError
            Auth-->>Client: close 1008 instead of intended 4001
        else Success
            FB-->>Auth: uid string
            Auth-->>Client: connection accepted
        end
    end

Comments Outside Diff (1)

  1. backend/utils/other/endpoints.py, line 128-132 (link)

    P2 The docstring still says the function only raises WebSocketException(code=1008), but it can now raise with codes 4001 or 4004 as well.

    Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Reviews (1): Last reviewed commit: "Differentiate websocket auth close codes" | Re-trigger Greptile

greptile-apps avatar Jun 06 '26 09:06 greptile-apps

Rebased and force-pushed onto current main.

Greptile follow-up addressed in the current branch:

  • real CertificateFetchError is caught before the generic Exception handler and is covered by test_certificate_fetch_error_sends_close_4001
  • the fallback no longer treats every key message as refreshable; only expired/certificate map to 4001, with API key invalid covered as 1008
  • the _verify_ws_auth docstring now documents 1008, 4001, and 4004

Backend verification passes: python -m pytest tests\unit\test_ws_auth_handshake.py -q -> 23 passed, 1 warning. I could not run Dart/Flutter formatting locally because this Windows host does not have dart or flutter installed.

tianmind-studio avatar Jun 08 '26 14:06 tianmind-studio