diff --git a/CHANGELOG.md b/CHANGELOG.md index df805c56a..052f5c305 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ ## [Unreleased] +### Added + +- **Measurement tokens can log custom-metric values.** A script or a + Home Assistant rule holding a measurement token can now post a value + to `POST /api/custom-metrics/{id}/entries` for a custom metric you + already created. The token still cannot list, read, create, change or + delete custom metrics or their values, and a metric of another account + answers 404. A metric's ID is the part after `/custom-metrics/` in the + address of its page, and the token card in Settings says so. Values + posted this way are not marked as coming from an external device; the + audit log records which token wrote them. Measurement tokens you + already have can do this too, without being created again. (#1377) + ### Fixed - **Opening a record on a phone.** In the account menu, "Open a record" diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml index b5974f168..803f6797f 100644 --- a/docs/api/openapi.yaml +++ b/docs/api/openapi.yaml @@ -3617,21 +3617,24 @@ paths: the only place it ever exists; it is stored as an HMAC and no path re-reveals it. - **What it can do.** `POST /api/measurements` and `POST /api/measurements/batch`, on its owner's own record. Rows - it writes carry `source: EXTERNAL`, resolved from the credential rather than taken from the body, so a reading - pushed by a bridge stays distinguishable from one typed in by hand and can be picked out with the source filter. - A body naming ANY source is refused 422 rather than relabelled — honouring it would defeat the label, overriding - it silently would hand the caller rows it did not ask for. `APPLE_HEALTH` is the one that would do real damage: - it is half a dedup key the phone also writes into, it participates in the cross-source merge, and it is what + **What it can do.** `POST /api/measurements` and `POST /api/measurements/batch`, on its owner's own record, and + `POST /api/custom-metrics/{id}/entries` for a custom metric its owner already created (it cannot list, create, + edit or delete metrics, so the id comes from the metric's page in the app). Measurement rows it writes carry + `source: EXTERNAL`, resolved from the credential rather than taken from the body, so a reading pushed by a + bridge stays distinguishable from one typed in by hand and can be picked out with the source filter. A body + naming ANY source is refused 422 rather than relabelled — honouring it would defeat the label, overriding it + silently would hand the caller rows it did not ask for. `APPLE_HEALTH` is the one that would do real damage: it + is half a dedup key the phone also writes into, it participates in the cross-source merge, and it is what decides the Apple Health card may claim a sync happened. For the same reason a write through this credential does not move the native client's sync checkpoint. The rows stay editable by their owner, unlike a connected provider's — the hardware behind the token is the user's own. - **What it cannot do.** Everything else, including the measurement reads on the same paths, the edit and delete - legs, and the export — a scope grants what it names and nothing adjacent. It cannot be pointed at a shared - record: a request carrying the account selector is refused 403 before any grant is read, whatever grants its - holder actually has. And it cannot mint another token, this endpoint included. + **What it cannot do.** Everything else, including the measurement reads on the same paths, the custom-metric + list and value reads, the edit and delete legs, and the export — a scope grants what it names and nothing + adjacent. It cannot be pointed at a shared record: a request carrying the account selector is refused 403 before + any grant is read, whatever grants its holder actually has. And it cannot mint another token, this endpoint + included. Minting requires a COOKIE SESSION with a fresh proof: a sign-in or `POST /api/auth/reproof` within the last five @@ -21140,7 +21143,19 @@ paths: tags: - Custom metrics summary: Log a value - description: Records a value against the custom metric, snapshotting the metric's unit. Audits as `customMetricEntry.create`. + description: >- + Records a value against the custom metric, snapshotting the metric's unit. Audits as `customMetricEntry.create`. + + + **Narrow token.** Also reachable with a `measurements:write` Bearer (minted at `POST /api/tokens/measurements`), + the supported way to push a custom metric's value from a script or a home-automation rule. Such a credential + writes only to its owner's own live metrics: an id that is unknown, deleted, or another account's answers the + same 404, and a request carrying the account selector is refused 403 before any sharing grant is read. This POST + is all the scope reaches on custom metrics. The value list on this same path, the metric list, and creating, + editing or deleting a metric or a value name no scope and refuse it 403, so the metric id has to come from its + owner: it is the path segment after `/custom-metrics/` in the address of the metric's page in the app. The entry + carries no source of its own; the audit row names the token that wrote it. Every other narrow token, + `workouts:write` included, is refused 403. parameters: - in: path name: id diff --git a/messages/de.json b/messages/de.json index 3d4b52554..f20b0b617 100644 --- a/messages/de.json +++ b/messages/de.json @@ -6992,9 +6992,9 @@ "apiTokensDescription": "Tokens für Messwerte, Trainings, Dokumente und Medikamenten-Einnahme prüfen und widerrufen.", "measurementsToken": { "title": "Messwert-Tokens", - "description": "Erzeuge ein Token, damit eine Waage, eine Uhr oder deine Hausautomatisierung Werte eintragen kann.", + "description": "Erzeuge ein Token, damit eine Waage, eine Uhr oder deine Hausautomatisierung Messwerte und Werte deiner eigenen Metriken eintragen kann.", "detail": "Das Token wird nur einmal angezeigt.", - "scopeNote": "Es kann ausschließlich neue Werte in deine eigene Akte eintragen. Es kann deine Daten nicht lesen, nichts ändern oder löschen und kein weiteres Token erstellen. Werte werden als von einem externen Gerät gekennzeichnet, damit du sie später erkennst, und lassen sich jederzeit korrigieren.", + "scopeNote": "Es kann ausschließlich neue Werte in deine eigene Akte eintragen, auch für eigene Metriken, die du bereits angelegt hast. Es kann deine Daten nicht lesen, keine Metrik anlegen, nichts ändern oder löschen und kein weiteres Token erstellen. Messwerte werden als von einem externen Gerät gekennzeichnet, damit du sie später erkennst; Werte eigener Metriken tragen keine solche Kennzeichnung. Beides lässt sich jederzeit korrigieren. Die ID einer eigenen Metrik ist der Teil nach /custom-metrics/ in der Adresse ihrer Seite.", "createFailed": "Das Token konnte nicht erstellt werden. Bitte versuche es erneut.", "namePlaceholder": "Name, z. B. Home Assistant", "appleHealth": { diff --git a/messages/en.json b/messages/en.json index 3c2d410d5..eb5be78e0 100644 --- a/messages/en.json +++ b/messages/en.json @@ -6992,9 +6992,9 @@ "apiTokensDescription": "Review and revoke tokens for measurements, workouts, documents and medication intake.", "measurementsToken": { "title": "Measurement tokens", - "description": "Mint a token so a scale, a watch bridge or your home automation can add readings.", + "description": "Mint a token so a scale, a watch bridge or your home automation can add readings and custom-metric values.", "detail": "The token is shown once.", - "scopeNote": "It can only add new readings to your own record. It cannot read your data, change or delete anything, or create another token. Readings are marked as coming from an external device, so you can tell them apart later, and you can still correct them yourself.", + "scopeNote": "It can only add new readings to your own record, and values to custom metrics you already created. It cannot read your data, create a custom metric, change or delete anything, or create another token. Readings are marked as coming from an external device, so you can tell them apart later; custom-metric values carry no such mark. You can still correct both yourself. A custom metric's ID is the part after /custom-metrics/ in the address of its page.", "createFailed": "The token could not be created. Please try again.", "namePlaceholder": "Name, e.g. Home Assistant", "appleHealth": { diff --git a/messages/es.json b/messages/es.json index a51d8607e..775344b65 100644 --- a/messages/es.json +++ b/messages/es.json @@ -6992,9 +6992,9 @@ "apiTokensDescription": "Revisa y revoca los tokens de mediciones, entrenamientos, documentos y tomas de medicación.", "measurementsToken": { "title": "Tokens de mediciones", - "description": "Crea un token para que una báscula, un reloj o tu domótica añadan mediciones.", + "description": "Crea un token para que una báscula, un reloj o tu domótica añadan mediciones y valores de tus métricas personalizadas.", "detail": "El token se muestra una sola vez.", - "scopeNote": "Solo puede añadir mediciones nuevas a tu propio historial: no puede leer tus datos, ni modificar o borrar nada, ni crear otro token. Las mediciones se marcan como procedentes de un dispositivo externo, así las distingues más tarde, y puedes corregirlas igualmente.", + "scopeNote": "Solo puede añadir mediciones nuevas a tu propio historial y valores a las métricas personalizadas que ya creaste: no puede leer tus datos, ni crear una métrica, ni modificar o borrar nada, ni crear otro token. Las mediciones se marcan como procedentes de un dispositivo externo, así las distingues más tarde; los valores de las métricas personalizadas no llevan esa marca. Puedes corregir ambos igualmente. El ID de una métrica personalizada es la parte que sigue a /custom-metrics/ en la dirección de su página.", "createFailed": "No se pudo crear el token. Inténtalo de nuevo.", "namePlaceholder": "Nombre, p. ej. Home Assistant", "appleHealth": { diff --git a/messages/fr.json b/messages/fr.json index 0e8816535..a975e27db 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -6992,9 +6992,9 @@ "apiTokensDescription": "Consultez et révoquez les jetons des mesures, entraînements, documents et prises de médicaments.", "measurementsToken": { "title": "Jetons de mesures", - "description": "Créez un jeton pour qu'une balance, une montre ou votre domotique ajoutent des mesures.", + "description": "Créez un jeton pour qu'une balance, une montre ou votre domotique ajoutent des mesures et des valeurs à vos mesures personnalisées.", "detail": "Le jeton n'est affiché qu'une fois.", - "scopeNote": "Il peut uniquement ajouter de nouvelles mesures à votre propre dossier : il ne peut pas lire vos données, ni modifier ou supprimer quoi que ce soit, ni créer un autre jeton. Les mesures sont signalées comme provenant d'un appareil externe, ce qui vous permet de les reconnaître plus tard, et vous pouvez toujours les corriger.", + "scopeNote": "Il peut uniquement ajouter de nouvelles mesures à votre propre dossier, ainsi que des valeurs aux mesures personnalisées que vous avez déjà créées : il ne peut pas lire vos données, ni créer une mesure personnalisée, ni modifier ou supprimer quoi que ce soit, ni créer un autre jeton. Les mesures sont signalées comme provenant d'un appareil externe, ce qui vous permet de les reconnaître plus tard ; les valeurs des mesures personnalisées ne portent pas cette marque. Vous pouvez toujours corriger les unes comme les autres. L'identifiant d'une mesure personnalisée est la partie qui suit /custom-metrics/ dans l'adresse de sa page.", "createFailed": "Le jeton n'a pas pu être créé. Veuillez réessayer.", "namePlaceholder": "Nom, p. ex. Home Assistant", "appleHealth": { diff --git a/messages/it.json b/messages/it.json index f73de41b3..d74b13623 100644 --- a/messages/it.json +++ b/messages/it.json @@ -6992,9 +6992,9 @@ "apiTokensDescription": "Rivedi e revoca i token per misurazioni, allenamenti, documenti e assunzioni di farmaci.", "measurementsToken": { "title": "Token per misurazioni", - "description": "Crea un token perché una bilancia, un orologio o la tua domotica aggiungano misurazioni.", + "description": "Crea un token perché una bilancia, un orologio o la tua domotica aggiungano misurazioni e valori delle tue metriche personalizzate.", "detail": "Il token viene mostrato una sola volta.", - "scopeNote": "Può soltanto aggiungere nuove misurazioni alla tua cartella: non può leggere i tuoi dati, modificare o eliminare nulla, né creare un altro token. Le misurazioni vengono contrassegnate come provenienti da un dispositivo esterno, così le riconosci in seguito, e puoi comunque correggerle.", + "scopeNote": "Può soltanto aggiungere nuove misurazioni alla tua cartella e valori alle metriche personalizzate che hai già creato: non può leggere i tuoi dati, creare una metrica, modificare o eliminare nulla, né creare un altro token. Le misurazioni vengono contrassegnate come provenienti da un dispositivo esterno, così le riconosci in seguito; i valori delle metriche personalizzate non hanno questo contrassegno. Puoi comunque correggere entrambi. L'ID di una metrica personalizzata è la parte che segue /custom-metrics/ nell'indirizzo della sua pagina.", "createFailed": "Non è stato possibile creare il token. Riprova.", "namePlaceholder": "Nome, ad es. Home Assistant", "appleHealth": { diff --git a/messages/ko.json b/messages/ko.json index 5f1f95d9b..fc0e19afb 100644 --- a/messages/ko.json +++ b/messages/ko.json @@ -6992,9 +6992,9 @@ "apiTokensDescription": "측정값, 운동, 문서, 복용 기록용 토큰을 확인하고 폐기해요.", "measurementsToken": { "title": "측정 토큰", - "description": "체중계나 시계, 홈 오토메이션이 측정값을 기록할 수 있도록 토큰을 만들어요.", + "description": "체중계나 시계, 홈 오토메이션이 측정값과 사용자 지표 값을 기록할 수 있도록 토큰을 만들어요.", "detail": "토큰은 한 번만 표시돼요.", - "scopeNote": "본인 기록에 새 측정값을 추가하는 것만 할 수 있어요. 데이터를 읽거나, 무언가를 고치거나 지우거나, 다른 토큰을 만들 수는 없어요. 측정값은 외부 기기에서 온 것으로 표시되니 나중에 구분할 수 있고, 언제든 고칠 수 있어요.", + "scopeNote": "본인 기록에 새 측정값을 추가하고, 이미 만든 사용자 지표에 값을 추가하는 것만 할 수 있어요. 데이터를 읽거나, 사용자 지표를 만들거나, 무언가를 고치거나 지우거나, 다른 토큰을 만들 수는 없어요. 측정값은 외부 기기에서 온 것으로 표시되어 나중에 구분할 수 있지만, 사용자 지표 값에는 이런 표시가 없어요. 둘 다 언제든 고칠 수 있어요. 사용자 지표의 ID는 해당 지표 페이지 주소에서 /custom-metrics/ 뒤에 오는 부분이에요.", "createFailed": "토큰을 만들지 못했어요. 다시 시도해 주세요.", "namePlaceholder": "이름 (예: Home Assistant)", "appleHealth": { diff --git a/messages/nl.json b/messages/nl.json index a0d5d7cd3..568855935 100644 --- a/messages/nl.json +++ b/messages/nl.json @@ -6992,9 +6992,9 @@ "apiTokensDescription": "Bekijk tokens voor metingen, trainingen, documenten en medicatie-inname en trek ze in.", "measurementsToken": { "title": "Metingtokens", - "description": "Maak een token aan zodat een weegschaal, een horlogekoppeling of je domotica metingen kan toevoegen.", + "description": "Maak een token aan zodat een weegschaal, een horlogekoppeling of je domotica metingen en waarden voor je eigen metingen kan toevoegen.", "detail": "Het token wordt één keer getoond.", - "scopeNote": "Het kan alleen nieuwe metingen aan je eigen dossier toevoegen. Het kan je gegevens niet lezen, niets wijzigen of verwijderen en geen ander token aanmaken. Metingen worden gemarkeerd als afkomstig van een extern apparaat, zodat je ze later kunt onderscheiden, en je kunt ze nog steeds zelf corrigeren.", + "scopeNote": "Het kan alleen nieuwe metingen aan je eigen dossier toevoegen, en waarden aan eigen metingen die je al hebt aangemaakt. Het kan je gegevens niet lezen, geen eigen meting aanmaken, niets wijzigen of verwijderen en geen ander token aanmaken. Metingen worden gemarkeerd als afkomstig van een extern apparaat, zodat je ze later kunt onderscheiden; waarden van eigen metingen krijgen die markering niet. Je kunt beide nog steeds zelf corrigeren. De ID van een eigen meting is het deel na /custom-metrics/ in het adres van de pagina ervan.", "createFailed": "Het token kon niet worden aangemaakt. Probeer het opnieuw.", "namePlaceholder": "Naam, bijv. Home Assistant", "appleHealth": { diff --git a/messages/pl.json b/messages/pl.json index 6be2c1707..53c7e2046 100644 --- a/messages/pl.json +++ b/messages/pl.json @@ -6992,9 +6992,9 @@ "apiTokensDescription": "Przeglądaj i unieważniaj tokeny do pomiarów, treningów, dokumentów i przyjęć leków.", "measurementsToken": { "title": "Tokeny pomiarów", - "description": "Utwórz token, aby waga, zegarek lub automatyka domowa mogły dodawać pomiary.", + "description": "Utwórz token, aby waga, zegarek lub automatyka domowa mogły dodawać pomiary i wartości Twoich metryk własnych.", "detail": "Token pokazujemy tylko raz.", - "scopeNote": "Może wyłącznie dodawać nowe pomiary do Twojej dokumentacji: nie odczyta danych, niczego nie zmieni ani nie usunie i nie utworzy kolejnego tokenu. Pomiary są oznaczane jako pochodzące z urządzenia zewnętrznego, dzięki czemu później je rozpoznasz, i nadal możesz je poprawić.", + "scopeNote": "Może wyłącznie dodawać nowe pomiary do Twojej dokumentacji oraz wartości do już utworzonych metryk własnych: nie odczyta danych, nie utworzy metryki, niczego nie zmieni ani nie usunie i nie utworzy kolejnego tokenu. Pomiary są oznaczane jako pochodzące z urządzenia zewnętrznego, dzięki czemu później je rozpoznasz; wartości metryk własnych nie mają takiego oznaczenia. Jedne i drugie nadal możesz poprawić. Identyfikator metryki własnej to część po /custom-metrics/ w adresie jej strony.", "createFailed": "Nie udało się utworzyć tokenu. Spróbuj ponownie.", "namePlaceholder": "Nazwa, np. Home Assistant", "appleHealth": { diff --git a/messages/pt-BR.json b/messages/pt-BR.json index 8f58fb8a6..1c4729025 100644 --- a/messages/pt-BR.json +++ b/messages/pt-BR.json @@ -6992,9 +6992,9 @@ "apiTokensDescription": "Revise e revogue tokens para medições, treinos, documentos e tomadas de medicamentos.", "measurementsToken": { "title": "Tokens de medição", - "description": "Gere um token para que uma balança, uma ponte de relógio ou sua automação residencial possa adicionar leituras.", + "description": "Gere um token para que uma balança, uma ponte de relógio ou sua automação residencial possa adicionar leituras e valores das suas métricas personalizadas.", "detail": "O token é exibido uma vez.", - "scopeNote": "Ele só pode adicionar novas leituras ao seu próprio registro. Não pode ler seus dados, alterar ou excluir nada, nem criar outro token. As leituras são marcadas como vindas de um dispositivo externo, para você distingui-las depois, e você ainda pode corrigi-las você mesmo.", + "scopeNote": "Ele só pode adicionar novas leituras ao seu próprio registro e valores às métricas personalizadas que você já criou. Não pode ler seus dados, criar uma métrica, alterar ou excluir nada, nem criar outro token. As leituras são marcadas como vindas de um dispositivo externo, para você distingui-las depois; os valores de métricas personalizadas não recebem essa marca. Você ainda pode corrigir ambos. O ID de uma métrica personalizada é a parte depois de /custom-metrics/ no endereço da página dela.", "createFailed": "O token não pôde ser criado. Tente novamente.", "namePlaceholder": "Nome, ex.: Home Assistant", "appleHealth": { diff --git a/messages/ru.json b/messages/ru.json index a6df58670..17c31b407 100644 --- a/messages/ru.json +++ b/messages/ru.json @@ -6992,9 +6992,9 @@ "apiTokensDescription": "Просматривайте и отзывайте токены для измерений, тренировок, документов и приёма лекарств.", "measurementsToken": { "title": "Токены измерений", - "description": "Создайте токен, чтобы весы, мост для часов или ваша система умного дома могли добавлять измерения.", + "description": "Создайте токен, чтобы весы, мост для часов или ваша система умного дома могли добавлять измерения и значения ваших собственных показателей.", "detail": "Токен показывается один раз.", - "scopeNote": "Он может только добавлять новые измерения в вашу собственную историю. Он не может читать ваши данные, изменять или удалять что-либо или создавать другой токен. Измерения помечаются как пришедшие с внешнего устройства, чтобы вы могли отличить их позже, и вы всё равно можете исправить их сами.", + "scopeNote": "Он может только добавлять новые измерения в вашу собственную историю и значения в уже созданные вами собственные показатели. Он не может читать ваши данные, создавать показатели, изменять или удалять что-либо или создавать другой токен. Измерения помечаются как пришедшие с внешнего устройства, чтобы вы могли отличить их позже; значения собственных показателей такой пометки не получают. Вы всё равно можете исправить и то, и другое сами. Идентификатор собственного показателя указан в адресе его страницы после /custom-metrics/.", "createFailed": "Не удалось создать токен. Попробуйте снова.", "namePlaceholder": "Название, например Home Assistant", "appleHealth": { diff --git a/src/__tests__/bearer-scope-enforcement-guard.test.ts b/src/__tests__/bearer-scope-enforcement-guard.test.ts index 8f089e0e6..990bcb1ee 100644 --- a/src/__tests__/bearer-scope-enforcement-guard.test.ts +++ b/src/__tests__/bearer-scope-enforcement-guard.test.ts @@ -430,6 +430,49 @@ describe("T4 — declared scopes are exported constants, never string literals", }); }); +describe("T4a — `measurements:write` opens exactly three doors", () => { + it("the two measurement writes and the custom-metric value write, POST only", () => { + // The set of files naming the scope IS its reach. The single and batch + // measurement writes, and logging a value against a custom metric the + // person already made. Not the measurement reads, not the custom-metric + // list or detail, and not creating, editing or deleting a metric: a + // fourth file here is a widening and belongs in review. + const declaring = sourceFiles().filter((rel) => { + const src = read(rel); + return ( + requireAuthScopes(src).includes("MEASUREMENTS_WRITE_SCOPE") || + recordAuthScopes(src).includes("MEASUREMENTS_WRITE_SCOPE") + ); + }); + expect(declaring).toEqual([ + "app/api/custom-metrics/[id]/entries/route.ts", + "app/api/measurements/batch/route.ts", + "app/api/measurements/route.ts", + ]); + + // Within the custom-metric file, once, and on the POST: the GET beside it + // lists the metric's values and must keep refusing the token. + const entries = readSource( + "src/app/api/custom-metrics/[id]/entries/route.ts", + "MEASUREMENTS_WRITE_SCOPE", + ); + expect( + requireAuthScopes(entries).filter( + (x) => x === "MEASUREMENTS_WRITE_SCOPE", + ), + ).toHaveLength(1); + expect(recordAuthScopes(entries)).toEqual([]); + const postBody = entries.slice( + entries.indexOf("async function postCustomMetricEntry"), + ); + expect( + requireAuthScopes(postBody).filter( + (x) => x === "MEASUREMENTS_WRITE_SCOPE", + ), + ).toHaveLength(1); + }); +}); + describe("T4b — `documents:write` opens exactly two doors", () => { it("only the vault upload and the source-key lookup declare the scope", () => { // The scope admits a narrow token wherever it is named, so the set of diff --git a/src/app/api/custom-metrics/[id]/entries/route.ts b/src/app/api/custom-metrics/[id]/entries/route.ts index d4e9ea3c9..7e0c764f3 100644 --- a/src/app/api/custom-metrics/[id]/entries/route.ts +++ b/src/app/api/custom-metrics/[id]/entries/route.ts @@ -1,6 +1,11 @@ import { NextRequest } from "next/server"; -import { apiHandler, requireAuth, requireRecordAuth } from "@/lib/api-handler"; +import { + apiHandler, + isScopedCredential, + requireAuth, + requireRecordAuth, +} from "@/lib/api-handler"; import { apiError, apiSuccess, @@ -16,6 +21,7 @@ import { encryptNote } from "@/lib/crypto/note-cipher"; import { prisma } from "@/lib/db"; import { withIdempotency } from "@/lib/idempotency"; import { annotate } from "@/lib/logging/context"; +import { MEASUREMENTS_WRITE_SCOPE } from "@/lib/measurements/scopes"; import { createCustomMetricEntrySchema, listCustomMetricEntriesSchema, @@ -28,8 +34,9 @@ import { * GET lists the metric's values with offset pagination (the chart + history * feed). POST records a value, snapshotting the metric's current `unit` onto * the entry at write time (historical truth). `userId` is always narrowed from - * the session and the parent metric is verified owner-scoped (a forged / foreign - * id is a 404) before any value is read or written. + * the session (or, on POST, the measurement-ingest token) and the parent metric + * is verified owner-scoped (a forged / foreign id is a 404) before any value is + * read or written. */ type RouteParams = { params: Promise<{ id: string }> }; @@ -105,7 +112,27 @@ async function postCustomMetricEntry( // product did not offer. Whoever builds a delegate-reachable way to log a // tracked value adds it back in the same diff: the argument for admitting it // was never wrong, and the GET arm above stays delegable meanwhile. - const { user } = await requireAuth(); + // + // It does accept the measurement-ingest token (#1377): a custom metric's + // value is a reading the person defined themselves, and the bridge that + // pushes their weight is the one that would push it. What that admits is + // this POST and nothing beside it. The GET above names no scope, nor do the + // metric's own create / edit / delete routes, so the token can add a value + // to a metric that already exists and cannot list the metrics, read one + // back, or make a new one. The id it writes to comes from the person, who + // reads it off the metric's page; a token that has only ever been pasted + // into a scale's uploader never learns one. + // + // `requireAuth` rather than the record resolver, so the selector refusal is + // the undeclared-mode one every credential meets here: the token is on its + // owner's record or nowhere. The ownership query below then turns any id + // that is not that owner's live metric into the same 404 an unknown id gets. + const auth = await requireAuth(MEASUREMENTS_WRITE_SCOPE); + const { user } = auth; + // A custom-metric entry has no source column, so the row cannot say a + // bridge wrote it the way an `EXTERNAL` measurement does. The audit row + // can, and it names the token, so revoking the right one is possible later. + const ingestTokenId = isScopedCredential(auth) ? auth.session.id : null; const { id } = await params; @@ -156,12 +183,20 @@ async function postCustomMetricEntry( await auditLog("customMetricEntry.create", { userId: user.id, ipAddress: getClientIp(request), - details: { customMetricId: id, entryId: created.id }, + details: { + customMetricId: id, + entryId: created.id, + ...(ingestTokenId ? { ingestTokenId } : {}), + }, }); annotate({ action: { name: "custom-metric.entry.create" }, - meta: { customMetricId: id, entryId: created.id }, + meta: { + customMetricId: id, + entryId: created.id, + via_ingest_scope: ingestTokenId !== null, + }, }); invalidateUserCorrelationPatterns(user.id); diff --git a/src/lib/openapi/routes/auth.ts b/src/lib/openapi/routes/auth.ts index 1af5ecfac..269c79df9 100644 --- a/src/lib/openapi/routes/auth.ts +++ b/src/lib/openapi/routes/auth.ts @@ -2011,8 +2011,8 @@ export const authPaths: NonNullable = { summary: "Mint a measurement-ingest token", description: "Mints a Bearer scoped to exactly `measurements:write` and audits the mint. THE RESPONSE CARRIES THE RAW TOKEN — the only place it ever exists; it is stored as an HMAC and no path re-reveals it.\n\n" + - "**What it can do.** `POST /api/measurements` and `POST /api/measurements/batch`, on its owner's own record. Rows it writes carry `source: EXTERNAL`, resolved from the credential rather than taken from the body, so a reading pushed by a bridge stays distinguishable from one typed in by hand and can be picked out with the source filter. A body naming ANY source is refused 422 rather than relabelled — honouring it would defeat the label, overriding it silently would hand the caller rows it did not ask for. `APPLE_HEALTH` is the one that would do real damage: it is half a dedup key the phone also writes into, it participates in the cross-source merge, and it is what decides the Apple Health card may claim a sync happened. For the same reason a write through this credential does not move the native client's sync checkpoint. The rows stay editable by their owner, unlike a connected provider's — the hardware behind the token is the user's own.\n\n" + - "**What it cannot do.** Everything else, including the measurement reads on the same paths, the edit and delete legs, and the export — a scope grants what it names and nothing adjacent. It cannot be pointed at a shared record: a request carrying the account selector is refused 403 before any grant is read, whatever grants its holder actually has. And it cannot mint another token, this endpoint included.\n\n" + + "**What it can do.** `POST /api/measurements` and `POST /api/measurements/batch`, on its owner's own record, and `POST /api/custom-metrics/{id}/entries` for a custom metric its owner already created (it cannot list, create, edit or delete metrics, so the id comes from the metric's page in the app). Measurement rows it writes carry `source: EXTERNAL`, resolved from the credential rather than taken from the body, so a reading pushed by a bridge stays distinguishable from one typed in by hand and can be picked out with the source filter. A body naming ANY source is refused 422 rather than relabelled — honouring it would defeat the label, overriding it silently would hand the caller rows it did not ask for. `APPLE_HEALTH` is the one that would do real damage: it is half a dedup key the phone also writes into, it participates in the cross-source merge, and it is what decides the Apple Health card may claim a sync happened. For the same reason a write through this credential does not move the native client's sync checkpoint. The rows stay editable by their owner, unlike a connected provider's — the hardware behind the token is the user's own.\n\n" + + "**What it cannot do.** Everything else, including the measurement reads on the same paths, the custom-metric list and value reads, the edit and delete legs, and the export — a scope grants what it names and nothing adjacent. It cannot be pointed at a shared record: a request carrying the account selector is refused 403 before any grant is read, whatever grants its holder actually has. And it cannot mint another token, this endpoint included.\n\n" + "Minting requires a COOKIE SESSION with a fresh proof: a sign-in or `POST /api/auth/reproof` within the last five minutes (with a second factor, on an account that has one), otherwise 401 `auth.reproof.required` with `meta.methods`. No Bearer credential reaches this endpoint at any scope, wildcard included — not because a wildcard lacks the reach, but because of the lifetimes involved: a native access token lives a day and what it could mint here lives a year, so admitting one would let a short-lived compromise leave behind a credential that outlives revoking it. Gated by the operator's instance-wide API switch. Body capped at 16 KiB; 10 mints per user per minute, and at most 10 live tokens held at once. Tokens appear in `GET /api/tokens` and are revoked at `DELETE /api/tokens/{id}` like any other — revoking frees a slot against the ceiling.", requestBody: { required: true, diff --git a/src/lib/openapi/routes/custom-metrics.ts b/src/lib/openapi/routes/custom-metrics.ts index d091a0dd7..0efca7e43 100644 --- a/src/lib/openapi/routes/custom-metrics.ts +++ b/src/lib/openapi/routes/custom-metrics.ts @@ -294,7 +294,8 @@ export const customMetricPaths: NonNullable = { tags: ["Custom metrics"], summary: "Log a value", description: - "Records a value against the custom metric, snapshotting the metric's unit. Audits as `customMetricEntry.create`.", + "Records a value against the custom metric, snapshotting the metric's unit. Audits as `customMetricEntry.create`.\n\n" + + "**Narrow token.** Also reachable with a `measurements:write` Bearer (minted at `POST /api/tokens/measurements`), the supported way to push a custom metric's value from a script or a home-automation rule. Such a credential writes only to its owner's own live metrics: an id that is unknown, deleted, or another account's answers the same 404, and a request carrying the account selector is refused 403 before any sharing grant is read. This POST is all the scope reaches on custom metrics. The value list on this same path, the metric list, and creating, editing or deleting a metric or a value name no scope and refuse it 403, so the metric id has to come from its owner: it is the path segment after `/custom-metrics/` in the address of the metric's page in the app. The entry carries no source of its own; the audit row names the token that wrote it. Every other narrow token, `workouts:write` included, is refused 403.", requestParams: { path: z.object({ id: z.string() }) }, parameters: [idempotencyKeyParameter], requestBody: { diff --git a/tests/integration/bearer-scope-enforcement.test.ts b/tests/integration/bearer-scope-enforcement.test.ts index 551fbdd45..035d0cfb6 100644 --- a/tests/integration/bearer-scope-enforcement.test.ts +++ b/tests/integration/bearer-scope-enforcement.test.ts @@ -457,7 +457,7 @@ describe("B7 — cookie sessions are untouched", () => { }); }); -describe("B8 — the measurement-ingest scope reaches its two routes and no others", () => { +describe("B8 — the measurement-ingest scope reaches its measurement routes and no others", () => { /** * A second account, plus a live, accepted, record-wide grant letting the * token's owner write to it. @@ -948,6 +948,281 @@ describe("B8 — the measurement-ingest scope reaches its two routes and no othe }); }); +describe("B10 — the measurement-ingest scope logs values on its owner's custom metrics (#1377)", () => { + const OTHER_ID = "user-bearer-scope-other"; + + async function seedMetric(userId = USER_ID, name = "Grip strength") { + return getPrismaClient().customMetric.create({ + data: { userId, name, unit: "kg" }, + }); + } + + async function seedOtherAccount(): Promise { + await getPrismaClient().user.create({ + data: { + id: OTHER_ID, + username: "scope-other", + email: "scope-other@example.test", + timezone: "UTC", + }, + }); + } + + function params(id: string) { + return { params: Promise.resolve({ id }) }; + } + + function postValue( + metricId: string, + extraHeaders: Record = {}, + ): NextRequest { + return new NextRequest( + `https://health.example/api/custom-metrics/${metricId}/entries`, + { + method: "POST", + headers: { + authorization: headerJar.get("authorization")!, + "content-type": "application/json", + ...extraHeaders, + }, + body: JSON.stringify({ + value: 41.5, + measuredAt: "2026-11-01T07:00:00.000Z", + }), + } as never, + ); + } + + it("admits the scope on its owner's metric, and the audit row names the token", async () => { + const metric = await seedMetric(); + const raw = await armToken(["measurements:write"], "cmwrite1"); + const { POST } = + await import("@/app/api/custom-metrics/[id]/entries/route"); + + const res = await POST(postValue(metric.id), params(metric.id)); + + expect(res.status).toBe(201); + const row = await getPrismaClient().customMetricEntry.findFirstOrThrow({ + where: { customMetricId: metric.id }, + }); + expect(row.userId).toBe(USER_ID); + expect(row.value).toBe(41.5); + // The metric's unit, snapshotted; the token cannot name one. + expect(row.unit).toBe("kg"); + + // The entry has no source column, so the audit row is what says a bridge + // wrote it — and which token, so the right one can be revoked. + const token = await getPrismaClient().apiToken.findUniqueOrThrow({ + where: { tokenHash: hashToken(raw) }, + }); + const audit = await getPrismaClient().auditLog.findFirstOrThrow({ + where: { action: "customMetricEntry.create", userId: USER_ID }, + }); + expect(JSON.parse(audit.details!)).toMatchObject({ + customMetricId: metric.id, + entryId: row.id, + ingestTokenId: token.id, + }); + }); + + it("a retry under the same Idempotency-Key writes one value", async () => { + const metric = await seedMetric(); + await armToken(["measurements:write"], "cmwrite2"); + const { POST } = + await import("@/app/api/custom-metrics/[id]/entries/route"); + const key = { "idempotency-key": "grip-2026-11-01" }; + + const first = await POST(postValue(metric.id, key), params(metric.id)); + const second = await POST(postValue(metric.id, key), params(metric.id)); + + expect(first.status).toBe(201); + expect(second.status).toBe(201); + const a = (await first.json()) as { data: { id: string } }; + const b = (await second.json()) as { data: { id: string } }; + expect(b.data.id).toBe(a.data.id); + expect(await getPrismaClient().customMetricEntry.count()).toBe(1); + }); + + it("refuses another account's metric id with the same 404 as an unknown one", async () => { + await seedOtherAccount(); + const foreign = await seedMetric(OTHER_ID, "Their metric"); + await armToken(["measurements:write"], "cmwrite3"); + const { POST } = + await import("@/app/api/custom-metrics/[id]/entries/route"); + + const res = await POST(postValue(foreign.id), params(foreign.id)); + const unknown = await POST( + postValue("cm_does_not_exist"), + params("cm_does_not_exist"), + ); + + expect(res.status).toBe(404); + expect(unknown.status).toBe(404); + // Indistinguishable, so the 404 tells a token holder nothing about which + // ids exist on other accounts. + expect((await res.json()).error).toBe((await unknown.json()).error); + // Nothing on the other account, and nothing quietly on the holder's own. + expect(await getPrismaClient().customMetricEntry.count()).toBe(0); + }); + + it("refuses a deleted metric of its own owner", async () => { + const metric = await seedMetric(); + await getPrismaClient().customMetric.update({ + where: { id: metric.id }, + data: { deletedAt: new Date() }, + }); + await armToken(["measurements:write"], "cmwrite4"); + const { POST } = + await import("@/app/api/custom-metrics/[id]/entries/route"); + + const res = await POST(postValue(metric.id), params(metric.id)); + + expect(res.status).toBe(404); + expect(await getPrismaClient().customMetricEntry.count()).toBe(0); + }); + + it.each([ + ["workouts:write"], + ["documents:write"], + ["medication:ingest"], + ["fhir:read"], + ["health:read", "health:write"], + ])( + "still refuses a narrow token that is not the ingest scope: %s", + async (...scopes) => { + const metric = await seedMetric(); + await armToken(scopes, `cmnarrow-${scopes.join("-")}`); + const { POST } = + await import("@/app/api/custom-metrics/[id]/entries/route"); + + const res = await POST(postValue(metric.id), params(metric.id)); + + expect(res.status).toBe(403); + expect(await getPrismaClient().customMetricEntry.count()).toBe(0); + }, + ); + + it("is refused on every other custom-metric leg", async () => { + const metric = await seedMetric(); + const entry = await getPrismaClient().customMetricEntry.create({ + data: { + userId: USER_ID, + customMetricId: metric.id, + value: 40, + unit: "kg", + measuredAt: new Date("2026-10-31T07:00:00.000Z"), + }, + }); + await armToken(["measurements:write"], "cmwrite5"); + const bearer = headerJar.get("authorization")!; + const send = (path: string, method: string, body?: unknown) => + new NextRequest(`https://health.example${path}`, { + method, + headers: { + authorization: bearer, + "content-type": "application/json", + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + } as never); + const base = `/api/custom-metrics/${metric.id}`; + const entryParams = { + params: Promise.resolve({ id: metric.id, entryId: entry.id }), + }; + + const list = await import("@/app/api/custom-metrics/route"); + const one = await import("@/app/api/custom-metrics/[id]/route"); + const values = await import("@/app/api/custom-metrics/[id]/entries/route"); + const single = + await import("@/app/api/custom-metrics/[id]/entries/[entryId]/route"); + const restore = + await import("@/app/api/custom-metrics/[id]/entries/restore/route"); + + const statuses = { + // The list handler takes no request; the Bearer rides `next/headers`. + listMetrics: (await list.GET()).status, + createMetric: ( + await list.POST( + send("/api/custom-metrics", "POST", { name: "New", unit: "x" }), + ) + ).status, + readMetric: (await one.GET(send(base, "GET"), params(metric.id))).status, + editMetric: ( + await one.PATCH(send(base, "PATCH", { unit: "lb" }), params(metric.id)) + ).status, + deleteMetric: (await one.DELETE(send(base, "DELETE"), params(metric.id))) + .status, + listValues: ( + await values.GET(send(`${base}/entries`, "GET"), params(metric.id)) + ).status, + editValue: ( + await single.PATCH( + send(`${base}/entries/${entry.id}`, "PATCH", { value: 1 }), + entryParams, + ) + ).status, + deleteValue: ( + await single.DELETE( + send(`${base}/entries/${entry.id}`, "DELETE"), + entryParams, + ) + ).status, + restoreValues: ( + await restore.POST( + send(`${base}/entries/restore`, "POST", { ids: [entry.id] }), + params(metric.id), + ) + ).status, + }; + + expect(statuses).toEqual({ + listMetrics: 403, + createMetric: 403, + readMetric: 403, + editMetric: 403, + deleteMetric: 403, + listValues: 403, + editValue: 403, + deleteValue: 403, + restoreValues: 403, + }); + // And nothing moved. + const after = await getPrismaClient().customMetric.findUniqueOrThrow({ + where: { id: metric.id }, + }); + expect(after.unit).toBe("kg"); + expect(after.deletedAt).toBeNull(); + expect(await getPrismaClient().customMetric.count()).toBe(1); + const entryAfter = + await getPrismaClient().customMetricEntry.findUniqueOrThrow({ + where: { id: entry.id }, + }); + expect(entryAfter.value).toBe(40); + expect(entryAfter.deletedAt).toBeNull(); + }); + + it("is refused a shared record's metric its holder may genuinely write to", async () => { + await seedOtherAccount(); + await getPrismaClient().accountGrant.create({ + data: { + grantorId: OTHER_ID, + granteeId: USER_ID, + access: "WRITE", + acceptedAt: new Date(), + }, + }); + const shared = await seedMetric(OTHER_ID, "Shared metric"); + await armToken(["measurements:write"], "cmwrite6"); + headerJar.set(ACCOUNT_SELECTOR_HEADER, OTHER_ID); + const { POST } = + await import("@/app/api/custom-metrics/[id]/entries/route"); + + const res = await POST(postValue(shared.id), params(shared.id)); + + expect(res.status).toBe(403); + expect(await getPrismaClient().customMetricEntry.count()).toBe(0); + }); +}); + describe("B9 — the workout-ingest scope reaches the workout batch and nothing else", () => { function postWorkouts(entries: Array>): NextRequest { return new NextRequest("https://health.example/api/workouts/batch", {