Search in sources :

Example 86 with Parameter

use of io.swagger.v3.oas.models.parameters.Parameter in project swagger-core by swagger-api.

the class ParameterSerializationTest method testReadOnlyParameter.

@Test(description = "should mark a parameter as readOnly")
public void testReadOnlyParameter() throws Exception {
    final QueryParameter qp = new QueryParameter();
    qp.setSchema(new StringSchema().readOnly(true));
    final String json = "{" + "   \"in\":\"query\"," + "   \"schema\":{" + "      \"type\":\"string\"," + "      \"readOnly\":true" + "   }" + "}";
    SerializationMatchers.assertEqualsToJson(qp, json);
}
Also used : QueryParameter(io.swagger.v3.oas.models.parameters.QueryParameter) StringSchema(io.swagger.v3.oas.models.media.StringSchema) Test(org.testng.annotations.Test)

Example 87 with Parameter

use of io.swagger.v3.oas.models.parameters.Parameter in project swagger-core by swagger-api.

the class ParameterSerializationTest method serializeIntegerArrayPathParameter.

@Test(description = "it should serialize a PathParameter with integer array")
public void serializeIntegerArrayPathParameter() {
    final Parameter p = new PathParameter().schema(new ArraySchema().items(new IntegerSchema()));
    final String json = "{\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"array\",\"items\":{\"type\":\"integer\",\"format\":\"int32\"}}}\n";
    SerializationMatchers.assertEqualsToJson(p, json);
}
Also used : ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) IntegerSchema(io.swagger.v3.oas.models.media.IntegerSchema) Parameter(io.swagger.v3.oas.models.parameters.Parameter) QueryParameter(io.swagger.v3.oas.models.parameters.QueryParameter) HeaderParameter(io.swagger.v3.oas.models.parameters.HeaderParameter) PathParameter(io.swagger.v3.oas.models.parameters.PathParameter) PathParameter(io.swagger.v3.oas.models.parameters.PathParameter) Test(org.testng.annotations.Test)

Example 88 with Parameter

use of io.swagger.v3.oas.models.parameters.Parameter in project cas by apereo.

the class AmazonSecurityTokenServiceEndpoint method fetchCredentials.

/**
 * Fetch credentials.
 *
 * @param duration     the duration
 * @param tokenCode    the token code
 * @param profile      the profile
 * @param serialNumber the serial number
 * @param roleArn      the role arn
 * @param requestBody  the request body
 * @param request      the request
 * @param response     the response
 * @return the map
 */
