From 13c1260f3be5fb03d379dbd131236918ab199a66 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:08:14 -0600 Subject: [PATCH 1/4] feat(rbac): store API keys as hashes API keys were stored, held in memory and sent between nodes as the keys themselves, so anyone who could read parseable.json could use every key. Keep the SHA-256 of each key and its last four characters instead. Keys are generated by the server from 122 random bits, so an unsalted fast hash is enough, and it is computed once per request. The key is returned by the request that creates it and cannot be read back: GET /api/prism/v1/apikeys/{id} now returns it masked, as the list does. Validation and request authentication compare hashes. Records stored with the key are still read, and are written back hashed: for the default tenant by the write every query or standalone node makes at start, for other tenants by a write added to the tenant loader. Existing keys keep working. Older versions cannot read the hashed records, so this is a one-way change. Co-Authored-By: Claude Fable 5.2 --- frontend/src/features/team/ApiKeysTab.test.ts | 93 ------- src/handlers/http/apikeys.rs | 91 +++++-- src/handlers/http/middleware.rs | 4 +- src/parseable/mod.rs | 20 ++ src/rbac/user.rs | 246 +++++++++++++++++- 5 files changed, 330 insertions(+), 124 deletions(-) delete mode 100644 frontend/src/features/team/ApiKeysTab.test.ts diff --git a/frontend/src/features/team/ApiKeysTab.test.ts b/frontend/src/features/team/ApiKeysTab.test.ts deleted file mode 100644 index bfc858ce2..000000000 --- a/frontend/src/features/team/ApiKeysTab.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest'; -import type { ApiKey } from '../../lib/types'; -import { copyApiKey } from './ApiKeysTab'; - -afterEach(() => vi.unstubAllGlobals()); - -const key: ApiKey = { - keyId: 'key-id', - keyName: 'automation', - apiKey: 'full-test-key', - roles: ['analysts'], - createdBy: 'admin', - createdAt: '2026-10-08T12:00:00Z', - modifiedAt: '2026-10-08T12:00:00Z', -}; - -class TestClipboardItem { - constructor(readonly data: Record>) {} -} - -describe('API key clipboard', () => { - it('starts writing synchronously before the key fetch resolves', async () => { - vi.stubGlobal('ClipboardItem', TestClipboardItem); - const write = vi.fn().mockResolvedValue(undefined); - vi.stubGlobal('navigator', { clipboard: { write } }); - let resolveKey!: (value: ApiKey) => void; - const fetching = new Promise((resolve) => { - resolveKey = resolve; - }); - - const copying = copyApiKey(fetching, { current: true }); - expect(write).toHaveBeenCalledTimes(1); - const [item] = write.mock.calls[0][0] as TestClipboardItem[]; - resolveKey(key); - const blob = await item.data['text/plain']; - expect(blob.type).toBe('text/plain'); - expect(await blob.text()).toBe(key.apiKey); - await copying; - }); - - it('falls back to writeText when ClipboardItem is unavailable', async () => { - vi.stubGlobal('ClipboardItem', undefined); - const writeText = vi.fn().mockResolvedValue(undefined); - vi.stubGlobal('navigator', { clipboard: { writeText } }); - - await copyApiKey(Promise.resolve(key), { current: true }); - expect(writeText).toHaveBeenCalledWith(key.apiKey); - }); - - it.each([true, false])( - 'shows a clear clipboard failure (ClipboardItem: %s)', - async (available) => { - vi.stubGlobal('ClipboardItem', available ? TestClipboardItem : undefined); - const failure = new DOMException('The request is not allowed.', 'NotAllowedError'); - const write = vi.fn().mockRejectedValue(failure); - vi.stubGlobal('navigator', { clipboard: { write, writeText: write } }); - - await expect(copyApiKey(Promise.resolve(key), { current: true })).rejects.toThrow( - 'Unable to copy API key. Check your browser clipboard permissions and try again.', - ); - }, - ); - - it.each([true, false])( - 'preserves the original key-fetch error (ClipboardItem: %s)', - async (available) => { - vi.stubGlobal('ClipboardItem', available ? TestClipboardItem : undefined); - const failure = new Error('Permission denied'); - const write = vi.fn(async ([item]: TestClipboardItem[]) => { - await item.data['text/plain'].catch(() => { - throw new DOMException('Could not read clipboard data.', 'NotAllowedError'); - }); - }); - const writeText = vi.fn(); - vi.stubGlobal('navigator', { clipboard: { write, writeText } }); - - await expect(copyApiKey(Promise.reject(failure), { current: true })).rejects.toBe(failure); - expect(writeText).not.toHaveBeenCalled(); - }, - ); - - it('does not write the fetched key after unmount in the fallback path', async () => { - vi.stubGlobal('ClipboardItem', undefined); - const writeText = vi.fn(); - vi.stubGlobal('navigator', { clipboard: { writeText } }); - const active = { current: true }; - const copying = copyApiKey(Promise.resolve(key), active); - active.current = false; - - await copying; - expect(writeText).not.toHaveBeenCalled(); - }); -}); diff --git a/src/handlers/http/apikeys.rs b/src/handlers/http/apikeys.rs index 003bcfec7..be4055938 100644 --- a/src/handlers/http/apikeys.rs +++ b/src/handlers/http/apikeys.rs @@ -16,7 +16,7 @@ use crate::{ Users, map::{read_user_groups, roles, users}, role::model::{DefaultPrivilege, Role, RoleType}, - user::{User, UserType}, + user::{User, UserType, hash_api_key}, }, utils::{get_user_and_tenant_from_request, is_admin}, }; @@ -41,12 +41,14 @@ fn generate_api_key_value() -> String { uuid::Uuid::new_v4().to_string() } -/// Serialisable shape returned by create / get. +/// Serialisable shape returned by create and get. `api_key` is the key itself +/// only in the response to create, the one time the server has it; get returns it +/// masked, as list does. #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct ApiKeyResponse<'a> { key_id: Ulid, - api_key: &'a str, + api_key: String, key_name: &'a str, roles: &'a HashSet, created_by: &'a str, @@ -55,16 +57,25 @@ struct ApiKeyResponse<'a> { expires_at: Option>, } -impl<'a> TryFrom<&'a User> for ApiKeyResponse<'a> { - type Error = ApiKeyError; +impl<'a> ApiKeyResponse<'a> { + /// The response to creating `user` with the key `created_key`, which is + /// returned this once + fn created(user: &'a User, created_key: String) -> Result { + Self::new(user, Some(created_key)) + } - fn try_from(user: &'a User) -> Result { + /// The details of `user`, with its key masked + fn masked(user: &'a User) -> Result { + Self::new(user, None) + } + + fn new(user: &'a User, created_key: Option) -> Result { let api_key = user .as_api_key() .ok_or_else(|| ApiKeyError::KeyNotFound(user.userid().to_string()))?; Ok(Self { key_id: api_key.key_id, - api_key: &api_key.api_key, + api_key: created_key.unwrap_or_else(|| api_key.masked_key()), key_name: &api_key.key_name, roles: &user.roles, created_by: &api_key.created_by, @@ -203,15 +214,9 @@ fn tenant_entries( impl ApiKeyListEntry { fn from_user(user: &User) -> Option { let api_key = user.as_api_key()?; - let masked = if api_key.api_key.len() >= 4 { - let last4 = &api_key.api_key[api_key.api_key.len() - 4..]; - format!("****{last4}") - } else { - "****".to_string() - }; Some(Self { key_id: api_key.key_id, - api_key: masked, + api_key: api_key.masked_key(), key_name: api_key.key_name.clone(), roles: user.roles.clone(), created_by: api_key.created_by.clone(), @@ -305,10 +310,11 @@ pub async fn create_api_key( } let key_id = Ulid::new(); + // The key is kept only until the response is written: the user holds its hash let api_key_value = generate_api_key_value(); let mut user = User::new_api_key( key_id, - api_key_value, + api_key_value.clone(), body.key_name, body.roles, created_by, @@ -351,7 +357,7 @@ pub async fn create_api_key( tracing::error!("Failed to sync API-key user creation: {e}"); } - let response = ApiKeyResponse::try_from(&user)?; + let response = ApiKeyResponse::created(&user, api_key_value)?; Ok(HttpResponse::Ok().json(response)) } @@ -442,17 +448,20 @@ pub async fn validate_api_key( let (_, tenant_id) = get_user_and_tenant_from_request(&req) .map_err(|_| ApiKeyError::Unauthorized("Missing user identity".into()))?; let now = Utc::now(); + let hash = hash_api_key(&body.api_key); let valid = collect_tenant_api_keys(&tenant_id) .iter() .filter_map(|u| u.as_api_key()) - .any(|k| k.matches_active_key(&body.api_key, now)); + .any(|k| k.matches_active_hash(&hash, now)); Ok(HttpResponse::Ok().json(ValidateApiKeyResponse { valid })) } /// GET /api/prism/v1/apikeys/{key_id} /// -/// Get a specific API key (full key visible). Only admins can get keys. +/// Get a specific API key. Only admins can get keys. The key itself is not +/// kept, so `apiKey` is masked here as it is in the list: the key is returned +/// once, by the request that creates it. pub async fn get_api_key( req: HttpRequest, path: web::Path, @@ -467,7 +476,7 @@ pub async fn get_api_key( .find(|u| u.as_api_key().map(|k| k.key_id == key_id).unwrap_or(false)) .ok_or_else(|| ApiKeyError::KeyNotFound(key_id.to_string()))?; - let response = ApiKeyResponse::try_from(&user)?; + let response = ApiKeyResponse::masked(&user)?; Ok(HttpResponse::Ok().json(response)) } @@ -508,12 +517,50 @@ mod tests { }; key.expires_at = Some(expiry); assert!(!key.matches_active_key("test-secret", expiry)); - let detail = serde_json::to_value(ApiKeyResponse::try_from(&user).unwrap()).unwrap(); + let detail = serde_json::to_value(ApiKeyResponse::masked(&user).unwrap()).unwrap(); let entry = serde_json::to_value(ApiKeyListEntry::from_user(&user).unwrap()).unwrap(); assert_eq!(detail["expiresAt"], serde_json::to_value(expiry).unwrap()); assert_eq!(entry["expiresAt"], detail["expiresAt"]); assert_eq!(entry["apiKey"], "****cret"); - assert_eq!(detail["apiKey"], "test-secret"); + assert_eq!(detail["apiKey"], "****cret"); + } + + /// The key is in the response to create and nowhere after it: get and list + /// return the mask, and neither they nor the stored user hold the key or + /// its hash where a response could show it. + #[test] + fn key_is_returned_by_create_only() { + let key = generate_api_key_value(); + let user = User::new_api_key( + Ulid::new(), + key.clone(), + "test".into(), + HashSet::new(), + "admin".into(), + None, + ); + let created = + serde_json::to_value(ApiKeyResponse::created(&user, key.clone()).unwrap()).unwrap(); + assert_eq!(created["apiKey"], key.as_str()); + + let masked = format!("****{}", &key[key.len() - 4..]); + let detail = serde_json::to_string(&ApiKeyResponse::masked(&user).unwrap()).unwrap(); + let entry = serde_json::to_string(&ApiKeyListEntry::from_user(&user).unwrap()).unwrap(); + let hash = hash_api_key(&key); + for response in [&detail, &entry] { + let value: serde_json::Value = serde_json::from_str(response).unwrap(); + assert_eq!(value["apiKey"], masked.as_str()); + assert!(!response.contains(&key), "{response}"); + assert!(!response.contains(&hash), "{response}"); + assert!(value.get("keyHash").is_none(), "{response}"); + } + // The same fields as the response to create, so clients read both alike + let detail: serde_json::Value = serde_json::from_str(&detail).unwrap(); + assert_eq!( + detail.as_object().unwrap().keys().collect::>(), + created.as_object().unwrap().keys().collect::>() + ); + assert!(!serde_json::to_string(&user).unwrap().contains(&key)); } #[test] @@ -526,7 +573,7 @@ mod tests { "admin".into(), None, ); - let detail = serde_json::to_value(ApiKeyResponse::try_from(&user).unwrap()).unwrap(); + let detail = serde_json::to_value(ApiKeyResponse::masked(&user).unwrap()).unwrap(); let entry = serde_json::to_value(ApiKeyListEntry::from_user(&user).unwrap()).unwrap(); assert!(detail.get("expiresAt").unwrap().is_null()); assert!(entry.get("expiresAt").unwrap().is_null()); diff --git a/src/handlers/http/middleware.rs b/src/handlers/http/middleware.rs index 9f5ce104a..3562496a7 100644 --- a/src/handlers/http/middleware.rs +++ b/src/handlers/http/middleware.rs @@ -502,9 +502,11 @@ fn find_api_key_user(api_key_value: &str, tenant_id: &Option) -> Option< let users_guard = users(); let tenant_users = users_guard.get(tenant)?; let now = Utc::now(); + // Stored keys are hashes: hash the presented one once for the whole scan + let hash = user::hash_api_key(api_key_value); tenant_users.values().find_map(|user| { if let UserType::ApiKey(api_key) = &user.ty - && api_key.matches_active_key(api_key_value, now) + && api_key.matches_active_hash(&hash, now) { Some(user.clone()) } else { diff --git a/src/parseable/mod.rs b/src/parseable/mod.rs index a757afc99..05d5332b4 100644 --- a/src/parseable/mod.rs +++ b/src/parseable/mod.rs @@ -1296,6 +1296,26 @@ impl Parseable { validate_tenant_id(&tenant_id).map_err(|e| anyhow::anyhow!(e))?; let metadata: StorageMetadata = serde_json::from_slice(&meta)?; + // An API key stored before keys were hashed was hashed by reading + // it. Write the metadata back so that the key itself leaves + // storage now, not at the tenant's next change. The nodes that + // write the default tenant's metadata at every start (see + // `resolve_parseable_metadata`) do this for theirs; the key keeps + // working either way, so a failure here only delays it. + if matches!(self.options.mode, Mode::All | Mode::Query) + && crate::rbac::user::stores_unhashed_api_key(&meta) + && let Err(error) = self + .metastore + .put_parseable_metadata(&metadata, &Some(tenant_id.clone())) + .await + { + tracing::warn!( + %tenant_id, + %error, + "Could not rewrite tenant metadata with its API keys hashed" + ); + } + TENANT_METADATA.insert_tenant(tenant_id.clone(), metadata.clone()); recognized_tenants.push(tenant_id); } else if !is_multi_tenant { diff --git a/src/rbac/user.rs b/src/rbac/user.rs index 495958231..8dbe4dd33 100644 --- a/src/rbac/user.rs +++ b/src/rbac/user.rs @@ -99,8 +99,8 @@ impl UpdateUser { pub enum UserType { // Order matters for `#[serde(untagged)]`: the most specific variant must // come first so it wins deserialization when its distinctive fields are - // present. `ApiKey` carries `api_key`/`key_id` which neither `Native` nor - // `OAuth` have. + // present. `ApiKey` carries `key_id` and `key_hash` (`api_key` in records + // written before keys were hashed) which neither `Native` nor `OAuth` have. ApiKey(Box), OAuth(Box), Native(Basic), @@ -137,6 +137,9 @@ impl User { ) } + /// A user for the API key `api_key`. Only the hash of the key and its + /// last characters are kept, so the caller must hand the key to its owner + /// now: it cannot be read back. pub fn new_api_key( key_id: Ulid, api_key: String, @@ -150,7 +153,8 @@ impl User { ty: UserType::ApiKey(Box::new(ApiKeyUser { userid: key_id.to_string(), key_id, - api_key, + key_hash: hash_api_key(&api_key), + key_hint: api_key_hint(&api_key), key_name, created_by, created_at: now, @@ -353,12 +357,22 @@ pub fn get_super_admin_user() -> User { /// `User::userid()` can return `&str` alongside the Native/OAuth variants). /// Permissions for this user are derived from the `roles` set on the parent /// `User`, exactly like native and OAuth users. +/// +/// The key itself is not kept. It is shown once, when it is created; what is +/// stored, held in memory and sent to the other nodes is `key_hash`, so reading +/// the metadata does not give anyone a credential. Records written before keys +/// were hashed hold the key as `apiKey`: they are read (`StoredApiKeyUser`), and +/// written back hashed the next time the metadata is written. #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] +#[serde(rename_all = "camelCase", try_from = "StoredApiKeyUser")] pub struct ApiKeyUser { pub userid: String, pub key_id: Ulid, - pub api_key: String, + /// SHA-256 of the key, in lowercase hex, see `hash_api_key` + pub key_hash: String, + /// The last characters of the key, for listings (`****abcd`), see + /// `api_key_hint` + pub key_hint: String, pub key_name: String, pub created_by: String, pub created_at: DateTime, @@ -374,7 +388,18 @@ impl ApiKeyUser { } pub fn matches_active_key(&self, value: &str, now: DateTime) -> bool { - self.api_key == value && !self.is_expired_at(now) + self.matches_active_hash(&hash_api_key(value), now) + } + + /// As `matches_active_key`, for a key already hashed with `hash_api_key`: + /// callers that compare one key with many users hash it once. + pub fn matches_active_hash(&self, hash: &str, now: DateTime) -> bool { + hashes_equal(&self.key_hash, hash) && !self.is_expired_at(now) + } + + /// The key as listings show it: its last characters after a mask + pub fn masked_key(&self) -> String { + format!("****{}", self.key_hint) } /// Ephemeral sessions never outlive the credential that created them. @@ -388,6 +413,97 @@ impl ApiKeyUser { } } +/// What is stored of an API key: its SHA-256 in lowercase hex. +/// +/// Keys are generated by the server from 122 random bits, so a plain fast hash +/// is enough: there is no small set of likely keys to try, which is what the +/// salt and the cost of a password hash defend against, and the hash is computed +/// for every request the key authenticates. +pub fn hash_api_key(key: &str) -> String { + use sha2::{Digest, Sha256}; + hex::encode(Sha256::digest(key.as_bytes())) +} + +/// The last four characters of a key, kept so that listings can tell keys apart. +/// Empty for a key under eight characters, of which it would give away half or +/// more (generated keys have 36). +pub fn api_key_hint(key: &str) -> String { + let chars = key.chars().count(); + if chars < 8 { + return String::new(); + } + key.chars().skip(chars - 4).collect() +} + +/// Whether two hashes are the same, in time that does not depend on where they +/// differ +fn hashes_equal(a: &str, b: &str) -> bool { + a.len() == b.len() + && a.bytes() + .zip(b.bytes()) + .fold(0u8, |differing, (a, b)| differing | (a ^ b)) + == 0 +} + +/// Whether `metadata`, the stored JSON of a tenant's metadata, holds an API key +/// written before keys were hashed. Reading it hashes the key, so writing the +/// metadata back removes the key from storage. +pub fn stores_unhashed_api_key(metadata: &[u8]) -> bool { + serde_json::from_slice::(metadata).is_ok_and(|metadata| { + metadata["users"].as_array().is_some_and(|users| { + users + .iter() + .any(|user| user.get("keyId").is_some() && user.get("apiKey").is_some()) + }) + }) +} + +/// An API key user as stored: with `keyHash` and `keyHint`, or, in records +/// written before keys were hashed, with the key itself as `apiKey`. +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase")] +struct StoredApiKeyUser { + userid: String, + key_id: Ulid, + #[serde(default)] + api_key: Option, + #[serde(default)] + key_hash: Option, + #[serde(default)] + key_hint: Option, + key_name: String, + created_by: String, + created_at: DateTime, + modified_at: DateTime, + #[serde(default)] + expires_at: Option>, +} + +impl TryFrom for ApiKeyUser { + type Error = &'static str; + + fn try_from(stored: StoredApiKeyUser) -> Result { + // A record that has a hash is never rehashed from `apiKey`: the hash is + // what authenticated since it was written. + let (key_hash, key_hint) = match (stored.key_hash, stored.api_key) { + (Some(hash), _) => (hash, stored.key_hint.unwrap_or_default()), + (None, Some(key)) => (hash_api_key(&key), api_key_hint(&key)), + (None, None) => return Err("an API key user needs keyHash"), + }; + Ok(Self { + userid: stored.userid, + key_id: stored.key_id, + key_hash, + key_hint, + key_name: stored.key_name, + created_by: stored.created_by, + created_at: stored.created_at, + modified_at: stored.modified_at, + expires_at: stored.expires_at, + }) + } +} + #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct OAuth { pub userid: String, @@ -943,10 +1059,14 @@ mod apikey_serde_tests { assert_eq!(user.userid(), key_id.to_string()); let json = serde_json::to_string(&user).expect("serialize User(ApiKey)"); + // The key is not in what is stored and sent to other nodes: its hash is + assert!(!json.contains("secret-token"), "json = {json}"); + assert!(!json.contains("\"apiKey\""), "json = {json}"); assert!( - json.contains("\"apiKey\":\"secret-token\""), + json.contains(&format!("\"keyHash\":\"{}\"", hash_api_key("secret-token"))), "json = {json}" ); + assert!(json.contains("\"keyHint\":\"oken\""), "json = {json}"); assert!(json.contains("\"roles\""), "json = {json}"); assert!(json.contains("\"userid\""), "json = {json}"); @@ -957,7 +1077,117 @@ mod apikey_serde_tests { let ak = back.as_api_key().expect("ApiKey variant"); assert_eq!(ak.key_id, key_id); assert_eq!(ak.userid, key_id.to_string()); - assert_eq!(ak.api_key, "secret-token"); + assert_eq!(ak, user.as_api_key().unwrap()); + let now = Utc::now(); + assert!(ak.matches_active_key("secret-token", now)); + assert!(!ak.matches_active_key("secret-toke", now)); + assert!(!ak.matches_active_key("", now)); + // What is stored is not itself a key + assert!(!ak.matches_active_key(&ak.key_hash, now)); + assert_eq!(ak.masked_key(), "****oken"); + } + + #[test] + fn api_key_hash_is_sha256_in_lowercase_hex() { + // FIPS 180-2 test vector + assert_eq!( + hash_api_key("abc"), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + assert_eq!(hash_api_key("").len(), 64); + } + + #[test] + fn hint_is_the_last_four_characters_of_a_long_enough_key() { + assert_eq!(api_key_hint("550e8400-e29b-41d4-a716-446655440000"), "0000"); + assert_eq!(api_key_hint("12345678"), "5678"); + // Not half or more of a short key, and never cut inside a character + assert_eq!(api_key_hint("1234567"), ""); + assert_eq!(api_key_hint(""), ""); + assert_eq!(api_key_hint("ключ-ключ"), "ключ"); + } + + /// A record written before keys were hashed, exactly as it was stored + fn unhashed_record(key: &str) -> serde_json::Value { + serde_json::json!({ + "userid": "01KPWAKVAQVXJGTKRKZCSVVCDF", + "keyId": "01KPWAKVAQVXJGTKRKZCSVVCDF", + "apiKey": key, + "keyName": "diag-test-key", + "createdBy": "admin", + "createdAt": "2026-01-01T12:00:00Z", + "modifiedAt": "2026-01-01T12:00:00Z", + "expiresAt": null, + "roles": ["admin"], + "user_groups": [], + "tenant": null, + "protected": false + }) + } + + #[test] + fn record_stored_with_the_key_is_read_and_written_back_hashed() { + let key = "550e8400-e29b-41d4-a716-446655440000"; + let user: User = serde_json::from_value(unhashed_record(key)).unwrap(); + let api_key = user.as_api_key().expect("ApiKey variant"); + assert_eq!(api_key.key_hash, hash_api_key(key)); + assert_eq!(api_key.key_hint, "0000"); + assert_eq!(api_key.key_name, "diag-test-key"); + // The key keeps working + assert!(api_key.matches_active_key(key, Utc::now())); + + let written = serde_json::to_string(&user).unwrap(); + assert!(!written.contains(key), "{written}"); + assert!(!written.contains("apiKey"), "{written}"); + let back: User = serde_json::from_str(&written).unwrap(); + assert_eq!(back, user); + } + + #[test] + fn stored_hash_wins_over_a_key_stored_beside_it() { + let mut record = unhashed_record("the-key-in-the-record"); + record["keyHash"] = hash_api_key("the-key-that-was-hashed").into(); + record["keyHint"] = "shed".into(); + let user: User = serde_json::from_value(record).unwrap(); + let api_key = user.as_api_key().unwrap(); + let now = Utc::now(); + assert!(api_key.matches_active_key("the-key-that-was-hashed", now)); + assert!(!api_key.matches_active_key("the-key-in-the-record", now)); + assert_eq!(api_key.key_hint, "shed"); + } + + #[test] + fn api_key_record_without_hash_or_key_is_rejected() { + let mut record = unhashed_record("unused"); + record.as_object_mut().unwrap().remove("apiKey"); + assert!(serde_json::from_value::(record.clone()).is_err()); + // A hash without a hint is enough: the listing shows the mask alone + record["keyHash"] = hash_api_key("some-key").into(); + let user: User = serde_json::from_value(record).unwrap(); + assert_eq!(user.as_api_key().unwrap().masked_key(), "****"); + } + + #[test] + fn unhashed_keys_are_found_in_stored_metadata() { + let metadata = |users: serde_json::Value| { + serde_json::to_vec(&serde_json::json!({ "version": "v7", "users": users })).unwrap() + }; + let unhashed = unhashed_record("550e8400-e29b-41d4-a716-446655440000"); + let hashed = + serde_json::to_value(serde_json::from_value::(unhashed.clone()).unwrap()) + .unwrap(); + let (native, _) = User::new_basic("alice".into(), None, false); + let native = serde_json::to_value(native).unwrap(); + + assert!(stores_unhashed_api_key(&metadata(serde_json::json!([ + native, hashed, unhashed + ])))); + assert!(!stores_unhashed_api_key(&metadata(serde_json::json!([ + native, hashed + ])))); + assert!(!stores_unhashed_api_key(&metadata(serde_json::json!([])))); + assert!(!stores_unhashed_api_key(b"not json")); + assert!(!stores_unhashed_api_key(b"{}")); } #[test] From 852376ae034499cc28a5b1dd20ba2d1ffc795191 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:08:14 -0600 Subject: [PATCH 2/4] feat(frontend): show an API key only when it is created The server no longer keeps API keys, so the key list cannot copy one later. Remove the copy action and the client call behind it, and say on the creation sheet that the key is shown this once. Co-Authored-By: Claude Fable 5.2 --- frontend/docs/api-contracts.md | 5 +- frontend/docs/prism-parity.md | 2 +- frontend/e2e/api-key-expiration.spec.ts | 7 +-- frontend/e2e/team.spec.ts | 11 ++-- frontend/src/features/team/ApiKeysTab.tsx | 65 +---------------------- frontend/src/features/team/shared.tsx | 2 +- frontend/src/features/team/team.css | 7 --- frontend/src/lib/client.ts | 6 --- frontend/src/lib/demo.ts | 4 -- frontend/src/lib/demoTeam.test.ts | 4 +- frontend/src/lib/teamClient.test.ts | 7 --- frontend/src/lib/types.ts | 1 - 12 files changed, 15 insertions(+), 106 deletions(-) diff --git a/frontend/docs/api-contracts.md b/frontend/docs/api-contracts.md index e7f3438c6..c6d351d75 100644 --- a/frontend/docs/api-contracts.md +++ b/frontend/docs/api-contracts.md @@ -45,10 +45,11 @@ Team requests share the cookie session and `credentials: 'include'`. The adminis | `setDefaultRole(name)` | `PUT /api/v1/role/default` | JSON string body; empty success | | `clearDefaultRole()` | `DELETE /api/v1/role/default` | Empty success | | `listApiKeys(signal?)` | `GET /api/prism/v1/apikeys` | Array of `{keyId, apiKey, keyName, roles, createdBy, createdAt, modifiedAt, expiresAt}`; `apiKey` is masked as `****` plus the last four characters | -| `createApiKey(name, roles, ttlSeconds?)` | `POST /api/prism/v1/apikeys` | Body `{keyName, roles, ttlSeconds?}`; returns the same shape with the full generated key | -| `getApiKey(id, signal?)` | `GET /api/prism/v1/apikeys/{encoded id}` | Full key, retrieved only on an explicit copy action | +| `createApiKey(name, roles, ttlSeconds?)` | `POST /api/prism/v1/apikeys` | Body `{keyName, roles, ttlSeconds?}`; returns the same shape with the full generated key, the only time it is returned | | `deleteApiKey(id)` | `DELETE /api/prism/v1/apikeys/{encoded id}` | Checked success; backend returns `{keyId, keyName, message}` | +The server keeps only a hash of each API key, so a key cannot be read back after the response that creates it. `GET /api/prism/v1/apikeys/{id}` returns the same masked `apiKey` as the list, and the client does not call it. + API key listing accepts `?privilege=reader|ingestor|admin|writer|editor|superadmin` (alias `priviledge`), matching direct or group-inherited role privileges by kind (an admin key does not match `reader`, and a super-admin key does not match `admin`). Each entry's `roles` lists direct roles only. Unknown or differently cased values, or a repeated parameter, return 400; unknown parameter names are ignored and leave the list unfiltered. API key expiry is optional: `ttlSeconds` must be an integer from 1800 (30 minutes) through 7776000 (90 days), inclusive; invalid values return 400. Omitted or null TTL means no expiration. Responses include `expiresAt`, a UTC timestamp or null; the frontend also accepts an omitted field from older servers for legacy records. Finite lifetimes are elapsed durations from creation, independent of time zones or daylight saving changes. The creation form defaults to 90 days and offers presets, custom minutes/hours/days, and No expiration. TTL cannot be edited after creation. Expired keys remain listed and deletable; their names remain reserved until deletion. diff --git a/frontend/docs/prism-parity.md b/frontend/docs/prism-parity.md index 6976de5e7..17f8ff9d7 100644 --- a/frontend/docs/prism-parity.md +++ b/frontend/docs/prism-parity.md @@ -68,7 +68,7 @@ Original authenticated shell geometry was relayed to the implementation owners i ## Final implemented scope and remaining visual differences -Team administration is implemented at `/team` with Prism-compatible `roles`, `user`, `groups` and `apikeys` query tabs. Admin navigation replaces the classic-only Users and Roles links. Native users, one-time passwords, role creation and full-array privilege edits, typed deletion, OIDC defaults, group mappings and safe role inspection, and API-key creation/copy/deletion use this checkout's backend contracts. Each tab has search and 25-row pagination; users support name/email/method sorting. The community OIDC explanations and status sentences are preserved, including provider-only removal protection, legacy provenance, manual overlaps and sign-in/session refresh wording. +Team administration is implemented at `/team` with Prism-compatible `roles`, `user`, `groups` and `apikeys` query tabs. Admin navigation replaces the classic-only Users and Roles links. Native users, one-time passwords, role creation and full-array privilege edits, typed deletion, OIDC defaults, group mappings and safe role inspection, and API-key creation (the key is shown once, with a copy action)/deletion use this checkout's backend contracts. Each tab has search and 25-row pagination; users support name/email/method sorting. The community OIDC explanations and status sentences are preserved, including provider-only removal protection, legacy provenance, manual overlaps and sign-in/session refresh wording. Alerts is native under Observe, after Metrics; the Classic UI sidebar group is removed. `/alerts`, `/alerts/new`, `/alerts/:id`, `/alerts/:id/edit` and `/alerts/targets` cover list/search/tags/sort/pagination, PromQL and SQL thresholds, non-notifying previews, runtime instances/delivery failures, hold duration, optional targets, evaluate/enable/mute/duplicate/delete and target management. Fork behavior survives: explicit `promqlAlerts` capability, independent per-series state, transition-based notifications, three delivery attempts, state-only rules and dashboard handoff URL fields. Frequency uses the server's minute units rather than classic's inconsistent day options. diff --git a/frontend/e2e/api-key-expiration.spec.ts b/frontend/e2e/api-key-expiration.spec.ts index 5bc8c7673..defd44ec6 100644 --- a/frontend/e2e/api-key-expiration.spec.ts +++ b/frontend/e2e/api-key-expiration.spec.ts @@ -174,16 +174,13 @@ test('expiration updates at the deadline, disables copying and preserves deletio ]); const soon = row(page, 'soon'); await expect(soon.getByText('Expired', { exact: true })).toHaveCount(0); - await expect(soon.getByRole('button', { name: 'Copy API key for soon' })).toBeEnabled(); await page.clock.fastForward(30_000); await expect(soon.getByText('Expired', { exact: true })).toBeVisible(); - await expect(soon.getByRole('button', { name: 'Copy API key for soon' })).toBeDisabled(); for (const name of ['legacy', 'forever']) { await expect(row(page, name)).toContainText('No expiration'); - await expect( - row(page, name).getByRole('button', { name: `Copy API key for ${name}` }), - ).toBeEnabled(); } + // The key is shown once, when it is created: no row offers to copy it + await expect(page.getByRole('button', { name: /^Copy API key/ })).toHaveCount(0); await soon.getByRole('button', { name: 'Delete API key soon' }).click(); const dialog = page.getByRole('dialog', { name: 'Delete API key', exact: true }); await dialog.getByLabel('Confirmation name').fill('soon'); diff --git a/frontend/e2e/team.spec.ts b/frontend/e2e/team.spec.ts index 0c4306328..1b55709c7 100644 --- a/frontend/e2e/team.spec.ts +++ b/frontend/e2e/team.spec.ts @@ -386,7 +386,7 @@ test('OIDC groups map exact role names and have a search empty state', async ({ await expect(page.getByRole('button', { name: /Add (group|role)/ })).toHaveCount(0); }); -test('API keys are created once, copied through GET, masked in the table and deleted by name', async ({ +test('API keys are shown once at creation, masked in the table and deleted by name', async ({ page, context, }) => { @@ -401,7 +401,9 @@ test('API keys are created once, copied through GET, masked in the table and del const key = await sheet.getByLabel('API key', { exact: true }).inputValue(); expect(key).toBeTruthy(); await expect( - sheet.getByText('Store this key securely. Admins can copy it again from the API keys list.'), + sheet.getByText( + 'This is the only time you can see this key. Store it securely; if it is lost, delete it and create another.', + ), ).toBeVisible(); await sheet.getByRole('button', { name: 'Copy API key', exact: true }).click(); await expect(sheet.getByRole('status')).toHaveText('API key copied to clipboard'); @@ -413,9 +415,8 @@ test('API keys are created once, copied through GET, masked in the table and del const row = namedRow(page, 'automation-key'); await expect(row).toContainText(`****${key.slice(-4)}`); await expect(page.getByText(key, { exact: true })).toHaveCount(0); - await row.getByRole('button', { name: 'Copy API key for automation-key' }).click(); - await expect(row.getByRole('status')).toHaveText('API key copied to clipboard'); - expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(key); + // The key cannot be read back: the list has no copy action + await expect(row.getByRole('button', { name: /^Copy API key/ })).toHaveCount(0); await row.getByRole('button', { name: 'Delete API key automation-key' }).click(); const remove = page.getByRole('dialog', { name: 'Delete API key', exact: true }); await expect(remove.locator('[data-dialog-confirm]')).toBeDisabled(); diff --git a/frontend/src/features/team/ApiKeysTab.tsx b/frontend/src/features/team/ApiKeysTab.tsx index 4476ddaf0..160dd4403 100644 --- a/frontend/src/features/team/ApiKeysTab.tsx +++ b/frontend/src/features/team/ApiKeysTab.tsx @@ -1,5 +1,4 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; -import { Copy } from 'lucide-react'; +import { useCallback, useEffect, useState } from 'react'; import { Badge, Button, @@ -7,7 +6,6 @@ import { EmptyState, Pagination, TypedConfirmDialog, - InlineError, } from '../../components/ui'; import { QueryState } from '../../components/explorer/QueryState'; import { useApp } from '../../app/AppProvider'; @@ -18,63 +16,6 @@ import { useCollection } from '../../hooks/useCollection'; import { useMutation } from '../../hooks/useMutation'; import { isApiKeyExpired } from './apiKeyExpiration'; -export async function copyApiKey(key: Promise, active: { current: boolean }) { - try { - if (typeof ClipboardItem !== 'undefined') { - await navigator.clipboard.write([ - new ClipboardItem({ - 'text/plain': key.then((result) => new Blob([result.apiKey], { type: 'text/plain' })), - }), - ]); - } else { - const result = await key; - if (!active.current) return; - await navigator.clipboard.writeText(result.apiKey); - } - } catch { - // Preserve fetch errors before translating a clipboard failure. - await key; - throw new Error( - 'Unable to copy API key. Check your browser clipboard permissions and try again.', - ); - } -} - -function CopyKey({ apiKey, expired }: { apiKey: ApiKey; expired: boolean }) { - const { client } = useApp(); - const [status, setStatus] = useState(''); - const mutation = useMutation(); - const active = useRef(true); - useEffect(() => { - active.current = true; - return () => { - active.current = false; - }; - }, []); - function copy() { - setStatus(''); - void mutation.run(async () => { - await copyApiKey(client.getApiKey(apiKey.keyId), active); - if (active.current) setStatus('API key copied to clipboard'); - }); - } - return ( -
- - - {status} -
- ); -} - function DeleteKey({ apiKey, onClose, @@ -203,10 +144,6 @@ export function ApiKeysTab({
-
diff --git a/frontend/src/features/team/team.css b/frontend/src/features/team/team.css index 01f3d7c0d..3b92ea2c9 100644 --- a/frontend/src/features/team/team.css +++ b/frontend/src/features/team/team.css @@ -101,13 +101,6 @@ color: var(--color-muted); overflow-wrap: anywhere; } -.team-copy { - display: flex; - flex-direction: column; -} -.team-copy [role='status'] { - font-size: 11px; -} .team-empty { padding: 20px; color: var(--color-muted); diff --git a/frontend/src/lib/client.ts b/frontend/src/lib/client.ts index 79944f5a1..99a1a4f90 100644 --- a/frontend/src/lib/client.ts +++ b/frontend/src/lib/client.ts @@ -457,12 +457,6 @@ export function createClient({ if (!apiKey(data)) return malformed(keys); return data; }, - async getApiKey(id, signal) { - const endpoint = `${keys}/${encodeURIComponent(id)}`; - const data = await readJson(endpoint, { signal }, onUnauthorized); - if (!apiKey(data)) return malformed(endpoint); - return data; - }, deleteApiKey: (id) => mutate(`${keys}/${encodeURIComponent(id)}`, { method: 'DELETE' }), createDataset: (name, options) => { const headers: Record = { 'X-P-Telemetry-Type': options.telemetryType }; diff --git a/frontend/src/lib/demo.ts b/frontend/src/lib/demo.ts index a73bc34e3..04e357223 100644 --- a/frontend/src/lib/demo.ts +++ b/frontend/src/lib/demo.ts @@ -717,10 +717,6 @@ export function createDemoClient(): ParseableClient { keys.push(key); return clone(key); }, - async getApiKey(id, signal) { - await ready(signal); - return clone(findKey(id)); - }, async deleteApiKey(id) { await ready(); const key = findKey(id); diff --git a/frontend/src/lib/demoTeam.test.ts b/frontend/src/lib/demoTeam.test.ts index 5bdb0165e..c87151027 100644 --- a/frontend/src/lib/demoTeam.test.ts +++ b/frontend/src/lib/demoTeam.test.ts @@ -189,7 +189,6 @@ describe('per-client Team demo', () => { const client = createDemoClient(); const key = await client.createApiKey('test-key', ['editors']); expect(key.keyId).toMatch(/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/); - expect((await client.getApiKey(key.keyId)).apiKey).toBe(key.apiKey); expect((await client.listApiKeys()).find((item) => item.keyId === key.keyId)?.apiKey).toBe( `****${key.apiKey.slice(-4)}`, ); @@ -198,7 +197,7 @@ describe('per-client Team demo', () => { 'Roles do not exist', ); await client.deleteApiKey(key.keyId); - await expect(client.getApiKey(key.keyId)).rejects.toMatchObject({ status: 404 }); + await expect(client.deleteApiKey(key.keyId)).rejects.toMatchObject({ status: 404 }); expect(await client.listApiKeys()).toHaveLength(2); }); it.each([1800, 7776000])( @@ -208,7 +207,6 @@ describe('per-client Team demo', () => { const users = await client.listUsers(); const key = await client.createApiKey('finite-key', ['analysts'], ttlSeconds); expect(Date.parse(key.expiresAt!) - Date.parse(key.createdAt)).toBe(ttlSeconds * 1000); - expect((await client.getApiKey(key.keyId)).expiresAt).toBe(key.expiresAt); expect((await client.listApiKeys()).find((item) => item.keyId === key.keyId)?.expiresAt).toBe( key.expiresAt, ); diff --git a/frontend/src/lib/teamClient.test.ts b/frontend/src/lib/teamClient.test.ts index 89004efc8..c87a6b4b9 100644 --- a/frontend/src/lib/teamClient.test.ts +++ b/frontend/src/lib/teamClient.test.ts @@ -150,12 +150,6 @@ const cases: Case[] = [ body: { keyName: 'ingestion', roles: ['analysts'], ttlSeconds: 7776000 }, reply: { ...key, expiresAt: '2027-01-06T12:00:00Z' }, }, - { - name: 'get API key', - run: (c, s) => c.getApiKey('key/id', s), - url: '/api/prism/v1/apikeys/key%2Fid', - reply: { ...key, apiKey: 'full-test-key' }, - }, { name: 'delete API key', run: (c) => c.deleteApiKey('key/id'), @@ -347,7 +341,6 @@ describe('Team HTTP contracts', () => { { run: (c) => c.defaultRole(), reply: { role: 'analysts' } }, { run: (c) => c.listApiKeys(), reply: [{ ...key, roles: 'analysts' }] }, { run: (c) => c.createApiKey('key', []), reply: { ...key, createdAt: 'invalid' } }, - { run: (c) => c.getApiKey('key'), reply: { keyId: 'key' } }, ...[42, 'invalid', '', '2026-10-08', '2026-10-08T12:00:00+02:00'].map((expiresAt) => ({ run: (c: ParseableClient) => c.listApiKeys(), reply: [{ ...key, expiresAt }], diff --git a/frontend/src/lib/types.ts b/frontend/src/lib/types.ts index fb55fb0e6..329a57eef 100644 --- a/frontend/src/lib/types.ts +++ b/frontend/src/lib/types.ts @@ -496,6 +496,5 @@ export interface ParseableClient { clearDefaultRole(): Promise; listApiKeys(signal?: AbortSignal): Promise; createApiKey(name: string, roles: string[], ttlSeconds?: number | null): Promise; - getApiKey(id: string, signal?: AbortSignal): Promise; deleteApiKey(id: string): Promise; } From 2e1133bebcfea8010abb83100f10475eed2710f1 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:41:18 -0600 Subject: [PATCH 3/4] fix(rbac): hash keys in the tenant staging copy too, and flag a malformed stored hash Review follow-ups to storing API keys as hashes. - The rewrite of a tenant's metadata in the tenant loader updated storage but not this node's staging copy, which kept the key until the tenant's next change. Write both. - A stored hash in another form (uppercase, wrong length) loaded and never matched, without a word. Read it in any case, and warn when it is not a SHA-256 in hex. It still loads: refusing it would fail the whole metadata. - Say in the loader that it runs only where validate_multi_tenancy is called at start, which this repository's own main does not do. Co-Authored-By: Claude Fable 5.2 --- src/parseable/mod.rs | 44 +++++++++++++++++++++++++++++--------------- src/rbac/user.rs | 41 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 69 insertions(+), 16 deletions(-) diff --git a/src/parseable/mod.rs b/src/parseable/mod.rs index 05d5332b4..9bad21ff9 100644 --- a/src/parseable/mod.rs +++ b/src/parseable/mod.rs @@ -1297,23 +1297,37 @@ impl Parseable { let metadata: StorageMetadata = serde_json::from_slice(&meta)?; // An API key stored before keys were hashed was hashed by reading - // it. Write the metadata back so that the key itself leaves - // storage now, not at the tenant's next change. The nodes that - // write the default tenant's metadata at every start (see + // it. Write the metadata back, to storage and to this node's + // staging copy, so that the key itself leaves both now, not at + // the tenant's next change. The nodes that write the default + // tenant's metadata at every start (see // `resolve_parseable_metadata`) do this for theirs; the key keeps // working either way, so a failure here only delays it. - if matches!(self.options.mode, Mode::All | Mode::Query) - && crate::rbac::user::stores_unhashed_api_key(&meta) - && let Err(error) = self - .metastore - .put_parseable_metadata(&metadata, &Some(tenant_id.clone())) - .await - { - tracing::warn!( - %tenant_id, - %error, - "Could not rewrite tenant metadata with its API keys hashed" - ); + // + // This runs only where `validate_multi_tenancy` is called at + // start, which this repository's own `main` does not do: there a + // tenant's keys are hashed in storage at its next metadata write. + if crate::rbac::user::stores_unhashed_api_key(&meta) { + let tenant = Some(tenant_id.clone()); + if matches!(self.options.mode, Mode::All | Mode::Query) + && let Err(error) = self + .metastore + .put_parseable_metadata(&metadata, &tenant) + .await + { + tracing::warn!( + %tenant_id, + %error, + "Could not rewrite tenant metadata with its API keys hashed" + ); + } + if let Err(error) = crate::storage::put_staging_metadata(&metadata, &tenant) { + tracing::warn!( + %tenant_id, + %error, + "Could not rewrite the staging copy of tenant metadata with its API keys hashed" + ); + } } TENANT_METADATA.insert_tenant(tenant_id.clone(), metadata.clone()); diff --git a/src/rbac/user.rs b/src/rbac/user.rs index 8dbe4dd33..13a0a85c0 100644 --- a/src/rbac/user.rs +++ b/src/rbac/user.rs @@ -486,7 +486,21 @@ impl TryFrom for ApiKeyUser { // A record that has a hash is never rehashed from `apiKey`: the hash is // what authenticated since it was written. let (key_hash, key_hint) = match (stored.key_hash, stored.api_key) { - (Some(hash), _) => (hash, stored.key_hint.unwrap_or_default()), + (Some(hash), _) => { + // `hash_api_key` gives 64 lowercase hex characters, and that is + // what a presented key is compared with. A hash edited into + // another form would load, be listed and never match. Refusing it + // here would fail the load of the whole metadata, so say so. + let hash = hash.to_ascii_lowercase(); + if hash.len() != 64 || !hash.bytes().all(|byte| byte.is_ascii_hexdigit()) { + tracing::warn!( + key_id = %stored.key_id, + key_name = %stored.key_name, + "Stored API key hash is not a SHA-256 in hex: this key cannot authenticate; delete it and create another" + ); + } + (hash, stored.key_hint.unwrap_or_default()) + } (None, Some(key)) => (hash_api_key(&key), api_key_hint(&key)), (None, None) => return Err("an API key user needs keyHash"), }; @@ -1156,6 +1170,31 @@ mod apikey_serde_tests { assert_eq!(api_key.key_hint, "shed"); } + #[test] + fn stored_hash_is_read_in_any_case_and_a_malformed_one_never_matches() { + let key = "550e8400-e29b-41d4-a716-446655440000"; + let now = Utc::now(); + let mut record = unhashed_record("unused"); + record.as_object_mut().unwrap().remove("apiKey"); + + record["keyHash"] = hash_api_key(key).to_ascii_uppercase().into(); + let user: User = serde_json::from_value(record.clone()).unwrap(); + let api_key = user.as_api_key().unwrap(); + assert_eq!(api_key.key_hash, hash_api_key(key)); + assert!(api_key.matches_active_key(key, now)); + + // Loads, so that one bad record does not take the metadata with it, and + // authenticates nothing + for malformed in ["", "abc", &hash_api_key(key)[..63], &"g".repeat(64)] { + record["keyHash"] = malformed.into(); + let user: User = serde_json::from_value(record.clone()).unwrap(); + let api_key = user.as_api_key().unwrap(); + for presented in [key, "", malformed] { + assert!(!api_key.matches_active_key(presented, now), "{malformed:?}"); + } + } + } + #[test] fn api_key_record_without_hash_or_key_is_rejected() { let mut record = unhashed_record("unused"); From 06cfe0c5a921695ef5a293476c79115b401590e1 Mon Sep 17 00:00:00 2001 From: VibeSWE <338779468+VibeSWE@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:45:52 -0600 Subject: [PATCH 4/4] ci: make Quest's API key test expect the masked key Quest, upstream's integration suite, checks that GET /api/prism/v1/apikeys/{id} returns the key itself. This server now keeps only a hash and returns the mask, so that one assertion fails in the smoke and the full runs. Patch the assertion in the pinned Quest source before the test image is built, so the test still covers get, with this server's contract. The patch step fails if the pinned source stops matching. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/integration-test.yaml | 3 +++ docker-compose-quest.yaml | 6 ++++++ scripts/ci/quest-api-key-hash.patch | 20 ++++++++++++++++++++ 3 files changed, 29 insertions(+) create mode 100644 scripts/ci/quest-api-key-hash.patch diff --git a/.github/workflows/integration-test.yaml b/.github/workflows/integration-test.yaml index 9c4997522..d001dc8e2 100644 --- a/.github/workflows/integration-test.yaml +++ b/.github/workflows/integration-test.yaml @@ -98,6 +98,9 @@ jobs: git -C "$src" fetch --quiet --depth 1 https://github.com/parseablehq/quest.git "$QUEST_SOURCE_REF" git -C "$src" checkout --quiet FETCH_HEAD test "$(git -C "$src" rev-parse HEAD)" = "$QUEST_SOURCE_REF" + # This server returns an API key masked where upstream returns the + # key; see the patch for why. Drop it if Quest stops expecting the key. + git -C "$src" apply "$GITHUB_WORKSPACE/scripts/ci/quest-api-key-hash.patch" docker build --tag "$QUEST_IMAGE" "$src" - name: Run Quest run: docker compose up --no-build --exit-code-from quest diff --git a/docker-compose-quest.yaml b/docker-compose-quest.yaml index af3f6e2d8..17d17113b 100644 --- a/docker-compose-quest.yaml +++ b/docker-compose-quest.yaml @@ -2,6 +2,12 @@ # Find pin references: grep -rnE 'issue #151|f4a026e' . # Remove the pin in quest-source here and QUEST_SOURCE_REF in # .github/workflows/integration-test.yaml; the five extends callers can stay. +# +# Quest built straight from this commit fails TestSmokeAPIKeyLifecycle/GetAPIKey: +# it expects GET /api/prism/v1/apikeys/{id} to return the key, and this server +# returns it masked. CI applies scripts/ci/quest-api-key-hash.patch before +# building; for a local run, build an image from a patched checkout and pass it +# as QUEST_IMAGE. services: quest-source: build: diff --git a/scripts/ci/quest-api-key-hash.patch b/scripts/ci/quest-api-key-hash.patch new file mode 100644 index 000000000..70f4f11cb --- /dev/null +++ b/scripts/ci/quest-api-key-hash.patch @@ -0,0 +1,20 @@ +This server stores API keys as hashes, so GET /api/prism/v1/apikeys/{id} +returns the key masked, as the list does, where upstream Parseable returns +the key itself. Quest's API key test expects upstream's behaviour; this +patch makes it expect the mask. It is applied to the pinned Quest source by +.github/workflows/integration-test.yaml before the test image is built, and +fails that step if the source no longer matches. + +diff --git i/tests/integration/apikey_test.go w/tests/integration/apikey_test.go +index e4a0297..aec70ea 100644 +--- i/tests/integration/apikey_test.go ++++ w/tests/integration/apikey_test.go +@@ -163,7 +163,7 @@ func TestSmokeAPIKeyLifecycle(t *testing.T) { + key, err := readJsonBody[testAPIKeyResponse](response.Body) + require.NoError(t, err) + require.Equal(t, created.KeyID, key.KeyID) +- require.Equal(t, created.APIKey, key.APIKey) ++ require.Equal(t, "****"+created.APIKey[len(created.APIKey)-4:], key.APIKey) + require.Equal(t, keyName, key.KeyName) + require.ElementsMatch(t, []string{role}, key.Roles) + })