Skip to content

Commit

Permalink
apply formatting rules
Browse files Browse the repository at this point in the history
  • Loading branch information
nenaraab committed Feb 10, 2020
1 parent 447f826 commit a84e7ce
Show file tree
Hide file tree
Showing 24 changed files with 68 additions and 68 deletions.
24 changes: 12 additions & 12 deletions api/src/main/java/com/sap/xsa/security/container/XSUserInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ public interface XSUserInfo {
* - subaccount id: identifier for the subaccount
*
* @deprecated Can be replaced with
* {@code token.getClaimAsString(TokenClaims.USER_NAME)} from
* the {@code com.sap.cloud.security.token} package or with
* {@code token.getClaimAsString(TokenClaims.USER_NAME)} from the
* {@code com.sap.cloud.security.token} package or with
* {@code token.getPrincipal()}.
* @return user name
* @throws XSUserInfoException
Expand All @@ -41,9 +41,9 @@ public interface XSUserInfo {
* Given name of the user.
*
* @deprecated Can be replaced with
* {@code token.getClaimAsString(TokenClaims.GIVEN_NAME)} from
* the {@code com.sap.cloud.security.token} package. Only if it is
* not an external attribute.
* {@code token.getClaimAsString(TokenClaims.GIVEN_NAME)} from the
* {@code com.sap.cloud.security.token} package. Only if it is not
* an external attribute.
* @return given name
* @throws XSUserInfoException
* if attribute is not available in the authentication token
Expand All @@ -55,9 +55,9 @@ public interface XSUserInfo {
* Familiy name of the user.
*
* @deprecated Can be replaced with
* {@code token.getClaimAsString(TokenClaims.FAMILY_NAME)}
* from the {@code com.sap.cloud.security.token} package. Only if it
* is not an external attribute.
* {@code token.getClaimAsString(TokenClaims.FAMILY_NAME)} from the
* {@code com.sap.cloud.security.token} package. Only if it is not
* an external attribute.
* @return family name
* @throws XSUserInfoException
* if attribute is not available in the authentication token
Expand Down Expand Up @@ -85,8 +85,8 @@ public interface XSUserInfo {
* Return identity zone which is the same like the subaccount id (tenant id).
*
* @deprecated Can be replaced with
* {@code token.getClaimAsString(TokenClaims.XSUAA.ZONE_ID)}
* from the {@code com.sap.cloud.security.token} package.
* {@code token.getClaimAsString(TokenClaims.XSUAA.ZONE_ID)} from
* the {@code com.sap.cloud.security.token} package.
* @return identity zone
* @throws XSUserInfoException
* if attribute is not available in the authentication token
Expand All @@ -99,8 +99,8 @@ public interface XSUserInfo {
* id).
*
* @deprecated Can be replaced with
* {@code token.getClaimAsString(TokenClaims.XSUAA.ZONE_ID)}
* from the {@code com.sap.cloud.security.token} package.
* {@code token.getClaimAsString(TokenClaims.XSUAA.ZONE_ID)} from
* the {@code com.sap.cloud.security.token} package.
* @return subaccount identifier
* @throws XSUserInfoException
* if attribute is not available in the authentication token
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,8 @@ public void createToken_tokenIsValid() throws IOException {
OAuth2ServiceConfiguration configuration = Environments.getCurrent().getXsuaaConfiguration();

OAuth2TokenKeyService tokenKeyServiceMock = Mockito.mock(OAuth2TokenKeyService.class);
when(tokenKeyServiceMock.retrieveTokenKeys(any())).thenReturn(IOUtils.resourceToString("/jsonWebTokenKeys.json", StandardCharsets.UTF_8));
when(tokenKeyServiceMock.retrieveTokenKeys(any()))
.thenReturn(IOUtils.resourceToString("/jsonWebTokenKeys.json", StandardCharsets.UTF_8));

CombiningValidator<Token> tokenValidator = JwtValidatorBuilder.getInstance(configuration)
.withOAuth2TokenKeyService(tokenKeyServiceMock)
Expand All @@ -227,7 +228,8 @@ public void createToken_discoverOidcJwksEndpoint_tokenIsValid() throws Exception
OAuth2ServiceConfiguration configuration = Environments.getCurrent().getXsuaaConfiguration();

OAuth2TokenKeyService tokenKeyServiceMock = Mockito.mock(OAuth2TokenKeyService.class);
when(tokenKeyServiceMock.retrieveTokenKeys(any())).thenReturn(IOUtils.resourceToString("/jsonWebTokenKeys.json", StandardCharsets.UTF_8));
when(tokenKeyServiceMock.retrieveTokenKeys(any()))
.thenReturn(IOUtils.resourceToString("/jsonWebTokenKeys.json", StandardCharsets.UTF_8));

OAuth2ServiceEndpointsProvider endpointsProviderMock = Mockito.mock(OAuth2ServiceEndpointsProvider.class);
when(endpointsProviderMock.getJwksUri()).thenReturn(URI.create("http://auth.com/token_keys"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ public class SecurityTestRuleTest {
.useApplicationServer(forService(XSUAA).usePort(APPLICATION_SERVER_PORT))
.addApplicationServlet(TestServlet.class, "/hi");


@Test
public void getTokenKeysRequest_responseContainsExpectedTokenKeys()
throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@
* </dependency>
* }
* </pre>
* By default it used Apache Rest Client for communicating with the OAuth2 Server.
*
* By default it used Apache Rest Client for communicating with the OAuth2
* Server.
*/
public class SAPOfflineTokenServicesCloud implements ResourceServerTokenServices, InitializingBean {

Expand All @@ -55,7 +57,8 @@ public class SAPOfflineTokenServicesCloud implements ResourceServerTokenServices
private ScopeConverter xsuaaScopeConverter;

/**
* Constructs an instance which is preconfigured for XSUAA service configuration from SAP CP Environment.
* Constructs an instance which is preconfigured for XSUAA service configuration
* from SAP CP Environment.
*/
public SAPOfflineTokenServicesCloud() {
this(Environments.getCurrent().getXsuaaConfiguration());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,10 +103,7 @@ public String getSubaccountId() throws XSUserInfoException {

@Override
/**
* "ext_attr": {
* "enhancer": "XSUAA",
* "zdn": "paas-subdomain"
* },
* "ext_attr": { "enhancer": "XSUAA", "zdn": "paas-subdomain" },
*/
public String getSubdomain() throws XSUserInfoException {
return Optional.ofNullable(getExternalAttribute(ZDN)).orElse(null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
import static com.sap.cloud.security.token.TokenClaims.XSUAA.ISSUED_AT;

/**
* Decodes and parses encoded JSON Web Token (JWT) and provides access to
* token header parameters and claims.
* Decodes and parses encoded JSON Web Token (JWT) and provides access to token
* header parameters and claims.
*/
public abstract class AbstractToken implements Token {
protected final DefaultJsonObject tokenHeader;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
import java.util.Set;

/**
* Represents an access token in the format of a JSON Web Token (not a short opaque token).
* In difference to a ID token the access token has no/less information about the user but
* has information about the authorities (scopes).
* Represents an access token in the format of a JSON Web Token (not a short
* opaque token). In difference to a ID token the access token has no/less
* information about the user but has information about the authorities
* (scopes).
*/
public interface AccessToken extends Token {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,12 @@ public static Token getToken() {
* Returns the token that is saved in thread wide storage.
*
*
* @return the token or null if the storage is empty or the token
* does not implement the {@code AccessToken} interface.
* @return the token or null if the storage is empty or the token does not
* implement the {@code AccessToken} interface.
*/
@Nullable
public static AccessToken getAccessToken() {
return tokenStorage.get() instanceof AccessToken ? (AccessToken) tokenStorage.get() : null;
return tokenStorage.get() instanceof AccessToken ? (AccessToken) tokenStorage.get() : null;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,7 @@ public interface Token {
Instant getNotBefore();

/**
* Get the encoded jwt token, e.g. for token forwarding to another
* app.
* Get the encoded jwt token, e.g. for token forwarding to another app.
*
* <p>
* Never expose this token via log or via HTTP.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ private TokenClaims() {

public final class XSUAA {


private XSUAA() {
}

Expand All @@ -38,12 +37,10 @@ private XSUAA() {
public static final String TRUSTED_CLIENT_ID_SUFFIX = "trustedclientidsuffix";
}

/* SAP User token
public final class SAP_ID {
private SAP_ID() {
}
// public static final String SAP_ZONE_ID = "sap_zid";
// public static final String SAP_USER_ID = "sap_uid";
}*/
/*
* SAP User token public final class SAP_ID { private SAP_ID() { }
*
* // public static final String SAP_ZONE_ID = "sap_zid"; // public static final
* String SAP_USER_ID = "sap_uid"; }
*/
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import static com.sap.cloud.security.token.validation.validators.JsonWebKeyConstants.BEGIN_PUBLIC_KEY;
import static com.sap.cloud.security.token.validation.validators.JsonWebKeyConstants.END_PUBLIC_KEY;


class JsonWebKeyImpl implements JsonWebKey {
private final JwtSignatureAlgorithm keyAlgorithm;
private final String keyId;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public ValidationResult validate(Token token) {
private ValidationResult matchesTokenIssuerDomain(String issuer) {
URI issuerUri;
try {
if(!issuer.startsWith("http")) {
if (!issuer.startsWith("http")) {
return createInvalid(
"Issuer is not trusted because 'iss' claim '{}' does not provide a valid URI (missing http scheme). Please contact your Identity Provider Administrator.",
issuer);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* https://www.rfc-editor.org/rfc/rfc7518.html#section-6.1
*/
public enum JwtSignatureAlgorithm {
RS256("RSA", "RS256", "SHA256withRSA")/*, ES256("EC", "ES256", "SHA256withECDSA")// Eliptic curve */;
RS256("RSA", "RS256", "SHA256withRSA")/* , ES256("EC", "ES256", "SHA256withECDSA")// Eliptic curve */;

private final String type;
private final String value;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,9 @@ private String getOrDefaultKeyId(Token token) {
private String getOrDefaultSignatureAlgorithm(Token token) {
String algHeader = token.getHeaderParameterAsString(ALGORITHM_PARAMETER_NAME);

if(JwtSignatureAlgorithm.fromValue(algHeader) == null) {
throw new IllegalArgumentException("Jwt token with signature algorithm '" + algHeader + "' is not supported.");
if (JwtSignatureAlgorithm.fromValue(algHeader) == null) {
throw new IllegalArgumentException(
"Jwt token with signature algorithm '" + algHeader + "' is not supported.");
}
return JwtSignatureAlgorithm.RS256.value();
}
Expand Down Expand Up @@ -147,7 +148,7 @@ static Validation getInstance() {
}

ValidationResult validate(OAuth2TokenKeyServiceWithCache tokenKeyService, String token,
String tokenAlgorithm, String tokenKeyId, URI tokenKeysUrl, String fallbackPublicKey) {
String tokenAlgorithm, String tokenKeyId, URI tokenKeysUrl, String fallbackPublicKey) {
ValidationResult validationResult;

validationResult = setSupportedJwtAlgorithm(tokenAlgorithm);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ public JwtValidatorBuilder withOidcConfigurationService(OidcConfigurationService
* @return this builder
*/
public JwtValidatorBuilder withHttpClient(CloseableHttpClient httpClient) {
if(httpClient != null) {
if (httpClient != null) {
this.oidcConfigurationService = new DefaultOidcConfigurationService(httpClient);
this.tokenKeyService = new DefaultOAuth2TokenKeyService(httpClient);
}
Expand Down Expand Up @@ -191,7 +191,7 @@ private List<Validator<Token>> createDefaultValidators() {

private JwtAudienceValidator createAudienceValidator() {
JwtAudienceValidator jwtAudienceValidator = new JwtAudienceValidator(configuration.getClientId());
if(configuration.hasProperty(CFConstants.XSUAA.APP_ID)) {
if (configuration.hasProperty(CFConstants.XSUAA.APP_ID)) {
jwtAudienceValidator.configureTrustedClientId(configuration.getProperty(CFConstants.XSUAA.APP_ID));
}
if (otherConfiguration != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,8 @@ public void testRequestToken_isNotImplemented() {

@Test
public void getHdbToken_AuthCodeToken_NoAttributes() throws XSUserInfoException, IOException {
XsuaaToken token = new XsuaaToken(IOUtils.resourceToString("/xsuaaXsaAccessTokenRSA256_signedWithVerificationKey.txt", UTF_8));
XsuaaToken token = new XsuaaToken(
IOUtils.resourceToString("/xsuaaXsaAccessTokenRSA256_signedWithVerificationKey.txt", UTF_8));
OAuth2ServiceConfiguration configuration = OAuth2ServiceConfigurationBuilder.forService(Service.XSUAA)
.withClientId("sb-java-hello-world!i1")
.withProperty(CFConstants.XSUAA.APP_ID, "java-hello-world!i1")
Expand Down Expand Up @@ -331,7 +332,6 @@ public void getHdbToken_AudCodeToken_WithAttributes() throws XSUserInfoException
.withProperty("identityzoneid", "uaa")
.build();


cut = new XSUserInfoAdapter(token, configuration);

assertThat(cut.getHdbToken()).isNotNull();
Expand Down Expand Up @@ -360,7 +360,8 @@ public void isForeignModeFalse_whenTrustedClientIdSuffixMatches() throws XSUserI
}

@Test
public void isForeignModeFalse_WhenIdentityZoneDoesNotMatchButCliendIdIsApplicationPlan() throws XSUserInfoException {
public void isForeignModeFalse_WhenIdentityZoneDoesNotMatchButCliendIdIsApplicationPlan()
throws XSUserInfoException {
String tokenClientId = "sb-application!t0123"; // cid
String identityZone = "brokerplanmasterapp!b123"; // ext_attr -> zdn
OAuth2ServiceConfiguration configuration = OAuth2ServiceConfigurationBuilder.forService(Service.XSUAA)
Expand All @@ -384,7 +385,6 @@ public void isForeignModeFalse_WhenClientIdAndIdentityZonesMatch() throws XSUser
.withProperty(IDENTITY_ZONE, identityZone)
.build();


cut = createComponentUnderTestSpy(configuration);
doReturn(tokenClientId).when(cut).getClientId();
doReturn(identityZone).when(cut).getIdentityZone();
Expand Down Expand Up @@ -429,8 +429,8 @@ private XSUserInfoAdapter createComponentUnderTestSpy() throws XSUserInfoExcepti
return spy(new XSUserInfoAdapter(mock(XsuaaToken.class), mock(OAuth2ServiceConfiguration.class)));
}


private XSUserInfoAdapter createComponentUnderTestSpy(OAuth2ServiceConfiguration configuration) throws XSUserInfoException {
private XSUserInfoAdapter createComponentUnderTestSpy(OAuth2ServiceConfiguration configuration)
throws XSUserInfoException {
return spy(new XSUserInfoAdapter(Mockito.mock(XsuaaToken.class), configuration));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,8 @@ public void tokenWithoutExpirationDate_isExpired() {

@Test
public void tokenWithLongExpiration_isNotExpired() {
AbstractToken tokenWithNoExpiration = new MockTokenBuilder().withExpiration(MockTokenBuilder.NO_EXPIRE_DATE).build();
AbstractToken tokenWithNoExpiration = new MockTokenBuilder().withExpiration(MockTokenBuilder.NO_EXPIRE_DATE)
.build();
when(tokenWithNoExpiration.isExpired()).thenCallRealMethod();

assertThat(tokenWithNoExpiration.isExpired()).isFalse();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@ public void clearingTokenInDifferentThreadDoesNotAffectMainThread()
}

@Test
public void getAccessTokenReturnsNullIfTokenDoesNotImplementInterface() throws ExecutionException, InterruptedException, IOException {
public void getAccessTokenReturnsNullIfTokenDoesNotImplementInterface()
throws ExecutionException, InterruptedException, IOException {
SecurityContext.setToken(TOKEN);
assertThat(SecurityContext.getAccessToken()).isNull();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ public void xsuaaTokenValidationFails_withIasCombiningValidator() throws IOExcep

ValidationResult result = tokenValidator.validate(xsuaaToken);
assertThat(result.isValid()).isFalse();
assertThat(result.getErrorDescription()).startsWith("Issuer is not trusted because 'iss' 'http://auth.com' does not match host 'myauth.com' of the identity provider");
assertThat(result.getErrorDescription()).startsWith(
"Issuer is not trusted because 'iss' 'http://auth.com' does not match host 'myauth.com' of the identity provider");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public void getKeyByAlgorithmAndId_returnsNull_onEmptyJSONWebKeySet() {
@Test
@Ignore
public void getKeyByAlgorithmAndId_returnsNull_whenKeyTypeDoesNotMatch() {
JwtSignatureAlgorithm differentKeyAlgorithm = JwtSignatureAlgorithm.RS256; //ES256
JwtSignatureAlgorithm differentKeyAlgorithm = JwtSignatureAlgorithm.RS256; // ES256

cut.put(JSON_WEB_KEY);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ public void validate_tokenAudienceMatchesForeignClientId() {
@Test
public void validate_clientIdMatchesTokenAudienceWithoutDot() {
// configures token audience
Mockito.when(token.getAudiences()).thenReturn(Sets.newLinkedHashSet("client", "foreignclient", "sb-test4!t1.data.x"));
Mockito.when(token.getAudiences())
.thenReturn(Sets.newLinkedHashSet("client", "foreignclient", "sb-test4!t1.data.x"));

// configures audience validator with client-id from VCAP_SERVICES
ValidationResult result = new JwtAudienceValidator("sb-test4!t1")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -199,12 +199,11 @@ public void validationFails_whenOAuthServerIsUnavailable() throws OAuth2ServiceE
@Test
@Ignore // Not yet supported
public void jsonECSignatureMatchesJWKS() {
/*{
"kty": "EC",
"kid": "key-id-1",
"alg": "ES256",
"value": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEQgb5npLHd0Bk61bNnjK632uwmBfr\nF7I8hoPgaOZjyhh+BrPDO6CL6D/aW/yPObXXm7SpZogmRwGROcOA3yUleg==\n-----END PUBLIC KEY-----"
}*/
/*
* { "kty": "EC", "kid": "key-id-1", "alg": "ES256", "value":
* "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEQgb5npLHd0Bk61bNnjK632uwmBfr\nF7I8hoPgaOZjyhh+BrPDO6CL6D/aW/yPObXXm7SpZogmRwGROcOA3yUleg==\n-----END PUBLIC KEY-----"
* }
*/
String ecSignedToken = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.4iVk3-Y0v4RT4_9IaQlp-8dZ_4fsTzIylgrPTDLrEvTHBTyVS3tgPbr2_IZfLETtiKRqCg0aQ5sh9eIsTTwB1g";
assertThat(cut.validate(ecSignedToken, "ES256", "key-id-1", null, null).isValid(), is(true));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ public interface OAuth2TokenKeyService {
*
* @param tokenKeysEndpointUri
* the token endpoint URI (jku).
* @return An endpoint which returns the list of JSON Web Token (JWT) keys as JSON string.
* @return An endpoint which returns the list of JSON Web Token (JWT) keys as
* JSON string.
* @throws OAuth2ServiceException
* in case of an error during the http request.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,6 @@ public void retrieveTokenKeys_executesHttpGetRequestWithCorrectURI() throws IOEx

}



private CloseableHttpResponse mockResponse() throws IOException {
CloseableHttpResponse response = HttpClientTestFactory.createHttpResponse(jsonWebKeysAsString);
when(httpClient.execute(any())).thenReturn(response);
Expand Down

0 comments on commit a84e7ce

Please sign in to comment.