Skip to content

feat: setUserJwt, setUserJwtProvider and setAuthTokens (customer identity) - #61

Merged
boehlerlukas merged 5 commits into
masterfrom
feat/customer-identity
Nov 7, 2026
Merged

boehlerlukas merged 5 commits into
masterfrom
feat/customer-identity

Conversation

@boehlerlukas

@boehlerlukas boehlerlukas commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Customer identity for the Android SDK, following .handover/customer-identity/CONTRACT.md §2 (transport), §3 (identify results), §5 (POST /sessions/auth-tokens) and §6 (SDK methods), and the call shapes in the docs PR (documentation/android/user-identity.mdx, guides/customer-identity.mdx).

Methods

  • Gleap.getInstance().setUserJwt(String token): decodes the payload (base64url JSON, no signature check), reads userId or user_id (string or number), sends POST /sessions/identify with userId, userHash = token and no contact fields (plus lang, platform, deviceType as always). Refused with a log line and no request when the token is not three non-empty base64url segments, has no user id or is over 4096 characters. Memory only: setGleapUserSession never writes a JWT to the session store.
  • Gleap.getInstance().setUserJwtProvider(GleapUserJwtProvider provider): new public interface GleapUserJwtProvider { void fetchToken(Callback callback); interface Callback { void onToken(String token); } }, called on the main thread. Asked on an identify 401 containing token_expired (retried once with the new token) and before an identify is sent again (file session refresh, retry after a network failure) when the token's exp is within 5 minutes. One call in flight, 10 s timeout, 30 s pause after a failure (null, not a JWT with a user id, exception, timeout).
  • Gleap.getInstance().setAuthTokens(Map<String, String> tokens): POST /sessions/auth-tokens with { "tokens": { name: value } } and the identify headers; a null value removes a token, invalid names (^[a-zA-Z][a-zA-Z0-9_-]{0,39}$) are skipped with a log line. Kept in memory and resent after a signed identify on a new session; a 401 logs a warning and keeps the session.
  • clearIdentity() also drops the token and the auth tokens; the provider stays.

Behaviour changes

  • GleapSessionProperties.equals now compares an identity token (when the new identify carries a JWT); the token the server accepted stays with the in-memory session properties, so a new token is sent even when nothing else changed and the same token is not sent twice. A legacy hash is still not compared. A setUserJwt identify compares only the user id and the token.
  • An identify 401 whose body contains token_expired or token_invalid no longer calls clearRejectedIdentity (warning logged; token_expired goes to the provider). signature_required and other 4xx with a JSON body keep today's behaviour.

Difference from the documented shape

None: the docs' Java lambda setUserJwtProvider(callback -> myBackend.fetchGleapToken(token -> callback.onToken(token))) and Kotlin GleapUserJwtProvider { callback -> ... } both compile against the single-method interface.

Grant transport (.handover/customer-identity/INTERCOM-MODEL.md §1, §2, §13)

  • Grant store (GleapSessionController): identity.grant from a session answer is kept in memory and in the session store (SharedPreferences via KeyValueStore: grant, grant_session_id), bound to the answer's gleapId; the expiry is read from the grant's exp. An app restart stays signed until it expires (loaded with the stored session, only when it belongs to it). An answer with identity but no grant (an unsigned identify) drops it; an answer without identity keeps it while the session is the same.
  • Header: Gleap-Grant via GleapHttp.addGrantHeader in openSessionPost (sessions, identify, partial update, auth tokens) and addReportSessionHeaders (reports, events, uploads), in GleapCaptureApi (JSON posts and the OkHttp file upload). Only sent with the session id the grant was issued to. An expired grant is still sent (the server may extend it once).
  • Messenger: GleapWidgetMessages.sessionUpdate() carries a top-level grant (string or null); it is pushed on every session answer (GleapMainActivity.refreshSession), so a new identify or renewal re-sends it.
  • Renewal: a grant that expires within 5 minutes is renewed by sending the last signed identify again (the forced resend the file session refresh uses; the JWT provider is asked first when the token expires within 5 minutes too), on a timer and in onActivityStarted, at most once a minute. Classic projects (no grant) never trigger it.
  • identity_mismatch (400): GleapIdentifyService returns IDENTITY_MISMATCH; GleapSessionController.restartForIdentify drops the local session (store, grant, file session, push group), keeps the identify, the provider and the auth tokens, starts a fresh visitor session and sends the identify once more on it. A second mismatch starts over as a guest. token_expired / token_invalid handling is unchanged.
  • clearIdentity drops the grant (memory and store).
  • New public API: Gleap.getInstance().setSessionDuration(long milliseconds) (also on iGleap), sent as sessionDuration with every identify; 0 removes it. Nothing else new is public.

