Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/`:
Expand Down
12 changes: 12 additions & 0 deletions docs/migrations/2026-11-09_users_created_at.sql
Original file line number Diff line number Diff line change
@@ -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;
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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/**")
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Map<String, String>> unavailable() {
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body(Map.of("error", "unavailable"));
}
}
22 changes: 22 additions & 0 deletions src/main/java/com/example/AviaryService/entity/User.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.example.AviaryService.entity;

import jakarta.persistence.*;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

Expand Down Expand Up @@ -49,6 +51,22 @@ 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) {
// Microseconds: what the database keeps. Linux clocks give
// nanoseconds, so without this the saved value reads back different.
createdAt = Instant.now().truncatedTo(ChronoUnit.MICROS);
}
}

public User(){

}
Expand Down Expand Up @@ -105,6 +123,10 @@ public void setFlightLogs(List<FlightLog> 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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -15,4 +16,12 @@ public interface FlightLogRepository extends JpaRepository<FlightLog, Long> {

// Every flight the account owns, across aircraft.
List<FlightLog> 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();
}
Original file line number Diff line number Diff line change
@@ -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<User, Long>{
public interface UserRepository extends JpaRepository<User, Long>{
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<Instant> findRecentSignupTimes(Pageable page);
}
Original file line number Diff line number Diff line change
@@ -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<String> 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) {
}
Loading
Loading