8000 feat: enable key rotation by sreya · Pull Request #15066 · coder/coder · GitHub
[go: up one dir, main page]

Skip to content

feat: enable key rotation #15066

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

Merged
merged 42 commits into from
Oct 25, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
b745c8e
feat: enable key rotation
sreya Oct 5, 2024
b98bff0
add migration
sreya Oct 5, 2024
0646b30
Refactor cryptographic key handling for OIDC and API keys
sreya Oct 5, 2024
b73b210
the end is nigh
sreya Oct 5, 2024
7fe88ea
fix migrations
sreya Oct 14, 2024
0323f79
Refactor key cache management for better clarity
sreya Oct 14, 2024
7413907
hm
sreya Oct 14, 2024
2ea31ab
fixing tests
sreya Oct 14, 2024
d0d168b
time to fix it
sreya Oct 15, 2024
33cdb96
Refactor cryptokeys Fetcher to include feature param
sreya Oct 16, 2024
08570b7
Refactor key caching and logging behavior
sreya Oct 16, 2024
b770762
Refactor crypto_key_feature migration logic
sreya Oct 16, 2024
7557ed2
Refactor key management and enhance logging
sreya Oct 16, 2024
fa9a75d
Update cryptokey feature test and migration logic
sreya Oct 17, 2024
94987b6
gen
sreya Oct 17, 2024
76561ac
Refactor cryptokeys cache to include key reader context
sreya Oct 17, 2024
53dcf36
Refactor jwtutils to remove redundant key reader
sreya Oct 17, 2024
c656d00
Remove unused cryptokey feature fixtures
sreya Oct 17, 2024
e7cfb46
Refactor cryptokeys comments and variable typo
sreya Oct 17, 2024
6432b0d
fix comments
sreya Oct 17, 2024
9ad187d
move rotator out of coderd
sreya Oct 17, 2024
d16e98f
remove composite jwtutil interfaces
sreya Oct 17, 2024
3809cd5
fix tests caused by moving rotator initiation out of coderd
sreya Oct 17, 2024
6d3c103
pr comments
sreya Oct 20, 2024
a3020fc
Merge branch 'main' into jon/glue
sreya Oct 20, 2024
bfa88b7
Refactor tests to remove direct database setup
sreya Oct 20, 2024
495c28f
Rename cryptokey migration files to update sequence
sreya Oct 20, 2024
692bb36
Fix conditional logging in key cache initialization
sreya Oct 20, 2024
4028995
Refactor crypto key management in tests
sreya Oct 20, 2024
6b9a3e4
add test for oidc jwt
sreya Oct 21, 2024
5ee6ad5
add test for tailnet_resume jwt
sreya Oct 21, 2024
886d87c
add test for workspaceapps
sreya Oct 21, 2024
5261442
add test for signedtoken
sreya Oct 22, 2024
4a1d974
fix migrations
sreya Oct 22, 2024
092a241
fmt
sreya Oct 22, 2024
87828a2
pr comments
sreya Oct 22, 2024
6aa90bc
Merge branch 'main' into jon/glue
sreya Oct 22, 2024
358aaa8
Rename cryptokey migration files to update sequence
sreya Oct 22, 2024
ad237ad
Merge branch 'main' into jon/glue
sreya Oct 24, 2024
5798a33
migrations
sreya Oct 24, 2024
200cd68
Refactor StaticKey to jwtutils package
sreya Oct 24, 2024
2194b4d
fix tests
sreya Oct 24, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
feat: enable key rotation
  • Loading branch information