@PostMapping
@Operation(summary = "Fetch temporary credentials from Amazon Security Token Service", parameters = { @Parameter(name = "duration"), @Parameter(name = "tokenCode"), @Parameter(name = "profile"), @Parameter(name = "serialNumber"), @Parameter(name = "roleArn"), @Parameter(name = "requestBody"), @Parameter(name = "request"), @Parameter(name = "response") })
public ResponseEntity<String> fetchCredentials(@RequestParam(required = false, defaultValue = "PT1H") final String duration, @RequestParam(value = "token", required = false) final String tokenCode, @RequestParam(required = false) final String profile, @RequestParam(required = false) final String serialNumber, @RequestParam(required = false) final String roleArn, @RequestBody final MultiValueMap<String, String> requestBody, final HttpServletRequest request, final HttpServletResponse response) {
    var authenticationResult = (AuthenticationResult) null;
    try {
        authenticationResult = restAuthenticationService.authenticate(requestBody, request, response).orElseThrow(AuthenticationException::new);
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Authentication failed");
    }
    val amz = casProperties.getAmazonSts();
    val principal = authenticationResult.getAuthentication().getPrincipal();
    LOGGER.debug("Authenticated principal: [{}]", principal);
    val authz = authorizePrincipal(amz, principal);
    if (authz.isPresent()) {
        return authz.get();
    }
    val credentials = ChainingAWSCredentialsProvider.getInstance(amz.getCredentialAccessKey(), amz.getCredentialSecretKey(), amz.getProfilePath(), StringUtils.defaultString(profile, amz.getProfileName()));
    val builder = StsClient.builder();
    AmazonClientConfigurationBuilder.prepareClientBuilder(builder, credentials, amz);
    val client = builder.build();
    if (amz.isRbacEnabled()) {
        val attributeValues = principal.getAttributes().get(amz.getPrincipalAttributeName());
        LOGGER.debug("Found roles [{}]", attributeValues);
        if (attributeValues.size() > 1) {
            if (StringUtils.isBlank(roleArn)) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Found multiple roles and none is specified. Current roles: " + attributeValues);
            }
            if (attributeValues.stream().noneMatch(value -> RegexUtils.find(roleArn, value.toString()))) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Specified role is not allowed. Current roles:" + attributeValues);
            }
        }
        val role = StringUtils.defaultString(roleArn, attributeValues.get(0).toString());
        LOGGER.debug("Using role [{}]", role);
        val roleRequest = AssumeRoleRequest.builder().durationSeconds(Long.valueOf(Beans.newDuration(duration).toSeconds()).intValue()).roleArn(role).roleSessionName(UUID.randomUUID().toString()).serialNumber(serialNumber).tokenCode(tokenCode).build();
        val sessionResult = client.assumeRole(roleRequest);
        val stsCredentials = sessionResult.credentials();
        return createOutputResponse(amz, stsCredentials);
    }
    val sessionTokenRequest = GetSessionTokenRequest.builder().durationSeconds(Long.valueOf(Beans.newDuration(duration).toSeconds()).intValue()).serialNumber(serialNumber).tokenCode(tokenCode).build();
    val sessionResult = client.getSessionToken(sessionTokenRequest);
    val stsCredentials = sessionResult.credentials();
    return createOutputResponse(amz, stsCredentials);
}
Also used : lombok.val(lombok.val) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) PostMapping(org.springframework.web.bind.annotation.PostMapping) Operation(io.swagger.v3.oas.annotations.Operation)

Example 89 with Parameter

use of io.swagger.v3.oas.models.parameters.Parameter in project cas by apereo.

the class OidcJwksEndpointController method handleRequestInternal.

/**
 * Handle request for jwk set.
 *
 * @param request  the request
 * @param response the response
 * @param state    the state
 * @return the jwk set
 */
