-
Notifications
You must be signed in to change notification settings - Fork 952
feat: encrypt oidc and git auth tokens in the database #7959
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
Closed
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
6651fe1
feat: encrypt oidc and git auth tokens in the database
kylecarbs b9251fd
Fix dbcrypt
kylecarbs deb577b
Automatically delete rows when not encrypted
kylecarbs faa20ad
gen
kylecarbs 2e19360
Merge branch 'main' into dbcrypt
kylecarbs 614065b
Merge branch 'main' into dbcrypt
kylecarbs 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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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
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,196 @@ | ||
package dbcrypt | ||
|
||
import ( | ||
"context" | ||
"database/sql" | ||
"encoding/base64" | ||
"runtime" | ||
"strings" | ||
"sync/atomic" | ||
|
||
"cdr.dev/slog" | ||
"golang.org/x/xerrors" | ||
|
||
"github.com/coder/coder/coderd/database" | ||
"github.com/coder/coder/cryptorand" | ||
) | ||
|
||
// MagicPrefix is prepended to all encrypted values in the database. | ||
// This is used to determine if a value is encrypted or not. | ||
// If it is encrypted but a key is not provided, an error is returned. | ||
const MagicPrefix = "dbcrypt-" | ||
|
||
type Options struct { | ||
// ExternalTokenCipher is an optional cipher that is used | ||
// to encrypt/decrypt user link and git auth link tokens. If this is nil, | ||
// then no encryption/decryption will be performed. | ||
ExternalTokenCipher *atomic.Pointer[cryptorand.Cipher] | ||
Logger slog.Logger | ||
} | ||
|
||
// New creates a database.Store wrapper that encrypts/decrypts values | ||
// stored at rest in the database. | ||
func New(db database.Store, options *Options) database.Store { | ||
return &dbCrypt{ | ||
Options: options, | ||
Store: db, | ||
} | ||
} | ||
|
||
type dbCrypt struct { | ||
*Options | ||
database.Store | ||
} | ||
|
||
func (db *dbCrypt) InTx(function func(database.Store) error, txOpts *sql.TxOptions) error { | ||
return db.Store.InTx(func(s database.Store) error { | ||
return function(&dbCrypt{ | ||
Options: db.Options, | ||
Store: s, | ||
}) | ||
}, txOpts) | ||
} | ||
|
||
func (db *dbCrypt) GetUserLinkByLinkedID(ctx context.Context, linkedID string) (database.UserLink, error) { | ||
link, err := db.Store.GetUserLinkByLinkedID(ctx, linkedID) | ||
if err != nil { | ||
return database.UserLink{}, err | ||
} | ||
return link, db.decryptFields(func() error { | ||
return db.Store.DeleteUserLinkByLinkedID(ctx, linkedID) | ||
}, &link.OAuthAccessToken, &link.OAuthRefreshToken) | ||
} | ||
|
||
func (db *dbCrypt) GetUserLinkByUserIDLoginType(ctx context.Context, params database.GetUserLinkByUserIDLoginTypeParams) (database.UserLink, error) { | ||
link, err := db.Store.GetUserLinkByUserIDLoginType(ctx, params) | ||
if err != nil { | ||
return database.UserLink{}, err | ||
} | ||
return link, db.decryptFields(func() error { | ||
return db.Store.DeleteUserLinkByLinkedID(ctx, link.LinkedID) | ||
}, &link.OAuthAccessToken, &link.OAuthRefreshToken) | ||
} | ||
|
||
func (db *dbCrypt) InsertUserLink(ctx context.Context, params database.InsertUserLinkParams) (database.UserLink, error) { | ||
err := db.encryptFields(¶ms.OAuthAccessToken, ¶ms.OAuthRefreshToken) | ||
if err != nil { | ||
return database.UserLink{}, err | ||
} | ||
return db.Store.InsertUserLink(ctx, params) | ||
} | ||
|
||
func (db *dbCrypt) UpdateUserLink(ctx context.Context, params database.UpdateUserLinkParams) (database.UserLink, error) { | ||
err := db.encryptFields(¶ms.OAuthAccessToken, ¶ms.OAuthRefreshToken) | ||
if err != nil { | ||
return database.UserLink{}, err | ||
} | ||
return db.Store.UpdateUserLink(ctx, params) | ||
} | ||
|
||
func (db *dbCrypt) InsertGitAuthLink(ctx context.Context, params database.InsertGitAuthLinkParams) (database.GitAuthLink, error) { | ||
err := db.encryptFields(¶ms.OAuthAccessToken, ¶ms.OAuthRefreshToken) | ||
if err != nil { | ||
return database.GitAuthLink{}, err | ||
} | ||
return db.Store.InsertGitAuthLink(ctx, params) | ||
} | ||
|
||
func (db *dbCrypt) GetGitAuthLink(ctx context.Context, params database.GetGitAuthLinkParams) (database.GitAuthLink, error) { | ||
link, err := db.Store.GetGitAuthLink(ctx, params) | ||
if err != nil { | ||
return database.GitAuthLink{}, err | ||
} | ||
return link, db.decryptFields(func() error { | ||
return db.Store.DeleteGitAuthLink(ctx, database.DeleteGitAuthLinkParams{ | ||
ProviderID: params.ProviderID, | ||
UserID: params.UserID, | ||
}) | ||
}, &link.OAuthAccessToken, &link.OAuthRefreshToken) | ||
} | ||
|
||
func (db *dbCrypt) UpdateGitAuthLink(ctx context.Context, params database.UpdateGitAuthLinkParams) (database.GitAuthLink, error) { | ||
err := db.encryptFields(¶ms.OAuthAccessToken, ¶ms.OAuthRefreshToken) | ||
if err != nil { | ||
return database.GitAuthLink{}, err | ||
} | ||
return db.Store.UpdateGitAuthLink(ctx, params) | ||
} | ||
|
||
func (db *dbCrypt) encryptFields(fields ...*string) error { | ||
cipherPtr := db.ExternalTokenCipher.Load() | ||
// If no cipher is loaded, then we don't need to encrypt or decrypt anything! | ||
if cipherPtr == nil { | ||
return nil | ||
} | ||
cipher := *cipherPtr | ||
for _, field := range fields { | ||
if field == nil { | ||
continue | ||
} | ||
|
||
encrypted, err := cipher.Encrypt([]byte(*field)) | ||
if err != nil { | ||
return err | ||
} | ||
// Base64 is used to support UTF-8 encoding in PostgreSQL. | ||
*field = MagicPrefix + base64.StdEncoding.EncodeToString(encrypted) | ||
} | ||
return nil | ||
} | ||
|
||
// decryptFields decrypts the given fields in place. | ||
// If the value fails to decrypt, sql.ErrNoRows will be returned. | ||
func (db *dbCrypt) decryptFields(deleteFn func() error, fields ...*string) error { | ||
delete := func(reason string) error { | ||
err := deleteFn() | ||
if err != nil { | ||
return xerrors.Errorf("delete encrypted row: %w", err) | ||
} | ||
pc, _, _, ok := runtime.Caller(2) | ||
details := runtime.FuncForPC(pc) | ||
if ok && details != nil { | ||
db.Logger.Debug(context.Background(), "deleted row", slog.F("reason", reason), slog.F("caller", details.Name())) | ||
} | ||
return sql.ErrNoRows | ||
} | ||
|
||
cipherPtr := db.ExternalTokenCipher.Load() | ||
// If no cipher is loaded, then we don't need to encrypt or decrypt anything! | ||
if cipherPtr == nil { | ||
for _, field := range fields { | ||
if field == nil { | ||
continue | ||
} | ||
if strings.HasPrefix(*field, MagicPrefix) { | ||
// If we have a magic prefix but encryption is disabled, | ||
// we should delete the row. | ||
return delete("encryption disabled") | ||
} | ||
} | ||
return nil | ||
} | ||
|
||
cipher := *cipherPtr | ||
for _, field := range fields { | ||
if field == nil { | ||
continue | ||
} | ||
if len(*field) < len(MagicPrefix) || !strings.HasPrefix(*field, MagicPrefix) { | ||
// We do not force encryption of unencrypted rows. This could be damaging | ||
// to the deployment, and admins can always manually purge data. | ||
continue | ||
} | ||
data, err := base64.StdEncoding.DecodeString((*field)[len(MagicPrefix):]) | ||
if err != nil { | ||
// If it's not base64 with the prefix, we should delete the row. | ||
return delete("stored value was not base64 encoded") | ||
} | ||
decrypted, err := cipher.Decrypt(data) | ||
if err != nil { | ||
// If the encryption key changed, we should delete the row. | ||
return delete("encryption key changed") | ||
} | ||
*field = string(decrypted) | ||
} | ||
return nil | ||
} |
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.
What happens when the key is accidentally not specified during coder startup? All rows will start being deleted when they're queried? This seems like a really bad idea
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.
All data encrypted at rest is intentionally temporary. We will not do this for any data that must persist.
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 should be written in a very prominent comment at the top of the file or something then, because I can definitely see this being used for e.g. gitauth by another engineer who doesn't know about this limitation
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.
Agreed will add
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.
What about ssh keys that should use encryption at rest ?
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.
@Adphi that isn't in this PR yet, but I'm not sure what we should do in that case. Maybe stop the server from starting with a warning that is dismissable?
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.
If I may, perhaps when the encryption key is wrong, the program should crash loudly to preserve the integrity of the secrets.
And maybe add a command line flag or environment variable to allow all encrypted data to be erased, recovery style.
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.
Agreed!