package store import ( "context" "crypto/ecdh" "crypto/rand" "database/sql" "errors" "fmt" "strings" "sync" "time" ) // KeyScope identifies one encrypted data scope. Tenant scopes hold the SMTP // credentials, person scopes hold e-mail addresses. Editors hold the person // scopes of their tenants; a reader only holds the scope of the person linked // to their account. type KeyScope struct { Type string TenantID string ID string } func (s KeyScope) String() string { return s.Type + "|" + s.TenantID + "|" + s.ID } const ( ScopeTenant = "tenant" ScopePerson = "person" ) // Keyring holds the decrypted private key of one user and the data keys that // were unlocked during this login. It is only kept in memory. type Keyring struct { UserID string privateKey []byte mu sync.RWMutex deks map[string][]byte } func newKeyring(userID string, privateKey []byte) *Keyring { return &Keyring{ UserID: userID, privateKey: privateKey, deks: map[string][]byte{}, } } // DEK returns a cached data key. func (k *Keyring) DEK(scope KeyScope) ([]byte, bool) { k.mu.RLock() defer k.mu.RUnlock() value, ok := k.deks[scope.String()] return value, ok } func (k *Keyring) remember(scope KeyScope, dek []byte) { k.mu.Lock() defer k.mu.Unlock() k.deks[scope.String()] = append([]byte{}, dek...) } type keyringContextKey struct{} // WithKeyring attaches an unlocked keyring to a request context. func WithKeyring(ctx context.Context, keyring *Keyring) context.Context { return context.WithValue(ctx, keyringContextKey{}, keyring) } // KeyringFrom returns the request's keyring, or nil when the session is locked. func KeyringFrom(ctx context.Context) *Keyring { keyring, _ := ctx.Value(keyringContextKey{}).(*Keyring) return keyring } // EnsureUserKeys creates the user's X25519 keypair on first login and returns // an unlocked keyring. The private key is protected by a KEK derived from the // login password. func (s *Store) EnsureUserKeys(ctx context.Context, userID, password string) (*Keyring, error) { var salt, publicKey, wrappedPrivate []byte var version string err := s.db.QueryRowContext(ctx, "SELECT kdf_salt, kdf_version, public_key, wrapped_private FROM user_keys WHERE user_id=?", userID).Scan(&salt, &version, &publicKey, &wrappedPrivate) switch { case errors.Is(err, sql.ErrNoRows): return s.createUserKeys(ctx, userID, password) case err != nil: return nil, err } if version != kdfVersion { return nil, fmt.Errorf("unbekannte Schlüsselversion %q", version) } kek := deriveUserKEK(password, salt) privateKey, err := openAESGCM(kek, wrappedPrivate, keyAAD("user-private", userID)) if err != nil { return nil, errors.New("das Passwort konnte die gespeicherten Schlüssel nicht entsperren") } return newKeyring(userID, privateKey), nil } func (s *Store) createUserKeys(ctx context.Context, userID, password string) (*Keyring, error) { salt, err := newSalt() if err != nil { return nil, err } curve := ecdh.X25519() private, err := curve.GenerateKey(rand.Reader) if err != nil { return nil, err } privateKey := private.Bytes() kek := deriveUserKEK(password, salt) wrapped, err := sealAESGCM(kek, privateKey, keyAAD("user-private", userID)) if err != nil { return nil, err } now := time.Now().UTC().Format(time.RFC3339) _, err = s.db.ExecContext(ctx, ` INSERT INTO user_keys(user_id, kdf_salt, kdf_version, public_key, wrapped_private, created_at, updated_at) VALUES(?, ?, ?, ?, ?, ?, ?) ON CONFLICT(user_id) DO UPDATE SET kdf_salt=excluded.kdf_salt, kdf_version=excluded.kdf_version, public_key=excluded.public_key, wrapped_private=excluded.wrapped_private, updated_at=excluded.updated_at`, userID, salt, kdfVersion, private.PublicKey().Bytes(), wrapped, now, now) if err != nil { return nil, err } return newKeyring(userID, privateKey), nil } // HasUserKeys reports whether an account already has key material. func (s *Store) HasUserKeys(ctx context.Context, userID string) bool { var count int err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM user_keys WHERE user_id=?", userID).Scan(&count) return err == nil && count > 0 } // UnlockAccessibleKeys unwraps every data key that has been granted to this // user. Missing wrappers are skipped; the affected pages report locked data. func (s *Store) UnlockAccessibleKeys(ctx context.Context, keyring *Keyring) error { if keyring == nil { return errKeyLocked } type wrapperRow struct { scope KeyScope ephemeral []byte wrapped []byte } rows, err := s.db.QueryContext(ctx, ` SELECT scope_type, tenant_id, scope_id, ephemeral_public, wrapped_dek FROM key_wrappers WHERE user_id=?`, keyring.UserID) if err != nil { return err } var wrappers []wrapperRow for rows.Next() { var row wrapperRow if err := rows.Scan(&row.scope.Type, &row.scope.TenantID, &row.scope.ID, &row.ephemeral, &row.wrapped); err != nil { rows.Close() return err } wrappers = append(wrappers, row) } if err := rows.Err(); err != nil { rows.Close() return err } rows.Close() for _, row := range wrappers { dek, err := unwrapDEK(keyring.privateKey, row.ephemeral, row.wrapped, row.scope.String()) if err != nil { continue } keyring.remember(row.scope, dek) } return nil } // SecretIsInitialized reports whether a tenant has been migrated to encrypted // secrets. Until then the legacy plaintext columns remain readable. func (s *Store) SecretIsInitialized(ctx context.Context, tenantID string) bool { var count int err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM secret_state WHERE tenant_id=?", tenantID).Scan(&count) return err == nil && count > 0 } // BootstrapTenant encrypts the legacy plaintext values of one tenant and // grants the first key holder access. It is idempotent and also migrates // plaintext that reached the database after the initial migration, for // example demo data restored by a command-line seeding run. func (s *Store) BootstrapTenant(ctx context.Context, keyring *Keyring, tenantID string) error { if s.SecretIsInitialized(ctx, tenantID) { var legacy int if err := s.db.QueryRowContext(ctx, ` SELECT (SELECT COUNT(*) FROM people WHERE tenant_id=? AND email<>'') + (SELECT COUNT(*) FROM tenant_settings WHERE tenant_id=? AND key LIKE 'smtp.%')`, tenantID, tenantID).Scan(&legacy); err != nil { return err } if legacy == 0 { return nil } } tenantScope := KeyScope{Type: ScopeTenant, TenantID: tenantID, ID: tenantID} if _, err := s.ensureScope(ctx, keyring, tenantScope); err != nil { return err } // Prepare every person scope first so the migration transaction only has // to write data. peopleRows, err := s.db.QueryContext(ctx, "SELECT id FROM people WHERE tenant_id=?", tenantID) if err != nil { return err } var peopleIDs []string for peopleRows.Next() { var id string if err := peopleRows.Scan(&id); err != nil { peopleRows.Close() return err } peopleIDs = append(peopleIDs, id) } if err := peopleRows.Err(); err != nil { peopleRows.Close() return err } peopleRows.Close() for _, id := range peopleIDs { scope := KeyScope{Type: ScopePerson, TenantID: tenantID, ID: id} if _, err := s.ensureScope(ctx, keyring, scope); err != nil { return err } } tx, err := s.db.BeginTx(ctx, nil) if err != nil { return err } defer tx.Rollback() settingsRows, err := tx.QueryContext(ctx, "SELECT key, value FROM tenant_settings WHERE tenant_id=? AND key LIKE 'smtp.%'", tenantID) if err != nil { return err } type legacySecret struct { key string value string } var legacy []legacySecret for settingsRows.Next() { var item legacySecret if err := settingsRows.Scan(&item.key, &item.value); err != nil { settingsRows.Close() return err } legacy = append(legacy, item) } if err := settingsRows.Err(); err != nil { settingsRows.Close() return err } settingsRows.Close() tenantDEK, _ := keyring.DEK(tenantScope) for _, item := range legacy { if strings.TrimSpace(item.value) != "" { sealed, err := sealAESGCM(tenantDEK, []byte(item.value), keyAAD(ScopeTenant, tenantID, tenantID, item.key)) if err != nil { return err } if _, err := tx.ExecContext(ctx, ` INSERT INTO secrets(tenant_id, scope_type, scope_id, secret_key, ciphertext, updated_at) VALUES(?, ?, ?, ?, ?, ?) ON CONFLICT(tenant_id, scope_type, scope_id, secret_key) DO NOTHING`, tenantID, ScopeTenant, tenantID, item.key, sealed, time.Now().UTC().Format(time.RFC3339)); err != nil { return err } } if _, err := tx.ExecContext(ctx, "DELETE FROM tenant_settings WHERE tenant_id=? AND key=?", tenantID, item.key); err != nil { return err } } type legacyContact struct { id, email string } contactRows, err := tx.QueryContext(ctx, "SELECT id, email FROM people WHERE tenant_id=? AND email<>''", tenantID) if err != nil { return err } var contacts []legacyContact for contactRows.Next() { var item legacyContact if err := contactRows.Scan(&item.id, &item.email); err != nil { contactRows.Close() return err } contacts = append(contacts, item) } if err := contactRows.Err(); err != nil { contactRows.Close() return err } contactRows.Close() for _, item := range contacts { scope := KeyScope{Type: ScopePerson, TenantID: tenantID, ID: item.id} dek, ok := keyring.DEK(scope) if !ok { continue } if strings.TrimSpace(item.email) == "" { continue } sealed, err := sealAESGCM(dek, []byte(item.email), keyAAD(ScopePerson, tenantID, item.id, "email")) if err != nil { return err } if _, err := tx.ExecContext(ctx, ` INSERT INTO secrets(tenant_id, scope_type, scope_id, secret_key, ciphertext, updated_at) VALUES(?, ?, ?, ?, ?, ?) ON CONFLICT(tenant_id, scope_type, scope_id, secret_key) DO NOTHING`, tenantID, ScopePerson, item.id, "email", sealed, time.Now().UTC().Format(time.RFC3339)); err != nil { return err } if _, err := tx.ExecContext(ctx, "UPDATE people SET email='' WHERE tenant_id=? AND id=?", tenantID, item.id); err != nil { return err } } if _, err := tx.ExecContext(ctx, "INSERT INTO secret_state(tenant_id, initialized_at) VALUES(?, ?) ON CONFLICT(tenant_id) DO NOTHING", tenantID, time.Now().UTC().Format(time.RFC3339)); err != nil { return err } if err := tx.Commit(); err != nil { return err } return s.ReconcileTenant(ctx, keyring, tenantID) } // ReconcileTenant creates missing data scopes and grants them to all eligible // accounts that already have key material. It requires an unlocked key holder // for this tenant. func (s *Store) ReconcileTenant(ctx context.Context, keyring *Keyring, tenantID string) error { if keyring == nil { return errKeyLocked } editors, err := s.tenantKeyRecipients(ctx, tenantID) if err != nil { return err } // Grant what this key holder can reach and report the first inaccessible // scope afterwards. A new editor can then receive the remaining scopes // from another unlocked editor without losing partial access. var firstErr error rememberError := func(err error) { if err != nil && firstErr == nil { firstErr = err } } tenantScope := KeyScope{Type: ScopeTenant, TenantID: tenantID, ID: tenantID} if _, err := s.ensureScope(ctx, keyring, tenantScope); err != nil { rememberError(err) } else if err := s.grantScope(ctx, keyring, tenantScope, editors); err != nil { rememberError(err) } rows, err := s.db.QueryContext(ctx, "SELECT id FROM people WHERE tenant_id=?", tenantID) if err != nil { return err } var peopleIDs []string for rows.Next() { var id string if err := rows.Scan(&id); err != nil { rows.Close() return err } peopleIDs = append(peopleIDs, id) } if err := rows.Err(); err != nil { rows.Close() return err } rows.Close() for _, personID := range peopleIDs { scope := KeyScope{Type: ScopePerson, TenantID: tenantID, ID: personID} if _, err := s.ensureScope(ctx, keyring, scope); err != nil { rememberError(err) continue } recipients := append([]string{}, editors...) if linked := s.linkedReaderForPerson(ctx, tenantID, personID); linked != "" { recipients = append(recipients, linked) } if err := s.grantScope(ctx, keyring, scope, recipients); err != nil { rememberError(err) } } return firstErr } // linkedReaderForPerson returns the active reader account that is linked to // the given person. Only that account may decrypt the person's own e-mail // address; administrators and unlinked readers stay excluded. func (s *Store) linkedReaderForPerson(ctx context.Context, tenantID, personID string) string { var id string err := s.db.QueryRowContext(ctx, ` SELECT id FROM users WHERE active=1 AND role='reader' AND linked_tenant_id=? AND linked_person_id=? ORDER BY id LIMIT 1`, tenantID, personID).Scan(&id) if err != nil { return "" } return id } func (s *Store) tenantKeyRecipients(ctx context.Context, tenantID string) ([]string, error) { rows, err := s.db.QueryContext(ctx, ` SELECT id FROM users WHERE active=1 AND role='editor' AND id IN ( SELECT user_id FROM memberships WHERE tenant_id=? ) ORDER BY id`, tenantID) if err != nil { return nil, err } defer rows.Close() var ids []string for rows.Next() { var id string if err := rows.Scan(&id); err != nil { return nil, err } ids = append(ids, id) } return ids, rows.Err() } // ensureScope returns the DEK for a scope, creating it and wrapping it for the // keyring user when the scope is new. If the scope exists but the user has no // wrapper, errNoKeyAccess is returned. func (s *Store) ensureScope(ctx context.Context, keyring *Keyring, scope KeyScope) ([]byte, error) { if keyring == nil { return nil, errKeyLocked } if dek, ok := keyring.DEK(scope); ok { return dek, nil } dek, err := s.scopeDEK(ctx, keyring, scope) if err == nil { return dek, nil } if !errors.Is(err, errNoKeyAccess) { return nil, err } // A scope exists only when at least one wrapper is present. var count int if err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM key_wrappers WHERE scope_type=? AND tenant_id=? AND scope_id=?", scope.Type, scope.TenantID, scope.ID).Scan(&count); err != nil { return nil, err } if count > 0 { return nil, errNoKeyAccess } // A scope without wrappers but with stored secrets has lost its data key. // Never silently replace it, otherwise the old data would be unreadable. var secrets int if err := s.db.QueryRowContext(ctx, ` SELECT COUNT(*) FROM secrets WHERE tenant_id=? AND scope_type=? AND scope_id=?`, scope.TenantID, scope.Type, scope.ID).Scan(&secrets); err != nil { return nil, err } if secrets > 0 { return nil, errNoKeyAccess } dek, err = newDEK() if err != nil { return nil, err } if err := s.grantScopeDEK(ctx, keyring, scope, dek, []string{keyring.UserID}); err != nil { return nil, err } keyring.remember(scope, dek) return dek, nil } // scopeDEK unwraps the data key for the keyring user. func (s *Store) scopeDEK(ctx context.Context, keyring *Keyring, scope KeyScope) ([]byte, error) { if keyring == nil { return nil, errKeyLocked } if dek, ok := keyring.DEK(scope); ok { return dek, nil } var ephemeral, wrapped []byte err := s.db.QueryRowContext(ctx, ` SELECT ephemeral_public, wrapped_dek FROM key_wrappers WHERE scope_type=? AND tenant_id=? AND scope_id=? AND user_id=?`, scope.Type, scope.TenantID, scope.ID, keyring.UserID).Scan(&ephemeral, &wrapped) if errors.Is(err, sql.ErrNoRows) { return nil, errNoKeyAccess } if err != nil { return nil, err } dek, err := unwrapDEK(keyring.privateKey, ephemeral, wrapped, scope.String()) if err != nil { return nil, err } keyring.remember(scope, dek) return dek, nil } func (s *Store) grantScope(ctx context.Context, keyring *Keyring, scope KeyScope, userIDs []string) error { dek, err := s.ensureScope(ctx, keyring, scope) if err != nil { return err } return s.grantScopeDEK(ctx, keyring, scope, dek, userIDs) } func (s *Store) grantScopeDEK(ctx context.Context, keyring *Keyring, scope KeyScope, dek []byte, userIDs []string) error { seen := map[string]bool{} for _, userID := range userIDs { if userID == "" || seen[userID] { continue } seen[userID] = true publicKey, err := s.userPublicKey(ctx, userID) if err != nil || len(publicKey) == 0 { continue } ephemeral, wrapped, err := wrapDEK(publicKey, dek, scope.String()) if err != nil { return err } if _, err := s.db.ExecContext(ctx, ` INSERT INTO key_wrappers(scope_type, tenant_id, scope_id, user_id, ephemeral_public, wrapped_dek, created_at) VALUES(?, ?, ?, ?, ?, ?, ?) ON CONFLICT(scope_type, tenant_id, scope_id, user_id) DO UPDATE SET ephemeral_public=excluded.ephemeral_public, wrapped_dek=excluded.wrapped_dek, created_at=excluded.created_at`, scope.Type, scope.TenantID, scope.ID, userID, ephemeral, wrapped, time.Now().UTC().Format(time.RFC3339)); err != nil { return err } } return nil } func (s *Store) userPublicKey(ctx context.Context, userID string) ([]byte, error) { var publicKey []byte err := s.db.QueryRowContext(ctx, "SELECT public_key FROM user_keys WHERE user_id=?", userID).Scan(&publicKey) if errors.Is(err, sql.ErrNoRows) { return nil, nil } return publicKey, err } // SecretValue decrypts one stored secret. When the tenant has not been // initialized yet, legacy tenant settings are only readable with an unlocked // editor keyring. func (s *Store) SecretValue(ctx context.Context, tenantID, scopeType, scopeID, key string) (string, bool) { if !s.SecretIsInitialized(ctx, tenantID) { if scopeType == ScopeTenant && KeyringFrom(ctx) != nil { value := s.TenantSetting(ctx, tenantID, key) return value, value != "" } return "", false } keyring := KeyringFrom(ctx) if keyring == nil { return "", false } scope := KeyScope{Type: scopeType, TenantID: tenantID, ID: scopeID} dek, err := s.scopeDEK(ctx, keyring, scope) if err != nil { return "", false } var sealed []byte err = s.db.QueryRowContext(ctx, ` SELECT ciphertext FROM secrets WHERE tenant_id=? AND scope_type=? AND scope_id=? AND secret_key=?`, tenantID, scopeType, scopeID, key).Scan(&sealed) if err != nil { return "", false } plaintext, err := openAESGCM(dek, sealed, keyAAD(scopeType, tenantID, scopeID, key)) if err != nil { return "", false } return string(plaintext), true } // SecretExists reports whether an encrypted value is present. func (s *Store) SecretExists(ctx context.Context, tenantID, scopeType, scopeID, key string) bool { var count int err := s.db.QueryRowContext(ctx, ` SELECT COUNT(*) FROM secrets WHERE tenant_id=? AND scope_type=? AND scope_id=? AND secret_key=?`, tenantID, scopeType, scopeID, key).Scan(&count) return err == nil && count > 0 } // SetSecret encrypts and stores one value. An empty value removes it. Before // a tenant is initialized, legacy tenant settings may only be written with an // unlocked editor keyring present. func (s *Store) SetSecret(ctx context.Context, tenantID, scopeType, scopeID, key, value string) error { if !s.SecretIsInitialized(ctx, tenantID) { if scopeType == ScopeTenant && KeyringFrom(ctx) != nil { return s.SetTenantSetting(ctx, tenantID, key, value) } if scopeType == ScopeTenant { return errKeyLocked } return nil } keyring := KeyringFrom(ctx) if keyring == nil { return errKeyLocked } scope := KeyScope{Type: scopeType, TenantID: tenantID, ID: scopeID} dek, err := s.scopeDEK(ctx, keyring, scope) if err != nil { return err } if strings.TrimSpace(value) == "" { _, err := s.db.ExecContext(ctx, ` DELETE FROM secrets WHERE tenant_id=? AND scope_type=? AND scope_id=? AND secret_key=?`, tenantID, scopeType, scopeID, key) return err } sealed, err := sealAESGCM(dek, []byte(value), keyAAD(scopeType, tenantID, scopeID, key)) if err != nil { return err } _, err = s.db.ExecContext(ctx, ` INSERT INTO secrets(tenant_id, scope_type, scope_id, secret_key, ciphertext, updated_at) VALUES(?, ?, ?, ?, ?, ?) ON CONFLICT(tenant_id, scope_type, scope_id, secret_key) DO UPDATE SET ciphertext=excluded.ciphertext, updated_at=excluded.updated_at`, tenantID, scopeType, scopeID, key, sealed, time.Now().UTC().Format(time.RFC3339)) return err } // EnsurePersonScope creates the person scope if needed and grants it to all // active editors plus the linked reader. It works with an editor keyring and // with a reader keyring that already holds the person's data key; the latter // lets a reader refresh editor access after a new editor was created. func (s *Store) EnsurePersonScope(ctx context.Context, keyring *Keyring, tenantID, personID string) error { if keyring == nil || !s.SecretIsInitialized(ctx, tenantID) { return nil } scope := KeyScope{Type: ScopePerson, TenantID: tenantID, ID: personID} if _, err := s.ensureScope(ctx, keyring, scope); err != nil { return err } recipients, err := s.tenantKeyRecipients(ctx, tenantID) if err != nil { return err } if linked := s.linkedReaderForPerson(ctx, tenantID, personID); linked != "" { recipients = append(recipients, linked) } return s.grantScope(ctx, keyring, scope, recipients) } // PersonContactSecrets loads and decrypts the e-mail address of one person. // Values that exist but cannot be decrypted are reported as locked. func (s *Store) PersonContactSecrets(ctx context.Context, tenantID, personID string) (email string, emailLocked bool) { if !s.SecretIsInitialized(ctx, tenantID) { return "", false } rows, err := s.db.QueryContext(ctx, ` SELECT ciphertext FROM secrets WHERE tenant_id=? AND scope_type=? AND scope_id=? AND secret_key='email'`, tenantID, ScopePerson, personID) if err != nil { return "", false } var sealedValues [][]byte for rows.Next() { var sealed []byte if err := rows.Scan(&sealed); err != nil { rows.Close() return "", false } sealedValues = append(sealedValues, sealed) } rows.Close() keyring := KeyringFrom(ctx) var dek []byte if keyring != nil { dek, _ = s.scopeDEK(ctx, keyring, KeyScope{Type: ScopePerson, TenantID: tenantID, ID: personID}) } for _, sealed := range sealedValues { if dek != nil { plaintext, err := openAESGCM(dek, sealed, keyAAD(ScopePerson, tenantID, personID, "email")) if err == nil { return string(plaintext), false } } emailLocked = true } return "", emailLocked } // DeletePersonSecrets removes all encrypted values and wrappers of a person. func (s *Store) DeletePersonSecrets(ctx context.Context, tenantID, personID string) error { if _, err := s.db.ExecContext(ctx, ` DELETE FROM secrets WHERE tenant_id=? AND scope_type=? AND scope_id=?`, tenantID, ScopePerson, personID); err != nil { return err } _, err := s.db.ExecContext(ctx, ` DELETE FROM key_wrappers WHERE scope_type=? AND tenant_id=? AND scope_id=?`, ScopePerson, tenantID, personID) return err } // ScopesForUser lists the scopes whose DEKs are wrapped for one account. func (s *Store) ScopesForUser(ctx context.Context, userID string) ([]KeyScope, error) { rows, err := s.db.QueryContext(ctx, ` SELECT scope_type, tenant_id, scope_id FROM key_wrappers WHERE user_id=?`, userID) if err != nil { return nil, err } defer rows.Close() var scopes []KeyScope for rows.Next() { var scope KeyScope if err := rows.Scan(&scope.Type, &scope.TenantID, &scope.ID); err != nil { return nil, err } scopes = append(scopes, scope) } return scopes, rows.Err() } // ResetUserKeys replaces an account's keypair, e.g. after an administrator set // a new temporary password. Existing wrappers become invalid and are returned // so an unlocked administrator can grant them again. func (s *Store) ResetUserKeys(ctx context.Context, userID, newPassword string) (*Keyring, []KeyScope, error) { scopes, err := s.ScopesForUser(ctx, userID) if err != nil { return nil, nil, err } if err := s.DeleteUserKeys(ctx, userID); err != nil { return nil, nil, err } keyring, err := s.createUserKeys(ctx, userID, newPassword) if err != nil { return nil, nil, err } return keyring, scopes, nil } // DeleteUserKeys removes the key material and all wrappers of an account. func (s *Store) DeleteUserKeys(ctx context.Context, userID string) error { if _, err := s.db.ExecContext(ctx, "DELETE FROM key_wrappers WHERE user_id=?", userID); err != nil { return err } _, err := s.db.ExecContext(ctx, "DELETE FROM user_keys WHERE user_id=?", userID) return err } // PruneUserWrappers enforces the key access policy. Editors keep the scopes of // their tenant memberships. A reader may hold exactly one wrapper: the person // scope of the account they are linked to. Administrators never hold key // material. func (s *Store) PruneUserWrappers(ctx context.Context, userID string) error { var role, linkedTenantID, linkedPersonID string var active int err := s.db.QueryRowContext(ctx, ` SELECT role, active, linked_tenant_id, linked_person_id FROM users WHERE id=?`, userID). Scan(&role, &active, &linkedTenantID, &linkedPersonID) if errors.Is(err, sql.ErrNoRows) { return nil } if err != nil { return err } userRole := UserRole(role) if userRole == RoleAdmin { if _, err := s.db.ExecContext(ctx, "DELETE FROM key_wrappers WHERE user_id=?", userID); err != nil { return err } _, err := s.db.ExecContext(ctx, "DELETE FROM user_keys WHERE user_id=?", userID) return err } if active == 0 { _, err := s.db.ExecContext(ctx, "DELETE FROM key_wrappers WHERE user_id=?", userID) return err } if userRole == RoleEditor { _, err := s.db.ExecContext(ctx, ` DELETE FROM key_wrappers WHERE user_id=? AND tenant_id NOT IN ( SELECT tenant_id FROM memberships WHERE user_id=? )`, userID, userID) return err } if linkedTenantID == "" || linkedPersonID == "" { _, err := s.db.ExecContext(ctx, "DELETE FROM key_wrappers WHERE user_id=?", userID) return err } _, err = s.db.ExecContext(ctx, ` DELETE FROM key_wrappers WHERE user_id=? AND NOT ( scope_type='person' AND tenant_id=? AND scope_id=? )`, userID, linkedTenantID, linkedPersonID) return err } // HasScopeAccess reports whether a data key for the scope is wrapped for the // account. It is used to decide whether a reader may edit their own contact. func (s *Store) HasScopeAccess(ctx context.Context, userID string, scope KeyScope) bool { var count int err := s.db.QueryRowContext(ctx, ` SELECT COUNT(*) FROM key_wrappers WHERE scope_type=? AND tenant_id=? AND scope_id=? AND user_id=?`, scope.Type, scope.TenantID, scope.ID, userID).Scan(&count) return err == nil && count > 0 } // RewrapScopes grants the given scopes to a user from an unlocked keyring. func (s *Store) RewrapScopes(ctx context.Context, keyring *Keyring, userID string, scopes []KeyScope) (int, error) { if keyring == nil { return 0, errKeyLocked } publicKey, err := s.userPublicKey(ctx, userID) if err != nil || len(publicKey) == 0 { return 0, err } granted := 0 for _, scope := range scopes { dek, err := s.scopeDEK(ctx, keyring, scope) if err != nil { continue } ephemeral, wrapped, err := wrapDEK(publicKey, dek, scope.String()) if err != nil { return granted, err } if _, err := s.db.ExecContext(ctx, ` INSERT INTO key_wrappers(scope_type, tenant_id, scope_id, user_id, ephemeral_public, wrapped_dek, created_at) VALUES(?, ?, ?, ?, ?, ?, ?) ON CONFLICT(scope_type, tenant_id, scope_id, user_id) DO UPDATE SET ephemeral_public=excluded.ephemeral_public, wrapped_dek=excluded.wrapped_dek, created_at=excluded.created_at`, scope.Type, scope.TenantID, scope.ID, userID, ephemeral, wrapped, time.Now().UTC().Format(time.RFC3339)); err != nil { return granted, err } granted++ } return granted, nil } // RekeyUserPassword keeps the same keypair but protects it with a new KEK. func (s *Store) RekeyUserPassword(ctx context.Context, userID, currentPassword, newPassword string) (*Keyring, error) { var salt, publicKey, wrappedPrivate []byte err := s.db.QueryRowContext(ctx, "SELECT kdf_salt, public_key, wrapped_private FROM user_keys WHERE user_id=?", userID). Scan(&salt, &publicKey, &wrappedPrivate) if errors.Is(err, sql.ErrNoRows) { return s.EnsureUserKeys(ctx, userID, newPassword) } if err != nil { return nil, err } privateKey, err := openAESGCM(deriveUserKEK(currentPassword, salt), wrappedPrivate, keyAAD("user-private", userID)) if err != nil { return nil, err } newSalt, err := newSalt() if err != nil { return nil, err } wrapped, err := sealAESGCM(deriveUserKEK(newPassword, newSalt), privateKey, keyAAD("user-private", userID)) if err != nil { return nil, err } if _, err := s.db.ExecContext(ctx, ` UPDATE user_keys SET kdf_salt=?, wrapped_private=?, updated_at=? WHERE user_id=?`, newSalt, wrapped, time.Now().UTC().Format(time.RFC3339), userID); err != nil { return nil, err } return newKeyring(userID, privateKey), nil }