Просмотр исходного кода

fix(api): store API keys as SHA-256 digests

Anyone who could read the database or a backup could reuse the plaintext
tokens stored in api_keys. Existing keys keep working after the
migration, but a token is now shown only once, when the key is created,
and listing keys no longer returns it.
Frédéric Guillot 6 часов назад
Родитель
Сommit
6f9bb6d362
35 измененных файлов с 187 добавлено и 46 удалено
  1. 1 1
      client/model.go
  2. 2 2
      internal/api/api_key_integration_test.go
  3. 6 0
      internal/crypto/crypto.go
  4. 14 0
      internal/database/migrations.go
  5. 1 1
      internal/locale/translations/ar_SA.json
  6. 1 1
      internal/locale/translations/de_DE.json
  7. 1 1
      internal/locale/translations/el_EL.json
  8. 1 1
      internal/locale/translations/en_US.json
  9. 1 1
      internal/locale/translations/es_ES.json
  10. 1 1
      internal/locale/translations/fi_FI.json
  11. 1 1
      internal/locale/translations/fr_FR.json
  12. 1 1
      internal/locale/translations/gl_ES.json
  13. 1 1
      internal/locale/translations/hi_IN.json
  14. 1 1
      internal/locale/translations/id_ID.json
  15. 1 1
      internal/locale/translations/it_IT.json
  16. 1 1
      internal/locale/translations/ja_JP.json
  17. 1 1
      internal/locale/translations/ko_KR.json
  18. 1 1
      internal/locale/translations/nan_Latn_pehoeji.json
  19. 1 1
      internal/locale/translations/nl_NL.json
  20. 1 1
      internal/locale/translations/pl_PL.json
  21. 1 1
      internal/locale/translations/pt_BR.json
  22. 1 1
      internal/locale/translations/ro_RO.json
  23. 1 1
      internal/locale/translations/ru_RU.json
  24. 1 1
      internal/locale/translations/tr_TR.json
  25. 1 1
      internal/locale/translations/uk_UA.json
  26. 1 1
      internal/locale/translations/vi_VN.json
  27. 1 1
      internal/locale/translations/zh_CN.json
  28. 1 1
      internal/locale/translations/zh_TW.json
  29. 1 1
      internal/model/api_key.go
  30. 8 10
      internal/storage/api_key.go
  31. 111 0
      internal/storage/api_key_integration_test.go
  32. 2 2
      internal/storage/user.go
  33. 7 4
      internal/template/templates/views/api_keys.html
  34. 7 0
      internal/ui/api_key_list.go
  35. 4 2
      internal/ui/api_key_save.go

+ 1 - 1
client/model.go