sreya committed Oct 16, 2024
commit b745c8eab95584fe00f7c49e57f79f2b07b6df9f
14 changes: 14 additions & 0 deletions coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import (
"github.com/coder/quartz"
"github.com/coder/serpent"

"github.com/coder/coder/v2/coderd/cryptokeys"
"github.com/coder/coder/v2/coderd/entitlements"
"github.com/coder/coder/v2/coderd/idpsync"
"github.com/coder/coder/v2/coderd/runtimeconfig"
Expand Down Expand Up @@ -609,6 +610,14 @@ func New(options *Options) *API {
api.Logger.Fatal(api.ctx, "failed to initialize tailnet client service", slog.Error(err))
}

// Start a background process that rotates keys.
err = cryptokeys.StartRotator(api.ctx, api.Logger.Named("keyrotator"), api.Database)
if err != nil {
api.Logger.Fatal(api.ctx, "start key rotator", slog.Error(err))
}

api.oauthConvertKeycache = cryptokeys.NewDBCache(api.Logger.Named("oauth_convert_keycache"), api.Database, database.CryptoKeyFeatureOidcConvert)

api.statsReporter = workspacestats.NewReporter(workspacestats.ReporterOptions{
Database: options.Database,
Logger: options.Logger.Named("workspacestats"),
Expand Down Expand Up @@ -1389,6 +1398,11 @@ type API struct {
// dbRolluper rolls up template usage stats from raw agent and app
// stats. This is used to provide insights in the WebUI.
dbRolluper *dbrollup.Rolluper

// resumeTokenKeycache is used to fetch and cache keys used for signing JWTs
// oauthConvertKeycache is used to fetch and cache keys used for signing JWTs
// during OAuth conversions. See userauth.go.convertUserToOauth.
oauthConvertKeycache cryptokeys.Keycache
}

// Close waits for all WebSocket connections to drain before returning.
Expand Down
3 changes: 3 additions & 0 deletions coderd/cryptokeys/rotate.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (

"cdr.dev/slog"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/quartz"
)
Expand Down Expand Up @@ -54,6 +55,8 @@ func WithKeyDuration(keyDuration time.Duration) RotatorOption {
// It ensures there's at least one valid key per feature prior to returning.
// Canceling the provided context will stop the background process.
func StartRotator(ctx context.Context, logger slog.Logger, db database.Store, opts ...RotatorOption) error {
//nolint:gocritic // KeyRotator can only rotate crypto keys.
ctx = dbauthz.AsSystemRestricted(ctx)
kr := &rotator{
db: db,
logger: logger,
Expand Down
23 changes: 23 additions & 0 deletions coderd/database/dbauthz/dbauthz.go
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,24 @@ var (
Scope: rbac.ScopeAll,
}.WithCachedASTValue()

// See cryptokeys package.
subjectCryptoKey = rbac.Subject{
FriendlyName: "Crypto Key Rotator",
ID: uuid.Nil.String(),
Roles: rbac.Roles([]rbac.Role{
{
Identifier: rbac.RoleIdentifier{Name: "keyrotator"},
DisplayName: "Key Rotator",
Site: rbac.Permissions(map[string][]policy.Action{
rbac.ResourceCryptoKey.Type: {policy.WildcardSymbol, policy.ActionRead},
}),
Org: map[string][]rbac.Permission{},
User: []rbac.Permission{},
},
}),
Scope: rbac.ScopeAll,
}.WithCachedASTValue()

subjectSystemRestricted = rbac.Subject{
FriendlyName: "System",
ID: uuid.Nil.String(),
Expand Down Expand Up @@ -281,6 +299,11 @@ func AsHangDetector(ctx context.Context) context.Context {
return context.WithValue(ctx, authContextKey{}, subjectHangDetector)
}

// AsKeyRotator returns a context with an actor that has permissions required for rotating crypto keys.
func AsKeyRotator(ctx context.Context) context.Context {
return context.WithValue(ctx, authContextKey{}, subjectCryptoKey)
}

// AsSystemRestricted returns a context with an actor that has permissions
// required for various system operations (login, logout, metrics cache).
func AsSystemRestricted(ctx context.Context) context.Context {
Expand Down
34 changes: 17 additions & 17 deletions coderd/userauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,18 @@ import (
"time"

"github.com/coreos/go-oidc/v3/oidc"
"github.com/golang-jwt/jwt/v4"
"github.com/go-jose/go-jose/v4"
"github.com/go-jose/go-jose/v4/jwt"
"github.com/google/go-github/v43/github"
"github.com/google/uuid"
"github.com/moby/moby/pkg/namesgenerator"
"golang.org/x/oauth2"
"golang.org/x/xerrors"

"cdr.dev/slog"
"github.com/coder/coder/v2/coderd/cryptokeys"
"github.com/coder/coder/v2/coderd/idpsync"
"github.com/coder/coder/v2/coderd/jwtutils"

"github.com/coder/coder/v2/coderd/apikey"
"github.com/coder/coder/v2/coderd/audit"
Expand All @@ -49,7 +53,7 @@ const (
)

type OAuthConvertStateClaims struct {
jwt.RegisteredClaims
jwt.Claims

UserID uuid.UUID `json:"user_id"`
State string `json:"state"`
Expand Down Expand Up @@ -149,11 +153,11 @@ func (api *API) postConvertLoginType(rw http.ResponseWriter, r *http.Request) {
// Eg: Developers with more than 1 deployment.
now := time.Now()
claims := &OAuthConvertStateClaims{
RegisteredClaims: jwt.RegisteredClaims{
Claims: jwt.Claims{
Issuer: api.DeploymentID,
Subject: stateString,
Audience: []string{user.ID.String()},
ExpiresAt: jwt.NewNumericDate(now.Add(time.Minute * 5)),
Expiry: jwt.NewNumericDate(now.Add(time.Minute * 5)),
NotBefore: jwt.NewNumericDate(now.Add(time.Second * -1)),
IssuedAt: jwt.NewNumericDate(now),
ID: uuid.NewString(),
Expand All @@ -164,9 +168,7 @@ func (api *API) postConvertLoginType(rw http.ResponseWriter, r *http.Request) {
ToLoginType: req.ToType,
}

token := jwt.NewWithClaims(jwt.SigningMethodHS512, claims)
// Key must be a byte slice, not an array. So make sure to include the [:]
tokenString, err := token.SignedString(api.OAuthSigningKey[:])
token, err := jwtutils.Sign(dbauthz.AsKeyRotator(ctx), api.oauthConvertKeycache, claims)
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Internal error signing state jwt.",
Expand All @@ -176,8 +178,8 @@ func (api *API) postConvertLoginType(rw http.ResponseWriter, r *http.Request) {
}

aReq.New = database.AuditOAuthConvertState{
CreatedAt: claims.IssuedAt.Time,
ExpiresAt: claims.ExpiresAt.Time,
CreatedAt: claims.IssuedAt.Time(),
ExpiresAt: claims.Expiry.Time(),
FromLoginType: database.LoginType(claims.FromLoginType),
ToLoginType: database.LoginType(claims.ToLoginType),
UserID: claims.UserID,
Expand All @@ -186,8 +188,8 @@ func (api *API) postConvertLoginType(rw http.ResponseWriter, r *http.Request) {
http.SetCookie(rw, &http.Cookie{
Name: OAuthConvertCookieValue,
Path: "/",
Value: tokenString,
Expires: claims.ExpiresAt.Time,
Value: token,
Expires: claims.Expiry.Time(),
Secure: api.SecureAuthCookie,
HttpOnly: true,
// Must be SameSite to work on the redirected auth flow from the
Expand All @@ -196,7 +198,7 @@ func (api *API) postConvertLoginType(rw http.ResponseWriter, r *http.Request) {
})
httpapi.Write(ctx, rw, http.StatusCreated, codersdk.OAuthConversionResponse{
StateString: stateString,
ExpiresAt: claims.ExpiresAt.Time,
ExpiresAt: claims.Expiry.Time(),
ToType: claims.ToLoginType,
UserID: claims.UserID,
})
Expand Down Expand Up @@ -1675,10 +1677,8 @@ func (api *API) convertUserToOauth(ctx context.Context, r *http.Request, db data
}
}
var claims OAuthConvertStateClaims
token, err := jwt.ParseWithClaims(jwtCookie.Value, &claims, func(_ *jwt.Token) (interface{}, error) {
return api.OAuthSigningKey[:], nil
})
if xerrors.Is(err, jwt.ErrSignatureInvalid) || !token.Valid {
err = jwtutils.Verify(dbauthz.AsKeyRotator(ctx), api.oauthConvertKeycache, jwtCookie.Value, &claims)
if xerrors.Is(err, cryptokeys.ErrKeyNotFound) || xerrors.Is(err, cryptokeys.ErrKeyInvalid) || xerrors.Is(err, jose.ErrCryptoFailure) {
// These errors are probably because the user is mixing 2 coder deployments.
return database.User{}, idpsync.HTTPError{
Code: http.StatusBadRequest,
Expand Down Expand Up @@ -1707,7 +1707,7 @@ func (api *API) convertUserToOauth(ctx context.Context, r *http.Request, db data
oauthConvertAudit.UserID = claims.UserID
oauthConvertAudit.Old = user

if claims.RegisteredClaims.Issuer != api.DeploymentID {
if claims.Issuer != api.DeploymentID {
return database.User{}, idpsync.HTTPError{
Code: http.StatusForbidden,
Msg: "Request to convert login type failed. Issuer mismatch. Found a cookie from another coder deployment, please try again.",
Expand Down
0