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
Prev Previous commit
Next Next commit
Refactor key cache management for better clarity
- Consolidates key cache handling by replacing legacy key cache references with central key caches.
- Enhances modularity and maintainability by using consistent key management methods.
- Removes redundant `StaticKeyManager` implementation for streamlined code.
- Adjusts cryptographic key generation and cache utilization across critical components.
  • Loading branch information
sreya committed Oct 16, 2024
commit 0323f791865e40c6c4dc3e27ed84afcda9d6647e
17 changes: 5 additions & 12 deletions coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,11 @@ type Options struct {

// OneTimePasscodeValidityPeriod specifies how long a one time passcode should be valid for.
OneTimePasscodeValidityPeriod time.Duration

// Keycaches
AppSigningKeyCache cryptokeys.SigningKeycache
AppEncryptionKeyCache cryptokeys.EncryptionKeycache
OIDCConvertKeyCache cryptokeys.SigningKeycache
}

// @title Coder API
Expand Down Expand Up @@ -622,12 +627,6 @@ func New(options *Options) *API {
api.Logger.Fatal(api.ctx, "start key rotator", slog.Error(err))
}

api.oauthConvertKeycache, err = cryptokeys.NewSigningCache(api.Logger.Named("oauth_convert_keycache"), api.Database, database.CryptoKeyFeatureOIDCConvert)
if err != nil {
api.Logger.Fatal(api.ctx, "failed to initialize oauth convert key cache", slog.Error(err))
}
api.workspaceAppsKeyCache = appEncryptingKeyCache

