diff --git a/.gitignore b/.gitignore index 14f14f1..68b554a 100644 --- a/.gitignore +++ b/.gitignore @@ -56,3 +56,7 @@ gradle.properties COOKIES.txt HTTP_FUNDAMENTALS.txt ROUTING.txt + +# Spec-driven planning files -- kept local +.specify/ +specs/ diff --git a/README.md b/README.md index af1d997..898b00e 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ **Aviary is live โ€” just open it in your browser:** -### ๐Ÿ‘‰ https://aviarist-d300b0c36379.herokuapp.com/login +### ๐Ÿ‘‰ https://aviary.danielibarra.com No install, no setup, nothing to download. Register a username + password and you're in. Everything below is for people who want to *develop* Aviary; if you just want to *use* it, the link above is all you need. @@ -13,8 +13,8 @@ No install, no setup, nothing to download. Register a username + password and yo A multi-user maintenance and flight-hours tracker for general-aviation aircraft owners: - **Service timeline** โ€” track every recurring maintenance item (annual, transponder/pitot-static tests, VOR checks, oil changes, etc.) on a **calendar cycle** (days/months/years) *or* an **engine-hours cycle**. Each row shows last-done, next-due, and live "time left," and a one-click **Complete Maintenance** button rolls the dates and hours forward automatically. -- **Hours tracking** โ€” Hobbs and Tach meters with a manual baseline "floor," so log-book activity can only ever raise the displayed hours, never silently lower them. -- **Log book** โ€” record flights by hand (from/to airport, Hobbs/Tach out and in) **or import a Garmin avionics CSV** and let the app derive block time (oil pressure > 15 psi) and airborne time (groundspeed > 35 kt) for you. +- **Hours tracking** โ€” block time and time in service, each with a manual baseline "floor," so log-book activity can only ever raise the displayed hours, never silently lower them. +- **Log book** โ€” record flights by hand (from/to airport, block time and time in service out and in) **or import a Garmin avionics CSV** and let the app derive block time (oil pressure > 15 psi) and airborne time (groundspeed > 35 kt) for you. - **Aircraft info card** โ€” make/model, tail number, owner, and serial number, editable inline. Each account is fully isolated โ€” its own aircraft, service timeline, flight logs, and custom maintenance descriptions. Ownership is enforced server-side on every write. @@ -24,9 +24,17 @@ Each account is fully isolated โ€” its own aircraft, service timeline, flight lo 1. **Register** at the link above (or **log in**). 2. **Fill in your aircraft info** โ€” make/model, tail number, owner, serial. 3. **Build your service timeline** โ€” add maintenance items with a calendar or hours cycle. Rows are drag-reorderable, and you can insert title rows to group them. -4. **Set your hours** โ€” enter current Hobbs and Tach manually, or let the log book keep them current. +4. **Set your hours** โ€” enter current block time and time in service manually, or let the log book keep them current. 5. **Log flights** โ€” add entries by hand, or upload a Garmin CSV and Aviary computes the times and updates your meters. +## Connect an AI assistant + +Aviary is also an MCP server, so an AI assistant can import your existing maintenance records โ€” a spreadsheet, a typed list, another tracker's export โ€” into your service timeline. + +Add `https://aviary.danielibarra.com/mcp` as a remote (HTTP) MCP server in any assistant that supports MCP, then sign in when it asks. + +You sign in on Aviary's own login page and approve access; the assistant never sees your password. Then hand it your records and ask it to import them. It shows you a **proposal** first โ€” the items it will add, anything it isn't sure about, and any rows it couldn't use and why. Nothing is added until you tell it to go ahead, and it never changes or deletes items you already have. See or disconnect assistants any time under the robot icon on the dashboard (**Connected assistants**). + --- ## Local development @@ -84,7 +92,7 @@ push to main ``` - **Staging** (`aviarist-staging`) is deployed on every push to `main`, authenticated with the `HEROKU_API_KEY` GitHub Actions secret. -- **Production** (`aviarist-d300b0c36379`, the link at the top) is a separate app, promoted from staging deliberately once it looks good. +- **Production** (Heroku app `aviarist-d300b0c36379`, served at the link at the top) is a separate app, promoted from staging deliberately once it looks good. - Heroku runs the app from the `Procfile` (`java -jar build/libs/AviaryService-0.0.1-SNAPSHOT.jar`) on Java 21 (`system.properties`). Schema changes apply via Hibernate `ddl-auto=update`. ## Architecture diff --git a/build.gradle b/build.gradle index 20d0284..8405b68 100644 --- a/build.gradle +++ b/build.gradle @@ -41,6 +41,10 @@ dependencies { implementation 'com.h2database:h2:2.2.224' implementation 'org.apache.poi:poi:5.4.1' implementation 'org.springframework.ai:spring-ai-starter-mcp-server-webmvc' + // OAuth sign-in for MCP clients: Aviary issues the tokens (authorization server) + // and /mcp checks them (resource server). + implementation 'org.springframework.boot:spring-boot-starter-oauth2-authorization-server' + implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server' // Source: https://mvnrepository.com/artifact/software.amazon.awssdk/ses implementation("software.amazon.awssdk:sesv2:2.56.0") // Server-side PDF rendering for Download PDF (docs/specs/SHARE_EXPORT_SPEC.md) -- diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.md index bb148c5..b4f9b40 100644 --- a/docs/architecture/ARCHITECTURE.md +++ b/docs/architecture/ARCHITECTURE.md @@ -18,12 +18,13 @@ Spring Boot 3.4.3 ยท Java 21 ยท Spring MVC + Security + Data JPA ยท Thymeleaf ยท 1. Browser loads `GET /dashboard` โ†’ `UserController` fetches the user's timelines, flight logs, hours, aircraft info โ†’ Thymeleaf renders `dashboard.html`. 2. User edits a cell โ†’ `dashboard.js` debounces and `POST`s JSON via axios (with the Spring CSRF token from ``) to an endpoint like `/update/{id}`. 3. Controller updates the entity via the repository and returns JSON. -4. "Time Left" is computed **client-side** from the due date + current Tach hours. +4. "Time Left" is computed **client-side** from the due date + current time in service hours. ## Cross-cutting concerns - **Auth:** Spring Security form login, BCrypt passwords, single `USER` role. See [BACKEND](BACKEND.md#auth). - **Per-user scoping:** every entity has a `user_id`; queries filter by the authenticated user. See [DATABASE](DATABASE.md). -- **Hours model:** flight logs roll up into `User.hobbsHours` / `tachHours`, which maintenance due-dates count against. +- **AI assistants (MCP):** `/mcp` is an MCP server secured by Aviary's own OAuth authorization server (CIMD clients, PKCE, opaque hashed tokens). Assistants preview and import service timeline items; nothing is saved until the owner confirms. See [BACKEND](BACKEND.md#mcp-server--ai-assistant-sign-in). +- **Hours model:** flight logs roll up into `User.blockTimeHours` / `timeInServiceHours`, which maintenance due-dates count against. ## Known issues (high level โ€” details in the area maps) - Local dev uses **in-memory H2** (data is lost on restart). See [DATABASE](DATABASE.md). diff --git a/docs/architecture/BACKEND.md b/docs/architecture/BACKEND.md index 7cab998..9b3ae54 100644 --- a/docs/architecture/BACKEND.md +++ b/docs/architecture/BACKEND.md @@ -17,7 +17,7 @@ `SecurityConfig`: - `BCryptPasswordEncoder` bean. - `UserDetailsService` looks up `UserRepository.findByUsername`, builds a Spring user with role `USER`. Throws `UsernameNotFoundException` if missing. -- Filter chain: `/register`, `/login`, `/css/**`, `/js/**`, `/images/**` are public; **everything else requires auth**. Form login at `/login`, success โ†’ `/dashboard`. Logout at `POST /logout` โ†’ `/login?logout`. +- Filter chains, in order: (0) OAuth authorization server endpoints (`oauth/AuthorizationServerConfig`), (1) `/mcp` bearer-token resource server, (2) static assets, (3) everything else. In the main chain `/register`, `/login`, `/css/**`, `/js/**`, `/images/**`, `/.well-known/oauth-protected-resource` are public; **everything else requires auth**. Form login at `/login`, success โ†’ `/dashboard` (or back to `/oauth2/authorize` when the login interrupted an assistant's sign-in). Logout at `POST /logout` โ†’ `/login?logout`. - CSRF is on (Spring default); the frontend sends the token from ``. Exempt: `POST /alerts/confirm|decline|unsubscribe` (their unguessable token is the auth). - **Login lockout:** `LoginAttemptService` counts wrong passwords per username (5 in 15 min). `UserDetailsService` then builds the user with `accountLocked(true)`, so Spring refuses before checking the password; a custom failure handler sends a `LockedException` to `/login?locked` (other failures โ†’ `/login?error`). A successful login clears the count. In memory: resets on restart, per dyno. - **Emailed alert links:** `GET /alerts/confirm|decline|unsubscribe?token=` only renders a one-button page; the button POSTs to the same path to change state. Mail scanners open every link, so a state-changing GET would confirm/unsubscribe people on its own. @@ -34,16 +34,16 @@ | DELETE | `/delete/{id}` | โ€” | 200 / 403 / 404 | deletes a timeline row. Ownership checked (403 if not owner) | | POST | `/updateOrder` | `List` ids | void | reorders timelines; user-scoped, matches ids with `.equals` | | POST | `/updateUserInfo` | JSON aircraft fields | status JSON | updates makeModel/tailNumber/ownerName/makeModelSN for auth user | -| POST | `/updateHours` | `hobbsTimeToAdd`/`tachTimeToAdd`/`newHobbsTime`/`newTachTime` | hours JSON | set-or-add Hobbs/Tach. 400 for NaN/Infinity, a negative set value, or an add that would go below 0 (checked before anything changes) | +| POST | `/updateHours` | `blockTimeToAdd`/`timeInServiceToAdd`/`newBlockTime`/`newTimeInService` | hours JSON | set-or-add block time / time in service. 400 for NaN/Infinity, a negative set value, or an add that would go below 0 (checked before anything changes) | | GET | `/flightlogs` | โ€” | `List` JSON | auth user's logs | | POST | `/addflightlog` | `FlightLog` JSON | log + new totals JSON | recomputes hours via `calculateMergedHours` | | DELETE | `/deleteflightlog/{id}` | โ€” | status + new totals | **ownership checked** (403 if not owner) | | DELETE | `/deleteOption/{id}` | โ€” | text | description option; **ownership checked** (403 if not owner) | ## Key logic -- **`calculateMergedHours(logs, useHobbs)`** โ€” sums flight time across all logs by **merging overlapping intervals** so overlapping flights don't double-count. Hobbs uses `hobbsOut`/`hobbsIn`; Tach uses `tachIn`/`tachOut`. Result is written back to `User.hobbsHours`/`tachHours` on add/delete of a log. +- **`calculateMergedHours(logs, useBlockTime)`** โ€” sums flight time across all logs by **merging overlapping intervals** so overlapping flights don't double-count. Block time uses `blockTimeOut`/`blockTimeIn`; time in service uses `timeInServiceOut`/`timeInServiceIn`. Result is written back to `User.blockTimeHours`/`timeInServiceHours` on add/delete of a log. - **`saveCustomDescriptionOption`** โ€” persists a user's custom Service Timeline "Description" values so they reappear in the dropdown. -- **Hours "last updated" stamps:** `/updateHours` sets `hobbsUpdatedAt`/`tachUpdatedAt` (UTC `Instant`) + `*UpdatedSource = "manual"` for whichever value changed; `/addflightlog` and `/deleteflightlog` set both with source `"flightlog"`. `GET /dashboard` passes the 4 values (timestamps as ISO strings) to the view, which renders them in the browser's local time. +- **Hours "last updated" stamps:** `/updateHours` sets `blockTimeUpdatedAt`/`timeInServiceUpdatedAt` (UTC `Instant`) + `*UpdatedSource = "manual"` for whichever value changed; `/addflightlog` and `/deleteflightlog` set both with source `"flightlog"`. `GET /dashboard` passes the 4 values (timestamps as ISO strings) to the view, which renders them in the browser's local time. ## Time Left + PDF - `DueDates.formatTimeLeft(dueDate, dueHours, today, currentTimeInService)` is the one server-side Time Left formatter (smart format, see [FRONTEND](FRONTEND.md)). Used by `PdfExportService` (computed at render time โ€” the stored `timeLeft` column goes stale) and `/completeMaintenance/{id}`. @@ -52,6 +52,13 @@ ## Local demo data `config/DemoDataSeeder` (`@Profile({"h2","main"})`, never Heroku/tests) creates **demo / Demo-pass-123** once: section titles, items due at every Time Left scale, 6 chained flight logs, 3 pending + 1 dismissed AeroAPI suggestions. Delete the `demo` user to regenerate with fresh relative dates. +## MCP server + AI assistant sign-in +Aviary is an MCP server at `POST /mcp` (Spring AI, Streamable HTTP, SYNC) and its own OAuth authorization server, so AI assistants sign in as an owner. +- **Sign-in:** authorization code + PKCE (S256 only), public clients only. Assistants identify with a **Client ID Metadata Document**: `client_id` is an https URL that `CimdFetcher` downloads (SSRF-guarded: https, no IP literals, no private/loopback/link-local DNS, no redirects, 5 KB, 5 s) and `CimdRegisteredClientRepository` turns into a client (cached 1 h). Dynamic Client Registration is off. Loopback redirect URIs may use any port (`AuthorizationServerConfig.validateRedirectUri`). Owner approves on `/oauth2/consent` (`ConsentController`). +- **Tokens:** opaque, 7 days, no refresh tokens (Spring Authorization Server 1.4 gives public clients none). Stored by `JpaOAuth2AuthorizationService` in `oauth_authorizations` with token values **SHA-256 hashed**. `LocalOpaqueTokenIntrospector` checks every `/mcp` call against that table, so **Disconnect** (`/account/connections`, deletes the row) cuts an assistant off on its next request. No/dead token โ†’ 401 with `WWW-Authenticate: Bearer resource_metadata=โ€ฆ`; token without `aviary.read` โ†’ 403. +- **Tools** (`mcp/`): `list_flights`, `get_import_format`, `list_service_timeline`, `propose_timeline_import`, `continue_poor_fit`, `confirm_timeline_import`. Each checks its scope and gets the owner from `McpCurrentUser` (the token's user โ€” never a parameter). +- **Import:** `TimelineImportService` + pure `util/TimelineImportRules`. Propose stores an `import_proposals` row (24 h, one open per owner) and changes nothing; confirm adds exactly the proposed rows after the existing ones in one transaction (all or nothing), never edits existing rows, skips name matches unless the owner opts in, and writes a `timeline_import_records` row. Rate limits: 30 proposals / 10 confirms per owner per hour. + ## Input limits & rate limits - **Text length:** every text column is varchar(255). `Validation.maxLength` checks item/description/aircraft fields/airports/description options up front and returns a 400 with a readable message; `GlobalExceptionHandler` catches anything missed. The AeroAPI key is capped at 100 chars (it's stored encrypted, which roughly doubles its length). - **Outbound email:** `OutboundEmailLimiter` allows 10 user-triggered emails per user per hour โ€” alert recipient invites/resends and `POST /pdf/email` โ€” then 429. Scheduled digests and "Send alert now" aren't counted (the latter has per-recipient limits in `sendDigest`). Max 10 alert recipients per user. diff --git a/docs/architecture/DATABASE.md b/docs/architecture/DATABASE.md index 36ec5d2..afc0224 100644 --- a/docs/architecture/DATABASE.md +++ b/docs/architecture/DATABASE.md @@ -26,6 +26,18 @@ One-to-many (cascade ALL) โ†’ `serviceTimeline`, `flightLogs`. ### `flight_suggestions` (`FlightSuggestion`) `id`, `tailNumber`, `faFlightId` (unique per user), `departureTime`, `arrivalTime` (`Instant`), `origin`, `destination`, `status` (String "pending" | "accepted" | "dismissed"), `createdAt`, `user_id`. AeroAPI-detected flights awaiting a user decision โ€” see `docs/ADSB_SYNC_SPEC.md`. +### `import_proposals` (`ImportProposal`) +`id`, `user_id` (not null), `status` ("OPEN" | "NEEDS_FIT_CONFIRMATION" | "CONFIRMED" | "REPLACED" | "EXPIRED"), `itemsJson` / `rejectedJson` (TEXT, JSON lists), `submittedCount`, `createdAt`, `expiresAt` (+24 h), `confirmedAt`, `connectionClientId`. An AI assistant's previewed timeline import; at most one OPEN/NEEDS_FIT_CONFIRMATION per user. + +### `timeline_import_records` (`TimelineImportRecord`) +`id`, `user_id` (not null), `proposalId`, `clientId`, `clientName`, `itemCount`, `importedAt`. One row per confirmed import; shown on Connected assistants. + +### `oauth_authorizations` (`OAuthAuthorizationEntity`) โ€” no `user_id` +String `id`, `registeredClientId` (assistant's CIMD URL), `principalName` (username), scopes, attributes (TEXT), and the authorization code / access token / refresh token **SHA-256 hashes** with issued/expires/metadata, plus `clientName`, `lastUsedAt`. One row = one connected assistant; deleting it disconnects. Keyed by username rather than FK because Spring Authorization Server works in principal names. + +### `oauth_consents` (`OAuthConsentEntity`) โ€” no `user_id` +Composite key (`registeredClientId`, `principalName`), `authorities`. Approved scopes per assistant per owner. + ## Relationships `User` 1โ€”* `ServiceTimeline`, `FlightLog` (both cascade ALL, JSON managed/back references to avoid serialization loops). `User` 1โ€”* `DescriptionOption`, `FlightSuggestion` (FK only, no mapped collection on `User` โ€” accessed via repository query). diff --git a/docs/architecture/FRONTEND.md b/docs/architecture/FRONTEND.md index 5297ee1..25a67d6 100644 --- a/docs/architecture/FRONTEND.md +++ b/docs/architecture/FRONTEND.md @@ -12,7 +12,7 @@ Each stylesheet defines the same CSS-variable palette (`--primary` green `#2C9B6 ## Dashboard structure - Fixed header (logo, **Share** menu, logout, settings gear). Share is a popover card (`.share-dropdown`, toggled via `hidden` + `aria-expanded` by `setShareOpen()` in `dashboard.js`): Print, Download PDF, then a divider and Email/Text marked with a "Soon" pill (`.share-coming-soon`). Closes on outside click, Escape, or picking an item; Arrow keys move between items. Styled with theme tokens so it works in dark mode. -- "My Hours" card: shows Hobbs/Tach, each with a small muted "last updated" line under it (`.hours-block` / `.hours-updated`) โ€” local date + time + relative ("2 days ago") + source ("you edited it" / "from a flight log"). Edit panel can **set** or **add** hours. +- "My Hours" card: shows block time and time in service, each with a small muted "last updated" line under it (`.hours-block` / `.hours-updated`) โ€” local date + time + relative ("2 days ago") + source ("you edited it" / "from a flight log"). Edit panel can **set** or **add** hours. - Two tabs: **Service Timeline** and **Log Book**. - Service Timeline table: drag-reorder (SortableJS via grip handle), title rows vs item rows, a custom Description dropdown (with add/remove custom options), and a Calendar/Clock picker for Last Done / Due Date. "Time Left" is computed client-side. - Log Book table: existing rows are **readonly**; an add-row appends a flight. @@ -23,7 +23,7 @@ Each stylesheet defines the same CSS-variable palette (`--primary` green `#2C9B6 - **AJAX:** `axios`, with the Spring CSRF token read from `` / `_csrf_header` and sent on every mutating call. - **Reorder:** SortableJS โ†’ `POST /updateOrder`. - **Time Left format ("smart"):** `formatCalendarTimeLeft()` โ€” under 60 days "45 days left", under a year "5 mo 12 days left", a year+ "1 yr 1 mo left"; overdue reads the same with "overdue"; hours stay "40.5 hours left". Calendar months via `calendarPeriod()` (same math as Java `Period.between`). **Must match `DueDates.formatCalendarTimeLeft` in Java** (PDF + Mark complete use it); verified identical across ~5.5k dates. -- **Time Left:** `calculateTimeLeft(dueDate, currentTach)` parses a due value that may hold a calendar date and/or an hours number (whole or decimal โ€” e.g. `100`, `100.5`, `.5`); recomputed on hours change and at midnight. The Clock-input sanitizer accepts digits plus a single decimal point. +- **Time Left:** `calculateTimeLeft(dueDateCal, dueDateHrs, currentTimeInServiceHours)` parses a due value that may hold a calendar date and/or an hours number (whole or decimal โ€” e.g. `100`, `100.5`, `.5`); recomputed on hours change and at midnight. The Clock-input sanitizer accepts digits plus a single decimal point. - **Custom dropdowns + date/clock pickers** are hand-rolled (no library). The chevron toggles a menu; tapping the Description text or an empty Last Done / Due Date cell toggles it too. One persistent document listener closes any open menu on a click outside it (`isDropdownToggle` in `dashboard.js`). - **Last Done / Due Date menu** buttons read Add / Remove (state is the button text). Removing a field that has a value takes two taps: the first arms it as a red "Remove?" (`.confirm-remove`), the second removes it and auto-saves; reopening the menu disarms it (`disarmRemoveButton`). Empty fields remove on one tap. - **`[hidden]` always wins** (`[hidden] { display: none !important; }` at the top of `dashboardstyle.css`). Toggle visibility with `el.hidden`; rules like `.settings-table tr { display: flex }` used to override the attribute and show hidden rows. diff --git a/docs/backend-notes/TRANSACTIONAL.md b/docs/backend-notes/TRANSACTIONAL.md index 969543a..75a79c1 100644 --- a/docs/backend-notes/TRANSACTIONAL.md +++ b/docs/backend-notes/TRANSACTIONAL.md @@ -82,15 +82,15 @@ for shredding โ€” including A's work. flightLogRepository.delete(log); // 1. remove the log List remainingLogs = flightLogRepository.findByUser(user); -double newHobbs = computeDisplayedHours(user, remainingLogs, true); -double newTach = computeDisplayedHours(user, remainingLogs, false); -user.setHobbsHours(newHobbs); +double newBlockTime = hoursService.recomputeChain(user, true); +double newTimeInService = hoursService.recomputeChain(user, false); +user.setBlockTimeHours(newBlockTime); ... userRepository.save(user); // 2. recompute the hours ``` -If step 1 commits and step 2 does not, the aircraft has a deleted flight but stale hobbs -and tach hours on screen. That is the exact bug class the recent commits have been fixing. +If step 1 commits and step 2 does not, the aircraft has a deleted flight but stale block time +and time in service hours on screen. That is the exact bug class the recent commits have been fixing. `@Transactional` is what guarantees both or neither. ## Which import to use @@ -188,7 +188,7 @@ Run the app: (`-Pdev` is defined in `build.gradle` and serves templates/CSS live from `src/` so frontend edits show without a rebuild.) -Then log in and change the hobbs hours. Expect log lines like: +Then log in and change the block time hours. Expect log lines like: ``` Getting transaction for [com.example.AviaryService.services.HoursService.updateHours] diff --git a/docs/planning/CHANGES.md b/docs/planning/CHANGES.md index 24028c6..4bfabee 100644 --- a/docs/planning/CHANGES.md +++ b/docs/planning/CHANGES.md @@ -166,12 +166,12 @@ user for the whole day. ## Multiple aircraft per user **What:** a user tracks more than one airplane. Each aircraft has its own -Service Timeline, aircraft-info card, flight logs, Hobbs/Tach hours, and +Service Timeline, aircraft-info card, flight logs, block time / time in service hours, and AeroAPI subscription โ€” one aircraft shown per page, with a switcher to pick the active one. Essentially every per-user thing becomes per-aircraft. **Current model (what has to change):** everything hangs off `User` -directly โ€” `User.tailNumber`, `User.hobbsHours`/`tachHours`, the +directly โ€” `User.tailNumber`, `User.blockTimeHours`/`timeInServiceHours`, the `makeModel`/`ownerName`/`makeModelSN` fields, `User.aeroApiKey`; and `ServiceTimeline`, `FlightLog`, `DescriptionOption`, `Subscription`, `FlightSuggestion`, `AlertPreference`/`AlertRecipient` are all @@ -180,7 +180,7 @@ directly โ€” `User.tailNumber`, `User.hobbsHours`/`tachHours`, the **What's involved:** 1. New `Aircraft` entity `@ManyToOne User`, owning: makeModel, tailNumber, - ownerName, serial, hobbsHours/tachHours + their + ownerName, serial, blockTimeHours/timeInServiceHours + their `*UpdatedAt`/`*UpdatedSource` stamps. Decide: `aeroApiKey` per-aircraft, or keep one key on `User` shared across their planes. 2. Re-parent `ServiceTimeline`, `FlightLog`, `DescriptionOption`, diff --git a/docs/planning/SERVICE_LAYER_PLAN.md b/docs/planning/SERVICE_LAYER_PLAN.md index 7cd5ce9..d372bf2 100644 --- a/docs/planning/SERVICE_LAYER_PLAN.md +++ b/docs/planning/SERVICE_LAYER_PLAN.md @@ -30,7 +30,7 @@ Only 4 of the current 30 methods are under 15 lines. **A service must never return `ResponseEntity`.** That is the single most important rule here. Services return plain objects; the controller turns them into HTTP. -Current worst offender: `parseGarminCsv` โ€” 158 lines of Hobbs/airborne math that +Current worst offender: `parseGarminCsv` โ€” 158 lines of block-time/airborne math that returns `ResponseEntity>`. Because of that it cannot be called from a scheduled job or tested without web types. diff --git a/docs/planning/STEPS.md b/docs/planning/STEPS.md index 18a6da2..1cf6672 100644 --- a/docs/planning/STEPS.md +++ b/docs/planning/STEPS.md @@ -205,8 +205,8 @@ flightlog-service, because it's a decision a *person* made. Two co-owners of the same plane can each accept or dismiss the same flight independently. Rules that cannot be broken: -- it **proposes**, the user accepts. Never write Hobbs/Tach automatically. -- ADS-B airborne time is not Hobbs time and not tach time. It's an estimate. +- it **proposes**, the user accepts. Never write block time / time in service automatically. +- ADS-B airborne time is not block time and not time in service. It's an estimate. - hours can go up, never down. AviaryService already has this floor rule. - if flightlog-service is down or slow, AviaryService still works โ€” time it out, fall back to manual entry. Never hang the page on it. @@ -289,7 +289,7 @@ Decided: two pieces, not one. - users, accounts, subscriptions - polls live positions for subscribed tails - shows "add these flights?" and remembers what each user answered -- writes the logbook, rolls Hobbs/Tach, updates maintenance dates +- writes the logbook, rolls block time / time in service, updates maintenance dates **Why split:** not because microservices are fashionable. Because a 3-4 GB download that un-gzips 70,000 files cannot run in the same process as the web app diff --git a/docs/specs/ADSB_DATA_SOURCE.md b/docs/specs/ADSB_DATA_SOURCE.md index 36a56d9..6ed8e8e 100644 --- a/docs/specs/ADSB_DATA_SOURCE.md +++ b/docs/specs/ADSB_DATA_SOURCE.md @@ -130,7 +130,7 @@ Each has three variants โ€” `scheduled_`, `estimated_`, `actual_`. **Use `actual only**; the others are predictions. > **`actual_off` โ†’ `actual_on` is the flight.** Duration = the difference between -> them. This is *airborne* time, not Hobbs. +> them. This is *airborne* time, not block time. #### Fields we use diff --git a/docs/specs/SHARE_EXPORT_SPEC.md b/docs/specs/SHARE_EXPORT_SPEC.md index db1f247..0104f48 100644 --- a/docs/specs/SHARE_EXPORT_SPEC.md +++ b/docs/specs/SHARE_EXPORT_SPEC.md @@ -95,7 +95,7 @@ Scope applies to **all four actions, including Print**: ## PDF content = data only, no UI chrome The PDF contains only the record content: **Service Timeline, Aircraft Info, -Hours (Hobbs/Tach), and Log Book**. All interactive controls are excluded โ€” +Hours (block time / time in service), and Log Book**. All interactive controls are excluded โ€” the Share menu, grip handles, trash/delete icons, complete-maintenance button, chevrons, dropdowns, etc. diff --git a/src/browserTest/java/com/example/AviaryService/browser/ConnectionsPageTest.java b/src/browserTest/java/com/example/AviaryService/browser/ConnectionsPageTest.java new file mode 100644 index 0000000..8dba0ce --- /dev/null +++ b/src/browserTest/java/com/example/AviaryService/browser/ConnectionsPageTest.java @@ -0,0 +1,83 @@ +package com.example.AviaryService.browser; + +import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; + +import java.time.Instant; +import java.util.UUID; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import com.example.AviaryService.entity.OAuthAuthorizationEntity; +import com.example.AviaryService.entity.TimelineImportRecord; +import com.example.AviaryService.repositories.OAuthAuthorizationRepository; +import com.example.AviaryService.repositories.TimelineImportRecordRepository; + +/** + * Account -> Connected assistants: a connected assistant is listed, the + * dashboard links to the page, and Disconnect removes it -- at desktop and + * phone widths. + */ +class ConnectionsPageTest extends BrowserTestBase { + + @Autowired + OAuthAuthorizationRepository authorizationRepository; + + @Autowired + TimelineImportRecordRepository importRecordRepository; + + private void seedConnection(String username) { + OAuthAuthorizationEntity e = new OAuthAuthorizationEntity(); + e.setId(UUID.randomUUID().toString()); + e.setRegisteredClientId("https://assistant.example.com/oauth/client.json"); + e.setPrincipalName(username); + e.setAuthorizationGrantType("authorization_code"); + e.setClientName("Test Assistant"); + e.setAccessTokenValue("sha256:" + UUID.randomUUID()); + e.setAccessTokenIssuedAt(Instant.now()); + authorizationRepository.save(e); + + TimelineImportRecord r = new TimelineImportRecord(); + r.setUser(userRepository.findByUsername(username)); + r.setClientId(e.getRegisteredClientId()); + r.setClientName("Test Assistant"); + r.setItemCount(3); + r.setImportedAt(Instant.now()); + importRecordRepository.save(r); + } + + private void listAndDisconnect(int width, int height) { + page.setViewportSize(width, height); + String username = seedUser("password123"); + seedConnection(username); + loginAs(username, "password123"); + + page.locator("#connections-link").click(); + page.waitForURL(baseUrl() + "/account/connections"); + + assertThat(page.locator(".connection-name")).hasText("Test Assistant"); + assertThat(page.locator(".connection-meta")).containsText("assistant.example.com"); + assertThat(page.locator(".connection-imports")).containsText("added 3 items"); + + // No sideways scrolling on a phone. + Object overflow = page.evaluate("document.documentElement.scrollWidth > window.innerWidth"); + if (Boolean.TRUE.equals(overflow)) { + throw new AssertionError("Connections page scrolls horizontally at " + width + "px"); + } + + page.locator("button.connection-disconnect").click(); + page.waitForURL("**/account/connections?disconnected"); + assertThat(page.locator(".connection")).hasCount(0); + assertThat(page.locator("body")).containsText("No AI assistants are connected"); + } + + @Test + void desktop() { + listAndDisconnect(1280, 800); + } + + @Test + void phone() { + listAndDisconnect(390, 844); + } +} diff --git a/src/main/java/com/example/AviaryService/config/SecurityConfig.java b/src/main/java/com/example/AviaryService/config/SecurityConfig.java index d421de9..3ac7da3 100644 --- a/src/main/java/com/example/AviaryService/config/SecurityConfig.java +++ b/src/main/java/com/example/AviaryService/config/SecurityConfig.java @@ -11,7 +11,13 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; +import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; +import org.springframework.security.web.savedrequest.HttpSessionRequestCache; +import org.springframework.security.web.savedrequest.SavedRequest; import org.springframework.core.annotation.Order; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector; import com.example.AviaryService.entity.User; import com.example.AviaryService.repositories.UserRepository; @@ -55,8 +61,34 @@ public UserDetailsService userDetailsService(LoginAttemptService loginAttemptSer }; } + // /mcp is called by AI assistants, not browsers: no session, no CSRF, and + // every request carries an OAuth access token Aviary issued (see + // oauth/AuthorizationServerConfig). A missing or dead token gets a 401 that + // points the assistant at the sign-in metadata, per the MCP auth spec. @Bean @Order(1) + public SecurityFilterChain mcpFilterChain(HttpSecurity http, OpaqueTokenIntrospector introspector, + @Value("${aviary.oauth.issuer}") String issuer) throws Exception { + String challenge = "Bearer resource_metadata=\"" + issuer + "/.well-known/oauth-protected-resource\""; + http + .securityMatcher("/mcp", "/mcp/**") + .authorizeHttpRequests(auth -> auth.anyRequest().hasAuthority("SCOPE_aviary.read")) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .csrf(csrf -> csrf.disable()) + .oauth2ResourceServer(oauth -> oauth + .opaqueToken(opaque -> opaque.introspector(introspector)) + // setStatus, not sendError: sendError forwards to /error, which + // the main chain answers with a redirect to /login instead of 401. + .authenticationEntryPoint((request, response, ex) -> { + response.setHeader("WWW-Authenticate", challenge); + response.setStatus(401); + }) + .accessDeniedHandler((request, response, ex) -> response.setStatus(403))); + return http.build(); + } + + @Bean + @Order(2) public SecurityFilterChain staticResourcesFilterChain(HttpSecurity http) throws Exception { http .securityMatcher("/css/**", "/js/**", "/images/**") @@ -67,12 +99,14 @@ public SecurityFilterChain staticResourcesFilterChain(HttpSecurity http) throws } @Bean - @Order(2) + @Order(3) public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { System.out.println("SecurityConfig loaded"); http .authorizeHttpRequests(auth -> auth .requestMatchers("/register", "/login", "/css/**", "/js/**", "/images/**").permitAll() + // OAuth discovery for MCP clients -- public by spec (RFC 9728). + .requestMatchers("/.well-known/oauth-protected-resource").permitAll() // Token-guarded alert links clicked from an email inbox -- the opaque // token is the auth, no login. See AlertPublicController. .requestMatchers("/alerts/confirm", "/alerts/decline", "/alerts/unsubscribe").permitAll() @@ -84,7 +118,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti .csrf(csrf -> csrf.ignoringRequestMatchers("/alerts/confirm", "/alerts/decline", "/alerts/unsubscribe")) .formLogin(form -> form .loginPage("/login") - .defaultSuccessUrl("/dashboard", true) // After login, go here + .successHandler(loginSuccessHandler()) // Locked out by LoginAttemptService -> say so instead of "wrong password". .failureHandler((request, response, exception) -> response.sendRedirect( request.getContextPath() + (exception instanceof LockedException ? "/login?locked" : "/login?error"))) @@ -103,4 +137,22 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti return http.build(); } + // After login, go to the dashboard -- unless the login was the middle of an + // AI assistant's sign-in (/oauth2/authorize), which has to resume so the + // owner reaches the consent page. + private static AuthenticationSuccessHandler loginSuccessHandler() { + HttpSessionRequestCache requestCache = new HttpSessionRequestCache(); + SavedRequestAwareAuthenticationSuccessHandler resume = new SavedRequestAwareAuthenticationSuccessHandler(); + resume.setRequestCache(requestCache); + return (request, response, authentication) -> { + SavedRequest saved = requestCache.getRequest(request, response); + if (saved != null && saved.getRedirectUrl().contains("/oauth2/authorize")) { + resume.onAuthenticationSuccess(request, response, authentication); + } else { + requestCache.removeRequest(request, response); + response.sendRedirect(request.getContextPath() + "/dashboard"); + } + }; + } + } \ No newline at end of file diff --git a/src/main/java/com/example/AviaryService/controllers/ConnectionsController.java b/src/main/java/com/example/AviaryService/controllers/ConnectionsController.java new file mode 100644 index 0000000..dda2221 --- /dev/null +++ b/src/main/java/com/example/AviaryService/controllers/ConnectionsController.java @@ -0,0 +1,65 @@ +package com.example.AviaryService.controllers; + +import java.security.Principal; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; + +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.server.ResponseStatusException; + +import com.example.AviaryService.entity.TimelineImportRecord; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.TimelineImportRecordRepository; +import com.example.AviaryService.repositories.UserRepository; +import com.example.AviaryService.services.imports.ConnectionService; + +// Account -> Connected assistants: the AI assistants signed in to this +// owner's account, with a Disconnect button for each. +@Controller +public class ConnectionsController { + + private final ConnectionService connectionService; + private final UserRepository userRepository; + private final TimelineImportRecordRepository importRecordRepository; + + public ConnectionsController(ConnectionService connectionService, UserRepository userRepository, + TimelineImportRecordRepository importRecordRepository) { + this.connectionService = connectionService; + this.userRepository = userRepository; + this.importRecordRepository = importRecordRepository; + } + + @GetMapping("/account/connections") + public String connections(Principal principal, Model model) { + User user = userRepository.findByUsername(principal.getName()); + model.addAttribute("connections", connectionService.list(user)); + // Recent imports, grouped by the assistant that made them. + Map> imports = new LinkedHashMap<>(); + for (TimelineImportRecord r : importRecordRepository.findTop20ByUserOrderByImportedAtDesc(user)) { + if (r.getClientId() != null) { + imports.computeIfAbsent(r.getClientId(), k -> new ArrayList<>()).add(r); + } + } + model.addAttribute("imports", imports); + return "connections"; + } + + @PostMapping("/account/connections/{id}/disconnect") + public String disconnect(Principal principal, @PathVariable String id) { + User user = userRepository.findByUsername(principal.getName()); + try { + connectionService.disconnect(user, id); + } catch (NoSuchElementException e) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND); + } + return "redirect:/account/connections?disconnected"; + } +} diff --git a/src/main/java/com/example/AviaryService/controllers/ConsentController.java b/src/main/java/com/example/AviaryService/controllers/ConsentController.java new file mode 100644 index 0000000..9129933 --- /dev/null +++ b/src/main/java/com/example/AviaryService/controllers/ConsentController.java @@ -0,0 +1,72 @@ +package com.example.AviaryService.controllers; + +import java.net.URI; +import java.security.Principal; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +import org.springframework.security.oauth2.server.authorization.client.RegisteredClient; +import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; + +import com.example.AviaryService.oauth.CimdRegisteredClientRepository; + +// The "Allow to access your Aviary account?" page shown during an +// AI assistant's sign-in. Approve/Deny post back to /oauth2/authorize, which +// Spring Authorization Server handles. +@Controller +public class ConsentController { + + public record ScopeLine(String scope, String description) {} + + private final RegisteredClientRepository registeredClientRepository; + + public ConsentController(RegisteredClientRepository registeredClientRepository) { + this.registeredClientRepository = registeredClientRepository; + } + + @GetMapping("/oauth2/consent") + public String consent(Principal principal, Model model, + @RequestParam("client_id") String clientId, + @RequestParam(value = "scope", required = false) String scope, + @RequestParam("state") String state) { + RegisteredClient client = registeredClientRepository.findByClientId(clientId); + if (client == null) { + model.addAttribute("error", "This assistant could not be verified."); + return "consent"; + } + + Set requested = new LinkedHashSet<>(); + if (scope != null) { + for (String s : scope.split(" ")) { + if (client.getScopes().contains(s)) requested.add(s); + } + } + List lines = new ArrayList<>(); + for (String s : requested) { + lines.add(new ScopeLine(s, describe(s))); + } + + model.addAttribute("clientId", clientId); + model.addAttribute("clientName", client.getClientName()); + model.addAttribute("clientHost", URI.create(clientId).getHost()); + model.addAttribute("state", state); + model.addAttribute("scopes", lines); + model.addAttribute("username", principal.getName()); + return "consent"; + } + + private static String describe(String scope) { + return switch (scope) { + case CimdRegisteredClientRepository.SCOPE_READ -> "Read your service timeline and flight log"; + case CimdRegisteredClientRepository.SCOPE_IMPORT -> + "Propose service timeline items for you to review, and add them once you confirm"; + default -> scope; + }; + } +} diff --git a/src/main/java/com/example/AviaryService/entity/ImportProposal.java b/src/main/java/com/example/AviaryService/entity/ImportProposal.java new file mode 100644 index 0000000..90021b5 --- /dev/null +++ b/src/main/java/com/example/AviaryService/entity/ImportProposal.java @@ -0,0 +1,79 @@ +package com.example.AviaryService.entity; + +import java.time.Instant; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; + +// A previewed service timeline import from an AI assistant. Nothing reaches +// the timeline until the owner confirms it. Items and rejected rows are kept +// as JSON (they are only ever read back whole). Status: OPEN (or +// NEEDS_FIT_CONFIRMATION when most rows didn't fit) -> CONFIRMED, or +// REPLACED by a newer proposal, or EXPIRED after 24 hours. +@Entity +@Table(name = "import_proposals") +public class ImportProposal { + + public static final String OPEN = "OPEN"; + public static final String NEEDS_FIT_CONFIRMATION = "NEEDS_FIT_CONFIRMATION"; + public static final String CONFIRMED = "CONFIRMED"; + public static final String REPLACED = "REPLACED"; + public static final String EXPIRED = "EXPIRED"; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(optional = false) + @JoinColumn(name = "user_id", nullable = false) + private User user; + + @Column(nullable = false) + private String status; + + @Column(columnDefinition = "TEXT") + private String itemsJson; + + @Column(columnDefinition = "TEXT") + private String rejectedJson; + + private int submittedCount; + + @Column(nullable = false) + private Instant createdAt; + + @Column(nullable = false) + private Instant expiresAt; + + private Instant confirmedAt; + + // The assistant's client_id (CIMD URL) that made the proposal. + @Column(length = 1000) + private String connectionClientId; + + public Long getId() { return id; } + public User getUser() { return user; } + public void setUser(User user) { this.user = user; } + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + public String getItemsJson() { return itemsJson; } + public void setItemsJson(String itemsJson) { this.itemsJson = itemsJson; } + public String getRejectedJson() { return rejectedJson; } + public void setRejectedJson(String rejectedJson) { this.rejectedJson = rejectedJson; } + public int getSubmittedCount() { return submittedCount; } + public void setSubmittedCount(int submittedCount) { this.submittedCount = submittedCount; } + public Instant getCreatedAt() { return createdAt; } + public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } + public Instant getExpiresAt() { return expiresAt; } + public void setExpiresAt(Instant expiresAt) { this.expiresAt = expiresAt; } + public Instant getConfirmedAt() { return confirmedAt; } + public void setConfirmedAt(Instant confirmedAt) { this.confirmedAt = confirmedAt; } + public String getConnectionClientId() { return connectionClientId; } + public void setConnectionClientId(String connectionClientId) { this.connectionClientId = connectionClientId; } +} diff --git a/src/main/java/com/example/AviaryService/entity/OAuthAuthorizationEntity.java b/src/main/java/com/example/AviaryService/entity/OAuthAuthorizationEntity.java new file mode 100644 index 0000000..e3c04d3 --- /dev/null +++ b/src/main/java/com/example/AviaryService/entity/OAuthAuthorizationEntity.java @@ -0,0 +1,114 @@ +package com.example.AviaryService.entity; + +import java.time.Instant; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.Table; + +// One connected AI assistant: the OAuth grant Aviary issued to it for one +// owner. Deleting the row disconnects the assistant -- its access token stops +// working on the next request. Token values are stored as SHA-256 hashes +// ("sha256:"), never the token itself. See oauth/JpaOAuth2AuthorizationService. +@Entity +@Table(name = "oauth_authorizations", indexes = { + @Index(name = "idx_oauth_auth_principal", columnList = "principalName"), + @Index(name = "idx_oauth_auth_access", columnList = "accessTokenValue"), + @Index(name = "idx_oauth_auth_refresh", columnList = "refreshTokenValue"), + @Index(name = "idx_oauth_auth_code", columnList = "authorizationCodeValue"), + @Index(name = "idx_oauth_auth_state", columnList = "state") +}) +public class OAuthAuthorizationEntity { + + @Id + private String id; + + // The assistant's client_id: the https URL of its metadata document. + @Column(length = 1000) + private String registeredClientId; + + // Aviary username the assistant acts for. + private String principalName; + + private String authorizationGrantType; + + @Column(length = 1000) + private String authorizedScopes; + + @Column(columnDefinition = "TEXT") + private String attributes; + + @Column(length = 500) + private String state; + + private String authorizationCodeValue; + private Instant authorizationCodeIssuedAt; + private Instant authorizationCodeExpiresAt; + @Column(columnDefinition = "TEXT") + private String authorizationCodeMetadata; + + private String accessTokenValue; + private Instant accessTokenIssuedAt; + private Instant accessTokenExpiresAt; + @Column(columnDefinition = "TEXT") + private String accessTokenMetadata; + @Column(length = 1000) + private String accessTokenScopes; + + private String refreshTokenValue; + private Instant refreshTokenIssuedAt; + private Instant refreshTokenExpiresAt; + @Column(columnDefinition = "TEXT") + private String refreshTokenMetadata; + + // Shown on the Connected assistants page. + private String clientName; + private Instant lastUsedAt; + + public String getId() { return id; } + public void setId(String id) { this.id = id; } + public String getRegisteredClientId() { return registeredClientId; } + public void setRegisteredClientId(String registeredClientId) { this.registeredClientId = registeredClientId; } + public String getPrincipalName() { return principalName; } + public void setPrincipalName(String principalName) { this.principalName = principalName; } + public String getAuthorizationGrantType() { return authorizationGrantType; } + public void setAuthorizationGrantType(String authorizationGrantType) { this.authorizationGrantType = authorizationGrantType; } + public String getAuthorizedScopes() { return authorizedScopes; } + public void setAuthorizedScopes(String authorizedScopes) { this.authorizedScopes = authorizedScopes; } + public String getAttributes() { return attributes; } + public void setAttributes(String attributes) { this.attributes = attributes; } + public String getState() { return state; } + public void setState(String state) { this.state = state; } + public String getAuthorizationCodeValue() { return authorizationCodeValue; } + public void setAuthorizationCodeValue(String authorizationCodeValue) { this.authorizationCodeValue = authorizationCodeValue; } + public Instant getAuthorizationCodeIssuedAt() { return authorizationCodeIssuedAt; } + public void setAuthorizationCodeIssuedAt(Instant authorizationCodeIssuedAt) { this.authorizationCodeIssuedAt = authorizationCodeIssuedAt; } + public Instant getAuthorizationCodeExpiresAt() { return authorizationCodeExpiresAt; } + public void setAuthorizationCodeExpiresAt(Instant authorizationCodeExpiresAt) { this.authorizationCodeExpiresAt = authorizationCodeExpiresAt; } + public String getAuthorizationCodeMetadata() { return authorizationCodeMetadata; } + public void setAuthorizationCodeMetadata(String authorizationCodeMetadata) { this.authorizationCodeMetadata = authorizationCodeMetadata; } + public String getAccessTokenValue() { return accessTokenValue; } + public void setAccessTokenValue(String accessTokenValue) { this.accessTokenValue = accessTokenValue; } + public Instant getAccessTokenIssuedAt() { return accessTokenIssuedAt; } + public void setAccessTokenIssuedAt(Instant accessTokenIssuedAt) { this.accessTokenIssuedAt = accessTokenIssuedAt; } + public Instant getAccessTokenExpiresAt() { return accessTokenExpiresAt; } + public void setAccessTokenExpiresAt(Instant accessTokenExpiresAt) { this.accessTokenExpiresAt = accessTokenExpiresAt; } + public String getAccessTokenMetadata() { return accessTokenMetadata; } + public void setAccessTokenMetadata(String accessTokenMetadata) { this.accessTokenMetadata = accessTokenMetadata; } + public String getAccessTokenScopes() { return accessTokenScopes; } + public void setAccessTokenScopes(String accessTokenScopes) { this.accessTokenScopes = accessTokenScopes; } + public String getRefreshTokenValue() { return refreshTokenValue; } + public void setRefreshTokenValue(String refreshTokenValue) { this.refreshTokenValue = refreshTokenValue; } + public Instant getRefreshTokenIssuedAt() { return refreshTokenIssuedAt; } + public void setRefreshTokenIssuedAt(Instant refreshTokenIssuedAt) { this.refreshTokenIssuedAt = refreshTokenIssuedAt; } + public Instant getRefreshTokenExpiresAt() { return refreshTokenExpiresAt; } + public void setRefreshTokenExpiresAt(Instant refreshTokenExpiresAt) { this.refreshTokenExpiresAt = refreshTokenExpiresAt; } + public String getRefreshTokenMetadata() { return refreshTokenMetadata; } + public void setRefreshTokenMetadata(String refreshTokenMetadata) { this.refreshTokenMetadata = refreshTokenMetadata; } + public String getClientName() { return clientName; } + public void setClientName(String clientName) { this.clientName = clientName; } + public Instant getLastUsedAt() { return lastUsedAt; } + public void setLastUsedAt(Instant lastUsedAt) { this.lastUsedAt = lastUsedAt; } +} diff --git a/src/main/java/com/example/AviaryService/entity/OAuthConsentEntity.java b/src/main/java/com/example/AviaryService/entity/OAuthConsentEntity.java new file mode 100644 index 0000000..65caa19 --- /dev/null +++ b/src/main/java/com/example/AviaryService/entity/OAuthConsentEntity.java @@ -0,0 +1,60 @@ +package com.example.AviaryService.entity; + +import java.io.Serializable; +import java.util.Objects; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.IdClass; +import jakarta.persistence.Table; + +// The scopes an owner approved for one assistant, so the consent page is only +// shown once. Deleted together with the authorization on disconnect. +@Entity +@Table(name = "oauth_consents") +@IdClass(OAuthConsentEntity.Key.class) +public class OAuthConsentEntity { + + @Id + @Column(length = 1000) + private String registeredClientId; + + @Id + private String principalName; + + @Column(length = 1000) + private String authorities; + + public String getRegisteredClientId() { return registeredClientId; } + public void setRegisteredClientId(String registeredClientId) { this.registeredClientId = registeredClientId; } + public String getPrincipalName() { return principalName; } + public void setPrincipalName(String principalName) { this.principalName = principalName; } + public String getAuthorities() { return authorities; } + public void setAuthorities(String authorities) { this.authorities = authorities; } + + public static class Key implements Serializable { + private String registeredClientId; + private String principalName; + + public Key() {} + + public Key(String registeredClientId, String principalName) { + this.registeredClientId = registeredClientId; + this.principalName = principalName; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof Key k)) return false; + return Objects.equals(registeredClientId, k.registeredClientId) + && Objects.equals(principalName, k.principalName); + } + + @Override + public int hashCode() { + return Objects.hash(registeredClientId, principalName); + } + } +} diff --git a/src/main/java/com/example/AviaryService/entity/TimelineImportRecord.java b/src/main/java/com/example/AviaryService/entity/TimelineImportRecord.java new file mode 100644 index 0000000..7ba335f --- /dev/null +++ b/src/main/java/com/example/AviaryService/entity/TimelineImportRecord.java @@ -0,0 +1,53 @@ +package com.example.AviaryService.entity; + +import java.time.Instant; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; + +// One confirmed import: who, when, which assistant, how many items. Shown on +// the Connected assistants page so an owner can see what an assistant added. +@Entity +@Table(name = "timeline_import_records") +public class TimelineImportRecord { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(optional = false) + @JoinColumn(name = "user_id", nullable = false) + private User user; + + private Long proposalId; + + @Column(length = 1000) + private String clientId; + + private String clientName; + + private int itemCount; + + @Column(nullable = false) + private Instant importedAt; + + public Long getId() { return id; } + public User getUser() { return user; } + public void setUser(User user) { this.user = user; } + public Long getProposalId() { return proposalId; } + public void setProposalId(Long proposalId) { this.proposalId = proposalId; } + public String getClientId() { return clientId; } + public void setClientId(String clientId) { this.clientId = clientId; } + public String getClientName() { return clientName; } + public void setClientName(String clientName) { this.clientName = clientName; } + public int getItemCount() { return itemCount; } + public void setItemCount(int itemCount) { this.itemCount = itemCount; } + public Instant getImportedAt() { return importedAt; } + public void setImportedAt(Instant importedAt) { this.importedAt = importedAt; } +} diff --git a/src/main/java/com/example/AviaryService/mcp/FlightTools.java b/src/main/java/com/example/AviaryService/mcp/FlightTools.java new file mode 100644 index 0000000..e58e4bd --- /dev/null +++ b/src/main/java/com/example/AviaryService/mcp/FlightTools.java @@ -0,0 +1,36 @@ +package com.example.AviaryService.mcp; + +import java.util.List; + +import org.springframework.ai.tool.annotation.Tool; +import org.springframework.stereotype.Component; + +import com.example.AviaryService.entity.User; +import com.example.AviaryService.services.flights.FlightLogService; + + +//MCP tools for flight logs. Thin door in front of FlightLogService. +@Component +public class FlightTools { + + //Only what the AI needs, never include the user (it holds the password hash) + public record FlightSummary(Long id, String from, String to, Double blockTimeOut, Double blockTimeIn) {} + + private final FlightLogService flightLogService; + private final McpCurrentUser currentUser; + + public FlightTools(FlightLogService flightLogService, McpCurrentUser currentUser) { + this.flightLogService = flightLogService; + this.currentUser = currentUser; + } + + @Tool(name = "list_flights", description = "List the owner's logged flights, newest first.") + public List listFlights() { + currentUser.requireScope("aviary.read"); + User user = currentUser.require(); + return flightLogService.listFor(user).stream() + .map(f -> new FlightSummary(f.getId(), f.getFromAirport(), f.getToAirport(), f.getBlockTimeOut(), f.getBlockTimeIn())) + .toList(); + } + +} diff --git a/src/main/java/com/example/AviaryService/mcp/McpConfig.java b/src/main/java/com/example/AviaryService/mcp/McpConfig.java new file mode 100644 index 0000000..9cf4891 --- /dev/null +++ b/src/main/java/com/example/AviaryService/mcp/McpConfig.java @@ -0,0 +1,16 @@ +package com.example.AviaryService.mcp; + +import org.springframework.ai.tool.ToolCallbackProvider; +import org.springframework.ai.tool.method.MethodToolCallbackProvider; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class McpConfig { + + @Bean + ToolCallbackProvider aviaryTools(FlightTools flightTools, TimelineImportTools timelineImportTools) { + return MethodToolCallbackProvider.builder().toolObjects(flightTools, timelineImportTools).build(); + } + +} diff --git a/src/main/java/com/example/AviaryService/mcp/McpCurrentUser.java b/src/main/java/com/example/AviaryService/mcp/McpCurrentUser.java new file mode 100644 index 0000000..22f24f7 --- /dev/null +++ b/src/main/java/com/example/AviaryService/mcp/McpCurrentUser.java @@ -0,0 +1,58 @@ +package com.example.AviaryService.mcp; + +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; +import org.springframework.stereotype.Component; + +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.UserRepository; + +// Who an MCP tool call is acting for: the owner the access token was issued +// to. Every tool goes through here, so no tool can pick a user on its own. +@Component +public class McpCurrentUser { + + private final UserRepository userRepository; + + public McpCurrentUser(UserRepository userRepository) { + this.userRepository = userRepository; + } + + // The token's owner. Throws instead of returning null so a tool can never + // fall through to "no user" and touch someone else's rows. + public User require() { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth == null || !auth.isAuthenticated() || auth.getName() == null) { + throw new AccessDeniedException("Not signed in"); + } + User user = userRepository.findByUsername(auth.getName()); + if (user == null) { + throw new AccessDeniedException("Account not found"); + } + return user; + } + + // The assistant's client_id (its metadata URL), or null outside a real + // token -- recorded on proposals so the owner can see which assistant + // imported what. + public String clientId() { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth != null && auth.getPrincipal() instanceof OAuth2AuthenticatedPrincipal principal) { + Object id = principal.getAttribute("client_id"); + return id == null ? null : id.toString(); + } + return null; + } + + // The token was granted this scope, e.g. "aviary.timeline.import". + public void requireScope(String scope) { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + boolean granted = auth != null && auth.getAuthorities().stream() + .anyMatch(a -> a.getAuthority().equals("SCOPE_" + scope)); + if (!granted) { + throw new AccessDeniedException("This assistant was not granted " + scope); + } + } +} diff --git a/src/main/java/com/example/AviaryService/mcp/TimelineImportTools.java b/src/main/java/com/example/AviaryService/mcp/TimelineImportTools.java new file mode 100644 index 0000000..dd4144c --- /dev/null +++ b/src/main/java/com/example/AviaryService/mcp/TimelineImportTools.java @@ -0,0 +1,125 @@ +package com.example.AviaryService.mcp; + +import java.time.LocalDate; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.ai.tool.annotation.Tool; +import org.springframework.ai.tool.annotation.ToolParam; +import org.springframework.stereotype.Component; + +import com.example.AviaryService.entity.User; +import com.example.AviaryService.oauth.CimdRegisteredClientRepository; +import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.services.imports.TimelineImportService; +import com.example.AviaryService.services.imports.TimelineImportService.ImportResult; +import com.example.AviaryService.util.DueDates; +import com.example.AviaryService.util.Formatting; +import com.example.AviaryService.util.TimelineImportRules; +import com.example.AviaryService.util.TimelineImportRules.InputItem; +import com.example.AviaryService.util.TimelineImportRules.RejectedRow; + +// MCP tools for importing a service timeline. Thin door in front of +// TimelineImportService: check scope, resolve the token's owner, delegate. +// Outputs are records that never include the User (it holds the password hash). +@Component +public class TimelineImportTools { + + public record ImportFormat(Map itemFields, List rules, int maxItems, String example) {} + + public record TimelineRow(Long id, String item, String description, boolean isTitle, + String lastDone, String due, String cycle, String timeLeft) {} + + private final TimelineImportService importService; + private final ServiceTimelineRepository timelineRepository; + private final McpCurrentUser currentUser; + + public TimelineImportTools(TimelineImportService importService, ServiceTimelineRepository timelineRepository, + McpCurrentUser currentUser) { + this.importService = importService; + this.timelineRepository = timelineRepository; + this.currentUser = currentUser; + } + + @Tool(name = "get_import_format", description = """ + How Aviary service timeline items must look, with the rules and an example. Call this first, then \ + convert the owner's maintenance records (any format) into these items before proposing.""") + public ImportFormat getImportFormat() { + currentUser.requireScope(CimdRegisteredClientRepository.SCOPE_READ); + Map fields = new LinkedHashMap<>(); + fields.put("item", "required: the maintenance item's name, up to 255 characters"); + fields.put("description", "optional, up to 255 characters"); + fields.put("isTitle", "true for a heading row that groups the items under it"); + fields.put("lastDoneDate", "YYYY-MM-DD"); + fields.put("lastDoneHours", "time in service hours when last done, 0 or more"); + fields.put("cycleCalendarValue", "whole number 1-1200"); + fields.put("cycleCalendarUnit", "DAYS, MONTHS, or YEARS"); + fields.put("cycleHours", "hours interval, above 0"); + fields.put("dueDateDate", "YYYY-MM-DD, only if no interval is known"); + fields.put("dueDateHours", "hours, only if no interval is known"); + fields.put("dateAmbiguous", "true if you weren't sure which date was meant"); + fields.put("onCondition", "true for an item with no fixed interval (inspected/replaced on condition); it needs no dates"); + fields.put("sourceRow", "the original line from the owner's records"); + return new ImportFormat(fields, TimelineImportRules.RULES, TimelineImportRules.MAX_ITEMS, + TimelineImportRules.FORMAT_EXAMPLE); + } + + @Tool(name = "list_service_timeline", description = "The owner's current service timeline items, in order.") + public List listServiceTimeline() { + currentUser.requireScope(CimdRegisteredClientRepository.SCOPE_READ); + User user = currentUser.require(); + LocalDate today = LocalDate.now(); + return timelineRepository.findByUserOrderByTimelineOrderAsc(user).stream() + .map(t -> new TimelineRow(t.getId(), t.getItem(), t.getDescription(), t.getIsTitle(), + join(t.getLastDoneDate(), t.getLastDoneHours()), + join(t.getDueDateDate(), t.getDueDateHours()), + Formatting.formatCycle(t.getCycleCalendarValue(), t.getCycleCalendarUnit(), t.getCycleHours()), + t.getIsTitle() ? null + : DueDates.formatTimeLeft(t.getDueDateDate(), t.getDueDateHours(), today, user.getTimeInServiceHours()))) + .toList(); + } + + @Tool(name = "propose_timeline_import", description = """ + Preview importing service timeline items. Send every maintenance item in the owner's records -- an item \ + only needs a name. Changes nothing: returns a proposal with the items as Aviary would store them, flags \ + and notes for the owner to check, and rows that can't be imported with reasons. Show the owner the \ + proposal before confirming. Calling this again replaces the previous proposal (use it to revise).""") + public ImportResult proposeTimelineImport( + @ToolParam(description = "Items converted from the owner's records; see get_import_format") List items, + @ToolParam(description = "Rows that are not maintenance items at all, each with a reason. Never put a real item here just because it has no dates.", required = false) + List rejectedBySource) { + currentUser.requireScope(CimdRegisteredClientRepository.SCOPE_IMPORT); + User user = currentUser.require(); + return importService.propose(user, items, rejectedBySource, currentUser.clientId()); + } + + @Tool(name = "continue_poor_fit", description = """ + For a POOR_FIT proposal: the owner agreed to continue with only the rows that fit. Returns the proposal, \ + which can then be confirmed.""") + public ImportResult continuePoorFit(@ToolParam(description = "proposalId from propose_timeline_import") Long proposalId) { + currentUser.requireScope(CimdRegisteredClientRepository.SCOPE_IMPORT); + return importService.continuePoorFit(currentUser.require(), proposalId); + } + + @Tool(name = "confirm_timeline_import", description = """ + Add a proposal's items to the owner's service timeline. Only call this after the owner has seen the \ + proposal and said to go ahead. Items matching ones already on the timeline are skipped unless listed in \ + addDuplicatesAnyway. Existing items are never changed.""") + public ImportResult confirmTimelineImport( + @ToolParam(description = "proposalId from propose_timeline_import") Long proposalId, + @ToolParam(description = "Indexes of DUPLICATE_EXISTING items the owner wants added anyway", required = false) + List addDuplicatesAnyway) { + currentUser.requireScope(CimdRegisteredClientRepository.SCOPE_IMPORT); + return importService.confirm(currentUser.require(), proposalId, + addDuplicatesAnyway == null ? null : new HashSet<>(addDuplicatesAnyway)); + } + + private static String join(String date, String hours) { + String d = date == null ? "" : date; + String h = hours == null ? "" : hours; + String s = (d + " " + h).trim(); + return s.isEmpty() ? null : s; + } +} diff --git a/src/main/java/com/example/AviaryService/oauth/AuthorizationServerConfig.java b/src/main/java/com/example/AviaryService/oauth/AuthorizationServerConfig.java new file mode 100644 index 0000000..f2b4ec9 --- /dev/null +++ b/src/main/java/com/example/AviaryService/oauth/AuthorizationServerConfig.java @@ -0,0 +1,215 @@ +package com.example.AviaryService.oauth; + +import java.net.URI; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; +import org.springframework.http.MediaType; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.oauth2.core.OAuth2Error; +import org.springframework.security.oauth2.core.OAuth2ErrorCodes; +import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeRequestAuthenticationContext; +import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeRequestAuthenticationException; +import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeRequestAuthenticationProvider; +import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeRequestAuthenticationToken; +import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeRequestAuthenticationValidator; +import org.springframework.security.oauth2.server.authorization.client.RegisteredClient; +import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer; +import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings; +import org.springframework.security.oauth2.server.authorization.web.authentication.OAuth2AuthorizationCodeRequestAuthenticationConverter; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; +import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; + +// Aviary is its own OAuth authorization server so an AI assistant can sign in +// as an owner (MCP auth spec). Owners sign in on the normal /login page and +// approve the assistant on /oauth2/consent. Assistants are public clients +// identified by a Client ID Metadata Document, must use PKCE (S256), and get +// opaque access tokens that /mcp checks against the database. +@Configuration +public class AuthorizationServerConfig { + + private static final String ALL_SCOPES = + CimdRegisteredClientRepository.SCOPE_READ + " " + CimdRegisteredClientRepository.SCOPE_IMPORT; + + @Bean + @Order(0) + public SecurityFilterChain authorizationServerFilterChain(HttpSecurity http) throws Exception { + OAuth2AuthorizationServerConfigurer authorizationServer = OAuth2AuthorizationServerConfigurer.authorizationServer(); + OAuth2AuthorizationCodeRequestAuthenticationConverter codeRequestConverter = + new OAuth2AuthorizationCodeRequestAuthenticationConverter(); + + http + .securityMatcher(authorizationServer.getEndpointsMatcher()) + .with(authorizationServer, as -> as + .authorizationEndpoint(endpoint -> endpoint + .consentPage("/oauth2/consent") + // An assistant that asks for no scope gets both; an empty + // grant would just fail on every /mcp call. + .authorizationRequestConverters(converters -> converters.add(0, request -> + isCodeRequestWithoutScope(request) + ? codeRequestConverter.convert(new DefaultScopeRequest(request)) + : null)) + .authenticationProviders(configureRedirectUriValidator())) + .authorizationServerMetadataEndpoint(metadata -> metadata + .authorizationServerMetadataCustomizer(builder -> builder + .tokenEndpointAuthenticationMethods(methods -> { + methods.clear(); + methods.add("none"); + }) + .codeChallengeMethods(methods -> { + methods.clear(); + methods.add("S256"); + }) + .scopes(scopes -> { + scopes.add(CimdRegisteredClientRepository.SCOPE_READ); + scopes.add(CimdRegisteredClientRepository.SCOPE_IMPORT); + }) + .claim("client_id_metadata_document_supported", true)))) + .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) + // Not signed in yet -> Aviary's normal login page, then back here. + .exceptionHandling(exceptions -> exceptions.defaultAuthenticationEntryPointFor( + new LoginUrlAuthenticationEntryPoint("/login"), + new MediaTypeRequestMatcher(MediaType.TEXT_HTML))); + return http.build(); + } + + @Bean + public AuthorizationServerSettings authorizationServerSettings(@Value("${aviary.oauth.issuer}") String issuer) { + return AuthorizationServerSettings.builder().issuer(issuer).build(); + } + + private static boolean isCodeRequestWithoutScope(HttpServletRequest request) { + return "GET".equals(request.getMethod()) + && "code".equals(request.getParameter("response_type")) + && (request.getParameter("scope") == null || request.getParameter("scope").isBlank()); + } + + private static class DefaultScopeRequest extends HttpServletRequestWrapper { + DefaultScopeRequest(HttpServletRequest request) { + super(request); + } + + @Override + public String getParameter(String name) { + return "scope".equals(name) ? ALL_SCOPES : super.getParameter(name); + } + + @Override + public String[] getParameterValues(String name) { + return "scope".equals(name) ? new String[] { ALL_SCOPES } : super.getParameterValues(name); + } + + // Spring Authorization Server reads GET parameters from the raw query + // string, so the default scope has to be added there too. + @Override + public String getQueryString() { + String original = super.getQueryString() == null ? "" : super.getQueryString(); + StringBuilder qs = new StringBuilder(); + for (String part : original.split("&")) { + if (part.isEmpty() || part.equals("scope") || part.startsWith("scope=")) continue; + if (qs.length() > 0) qs.append('&'); + qs.append(part); + } + if (qs.length() > 0) qs.append('&'); + qs.append("scope=").append(java.net.URLEncoder.encode(ALL_SCOPES, java.nio.charset.StandardCharsets.UTF_8)); + return qs.toString(); + } + + @Override + public Map getParameterMap() { + Map map = new HashMap<>(super.getParameterMap()); + map.put("scope", new String[] { ALL_SCOPES }); + return Collections.unmodifiableMap(map); + } + } + + private static Consumer> configureRedirectUriValidator() { + return providers -> providers.forEach(provider -> { + if (provider instanceof OAuth2AuthorizationCodeRequestAuthenticationProvider codeProvider) { + Consumer redirectCheck = + AuthorizationServerConfig::validateRedirectUri; + codeProvider.setAuthenticationValidator( + redirectCheck.andThen(OAuth2AuthorizationCodeRequestAuthenticationValidator.DEFAULT_SCOPE_VALIDATOR)); + } + }); + } + + // Exact match against the client's metadata document, except that a + // loopback redirect (localhost / 127.0.0.1 / [::1]) may use any port -- + // desktop assistants listen on a random local port + // (RFC 8252 section 7.3). Spring's default validator rejects "localhost". + static void validateRedirectUri(OAuth2AuthorizationCodeRequestAuthenticationContext context) { + OAuth2AuthorizationCodeRequestAuthenticationToken auth = context.getAuthentication(); + RegisteredClient client = context.getRegisteredClient(); + String requested = auth.getRedirectUri(); + Set registered = client.getRedirectUris(); + + if (requested == null || requested.isBlank()) { + if (registered.size() == 1) return; + throw invalidRedirect(auth); + } + if (registered.contains(requested)) return; + + URI req = parse(requested); + if (req != null && isLoopback(req) && req.getFragment() == null) { + for (String r : registered) { + URI reg = parse(r); + if (reg != null && isLoopback(reg) + && req.getScheme().equalsIgnoreCase(reg.getScheme()) + && samePath(req, reg) + && java.util.Objects.equals(req.getRawQuery(), reg.getRawQuery())) { + return; + } + } + } + throw invalidRedirect(auth); + } + + private static URI parse(String uri) { + try { + URI u = URI.create(uri); + return u.getScheme() == null || u.getHost() == null ? null : u; + } catch (Exception e) { + return null; + } + } + + private static boolean isLoopback(URI uri) { + String host = uri.getHost(); + return "http".equalsIgnoreCase(uri.getScheme()) + && ("localhost".equalsIgnoreCase(host) || "127.0.0.1".equals(host) + || "[::1]".equals(host) || "::1".equals(host)); + } + + private static boolean samePath(URI a, URI b) { + String pa = a.getPath() == null || a.getPath().isEmpty() ? "/" : a.getPath(); + String pb = b.getPath() == null || b.getPath().isEmpty() ? "/" : b.getPath(); + return pa.equals(pb); + } + + // Built without the redirect URI so Spring shows an error instead of + // redirecting to the address that just failed the check. + private static OAuth2AuthorizationCodeRequestAuthenticationException invalidRedirect( + OAuth2AuthorizationCodeRequestAuthenticationToken auth) { + OAuth2AuthorizationCodeRequestAuthenticationToken withoutRedirect = + new OAuth2AuthorizationCodeRequestAuthenticationToken(auth.getAuthorizationUri(), auth.getClientId(), + (org.springframework.security.core.Authentication) auth.getPrincipal(), null, auth.getState(), + auth.getScopes(), auth.getAdditionalParameters()); + withoutRedirect.setAuthenticated(true); + return new OAuth2AuthorizationCodeRequestAuthenticationException( + new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST, "redirect_uri is not registered for this client", null), + withoutRedirect); + } +} diff --git a/src/main/java/com/example/AviaryService/oauth/CimdFetcher.java b/src/main/java/com/example/AviaryService/oauth/CimdFetcher.java new file mode 100644 index 0000000..6882199 --- /dev/null +++ b/src/main/java/com/example/AviaryService/oauth/CimdFetcher.java @@ -0,0 +1,200 @@ +package com.example.AviaryService.oauth; + +import java.io.IOException; +import java.io.InputStream; +import java.net.InetAddress; +import java.net.URI; +import java.net.UnknownHostException; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +import org.springframework.stereotype.Component; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +// Downloads an AI assistant's Client ID Metadata Document (CIMD): the JSON at +// its client_id URL that names it and lists where to send the user back after +// sign-in. The URL comes from whoever starts a sign-in, so it is untrusted -- +// this is the server-side fetch an attacker would aim at Aviary's own network +// (SSRF). Hence: https only, no IP-literal hosts, the host must not resolve +// to a private/loopback/link-local address, no redirects, small body, short +// timeout. +@Component +public class CimdFetcher { + + static final int MAX_BYTES = 5 * 1024; + static final Duration TIMEOUT = Duration.ofSeconds(5); + + public record ClientMetadata(String clientId, String clientName, List redirectUris) {} + + // Seams for tests: DNS lookup and the HTTP GET. + interface Resolver { + InetAddress[] resolve(String host) throws UnknownHostException; + } + + interface Transport { + // Returns the body, or throws if the status isn't 200 or the body is too big. + byte[] get(URI uri) throws IOException; + } + + private final Resolver resolver; + private final Transport transport; + private final ObjectMapper objectMapper = new ObjectMapper(); + + public CimdFetcher() { + this(InetAddress::getAllByName, new HttpTransport(TIMEOUT)); + } + + CimdFetcher(Resolver resolver, Transport transport) { + this.resolver = resolver; + this.transport = transport; + } + + // Throws IllegalArgumentException with a short reason when the URL or + // document isn't acceptable. + public ClientMetadata fetch(String clientId) { + URI uri = checkUrl(clientId); + checkHost(uri.getHost()); + + byte[] body; + try { + body = transport.get(uri); + } catch (IOException e) { + throw new IllegalArgumentException("Could not load client metadata: " + e.getMessage()); + } + + JsonNode doc; + try { + doc = objectMapper.readTree(body); + } catch (IOException e) { + throw new IllegalArgumentException("Client metadata is not valid JSON"); + } + if (doc == null || !doc.isObject()) { + throw new IllegalArgumentException("Client metadata is not a JSON object"); + } + if (!clientId.equals(doc.path("client_id").asText(null))) { + throw new IllegalArgumentException("client_id in the document does not match its URL"); + } + List redirectUris = new ArrayList<>(); + doc.path("redirect_uris").forEach(n -> { + if (n.isTextual() && !n.asText().isBlank()) redirectUris.add(n.asText()); + }); + if (redirectUris.isEmpty()) { + throw new IllegalArgumentException("Client metadata lists no redirect_uris"); + } + String name = doc.path("client_name").asText(null); + if (name == null || name.isBlank()) name = uri.getHost(); + if (name.length() > 100) name = name.substring(0, 100); + return new ClientMetadata(clientId, name, List.copyOf(redirectUris)); + } + + // A CIMD client_id: an https URL with a path and no credentials or fragment. + static boolean looksLikeCimdUrl(String clientId) { + try { + checkUrl(clientId); + return true; + } catch (IllegalArgumentException e) { + return false; + } + } + + private static URI checkUrl(String clientId) { + URI uri; + try { + uri = URI.create(clientId); + } catch (Exception e) { + throw new IllegalArgumentException("client_id is not a URL"); + } + if (!"https".equalsIgnoreCase(uri.getScheme())) { + throw new IllegalArgumentException("client_id must be an https URL"); + } + if (uri.getHost() == null || uri.getUserInfo() != null || uri.getFragment() != null) { + throw new IllegalArgumentException("client_id URL is not allowed"); + } + if (uri.getPath() == null || uri.getPath().isEmpty() || "/".equals(uri.getPath())) { + throw new IllegalArgumentException("client_id URL must have a path"); + } + return uri; + } + + private void checkHost(String host) { + String h = host.startsWith("[") ? host.substring(1, host.length() - 1) : host; + if (isIpLiteral(h)) { + throw new IllegalArgumentException("client_id host must be a name, not an IP address"); + } + InetAddress[] addresses; + try { + addresses = resolver.resolve(h); + } catch (UnknownHostException e) { + throw new IllegalArgumentException("client_id host does not resolve"); + } + if (addresses == null || addresses.length == 0) { + throw new IllegalArgumentException("client_id host does not resolve"); + } + for (InetAddress a : addresses) { + if (a.isLoopbackAddress() || a.isSiteLocalAddress() || a.isLinkLocalAddress() + || a.isAnyLocalAddress() || a.isMulticastAddress() || isUniqueLocalV6(a) || isCarrierNat(a)) { + throw new IllegalArgumentException("client_id host points to a private address"); + } + } + } + + private static boolean isIpLiteral(String host) { + return host.matches("[0-9.]+") || host.contains(":"); + } + + // fc00::/7 + private static boolean isUniqueLocalV6(InetAddress a) { + byte[] b = a.getAddress(); + return b.length == 16 && (b[0] & 0xFE) == 0xFC; + } + + // 100.64.0.0/10 + private static boolean isCarrierNat(InetAddress a) { + byte[] b = a.getAddress(); + return b.length == 4 && (b[0] & 0xFF) == 100 && (b[1] & 0xC0) == 64; + } + + static class HttpTransport implements Transport { + private final Duration timeout; + private final HttpClient client; + + HttpTransport(Duration timeout) { + this.timeout = timeout; + this.client = HttpClient.newBuilder() + .connectTimeout(timeout) + .followRedirects(HttpClient.Redirect.NEVER) + .build(); + } + + @Override + public byte[] get(URI uri) throws IOException { + HttpRequest request = HttpRequest.newBuilder(uri) + .timeout(timeout) + .header("Accept", "application/json") + .GET().build(); + HttpResponse response; + try { + response = client.send(request, HttpResponse.BodyHandlers.ofInputStream()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("interrupted"); + } + try (InputStream in = response.body()) { + if (response.statusCode() != 200) { + throw new IOException("status " + response.statusCode()); + } + byte[] body = in.readNBytes(MAX_BYTES + 1); + if (body.length > MAX_BYTES) { + throw new IOException("document larger than " + MAX_BYTES + " bytes"); + } + return body; + } + } + } +} diff --git a/src/main/java/com/example/AviaryService/oauth/CimdRegisteredClientRepository.java b/src/main/java/com/example/AviaryService/oauth/CimdRegisteredClientRepository.java new file mode 100644 index 0000000..baf4a56 --- /dev/null +++ b/src/main/java/com/example/AviaryService/oauth/CimdRegisteredClientRepository.java @@ -0,0 +1,110 @@ +package com.example.AviaryService.oauth; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.oauth2.core.AuthorizationGrantType; +import org.springframework.security.oauth2.core.ClientAuthenticationMethod; +import org.springframework.security.oauth2.server.authorization.client.RegisteredClient; +import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository; +import org.springframework.security.oauth2.server.authorization.settings.ClientSettings; +import org.springframework.security.oauth2.server.authorization.settings.OAuth2TokenFormat; +import org.springframework.security.oauth2.server.authorization.settings.TokenSettings; +import org.springframework.stereotype.Component; + +// Aviary has no client sign-up. An AI assistant identifies itself with an +// https client_id URL (Client ID Metadata Document, the MCP spec's preferred +// method), and this builds the client from that document on demand. Dynamic +// Client Registration is deliberately unsupported -- save() refuses. +@Component +public class CimdRegisteredClientRepository implements RegisteredClientRepository { + + public static final String SCOPE_READ = "aviary.read"; + public static final String SCOPE_IMPORT = "aviary.timeline.import"; + + // Spring Authorization Server 1.4 never gives public clients a refresh + // token, so the access token is the whole session. Kept long enough that + // the owner isn't sent back to sign in every hour; safe because tokens are + // opaque, stored hashed, and Disconnect kills one on its next request. + static final Duration ACCESS_TOKEN_TTL = Duration.ofDays(7); + static final Duration CACHE_TTL = Duration.ofHours(1); + + private record Cached(RegisteredClient client, Instant fetchedAt) {} + + private final CimdFetcher fetcher; + private final Clock clock; + private final Map cache = new ConcurrentHashMap<>(); + + @Autowired + public CimdRegisteredClientRepository(CimdFetcher fetcher) { + this(fetcher, Clock.systemUTC()); + } + + CimdRegisteredClientRepository(CimdFetcher fetcher, Clock clock) { + this.fetcher = fetcher; + this.clock = clock; + } + + @Override + public void save(RegisteredClient registeredClient) { + throw new UnsupportedOperationException("Client registration is not supported; use a Client ID Metadata Document"); + } + + // The client's id is its URL, so both lookups are the same. + @Override + public RegisteredClient findById(String id) { + return findByClientId(id); + } + + // null when the URL isn't a usable CIMD document -- Spring then rejects + // the sign-in with invalid_client. + @Override + public RegisteredClient findByClientId(String clientId) { + if (clientId == null || !CimdFetcher.looksLikeCimdUrl(clientId)) { + return null; + } + Cached hit = cache.get(clientId); + if (hit != null && hit.fetchedAt().plus(CACHE_TTL).isAfter(clock.instant())) { + return hit.client(); + } + CimdFetcher.ClientMetadata metadata; + try { + metadata = fetcher.fetch(clientId); + } catch (IllegalArgumentException e) { + // The assistant's site is down or its document broke: keep using + // the last good copy rather than cutting off a connected assistant. + return hit != null ? hit.client() : null; + } + RegisteredClient client = toClient(metadata); + cache.put(clientId, new Cached(client, clock.instant())); + return client; + } + + private static RegisteredClient toClient(CimdFetcher.ClientMetadata metadata) { + return RegisteredClient.withId(metadata.clientId()) + .clientId(metadata.clientId()) + .clientName(metadata.clientName()) + .clientAuthenticationMethod(ClientAuthenticationMethod.NONE) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN) + .redirectUris(uris -> uris.addAll(metadata.redirectUris())) + .scope(SCOPE_READ) + .scope(SCOPE_IMPORT) + .clientSettings(ClientSettings.builder() + .requireProofKey(true) + .requireAuthorizationConsent(true) + .build()) + .tokenSettings(TokenSettings.builder() + .accessTokenFormat(OAuth2TokenFormat.REFERENCE) + .accessTokenTimeToLive(ACCESS_TOKEN_TTL) + .authorizationCodeTimeToLive(Duration.ofMinutes(5)) + .refreshTokenTimeToLive(Duration.ofDays(30)) + .reuseRefreshTokens(false) + .build()) + .build(); + } +} diff --git a/src/main/java/com/example/AviaryService/oauth/JpaOAuth2AuthorizationConsentService.java b/src/main/java/com/example/AviaryService/oauth/JpaOAuth2AuthorizationConsentService.java new file mode 100644 index 0000000..2a71bed --- /dev/null +++ b/src/main/java/com/example/AviaryService/oauth/JpaOAuth2AuthorizationConsentService.java @@ -0,0 +1,76 @@ +package com.example.AviaryService.oauth; + +import java.util.HashSet; +import java.util.Set; + +import org.springframework.dao.DataRetrievalFailureException; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsent; +import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService; +import org.springframework.security.oauth2.server.authorization.client.RegisteredClient; +import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import com.example.AviaryService.entity.OAuthConsentEntity; +import com.example.AviaryService.repositories.OAuthConsentRepository; + +// Remembers which scopes an owner approved for an assistant. +@Service +@Transactional +public class JpaOAuth2AuthorizationConsentService implements OAuth2AuthorizationConsentService { + + private final OAuthConsentRepository repository; + private final RegisteredClientRepository registeredClientRepository; + + public JpaOAuth2AuthorizationConsentService(OAuthConsentRepository repository, + RegisteredClientRepository registeredClientRepository) { + this.repository = repository; + this.registeredClientRepository = registeredClientRepository; + } + + @Override + public void save(OAuth2AuthorizationConsent consent) { + repository.save(toEntity(consent)); + } + + @Override + public void remove(OAuth2AuthorizationConsent consent) { + repository.deleteById(new OAuthConsentEntity.Key(consent.getRegisteredClientId(), consent.getPrincipalName())); + } + + @Override + @Transactional(readOnly = true) + public OAuth2AuthorizationConsent findById(String registeredClientId, String principalName) { + return repository.findById(new OAuthConsentEntity.Key(registeredClientId, principalName)) + .map(this::toObject).orElse(null); + } + + private OAuth2AuthorizationConsent toObject(OAuthConsentEntity entity) { + RegisteredClient client = registeredClientRepository.findById(entity.getRegisteredClientId()); + if (client == null) { + throw new DataRetrievalFailureException( + "The client '" + entity.getRegisteredClientId() + "' could not be loaded."); + } + OAuth2AuthorizationConsent.Builder builder = + OAuth2AuthorizationConsent.withId(entity.getRegisteredClientId(), entity.getPrincipalName()); + for (String authority : StringUtils.commaDelimitedListToSet(entity.getAuthorities())) { + builder.authority(new SimpleGrantedAuthority(authority)); + } + return builder.build(); + } + + private OAuthConsentEntity toEntity(OAuth2AuthorizationConsent consent) { + OAuthConsentEntity entity = new OAuthConsentEntity(); + entity.setRegisteredClientId(consent.getRegisteredClientId()); + entity.setPrincipalName(consent.getPrincipalName()); + Set authorities = new HashSet<>(); + for (GrantedAuthority authority : consent.getAuthorities()) { + authorities.add(authority.getAuthority()); + } + entity.setAuthorities(StringUtils.collectionToCommaDelimitedString(authorities)); + return entity; + } +} diff --git a/src/main/java/com/example/AviaryService/oauth/JpaOAuth2AuthorizationService.java b/src/main/java/com/example/AviaryService/oauth/JpaOAuth2AuthorizationService.java new file mode 100644 index 0000000..7659e74 --- /dev/null +++ b/src/main/java/com/example/AviaryService/oauth/JpaOAuth2AuthorizationService.java @@ -0,0 +1,219 @@ +package com.example.AviaryService.oauth; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Consumer; + +import org.springframework.dao.DataRetrievalFailureException; +import org.springframework.security.jackson2.SecurityJackson2Modules; +import org.springframework.security.oauth2.core.AuthorizationGrantType; +import org.springframework.security.oauth2.core.OAuth2AccessToken; +import org.springframework.security.oauth2.core.OAuth2RefreshToken; +import org.springframework.security.oauth2.core.OAuth2Token; +import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; +import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; +import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationCode; +import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; +import org.springframework.security.oauth2.server.authorization.OAuth2TokenType; +import org.springframework.security.oauth2.server.authorization.client.RegisteredClient; +import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository; +import org.springframework.security.oauth2.server.authorization.jackson2.OAuth2AuthorizationServerJackson2Module; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import com.example.AviaryService.entity.OAuthAuthorizationEntity; +import com.example.AviaryService.repositories.OAuthAuthorizationRepository; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.Module; +import com.fasterxml.jackson.databind.ObjectMapper; + +// Stores OAuth grants in the database (survives dyno restarts) using the +// Spring Authorization Server "core services with JPA" pattern. +// +// Token values are hashed before they are stored or looked up, so a database +// leak doesn't hand out working tokens. A loaded authorization therefore +// carries the hash, not the real token; Spring only uses the loaded token's +// dates and flags, and hash() leaves an already-hashed value alone so saving +// a loaded authorization doesn't hash it twice. +@Service +@Transactional +public class JpaOAuth2AuthorizationService implements OAuth2AuthorizationService { + + static final String HASH_PREFIX = "sha256:"; + + private final OAuthAuthorizationRepository repository; + private final RegisteredClientRepository registeredClientRepository; + private final ObjectMapper objectMapper = new ObjectMapper(); + + public JpaOAuth2AuthorizationService(OAuthAuthorizationRepository repository, + RegisteredClientRepository registeredClientRepository) { + this.repository = repository; + this.registeredClientRepository = registeredClientRepository; + ClassLoader classLoader = JpaOAuth2AuthorizationService.class.getClassLoader(); + List securityModules = SecurityJackson2Modules.getModules(classLoader); + this.objectMapper.registerModules(securityModules); + this.objectMapper.registerModule(new OAuth2AuthorizationServerJackson2Module()); + } + + @Override + public void save(OAuth2Authorization authorization) { + OAuthAuthorizationEntity existing = repository.findById(authorization.getId()).orElse(null); + OAuthAuthorizationEntity entity = toEntity(authorization); + if (existing != null) { + entity.setLastUsedAt(existing.getLastUsedAt()); + if (entity.getClientName() == null) entity.setClientName(existing.getClientName()); + } + repository.save(entity); + } + + @Override + public void remove(OAuth2Authorization authorization) { + repository.deleteById(authorization.getId()); + } + + @Override + @Transactional(readOnly = true) + public OAuth2Authorization findById(String id) { + return repository.findById(id).map(this::toObject).orElse(null); + } + + @Override + @Transactional(readOnly = true) + public OAuth2Authorization findByToken(String token, OAuth2TokenType tokenType) { + if (token == null) return null; + Optional result; + if (tokenType == null) { + String hashed = hash(token); + result = repository.findByState(token) + .or(() -> repository.findByAuthorizationCodeValue(hashed)) + .or(() -> repository.findByAccessTokenValue(hashed)) + .or(() -> repository.findByRefreshTokenValue(hashed)); + } else if (OAuth2ParameterNames.STATE.equals(tokenType.getValue())) { + result = repository.findByState(token); + } else if (OAuth2ParameterNames.CODE.equals(tokenType.getValue())) { + result = repository.findByAuthorizationCodeValue(hash(token)); + } else if (OAuth2TokenType.ACCESS_TOKEN.equals(tokenType)) { + result = repository.findByAccessTokenValue(hash(token)); + } else if (OAuth2TokenType.REFRESH_TOKEN.equals(tokenType)) { + result = repository.findByRefreshTokenValue(hash(token)); + } else { + result = Optional.empty(); + } + return result.map(this::toObject).orElse(null); + } + + // SHA-256 of a token, prefixed so an already-hashed value passes through. + static String hash(String value) { + if (value == null || value.startsWith(HASH_PREFIX)) return value; + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)); + return HASH_PREFIX + HexFormat.of().formatHex(digest); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + private OAuth2Authorization toObject(OAuthAuthorizationEntity entity) { + RegisteredClient registeredClient = registeredClientRepository.findById(entity.getRegisteredClientId()); + if (registeredClient == null) { + throw new DataRetrievalFailureException( + "The client '" + entity.getRegisteredClientId() + "' could not be loaded."); + } + + OAuth2Authorization.Builder builder = OAuth2Authorization.withRegisteredClient(registeredClient) + .id(entity.getId()) + .principalName(entity.getPrincipalName()) + .authorizationGrantType(new AuthorizationGrantType(entity.getAuthorizationGrantType())) + .authorizedScopes(StringUtils.commaDelimitedListToSet(entity.getAuthorizedScopes())) + .attributes(attributes -> attributes.putAll(parseMap(entity.getAttributes()))); + if (entity.getState() != null) { + builder.attribute(OAuth2ParameterNames.STATE, entity.getState()); + } + + if (entity.getAuthorizationCodeValue() != null) { + OAuth2AuthorizationCode code = new OAuth2AuthorizationCode(entity.getAuthorizationCodeValue(), + entity.getAuthorizationCodeIssuedAt(), entity.getAuthorizationCodeExpiresAt()); + builder.token(code, metadata -> metadata.putAll(parseMap(entity.getAuthorizationCodeMetadata()))); + } + if (entity.getAccessTokenValue() != null) { + OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, + entity.getAccessTokenValue(), entity.getAccessTokenIssuedAt(), entity.getAccessTokenExpiresAt(), + StringUtils.commaDelimitedListToSet(entity.getAccessTokenScopes())); + builder.token(accessToken, metadata -> metadata.putAll(parseMap(entity.getAccessTokenMetadata()))); + } + if (entity.getRefreshTokenValue() != null) { + OAuth2RefreshToken refreshToken = new OAuth2RefreshToken(entity.getRefreshTokenValue(), + entity.getRefreshTokenIssuedAt(), entity.getRefreshTokenExpiresAt()); + builder.token(refreshToken, metadata -> metadata.putAll(parseMap(entity.getRefreshTokenMetadata()))); + } + return builder.build(); + } + + private OAuthAuthorizationEntity toEntity(OAuth2Authorization authorization) { + OAuthAuthorizationEntity entity = new OAuthAuthorizationEntity(); + entity.setId(authorization.getId()); + entity.setRegisteredClientId(authorization.getRegisteredClientId()); + entity.setPrincipalName(authorization.getPrincipalName()); + entity.setAuthorizationGrantType(authorization.getAuthorizationGrantType().getValue()); + entity.setAuthorizedScopes(StringUtils.collectionToDelimitedString(authorization.getAuthorizedScopes(), ",")); + entity.setAttributes(writeMap(authorization.getAttributes())); + entity.setState(authorization.getAttribute(OAuth2ParameterNames.STATE)); + + RegisteredClient client = registeredClientRepository.findById(authorization.getRegisteredClientId()); + if (client != null) entity.setClientName(client.getClientName()); + + setTokenValues(authorization.getToken(OAuth2AuthorizationCode.class), + entity::setAuthorizationCodeValue, entity::setAuthorizationCodeIssuedAt, + entity::setAuthorizationCodeExpiresAt, entity::setAuthorizationCodeMetadata); + + OAuth2Authorization.Token accessToken = authorization.getToken(OAuth2AccessToken.class); + setTokenValues(accessToken, entity::setAccessTokenValue, entity::setAccessTokenIssuedAt, + entity::setAccessTokenExpiresAt, entity::setAccessTokenMetadata); + if (accessToken != null && accessToken.getToken().getScopes() != null) { + entity.setAccessTokenScopes(StringUtils.collectionToDelimitedString(accessToken.getToken().getScopes(), ",")); + } + + setTokenValues(authorization.getToken(OAuth2RefreshToken.class), + entity::setRefreshTokenValue, entity::setRefreshTokenIssuedAt, + entity::setRefreshTokenExpiresAt, entity::setRefreshTokenMetadata); + return entity; + } + + private void setTokenValues(OAuth2Authorization.Token token, + Consumer valueConsumer, + Consumer issuedAtConsumer, + Consumer expiresAtConsumer, + Consumer metadataConsumer) { + if (token != null) { + OAuth2Token oAuth2Token = token.getToken(); + valueConsumer.accept(hash(oAuth2Token.getTokenValue())); + issuedAtConsumer.accept(oAuth2Token.getIssuedAt()); + expiresAtConsumer.accept(oAuth2Token.getExpiresAt()); + metadataConsumer.accept(writeMap(token.getMetadata())); + } + } + + private Map parseMap(String data) { + if (data == null) return Map.of(); + try { + return objectMapper.readValue(data, new TypeReference>() {}); + } catch (Exception ex) { + throw new IllegalArgumentException(ex.getMessage(), ex); + } + } + + private String writeMap(Map metadata) { + try { + return objectMapper.writeValueAsString(metadata); + } catch (Exception ex) { + throw new IllegalArgumentException(ex.getMessage(), ex); + } + } +} diff --git a/src/main/java/com/example/AviaryService/oauth/LocalOpaqueTokenIntrospector.java b/src/main/java/com/example/AviaryService/oauth/LocalOpaqueTokenIntrospector.java new file mode 100644 index 0000000..96a4240 --- /dev/null +++ b/src/main/java/com/example/AviaryService/oauth/LocalOpaqueTokenIntrospector.java @@ -0,0 +1,85 @@ +package com.example.AviaryService.oauth; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal; +import org.springframework.security.oauth2.core.OAuth2AccessToken; +import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; +import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; +import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; +import org.springframework.security.oauth2.server.authorization.OAuth2TokenType; +import org.springframework.security.oauth2.server.resource.introspection.BadOpaqueTokenException; +import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import com.example.AviaryService.repositories.OAuthAuthorizationRepository; + +// Checks a /mcp bearer token against the stored grants -- in process, no HTTP +// call. A token is good only while its grant row exists, so Disconnect (which +// deletes the row) cuts the assistant off on its very next request. +@Component +public class LocalOpaqueTokenIntrospector implements OpaqueTokenIntrospector { + + private static final Duration LAST_USED_RESOLUTION = Duration.ofMinutes(1); + + private final OAuth2AuthorizationService authorizationService; + private final OAuthAuthorizationRepository repository; + private final Clock clock; + + @Autowired + public LocalOpaqueTokenIntrospector(OAuth2AuthorizationService authorizationService, + OAuthAuthorizationRepository repository) { + this(authorizationService, repository, Clock.systemUTC()); + } + + LocalOpaqueTokenIntrospector(OAuth2AuthorizationService authorizationService, + OAuthAuthorizationRepository repository, Clock clock) { + this.authorizationService = authorizationService; + this.repository = repository; + this.clock = clock; + } + + @Override + @Transactional + public OAuth2AuthenticatedPrincipal introspect(String token) { + OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); + if (authorization == null) { + throw new BadOpaqueTokenException("Unknown or revoked token"); + } + OAuth2Authorization.Token accessToken = authorization.getAccessToken(); + Instant now = clock.instant(); + if (accessToken == null || accessToken.isInvalidated() + || (accessToken.getToken().getExpiresAt() != null && !accessToken.getToken().getExpiresAt().isAfter(now))) { + throw new BadOpaqueTokenException("Token is no longer active"); + } + + touchLastUsed(authorization.getId(), now); + + List authorities = accessToken.getToken().getScopes().stream() + .map(scope -> (GrantedAuthority) new SimpleGrantedAuthority("SCOPE_" + scope)) + .toList(); + return new DefaultOAuth2AuthenticatedPrincipal(authorization.getPrincipalName(), + Map.of("sub", authorization.getPrincipalName(), "client_id", authorization.getRegisteredClientId()), + authorities); + } + + // "Last used" on the Connected assistants page. Written at most once a + // minute so a busy assistant doesn't turn every call into a DB write. + private void touchLastUsed(String authorizationId, Instant now) { + repository.findById(authorizationId).ifPresent(entity -> { + Instant last = entity.getLastUsedAt(); + if (last == null || last.plus(LAST_USED_RESOLUTION).isBefore(now)) { + entity.setLastUsedAt(now); + repository.save(entity); + } + }); + } +} diff --git a/src/main/java/com/example/AviaryService/oauth/ProtectedResourceMetadataController.java b/src/main/java/com/example/AviaryService/oauth/ProtectedResourceMetadataController.java new file mode 100644 index 0000000..332b99c --- /dev/null +++ b/src/main/java/com/example/AviaryService/oauth/ProtectedResourceMetadataController.java @@ -0,0 +1,31 @@ +package com.example.AviaryService.oauth; + +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +// OAuth Protected Resource Metadata (RFC 9728) for /mcp. An assistant that +// gets a 401 from /mcp reads this to find out where to sign in. +@RestController +public class ProtectedResourceMetadataController { + + private final String issuer; + + public ProtectedResourceMetadataController(@Value("${aviary.oauth.issuer}") String issuer) { + this.issuer = issuer; + } + + @GetMapping("/.well-known/oauth-protected-resource") + public Map metadata() { + return Map.of( + "resource", issuer + "/mcp", + "authorization_servers", List.of(issuer), + "scopes_supported", List.of(CimdRegisteredClientRepository.SCOPE_READ, + CimdRegisteredClientRepository.SCOPE_IMPORT), + "bearer_methods_supported", List.of("header"), + "resource_name", "Aviary"); + } +} diff --git a/src/main/java/com/example/AviaryService/repositories/ImportProposalRepository.java b/src/main/java/com/example/AviaryService/repositories/ImportProposalRepository.java new file mode 100644 index 0000000..37f42ff --- /dev/null +++ b/src/main/java/com/example/AviaryService/repositories/ImportProposalRepository.java @@ -0,0 +1,17 @@ +package com.example.AviaryService.repositories; + +import java.util.Collection; +import java.util.List; +import java.util.Optional; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.example.AviaryService.entity.ImportProposal; +import com.example.AviaryService.entity.User; + +// Every lookup is by owner as well as id -- another owner's proposal id just +// isn't found. +public interface ImportProposalRepository extends JpaRepository { + Optional findByIdAndUser(Long id, User user); + List findByUserAndStatusIn(User user, Collection statuses); +} diff --git a/src/main/java/com/example/AviaryService/repositories/OAuthAuthorizationRepository.java b/src/main/java/com/example/AviaryService/repositories/OAuthAuthorizationRepository.java new file mode 100644 index 0000000..763a92a --- /dev/null +++ b/src/main/java/com/example/AviaryService/repositories/OAuthAuthorizationRepository.java @@ -0,0 +1,18 @@ +package com.example.AviaryService.repositories; + +import java.util.List; +import java.util.Optional; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.example.AviaryService.entity.OAuthAuthorizationEntity; + +// Token values passed in here are already hashed -- see JpaOAuth2AuthorizationService. +public interface OAuthAuthorizationRepository extends JpaRepository { + Optional findByState(String state); + Optional findByAuthorizationCodeValue(String authorizationCode); + Optional findByAccessTokenValue(String accessToken); + Optional findByRefreshTokenValue(String refreshToken); + List findByPrincipalName(String principalName); + Optional findByIdAndPrincipalName(String id, String principalName); +} diff --git a/src/main/java/com/example/AviaryService/repositories/OAuthConsentRepository.java b/src/main/java/com/example/AviaryService/repositories/OAuthConsentRepository.java new file mode 100644 index 0000000..ee69c95 --- /dev/null +++ b/src/main/java/com/example/AviaryService/repositories/OAuthConsentRepository.java @@ -0,0 +1,8 @@ +package com.example.AviaryService.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.example.AviaryService.entity.OAuthConsentEntity; + +public interface OAuthConsentRepository extends JpaRepository { +} diff --git a/src/main/java/com/example/AviaryService/repositories/TimelineImportRecordRepository.java b/src/main/java/com/example/AviaryService/repositories/TimelineImportRecordRepository.java new file mode 100644 index 0000000..71fc91f --- /dev/null +++ b/src/main/java/com/example/AviaryService/repositories/TimelineImportRecordRepository.java @@ -0,0 +1,12 @@ +package com.example.AviaryService.repositories; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.example.AviaryService.entity.TimelineImportRecord; +import com.example.AviaryService.entity.User; + +public interface TimelineImportRecordRepository extends JpaRepository { + List findTop20ByUserOrderByImportedAtDesc(User user); +} diff --git a/src/main/java/com/example/AviaryService/services/dashboard/TimelineService.java b/src/main/java/com/example/AviaryService/services/dashboard/TimelineService.java index 89c3095..b349ed9 100644 --- a/src/main/java/com/example/AviaryService/services/dashboard/TimelineService.java +++ b/src/main/java/com/example/AviaryService/services/dashboard/TimelineService.java @@ -161,17 +161,8 @@ public CompletedMaintenance completeMaintenance(User user, Long id) { LocalDate today = LocalDate.now(); double currentTimeInService = user.getTimeInServiceHours(); - LocalDate dueDateLd = null; - if (hasCalendar) { - switch (calUnit) { - case "DAYS": dueDateLd = today.plusDays(calVal); break; - case "MONTHS": dueDateLd = today.plusMonths(calVal); break; - case "YEARS": dueDateLd = today.plusYears(calVal); break; - default: - throw new IllegalArgumentException("Invalid calendar unit: " + calUnit); - } - } - Double dueHours = hasHours ? (currentTimeInService + hrsCycle) : null; + LocalDate dueDateLd = hasCalendar ? DueDates.nextDueDate(today, calVal, calUnit) : null; + Double dueHours = hasHours ? DueDates.nextDueHours(currentTimeInService, hrsCycle) : null; // Only update fields that belong to the active cycle type โ€” leave the other type's // fields untouched so they stay visible in the UI after repaint. diff --git a/src/main/java/com/example/AviaryService/services/flights/FlightLogService.java b/src/main/java/com/example/AviaryService/services/flights/FlightLogService.java index b70affd..7d8cb71 100644 --- a/src/main/java/com/example/AviaryService/services/flights/FlightLogService.java +++ b/src/main/java/com/example/AviaryService/services/flights/FlightLogService.java @@ -63,8 +63,8 @@ public List listFor(User user) { // fit the user's other flights. @Transactional public AddedFlightLog add(User user, FlightLog newLog, boolean force) { - // Clamp readings to hundredths. Real meters never exceed 2dp (Hobbs - // 0.1, Tach 0.01), and this keeps CSV-prefilled or client-computed + // Clamp readings to hundredths. Real meters never exceed 2dp (block + // time 0.1, time in service 0.01), and this keeps CSV-prefilled or client-computed // values from carrying float artifacts into storage. newLog.setBlockTimeOut(Formatting.roundHoursOrNull(newLog.getBlockTimeOut())); newLog.setBlockTimeIn(Formatting.roundHoursOrNull(newLog.getBlockTimeIn())); diff --git a/src/main/java/com/example/AviaryService/services/imports/ConnectionService.java b/src/main/java/com/example/AviaryService/services/imports/ConnectionService.java new file mode 100644 index 0000000..d24ca5f --- /dev/null +++ b/src/main/java/com/example/AviaryService/services/imports/ConnectionService.java @@ -0,0 +1,67 @@ +package com.example.AviaryService.services.imports; + +import java.net.URI; +import java.time.Instant; +import java.util.Comparator; +import java.util.List; +import java.util.NoSuchElementException; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.example.AviaryService.entity.OAuthAuthorizationEntity; +import com.example.AviaryService.entity.OAuthConsentEntity; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.OAuthAuthorizationRepository; +import com.example.AviaryService.repositories.OAuthConsentRepository; + +// The owner's connected AI assistants, for the Connected assistants page. +// Only finished sign-ins count -- a grant with no access token is a sign-in +// that was started and abandoned. +@Service +public class ConnectionService { + + public record Connection(String id, String clientId, String clientName, String clientHost, Instant connectedAt, Instant lastUsedAt) {} + + private final OAuthAuthorizationRepository authorizationRepository; + private final OAuthConsentRepository consentRepository; + + public ConnectionService(OAuthAuthorizationRepository authorizationRepository, + OAuthConsentRepository consentRepository) { + this.authorizationRepository = authorizationRepository; + this.consentRepository = consentRepository; + } + + @Transactional(readOnly = true) + public List list(User user) { + return authorizationRepository.findByPrincipalName(user.getUsername()).stream() + .filter(a -> a.getAccessTokenValue() != null) + .map(a -> new Connection(a.getId(), a.getRegisteredClientId(), + a.getClientName() != null ? a.getClientName() : hostOf(a.getRegisteredClientId()), + hostOf(a.getRegisteredClientId()), + a.getAccessTokenIssuedAt(), + a.getLastUsedAt())) + .sorted(Comparator.comparing(Connection::connectedAt, Comparator.nullsLast(Comparator.reverseOrder()))) + .toList(); + } + + // Deletes the grant (the assistant's token stops working on its next + // request) and the remembered consent (it has to ask again). Throws + // NoSuchElementException if the id isn't one of this owner's grants. + @Transactional + public void disconnect(User user, String id) { + OAuthAuthorizationEntity grant = authorizationRepository.findByIdAndPrincipalName(id, user.getUsername()) + .orElseThrow(() -> new NoSuchElementException("No such connection")); + authorizationRepository.delete(grant); + consentRepository.deleteById(new OAuthConsentEntity.Key(grant.getRegisteredClientId(), user.getUsername())); + } + + static String hostOf(String clientId) { + try { + String host = URI.create(clientId).getHost(); + return host != null ? host : clientId; + } catch (Exception e) { + return clientId; + } + } +} diff --git a/src/main/java/com/example/AviaryService/services/imports/TimelineImportService.java b/src/main/java/com/example/AviaryService/services/imports/TimelineImportService.java new file mode 100644 index 0000000..47c05c0 --- /dev/null +++ b/src/main/java/com/example/AviaryService/services/imports/TimelineImportService.java @@ -0,0 +1,398 @@ +package com.example.AviaryService.services.imports; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +import com.example.AviaryService.entity.ImportProposal; +import com.example.AviaryService.entity.OAuthAuthorizationEntity; +import com.example.AviaryService.entity.ServiceTimeline; +import com.example.AviaryService.entity.TimelineImportRecord; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.ImportProposalRepository; +import com.example.AviaryService.repositories.OAuthAuthorizationRepository; +import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.repositories.TimelineImportRecordRepository; +import com.example.AviaryService.util.DueDates; +import com.example.AviaryService.util.Formatting; +import com.example.AviaryService.util.SlidingWindowLimiter; +import com.example.AviaryService.util.TimelineImportRules; +import com.example.AviaryService.util.TimelineImportRules.ImportFlag; +import com.example.AviaryService.util.TimelineImportRules.InputItem; +import com.example.AviaryService.util.TimelineImportRules.ItemResult; +import com.example.AviaryService.util.TimelineImportRules.ProposedItem; +import com.example.AviaryService.util.TimelineImportRules.RejectedRow; +import com.example.AviaryService.util.TimelineImportRules.SubmissionOutcome; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +// Service timeline import through an AI assistant: propose (preview only), +// continue a poor fit, confirm (saves exactly the proposal, all or nothing). +// Imports only ever add rows -- existing items are never changed or deleted. +// Every lookup is by owner, so one owner can't see or confirm another's +// proposal. +@Service +public class TimelineImportService { + + private static final Logger log = LoggerFactory.getLogger(TimelineImportService.class); + + static final Duration PROPOSAL_TTL = Duration.ofHours(24); + static final int PROPOSALS_PER_HOUR = 30; + static final int CONFIRMS_PER_HOUR = 10; + private static final List LIVE = List.of(ImportProposal.OPEN, ImportProposal.NEEDS_FIT_CONFIRMATION); + + // What the MCP tools return. Fields that don't apply to a status are left + // out of the JSON. + @JsonInclude(JsonInclude.Include.NON_NULL) + public record ImportResult(String status, Long proposalId, String expiresAt, + List items, List rejected, + String summary, String message, String example, + Integer addedCount, List skippedDuplicates, List newDuplicates, + Long retryAfterSeconds) { + + static ImportResult status(String status, String message) { + return new ImportResult(status, null, null, null, null, null, message, null, null, null, null, null); + } + } + + private final ImportProposalRepository proposalRepository; + private final ServiceTimelineRepository timelineRepository; + private final TimelineImportRecordRepository recordRepository; + private final OAuthAuthorizationRepository authorizationRepository; + private final TransactionTemplate transaction; + private final ObjectMapper objectMapper = new ObjectMapper(); + private final Clock clock; + private final SlidingWindowLimiter proposeLimiter; + private final SlidingWindowLimiter confirmLimiter; + + @Autowired + public TimelineImportService(ImportProposalRepository proposalRepository, + ServiceTimelineRepository timelineRepository, + TimelineImportRecordRepository recordRepository, + OAuthAuthorizationRepository authorizationRepository, + PlatformTransactionManager transactionManager) { + this(proposalRepository, timelineRepository, recordRepository, authorizationRepository, + transactionManager, Clock.systemUTC()); + } + + TimelineImportService(ImportProposalRepository proposalRepository, + ServiceTimelineRepository timelineRepository, + TimelineImportRecordRepository recordRepository, + OAuthAuthorizationRepository authorizationRepository, + PlatformTransactionManager transactionManager, + Clock clock) { + this.proposalRepository = proposalRepository; + this.timelineRepository = timelineRepository; + this.recordRepository = recordRepository; + this.authorizationRepository = authorizationRepository; + this.transaction = new TransactionTemplate(transactionManager); + this.clock = clock; + this.proposeLimiter = new SlidingWindowLimiter(PROPOSALS_PER_HOUR, Duration.ofHours(1), clock); + this.confirmLimiter = new SlidingWindowLimiter(CONFIRMS_PER_HOUR, Duration.ofHours(1), clock); + } + + // ---- propose ---- + + // Builds and stores a proposal. Changes nothing on the timeline. Any + // earlier open proposal of this owner is replaced. + public ImportResult propose(User user, List items, List rejectedBySource, String clientId) { + List input = items == null ? List.of() : items; + List fromSource = cleanSourceRejects(rejectedBySource); + + if (input.size() > TimelineImportRules.MAX_ITEMS) { + return ImportResult.status("TOO_LARGE", "That's " + input.size() + " items; the most one proposal can hold is " + + TimelineImportRules.MAX_ITEMS + ". Split the records and propose each part separately."); + } + if (!proposeLimiter.tryAcquire(user.getUsername())) { + return rateLimited("Too many proposals in the last hour. Try again later."); + } + + return transaction.execute(tx -> { + LocalDate today = LocalDate.now(clock.withZone(ZoneOffset.UTC)); + ItemResult result = TimelineImportRules.evaluate(input, existingNames(user), today); + List rejected = new ArrayList<>(result.rejected()); + rejected.addAll(fromSource); + int submitted = input.size() + fromSource.size(); + + SubmissionOutcome outcome = TimelineImportRules.classify(input.size(), submitted, rejected.size(), result); + if (outcome == SubmissionOutcome.REJECTED) { + return new ImportResult("REJECTED", null, null, null, rejected, null, + "No maintenance items were found, so nothing was proposed. Every row was either missing an item " + + "name or set aside as not being a maintenance item (reasons below). See the example for the format.", + TimelineImportRules.FORMAT_EXAMPLE, null, null, null, null); + } + + for (ImportProposal old : proposalRepository.findByUserAndStatusIn(user, LIVE)) { + old.setStatus(ImportProposal.REPLACED); + proposalRepository.save(old); + } + + Instant now = clock.instant(); + ImportProposal proposal = new ImportProposal(); + proposal.setUser(user); + proposal.setStatus(outcome == SubmissionOutcome.POOR_FIT ? ImportProposal.NEEDS_FIT_CONFIRMATION : ImportProposal.OPEN); + proposal.setItemsJson(write(result.items())); + proposal.setRejectedJson(write(rejected)); + proposal.setSubmittedCount(submitted); + proposal.setCreatedAt(now); + proposal.setExpiresAt(now.plus(PROPOSAL_TTL)); + proposal.setConnectionClientId(clientId); + proposalRepository.save(proposal); + + String summary = summarize(result.items(), rejected); + if (outcome == SubmissionOutcome.POOR_FIT) { + return new ImportResult("POOR_FIT", proposal.getId(), proposal.getExpiresAt().toString(), result.items(), rejected, + summary, + rejected.size() + " of " + submitted + " rows didn't fit Aviary's format (reasons below). " + + "Ask the owner whether to continue with only the rows that fit; if yes, call continue_poor_fit.", + null, null, null, null, null); + } + return new ImportResult("PROPOSED", proposal.getId(), proposal.getExpiresAt().toString(), result.items(), rejected, + summary, "Nothing has been added yet. Show the owner this proposal and confirm only when they say so.", + null, null, null, null, null); + }); + } + + // ---- continue a poor fit ---- + + public ImportResult continuePoorFit(User user, Long proposalId) { + return transaction.execute(tx -> { + ImportProposal proposal = proposalRepository.findByIdAndUser(proposalId, user).orElse(null); + ImportResult problem = checkUsable(proposal, true); + if (problem != null) return problem; + if (ImportProposal.NEEDS_FIT_CONFIRMATION.equals(proposal.getStatus())) { + proposal.setStatus(ImportProposal.OPEN); + proposalRepository.save(proposal); + } + List items = readItems(proposal); + return new ImportResult("PROPOSED", proposal.getId(), proposal.getExpiresAt().toString(), items, readRejected(proposal), + summarize(items, readRejected(proposal)), + "Continuing with only the rows that fit. Confirm when the owner says so.", + null, null, null, null, null); + }); + } + + // ---- confirm ---- + + // Adds exactly the proposed items after the owner's existing rows, in one + // transaction: if any row fails, none are saved. Items flagged as matching + // an existing item are skipped unless their index is in addDuplicatesAnyway; + // a match that appeared since the proposal is skipped and reported too. + public ImportResult confirm(User user, Long proposalId, Set addDuplicatesAnyway) { + if (!confirmLimiter.tryAcquire(user.getUsername())) { + return rateLimited("Too many imports in the last hour. Try again later."); + } + Set optIn = addDuplicatesAnyway == null ? Set.of() : addDuplicatesAnyway; + try { + return transaction.execute(tx -> { + ImportProposal proposal = proposalRepository.findByIdAndUser(proposalId, user).orElse(null); + ImportResult problem = checkUsable(proposal, false); + if (problem != null) return problem; + + List items = readItems(proposal); + Set existing = existingNames(user); + List skipped = new ArrayList<>(); + List newDuplicates = new ArrayList<>(); + + LocalDate today = LocalDate.now(clock.withZone(ZoneOffset.UTC)); + Double currentTis = user.getTimeInServiceHours(); + Integer max = timelineRepository.findMaxTimelineOrderByUser(user); + int order = max == null ? 0 : max + 1; + int added = 0; + + for (ProposedItem item : items) { + boolean matches = existing.contains(TimelineImportRules.normalizeName(item.item())); + if (matches && !optIn.contains(item.index())) { + if (item.flags().contains(ImportFlag.DUPLICATE_EXISTING)) { + skipped.add(item.item()); + } else { + newDuplicates.add(item.item()); + } + continue; + } + timelineRepository.save(toRow(user, item, order++, today, currentTis)); + added++; + } + + Instant now = clock.instant(); + proposal.setStatus(ImportProposal.CONFIRMED); + proposal.setConfirmedAt(now); + proposalRepository.save(proposal); + + TimelineImportRecord record = new TimelineImportRecord(); + record.setUser(user); + record.setProposalId(proposal.getId()); + record.setClientId(proposal.getConnectionClientId()); + record.setClientName(clientName(user, proposal.getConnectionClientId())); + record.setItemCount(added); + record.setImportedAt(now); + recordRepository.save(record); + + String message = "Added " + added + (added == 1 ? " item" : " items") + " to the service timeline."; + if (!skipped.isEmpty() || !newDuplicates.isEmpty()) { + message += " Skipped " + (skipped.size() + newDuplicates.size()) + + " that match items already on the timeline."; + } + return new ImportResult("IMPORTED", proposal.getId(), null, null, null, null, message, null, + added, skipped, newDuplicates, null); + }); + } catch (RuntimeException e) { + // The transaction rolled back, so nothing from this proposal was saved. + log.warn("Timeline import {} failed for {}", proposalId, user.getUsername(), e); + return ImportResult.status("FAILED", + "The import failed and nothing was added. The proposal is still open; try confirming again."); + } + } + + // null when the proposal can be acted on; otherwise the status to return. + private ImportResult checkUsable(ImportProposal proposal, boolean continuing) { + if (proposal == null) { + return ImportResult.status("NOT_FOUND", "No such proposal for this account."); + } + expireIfDue(proposal); + return switch (proposal.getStatus()) { + case ImportProposal.CONFIRMED -> ImportResult.status("ALREADY_CONFIRMED", "This proposal was already imported."); + case ImportProposal.REPLACED -> ImportResult.status("REPLACED", + "A newer proposal replaced this one. Confirm the newer proposal instead."); + case ImportProposal.EXPIRED -> ImportResult.status("EXPIRED", + "This proposal expired (proposals last 24 hours). Propose the records again."); + case ImportProposal.NEEDS_FIT_CONFIRMATION -> continuing ? null : ImportResult.status("NEEDS_FIT_CONFIRMATION", + "Most rows didn't fit. Ask the owner whether to continue with only the rows that fit, then call continue_poor_fit."); + default -> null; + }; + } + + private void expireIfDue(ImportProposal proposal) { + if (LIVE.contains(proposal.getStatus()) && !proposal.getExpiresAt().isAfter(clock.instant())) { + proposal.setStatus(ImportProposal.EXPIRED); + proposalRepository.save(proposal); + } + } + + private ServiceTimeline toRow(User user, ProposedItem item, int order, LocalDate today, Double currentTis) { + ServiceTimeline row = new ServiceTimeline(); + row.setUser(user); + row.setItem(item.item()); + row.setIsTitle(item.isTitle()); + row.setTimelineOrder(order); + if (item.isTitle()) { + return row; + } + row.setDescription(item.flags().contains(ImportFlag.ON_CONDITION) + ? onConditionDescription(item.description()) : item.description()); + row.setLastDoneDate(item.lastDoneDate()); + row.setLastDoneHours(item.lastDoneHours() == null ? null : Formatting.formatHours(item.lastDoneHours())); + row.setDueDateDate(item.dueDateDate()); + row.setDueDateHours(item.dueDateHours() == null ? null : Formatting.formatHours(item.dueDateHours())); + row.setCycleCalendarValue(item.cycleCalendarValue()); + row.setCycleCalendarUnit(item.cycleCalendarUnit()); + row.setCycleHours(item.cycleHours()); + row.setTimeLeft(DueDates.formatTimeLeft(row.getDueDateDate(), row.getDueDateHours(), today, currentTis)); + return row; + } + + // The timeline has no on-condition column, so the description says it -- + // otherwise the row shows up with every date blank and no explanation. + static String onConditionDescription(String description) { + if (description == null || description.isBlank()) return "On condition"; + if (description.toLowerCase().contains("on condition")) return description; + String withNote = description + " (on condition)"; + return withNote.length() <= com.example.AviaryService.util.Validation.MAX_TEXT ? withNote : description; + } + + private Set existingNames(User user) { + Set names = new HashSet<>(); + for (ServiceTimeline row : timelineRepository.findByUserOrderByTimelineOrderAsc(user)) { + names.add(TimelineImportRules.normalizeName(row.getItem())); + } + return names; + } + + private String clientName(User user, String clientId) { + if (clientId == null) return "Unknown assistant"; + for (OAuthAuthorizationEntity grant : authorizationRepository.findByPrincipalName(user.getUsername())) { + if (clientId.equals(grant.getRegisteredClientId()) && grant.getClientName() != null) { + return grant.getClientName(); + } + } + return ConnectionService.hostOf(clientId); + } + + private static String summarize(List items, List rejected) { + long real = items.stream().filter(i -> !i.isTitle()).count(); + long titles = items.size() - real; + long flagged = items.stream().filter(i -> !i.flags().isEmpty()).count(); + long duplicates = items.stream().filter(i -> i.flags().contains(ImportFlag.DUPLICATE_EXISTING)).count(); + long noSchedule = items.stream().filter(i -> i.flags().contains(ImportFlag.NO_SCHEDULE)).count(); + long onCondition = items.stream().filter(i -> i.flags().contains(ImportFlag.ON_CONDITION)).count(); + long dropped = items.stream().filter(i -> i.flags().contains(ImportFlag.VALUE_DROPPED)).count(); + StringBuilder sb = new StringBuilder(); + sb.append(real).append(real == 1 ? " item" : " items"); + if (titles > 0) sb.append(" and ").append(titles).append(titles == 1 ? " title row" : " title rows"); + sb.append(" to add"); + if (flagged > 0) sb.append(", ").append(flagged).append(" flagged for the owner to check"); + if (duplicates > 0) sb.append(" (").append(duplicates).append(" already on the timeline and skipped unless the owner opts in)"); + if (onCondition > 0) sb.append("; ").append(onCondition).append(" on condition"); + if (noSchedule > 0) sb.append("; ").append(noSchedule).append(" with no due date or interval (Time Left shows N/A)"); + if (dropped > 0) sb.append("; ").append(dropped).append(" with a value left blank (see notes)"); + sb.append("; ").append(rejected.size()).append(rejected.size() == 1 ? " row" : " rows").append(" can't be imported."); + return sb.toString(); + } + + private static List cleanSourceRejects(List rows) { + if (rows == null) return List.of(); + List out = new ArrayList<>(); + for (RejectedRow r : rows) { + if (r == null) continue; + out.add(new RejectedRow(truncate(r.sourceRow()), truncate(r.reason() == null ? "Could not be read." : r.reason()))); + } + return out; + } + + private static String truncate(String s) { + if (s == null) return ""; + return s.length() > TimelineImportRules.MAX_SOURCE_ROW ? s.substring(0, TimelineImportRules.MAX_SOURCE_ROW) : s; + } + + private static ImportResult rateLimited(String message) { + return new ImportResult("RATE_LIMITED", null, null, null, null, null, message, null, null, null, null, 3600L); + } + + private List readItems(ImportProposal p) { + return read(p.getItemsJson(), new TypeReference>() {}); + } + + private List readRejected(ImportProposal p) { + return read(p.getRejectedJson(), new TypeReference>() {}); + } + + private T read(String json, TypeReference type) { + try { + return objectMapper.readValue(json, type); + } catch (Exception e) { + throw new IllegalStateException("Stored proposal is unreadable", e); + } + } + + private String write(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } +} diff --git a/src/main/java/com/example/AviaryService/util/DueDates.java b/src/main/java/com/example/AviaryService/util/DueDates.java index 6a7e826..c6f26a8 100644 --- a/src/main/java/com/example/AviaryService/util/DueDates.java +++ b/src/main/java/com/example/AviaryService/util/DueDates.java @@ -14,6 +14,24 @@ public final class DueDates { private DueDates() { } + // The next due date one calendar cycle after lastDone. unit is + // "DAYS" | "MONTHS" | "YEARS"; month and year steps clamp to the end of a + // shorter month (Jan 31 + 1 month = Feb 28/29), the same as LocalDate. + public static LocalDate nextDueDate(LocalDate lastDone, int value, String unit) { + switch (unit) { + case "DAYS": return lastDone.plusDays(value); + case "MONTHS": return lastDone.plusMonths(value); + case "YEARS": return lastDone.plusYears(value); + default: + throw new IllegalArgumentException("Invalid calendar unit: " + unit); + } + } + + // The next due time-in-service one hours cycle after lastDoneHours. + public static double nextDueHours(double lastDoneHours, double cycleHours) { + return lastDoneHours + cycleHours; + } + // Whole days from today until dueDateDate (negative = overdue). null when the // string is blank or unparseable. dueDateDate is stored ISO ("2026-09-10"); // legacy rows may append hours ("2026-09-10 12.5") so only the first token diff --git a/src/main/java/com/example/AviaryService/util/Formatting.java b/src/main/java/com/example/AviaryService/util/Formatting.java index 74c7e4b..50188aa 100644 --- a/src/main/java/com/example/AviaryService/util/Formatting.java +++ b/src/main/java/com/example/AviaryService/util/Formatting.java @@ -4,8 +4,8 @@ public class Formatting { private Formatting() {} - // Real-world hour readings never exceed hundredths (Hobbs reads to 0.1, - // Tach to 0.01, AeroAPI is minute precision). Repeated double addition in + // Real-world hour readings never exceed hundredths (block time reads to + // 0.1, time in service to 0.01, AeroAPI is minute precision). Repeated double addition in // HoursService.recomputeChain otherwise leaves artifacts like // "2.0433333333333334". One home for the 2dp rule. public static double roundHours(double hours) { diff --git a/src/main/java/com/example/AviaryService/util/TimelineImportRules.java b/src/main/java/com/example/AviaryService/util/TimelineImportRules.java new file mode 100644 index 0000000..9d3be17 --- /dev/null +++ b/src/main/java/com/example/AviaryService/util/TimelineImportRules.java @@ -0,0 +1,377 @@ +package com.example.AviaryService.util; + +import java.time.LocalDate; +import java.time.Period; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +// Turns the service timeline items an AI assistant pulled out of an owner's +// records into Aviary items -- or into rejected rows with a plain reason. +// Pure (no Spring, no database) so every rule is unit-tested. +// +// Any row with a name is accepted -- owners' records come in every shape, and +// an item with no dates (on condition, or just not tracked yet) is still a +// real item. Nothing is guessed and nothing is lost silently: a value that +// can't be used is left blank and a note on the item says what and why, for +// the owner to see in the proposal. Only rows with no name are rejected. Due +// date / due hours come from last done + cycle with the same math as +// Complete Maintenance. +public final class TimelineImportRules { + + public static final int MAX_ITEMS = 200; + public static final int MAX_SOURCE_ROW = 500; + public static final int MAX_CALENDAR_VALUE = 1200; + + public enum ImportFlag { + AMBIGUOUS_DATE, // assistant wasn't sure which date was meant (e.g. 03/04/2025) + FUTURE_DATE, // last done is after today -- probably a typo + UNSUPPORTED_CYCLE, // e.g. "every 50 landings"; kept in the description, not tracked + CYCLE_INFERRED, // no cycle given; worked out from last done -> due + DUPLICATE_EXISTING, // same name as an item already on the timeline; skipped unless the owner opts in + DUPLICATE_IN_INPUT, // same name appears more than once in this import + ON_CONDITION, // marked on condition: inspected/replaced when its condition calls for it + NO_SCHEDULE, // no due date or interval at all; shows N/A until the owner adds one + VALUE_DROPPED // a value couldn't be used and was left blank -- see the item's notes + } + + // What the assistant sends for one item. Numbers arrive as text so one bad + // value is noted on that row instead of failing the whole call. + public record InputItem(String item, String description, Boolean isTitle, + String lastDoneDate, String lastDoneHours, + String cycleCalendarValue, String cycleCalendarUnit, String cycleHours, + String dueDateDate, String dueDateHours, + Boolean dateAmbiguous, String sourceRow, Boolean onCondition) {} + + public record ProposedItem(int index, String item, String description, boolean isTitle, + String lastDoneDate, Double lastDoneHours, + Integer cycleCalendarValue, String cycleCalendarUnit, Double cycleHours, + String dueDateDate, Double dueDateHours, + List flags, String sourceRow, List notes) {} + + public record RejectedRow(String sourceRow, String reason) {} + + public record ItemResult(List items, List rejected) {} + + // Shown by get_import_format and with every refused submission. + public static final String FORMAT_EXAMPLE = """ + [ + {"item": "Annual Inspection", "lastDoneDate": "2026-03-14", + "cycleCalendarValue": "12", "cycleCalendarUnit": "MONTHS", + "sourceRow": "Annual - 3/14/26 - yearly"}, + {"item": "Oil Change", "lastDoneHours": "1234.5", "cycleHours": "50", + "sourceRow": "Oil chg @ 1,234.5 hrs every 50"}, + {"item": "Engine", "isTitle": true, "sourceRow": "ENGINE"}, + {"item": "Flexible Fluid Hose", "description": "Replace", "onCondition": true, + "sourceRow": "Flexible Fluid Hose - Replace - On condition"} + ]"""; + + public static final List RULES = List.of( + "Include every maintenance item from the owner's records. An item only needs a name; send whatever dates, " + + "hours, and intervals it has. Never leave out an item because it has no dates or interval.", + "Mark items the records describe as on condition with onCondition: true.", + "Values that can't be used are left blank and explained in the item's notes -- the item is still imported.", + "Title rows (isTitle: true) group the items under them and only need a name.", + "Dates must be YYYY-MM-DD. If you can't tell which date was meant (03/04/2025), convert your best reading and set dateAmbiguous: true.", + "Hours are numbers of time in service, 0 or more.", + "Calendar intervals: a whole number from 1 to 1200 with unit DAYS, MONTHS, or YEARS. Hours intervals: a number above 0.", + "Any other interval (landings, cycles, ...) can't be tracked: send it as-is and it is kept in the description.", + "Put the original line in sourceRow so the owner can compare.", + "Only rows that are not maintenance items at all (or have no name you can find) go in rejectedBySource, with a reason.", + "At most " + MAX_ITEMS + " items per proposal."); + + private TimelineImportRules() {} + + public enum SubmissionOutcome { + PROPOSED, // a normal proposal + POOR_FIT, // more than half the rows didn't fit; owner must say to continue + REJECTED, // nothing usable -- not maintenance records, or too broken + TOO_LARGE // over MAX_ITEMS; split it up + } + + // The verdict on a whole submission. submitted counts every row the + // assistant sent (items + rows it couldn't read itself); rejected counts + // every row that didn't make it into the proposal. Title rows alone don't + // count as usable -- a list of headings isn't a timeline. + public static SubmissionOutcome classify(int itemCount, int submitted, int rejected, ItemResult result) { + if (itemCount > MAX_ITEMS) return SubmissionOutcome.TOO_LARGE; + boolean anyRealItem = result.items().stream().anyMatch(i -> !i.isTitle()); + if (submitted == 0 || !anyRealItem) return SubmissionOutcome.REJECTED; + if (rejected * 2 > submitted) return SubmissionOutcome.POOR_FIT; + return SubmissionOutcome.PROPOSED; + } + + // Lowercase, trimmed, inner whitespace collapsed -- "Annual inspection" + // and "annual inspection" are the same item. + public static String normalizeName(String name) { + return name == null ? "" : name.trim().replaceAll("\\s+", " ").toLowerCase(Locale.ROOT); + } + + public static ItemResult evaluate(List input, Set existingNormalizedNames, LocalDate today) { + List items = new ArrayList<>(); + List rejected = new ArrayList<>(); + Map seen = new HashMap<>(); // normalized name -> index into items + + for (InputItem in : input) { + if (in == null) continue; + Object result = evaluateOne(in, today); + if (result instanceof RejectedRow r) { + rejected.add(r); + continue; + } + ProposedItem p = (ProposedItem) result; + String key = normalizeName(p.item()); + EnumSet flags = p.flags().isEmpty() ? EnumSet.noneOf(ImportFlag.class) : EnumSet.copyOf(p.flags()); + + if (existingNormalizedNames.contains(key)) { + flags.add(ImportFlag.DUPLICATE_EXISTING); + } + if (!p.isTitle() && seen.containsKey(key)) { + int earlier = seen.get(key); + ProposedItem first = items.get(earlier); + if (sameContent(first, p)) { + // Exact repeat: show once, note the merge. + items.set(earlier, withFlags(first, add(first.flags(), ImportFlag.DUPLICATE_IN_INPUT))); + continue; + } + // Same name, different details: keep both for the owner to sort out. + items.set(earlier, withFlags(first, add(first.flags(), ImportFlag.DUPLICATE_IN_INPUT))); + flags.add(ImportFlag.DUPLICATE_IN_INPUT); + } + ProposedItem withIndex = withIndexAndFlags(p, items.size() + 1, List.copyOf(flags)); + if (!p.isTitle()) seen.putIfAbsent(key, items.size()); + items.add(withIndex); + } + return new ItemResult(List.copyOf(items), List.copyOf(rejected)); + } + + // A ProposedItem, or a RejectedRow when the row has no name. + private static Object evaluateOne(InputItem in, LocalDate today) { + String source = sourceOf(in); + List notes = new ArrayList<>(); + + String name = trimToNull(in.item()); + if (name == null) return new RejectedRow(source, "No item name."); + if (name.length() > Validation.MAX_TEXT) { + name = name.substring(0, Validation.MAX_TEXT); + notes.add("Name was cut to " + Validation.MAX_TEXT + " characters."); + } + String description = trimToNull(in.description()); + + if (Boolean.TRUE.equals(in.isTitle())) { + return new ProposedItem(0, name, null, true, null, null, null, null, null, null, null, List.of(), source, + List.copyOf(notes)); + } + + EnumSet flags = EnumSet.noneOf(ImportFlag.class); + + LocalDate lastDone = dateOrNote(in.lastDoneDate(), "Last done date", notes, flags); + LocalDate due = dateOrNote(in.dueDateDate(), "Due date", notes, flags); + Double lastHours = hoursOrNote(in.lastDoneHours(), "Last done hours", notes, flags); + Double dueHours = hoursOrNote(in.dueDateHours(), "Due hours", notes, flags); + if (lastDone != null && lastDone.isAfter(today)) flags.add(ImportFlag.FUTURE_DATE); + if (Boolean.TRUE.equals(in.dateAmbiguous())) flags.add(ImportFlag.AMBIGUOUS_DATE); + boolean onCondition = Boolean.TRUE.equals(in.onCondition()); + if (onCondition) flags.add(ImportFlag.ON_CONDITION); + + // Calendar cycle + Integer calValue = null; + String calUnit = null; + String rawUnit = trimToNull(in.cycleCalendarUnit()); + String rawValue = trimToNull(in.cycleCalendarValue()); + if (rawUnit != null || rawValue != null) { + String unit = normalizeUnit(rawUnit); + Integer v = parseWholeNumber(rawValue); + if (unit == null) { + // Not a unit Aviary can count down (landings, cycles, ...): + // keep it in the description so it isn't lost. + String interval = ((rawValue == null ? "" : rawValue + " ") + (rawUnit == null ? "" : rawUnit)).trim(); + flags.add(ImportFlag.UNSUPPORTED_CYCLE); + description = appendNote(description, "interval: " + interval); + notes.add("Interval \"" + interval + "\" isn't something Aviary can count down (it tracks days, " + + "months, years, and hours), so it was kept in the description instead."); + } else if (v == null || v < 1 || v > MAX_CALENDAR_VALUE) { + flags.add(ImportFlag.VALUE_DROPPED); + notes.add("Calendar interval \"" + (rawValue == null ? "" : rawValue) + " " + rawUnit + + "\" isn't a whole number from 1 to " + MAX_CALENDAR_VALUE + ", so it was left blank."); + } else { + calValue = v; + calUnit = unit; + } + } + + // Hours cycle + Double cycleHours = hoursOrNote(in.cycleHours(), "Hours interval", notes, flags); + if (cycleHours != null && cycleHours <= 0) { + flags.add(ImportFlag.VALUE_DROPPED); + notes.add("Hours interval must be above 0, so it was left blank."); + cycleHours = null; + } + + // No cycle given, but last done and due are: work it out. + if (calValue == null && lastDone != null && due != null && due.isAfter(lastDone)) { + Period p = Period.between(lastDone, due); + if (p.getDays() == 0 && p.toTotalMonths() > 0 && p.toTotalMonths() <= MAX_CALENDAR_VALUE) { + long months = p.toTotalMonths(); + if (months % 12 == 0) { + calValue = (int) (months / 12); + calUnit = "YEARS"; + } else { + calValue = (int) months; + calUnit = "MONTHS"; + } + } else { + long days = java.time.temporal.ChronoUnit.DAYS.between(lastDone, due); + if (days <= MAX_CALENDAR_VALUE) { + calValue = (int) days; + calUnit = "DAYS"; + } + } + if (calValue != null) flags.add(ImportFlag.CYCLE_INFERRED); + } + if (cycleHours == null && lastHours != null && dueHours != null && dueHours > lastHours) { + cycleHours = Formatting.roundHours(dueHours - lastHours); + flags.add(ImportFlag.CYCLE_INFERRED); + } + + // Due values: from last done + cycle when both are known, else as given. + if (calValue != null && lastDone != null) { + due = DueDates.nextDueDate(lastDone, calValue, calUnit); + } + if (cycleHours != null && lastHours != null) { + dueHours = Formatting.roundHours(DueDates.nextDueHours(lastHours, cycleHours)); + } + + if (!onCondition && due == null && dueHours == null && calValue == null && cycleHours == null) { + flags.add(ImportFlag.NO_SCHEDULE); + notes.add("No due date or interval, so Time Left will show N/A until one is added."); + } + + if (description != null && description.length() > Validation.MAX_TEXT) { + description = description.substring(0, Validation.MAX_TEXT); + notes.add("Description was cut to " + Validation.MAX_TEXT + " characters."); + } + + return new ProposedItem(0, name, description, false, + lastDone == null ? null : lastDone.toString(), lastHours, + calValue, calUnit, cycleHours, + due == null ? null : due.toString(), dueHours, + List.copyOf(flags), source, List.copyOf(notes)); + } + + private static LocalDate dateOrNote(String raw, String label, List notes, Set flags) { + try { + return parseDate(raw, label); + } catch (IllegalArgumentException e) { + flags.add(ImportFlag.VALUE_DROPPED); + notes.add(e.getMessage() + " It was left blank."); + return null; + } + } + + private static Double hoursOrNote(String raw, String label, List notes, Set flags) { + try { + return parseHours(raw, label); + } catch (IllegalArgumentException e) { + flags.add(ImportFlag.VALUE_DROPPED); + notes.add(e.getMessage() + " It was left blank."); + return null; + } + } + + private static String appendNote(String description, String note) { + return description == null ? note : description + " (" + note + ")"; + } + + private static String sourceOf(InputItem in) { + String s = trimToNull(in.sourceRow()); + if (s == null) { + s = String.join(" | ", java.util.stream.Stream.of(in.item(), in.lastDoneDate(), in.lastDoneHours(), + in.cycleCalendarValue(), in.cycleCalendarUnit(), in.cycleHours(), in.dueDateDate(), in.dueDateHours()) + .filter(Objects::nonNull).map(String::trim).filter(x -> !x.isEmpty()).toList()); + } + return s.length() > MAX_SOURCE_ROW ? s.substring(0, MAX_SOURCE_ROW) : s; + } + + private static LocalDate parseDate(String raw, String label) { + String s = trimToNull(raw); + if (s == null) return null; + if (!s.matches("\\d{4}-\\d{2}-\\d{2}")) { + throw new IllegalArgumentException(label + " \"" + s + "\" is not in YYYY-MM-DD form."); + } + try { + return LocalDate.parse(s); + } catch (DateTimeParseException e) { + throw new IllegalArgumentException(label + " \"" + s + "\" is not a real date."); + } + } + + // A number of hours, 0 or more. Thousands separators are allowed + // ("1,234.5"); anything else throws with a reason for the item's notes. + private static Double parseHours(String raw, String label) { + String s = trimToNull(raw); + if (s == null) return null; + String cleaned = s.replace(",", ""); + Double v = Parsing.parseDoubleOrNull(cleaned); + if (v == null || v.isNaN() || v.isInfinite()) { + throw new IllegalArgumentException(label + " \"" + s + "\" is not a number."); + } + if (v < 0) { + throw new IllegalArgumentException(label + " can't be negative."); + } + return Formatting.roundHours(v); + } + + private static Integer parseWholeNumber(String raw) { + if (raw == null) return null; + return Parsing.parseIntOrNull(raw.replace(",", "")); + } + + // DAYS / MONTHS / YEARS, also accepting the singular. + private static String normalizeUnit(String raw) { + if (raw == null) return null; + String u = raw.trim().toUpperCase(Locale.ROOT); + if (u.equals("DAY") || u.equals("MONTH") || u.equals("YEAR")) u = u + "S"; + return Parsing.normalizeCalendarUnit(u); + } + + private static String trimToNull(String s) { + if (s == null) return null; + String t = s.trim(); + return t.isEmpty() ? null : t; + } + + private static boolean sameContent(ProposedItem a, ProposedItem b) { + return Objects.equals(a.description(), b.description()) + && Objects.equals(a.lastDoneDate(), b.lastDoneDate()) + && Objects.equals(a.lastDoneHours(), b.lastDoneHours()) + && Objects.equals(a.cycleCalendarValue(), b.cycleCalendarValue()) + && Objects.equals(a.cycleCalendarUnit(), b.cycleCalendarUnit()) + && Objects.equals(a.cycleHours(), b.cycleHours()) + && Objects.equals(a.dueDateDate(), b.dueDateDate()) + && Objects.equals(a.dueDateHours(), b.dueDateHours()); + } + + private static List add(List flags, ImportFlag flag) { + Set s = new LinkedHashSet<>(flags); + s.add(flag); + return List.copyOf(s); + } + + private static ProposedItem withFlags(ProposedItem p, List flags) { + return withIndexAndFlags(p, p.index(), flags); + } + + private static ProposedItem withIndexAndFlags(ProposedItem p, int index, List flags) { + return new ProposedItem(index, p.item(), p.description(), p.isTitle(), p.lastDoneDate(), p.lastDoneHours(), + p.cycleCalendarValue(), p.cycleCalendarUnit(), p.cycleHours(), p.dueDateDate(), p.dueDateHours(), + flags, p.sourceRow(), p.notes()); + } +} diff --git a/src/main/resources/application-heroku.properties b/src/main/resources/application-heroku.properties index 14d8206..29f36ca 100644 --- a/src/main/resources/application-heroku.properties +++ b/src/main/resources/application-heroku.properties @@ -1,22 +1,25 @@ -# application-heroku.properties -spring.jpa.hibernate.ddl-auto=update -server.port=${PORT:8080} - -# This tells Spring Boot to prefer Heroku's SPRING_DATASOURCE_* vars -# (Heroku sets them automatically from DATABASE_URL) -spring.datasource.url=${SPRING_DATASOURCE_URL} -spring.datasource.username=${SPRING_DATASOURCE_USERNAME} -spring.datasource.password=${SPRING_DATASOURCE_PASSWORD} - -# Optional but recommended for Postgres on Heroku -spring.datasource.driver-class-name=org.postgresql.Driver -spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect - -# Turn off open-in-view if you don't need it (helps performance) -spring.jpa.open-in-view=false - -# Heroku's router terminates HTTPS and forwards plain HTTP with -# X-Forwarded-Proto. Trusting that header lets the app see requests as secure, -# so the session / remember-me cookies get the Secure flag and HSTS is sent. -server.forward-headers-strategy=native -server.servlet.session.cookie.secure=true +# application-heroku.properties +spring.jpa.hibernate.ddl-auto=update +server.port=${PORT:8080} + +# This tells Spring Boot to prefer Heroku's SPRING_DATASOURCE_* vars +# (Heroku sets them automatically from DATABASE_URL) +spring.datasource.url=${SPRING_DATASOURCE_URL} +spring.datasource.username=${SPRING_DATASOURCE_USERNAME} +spring.datasource.password=${SPRING_DATASOURCE_PASSWORD} + +# Optional but recommended for Postgres on Heroku +spring.datasource.driver-class-name=org.postgresql.Driver +spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect + +# Turn off open-in-view if you don't need it (helps performance) +spring.jpa.open-in-view=false + +# Heroku's router terminates HTTPS and forwards plain HTTP with +# X-Forwarded-Proto. Trusting that header lets the app see requests as secure, +# so the session / remember-me cookies get the Secure flag and HSTS is sent. +server.forward-headers-strategy=native +server.servlet.session.cookie.secure=true + +# Staging overrides this with AVIARY_OAUTH_ISSUER set to its own URL. +aviary.oauth.issuer=${AVIARY_OAUTH_ISSUER:https://aviary.danielibarra.com} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 075517b..ddff785 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -41,4 +41,7 @@ spring.web.resources.cache.cachecontrol.cache-public=true spring.ai.mcp.server.name=aviary spring.ai.mcp.server.version=0.0.1 spring.ai.mcp.server.type=SYNC -spring.ai.mcp.server.protocol=STREAMABLE \ No newline at end of file +spring.ai.mcp.server.protocol=STREAMABLE + +# OAuth issuer for MCP sign-in. The MCP resource URL is ${aviary.oauth.issuer}/mcp. +aviary.oauth.issuer=${AVIARY_OAUTH_ISSUER:http://localhost:8080} diff --git a/src/main/resources/static/css/connectionsstyle.css b/src/main/resources/static/css/connectionsstyle.css new file mode 100644 index 0000000..70f48ed --- /dev/null +++ b/src/main/resources/static/css/connectionsstyle.css @@ -0,0 +1,100 @@ +/* Consent + Connected assistants pages. Loaded after loginstyle.css and + reuses its color tokens and card look. */ + +.consent-card, +.connections-card { + background: var(--surface); + border: 1px solid var(--border); + border-radius: 16px; + box-shadow: var(--shadow-md); + width: 100%; + max-width: 520px; + padding: 32px 28px; + display: flex; + flex-direction: column; + gap: 16px; + line-height: 1.5; +} + +.consent-scopes { + padding-left: 20px; +} + +.consent-note, +.connections-empty, +.connection-meta { + color: var(--text-muted); + font-size: 0.9rem; +} + +.consent-actions { + display: flex; +} + +.consent-approve, +.consent-deny, +.connection-disconnect { + width: 100%; + padding: 12px; + border-radius: var(--radius); + font: inherit; + font-weight: 600; + cursor: pointer; +} + +.consent-approve { + background: var(--primary); + border: 1px solid var(--primary); + color: #fff; +} + +.consent-approve:hover { + background: var(--primary-dark); +} + +.consent-deny, +.connection-disconnect { + background: var(--surface); + border: 1px solid var(--border); + color: var(--text); +} + +.connections-list { + list-style: none; + display: flex; + flex-direction: column; + gap: 12px; +} + +.connection { + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 16px; + display: flex; + flex-direction: column; + gap: 8px; +} + +.connection-name { + font-weight: 600; +} + +.connection-imports { + padding-left: 20px; + font-size: 0.9rem; +} + +.connection-disconnect { + width: auto; + align-self: flex-start; + padding: 8px 14px; +} + +.connection-disconnect:hover { + border-color: #c0392b; + color: #c0392b; +} + +.connections-back { + color: var(--primary-dark); +} diff --git a/src/main/resources/static/css/dashboardstyle.css b/src/main/resources/static/css/dashboardstyle.css index 5e61e5f..2495186 100644 --- a/src/main/resources/static/css/dashboardstyle.css +++ b/src/main/resources/static/css/dashboardstyle.css @@ -182,6 +182,8 @@ input[type="checkbox"]:focus-visible { .fixed-header .header-right .logout-btn:hover, .fixed-header .share-btn:hover, .fixed-header #subscribe:hover { background: rgba(255,255,255,0.3); } +/* Connected assistants link: a link styled like the Logout button. */ +.fixed-header .header-right #connections-link { text-decoration: none; } .edit-hours-btn, .back-to-full-list-button { diff --git a/src/main/resources/templates/connections.html b/src/main/resources/templates/connections.html new file mode 100644 index 0000000..319c62d --- /dev/null +++ b/src/main/resources/templates/connections.html @@ -0,0 +1,47 @@ + + + + + + + Connected assistants + + + + + + + +
+