@GetMapping(value = { '/' + OidcConstants.BASE_OIDC_URL + '/' + OidcConstants.JWKS_URL, "/**/" + OidcConstants.JWKS_URL }, produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Produces the collection of keys from the keystore", parameters = { @Parameter(name = "state", description = "Filter keys by their state name", required = false) })
public ResponseEntity<String> handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response, @RequestParam(value = "state", required = false) final String state) {
    val webContext = new JEEContext(request, response);
    if (!getConfigurationContext().getOidcRequestSupport().isValidIssuerForEndpoint(webContext, OidcConstants.JWKS_URL)) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
    try {
        val resource = oidcJsonWebKeystoreGeneratorService.generate();
        val jsonJwks = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8);
        val jsonWebKeySet = new JsonWebKeySet(jsonJwks);
        val servicesManager = getConfigurationContext().getServicesManager();
        servicesManager.getAllServicesOfType(OidcRegisteredService.class).stream().filter(s -> {
            val serviceJwks = SpringExpressionLanguageValueResolver.getInstance().resolve(s.getJwks());
            return StringUtils.isNotBlank(serviceJwks);
        }).forEach(service -> {
            val set = OidcJsonWebKeyStoreUtils.getJsonWebKeySet(service, getConfigurationContext().getApplicationContext(), Optional.empty());
            set.ifPresent(keys -> keys.getJsonWebKeys().forEach(jsonWebKeySet::addJsonWebKey));
        });
        if (StringUtils.isNotBlank(state)) {
            jsonWebKeySet.getJsonWebKeys().removeIf(key -> {
                val st = OidcJsonWebKeystoreRotationService.JsonWebKeyLifecycleStates.getJsonWebKeyState(key).name();
                return !state.equalsIgnoreCase(st);
            });
        }
        val body = jsonWebKeySet.toJson(JsonWebKey.OutputControlLevel.PUBLIC_ONLY);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        return new ResponseEntity<>(body, HttpStatus.OK);
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
        return new ResponseEntity<>(StringEscapeUtils.escapeHtml4(e.getMessage()), HttpStatus.BAD_REQUEST);
    }
}
Also used : lombok.val(lombok.val) RequestParam(org.springframework.web.bind.annotation.RequestParam) StringUtils(org.apache.commons.lang3.StringUtils) OidcJsonWebKeystoreRotationService(org.apereo.cas.oidc.jwks.rotation.OidcJsonWebKeystoreRotationService) LoggingUtils(org.apereo.cas.util.LoggingUtils) Operation(io.swagger.v3.oas.annotations.Operation) HttpServletRequest(javax.servlet.http.HttpServletRequest) BaseOidcController(org.apereo.cas.oidc.web.controllers.BaseOidcController) GetMapping(org.springframework.web.bind.annotation.GetMapping) JEEContext(org.pac4j.core.context.JEEContext) OidcConstants(org.apereo.cas.oidc.OidcConstants) JsonWebKey(org.jose4j.jwk.JsonWebKey) MediaType(org.springframework.http.MediaType) lombok.val(lombok.val) HttpServletResponse(javax.servlet.http.HttpServletResponse) StringEscapeUtils(org.apache.commons.text.StringEscapeUtils) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet) StandardCharsets(java.nio.charset.StandardCharsets) OidcJsonWebKeystoreGeneratorService(org.apereo.cas.oidc.jwks.generator.OidcJsonWebKeystoreGeneratorService) OidcConfigurationContext(org.apereo.cas.oidc.OidcConfigurationContext) Parameter(io.swagger.v3.oas.annotations.Parameter) IOUtils(org.apache.commons.io.IOUtils) HttpStatus(org.springframework.http.HttpStatus) Slf4j(lombok.extern.slf4j.Slf4j) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) SpringExpressionLanguageValueResolver(org.apereo.cas.util.spring.SpringExpressionLanguageValueResolver) OidcJsonWebKeyStoreUtils(org.apereo.cas.oidc.jwks.OidcJsonWebKeyStoreUtils) Optional(java.util.Optional) ResponseEntity(org.springframework.http.ResponseEntity) ResponseEntity(org.springframework.http.ResponseEntity) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) JEEContext(org.pac4j.core.context.JEEContext) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet) GetMapping(org.springframework.web.bind.annotation.GetMapping) Operation(io.swagger.v3.oas.annotations.Operation)

Example 90 with Parameter

use of io.swagger.v3.oas.models.parameters.Parameter in project cas by apereo.

the class SamlRegisteredServiceCachedMetadataEndpoint method getCachedMetadataObject.

/**
 * Gets cached metadata object.
 *
 * @param serviceId the service id
 * @param entityId  the entity id
 * @return the cached metadata object
 */
