ci: expand shared package validation and test coverage
Lint / Lint (push) Successful in 32s
Docker / Docker Build & Push (push) Failing after 2m22s
Tests / Go backend (push) Failing after 1m2s
Tests / Dashboard checks (push) Failing after 35s

- Add lint, formatting, vet, and publish workflow checks
- Run Go database tests with PostgreSQL and add Java tests
- Make consumer sync opt-in; update docs and Go dependency
This commit is contained in:
Gabriel20xx committed 2026-10-19 21:46:52 +00:00
1 parent 937f51b4fb
commit 0ff94f9b10
107 files changed
+10124 -410

No files matched your search

@@ -73,24 +73,21 @@ import java.util.regex.Pattern;
* this class can be built and tested in isolation (see this package's
* README); it targets Java 8 for the same reason.
*
* <p>{@link #validate(String)} still hand-parses AuthGuard's small, fixed
* {@code GET /api/session/validate} response shape with a few targeted
* regular expressions rather than Jackson, keeping the minimal
* validate-only surface dependency-free beyond the JDK - {@code ResetManager},
* {@code Roles}, and {@code Totp}, the other classes in this package, stay
* that way too. The full-proxy methods added below (register/login/setup/
* reset/admin-user-management) are a different tradeoff: they must both
* build and parse a handful of small JSON request/response bodies, which
* would be considerably worse hand-rolled than {@code validate}'s
* fixed-shape parsing, so they use Jackson ({@code jackson-databind})
* instead. This makes {@code jackson-databind} a compile-time dependency of
* <p>{@link #validate(String)} parses AuthGuard's {@code GET /api/session/validate}
* response with Jackson and reads top-level fields only, so a nested object
* with the same field names cannot change the decision. {@code ResetManager},
* {@code Roles}, and {@code Totp}, the other classes in this package, use only
* the JDK. The full-proxy methods added below (register/login/setup/
* reset/admin-user-management) also build and parse a handful of small JSON
* request/response bodies, which would be considerably worse hand-rolled, so
* they use Jackson ({@code jackson-databind}) too. This makes {@code jackson-databind} a compile-time dependency of
* this whole class (Java has no way to make an import conditional on which
* methods a given consumer actually calls) - acceptable here because
* MegaBasterd, this package's only verified consumer, already depends on
* Jackson for its own code. A hypothetical future consumer that only ever
* calls {@code validate}/{@code middleware} and doesn't already carry
* Jackson would need to add it just to compile this file; that tradeoff was
* chosen deliberately over hand-rolling JSON request bodies with regex.
* chosen deliberately over hand-rolling JSON with regular expressions.
*/
public final class AuthClient {
@@ -106,10 +103,6 @@ public final class AuthClient {
*/
public static final String PROJECT_KEY_HEADER = "X-Project-Key";
private static final Pattern VALID_PATTERN = Pattern.compile("\"valid\"\\s*:\\s*(true|false)");
private static final Pattern USER_ID_PATTERN = Pattern.compile("\"user_id\"\\s*:\\s*(-?\\d+)");
private static final Pattern USERNAME_PATTERN = Pattern.compile("\"username\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"");
private static final Pattern ROLE_PATTERN = Pattern.compile("\"role\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"");
private static final String BEARER_PREFIX = "Bearer ";
/** Used only by the full-proxy methods below; see the class javadoc's Jackson tradeoff note. */
@@ -279,7 +272,8 @@ public final class AuthClient {
User user;
try {
user = validate(token);
} catch (InvalidSessionException | IOException ex) {
} catch (InvalidSessionException | IOException | IllegalStateException ex) {
// IllegalStateException is a client with no base URL yet; it fails closed like Node's middleware.
return onUnauthorized.get();
}
return onAuthenticated.handle(user);
@@ -829,59 +823,43 @@ public final class AuthClient {
return buffer.toString(StandardCharsets.UTF_8.name());
}
/** Defensively hand-parses AuthGuard's small, fixed response shape - see the class javadoc for why. */
/**
* Parses AuthGuard's response with Jackson and reads top-level fields only, so a nested object
* with the same field names cannot stand in for the real answer.
*/
private static RawPayload parsePayload(String body) {
if (body == null || body.isEmpty()) {
throw new IllegalArgumentException("empty AuthGuard response body");
}
Matcher validMatcher = VALID_PATTERN.matcher(body);
if (!validMatcher.find()) {
JsonNode root;
try {
root = JSON.readTree(body);
} catch (IOException ex) {
throw new IllegalArgumentException("AuthGuard response is not JSON: " + ex.getMessage(), ex);
}
if (root == null || !root.isObject()) {
throw new IllegalArgumentException("AuthGuard response is not a JSON object");
}
JsonNode validNode = root.get("valid");
if (validNode == null || !validNode.isBoolean()) {
throw new IllegalArgumentException("missing \"valid\" field in AuthGuard response");
}
boolean valid = Boolean.parseBoolean(validMatcher.group(1));
long userId = 0L;
Matcher userIdMatcher = USER_ID_PATTERN.matcher(body);
if (userIdMatcher.find()) {
userId = Long.parseLong(userIdMatcher.group(1));
JsonNode userIdNode = root.get("user_id");
if (userIdNode != null && userIdNode.isIntegralNumber()) {
if (!userIdNode.canConvertToLong()) {
throw new IllegalArgumentException("user_id is out of range in AuthGuard response");
}
userId = userIdNode.longValue();
}
return new RawPayload(valid, userId, extractString(USERNAME_PATTERN, body), extractString(ROLE_PATTERN, body));
return new RawPayload(validNode.booleanValue(), userId, textualField(root, "username"), textualField(root, "role"));
}
private static String extractString(Pattern pattern, String body) {
Matcher matcher = pattern.matcher(body);
return matcher.find() ? unescapeJson(matcher.group(1)) : "";
}
private static String unescapeJson(String raw) {
StringBuilder result = new StringBuilder(raw.length());
for (int index = 0; index < raw.length(); index++) {
char current = raw.charAt(index);
if (current != '\\' || index + 1 >= raw.length()) {
result.append(current);
continue;
}
char next = raw.charAt(++index);
switch (next) {
case '"': result.append('"'); break;
case '\\': result.append('\\'); break;
case '/': result.append('/'); break;
case 'n': result.append('\n'); break;
case 't': result.append('\t'); break;
case 'r': result.append('\r'); break;
case 'b': result.append('\b'); break;
case 'f': result.append('\f'); break;
case 'u':
if (index + 4 < raw.length()) {
result.append((char) Integer.parseInt(raw.substring(index + 1, index + 5), 16));
index += 4;
}
break;
default: result.append(next);
}
}
return result.toString();
private static String textualField(JsonNode root, String name) {
JsonNode node = root.get(name);
return node != null && node.isTextual() ? node.textValue() : "";
}
private static final class RawPayload {
@@ -2,6 +2,7 @@ package com.gabriel20xx.shared.auth;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Locale;
import javax.crypto.Mac;
@@ -77,7 +78,8 @@ public final class Totp {
| ((hash[index + 2] & 0xff) << 8)
| (hash[index + 3] & 0xff);
String candidate = String.format(Locale.ROOT, "%06d", code % 1_000_000);
if (candidate.equals(normalizedToken)) {
if (MessageDigest.isEqual(candidate.getBytes(StandardCharsets.US_ASCII),
normalizedToken.getBytes(StandardCharsets.US_ASCII))) {
return true;
}
} catch (Exception ex) {
@@ -278,6 +278,54 @@ class AuthClientTest {
assertEquals("user", result.role);
}
@Test
void validateReadsTopLevelFieldsOnlyWhenNestedFieldsRepeatThem() throws Exception {
// The nested object says valid:true, but the top-level answer is valid:false, so the session is invalid.
server = fakeAuthGuard(200, "{\"session\":{\"valid\":true,\"user_id\":99,\"username\":\"evil\",\"role\":\"admin\"},\"valid\":false}");
AuthClient client = new AuthClient(baseUrl(server));
assertThrows(InvalidSessionException.class, () -> client.validate("token"));
}
@Test
void validateIgnoresANestedValidFieldWhenTheTopLevelOneIsMissing() throws Exception {
server = fakeAuthGuard(200, "{\"data\":{\"valid\":true,\"user_id\":5,\"username\":\"x\",\"role\":\"admin\"}}");
AuthClient client = new AuthClient(baseUrl(server));
assertThrows(IOException.class, () -> client.validate("token"));
}
@Test
void validateAcceptsReorderedTopLevelFields() throws Exception {
server = fakeAuthGuard(200, "{\"username\":\"gabriel\",\"role\":\"admin\",\"user_id\":7,\"valid\":true}");
AuthClient client = new AuthClient(baseUrl(server));
AuthClient.User user = client.validate("token");
assertEquals(7L, user.id);
assertEquals("gabriel", user.username);
assertEquals("admin", user.role);
}
@Test
void validateDecodesEscapedUsernames() throws Exception {
server = fakeAuthGuard(200, "{\"valid\":true,\"user_id\":3,\"username\":\"a\\\"b\\u00e9\",\"role\":\"user\"}");
AuthClient client = new AuthClient(baseUrl(server));
assertEquals("a\"b\u00e9", client.validate("token").username);
}
@Test
void middlewareFailsClosedOnAClientWithNoBaseUrlYet() throws Exception {
AuthClient client = new AuthClient("");
Function<String, String> headerLookup = name -> "Authorization".equals(name) ? "Bearer some-token" : null;
String result = client.middleware(headerLookup, null,
user -> "authenticated", () -> "unauthorized");
assertEquals("unauthorized", result);
}
/** 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]);
@@ -0,0 +1,76 @@
package com.gabriel20xx.shared.auth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.jupiter.api.Test;
class ResetManagerTest {
@Test
void requestReturnsAnEightDigitHexCodeAndPrintsIt() {
ResetManager manager = new ResetManager();
PrintStream original = System.out;
ByteArrayOutputStream captured = new ByteArrayOutputStream();
System.setOut(new PrintStream(captured));
String code;
try {
code = manager.request();
} finally {
System.setOut(original);
}
assertTrue(code.matches("[0-9A-F]{8}"));
assertTrue(captured.toString().contains("ADMIN RESET CODE: " + code));
}
@Test
void confirmAcceptsTheCodeOnceAndTrimsAndCase() {
ResetManager manager = new ResetManager();
String code = quietRequest(manager);
assertFalse(manager.confirm(null));
assertTrue(manager.confirm(" " + code.toLowerCase() + " "));
assertFalse(manager.confirm(code));
}
@Test
void confirmRejectsAWrongCodeButKeepsTheCodeRetryable() {
ResetManager manager = new ResetManager();
String code = quietRequest(manager);
String wrong = code.charAt(0) == '0' ? "1" + code.substring(1) : "0" + code.substring(1);
assertFalse(manager.confirm(wrong));
assertTrue(manager.confirm(code));
}
@Test
void confirmFailsWithoutARequestedCode() {
assertFalse(new ResetManager().confirm("00000000"));
}
@Test
void aNewRequestInvalidatesThePreviousCode() {
ResetManager manager = new ResetManager();
String first = quietRequest(manager);
String second = quietRequest(manager);
if (!first.equals(second)) {
assertFalse(manager.confirm(first));
}
assertTrue(manager.confirm(second));
}
private static String quietRequest(ResetManager manager) {
PrintStream original = System.out;
System.setOut(new PrintStream(new ByteArrayOutputStream()));
try {
return manager.request();
} finally {
System.setOut(original);
}
}
}
@@ -0,0 +1,36 @@
package com.gabriel20xx.shared.auth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class RolesTest {
@Test
void normalizeIsCaseInsensitiveAndDefaultsToUser() {
assertEquals(Roles.SUPERADMIN, Roles.normalize(" SuperAdmin "));
assertEquals(Roles.ADMIN, Roles.normalize("ADMIN"));
assertEquals(Roles.USER, Roles.normalize("moderator"));
assertEquals(Roles.USER, Roles.normalize(""));
assertEquals(Roles.USER, Roles.normalize(null));
}
@Test
void onlyAdminRolesCanManageUsers() {
assertTrue(Roles.canManageUsers(Roles.SUPERADMIN));
assertTrue(Roles.canManageUsers(Roles.ADMIN));
assertFalse(Roles.canManageUsers(Roles.USER));
assertFalse(Roles.canManageUsers("moderator"));
}
@Test
void onlySuperadminCanAssignNonSuperadminRoles() {
assertTrue(Roles.canAssignRole(Roles.SUPERADMIN, Roles.ADMIN));
assertTrue(Roles.canAssignRole(Roles.SUPERADMIN, Roles.USER));
assertFalse(Roles.canAssignRole(Roles.SUPERADMIN, Roles.SUPERADMIN));
assertFalse(Roles.canAssignRole(Roles.ADMIN, Roles.USER));
assertFalse(Roles.canAssignRole(Roles.USER, Roles.USER));
}
}
@@ -0,0 +1,76 @@
package com.gabriel20xx.shared.auth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class TotpTest {
// RFC 6238 SHA-1 test secret "12345678901234567890", base32-encoded.
private static final String RFC_SECRET = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";
@Test
void verifyAcceptsTheRfc6238Vectors() {
// The RFC lists 8-digit codes; these are their last six digits.
assertTrue(Totp.verify(RFC_SECRET, "287082", 59_000L));
assertTrue(Totp.verify(RFC_SECRET, "081804", 1_111_111_109_000L));
assertTrue(Totp.verify(RFC_SECRET, "050471", 1_111_111_111_000L));
assertTrue(Totp.verify(RFC_SECRET, "005924", 1_234_567_890_000L));
assertTrue(Totp.verify(RFC_SECRET, "279037", 2_000_000_000_000L));
}
@Test
void verifyAcceptsOneStepEitherSideOfTheCurrentTime() {
// At t=59 the counter is 1. Counter 0 (t=0) and counter 2 (t=60) are inside the window.
assertTrue(Totp.verify(RFC_SECRET, "755224", 59_000L));
assertTrue(Totp.verify(RFC_SECRET, "359152", 59_000L));
}
@Test
void verifyRejectsCodesOutsideTheWindow() {
// Counter 3 (t=90) is two steps ahead of counter 1; 2 steps behind would need a negative counter.
assertFalse(Totp.verify(RFC_SECRET, "969429", 59_000L));
}
@Test
void verifyRejectsMalformedInput() {
assertFalse(Totp.verify(RFC_SECRET, null, 59_000L));
assertFalse(Totp.verify(RFC_SECRET, "", 59_000L));
assertFalse(Totp.verify(RFC_SECRET, "28708", 59_000L));
assertFalse(Totp.verify(RFC_SECRET, "28708a", 59_000L));
assertFalse(Totp.verify(RFC_SECRET, "2870821", 59_000L));
assertFalse(Totp.verify("", "287082", 59_000L));
assertFalse(Totp.verify(null, "287082", 59_000L));
assertFalse(Totp.verify("not base32!", "287082", 59_000L));
}
@Test
void verifyTrimsWhitespaceAroundTheCode() {
assertTrue(Totp.verify(RFC_SECRET, " 287082 ", 59_000L));
}
@Test
void verifyAcceptsASecretWithSpacesAndPadding() {
String spaced = "GEZD GNBV GY3T QOJQ GEZD GNBV GY3T QOJQ====";
assertTrue(Totp.verify(spaced, "287082", 59_000L));
}
@Test
void generatedSecretsAreBase32OfTheExpectedLength() {
String first = Totp.generateSecret();
String second = Totp.generateSecret();
assertEquals(32, first.length());
assertTrue(first.matches("[A-Z2-7]+"));
assertFalse(first.equals(second));
}
@Test
void provisioningUriCarriesTheSecretAndParameters() {
String uri = Totp.provisioningUri("Shared App", "gabriel", RFC_SECRET);
assertTrue(uri.startsWith("otpauth://totp/Shared%20App%3Agabriel?secret=" + RFC_SECRET));
assertTrue(uri.contains("&issuer=Shared%20App"));
assertTrue(uri.endsWith("&algorithm=SHA1&digits=6&period=30"));
}
}