Connected assistants

+

Disconnected.

+ +

+ No AI assistants are connected. Add Aviary to an assistant such as + an AI assistant to import your service timeline. +

+ +
    +
  • + Assistant + + assistant.example.com + ยท connected + Oct 20, 2026 + ยท last used + never + +
      +
    • Oct 20, 2026: added 3 items
    • +
    +
    + +
    +
  • +
+ + Back to dashboard +
+ + diff --git a/src/main/resources/templates/consent.html b/src/main/resources/templates/consent.html new file mode 100644 index 0000000..5cceb44 --- /dev/null +++ b/src/main/resources/templates/consent.html @@ -0,0 +1,52 @@ + + + + + + + Connect an assistant + + + + + + + + + + + + diff --git a/src/main/resources/templates/dashboard.html b/src/main/resources/templates/dashboard.html index 093d87b..6e24069 100644 --- a/src/main/resources/templates/dashboard.html +++ b/src/main/resources/templates/dashboard.html @@ -51,6 +51,9 @@ + +
diff --git a/src/test/java/com/example/AviaryService/mcp/McpHttpStatusTest.java b/src/test/java/com/example/AviaryService/mcp/McpHttpStatusTest.java new file mode 100644 index 0000000..72a8728 --- /dev/null +++ b/src/test/java/com/example/AviaryService/mcp/McpHttpStatusTest.java @@ -0,0 +1,36 @@ +package com.example.AviaryService.mcp; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.test.context.ActiveProfiles; + +// Against a real Tomcat, not MockMvc: MockMvc skips the servlet error +// dispatch, which once turned the /mcp 401 into a redirect to /login. +// MCP clients only start sign-in on a real 401. +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@ActiveProfiles("test") +class McpHttpStatusTest { + + @LocalServerPort + int port; + + @Test + void noTokenIsA401NotARedirect() throws Exception { + HttpClient client = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NEVER).build(); + HttpResponse response = client.send(HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/mcp")) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString("{}")).build(), + HttpResponse.BodyHandlers.ofString()); + assertEquals(401, response.statusCode()); + assertTrue(response.headers().firstValue("WWW-Authenticate").orElse("").contains("resource_metadata=")); + } +} diff --git a/src/test/java/com/example/AviaryService/mcp/McpSecurityTest.java b/src/test/java/com/example/AviaryService/mcp/McpSecurityTest.java new file mode 100644 index 0000000..1f36f2a --- /dev/null +++ b/src/test/java/com/example/AviaryService/mcp/McpSecurityTest.java @@ -0,0 +1,108 @@ +package com.example.AviaryService.mcp; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.opaqueToken; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +import com.example.AviaryService.entity.FlightLog; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.FlightLogRepository; +import com.example.AviaryService.repositories.UserRepository; + +// /mcp is closed to anyone without a valid Aviary-issued token, and a tool +// only ever sees the token owner's data (constitution Principle I). +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +@Transactional +class McpSecurityTest { + + @Autowired MockMvc mvc; + @Autowired UserRepository userRepository; + @Autowired FlightLogRepository flightLogRepository; + @Autowired FlightTools flightTools; + @Autowired McpCurrentUser currentUser; + + private User alice; + private User bob; + + @BeforeEach + void setUp() { + alice = saveUser("alice-"); + bob = saveUser("bob-"); + FlightLog log = new FlightLog(); + log.setUser(bob); + log.setFromAirport("KSFO"); + log.setToAirport("KLAX"); + flightLogRepository.save(log); + } + + private User saveUser(String prefix) { + User u = new User(); + u.setUsername(prefix + System.nanoTime()); + u.setPassword("x"); + return userRepository.save(u); + } + + @Test + void noTokenGets401PointingAtMetadata() throws Exception { + mvc.perform(post("/mcp").contentType(MediaType.APPLICATION_JSON).content("{}")) + .andExpect(status().isUnauthorized()) + .andExpect(header().string("WWW-Authenticate", + "Bearer resource_metadata=\"http://localhost:8080/.well-known/oauth-protected-resource\"")); + } + + @Test + void unknownTokenGets401() throws Exception { + mvc.perform(post("/mcp").header("Authorization", "Bearer not-a-real-token") + .contentType(MediaType.APPLICATION_JSON).content("{}")) + .andExpect(status().isUnauthorized()); + } + + @Test + void tokenWithoutReadScopeGets403() throws Exception { + mvc.perform(post("/mcp") + .with(opaqueToken().attributes(a -> a.put("sub", alice.getUsername())) + .authorities(new SimpleGrantedAuthority("SCOPE_something.else"))) + .contentType(MediaType.APPLICATION_JSON).content("{}")) + .andExpect(status().isForbidden()); + } + + @Test + void flightToolsOnlySeeTheTokenOwnersFlights() { + assertEquals(0, McpTestSupport.as(alice.getUsername(), () -> flightTools.listFlights()).size()); + assertEquals(1, McpTestSupport.as(bob.getUsername(), () -> flightTools.listFlights()).size()); + } + + @Test + void noSignedInUserMeansNoAccess() { + assertThrows(AccessDeniedException.class, () -> flightTools.listFlights()); + } + + @Test + void missingScopeIsRefusedInsideTools() { + assertThrows(AccessDeniedException.class, + () -> McpTestSupport.as(alice.getUsername(), List.of("aviary.read"), + () -> { currentUser.requireScope("aviary.timeline.import"); return null; })); + assertTrue(McpTestSupport.as(alice.getUsername(), List.of("aviary.read"), + () -> currentUser.require().getUsername().equals(alice.getUsername()))); + } +} diff --git a/src/test/java/com/example/AviaryService/mcp/McpTestSupport.java b/src/test/java/com/example/AviaryService/mcp/McpTestSupport.java new file mode 100644 index 0000000..393ba40 --- /dev/null +++ b/src/test/java/com/example/AviaryService/mcp/McpTestSupport.java @@ -0,0 +1,34 @@ +package com.example.AviaryService.mcp; + +import java.util.Arrays; +import java.util.List; +import java.util.function.Supplier; + +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; + +// Runs MCP tool methods as if a bearer token for `username` with `scopes` had +// just been accepted on /mcp -- so tool tests don't need the JSON-RPC handshake. +public final class McpTestSupport { + + private McpTestSupport() {} + + public static T as(String username, List scopes, Supplier call) { + List authorities = scopes.stream() + .map(s -> (GrantedAuthority) new SimpleGrantedAuthority("SCOPE_" + s)) + .toList(); + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken(username, null, authorities)); + try { + return call.get(); + } finally { + SecurityContextHolder.clearContext(); + } + } + + public static T as(String username, Supplier call) { + return as(username, Arrays.asList("aviary.read", "aviary.timeline.import"), call); + } +} diff --git a/src/test/java/com/example/AviaryService/mcp/TimelineImportToolsTest.java b/src/test/java/com/example/AviaryService/mcp/TimelineImportToolsTest.java new file mode 100644 index 0000000..e23aad2 --- /dev/null +++ b/src/test/java/com/example/AviaryService/mcp/TimelineImportToolsTest.java @@ -0,0 +1,103 @@ +package com.example.AviaryService.mcp; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.test.context.ActiveProfiles; + +import com.example.AviaryService.entity.ServiceTimeline; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.repositories.UserRepository; +import com.example.AviaryService.services.imports.TimelineImportService.ImportResult; +import com.example.AviaryService.util.TimelineImportRules.InputItem; +import com.fasterxml.jackson.databind.ObjectMapper; + +// The MCP tool layer: scopes are enforced, the token owner is the only user a +// tool can touch, and outputs never carry the User entity. +@SpringBootTest +@ActiveProfiles("test") +class TimelineImportToolsTest { + + @Autowired TimelineImportTools tools; + @Autowired UserRepository userRepository; + @Autowired ServiceTimelineRepository timelineRepository; + + private User alice; + private User bob; + + @BeforeEach + void setUp() { + alice = saveUser("tools-alice-"); + bob = saveUser("tools-bob-"); + ServiceTimeline t = new ServiceTimeline(); + t.setUser(bob); + t.setItem("Bob's annual"); + t.setTimelineOrder(0); + timelineRepository.save(t); + } + + private User saveUser(String prefix) { + User u = new User(); + u.setUsername(prefix + System.nanoTime()); + u.setPassword("secret-hash"); + u.setTimeInServiceHours(500.0); + return userRepository.save(u); + } + + private static List oneItem() { + return List.of(new InputItem("Oil", null, null, null, "450", null, null, "50", null, null, null, "Oil 450 / 50", null)); + } + + @Test + void importFormatHasLimitAndExample() { + TimelineImportTools.ImportFormat f = McpTestSupport.as(alice.getUsername(), () -> tools.getImportFormat()); + assertEquals(200, f.maxItems()); + assertFalse(f.example().isBlank()); + } + + @Test + void listOnlyShowsOwnRowsAndNoUser() throws Exception { + List mine = McpTestSupport.as(alice.getUsername(), () -> tools.listServiceTimeline()); + assertEquals(0, mine.size()); + List bobs = McpTestSupport.as(bob.getUsername(), () -> tools.listServiceTimeline()); + assertEquals(1, bobs.size()); + String json = new ObjectMapper().writeValueAsString(bobs); + assertFalse(json.contains("secret-hash")); + assertFalse(json.contains("\"user\"")); + } + + @Test + void importToolsNeedImportScope() { + assertThrows(AccessDeniedException.class, () -> McpTestSupport.as(alice.getUsername(), List.of("aviary.read"), + () -> tools.proposeTimelineImport(oneItem(), null))); + assertThrows(AccessDeniedException.class, () -> McpTestSupport.as(alice.getUsername(), List.of("aviary.read"), + () -> tools.confirmTimelineImport(1L, null))); + assertThrows(AccessDeniedException.class, () -> McpTestSupport.as(alice.getUsername(), List.of("aviary.read"), + () -> tools.continuePoorFit(1L))); + } + + @Test + void proposeThenConfirmAsOwner() { + ImportResult proposed = McpTestSupport.as(alice.getUsername(), () -> tools.proposeTimelineImport(oneItem(), null)); + assertEquals("PROPOSED", proposed.status()); + + // Bob can't confirm Alice's proposal. + assertEquals("NOT_FOUND", McpTestSupport.as(bob.getUsername(), + () -> tools.confirmTimelineImport(proposed.proposalId(), null)).status()); + + ImportResult imported = McpTestSupport.as(alice.getUsername(), + () -> tools.confirmTimelineImport(proposed.proposalId(), null)); + assertEquals("IMPORTED", imported.status()); + assertEquals(1, imported.addedCount()); + assertEquals(1, McpTestSupport.as(alice.getUsername(), () -> tools.listServiceTimeline()).size()); + } +} diff --git a/src/test/java/com/example/AviaryService/oauth/CimdFetcherTest.java b/src/test/java/com/example/AviaryService/oauth/CimdFetcherTest.java new file mode 100644 index 0000000..7cc995a --- /dev/null +++ b/src/test/java/com/example/AviaryService/oauth/CimdFetcherTest.java @@ -0,0 +1,165 @@ +package com.example.AviaryService.oauth; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.UnknownHostException; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import com.sun.net.httpserver.HttpServer; + +// The CIMD fetch takes a URL from whoever starts a sign-in, so these pin down +// the SSRF guard: what it refuses before connecting, and what it refuses in +// the response. +class CimdFetcherTest { + + private static final String URL = "https://assistant.example.com/oauth/client.json"; + private static final InetAddress PUBLIC = addr("93.184.216.34"); + + private HttpServer server; + + @AfterEach + void stopServer() { + if (server != null) server.stop(0); + } + + private static InetAddress addr(String ip) { + try { + return InetAddress.getByName(ip); + } catch (UnknownHostException e) { + throw new IllegalStateException(e); + } + } + + private static CimdFetcher fetcher(InetAddress resolved, String body) { + return new CimdFetcher(host -> new InetAddress[] { resolved }, + uri -> body.getBytes(StandardCharsets.UTF_8)); + } + + private static String doc(String clientId) { + return "{\"client_id\":\"" + clientId + "\",\"client_name\":\"Test Assistant\"," + + "\"redirect_uris\":[\"http://localhost/callback\"]}"; + } + + @Test + void acceptsValidDocument() { + CimdFetcher.ClientMetadata m = fetcher(PUBLIC, doc(URL)).fetch(URL); + assertEquals("Test Assistant", m.clientName()); + assertEquals(List.of("http://localhost/callback"), m.redirectUris()); + } + + @Test + void rejectsHttpUrl() { + String url = "http://assistant.example.com/client.json"; + assertThrows(IllegalArgumentException.class, () -> fetcher(PUBLIC, doc(url)).fetch(url)); + } + + @Test + void rejectsUrlWithoutPath() { + String url = "https://assistant.example.com/"; + assertThrows(IllegalArgumentException.class, () -> fetcher(PUBLIC, doc(url)).fetch(url)); + } + + @Test + void rejectsIpLiteralHosts() { + for (String url : List.of("https://93.184.216.34/client.json", "https://[2001:db8::1]/client.json")) { + assertThrows(IllegalArgumentException.class, () -> fetcher(PUBLIC, doc(url)).fetch(url), url); + } + } + + @Test + void rejectsHostsResolvingToPrivateAddresses() { + for (String ip : List.of("127.0.0.1", "10.0.0.5", "172.16.0.1", "192.168.1.1", "169.254.169.254", + "100.64.0.1", "0.0.0.0", "::1", "fe80::1", "fd00::1")) { + CimdFetcher f = fetcher(addr(ip), doc(URL)); + assertThrows(IllegalArgumentException.class, () -> f.fetch(URL), ip); + } + } + + @Test + void rejectsWhenAnyResolvedAddressIsPrivate() { + CimdFetcher f = new CimdFetcher(host -> new InetAddress[] { PUBLIC, addr("10.0.0.1") }, + uri -> doc(URL).getBytes(StandardCharsets.UTF_8)); + assertThrows(IllegalArgumentException.class, () -> f.fetch(URL)); + } + + @Test + void rejectsMismatchedClientId() { + assertThrows(IllegalArgumentException.class, + () -> fetcher(PUBLIC, doc("https://other.example.com/client.json")).fetch(URL)); + } + + @Test + void rejectsDocumentWithoutRedirectUris() { + String body = "{\"client_id\":\"" + URL + "\",\"redirect_uris\":[]}"; + assertThrows(IllegalArgumentException.class, () -> fetcher(PUBLIC, body).fetch(URL)); + } + + @Test + void rejectsNonJson() { + assertThrows(IllegalArgumentException.class, () -> fetcher(PUBLIC, "").fetch(URL)); + } + + // The transport itself, against a real local server. + + private URI serve(int status, byte[] body, long delayMs) throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/client.json", exchange -> { + try { + Thread.sleep(delayMs); + } catch (InterruptedException ignored) { + Thread.currentThread().interrupt(); + } + if (status == 302) exchange.getResponseHeaders().add("Location", "http://169.254.169.254/"); + exchange.sendResponseHeaders(status, body.length == 0 ? -1 : body.length); + if (body.length > 0) { + try (OutputStream out = exchange.getResponseBody()) { + out.write(body); + } + } + exchange.close(); + }); + server.start(); + return URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/client.json"); + } + + @Test + void transportReturnsSmallBody() throws IOException { + URI uri = serve(200, "{}".getBytes(StandardCharsets.UTF_8), 0); + byte[] body = new CimdFetcher.HttpTransport(Duration.ofSeconds(2)).get(uri); + assertEquals("{}", new String(body, StandardCharsets.UTF_8)); + } + + @Test + void transportRejectsOversizeBody() throws IOException { + URI uri = serve(200, new byte[CimdFetcher.MAX_BYTES + 1], 0); + IOException e = assertThrows(IOException.class, + () -> new CimdFetcher.HttpTransport(Duration.ofSeconds(2)).get(uri)); + assertTrue(e.getMessage().contains("larger")); + } + + @Test + void transportDoesNotFollowRedirects() throws IOException { + URI uri = serve(302, new byte[0], 0); + IOException e = assertThrows(IOException.class, + () -> new CimdFetcher.HttpTransport(Duration.ofSeconds(2)).get(uri)); + assertTrue(e.getMessage().contains("302")); + } + + @Test + void transportTimesOut() throws IOException { + URI uri = serve(200, "{}".getBytes(StandardCharsets.UTF_8), 1500); + assertThrows(IOException.class, () -> new CimdFetcher.HttpTransport(Duration.ofMillis(200)).get(uri)); + } +} diff --git a/src/test/java/com/example/AviaryService/oauth/CimdRegisteredClientRepositoryTest.java b/src/test/java/com/example/AviaryService/oauth/CimdRegisteredClientRepositoryTest.java new file mode 100644 index 0000000..55e36d1 --- /dev/null +++ b/src/test/java/com/example/AviaryService/oauth/CimdRegisteredClientRepositoryTest.java @@ -0,0 +1,93 @@ +package com.example.AviaryService.oauth; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.springframework.security.oauth2.core.ClientAuthenticationMethod; +import org.springframework.security.oauth2.server.authorization.client.RegisteredClient; +import org.springframework.security.oauth2.server.authorization.settings.OAuth2TokenFormat; + +class CimdRegisteredClientRepositoryTest { + + private static final String URL = "https://assistant.example.com/client.json"; + + private static class MutableClock extends Clock { + Instant now = Instant.parse("2026-10-20T12:00:00Z"); + @Override public ZoneOffset getZone() { return ZoneOffset.UTC; } + @Override public Clock withZone(java.time.ZoneId zone) { return this; } + @Override public Instant instant() { return now; } + } + + private final CimdFetcher fetcher = mock(CimdFetcher.class); + private final MutableClock clock = new MutableClock(); + private final CimdRegisteredClientRepository repo = new CimdRegisteredClientRepository(fetcher, clock); + + private void documentIsGood() { + when(fetcher.fetch(URL)).thenReturn( + new CimdFetcher.ClientMetadata(URL, "Assistant", List.of("http://localhost/callback"))); + } + + @Test + void buildsPublicPkceClientWithOpaqueTokens() { + documentIsGood(); + RegisteredClient c = repo.findByClientId(URL); + assertEquals(URL, c.getClientId()); + assertTrue(c.getClientAuthenticationMethods().contains(ClientAuthenticationMethod.NONE)); + assertTrue(c.getClientSettings().isRequireProofKey()); + assertTrue(c.getClientSettings().isRequireAuthorizationConsent()); + assertEquals(OAuth2TokenFormat.REFERENCE, c.getTokenSettings().getAccessTokenFormat()); + } + + @Test + void nonCimdClientIdIsUnknownWithoutFetching() { + assertNull(repo.findByClientId("my-client")); + assertNull(repo.findByClientId("http://assistant.example.com/client.json")); + } + + @Test + void cachesForAnHour() { + documentIsGood(); + repo.findByClientId(URL); + repo.findByClientId(URL); + verify(fetcher, times(1)).fetch(URL); + clock.now = clock.now.plus(Duration.ofMinutes(61)); + repo.findByClientId(URL); + verify(fetcher, times(2)).fetch(URL); + } + + @Test + void keepsLastGoodCopyWhenRefetchFails() { + documentIsGood(); + repo.findByClientId(URL); + when(fetcher.fetch(URL)).thenThrow(new IllegalArgumentException("site down")); + clock.now = clock.now.plus(Duration.ofHours(2)); + assertNotNull(repo.findByClientId(URL)); + } + + @Test + void unknownWhenFirstFetchFails() { + when(fetcher.fetch(URL)).thenThrow(new IllegalArgumentException("bad")); + assertNull(repo.findByClientId(URL)); + } + + @Test + void registrationIsRefused() { + documentIsGood(); + RegisteredClient c = repo.findByClientId(URL); + assertThrows(UnsupportedOperationException.class, () -> repo.save(c)); + } +} diff --git a/src/test/java/com/example/AviaryService/oauth/OAuthFlowIntegrationTest.java b/src/test/java/com/example/AviaryService/oauth/OAuthFlowIntegrationTest.java new file mode 100644 index 0000000..b8f82de --- /dev/null +++ b/src/test/java/com/example/AviaryService/oauth/OAuthFlowIntegrationTest.java @@ -0,0 +1,334 @@ +package com.example.AviaryService.oauth; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Base64; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.util.UriComponentsBuilder; + +import com.example.AviaryService.entity.OAuthAuthorizationEntity; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.OAuthAuthorizationRepository; +import com.example.AviaryService.repositories.UserRepository; +import com.example.AviaryService.services.imports.ConnectionService; +import com.fasterxml.jackson.databind.ObjectMapper; + +// The whole sign-in an AI assistant does: authorize -> consent -> token with +// PKCE -> call /mcp -> owner disconnects -> token stops working. The CIMD +// download is stubbed; everything else is the real filter chains and the +// real (hashed) database storage. +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +@Transactional +class OAuthFlowIntegrationTest { + + private static final String CLIENT_ID = "https://assistant.example.com/oauth/client.json"; + private static final String REDIRECT = "http://127.0.0.1:54321/callback"; + + @Autowired MockMvc mvc; + @Autowired UserRepository userRepository; + @Autowired OAuthAuthorizationRepository authorizationRepository; + @Autowired ConnectionService connectionService; + @Autowired com.example.AviaryService.repositories.FlightLogRepository flightLogRepository; + @MockitoBean CimdFetcher cimdFetcher; + + private final ObjectMapper json = new ObjectMapper(); + private User owner; + + @BeforeEach + void setUp() { + owner = new User(); + owner.setUsername("oauth-" + System.nanoTime()); + owner.setPassword("x"); + userRepository.save(owner); + when(cimdFetcher.fetch(anyString())).thenReturn(new CimdFetcher.ClientMetadata( + CLIENT_ID, "Test Assistant", List.of("http://localhost/callback"))); + } + + private static String challenge(String verifier) throws Exception { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(verifier.getBytes(StandardCharsets.US_ASCII)); + return Base64.getUrlEncoder().withoutPadding().encodeToString(digest); + } + + private static Map> query(String url) { + return UriComponentsBuilder.fromUriString(url).build().getQueryParams(); + } + + // Spring reads GET /oauth2/authorize parameters from the raw query string, + // so they go in the URL rather than MockMvc's .param(). + private static java.net.URI authorizeUrl(String... keyValues) { + UriComponentsBuilder b = UriComponentsBuilder.fromPath("/oauth2/authorize"); + for (int i = 0; i < keyValues.length; i += 2) { + b.queryParam(keyValues[i], keyValues[i + 1]); + } + return b.encode().build().toUri(); + } + + // Runs authorize + consent and returns the authorization code. + private String authorize(String verifier) throws Exception { + MvcResult toConsent = mvc.perform(get(authorizeUrl( + "response_type", "code", + "client_id", CLIENT_ID, + "redirect_uri", REDIRECT, + "scope", "aviary.read aviary.timeline.import", + "state", "client-state", + "code_challenge", challenge(verifier), + "code_challenge_method", "S256", + "resource", "http://localhost:8080/mcp")) + .with(user(owner.getUsername()))) + .andReturn(); + assertEquals(302, toConsent.getResponse().getStatus(), toConsent.getResponse().getErrorMessage()); + String consentUrl = toConsent.getResponse().getRedirectedUrl(); + assertNotNull(consentUrl); + assertTrue(consentUrl.contains("/oauth2/consent"), consentUrl); + String serverState = query(consentUrl).get("state").get(0); + + MvcResult toClient = mvc.perform(post("/oauth2/authorize") + .param("client_id", CLIENT_ID) + .param("state", java.net.URLDecoder.decode(serverState, StandardCharsets.UTF_8)) + .param("scope", "aviary.read") + .param("scope", "aviary.timeline.import") + .with(user(owner.getUsername()))) + .andExpect(status().is3xxRedirection()) + .andReturn(); + String callback = toClient.getResponse().getRedirectedUrl(); + assertTrue(callback.startsWith(REDIRECT), callback); + assertEquals("client-state", query(callback).get("state").get(0)); + return query(callback).get("code").get(0); + } + + private Map exchange(String code, String verifier) throws Exception { + MvcResult tokens = mvc.perform(post("/oauth2/token") + .param("grant_type", "authorization_code") + .param("code", java.net.URLDecoder.decode(code, StandardCharsets.UTF_8)) + .param("redirect_uri", REDIRECT) + .param("client_id", CLIENT_ID) + .param("code_verifier", verifier)) + .andExpect(status().isOk()) + .andReturn(); + return json.readValue(tokens.getResponse().getContentAsString(), Map.class); + } + + private int callMcp(String accessToken) throws Exception { + String initialize = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{" + + "\"protocolVersion\":\"2025-06-18\",\"capabilities\":{}," + + "\"clientInfo\":{\"name\":\"test\",\"version\":\"1\"}}}"; + return mvc.perform(post("/mcp") + .header("Authorization", "Bearer " + accessToken) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON, MediaType.TEXT_EVENT_STREAM) + .content(initialize)) + .andReturn().getResponse().getStatus(); + } + + // A real JSON-RPC tool call over /mcp: proves the token's owner reaches + // the tool (not just that the filter let the request through). + private String callTool(String accessToken, String tool) throws Exception { + String initialize = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{" + + "\"protocolVersion\":\"2025-06-18\",\"capabilities\":{}," + + "\"clientInfo\":{\"name\":\"test\",\"version\":\"1\"}}}"; + MvcResult init = mvc.perform(post("/mcp") + .header("Authorization", "Bearer " + accessToken) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON, MediaType.TEXT_EVENT_STREAM) + .content(initialize)) + .andReturn(); + String session = init.getResponse().getHeader("Mcp-Session-Id"); + assertNotNull(session, "status " + init.getResponse().getStatus() + " " + init.getResponse().getContentAsString()); + + mvc.perform(post("/mcp") + .header("Authorization", "Bearer " + accessToken) + .header("Mcp-Session-Id", session) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON, MediaType.TEXT_EVENT_STREAM) + .content("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}")); + + MvcResult call = mvc.perform(post("/mcp") + .header("Authorization", "Bearer " + accessToken) + .header("Mcp-Session-Id", session) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON, MediaType.TEXT_EVENT_STREAM) + .content("{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"" + tool + "\",\"arguments\":{}}}")) + .andReturn(); + if (call.getRequest().isAsyncStarted()) { + call = mvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch(call)).andReturn(); + } + return call.getResponse().getContentAsString(); + } + + @Test + void toolCallRunsAsTheTokenOwner() throws Exception { + com.example.AviaryService.entity.FlightLog log = new com.example.AviaryService.entity.FlightLog(); + log.setUser(owner); + log.setFromAirport("KPAO"); + log.setToAirport("KMRY"); + flightLogRepository.save(log); + + String verifier = "verifier-" + "t".repeat(50); + String accessToken = (String) exchange(authorize(verifier), verifier).get("access_token"); + String body = callTool(accessToken, "list_flights"); + assertTrue(body.contains("KPAO"), body); + assertFalse(body.contains("\"isError\":true"), body); + } + + @Test + void fullSignInThenDisconnect() throws Exception { + String verifier = "verifier-" + "x".repeat(50); + Map tokens = exchange(authorize(verifier), verifier); + + String accessToken = (String) tokens.get("access_token"); + assertNotNull(accessToken); + assertEquals("Bearer", tokens.get("token_type")); + // Spring Authorization Server 1.4 gives public clients no refresh token; + // the 7-day access token is the session (see CimdRegisteredClientRepository). + assertFalse(tokens.containsKey("refresh_token")); + + // Stored hashed, never as the token itself. + List rows = authorizationRepository.findByPrincipalName(owner.getUsername()); + assertEquals(1, rows.size()); + assertTrue(rows.get(0).getAccessTokenValue().startsWith("sha256:")); + assertNotEquals(accessToken, rows.get(0).getAccessTokenValue()); + assertEquals("Test Assistant", rows.get(0).getClientName()); + + assertEquals(200, callMcp(accessToken)); + + // Shows on the Connected assistants page, then the owner disconnects it. + List connections = connectionService.list(owner); + assertEquals(1, connections.size()); + connectionService.disconnect(owner, connections.get(0).id()); + + assertEquals(401, callMcp(accessToken)); + } + + @Test + void wrongVerifierIsRejected() throws Exception { + String verifier = "verifier-" + "y".repeat(50); + String code = authorize(verifier); + mvc.perform(post("/oauth2/token") + .param("grant_type", "authorization_code") + .param("code", java.net.URLDecoder.decode(code, StandardCharsets.UTF_8)) + .param("redirect_uri", REDIRECT) + .param("client_id", CLIENT_ID) + .param("code_verifier", "some-other-verifier-" + "z".repeat(40))) + .andExpect(status().isBadRequest()); + } + + @Test + void codeCannotBeUsedTwice() throws Exception { + String verifier = "verifier-" + "w".repeat(50); + String code = authorize(verifier); + exchange(code, verifier); + mvc.perform(post("/oauth2/token") + .param("grant_type", "authorization_code") + .param("code", java.net.URLDecoder.decode(code, StandardCharsets.UTF_8)) + .param("redirect_uri", REDIRECT) + .param("client_id", CLIENT_ID) + .param("code_verifier", verifier)) + .andExpect(status().isBadRequest()); + } + + @Test + void authorizeWithoutPkceIsRejected() throws Exception { + MvcResult result = mvc.perform(get(authorizeUrl( + "response_type", "code", + "client_id", CLIENT_ID, + "redirect_uri", REDIRECT, + "scope", "aviary.read", + "state", "s")) + .with(user(owner.getUsername()))) + .andReturn(); + String redirect = result.getResponse().getRedirectedUrl(); + assertTrue(redirect == null || redirect.contains("error="), String.valueOf(redirect)); + assertTrue(redirect == null || !redirect.contains("code="), redirect); + } + + @Test + void unregisteredRedirectUriIsRejectedWithoutRedirecting() throws Exception { + MvcResult result = mvc.perform(get(authorizeUrl( + "response_type", "code", + "client_id", CLIENT_ID, + "redirect_uri", "https://evil.example.net/callback", + "scope", "aviary.read", + "state", "s", + "code_challenge", challenge("v".repeat(50)), + "code_challenge_method", "S256")) + .with(user(owner.getUsername()))) + .andReturn(); + assertEquals(400, result.getResponse().getStatus()); + } + + @Test + void notSignedInGoesToLogin() throws Exception { + MvcResult result = mvc.perform(get(authorizeUrl( + "response_type", "code", + "client_id", CLIENT_ID, + "redirect_uri", REDIRECT, + "scope", "aviary.read", + "state", "s", + "code_challenge", challenge("v".repeat(50)), + "code_challenge_method", "S256")) + .accept(MediaType.TEXT_HTML)) + .andReturn(); + assertEquals(302, result.getResponse().getStatus(), result.getResponse().getErrorMessage()); + assertTrue(result.getResponse().getRedirectedUrl().endsWith("/login")); + } + + @Test + void noScopeRequestedGetsBothScopes() throws Exception { + MvcResult result = mvc.perform(get(authorizeUrl( + "response_type", "code", + "client_id", CLIENT_ID, + "redirect_uri", REDIRECT, + "state", "s", + "code_challenge", challenge("v".repeat(50)), + "code_challenge_method", "S256")) + .with(user(owner.getUsername()))) + .andReturn(); + assertEquals(302, result.getResponse().getStatus(), result.getResponse().getErrorMessage()); + String scope = java.net.URLDecoder.decode( + query(result.getResponse().getRedirectedUrl()).get("scope").get(0), StandardCharsets.UTF_8); + assertTrue(scope.contains("aviary.read") && scope.contains("aviary.timeline.import"), scope); + } + + @Test + void metadataAdvertisesCimdAndPkce() throws Exception { + MvcResult result = mvc.perform(get("/.well-known/oauth-authorization-server")) + .andExpect(status().isOk()).andReturn(); + Map metadata = json.readValue(result.getResponse().getContentAsString(), Map.class); + assertEquals(Boolean.TRUE, metadata.get("client_id_metadata_document_supported")); + assertEquals(List.of("none"), metadata.get("token_endpoint_auth_methods_supported")); + assertEquals(List.of("S256"), metadata.get("code_challenge_methods_supported")); + assertFalse(metadata.containsKey("registration_endpoint")); + + MvcResult prm = mvc.perform(get("/.well-known/oauth-protected-resource")) + .andExpect(status().isOk()).andReturn(); + Map resource = json.readValue(prm.getResponse().getContentAsString(), Map.class); + assertEquals("http://localhost:8080/mcp", resource.get("resource")); + } +} diff --git a/src/test/java/com/example/AviaryService/services/imports/ConnectionServiceTest.java b/src/test/java/com/example/AviaryService/services/imports/ConnectionServiceTest.java new file mode 100644 index 0000000..67b1f58 --- /dev/null +++ b/src/test/java/com/example/AviaryService/services/imports/ConnectionServiceTest.java @@ -0,0 +1,87 @@ +package com.example.AviaryService.services.imports; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.time.Instant; +import java.util.NoSuchElementException; +import java.util.UUID; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.transaction.annotation.Transactional; + +import com.example.AviaryService.entity.OAuthAuthorizationEntity; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.OAuthAuthorizationRepository; +import com.example.AviaryService.repositories.UserRepository; + +@SpringBootTest +@ActiveProfiles("test") +@Transactional +class ConnectionServiceTest { + + @Autowired ConnectionService connectionService; + @Autowired OAuthAuthorizationRepository repository; + @Autowired UserRepository userRepository; + + private User alice; + private User bob; + + @BeforeEach + void setUp() { + alice = saveUser("alice-"); + bob = saveUser("bob-"); + } + + private User saveUser(String prefix) { + User u = new User(); + u.setUsername(prefix + System.nanoTime()); + u.setPassword("x"); + return userRepository.save(u); + } + + private OAuthAuthorizationEntity grant(User owner, boolean finished) { + OAuthAuthorizationEntity e = new OAuthAuthorizationEntity(); + e.setId(UUID.randomUUID().toString()); + e.setRegisteredClientId("https://assistant.example.com/oauth/client.json"); + e.setPrincipalName(owner.getUsername()); + e.setAuthorizationGrantType("authorization_code"); + e.setClientName("Test Assistant"); + if (finished) { + e.setAccessTokenValue("sha256:" + UUID.randomUUID()); + e.setAccessTokenIssuedAt(Instant.now()); + } + return repository.save(e); + } + + @Test + void listsOnlyOwnFinishedConnections() { + grant(alice, true); + grant(alice, false); // abandoned sign-in + grant(bob, true); + + var list = connectionService.list(alice); + assertEquals(1, list.size()); + assertEquals("Test Assistant", list.get(0).clientName()); + assertEquals("assistant.example.com", list.get(0).clientHost()); + } + + @Test + void cannotDisconnectSomeoneElsesConnection() { + OAuthAuthorizationEntity bobs = grant(bob, true); + assertThrows(NoSuchElementException.class, () -> connectionService.disconnect(alice, bobs.getId())); + assertTrue(repository.findById(bobs.getId()).isPresent()); + } + + @Test + void disconnectRemovesTheGrant() { + OAuthAuthorizationEntity mine = grant(alice, true); + connectionService.disconnect(alice, mine.getId()); + assertTrue(repository.findById(mine.getId()).isEmpty()); + } +} diff --git a/src/test/java/com/example/AviaryService/services/imports/TimelineImportServiceTest.java b/src/test/java/com/example/AviaryService/services/imports/TimelineImportServiceTest.java new file mode 100644 index 0000000..ecb845f --- /dev/null +++ b/src/test/java/com/example/AviaryService/services/imports/TimelineImportServiceTest.java @@ -0,0 +1,302 @@ +package com.example.AviaryService.services.imports; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.time.Instant; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +import com.example.AviaryService.entity.ImportProposal; +import com.example.AviaryService.entity.ServiceTimeline; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.ImportProposalRepository; +import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.repositories.TimelineImportRecordRepository; +import com.example.AviaryService.repositories.UserRepository; +import com.example.AviaryService.services.dashboard.TimelineService; +import com.example.AviaryService.services.imports.TimelineImportService.ImportResult; +import com.example.AviaryService.util.TimelineImportRules.InputItem; +import com.example.AviaryService.util.TimelineImportRules.RejectedRow; + +// Propose / continue / confirm against real H2. Not @Transactional: confirm +// runs its own transaction and the all-or-nothing test needs to see what it +// actually committed. Every test uses fresh users, so leftover rows don't +// interfere. +@SpringBootTest +@ActiveProfiles("test") +class TimelineImportServiceTest { + + @Autowired TimelineImportService importService; + @Autowired TimelineService timelineService; + @Autowired ImportProposalRepository proposalRepository; + @Autowired ServiceTimelineRepository timelineRepository; + @Autowired TimelineImportRecordRepository recordRepository; + @Autowired UserRepository userRepository; + + private User alice; + private User bob; + + @BeforeEach + void setUp() { + alice = saveUser("import-alice-"); + bob = saveUser("import-bob-"); + } + + private User saveUser(String prefix) { + User u = new User(); + u.setUsername(prefix + System.nanoTime()); + u.setPassword("x"); + u.setTimeInServiceHours(1000.0); + return userRepository.save(u); + } + + private ServiceTimeline existing(User owner, String name, int order) { + ServiceTimeline t = new ServiceTimeline(); + t.setUser(owner); + t.setItem(name); + t.setTimelineOrder(order); + t.setLastDoneDate("2026-01-01"); + return timelineRepository.save(t); + } + + private static InputItem calendarItem(String name, String lastDone, String months) { + return new InputItem(name, null, null, lastDone, null, months, "MONTHS", null, null, null, null, name + " row", null); + } + + private static InputItem hoursItem(String name, String lastHours, String cycle) { + return new InputItem(name, null, null, null, lastHours, null, null, cycle, null, null, null, name + " row", null); + } + + private static InputItem junk(String text) { + return new InputItem(null, null, null, null, null, null, null, null, null, null, null, text, null); + } + + private List rows(User u) { + return timelineRepository.findByUserOrderByTimelineOrderAsc(u); + } + + // ---- propose (US1) ---- + + @Test + void proposeLeavesTimelineUnchanged() { + existing(alice, "Annual", 0); + ImportResult r = importService.propose(alice, + List.of(calendarItem("ELT", "2026-01-10", "12"), hoursItem("Oil", "1000", "50")), null, null); + assertEquals("PROPOSED", r.status()); + assertNotNull(r.proposalId()); + assertEquals(2, r.items().size()); + assertEquals(1, rows(alice).size()); + } + + @Test + void secondProposalReplacesFirst() { + ImportResult first = importService.propose(alice, List.of(hoursItem("Oil", "1000", "50")), null, null); + ImportResult second = importService.propose(alice, List.of(hoursItem("Oil", "1000", "25")), null, null); + assertEquals(ImportProposal.REPLACED, proposalRepository.findById(first.proposalId()).orElseThrow().getStatus()); + assertEquals(ImportProposal.OPEN, proposalRepository.findById(second.proposalId()).orElseThrow().getStatus()); + assertEquals("REPLACED", importService.confirm(alice, first.proposalId(), null).status()); + } + + @Test + void proposalExpiresAfter24Hours() { + ImportResult r = importService.propose(alice, List.of(hoursItem("Oil", "1000", "50")), null, null); + ImportProposal p = proposalRepository.findById(r.proposalId()).orElseThrow(); + assertEquals(TimelineImportService.PROPOSAL_TTL, java.time.Duration.between(p.getCreatedAt(), p.getExpiresAt())); + + p.setExpiresAt(Instant.now().minusSeconds(1)); + proposalRepository.save(p); + assertEquals("EXPIRED", importService.confirm(alice, r.proposalId(), null).status()); + assertEquals(0, rows(alice).size()); + } + + @Test + void proposalRateLimit() { + for (int i = 0; i < TimelineImportService.PROPOSALS_PER_HOUR; i++) { + assertEquals("PROPOSED", importService.propose(alice, List.of(hoursItem("Oil", "1000", "50")), null, null).status()); + } + ImportResult limited = importService.propose(alice, List.of(hoursItem("Oil", "1000", "50")), null, null); + assertEquals("RATE_LIMITED", limited.status()); + assertNotNull(limited.retryAfterSeconds()); + // Per owner: bob is unaffected. + assertEquals("PROPOSED", importService.propose(bob, List.of(hoursItem("Oil", "1000", "50")), null, null).status()); + } + + @Test + void otherOwnerCannotUseProposal() { + ImportResult r = importService.propose(alice, List.of(hoursItem("Oil", "1000", "50")), null, null); + assertEquals("NOT_FOUND", importService.confirm(bob, r.proposalId(), null).status()); + assertEquals("NOT_FOUND", importService.continuePoorFit(bob, r.proposalId()).status()); + assertEquals(0, rows(bob).size()); + assertEquals(ImportProposal.OPEN, proposalRepository.findById(r.proposalId()).orElseThrow().getStatus()); + } + + @Test + void sourceRejectsAppearInProposal() { + ImportResult r = importService.propose(alice, List.of(hoursItem("Oil", "1000", "50")), + List.of(new RejectedRow("smudged line", "Unreadable")), null); + assertEquals("PROPOSED", r.status()); + assertTrue(r.rejected().stream().anyMatch(x -> x.sourceRow().equals("smudged line"))); + } + + // ---- confirm (US2) ---- + + @Test + void confirmAddsExactlyTheProposalAfterExistingRows() { + existing(alice, "Annual", 0); + existing(alice, "Transponder", 1); + ImportResult p = importService.propose(alice, + List.of(new InputItem("Engine", null, true, null, null, null, null, null, null, null, null, "ENGINE", null), + hoursItem("Oil", "1,000", "50"), + calendarItem("ELT", "2026-01-10", "12")), null, "https://assistant.example.com/oauth/client.json"); + + ImportResult r = importService.confirm(alice, p.proposalId(), null); + assertEquals("IMPORTED", r.status(), r.message()); + assertEquals(3, r.addedCount()); + + List all = rows(alice); + assertEquals(List.of("Annual", "Transponder", "Engine", "Oil", "ELT"), + all.stream().map(ServiceTimeline::getItem).toList()); + assertEquals(List.of(0, 1, 2, 3, 4), all.stream().map(ServiceTimeline::getTimelineOrder).toList()); + assertEquals("2026-01-01", all.get(0).getLastDoneDate()); // existing row untouched + + ServiceTimeline oil = all.get(3); + assertEquals("1000", oil.getLastDoneHours()); + assertEquals("1050", oil.getDueDateHours()); + assertEquals(50.0, oil.getCycleHours()); + ServiceTimeline elt = all.get(4); + assertEquals("2027-01-10", elt.getDueDateDate()); + assertTrue(all.get(2).getIsTitle()); + + assertEquals(1, recordRepository.findTop20ByUserOrderByImportedAtDesc(alice).size()); + assertEquals(3, recordRepository.findTop20ByUserOrderByImportedAtDesc(alice).get(0).getItemCount()); + assertEquals("ALREADY_CONFIRMED", importService.confirm(alice, p.proposalId(), null).status()); + } + + @Test + void duplicatesSkippedUnlessOptedIn() { + existing(alice, "Oil Change", 0); + existing(alice, "Annual", 1); + ImportResult p = importService.propose(alice, + List.of(hoursItem("oil change", "1000", "50"), calendarItem("annual", "2026-02-01", "12"), + hoursItem("Mags", "1000", "500")), null, null); + int annualIndex = p.items().stream().filter(i -> i.item().equals("annual")).findFirst().orElseThrow().index(); + + ImportResult r = importService.confirm(alice, p.proposalId(), Set.of(annualIndex)); + assertEquals(2, r.addedCount()); + assertEquals(List.of("oil change"), r.skippedDuplicates()); + assertEquals(List.of("Oil Change", "Annual", "annual", "Mags"), + rows(alice).stream().map(ServiceTimeline::getItem).toList()); + } + + @Test + void matchAddedAfterProposalIsSkippedAndReported() { + ImportResult p = importService.propose(alice, List.of(hoursItem("Oil", "1000", "50"), hoursItem("Mags", "1000", "500")), null, null); + existing(alice, "OIL", 0); + ImportResult r = importService.confirm(alice, p.proposalId(), null); + assertEquals(1, r.addedCount()); + assertEquals(List.of("Oil"), r.newDuplicates()); + } + + @Test + void failedConfirmSavesNothing() { + ImportResult p = importService.propose(alice, + List.of(hoursItem("One", "1", "5"), hoursItem("Two", "1", "5"), hoursItem("Three", "1", "5")), null, null); + // Corrupt item 3 in storage so its insert fails (name too long for the column). + ImportProposal stored = proposalRepository.findById(p.proposalId()).orElseThrow(); + stored.setItemsJson(stored.getItemsJson().replace("\"Three\"", "\"" + "x".repeat(400) + "\"")); + proposalRepository.save(stored); + + ImportResult r = importService.confirm(alice, p.proposalId(), null); + assertEquals("FAILED", r.status()); + assertEquals(0, rows(alice).size()); + assertEquals(ImportProposal.OPEN, proposalRepository.findById(p.proposalId()).orElseThrow().getStatus()); + assertEquals(0, recordRepository.findTop20ByUserOrderByImportedAtDesc(alice).size()); + } + + @Test + void confirmRateLimit() { + for (int i = 0; i < TimelineImportService.CONFIRMS_PER_HOUR; i++) { + importService.confirm(alice, -1L, null); + } + assertEquals("RATE_LIMITED", importService.confirm(alice, -1L, null).status()); + } + + @Test + void importedItemWorksWithCompleteMaintenance() { + ImportResult p = importService.propose(alice, List.of(hoursItem("Oil", "900", "50")), null, null); + importService.confirm(alice, p.proposalId(), null); + ServiceTimeline oil = rows(alice).get(0); + TimelineService.CompletedMaintenance done = timelineService.completeMaintenance(alice, oil.getId()); + assertEquals("1000", done.lastDone()); + assertEquals("1050", done.dueDate()); + } + + @Test + void onConditionItemIsImportedAndLabeled() { + ImportResult p = importService.propose(alice, List.of( + new InputItem("Flexible Fluid Hose", "Replace", null, null, null, null, null, null, null, null, null, "hose row", true), + new InputItem("Brake Pads", null, null, null, null, null, null, null, null, null, null, "pads row", true)), + null, null); + assertEquals("PROPOSED", p.status(), p.message()); + assertEquals("IMPORTED", importService.confirm(alice, p.proposalId(), null).status()); + List all = rows(alice); + assertEquals("Replace (on condition)", all.get(0).getDescription()); + assertEquals("On condition", all.get(1).getDescription()); + assertNull(all.get(0).getDueDateDate()); + } + + @Test + void onConditionDescriptionRules() { + assertEquals("On condition", TimelineImportService.onConditionDescription(null)); + assertEquals("Replace On Condition", TimelineImportService.onConditionDescription("Replace On Condition")); + String long255 = "x".repeat(250); + assertEquals(long255, TimelineImportService.onConditionDescription(long255)); + } + + // ---- refusals (US3) ---- + + @Test + void unrelatedInputCreatesNoProposal() { + long before = proposalRepository.count(); + ImportResult r = importService.propose(alice, List.of(junk("Banana bread: 3 bananas"), junk("Bake 350F 1 hr")), null, null); + assertEquals("REJECTED", r.status()); + assertNull(r.proposalId()); + assertNotNull(r.example()); + assertEquals(2, r.rejected().size()); + assertEquals(before, proposalRepository.count()); + } + + @Test + void tooLargeCreatesNoProposal() { + long before = proposalRepository.count(); + List many = new java.util.ArrayList<>(); + for (int i = 0; i < 201; i++) many.add(hoursItem("Item " + i, "1", "5")); + assertEquals("TOO_LARGE", importService.propose(alice, many, null, null).status()); + assertEquals(before, proposalRepository.count()); + } + + @Test + void poorFitNeedsContinueBeforeConfirm() { + ImportResult p = importService.propose(alice, + List.of(hoursItem("Oil", "1000", "50"), junk("??"), junk("###")), null, null); + assertEquals("POOR_FIT", p.status()); + assertEquals(ImportProposal.NEEDS_FIT_CONFIRMATION, + proposalRepository.findById(p.proposalId()).orElseThrow().getStatus()); + + assertEquals("NEEDS_FIT_CONFIRMATION", importService.confirm(alice, p.proposalId(), null).status()); + assertEquals(0, rows(alice).size()); + + assertEquals("PROPOSED", importService.continuePoorFit(alice, p.proposalId()).status()); + assertEquals("IMPORTED", importService.confirm(alice, p.proposalId(), null).status()); + assertEquals(1, rows(alice).size()); + } +} diff --git a/src/test/java/com/example/AviaryService/util/TimelineImportRulesTest.java b/src/test/java/com/example/AviaryService/util/TimelineImportRulesTest.java new file mode 100644 index 0000000..740ee92 --- /dev/null +++ b/src/test/java/com/example/AviaryService/util/TimelineImportRulesTest.java @@ -0,0 +1,322 @@ +package com.example.AviaryService.util; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.time.LocalDate; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Test; + +import com.example.AviaryService.util.TimelineImportRules.ImportFlag; +import com.example.AviaryService.util.TimelineImportRules.InputItem; +import com.example.AviaryService.util.TimelineImportRules.ItemResult; +import com.example.AviaryService.util.TimelineImportRules.ProposedItem; +import com.example.AviaryService.util.TimelineImportRules.SubmissionOutcome; + +class TimelineImportRulesTest { + + private static final LocalDate TODAY = LocalDate.of(2026, 10, 20); + + // Builder-ish helper: item name + key/value pairs. + private static InputItem item(String name, String... kv) { + String lastDoneDate = null, lastDoneHours = null, calValue = null, calUnit = null, cycleHours = null; + String dueDate = null, dueHours = null, description = null, source = null; + Boolean title = null, ambiguous = null, onCondition = null; + for (int i = 0; i < kv.length; i += 2) { + String v = kv[i + 1]; + switch (kv[i]) { + case "lastDoneDate" -> lastDoneDate = v; + case "lastDoneHours" -> lastDoneHours = v; + case "calValue" -> calValue = v; + case "calUnit" -> calUnit = v; + case "cycleHours" -> cycleHours = v; + case "dueDate" -> dueDate = v; + case "dueHours" -> dueHours = v; + case "description" -> description = v; + case "source" -> source = v; + case "title" -> title = Boolean.valueOf(v); + case "ambiguous" -> ambiguous = Boolean.valueOf(v); + case "onCondition" -> onCondition = Boolean.valueOf(v); + default -> throw new IllegalArgumentException(kv[i]); + } + } + return new InputItem(name, description, title, lastDoneDate, lastDoneHours, calValue, calUnit, cycleHours, + dueDate, dueHours, ambiguous, source, onCondition); + } + + private static ItemResult eval(InputItem... items) { + return TimelineImportRules.evaluate(List.of(items), Set.of(), TODAY); + } + + private static ProposedItem only(ItemResult r) { + assertEquals(List.of(), r.rejected(), "unexpected rejects"); + assertEquals(1, r.items().size()); + return r.items().get(0); + } + + private static String onlyReject(ItemResult r) { + assertEquals(0, r.items().size(), "expected a reject"); + assertEquals(1, r.rejected().size()); + return r.rejected().get(0).reason(); + } + + @Test + void nameIsRequired() { + assertTrue(onlyReject(eval(item(" ", "lastDoneDate", "2026-01-01"))).contains("No item name")); + } + + @Test + void longNameIsCutNotRejected() { + ProposedItem p = only(eval(item("x".repeat(300), "lastDoneDate", "2026-01-01"))); + assertEquals(255, p.item().length()); + assertTrue(p.notes().get(0).contains("255")); + } + + // Owners' records come in every shape: an item with only a name is still an item. + @Test + void itemWithOnlyANameIsImportedAndFlagged() { + ProposedItem p = only(eval(item("Brake pads", "description", "Replace when worn"))); + assertTrue(p.flags().contains(ImportFlag.NO_SCHEDULE)); + assertEquals("Replace when worn", p.description()); + assertTrue(p.notes().get(0).contains("N/A")); + } + + @Test + void onConditionItemIsNotAlsoNoSchedule() { + ProposedItem p = only(eval(item("Hose", "onCondition", "true"))); + assertFalse(p.flags().contains(ImportFlag.NO_SCHEDULE)); + } + + @Test + void onConditionItemNeedsNoDates() { + ProposedItem p = only(eval(item("Flexible Fluid Hose", "description", "Replace", "onCondition", "true"))); + assertTrue(p.flags().contains(ImportFlag.ON_CONDITION)); + assertNull(p.lastDoneDate()); + assertNull(p.dueDateDate()); + } + + @Test + void onConditionItemKeepsDatesItHas() { + ProposedItem p = only(eval(item("Battery - Main", "lastDoneDate", "2024-01-05", "onCondition", "true"))); + assertEquals("2024-01-05", p.lastDoneDate()); + assertTrue(p.flags().contains(ImportFlag.ON_CONDITION)); + } + + @Test + void onConditionCountsAsARealItem() { + ItemResult r = eval(item("Hose", "onCondition", "true")); + assertEquals(SubmissionOutcome.PROPOSED, TimelineImportRules.classify(1, 1, 0, r)); + } + + @Test + void titleRowOnlyNeedsName() { + ProposedItem p = only(eval(item("Engine", "title", "true"))); + assertTrue(p.isTitle()); + assertNull(p.lastDoneDate()); + } + + @Test + void badDateIsLeftBlankWithNote() { + ProposedItem p = only(eval(item("Annual", "lastDoneDate", "3/14/2026", "calValue", "12", "calUnit", "MONTHS"))); + assertNull(p.lastDoneDate()); + assertEquals(12, p.cycleCalendarValue()); + assertTrue(p.flags().contains(ImportFlag.VALUE_DROPPED)); + assertTrue(p.notes().get(0).contains("YYYY-MM-DD")); + assertTrue(only(eval(item("Annual", "lastDoneDate", "2026-02-30"))).notes().get(0).contains("not a real date")); + } + + @Test + void ambiguousDateIsFlagged() { + ProposedItem p = only(eval(item("Annual", "lastDoneDate", "2025-03-04", "ambiguous", "true"))); + assertTrue(p.flags().contains(ImportFlag.AMBIGUOUS_DATE)); + } + + @Test + void futureLastDoneIsFlagged() { + ProposedItem p = only(eval(item("Annual", "lastDoneDate", "2027-01-01"))); + assertTrue(p.flags().contains(ImportFlag.FUTURE_DATE)); + assertFalse(only(eval(item("Annual", "lastDoneDate", "2026-10-20"))).flags().contains(ImportFlag.FUTURE_DATE)); + } + + @Test + void badHoursAreLeftBlankWithNote() { + ProposedItem neg = only(eval(item("Oil", "lastDoneHours", "-5", "cycleHours", "50"))); + assertNull(neg.lastDoneHours()); + assertEquals(50.0, neg.cycleHours()); + assertTrue(neg.notes().get(0).contains("negative")); + assertTrue(only(eval(item("Oil", "lastDoneHours", "abc"))).notes().get(0).contains("not a number")); + ProposedItem zero = only(eval(item("Oil", "cycleHours", "0"))); + assertNull(zero.cycleHours()); + assertTrue(zero.notes().get(0).contains("above 0")); + } + + @Test + void thousandsSeparatorInHoursIsAccepted() { + assertEquals(1234.5, only(eval(item("Oil", "lastDoneHours", "1,234.5"))).lastDoneHours()); + } + + @Test + void unsupportedUnitIsDroppedAndFlagged() { + ProposedItem p = only(eval(item("Gear", "lastDoneDate", "2026-01-01", "calValue", "50", "calUnit", "LANDINGS"))); + assertTrue(p.flags().contains(ImportFlag.UNSUPPORTED_CYCLE)); + assertNull(p.cycleCalendarValue()); + assertNull(p.cycleCalendarUnit()); + } + + @Test + void unsupportedUnitIsKeptInDescription() { + ProposedItem p = only(eval(item("Gear", "description", "Inspect", "calValue", "50", "calUnit", "landings"))); + assertEquals("Inspect (interval: 50 landings)", p.description()); + assertTrue(p.flags().contains(ImportFlag.UNSUPPORTED_CYCLE)); + assertTrue(p.flags().contains(ImportFlag.NO_SCHEDULE)); + } + + @Test + void calendarValueOutOfRangeIsLeftBlankWithNote() { + for (String bad : new String[] { "0", "1201", "1.5" }) { + ProposedItem p = only(eval(item("A", "calValue", bad, "calUnit", "MONTHS"))); + assertNull(p.cycleCalendarValue(), bad); + assertTrue(p.notes().get(0).contains("1 to 1200"), bad); + } + assertEquals(1200, only(eval(item("A", "calValue", "1200", "calUnit", "days"))).cycleCalendarValue()); + } + + @Test + void singularUnitIsAccepted() { + assertEquals("YEARS", only(eval(item("A", "calValue", "1", "calUnit", "year"))).cycleCalendarUnit()); + } + + @Test + void cycleInferredFromLastDoneAndDue() { + ProposedItem yearly = only(eval(item("Annual", "lastDoneDate", "2026-03-14", "dueDate", "2027-03-14"))); + assertEquals(1, yearly.cycleCalendarValue()); + assertEquals("YEARS", yearly.cycleCalendarUnit()); + assertTrue(yearly.flags().contains(ImportFlag.CYCLE_INFERRED)); + + ProposedItem monthly = only(eval(item("ELT", "lastDoneDate", "2026-01-10", "dueDate", "2026-07-10"))); + assertEquals(6, monthly.cycleCalendarValue()); + assertEquals("MONTHS", monthly.cycleCalendarUnit()); + + ProposedItem daily = only(eval(item("Check", "lastDoneDate", "2026-01-10", "dueDate", "2026-02-19"))); + assertEquals(40, daily.cycleCalendarValue()); + assertEquals("DAYS", daily.cycleCalendarUnit()); + + ProposedItem hours = only(eval(item("Oil", "lastDoneHours", "1200", "dueHours", "1250"))); + assertEquals(50.0, hours.cycleHours()); + assertTrue(hours.flags().contains(ImportFlag.CYCLE_INFERRED)); + } + + @Test + void dueDateComputedForEachUnit() { + assertEquals("2026-04-10", only(eval(item("A", "lastDoneDate", "2026-01-10", "calValue", "90", "calUnit", "DAYS"))).dueDateDate()); + assertEquals("2026-04-10", only(eval(item("A", "lastDoneDate", "2026-01-10", "calValue", "3", "calUnit", "MONTHS"))).dueDateDate()); + assertEquals("2028-01-10", only(eval(item("A", "lastDoneDate", "2026-01-10", "calValue", "2", "calUnit", "YEARS"))).dueDateDate()); + } + + @Test + void dueDateClampsAtMonthEndAndLeapDay() { + assertEquals("2026-02-28", only(eval(item("A", "lastDoneDate", "2026-01-31", "calValue", "1", "calUnit", "MONTHS"))).dueDateDate()); + assertEquals("2028-02-29", only(eval(item("A", "lastDoneDate", "2028-01-31", "calValue", "1", "calUnit", "MONTHS"))).dueDateDate()); + assertEquals("2025-02-28", only(eval(item("A", "lastDoneDate", "2024-02-29", "calValue", "1", "calUnit", "YEARS"))).dueDateDate()); + } + + @Test + void dueHoursAreLastDonePlusCycle() { + ProposedItem p = only(eval(item("Oil", "lastDoneHours", "1234.5", "cycleHours", "50"))); + assertEquals(1284.5, p.dueDateHours()); + } + + @Test + void givenDueKeptWhenItCannotBeComputed() { + ProposedItem p = only(eval(item("ELT battery", "dueDate", "2027-06-01"))); + assertEquals("2027-06-01", p.dueDateDate()); + assertNull(p.cycleCalendarUnit()); + } + + @Test + void duplicateOfExistingIsFlagged() { + ItemResult r = TimelineImportRules.evaluate( + List.of(item("annual INSPECTION", "lastDoneDate", "2026-01-01")), + Set.of(TimelineImportRules.normalizeName("Annual Inspection")), TODAY); + assertTrue(only(r).flags().contains(ImportFlag.DUPLICATE_EXISTING)); + } + + @Test + void exactRepeatInInputIsMerged() { + ItemResult r = eval(item("Oil", "lastDoneHours", "100", "cycleHours", "50"), + item("oil", "lastDoneHours", "100", "cycleHours", "50")); + ProposedItem p = only(r); + assertTrue(p.flags().contains(ImportFlag.DUPLICATE_IN_INPUT)); + } + + @Test + void sameNameDifferentDetailsKeepsBoth() { + ItemResult r = eval(item("Oil", "lastDoneHours", "100", "cycleHours", "50"), + item("Oil", "lastDoneHours", "300", "cycleHours", "50")); + assertEquals(2, r.items().size()); + assertTrue(r.items().get(0).flags().contains(ImportFlag.DUPLICATE_IN_INPUT)); + assertTrue(r.items().get(1).flags().contains(ImportFlag.DUPLICATE_IN_INPUT)); + } + + @Test + void indexesAreOneBasedInOrderAndSourceKept() { + ItemResult r = eval(item("Engine", "title", "true"), + item("Oil", "lastDoneHours", "100", "source", "Oil chg 100"), + item("", "source", "garbage row"), + item("Annual", "lastDoneDate", "2026-01-01")); + assertEquals(List.of(1, 2, 3), r.items().stream().map(ProposedItem::index).toList()); + assertEquals("Oil chg 100", r.items().get(1).sourceRow()); + assertEquals("garbage row", r.rejected().get(0).sourceRow()); + } + + @Test + void longSourceRowIsTruncated() { + ProposedItem p = only(eval(item("Oil", "lastDoneHours", "1", "source", "y".repeat(800)))); + assertEquals(TimelineImportRules.MAX_SOURCE_ROW, p.sourceRow().length()); + } + // ---- whole-submission verdict ---- + + private static SubmissionOutcome classify(InputItem... items) { + ItemResult r = eval(items); + return TimelineImportRules.classify(items.length, items.length, r.rejected().size(), r); + } + + private static InputItem junk() { + return item("", "source", "not maintenance"); + } + + private static InputItem good(String name) { + return item(name, "lastDoneHours", "10", "cycleHours", "50"); + } + + @Test + void nothingMappedIsRejected() { + assertEquals(SubmissionOutcome.REJECTED, classify(junk(), junk())); + assertEquals(SubmissionOutcome.REJECTED, TimelineImportRules.classify(0, 0, 0, eval())); + } + + @Test + void onlyTitleRowsIsRejected() { + assertEquals(SubmissionOutcome.REJECTED, classify(item("Engine", "title", "true"), junk())); + } + + @Test + void moreThanHalfRejectedIsPoorFit() { + assertEquals(SubmissionOutcome.POOR_FIT, classify(good("A"), junk(), junk())); + } + + @Test + void exactlyHalfRejectedIsStillProposed() { + assertEquals(SubmissionOutcome.PROPOSED, classify(good("A"), junk())); + } + + @Test + void over200IsTooLarge() { + assertEquals(SubmissionOutcome.TOO_LARGE, TimelineImportRules.classify(201, 201, 0, eval(good("A")))); + assertEquals(SubmissionOutcome.PROPOSED, TimelineImportRules.classify(200, 200, 0, eval(good("A")))); + } +} diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties index d431d81..7e67c0e 100644 --- a/src/test/resources/application.properties +++ b/src/test/resources/application.properties @@ -16,3 +16,12 @@ aviary.remember-me.key=test-key-not-a-secret # key (that lives in .env, gitignored) โ€” generated fresh, only ever encrypts # throwaway values in the in-memory H2 test context. aviary.aero-api-key.secret=R9dZLqm/C2AZP/BSNoKen2zLd59P86OoWn5Xtvb7SVQ= + +# OAuth issuer for MCP sign-in; same value the main config defaults to. +aviary.oauth.issuer=http://localhost:8080 + +# Same MCP transport as the app (this file replaces the main application.properties in tests). +spring.ai.mcp.server.name=aviary +spring.ai.mcp.server.version=0.0.1 +spring.ai.mcp.server.type=SYNC +spring.ai.mcp.server.protocol=STREAMABLE