Not covered

  • The realtime WebSocket and the widget URL (GleapURLGenerator) carry gleapId / gleapHash as query parameters; neither gets the grant (it does not belong in a URL). The widget receives it through session-update only.
  • The spec's one-time 1-hour extension of an expired grant has no defined return channel yet; the SDK takes a new grant only from identity.grant in a session answer.

Verification

  • ./gradlew test (JAVA_HOME = Android Studio jbr) → BUILD SUCCESSFUL; 239 tests, 0 failures, 0 errors in each of testDebugUnitTest and testReleaseUnitTest.

  • New tests: GleapUserJwtTest (payload decoding, shape/length rules, expiry window, 401 code detection, equals with tokens), GleapUserJwtProviderGateTest (one in flight, 10 s timeout, 30 s pause, invalid result, throwing provider, new provider after a failure), CustomerIdentityTest (identify body, invalid token no request, resend on token change, token_invalid keeps the session, signature_required still clears, token_expired → provider → one retry, renewal before a file session refresh, auth tokens body/null/once per session/resend after signed identify, clearIdentity keeps the provider).

  • Grant transport: ./gradlew assembleRelease → success; ./gradlew :gleap:testReleaseUnitTest → 244 tests, 0 failures. New GleapGrantTest: grant on the session's requests (and never with another session id) + in session-update, survives an app start and leaves with clearIdentity, an unsigned identify drops it, identity_mismatch → fresh visitor → one more identify with the token, sessionDuration in the identify body.

Final-review fixes (b8e1fa9)

  • signature_required is logged (logcat tag Gleap) before the SDK starts over as a guest (behaviour unchanged): "Gleap: this project enforces identity verification and the identify had no valid signature (signature_required). Pass a token from your backend to setUserJwt."
  • Re-minted tokens are not re-identified. GleapSessionProperties.equals compares GleapUserJwt.identityFingerprint: the token's kid and its claims without iat/exp/nbf/jti, keys sorted (was: the raw token string). A backend that mints a fresh token per app start no longer causes an identify on every start; a changed claim or key is still sent once.
  • store.remove("grant") (and grant_session_id) only when a grant was stored (grantStored, set on load and on write, reset on store.clear()).
  • Grant backup: the SDK ships no backup_rules / data_extraction_rules, so nothing was added. The stored grant is encrypted with an AndroidKeyStore key, which is not part of a backup, so a restored copy cannot be read on another device.

Checks: ./gradlew test → passes, 245 tests in each of testDebugUnitTest and testReleaseUnitTest, 0 failures (new: fingerprint/equals, signature_required detection, re-minted token not resent).

Final re-check fixes (cdd9322)

Contract addition (Server in parallel): in Signed mode the /sessions and identify answers for an identified session without a grant carry identity: { signed: false, grant: null, mode: 'signed' }; Classic carries no identity.

  • Returning users after a switch to Signed get a grant. applyGrant keeps identity.mode. A non-identify session answer for an identified session on a Signed project without a grant queues the held identify once: the app's last identify with a hash, or the user hash kept in the store from the last app start (processSessionActionResult). GleapIdentifyService asks claimSignedGrantRequest, which marks the session id (memory only), so the unchanged identify is sent once per app start and session and never in a loop; Classic projects still skip it. A refusal of that grant-only identify keeps the session (logged) instead of starting over as a guest.
  • setUserJwt before initialize was dropped silently; it is now buffered (memory only) and sent by GleapInitializer right after the session controller exists, queued behind the stored session. clearIdentity drops a buffered token.
  • Renewal runnable: removeCallbacks (new GleapMainThread.removeCallbacks) before posting, so only one renewal is pending.
  • Short sessions: renew at min(5 min, lifetime/2) before expiry (lifetime = exp - iat, or exp - arrival without iat); a renewal held back by the 60 s throttle is re-armed once for when the minute is over.
  • Provider tokens: a token with exp <= now, or the exact token the server just refused (token_expired / token_invalid), counts as a failure (30 s pause). CustomerIdentityTest.anExpiredRetryIsNotRetriedAgain now expects the refused token not to be sent a second time.

