|
| 1 | +/* |
| 2 | +Copyright 2020 The Kubernetes Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +// Package openidmetadata tests the OIDC discovery endpoints which are part of |
| 18 | +// the ServiceAccountIssuerDiscovery feature. |
| 19 | +package openidmetadata |
| 20 | + |
| 21 | +import ( |
| 22 | + "context" |
| 23 | + "fmt" |
| 24 | + "io/ioutil" |
| 25 | + "log" |
| 26 | + "net/http" |
| 27 | + |
| 28 | + oidc "github.com/coreos/go-oidc" |
| 29 | + "github.com/spf13/cobra" |
| 30 | + "golang.org/x/oauth2" |
| 31 | + "gopkg.in/square/go-jose.v2/jwt" |
| 32 | + "k8s.io/client-go/rest" |
| 33 | +) |
| 34 | + |
| 35 | +// CmdTestServiceAccountIssuerDiscovery is used by agnhost Cobra. |
| 36 | +var CmdTestServiceAccountIssuerDiscovery = &cobra.Command{ |
| 37 | + Use: "test-service-account-issuer-discovery", |
| 38 | + Short: "Tests the ServiceAccountIssuerDiscovery feature", |
| 39 | + Long: "Reads in a mounted token and attempts to verify it against the API server's " + |
| 40 | + "OIDC endpoints, using a third-party OIDC implementation.", |
| 41 | + Args: cobra.MaximumNArgs(0), |
| 42 | + Run: main, |
| 43 | +} |
| 44 | + |
| 45 | +var ( |
| 46 | + tokenPath string |
| 47 | + audience string |
| 48 | + inClusterDiscovery bool |
| 49 | +) |
| 50 | + |
| 51 | +func init() { |
| 52 | + fs := CmdTestServiceAccountIssuerDiscovery.Flags() |
| 53 | + fs.StringVar(&tokenPath, "token-path", "", "Path to read service account token from.") |
| 54 | + fs.StringVar(&audience, "audience", "", "Audience to check on received token.") |
| 55 | + fs.BoolVar(&inClusterDiscovery, "in-cluster-discovery", false, |
| 56 | + "Includes the in-cluster bearer token in request headers. "+ |
| 57 | + "Use when validating against API server's discovery endpoints, "+ |
| 58 | + "which require authentication.") |
| 59 | +} |
| 60 | + |
| 61 | +func main(cmd *cobra.Command, args []string) { |
| 62 | + ctx, err := withOAuth2Client(context.Background()) |
| 63 | + if err != nil { |
| 64 | + log.Fatal(err) |
| 65 | + } |
| 66 | + |
| 67 | + raw, err := gettoken() |
| 68 | + if err != nil { |
| 69 | + log.Fatal(err) |
| 70 | + } |
| 71 | + log.Print("OK: Got token") |
| 72 | + tok, err := jwt.ParseSigned(raw) |
| 73 | + if err != nil { |
| 74 | + log.Fatal(err) |
| 75 | + } |
| 76 | + var unsafeClaims claims |
| 77 | + if err := tok.UnsafeClaimsWithoutVerification(&unsafeClaims); err != nil { |
| 78 | + log.Fatal(err) |
| 79 | + } |
| 80 | + log.Printf("OK: got issuer %s", unsafeClaims.Issuer) |
| 81 | + log.Printf("Full, not-validated claims: \n%#v", unsafeClaims) |
| 82 | + |
| 83 | + iss, err := oidc.NewProvider(ctx, unsafeClaims.Issuer) |
| 84 | + if err != nil { |
| 85 | + log.Fatal(err) |
| 86 | + } |
| 87 | + log.Printf("OK: Constructed OIDC provider for issuer %v", unsafeClaims.Issuer) |
| 88 | + |
| 89 | + validTok, err := iss.Verifier(&oidc.Config{ClientID: audience}).Verify(ctx, raw) |
| 90 | + if err != nil { |
| 91 | + log.Fatal(err) |
| 92 | + } |
| 93 | + log.Print("OK: Validated signature on JWT") |
| 94 | + |
| 95 | + var safeClaims claims |
| 96 | + if err := validTok.Claims(&safeClaims); err != nil { |
| 97 | + log.Fatal(err) |
| 98 | + } |
| 99 | + log.Print("OK: Got valid claims from token!") |
| 100 | + log.Printf("Full, validated claims: \n%#v", &safeClaims) |
| 101 | +} |
| 102 | + |
| 103 | +type kubeName struct { |
| 104 | + Name string `json:"name"` |
| 105 | + UID string `json:"uid"` |
| 106 | +} |
| 107 | + |
| 108 | +type kubeClaims struct { |
| 109 | + Namespace string `json:"namespace"` |
| 110 | + ServiceAccount kubeName `json:"serviceaccount"` |
| 111 | +} |
| 112 | + |
| 113 | +type claims struct { |
| 114 | + jwt.Claims |
| 115 | + |
| 116 | + Kubernetes kubeClaims `json:"kubernetes.io"` |
| 117 | +} |
| 118 | + |
| 119 | +func (k *claims) String() string { |
| 120 | + return fmt.Sprintf("%s/%s for %s", k.Kubernetes.Namespace, k.Kubernetes.ServiceAccount.Name, k.Audience) |
| 121 | +} |
| 122 | + |
| 123 | +func gettoken() (string, error) { |
| 124 | + b, err := ioutil.ReadFile(tokenPath) |
| 125 | + return string(b), err |
| 126 | +} |
| 127 | + |
| 128 | +// withOAuth2Client returns a context that includes an HTTP Client, under the |
| 129 | +// oauth2.HTTPClient key. If --in-cluster-discovery is true, the client will |
| 130 | +// use the Kubernetes InClusterConfig. Otherwise it will use |
| 131 | +// http.DefaultTransport. |
| 132 | +// The `oidc` library respects the oauth2.HTTPClient context key; if it is set, |
| 133 | +// the library will use the provided http.Client rather than the default |
| 134 | +// HTTP client. |
| 135 | +// This allows us to ensure requests get routed to the API server for |
| 136 | +// --in-cluster-discovery, in a client configured with the appropriate CA. |
| 137 | +func withOAuth2Client(context.Context) (context.Context, error) { |
| 138 | + // TODO(mtaufen): Someday, might want to change this so that we can test |
| 139 | + // TokenProjection with an API audience set to the external provider with |
| 140 | + // requests against external endpoints (in which case we'd send |
| 141 | + // a different token with a non-Kubernetes audience). |
| 142 | + |
| 143 | + // By default, use the default http transport with the system root bundle, |
| 144 | + // since it's validating against the external internet. |
| 145 | + rt := http.DefaultTransport |
| 146 | + if inClusterDiscovery { |
| 147 | + // If in-cluster discovery, then use the in-cluster config so we can |
| 148 | + // authenticate with the API server. |
| 149 | + cfg, err := rest.InClusterConfig() |
| 150 | + if err != nil { |
| 151 | + return nil, err |
| 152 | + } |
| 153 | + rt, err = rest.TransportFor(cfg) |
| 154 | + if err != nil { |
| 155 | + return nil, fmt.Errorf("could not get roundtripper: %v", err) |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + ctx := context.WithValue(context.Background(), |
| 160 | + oauth2.HTTPClient, &http.Client{ |
| 161 | + Transport: rt, |
| 162 | + }) |
| 163 | + return ctx, nil |
| 164 | +} |
0 commit comments