-
Notifications
You must be signed in to change notification settings - Fork 4
Embed cluster CA in kubeconfig if necessary #37
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
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
539c1bf
feat: embed cluster CA in kubeconfig via TLS probe
matejvasek 945abf9
fix: skip public CAs in cluster CA probe
matejvasek 880dff7
refactor: use handler struct for cluster CA
matejvasek 53fc9d2
fix: return 500 when CA file is missing
matejvasek fac27ed
feat: add --kube-root-ca-path flag for local dev
matejvasek ea3bc97
test: add tests for empty and malformed CA files
matejvasek af5d559
docs: update progress log for kubeconfig CA session
matejvasek 9cd7743
refactor: split backend handlers into separate files
matejvasek 4571907
perf: cache CA file read with sync.Once
matejvasek File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "crypto/tls" | ||
| "crypto/x509" | ||
| "encoding/base64" | ||
| "encoding/pem" | ||
| "net" | ||
| "net/http" | ||
| "net/url" | ||
| "os" | ||
| "sync" | ||
| "time" | ||
| ) | ||
|
|
||
| const defaultCAPath = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt" | ||
|
|
||
| // clusterCAHandler probes the API server's TLS certificate to decide whether | ||
| // to return the service account CA bundle for embedding in a kubeconfig. | ||
| type clusterCAHandler struct { | ||
| // CAPath is the path to the service account CA certificate file. | ||
| CAPath string | ||
| // SystemTLS returns the TLS config used for the system roots probe. | ||
| // When nil, an empty tls.Config (system trust store) is used. | ||
| SystemTLS func() *tls.Config | ||
|
|
||
| caOnce sync.Once | ||
| caPEM []byte | ||
| caPool *x509.CertPool | ||
| caErr string | ||
| } | ||
|
|
||
| func (h *clusterCAHandler) systemTLSConfig() *tls.Config { | ||
| if h.SystemTLS != nil { | ||
| return h.SystemTLS() | ||
| } | ||
| return &tls.Config{} | ||
| } | ||
|
|
||
| // loadCA reads and parses the CA file, storing results on the struct. | ||
| func (h *clusterCAHandler) loadCA() { | ||
| data, err := os.ReadFile(h.CAPath) | ||
| if err != nil { | ||
| h.caErr = "failed to read CA file: " + err.Error() | ||
| return | ||
| } | ||
|
|
||
| pool := x509.NewCertPool() | ||
| rest := data | ||
| var found bool | ||
| for { | ||
| var block *pem.Block | ||
| block, rest = pem.Decode(rest) | ||
| if block == nil { | ||
| break | ||
| } | ||
| if block.Type != "CERTIFICATE" { | ||
| continue | ||
| } | ||
|
|
||
| cert, err := x509.ParseCertificate(block.Bytes) | ||
| if err != nil { | ||
| h.caErr = "failed to parse CA certificate: " + err.Error() | ||
| return | ||
| } | ||
| pool.AddCert(cert) | ||
| found = true | ||
| } | ||
| if !found { | ||
| h.caErr = "no valid certificates found in CA file" | ||
| return | ||
| } | ||
|
|
||
| h.caPEM = data | ||
| h.caPool = pool | ||
| } | ||
|
|
||
| func (h *clusterCAHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | ||
| serverParam := r.URL.Query().Get("server") | ||
| if serverParam == "" { | ||
| jsonError(w, "missing required query parameter: server", http.StatusBadRequest) | ||
| return | ||
| } | ||
|
|
||
| parsed, err := url.Parse(serverParam) | ||
| if err != nil || parsed.Scheme != "https" { | ||
| jsonError(w, "server must be an HTTPS URL", http.StatusBadRequest) | ||
| return | ||
| } | ||
|
|
||
| host := parsed.Host | ||
| if parsed.Port() == "" { | ||
| host = host + ":443" | ||
| } | ||
|
|
||
| // Probe 1: try system trust store. If the server's cert is publicly | ||
| // trusted, there is no need to embed a CA in the kubeconfig. | ||
| dialer := &net.Dialer{Timeout: 5 * time.Second} | ||
| if conn, err := tls.DialWithDialer(dialer, "tcp", host, h.systemTLSConfig()); err == nil { | ||
| conn.Close() | ||
| jsonOK(w, map[string]interface{}{"ca": nil}) | ||
| return | ||
| } | ||
|
|
||
| // Probe 2: try the service account CA bundle. If it verifies the | ||
| // server, the cert is privately signed and the runner will need it. | ||
| h.caOnce.Do(h.loadCA) | ||
| if h.caErr != "" { | ||
| jsonError(w, h.caErr, http.StatusInternalServerError) | ||
| return | ||
| } | ||
|
|
||
| conn, err := tls.DialWithDialer(dialer, "tcp", host, &tls.Config{ | ||
| RootCAs: h.caPool, | ||
| }) | ||
| if err != nil { | ||
| // Neither system roots nor the SA bundle can verify the server. | ||
| jsonOK(w, map[string]interface{}{"ca": nil}) | ||
| return | ||
| } | ||
| conn.Close() | ||
|
|
||
| encoded := base64.StdEncoding.EncodeToString(h.caPEM) | ||
| jsonOK(w, map[string]string{"ca": encoded}) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,163 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "io" | ||
| "io/fs" | ||
| "log" | ||
| "net/http" | ||
| "os" | ||
| "path/filepath" | ||
| "regexp" | ||
| "strings" | ||
|
|
||
| cigithub "knative.dev/func/pkg/ci/github" | ||
| "knative.dev/func/pkg/functions" | ||
| ) | ||
|
|
||
| type funcCreateRequest struct { | ||
| Name string `json:"name"` | ||
| Runtime string `json:"runtime"` | ||
| Registry string `json:"registry"` | ||
| Namespace string `json:"namespace"` | ||
| Branch string `json:"branch"` | ||
| } | ||
|
|
||
| // validName restricts function names to lowercase DNS-label characters. | ||
| var validName = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]*[a-z0-9])?$`) | ||
|
|
||
| // validRuntimes is the set of supported function runtimes. | ||
| var validRuntimes = map[string]bool{ | ||
| "node": true, "python": true, "go": true, "quarkus": true, | ||
| } | ||
|
|
||
| // validBranch restricts branch names to safe git ref characters. | ||
| var validBranch = regexp.MustCompile(`^[a-zA-Z0-9]([a-zA-Z0-9._/-]*[a-zA-Z0-9])?$`) | ||
|
|
||
| // validNamespace restricts namespaces to valid Kubernetes names. | ||
| var validNamespace = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]*[a-z0-9])?$`) | ||
|
|
||
| type fileEntry struct { | ||
| Path string `json:"path"` | ||
| Mode string `json:"mode"` | ||
| Content string `json:"content"` | ||
| Type string `json:"type"` | ||
| } | ||
|
|
||
| func handleFuncCreate(w http.ResponseWriter, r *http.Request) { | ||
| var cfg funcCreateRequest | ||
| r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // 1 MB limit | ||
| if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil { | ||
| jsonError(w, "invalid request body: "+err.Error(), http.StatusBadRequest) | ||
| return | ||
| } | ||
|
|
||
| if !validName.MatchString(cfg.Name) { | ||
| jsonError(w, "invalid function name: must contain only lowercase alphanumeric characters and hyphens", http.StatusBadRequest) | ||
| return | ||
| } | ||
| if !validRuntimes[cfg.Runtime] { | ||
| jsonError(w, "invalid runtime: must be one of node, python, go, quarkus", http.StatusBadRequest) | ||
| return | ||
| } | ||
| if !validBranch.MatchString(cfg.Branch) { | ||
| jsonError(w, "invalid branch name", http.StatusBadRequest) | ||
| return | ||
| } | ||
| if !validNamespace.MatchString(cfg.Namespace) { | ||
| jsonError(w, "invalid namespace: must contain only lowercase alphanumeric characters and hyphens", http.StatusBadRequest) | ||
| return | ||
| } | ||
|
|
||
| tmpDir, err := os.MkdirTemp("", "func-create-*") | ||
| if err != nil { | ||
| jsonError(w, "failed to create temp dir: "+err.Error(), http.StatusInternalServerError) | ||
| return | ||
| } | ||
| defer os.RemoveAll(tmpDir) | ||
|
|
||
| root := filepath.Join(tmpDir, cfg.Name) | ||
|
|
||
| client := functions.New() | ||
| _, err = client.Init(functions.Function{ | ||
| Name: cfg.Name, | ||
| Root: root, | ||
| Runtime: cfg.Runtime, | ||
| Registry: cfg.Registry, | ||
| Namespace: cfg.Namespace, | ||
| Template: "http", | ||
| }) | ||
| if err != nil { | ||
| jsonError(w, "failed to initialize function: "+err.Error(), http.StatusInternalServerError) | ||
| return | ||
| } | ||
|
|
||
| if err := generateCIWorkflow(root, cfg.Runtime, cfg.Branch, cfg.Registry); err != nil { | ||
| jsonError(w, "failed to generate CI workflow: "+err.Error(), http.StatusInternalServerError) | ||
| return | ||
| } | ||
|
|
||
| var files []fileEntry | ||
| err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if d.IsDir() { | ||
| return nil | ||
| } | ||
| relPath, err := filepath.Rel(root, path) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| content, err := os.ReadFile(path) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| mode := "100644" | ||
| info, err := d.Info() | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if info.Mode()&0111 != 0 { | ||
| mode = "100755" | ||
| } | ||
| if info.Mode()&os.ModeSymlink != 0 { | ||
| mode = "120000" | ||
| } | ||
| files = append(files, fileEntry{ | ||
| Path: relPath, | ||
| Mode: mode, | ||
| Content: string(content), | ||
| Type: "blob", | ||
| }) | ||
| return nil | ||
| }) | ||
| if err != nil { | ||
| jsonError(w, "failed to read generated files: "+err.Error(), http.StatusInternalServerError) | ||
| return | ||
| } | ||
|
|
||
| w.Header().Set("Content-Type", "application/json") | ||
| if err := json.NewEncoder(w).Encode(files); err != nil { | ||
| log.Printf("failed to encode response: %v", err) | ||
| } | ||
| } | ||
|
|
||
| const ocpInternalRegistry = "image-registry.openshift-image-registry.svc:5000/" | ||
|
|
||
| func generateCIWorkflow(root, runtime, branch, registry string) error { | ||
| gen := cigithub.NewWorkflowGenerator( | ||
| cigithub.WithWorkflowConfig(cigithub.WorkflowConfig{ | ||
| Branch: branch, | ||
| RegistryLogin: !strings.HasPrefix(registry, ocpInternalRegistry), | ||
| TestStep: cigithub.DefaultTestStep, | ||
| }), | ||
| cigithub.WithMessageWriter(io.Discard), | ||
| ) | ||
|
|
||
| return gen.Generate(context.Background(), functions.Function{ | ||
| Root: root, | ||
| Runtime: runtime, | ||
| }) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.