api.statsReporter = workspacestats.NewReporter(workspacestats.ReporterOptions{
Database: options.Database,
Logger: options.Logger.Named("workspacestats"),
Expand Down Expand Up @@ -1406,12 +1405,6 @@ 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.SigningKeycache
workspaceAppsKeyCache cryptokeys.EncryptionKeycache
}

// Close waits for all WebSocket connections to drain before returning.
Expand Down
14 changes: 12 additions & 2 deletions coderd/coderdtest/coderdtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import (
"github.com/coder/coder/v2/coderd/audit"
"github.com/coder/coder/v2/coderd/autobuild"
"github.com/coder/coder/v2/coderd/awsidentity"
"github.com/coder/coder/v2/coderd/cryptokeys"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/db2sdk"
"github.com/coder/coder/v2/coderd/database/dbauthz"
Expand Down Expand Up @@ -157,8 +158,7 @@ type Options struct {
DatabaseRolluper *dbrollup.Rolluper
WorkspaceUsageTrackerFlush chan int
WorkspaceUsageTrackerTick chan time.Time

NotificationsEnqueuer notifications.Enqueuer
NotificationsEnqueuer notifications.Enqueuer
}

// New constructs a codersdk client connected to an in-memory API instance.
Expand Down Expand Up @@ -326,6 +326,13 @@ func NewOptions(t testing.TB, options *Options) (func(http.Handler), context.Can
}
auditor.Store(&options.Auditor)

oidcConvertKeyCache, err := cryptokeys.NewSigningCache(options.Logger.Named("oidc_convert_keycache"), options.Database, database.CryptoKeyFeatureOIDCConvert)
require.NoError(t, err)
appSigningKeyCache, err := cryptokeys.NewSigningCache(options.Logger.Named("app_signing_keycache"), options.Database, database.CryptoKeyFeatureWorkspaceAppsToken)
require.NoError(t, err)
appEncryptionKeyCache, err := cryptokeys.NewEncryptionCache(options.Logger.Named("app_encryption_keycache"), options.Database, database.CryptoKeyFeatureWorkspaceAppsAPIKey)
require.NoError(t, err)

ctx, cancelFunc := context.WithCancel(context.Background())
lifecycleExecutor := autobuild.NewExecutor(
ctx,
Expand Down Expand Up @@ -533,6 +540,9 @@ func NewOptions(t testing.TB, options *Options) (func(http.Handler), context.Can
WorkspaceUsageTracker: wuTracker,
NotificationsEnqueuer: options.NotificationsEnqueuer,
OneTimePasscodeValidityPeriod: options.OneTimePasscodeValidityPeriod,
AppSigningKeyCache: appSigningKeyCache,
AppEncryptionKeyCache: appEncryptionKeyCache,
OIDCConvertKeyCache: oidcConvertKeyCache,
}
}

Expand Down
4 changes: 4 additions & 0 deletions coderd/cryptokeys/rotate.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,8 @@ func generateNewSecret(feature database.CryptoKeyFeature) (string, error) {
switch feature {
case database.CryptoKeyFeatureWorkspaceAppsAPIKey:
return generateKey(32)
case database.CryptoKeyFeatureWorkspaceAppsToken:
return generateKey(64)
case database.CryptoKeyFeatureOIDCConvert:
return generateKey(64)
case database.CryptoKeyFeatureTailnetResume:
Expand All @@ -252,6 +254,8 @@ func tokenDuration(feature database.CryptoKeyFeature) time.Duration {
switch feature {
case database.CryptoKeyFeatureWorkspaceAppsAPIKey:
return WorkspaceAppsTokenDuration
case database.CryptoKeyFeatureWorkspaceAppsToken:
return WorkspaceAppsTokenDuration
case database.CryptoKeyFeatureOIDCConvert:
return OIDCConvertTokenDuration
case database.CryptoKeyFeatureTailnetResume:
Expand Down
27 changes: 0 additions & 27 deletions coderd/jwtutils/jwe.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,30 +130,3 @@ func Decrypt(ctx context.Context, d DecryptKeyProvider, token string, claims Cla

return claims.Validate(options.RegisteredClaims)
}

type StaticKeyManager struct {
ID string
Key interface{}
}

func (s StaticKeyManager) SigningKey(_ context.Context) (string, interface{}, error) {
return s.ID, s.Key, nil
}

func (s StaticKeyManager) VerifyingKey(_ context.Context, id string) (interface{}, error) {
if id != s.ID {
return nil, xerrors.Errorf("invalid id %q", id)
}
return s.Key, nil
}

func (s StaticKeyManager) EncryptingKey(_ context.Context) (string, interface{}, error) {
return s.ID, s.Key, nil
}

func (s StaticKeyManager) DecryptingKey(_ context.Context, id string) (interface{}, error) {
if id != s.ID {
return nil, xerrors.Errorf("invalid id %q", id)
}
return s.Key, nil
}
4 changes: 2 additions & 2 deletions coderd/userauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ func (api *API) postConvertLoginType(rw http.ResponseWriter, r *http.Request) {
ToLoginType: req.ToType,
}

token, err := jwtutils.Sign(dbauthz.AsKeyRotator(ctx), api.oauthConvertKeycache, claims)
token, err := jwtutils.Sign(dbauthz.AsKeyRotator(ctx), api.OIDCConvertKeyCache, claims)
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Internal error signing state jwt.",
Expand Down Expand Up @@ -1676,7 +1676,7 @@ func (api *API) convertUserToOauth(ctx context.Context, r *http.Request, db data
}
}
var claims OAuthConvertStateClaims
err = jwtutils.Verify(dbauthz.AsKeyRotator(ctx), api.oauthConvertKeycache, jwtCookie.Value, &claims)
err = jwtutils.Verify(dbauthz.AsKeyRotator(ctx), api.OIDCConvertKeyCache, 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{
Expand Down
2 changes: 1 addition & 1 deletion coderd/workspaceagents_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -560,7 +560,7 @@ func TestWorkspaceAgentClientCoordinate_ResumeToken(t *testing.T) {
resumeTokenSigningKey, err := tailnet.GenerateResumeTokenSigningKey()
mgr := jwtutils.StaticKeyManager{
ID: uuid.New().String(),
Key: resumeTokenSigningKey,
Key: resumeTokenSigningKey[:],
}
require.NoError(t, err)
resumeTokenProvider := newResumeTokenRecordingProvider(
Expand Down
2 changes: 1 addition & 1 deletion coderd/workspaceapps.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ func (api *API) workspaceApplicationAuth(rw http.ResponseWriter, r *http.Request
return
}

encryptedAPIKey, err := jwtutils.Encrypt(ctx, api.workspaceAppsKeyCache, workspaceapps.EncryptedAPIKeyPayload{
encryptedAPIKey, err := jwtutils.Encrypt(ctx, api.AppEncryptionKeyCache, workspaceapps.EncryptedAPIKeyPayload{
APIKey: cookie.Value,
})
if err != nil {
Expand Down
3 changes: 2 additions & 1 deletion coderd/workspaceapps/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import (
"golang.org/x/exp/slices"
"golang.org/x/xerrors"

"github.com/go-jose/go-jose/v4/jwt"

"cdr.dev/slog"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
Expand All @@ -22,7 +24,6 @@ import (
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/coderd/rbac/policy"
"github.com/coder/coder/v2/codersdk"
"github.com/go-jose/go-jose/v4/jwt"
)

// DBTokenProvider provides authentication and authorization for workspace apps
Expand Down
10 changes: 7 additions & 3 deletions coderd/workspaceapps/db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"github.com/coder/coder/v2/agent/agenttest"
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/coderd/httpmw"
"github.com/coder/coder/v2/coderd/jwtutils"
"github.com/coder/coder/v2/coderd/workspaceapps"
"github.com/coder/coder/v2/coderd/workspaceapps/appurl"
"github.com/coder/coder/v2/codersdk"
Expand Down Expand Up @@ -295,7 +296,8 @@ func Test_ResolveRequest(t *testing.T) {
require.Equal(t, codersdk.SignedAppTokenCookie, cookie.Name)
require.Equal(t, req.BasePath, cookie.Path)

parsedToken, err := api.workspaceAppsKeyCache.VerifySignedToken(cookie.Value)
var parsedToken workspaceapps.SignedToken
err := jwtutils.Verify(ctx, api.AppSigningKeyCache, cookie.Value, &parsedToken)
require.NoError(t, err)
// normalize expiry
require.WithinDuration(t, token.Expiry.Time(), parsedToken.Expiry.Time(), 2*time.Second)
Expand Down Expand Up @@ -551,7 +553,8 @@ func Test_ResolveRequest(t *testing.T) {
AgentID: agentID,
AppURL: appURL,
}
badTokenStr, err := api.AppSecurityKey.SignToken(badToken)

badTokenStr, err := jwtutils.Sign(ctx, api.AppSigningKeyCache, badToken)
require.NoError(t, err)

req := (workspaceapps.Request{
Expand Down Expand Up @@ -594,7 +597,8 @@ func Test_ResolveRequest(t *testing.T) {
require.Len(t, cookies, 1)
require.Equal(t, cookies[0].Name, codersdk.SignedAppTokenCookie)
require.NotEqual(t, cookies[0].Value, badTokenStr)
parsedToken, err := api.AppSecurityKey.VerifySignedToken(cookies[0].Value)
var parsedToken workspaceapps.SignedToken
err = jwtutils.Verify(ctx, api.AppSigningKeyCache, cookies[0].Value, &parsedToken)
require.NoError(t, err)
require.Equal(t, appNameOwner, parsedToken.AppSlugOrPort)
})
Expand Down
3 changes: 2 additions & 1 deletion coderd/workspaceapps/token_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ import (
"testing"
"time"

"github.com/go-jose/go-jose/v4/jwt"

"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/testutil"
"github.com/go-jose/go-jose/v4/jwt"

"github.com/google/uuid"
"github.com/stretchr/testify/require"
Expand Down
4 changes: 2 additions & 2 deletions codersdk/workspacesdk/connector_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ func TestTailnetAPIConnector_ResumeToken(t *testing.T) {
require.NoError(t, err)
mgr := jwtutils.StaticKeyManager{
ID: uuid.New().String(),
Key: resumeTokenSigningKey,
Key: resumeTokenSigningKey[:],
}
resumeTokenProvider := tailnet.NewResumeTokenKeyProvider(mgr, clock, time.Hour)
svc, err := tailnet.NewClientService(tailnet.ClientServiceOptions{
Expand Down Expand Up @@ -287,7 +287,7 @@ func TestTailnetAPIConnector_ResumeTokenFailure(t *testing.T) {
require.NoError(t, err)
mgr := jwtutils.StaticKeyManager{
ID: uuid.New().String(),
Key: resumeTokenSigningKey,
Key: resumeTokenSigningKey[:],
}
resumeTokenProvider := tailnet.NewResumeTokenKeyProvider(mgr, clock, time.Hour)
svc, err := tailnet.NewClientService(tailnet.ClientServiceOptions{
Expand Down
24 changes: 11 additions & 13 deletions enterprise/wsproxy/wsproxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (
"github.com/coder/coder/v2/buildinfo"
"github.com/coder/coder/v2/cli/cliutil"
"github.com/coder/coder/v2/coderd"
"github.com/coder/coder/v2/coderd/cryptokeys"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/httpmw"
"github.com/coder/coder/v2/coderd/tracing"
Expand Down Expand Up @@ -92,7 +93,9 @@ type Options struct {
// from the dashboardURL. This should only be used in development.
AllowAllCors bool

StatsCollectorOptions workspaceapps.StatsCollectorOptions
StatsCollectorOptions workspaceapps.StatsCollectorOptions
WorkspaceAppsEncryptionKeycache cryptokeys.EncryptionKeycache
WorkspaceAppsSigningKeycache cryptokeys.SigningKeycache
}

func (o *Options) Validate() error {
Expand Down Expand Up @@ -240,11 +243,6 @@ func New(ctx context.Context, opts *Options) (*Server, error) {
return nil, xerrors.Errorf("handle register: %w", err)
}

secKey, err := workspaceapps.KeyFromString(regResp.AppSecurityKey)
if err != nil {
return nil, xerrors.Errorf("parse app security key: %w", err)
}

agentProvider, err := coderd.NewServerTailnet(ctx,
s.Logger,
nil,
Expand Down Expand Up @@ -277,14 +275,14 @@ func New(ctx context.Context, opts *Options) (*Server, error) {
HostnameRegex: opts.AppHostnameRegex,
RealIPConfig: opts.RealIPConfig,
SignedTokenProvider: &TokenProvider{
DashboardURL: opts.DashboardURL,
AccessURL: opts.AccessURL,
AppHostname: opts.AppHostname,
Client: client,
SecurityKey: secKey,
Logger: s.Logger.Named("proxy_token_provider"),
DashboardURL: opts.DashboardURL,
AccessURL: opts.AccessURL,
AppHostname: opts.AppHostname,
Client: client,
SigningKey: opts.WorkspaceAppsSigningKeycache,
EncryptingKey: opts.WorkspaceAppsEncryptionKeycache,
Logger: s.Logger.Named("proxy_token_provider"),
},
AppSecurityKey: secKey,

DisablePathApps: opts.DisablePathApps,
SecureAuthCookie: opts.SecureAuthCookie,
Expand Down
2 changes: 1 addition & 1 deletion tailnet/resume_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,6 @@ func TestResumeTokenKeyProvider(t *testing.T) {
func newKeySigner(key tailnet.ResumeTokenSigningKey) jwtutils.SigningKeyManager {
return jwtutils.StaticKeyManager{
ID: uuid.New().String(),
Key: key,
Key: key[:],
}
}