Repository navigation
Labels
mcpLetting an AI assistant connect (MCP, OAuth, tokens)Letting an AI assistant connect (MCP, OAuth, tokens)
Description
Part of #166. First of six. Read "Shared design" and the threat table in #166 before starting; the names and numbers there are fixed.
What this issue is for
- The owner's switch Let apps connect on Manage Users, off by default. Everything below does nothing while it is off.
- One store for every connection,
api_grants, and the tokens under it,api_tokens. Tokens are stored as SHA-256 only. - A second extractor,
ApiUser, built only fromAuthorization: Bearer …. One probe route to test it:GET /api/v1/whoami(the account's id, the app's name, the scopes). - Connected apps on the profile: each grant with its name, scopes, courses, created, expires and last used, and Revoke. Below it, Make a token: a name, the scopes, an optional course list, an expiry (30 days, 90 days, a year). It asks for the account's password again, then shows the token once with a Copy button.
- The owner sees every account's grants on Manage Users (app name, account, last used, expires) and can revoke any of them. A superuser does not see them.
Security rules for this issue
- Hashed at rest. No token and no hash appears in any page, log line or error. A test reads the database after making a token and finds no plain token.
- Bearer only. A cookie on
/api/v1/whoamigets 401. A bearer token on/profilegets the sign-in redirect. The proxy sign-in header gives no API access. - Never in the address. A request with
?access_token=or?token=is refused with 400, even beside a good header. - Checked on every request, not cached past it: the switch is on, the grant exists and has not expired, the account still has Create courses, the account is not waiting behind a temporary-password change. Any "no" is a 401 with an empty body that names nobody.
- Constant work for a bad token. Look tokens up by hash, so timing says nothing about a near miss.
- Revoked by events. Changing the password, the owner setting a temporary password, and the owner turning off two-factor for the account each delete every grant of that account. Say so on those screens.
- Making a token is a sensitive action. It needs the current password in the same form, is counted by
PASSWORD_PER_USER, and is not offered to a session that came from the proxy header without a password (that account has none to check; it uses OAuth from issue 3 instead). - Limits. Ten bad tokens per address in ten minutes, then 429 (
security::RateLimits, keyed bysecurity::client_ip). At most 4 grants per account and a cap on rows in both tables insrc/caps.rs; a fifth grant is refused with a message saying to revoke one. - Expiry is real. Expired grants and tokens are purged in the job that purges sessions. No grant without an expiry.
- Deletion. Both tables reference
userswithON DELETE CASCADE, and are indocs/data-inventory.md. last usedis written at most once a minute per grant, so reads do not turn into SD-card writes.
Not here
/mcp (issue 2), OAuth (issue 3). No course route yet.
How to QA it
- Run it: the dev server (
./.dev-start --reset --seed --background, then/dev/login), or a release build (scripts/release-qa/matrix.sh distto check a tarball you built;cd scripts/release-qa && docker compose up -d, then the owner link fromdocker compose logs). You are the owner. - Open Profile. There is no Connected apps section.
- Open Manage Users. Under the AI switch there is Let apps connect, off. Turn it on.
- Open Profile again. Connected apps says no app is connected, with Make a token under it.
- Click Make a token, name it
Test, leave the defaults, type a wrong password, click Make. You see the password error and no token. - Do it again with the right password. A dialog shows a token starting with
skr_and says it will not be shown again. Copy it and close. The list shows Test, both scopes, expires in 90 days, never used. - In a terminal:
curl -H "Authorization: Bearer <token>" <url>/api/v1/whoamiprints your id,Testand the scopes. Reload the profile: last used now has a time. -
curl <url>/api/v1/whoamiwith one character of the token changed prints nothing and the status is 401 (-ito see it). -
curl -i "<url>/api/v1/whoami?access_token=<token>"answers 400. - In a private window, register a second account. As the owner, make it a Student on Manage Users. As that account, Profile has no Connected apps section.
- As the owner, Manage Users lists the Test grant under Connected apps with your address. Click Revoke there. The curl from before now answers 401 and the profile list is empty.
- Make another token, then change your password on the profile. The page says your connected apps were disconnected, and the token answers 401.
- Make another token, then turn Let apps connect off. The token answers 404. Turn it on: the token works again.
House rules for this repository
- Read
CLAUDE.mdfirst, thendocs/architecture.md("Where things live"). - Never run
cargo fmt. - App text goes in
i18n/en.yamland, translated, in the five other language files. - A new migration is the next
src/db/migrations/vNNN_<name>.sql, appended toMIGRATIONS; update the schema-version asserts insrc/db/tests.rsand the tables indocs/architecture.mdanddocs/data-inventory.md. - No new crate. A source file stays under 1,500 non-test lines.
- Add a line under "Unreleased" in
CHANGELOG.md, written for the person running the server. - For reference only, the hosted app's version of this lives in alexbeeken/skrongle (
src/auth/api.rs,src/oauth_server.rs,src/mcp.rs,src/routes/mcp.rs,docs/security-oauth-mcp.md). Don't copy what a mini has no use for: no publish scope, no REST routes, no vendor client list, no e-mail or Google sign-in.
Metadata
Metadata
Assignees
Labels
mcpLetting an AI assistant connect (MCP, OAuth, tokens)Letting an AI assistant connect (MCP, OAuth, tokens)
Activity
alexbeeken commentedon Nov 12, 2026
Implementation notes (where things are in this repo)
Checked against
mainon 2026-11-12. Line numbers drift; search for the names.~/Code/spanish-learning(read only, do not change it):src/auth/api.rs(grants, tokens,ApiUser), its tests insrc/auth/api/tests.rs, anddocs/features-connected-apps.md. Port the ideas, not the file: leave outcourses:publish, suspension, account export, REST routes and anything about e-mail or Google.src/auth/api.rs(there is alreadysrc/auth/cache.rs): theScopeenum,Grant,mint,user_for_token,revoke,revoke_all_for_user,purge_expired, and theApiUserextractor. Routes in a newsrc/routes/api.rs(whoami) andsrc/routes/profile/apps.rs(the Connected apps forms). Keepsrc/auth.rsandsrc/routes/profile.rsfrom growing: both are large.auth::hash_token(seeDELETE FROM sessions WHERE session_token = ?1insrc/auth.rs). Use the same function for API tokens. Random bytes:random::fill(src/random.rs). Encode the 32 bytes as hex or base64url after theskr_prefix with what is already inCargo.toml.auth::verify_password_async(src/auth.rs), asroutes::profile::change_passworddoes. Count it withsecurity::PASSWORD_PER_USER.src/settings.rshasAI_OFF,ai_offandset_ai_off; addAPPS_ON,apps_onandset_apps_onbeside them (stored "1" when on; absent means off). The form isroutes::manage::set_aiand its part oftemplates/manage.html; add a sibling routePOST /manage/appsand a sibling switch. IfCurrentUsercarriesai_offfrom a cache (src/auth/cache.rs), do the same forapps_onso no request pays an extra query.revoke_all_for_userin the sameDb::callas:routes::profile::change_password,routes::password::change,routes::manage::set_temp_password,routes::manage::turn_off_two_factor.CurrentUser::must_change_password/AppError::ApiPasswordChangeRequired;ApiUserreadsusers.must_change_passwordand answers 401.Perm::CreateCoursesinsrc/perms.rs; owners have every permission.ApiUserneeds the same ruleCurrentUser::canuses; share the function rather than copy it.API_BAD_TOKENS_PER_IPbesideLOGIN_PER_IPinsrc/security.rs; the client address issecurity::client_ip. Row caps go insrc/caps.rsbesideMAX_SESSIONS_PER_ACCOUNT.DELETE FROM sessions WHERE expires_at < ?1function insrc/auth.rs; find its caller and callpurge_expiredfrom the same place.routes::router(src/routes/mod.rs), the/manage/...and/api/profilelines show the style./api/v1/whoamimust not sit behind any layer that reads the session cookie to decide access.src/error.rshasUnauthorized,ApiNoPermission,ApiTooManyRequests. Add what is missing (an empty-body 401 for the API, a 400 for a token in the address); do not reuse a variant that renders a page.src/db/migrations/v005_error_kind.sql(check what is newest onmainfirst). Two tables:api_grants(id, user_id REFERENCES users ON DELETE CASCADE, client_id, client_name, scopes, courses, created_at, expires_at, last_used_at)andapi_tokens(id, grant_id REFERENCES api_grants ON DELETE CASCADE, kind, token_hash UNIQUE, expires_at), with an index onapi_tokens(expires_at)andapi_grants(user_id).kindispersonal,accessorrefresh(issue 3 uses the last two).src/auth/api/tests.rs) and insrc/routes/tests.rsstyle for the HTTP checks. One browser spece2e/specs/connected-apps.spec.ts(read.claude/rules/e2e.mdanddocs/testing.md"Markup hooks" first): switch on, make a token, see it listed, revoke.docs/features.md(a "Connected apps" section),docs/architecture.md("Where things live", the route list, the schema),docs/data-inventory.md,docs/testing.md(the test ids),docs/self-hosting.md(one paragraph on the switch).