Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Closed
kylecarbs wants to merge6 commits intomainfromdbcrypt
Closed
Show file tree
Hide file tree
Changes fromall commits
Commits
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
3 changes: 3 additions & 0 deletionscoderd/apidoc/docs.go
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

3 changes: 3 additions & 0 deletionscoderd/apidoc/swagger.json
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

2 changes: 1 addition & 1 deletioncoderd/authorize.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -75,7 +75,7 @@ func (h *HTTPAuthorizer) Authorize(r *http.Request, action rbac.Action, object r
}
// Log information for debugging. This will be very helpful
// in the early days
logger.Warn(r.Context(), "unauthorized",
logger.Debug(r.Context(), "unauthorized",
slog.F("roles", roles.Actor.SafeRoleNames()),
slog.F("actor_id", roles.Actor.ID),
slog.F("actor_name", roles.ActorName),
Expand Down
13 changes: 13 additions & 0 deletionscoderd/database/dbauthz/dbauthz.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -707,6 +707,15 @@ func (q *querier) DeleteApplicationConnectAPIKeysByUserID(ctx context.Context, u
return q.db.DeleteApplicationConnectAPIKeysByUserID(ctx, userID)
}

func (q *querier) DeleteGitAuthLink(ctx context.Context, arg database.DeleteGitAuthLinkParams) error {
return deleteQ(q.log, q.auth, func(ctx context.Context, arg database.DeleteGitAuthLinkParams) (database.GitAuthLink, error) {
return q.db.GetGitAuthLink(ctx, database.GetGitAuthLinkParams{
ProviderID: arg.ProviderID,
UserID: arg.UserID,
})
}, q.db.DeleteGitAuthLink)(ctx, arg)
}

func (q *querier) DeleteGitSSHKey(ctx context.Context, userID uuid.UUID) error {
return deleteQ(q.log, q.auth, q.db.GetGitSSHKey, q.db.DeleteGitSSHKey)(ctx, userID)
}
Expand DownExpand Up@@ -765,6 +774,10 @@ func (q *querier) DeleteReplicasUpdatedBefore(ctx context.Context, updatedAt tim
return q.db.DeleteReplicasUpdatedBefore(ctx, updatedAt)
}

func (q *querier) DeleteUserLinkByLinkedID(ctx context.Context, linkedID string) error {
return deleteQ(q.log, q.auth, q.db.GetUserLinkByLinkedID, q.db.DeleteUserLinkByLinkedID)(ctx, linkedID)
}

func (q *querier) GetAPIKeyByID(ctx context.Context, id string) (database.APIKey, error) {
return fetch(q.log, q.auth, q.db.GetAPIKeyByID)(ctx, id)
}
Expand Down
196 changes: 196 additions & 0 deletionscoderd/database/dbcrypt/dbcrypt.go
View file
Open in desktop
Original file line numberDiff line numberDiff 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(&params.OAuthAccessToken, &params.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(&params.OAuthAccessToken, &params.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(&params.OAuthAccessToken, &params.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(&params.OAuthAccessToken, &params.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")
Comment on lines +165 to +167
Copy link
Member

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

Copy link
MemberAuthor

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.

Copy link
Member

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

Copy link
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Agreed will add

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.

What about ssh keys that should use encryption at rest ?

Copy link
MemberAuthor

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?

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.

Copy link
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Agreed!

}
}
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
}
Loading

[8]ページ先頭

©2009-2025 Movatter.jp