forked from micahhausler/k8s-oidc-helper
-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 7ad4491
Showing
5 changed files
with
370 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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,35 @@ | ||
# Compiled Object files, Static and Dynamic libs (Shared Objects) | ||
*.o | ||
*.a | ||
*.so | ||
|
||
# Folders | ||
_obj | ||
_test | ||
|
||
# Coverage | ||
coverage.out | ||
|
||
# Build artifacts | ||
k8s-oidc-helper | ||
|
||
# Architecture specific extensions/prefixes | ||
*.[568vq] | ||
[568vq].out | ||
|
||
*.cgo1.go | ||
*.cgo2.c | ||
_cgo_defun.c | ||
_cgo_gotypes.go | ||
_cgo_export.* | ||
|
||
_testmain.go | ||
|
||
*.exe | ||
*.test | ||
*.prof | ||
|
||
.idea/ | ||
|
||
# Ignore vim files | ||
*.swp |
This file contains 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,15 @@ | ||
# To build: | ||
# $ docker run --rm -v $(pwd):/go/src/github.com/micahhausler/k8s-oidc-helper -w /go/src/github.com/micahhausler/k8s-oidc-helper golang:1.7 go build -v -a -tags netgo -installsuffix netgo -ldflags '-w' | ||
# $ docker build -t micahhausler/k8s-oidc-helper . | ||
# | ||
# To run: | ||
# $ docker run micahhausler/k8s-oidc-helper | ||
|
||
FROM busybox | ||
|
||
MAINTAINER Micah Hausler, <[email protected]> | ||
|
||
COPY k8s-oidc-helper /bin/k8s-oidc-helper | ||
RUN chmod 755 /bin/k8s-oidc-helper | ||
|
||
ENTRYPOINT ["/bin/k8s-oidc-helper"] |
This file contains 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,21 @@ | ||
The MIT License (MIT) | ||
|
||
Copyright (c) 2016 Micah Hausler | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains 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,88 @@ | ||
# k8s-oidc-helper | ||
|
||
This is a small helper tool to get a user get authenticated with | ||
[Kubernetes OIDC](http://kubernetes.io/docs/admin/authentication/) using Google | ||
as the Identity Provider. | ||
|
||
Given a ClientID and ClientSecret, the tool will output the necessary | ||
configurtion for `kubectl` that you can add to `~/.kube/config` | ||
|
||
## Setup | ||
|
||
There is a bit of setup involved before you can use this tool. | ||
|
||
First, you'll need to create a project and OAuth 2.0 Credential in the Google | ||
Cloud Console. You can follow [this guide](https://developers.google.com/identity/sign-in/web/devconsole-project) | ||
on creating an application, but do *NOT* create a web application. You'll need | ||
to select "Other" as the Application Type. Once that is created, you can | ||
download the ClientID and ClientSecret as a JSON file for ease of use. | ||
|
||
|
||
Second, your kube-apiserver will need the following flags on to use OpenID Connect. | ||
|
||
``` | ||
--oidc-issuer-url=https://accounts.google.com \ | ||
--oidc-username-claim=email \ | ||
--oidc-client-id=<Your client ID>\ | ||
``` | ||
|
||
### Role-Based Access Control | ||
|
||
If you are using [RBAC](http://kubernetes.io/docs/admin/authorization/) as your | ||
`--authorization-mode`, you can use the following `ClusterRole` and | ||
`ClusterRoleBinding` for administrators that need cluster-wide access. | ||
|
||
```yaml | ||
kind: ClusterRole | ||
apiVersion: rbac.authorization.k8s.io/v1alpha1 | ||
metadata: | ||
name: admin-role | ||
rules: | ||
- apiGroups: ["*"] | ||
resources: ["*"] | ||
verbs: ["*"] | ||
nonResourceURLs: ["*"] | ||
--- | ||
kind: ClusterRoleBinding | ||
apiVersion: rbac.authorization.k8s.io/v1alpha1 | ||
metadata: | ||
name: admin-binding | ||
subjects: | ||
- kind: User | ||
name: [email protected] | ||
roleRef: | ||
kind: ClusterRole | ||
name: admin-role | ||
``` | ||
## Installation | ||
``` | ||
go install github.com/micahhausler/k8s-oidc-helper | ||
``` | ||
|
||
## Usage | ||
|
||
``` | ||
Usage of ./k8s-oidc-helper: | ||
-client-id string | ||
The ClientID for the application | ||
-client-secret string | ||
The ClientSecret for the application | ||
-config string | ||
Path to a json file containing your application's ClientID and ClientSecret. | ||
-open | ||
Open the oauth approval URL in the browser | ||
-version | ||
print version and exit | ||
``` | ||
|
||
## Wishlist | ||
|
||
- [ ] Add tests/CI | ||
- [ ] Add docker builds to CI | ||
|
||
## License | ||
|
||
MIT License. See [License](/LICENSE) for full text |
This file contains 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,211 @@ | ||
package main | ||
|
||
import ( | ||
"bufio" | ||
"encoding/json" | ||
"flag" | ||
"fmt" | ||
yaml "gopkg.in/yaml.v2" | ||
"net/http" | ||
"net/url" | ||
"os" | ||
"os/exec" | ||
"strings" | ||
) | ||
|
||
const Version = "0.0.1" | ||
|
||
var version = flag.Bool("version", false, "print version and exit") | ||
|
||
var openBrowser = flag.Bool("open", false, "Open the oauth approval URL in the browser") | ||
|
||
var clientIDFlag = flag.String("client-id", "", "The ClientID for the application") | ||
var clientSecretFlag = flag.String("client-secret", "", "The ClientSecret for the application") | ||
var appFile = flag.String("config", "", "Path to a json file containing your application's ClientID and ClientSecret.") | ||
|
||
const oauthUrl = "https://accounts.google.com/o/oauth2/auth?redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&client_id=%s&scope=openid+email+profile&approval_prompt=force&access_type=offline" | ||
|
||
type ConfigFile struct { | ||
Installed *GoogleConfig `json:"installed"` | ||
} | ||
|
||
type GoogleConfig struct { | ||
ClientID string `json:"client_id"` | ||
ClientSecret string `json:"client_secret"` | ||
} | ||
|
||
type TokenResponse struct { | ||
AccessToken string `json:"access_token"` | ||
RefreshToken string `json:"refresh_token"` | ||
IdToken string `json:"id_token"` | ||
} | ||
|
||
func readConfig(path string) (*GoogleConfig, error) { | ||
f, err := os.Open(path) | ||
defer f.Close() | ||
if err != nil { | ||
return nil, err | ||
} | ||
cf := &ConfigFile{} | ||
err = json.NewDecoder(f).Decode(cf) | ||
if err != nil { | ||
return nil, err | ||
} | ||
return cf.Installed, nil | ||
} | ||
|
||
// Get the id_token and refresh_token from google | ||
func getTokens(clientID, clientSecret, code string) (*TokenResponse, error) { | ||
val := url.Values{} | ||
val.Add("grant_type", "authorization_code") | ||
val.Add("redirect_uri", "urn:ietf:wg:oauth:2.0:oob") | ||
val.Add("client_id", clientID) | ||
val.Add("client_secret", clientSecret) | ||
val.Add("code", code) | ||
|
||
resp, err := http.PostForm("https://www.googleapis.com/oauth2/v3/token", val) | ||
defer resp.Body.Close() | ||
if err != nil { | ||
return nil, err | ||
} | ||
tr := &TokenResponse{} | ||
err = json.NewDecoder(resp.Body).Decode(tr) | ||
if err != nil { | ||
return nil, err | ||
} | ||
return tr, nil | ||
} | ||
|
||
type KubectlUser struct { | ||
Name string `yaml:"name"` | ||
KubeUserInfo *KubeUserInfo `yaml:"user"` | ||
} | ||
|
||
type KubeUserInfo struct { | ||
AuthProvider *AuthProvider `yaml:"auth-provider"` | ||
} | ||
|
||
type AuthProvider struct { | ||
APConfig *APConfig `yaml:"config"` | ||
Name string `yaml:"name"` | ||
} | ||
|
||
type APConfig struct { | ||
ClientID string `yaml:"client-id"` | ||
ClientSecret string `yaml:"client-secret"` | ||
IdToken string `yaml:"id-token"` | ||
IdpIssuerUrl string `yaml:"idp-issuer-url"` | ||
RefreshToken string `yaml:"refresh-token"` | ||
} | ||
|
||
type UserInfo struct { | ||
Email string `json:"email"` | ||
} | ||
|
||
func getUserEmail(accessToken string) (string, error) { | ||
uri, _ := url.Parse("https://www.googleapis.com/oauth2/v1/userinfo") | ||
q := uri.Query() | ||
q.Set("alt", "json") | ||
q.Set("access_token", accessToken) | ||
uri.RawQuery = q.Encode() | ||
resp, err := http.Get(uri.String()) | ||
defer resp.Body.Close() | ||
if err != nil { | ||
return "", err | ||
} | ||
ui := &UserInfo{} | ||
err = json.NewDecoder(resp.Body).Decode(ui) | ||
if err != nil { | ||
return "", err | ||
} | ||
return ui.Email, nil | ||
} | ||
|
||
func generateUser(email, clientId, clientSecret, idToken, refreshToken string) *KubectlUser { | ||
return &KubectlUser{ | ||
Name: email, | ||
KubeUserInfo: &KubeUserInfo{ | ||
AuthProvider: &AuthProvider{ | ||
APConfig: &APConfig{ | ||
ClientID: clientId, | ||
ClientSecret: clientSecret, | ||
IdToken: idToken, | ||
IdpIssuerUrl: "https://accounts.google.com", | ||
RefreshToken: refreshToken, | ||
}, | ||
Name: "oidc", | ||
}, | ||
}, | ||
} | ||
} | ||
|
||
func main() { | ||
|
||
flag.Usage = func() { | ||
fmt.Fprintf(os.Stderr, "Usage of %s:\n\n", os.Args[0]) | ||
flag.PrintDefaults() | ||
} | ||
|
||
flag.Parse() | ||
|
||
if *version { | ||
fmt.Printf("k8s-oidc-helper %s\n", Version) | ||
os.Exit(0) | ||
} | ||
|
||
var gcf *GoogleConfig | ||
var err error | ||
if len(*appFile) > 0 { | ||
gcf, err = readConfig(*appFile) | ||
if err != nil { | ||
fmt.Printf("Error reading config file %s: %s\n", *appFile, err) | ||
os.Exit(1) | ||
} | ||
} | ||
var clientID string | ||
var clientSecret string | ||
if gcf != nil { | ||
clientID = gcf.ClientID | ||
clientSecret = gcf.ClientSecret | ||
} else { | ||
clientID = *clientIDFlag | ||
clientSecret = *clientSecretFlag | ||
} | ||
|
||
if *openBrowser { | ||
cmd := exec.Command("open", fmt.Sprintf(oauthUrl, clientID)) | ||
err = cmd.Start() | ||
} | ||
if !*openBrowser || err != nil { | ||
fmt.Printf("Open this url in your browser: %s\n", fmt.Sprintf(oauthUrl, clientID)) | ||
} | ||
|
||
reader := bufio.NewReader(os.Stdin) | ||
fmt.Print("Enter the code Google gave you: ") | ||
code, _ := reader.ReadString('\n') | ||
code = strings.TrimSpace(code) | ||
|
||
tokResponse, err := getTokens(clientID, clientSecret, code) | ||
if err != nil { | ||
fmt.Printf("Error getting tokens: %s\n", err) | ||
os.Exit(1) | ||
} | ||
|
||
email, err := getUserEmail(tokResponse.AccessToken) | ||
if err != nil { | ||
fmt.Printf("Error getting user email: %s\n", err) | ||
os.Exit(1) | ||
} | ||
|
||
userConfig := generateUser(email, clientID, clientSecret, tokResponse.IdToken, tokResponse.RefreshToken) | ||
output := map[string][]*KubectlUser{} | ||
output["users"] = []*KubectlUser{userConfig} | ||
response, err := yaml.Marshal(output) | ||
if err != nil { | ||
fmt.Printf("Error marshaling yaml: %s\n", err) | ||
os.Exit(1) | ||
} | ||
fmt.Println("\n# Add the following to your ~/.kube/config") | ||
fmt.Println(string(response)) | ||
|
||
} |