Skip to content

Commit

Permalink
Merge branch 'master' into snyk-upgrade-d1d2426be27da606eef8d0f2528b3949
Browse files Browse the repository at this point in the history
  • Loading branch information
rrayst authored Oct 7, 2024
2 parents 6933369 + f7e2c9a commit f590104
Show file tree
Hide file tree
Showing 20 changed files with 188 additions and 54 deletions.
2 changes: 1 addition & 1 deletion core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-exporter-otlp</artifactId>
<version>1.41.0</version>
<version>1.42.0</version>
</dependency>
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ private Outcome respondWithTokenAndRedirect(Exchange exc, String token, String t

public String generateAccessToken(Client client) {
synchronized (session) {
String token = authServer.getTokenGenerator().getToken(session.getUserName(), client.getClientId(), client.getClientSecret());
String token = authServer.getTokenGenerator().getToken(session.getUserName(), client.getClientId(), client.getClientSecret(), null);
authServer.getSessionFinder().addSessionForToken(token,session);
return token;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

package com.predic8.membrane.core.interceptor.oauth2.request;

import com.google.common.collect.ImmutableMap;
import com.predic8.membrane.core.exchange.Exchange;
import com.predic8.membrane.core.http.Header;
import com.predic8.membrane.core.http.Response;
Expand Down Expand Up @@ -138,12 +139,30 @@ protected boolean verifyClientThroughParams(){
}
}

protected String createTokenForVerifiedUserAndClient(){
return authServer.getTokenGenerator().getToken(getUsername(), getClientId(), getClientSecret());
protected String createTokenForVerifiedUserAndClient(Map<String, String> userParams){
return authServer.getTokenGenerator().getToken(getUsername(), getClientId(), getClientSecret(), claimsMap(userParams));
}

protected Map<String, Object> claimsMap(Map<String, String> userParams) {
if (userParams.containsKey("aud"))
return ImmutableMap.of("aud", userParams.get("aud").split(" "));
return ImmutableMap.of();
}

protected Map<String, Object> claimsMapForRefresh(Map<String, String> userParams) {
if (userParams.containsKey("aud"))
return ImmutableMap.of("i-aud", userParams.get("aud").split(" "));
return ImmutableMap.of();
}

protected Map<String, Object> claimsMapFromRefresh(Map<String, Object> refreshClaims) {
if (refreshClaims.containsKey("i-aud"))
return ImmutableMap.of("aud", refreshClaims.get("i-aud"));
return ImmutableMap.of();
}

protected String createTokenForVerifiedClient(){
return authServer.getTokenGenerator().getToken(getClientId(), getClientId(), getClientSecret());
return authServer.getTokenGenerator().getToken(getClientId(), getClientId(), getClientSecret(), null);
}

public String getPrompt() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,11 @@ protected Response processWithParameters() throws Exception {
}

scope = getScope(session);
token = authServer.getTokenGenerator().getToken(username, client.getClientId(), client.getClientSecret());
token = authServer.getTokenGenerator().getToken(username, client.getClientId(), client.getClientSecret(), null);
expiration = authServer.getTokenGenerator().getExpiration();
authServer.getSessionFinder().addSessionForToken(token,session);

refreshToken = authServer.getRefreshTokenGenerator().getToken(username, client.getClientId(), client.getClientSecret());
refreshToken = authServer.getRefreshTokenGenerator().getToken(username, client.getClientId(), client.getClientSecret(), null);
authServer.getSessionFinder().addSessionForRefreshToken(refreshToken, session);
if (OAuth2Util.isOpenIdScope(scope)) {
idToken = createSignedIdToken(session, username, client);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ protected Response processWithParameters() throws Exception {
authServer.getSessionFinder().addSessionForToken(token,session);

if (authServer.isIssueNonSpecRefreshTokens()) {
refreshToken = authServer.getRefreshTokenGenerator().getToken(client.getClientId(), client.getClientId(), client.getClientSecret());
refreshToken = authServer.getRefreshTokenGenerator().getToken(client.getClientId(), client.getClientId(), client.getClientSecret(), null);
authServer.getSessionFinder().addSessionForRefreshToken(refreshToken, session);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ protected Response processWithParameters() throws Exception {
return OAuth2Util.createParameterizedJsonErrorResponse(exc,jsonGen,"error","access_denied");

scope = getScope();
token = createTokenForVerifiedUserAndClient();
token = createTokenForVerifiedUserAndClient(userParams);
expiration = authServer.getTokenGenerator().getExpiration();
refreshToken = authServer.getRefreshTokenGenerator().getToken(getUsername(), getClientId(), getClientSecret());
refreshToken = authServer.getRefreshTokenGenerator().getToken(getUsername(), getClientId(), getClientSecret(), claimsMapForRefresh(userParams));

SessionManager.Session session = createSessionForAuthorizedUserWithParams();
synchronized(session) {
Expand All @@ -78,7 +78,7 @@ protected Response processWithParameters() throws Exception {
return OAuth2Util.createParameterizedJsonErrorResponse(exc, jsonGen, "error", "invalid_grant_type");
}

refreshToken = authServer.getRefreshTokenGenerator().getToken(client.getClientId(), client.getClientId(), client.getClientSecret());
refreshToken = authServer.getRefreshTokenGenerator().getToken(client.getClientId(), client.getClientId(), client.getClientSecret(), claimsMapForRefresh(userParams));
authServer.getSessionFinder().addSessionForRefreshToken(refreshToken, session);

if (authServer.isIssueNonSpecIdTokens() && OAuth2Util.isOpenIdScope(scope)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import com.predic8.membrane.core.interceptor.oauth2.tokengenerators.JwtGenerator;

import java.util.ArrayList;
import java.util.Map;
import java.util.NoSuchElementException;

import org.jose4j.lang.JoseException;
Expand All @@ -49,8 +50,10 @@ protected Response processWithParameters() throws Exception {
return OAuth2Util.createParameterizedJsonErrorResponse(exc,jsonGen,"error","unauthorized_client");

String username;
Map<String, Object> additionalClaims;
try {
username = authServer.getRefreshTokenGenerator().getUsername(getRefreshToken());
additionalClaims = authServer.getRefreshTokenGenerator().getAdditionalClaims(getRefreshToken());
}catch(NoSuchElementException ex){
return OAuth2Util.createParameterizedJsonErrorResponse(exc, jsonGen,"error", "invalid_request");
}
Expand Down Expand Up @@ -81,9 +84,9 @@ protected Response processWithParameters() throws Exception {
}

scope = getScope();
token = authServer.getTokenGenerator().getToken(getUsername(),getClientId(),getClientSecret());
token = authServer.getTokenGenerator().getToken(getUsername(),getClientId(),getClientSecret(), claimsMapFromRefresh(additionalClaims));
expiration = authServer.getTokenGenerator().getExpiration();
refreshToken = authServer.getRefreshTokenGenerator().getToken(getUsername(), getClientId(), getClientSecret());
refreshToken = authServer.getRefreshTokenGenerator().getToken(getUsername(), getClientId(), getClientSecret(), additionalClaims);

SessionManager.Session session = authServer.getSessionFinder().getSessionForRefreshToken(getRefreshToken());
synchronized(session) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import com.predic8.membrane.annot.MCAttribute;
import com.predic8.membrane.annot.MCChildElement;
import com.predic8.membrane.annot.MCElement;
import com.predic8.membrane.annot.MCTextContent;
import com.predic8.membrane.core.Router;
import com.predic8.membrane.core.config.security.Blob;
import com.predic8.membrane.core.interceptor.session.JwtSessionManager;
Expand All @@ -38,6 +37,9 @@
import java.security.SecureRandom;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toUnmodifiableMap;

@MCElement(name = "bearerJwtToken")
public class BearerJwtTokenGenerator implements TokenGenerator {
Expand Down Expand Up @@ -76,12 +78,14 @@ public String getTokenType() {
}

@Override
public String getToken(String username, String clientId, String clientSecret) {
public String getToken(String username, String clientId, String clientSecret, Map<String, Object> additionalClaims) {
JwtClaims claims = new JwtClaims();
claims.setSubject(username);
claims.setClaim("clientId", clientId);
if (expiration != 0)
claims.setExpirationTimeMinutesInTheFuture(expiration / 60.0f);
if (additionalClaims != null)
additionalClaims.forEach(claims::setClaim);
JsonWebSignature jws = new JsonWebSignature();
jws.setPayload(claims.toJson());
jws.setKey(rsaJsonWebKey.getRsaPrivateKey());
Expand Down Expand Up @@ -111,6 +115,21 @@ public String getUsername(String token) throws NoSuchElementException {
}
}

@Override
public Map<String, Object> getAdditionalClaims(String token) throws NoSuchElementException {
try {
return verify(token).getClaimsMap().entrySet().stream()
.filter(e -> !isNormalClaim(e.getKey()))
.collect(toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue));
} catch (InvalidJwtException e) {
throw new NoSuchElementException(e);
}
}

private boolean isNormalClaim(String key) {
return "sub".equals(key) || "clientId".equals(key) || "exp".equals(key);
}

@Override
public String getClientId(String token) throws NoSuchElementException {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.ConcurrentHashMap;

Expand Down Expand Up @@ -74,7 +75,7 @@ public String getTokenType() {
}

@Override
public String getToken(String username, String clientId, String clientSecret) {
public String getToken(String username, String clientId, String clientSecret, Map<String, Object> additionalClaims) {
String token = new BigInteger(130, random).toString(32);
tokenToUser.put(token, new User(username, clientId, clientSecret));
return token;
Expand All @@ -89,6 +90,11 @@ public String getUsername(String token) throws NoSuchElementException {
}
}

@Override
public Map<String, Object> getAdditionalClaims(String token) throws NoSuchElementException {
return Map.of();
}

@Override
public String getClientId(String token) throws NoSuchElementException {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

import com.predic8.membrane.core.Router;

import java.util.Map;
import java.util.NoSuchElementException;

public interface TokenGenerator {
Expand All @@ -28,7 +29,7 @@ public interface TokenGenerator {
/**
* @return a new token for the specified user and client.
*/
String getToken(String username, String clientId, String clientSecret);
String getToken(String username, String clientId, String clientSecret, Map<String, Object> additionalClaims);

/**
* Checks the token for validity. Returns the username the token was generated for.
Expand All @@ -38,6 +39,14 @@ public interface TokenGenerator {
*/
String getUsername(String token) throws NoSuchElementException;

/**
* Checks the token for validity. Returns the additional claims the token was generated for.
* @param token The token.
* @return The additional claims.
* @throws NoSuchElementException if the token is not valid.
*/
Map<String, Object> getAdditionalClaims(String token) throws NoSuchElementException;

/**
* Checks the token for validity. Returns the clientId the token was generated for.
* @param token The token.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import javax.xml.transform.TransformerException;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Objects;
import java.util.regex.Pattern;
Expand Down Expand Up @@ -86,7 +88,7 @@ private static Response createMethodNotAllowedSOAPFault() throws Exception {
return ok(getSoapFault("Method Not Allowed", "405", "Use POST to access the service.")).contentType(APPLICATION_XML).build();
}

private Response createWSDLResponse(Exchange exc) throws XMLStreamException {
private Response createWSDLResponse(Exchange exc) throws XMLStreamException, FileNotFoundException {
return ok().header(CONTENT_TYPE, TEXT_XML_UTF8)
.body(setWsdlServer(
getResourceAsStream(this,"/wsdl/city.wsdl"),exc)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public void init() throws Exception {
initOpenAPI();
}

private void initOpenAPI() throws IOException, ClassNotFoundException {
private void initOpenAPI() throws IOException, ClassNotFoundException, URISyntaxException {
if (specs.isEmpty())
return;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

Expand Down Expand Up @@ -60,7 +61,7 @@ public class OpenAPIPublisher {

protected Map<String, OpenAPIRecord> apis;

public OpenAPIPublisher(Map<String, OpenAPIRecord> apis) throws IOException, ClassNotFoundException {
public OpenAPIPublisher(Map<String, OpenAPIRecord> apis) throws IOException, ClassNotFoundException, URISyntaxException {
this.apis = apis;
swaggerUiHtmlTemplate = createTemplate("/openapi/swagger-ui.html");
apiOverviewHtmlTemplate = createTemplate("/openapi/overview.html");
Expand Down Expand Up @@ -142,8 +143,8 @@ private Outcome returnOpenApiAsYaml(Exchange exc, OpenAPIRecord rec, Router rout
return RETURN;
}

private Template createTemplate(String filePath) throws ClassNotFoundException, IOException {
return new StreamingTemplateEngine().createTemplate(new InputStreamReader(getResourceAsStream(this, filePath)));
private Template createTemplate(String filePath) throws ClassNotFoundException, IOException, URISyntaxException {
return new StreamingTemplateEngine().createTemplate(new InputStreamReader(Objects.requireNonNull(getResourceAsStream(this, filePath))));
}

private String renderOverviewTemplate(Router router) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public class OpenAPIPublisherInterceptor extends AbstractInterceptor {
private final Template swaggerUiHtmlTemplate;
private final Template apiOverviewHtmlTemplate;

public OpenAPIPublisherInterceptor(Map<String, OpenAPIRecord> apis) throws IOException, ClassNotFoundException {
public OpenAPIPublisherInterceptor(Map<String, OpenAPIRecord> apis) throws IOException, ClassNotFoundException, URISyntaxException {
name = "OpenAPI Publisher";
this.apis = apis;
swaggerUiHtmlTemplate = createTemplate("/openapi/swagger-ui.html");
Expand All @@ -69,7 +69,7 @@ public OpenAPIPublisherInterceptor(Map<String, OpenAPIRecord> apis) throws IOExc
}

private Template createTemplate(String filePath) throws ClassNotFoundException, IOException {
return new StreamingTemplateEngine().createTemplate(new InputStreamReader(getResourceAsStream(this, filePath)));
return new StreamingTemplateEngine().createTemplate(new InputStreamReader(Objects.requireNonNull(getResourceAsStream(this, filePath))));
}

@Override
Expand Down
Loading

0 comments on commit f590104

Please sign in to comment.