GeezerVison is showing github.com — feat: Apply Intermediate TLS defaults on API fallback and handle transient errors by ugiordan · Pull Request #6587 · feast-dev/feast
feat: Apply Intermediate TLS defaults on API fallback and handle transient errors
#6587
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
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.go
(3)
No extension
(1)
All 2 file types selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -12,7 +12,7 @@ COPY --chown=1001:0 go.sum go.sum
RUN go mod download
# Copy the go source
COPY --chown=1001:0 cmd/main.go cmd/main.go
COPY --chown=1001:0 cmd/ cmd/
COPY --chown=1001:0 api/ api/
COPY --chown=1001:0 internal/controller/ internal/controller/
Expand All
@@ -21,7 +21,7 @@ COPY --chown=1001:0 internal/controller/ internal/controller/
# was called. For example, if we call make docker-build in a local env which has the Apple Silicon M1 SO
# the docker BUILDPLATFORM arg will be linux/arm64 when for Apple x86 it will be linux/amd64. Therefore,
# by leaving it empty we can ensure that the container and binary shipped on it will have the same platform.
RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -a -o manager cmd/main.go
RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -a -o manager ./ cmd/
FROM registry.access.redhat.com/ubi9/ubi-minimal:9.8
WORKDIR /
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -34,8 +34,6 @@ import (
corev1 "k8s.io/api/core/v1"
policyv1 "k8s.io/api/policy/v1"
rbacv1 "k8s.io/api/rbac/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
apimeta "k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
Expand Down
Expand Up
@@ -102,7 +100,7 @@ func main() {
var probeAddr string
var secureMetrics bool
var featureStoreMetrics bool
var tlsOpts []func(*tls.Config)
tlsOpts := make( []func(*tls.Config), 0, 2 )
flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+
"Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.")
flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.")
Expand Down
Expand Up
@@ -130,46 +128,12 @@ func main() {
os.Exit(1)
}
tlsProfileFetched := false
tlsProfile, err := tlspkg.FetchAPIServerTLSProfile(context.Background(), bootstrapClient)
tlsResult, err := bootstrapTLS(context.Background(), bootstrapClient)
if err != nil {
switch {
case apimeta.IsNoMatchError(err):
setupLog.Info("TLS profile not available, using hardened defaults (non-OpenShift cluster)")
case apierrors.IsNotFound(err):
setupLog.Info("APIServer resource not found, using hardened defaults")
default:
setupLog.Error(err, "unable to read APIServer TLS profile, refusing to start with unknown TLS posture")
os.Exit(1)
}
} else {
tlsProfileFetched = true
tlsConfigFn, unsupported := tlspkg.NewTLSConfigFromProfile(tlsProfile)
if len(unsupported) > 0 {
setupLog.Info("TLS profile contains ciphers unsupported by Go", "unsupported", unsupported)
}
tlsOpts = append(tlsOpts, tlsConfigFn)
}
tlsAdherenceFetched := false
tlsAdherence, err := tlspkg.FetchAPIServerTLSAdherencePolicy(context.Background(), bootstrapClient)
if err != nil {
switch {
case apimeta.IsNoMatchError(err):
setupLog.Info("TLS adherence policy not available (non-OpenShift cluster)")
case apierrors.IsNotFound(err):
setupLog.Info("APIServer resource not found, skipping adherence policy")
default:
setupLog.Error(err, "unable to read APIServer TLS adherence policy, refusing to start")
os.Exit(1)
}
} else {
tlsAdherenceFetched = true
setupLog.Error(err, "TLS bootstrap failed")
os.Exit(1)
}
tlsOpts = append(tlsOpts, func(c *tls.Config) {
c.NextProtos = []string{"h2", "http/1.1"}
})
tlsOpts = append(tlsOpts, tlsResult.TLSOpts...)
webhookServer := webhook.NewServer(webhook.Options{
TLSOpts: tlsOpts,
Expand Down
Expand Up
@@ -271,17 +235,17 @@ func main() {
ctx, cancel := context.WithCancel(ctrl.SetupSignalHandler())
defer cancel()
if tlsProfileFetched {
if tlsResult.ProfileFetched {
watcher := &tlspkg.SecurityProfileWatcher{
Client: mgr.GetClient(),
InitialTLSProfileSpec: tlsProfile ,
InitialTLSProfileSpec: tlsResult.ProfileSpec ,
OnProfileChange: func(_ context.Context, _, _ configv1.TLSProfileSpec) {
setupLog.Info("TLS profile changed, initiating shutdown to reload")
cancel()
},
}
if tlsAdherenceFetched {
watcher.InitialTLSAdherencePolicy = tlsAdherence
if tlsResult.AdherenceFetched {
watcher.InitialTLSAdherencePolicy = tlsResult.AdherencePolicy
watcher.OnAdherencePolicyChange = func(_ context.Context, _, _ configv1.TLSAdherencePolicy) {
setupLog.Info("TLS adherence policy changed, initiating shutdown to reload")
cancel()
Expand Down
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,134 @@
/*
Copyright 2024 Feast Community.
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 main
import (
"context"
"crypto/tls"
"errors"
"fmt"
"time"
configv1 "github.com/openshift/api/config/v1"
tlspkg "github.com/openshift/controller-runtime-common/pkg/tls"
apierrors "k8s.io/apimachinery/pkg/api/errors"
apimeta "k8s.io/apimachinery/pkg/api/meta"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
)
const (
tlsFetchTimeout = 10 * time.Second
alpnH2 = "h2"
alpnHTTP11 = "http/1.1"
)
type tlsBootstrapResult struct {
TLSOpts []func(*tls.Config)
ProfileFetched bool
ProfileSpec configv1.TLSProfileSpec
AdherenceFetched bool
AdherencePolicy configv1.TLSAdherencePolicy
UnsupportedCiphers []string
}
func fetchTLSProfile(ctx context.Context, k8sClient client.Client) (configv1.TLSProfileSpec, bool, error) {
fetchCtx, cancel := context.WithTimeout(ctx, tlsFetchTimeout)
defer cancel()
profile, err := tlspkg.FetchAPIServerTLSProfile(fetchCtx, k8sClient)
if err != nil {
return classifyTLSProfileError(err)
}
return profile, true, nil
}
func classifyTLSProfileError(err error) (configv1.TLSProfileSpec, bool, error) {
intermediate := *configv1.TLSProfiles[configv1.TLSProfileIntermediateType]
switch {
case apimeta.IsNoMatchError(err):
return intermediate, false, nil
case apierrors.IsNotFound(err):
return intermediate, false, nil
case isTransientError(err):
return intermediate, true, nil
default:
return configv1.TLSProfileSpec{}, false, fmt.Errorf("unable to read APIServer TLS profile: %w", err)
}
}
func fetchTLSAdherencePolicy(ctx context.Context, k8sClient client.Client) (configv1.TLSAdherencePolicy, bool, error) {
fetchCtx, cancel := context.WithTimeout(ctx, tlsFetchTimeout)
defer cancel()
policy, err := tlspkg.FetchAPIServerTLSAdherencePolicy(fetchCtx, k8sClient)
if err == nil {
return policy, true, nil
}
switch {
case apimeta.IsNoMatchError(err),
apierrors.IsNotFound(err),
isTransientError(err):
return "", false, nil
default:
return "", false, fmt.Errorf("unable to read APIServer TLS adherence policy: %w", err)
}
}
func bootstrapTLS(ctx context.Context, k8sClient client.Client) (*tlsBootstrapResult, error) {
logger := log.FromContext(ctx)
result := &tlsBootstrapResult{
TLSOpts: make([]func(*tls.Config), 0, 2),
}
profile, profileFetched, err := fetchTLSProfile(ctx, k8sClient)
if err != nil {
return nil, err
}
result.ProfileFetched = profileFetched
result.ProfileSpec = profile
tlsConfigFn, unsupported := tlspkg.NewTLSConfigFromProfile(profile)
result.UnsupportedCiphers = unsupported
if len(unsupported) > 0 {
logger.Info("TLS profile contains ciphers unsupported by Go", "unsupported", unsupported)
}
result.TLSOpts = append(result.TLSOpts, tlsConfigFn)
adherence, adherenceFetched, err := fetchTLSAdherencePolicy(ctx, k8sClient)
if err != nil {
Comment thread
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more .
dead code - function returns error but can never return a non-nil error.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
return nil, err
}
result.AdherenceFetched = adherenceFetched
result.AdherencePolicy = adherence
result.TLSOpts = append(result.TLSOpts, func(c *tls.Config) {
c.NextProtos = []string{alpnH2, alpnHTTP11}
})
return result, nil
}
func isTransientError(err error) bool {
return apierrors.IsServiceUnavailable(err) ||
apierrors.IsTimeout(err) ||
apierrors.IsServerTimeout(err) ||
apierrors.IsTooManyRequests(err) ||
errors.Is(err, context.DeadlineExceeded)
}
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.