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
14 changes: 14 additions & 0 deletions changelog/v0.2.20.md
Original file line number Diff line number Diff line change
@@ -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.
51 changes: 51 additions & 0 deletions deploy/dokploy/compose-staging.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Staging stack: Develop, On Push. Separate database, volumes and host port from production.
# Reach it on http://<server-ip>: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:
14 changes: 11 additions & 3 deletions docs/ADMIN-UI.md
Original file line number Diff line number Diff line change
Expand Up @@ -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://<gateway>/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 \
Expand Down
21 changes: 21 additions & 0 deletions docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
7 changes: 7 additions & 0 deletions docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion path-gateway/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<parent>
<groupId>io.github.an1ndra</groupId>
<artifactId>path-parent</artifactId>
<version>0.2.19</version>
<version>0.2.20</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
Original file line number Diff line number Diff line change
@@ -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<String, Object> status() {
return auth.status();
}

@PostMapping("/auth/setup")
public Map<String, Object> setup(@RequestBody Credentials input, HttpServletRequest request) {
AdminAuthService.SessionResult result = auth.setup(input.username(), input.password());
return sessionResponse(result, request);
}

@PostMapping("/auth/login")
public Map<String, Object> 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<String, Object> me(HttpServletRequest request) {
AdminUser user = currentUser(request);
Map<String, Object> out = new LinkedHashMap<>(auth.view(user));
out.put("scopes", auth.scopesFor(user));
return out;
}

@PostMapping("/auth/logout")
public Map<String, Object> logout(HttpServletRequest request) {
auth.logout(request.getHeader(AuthFilter.ADMIN_SESSION_HEADER));
return Map.of("ok", true);
}

@GetMapping("/auth/github/start")
public Map<String, Object> 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<Map<String, Object>> users() {
return auth.listUsers();
}

@PostMapping("/users")
public Map<String, Object> createUser(@RequestBody UserInput input) {
Map<String, Object> 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<String, Object> updateUser(@PathVariable Long id, @RequestBody UserUpdate input) {
Map<String, Object> 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<String, Object> 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<String, Object> sessionResponse(AdminAuthService.SessionResult result,
HttpServletRequest request) {
Map<String, Object> 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);
}
}
Loading