Sync shared snapshot from de9b599

This commit is contained in:
Gabriel20xx committed 2026-09-02 20:50:21 +02:00
1 parent eb113a7029
commit 49e3c7d561
9 files changed
+697 -44

No files matched your search

+18 -2
View File
@@ -75,10 +75,14 @@ func WithCookieName(name string) Option {
return func(c *Client) { c.cookieName = name } return func(c *Client) { c.cookieName = name }
} }
// New creates a Client for the AuthServer instance at baseURL. // New creates a Client for the AuthServer instance at baseURL. baseURL may
// be given without a scheme (e.g. "auth.example.com" or "192.168.1.50:8080")
// - "https://" is assumed in that case, so a deployment only needs to name
// the host, not repeat the scheme; an explicit "http://" (for a plain-HTTP
// local/LAN AuthServer) is left as-is.
func New(baseURL string, opts ...Option) *Client { func New(baseURL string, opts ...Option) *Client {
c := &Client{ c := &Client{
baseURL: strings.TrimRight(strings.TrimSpace(baseURL), "/"), baseURL: normalizeBaseURL(baseURL),
httpClient: &http.Client{Timeout: 5 * time.Second}, httpClient: &http.Client{Timeout: 5 * time.Second},
cookieName: DefaultCookieName, cookieName: DefaultCookieName,
} }
@@ -88,6 +92,18 @@ func New(baseURL string, opts ...Option) *Client {
return c return c
} }
func normalizeBaseURL(baseURL string) string {
trimmed := strings.TrimRight(strings.TrimSpace(baseURL), "/")
if trimmed == "" {
return trimmed
}
lower := strings.ToLower(trimmed)
if strings.HasPrefix(lower, "http://") || strings.HasPrefix(lower, "https://") {
return trimmed
}
return "https://" + trimmed
}
// Validate calls AuthServer's GET /api/session/validate with token as a // Validate calls AuthServer's GET /api/session/validate with token as a
// Bearer credential and returns the resolved user. It returns // Bearer credential and returns the resolved user. It returns
// ErrInvalidSession (wrapped) when AuthServer reports the session as not // ErrInvalidSession (wrapped) when AuthServer reports the session as not
+26
View File
@@ -8,6 +8,32 @@ import (
"testing" "testing"
) )
func TestNewNormalizesBaseURL(t *testing.T) {
cases := []struct {
name string
input string
want string
}{
{name: "bare host gets https", input: "auth.example.com", want: "https://auth.example.com"},
{name: "bare host:port gets https", input: "192.168.1.50:8080", want: "https://192.168.1.50:8080"},
{name: "explicit http is left alone", input: "http://auth.example.com", want: "http://auth.example.com"},
{name: "explicit https is left alone", input: "https://auth.example.com", want: "https://auth.example.com"},
{name: "scheme match is case-insensitive", input: "HTTP://auth.example.com", want: "HTTP://auth.example.com"},
{name: "trailing slash stripped before scheme check", input: "auth.example.com/", want: "https://auth.example.com"},
{name: "surrounding whitespace trimmed", input: " auth.example.com ", want: "https://auth.example.com"},
{name: "empty stays empty", input: "", want: ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
client := New(tc.input)
if got := client.baseURL; got != tc.want {
t.Fatalf("New(%q).baseURL = %q, want %q", tc.input, got, tc.want)
}
})
}
}
func TestSetupStatus(t *testing.T) { func TestSetupStatus(t *testing.T) {
cases := []struct { cases := []struct {
name string name string
+9
View File
@@ -26,9 +26,18 @@
<maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.target>1.8</maven.compiler.target>
<junit.version>5.10.2</junit.version> <junit.version>5.10.2</junit.version>
<!-- Pinned to match MegaBasterd/pom.xml's jackson-databind version - both
poms compile the exact same AuthClient.java, which now builds/parses
JSON via Jackson for its full (non-validate-only) method surface. -->
<jackson.version>2.18.6</jackson.version>
</properties> </properties>
<dependencies> <dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.junit.jupiter</groupId> <groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId> <artifactId>junit-jupiter</artifactId>
@@ -1,13 +1,21 @@
package com.gabriel20xx.shared.auth; package com.gabriel20xx.shared.auth;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Supplier; import java.util.function.Supplier;
import java.util.regex.Matcher; import java.util.regex.Matcher;
@@ -18,49 +26,71 @@ import java.util.regex.Pattern;
* AuthGuard instance instead of embedding its own local user table. * AuthGuard instance instead of embedding its own local user table.
* *
* <p>A service that switches to AuthGuard trades "its own local user table" * <p>A service that switches to AuthGuard trades "its own local user table"
* for "one HTTP call per request to AuthGuard's {@code /api/session/validate}", * for "HTTP calls to AuthGuard's API", gaining a single shared identity
* gaining a single shared identity across every project that does the same. * across every project that does the same. Mirrors
* Mirrors {@code shared/backend/authclient} (Go, {@code client.go}) and * {@code shared/backend/authclient} (Go, {@code client.go}),
* {@code shared/packages/node-backend/src/authclient.js} (Node) - keep the * {@code shared/packages/node-backend/src/authclient.js} (Node), and
* three in sync if any of them changes shape. This package is additive: no * {@code shared/packages/python-backend/src/shared_backend/authclient.py}
* project is wired up to use it automatically just because this class * (Python) - keep all four in sync if any of them changes shape.
* exists.
* *
* <h2>Two deliberate deviations from the task-literal Java 11+/record design</h2> * <p>Two kinds of consumer, two parts of this class:
* <ul>
* <li>A service that only needs to gate requests behind "is this a valid
* AuthGuard session" uses {@link #validate(String)} /
* {@link #extractToken} / {@link #middleware}, calling only
* {@code GET /api/session/validate}. This is the original, minimal
* surface of this class.</li>
* <li>A service that runs its own login/register/admin-user-management
* screens proxied to AuthGuard (mirroring the Go/Node/Python clients'
* full method set - see e.g.
* {@code Original/GameStream/backend/cmd/gamestreamd/auth.go} for the
* reference Go implementation of this pattern; MegaBasterd's own
* migration, {@code WebServer.java}, is the reference Java one) uses
* the additional methods below: {@link #register}, {@link #login},
* {@link #logout}, {@link #me}, {@code totpEnable}/{@code Verify}/
* {@code Disable}, {@code requestPasswordReset}/
* {@code confirmPasswordReset}, {@code list}/{@code create}/
* {@code update}/{@code deleteManagedUser}, {@link #setupStatus}.</li>
* </ul>
*
* <h2>Deliberate deviations from the task-literal Java 11+/record design</h2>
* *
* <p>This class intentionally targets Java 8 source/binary compatibility - * <p>This class intentionally targets Java 8 source/binary compatibility -
* it uses {@link java.net.HttpURLConnection} rather than * it uses {@link java.net.HttpURLConnection} rather than
* {@code java.net.http.HttpClient} (added in Java 11), and a plain nested * {@code java.net.http.HttpClient} (added in Java 11), and plain nested
* final class ({@link User}) rather than a Java {@code record} (added in * final classes ({@link User}, {@link PublicUser}, etc.) rather than a Java
* Java 16) - and hand-parses AuthGuard's small, fixed JSON response shape * {@code record} (added in Java 16). This is ground-truth driven, not
* rather than depending on Jackson/Gson. Both choices are ground-truth * stylistic: java-backend has no build file of its own (unlike its
* driven, not stylistic: * {@code node-backend}/{@code python-backend} siblings, which have a
* {@code package.json}/{@code pyproject.toml}). Its <em>only</em> verified
* real consumer, MegaBasterd, compiles this exact source directory straight
* into its own build via the {@code build-helper-maven-plugin}
* "add-shared-java-auth" execution in {@code MegaBasterd/pom.xml}, which
* pins {@code <maven.compiler.source>}/{@code <target>} to {@code 1.8}. Java
* 11 APIs or {@code record} syntax here would fail to compile in that real
* build, or fail at runtime on an actual Java 8 JVM even if it happened to
* compile. A standalone {@code pom.xml} was added to this package purely so
* this class can be built and tested in isolation (see this package's
* README); it targets Java 8 for the same reason.
* *
* <ul> * <p>{@link #validate(String)} still hand-parses AuthGuard's small, fixed
* <li>java-backend has no build file of its own (unlike its * {@code GET /api/session/validate} response shape with a few targeted
* {@code node-backend}/{@code python-backend} siblings, which have a * regular expressions rather than Jackson, keeping the minimal
* {@code package.json}/{@code pyproject.toml}). Its <em>only</em> * validate-only surface dependency-free beyond the JDK - {@code ResetManager},
* verified real consumer, MegaBasterd, compiles this exact source * {@code Roles}, and {@code Totp}, the other classes in this package, stay
* directory straight into its own build via the * that way too. The full-proxy methods added below (register/login/setup/
* {@code build-helper-maven-plugin} "add-shared-java-auth" execution * reset/admin-user-management) are a different tradeoff: they must both
* in {@code MegaBasterd/pom.xml}, which pins * build and parse a handful of small JSON request/response bodies, which
* {@code <maven.compiler.source>}/{@code <target>} to {@code 1.8}. * would be considerably worse hand-rolled than {@code validate}'s
* Java 11 APIs or {@code record} syntax here would fail to compile in * fixed-shape parsing, so they use Jackson ({@code jackson-databind})
* that real build, or fail at runtime on an actual Java 8 JVM even if * instead. This makes {@code jackson-databind} a compile-time dependency of
* it happened to compile. A standalone {@code pom.xml} was added to * this whole class (Java has no way to make an import conditional on which
* this package purely so this class can be built and tested in * methods a given consumer actually calls) - acceptable here because
* isolation (see this package's README); it targets Java 8 for the * MegaBasterd, this package's only verified consumer, already depends on
* same reason.</li> * Jackson for its own code. A hypothetical future consumer that only ever
* <li>{@code ResetManager}, {@code Roles}, and {@code Totp} - the only * calls {@code validate}/{@code middleware} and doesn't already carry
* other classes in this package - have zero runtime dependencies * Jackson would need to add it just to compile this file; that tradeoff was
* beyond the JDK. Requiring Jackson/Gson here would make this the one * chosen deliberately over hand-rolling JSON request bodies with regex.
* class in java-backend that forces a dependency onto every consumer,
* even ones (unlike MegaBasterd) that don't already carry a JSON
* library. AuthGuard's response shape is small and fixed
* ({@code {"valid":bool,"user_id":number,"username":string,"role":string}}),
* so it is parsed defensively with a few targeted regular expressions
* instead.</li>
* </ul>
*/ */
public final class AuthClient { public final class AuthClient {
@@ -74,6 +104,9 @@ public final class AuthClient {
private static final Pattern ROLE_PATTERN = Pattern.compile("\"role\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\""); private static final Pattern ROLE_PATTERN = Pattern.compile("\"role\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"");
private static final String BEARER_PREFIX = "Bearer "; private static final String BEARER_PREFIX = "Bearer ";
/** Used only by the full-proxy methods below; see the class javadoc's Jackson tradeoff note. */
private static final ObjectMapper JSON = new ObjectMapper();
private final String baseUrl; private final String baseUrl;
private final String cookieName; private final String cookieName;
private final int timeoutMillis; private final int timeoutMillis;
@@ -220,6 +253,403 @@ public final class AuthClient {
} }
} }
// --- Full API surface ---------------------------------------------------
//
// validate/middleware above are all a service needs when it only ever
// forwards an already-established AuthGuard session to check it's still
// valid. A service that used to run its own local register/login/logout/
// TOTP/password-reset/admin-user-management flow and is migrating that
// flow onto AuthGuard instead needs to originate those same calls
// itself - that's what the rest of this class adds. Every method mirrors
// one of AuthGuard's internal/httpapi handlers exactly (method, path,
// request/response JSON shape) - see the Go client (client.go) this was
// ported from for the source of truth.
//
// Cookie forwarding: register() and login() both return the Set-Cookie
// header value(s) AuthGuard's response carried, as SessionResult.cookies
// (logout() returns them directly). A service proxying its own e.g.
// POST /login to AuthGuard's POST /api/login should generally pass these
// straight through to its own response (e.g.
// exchange.getResponseHeaders().add("Set-Cookie", cookie) for each
// value): the browser then transparently holds AuthGuard's own
// auth_session cookie, and every subsequent request's session token is
// that same cookie value - no separate mapping between "the proxying
// service's own session cookie" and "the AuthGuard token" is needed
// anywhere. A service adopting this pattern should stop minting a
// session cookie of its own and read/forward the incoming auth_session
// cookie the same way middleware/extractToken does.
/**
* The account {@link #register}/{@link #login}/{@link #me} return. Deliberately
* distinct from the slimmer {@link User} type {@link #validate}/{@link #middleware}
* use (which mirrors {@code GET /api/session/validate}'s smaller shape and does not
* carry TOTP status at all).
*/
public static final class PublicUser {
public final long id;
public final String username;
public final String email;
public final String role;
public final boolean totpEnabled;
public PublicUser(long id, String username, String email, String role, boolean totpEnabled) {
this.id = id;
this.username = username == null ? "" : username;
this.email = email == null ? "" : email;
this.role = role == null ? "" : role;
this.totpEnabled = totpEnabled;
}
}
/** One row of {@code GET /api/admin/users}, and the payload {@link #createManagedUser} returns. */
public static final class ManagedUser {
public final long id;
public final String username;
public final String email;
public final String role;
/** Raw ISO-8601 timestamp string as AuthGuard returns it - not parsed, to avoid a java.time/Jackson-datatype dependency for one display field. */
public final String createdAt;
public ManagedUser(long id, String username, String email, String role, String createdAt) {
this.id = id;
this.username = username == null ? "" : username;
this.email = email == null ? "" : email;
this.role = role == null ? "" : role;
this.createdAt = createdAt == null ? "" : createdAt;
}
}
/** Returned by {@link #register} and {@link #login}: the resolved account, plus the Set-Cookie header value(s) the response carried. */
public static final class SessionResult {
public final PublicUser user;
public final List<String> cookies;
public SessionResult(PublicUser user, List<String> cookies) {
this.user = user;
this.cookies = cookies;
}
}
/** Returned by {@link #totpEnable}: a freshly provisioned, not yet active TOTP secret and its otpauth:// URI. Confirm it with {@link #totpVerify}. */
public static final class TOTPEnableResult {
public final String secret;
public final String otpauthUrl;
public final boolean enabled;
public TOTPEnableResult(String secret, String otpauthUrl, boolean enabled) {
this.secret = secret == null ? "" : secret;
this.otpauthUrl = otpauthUrl == null ? "" : otpauthUrl;
this.enabled = enabled;
}
}
/**
* Body of {@link #createManagedUser} ({@code POST /api/admin/users}) and
* {@link #updateManagedUser} ({@code PUT /api/admin/users/{id}}). On update, a
* {@code null}/blank {@code username}/{@code email}/{@code password} field means
* "leave unchanged" (AuthGuard applies only non-empty fields); {@code role} is
* only honored when {@code null} is not passed and AuthGuard's own authorization
* rules let the caller reassign it (only a superadmin actor, and never onto/away
* from a superadmin target) - this class does not re-implement or pre-validate
* those rules.
*/
public static final class ManagedUserInput {
public final String username;
public final String email;
public final String password;
public final String role;
public ManagedUserInput(String username, String email, String password, String role) {
this.username = username;
this.email = email;
this.password = password;
this.role = role;
}
}
/**
* Thrown when AuthGuard responds with a non-2xx status to one of the
* register/login/.../setupStatus methods (not thrown by {@link #validate}, which
* uses {@link InvalidSessionException} for its one specific non-2xx case). Carries
* the status code and (when AuthGuard's JSON body decoded successfully) its
* {@code {"error": "..."}} message, so a caller can map it back onto its own
* service's response shape/status code rather than exposing AuthGuard's wording
* verbatim.
*/
public static final class APIError extends IOException {
public final int statusCode;
/**
* Set only by {@link #login}, mirroring AuthGuard's {@code {"totp_required": true}}
* flag on a 401 that means "credentials were correct, but this account has
* two-factor auth enabled and no (or an incorrect) code was supplied" - distinct
* from a plain invalid-credentials 401.
*/
public final boolean totpRequired;
public APIError(int statusCode, String message, boolean totpRequired) {
super("authclient: authguard responded " + statusCode + ": " + message);
this.statusCode = statusCode;
this.totpRequired = totpRequired;
}
}
/**
* Calls {@code GET /api/setup-status}, an unauthenticated endpoint that reports
* whether AuthGuard has any account at all. Accounts are centralized in AuthGuard,
* so a caller with its own "first launch, create the initial admin" flow should
* consult this first: when it reports {@code false}, some account already exists
* (possibly created by a different project, or directly against AuthGuard), and the
* caller should show its ordinary login screen instead of its own account-creation form.
*/
public boolean setupStatus() throws IOException {
JsonNode node = JSON.readTree(call("GET", "/api/setup-status", "", null).body);
return node.path("setup_required").asBoolean(false);
}
/** Calls {@code POST /api/register}, creating a new AuthGuard account and starting a session for it. */
public SessionResult register(String username, String email, String password) throws IOException {
ObjectNode body = JSON.createObjectNode();
body.put("username", username);
body.put("email", email);
body.put("password", password);
CallResult result = call("POST", "/api/register", "", body);
return new SessionResult(parsePublicUser(JSON.readTree(result.body).path("user")), result.cookies);
}
/**
* Calls {@code POST /api/login}. {@code totpToken} may be empty; AuthGuard raises an
* {@link APIError} with {@link APIError#totpRequired} set when the account has
* two-factor auth enabled and no valid code was supplied.
*/
public SessionResult login(String usernameOrEmail, String password, String totpToken) throws IOException {
ObjectNode body = JSON.createObjectNode();
body.put("username_or_email", usernameOrEmail);
body.put("password", password);
if (totpToken != null && !totpToken.isEmpty()) {
body.put("totp_token", totpToken);
}
CallResult result = call("POST", "/api/login", "", body);
return new SessionResult(parsePublicUser(JSON.readTree(result.body).path("user")), result.cookies);
}
/**
* Calls {@code POST /api/logout}, deleting the session identified by {@code token}
* server-side. Returns the (cookie-clearing) Set-Cookie header value(s) AuthGuard's
* response carried.
*/
public List<String> logout(String token) throws IOException {
return call("POST", "/api/logout", token, null).cookies;
}
/** Calls {@code GET /api/me}, resolving {@code token} to its account. */
public PublicUser me(String token) throws IOException {
return parsePublicUser(JSON.readTree(call("GET", "/api/me", token, null).body).path("user"));
}
/**
* Calls {@code POST /api/totp/enable}, provisioning (or re-provisioning) a pending
* TOTP secret for {@code token}'s account. The secret is not active until
* {@link #totpVerify} confirms a generated code.
*/
public TOTPEnableResult totpEnable(String token) throws IOException {
JsonNode node = JSON.readTree(call("POST", "/api/totp/enable", token, null).body);
return new TOTPEnableResult(node.path("secret").asText(""), node.path("otpauth_url").asText(""), node.path("enabled").asBoolean(false));
}
/** Calls {@code POST /api/totp/verify}, confirming {@code code} against the pending secret {@link #totpEnable} provisioned and activating two-factor auth. */
public void totpVerify(String token, String code) throws IOException {
ObjectNode body = JSON.createObjectNode();
body.put("token", code);
call("POST", "/api/totp/verify", token, body);
}
/** Calls {@code POST /api/totp/disable}, turning two-factor auth off for {@code token}'s account. AuthGuard requires {@code code} to be one last valid TOTP code as proof of possession. */
public void totpDisable(String token, String code) throws IOException {
ObjectNode body = JSON.createObjectNode();
body.put("token", code);
call("POST", "/api/totp/disable", token, body);
}
/**
* Calls {@code POST /api/password-reset/request}. AuthGuard prints a one-time code
* to its own process console; only an operator with access to that console can relay
* it onward. Called with a blank {@code usernameOrEmail}, the target is AuthGuard's
* superadmin account - AuthGuard's own web UI is the intended place to drive this,
* not an individual project.
*/
public void requestPasswordReset(String usernameOrEmail) throws IOException {
ObjectNode body = JSON.createObjectNode();
body.put("username_or_email", usernameOrEmail == null ? "" : usernameOrEmail);
call("POST", "/api/password-reset/request", "", body);
}
/** Calls {@code POST /api/password-reset/confirm} with the code an operator relayed out-of-band and a new password, and invalidates every existing session for that account. */
public void confirmPasswordReset(String code, String newPassword) throws IOException {
ObjectNode body = JSON.createObjectNode();
body.put("code", code);
body.put("password", newPassword);
call("POST", "/api/password-reset/confirm", "", body);
}
/** Calls {@code GET /api/admin/users}. {@code token}'s account must satisfy AuthGuard's CanManageUsers check (admin or superadmin), or this throws an {@link APIError} with statusCode 401/403. */
public List<ManagedUser> listManagedUsers(String token) throws IOException {
JsonNode usersNode = JSON.readTree(call("GET", "/api/admin/users", token, null).body).path("users");
List<ManagedUser> users = new ArrayList<ManagedUser>();
if (usersNode.isArray()) {
for (JsonNode node : usersNode) {
users.add(parseManagedUser(node));
}
}
return users;
}
/** Calls {@code POST /api/admin/users}. Only a superadmin actor may set {@code role} to anything other than "user"; anyone else's requested role is silently ignored by AuthGuard. */
public ManagedUser createManagedUser(String token, ManagedUserInput input) throws IOException {
CallResult result = call("POST", "/api/admin/users", token, managedUserInputToJson(input));
return parseManagedUser(JSON.readTree(result.body).path("user"));
}
/** Calls {@code PUT /api/admin/users/{id}}; see {@link ManagedUserInput}'s doc comment. */
public void updateManagedUser(String token, long id, ManagedUserInput input) throws IOException {
call("PUT", "/api/admin/users/" + id, token, managedUserInputToJson(input));
}
/** Calls {@code DELETE /api/admin/users/{id}}. */
public void deleteManagedUser(String token, long id) throws IOException {
call("DELETE", "/api/admin/users/" + id, token, null);
}
private static PublicUser parsePublicUser(JsonNode node) {
return new PublicUser(
node.path("id").asLong(0),
node.path("username").asText(""),
node.path("email").asText(""),
node.path("role").asText(""),
node.path("totp_enabled").asBoolean(false));
}
private static ManagedUser parseManagedUser(JsonNode node) {
return new ManagedUser(
node.path("id").asLong(0),
node.path("username").asText(""),
node.path("email").asText(""),
node.path("role").asText(""),
node.path("created_at").asText(""));
}
private static ObjectNode managedUserInputToJson(ManagedUserInput input) {
ObjectNode body = JSON.createObjectNode();
if (input.username != null && !input.username.isEmpty()) {
body.put("username", input.username);
}
if (input.email != null && !input.email.isEmpty()) {
body.put("email", input.email);
}
if (input.password != null && !input.password.isEmpty()) {
body.put("password", input.password);
}
if (input.role != null) {
body.put("role", input.role);
}
return body;
}
/** The decoded JSON response body plus any Set-Cookie header value(s); see {@link #call}. */
private static final class CallResult {
private final String body;
private final List<String> cookies;
private CallResult(String body, List<String> cookies) {
this.body = body;
this.cookies = cookies;
}
}
/**
* Runs one JSON request/response round trip against AuthGuard: builds a JSON request
* (skipped when {@code body} is {@code null}), attaches {@code token} as a Bearer
* credential (skipped when {@code token} is blank), and returns the decoded response
* body text plus any Set-Cookie header value(s). Throws {@link APIError} for a
* non-2xx response, a plain {@link IOException} for a transport failure - mirrors Go's
* {@code Client.call}/Node's {@code AuthClient#_call}/Python's {@code AuthClient._call} exactly.
*/
private CallResult call(String method, String path, String token, Object body) throws IOException {
if (baseUrl.isEmpty()) {
throw new IllegalStateException("authclient: client has no base URL");
}
URL url = new URL(baseUrl + path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
connection.setConnectTimeout(timeoutMillis);
connection.setReadTimeout(timeoutMillis);
if (token != null && !token.isEmpty()) {
connection.setRequestProperty("Authorization", BEARER_PREFIX + token);
}
byte[] payload = null;
if (body != null) {
connection.setRequestProperty("Content-Type", "application/json");
payload = JSON.writeValueAsBytes(body);
connection.setDoOutput(true);
}
int status;
String responseBody;
List<String> cookies;
try {
if (payload != null) {
OutputStream out = connection.getOutputStream();
try {
out.write(payload);
} finally {
out.close();
}
}
status = connection.getResponseCode();
InputStream stream = status >= 400 ? connection.getErrorStream() : connection.getInputStream();
responseBody = readAll(stream);
cookies = new ArrayList<String>();
for (Map.Entry<String, List<String>> entry : connection.getHeaderFields().entrySet()) {
if (entry.getKey() != null && entry.getKey().equalsIgnoreCase("Set-Cookie")) {
cookies.addAll(entry.getValue());
}
}
} catch (IOException ex) {
throw new IOException("authclient: call AuthGuard: " + ex.getMessage(), ex);
} finally {
connection.disconnect();
}
if (status < 200 || status >= 300) {
String message = null;
boolean totpRequired = false;
if (responseBody != null && !responseBody.isEmpty()) {
try {
JsonNode node = JSON.readTree(responseBody);
if (node.hasNonNull("error")) {
message = node.get("error").asText();
}
if (node.hasNonNull("totp_required")) {
totpRequired = node.get("totp_required").asBoolean();
}
} catch (IOException ignored) {
// Fall through to the generic message below.
}
}
if (message == null || message.isEmpty()) {
message = "request failed (" + status + ")";
}
throw new APIError(status, message, totpRequired);
}
return new CallResult(responseBody, cookies);
}
/** Package-private accessor for {@link #normalizeBaseUrl}'s scheme-detection test coverage; not part of the public API. */
String baseUrlForTest() {
return baseUrl;
}
private String extractCookieToken(String cookieHeader) { private String extractCookieToken(String cookieHeader) {
if (cookieHeader == null || cookieHeader.isEmpty()) { if (cookieHeader == null || cookieHeader.isEmpty()) {
return ""; return "";
@@ -249,12 +679,26 @@ public final class AuthClient {
return connection; return connection;
} }
/**
* Trims {@code baseUrl}, strips a trailing slash, and - if the result has
* no scheme - assumes {@code https://}, so a deployment only needs to
* name the host (e.g. {@code "auth.example.com"} or
* {@code "192.168.1.50:8080"}), not repeat the scheme. An explicit
* {@code http://} (for a plain-HTTP local/LAN AuthGuard) is left as-is.
*/
private static String normalizeBaseUrl(String baseUrl) { private static String normalizeBaseUrl(String baseUrl) {
String trimmed = baseUrl == null ? "" : baseUrl.trim(); String trimmed = baseUrl == null ? "" : baseUrl.trim();
while (trimmed.endsWith("/")) { while (trimmed.endsWith("/")) {
trimmed = trimmed.substring(0, trimmed.length() - 1); trimmed = trimmed.substring(0, trimmed.length() - 1);
} }
return trimmed; if (trimmed.isEmpty()) {
return trimmed;
}
String lower = trimmed.toLowerCase(Locale.ROOT);
if (lower.startsWith("http://") || lower.startsWith("https://")) {
return trimmed;
}
return "https://" + trimmed;
} }
private static String readAll(InputStream in) throws IOException { private static String readAll(InputStream in) throws IOException {
@@ -6,13 +6,16 @@ import java.io.OutputStream;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* Mirrors shared/packages/node-backend/test/authclient.test.js's coverage, * Mirrors shared/packages/node-backend/test/authclient.test.js's coverage,
@@ -34,6 +37,75 @@ class AuthClientTest {
} }
} }
@Test
void constructorAssumesHttpsForABareHost() {
assertEquals("https://auth.example.com", new AuthClient("auth.example.com").baseUrlForTest());
assertEquals("https://192.168.1.50:8080", new AuthClient("192.168.1.50:8080").baseUrlForTest());
}
@Test
void constructorLeavesAnExplicitSchemeAlone() {
assertEquals("http://auth.example.com", new AuthClient("http://auth.example.com").baseUrlForTest());
assertEquals("https://auth.example.com", new AuthClient("https://auth.example.com").baseUrlForTest());
assertEquals("HTTP://auth.example.com", new AuthClient("HTTP://auth.example.com").baseUrlForTest());
}
@Test
void constructorStripsTrailingSlashBeforeCheckingScheme() {
assertEquals("https://auth.example.com", new AuthClient("auth.example.com/").baseUrlForTest());
}
@Test
void setupStatusReflectsAuthGuardSetupRequired() throws Exception {
server = fakeEndpoint("/api/setup-status", 200, "{\"setup_required\":true}");
AuthClient client = new AuthClient(baseUrl(server));
assertTrue(client.setupStatus());
}
@Test
void registerReturnsTheUserAndForwardsSetCookieValues() throws Exception {
server = fakeEndpointCapturingRequest(
"/api/register",
200,
"{\"user\":{\"id\":7,\"username\":\"gabriel\",\"email\":\"g@example.com\",\"role\":\"superadmin\",\"totp_enabled\":false}}",
new String[] {"auth_session=abc123; HttpOnly; Path=/"});
AuthClient client = new AuthClient(baseUrl(server));
AuthClient.SessionResult result = client.register("gabriel", "g@example.com", "hunter2!!");
assertEquals(7L, result.user.id);
assertEquals("gabriel", result.user.username);
assertFalse(result.user.totpEnabled);
assertEquals(List.of("auth_session=abc123; HttpOnly; Path=/"), result.cookies);
}
@Test
void loginRaisesApiErrorWithTotpRequiredOnA401AskingForACode() throws Exception {
server = fakeEndpoint("/api/login", 401, "{\"error\":\"two-factor authentication code required\",\"totp_required\":true}");
AuthClient client = new AuthClient(baseUrl(server));
AuthClient.APIError error = assertThrows(AuthClient.APIError.class, () -> client.login("gabriel", "hunter2", ""));
assertEquals(401, error.statusCode);
assertTrue(error.totpRequired);
}
@Test
void listManagedUsersMapsEveryRow() throws Exception {
server = fakeEndpoint(
"/api/admin/users",
200,
"{\"users\":[{\"id\":1,\"username\":\"a\",\"email\":\"a@x.com\",\"role\":\"admin\",\"created_at\":\"2026-01-01T00:00:00Z\"}]}");
AuthClient client = new AuthClient(baseUrl(server));
List<AuthClient.ManagedUser> users = client.listManagedUsers("token");
assertEquals(1, users.size());
assertEquals("a", users.get(0).username);
assertEquals("2026-01-01T00:00:00Z", users.get(0).createdAt);
}
@Test @Test
void validateResolvesUserOnValidSession() throws Exception { void validateResolvesUserOnValidSession() throws Exception {
server = fakeAuthGuard(200, "{\"valid\":true,\"user_id\":7,\"username\":\"gabriel\",\"role\":\"admin\"}"); server = fakeAuthGuard(200, "{\"valid\":true,\"user_id\":7,\"username\":\"gabriel\",\"role\":\"admin\"}");
@@ -128,6 +200,31 @@ class AuthClientTest {
assertEquals("user", result.role); assertEquals("user", result.role);
} }
/** Like fakeAuthGuard, but for one arbitrary path instead of the fixed /api/session/validate one. */
private static HttpServer fakeEndpoint(String path, int status, String body) throws IOException {
return fakeEndpointCapturingRequest(path, status, body, new String[0]);
}
/** Like fakeEndpoint, but also sets the given Set-Cookie header value(s) on the response. */
private static HttpServer fakeEndpointCapturingRequest(String path, int status, String body, String[] setCookies) throws IOException {
HttpServer httpServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
httpServer.createContext(path, exchange -> {
// Drain the request body so the client's write doesn't block/fail.
exchange.getRequestBody().readAllBytes();
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json");
for (String cookie : setCookies) {
exchange.getResponseHeaders().add("Set-Cookie", cookie);
}
exchange.sendResponseHeaders(status, bytes.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(bytes);
}
});
httpServer.start();
return httpServer;
}
private static HttpServer fakeAuthGuard(int status, String body) throws IOException { private static HttpServer fakeAuthGuard(int status, String body) throws IOException {
HttpServer httpServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); HttpServer httpServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
httpServer.createContext("/api/session/validate", exchange -> { httpServer.createContext("/api/session/validate", exchange -> {
+11 -1
View File
@@ -57,15 +57,25 @@ export class APIError extends Error {
export class AuthClient { export class AuthClient {
/** /**
* @param {string} baseUrl - AuthGuard's base URL (e.g. from AUTHGUARD_URL), no trailing slash required. * @param {string} baseUrl - AuthGuard's base URL (e.g. from AUTHGUARD_URL), no trailing slash required.
* May be given without a scheme (e.g. "auth.example.com" or "192.168.1.50:8080") -
* "https://" is assumed in that case, so a deployment only needs to name the
* host, not repeat the scheme; an explicit "http://" (for a plain-HTTP
* local/LAN AuthGuard) is left as-is.
* @param {{cookieName?: string, timeoutMs?: number, fetchImpl?: typeof fetch}} [options] * @param {{cookieName?: string, timeoutMs?: number, fetchImpl?: typeof fetch}} [options]
*/ */
constructor(baseUrl, options = {}) { constructor(baseUrl, options = {}) {
this.baseUrl = String(baseUrl ?? '').trim().replace(/\/+$/, ''); this.baseUrl = AuthClient._normalizeBaseUrl(baseUrl);
this.cookieName = options.cookieName ?? DEFAULT_COOKIE_NAME; this.cookieName = options.cookieName ?? DEFAULT_COOKIE_NAME;
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
this.fetchImpl = options.fetchImpl ?? fetch; this.fetchImpl = options.fetchImpl ?? fetch;
} }
static _normalizeBaseUrl(baseUrl) {
const trimmed = String(baseUrl ?? '').trim().replace(/\/+$/, '');
if (!trimmed) return trimmed;
return /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
}
// --- session validation (the original, minimal surface) ----------------- // --- session validation (the original, minimal surface) -----------------
/** /**
@@ -31,6 +31,26 @@ function recordingFetch(responses) {
return wrapped; return wrapped;
} }
test('constructor assumes https for a bare host', () => {
assert.equal(new AuthClient('auth.example.com').baseUrl, 'https://auth.example.com');
assert.equal(new AuthClient('192.168.1.50:8080').baseUrl, 'https://192.168.1.50:8080');
});
test('constructor leaves an explicit scheme alone', () => {
assert.equal(new AuthClient('http://auth.example.com').baseUrl, 'http://auth.example.com');
assert.equal(new AuthClient('https://auth.example.com').baseUrl, 'https://auth.example.com');
assert.equal(new AuthClient('HTTP://auth.example.com').baseUrl, 'HTTP://auth.example.com');
});
test('constructor strips a trailing slash before checking the scheme', () => {
assert.equal(new AuthClient('auth.example.com/').baseUrl, 'https://auth.example.com');
});
test('constructor trims whitespace and leaves an empty base URL empty', () => {
assert.equal(new AuthClient(' auth.example.com ').baseUrl, 'https://auth.example.com');
assert.equal(new AuthClient('').baseUrl, '');
});
test('validate resolves the user on a valid session', async () => { test('validate resolves the user on a valid session', async () => {
const client = new AuthClient('https://auth.example.com', { const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } }]), fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } }]),
@@ -61,6 +61,15 @@ DEFAULT_TIMEOUT = 5.0
_BEARER_PREFIX = "Bearer " _BEARER_PREFIX = "Bearer "
def _normalize_base_url(base_url: str) -> str:
trimmed = str(base_url or "").strip().rstrip("/")
if not trimmed:
return trimmed
if trimmed.lower().startswith(("http://", "https://")):
return trimmed
return f"https://{trimmed}"
class InvalidSessionError(Exception): class InvalidSessionError(Exception):
"""Raised by validate() / resolve_user() when AuthGuard reports the """Raised by validate() / resolve_user() when AuthGuard reports the
token/cookie as not currently valid (expired, unknown, or missing).""" token/cookie as not currently valid (expired, unknown, or missing)."""
@@ -170,11 +179,15 @@ class AuthClient:
timeout: float = DEFAULT_TIMEOUT, timeout: float = DEFAULT_TIMEOUT,
) -> None: ) -> None:
"""base_url is AuthGuard's base URL, e.g. "https://auth.example.com" """base_url is AuthGuard's base URL, e.g. "https://auth.example.com"
(no trailing slash required). cookie_name is the cookie (no trailing slash required). May be given without a scheme (e.g.
"auth.example.com" or "192.168.1.50:8080") -- "https://" is assumed
in that case, so a deployment only needs to name the host, not repeat
the scheme; an explicit "http://" (for a plain-HTTP local/LAN
AuthGuard) is left as-is. cookie_name is the cookie
token_from_request looks for when there is no Authorization header; token_from_request looks for when there is no Authorization header;
it must match AuthGuard's SessionCookieName. timeout is the request it must match AuthGuard's SessionCookieName. timeout is the request
timeout in seconds for the underlying blocking HTTP call.""" timeout in seconds for the underlying blocking HTTP call."""
self.base_url = str(base_url or "").strip().rstrip("/") self.base_url = _normalize_base_url(base_url)
self.cookie_name = cookie_name self.cookie_name = cookie_name
self.timeout = timeout self.timeout = timeout
@@ -49,6 +49,24 @@ def _fake_http_error(status: int, payload: dict) -> urllib.error.HTTPError:
) )
class AuthClientBaseUrlTests(unittest.TestCase):
def test_bare_host_assumes_https(self) -> None:
self.assertEqual(AuthClient("auth.example.com").base_url, "https://auth.example.com")
self.assertEqual(AuthClient("192.168.1.50:8080").base_url, "https://192.168.1.50:8080")
def test_explicit_scheme_left_alone(self) -> None:
self.assertEqual(AuthClient("http://auth.example.com").base_url, "http://auth.example.com")
self.assertEqual(AuthClient("https://auth.example.com").base_url, "https://auth.example.com")
self.assertEqual(AuthClient("HTTP://auth.example.com").base_url, "HTTP://auth.example.com")
def test_trailing_slash_stripped_before_scheme_check(self) -> None:
self.assertEqual(AuthClient("auth.example.com/").base_url, "https://auth.example.com")
def test_whitespace_trimmed_and_empty_stays_empty(self) -> None:
self.assertEqual(AuthClient(" auth.example.com ").base_url, "https://auth.example.com")
self.assertEqual(AuthClient("").base_url, "")
class AuthClientValidateTests(unittest.IsolatedAsyncioTestCase): class AuthClientValidateTests(unittest.IsolatedAsyncioTestCase):
def setUp(self) -> None: def setUp(self) -> None:
self.client = AuthClient("https://authguard.example") self.client = AuthClient("https://authguard.example")