Skip to content

Commit

Permalink
STS kan angi konfig slik som naiserator legger inn for Azure (#1051)
Browse files Browse the repository at this point in the history
  • Loading branch information
jolarsen authored Jan 18, 2022
1 parent 85c9eae commit 6800636
Show file tree
Hide file tree
Showing 24 changed files with 143 additions and 603 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
Expand Down Expand Up @@ -44,6 +45,14 @@ public static <T> List<T> fromJson(String json, TypeReference<List<T>> typeRefer
}
}

public static JsonNode treeFromJson(String json) {
try {
return MAPPER.readTree(json);
} catch (IOException e) {
throw new TekniskException("F-919328", "Fikk IO exception ved parsing av JSON", e);
}
}

public static String toJson(Object obj) {
try {
return MAPPER.writeValueAsString(obj);
Expand Down
4 changes: 4 additions & 0 deletions felles/sikkerhet/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@
<groupId>no.nav.foreldrepenger.felles</groupId>
<artifactId>felles-log</artifactId>
</dependency>
<dependency>
<groupId>no.nav.foreldrepenger.felles</groupId>
<artifactId>felles-mapper</artifactId>
</dependency>
<dependency>
<groupId>no.nav.foreldrepenger</groupId>
<artifactId>konfig</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.nimbusds.oauth2.sdk.as.AuthorizationServerMetadata;

import no.nav.foreldrepenger.konfig.Environment;
import no.nav.vedtak.exception.TekniskException;
Expand All @@ -40,6 +39,7 @@
import no.nav.vedtak.sikkerhet.oidc.IdTokenAndRefreshTokenProvider;
import no.nav.vedtak.sikkerhet.oidc.OidcProviderConfig;
import no.nav.vedtak.sikkerhet.oidc.WellKnownConfigurationHelper;
import no.nav.vedtak.sikkerhet.oidc.WellKnownOpenIdConfiguration;

// TODO, denne klassen er en katastrofe
public class OpenAMHelper {
Expand Down Expand Up @@ -87,22 +87,22 @@ public static String getIssoPassword() {
.orElse(ENV.getProperty(OPEN_ID_CONNECT_PASSWORD));
}

public static AuthorizationServerMetadata getOpenAmWellKnownConfig() {
return WellKnownConfigurationHelper.getWellKnownConfig
(Optional.ofNullable(ENV.getProperty(OPEN_AM_WELL_KNOWN_URL))
.orElse(ENV.getProperty(OPEN_ID_CONNECT_ISSO_HOST) + WELL_KNOWN_ENDPOINT), null);
public static WellKnownOpenIdConfiguration getOpenAmWellKnownConfig() {
var discoveryURL = Optional.ofNullable(ENV.getProperty(OPEN_AM_WELL_KNOWN_URL))
.orElse(ENV.getProperty(OPEN_ID_CONNECT_ISSO_HOST) + WELL_KNOWN_ENDPOINT);
return WellKnownConfigurationHelper.getWellKnownConfig(discoveryURL, null);
}

public static String getIssoIssuerUrl() {
return getOpenAmWellKnownConfig().getIssuer().getValue();
return getOpenAmWellKnownConfig().issuer();
}

public static String getIssoJwksUrl() {
return getOpenAmWellKnownConfig().getJWKSetURI().toString();
return getOpenAmWellKnownConfig().jwks_uri();
}

public static String getAuthorizationEndpoint() {
return getOpenAmWellKnownConfig().getAuthorizationEndpointURI().toString();
return getOpenAmWellKnownConfig().authorization_endpoint();
}

public IdTokenAndRefreshToken getToken() throws IOException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@ public final class OidcProvider {
private final URL issuer;
private final URL jwks;
private final URI tokenEndpoint;
private final URI authorizationEndpoint;
private final boolean useProxyForJwks;
private final String proxy;
private final String clientName;
private final int allowedClockSkewInSeconds;
private final boolean skipAudienceValidation;

public OidcProvider(OidcProviderType type,
URL issuer, URL jwks, URI tokenEndpoint,
URL issuer, URL jwks, URI tokenEndpoint, URI authorizationEndpoint,
boolean useProxyForJwks, String proxy, String clientName,
int allowedClockSkewInSeconds, boolean skipAudienceValidation) {
this.type = type;
Expand All @@ -24,6 +25,7 @@ public OidcProvider(OidcProviderType type,
this.useProxyForJwks = useProxyForJwks;
this.proxy = proxy;
this.tokenEndpoint = tokenEndpoint;
this.authorizationEndpoint = authorizationEndpoint;
this.clientName = clientName;
this.allowedClockSkewInSeconds = allowedClockSkewInSeconds;
this.skipAudienceValidation = skipAudienceValidation;
Expand All @@ -45,6 +47,10 @@ public URI getTokenEndpoint() {
return tokenEndpoint;
}

public URI getAuthorizationEndpoint() {
return authorizationEndpoint;
}

public boolean isUseProxyForJwks() {
return useProxyForJwks;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package no.nav.vedtak.sikkerhet.oidc;

import static no.nav.vedtak.sikkerhet.oidc.WellKnownConfigurationHelper.getAuthorizationEndpointFra;
import static no.nav.vedtak.sikkerhet.oidc.WellKnownConfigurationHelper.getIssuerFra;
import static no.nav.vedtak.sikkerhet.oidc.WellKnownConfigurationHelper.getJwksFra;
import static no.nav.vedtak.sikkerhet.oidc.WellKnownConfigurationHelper.getTokenEndpointFra;
Expand Down Expand Up @@ -29,11 +30,17 @@ public final class OidcProviderConfig {
public static final String OPEN_AM_CLIENT_SECRET = "oidc.open.am.client.secret";

private static final String STS_WELL_KNOWN_URL = "oidc.sts.well.known.url";
private static final String STS_CONFIG_ISSUER = "oidc.sts.openid.config.issuer";
private static final String STS_CONFIG_JWKS_URI = "oidc.sts.openid.config.jwks.uri";
private static final String STS_CONFIG_TOKEN_ENDPOINT = "oidc.sts.openid.config.token.endpoint";

private static final String LOGINSERVICE_IDPORTEN_DISCOVERY_URL = "loginservice.idporten.discovery.url"; // naiserator
private static final String LOGINSERVICE_CLIENT_ID = "loginservice.idporten.audience"; // naiserator

private static final String AZURE_WELL_KNOWN_URL = "azure.app.well.known.url"; // naiserator
private static final String AZURE_CONFIG_ISSUER = "azure.openid.config.issuer"; // naiserator
private static final String AZURE_CONFIG_JWKS_URI = "azure.openid.config.jwks.uri"; // naiserator
private static final String AZURE_CONFIG_TOKEN_ENDPOINT = "azure.openid.config.token.endpoint"; // naiserator
private static final String AZURE_CLIENT_ID = "azure.app.client.id"; // naiserator
private static final String AZURE_HTTP_PROXY = "azure.http.proxy"; // settes ikke av naiserator

Expand Down Expand Up @@ -86,7 +93,7 @@ private static Set<OidcProvider> hentConfig() {
idProviderConfigs.add(createOpenAmConfiguration(ENV.getProperty(OPEN_AM_WELL_KNOWN_URL)));

// OIDC STS
if (ENV.getProperty(STS_WELL_KNOWN_URL) != null || ENV.getProperty("oidc.sts.issuer.url") != null) { // Det er kanskje noen apper som ikke bruker STS token validering??
if (ENV.getProperty(STS_WELL_KNOWN_URL) != null || ENV.getProperty("oidc.sts.issuer.url") != null || ENV.getProperty(STS_CONFIG_ISSUER) != null) { // Det er kanskje noen apper som ikke bruker STS token validering??
idProviderConfigs.add(createStsConfiguration(ENV.getProperty(STS_WELL_KNOWN_URL)));
}

Expand All @@ -112,8 +119,8 @@ private static Set<OidcProvider> hentConfig() {
}

LOG.info("ID Providere som er tilgjengelig: {}", idProviderConfigs.stream()
.map(OidcProvider::getIssuer)
.map(URL::getHost)
.map(OidcProvider::getType)
.map(OidcProviderType::name)
.collect(Collectors.joining(", ")));

return idProviderConfigs;
Expand All @@ -126,18 +133,25 @@ private static OidcProvider createOpenAmConfiguration(String wellKnownUrl) {
getIssuerFra(wellKnownUrl).orElseGet(OpenAMHelper::getIssoIssuerUrl),
getJwksFra(wellKnownUrl).orElseGet(OpenAMHelper::getIssoJwksUrl),
getTokenEndpointFra(wellKnownUrl).orElse(null),
getAuthorizationEndpointFra(wellKnownUrl).orElse(null),
false, null,
OpenAMHelper.getIssoUserName(),
true);
}

private static OidcProvider createStsConfiguration(String wellKnownUrl) {
LOG.debug("Oppretter OpenAM konfig fra '{}'", wellKnownUrl);
LOG.debug("Oppretter STS konfig fra '{}'", wellKnownUrl);
return createConfiguration(OidcProviderType.STS,
"oidc_sts",
getIssuerFra(wellKnownUrl).orElseGet(() -> ENV.getProperty("oidc.sts.issuer.url")),
getJwksFra(wellKnownUrl).orElseGet(() -> ENV.getProperty("oidc.sts.jwks.url")),
getTokenEndpointFra(wellKnownUrl).orElse(null),
Optional.ofNullable(ENV.getProperty(STS_CONFIG_ISSUER))
.or(() -> getIssuerFra(wellKnownUrl))
.orElseGet(() -> ENV.getProperty("oidc.sts.issuer.url")),
Optional.ofNullable(ENV.getProperty(STS_CONFIG_JWKS_URI))
.or(() -> getJwksFra(wellKnownUrl))
.orElseGet(() -> ENV.getProperty("oidc.sts.jwks.url")),
Optional.ofNullable(ENV.getProperty(STS_CONFIG_TOKEN_ENDPOINT)).map(URI::create)
.or(() -> getTokenEndpointFra(wellKnownUrl)).orElse(null),
null,
false, null,
"Client name is not used for OIDC STS",
true);
Expand All @@ -148,10 +162,13 @@ private static OidcProvider createAzureAppConfiguration(String wellKnownUrl) {
var useProxy = ENV.isLocal() ? null : ENV.getProperty(AZURE_HTTP_PROXY, getDefaultProxy());
return createConfiguration(OidcProviderType.AZUREAD,
"oidc_azure",
getIssuerFra(wellKnownUrl, useProxy).orElseGet(() -> ENV.getProperty("azure.openid.config.issuer")),
getJwksFra(wellKnownUrl, useProxy).orElseGet(() -> ENV.getRequiredProperty("azure.openid.config.jwks.uri")),
getTokenEndpointFra(wellKnownUrl, useProxy).orElseGet(() ->
Optional.ofNullable(ENV.getRequiredProperty("azure.openid.config.token.endpoint")).map(URI::create).orElse(null)),
Optional.ofNullable(ENV.getProperty(AZURE_CONFIG_ISSUER))
.orElseGet(() -> getIssuerFra(wellKnownUrl, useProxy).orElse(null)),
Optional.ofNullable(ENV.getProperty(AZURE_CONFIG_JWKS_URI))
.orElseGet(() -> getJwksFra(wellKnownUrl, useProxy).orElse(null)),
Optional.ofNullable(ENV.getProperty(AZURE_CONFIG_TOKEN_ENDPOINT)).map(URI::create)
.orElseGet(() -> getTokenEndpointFra(wellKnownUrl, useProxy).orElse(null)),
null,
!ENV.isLocal(), useProxy,
ENV.getRequiredProperty(AZURE_CLIENT_ID),
true);
Expand All @@ -164,6 +181,7 @@ private static OidcProvider createLoginServiceConfiguration(String wellKnownUrl)
getIssuerFra(wellKnownUrl, useProxy).orElseThrow(),
getJwksFra(wellKnownUrl, useProxy).orElseThrow(),
getTokenEndpointFra(wellKnownUrl, useProxy).orElse(null),
getAuthorizationEndpointFra(wellKnownUrl).orElse(null),
!ENV.isLocal(), useProxy,
ENV.getRequiredProperty(LOGINSERVICE_CLIENT_ID),
false);
Expand All @@ -175,6 +193,7 @@ private static OidcProvider createTokenXConfiguration(String wellKnownUrl) {
getIssuerFra(wellKnownUrl).orElseThrow(),
getJwksFra(wellKnownUrl).orElseThrow(),
getTokenEndpointFra(wellKnownUrl).orElse(null),
getAuthorizationEndpointFra(wellKnownUrl).orElse(null),
false, null,
ENV.getRequiredProperty(TOKEN_X_CLIENT_ID),
false);
Expand All @@ -185,6 +204,7 @@ private static OidcProvider createConfiguration(OidcProviderType type,
String issuer,
String jwks,
URI tokenEndpoint,
URI authorizationEndpoint,
boolean useProxyForJwks,
String proxy,
String clientName,
Expand All @@ -194,6 +214,7 @@ private static OidcProvider createConfiguration(OidcProviderType type,
url(issuer, "issuer", providerName),
url(jwks, "jwks", providerName),
tokenEndpoint,
authorizationEndpoint,
useProxyForJwks,
proxy,
Objects.requireNonNull(clientName),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
Expand All @@ -13,10 +16,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.nimbusds.jose.util.DefaultResourceRetriever;
import com.nimbusds.oauth2.sdk.ParseException;
import com.nimbusds.oauth2.sdk.as.AuthorizationServerMetadata;

import no.nav.foreldrepenger.felles.integrasjon.rest.DefaultJsonMapper;
import no.nav.foreldrepenger.konfig.Environment;
import no.nav.vedtak.exception.TekniskException;

Expand All @@ -25,54 +25,72 @@ public class WellKnownConfigurationHelper {
private static final Logger LOG = LoggerFactory.getLogger(WellKnownConfigurationHelper.class);
private static final Environment ENV = Environment.current();

private static Map<String, AuthorizationServerMetadata> wellKnownConfigMap = Collections.synchronizedMap(new LinkedHashMap<>());;
private static Map<String, WellKnownOpenIdConfiguration> wellKnownConfigMap = Collections.synchronizedMap(new LinkedHashMap<>());;

public static WellKnownOpenIdConfiguration getWellKnownConfig(URI discoveryUrl) {
return getWellKnownConfig(discoveryUrl.toString(), null);
}

public static synchronized AuthorizationServerMetadata getWellKnownConfig(String discoveryUrl, String proxyUrl) {
public static synchronized WellKnownOpenIdConfiguration getWellKnownConfig(String discoveryUrl, String proxyUrl) {
if (wellKnownConfigMap.get(discoveryUrl) == null) {
wellKnownConfigMap.put(discoveryUrl, retrieveAuthorizationServerMetadata(discoveryUrl, proxyUrl));
wellKnownConfigMap.put(discoveryUrl, hentWellKnownConfig(discoveryUrl, proxyUrl));
}
return wellKnownConfigMap.get(discoveryUrl);
}

public static Optional<String> getIssuerFra(String discoveryURL) {
static Optional<String> getIssuerFra(String discoveryURL) {
return getIssuerFra(discoveryURL, null);
}

public static Optional<String> getIssuerFra(String discoveryURL, String proxyUrl) {
static Optional<String> getIssuerFra(String discoveryURL, String proxyUrl) {
LOG.debug("Henter issuer fra {}", discoveryURL);
return Optional.ofNullable(discoveryURL).map(u -> getWellKnownConfig(u, proxyUrl).getIssuer().getValue());
return Optional.ofNullable(discoveryURL).map(u -> getWellKnownConfig(u, proxyUrl).issuer());
}

public static Optional<String> getJwksFra(String discoveryURL) {
static Optional<String> getJwksFra(String discoveryURL) {
return getJwksFra(discoveryURL, null);
}

public static Optional<String> getJwksFra(String discoveryURL, String proxyUrl) {
static Optional<String> getJwksFra(String discoveryURL, String proxyUrl) {
LOG.debug("Henter jwki_uri fra {}", discoveryURL);
return Optional.ofNullable(discoveryURL).map(u -> getWellKnownConfig(u, proxyUrl).getJWKSetURI().toString());
return Optional.ofNullable(discoveryURL).map(u -> getWellKnownConfig(u, proxyUrl).jwks_uri().toString());
}

public static Optional<URI> getTokenEndpointFra(String discoveryURL) {
static Optional<URI> getTokenEndpointFra(String discoveryURL) {
return getTokenEndpointFra(discoveryURL, null);
}

public static Optional<URI> getTokenEndpointFra(String discoveryURL, String proxyUrl) {
static Optional<URI> getTokenEndpointFra(String discoveryURL, String proxyUrl) {
LOG.debug("Henter token_endpoint fra {}", discoveryURL);
return Optional.ofNullable(discoveryURL).map(u -> getWellKnownConfig(u, proxyUrl).getTokenEndpointURI());
return Optional.ofNullable(discoveryURL).map(u -> getWellKnownConfig(u, proxyUrl).token_endpoint()).map(URI::create);
}

private static AuthorizationServerMetadata retrieveAuthorizationServerMetadata(String discoveryURL, String proxyUrl) {
static Optional<URI> getAuthorizationEndpointFra(String discoveryURL) {
return Optional.ofNullable(discoveryURL).map(u -> getWellKnownConfig(u, null).authorization_endpoint()).map(URI::create);
}

private static WellKnownOpenIdConfiguration hentWellKnownConfig(String discoveryURL, String proxyUrl) {
try {
LOG.debug("Henter well-known konfig fra '{}'", discoveryURL);
var resourceRetriever = new DefaultResourceRetriever();
var clientBuilder = HttpClient.newBuilder();
Optional.ofNullable(proxyUrl)
.filter(s -> !s.isEmpty())
.map(URI::create)
.map(u -> new InetSocketAddress(u.getHost(), u.getPort()))
.map(s -> new Proxy(Proxy.Type.HTTP, s))
.ifPresent(resourceRetriever::setProxy);
var url = URI.create(discoveryURL).toURL();
return AuthorizationServerMetadata.parse(resourceRetriever.retrieveResource(url).getContent());
} catch (ParseException | IOException e) {
.map(ProxySelector::of)
.ifPresent(clientBuilder::proxy);
var client = clientBuilder.build();
var request = HttpRequest.newBuilder()
.uri(URI.create(discoveryURL))
.header("accept", "application/json")
.GET()
.build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString()).body();
return response != null ? DefaultJsonMapper.MAPPER.readerFor(WellKnownOpenIdConfiguration.class).readValue(response) : null;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new TekniskException("F-999999", String.format("Exception when retrieving metadata from issuer %s", discoveryURL), e);
} catch (IOException e) {
throw new TekniskException("F-999999", String.format("Exception when retrieving metadata from issuer %s", discoveryURL), e);
}
}
Expand All @@ -81,8 +99,8 @@ public static void setWellKnownConfig(String discoveryUrl, String jsonAsString)
guardForTestOnly();
wellKnownConfigMap.computeIfAbsent(discoveryUrl, key -> {
try {
return AuthorizationServerMetadata.parse(jsonAsString);
} catch (ParseException e) {
return DefaultJsonMapper.MAPPER.readerFor(WellKnownOpenIdConfiguration.class).readValue(jsonAsString);
} catch (IOException e) {
throw new IllegalArgumentException("Ugyldig json: ", e);
}
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package no.nav.vedtak.sikkerhet.oidc;

/*
* Interessante elementer fra en standard respons fra .well-known/openid-configuration
* authorization_endpoint er stort sett interessant for ISSO
*/
public record WellKnownOpenIdConfiguration(String issuer,
String jwks_uri,
String token_endpoint,
String authorization_endpoint) {

}
Loading

0 comments on commit 6800636

Please sign in to comment.