@@ -401,7 +401,7 @@ type VersionResponse struct {
 type APIKey struct {
 	ID          int64      `json:"id"`
 	UserID      int64      `json:"user_id"`
-	Token       string     `json:"token"`
+	Token       string     `json:"token,omitempty"` // Only returned by CreateAPIKey.
 	Description string     `json:"description"`
 	LastUsedAt  *time.Time `json:"last_used_at"`
 	CreatedAt   time.Time  `json:"created_at"`

+ 2 - 2
internal/api/api_key_integration_test.go

@@ -61,8 +61,8 @@ func TestAPIKeysEndpoint(t *testing.T) {
 	if apiKeys[0].UserID != regularTestUser.ID {
 		t.Fatalf(`Invalid user ID for API key, got "%v" instead of "%v"`, apiKeys[0].UserID, regularTestUser.ID)
 	}
-	if apiKeys[0].Token != apiKey.Token {
-		t.Fatalf(`Invalid API key token, got "%v" instead of "%v"`, apiKeys[0].Token, apiKey.Token)
+	if apiKeys[0].Token != "" {
+		t.Fatalf(`Listing API keys should not return their token, got "%v"`, apiKeys[0].Token)
 	}
 	if apiKeys[0].Description != "Test API Key" {
 		t.Fatalf(`Invalid API key description, got "%v" instead of "Test API Key"`, apiKeys[0].Description)

+ 6 - 0
internal/crypto/crypto.go

@@ -28,6 +28,12 @@ func SHA256(value string) string {
 	return hex.EncodeToString(h[:])
 }
 
+// HashToken returns the SHA-256 digest of a random token, to store and look it up without keeping the token itself.
+func HashToken(token string) []byte {
+	digest := sha256.Sum256([]byte(token))
+	return digest[:]
+}
+
 // GenerateRandomBytes returns random bytes.
 func GenerateRandomBytes(size int) []byte {
 	b := make([]byte, size)

+ 14 - 0
internal/database/migrations.go

@@ -1590,4 +1590,18 @@ var migrations = [...]func(tx *sql.Tx) error{
 		_, err = tx.Exec(sql)
 		return err
 	},
+	func(tx *sql.Tx) (err error) {
+		// Keep only the SHA-256 digest of each API key, so a copy of the
+		// database is not enough to call the API. Existing keys keep
+		// working because the server hashes the X-Auth-Token header the
+		// same way before looking it up.
+		_, err = tx.Exec(`
+			ALTER TABLE api_keys ADD COLUMN token_hash bytea;
+			UPDATE api_keys SET token_hash = sha256(convert_to(token, 'UTF8'));
+			ALTER TABLE api_keys ALTER COLUMN token_hash SET NOT NULL;
+			CREATE UNIQUE INDEX api_keys_token_hash_idx ON api_keys (token_hash);
+			ALTER TABLE api_keys DROP COLUMN token;
+		`)
+		return err
+	},
 }

+ 1 - 1
internal/locale/translations/ar_SA.json

@@ -483,8 +483,8 @@
     "page.api_keys.table.created_at": "تاريخ الإنشاء",
     "page.api_keys.table.description": "الوصف",
     "page.api_keys.table.last_used_at": "آخر استخدام",
-    "page.api_keys.table.token": "الرمز",
     "page.api_keys.title": "مفاتيح API",
+    "page.api_keys.token_shown_once": "انسخ مفتاح API هذا الآن. لأسباب أمنية، لن يتم عرضه مرة أخرى.",
     "page.authentication.title": "المصادقة",
     "page.categories.entries": "المقالات",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/de_DE.json

@@ -471,8 +471,8 @@
     "page.api_keys.table.created_at": "Erstellungsdatum",
     "page.api_keys.table.description": "Beschreibung",
     "page.api_keys.table.last_used_at": "Zuletzt verwendeten",
-    "page.api_keys.table.token": "Zeichen",
     "page.api_keys.title": "API-Schlüssel",
+    "page.api_keys.token_shown_once": "Kopieren Sie diesen API-Schlüssel jetzt. Aus Sicherheitsgründen wird er nicht erneut angezeigt.",
     "page.authentication.title": "Authentifizierung",
     "page.categories.entries": "Artikel",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/el_EL.json

@@ -471,8 +471,8 @@
     "page.api_keys.table.created_at": "Ημερομηνία Δημιουργίας",
     "page.api_keys.table.description": "Περιγραφή",
     "page.api_keys.table.last_used_at": "Τελευταία Χρήση",
-    "page.api_keys.table.token": "Διακριτικό",
     "page.api_keys.title": "Κλειδιά API",
+    "page.api_keys.token_shown_once": "Αντιγράψτε αυτό το κλειδί API τώρα. Για λόγους ασφαλείας, δεν θα εμφανιστεί ξανά.",
     "page.authentication.title": "Έλεγχος ταυτότητας",
     "page.categories.entries": "Άρθρα",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/en_US.json

@@ -471,8 +471,8 @@
     "page.api_keys.table.created_at": "Creation Date",
     "page.api_keys.table.description": "Description",
     "page.api_keys.table.last_used_at": "Last Used",
-    "page.api_keys.table.token": "Token",
     "page.api_keys.title": "API Keys",
+    "page.api_keys.token_shown_once": "Copy this API key now. For security reasons, it will not be shown again.",
     "page.authentication.title": "Authentication",
     "page.categories.entries": "Entries",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/es_ES.json

@@ -471,8 +471,8 @@
     "page.api_keys.table.created_at": "Fecha de creación",
     "page.api_keys.table.description": "Descripción",
     "page.api_keys.table.last_used_at": "Último utilizado",
-    "page.api_keys.table.token": "simbólico",
     "page.api_keys.title": "Claves API",
+    "page.api_keys.token_shown_once": "Copie esta clave API ahora. Por motivos de seguridad, no se volverá a mostrar.",
     "page.authentication.title": "Autenticación",
     "page.categories.entries": "Artículos",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/fi_FI.json

@@ -471,8 +471,8 @@
     "page.api_keys.table.created_at": "Luomispäivä",
     "page.api_keys.table.description": "Kuvaus",
     "page.api_keys.table.last_used_at": "Viimeksi käytetty",
-    "page.api_keys.table.token": "Tunnus",
     "page.api_keys.title": "API-avaimet",
+    "page.api_keys.token_shown_once": "Kopioi tämä API-avain nyt. Turvallisuussyistä sitä ei näytetä uudelleen.",
     "page.authentication.title": "Todennus",
     "page.categories.entries": "Artikkelit",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/fr_FR.json

@@ -471,8 +471,8 @@
     "page.api_keys.table.created_at": "Date de création",
     "page.api_keys.table.description": "Description",
     "page.api_keys.table.last_used_at": "Dernière utilisation",
-    "page.api_keys.table.token": "Jeton",
     "page.api_keys.title": "Clés d'API",
+    "page.api_keys.token_shown_once": "Copiez cette clé d'API maintenant. Pour des raisons de sécurité, elle ne sera plus affichée.",
     "page.authentication.title": "Authentification",
     "page.categories.entries": "Articles",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/gl_ES.json

@@ -471,8 +471,8 @@
     "page.api_keys.table.created_at": "Data de creación",
     "page.api_keys.table.description": "Descrición",
     "page.api_keys.table.last_used_at": "Último uso",
-    "page.api_keys.table.token": "Token",
     "page.api_keys.title": "Claves da API",
+    "page.api_keys.token_shown_once": "Copia esta clave da API agora. Por motivos de seguridade, non se volverá mostrar.",
     "page.authentication.title": "Autenticación",
     "page.categories.entries": "Entradas",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/hi_IN.json

@@ -471,8 +471,8 @@
     "page.api_keys.table.created_at": "निर्माण तिथि",
     "page.api_keys.table.description": "विवरण",
     "page.api_keys.table.last_used_at": "आखरी इस्त्तमाल किया गया",
-    "page.api_keys.table.token": "टोकन",
     "page.api_keys.title": "एपीआई कुंजी",
+    "page.api_keys.token_shown_once": "इस एपीआई कुंजी को अभी कॉपी करें। सुरक्षा कारणों से, इसे दोबारा नहीं दिखाया जाएगा।",
     "page.authentication.title": "प्रमाणीकरण",
     "page.categories.entries": "विषयवस्तुया",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/id_ID.json

@@ -468,8 +468,8 @@
     "page.api_keys.table.created_at": "Tanggal Pembuatan",
     "page.api_keys.table.description": "Deskripsi",
     "page.api_keys.table.last_used_at": "Terakhir Digunakan",
-    "page.api_keys.table.token": "Token",
     "page.api_keys.title": "Kunci API",
+    "page.api_keys.token_shown_once": "Salin kunci API ini sekarang. Demi alasan keamanan, kunci ini tidak akan ditampilkan lagi.",
     "page.authentication.title": "Autentikasi",
     "page.categories.entries": "Artikel",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/it_IT.json

@@ -471,8 +471,8 @@
     "page.api_keys.table.created_at": "Data di creazione",
     "page.api_keys.table.description": "Descrizione",
     "page.api_keys.table.last_used_at": "Ultimo uso",
-    "page.api_keys.table.token": "Gettone",
     "page.api_keys.title": "Chiavi API",
+    "page.api_keys.token_shown_once": "Copia questa chiave API ora. Per motivi di sicurezza, non verrà più mostrata.",
     "page.authentication.title": "Autenticazione",
     "page.categories.entries": "Articoli",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/ja_JP.json

@@ -468,8 +468,8 @@
     "page.api_keys.table.created_at": "作成日",
     "page.api_keys.table.description": "説明",
     "page.api_keys.table.last_used_at": "最終使用",
-    "page.api_keys.table.token": "トークン",
     "page.api_keys.title": "API キー",
+    "page.api_keys.token_shown_once": "この API キーを今すぐコピーしてください。セキュリティ上の理由から、再度表示されることはありません。",
     "page.authentication.title": "認証",
     "page.categories.entries": "記事一覧",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/ko_KR.json

@@ -468,8 +468,8 @@
     "page.api_keys.table.created_at": "생성일",
     "page.api_keys.table.description": "설명",
     "page.api_keys.table.last_used_at": "마지막 사용",
-    "page.api_keys.table.token": "토큰",
     "page.api_keys.title": "API 키",
+    "page.api_keys.token_shown_once": "지금 이 API 키를 복사하세요. 보안상의 이유로 다시 표시되지 않습니다.",
     "page.authentication.title": "인증",
     "page.categories.entries": "게시물 목록",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/nan_Latn_pehoeji.json

@@ -468,8 +468,8 @@
     "page.api_keys.table.created_at": "Kiàn-tì li̍t-kî",
     "page.api_keys.table.description": "Biâu-su̍t",
     "page.api_keys.table.last_used_at": "Siōng-bóe pái sú-iōng",
-    "page.api_keys.table.token": "Só-sî",
     "page.api_keys.title": "API só-sî",
+    "page.api_keys.token_shown_once": "Chhiáⁿ chit-má khó-pih chit ê API só-sî. Ūi-tio̍h an-choân, i bē koh hián-sī.",
     "page.authentication.title": "Giām-chèng",
     "page.categories.entries": "Siau-sit",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/nl_NL.json

@@ -471,8 +471,8 @@
     "page.api_keys.table.created_at": "Aanmaakdatum",
     "page.api_keys.table.description": "Omschrijving",
     "page.api_keys.table.last_used_at": "Laatst gebruikt",
-    "page.api_keys.table.token": "API-token",
     "page.api_keys.title": "API-sleutels",
+    "page.api_keys.token_shown_once": "Kopieer deze API-sleutel nu. Om veiligheidsredenen wordt hij niet opnieuw getoond.",
     "page.authentication.title": "Authenticatie",
     "page.categories.entries": "Artikelen",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/pl_PL.json

@@ -474,8 +474,8 @@
     "page.api_keys.table.created_at": "Data utworzenia",
     "page.api_keys.table.description": "Opis",
     "page.api_keys.table.last_used_at": "Ostatnio używane",
-    "page.api_keys.table.token": "Token",
     "page.api_keys.title": "Klucze API",
+    "page.api_keys.token_shown_once": "Skopiuj teraz ten klucz API. Ze względów bezpieczeństwa nie zostanie on ponownie wyświetlony.",
     "page.authentication.title": "Uwierzytelnianie",
     "page.categories.entries": "Wpisy",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/pt_BR.json

@@ -471,8 +471,8 @@
     "page.api_keys.table.created_at": "Data de criação",
     "page.api_keys.table.description": "Descrição",
     "page.api_keys.table.last_used_at": "Ultima utilização",
-    "page.api_keys.table.token": "Token",
     "page.api_keys.title": "Chaves de API",
+    "page.api_keys.token_shown_once": "Copie esta chave de API agora. Por motivos de segurança, ela não será exibida novamente.",
     "page.authentication.title": "Autenticação",
     "page.categories.entries": "Itens",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/ro_RO.json

@@ -474,8 +474,8 @@
     "page.api_keys.table.created_at": "Dată Creare",
     "page.api_keys.table.description": "Descriere",
     "page.api_keys.table.last_used_at": "Utilizat ultima dată",
-    "page.api_keys.table.token": "Token",
     "page.api_keys.title": "Chei API",
+    "page.api_keys.token_shown_once": "Copiați această cheie API acum. Din motive de securitate, nu va mai fi afișată.",
     "page.authentication.title": "Autentificare",
     "page.categories.entries": "Intrări",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/ru_RU.json

@@ -474,8 +474,8 @@
     "page.api_keys.table.created_at": "Дата создания",
     "page.api_keys.table.description": "Описание",
     "page.api_keys.table.last_used_at": "Последнее использование",
-    "page.api_keys.table.token": "Токен",
     "page.api_keys.title": "API-ключи",
+    "page.api_keys.token_shown_once": "Скопируйте этот API-ключ сейчас. В целях безопасности он больше не будет показан.",
     "page.authentication.title": "Аутентификация",
     "page.categories.entries": "Статьи",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/tr_TR.json

@@ -471,8 +471,8 @@
     "page.api_keys.table.created_at": "Oluşturulma Tarihi",
     "page.api_keys.table.description": "Açıklama",
     "page.api_keys.table.last_used_at": "Son Kullanılma",
-    "page.api_keys.table.token": "Token",
     "page.api_keys.title": "API Anahtarları",
+    "page.api_keys.token_shown_once": "Bu API anahtarını şimdi kopyalayın. Güvenlik nedeniyle tekrar gösterilmeyecektir.",
     "page.authentication.title": "Kimlik Doğrulama",
     "page.categories.entries": "Makaleler",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/uk_UA.json

@@ -474,8 +474,8 @@
     "page.api_keys.table.created_at": "Дата створення",
     "page.api_keys.table.description": "Опис",
     "page.api_keys.table.last_used_at": "Дата останнього використання",
-    "page.api_keys.table.token": "Токен",
     "page.api_keys.title": "Ключі API",
+    "page.api_keys.token_shown_once": "Скопіюйте цей ключ API зараз. З міркувань безпеки його більше не буде показано.",
     "page.authentication.title": "Автентифікація",
     "page.categories.entries": "Статті",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/vi_VN.json

@@ -468,8 +468,8 @@
     "page.api_keys.table.created_at": "Ngày tạo",
     "page.api_keys.table.description": "Mô tả",
     "page.api_keys.table.last_used_at": "Lần dùng cuối",
-    "page.api_keys.table.token": "Token",
     "page.api_keys.title": "Khóa API",
+    "page.api_keys.token_shown_once": "Hãy sao chép khóa API này ngay bây giờ. Vì lý do bảo mật, khóa sẽ không được hiển thị lại.",
     "page.authentication.title": "Xác thực",
     "page.categories.entries": "Bài viết",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/zh_CN.json

@@ -468,8 +468,8 @@
     "page.api_keys.table.created_at": "创建日期",
     "page.api_keys.table.description": "描述",
     "page.api_keys.table.last_used_at": "最后使用",
-    "page.api_keys.table.token": "令牌",
     "page.api_keys.title": "API 密钥",
+    "page.api_keys.token_shown_once": "请立即复制此 API 密钥。出于安全原因,它将不会再次显示。",
     "page.authentication.title": "认证",
     "page.categories.entries": "条目",
     "page.categories.feed_count": [

+ 1 - 1
internal/locale/translations/zh_TW.json

@@ -468,8 +468,8 @@
     "page.api_keys.table.created_at": "建立日期",
     "page.api_keys.table.description": "描述",
     "page.api_keys.table.last_used_at": "最後使用",
-    "page.api_keys.table.token": "金鑰",
     "page.api_keys.title": "API 金鑰",
+    "page.api_keys.token_shown_once": "請立即複製此 API 金鑰。基於安全考量,它將不會再次顯示。",
     "page.authentication.title": "認證",
     "page.categories.entries": "檢視內容",
     "page.categories.feed_count": [

+ 1 - 1
internal/model/api_key.go

@@ -13,7 +13,7 @@ import (
 type APIKey struct {
 	ID          int64      `json:"id"`
 	UserID      int64      `json:"user_id"`
-	Token       string     `json:"token"`
+	Token       string     `json:"token,omitempty"` // Only set by CreateAPIKey: the database keeps a SHA-256 digest.
 	Description string     `json:"description"`
 	LastUsedAt  *time.Time `json:"last_used_at"`
 	CreatedAt   time.Time  `json:"created_at"`

+ 8 - 10
internal/storage/api_key.go

@@ -23,8 +23,8 @@ func (s *Storage) APIKeyExists(userID int64, description string) bool {
 
 // SetAPIKeyUsedTimestamp updates the last used date of an API Key.
 func (s *Storage) SetAPIKeyUsedTimestamp(userID int64, token string) error {
-	query := `UPDATE api_keys SET last_used_at=now() WHERE user_id=$1 and token=$2`
-	_, err := s.db.Exec(query, userID, token)
+	query := `UPDATE api_keys SET last_used_at=now() WHERE user_id=$1 and token_hash=$2`
+	_, err := s.db.Exec(query, userID, crypto.HashToken(token))
 	if err != nil {
 		return fmt.Errorf(`store: unable to update last used date for API key: %v`, err)
 	}
@@ -36,7 +36,7 @@ func (s *Storage) SetAPIKeyUsedTimestamp(userID int64, token string) error {
 func (s *Storage) APIKeys(userID int64) (model.APIKeys, error) {
 	query := `
 		SELECT
-			id, user_id, token, description, last_used_at, created_at
+			id, user_id, description, last_used_at, created_at
 		FROM
 			api_keys
 		WHERE
@@ -55,7 +55,6 @@ func (s *Storage) APIKeys(userID int64) (model.APIKeys, error) {
 		if err := rows.Scan(
 			&apiKey.ID,
 			&apiKey.UserID,
-			&apiKey.Token,
 			&apiKey.Description,
 			&apiKey.LastUsedAt,
 			&apiKey.CreatedAt,
@@ -69,26 +68,25 @@ func (s *Storage) APIKeys(userID int64) (model.APIKeys, error) {
 	return apiKeys, nil
 }
 
-// CreateAPIKey inserts a new API key.
+// CreateAPIKey inserts a new API key and returns it with its token, which is not stored and cannot be read again.
 func (s *Storage) CreateAPIKey(userID int64, description string) (*model.APIKey, error) {
 	query := `
 		INSERT INTO api_keys
-			(user_id, token, description)
+			(user_id, token_hash, description)
 		VALUES
 			($1, $2, $3)
 		RETURNING
-			id, user_id, token, description, last_used_at, created_at
+			id, user_id, description, last_used_at, created_at
 	`
-	var apiKey model.APIKey
+	apiKey := model.APIKey{Token: crypto.GenerateRandomStringHex(32)}
 	err := s.db.QueryRow(
 		query,
 		userID,
-		crypto.GenerateRandomStringHex(32),
+		crypto.HashToken(apiKey.Token),
 		description,
 	).Scan(
 		&apiKey.ID,
 		&apiKey.UserID,
-		&apiKey.Token,
 		&apiKey.Description,
 		&apiKey.LastUsedAt,
 		&apiKey.CreatedAt,

+ 111 - 0
internal/storage/api_key_integration_test.go

@@ -0,0 +1,111 @@
+// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package storage
+
+import (
+	"bytes"
+	"database/sql"
+	"encoding/hex"
+	"strings"
+	"testing"
+
+	"miniflux.app/v2/internal/crypto"
+)
+
+func TestCreateAPIKeyStoresOnlyTheTokenHash(t *testing.T) {
+	db := openTestDatabase(t)
+	store := NewStorage(db)
+	userID := createAPIKeyTestUser(t, db)
+
+	apiKey, err := store.CreateAPIKey(userID, "Test")
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(apiKey.Token) != 64 {
+		t.Fatalf(`Expected a 64-character token, got %q`, apiKey.Token)
+	}
+
+	var storedRow string
+	var storedHash []byte
+	if err := db.QueryRow(`SELECT row_to_json(api_keys)::text, token_hash FROM api_keys WHERE id=$1`, apiKey.ID).Scan(&storedRow, &storedHash); err != nil {
+		t.Fatal(err)
+	}
+	if strings.Contains(storedRow, apiKey.Token) {
+		t.Errorf(`The api_keys row contains the plaintext token: %s`, storedRow)
+	}
+	if !bytes.Equal(storedHash, crypto.HashToken(apiKey.Token)) {
+		t.Errorf(`Expected the SHA-256 digest of the token to be stored`)
+	}
+
+	user, err := store.UserByAPIKey(apiKey.Token)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if user == nil || user.ID != userID {
+		t.Fatalf(`Expected the token to authenticate user %d, got %+v`, userID, user)
+	}
+
+	// The stored digest must not be usable as an API key.
+	if user, err := store.UserByAPIKey(hex.EncodeToString(storedHash)); err != nil || user != nil {
+		t.Errorf(`Expected no user for the stored digest, got %+v (error: %v)`, user, err)
+	}
+
+	apiKeys, err := store.APIKeys(userID)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(apiKeys) != 1 || apiKeys[0].Token != "" {
+		t.Errorf(`Expected one API key without its token, got %+v`, apiKeys)
+	}
+}
+
+func TestUserByAPIKeyFindsKeysHashedByTheMigration(t *testing.T) {
+	db := openTestDatabase(t)
+	store := NewStorage(db)
+	userID := createAPIKeyTestUser(t, db)
+
+	// The migration hashes existing tokens in SQL; the digest must match the one computed in Go.
+	legacyToken := crypto.GenerateRandomStringHex(32)
+	if _, err := db.Exec(
+		`INSERT INTO api_keys (user_id, token_hash, description) VALUES ($1, sha256(convert_to($2, 'UTF8')), 'Legacy')`,
+		userID, legacyToken,
+	); err != nil {
+		t.Fatal(err)
+	}
+
+	user, err := store.UserByAPIKey(legacyToken)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if user == nil || user.ID != userID {
+		t.Fatalf(`Expected the migrated token to authenticate user %d, got %+v`, userID, user)
+	}
+
+	if err := store.SetAPIKeyUsedTimestamp(userID, legacyToken); err != nil {
+		t.Fatal(err)
+	}
+	var lastUsedAtIsSet bool
+	if err := db.QueryRow(`SELECT last_used_at IS NOT NULL FROM api_keys WHERE user_id=$1`, userID).Scan(&lastUsedAtIsSet); err != nil {
+		t.Fatal(err)
+	}
+	if !lastUsedAtIsSet {
+		t.Errorf(`Expected SetAPIKeyUsedTimestamp to update last_used_at`)
+	}
+}
+
+func createAPIKeyTestUser(t *testing.T, db *sql.DB) int64 {
+	t.Helper()
+
+	var userID int64
+	username := "api_key_test_user_" + crypto.GenerateRandomStringHex(10)
+	if err := db.QueryRow(`INSERT INTO users (username) VALUES ($1) RETURNING id`, username).Scan(&userID); err != nil {
+		t.Fatal(err)
+	}
+	t.Cleanup(func() {
+		if _, err := db.Exec(`DELETE FROM users WHERE id=$1`, userID); err != nil {
+			t.Errorf(`Unable to remove user %d: %v`, userID, err)
+		}
+	})
+	return userID
+}

+ 2 - 2
internal/storage/user.go

@@ -518,9 +518,9 @@ func (s *Storage) UserByAPIKey(token string) (*model.User, error) {
 		INNER JOIN
 			api_keys ON api_keys.user_id=u.id
 		WHERE
-			api_keys.token = $1
+			api_keys.token_hash = $1
 	`
-	return s.fetchUser(query, token)
+	return s.fetchUser(query, crypto.HashToken(token))
 }
 
 func (s *Storage) fetchUser(query string, args ...any) (*model.User, error) {

+ 7 - 4
internal/template/templates/views/api_keys.html

@@ -8,6 +8,13 @@
 {{ end }}
 
 {{ define "content"}}
+{{ if .createdAPIKey }}
+<div role="alert" class="alert alert-success">
+    <p>{{ t "page.api_keys.token_shown_once" }}</p>
+    <p><strong>{{ .createdAPIKey.Description }}</strong> = <code>{{ .createdAPIKey.Token }}</code></p>
+</div>
+{{ end }}
+
 {{ if .apiKeys }}
 {{ range .apiKeys }}
     <table>
@@ -15,10 +22,6 @@
         <th class="column-25">{{ t "page.api_keys.table.description" }}</th>
         <td>{{ .Description }}</td>
     </tr>
-    <tr>
-        <th>{{ t "page.api_keys.table.token" }}</th>
-        <td>{{ .Token }}</td>
-    </tr>
     <tr>
         <th>{{ t "page.api_keys.table.last_used_at" }}</th>
         <td>

+ 7 - 0
internal/ui/api_key_list.go

@@ -8,6 +8,7 @@ import (
 
 	"miniflux.app/v2/internal/http/request"
 	"miniflux.app/v2/internal/http/response"
+	"miniflux.app/v2/internal/model"
 	"miniflux.app/v2/internal/ui/view"
 )
 
@@ -18,6 +19,11 @@ func (h *handler) showAPIKeysPage(w http.ResponseWriter, r *http.Request) {
 		return
 	}
 
+	h.renderAPIKeysPage(w, r, user, nil)
+}
+
+// renderAPIKeysPage lists the user's API keys, with the token of createdAPIKey when it was just created.
+func (h *handler) renderAPIKeysPage(w http.ResponseWriter, r *http.Request, user *model.User, createdAPIKey *model.APIKey) {
 	apiKeys, err := h.store.APIKeys(user.ID)
 	if err != nil {
 		response.HTMLServerError(w, r, err)
@@ -26,6 +32,7 @@ func (h *handler) showAPIKeysPage(w http.ResponseWriter, r *http.Request) {
 
 	view := view.New(h.tpl, r)
 	view.Set("apiKeys", apiKeys)
+	view.Set("createdAPIKey", createdAPIKey)
 	view.Set("menu", "settings")
 	view.Set("user", user)
 	navMetadata, _ := h.store.GetNavMetadata(user.ID)

+ 4 - 2
internal/ui/api_key_save.go

@@ -39,10 +39,12 @@ func (h *handler) saveAPIKey(w http.ResponseWriter, r *http.Request) {
 		return
 	}
 
-	if _, err = h.store.CreateAPIKey(user.ID, apiKeyCreationRequest.Description); err != nil {
+	apiKey, err := h.store.CreateAPIKey(user.ID, apiKeyCreationRequest.Description)
+	if err != nil {
 		response.HTMLServerError(w, r, err)
 		return
 	}
 
-	response.HTMLRedirect(w, r, h.routePath("/keys"))
+	// Render the token in this response rather than redirecting: only its hash is stored, so it cannot be shown later.
+	h.renderAPIKeysPage(w, r, user, apiKey)
 }