From 3a33e1b1fe1d19a73dc5fe8d3d292977791f8b46 Mon Sep 17 00:00:00 2001 From: dannysusername Date: Mon, 9 Nov 2026 18:06:45 -0500 Subject: [PATCH 1/2] Add public stats endpoint for DanielIbarra.com GET /api/public/stats returns live, anonymous Aviary totals for the portfolio's Aviary panel: users, aircraft, flights, hours flown (time in service), alerts sent, signups in the last 7/30 days, and up to 10 date-only "New pilot joined" lines. Nothing about any one account. - Public, read-only filter chain for /api/public/**: no login, no session, GET only. CORS only for aviary.public-stats.allowed-origins (env AVIARY_PUBLIC_STATS_ORIGINS, defaults to danielibarra.com). - Rate limited to 60 calls per IP per 10 minutes (429 + Retry-After). - Numbers are cached for 15 minutes and recomputed only on request, one thread at a time, so traffic never turns into per-visitor queries and nothing wakes Neon on a timer. A failed refresh keeps serving the last snapshot; 503 only if none exists yet. - users.created_at (nullable, set by @PrePersist) records signup dates from now on. Existing accounts stay NULL: no guessed dates. Additive; migration note in docs/migrations. - All accounts are counted for now, test accounts included. - Tests: service caching and shaping, real queries on H2, and endpoint checks (public, no session, CORS allow/deny, POST refused, 429, and no username or tail number in the body). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01M4dsGvpqnWiNuLHPLuGXx4 --- README.md | 18 +++ .../2026-11-09_users_created_at.sql | 12 ++ .../AviaryServiceApplication.java | 4 + .../AviaryService/config/SecurityConfig.java | 40 ++++- .../controllers/PublicStatsController.java | 66 +++++++++ .../example/AviaryService/entity/User.java | 19 +++ .../repositories/FlightLogRepository.java | 9 ++ .../repositories/UserRepository.java | 17 ++- .../services/stats/PublicStatsProperties.java | 21 +++ .../services/stats/PublicStatsService.java | 134 +++++++++++++++++ .../services/stats/PublicStatsSnapshot.java | 28 ++++ .../PublicStatsUnavailableException.java | 9 ++ src/main/resources/application.properties | 8 + .../PublicStatsControllerTest.java | 109 ++++++++++++++ .../stats/PublicStatsQueriesTest.java | 94 ++++++++++++ .../stats/PublicStatsServiceTest.java | 138 ++++++++++++++++++ 16 files changed, 723 insertions(+), 3 deletions(-) create mode 100644 docs/migrations/2026-11-09_users_created_at.sql create mode 100644 src/main/java/com/example/AviaryService/controllers/PublicStatsController.java create mode 100644 src/main/java/com/example/AviaryService/services/stats/PublicStatsProperties.java create mode 100644 src/main/java/com/example/AviaryService/services/stats/PublicStatsService.java create mode 100644 src/main/java/com/example/AviaryService/services/stats/PublicStatsSnapshot.java create mode 100644 src/main/java/com/example/AviaryService/services/stats/PublicStatsUnavailableException.java create mode 100644 src/test/java/com/example/AviaryService/controllers/PublicStatsControllerTest.java create mode 100644 src/test/java/com/example/AviaryService/services/stats/PublicStatsQueriesTest.java create mode 100644 src/test/java/com/example/AviaryService/services/stats/PublicStatsServiceTest.java diff --git a/README.md b/README.md index 9f9779e..8017766 100644 --- a/README.md +++ b/README.md @@ -141,6 +141,24 @@ push to main **Try it locally:** run `./gradlew bootRun`, then add `http://localhost:8080/mcp` as a remote MCP server in an MCP client (or use the [MCP Inspector](https://github.com/modelcontextprotocol/inspector)) and sign in with a seeded account. +## Public stats endpoint + +`GET /api/public/stats` feeds the live Aviary panel on [danielibarra.com](https://danielibarra.com). It's public (no login) and read-only, and it returns only totals plus up to 10 anonymous, date-only signup lines. It never returns anything about one account. + +```json +{"users":11,"aircraft":12,"flights":25,"hoursFlown":0.0,"alertsSent":1, + "signupsLast7Days":0,"signupsLast30Days":0, + "recentSignups":[{"label":"New pilot joined","date":"2026-11-12"}], + "generatedAt":"2026-11-12T18:30:00Z"} +``` + +- **Cached:** counts are computed at most once every 15 minutes, and only when someone asks, so the endpoint never wakes the database on a timer. Responses carry `Cache-Control: public, max-age=300`. +- **Rate limited:** 60 calls per IP per 10 minutes, then `429`. +- **CORS:** only sites in `aviary.public-stats.allowed-origins` (env `AVIARY_PUBLIC_STATS_ORIGINS`, default `https://danielibarra.com,https://www.danielibarra.com`) can read it from a browser. Add `http://localhost:5050` to preview the portfolio locally. +- **Counts:** every account is counted, test accounts included for now. Signup dates (`users.created_at`) start with accounts created after this shipped; older accounts count as users but never appear in the feed. + +Design and contract: [specs/004-public-aviary-stats/](specs/004-public-aviary-stats/). + ## Architecture The app is a small, conventional Spring MVC project under `src/main/java/com/example/AviaryService/`: diff --git a/docs/migrations/2026-11-09_users_created_at.sql b/docs/migrations/2026-11-09_users_created_at.sql new file mode 100644 index 0000000..b7c69bc --- /dev/null +++ b/docs/migrations/2026-11-09_users_created_at.sql @@ -0,0 +1,12 @@ +-- Signup date on accounts (specs/004-public-aviary-stats). +-- +-- Additive: Hibernate ddl-auto=update adds this nullable column on boot from +-- entity/User.java (createdAt, set by @PrePersist). This file is the explicit +-- record and covers any DB where ddl-auto is off. PostgreSQL syntax. +-- +-- Existing rows stay NULL on purpose. Their real signup date isn't known, and +-- the only other dates (aircraft.created_at) were set by AircraftBackfill on +-- 2026-11-09, so copying them would make every old account look new. +-- See specs/004-public-aviary-stats/research.md R3. + +ALTER TABLE users ADD COLUMN IF NOT EXISTS created_at TIMESTAMP WITH TIME ZONE; diff --git a/src/main/java/com/example/AviaryService/AviaryServiceApplication.java b/src/main/java/com/example/AviaryService/AviaryServiceApplication.java index 8b7b4e5..dc45fae 100644 --- a/src/main/java/com/example/AviaryService/AviaryServiceApplication.java +++ b/src/main/java/com/example/AviaryService/AviaryServiceApplication.java @@ -2,10 +2,14 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.scheduling.annotation.EnableScheduling; +import com.example.AviaryService.services.stats.PublicStatsProperties; + @SpringBootApplication @EnableScheduling +@EnableConfigurationProperties(PublicStatsProperties.class) public class AviaryServiceApplication { public static void main(String[] args) { diff --git a/src/main/java/com/example/AviaryService/config/SecurityConfig.java b/src/main/java/com/example/AviaryService/config/SecurityConfig.java index 3ac7da3..586a53f 100644 --- a/src/main/java/com/example/AviaryService/config/SecurityConfig.java +++ b/src/main/java/com/example/AviaryService/config/SecurityConfig.java @@ -19,7 +19,14 @@ import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector; +import java.util.List; + +import org.springframework.http.HttpMethod; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; + import com.example.AviaryService.entity.User; +import com.example.AviaryService.services.stats.PublicStatsProperties; import com.example.AviaryService.repositories.UserRepository; import com.example.AviaryService.services.account.LoginAttemptService; @@ -87,8 +94,39 @@ public SecurityFilterChain mcpFilterChain(HttpSecurity http, OpaqueTokenIntrospe return http.build(); } + // /api/public/** is read by DanielIbarra.com's page from visitors' browsers + // (see PublicStatsController). No login, no session, no CSRF (GET only, no + // cookies). Every other method is refused. CORS lets only the sites in + // aviary.public-stats.allowed-origins read the answer from a browser. @Bean @Order(2) + public SecurityFilterChain publicApiFilterChain(HttpSecurity http, PublicStatsProperties statsProps) throws Exception { + CorsConfiguration cors = new CorsConfiguration(); + cors.setAllowedOrigins(statsProps.allowedOrigins()); + cors.setAllowedMethods(List.of("GET")); + cors.setAllowCredentials(false); + cors.setMaxAge(3600L); + UrlBasedCorsConfigurationSource corsSource = new UrlBasedCorsConfigurationSource(); + corsSource.registerCorsConfiguration("/api/public/**", cors); + + http + .securityMatcher("/api/public/**") + .authorizeHttpRequests(auth -> auth + .requestMatchers(HttpMethod.GET, "/api/public/**").permitAll() + .requestMatchers(HttpMethod.OPTIONS, "/api/public/**").permitAll() + .anyRequest().denyAll()) + .cors(c -> c.configurationSource(corsSource)) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .requestCache(cache -> cache.disable()) + .securityContext(ctx -> ctx.disable()) + .csrf(csrf -> csrf.disable()) + .exceptionHandling(ex -> ex.accessDeniedHandler((request, response, e) -> response.setStatus(403)) + .authenticationEntryPoint((request, response, e) -> response.setStatus(403))); + return http.build(); + } + + @Bean + @Order(3) public SecurityFilterChain staticResourcesFilterChain(HttpSecurity http) throws Exception { http .securityMatcher("/css/**", "/js/**", "/images/**") @@ -99,7 +137,7 @@ public SecurityFilterChain staticResourcesFilterChain(HttpSecurity http) throws } @Bean - @Order(3) + @Order(4) public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { System.out.println("SecurityConfig loaded"); http diff --git a/src/main/java/com/example/AviaryService/controllers/PublicStatsController.java b/src/main/java/com/example/AviaryService/controllers/PublicStatsController.java new file mode 100644 index 0000000..551603c --- /dev/null +++ b/src/main/java/com/example/AviaryService/controllers/PublicStatsController.java @@ -0,0 +1,66 @@ +package com.example.AviaryService.controllers; + +import java.time.Duration; +import java.util.Map; + +import org.springframework.http.CacheControl; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.example.AviaryService.services.stats.PublicStatsService; +import com.example.AviaryService.services.stats.PublicStatsUnavailableException; +import com.example.AviaryService.util.SlidingWindowLimiter; + +import jakarta.servlet.http.HttpServletRequest; + +// The live numbers on DanielIbarra.com's Aviary panel come from here. +// +// A small script on the portfolio page calls GET /api/public/stats from the +// visitor's browser. It's public (no login) and read-only: it returns only +// totals and anonymous signup dates, never anything about one account. +// SecurityConfig's publicApiFilterChain lets it through without a session and +// allows only DanielIbarra.com to read it from a browser (CORS). +// +// Public endpoints must be rate limited (constitution V): 60 calls per IP per +// 10 minutes. The numbers themselves are cached in PublicStatsService, so even +// heavy traffic doesn't reach the database more than once per 15 minutes. +// Contract: specs/004-public-aviary-stats/contracts/public-stats-api.md +@RestController +@RequestMapping("/api/public") +public class PublicStatsController { + + static final int MAX_PER_WINDOW = 60; + static final Duration WINDOW = Duration.ofMinutes(10); + + private final PublicStatsService statsService; + private final SlidingWindowLimiter limiter = new SlidingWindowLimiter(MAX_PER_WINDOW, WINDOW); + + public PublicStatsController(PublicStatsService statsService) { + this.statsService = statsService; + } + + @GetMapping("/stats") + public ResponseEntity stats(HttpServletRequest request) { + // Behind Heroku's router this is the real client IP + // (server.forward-headers-strategy=native in application-heroku.properties). + if (!limiter.tryAcquire(request.getRemoteAddr())) { + return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS) + .header(HttpHeaders.RETRY_AFTER, String.valueOf(WINDOW.toSeconds())) + .body(Map.of("error", "rate_limited")); + } + return ResponseEntity.ok() + .cacheControl(CacheControl.maxAge(Duration.ofMinutes(5)).cachePublic()) + .body(statsService.current()); + } + + // No numbers computed yet and the database can't be reached. + @ExceptionHandler(PublicStatsUnavailableException.class) + public ResponseEntity> unavailable() { + return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body(Map.of("error", "unavailable")); + } +} diff --git a/src/main/java/com/example/AviaryService/entity/User.java b/src/main/java/com/example/AviaryService/entity/User.java index a220010..d6f067d 100644 --- a/src/main/java/com/example/AviaryService/entity/User.java +++ b/src/main/java/com/example/AviaryService/entity/User.java @@ -1,6 +1,7 @@ package com.example.AviaryService.entity; import jakarta.persistence.*; +import java.time.Instant; import java.util.ArrayList; import java.util.List; @@ -49,6 +50,20 @@ public class User { @Column private String aeroApiKey; + // When the account was created. Set once on first save, never changed. + // Null for accounts made before this was recorded (2026-11): those aren't + // given guessed dates. Feeds the public signup feed (specs/004-public-aviary-stats). + @Column(name = "created_at", updatable = false) + @JsonIgnore + private Instant createdAt; + + @PrePersist + void onCreate() { + if (createdAt == null) { + createdAt = Instant.now(); + } + } + public User(){ } @@ -105,6 +120,10 @@ public void setFlightLogs(List flightLogs) { public Aircraft getLastViewedAircraft() { return lastViewedAircraft; } public void setLastViewedAircraft(Aircraft lastViewedAircraft) { this.lastViewedAircraft = lastViewedAircraft; } + public Instant getCreatedAt() { return createdAt; } + // Tests only: lets a test place a signup at a known moment. + public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } + public String getAeroApiKey() { return aeroApiKey; } diff --git a/src/main/java/com/example/AviaryService/repositories/FlightLogRepository.java b/src/main/java/com/example/AviaryService/repositories/FlightLogRepository.java index 45c0b0b..cf893de 100644 --- a/src/main/java/com/example/AviaryService/repositories/FlightLogRepository.java +++ b/src/main/java/com/example/AviaryService/repositories/FlightLogRepository.java @@ -4,6 +4,7 @@ import com.example.AviaryService.entity.FlightLog; import com.example.AviaryService.entity.User; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; import java.util.List; import java.util.Optional; @@ -15,4 +16,12 @@ public interface FlightLogRepository extends JpaRepository { // Every flight the account owns, across aircraft. List findByUser(User user); + + // Public stats: total time-in-service hours across all flights. Rows with a + // missing reading, or in <= out, are skipped so one bad row can't lower the + // total. Null when no row qualifies. + @Query("select sum(f.timeInServiceIn - f.timeInServiceOut) from FlightLog f " + + "where f.timeInServiceIn is not null and f.timeInServiceOut is not null " + + "and f.timeInServiceIn > f.timeInServiceOut") + Double sumHoursFlown(); } diff --git a/src/main/java/com/example/AviaryService/repositories/UserRepository.java b/src/main/java/com/example/AviaryService/repositories/UserRepository.java index 86f2442..d49588b 100644 --- a/src/main/java/com/example/AviaryService/repositories/UserRepository.java +++ b/src/main/java/com/example/AviaryService/repositories/UserRepository.java @@ -1,10 +1,23 @@ package com.example.AviaryService.repositories; +import java.time.Instant; +import java.util.List; + +import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; import com.example.AviaryService.entity.User; -public interface UserRepository extends JpaRepository{ +public interface UserRepository extends JpaRepository{ User findByUsername(String username); - + + // Public stats (services/stats/PublicStatsService): accounts created after + // a moment. Accounts with no createdAt (made before it was recorded) never match. + long countByCreatedAtAfter(Instant since); + + // Public stats: the newest signup times, newest first. Returns timestamps + // only -- never User rows -- so no account details reach the stats code. + @Query("select u.createdAt from User u where u.createdAt is not null order by u.createdAt desc") + List findRecentSignupTimes(Pageable page); } diff --git a/src/main/java/com/example/AviaryService/services/stats/PublicStatsProperties.java b/src/main/java/com/example/AviaryService/services/stats/PublicStatsProperties.java new file mode 100644 index 0000000..fb5304a --- /dev/null +++ b/src/main/java/com/example/AviaryService/services/stats/PublicStatsProperties.java @@ -0,0 +1,21 @@ +package com.example.AviaryService.services.stats; + +import java.time.Duration; +import java.time.ZoneId; +import java.util.List; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.bind.DefaultValue; + +// Settings for the public stats endpoint (aviary.public-stats.* in +// application.properties). The defaults here match that file, so the app and +// the tests (whose application.properties replaces the main one) behave the same. +@ConfigurationProperties(prefix = "aviary.public-stats") +public record PublicStatsProperties( + // Sites whose pages may read the stats from a browser (CORS). + @DefaultValue({"https://danielibarra.com", "https://www.danielibarra.com"}) List allowedOrigins, + // Signup dates are shown as a calendar date in this zone. + @DefaultValue("America/New_York") ZoneId zone, + // How long one snapshot is served before it's recomputed. + @DefaultValue("PT15M") Duration ttl) { +} diff --git a/src/main/java/com/example/AviaryService/services/stats/PublicStatsService.java b/src/main/java/com/example/AviaryService/services/stats/PublicStatsService.java new file mode 100644 index 0000000..2fd617d --- /dev/null +++ b/src/main/java/com/example/AviaryService/services/stats/PublicStatsService.java @@ -0,0 +1,134 @@ +package com.example.AviaryService.services.stats; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.concurrent.locks.ReentrantLock; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; + +import com.example.AviaryService.repositories.AircraftRepository; +import com.example.AviaryService.repositories.AlertSendLogRepository; +import com.example.AviaryService.repositories.FlightLogRepository; +import com.example.AviaryService.repositories.UserRepository; +import com.example.AviaryService.services.stats.PublicStatsSnapshot.SignupEntry; + +// Builds the public numbers shown on DanielIbarra.com and keeps them in memory. +// +// Counting on every page view would let a busy (or scraped) portfolio page put +// load on Aviary's database. So one snapshot is kept and served until it's +// older than the TTL (15 minutes by default). The next request after that +// recomputes it -- one thread at a time; everyone else keeps getting the old +// one. There's no timer: if nobody looks, nothing runs, so the stats never +// wake the Neon database on their own. See specs/004-public-aviary-stats/research.md R2. +// +// Every account is counted for now, test accounts included (spec FR-009). +// If they're left out later, this is the one place to change. +@Service +public class PublicStatsService { + + private static final Logger log = LoggerFactory.getLogger(PublicStatsService.class); + + static final String SIGNUP_LABEL = "New pilot joined"; + static final int MAX_RECENT_SIGNUPS = 10; + + private final UserRepository userRepository; + private final AircraftRepository aircraftRepository; + private final FlightLogRepository flightLogRepository; + private final AlertSendLogRepository alertSendLogRepository; + private final PublicStatsProperties props; + private final Clock clock; + + private final ReentrantLock refreshLock = new ReentrantLock(); + private volatile PublicStatsSnapshot cached; + + @Autowired + public PublicStatsService(UserRepository userRepository, AircraftRepository aircraftRepository, + FlightLogRepository flightLogRepository, AlertSendLogRepository alertSendLogRepository, + PublicStatsProperties props) { + this(userRepository, aircraftRepository, flightLogRepository, alertSendLogRepository, props, Clock.systemUTC()); + } + + PublicStatsService(UserRepository userRepository, AircraftRepository aircraftRepository, + FlightLogRepository flightLogRepository, AlertSendLogRepository alertSendLogRepository, + PublicStatsProperties props, Clock clock) { + this.userRepository = userRepository; + this.aircraftRepository = aircraftRepository; + this.flightLogRepository = flightLogRepository; + this.alertSendLogRepository = alertSendLogRepository; + this.props = props; + this.clock = clock; + } + + // The current public numbers. Fresh snapshot -> returned as is, no queries. + public PublicStatsSnapshot current() { + PublicStatsSnapshot snap = cached; + if (snap != null && !isStale(snap)) { + return snap; + } + if (snap != null) { + // Stale: one thread refreshes, the rest serve the old numbers now. + if (!refreshLock.tryLock()) { + return snap; + } + } else { + // Nothing to serve yet: wait for whoever is computing the first one. + refreshLock.lock(); + } + try { + PublicStatsSnapshot latest = cached; + if (latest != null && !isStale(latest)) { + return latest; // another thread refreshed while we waited + } + try { + cached = compute(); + return cached; + } catch (RuntimeException e) { + if (latest != null) { + log.warn("Public stats refresh failed; serving snapshot from {}", latest.generatedAt(), e); + return latest; + } + throw new PublicStatsUnavailableException(e); + } + } finally { + refreshLock.unlock(); + } + } + + private boolean isStale(PublicStatsSnapshot snap) { + return Duration.between(snap.generatedAt(), clock.instant()).compareTo(props.ttl()) >= 0; + } + + private PublicStatsSnapshot compute() { + Instant now = clock.instant(); + + // Hours flown = time in service. Block time is empty on production + // flights, so it would always show 0 (research R6). + Double hours = flightLogRepository.sumHoursFlown(); + double hoursFlown = hours == null ? 0.0 : Math.round(hours * 10.0) / 10.0; + + // Accounts made before signup dates were recorded have no createdAt; + // they count above but never show up here (no guessed dates, R3). + List recent = userRepository + .findRecentSignupTimes(PageRequest.of(0, MAX_RECENT_SIGNUPS)) + .stream() + .map(ts -> new SignupEntry(SIGNUP_LABEL, ts.atZone(props.zone()).toLocalDate().toString())) + .toList(); + + return new PublicStatsSnapshot( + userRepository.count(), + aircraftRepository.count(), + flightLogRepository.count(), + hoursFlown, + alertSendLogRepository.count(), + userRepository.countByCreatedAtAfter(now.minus(Duration.ofDays(7))), + userRepository.countByCreatedAtAfter(now.minus(Duration.ofDays(30))), + recent, + now); + } +} diff --git a/src/main/java/com/example/AviaryService/services/stats/PublicStatsSnapshot.java b/src/main/java/com/example/AviaryService/services/stats/PublicStatsSnapshot.java new file mode 100644 index 0000000..b151071 --- /dev/null +++ b/src/main/java/com/example/AviaryService/services/stats/PublicStatsSnapshot.java @@ -0,0 +1,28 @@ +package com.example.AviaryService.services.stats; + +import java.time.Instant; +import java.util.List; + +// The public numbers about Aviary at one moment, as sent to DanielIbarra.com. +// Only totals and anonymous, date-only signup lines. Nothing in here may point +// back at one account: no IDs, usernames, emails, tail numbers or per-user +// numbers (spec FR-008). Adding a field is a contract change -- see +// specs/004-public-aviary-stats/contracts/public-stats-api.md. +public record PublicStatsSnapshot( + long users, + long aircraft, + long flights, + double hoursFlown, + long alertsSent, + long signupsLast7Days, + long signupsLast30Days, + List recentSignups, + Instant generatedAt) { + + public PublicStatsSnapshot { + recentSignups = recentSignups == null ? List.of() : List.copyOf(recentSignups); + } + + // One line in the "recent signups" feed: a fixed label and a YYYY-MM-DD date. + public record SignupEntry(String label, String date) {} +} diff --git a/src/main/java/com/example/AviaryService/services/stats/PublicStatsUnavailableException.java b/src/main/java/com/example/AviaryService/services/stats/PublicStatsUnavailableException.java new file mode 100644 index 0000000..cb838f4 --- /dev/null +++ b/src/main/java/com/example/AviaryService/services/stats/PublicStatsUnavailableException.java @@ -0,0 +1,9 @@ +package com.example.AviaryService.services.stats; + +// No stats have been computed yet and computing them just failed (e.g. the +// database is down). PublicStatsController turns this into a 503. +public class PublicStatsUnavailableException extends RuntimeException { + public PublicStatsUnavailableException(Throwable cause) { + super("Public stats are unavailable", cause); + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index ddff785..f8568d2 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -45,3 +45,11 @@ 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} + +# Public stats for DanielIbarra.com (specs/004-public-aviary-stats/). +# Sites allowed to read GET /api/public/stats from a browser (CORS). Comma-separated. +aviary.public-stats.allowed-origins=${AVIARY_PUBLIC_STATS_ORIGINS:https://danielibarra.com,https://www.danielibarra.com} +# Time zone used for signup dates (date only, no time of day). +aviary.public-stats.zone=America/New_York +# How long one computed snapshot is served before it's recomputed. +aviary.public-stats.ttl=PT15M diff --git a/src/test/java/com/example/AviaryService/controllers/PublicStatsControllerTest.java b/src/test/java/com/example/AviaryService/controllers/PublicStatsControllerTest.java new file mode 100644 index 0000000..dfdc8db --- /dev/null +++ b/src/test/java/com/example/AviaryService/controllers/PublicStatsControllerTest.java @@ -0,0 +1,109 @@ +package com.example.AviaryService.controllers; + +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +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.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +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.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.AircraftRepository; +import com.example.AviaryService.repositories.UserRepository; +import com.example.AviaryService.support.TestFleet; + +// GET /api/public/stats: public, read-only, rate limited, CORS for +// DanielIbarra.com only, and never anything about one account. +// Contract: specs/004-public-aviary-stats/contracts/public-stats-api.md +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +class PublicStatsControllerTest { + + @Autowired MockMvc mvc; + @Autowired UserRepository userRepository; + @Autowired AircraftRepository aircraftRepository; + + @Test + void publicWithoutLoginAndCreatesNoSession() throws Exception { + MvcResult res = mvc.perform(get("/api/public/stats").with(r -> { r.setRemoteAddr("10.0.0.1"); return r; })) + .andExpect(status().isOk()) + .andExpect(header().string("Cache-Control", containsString("max-age=300"))) + .andExpect(jsonPath("$.users").isNumber()) + .andExpect(jsonPath("$.aircraft").isNumber()) + .andExpect(jsonPath("$.flights").isNumber()) + .andExpect(jsonPath("$.hoursFlown").isNumber()) + .andExpect(jsonPath("$.alertsSent").isNumber()) + .andExpect(jsonPath("$.signupsLast7Days").isNumber()) + .andExpect(jsonPath("$.signupsLast30Days").isNumber()) + .andExpect(jsonPath("$.recentSignups").isArray()) + .andExpect(jsonPath("$.generatedAt").isString()) + .andReturn(); + assertFalse(res.getResponse().getHeaderNames().contains("Set-Cookie")); + assertNull(res.getRequest().getSession(false), "endpoint must not create a session"); + } + + @Test + void corsAllowsDanielIbarraDotCom() throws Exception { + mvc.perform(get("/api/public/stats").header("Origin", "https://danielibarra.com") + .with(r -> { r.setRemoteAddr("10.0.0.2"); return r; })) + .andExpect(status().isOk()) + .andExpect(header().string("Access-Control-Allow-Origin", "https://danielibarra.com")); + } + + @Test + void corsRefusesOtherSites() throws Exception { + mvc.perform(get("/api/public/stats").header("Origin", "https://evil.example") + .with(r -> { r.setRemoteAddr("10.0.0.3"); return r; })) + .andExpect(header().doesNotExist("Access-Control-Allow-Origin")); + } + + @Test + void writesAreRefused() throws Exception { + int code = mvc.perform(post("/api/public/stats").with(r -> { r.setRemoteAddr("10.0.0.4"); return r; })) + .andReturn().getResponse().getStatus(); + assertNotEquals(200, code); + } + + @Test + void rateLimitedPerIp() throws Exception { + for (int i = 0; i < PublicStatsController.MAX_PER_WINDOW; i++) { + mvc.perform(get("/api/public/stats").with(r -> { r.setRemoteAddr("10.9.9.9"); return r; })) + .andExpect(status().isOk()); + } + mvc.perform(get("/api/public/stats").with(r -> { r.setRemoteAddr("10.9.9.9"); return r; })) + .andExpect(status().isTooManyRequests()) + .andExpect(header().exists("Retry-After")) + .andExpect(jsonPath("$.error").value("rate_limited")); + // A different visitor is unaffected. + mvc.perform(get("/api/public/stats").with(r -> { r.setRemoteAddr("10.9.9.10"); return r; })) + .andExpect(status().isOk()); + } + + // Constitution I: the public endpoint must not leak any one account's data. + @Test + void responseHasNoAccountDetails() throws Exception { + User u = userRepository.save(new User("leakcheck-user", "x")); + TestFleet.addAircraft(aircraftRepository, userRepository, u, "N0LEAK", "Leak Check Owner", 0, 0); + + String body = mvc.perform(get("/api/public/stats").with(r -> { r.setRemoteAddr("10.0.0.5"); return r; })) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + + for (String forbidden : new String[] {"leakcheck-user", "N0LEAK", "Leak Check Owner", + "DanielIbarra", "TomasIbarra", "\"id\"", "\"username\"", "\"password\"", "\"tailNumber\""}) { + assertFalse(body.contains(forbidden), "response leaked " + forbidden + ": " + body); + } + } +} diff --git a/src/test/java/com/example/AviaryService/services/stats/PublicStatsQueriesTest.java b/src/test/java/com/example/AviaryService/services/stats/PublicStatsQueriesTest.java new file mode 100644 index 0000000..97ae266 --- /dev/null +++ b/src/test/java/com/example/AviaryService/services/stats/PublicStatsQueriesTest.java @@ -0,0 +1,94 @@ +package com.example.AviaryService.services.stats; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +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 org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.domain.PageRequest; +import org.springframework.test.context.ActiveProfiles; +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; + +import jakarta.persistence.EntityManager; + +// The public stats queries against a real (H2) database. The seeders also put +// rows in this database, so totals are checked as before/after differences. +@SpringBootTest +@ActiveProfiles("test") +@Transactional +class PublicStatsQueriesTest { + + @Autowired UserRepository userRepository; + @Autowired FlightLogRepository flightLogRepository; + @Autowired EntityManager em; + + @Test + void hoursFlownSkipsMissingAndBackwardsReadings() { + double before = orZero(flightLogRepository.sumHoursFlown()); + User u = userRepository.save(new User("stats-hours-user", "x")); + flightLogRepository.save(new FlightLog("KTMB", "KFLL", null, null, 101.5, 100.0, u)); // +1.5 + flightLogRepository.save(new FlightLog("KTMB", "KFLL", null, null, 50.0, 50.0, u)); // skipped: in == out + flightLogRepository.save(new FlightLog("KTMB", "KFLL", null, null, 49.0, 50.0, u)); // skipped: in < out + flightLogRepository.save(new FlightLog("KTMB", "KFLL", null, null, null, 10.0, u)); // skipped: missing + assertEquals(1.5, orZero(flightLogRepository.sumHoursFlown()) - before, 1e-9); + } + + @Test + void newAccountGetsCreatedAtThatNeverChanges() { + User u = userRepository.saveAndFlush(new User("stats-created-user", "x")); + Instant created = u.getCreatedAt(); + assertNotNull(created); + + u.setPassword("y"); + userRepository.saveAndFlush(u); + em.clear(); + assertEquals(created, userRepository.findById(u.getId()).orElseThrow().getCreatedAt()); + } + + @Test + void accountsWithoutCreatedAtAreNeverListedOrCountedAsRecent() { + User old = userRepository.saveAndFlush(new User("stats-legacy-user", "x")); + // Simulate an account made before signup dates were recorded. + em.createQuery("update User u set u.createdAt = null where u.id = :id") + .setParameter("id", old.getId()).executeUpdate(); + em.clear(); + assertNull(userRepository.findById(old.getId()).orElseThrow().getCreatedAt()); + + List recent = userRepository.findRecentSignupTimes(PageRequest.of(0, 1000)); + assertFalse(recent.contains(null)); + long recentCount = userRepository.countByCreatedAtAfter(Instant.EPOCH); + assertTrue(recentCount < userRepository.count(), "legacy account counts as a user but not as a dated signup"); + } + + @Test + void recentSignupsNewestFirstAndCapped() { + for (int i = 0; i < 12; i++) { + User u = new User("stats-feed-user-" + i, "x"); + u.setCreatedAt(Instant.parse("2030-01-01T00:00:00Z").plusSeconds(i * 3600L)); + userRepository.save(u); + } + userRepository.flush(); + List top = userRepository.findRecentSignupTimes(PageRequest.of(0, 10)); + assertEquals(10, top.size()); + assertEquals(Instant.parse("2030-01-01T11:00:00Z"), top.get(0)); + for (int i = 1; i < top.size(); i++) { + assertTrue(!top.get(i).isAfter(top.get(i - 1)), "newest first"); + } + } + + private static double orZero(Double d) { + return d == null ? 0.0 : d; + } +} diff --git a/src/test/java/com/example/AviaryService/services/stats/PublicStatsServiceTest.java b/src/test/java/com/example/AviaryService/services/stats/PublicStatsServiceTest.java new file mode 100644 index 0000000..e3c1ea3 --- /dev/null +++ b/src/test/java/com/example/AviaryService/services/stats/PublicStatsServiceTest.java @@ -0,0 +1,138 @@ +package com.example.AviaryService.services.stats; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +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.ZoneId; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.data.domain.Pageable; + +import com.example.AviaryService.repositories.AircraftRepository; +import com.example.AviaryService.repositories.AlertSendLogRepository; +import com.example.AviaryService.repositories.FlightLogRepository; +import com.example.AviaryService.repositories.UserRepository; +import com.example.AviaryService.services.stats.PublicStatsSnapshot.SignupEntry; + +// Caching and number-shaping rules of PublicStatsService, with the database +// mocked out. The real queries are covered by PublicStatsQueriesTest. +class PublicStatsServiceTest { + + static class TestClock extends Clock { + Instant now = Instant.parse("2026-11-10T12:00:00Z"); + @Override public ZoneId getZone() { return ZoneOffset.UTC; } + @Override public Clock withZone(ZoneId zone) { return this; } + @Override public Instant instant() { return now; } + } + + UserRepository users = mock(UserRepository.class); + AircraftRepository aircraft = mock(AircraftRepository.class); + FlightLogRepository flights = mock(FlightLogRepository.class); + AlertSendLogRepository alerts = mock(AlertSendLogRepository.class); + TestClock clock = new TestClock(); + PublicStatsProperties props = new PublicStatsProperties( + List.of("https://danielibarra.com"), ZoneId.of("America/New_York"), Duration.ofMinutes(15)); + PublicStatsService service; + + @BeforeEach + void setUp() { + when(users.count()).thenReturn(3L); + when(aircraft.count()).thenReturn(4L); + when(flights.count()).thenReturn(5L); + when(flights.sumHoursFlown()).thenReturn(12.345); + when(alerts.count()).thenReturn(2L); + when(users.findRecentSignupTimes(any(Pageable.class))).thenReturn(List.of()); + service = new PublicStatsService(users, aircraft, flights, alerts, props, clock); + } + + @Test + void countsEveryAccountAndTotal() { + PublicStatsSnapshot s = service.current(); + assertEquals(3, s.users()); + assertEquals(4, s.aircraft()); + assertEquals(5, s.flights()); + assertEquals(12.3, s.hoursFlown()); + assertEquals(2, s.alertsSent()); + assertEquals(clock.now, s.generatedAt()); + } + + @Test + void emptyDatabaseGivesZerosNotNulls() { + when(users.count()).thenReturn(0L); + when(flights.sumHoursFlown()).thenReturn(null); + PublicStatsSnapshot s = service.current(); + assertEquals(0, s.users()); + assertEquals(0.0, s.hoursFlown()); + assertTrue(s.recentSignups().isEmpty()); + } + + @Test + void servesCachedSnapshotUntilTtlPasses() { + PublicStatsSnapshot first = service.current(); + clock.now = clock.now.plus(Duration.ofMinutes(14)); + assertSame(first, service.current()); + verify(users, times(1)).count(); + + clock.now = clock.now.plus(Duration.ofMinutes(1)); + PublicStatsSnapshot second = service.current(); + verify(users, times(2)).count(); + assertEquals(clock.now, second.generatedAt()); + } + + @Test + void failedRefreshKeepsServingOldSnapshot() { + PublicStatsSnapshot first = service.current(); + clock.now = clock.now.plus(Duration.ofMinutes(20)); + when(users.count()).thenThrow(new RuntimeException("db down")); + assertSame(first, service.current()); + } + + @Test + void failureWithNoSnapshotYetIsUnavailable() { + when(users.count()).thenThrow(new RuntimeException("db down")); + assertThrows(PublicStatsUnavailableException.class, service::current); + } + + @Test + void signupsAreDateOnlyInConfiguredZoneWithFixedLabel() { + // 03:00 UTC on Nov 10 is still the evening of Nov 9 in New York. + when(users.findRecentSignupTimes(any(Pageable.class))) + .thenReturn(List.of(Instant.parse("2026-11-10T03:00:00Z"))); + List feed = service.current().recentSignups(); + assertEquals(List.of(new SignupEntry("New pilot joined", "2026-11-09")), feed); + } + + @Test + void asksForAtMostTenSignups() { + List ten = new ArrayList<>(); + for (int i = 0; i < 10; i++) ten.add(clock.now.minus(Duration.ofDays(i))); + when(users.findRecentSignupTimes(any(Pageable.class))).thenAnswer(inv -> { + assertEquals(10, ((Pageable) inv.getArgument(0)).getPageSize()); + return ten; + }); + assertEquals(10, service.current().recentSignups().size()); + } + + @Test + void signupWindowsAreSevenAndThirtyDays() { + when(users.countByCreatedAtAfter(clock.now.minus(Duration.ofDays(7)))).thenReturn(1L); + when(users.countByCreatedAtAfter(clock.now.minus(Duration.ofDays(30)))).thenReturn(6L); + PublicStatsSnapshot s = service.current(); + assertEquals(1, s.signupsLast7Days()); + assertEquals(6, s.signupsLast30Days()); + } +} From 8aab4815234dfb9c3661a499adba2b68e4e8a7c9 Mon Sep 17 00:00:00 2001 From: dannysusername Date: Mon, 9 Nov 2026 18:10:59 -0500 Subject: [PATCH 2/2] Store createdAt at microsecond precision Linux clocks give nanosecond Instants but the database keeps microseconds, so a freshly saved account's createdAt didn't match what was read back (failed in CI, passed on macOS). Truncate when it's set. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01M4dsGvpqnWiNuLHPLuGXx4 --- src/main/java/com/example/AviaryService/entity/User.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/example/AviaryService/entity/User.java b/src/main/java/com/example/AviaryService/entity/User.java index d6f067d..f8a7e33 100644 --- a/src/main/java/com/example/AviaryService/entity/User.java +++ b/src/main/java/com/example/AviaryService/entity/User.java @@ -2,6 +2,7 @@ import jakarta.persistence.*; import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; @@ -60,7 +61,9 @@ public class User { @PrePersist void onCreate() { if (createdAt == null) { - createdAt = Instant.now(); + // Microseconds: what the database keeps. Linux clocks give + // nanoseconds, so without this the saved value reads back different. + createdAt = Instant.now().truncatedTo(ChronoUnit.MICROS); } }