2016-07-25 20:00:28 +00:00
|
|
|
package kubernetes
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2017-03-08 18:33:19 +00:00
|
|
|
"context"
|
2016-07-25 20:00:28 +00:00
|
|
|
"crypto/tls"
|
|
|
|
"crypto/x509"
|
2016-10-27 22:55:23 +00:00
|
|
|
"encoding/base32"
|
2016-10-05 23:04:48 +00:00
|
|
|
"encoding/base64"
|
2016-07-25 20:00:28 +00:00
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
2016-10-27 22:55:23 +00:00
|
|
|
"hash"
|
|
|
|
"hash/fnv"
|
2016-07-25 20:00:28 +00:00
|
|
|
"io"
|
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"path"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
2021-02-15 07:53:59 +00:00
|
|
|
"github.com/Masterminds/semver"
|
2016-11-03 21:32:23 +00:00
|
|
|
"github.com/ghodss/yaml"
|
2017-01-14 00:49:06 +00:00
|
|
|
"golang.org/x/net/http2"
|
2016-07-25 20:00:28 +00:00
|
|
|
|
2019-02-22 12:19:23 +00:00
|
|
|
"github.com/dexidp/dex/pkg/log"
|
2018-09-03 06:44:44 +00:00
|
|
|
"github.com/dexidp/dex/storage"
|
|
|
|
"github.com/dexidp/dex/storage/kubernetes/k8sapi"
|
2016-07-25 20:00:28 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type client struct {
|
2016-10-13 23:50:20 +00:00
|
|
|
client *http.Client
|
|
|
|
baseURL string
|
|
|
|
namespace string
|
2019-02-22 12:19:23 +00:00
|
|
|
logger log.Logger
|
2016-07-25 20:00:28 +00:00
|
|
|
|
2016-10-27 22:55:23 +00:00
|
|
|
// Hash function to map IDs (which could span a large range) to Kubernetes names.
|
|
|
|
// While this is not currently upgradable, it could be in the future.
|
|
|
|
//
|
|
|
|
// The default hash is a non-cryptographic hash, because cryptographic hashes
|
|
|
|
// always produce sums too long to fit into a Kubernetes name. Because of this,
|
|
|
|
// gets, updates, and deletes are _always_ checked for collisions.
|
|
|
|
hash func() hash.Hash
|
|
|
|
|
2016-10-13 23:50:20 +00:00
|
|
|
// API version of the oidc resources. For example "oidc.coreos.com". This is
|
|
|
|
// currently not configurable, but could be in the future.
|
|
|
|
apiVersion string
|
2021-02-15 07:53:59 +00:00
|
|
|
// API version of the custom resource definitions.
|
|
|
|
// Different Kubernetes version requires to create CRD in certain API. It will be discovered automatically on
|
|
|
|
// storage opening.
|
|
|
|
crdAPIVersion string
|
2016-07-25 20:00:28 +00:00
|
|
|
|
2016-10-13 23:50:20 +00:00
|
|
|
// This is called once the client's Close method is called to signal goroutines,
|
|
|
|
// such as the one creating third party resources, to stop.
|
|
|
|
cancel context.CancelFunc
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
|
|
|
|
2016-10-27 22:55:23 +00:00
|
|
|
// idToName maps an arbitrary ID, such as an email or client ID to a Kubernetes object name.
|
2019-12-18 14:50:36 +00:00
|
|
|
func (cli *client) idToName(s string) string {
|
|
|
|
return idToName(s, cli.hash)
|
2016-10-27 22:55:23 +00:00
|
|
|
}
|
|
|
|
|
2017-02-01 00:11:59 +00:00
|
|
|
// offlineTokenName maps two arbitrary IDs, to a single Kubernetes object name.
|
|
|
|
// This is used when more than one field is used to uniquely identify the object.
|
2019-12-18 14:50:36 +00:00
|
|
|
func (cli *client) offlineTokenName(userID string, connID string) string {
|
|
|
|
return offlineTokenName(userID, connID, cli.hash)
|
2017-02-01 00:11:59 +00:00
|
|
|
}
|
|
|
|
|
2016-10-27 22:55:23 +00:00
|
|
|
// Kubernetes names must match the regexp '[a-z0-9]([-a-z0-9]*[a-z0-9])?'.
|
|
|
|
var encoding = base32.NewEncoding("abcdefghijklmnopqrstuvwxyz234567")
|
|
|
|
|
|
|
|
func idToName(s string, h func() hash.Hash) string {
|
|
|
|
return strings.TrimRight(encoding.EncodeToString(h().Sum([]byte(s))), "=")
|
|
|
|
}
|
|
|
|
|
2017-02-01 00:11:59 +00:00
|
|
|
func offlineTokenName(userID string, connID string, h func() hash.Hash) string {
|
2017-02-24 20:55:04 +00:00
|
|
|
hash := h()
|
|
|
|
hash.Write([]byte(userID))
|
|
|
|
hash.Write([]byte(connID))
|
|
|
|
return strings.TrimRight(encoding.EncodeToString(hash.Sum(nil)), "=")
|
2017-02-01 00:11:59 +00:00
|
|
|
}
|
|
|
|
|
2019-12-18 14:50:36 +00:00
|
|
|
func (cli *client) urlFor(apiVersion, namespace, resource, name string) string {
|
2016-07-25 20:00:28 +00:00
|
|
|
basePath := "apis/"
|
|
|
|
if apiVersion == "v1" {
|
|
|
|
basePath = "api/"
|
|
|
|
}
|
|
|
|
|
|
|
|
var p string
|
|
|
|
if namespace != "" {
|
|
|
|
p = path.Join(basePath, apiVersion, "namespaces", namespace, resource, name)
|
|
|
|
} else {
|
|
|
|
p = path.Join(basePath, apiVersion, resource, name)
|
|
|
|
}
|
2019-12-18 14:50:36 +00:00
|
|
|
if strings.HasSuffix(cli.baseURL, "/") {
|
|
|
|
return cli.baseURL + p
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
2019-12-18 14:50:36 +00:00
|
|
|
return cli.baseURL + "/" + p
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
|
|
|
|
2016-10-13 23:50:20 +00:00
|
|
|
// Define an error interface so we can get at the underlying status code if it's
|
|
|
|
// absolutely necessary. For instance when we need to see if an error indicates
|
|
|
|
// a resource already exists.
|
|
|
|
type httpError interface {
|
|
|
|
StatusCode() int
|
|
|
|
}
|
|
|
|
|
|
|
|
var _ httpError = (*httpErr)(nil)
|
|
|
|
|
2016-07-25 20:00:28 +00:00
|
|
|
type httpErr struct {
|
|
|
|
method string
|
|
|
|
url string
|
2016-10-13 23:50:20 +00:00
|
|
|
status int
|
2016-07-25 20:00:28 +00:00
|
|
|
body []byte
|
|
|
|
}
|
|
|
|
|
2016-10-13 23:50:20 +00:00
|
|
|
func (e *httpErr) StatusCode() int {
|
|
|
|
return e.status
|
|
|
|
}
|
|
|
|
|
2016-07-25 20:00:28 +00:00
|
|
|
func (e *httpErr) Error() string {
|
2016-10-13 23:50:20 +00:00
|
|
|
return fmt.Sprintf("%s %s %s: response from server \"%s\"", e.method, e.url, http.StatusText(e.status), bytes.TrimSpace(e.body))
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func checkHTTPErr(r *http.Response, validStatusCodes ...int) error {
|
|
|
|
for _, status := range validStatusCodes {
|
|
|
|
if r.StatusCode == status {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-17 06:12:39 +00:00
|
|
|
body, err := io.ReadAll(io.LimitReader(r.Body, 2<<15)) // 64 KiB
|
2016-07-25 20:00:28 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("read response body: %v", err)
|
|
|
|
}
|
|
|
|
|
2016-10-23 14:42:42 +00:00
|
|
|
// Check this case after we read the body so the connection can be reused.
|
|
|
|
if r.StatusCode == http.StatusNotFound {
|
|
|
|
return storage.ErrNotFound
|
|
|
|
}
|
2018-12-27 08:26:39 +00:00
|
|
|
if r.Request.Method == http.MethodPost && r.StatusCode == http.StatusConflict {
|
2017-02-24 03:20:50 +00:00
|
|
|
return storage.ErrAlreadyExists
|
|
|
|
}
|
2016-10-23 14:42:42 +00:00
|
|
|
|
2016-07-25 20:00:28 +00:00
|
|
|
var url, method string
|
|
|
|
if r.Request != nil {
|
|
|
|
method = r.Request.Method
|
|
|
|
url = r.Request.URL.String()
|
|
|
|
}
|
2016-10-23 14:42:42 +00:00
|
|
|
return &httpErr{method, url, r.StatusCode, body}
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Close the response body. The initial request is drained so the connection can
|
|
|
|
// be reused.
|
|
|
|
func closeResp(r *http.Response) {
|
2021-09-17 06:12:39 +00:00
|
|
|
io.Copy(io.Discard, r.Body)
|
2016-07-25 20:00:28 +00:00
|
|
|
r.Body.Close()
|
|
|
|
}
|
|
|
|
|
2019-12-18 14:50:36 +00:00
|
|
|
func (cli *client) get(resource, name string, v interface{}) error {
|
|
|
|
return cli.getResource(cli.apiVersion, cli.namespace, resource, name, v)
|
2017-09-19 22:31:58 +00:00
|
|
|
}
|
|
|
|
|
2019-12-18 14:50:36 +00:00
|
|
|
func (cli *client) getResource(apiVersion, namespace, resource, name string, v interface{}) error {
|
|
|
|
url := cli.urlFor(apiVersion, namespace, resource, name)
|
|
|
|
resp, err := cli.client.Get(url)
|
2016-07-25 20:00:28 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer closeResp(resp)
|
|
|
|
if err := checkHTTPErr(resp, http.StatusOK); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return json.NewDecoder(resp.Body).Decode(v)
|
|
|
|
}
|
|
|
|
|
2019-12-18 14:50:36 +00:00
|
|
|
func (cli *client) list(resource string, v interface{}) error {
|
|
|
|
return cli.get(resource, "", v)
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
|
|
|
|
2019-12-18 14:50:36 +00:00
|
|
|
func (cli *client) post(resource string, v interface{}) error {
|
|
|
|
return cli.postResource(cli.apiVersion, cli.namespace, resource, v)
|
2016-10-13 23:50:20 +00:00
|
|
|
}
|
|
|
|
|
2019-12-18 14:50:36 +00:00
|
|
|
func (cli *client) postResource(apiVersion, namespace, resource string, v interface{}) error {
|
2016-07-25 20:00:28 +00:00
|
|
|
body, err := json.Marshal(v)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("marshal object: %v", err)
|
|
|
|
}
|
|
|
|
|
2019-12-18 14:50:36 +00:00
|
|
|
url := cli.urlFor(apiVersion, namespace, resource, "")
|
|
|
|
resp, err := cli.client.Post(url, "application/json", bytes.NewReader(body))
|
2016-07-25 20:00:28 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer closeResp(resp)
|
|
|
|
return checkHTTPErr(resp, http.StatusCreated)
|
|
|
|
}
|
|
|
|
|
2021-02-15 07:53:59 +00:00
|
|
|
func (cli *client) detectKubernetesVersion() error {
|
|
|
|
var version struct{ GitVersion string }
|
|
|
|
|
|
|
|
url := cli.baseURL + "/version"
|
|
|
|
resp, err := cli.client.Get(url)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
defer closeResp(resp)
|
|
|
|
if err := checkHTTPErr(resp, http.StatusOK); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := json.NewDecoder(resp.Body).Decode(&version); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
clusterVersion, err := semver.NewVersion(version.GitVersion)
|
|
|
|
if err != nil {
|
|
|
|
cli.logger.Warnf("cannot detect Kubernetes version (%s): %v", clusterVersion, err)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if clusterVersion.LessThan(semver.MustParse("v1.16.0")) {
|
|
|
|
cli.crdAPIVersion = legacyCRDAPIVersion
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-12-18 14:50:36 +00:00
|
|
|
func (cli *client) delete(resource, name string) error {
|
|
|
|
url := cli.urlFor(cli.apiVersion, cli.namespace, resource, name)
|
2016-07-25 20:00:28 +00:00
|
|
|
req, err := http.NewRequest("DELETE", url, nil)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("create delete request: %v", err)
|
|
|
|
}
|
2019-12-18 14:50:36 +00:00
|
|
|
resp, err := cli.client.Do(req)
|
2016-07-25 20:00:28 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("delete request: %v", err)
|
|
|
|
}
|
|
|
|
defer closeResp(resp)
|
|
|
|
return checkHTTPErr(resp, http.StatusOK)
|
|
|
|
}
|
|
|
|
|
2019-12-18 14:50:36 +00:00
|
|
|
func (cli *client) deleteAll(resource string) error {
|
2016-10-05 23:04:48 +00:00
|
|
|
var list struct {
|
|
|
|
k8sapi.TypeMeta `json:",inline"`
|
|
|
|
k8sapi.ListMeta `json:"metadata,omitempty"`
|
|
|
|
Items []struct {
|
|
|
|
k8sapi.TypeMeta `json:",inline"`
|
|
|
|
k8sapi.ObjectMeta `json:"metadata,omitempty"`
|
|
|
|
} `json:"items"`
|
|
|
|
}
|
2019-12-18 14:50:36 +00:00
|
|
|
if err := cli.list(resource, &list); err != nil {
|
2016-10-05 23:04:48 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
for _, item := range list.Items {
|
2019-12-18 14:50:36 +00:00
|
|
|
if err := cli.delete(resource, item.Name); err != nil {
|
2016-10-05 23:04:48 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-12-18 14:50:36 +00:00
|
|
|
func (cli *client) put(resource, name string, v interface{}) error {
|
2016-07-25 20:00:28 +00:00
|
|
|
body, err := json.Marshal(v)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("marshal object: %v", err)
|
|
|
|
}
|
|
|
|
|
2019-12-18 14:50:36 +00:00
|
|
|
url := cli.urlFor(cli.apiVersion, cli.namespace, resource, name)
|
2016-07-25 20:00:28 +00:00
|
|
|
req, err := http.NewRequest("PUT", url, bytes.NewReader(body))
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("create patch request: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
req.Header.Set("Content-Length", strconv.Itoa(len(body)))
|
|
|
|
|
2019-12-18 14:50:36 +00:00
|
|
|
resp, err := cli.client.Do(req)
|
2016-07-25 20:00:28 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("patch request: %v", err)
|
|
|
|
}
|
|
|
|
defer closeResp(resp)
|
|
|
|
|
|
|
|
return checkHTTPErr(resp, http.StatusOK)
|
|
|
|
}
|
|
|
|
|
2020-06-30 11:12:36 +00:00
|
|
|
// Copied from https://github.com/gtank/cryptopasta
|
|
|
|
func defaultTLSConfig() *tls.Config {
|
|
|
|
return &tls.Config{
|
|
|
|
// Avoids most of the memorably-named TLS attacks
|
|
|
|
MinVersion: tls.VersionTLS12,
|
|
|
|
// Causes servers to use Go's default ciphersuite preferences,
|
|
|
|
// which are tuned to avoid attacks. Does nothing on clients.
|
|
|
|
PreferServerCipherSuites: true,
|
|
|
|
// Only use curves which have constant-time implementations
|
|
|
|
CurvePreferences: []tls.CurveID{
|
|
|
|
tls.CurveP256,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-06 22:10:11 +00:00
|
|
|
func newClient(cluster k8sapi.Cluster, user k8sapi.AuthInfo, namespace string, logger log.Logger, inCluster bool) (*client, error) {
|
2020-06-30 11:12:36 +00:00
|
|
|
tlsConfig := defaultTLSConfig()
|
2016-10-05 23:04:48 +00:00
|
|
|
data := func(b string, file string) ([]byte, error) {
|
|
|
|
if b != "" {
|
|
|
|
return base64.StdEncoding.DecodeString(b)
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
|
|
|
if file == "" {
|
|
|
|
return nil, nil
|
|
|
|
}
|
2021-09-17 06:12:39 +00:00
|
|
|
return os.ReadFile(file)
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if caData, err := data(cluster.CertificateAuthorityData, cluster.CertificateAuthority); err != nil {
|
|
|
|
return nil, err
|
|
|
|
} else if caData != nil {
|
|
|
|
tlsConfig.RootCAs = x509.NewCertPool()
|
|
|
|
if !tlsConfig.RootCAs.AppendCertsFromPEM(caData) {
|
|
|
|
return nil, fmt.Errorf("no certificate data found: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
clientCert, err := data(user.ClientCertificateData, user.ClientCertificate)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
clientKey, err := data(user.ClientKeyData, user.ClientKey)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if clientCert != nil && clientKey != nil {
|
|
|
|
cert, err := tls.X509KeyPair(clientCert, clientKey)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to load client cert: %v", err)
|
|
|
|
}
|
|
|
|
tlsConfig.Certificates = []tls.Certificate{cert}
|
|
|
|
}
|
|
|
|
|
2017-01-14 00:49:06 +00:00
|
|
|
var t http.RoundTripper
|
|
|
|
httpTransport := &http.Transport{
|
2016-07-25 20:00:28 +00:00
|
|
|
Proxy: http.ProxyFromEnvironment,
|
2021-04-20 11:41:12 +00:00
|
|
|
DialContext: (&net.Dialer{
|
2016-07-25 20:00:28 +00:00
|
|
|
Timeout: 30 * time.Second,
|
|
|
|
KeepAlive: 30 * time.Second,
|
2021-04-20 11:41:12 +00:00
|
|
|
}).DialContext,
|
2016-07-25 20:00:28 +00:00
|
|
|
TLSClientConfig: tlsConfig,
|
|
|
|
TLSHandshakeTimeout: 10 * time.Second,
|
|
|
|
ExpectContinueTimeout: 1 * time.Second,
|
|
|
|
}
|
|
|
|
|
2017-01-14 00:49:06 +00:00
|
|
|
// Since we set a custom TLS client config we have to explicitly
|
|
|
|
// enable HTTP/2.
|
|
|
|
//
|
|
|
|
// https://github.com/golang/go/blob/go1.7.4/src/net/http/transport.go#L200-L206
|
|
|
|
if err := http2.ConfigureTransport(httpTransport); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2021-05-06 22:10:11 +00:00
|
|
|
t = wrapRoundTripper(httpTransport, user, inCluster)
|
2016-07-25 20:00:28 +00:00
|
|
|
|
2017-09-13 20:38:10 +00:00
|
|
|
apiVersion := "dex.coreos.com/v1"
|
2017-09-13 17:57:54 +00:00
|
|
|
|
|
|
|
logger.Infof("kubernetes client apiVersion = %s", apiVersion)
|
2016-08-02 05:53:12 +00:00
|
|
|
return &client{
|
2017-09-26 23:09:40 +00:00
|
|
|
client: &http.Client{
|
|
|
|
Transport: t,
|
|
|
|
Timeout: 15 * time.Second,
|
|
|
|
},
|
2021-02-15 07:53:59 +00:00
|
|
|
baseURL: cluster.Server,
|
|
|
|
hash: func() hash.Hash { return fnv.New64() },
|
|
|
|
namespace: namespace,
|
|
|
|
apiVersion: apiVersion,
|
|
|
|
crdAPIVersion: crdAPIVersion,
|
|
|
|
logger: logger,
|
2016-08-02 05:53:12 +00:00
|
|
|
}, nil
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func loadKubeConfig(kubeConfigPath string) (cluster k8sapi.Cluster, user k8sapi.AuthInfo, namespace string, err error) {
|
2021-09-17 06:12:39 +00:00
|
|
|
data, err := os.ReadFile(kubeConfigPath)
|
2016-07-25 20:00:28 +00:00
|
|
|
if err != nil {
|
|
|
|
err = fmt.Errorf("read %s: %v", kubeConfigPath, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
var c k8sapi.Config
|
|
|
|
if err = yaml.Unmarshal(data, &c); err != nil {
|
|
|
|
err = fmt.Errorf("unmarshal %s: %v", kubeConfigPath, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
cluster, user, namespace, err = currentContext(&c)
|
|
|
|
if namespace == "" {
|
|
|
|
namespace = "default"
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-10-22 06:07:38 +00:00
|
|
|
func namespaceFromServiceAccountJWT(s string) (string, error) {
|
|
|
|
// The service account token is just a JWT. Parse it as such.
|
|
|
|
parts := strings.Split(s, ".")
|
|
|
|
if len(parts) < 2 {
|
|
|
|
// It's extremely important we don't log the actual service account token.
|
|
|
|
return "", fmt.Errorf("malformed service account token: expected 3 parts got %d", len(parts))
|
|
|
|
}
|
|
|
|
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("malformed service account token: %v", err)
|
|
|
|
}
|
|
|
|
var data struct {
|
|
|
|
// The claim Kubernetes uses to identify which namespace a service account belongs to.
|
|
|
|
//
|
|
|
|
// See: https://github.com/kubernetes/kubernetes/blob/v1.4.3/pkg/serviceaccount/jwt.go#L42
|
|
|
|
Namespace string `json:"kubernetes.io/serviceaccount/namespace"`
|
|
|
|
}
|
|
|
|
if err := json.Unmarshal(payload, &data); err != nil {
|
|
|
|
return "", fmt.Errorf("malformed service account token: %v", err)
|
|
|
|
}
|
|
|
|
if data.Namespace == "" {
|
|
|
|
return "", errors.New(`jwt claim "kubernetes.io/serviceaccount/namespace" not found`)
|
|
|
|
}
|
|
|
|
return data.Namespace, nil
|
|
|
|
}
|
|
|
|
|
2021-04-20 11:41:12 +00:00
|
|
|
func namespaceFromFile(path string) (string, error) {
|
2021-09-17 06:12:39 +00:00
|
|
|
data, err := os.ReadFile(path)
|
2021-04-20 11:41:12 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return string(data), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func getInClusterConfigNamespace(token, namespaceENV, namespacePath string) (string, error) {
|
|
|
|
namespace := os.Getenv(namespaceENV)
|
|
|
|
if namespace != "" {
|
|
|
|
return namespace, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
namespace, err := namespaceFromServiceAccountJWT(token)
|
|
|
|
if err == nil {
|
|
|
|
return namespace, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
err = fmt.Errorf("inspect service account token: %v", err)
|
|
|
|
namespace, fileErr := namespaceFromFile(namespacePath)
|
|
|
|
if fileErr == nil {
|
|
|
|
return namespace, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return "", fmt.Errorf("%v: trying to get namespace from file: %v", err, fileErr)
|
|
|
|
}
|
|
|
|
|
|
|
|
func inClusterConfig() (k8sapi.Cluster, k8sapi.AuthInfo, string, error) {
|
|
|
|
const (
|
|
|
|
serviceAccountPath = "/var/run/secrets/kubernetes.io/serviceaccount/"
|
|
|
|
serviceAccountTokenPath = serviceAccountPath + "token"
|
|
|
|
serviceAccountCAPath = serviceAccountPath + "ca.crt"
|
|
|
|
serviceAccountNamespacePath = serviceAccountPath + "namespace"
|
|
|
|
|
|
|
|
kubernetesServiceHostENV = "KUBERNETES_SERVICE_HOST"
|
|
|
|
kubernetesServicePortENV = "KUBERNETES_SERVICE_PORT"
|
|
|
|
kubernetesPodNamespaceENV = "KUBERNETES_POD_NAMESPACE"
|
|
|
|
)
|
|
|
|
|
|
|
|
host, port := os.Getenv(kubernetesServiceHostENV), os.Getenv(kubernetesServicePortENV)
|
2016-07-25 20:00:28 +00:00
|
|
|
if len(host) == 0 || len(port) == 0 {
|
2021-04-20 11:41:12 +00:00
|
|
|
return k8sapi.Cluster{}, k8sapi.AuthInfo{}, "", fmt.Errorf(
|
|
|
|
"unable to load in-cluster configuration, %s and %s must be defined",
|
|
|
|
kubernetesServiceHostENV,
|
|
|
|
kubernetesServicePortENV,
|
|
|
|
)
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
2020-02-06 17:58:18 +00:00
|
|
|
// we need to wrap IPv6 addresses in square brackets
|
|
|
|
// IPv4 also works with square brackets
|
|
|
|
host = "[" + host + "]"
|
2021-04-20 11:41:12 +00:00
|
|
|
cluster := k8sapi.Cluster{
|
2016-07-25 20:00:28 +00:00
|
|
|
Server: "https://" + host + ":" + port,
|
2021-04-20 11:41:12 +00:00
|
|
|
CertificateAuthority: serviceAccountCAPath,
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
2021-04-20 11:41:12 +00:00
|
|
|
|
2021-09-17 06:12:39 +00:00
|
|
|
token, err := os.ReadFile(serviceAccountTokenPath)
|
2016-07-25 20:00:28 +00:00
|
|
|
if err != nil {
|
2021-04-20 11:41:12 +00:00
|
|
|
return cluster, k8sapi.AuthInfo{}, "", err
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
2016-10-22 06:07:38 +00:00
|
|
|
|
2021-04-20 11:41:12 +00:00
|
|
|
user := k8sapi.AuthInfo{Token: string(token)}
|
|
|
|
|
|
|
|
namespace, err := getInClusterConfigNamespace(user.Token, kubernetesPodNamespaceENV, serviceAccountNamespacePath)
|
|
|
|
if err != nil {
|
|
|
|
return cluster, user, "", err
|
2016-10-22 06:07:38 +00:00
|
|
|
}
|
|
|
|
|
2021-04-20 11:41:12 +00:00
|
|
|
return cluster, user, namespace, nil
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func currentContext(config *k8sapi.Config) (cluster k8sapi.Cluster, user k8sapi.AuthInfo, ns string, err error) {
|
|
|
|
if config.CurrentContext == "" {
|
2016-10-25 18:51:59 +00:00
|
|
|
if len(config.Contexts) == 1 {
|
|
|
|
config.CurrentContext = config.Contexts[0].Name
|
|
|
|
} else {
|
|
|
|
return cluster, user, "", errors.New("kubeconfig has no current context")
|
|
|
|
}
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
2021-04-20 11:41:12 +00:00
|
|
|
k8sContext, ok := func() (k8sapi.Context, bool) {
|
2016-07-25 20:00:28 +00:00
|
|
|
for _, namedContext := range config.Contexts {
|
|
|
|
if namedContext.Name == config.CurrentContext {
|
|
|
|
return namedContext.Context, true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return k8sapi.Context{}, false
|
|
|
|
}()
|
|
|
|
if !ok {
|
|
|
|
return cluster, user, "", fmt.Errorf("no context named %q found", config.CurrentContext)
|
|
|
|
}
|
|
|
|
|
|
|
|
cluster, ok = func() (k8sapi.Cluster, bool) {
|
|
|
|
for _, namedCluster := range config.Clusters {
|
2021-04-20 11:41:12 +00:00
|
|
|
if namedCluster.Name == k8sContext.Cluster {
|
2016-07-25 20:00:28 +00:00
|
|
|
return namedCluster.Cluster, true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return k8sapi.Cluster{}, false
|
|
|
|
}()
|
|
|
|
if !ok {
|
2021-04-20 11:41:12 +00:00
|
|
|
return cluster, user, "", fmt.Errorf("no cluster named %q found", k8sContext.Cluster)
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
user, ok = func() (k8sapi.AuthInfo, bool) {
|
|
|
|
for _, namedAuthInfo := range config.AuthInfos {
|
2021-04-20 11:41:12 +00:00
|
|
|
if namedAuthInfo.Name == k8sContext.AuthInfo {
|
2016-07-25 20:00:28 +00:00
|
|
|
return namedAuthInfo.AuthInfo, true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return k8sapi.AuthInfo{}, false
|
|
|
|
}()
|
|
|
|
if !ok {
|
2021-04-20 11:41:12 +00:00
|
|
|
return cluster, user, "", fmt.Errorf("no user named %q found", k8sContext.AuthInfo)
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
2021-04-20 11:41:12 +00:00
|
|
|
return cluster, user, k8sContext.Namespace, nil
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|