-
Notifications
You must be signed in to change notification settings - Fork 50
Added OIDC client #547
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
Open
dasarinaidu
wants to merge
1
commit into
rancher:main
Choose a base branch
from
dasarinaidu:oidc-client
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Added OIDC client #547
Changes from all commits
Commits
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
Some comments aren't visible on the classic Files Changed page.
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,25 @@ | ||
| package oidc | ||
|
|
||
| const ( | ||
| ConfigurationFileKey = "oidc" | ||
| OIDCProviderFeatureFlag = "oidc-provider" | ||
| DefaultTokenExpirationSeconds = 3600 | ||
| DefaultRefreshTokenExpirationSeconds = 86400 | ||
| ) | ||
|
|
||
| var DefaultAutomationScopes = []string{ | ||
| "openid", | ||
| "profile", | ||
| "offline_access", | ||
| "rancher:users", | ||
| } | ||
|
|
||
| type Config struct { | ||
| ClientName string `json:"clientName" yaml:"clientName"` | ||
| RedirectURI string `json:"redirectURI" yaml:"redirectURI"` | ||
| Scopes []string `json:"scopes" yaml:"scopes"` | ||
| TokenExpirationSeconds int `json:"tokenExpirationSeconds" yaml:"tokenExpirationSeconds"` | ||
| RefreshTokenExpirationSeconds int `json:"refreshTokenExpirationSeconds" yaml:"refreshTokenExpirationSeconds"` | ||
| AdminUsername string `json:"adminUsername" yaml:"adminUsername"` | ||
| AdminPassword string `json:"adminPassword" yaml:"adminPassword"` | ||
| } |
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,170 @@ | ||
| package oidc | ||
|
|
||
| import ( | ||
| "crypto/rand" | ||
| "crypto/tls" | ||
| "encoding/base64" | ||
| "encoding/json" | ||
| "fmt" | ||
| "net/http" | ||
| "net/url" | ||
| "strings" | ||
|
|
||
| management "github.com/rancher/shepherd/clients/rancher/generated/management/v3" | ||
| oidcext "github.com/rancher/shepherd/extensions/auth/oidc" | ||
| sheptoken "github.com/rancher/shepherd/extensions/token" | ||
| "github.com/rancher/shepherd/pkg/clientbase" | ||
| "github.com/rancher/shepherd/pkg/config" | ||
| "github.com/rancher/shepherd/pkg/session" | ||
| "github.com/sirupsen/logrus" | ||
| ) | ||
|
|
||
| type APIClient struct { | ||
| rancherURL string | ||
| httpClient *http.Client | ||
| noRedirectClient *http.Client | ||
| Config *Config | ||
| session *session.Session | ||
| } | ||
|
|
||
| // NewAPIClient constructs an APIClient and loads the "oidc" config block. | ||
| func NewAPIClient(rancherURL string, session *session.Session) *APIClient { | ||
| transport := &http.Transport{ | ||
| TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // nolint:gosec | ||
| } | ||
| normalizedURL := strings.TrimRight(rancherURL, "/") | ||
| if !strings.HasPrefix(normalizedURL, "https://") && !strings.HasPrefix(normalizedURL, "http://") { | ||
| normalizedURL = "https://" + normalizedURL | ||
| } | ||
| oidcConfig := new(Config) | ||
| config.LoadConfig(ConfigurationFileKey, oidcConfig) | ||
| return &APIClient{ | ||
| rancherURL: normalizedURL, | ||
| Config: oidcConfig, | ||
| session: session, | ||
| httpClient: &http.Client{Transport: transport}, | ||
| noRedirectClient: &http.Client{ | ||
| Transport: transport, | ||
| CheckRedirect: func(req *http.Request, via []*http.Request) error { | ||
| return http.ErrUseLastResponse | ||
| }, | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| // GetDiscovery fetches the OIDC provider metadata document. | ||
| func (c *APIClient) GetDiscovery() (*clientbase.Response, map[string]interface{}, error) { | ||
| return oidcext.Discovery(c.httpClient, c.rancherURL) | ||
| } | ||
|
|
||
| // RefreshAccessToken exchanges a refresh_token for a new TokenSet. | ||
| func (c *APIClient) RefreshAccessToken(refreshToken, clientID, clientSecret string) (*oidcext.TokenSet, error) { | ||
| return oidcext.RefreshAccessToken(c.httpClient, c.rancherURL, refreshToken, clientID, clientSecret) | ||
| } | ||
|
|
||
| // RawRequest executes an HTTP request against a Rancher API path. | ||
| func (c *APIClient) RawRequest(method, path, authHeader string) (*clientbase.Response, error) { | ||
| headers := map[string]string{} | ||
| if authHeader != "" { | ||
| headers["Authorization"] = authHeader | ||
| } | ||
| return clientbase.Do(c.httpClient, method, c.rancherURL+path, nil, headers) | ||
| } | ||
|
|
||
| // CompleteAuthCodeFlow drives the headless PKCE authorization-code flow and returns a TokenSet. | ||
| func (c *APIClient) CompleteAuthCodeFlow(clientID, clientSecret, redirectURI, scopes, username, password string) (*oidcext.TokenSet, error) { | ||
| const maxAttempts = 5 | ||
| for attempt := 1; attempt <= maxAttempts; attempt++ { | ||
| tokenResp, err := sheptoken.GenerateUserToken(&management.User{Username: username, Password: password}, strings.TrimPrefix(c.rancherURL, "https://")) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("step 1 (Rancher login): %w", err) | ||
| } | ||
| rancherToken := tokenResp.Token | ||
| pkce, err := oidcext.GeneratePKCE() | ||
| if err != nil { | ||
| return nil, fmt.Errorf("step 2 (PKCE generation): %w", err) | ||
| } | ||
| state, err := randomState(12) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("step 2 (state generation): %w", err) | ||
| } | ||
| nonce, err := randomState(12) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("step 2 (nonce generation): %w", err) | ||
| } | ||
| params := url.Values{ | ||
| "response_type": {"code"}, | ||
| "client_id": {clientID}, | ||
| "redirect_uri": {redirectURI}, | ||
| "scope": {scopes}, | ||
| "state": {state}, | ||
| "nonce": {nonce}, | ||
| "code_challenge": {pkce.Challenge}, | ||
| "code_challenge_method": {"S256"}, | ||
| } | ||
| authURL := c.rancherURL + oidcext.OIDCAuthPath + "?" + params.Encode() | ||
| authResp, err := clientbase.Do(c.noRedirectClient, "GET", authURL, nil, map[string]string{ | ||
| "Authorization": "Bearer " + rancherToken, | ||
| }) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("step 3 (auth endpoint GET): %w", err) | ||
| } | ||
| if authResp.StatusCode != http.StatusFound { | ||
| return nil, fmt.Errorf("step 3 expected 302 from auth endpoint, got %d: %s", | ||
| authResp.StatusCode, authResp.Body) | ||
| } | ||
| location := authResp.Header.Get("Location") | ||
| if location == "" { | ||
| return nil, fmt.Errorf("step 4: auth endpoint returned 302 but no Location header") | ||
| } | ||
| if strings.Contains(location, "/dashboard/auth/login") { | ||
| logrus.Infof("step 4: auth endpoint redirected to dashboard login β Rancher session token was rejected, retrying") | ||
| continue | ||
| } | ||
| redirectParsed, err := url.Parse(location) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("step 4: parsing Location URL %q: %w", location, err) | ||
| } | ||
| authCode := redirectParsed.Query().Get("code") | ||
| if authCode == "" { | ||
| return nil, fmt.Errorf("step 4: no 'code' parameter in redirect Location %q", location) | ||
| } | ||
| if redirectParsed.Query().Get("state") != state { | ||
| return nil, fmt.Errorf("step 4: state mismatch") | ||
| } | ||
| body := url.Values{ | ||
| "grant_type": {"authorization_code"}, | ||
| "code": {authCode}, | ||
| "code_verifier": {pkce.Verifier}, | ||
| "client_id": {clientID}, | ||
| "client_secret": {clientSecret}, | ||
| "redirect_uri": {redirectURI}, | ||
| } | ||
| resp, err := clientbase.Do(c.httpClient, "POST", c.rancherURL+oidcext.OIDCTokenPath, body, map[string]string{ | ||
| "Content-Type": "application/x-www-form-urlencoded", | ||
| }) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("token exchange POST: %w", err) | ||
| } | ||
| if resp.StatusCode != http.StatusOK { | ||
| return nil, fmt.Errorf("token exchange returned %d: %s", resp.StatusCode, resp.Body) | ||
| } | ||
| var ts oidcext.TokenSet | ||
| if err := json.Unmarshal(resp.Body, &ts); err != nil { | ||
| return nil, fmt.Errorf("parsing token response: %w", err) | ||
| } | ||
| if ts.AccessToken == "" { | ||
| return nil, fmt.Errorf("token response missing access_token field") | ||
| } | ||
| return &ts, nil | ||
| } | ||
| return nil, fmt.Errorf("PKCE auth flow failed after %d attempts", maxAttempts) | ||
| } | ||
|
|
||
| func randomState(n int) (string, error) { | ||
| raw := make([]byte, n) | ||
| if _, err := rand.Read(raw); err != nil { | ||
| return "", fmt.Errorf("generating random state: %w", err) | ||
| } | ||
| return base64.RawURLEncoding.EncodeToString(raw), nil | ||
| } |
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,39 @@ | ||
| package oidc | ||
|
|
||
| import ( | ||
| "crypto/rand" | ||
| "encoding/base64" | ||
| "encoding/json" | ||
| "fmt" | ||
| "strings" | ||
| ) | ||
|
|
||
| // DecodeJWTPayload decodes the payload section of a JWT without verifying the signature. | ||
| func DecodeJWTPayload(token string) (map[string]interface{}, error) { | ||
| parts := strings.Split(token, ".") | ||
| if len(parts) != 3 { | ||
| return nil, fmt.Errorf("invalid JWT structure: expected 3 parts, got %d", len(parts)) | ||
| } | ||
| payload, err := base64.RawURLEncoding.DecodeString(parts[1]) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("decoding JWT payload: %w", err) | ||
| } | ||
| var claims map[string]interface{} | ||
| if err := json.Unmarshal(payload, &claims); err != nil { | ||
| return nil, fmt.Errorf("parsing JWT claims: %w", err) | ||
| } | ||
| return claims, nil | ||
| } | ||
|
|
||
| // TamperJWTSignature replaces the signature segment of a JWT with random bytes. | ||
| func TamperJWTSignature(token string) (string, error) { | ||
| parts := strings.Split(token, ".") | ||
| if len(parts) != 3 { | ||
| return "", fmt.Errorf("invalid JWT: cannot tamper signature") | ||
| } | ||
| fakeSig := make([]byte, 32) | ||
| if _, err := rand.Read(fakeSig); err != nil { | ||
| return "", fmt.Errorf("generating fake signature: %w", err) | ||
| } | ||
| return parts[0] + "." + parts[1] + "." + base64.RawURLEncoding.EncodeToString(fakeSig), nil | ||
| } |
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,69 @@ | ||
| package oidc | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "fmt" | ||
| "net/http" | ||
| "net/url" | ||
|
|
||
| "github.com/rancher/shepherd/pkg/clientbase" | ||
| ) | ||
|
|
||
| const ( | ||
| OIDCClientGroup = "management.cattle.io" | ||
| OIDCClientVersion = "v3" | ||
| OIDCClientResource = "oidcclients" | ||
| OIDCClientKind = "OIDCClient" | ||
|
|
||
| OIDCDiscoveryPath = "/oidc/.well-known/openid-configuration" | ||
| OIDCAuthPath = "/oidc/authorize" | ||
| OIDCTokenPath = "/oidc/token" | ||
| UsersPath = "/v3/users" | ||
| ClustersPath = "/v3/clusters" | ||
| ) | ||
|
|
||
| type TokenSet struct { | ||
| AccessToken string `json:"access_token"` | ||
| IDToken string `json:"id_token"` | ||
| RefreshToken string `json:"refresh_token"` | ||
| TokenType string `json:"token_type"` | ||
| ExpiresIn int `json:"expires_in"` | ||
| Scope string `json:"scope"` | ||
| } | ||
|
|
||
| // Discovery fetches the OIDC provider metadata document. | ||
| func Discovery(httpClient *http.Client, rancherURL string) (*clientbase.Response, map[string]interface{}, error) { | ||
| resp, err := clientbase.Do(httpClient, "GET", rancherURL+OIDCDiscoveryPath, nil, nil) | ||
| if err != nil { | ||
| return nil, nil, fmt.Errorf("fetching OIDC discovery: %w", err) | ||
| } | ||
| var doc map[string]interface{} | ||
| if err := json.Unmarshal(resp.Body, &doc); err != nil { | ||
| return resp, nil, fmt.Errorf("parsing discovery document: %w", err) | ||
| } | ||
| return resp, doc, nil | ||
| } | ||
|
|
||
| // RefreshAccessToken exchanges a refresh_token for a new TokenSet. | ||
| func RefreshAccessToken(httpClient *http.Client, rancherURL, refreshToken, clientID, clientSecret string) (*TokenSet, error) { | ||
| body := url.Values{ | ||
| "grant_type": {"refresh_token"}, | ||
| "refresh_token": {refreshToken}, | ||
| "client_id": {clientID}, | ||
| "client_secret": {clientSecret}, | ||
| } | ||
| resp, err := clientbase.Do(httpClient, "POST", rancherURL+OIDCTokenPath, body, map[string]string{ | ||
| "Content-Type": "application/x-www-form-urlencoded", | ||
| }) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("refresh token POST: %w", err) | ||
| } | ||
| if resp.StatusCode != http.StatusOK { | ||
| return nil, fmt.Errorf("refresh returned %d: %s", resp.StatusCode, resp.Body) | ||
| } | ||
| var ts TokenSet | ||
| if err := json.Unmarshal(resp.Body, &ts); err != nil { | ||
| return nil, fmt.Errorf("parsing refresh response: %w", err) | ||
| } | ||
| return &ts, nil | ||
| } | ||
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.
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.
this can be removed later when you update OIDCClient CRUD to use wrangler context after the pkg/apis bump in go.mod