diff --git a/changelog/v0.2.20.md b/changelog/v0.2.20.md new file mode 100644 index 0000000..ecc2f9d --- /dev/null +++ b/changelog/v0.2.20.md @@ -0,0 +1,14 @@ +# v0.2.20 + +Console login with password accounts and GitHub OAuth. + +## Added + +- Username/password login backed by PBKDF2 hashes and revocable sessions + (`X-Admin-Session`, `GATEWAY_SESSION_TTL`, default 7 days). +- GitHub OAuth login with a signed state, configurable client id/secret, + callback and console redirect, plus an optional allowed-users list. +- First-run setup creates the owner; Users management adds owner/admin/viewer + accounts with password reset, enable/disable and delete. +- The console login screen replaces the pasted admin token with the setup, + password and GitHub forms. `X-Admin-Token` remains for automation. diff --git a/deploy/dokploy/compose-staging.yml b/deploy/dokploy/compose-staging.yml new file mode 100644 index 0000000..f7481b3 --- /dev/null +++ b/deploy/dokploy/compose-staging.yml @@ -0,0 +1,51 @@ +# Staging stack: Develop, On Push. Separate database, volumes and host port from production. +# Reach it on http://:8081 (or add a domain in Dokploy later). +services: + postgres: + image: postgres:16-alpine + restart: unless-stopped + environment: + POSTGRES_DB: path + POSTGRES_USER: path + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD} + volumes: + - pgdata_staging:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U path -d path"] + interval: 5s + timeout: 3s + retries: 20 + + gateway: + build: + context: ../.. + dockerfile: Dockerfile + restart: unless-stopped + depends_on: + postgres: + condition: service_healthy + environment: + SPRING_PROFILES_ACTIVE: postgres + DB_URL: jdbc:postgresql://postgres:5432/path + DB_USER: path + DB_PASSWORD: ${POSTGRES_PASSWORD} + PORT: "8080" + GATEWAY_MASTER_KEY: ${GATEWAY_MASTER_KEY:?set GATEWAY_MASTER_KEY} + GATEWAY_ADMIN_TOKEN: ${GATEWAY_ADMIN_TOKEN:?set GATEWAY_ADMIN_TOKEN} + GATEWAY_CORS_ORIGINS: ${GATEWAY_CORS_ORIGINS:-*} + GATEWAY_MAX_REQUEST_BYTES: "16777216" + GATEWAY_RATE_LIMIT_BACKEND: memory + GATEWAY_USAGE_RETENTION: 30d + GATEWAY_DRAIN_TIMEOUT: 25s + # Staging is for trying routes quickly; the demo catalogue is useful here. + GATEWAY_SEED_DEFAULTS: "true" + GATEWAY_API_DOCS: "true" + ports: + - "8081:8080" + stop_grace_period: 40s + volumes: + - pathdata_staging:/app/data + +volumes: + pgdata_staging: + pathdata_staging: diff --git a/docs/ADMIN-UI.md b/docs/ADMIN-UI.md index 39be92e..cc3e7ff 100644 --- a/docs/ADMIN-UI.md +++ b/docs/ADMIN-UI.md @@ -21,9 +21,17 @@ selected by `Accept-Language`. ## Auth -The console logs in with an **admin token** (`X-Admin-Token`), kept in `sessionStorage`. -There are no user accounts, passwords or cookies. Mint per-person tokens so actions stay -attributable: +The console signs in with a **username/password account** or **GitHub OAuth** and keeps +the resulting session token in `sessionStorage`. The first visit shows a setup form that +creates the owner; later users are managed on the Users page with `owner`, `admin` or +`viewer` roles. `X-Admin-Token` remains supported for automation and bootstrap, but the +console no longer asks for it. + +GitHub login needs an OAuth app whose callback is +`https:///admin/auth/github/callback`; set `GATEWAY_GITHUB_CLIENT_ID`, +`GATEWAY_GITHUB_CLIENT_SECRET`, `GATEWAY_GITHUB_REDIRECT_URI` and +`GATEWAY_GITHUB_CONSOLE_URL`. `GATEWAY_GITHUB_ALLOWED_USERS` limits which GitHub logins +may create an account. ```bash curl -X POST http://localhost:8080/admin/tokens \ diff --git a/docs/API.md b/docs/API.md index 4ad6693..0c158d8 100644 --- a/docs/API.md +++ b/docs/API.md @@ -72,6 +72,27 @@ the response. --- +## Console auth + +The console signs in with a username/password account or GitHub OAuth. Successful login +returns a session token; send it as `X-Admin-Session`. Sessions expire after +`GATEWAY_SESSION_TTL` (default 7 days) and are revoked by logout. + +| Method | Path | Purpose | +|---|---|---| +| GET | `/admin/auth/status` | public: `setup_required`, `github_enabled` | +| POST | `/admin/auth/setup` | create the first owner; only while no users exist | +| POST | `/admin/auth/login` | `{username,password}` → `{session,user,scopes}` | +| GET | `/admin/auth/me` | the signed-in user and scopes | +| POST | `/admin/auth/logout` | revoke the current session | +| GET | `/admin/auth/github/start` | `{authorize_url}` for the GitHub redirect | +| GET | `/admin/auth/github/callback` | GitHub redirect target; ends at the console | +| GET/POST | `/admin/users` | list/create console users | +| PATCH/DELETE | `/admin/users/{id}` | role, password, email, enable/disable, delete | + +`X-Admin-Token` remains supported for automation and bootstrap; the console itself uses +sessions. A `viewer` can read but not mutate; `admin` and `owner` can write. + ## Public API ### `POST /v1/chat/completions` diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index d56899b..8d63102 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -14,6 +14,13 @@ except the provider credentials you actually use. | `GATEWAY_CORS_ORIGINS` | `*` | comma-separated origin patterns | | `GATEWAY_MAX_REQUEST_BYTES` | `1048576` | request bodies larger than this get 413 | | `GATEWAY_DRAIN_TIMEOUT` | `30s` | how long shutdown waits for in-flight streams | +| `GATEWAY_SESSION_TTL` | `7d` | console login session lifetime | +| `GATEWAY_GITHUB_CLIENT_ID` | empty | GitHub OAuth app client id; empty disables GitHub login | +| `GATEWAY_GITHUB_CLIENT_SECRET` | empty | GitHub OAuth app secret | +| `GATEWAY_GITHUB_REDIRECT_URI` | empty | public callback, e.g. `https://gw.example.com/admin/auth/github/callback` | +| `GATEWAY_GITHUB_CONSOLE_URL` | empty | console login page the callback redirects to | +| `GATEWAY_GITHUB_ALLOWED_USERS` | empty | comma-separated GitHub logins allowed to sign in; empty means existing users only | +| `GATEWAY_GITHUB_DEFAULT_ROLE` | `viewer` | role for an allowlisted GitHub user on first login | ## Keys and budgets diff --git a/path-gateway/pom.xml b/path-gateway/pom.xml index 08ecc50..99350ac 100644 --- a/path-gateway/pom.xml +++ b/path-gateway/pom.xml @@ -7,7 +7,7 @@ io.github.an1ndra path-parent - 0.2.19 + 0.2.20 ../pom.xml diff --git a/path-gateway/src/main/java/com/anindra/path/admin/AdminAuthController.java b/path-gateway/src/main/java/com/anindra/path/admin/AdminAuthController.java new file mode 100644 index 0000000..3c5ac6a --- /dev/null +++ b/path-gateway/src/main/java/com/anindra/path/admin/AdminAuthController.java @@ -0,0 +1,160 @@ +package com.anindra.path.admin; + +import com.anindra.path.api.ApiException; +import com.anindra.path.config.AuthFilter; +import com.anindra.path.config.GatewayProperties; +import com.anindra.path.domain.AdminUser; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.io.IOException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** Password and GitHub login, sessions, and user management. */ +@RestController +@RequestMapping("/admin") +@RequiredArgsConstructor +public class AdminAuthController { + + private final AdminAuthService auth; + private final GithubOAuthService github; + private final GatewayProperties props; + private final ObjectMapper mapper; + private final AuditService audit; + + public record Credentials(String username, String password) { + } + + public record UserInput(String username, String password, String role, String email) { + } + + public record UserUpdate(String password, String role, Boolean enabled, String email) { + } + + @GetMapping("/auth/status") + public Map status() { + return auth.status(); + } + + @PostMapping("/auth/setup") + public Map setup(@RequestBody Credentials input, HttpServletRequest request) { + AdminAuthService.SessionResult result = auth.setup(input.username(), input.password()); + return sessionResponse(result, request); + } + + @PostMapping("/auth/login") + public Map login(@RequestBody Credentials input, HttpServletRequest request) { + AdminAuthService.SessionResult result = auth.login(input.username(), input.password(), + request.getRemoteAddr(), request.getHeader("User-Agent")); + return sessionResponse(result, request); + } + + @GetMapping("/auth/me") + public Map me(HttpServletRequest request) { + AdminUser user = currentUser(request); + Map out = new LinkedHashMap<>(auth.view(user)); + out.put("scopes", auth.scopesFor(user)); + return out; + } + + @PostMapping("/auth/logout") + public Map logout(HttpServletRequest request) { + auth.logout(request.getHeader(AuthFilter.ADMIN_SESSION_HEADER)); + return Map.of("ok", true); + } + + @GetMapping("/auth/github/start") + public Map githubStart() { + return Map.of("authorize_url", github.authorizeUrl()); + } + + @GetMapping("/auth/github/callback") + public void githubCallback(@RequestParam(required = false) String code, + @RequestParam(required = false) String state, + HttpServletResponse response) throws IOException { + try { + AdminAuthService.SessionResult result = auth.githubLogin(github.callback(code, state)); + redirect(response, "session=" + result.token()); + } catch (ApiException e) { + redirect(response, "error=" + URLEncoder.encode(e.getMessage(), StandardCharsets.UTF_8)); + } + } + + @GetMapping("/users") + public List> users() { + return auth.listUsers(); + } + + @PostMapping("/users") + public Map createUser(@RequestBody UserInput input) { + Map created = auth.createUser(input.username(), input.password(), + input.role(), input.email()); + audit.record("user.create", "user:" + created.get("id"), Map.of("username", input.username())); + return created; + } + + @PatchMapping("/users/{id}") + public Map updateUser(@PathVariable Long id, @RequestBody UserUpdate input) { + Map updated = auth.updateUser(id, input.password(), input.role(), + input.enabled(), input.email()); + audit.record("user.update", "user:" + id, Map.of( + "role", String.valueOf(updated.get("role")), + "enabled", String.valueOf(updated.get("enabled")))); + return updated; + } + + @DeleteMapping("/users/{id}") + public Map deleteUser(@PathVariable Long id, HttpServletRequest request) { + Object actor = request.getAttribute(AuthFilter.ADMIN_USER_ID_ATTR); + auth.deleteUser(id, actor instanceof Long value ? value : null); + audit.record("user.delete", "user:" + id, null); + return Map.of("deleted", true, "id", id); + } + + private Map sessionResponse(AdminAuthService.SessionResult result, + HttpServletRequest request) { + Map out = new LinkedHashMap<>(); + out.put("session", result.token()); + out.put("user", auth.view(result.user())); + out.put("scopes", auth.scopesFor(result.user())); + return out; + } + + private AdminUser currentUser(HttpServletRequest request) { + Object id = request.getAttribute(AuthFilter.ADMIN_USER_ID_ATTR); + if (id instanceof Long userId) { + return auth.findById(userId) + .orElseThrow(() -> ApiException.unauthorized( + "Your session no longer maps to a user.", "session_invalid")); + } + Object principal = request.getAttribute(AuthFilter.ADMIN_PRINCIPAL_ATTR); + String name = principal instanceof TenancyService.Principal p ? p.name() : null; + if (name != null) { + return auth.listUsers().stream() + .filter(row -> name.equals(row.get("username"))) + .findFirst() + .flatMap(row -> auth.findById((Long) row.get("id"))) + .orElseThrow(() -> ApiException.unauthorized( + "This credential is not a console user.", "session_required")); + } + throw ApiException.unauthorized("Sign in to continue.", "session_required"); + } + + private void redirect(HttpServletResponse response, String fragment) throws IOException { + String console = props.getGithub().getConsoleUrl(); + if (console == null || console.isBlank()) { + response.setContentType("application/json"); + mapper.writeValue(response.getOutputStream(), Map.of("fragment", fragment)); + return; + } + String base = console.contains("#") ? console.substring(0, console.indexOf('#')) : console; + response.sendRedirect(base + "#" + fragment); + } +} diff --git a/path-gateway/src/main/java/com/anindra/path/admin/AdminAuthService.java b/path-gateway/src/main/java/com/anindra/path/admin/AdminAuthService.java new file mode 100644 index 0000000..f74875f --- /dev/null +++ b/path-gateway/src/main/java/com/anindra/path/admin/AdminAuthService.java @@ -0,0 +1,330 @@ +package com.anindra.path.admin; + +import com.anindra.path.api.ApiException; +import com.anindra.path.config.GatewayProperties; +import com.anindra.path.domain.AdminSession; +import com.anindra.path.domain.AdminUser; +import com.anindra.path.repo.AdminSessionRepository; +import com.anindra.path.repo.AdminUserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +/** Password/GitHub login, sessions and user management for the console. */ +@Service +@RequiredArgsConstructor +public class AdminAuthService { + + public record SessionResult(String token, AdminUser user) { + } + + public record GithubProfile(String id, String login, String email) { + } + + private static final String ALPHABET = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + private static final SecureRandom RANDOM = new SecureRandom(); + private static final Set ROLES = Set.of("owner", "admin", "viewer"); + + private final AdminUserRepository users; + private final AdminSessionRepository sessions; + private final GatewayProperties props; + + public Map status() { + Map out = new LinkedHashMap<>(); + out.put("setup_required", users.count() == 0); + out.put("github_enabled", githubEnabled()); + out.put("password_enabled", true); + return out; + } + + public boolean githubEnabled() { + return props.getGithub().getClientId() != null && !props.getGithub().getClientId().isBlank() + && props.getGithub().getClientSecret() != null + && !props.getGithub().getClientSecret().isBlank(); + } + + @Transactional + public SessionResult setup(String username, String password) { + if (users.count() > 0) { + throw new ApiException(409, "invalid_request_error", "setup_complete", + "An administrator already exists."); + } + AdminUser user = newUser(username, password, "owner"); + users.save(user); + return sessionFor(user, null, null); + } + + @Transactional + public SessionResult login(String username, String password, String ip, String userAgent) { + AdminUser user = users.findByUsernameIgnoreCase(username == null ? "" : username.trim()) + .orElseThrow(AdminAuthService::invalidCredentials); + if (!user.isEnabled() || user.getPasswordHash() == null + || !PasswordHasher.matches(password, user.getPasswordHash())) { + throw invalidCredentials(); + } + user.setLastLoginAt(Instant.now()); + users.save(user); + return sessionFor(user, ip, userAgent); + } + + public Optional authenticateSession(String rawToken) { + if (rawToken == null || rawToken.isBlank()) { + return Optional.empty(); + } + String hash = sha256(rawToken.trim()); + return sessions.findById(hash) + .filter(session -> session.getExpiresAt().isAfter(Instant.now())) + .flatMap(session -> users.findById(session.getUserId())) + .filter(AdminUser::isEnabled); + } + + @Transactional + public void logout(String rawToken) { + if (rawToken != null && !rawToken.isBlank()) { + sessions.deleteById(sha256(rawToken.trim())); + } + } + + @Transactional + public SessionResult githubLogin(GithubProfile profile) { + AdminUser user = users.findByGithubId(profile.id()) + .or(() -> users.findByGithubLoginIgnoreCase(profile.login())) + .orElseGet(() -> provisionGithubUser(profile)); + if (!user.isEnabled()) { + throw ApiException.forbidden("This user is disabled."); + } + user.setGithubId(profile.id()); + user.setGithubLogin(profile.login()); + if (profile.email() != null && !profile.email().isBlank()) { + user.setEmail(profile.email()); + } + user.setLastLoginAt(Instant.now()); + user.setUpdatedAt(Instant.now()); + users.save(user); + return sessionFor(user, null, null); + } + + private AdminUser provisionGithubUser(GithubProfile profile) { + boolean first = users.count() == 0; + String allowed = props.getGithub().getAllowedUsers(); + boolean allowlisted = allowed != null && Arrays.stream(allowed.split(",")) + .map(String::trim) + .filter(s -> !s.isBlank()) + .anyMatch(s -> s.equalsIgnoreCase(profile.login())); + if (!first && !allowlisted) { + throw ApiException.forbidden( + "GitHub user '" + profile.login() + "' is not allowed on this gateway."); + } + String role = first ? "owner" : normalizeRole(props.getGithub().getDefaultRole()); + AdminUser user = new AdminUser(); + user.setUsername(uniqueUsername(profile.login())); + user.setRole(role); + user.setEmail(profile.email()); + user.setGithubLogin(profile.login()); + user.setGithubId(profile.id()); + user.setEnabled(true); + user.setCreatedAt(Instant.now()); + return users.save(user); + } + + // ------------------------------------------------------------- user management + + public List> listUsers() { + List> out = new ArrayList<>(); + for (AdminUser user : users.findAllByOrderByUsernameAsc()) { + out.add(view(user)); + } + return out; + } + + public Optional findById(Long id) { + return users.findById(id); + } + + public Map view(AdminUser user) { + Map row = new LinkedHashMap<>(); + row.put("id", user.getId()); + row.put("username", user.getUsername()); + row.put("role", user.getRole()); + row.put("email", user.getEmail()); + row.put("github_login", user.getGithubLogin()); + row.put("enabled", user.isEnabled()); + row.put("has_password", user.getPasswordHash() != null); + row.put("created_at", user.getCreatedAt() == null ? null : user.getCreatedAt().toString()); + row.put("last_login_at", user.getLastLoginAt() == null ? null : user.getLastLoginAt().toString()); + return row; + } + + @Transactional + public Map createUser(String username, String password, String role, String email) { + AdminUser user = newUser(username, password, role); + user.setEmail(email == null || email.isBlank() ? null : email.trim()); + users.save(user); + return listUsers().stream() + .filter(row -> user.getId().equals(row.get("id"))) + .findFirst().orElseThrow(); + } + + @Transactional + public Map updateUser(Long id, String password, String role, Boolean enabled, + String email) { + AdminUser user = users.findById(id) + .orElseThrow(() -> ApiException.notFound("No user with id " + id, "user_not_found")); + if (password != null && !password.isBlank()) { + validatePassword(password); + user.setPasswordHash(PasswordHasher.hash(password)); + } + if (role != null) { + user.setRole(normalizeRole(role)); + } + if (enabled != null) { + if (!enabled && "owner".equals(user.getRole()) + && users.countByRoleAndEnabledTrue("owner") <= 1) { + throw ApiException.badRequest("The last enabled owner cannot be disabled.", "enabled"); + } + user.setEnabled(enabled); + } + if (email != null) { + user.setEmail(email.isBlank() ? null : email.trim()); + } + user.setUpdatedAt(Instant.now()); + users.save(user); + return listUsers().stream() + .filter(row -> id.equals(row.get("id"))) + .findFirst().orElseThrow(); + } + + @Transactional + public void deleteUser(Long id, Long actorId) { + AdminUser user = users.findById(id) + .orElseThrow(() -> ApiException.notFound("No user with id " + id, "user_not_found")); + if (id.equals(actorId)) { + throw ApiException.badRequest("You cannot delete your own account.", "id"); + } + if ("owner".equals(user.getRole()) && users.countByRoleAndEnabledTrue("owner") <= 1) { + throw ApiException.badRequest("The last owner cannot be deleted.", "id"); + } + sessions.findByUserId(id).forEach(sessions::delete); + users.delete(user); + } + + public Set scopesFor(AdminUser user) { + return "viewer".equals(user.getRole()) ? Set.of("read") : Set.of("read", "write"); + } + + // ------------------------------------------------------------- internals + + private SessionResult sessionFor(AdminUser user, String ip, String userAgent) { + String raw = "sess_" + random(48); + AdminSession session = new AdminSession(); + session.setTokenHash(sha256(raw)); + session.setUserId(user.getId()); + session.setCreatedAt(Instant.now()); + session.setExpiresAt(Instant.now().plus(props.getSessionTtl())); + session.setLastSeenAt(Instant.now()); + session.setIp(ip); + session.setUserAgent(userAgent == null ? null + : userAgent.substring(0, Math.min(userAgent.length(), 255))); + sessions.save(session); + return new SessionResult(raw, user); + } + + private AdminUser newUser(String username, String password, String role) { + String name = validateUsername(username); + validatePassword(password); + if (users.findByUsernameIgnoreCase(name).isPresent()) { + throw new ApiException(409, "invalid_request_error", "user_exists", + "A user with that username already exists."); + } + AdminUser user = new AdminUser(); + user.setUsername(name); + user.setPasswordHash(PasswordHasher.hash(password)); + user.setRole(normalizeRole(role)); + user.setEnabled(true); + user.setCreatedAt(Instant.now()); + return user; + } + + private String uniqueUsername(String githubLogin) { + String base = githubLogin == null || githubLogin.isBlank() ? "github-user" + : githubLogin.replaceAll("[^A-Za-z0-9._-]", "-"); + String candidate = base; + int suffix = 2; + while (users.findByUsernameIgnoreCase(candidate).isPresent()) { + candidate = base + "-" + suffix++; + } + return candidate; + } + + private static String validateUsername(String username) { + String value = username == null ? "" : username.trim(); + if (!value.matches("[A-Za-z0-9._-]{3,64}")) { + throw ApiException.badRequest( + "'username' must be 3-64 characters of letters, digits, dot, dash or underscore.", + "username"); + } + return value; + } + + private static void validatePassword(String password) { + if (password == null || password.length() < 10) { + throw ApiException.badRequest("'password' must be at least 10 characters.", "password"); + } + } + + private static String normalizeRole(String role) { + String value = role == null || role.isBlank() ? "viewer" : role.trim().toLowerCase(Locale.ROOT); + if (!ROLES.contains(value)) { + throw ApiException.badRequest("'role' must be owner, admin or viewer.", "role"); + } + return value; + } + + private static ApiException invalidCredentials() { + return ApiException.unauthorized("Invalid username or password.", "invalid_credentials"); + } + + private static String random(int length) { + StringBuilder sb = new StringBuilder(length); + for (int i = 0; i < length; i++) { + sb.append(ALPHABET.charAt(RANDOM.nextInt(ALPHABET.length()))); + } + return sb.toString(); + } + + private static String sha256(String value) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8)); + StringBuilder sb = new StringBuilder(64); + for (byte b : digest) { + sb.append(String.format("%02x", b)); + } + return sb.toString(); + } catch (Exception e) { + throw new IllegalStateException("SHA-256 is unavailable", e); + } + } + + @Scheduled(fixedDelay = 3_600_000) + @Transactional + void purgeExpiredSessions() { + sessions.deleteByExpiresAtBefore(Instant.now()); + } +} diff --git a/path-gateway/src/main/java/com/anindra/path/admin/GithubOAuthService.java b/path-gateway/src/main/java/com/anindra/path/admin/GithubOAuthService.java new file mode 100644 index 0000000..7175257 --- /dev/null +++ b/path-gateway/src/main/java/com/anindra/path/admin/GithubOAuthService.java @@ -0,0 +1,217 @@ +package com.anindra.path.admin; + +import com.anindra.path.api.ApiException; +import com.anindra.path.config.GatewayProperties; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.time.Duration; +import java.time.Instant; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; + +/** GitHub OAuth web flow. State is signed so the callback needs no server-side session. */ +@Service +@Slf4j +public class GithubOAuthService { + + private static final String AUTHORIZE = "https://github.com/login/oauth/authorize"; + private static final String TOKEN = "https://github.com/login/oauth/access_token"; + private static final String USER = "https://api.github.com/user"; + private static final String EMAILS = "https://api.github.com/user/emails"; + private static final long STATE_TTL_SECONDS = 600; + + private final GatewayProperties props; + private final ObjectMapper mapper; + private final HttpClient http = HttpClient.newBuilder() + .connectTimeout(Duration.ofSeconds(10)) + .build(); + private final byte[] stateKey; + + public GithubOAuthService(GatewayProperties props, ObjectMapper mapper) { + this.props = props; + this.mapper = mapper; + String master = props.getMasterKey(); + if (master != null && !master.isBlank()) { + this.stateKey = master.getBytes(StandardCharsets.UTF_8); + } else { + byte[] random = new byte[32]; + new SecureRandom().nextBytes(random); + this.stateKey = random; + } + } + + public String authorizeUrl() { + requireConfigured(); + String state = signedState(); + return AUTHORIZE + "?client_id=" + enc(props.getGithub().getClientId()) + + "&redirect_uri=" + enc(props.getGithub().getRedirectUri()) + + "&scope=" + enc("read:user user:email") + + "&state=" + enc(state); + } + + public AdminAuthService.GithubProfile callback(String code, String state) { + requireConfigured(); + verifyState(state); + if (code == null || code.isBlank()) { + throw ApiException.badRequest("Missing GitHub authorization code.", "code"); + } + String token = exchange(code); + JsonNode user = get(USER, token); + String id = user.path("id").asText(null); + String login = user.path("login").asText(null); + if (id == null || login == null) { + throw new ApiException(502, "upstream_error", "github_oauth_failed", + "GitHub did not return a user."); + } + String email = user.path("email").asText(null); + if (email == null || email.isBlank()) { + email = primaryEmail(token); + } + return new AdminAuthService.GithubProfile(id, login, email); + } + + private String exchange(String code) { + String form = "client_id=" + enc(props.getGithub().getClientId()) + + "&client_secret=" + enc(props.getGithub().getClientSecret()) + + "&code=" + enc(code) + + "&redirect_uri=" + enc(props.getGithub().getRedirectUri()); + try { + HttpRequest request = HttpRequest.newBuilder(URI.create(TOKEN)) + .timeout(Duration.ofSeconds(15)) + .header("Accept", "application/json") + .header("Content-Type", "application/x-www-form-urlencoded") + .POST(HttpRequest.BodyPublishers.ofString(form)) + .build(); + HttpResponse response = http.send(request, HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() / 100 != 2) { + throw oauthFailure("token exchange returned HTTP " + response.statusCode()); + } + JsonNode body = mapper.readTree(response.body()); + String token = body.path("access_token").asText(null); + if (token == null) { + throw oauthFailure("GitHub rejected the authorization code"); + } + return token; + } catch (ApiException e) { + throw e; + } catch (Exception e) { + log.warn("GitHub token exchange failed: {}", e.getMessage()); + throw oauthFailure("Could not reach GitHub"); + } + } + + private JsonNode get(String url, String token) { + try { + HttpRequest request = HttpRequest.newBuilder(URI.create(url)) + .timeout(Duration.ofSeconds(15)) + .header("Accept", "application/vnd.github+json") + .header("Authorization", "Bearer " + token) + .header("User-Agent", "path-gateway") + .GET() + .build(); + HttpResponse response = http.send(request, HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() / 100 != 2) { + throw oauthFailure("GitHub API returned HTTP " + response.statusCode()); + } + return mapper.readTree(response.body()); + } catch (ApiException e) { + throw e; + } catch (Exception e) { + log.warn("GitHub API call failed: {}", e.getMessage()); + throw oauthFailure("Could not reach GitHub"); + } + } + + private String primaryEmail(String token) { + JsonNode emails = get(EMAILS, token); + for (JsonNode email : emails) { + if (email.path("primary").asBoolean(false) && email.path("verified").asBoolean(false)) { + return email.path("email").asText(null); + } + } + return null; + } + + private void requireConfigured() { + if (props.getGithub().getClientId() == null || props.getGithub().getClientId().isBlank() + || props.getGithub().getClientSecret() == null + || props.getGithub().getClientSecret().isBlank()) { + throw new ApiException(501, "invalid_request_error", "github_not_configured", + "GitHub login is not configured on this gateway."); + } + } + + private String signedState() { + String payload = Instant.now().getEpochSecond() + "." + random(16); + String signature = hmac(payload); + return Base64.getUrlEncoder().withoutPadding() + .encodeToString((payload + "." + signature).getBytes(StandardCharsets.UTF_8)); + } + + private void verifyState(String state) { + if (state == null || state.isBlank()) { + throw ApiException.badRequest("Missing OAuth state.", "state"); + } + try { + String decoded = new String(Base64.getUrlDecoder().decode(state), StandardCharsets.UTF_8); + int split = decoded.lastIndexOf('.'); + String payload = decoded.substring(0, split); + String signature = decoded.substring(split + 1); + if (!MessageDigest.isEqual(hmac(payload).getBytes(StandardCharsets.UTF_8), + signature.getBytes(StandardCharsets.UTF_8))) { + throw ApiException.badRequest("Invalid OAuth state.", "state"); + } + long timestamp = Long.parseLong(payload.substring(0, payload.indexOf('.'))); + if (Instant.now().getEpochSecond() - timestamp > STATE_TTL_SECONDS) { + throw ApiException.badRequest("OAuth state expired.", "state"); + } + } catch (ApiException e) { + throw e; + } catch (RuntimeException e) { + throw ApiException.badRequest("Invalid OAuth state.", "state"); + } + } + + private String hmac(String payload) { + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(stateKey, "HmacSHA256")); + byte[] out = mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)); + StringBuilder sb = new StringBuilder(); + for (byte b : out) { + sb.append(String.format("%02x", b)); + } + return sb.toString(); + } catch (Exception e) { + throw new IllegalStateException("HMAC is unavailable", e); + } + } + + private static String enc(String value) { + return URLEncoder.encode(value == null ? "" : value, StandardCharsets.UTF_8); + } + + private static String random(int length) { + byte[] bytes = new byte[length]; + new SecureRandom().nextBytes(bytes); + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + + private static ApiException oauthFailure(String message) { + return new ApiException(502, "upstream_error", "github_oauth_failed", message); + } +} diff --git a/path-gateway/src/main/java/com/anindra/path/admin/PasswordHasher.java b/path-gateway/src/main/java/com/anindra/path/admin/PasswordHasher.java new file mode 100644 index 0000000..f09284d --- /dev/null +++ b/path-gateway/src/main/java/com/anindra/path/admin/PasswordHasher.java @@ -0,0 +1,57 @@ +package com.anindra.path.admin; + +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.util.Base64; + +/** PBKDF2-HMAC-SHA256, no external dependency. Format: pbkdf2$iterations$salt$hash. */ +public final class PasswordHasher { + + private static final int ITERATIONS = 210_000; + private static final int KEY_BITS = 256; + private static final int SALT_BYTES = 16; + private static final SecureRandom RANDOM = new SecureRandom(); + + private PasswordHasher() { + } + + public static String hash(String password) { + byte[] salt = new byte[SALT_BYTES]; + RANDOM.nextBytes(salt); + byte[] hash = derive(password, salt, ITERATIONS); + return "pbkdf2$" + ITERATIONS + "$" + + Base64.getEncoder().withoutPadding().encodeToString(salt) + "$" + + Base64.getEncoder().withoutPadding().encodeToString(hash); + } + + public static boolean matches(String password, String stored) { + if (password == null || stored == null) { + return false; + } + String[] parts = stored.split("\\$"); + if (parts.length != 4 || !"pbkdf2".equals(parts[0])) { + return false; + } + try { + int iterations = Integer.parseInt(parts[1]); + byte[] salt = Base64.getDecoder().decode(parts[2]); + byte[] expected = Base64.getDecoder().decode(parts[3]); + byte[] actual = derive(password, salt, iterations); + return MessageDigest.isEqual(expected, actual); + } catch (RuntimeException e) { + return false; + } + } + + private static byte[] derive(String password, byte[] salt, int iterations) { + try { + PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, KEY_BITS); + return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256") + .generateSecret(spec).getEncoded(); + } catch (Exception e) { + throw new IllegalStateException("PBKDF2 is unavailable", e); + } + } +} diff --git a/path-gateway/src/main/java/com/anindra/path/config/AuthFilter.java b/path-gateway/src/main/java/com/anindra/path/config/AuthFilter.java index 8d33d97..67ecefa 100644 --- a/path-gateway/src/main/java/com/anindra/path/config/AuthFilter.java +++ b/path-gateway/src/main/java/com/anindra/path/config/AuthFilter.java @@ -36,10 +36,13 @@ public class AuthFilter extends OncePerRequestFilter { /** Project concurrency cap for the resolved key, or absent when unlimited. */ public static final String PROJECT_CONCURRENCY_ATTR = "gateway.projectConcurrency"; public static final String ADMIN_PRINCIPAL_ATTR = "gateway.adminPrincipal"; + public static final String ADMIN_SESSION_HEADER = "X-Admin-Session"; + public static final String ADMIN_USER_ID_ATTR = "gateway.adminUserId"; private final ApiKeyService apiKeys; private final RateLimitStore rateLimiter; private final com.anindra.path.gateway.IpAccessService ipAccess; + private final com.anindra.path.admin.AdminAuthService adminAuth; private final com.anindra.path.admin.TenancyService tenancy; private final AdminAuthLimiter adminAuthLimiter; private final ClientAuthLimiter clientAuthLimiter; @@ -81,6 +84,10 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse } if (path.startsWith("/admin")) { + if (isPublicAdminAuth(path, request.getMethod())) { + chain.doFilter(request, response); + return; + } requireAdmin(request); } else if (path.startsWith("/actuator")) { requireActuatorAccess(request, path); @@ -233,6 +240,20 @@ private ClientKey resolveClientKey(HttpServletRequest request) { } private void requireAdmin(HttpServletRequest request) { + String session = request.getHeader(ADMIN_SESSION_HEADER); + if (session != null && !session.isBlank()) { + com.anindra.path.domain.AdminUser user = adminAuth.authenticateSession(session) + .orElseThrow(() -> ApiException.unauthorized( + "Your session is invalid or expired. Sign in again.", "session_invalid")); + com.anindra.path.admin.TenancyService.Principal principal = + new com.anindra.path.admin.TenancyService.Principal( + user.getUsername(), adminAuth.scopesFor(user)); + request.setAttribute(ADMIN_PRINCIPAL_ATTR, principal); + request.setAttribute(ADMIN_USER_ID_ATTR, user.getId()); + requireWrite(request, principal); + return; + } + // SSO at the edge: an authenticating proxy (Authentik, Keycloak, oauth2-proxy, Cloudflare // Access) resolves the human and injects an identity header. The gateway then trusts it // instead of a pasted token. This is only safe when the gateway cannot be reached except @@ -271,10 +292,27 @@ private void requireAdmin(HttpServletRequest request) { } request.setAttribute(ADMIN_PRINCIPAL_ATTR, principal); + requireWrite(request, principal); + } + + private static boolean isPublicAdminAuth(String path, String method) { + String verb = method == null ? "" : method.toUpperCase(); + if ("/admin/auth/status".equals(path) || "/admin/auth/github/start".equals(path) + || "/admin/auth/github/callback".equals(path)) { + return "GET".equals(verb); + } + if ("/admin/auth/login".equals(path) || "/admin/auth/setup".equals(path)) { + return "POST".equals(verb); + } + return false; + } + + private static void requireWrite(HttpServletRequest request, + com.anindra.path.admin.TenancyService.Principal principal) { boolean mutating = !"GET".equalsIgnoreCase(request.getMethod()) && !"HEAD".equalsIgnoreCase(request.getMethod()); if (mutating && !principal.canWrite()) { - throw ApiException.forbidden("This admin token has read-only scope."); + throw ApiException.forbidden("This account has read-only scope."); } } diff --git a/path-gateway/src/main/java/com/anindra/path/config/GatewayProperties.java b/path-gateway/src/main/java/com/anindra/path/config/GatewayProperties.java index dd95a15..4735dfa 100644 --- a/path-gateway/src/main/java/com/anindra/path/config/GatewayProperties.java +++ b/path-gateway/src/main/java/com/anindra/path/config/GatewayProperties.java @@ -85,6 +85,26 @@ public class GatewayProperties { private Alert alert = new Alert(); private Digest digest = new Digest(); private Errors errors = new Errors(); + private Github github = new Github(); + + /** Admin console login. Empty client id/secret leaves GitHub login disabled. */ + @Getter + @Setter + public static class Github { + private String clientId = ""; + private String clientSecret = ""; + /** Public gateway callback, e.g. https://path.example.com/admin/auth/github/callback. */ + private String redirectUri = ""; + /** Console login page, e.g. https://admin.example.com/login. */ + private String consoleUrl = ""; + /** Comma-separated GitHub logins allowed to sign in. Empty = only existing users. */ + private String allowedUsers = ""; + /** Role granted to an allowlisted GitHub user on first login. */ + private String defaultRole = "viewer"; + } + + /** How long a console login session stays valid. */ + private Duration sessionTtl = Duration.ofDays(7); /** * What an upstream failure looks like to the caller. Provider text can name the diff --git a/path-gateway/src/main/java/com/anindra/path/domain/AdminSession.java b/path-gateway/src/main/java/com/anindra/path/domain/AdminSession.java new file mode 100644 index 0000000..3ae121a --- /dev/null +++ b/path-gateway/src/main/java/com/anindra/path/domain/AdminSession.java @@ -0,0 +1,39 @@ +package com.anindra.path.domain; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.time.Instant; + +/** A console login session; the raw token is only in the browser. */ +@Entity +@Table(name = "admin_sessions") +@Getter +@Setter +@NoArgsConstructor +public class AdminSession { + + @Id + @Column(length = 64) + private String tokenHash; + + @Column(nullable = false) + private Long userId; + + @Column(nullable = false) + private Instant createdAt = Instant.now(); + + @Column(nullable = false) + private Instant expiresAt; + + @Column(nullable = false) + private Instant lastSeenAt = Instant.now(); + + @Column(length = 64) + private String ip; + + @Column(length = 255) + private String userAgent; +} diff --git a/path-gateway/src/main/java/com/anindra/path/domain/AdminUser.java b/path-gateway/src/main/java/com/anindra/path/domain/AdminUser.java new file mode 100644 index 0000000..6572527 --- /dev/null +++ b/path-gateway/src/main/java/com/anindra/path/domain/AdminUser.java @@ -0,0 +1,51 @@ +package com.anindra.path.domain; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.time.Instant; + +/** A person who can sign in to the admin console. */ +@Entity +@Table(name = "admin_users") +@Getter +@Setter +@NoArgsConstructor +public class AdminUser { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, unique = true, length = 64) + private String username; + + /** PBKDF2; null for a GitHub-only user until a password is set. */ + @Column(length = 255) + private String passwordHash; + + /** owner, admin or viewer. */ + @Column(nullable = false, length = 16) + private String role = "viewer"; + + @Column(length = 255) + private String email; + + @Column(unique = true, length = 128) + private String githubLogin; + + @Column(length = 64) + private String githubId; + + @Column(nullable = false) + private boolean enabled = true; + + @Column(nullable = false) + private Instant createdAt = Instant.now(); + + private Instant updatedAt; + + private Instant lastLoginAt; +} diff --git a/path-gateway/src/main/java/com/anindra/path/repo/AdminSessionRepository.java b/path-gateway/src/main/java/com/anindra/path/repo/AdminSessionRepository.java new file mode 100644 index 0000000..891e363 --- /dev/null +++ b/path-gateway/src/main/java/com/anindra/path/repo/AdminSessionRepository.java @@ -0,0 +1,14 @@ +package com.anindra.path.repo; + +import com.anindra.path.domain.AdminSession; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.time.Instant; +import java.util.List; + +public interface AdminSessionRepository extends JpaRepository { + + List findByUserId(Long userId); + + long deleteByExpiresAtBefore(Instant cutoff); +} diff --git a/path-gateway/src/main/java/com/anindra/path/repo/AdminUserRepository.java b/path-gateway/src/main/java/com/anindra/path/repo/AdminUserRepository.java new file mode 100644 index 0000000..668aae8 --- /dev/null +++ b/path-gateway/src/main/java/com/anindra/path/repo/AdminUserRepository.java @@ -0,0 +1,20 @@ +package com.anindra.path.repo; + +import com.anindra.path.domain.AdminUser; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; +import java.util.Optional; + +public interface AdminUserRepository extends JpaRepository { + + Optional findByUsernameIgnoreCase(String username); + + Optional findByGithubLoginIgnoreCase(String githubLogin); + + Optional findByGithubId(String githubId); + + List findAllByOrderByUsernameAsc(); + + long countByRoleAndEnabledTrue(String role); +} diff --git a/path-gateway/src/main/resources/application.yml b/path-gateway/src/main/resources/application.yml index f56fc03..db87fcb 100644 --- a/path-gateway/src/main/resources/application.yml +++ b/path-gateway/src/main/resources/application.yml @@ -120,6 +120,15 @@ gateway: enabled: ${GATEWAY_DIGEST:true} cron: "${GATEWAY_DIGEST_CRON:0 0 8 * * *}" usage-retention: ${GATEWAY_USAGE_RETENTION:180d} + # Console login: sessions, password accounts and GitHub OAuth. + session-ttl: ${GATEWAY_SESSION_TTL:7d} + github: + client-id: ${GATEWAY_GITHUB_CLIENT_ID:} + client-secret: ${GATEWAY_GITHUB_CLIENT_SECRET:} + redirect-uri: ${GATEWAY_GITHUB_REDIRECT_URI:} + console-url: ${GATEWAY_GITHUB_CONSOLE_URL:} + allowed-users: ${GATEWAY_GITHUB_ALLOWED_USERS:} + default-role: ${GATEWAY_GITHUB_DEFAULT_ROLE:viewer} # Provider error text can name the provider, echo part of a credential, or expose # internal hostnames. Off means callers get the gateway's own message; the full # cause is still logged and visible in the admin probe. diff --git a/path-gateway/src/main/resources/db/migration/V28__admin_users_sessions.sql b/path-gateway/src/main/resources/db/migration/V28__admin_users_sessions.sql new file mode 100644 index 0000000..b00a3c9 --- /dev/null +++ b/path-gateway/src/main/resources/db/migration/V28__admin_users_sessions.sql @@ -0,0 +1,34 @@ +-- Console users and login sessions. Passwords are PBKDF2 hashes; session tokens are +-- stored as SHA-256 hashes and never in plaintext. + +create table admin_users ( + id bigint generated by default as identity, + username varchar(64) not null, + password_hash varchar(255), + role varchar(16) not null default 'viewer', + email varchar(255), + github_login varchar(128), + github_id varchar(64), + enabled boolean not null default true, + created_at timestamp(6) with time zone not null, + updated_at timestamp(6) with time zone, + last_login_at timestamp(6) with time zone, + primary key (id), + constraint uq_admin_users_username unique (username), + constraint uq_admin_users_github_login unique (github_login) +); + +create table admin_sessions ( + token_hash varchar(64) not null, + user_id bigint not null, + created_at timestamp(6) with time zone not null, + expires_at timestamp(6) with time zone not null, + last_seen_at timestamp(6) with time zone not null, + ip varchar(64), + user_agent varchar(255), + primary key (token_hash), + constraint fk_admin_sessions_user foreign key (user_id) references admin_users (id) on delete cascade +); + +create index ix_admin_sessions_user on admin_sessions (user_id); +create index ix_admin_sessions_expires on admin_sessions (expires_at); diff --git a/path-gateway/src/test/java/com/anindra/path/AdminAuthFilterTest.java b/path-gateway/src/test/java/com/anindra/path/AdminAuthFilterTest.java new file mode 100644 index 0000000..d2fa21a --- /dev/null +++ b/path-gateway/src/test/java/com/anindra/path/AdminAuthFilterTest.java @@ -0,0 +1,107 @@ +package com.anindra.path; + +import com.anindra.path.admin.AdminAuthService; +import com.anindra.path.repo.AdminSessionRepository; +import com.anindra.path.repo.AdminUserRepository; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +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.web.servlet.MockMvc; + +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.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest(properties = { + "spring.datasource.url=jdbc:h2:mem:adminauthfilter;MODE=PostgreSQL;DB_CLOSE_DELAY=-1", + "spring.jpa.hibernate.ddl-auto=validate", + "gateway.admin-token=test-admin", + "gateway.bootstrap-demo-key=false", + "gateway.master-key-path=./target/test-master.key" +}) +@AutoConfigureMockMvc +class AdminAuthFilterTest { + + @Autowired + private MockMvc mvc; + + @Autowired + private ObjectMapper mapper; + + @Autowired + private AdminAuthService auth; + + @Autowired + private AdminUserRepository users; + + @Autowired + private AdminSessionRepository sessions; + + @BeforeEach + void clean() { + sessions.deleteAll(); + users.deleteAll(); + } + + private String setupSession() throws Exception { + String body = mvc.perform(post("/admin/auth/setup") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"username\":\"owner\",\"password\":\"correct horse battery\"}")) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + return mapper.readTree(body).path("session").asText(); + } + + @Test + void setupIsPublicAndTheSessionAuthenticatesAdminCalls() throws Exception { + String session = setupSession(); + + mvc.perform(get("/admin/settings").header("X-Admin-Session", session)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.auth_mode").exists()); + + mvc.perform(get("/admin/settings")) + .andExpect(status().isUnauthorized()); + } + + @Test + void theStatusEndpointIsPublicAndReportsSetup() throws Exception { + mvc.perform(get("/admin/auth/status")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.setup_required").value(true)); + } + + @Test + void aViewerSessionCannotWrite() throws Exception { + setupSession(); + auth.createUser("viewer", "viewer password", "viewer", null); + String body = mvc.perform(post("/admin/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"username\":\"viewer\",\"password\":\"viewer password\"}")) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + String viewerSession = mapper.readTree(body).path("session").asText(); + + mvc.perform(post("/admin/tokens") + .header("X-Admin-Session", viewerSession) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"name\":\"nope\",\"scopes\":\"read\"}")) + .andExpect(status().isForbidden()); + } + + @Test + void aWrongPasswordIs401() throws Exception { + setupSession(); + mvc.perform(post("/admin/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"username\":\"owner\",\"password\":\"wrong password\"}")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.error.code").value("invalid_credentials")); + } +} diff --git a/path-gateway/src/test/java/com/anindra/path/admin/AdminAuthServiceTest.java b/path-gateway/src/test/java/com/anindra/path/admin/AdminAuthServiceTest.java new file mode 100644 index 0000000..a0ade29 --- /dev/null +++ b/path-gateway/src/test/java/com/anindra/path/admin/AdminAuthServiceTest.java @@ -0,0 +1,93 @@ +package com.anindra.path.admin; + +import com.anindra.path.api.ApiException; +import com.anindra.path.repo.AdminSessionRepository; +import com.anindra.path.repo.AdminUserRepository; +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 java.time.Instant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@SpringBootTest(properties = { + "spring.datasource.url=jdbc:h2:mem:adminauthtest;MODE=PostgreSQL;DB_CLOSE_DELAY=-1", + "spring.jpa.hibernate.ddl-auto=validate", + "gateway.bootstrap-demo-key=false", + "gateway.master-key-path=./target/test-master.key" +}) +class AdminAuthServiceTest { + + @Autowired + private AdminAuthService auth; + + @Autowired + private AdminUserRepository users; + + @Autowired + private AdminSessionRepository sessions; + + @BeforeEach + void clean() { + sessions.deleteAll(); + users.deleteAll(); + } + + @Test + void theFirstSetupCreatesAnOwnerAndOnlyRunsOnce() { + var created = auth.setup("owner", "correct horse battery"); + assertThat(created.user().getRole()).isEqualTo("owner"); + assertThat(auth.status().get("setup_required")).isEqualTo(false); + + assertThatThrownBy(() -> auth.setup("second", "another long password")) + .isInstanceOf(ApiException.class) + .hasFieldOrPropertyWithValue("code", "setup_complete"); + } + + @Test + void passwordLoginCreatesAUsableSession() { + var setup = auth.setup("owner", "correct horse battery"); + auth.logout(setup.token()); + + var login = auth.login("owner", "correct horse battery", "127.0.0.1", "test"); + assertThat(auth.authenticateSession(login.token())).isPresent() + .get().extracting("username").isEqualTo("owner"); + } + + @Test + void aWrongPasswordIsRejected() { + auth.setup("owner", "correct horse battery"); + assertThatThrownBy(() -> auth.login("owner", "wrong password", null, null)) + .isInstanceOf(ApiException.class) + .hasFieldOrPropertyWithValue("code", "invalid_credentials"); + } + + @Test + void logoutAndExpiryInvalidateTheSession() throws Exception { + var setup = auth.setup("owner", "correct horse battery"); + auth.logout(setup.token()); + assertThat(auth.authenticateSession(setup.token())).isEmpty(); + + var login = auth.login("owner", "correct horse battery", null, null); + var stored = sessions.findById( + java.util.HexFormat.of().formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest(login.token().getBytes(java.nio.charset.StandardCharsets.UTF_8)))) + .orElseThrow(); + stored.setExpiresAt(Instant.now().minusSeconds(1)); + sessions.save(stored); + assertThat(auth.authenticateSession(login.token())).isEmpty(); + } + + @Test + void aViewerGetsReadScopeOnly() { + auth.setup("owner", "correct horse battery"); + var viewer = auth.createUser("viewer", "viewer password", "viewer", null); + var user = auth.findById((Long) viewer.get("id")).orElseThrow(); + + assertThat(auth.scopesFor(user)).containsExactly("read"); + } +} diff --git a/path-spring-ai/pom.xml b/path-spring-ai/pom.xml index f738c66..1abbfd6 100644 --- a/path-spring-ai/pom.xml +++ b/path-spring-ai/pom.xml @@ -7,7 +7,7 @@ io.github.an1ndra path-parent - 0.2.19 + 0.2.20 ../pom.xml diff --git a/pom.xml b/pom.xml index ea5ceb3..760710a 100644 --- a/pom.xml +++ b/pom.xml @@ -13,7 +13,7 @@ io.github.an1ndra path-parent - 0.2.19 + 0.2.20 pom path-parent Build parent for Path, the provider-agnostic LLM gateway, and its Spring AI adapter