@ReadOperation
@Operation(summary = "Get SAML2 cached metadata", parameters = { @Parameter(name = "serviceId", required = true), @Parameter(name = "entityId") })
public Map<String, Object> getCachedMetadataObject(final String serviceId, @Nullable final String entityId) {
    try {
        val registeredService = findRegisteredService(serviceId);
        val issuer = StringUtils.defaultIfBlank(entityId, registeredService.getServiceId());
        val criteriaSet = new CriteriaSet();
        criteriaSet.add(new EntityIdCriterion(issuer));
        criteriaSet.add(new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME));
        val metadataResolver = cachingMetadataResolver.resolve(registeredService, criteriaSet);
        val iteration = metadataResolver.resolve(criteriaSet).spliterator();
        return StreamSupport.stream(iteration, false).map(entity -> Pair.of(entity.getEntityID(), SamlUtils.transformSamlObject(openSamlConfigBean, entity).toString())).collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
        return CollectionUtils.wrap("error", e.getMessage());
    }
}
Also used : lombok.val(lombok.val) CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) ReadOperation(org.springframework.boot.actuate.endpoint.annotation.ReadOperation) SamlRegisteredServiceCachingMetadataResolver(org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver) StringUtils(org.apache.commons.lang3.StringUtils) DeleteOperation(org.springframework.boot.actuate.endpoint.annotation.DeleteOperation) SamlUtils(org.apereo.cas.support.saml.SamlUtils) LoggingUtils(org.apereo.cas.util.LoggingUtils) Operation(io.swagger.v3.oas.annotations.Operation) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) CollectionUtils(org.apereo.cas.util.CollectionUtils) Nullable(org.springframework.lang.Nullable) StreamSupport(java.util.stream.StreamSupport) ServicesManager(org.apereo.cas.services.ServicesManager) AuditableContext(org.apereo.cas.audit.AuditableContext) Endpoint(org.springframework.boot.actuate.endpoint.annotation.Endpoint) Collection(java.util.Collection) lombok.val(lombok.val) Collectors(java.util.stream.Collectors) RegisteredService(org.apereo.cas.services.RegisteredService) BaseCasActuatorEndpoint(org.apereo.cas.web.BaseCasActuatorEndpoint) SPSSODescriptor(org.opensaml.saml.saml2.metadata.SPSSODescriptor) OpenSamlConfigBean(org.apereo.cas.support.saml.OpenSamlConfigBean) Parameter(io.swagger.v3.oas.annotations.Parameter) Slf4j(lombok.extern.slf4j.Slf4j) AuditableExecution(org.apereo.cas.audit.AuditableExecution) EntityRoleCriterion(org.opensaml.saml.criterion.EntityRoleCriterion) NumberUtils(org.apache.commons.lang3.math.NumberUtils) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) EntityRoleCriterion(org.opensaml.saml.criterion.EntityRoleCriterion) ReadOperation(org.springframework.boot.actuate.endpoint.annotation.ReadOperation) ReadOperation(org.springframework.boot.actuate.endpoint.annotation.ReadOperation) DeleteOperation(org.springframework.boot.actuate.endpoint.annotation.DeleteOperation) Operation(io.swagger.v3.oas.annotations.Operation)

Aggregations

Parameter (io.swagger.v3.oas.models.parameters.Parameter)48 Test (org.testng.annotations.Test)39 Operation (io.swagger.v3.oas.models.Operation)28 Operation (io.swagger.v3.oas.annotations.Operation)27 lombok.val (lombok.val)26 OpenAPI (io.swagger.v3.oas.models.OpenAPI)20 Map (java.util.Map)17 ArrayList (java.util.ArrayList)16 ReadOperation (org.springframework.boot.actuate.endpoint.annotation.ReadOperation)15 OpenAPI3RequestValidationHandlerImpl (io.vertx.ext.web.api.contract.openapi3.impl.OpenAPI3RequestValidationHandlerImpl)14 Test (org.junit.Test)14 PathItem (io.swagger.v3.oas.models.PathItem)13 QueryParameter (io.swagger.v3.oas.models.parameters.QueryParameter)13 StringUtils (org.apache.commons.lang3.StringUtils)13 StringSchema (io.swagger.v3.oas.models.media.StringSchema)12 LinkedHashMap (java.util.LinkedHashMap)12 Parameter (io.swagger.v3.oas.annotations.Parameter)11 RequestParameters (io.vertx.ext.web.api.RequestParameters)11 HashMap (java.util.HashMap)11 Schema (io.swagger.v3.oas.models.media.Schema)10