-
Notifications
You must be signed in to change notification settings - Fork 0
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
Add OIDC access token validation #107
Merged
Merged
Changes from all commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
7266a19
Add gin middleware for verifying OIDC access tokens
7220f40
Add compensation for keyrotation
7a2088f
Add changelog entry
96dabb9
Invert condition tokenBearer
fredx30 f71e552
Remove newline
fredx30 84ceedf
Rename rsakey -> rsaKey
30e4ccb
Improve error messages from middleware tokken validations
92e9821
Cleaned up OICD env vars & added goDocs
8280aa6
Change magic number to rsaExponent
10921db
Change spelling of OICD to OIDC
10c2982
Grammar nit fixes
4df35ee
Upgrade to golang-jwt/jwt/v4
f5baa29
Add comments to exported methods.
21c0e03
Goimports -w formatting set
179fde8
Update copyrights text
fredx30 768f39f
Refactor Oidc to OIDC
8d6df19
Commit
applejag 3c48cc6
Error on init, warn on update
applejag c49d61a
Extract to configs
applejag bfd1198
Merge remote-tracking branch 'origin/master' into feature/add-oidc-to…
applejag 914978f
problem responses
applejag 8f70221
Panic handling
applejag 3acf4dc
Lint fixes, godoc comments
applejag 838785d
Comment grammar fix
fredx30 78355a8
Caps on env vars
fredx30 12ef751
Improve OIDC settings description
fredx30 61c2ed0
Remove commented out code.
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 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 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 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 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 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 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,161 @@ | ||
package main | ||
|
||
import ( | ||
"crypto/rsa" | ||
"encoding/base64" | ||
"encoding/json" | ||
"errors" | ||
"fmt" | ||
"math/big" | ||
"net/http" | ||
"strings" | ||
"time" | ||
|
||
"github.com/gin-gonic/gin" | ||
"github.com/iver-wharf/wharf-core/pkg/ginutil" | ||
"github.com/iver-wharf/wharf-core/pkg/problem" | ||
|
||
"github.com/golang-jwt/jwt/v4" | ||
) | ||
|
||
// This is a modified version of the code provided in the follow blog post and | ||
// GitHub repository: | ||
// - https://developer.okta.com/blog/2021/01/04/offline-jwt-validation-with-go | ||
// - https://github.com/oktadev/okta-offline-jwt-validation-example/tree/a61cc73bf893686c1efe67ce86448047205826bc | ||
// | ||
// Copyright 2019 Okta, Inc. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
// GetOIDCPublicKeys returns the public keys of the currently set WHARF_HTTP_OIDC_KEYSURL. | ||
func GetOIDCPublicKeys(keysURL string) (map[string]*rsa.PublicKey, error) { | ||
rsaKeys := make(map[string]*rsa.PublicKey) | ||
resp, err := http.Get(keysURL) | ||
if err != nil { | ||
return nil, fmt.Errorf("http GET keys URL: %w", err) | ||
} | ||
var body struct { | ||
Keys []struct { | ||
KeyID string `json:"kid"` | ||
Number string `json:"n"` | ||
} `json:"keys"` | ||
} | ||
err = json.NewDecoder(resp.Body).Decode(&body) | ||
if err != nil { | ||
return nil, fmt.Errorf("decode keys payload: %w", err) | ||
} | ||
log.Debug().Message("Updating keys for oidc.") | ||
rsaExponent := 65537 | ||
for _, key := range body.Keys { | ||
kid := key.KeyID | ||
rsakey := new(rsa.PublicKey) | ||
number, err := base64.RawURLEncoding.DecodeString(key.Number) | ||
if err != nil { | ||
return nil, fmt.Errorf("decode JWT 'n' field: %w", err) | ||
} | ||
rsakey.N = new(big.Int).SetBytes(number) | ||
rsakey.E = rsaExponent | ||
rsaKeys[kid] = rsakey | ||
} | ||
return rsaKeys, nil | ||
} | ||
|
||
func newOIDCMiddleware(rsaKeys map[string]*rsa.PublicKey, config OIDCConfig) *oidcMiddleware { | ||
return &oidcMiddleware{ | ||
rsaKeys: rsaKeys, | ||
config: config, | ||
} | ||
} | ||
|
||
type oidcMiddleware struct { | ||
rsaKeys map[string]*rsa.PublicKey | ||
config OIDCConfig | ||
} | ||
|
||
// VerifyTokenMiddleware is a gin middleware function that enforces validity of the access bearer token on every | ||
// request. This uses the environment vars WHARF_HTTP_OIDC_ISSUERURL and WHARF_HTTP_OIDC_AUDIENCEURL as limiters | ||
// that control the variety of tokens that pass validation. | ||
func (m *oidcMiddleware) VerifyTokenMiddleware(ginContext *gin.Context) { | ||
if m.rsaKeys == nil { | ||
ginutil.WriteProblem(ginContext, problem.Response{ | ||
Type: "/prob/api/oidc/missing-rsa-keys", | ||
Title: "Missing OIDC public keys.", | ||
Status: http.StatusInternalServerError, | ||
Detail: "The OIDC RSA public keys were not properly set up during initialization of the wharf-api.", | ||
}) | ||
ginContext.Abort() | ||
return | ||
} | ||
isValid := false | ||
errorMessage := "" | ||
tokenString := ginContext.Request.Header.Get("Authorization") | ||
if !strings.HasPrefix(tokenString, "Bearer ") { | ||
ginutil.WriteUnauthorized(ginContext, "Expected authorization scheme to be 'Bearer' (case sensitive), but was not.") | ||
ginContext.Abort() | ||
return | ||
} | ||
tokenString = strings.TrimPrefix(tokenString, "Bearer ") | ||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { | ||
if kid, ok := token.Header["kid"].(string); ok { | ||
return m.rsaKeys[kid], nil | ||
} | ||
return nil, errors.New("expected JWT to have string 'kid' field") | ||
}) | ||
if err != nil { | ||
errorMessage = err.Error() | ||
} else if !token.Valid { | ||
errorMessage = "invalid access bearer token." | ||
} else if token.Header["alg"] == nil { | ||
errorMessage = "missing 'alg' field." | ||
} else if token.Claims.(jwt.MapClaims)["aud"] != m.config.AudienceURL { | ||
errorMessage = "invalid 'aud' field." | ||
} else if iss, ok := token.Claims.(jwt.MapClaims)["iss"].(string); !ok { | ||
errorMessage = "invalid or missing 'iss' field: should be string." | ||
} else if !strings.Contains(iss, m.config.IssuerURL) { | ||
errorMessage = "invalid 'iss' field: disallowed issuer." | ||
} else { | ||
isValid = true | ||
} | ||
if !isValid { | ||
ginutil.WriteUnauthorized(ginContext, "Invalid JWT: "+errorMessage) | ||
ginContext.Abort() | ||
} | ||
} | ||
|
||
// SubscribeToKeyURLUpdates ensures new keys are fetched as necessary. | ||
// As a standard OIDC login provider keys should be checked for updates ever 1 day 1 hour. | ||
func (m *oidcMiddleware) SubscribeToKeyURLUpdates() { | ||
fetchOidcKeysTicker := time.NewTicker(m.config.UpdateInterval) | ||
fredx30 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
log.Debug().WithDuration("interval", m.config.UpdateInterval). | ||
Message("Subscribing to OIDC public keys rotation via periodic check timer.") | ||
go func() { | ||
for { | ||
<-fetchOidcKeysTicker.C | ||
fredx30 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
m.updateOIDCPublicKeys() | ||
} | ||
}() | ||
} | ||
|
||
func (m *oidcMiddleware) updateOIDCPublicKeys() { | ||
newKeys, err := GetOIDCPublicKeys(m.config.KeysURL) | ||
if err != nil { | ||
log.Warn().WithError(err). | ||
WithDuration("interval", m.config.UpdateInterval). | ||
Message("Failed to update OIDC public keys.") | ||
} else { | ||
m.rsaKeys = newKeys | ||
log.Info(). | ||
WithDuration("interval", m.config.UpdateInterval). | ||
Message("Successfully updated OIDC public keys.") | ||
} | ||
} |
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.
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.
I think the connection is easier to make towards daily keyrotation if the text mentions day so i would skip this fix.