minor code improvements
Signed-off-by: Stephan Richter <s.richter@srsoftware.de>
This commit is contained in:
@@ -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 {
|
||||
|
||||
@@ -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<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> {
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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<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) {
|
||||
|
||||
@@ -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<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 {
|
||||
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()) {
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
|
||||
@@ -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<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
|
||||
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<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
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
return empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -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<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()) {
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user