Disclosure: I'm the developer of ScooterLog, and this post is published from my account. It was drafted and published by an AI agent working on my behalf from the app's source code. ScooterLog is an independent app, not affiliated with, endorsed by or sponsored by Ola Electric.
ScooterLog builds a charge history and trip log for connected electric scooters. To do that, its server has to keep polling the scooter's cloud for each user, long after the user has closed the app. That means the server holds a login that is not its own: the session that the scooter's account issues when the user signs in with a one-time code.
This post is about how that small Python backend (one SQLite file, about 840 lines of store code) holds those sessions: what is encrypted, where the user id is allowed to come from, and why there are two ways out of the service, not one.
1. Sign-in is a one-time code, and nothing about it is kept
The user types a phone number, gets a one-time code from the scooter's own account service, and types it back. ScooterLog never sees or stores a password, because there is none. What comes back from a good code is a session (a small JSON object of headers), and that is the only secret the server keeps.
The phone number is not stored either. The user row is keyed by a hash of it, made with a server-side secret:
def phone_hash(phone):
return hashlib.sha256((PHONE_SALT + ':' + phone).encode()).hexdigest()
Why keep a hash at all? So that signing in again from a new phone finds the same row, the same history and the same alarms, instead of making a second account. The hash is a lookup key, not a contact detail: the server can tell "this is the same person as before" and nothing more. Since phone numbers are a small space, the secret in front of the number is what makes the hash worth anything, so it lives outside the database, in the environment.
2. The session is encrypted with its own key, created once
The session blob goes into the users table encrypted with Fernet (from the cryptography package), under a key that belongs to this service alone:
def cipher():
"""Service key for encrypting per-user token blobs; own key, 0600."""
DATA.mkdir(parents=True, exist_ok=True)
key = DATA / 'session-key'
if not key.exists():
with open(os.open(key, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600), 'wb') as f:
f.write(Fernet.generate_key())
return Fernet(key.read_bytes())
Three details matter here:
-
O_EXCL. If two workers start at the same moment, only one can create the file. The other gets an error rather than silently writing a second key and making every blob the first one wrote unreadable. -
0o600at creation, not achmodafterwards. There is no window in which the key file exists with default permissions. - Its own key. The same codebase also runs a private owner portal. The public service has a separate database and a separate key, so a mistake in one cannot decrypt the other's sessions.
Writing a session is one line before the SQL:
blob = cipher().encrypt(json.dumps(token).encode())
The test for this does not trust the code. It reads the raw database file and looks for the plaintext:
def test_token_encrypted_at_rest(self):
with open(os.environ['SCOOTERLOG_DB'], 'rb') as f:
raw = f.read()
self.assertNotIn(b'tokA', raw)
self.assertNotIn(b'tokB', raw)
That catches the mistake an assertion on the decrypt path never would, such as a debug column or a cache table that quietly stores the session in the clear.
3. The user id comes from the cookie, and only from the cookie
Every table has a user_id column, and every read and write is scoped by it. The rule written at the top of the store module is the one that does the work: the caller gets its user_id only from the authenticated session, never from client input.
The session cookie is the user id plus an HMAC of it:
def sign(user_id):
mac = hmac.new(COOKIE_SECRET.encode(), user_id.encode(), hashlib.sha256).hexdigest()
return user_id + '.' + mac
def verify_cookie(value):
if not value or '.' not in value:
return None
uid, mac = value.rsplit('.', 1)
good = hmac.new(COOKIE_SECRET.encode(), uid.encode(), hashlib.sha256).hexdigest()
return uid if hmac.compare_digest(mac, good) else None
It is set HttpOnly; SameSite=Strict; Secure, with a 30-day Max-Age. compare_digest keeps the check constant-time.
A user id alone is not enough, though, because requests also name a vehicle. Every function that takes a vehicle id checks ownership first and raises if it fails:
def _owns_vehicle(c, user_id, vehicle_id):
return c.execute('SELECT 1 FROM vehicles WHERE user_id=? AND vehicle_id=?',
(user_id, vehicle_id)).fetchone() is not None
The HTTP layer turns that PermissionError into a 403 in one place, so a handler cannot forget to. The tests write two users with two scooters and then try to cross over, in both directions:
def test_cannot_write_other_users_vehicle(self):
with self.assertRaises(PermissionError):
self.store.record_point(self.a, 'VB', {'source_ms': 1, 'battery_soc': 50})
def test_cannot_read_other_users_vehicle(self):
self.store.record_point(self.b, 'VB', {'source_ms': 1000, 'lat': 1.0, 'lng': 2.0, 'battery_soc': 40})
with self.assertRaises(PermissionError):
self.store.history(self.a, 'VB')
4. Two ways to leave: "stop polling" and "delete everything"
People leave a service like this for two different reasons, and one button cannot serve both.
Disconnect means "stop using my scooter account, but keep what you already built." It drops only the session and marks the row:
def disconnect_user(user_id):
"""Drop only the stored token; keep history until explicit delete."""
with _LOCK, connect() as c:
c.execute("UPDATE users SET token_blob=NULL, status='DISCONNECTED' WHERE user_id=?", (user_id,))
With the blob set to NULL, the poller has nothing to send, and get_token only returns a session for rows that are ACTIVE. The charge history stays readable, and signing in again picks up where it left off.
Delete my data (in the app under Settings) means "forget me." It walks every table by name:
def delete_user(user_id):
"""Remove everything we hold for this user. Isolated: WHERE user_id=? only."""
with _LOCK, connect() as c:
schema(c)
for t in ('history', 'charging', 'push_subs', 'alerts', 'prefs',
'vehicle_status', 'ola_cache', 'vehicles'):
c.execute(f'DELETE FROM {t} WHERE user_id=?', (user_id,))
c.execute('DELETE FROM users WHERE user_id=?', (user_id,))
c.execute('DELETE FROM links WHERE member_id=? OR owner_id=?', (user_id, user_id))
return c.total_changes
The tables do declare ON DELETE CASCADE, and the connection turns on PRAGMA foreign_keys=ON. So why list them? Because in SQLite that pragma is set per connection and is off by default. One script or migration that opens the file without it would delete the user row and leave every child row behind, now matching no user at all. An explicit list costs eight lines and does not depend on how the connection was opened. The links table, which joins one account to another's scooters, has no foreign key to cascade through anyway, so it would have been missed.
Both endpoints also clear the cookie in the same response (Max-Age=0), so the browser is signed out at the same moment as the data goes.
The test for delete checks the other user as carefully as the deleted one:
def test_delete_my_data_is_isolated(self):
self.store.record_point(self.a, 'VA', {'source_ms': 1, 'battery_soc': 10})
self.store.record_point(self.b, 'VB', {'source_ms': 1, 'battery_soc': 10})
self.store.delete_user(self.a)
self.assertIsNone(self.store.get_token(self.a))
self.assertEqual(self.store.user_vehicles(self.a), [])
# B is untouched
self.assertEqual(self.store.get_token(self.b)['headers']['X-ACCESS-TOKEN'], 'tokB')
self.assertEqual(len(self.store.history(self.b, 'VB')), 1)
The store tests (11 of them, including these four) run in about a second.
Takeaways
- If you must hold another service's session for your users, keep it as an encrypted blob, under a key that only this service has, created once with
O_EXCLand0600. - Test encryption at rest by reading the raw file for the plaintext, not by round-tripping through your own decrypt.
- Take the user id only from a signed cookie, and check ownership of every object the request names.
- Offer two exits: one that stops access but keeps the history, and one that deletes everything. Do not make users pick the drastic one just to stop the polling.
- In SQLite, do not let a privacy promise depend on
PRAGMA foreign_keys. Delete table by table.
ScooterLog is on Google Play. It only knows what the scooter's cloud reports, and readings can lag by a few minutes. It is a log, not a security service, and it does not control the scooter. ScooterLog is an independent app, not affiliated with, endorsed by or sponsored by Ola Electric.
AI Disclosure: this article was drafted and published by an AI agent on the developer's behalf, from the app's source code.
Top comments (0)