diff --git a/de.srsoftware.cookies/build.gradle b/de.srsoftware.cookies/build.gradle index a55b584..f2eceda 100644 --- a/de.srsoftware.cookies/build.gradle +++ b/de.srsoftware.cookies/build.gradle @@ -12,6 +12,7 @@ repositories { dependencies { testImplementation platform('org.junit:junit-bom:5.10.0') testImplementation 'org.junit.jupiter:junit-jupiter' + implementation project(':de.srsoftware.utils') } test { diff --git a/de.srsoftware.cookies/src/main/java/de/srsoftware/cookies/Cookie.java b/de.srsoftware.cookies/src/main/java/de/srsoftware/cookies/Cookie.java index 638e919..2c42e62 100644 --- a/de.srsoftware.cookies/src/main/java/de/srsoftware/cookies/Cookie.java +++ b/de.srsoftware.cookies/src/main/java/de/srsoftware/cookies/Cookie.java @@ -1,6 +1,7 @@ /* © SRSoftware 2024 */ package de.srsoftware.cookies; +import static de.srsoftware.utils.Optionals.nullable; import static java.lang.System.Logger.Level.*; import com.sun.net.httpserver.Headers; @@ -8,7 +9,6 @@ import com.sun.net.httpserver.HttpExchange; import java.util.Arrays; import java.util.List; import java.util.Map; -import java.util.Optional; public abstract class Cookie implements Map.Entry { static final System.Logger LOG = System.getLogger(SessionToken.class.getSimpleName()); @@ -41,7 +41,7 @@ public abstract class Cookie implements Map.Entry { } protected static List of(HttpExchange ex) { - return Optional.ofNullable(ex.getRequestHeaders().get("Cookie")).stream().flatMap(List::stream).flatMap(s -> Arrays.stream(s.split(";"))).map(String::trim).peek(cookie -> LOG.log(INFO, "received cookie {0}", cookie)).toList(); + return nullable(ex.getRequestHeaders().get("Cookie")).stream().flatMap(List::stream).flatMap(s -> Arrays.stream(s.split(";"))).map(String::trim).peek(cookie -> LOG.log(INFO, "received cookie {0}", cookie)).toList(); } @Override diff --git a/de.srsoftware.oidc.api/build.gradle b/de.srsoftware.oidc.api/build.gradle index 83f182c..7c9aa20 100644 --- a/de.srsoftware.oidc.api/build.gradle +++ b/de.srsoftware.oidc.api/build.gradle @@ -13,6 +13,7 @@ dependencies { testImplementation 'org.junit.jupiter:junit-jupiter' implementation 'org.json:json:20240303' implementation 'org.bitbucket.b_c:jose4j:0.9.6' + implementation project(':de.srsoftware.utils') } test { diff --git a/de.srsoftware.oidc.api/src/main/java/de/srsoftware/oidc/api/Client.java b/de.srsoftware.oidc.api/src/main/java/de/srsoftware/oidc/api/Client.java index bf0ec1d..ef38b6a 100644 --- a/de.srsoftware.oidc.api/src/main/java/de/srsoftware/oidc/api/Client.java +++ b/de.srsoftware.oidc.api/src/main/java/de/srsoftware/oidc/api/Client.java @@ -1,7 +1,9 @@ /* © SRSoftware 2024 */ package de.srsoftware.oidc.api; + import static de.srsoftware.oidc.api.Constants.*; +import static de.srsoftware.utils.Optionals.nullable; import java.util.*; @@ -38,7 +40,7 @@ public final class Client { } public Optional nonce() { - return Optional.ofNullable(nonce); + return nullable(nonce); } public String secret() { diff --git a/de.srsoftware.oidc.api/src/main/java/de/srsoftware/oidc/api/PathHandler.java b/de.srsoftware.oidc.api/src/main/java/de/srsoftware/oidc/api/PathHandler.java index 7ee0688..5f6c042 100644 --- a/de.srsoftware.oidc.api/src/main/java/de/srsoftware/oidc/api/PathHandler.java +++ b/de.srsoftware.oidc.api/src/main/java/de/srsoftware/oidc/api/PathHandler.java @@ -2,6 +2,7 @@ package de.srsoftware.oidc.api; import static de.srsoftware.oidc.api.Constants.AUTHORIZATION; +import static de.srsoftware.utils.Optionals.nullable; import static java.lang.System.Logger.Level.*; import static java.net.HttpURLConnection.*; import static java.nio.charset.StandardCharsets.UTF_8; @@ -98,7 +99,7 @@ public abstract class PathHandler implements HttpHandler { } public static Optional getHeader(HttpExchange ex, String key) { - return Optional.ofNullable(ex.getRequestHeaders().get(key)).map(List::stream).flatMap(Stream::findFirst); + return nullable(ex.getRequestHeaders().get(key)).map(List::stream).flatMap(Stream::findFirst); } public static String hostname(HttpExchange ex) { diff --git a/de.srsoftware.oidc.app/src/main/java/de/srsoftware/oidc/app/Application.java b/de.srsoftware.oidc.app/src/main/java/de/srsoftware/oidc/app/Application.java index fe6d6c4..7254545 100644 --- a/de.srsoftware.oidc.app/src/main/java/de/srsoftware/oidc/app/Application.java +++ b/de.srsoftware.oidc.app/src/main/java/de/srsoftware/oidc/app/Application.java @@ -4,11 +4,13 @@ package de.srsoftware.oidc.app; import static de.srsoftware.oidc.api.Constants.*; import static de.srsoftware.oidc.api.Permission.MANAGE_CLIENTS; -import static de.srsoftware.utils.Optionals.nonEmpty; +import static de.srsoftware.utils.Optionals.emptyIfBlank; import static de.srsoftware.utils.Paths.configDir; +import static de.srsoftware.utils.Strings.uuid; import static java.lang.System.Logger.Level.DEBUG; import static java.lang.System.Logger.Level.ERROR; import static java.lang.System.getenv; +import static java.util.Optional.empty; import com.sun.net.httpserver.HttpServer; import de.srsoftware.logging.ColorLogger; @@ -32,7 +34,7 @@ public class Application { public static final String API_USER = "/api/user"; public static final String FIRST_USER = "admin"; public static final String FIRST_USER_PASS = "admin"; - public static final String FIRST_UUID = UUID.randomUUID().toString(); + public static final String FIRST_UUID = uuid(); public static final String JWKS = "/api/jwks.json"; public static final String ROOT = "/"; public static final String STATIC_PATH = "/web"; @@ -45,7 +47,7 @@ public class Application { public static void main(String[] args) throws Exception { var argMap = map(args); - Optional basePath = argMap.get(BASE_PATH) instanceof Path p ? Optional.of(p) : Optional.empty(); + Optional basePath = argMap.get(BASE_PATH) instanceof Path p ? Optional.of(p) : empty(); var storageFile = (argMap.get(CONFIG_PATH) instanceof Path p ? p : configDir(APP_NAME).resolve("config.json")).toFile(); var keyDir = storageFile.getParentFile().toPath().resolve("keys"); var passwordHasher = new UuidHasher(); @@ -71,8 +73,8 @@ public class Application { var tokens = new ArrayList<>(List.of(args)); var map = new HashMap(); - nonEmpty(getenv(BASE_PATH)).map(Path::of).ifPresent(path -> map.put(BASE_PATH, path)); - nonEmpty(getenv(CONFIG_PATH)).map(Path::of).ifPresent(path -> map.put(CONFIG_PATH, path)); + emptyIfBlank(getenv(BASE_PATH)).map(Path::of).ifPresent(path -> map.put(BASE_PATH, path)); + emptyIfBlank(getenv(CONFIG_PATH)).map(Path::of).ifPresent(path -> map.put(CONFIG_PATH, path)); // Command line arguments override environment while (!tokens.isEmpty()) { diff --git a/de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/ClientController.java b/de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/ClientController.java index cfa93ea..e79f78e 100644 --- a/de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/ClientController.java +++ b/de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/ClientController.java @@ -3,6 +3,7 @@ package de.srsoftware.oidc.backend; import static de.srsoftware.oidc.api.Constants.*; import static de.srsoftware.oidc.api.Permission.MANAGE_CLIENTS; +import static de.srsoftware.utils.Strings.uuid; import static java.lang.System.Logger.Level.ERROR; import static java.net.HttpURLConnection.*; @@ -14,7 +15,6 @@ import java.time.Instant; import java.util.Arrays; import java.util.HashSet; import java.util.Map; -import java.util.UUID; import org.json.JSONObject; public class ClientController extends Controller { @@ -54,7 +54,7 @@ public class ClientController extends Controller { } } var state = json.getString(STATE); - var code = UUID.randomUUID().toString(); + var code = uuid(); authorizations.addCode(client, session.user(), code); return sendContent(ex, Map.of(CONFIRMED, true, CODE, code, REDIRECT_URI, redirect, STATE, state)); } diff --git a/de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/RotatingKeyManager.java b/de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/RotatingKeyManager.java index b5ff0da..fffe5df 100644 --- a/de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/RotatingKeyManager.java +++ b/de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/RotatingKeyManager.java @@ -1,12 +1,12 @@ /* © SRSoftware 2024 */ package de.srsoftware.oidc.backend; +import static de.srsoftware.utils.Strings.uuid; import static org.jose4j.jws.AlgorithmIdentifiers.RSA_USING_SHA256; import de.srsoftware.oidc.api.KeyManager; import de.srsoftware.oidc.api.KeyStorage; import java.io.IOException; -import java.util.UUID; import org.jose4j.jwk.PublicJsonWebKey; import org.jose4j.jwk.RsaJwkGenerator; import org.jose4j.lang.JoseException; @@ -29,7 +29,7 @@ public class RotatingKeyManager implements KeyManager { try { var key = RsaJwkGenerator.generateJwk(2048); key.setAlgorithm(RSA_USING_SHA256); - key.setKeyId(UUID.randomUUID().toString()); + key.setKeyId(uuid()); store.store(key); return key; } catch (JoseException e) { diff --git a/de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/TokenController.java b/de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/TokenController.java index b504472..b6554b9 100644 --- a/de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/TokenController.java +++ b/de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/TokenController.java @@ -2,7 +2,7 @@ package de.srsoftware.oidc.backend; import static de.srsoftware.oidc.api.Constants.*; -import static de.srsoftware.utils.Optionals.optional; +import static de.srsoftware.utils.Optionals.nullable; import static java.lang.System.Logger.Level.*; import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; @@ -71,19 +71,7 @@ public class TokenController extends PathHandler { if (!client.redirectUris().contains(uri)) sendContent(ex, HTTP_BAD_REQUEST, Map.of(ERROR, "unknown redirect uri", REDIRECT_URI, uri)); if (client.secret() != null) { - String clientSecret = optional(ex.getRequestHeaders().get(AUTHORIZATION)) - .map(list -> list.get(0)) - .filter(s -> s.startsWith("Basic ")) - .map(s -> s.substring(6)) - .map(s -> Base64.getDecoder().decode(s)) - .map(bytes -> new String(bytes, StandardCharsets.UTF_8)) - .filter(s -> s.startsWith("%s:".formatted(client.id()))) - .map(s -> s.substring(client.id().length() + 1).trim()) - .map(s -> { - System.err.println(s); - return s; - }) - .orElseGet(() -> map.get(CLIENT_SECRET)); + String clientSecret = nullable(ex.getRequestHeaders().get(AUTHORIZATION)).map(list -> list.get(0)).filter(s -> s.startsWith("Basic ")).map(s -> s.substring(6)).map(s -> Base64.getDecoder().decode(s)).map(bytes -> new String(bytes, StandardCharsets.UTF_8)).filter(s -> s.startsWith("%s:".formatted(client.id()))).map(s -> s.substring(client.id().length() + 1).trim()).orElseGet(() -> map.get(CLIENT_SECRET)); if (clientSecret == null) return sendContent(ex, HTTP_BAD_REQUEST, Map.of(ERROR, "client secret missing")); if (!client.secret().equals(clientSecret)) return sendContent(ex, HTTP_BAD_REQUEST, Map.of(ERROR, "client secret mismatch")); } diff --git a/de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/UserController.java b/de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/UserController.java index e181f64..ec4f15c 100644 --- a/de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/UserController.java +++ b/de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/UserController.java @@ -43,7 +43,7 @@ public class UserController extends Controller { var optUser = getBearer(ex).flatMap(users::forToken); if (optUser.isEmpty()) return sendEmptyResponse(HTTP_UNAUTHORIZED, ex); var user = optUser.get(); - var map = Map.of("sub",user.uuid(),"email",user.email()); + var map = Map.of("sub", user.uuid(), "email", user.email()); return sendContent(ex, new JSONObject(map)); } diff --git a/de.srsoftware.oidc.datastore.file/src/main/java/de/srsoftware/oidc/datastore/file/FileStore.java b/de.srsoftware.oidc.datastore.file/src/main/java/de/srsoftware/oidc/datastore/file/FileStore.java index f5a5902..d41b348 100644 --- a/de.srsoftware.oidc.datastore.file/src/main/java/de/srsoftware/oidc/datastore/file/FileStore.java +++ b/de.srsoftware.oidc.datastore.file/src/main/java/de/srsoftware/oidc/datastore/file/FileStore.java @@ -1,8 +1,9 @@ /* © SRSoftware 2024 */ package de.srsoftware.oidc.datastore.file; /* © SRSoftware 2024 */ import static de.srsoftware.oidc.api.User.*; -import static de.srsoftware.utils.Optionals.optional; +import static de.srsoftware.utils.Optionals.nullable; import static de.srsoftware.utils.Strings.uuid; +import static java.util.Optional.empty; import de.srsoftware.oidc.api.*; import java.io.File; @@ -14,8 +15,6 @@ import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.*; - -import de.srsoftware.utils.Optionals; import org.json.JSONObject; public class FileStore implements AuthorizationService, ClientService, SessionService, UserService { @@ -76,7 +75,7 @@ public class FileStore implements AuthorizationService, ClientService, SessionSe @Override public Optional forToken(String accessToken) { - return optional(accessTokens.get(accessToken)); + return nullable(accessTokens.get(accessToken)); } @Override @@ -103,7 +102,7 @@ public class FileStore implements AuthorizationService, ClientService, SessionSe return userOf(userData, userId); } catch (Exception ignored) { } - return Optional.empty(); + return empty(); } @Override @@ -119,9 +118,9 @@ public class FileStore implements AuthorizationService, ClientService, SessionSe return userOf(userData, userId); } } - return Optional.empty(); + return empty(); } catch (Exception e) { - return Optional.empty(); + return empty(); } } @@ -175,7 +174,7 @@ public class FileStore implements AuthorizationService, ClientService, SessionSe public Session createSession(User user) { var now = Instant.now(); var endOfSession = now.plus(sessionDuration); - return save(new Session(user, endOfSession, java.util.UUID.randomUUID().toString())); + return save(new Session(user, endOfSession, uuid().toString())); } @Override @@ -203,7 +202,7 @@ public class FileStore implements AuthorizationService, ClientService, SessionSe dropSession(sessionId); } catch (Exception ignored) { } - return Optional.empty(); + return empty(); } private Session save(Session session) { @@ -229,7 +228,7 @@ public class FileStore implements AuthorizationService, ClientService, SessionSe clients.put(clientId, client); return Optional.of(client); } - return Optional.empty(); + return empty(); } @@ -269,11 +268,11 @@ public class FileStore implements AuthorizationService, ClientService, SessionSe @Override public Optional forCode(String code) { var authorizations = json.getJSONObject(AUTHORIZATIONS); - if (!authorizations.has(code)) return Optional.empty(); + if (!authorizations.has(code)) return empty(); String authId = authorizations.getString(code); if (!authorizations.has(authId)) { authorizations.remove(code); - return Optional.empty(); + return empty(); } try { var expiration = Instant.ofEpochSecond(authorizations.getLong(authId)); @@ -285,7 +284,7 @@ public class FileStore implements AuthorizationService, ClientService, SessionSe } catch (Exception ignored) { } - return Optional.empty(); + return empty(); } @Override diff --git a/de.srsoftware.oidc.web/src/main/java/de/srsoftware/oidc/web/StaticPages.java b/de.srsoftware.oidc.web/src/main/java/de/srsoftware/oidc/web/StaticPages.java index fc6d895..47851bb 100644 --- a/de.srsoftware.oidc.web/src/main/java/de/srsoftware/oidc/web/StaticPages.java +++ b/de.srsoftware.oidc.web/src/main/java/de/srsoftware/oidc/web/StaticPages.java @@ -2,6 +2,7 @@ package de.srsoftware.oidc.web; import static java.lang.System.Logger.Level.*; +import static java.util.Optional.empty; import com.sun.net.httpserver.HttpExchange; import de.srsoftware.oidc.api.PathHandler; @@ -69,7 +70,7 @@ public class StaticPages extends PathHandler { private Optional loadFile(String language, String path) { try { var resource = base.map(b -> getLocalUrl(b, language, path)).orElseGet(() -> getResource(language, path)); - if (resource == null) return Optional.empty(); + if (resource == null) return empty(); var connection = resource.openConnection(); var contentType = connection.getContentType(); try (var in = connection.getInputStream()) { diff --git a/de.srsoftware.utils/src/main/java/de/srsoftware/utils/Optionals.java b/de.srsoftware.utils/src/main/java/de/srsoftware/utils/Optionals.java index 255366d..5c208d4 100644 --- a/de.srsoftware.utils/src/main/java/de/srsoftware/utils/Optionals.java +++ b/de.srsoftware.utils/src/main/java/de/srsoftware/utils/Optionals.java @@ -2,12 +2,14 @@ package de.srsoftware.utils; import java.util.Optional; +import static java.util.Optional.empty; + public class Optionals { - public static Optional optional(T val) { + public static Optional nullable(T val) { return Optional.ofNullable(val); } - public static Optional nonEmpty(String text) { - return text == null || text.isBlank() ? Optional.empty() : optional(text.trim()); + public static Optional emptyIfBlank(String text) { + return text == null || text.isBlank() ? empty() : nullable(text.trim()); } }