Browse Source

minor code improvements

Signed-off-by: Stephan Richter <s.richter@srsoftware.de>
sqlite
Stephan Richter 4 months ago
parent
commit
2752d80222
  1. 1
      de.srsoftware.cookies/build.gradle
  2. 4
      de.srsoftware.cookies/src/main/java/de/srsoftware/cookies/Cookie.java
  3. 1
      de.srsoftware.oidc.api/build.gradle
  4. 4
      de.srsoftware.oidc.api/src/main/java/de/srsoftware/oidc/api/Client.java
  5. 3
      de.srsoftware.oidc.api/src/main/java/de/srsoftware/oidc/api/PathHandler.java
  6. 12
      de.srsoftware.oidc.app/src/main/java/de/srsoftware/oidc/app/Application.java
  7. 4
      de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/ClientController.java
  8. 4
      de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/RotatingKeyManager.java
  9. 16
      de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/TokenController.java
  10. 2
      de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/UserController.java
  11. 25
      de.srsoftware.oidc.datastore.file/src/main/java/de/srsoftware/oidc/datastore/file/FileStore.java
  12. 3
      de.srsoftware.oidc.web/src/main/java/de/srsoftware/oidc/web/StaticPages.java
  13. 8
      de.srsoftware.utils/src/main/java/de/srsoftware/utils/Optionals.java

1
de.srsoftware.cookies/build.gradle

@ -12,6 +12,7 @@ repositories { @@ -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 {

4
de.srsoftware.cookies/src/main/java/de/srsoftware/cookies/Cookie.java

@ -1,6 +1,7 @@ @@ -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; @@ -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<String, String> {
static final System.Logger LOG = System.getLogger(SessionToken.class.getSimpleName());
@ -41,7 +41,7 @@ public abstract class Cookie implements Map.Entry<String, String> { @@ -41,7 +41,7 @@ public abstract class Cookie implements Map.Entry<String, String> {
}
protected static List<String> 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

1
de.srsoftware.oidc.api/build.gradle

@ -13,6 +13,7 @@ dependencies { @@ -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 {

4
de.srsoftware.oidc.api/src/main/java/de/srsoftware/oidc/api/Client.java

@ -1,7 +1,9 @@ @@ -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 { @@ -38,7 +40,7 @@ public final class Client {
}
public Optional nonce() {
return Optional.ofNullable(nonce);
return nullable(nonce);
}
public String secret() {

3
de.srsoftware.oidc.api/src/main/java/de/srsoftware/oidc/api/PathHandler.java

@ -2,6 +2,7 @@ @@ -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 { @@ -98,7 +99,7 @@ public abstract class PathHandler implements HttpHandler {
}
public static Optional<String> 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) {

12
de.srsoftware.oidc.app/src/main/java/de/srsoftware/oidc/app/Application.java

@ -4,11 +4,13 @@ package de.srsoftware.oidc.app; @@ -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 { @@ -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 { @@ -45,7 +47,7 @@ public class Application {
public static void main(String[] args) throws Exception {
var argMap = map(args);
Optional<Path> basePath = argMap.get(BASE_PATH) instanceof Path p ? Optional.of(p) : Optional.empty();
Optional<Path> 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 { @@ -71,8 +73,8 @@ public class Application {
var tokens = new ArrayList<>(List.of(args));
var map = new HashMap<String, Object>();
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()) {

4
de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/ClientController.java

@ -3,6 +3,7 @@ package de.srsoftware.oidc.backend; @@ -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; @@ -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 { @@ -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));
}

4
de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/RotatingKeyManager.java

@ -1,12 +1,12 @@ @@ -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 { @@ -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) {

16
de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/TokenController.java

@ -2,7 +2,7 @@ @@ -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 { @@ -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"));
}

2
de.srsoftware.oidc.backend/src/main/java/de/srsoftware/oidc/backend/UserController.java

@ -43,7 +43,7 @@ public class UserController extends Controller { @@ -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));
}

25
de.srsoftware.oidc.datastore.file/src/main/java/de/srsoftware/oidc/datastore/file/FileStore.java

@ -1,8 +1,9 @@ @@ -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; @@ -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 @@ -76,7 +75,7 @@ public class FileStore implements AuthorizationService, ClientService, SessionSe
@Override
public Optional<User> 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 @@ -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 @@ -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 @@ -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 @@ -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 @@ -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 @@ -269,11 +268,11 @@ public class FileStore implements AuthorizationService, ClientService, SessionSe
@Override
public Optional<Authorization> 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 @@ -285,7 +284,7 @@ public class FileStore implements AuthorizationService, ClientService, SessionSe
} catch (Exception ignored) {
}
return Optional.empty();
return empty();
}
@Override

3
de.srsoftware.oidc.web/src/main/java/de/srsoftware/oidc/web/StaticPages.java

@ -2,6 +2,7 @@ @@ -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 { @@ -69,7 +70,7 @@ public class StaticPages extends PathHandler {
private Optional<Response> 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()) {

8
de.srsoftware.utils/src/main/java/de/srsoftware/utils/Optionals.java

@ -2,12 +2,14 @@ @@ -2,12 +2,14 @@
package de.srsoftware.utils;
import java.util.Optional;
import static java.util.Optional.empty;
public class Optionals {
public static <T> Optional<T> optional(T val) {
public static <T> Optional<T> nullable(T val) {
return Optional.ofNullable(val);
}
public static Optional<String> nonEmpty(String text) {
return text == null || text.isBlank() ? Optional.empty() : optional(text.trim());
public static Optional<String> emptyIfBlank(String text) {
return text == null || text.isBlank() ? empty() : nullable(text.trim());
}
}

Loading…
Cancel
Save