Sign-in API for the Android app: /api/v1/auth/* (neiam_auth v0.5.0)

8849444 · gmorell · 2026-12-03 17:55

36 files +1061 -131
Message
{commit_body(@commit)}

Files changed

modified README.md
+10 −0
@@ -77,6 +77,16 @@ Tests use an in-memory bucket.
77 77 | `POD_IP`, `POD_NAMESPACE`, `RELEASE_COOKIE` | clustering in Kubernetes (below) |
78 78 | `SMTP_RELAY`, `SMTP_PORT`, `SMTP_USERNAME`, `SMTP_PASSWORD`, `SMTP_TLS`, `SMTP_SSL`, `SMTP_AUTH` | outgoing mail (login links, trip invites), as in the sibling apps; without `SMTP_RELAY`, mail is only logged |
79 79 | `MAIL_FROM_NAME`, `MAIL_FROM_ADDRESS` | who mail comes from (default `noreply@<PHX_HOST>`) |
80 +| `ANDROID_CERT_FINGERPRINTS` | the Android app's signing-cert SHA-256s, for `/.well-known/assetlinks.json` (docs/app-login.md) |
81 +| `APP_LOGIN_REDIRECT_URI`, `APP_LOGIN_OIDC_PROVIDER` | SSO from the Android app: where its code goes (default `cartosnap://auth`; empty turns it off) and which provider |
82 +
83 +## The Android app's log-in
84 +
85 +The Android app (`android/`) signs in by pairing (the code from Settings →
86 +Connected devices), by NEIAM (OIDC in the system browser, with PKCE), or by
87 +email (a sign-in link, or a password). Emailed sign-in links open the app
88 +when it is installed. The API, the security decisions and the deploy notes
89 +are in [docs/app-login.md](docs/app-login.md).
80 90
81 91 ## Clustering
82 92
deleted android/app/src/main/java/org/neiam/cartosnap/app/ui/PairScreen.kt
+0 −129
@@ -1,129 +0,0 @@
1 −package org.neiam.cartosnap.app.ui
2 −
3 −import android.os.Build
4 −import androidx.compose.foundation.layout.Arrangement
5 −import androidx.compose.foundation.layout.Column
6 −import androidx.compose.foundation.layout.fillMaxSize
7 −import androidx.compose.foundation.layout.fillMaxWidth
8 −import androidx.compose.foundation.layout.imePadding
9 −import androidx.compose.foundation.layout.padding
10 −import androidx.compose.foundation.layout.safeDrawingPadding
11 −import androidx.compose.foundation.text.KeyboardOptions
12 −import androidx.compose.material3.Button
13 −import androidx.compose.material3.CircularProgressIndicator
14 −import androidx.compose.material3.MaterialTheme
15 −import androidx.compose.material3.OutlinedTextField
16 −import androidx.compose.material3.Surface
17 −import androidx.compose.material3.Text
18 −import androidx.compose.runtime.Composable
19 −import androidx.compose.runtime.getValue
20 −import androidx.compose.runtime.mutableStateOf
21 −import androidx.compose.runtime.remember
22 −import androidx.compose.runtime.rememberCoroutineScope
23 −import androidx.compose.runtime.setValue
24 −import androidx.compose.ui.Modifier
25 −import androidx.compose.ui.text.font.FontFamily
26 −import androidx.compose.ui.text.input.ImeAction
27 −import androidx.compose.ui.text.input.KeyboardCapitalization
28 −import androidx.compose.ui.text.input.KeyboardType
29 −import androidx.compose.ui.platform.LocalContext
30 −import androidx.compose.ui.unit.dp
31 −import kotlinx.coroutines.Dispatchers
32 −import kotlinx.coroutines.launch
33 −import kotlinx.coroutines.withContext
34 −import org.neiam.cartosnap.app.BuildConfig
35 −import org.neiam.cartosnap.app.data.Api
36 −import org.neiam.cartosnap.app.data.ApiError
37 −import org.neiam.cartosnap.app.data.Session
38 −import org.neiam.cartosnap.app.data.normalizeServer
39 −import org.neiam.cartosnap.app.upload.QueuedPhoto
40 −import org.neiam.cartosnap.app.upload.Uploads
41 −
42 −/**
43 − * Pairing: the server and a code from the web's Settings → Connected
44 − * devices, traded for this device's key. Anything waiting from before
45 − * goes up once it's paired.
46 − */
47 −@Composable
48 −fun PairScreen(session: Session, onPaired: (Session.Credentials) -> Unit) {
49 − val context = LocalContext.current
50 − val scope = rememberCoroutineScope()
51 − var server by remember { mutableStateOf(BuildConfig.DEFAULT_SERVER) }
52 − var code by remember { mutableStateOf("") }
53 − var busy by remember { mutableStateOf(false) }
54 − var error by remember { mutableStateOf<String?>(null) }
55 −
56 − fun pair() {
57 − val base = normalizeServer(server)
58 − busy = true
59 − error = null
60 − scope.launch {
61 − try {
62 − val paired = withContext(Dispatchers.IO) {
63 − Api(base).pair(code.trim(), "${Build.MANUFACTURER} ${Build.MODEL}".trim())
64 − }
65 − val credentials = Session.Credentials(base, paired.token, paired.user.name)
66 − session.signIn(credentials)
67 − withContext(Dispatchers.IO) {
68 − Uploads.queue(context).requeue(QueuedPhoto.State.NEEDS_PAIRING)
69 − }
70 − Uploads.kick(context)
71 − onPaired(credentials)
72 − } catch (e: ApiError) {
73 − error = e.message
74 − } catch (e: Exception) {
75 − error = "Couldn't reach $base. Check the address and your connection."
76 − } finally {
77 − busy = false
78 − }
79 − }
80 − }
81 −
82 − Surface(Modifier.fillMaxSize()) {
83 − Column(
84 − Modifier.safeDrawingPadding().imePadding().padding(24.dp),
85 − verticalArrangement = Arrangement.spacedBy(16.dp),
86 − ) {
87 − Text("CartoSnap", style = MaterialTheme.typography.headlineMedium)
88 − Text(
89 − "Pair this phone with your account to share photos straight into your trips.",
90 − style = MaterialTheme.typography.bodyLarge,
91 − )
92 − Text(
93 − "On the web, open Settings → Connected devices → Pair a device, and enter what it shows.",
94 − style = MaterialTheme.typography.bodyMedium,
95 − )
96 − OutlinedTextField(
97 − value = server,
98 − onValueChange = { server = it },
99 − label = { Text("Server") },
100 − singleLine = true,
101 − keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Next),
102 − modifier = Modifier.fillMaxWidth(),
103 − )
104 − OutlinedTextField(
105 − value = code,
106 − onValueChange = { code = it.uppercase().take(12) },
107 − label = { Text("Pairing code") },
108 − placeholder = { Text("XK4F-9TQ2") },
109 − singleLine = true,
110 − textStyle = MaterialTheme.typography.titleLarge.copy(fontFamily = FontFamily.Monospace),
111 − keyboardOptions = KeyboardOptions(
112 − capitalization = KeyboardCapitalization.Characters,
113 − autoCorrectEnabled = false,
114 − keyboardType = KeyboardType.Ascii,
115 − imeAction = ImeAction.Done,
116 − ),
117 − modifier = Modifier.fillMaxWidth(),
118 − )
119 − error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
120 − Button(
121 − onClick = ::pair,
122 − enabled = !busy && server.isNotBlank() && code.count { it.isLetterOrDigit() } >= 8,
123 − modifier = Modifier.fillMaxWidth(),
124 − ) {
125 − if (busy) CircularProgressIndicator(Modifier.padding(2.dp)) else Text("Pair")
126 − }
127 − }
128 − }
129 −}
modified config/config.exs
+15 −0
@@ -20,6 +20,21 @@ config :neiam_auth,
20 20 user_schema: CartosnapApp.Accounts.User,
21 21 adapter: CartosnapApp.NeiamAuthAdapter
22 22
23 +# The Android app's sign-in (neiam_auth's NeiamAuth.App, docs/app-login.md):
24 +# its name, the package /.well-known/assetlinks.json vouches for (the
25 +# signing-cert fingerprints come from ANDROID_CERT_FINGERPRINTS at runtime),
26 +# and the app's scheme an SSO sign-in hands its one-time code to
27 +# (APP_LOGIN_REDIRECT_URI overrides it; empty turns SSO from the app off).
28 +config :neiam_auth, :app,
29 + app_name: "CartoSnap",
30 + android_package: "org.neiam.cartosnap.app",
31 + redirect_uri: "cartosnap://auth"
32 +
33 +# Credentials in request params stay out of the logs: passwords, magic-link,
34 +# invite and share tokens, pairing codes, the SSO callback's code and the
35 +# app's PKCE verifier.
36 +config :phoenix, :filter_parameters, ["password", "token", "code", "code_verifier"]
37 +
23 38 config :cartosnap_app, :scopes,
24 39 user: [
25 40 default: true,
added docs/app-login.md
+178 −0
@@ -0,0 +1,178 @@
1 +# Android log-in and App Links
2 +
3 +The Android app's log-in page and the `/api/v1/auth/*` API behind it. The
4 +shapes are shared with every NEIAM app (Elixir and Rust), so all their
5 +Android apps sign in the same way. The shared server parts live in
6 +neiam_auth (`NeiamAuth.App`, v0.5.0).
7 +
8 +## The log-in page
9 +
10 +- A header band (22% of the height; a left column in landscape) with the
11 + app's name, "login" under it, and a `?` that opens Help.
12 +- Three equal buttons share the rest: **Pair**, **OIDC** ("Sign in with
13 + NEIAM") and **Username**. Each opens its flow in a bottom sheet. Back or a
14 + swipe down closes it. Back from the page leaves the app.
15 +- A method the server has turned off is greyed out, with the server's
16 + reason (`GET /api/v1/auth/methods`).
17 +- **Pair** is the existing pairing, unchanged: Settings → Connected devices
18 + → Pair a device on the web shows the server and a code like `XK4F-9TQ2`,
19 + which the app trades for its device key (`POST /api/v1/pair`). CartoSnap
20 + has no QR code, so this sheet takes the two typed in; it is the shared
21 + page's "Scan" sheet, without the camera.
22 +- **OIDC** opens the IdP in a Custom Tab (the system browser, never a
23 + WebView), with PKCE. See [SSO](#sso-from-the-app).
24 +- **Username**: the email, with "Email me a sign-in link" first. Below it
25 + are a password field and "Sign in", for accounts that have set a password
26 + (Settings on the web).
27 +- **Help** explains each way in, where the pairing code is, that emailed
28 + sign-in links open the app, and the server in use (which can be changed
29 + there).
30 +
31 +The code is `android/app/src/main/java/org/neiam/cartosnap/app/auth/login/`.
32 +It is the same as in the other NEIAM apps except the package name and the
33 +Pair sheet (code instead of QR). The app's own glue is
34 +`auth/CartosnapLoginHost.kt`.
35 +
36 +## API
37 +
38 +All under `/api/v1`. A sign-in answers with a device key: the same key
39 +pairing yields (`Accounts.create_api_token/2`), labelled with the device's
40 +name. It is listed and can be unpaired under Settings → Connected devices,
41 +and lapses after 90 days unused, as a paired one.
42 +
43 +```json
44 +{"token": "...", "token_type": "Bearer", "user": {"id": "...", "email": "..."}}
45 +```
46 +
47 +Errors are `{"error": "<code>", "message": "..."}`, and every answer is
48 +`Cache-Control: no-store`, exactly as the Rust apps' (neiam-auth v0.6.0).
49 +(The rest of the app API keeps its own `{"error": {"code", "message"}}`.)
50 +
51 +| Endpoint | Body | Answers |
52 +|---|---|---|
53 +| `GET /auth/methods` | | `{app_name, server, scan, oidc: {enabled, label, provider, login_path}, password, magic_link, login_mode, reasons}` |
54 +| `POST /auth/password` | `{username_or_email, password, device_name}` (`login` is taken too) | 200 key; 401 `invalid_credentials` (the same for an unknown email and a wrong password, and at least 400 ms either way); 403 `refused` (must use SSO) / `password_login_off` (sso_strict); 400 `bad_request`; 429 `rate_limited` |
55 +| `POST /auth/magic_link` | `{email}` | 202, always the same neutral answer; 403 `password_login_off`; 429 |
56 +| `POST /auth/magic_link/exchange` | `{token, device_name}` | 200 key (plus `confirmed: true` when the link confirmed the account); 400 `invalid_link`; 403 `refused` / `unconfirmed` / `password_login_off`; 429 |
57 +| `POST /auth/magic_link/check` (device key) | `{token}` | `{valid, same_user}`; never spends the link |
58 +| `POST /auth/oidc/exchange` | `{code, code_verifier, device_name}` | 200 key; 400 `invalid_grant` / `bad_request`; 429 |
59 +| `GET /.well-known/assetlinks.json` (site root) | | the Digital Asset Links statement |
60 +
61 +`POST /pair`, `GET /me` and `PUT`/`DELETE /device` are unchanged.
62 +
63 +### What each path checks
64 +
65 +They make exactly the web's checks, with the web's own functions
66 +(`UserSessionController`, `UserLive.Login`):
67 +
68 +- **Login mode** (neiam_auth): password and magic links are off under
69 + `OIDC_LOGIN_MODE=sso_strict` (`NeiamAuth.local_login_enabled?/0`). Under
70 + `sso`, an account linked to a `REQUIRED_FOR_LINKED` provider is refused
71 + once it is identified (`NeiamAuth.password_login_allowed?/1`, through
72 + `CartosnapApp.NeiamAuthAdapter.sso_required?/1`, which has no rule of its
73 + own).
74 +- **Password**: `Accounts.get_user_by_email_and_password/2`, as the web
75 + log-in (an unknown email still costs a dummy hash). Confirmation isn't
76 + checked, as on the web: an account only gets a password from Settings,
77 + after it was confirmed. CartoSnap has no 2FA and no admin or guest rule.
78 +- **Magic-link request**: the web form's email (`deliver_login_instructions`
79 + with the web's own `/users/log-in/:token` URL), and the same rules:
80 + nothing is sent to an unknown account or one that must use SSO, and the
81 + answer doesn't say which.
82 +- **Magic-link exchange**: `Accounts.login_user_by_magic_link/1`, the web's
83 + own. The link is single-use and expires as on the web. Following it
84 + confirms an unconfirmed account, which expires that account's other
85 + sessions and keys as on the web (`UserAuth.disconnect_sessions/1`). The
86 + login mode is checked before the token is spent, so a refused link stays
87 + usable. An unconfirmed account that has a password (phx.gen.auth raises
88 + there) is refused with `unconfirmed`.
89 +- **Registration** stays invite-only: none of these make an account. SSO
90 + from the app follows `CartosnapApp.NeiamAuthAdapter` as the web does
91 + (`OIDC_PROVISION`, `OIDC_PROVISION_GROUPS`); a login refused as not
92 + invited shows the refusal in the browser tab, and the invite flow stays
93 + on the web.
94 +- **Rate limits** (`NeiamAuth.App.rate_limit/3`, per node; the Rust
95 + crate's): password 20 per IP and 5 per account per 15 min; each exchange
96 + 30 per IP per 15 min; magic-link requests 10 per IP and 5 per account per
97 + 15 min. CartoSnap had no limiter of its own.
98 +- Passwords, tokens, codes and verifiers are kept out of the logs
99 + (`:filter_parameters` in config/config.exs).
100 +
101 +## Magic links in the app
102 +
103 +The email is the web's normal one. Its link,
104 +`https://cs.neiam.org/users/log-in/<token>`, is a verified App Link. App
105 +Links name their host in the manifest, so this works for the production
106 +server, **cs.neiam.org**, only; with any other server the app signs in by
107 +pairing, SSO or password, and its emailed links open in the browser as
108 +before.
109 +
110 +- App installed and verified: the link opens the app. Signed out, the app
111 + signs in and goes home. Signed in as the same user, it just goes home
112 + (`/auth/magic_link/check`). Signed in as someone else, it asks first.
113 +- An expired or used link shows "This sign-in link has expired or was
114 + already used", with **Email me a new link**.
115 +- App not installed, or the email opened on a computer: the link opens the
116 + website and works exactly as before. Nothing about the web flow changed.
117 +
118 +Magic links only ever as App Links, never a custom scheme: the token is a
119 +credential by itself. The app never fetches or prefetches a link; it acts
120 +only when the user opens one.
121 +
122 +## SSO from the app
123 +
124 +1. The app makes a PKCE verifier and S256 challenge and opens a Custom Tab
125 + at `/auth/oidc/neiam/login?app=1&challenge=<S256>&device_name=<name>`.
126 +2. The usual OIDC flow runs, with the usual redirect URI
127 + (`https://cs.neiam.org/auth/oidc/neiam/callback`, `OIDC_REDIRECT_URI` in
128 + the deployment). **Authelia needs no change.**
129 +3. The callback starts no web session. neiam_auth stores a one-time code
130 + (random, SHA-256 at rest, bound to the user and the challenge, 2 minutes)
131 + and redirects to `cartosnap://auth?code=...`, the app's own scheme. A
132 + refusal shows an error page in the browser tab instead.
133 +4. The app posts the code and its verifier to `/auth/oidc/exchange`, on the
134 + server the sign-in was started on. The code works once. An expired code
135 + or a wrong verifier is refused, and a wrong verifier burns the code.
136 +
137 +A custom scheme, as in the Rust apps, because the app talks to whichever
138 +server the user picked, and an App Link must name its host at build time.
139 +Another app claiming `cartosnap://` would get a code it can't spend: the
140 +PKCE verifier never leaves this app.
141 +
142 +## Deploying
143 +
144 +- **Migration**: `create_neiam_auth_app_codes` (neiam_auth v0.5.0). It runs
145 + with the release's usual migrate step.
146 +- **Env**:
147 + - `ANDROID_CERT_FINGERPRINTS`: the SHA-256 fingerprint(s) of the APK
148 + signing certificate(s), comma-separated. Without it,
149 + `/.well-known/assetlinks.json` is `[]` and every link opens in the
150 + browser, as before. Get it from the release keystore (the CI secret
151 + `ANDROID_KEYSTORE`, see android/README.md):
152 +
153 + ```sh
154 + keytool -list -v -keystore release.jks | grep SHA256
155 + ```
156 +
157 + Add the debug key's fingerprint (`~/.android/debug.keystore`) too while
158 + testing debug builds.
159 + - `APP_LOGIN_REDIRECT_URI` (optional): where SSO in the app hands its
160 + code over; default `cartosnap://auth` (config/config.exs). Empty turns
161 + SSO in the app off. `APP_LOGIN_OIDC_PROVIDER` (optional): the provider
162 + the app's button uses; default the first one.
163 + - `OIDC_*`, `CARTOSNAP_PUBLIC_URL` (the `server` in `/auth/methods`, as
164 + in the pairing panel) and the mail settings are as before; without
165 + `SMTP_RELAY` the app's "Email me a sign-in link" is off.
166 + `ANDROID_APP_PACKAGE` is optional (the package is set in
167 + config/config.exs).
168 +- **Ingress**: `/.well-known/assetlinks.json` must reach Phoenix at
169 + `https://cs.neiam.org/.well-known/assetlinks.json`, over HTTPS, with no
170 + redirect and no auth in front. The existing catch-all ingress for the host
171 + (path `/`) does that.
172 +- **Authelia**: nothing. The app reuses the web's redirect URI.
173 +- **Android**: the App Link host is `appLinksHost` in
174 + `android/app/build.gradle.kts` (`cs.neiam.org`). It is also the default
175 + server of a fresh install.
176 +- **Verifying**: after installing a release build,
177 + `adb shell pm get-app-links org.neiam.cartosnap.app` should say `verified`
178 + for `cs.neiam.org`.
modified lib/cartosnap_app/accounts.ex
+31 −0
@@ -537,6 +537,37 @@ defmodule CartosnapApp.Accounts do
537 537 encoded
538 538 end
539 539
540 + @doc """
541 + Signs the app in: a device key, exactly as pairing makes one
542 + (`create_api_token/2`, labelled with the device name), in the body every
543 + `/api/v1/auth/*` sign-in answers with. `method` (`:password`,
544 + `:magic_link`, `:oidc`) is for the caller; the key is the same.
545 + Used by `CartosnapAppWeb.Api.V1.AuthController` and
546 + `NeiamAuth.App.ExchangePlug`.
547 + """
548 + def issue_app_token(%User{} = user, device_name, _method) do
549 + token = create_api_token(user, device_name)
550 +
551 + {:ok,
552 + %{
553 + token: token,
554 + token_type: "Bearer",
555 + user: %{id: user.id, email: user.email}
556 + }}
557 + end
558 +
559 + @doc """
560 + Whether mail actually leaves the server. Without SMTP_RELAY the mailer
561 + only logs (config/runtime.exs), so the app hides the "Email me a sign-in
562 + link" button.
563 + """
564 + def mail_configured? do
565 + Application.get_env(:cartosnap_app, CartosnapApp.Mailer, [])[:adapter] not in [
566 + nil,
567 + Swoosh.Adapters.Logger
568 + ]
569 + end
570 +
540 571 @doc """
541 572 The user a device key belongs to, and the key's id, or nil when it's
542 573 unknown, revoked or lapsed. Each use (at most daily) extends it.
added lib/cartosnap_app_web/api/v1/auth_controller.ex
+224 −0

Click to load diff…

modified lib/cartosnap_app_web/router.ex
+19 −0

Click to load diff…

modified mix.exs
+1 −1

Click to load diff…

modified mix.lock
+1 −1

Click to load diff…

added priv/repo/migrations/20261203174050_create_neiam_auth_app_codes.exs
+23 −0

Click to load diff…

added test/cartosnap_app_web/api/v1/auth_controller_test.exs
+530 −0

Click to load diff…

added test/cartosnap_app_web/assetlinks_test.exs
+29 −0

Click to load diff…

Parents: b6f7c30