Checks: ./gradlew test → 250 tests, 0 failures in each of testDebugUnitTest and testReleaseUnitTest. New: GleapGrantTest (held legacy hash sent once on a Signed session load, never repeated while the server answers without a grant, Classic skips the unchanged identify, setUserJwt before initialize sent once the SDK starts), GleapUserJwtProviderGateTest (expired / refused token fails).

🤖 Generated with Claude Code

Customer identity (contract §2, §3, §5, §6):

- Gleap.getInstance().setUserJwt(String) decodes the JWT payload (no
  signature check), reads userId / user_id and sends the existing identify
  with userHash = token and no contact fields. Not three base64url parts, no
  user id or over 4096 characters: log line, no request. Memory only (never
  written to the session store). GleapSessionProperties.equals compares an
  identity token, and the accepted token stays with the in-memory session
  properties, so a new token is sent even when nothing else changed.
- setUserJwtProvider(GleapUserJwtProvider) (callback.onToken(token)) is
  asked on identify 401 token_expired (one retry with the new token) and
  before an identify is sent again (file session refresh, retry) when the
  token expires within 5 minutes. One call in flight, 10 s timeout, 30 s
  pause after a failure (GleapUserJwtProviderGate).
- 401 token_expired / token_invalid keep the session and the user instead
  of clearRejectedIdentity; signature_required and other 4xx as before.
- setAuthTokens(Map<String, String>) posts to /sessions/auth-tokens (null
  removes), kept in memory and resent after a signed identify on a new
  session; 401 warns and keeps the session.
- clearIdentity drops the token and the auth tokens; the provider stays.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
boehlerlukas and others added 4 commits November 6, 2026 09:53
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…ionDuration)

Customer identity spec §1, §2, §13:

- The grant from a signed identify (identity.grant) is kept in memory and in
  the session store with its exp, bound to the session it was issued to, so
  an app restart stays signed until it expires.
- Gleap-Grant rides on every request of that session; never with another
  session's id.
- The Messenger gets it as a top-level `grant` in session-update, re-sent on
  every change (new identify, renewal, logout sends null).
- An identify answered without a grant drops it; clearIdentity drops it.
- A grant about to expire is renewed by replaying the last signed identify
  (through the JWT provider when the token expires too), at most once a
  minute, on a timer and on return to the foreground.
- 400 identity_mismatch: drop the local session, start a fresh visitor
  session, send the identify once more; a second mismatch starts over as a
  guest. token_expired / token_invalid unchanged.
- New optional config setSessionDuration (ms), sent with every identify.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…t they say

- An identify refused with signature_required logs why (still starts over as a guest).
- GleapSessionProperties.equals compares a token's kid and claims without
  iat/exp/nbf/jti, so a token re-minted per app start is not identified again.
- The stored grant is removed only when one was stored.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…itialize, short-session renewal

- A session answer with identity.mode 'signed' and no grant for an identified session queues the
  held identify (last identify, or the user hash kept from the last start) once per app start and
  session; GleapIdentifyService sends it even when unchanged (claimSignedGrantRequest marks the
  session, so it never loops) and a refusal of that grant-only identify keeps the session.
- setUserJwt before Gleap.initialize is buffered and sent once the session controller exists;
  clearIdentity drops it.
- Grant renewal: removeCallbacks before posting, renew at min(5 min, lifetime/2), re-arm once
  after the 60 s throttle.
- JWT provider: an expired token or the token the server just refused (token_expired /
  token_invalid) counts as a failure (30 s pause).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@boehlerlukas
boehlerlukas merged commit dc1deb1 into master Nov 7, 2026
1 check passed
@TobiasDuelli
TobiasDuelli deleted the feat/customer-identity branch November 18, 2026 20:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant