Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add: MTLS Support in API level #1349

Closed
wants to merge 12 commits into from
2 changes: 1 addition & 1 deletion adapter/internal/oasparser/config_generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ func GetEnforcerAPI(adapterInternalAPI model.AdapterInternalAPI, vhost string) *
BackendJWTTokenInfo: backendJWTTokenInfo,
// IsMockedApi: isMockedAPI,
ClientCertificates: clientCertificates,
MutualSSL: adapterInternalAPI.GetXWSO2MutualSSL(),
MutualSSL: adapterInternalAPI.GetMutualSSL(),
ApplicationSecurity: adapterInternalAPI.GetXWSO2ApplicationSecurity(),
// GraphQLSchema: adapterInternalAPI.GraphQLSchema,
// GraphqlComplexityInfo: adapterInternalAPI.GraphQLComplexities.Data.List,
Expand Down
14 changes: 7 additions & 7 deletions adapter/internal/oasparser/model/adapter_internal_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ type AdapterInternalAPI struct {
xWso2RequestBodyPass bool
IsDefaultVersion bool
clientCertificates []Certificate
xWso2MutualSSL string
mutualSSL string
xWso2ApplicationSecurity bool
EnvType string
backendJWTTokenInfo *BackendJWTTokenInfo
Expand Down Expand Up @@ -355,14 +355,14 @@ func (swagger *AdapterInternalAPI) GetXWSO2AuthHeader() string {
return swagger.xWso2AuthHeader
}

// SetXWSO2MutualSSL sets the optional or mandatory mTLS
func (swagger *AdapterInternalAPI) SetXWSO2MutualSSL(mutualSSl string) {
swagger.xWso2MutualSSL = mutualSSl
// SetMutualSSL sets the optional or mandatory mTLS
func (swagger *AdapterInternalAPI) SetMutualSSL(mutualSSl string) {
swagger.mutualSSL = mutualSSl
}

// GetXWSO2MutualSSL returns the optional or mandatory mTLS
func (swagger *AdapterInternalAPI) GetXWSO2MutualSSL() string {
return swagger.xWso2MutualSSL
// GetMutualSSL returns the optional or mandatory mTLS
func (swagger *AdapterInternalAPI) GetMutualSSL() string {
return swagger.mutualSSL
}

// SetXWSO2ApplicationSecurity sets the optional or mandatory application security
Expand Down
7 changes: 7 additions & 0 deletions adapter/internal/oasparser/model/http_route.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ func (swagger *AdapterInternalAPI) SetInfoHTTPRouteCR(httpRoute *gwapiv1b1.HTTPR
if authScheme.Spec.Override != nil && authScheme.Spec.Override.ExternalService.Disabled != nil {
disableAuthentications = *authScheme.Spec.Override.ExternalService.Disabled
}
var mutualSSL string
if authScheme.Spec.Override != nil && authScheme.Spec.Default != nil && authScheme.Spec.Default.ExternalService.AuthTypes != nil && authScheme.Spec.Override.ExternalService.AuthTypes != nil && authScheme.Spec.Override.ExternalService.AuthTypes.MutualSSL == "" {
mutualSSL = authScheme.Spec.Default.ExternalService.AuthTypes.MutualSSL
} else if authScheme.Spec.Override != nil && authScheme.Spec.Override.ExternalService.AuthTypes != nil && authScheme.Spec.Override.ExternalService.AuthTypes.MutualSSL != "" {
mutualSSL = authScheme.Spec.Override.ExternalService.AuthTypes.MutualSSL
}
swagger.mutualSSL = mutualSSL
}
var apiPolicy *dpv1alpha1.APIPolicy
if outputAPIPolicy != nil {
Expand Down
4 changes: 4 additions & 0 deletions adapter/internal/operator/PROJECT
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ resources:
kind: Authentication
path: github.com/wso2/apk/adapter/internal/operator/apis/dp/v1alpha1
version: v1alpha1
webhooks:
defaulting: true
validation: true
webhookVersion: v1
- api:
crdVersion: v1
namespaced: true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ type ServiceRef struct {

// APIAuth Authentication scheme type and details
type APIAuth struct {
// +optional
// +kubebuilder:validation:Enum=mandatory;optional
MutualSSL string `json:"mutualSSL,omitempty"`
JWT JWTAuth `json:"jwt,omitempty"`
APIKey []APIKeyAuth `json:"apiKey,omitempty"`
TestConsoleKey TestConsoleKeyAuth `json:"testConsoleKey,omitempty"`
Expand Down
105 changes: 105 additions & 0 deletions adapter/internal/operator/apis/dp/v1alpha1/authentication_webhook.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
* Copyright (c) 2022, WSO2 LLC. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

package v1alpha1

import (
"fmt"

apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/validation/field"
ctrl "sigs.k8s.io/controller-runtime"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/webhook"
)

// log is for logging in this package.
var authenticationlog = logf.Log.WithName("authentication-resource")

// SetupWebhookWithManager sets up and registers the webhook with the manager.
func (r *Authentication) SetupWebhookWithManager(mgr ctrl.Manager) error {
return ctrl.NewWebhookManagedBy(mgr).
For(r).
Complete()
}

// TODO(user): EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!

//+kubebuilder:webhook:path=/mutate-dp-wso2-com-v1alpha1-authentication,mutating=true,failurePolicy=fail,sideEffects=None,groups=dp.wso2.com,resources=authentications,verbs=create;update,versions=v1alpha1,name=mauthentication.kb.io,admissionReviewVersions=v1

var _ webhook.Defaulter = &Authentication{}

// Default implements webhook.Defaulter so a webhook will be registered for the type
func (r *Authentication) Default() {
authenticationlog.Info("default", "name", r.Name)

// TODO(user): fill in your defaulting logic.
}

// TODO(user): change verbs to "verbs=create;update;delete" if you want to enable deletion validation.
//+kubebuilder:webhook:path=/validate-dp-wso2-com-v1alpha1-authentication,mutating=false,failurePolicy=fail,sideEffects=None,groups=dp.wso2.com,resources=authentications,verbs=create;update,versions=v1alpha1,name=vauthentication.kb.io,admissionReviewVersions=v1

var _ webhook.Validator = &Authentication{}

// ValidateCreate implements webhook.Validator so a webhook will be registered for the type
func (r *Authentication) ValidateCreate() error {
fmt.Println("Auth validate create")
return r.validateAuthentication()
}

// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type
func (r *Authentication) ValidateUpdate(old runtime.Object) error {
return r.validateAuthentication()
}

// ValidateDelete implements webhook.Validator so a webhook will be registered for the type
func (r *Authentication) ValidateDelete() error {
authenticationlog.Info("validate delete", "name", r.Name)

// TODO(user): fill in your validation logic upon object deletion.
return nil
}

func (r *Authentication) validateAuthentication() error {
var allErrs field.ErrorList
var isMtlsDefault bool
var mtlsOverride string
if r.Spec.Default != nil && r.Spec.Default.ExternalService.AuthTypes != nil {
mtlsDefault := r.Spec.Default.ExternalService.AuthTypes.MutualSSL
if mtlsDefault != "" {
isMtlsDefault = true
}
}

if r.Spec.Override != nil && r.Spec.Override.ExternalService.AuthTypes != nil {
mtlsOverride = r.Spec.Override.ExternalService.AuthTypes.MutualSSL
}

if r.Spec.Override != nil && r.Spec.Override.ExternalService.AuthTypes != nil && mtlsOverride == "" && !isMtlsDefault {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec").Child("override").Child("ext").Child("authTypes").Child("mutualSSL"),
r.Spec.Override.ExternalService.AuthTypes.MutualSSL, "mutualSSL is mandatory when default is not set"))
}

if len(allErrs) > 0 {
return apierrors.NewInvalid(
schema.GroupKind{Group: "dp.wso2.com", Kind: "Authentication"},
r.Name, allErrs)
}
return nil
}
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,9 @@ var _ = BeforeSuite(func() {
err = (&Backend{}).SetupWebhookWithManager(mgr)
Expect(err).NotTo(HaveOccurred())

err = (&Authentication{}).SetupWebhookWithManager(mgr)
Expect(err).NotTo(HaveOccurred())

//+kubebuilder:scaffold:webhook

go func() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,11 @@ spec:
sendTokenToUpstream:
type: boolean
type: object
mutualSSL:
enum:
- mandatory
- optional
type: string
testConsoleKey:
description: TestConsoleKeyAuth Test Console Key Authentication
scheme details
Expand Down Expand Up @@ -153,6 +158,11 @@ spec:
sendTokenToUpstream:
type: boolean
type: object
mutualSSL:
enum:
- mandatory
- optional
type: string
testConsoleKey:
description: TestConsoleKeyAuth Test Console Key Authentication
scheme details
Expand Down
40 changes: 40 additions & 0 deletions adapter/internal/operator/config/webhook/manifests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,26 @@ webhooks:
resources:
- apipolicies
sideEffects: None
- admissionReviewVersions:
- v1
clientConfig:
service:
name: webhook-service
namespace: system
path: /mutate-dp-wso2-com-v1alpha1-authentication
failurePolicy: Fail
name: mauthentication.kb.io
rules:
- apiGroups:
- dp.wso2.com
apiVersions:
- v1alpha1
operations:
- CREATE
- UPDATE
resources:
- authentications
sideEffects: None
- admissionReviewVersions:
- v1
clientConfig:
Expand Down Expand Up @@ -152,6 +172,26 @@ webhooks:
resources:
- apipolicies
sideEffects: None
- admissionReviewVersions:
- v1
clientConfig:
service:
name: webhook-service
namespace: system
path: /validate-dp-wso2-com-v1alpha1-authentication
failurePolicy: Fail
name: vauthentication.kb.io
rules:
- apiGroups:
- dp.wso2.com
apiVersions:
- v1alpha1
operations:
- CREATE
- UPDATE
resources:
- authentications
sideEffects: None
- admissionReviewVersions:
- v1
clientConfig:
Expand Down
6 changes: 5 additions & 1 deletion adapter/internal/operator/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,12 @@ func InitOperator() {
loggers.LoggerAPKOperator.ErrorC(logging.GetErrorByCode(2652, err))
}

if err = (&dpv1alpha1.Authentication{}).SetupWebhookWithManager(mgr); err != nil {
loggers.LoggerAPKOperator.ErrorC(logging.GetErrorByCode(2655, err))
}

if err = (&dpv1alpha1.Backend{}).SetupWebhookWithManager(mgr); err != nil {
loggers.LoggerAPKOperator.ErrorC(logging.GetErrorByCode(3115, err))
loggers.LoggerAPKOperator.ErrorC(logging.GetErrorByCode(2656, err))
}

if err := dpcontrollers.NewGatewayController(mgr, operatorDataStore, updateHandler, &gatewaych); err != nil {
Expand Down
1 change: 1 addition & 0 deletions adapter/internal/operator/synchronizer/synchronizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ func GenerateAdapterInternalAPI(apiState APIState, httpRoute *HTTPRouteState, en
RateLimitPolicies: httpRoute.RateLimitPolicies,
ResourceRateLimitPolicies: httpRoute.ResourceRateLimitPolicies,
}

if err := adapterInternalAPI.SetInfoHTTPRouteCR(httpRoute.HTTPRoute, httpRouteParams); err != nil {
loggers.LoggerAPKOperator.ErrorC(logging.GetErrorByCode(2631, err))
return nil, err
Expand Down
12 changes: 12 additions & 0 deletions adapter/pkg/logging/logging_constant.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ const (
error2652 = 2652
error2653 = 2653
error2654 = 2654
error2655 = 2655
error2656 = 2656
)

// Error Log Pkg auth(3001-3099) Config Constants
Expand Down Expand Up @@ -379,6 +381,16 @@ var Mapper = map[int]ErrorDetails{
Message: "Unable to create webhook for InterceptorService: %v",
Severity: BLOCKER,
},
error2655: {
ErrorCode: error2655,
Message: "Unable to create webhook for Authentication: %v",
Severity: BLOCKER,
},
error2656: {
ErrorCode: error2656,
Message: "Unable to create webhook for Backend: %v",
Severity: BLOCKER,
},
error3001: {
ErrorCode: error3001,
Message: "Error reading ssh key file: %s",
Expand Down
52 changes: 27 additions & 25 deletions developer/tryout/samples/sample-auth.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,33 @@ metadata:
name: sand-http-bin-authentication
spec:
override:
mutualSSL: optional
type: ext
ext:
disabled: true
# serviceRef:
# group: wso2/v1alpha2
# kind: Backend
# name: ext_authz-server
# port: 1234
# authTypes:
# apiKey:
# - in: Header
# name: x-api-key
# default:
# type: ext
# ext:
# serviceRef:
# group: wso2/v1alpha2
# kind: Backend
# name: ext_authz-server
# port: 1234
# authTypes:
# apiKey:
# - in: Header
# name: x-api-key
disabled: false
serviceRef:
group: wso2/v1alpha2
kind: Backend
name: ext_authz-server
port: 1234
authTypes:
apiKey:
- in: Header
name: x-api-key
default:
mutualSSL: ""
type: ext
ext:
serviceRef:
group: wso2/v1alpha2
kind: Backend
name: ext_authz-server
port: 1234
authTypes:
apiKey:
- in: Header
name: x-api-key
targetRef:
kind: Resource
name: http-bin-api #provide API ref name
group: gateway.networking.k8s.io
kind: API
name: http-bin-api1 #provide API ref name
group: ""
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ public String init(Api api) {
.disableScopes(api.getDisableScopes()).trustStore(trustStore).organizationId(api.getOrganizationId())
.mtlsCertificateTiers(mtlsCertificateTiers).mutualSSL(mutualSSL).systemAPI(api.getSystemAPI())
.applicationSecurity(applicationSecurity).jwtConfigurationDto(jwtConfigurationDto)
.apiDefinition(apiDefinition).build();
.apiDefinition(apiDefinition).mutualSSL(api.getMutualSSL()).build();

initFilters();
return basePath;
Expand Down
Loading
Loading