Skip to content

Modern Docker Management, Designed for Everyone

fix: stale environment bootstrap API keys accumulating and being undeletable (#3501)

Kyle Mendellef7814b90a2f
diff --git a/.gitignore b/.gitignore
index 0956db38a..c98753455 100644
--- a/.gitignore
+++ b/.gitignore
@@ -18,6 +18,9 @@ dist/
# Claude
CLAUDE.md
/.tmp/
+
+# Deepsec scan artifacts
+.deepsec/
*.key
*.pem
*.crt
diff --git a/backend/api/handlers/environments.go b/backend/api/handlers/environments.go
index 88a642023..93236781f 100644
--- a/backend/api/handlers/environments.go
+++ b/backend/api/handlers/environments.go
@@ -603,7 +603,7 @@ func (h *EnvironmentHandler) createEnvironmentWithApiKeyInternal(ctx context.Con
}
// Generate API key for environment
- apiKeyDto, err := h.apiKeyService.CreateEnvironmentApiKey(ctx, created.ID, user.ID)
+ apiKeyDto, err := h.apiKeyService.CreateEnvironmentApiKey(ctx, created.ID)
if err != nil {
slog.ErrorContext(ctx, "Failed to create environment API key", "environmentID", created.ID, "error", err.Error())
return nil, huma.Error500InternalServerError("Failed to create environment API key")
@@ -619,6 +619,14 @@ func (h *EnvironmentHandler) createEnvironmentWithApiKeyInternal(ctx context.Con
}
updated, err := h.environmentService.UpdateEnvironment(ctx, created.ID, updates, &user.ID, &user.Username)
if err != nil {
+ // Remove the key so a failed create does not leave an orphaned row
+ // behind. ErrApiKeyProtected means the link actually landed and the
+ // update failed afterwards, so the key legitimately belongs to the
+ // environment and must survive; deleting the environment cascades it.
+ if delErr := h.apiKeyService.DeleteApiKey(ctx, apiKeyDto.ID); delErr != nil &&
+ !errors.Is(delErr, services.ErrApiKeyNotFound) && !errors.Is(delErr, services.ErrApiKeyProtected) {
+ slog.ErrorContext(ctx, "Failed to clean up unlinked environment API key", "environmentID", created.ID, "error", delErr.Error())
+ }
slog.ErrorContext(ctx, "Failed to link API key to environment", "environmentID", created.ID, "error", err.Error())
return nil, huma.Error500InternalServerError("Failed to link API key")
}
@@ -736,13 +744,10 @@ func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *Updat
return nil, err
}
- // Delete existing API key if any
- if updated.ApiKeyID != nil {
- _ = h.apiKeyService.DeleteApiKey(ctx, *updated.ApiKeyID)
- }
+ oldApiKeyID := updated.ApiKeyID
// Generate new API key
- apiKeyDto, err := h.apiKeyService.CreateEnvironmentApiKey(ctx, input.ID, user.ID)
+ apiKeyDto, err := h.apiKeyService.CreateEnvironmentApiKey(ctx, input.ID)
if err != nil {
slog.ErrorContext(ctx, "Failed to create new environment API key", "environmentID", input.ID, "error", err.Error())
return nil, huma.Error500InternalServerError("Failed to regenerate API key")
@@ -752,10 +757,27 @@ func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *Updat
apiKey := apiKeyDto.Key
err = h.environmentService.RegenerateEnvironmentApiKey(ctx, input.ID, apiKeyDto.ID, apiKey, user.ID, user.Username, updated.Name)
if err != nil {
+ // The new key was never linked; remove it so a failed rotation does
+ // not leave an orphaned valid credential behind.
+ if delErr := h.apiKeyService.DeleteApiKey(ctx, apiKeyDto.ID); delErr != nil && !errors.Is(delErr, services.ErrApiKeyNotFound) {
+ slog.ErrorContext(ctx, "Failed to clean up unlinked environment API key", "environmentID", input.ID, "error", delErr.Error())
+ }
slog.ErrorContext(ctx, "Failed to regenerate API key", "environmentID", input.ID, "error", err.Error())
return nil, huma.Error500InternalServerError("Failed to regenerate API key")
}
+ // Delete the previous key only after the environment points at the new
+ // one — while still referenced it is protected and the delete would be
+ // rejected, which is how stale bootstrap keys used to accumulate. A
+ // failed delete leaves the old key as a still-valid credential, so log
+ // it as an error; the key stays visible and deletable on the API Keys
+ // page.
+ if oldApiKeyID != nil && *oldApiKeyID != apiKeyDto.ID {
+ if err := h.apiKeyService.DeleteApiKey(ctx, *oldApiKeyID); err != nil && !errors.Is(err, services.ErrApiKeyNotFound) {
+ slog.ErrorContext(ctx, "Failed to delete previous environment API key; the old key remains valid until deleted manually", "environmentID", input.ID, "error", err.Error())
+ }
+ }
+
// Fetch updated environment
updated, err = h.environmentService.GetEnvironmentByID(ctx, input.ID)
if err != nil {
diff --git a/backend/internal/services/api_key_service.go b/backend/internal/services/api_key_service.go
index 698b60be1..7c29c027d 100644
--- a/backend/internal/services/api_key_service.go
+++ b/backend/internal/services/api_key_service.go
@@ -256,7 +256,9 @@ func (s *ApiKeyService) createAPIKeyWithRawKey(
}
return &apikey.ApiKeyCreatedDto{
- ApiKey: toAPIKeyDTOInternal(ak),
+ // A just-minted environment key is about to be linked as the
+ // environment's pairing key, so present it as bootstrap already.
+ ApiKey: toAPIKeyDTOInternal(ak, environmentID != nil),
Key: rawKey,
}, nil
}
@@ -265,18 +267,39 @@ func isStaticAPIKeyInternal(ak models.ApiKey) bool {
return ak.ManagedBy != nil && *ak.ManagedBy == managedByAdminBootstrap
}
-// isEnvironmentBootstrapKeyInternal identifies the auto-generated key minted by
-// CreateEnvironmentApiKey for environment pairing. Those keys have no owner
-// (UserID == nil) and are scoped to a single environment. They carry full
-// env-scoped permissions and must never be hand-edited or deleted via the API
-// — manually clearing the grants would silently break the paired edge agent
-// the next time it tries to authenticate. Cascade-delete still applies when
-// the environment row itself is removed.
-func isEnvironmentBootstrapKeyInternal(ak models.ApiKey) bool {
- return ak.UserID == nil && ak.EnvironmentID != nil
+// isEnvironmentReferencedApiKeyInternal reports whether an environment
+// currently references keyID as its pairing key (environments.api_key_id).
+// Referenced keys are the live environment bootstrap credentials: editing or
+// deleting one would silently break the paired edge agent the next time it
+// authenticates, so they are protected. Keys orphaned by regeneration are no
+// longer referenced and may be edited or deleted normally. Cascade-delete
+// still applies when the environment row itself is removed.
+func (s *ApiKeyService) isEnvironmentReferencedApiKeyInternal(ctx context.Context, keyID string) (bool, error) {
+ var count int64
+ if err := s.db.WithContext(ctx).Model(&models.Environment{}).
+ Where("api_key_id = ?", keyID).Count(&count).Error; err != nil {
+ return false, errors.WrapIf(err, "failed to check environment references for API key")
+ }
+ return count > 0, nil
+}
+
+// environmentReferencedApiKeyIDsInternal returns the set of API key ids
+// currently referenced by an environment, for tagging whole listings with a
+// single query instead of one per row.
+func (s *ApiKeyService) environmentReferencedApiKeyIDsInternal(ctx context.Context) (map[string]struct{}, error) {
+ var ids []string
+ if err := s.db.WithContext(ctx).Model(&models.Environment{}).
+ Where("api_key_id IS NOT NULL").Pluck("api_key_id", &ids).Error; err != nil {
+ return nil, errors.WrapIf(err, "failed to list environment-referenced API key ids")
+ }
+ set := make(map[string]struct{}, len(ids))
+ for _, id := range ids {
+ set[id] = struct{}{}
+ }
+ return set, nil
}
-func toAPIKeyDTOInternal(ak *models.ApiKey) apikey.ApiKey {
+func toAPIKeyDTOInternal(ak *models.ApiKey, isBootstrap bool) apikey.ApiKey {
return apikey.ApiKey{
ID: ak.ID,
Name: ak.Name,
@@ -285,7 +308,7 @@ func toAPIKeyDTOInternal(ak *models.ApiKey) apikey.ApiKey {
UserID: ak.UserID,
Kind: ak.Kind,
IsStatic: isStaticAPIKeyInternal(*ak),
- IsBootstrap: isEnvironmentBootstrapKeyInternal(*ak),
+ IsBootstrap: isBootstrap,
ExpiresAt: ak.ExpiresAt,
LastUsedAt: ak.LastUsedAt,
CreatedAt: ak.CreatedAt,
@@ -295,8 +318,8 @@ func toAPIKeyDTOInternal(ak *models.ApiKey) apikey.ApiKey {
// toAPIKeyDTOWithPermissionsInternal is like toAPIKeyDTOInternal but
// additionally attaches the key's persisted permission grants.
-func toAPIKeyDTOWithPermissionsInternal(ak *models.ApiKey) apikey.ApiKey {
- dto := toAPIKeyDTOInternal(ak)
+func toAPIKeyDTOWithPermissionsInternal(ak *models.ApiKey, isBootstrap bool) apikey.ApiKey {
+ dto := toAPIKeyDTOInternal(ak, isBootstrap)
dto.Permissions = make([]apikey.PermissionGrant, len(ak.PermissionGrants))
for i, grant := range ak.PermissionGrants {
dto.Permissions[i] = apikey.PermissionGrant{
@@ -445,7 +468,7 @@ func (s *ApiKeyService) ReconcileDefaultAdminAPIKey(ctx context.Context, rawKey
})
}
-func (s *ApiKeyService) CreateEnvironmentApiKey(ctx context.Context, environmentID string, userID string) (*apikey.ApiKeyCreatedDto, error) {
+func (s *ApiKeyService) CreateEnvironmentApiKey(ctx context.Context, environmentID string) (*apikey.ApiKeyCreatedDto, error) {
rawKey, err := s.generateApiKey()
if err != nil {
return nil, err
@@ -500,7 +523,11 @@ func (s *ApiKeyService) GetApiKey(ctx context.Context, id string) (*apikey.ApiKe
}
return nil, errors.WrapIf(err, "failed to get API key")
}
- return new(toAPIKeyDTOWithPermissionsInternal(&ak)), nil
+ isBootstrap, err := s.isEnvironmentReferencedApiKeyInternal(ctx, ak.ID)
+ if err != nil {
+ return nil, err
+ }
+ return new(toAPIKeyDTOWithPermissionsInternal(&ak, isBootstrap)), nil
}
func (s *ApiKeyService) ListApiKeys(ctx context.Context, params pagination.QueryParams) ([]apikey.ApiKey, pagination.Response, error) {
@@ -523,19 +550,28 @@ func (s *ApiKeyService) ListApiKeys(ctx context.Context, params pagination.Query
return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate API keys")
}
+ referenced, err := s.environmentReferencedApiKeyIDsInternal(ctx)
+ if err != nil {
+ return nil, pagination.Response{}, err
+ }
+
result := make([]apikey.ApiKey, len(apiKeys))
for i := range apiKeys {
// Include per-key permission grants so the edit form preloads with the
// key's actual current grants. Without this, the form starts empty and
// "Save" would wipe whatever grants the DB has.
- result[i] = toAPIKeyDTOWithPermissionsInternal(&apiKeys[i])
+ _, isBootstrap := referenced[apiKeys[i].ID]
+ result[i] = toAPIKeyDTOWithPermissionsInternal(&apiKeys[i], isBootstrap)
}
return result, paginationResp, nil
}
// ListApiKeysByUser returns every non-static, non-bootstrap API key owned by
-// userID. Used by the self-service personal-keys flow.
+// userID. Used by the self-service personal-keys flow. Keys referenced by an
+// environment are hidden even when they carry an owner (legacy bootstrap rows
+// created before user_id became nullable) — self-service must never touch a
+// live pairing credential.
func (s *ApiKeyService) ListApiKeysByUser(ctx context.Context, userID string) ([]apikey.ApiKey, error) {
var apiKeys []models.ApiKey
query := s.db.WithContext(ctx)
@@ -549,12 +585,17 @@ func (s *ApiKeyService) ListApiKeysByUser(ctx context.Context, userID string) ([
return nil, errors.WrapIf(err, "failed to list user api keys")
}
+ referenced, err := s.environmentReferencedApiKeyIDsInternal(ctx)
+ if err != nil {
+ return nil, err
+ }
+
result := make([]apikey.ApiKey, 0, len(apiKeys))
for i := range apiKeys {
- if isStaticAPIKeyInternal(apiKeys[i]) || isEnvironmentBootstrapKeyInternal(apiKeys[i]) {
+ if _, isBootstrap := referenced[apiKeys[i].ID]; isBootstrap || isStaticAPIKeyInternal(apiKeys[i]) {
continue
}
- result = append(result, toAPIKeyDTOWithPermissionsInternal(&apiKeys[i]))
+ result = append(result, toAPIKeyDTOWithPermissionsInternal(&apiKeys[i], false))
}
return result, nil
}
@@ -567,7 +608,12 @@ func (s *ApiKeyService) UpdateApiKey(ctx context.Context, callerPerms *authz.Per
}
return nil, errors.WrapIf(err, "failed to get API key")
}
- if isStaticAPIKeyInternal(ak) || isEnvironmentBootstrapKeyInternal(ak) {
+ if isStaticAPIKeyInternal(ak) {
+ return nil, ErrApiKeyProtected
+ }
+ if referenced, err := s.isEnvironmentReferencedApiKeyInternal(ctx, ak.ID); err != nil {
+ return nil, err
+ } else if referenced {
return nil, ErrApiKeyProtected
}
@@ -584,10 +630,10 @@ func (s *ApiKeyService) UpdateApiKey(ctx context.Context, callerPerms *authz.Per
return nil, err
}
if ak.UserID == nil {
- // No owner to cap against. The only legitimate ownerless keys are
- // environment bootstrap keys, rejected as protected above — refuse
- // grant edits on any other ownerless row rather than fall back to
- // a weaker caller-only check.
+ // No owner to cap against. Ownerless rows are (possibly stale)
+ // environment bootstrap keys — name/description edits are harmless,
+ // but refuse grant edits rather than fall back to a weaker
+ // caller-only check.
return nil, ErrApiKeyProtected
}
if err := s.validateGrantsAgainstOwnerInternal(ctx, *ak.UserID, req.Permissions); err != nil {
@@ -632,7 +678,7 @@ func (s *ApiKeyService) UpdateApiKey(ctx context.Context, callerPerms *authz.Per
UserID: ak.UserID,
Kind: ak.Kind,
IsStatic: isStaticAPIKeyInternal(ak),
- IsBootstrap: isEnvironmentBootstrapKeyInternal(ak),
+ IsBootstrap: false, // an environment-referenced key can't reach this return
ExpiresAt: ak.ExpiresAt,
LastUsedAt: ak.LastUsedAt,
CreatedAt: ak.CreatedAt,
@@ -671,7 +717,12 @@ func (s *ApiKeyService) DeleteApiKey(ctx context.Context, id string) error {
}
return errors.WrapIf(err, "failed to load API key")
}
- if isStaticAPIKeyInternal(apiKey) || isEnvironmentBootstrapKeyInternal(apiKey) {
+ if isStaticAPIKeyInternal(apiKey) {
+ return ErrApiKeyProtected
+ }
+ if referenced, err := s.isEnvironmentReferencedApiKeyInternal(ctx, apiKey.ID); err != nil {
+ return err
+ } else if referenced {
return ErrApiKeyProtected
}
diff --git a/backend/internal/services/api_key_service_test.go b/backend/internal/services/api_key_service_test.go
index f6a62489c..30c570e13 100644
--- a/backend/internal/services/api_key_service_test.go
+++ b/backend/internal/services/api_key_service_test.go
@@ -26,7 +26,7 @@ func setupAPIKeyServiceTestDB(t *testing.T) *database.DB {
dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared", strings.NewReplacer("/", "_", " ", "_").Replace(t.Name()))
db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})
require.NoError(t, err)
- require.NoError(t, db.AutoMigrate(&models.User{}, &models.ApiKey{}))
+ require.NoError(t, db.AutoMigrate(&models.User{}, &models.ApiKey{}, &models.Environment{}))
sqlDB, err := db.DB()
require.NoError(t, err)
@@ -157,10 +157,12 @@ func TestListApiKeysPermissionQueryCountIsConstant(t *testing.T) {
})
}
- require.Equal(t, int64(3), queryCounts[1])
- require.Equal(t, int64(3), queryCounts[5])
- require.Equal(t, int64(2), userQueryCounts[1])
- require.Equal(t, int64(2), userQueryCounts[5])
+ // Each list call spends one extra constant query on the set of
+ // environment-referenced key ids (bootstrap-protection flag).
+ require.Equal(t, int64(4), queryCounts[1])
+ require.Equal(t, int64(4), queryCounts[5])
+ require.Equal(t, int64(3), userQueryCounts[1])
+ require.Equal(t, int64(3), userQueryCounts[5])
}
func TestCreateDefaultAdminAPIKeyUsesProvidedRawKey(t *testing.T) {
@@ -588,10 +590,9 @@ func TestValidateAPIKeyRepeatedAuthenticationDoesNotGrowGoroutines(t *testing.T)
func TestGetEnvironmentByAPIKeyUpdatesLastUsedAt(t *testing.T) {
ctx := context.Background()
- service, db, userService := setupAPIKeyService(t)
- user := createTestAPIKeyUser(t, ctx, userService, "user-environment")
+ service, db, _ := setupAPIKeyService(t)
- created, err := service.CreateEnvironmentApiKey(ctx, "env-123", user.ID)
+ created, err := service.CreateEnvironmentApiKey(ctx, "env-123")
require.NoError(t, err)
require.Nil(t, fetchAPIKey(t, db, created.ID).LastUsedAt)
@@ -604,6 +605,48 @@ func TestGetEnvironmentByAPIKeyUpdatesLastUsedAt(t *testing.T) {
require.NotNil(t, apiKey.LastUsedAt)
}
+func TestApiKeyProtectedWhileEnvironmentReferenced(t *testing.T) {
+ ctx := context.Background()
+ service, db, _ := setupAPIKeyService(t)
+
+ created, err := service.CreateEnvironmentApiKey(ctx, "env-referenced")
+ require.NoError(t, err)
+
+ env := &models.Environment{
+ BaseModel: models.BaseModel{ID: "env-referenced"},
+ Name: "referenced",
+ ApiUrl: "http://localhost:2375",
+ ApiKeyID: &created.ID,
+ }
+ require.NoError(t, db.WithContext(ctx).Create(env).Error)
+
+ // Referenced by the environment: protected from update and delete.
+ require.ErrorIs(t, service.DeleteApiKey(ctx, created.ID), ErrApiKeyProtected)
+ _, err = service.UpdateApiKey(ctx, authz.SudoPermissionSet(), created.ID, apikey.UpdateApiKey{Name: new("renamed")})
+ require.ErrorIs(t, err, ErrApiKeyProtected)
+
+ // Legacy pre-046 bootstrap rows carry an owner; the reference alone must
+ // still protect them.
+ legacyUserID := "legacy-owner"
+ legacy := &models.ApiKey{
+ BaseModel: models.BaseModel{ID: "legacy-key"},
+ Name: "Environment Bootstrap Key - legacy",
+ KeyHash: "hash",
+ KeyPrefix: "arc_lgcy",
+ Kind: models.ApiKeyKindScoped,
+ UserID: &legacyUserID,
+ EnvironmentID: new("env-referenced"),
+ }
+ require.NoError(t, db.WithContext(ctx).Create(legacy).Error)
+ require.NoError(t, db.WithContext(ctx).Model(&models.Environment{}).
+ Where("id = ?", env.ID).Update("api_key_id", legacy.ID).Error)
+ require.ErrorIs(t, service.DeleteApiKey(ctx, legacy.ID), ErrApiKeyProtected)
+
+ // The first key is no longer referenced (simulates regeneration): stale
+ // keys are deletable.
+ require.NoError(t, service.DeleteApiKey(ctx, created.ID))
+}
+
func TestValidateAPIKeyInvalidDoesNotUpdateLastUsedAt(t *testing.T) {
ctx := context.Background()
service, db, userService := setupAPIKeyService(t)
@@ -629,10 +672,9 @@ func TestValidateAPIKeyRejectsShortPrefixedInput(t *testing.T) {
func TestGetEnvironmentByAPIKeyExpiredDoesNotUpdateLastUsedAt(t *testing.T) {
ctx := context.Background()
- service, db, userService := setupAPIKeyService(t)
- user := createTestAPIKeyUser(t, ctx, userService, "user-expired")
+ service, db, _ := setupAPIKeyService(t)
- created, err := service.CreateEnvironmentApiKey(ctx, "env-expired", user.ID)
+ created, err := service.CreateEnvironmentApiKey(ctx, "env-expired")
require.NoError(t, err)
expiredAt := time.Now().Add(-time.Minute)
@@ -659,7 +701,7 @@ func TestCreateEnvironmentApiKeySeedsAllPermissionsScopedToEnv(t *testing.T) {
grantGlobalAdmin(t, roleSvc, admin.ID)
envID := "env-bootstrap-test"
- created, err := service.CreateEnvironmentApiKey(ctx, envID, admin.ID)
+ created, err := service.CreateEnvironmentApiKey(ctx, envID)
require.NoError(t, err)
// Resolve the per-key permission set and confirm every permission is
@@ -708,10 +750,9 @@ func TestBackfillApiKeyPermissionsRepairsExistingBootstrapKey(t *testing.T) {
func TestGetEnvironmentByAPIKeyRecentLastUsedAtDoesNotRewriteImmediately(t *testing.T) {
ctx := context.Background()
- service, db, userService := setupAPIKeyService(t)
- user := createTestAPIKeyUser(t, ctx, userService, "user-environment-recent")
+ service, db, _ := setupAPIKeyService(t)
- created, err := service.CreateEnvironmentApiKey(ctx, "env-456", user.ID)
+ created, err := service.CreateEnvironmentApiKey(ctx, "env-456")
require.NoError(t, err)
recent := time.Now().Add(-time.Minute)
diff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.go
index 8527231b5..96b8ba456 100644
--- a/backend/internal/services/environment_service.go
+++ b/backend/internal/services/environment_service.go
@@ -755,15 +755,33 @@ func (s *EnvironmentService) applySwarmNodeAgentApiKeyInternal(
return "", errors.New("api key service not configured")
}
- apiKeyDto, err := s.apiKeyService.CreateEnvironmentApiKey(ctx, env.ID, userID)
+ oldApiKeyID := env.ApiKeyID
+
+ apiKeyDto, err := s.apiKeyService.CreateEnvironmentApiKey(ctx, env.ID)
if err != nil {
return "", errors.WrapIf(err, "failed to create environment API key")
}
if err := s.RegenerateEnvironmentApiKey(ctx, env.ID, apiKeyDto.ID, apiKeyDto.Key, userID, username, env.Name); err != nil {
+ // The new key was never linked; remove it so a failed rotation does
+ // not leave an orphaned valid credential behind.
+ if delErr := s.apiKeyService.DeleteApiKey(ctx, apiKeyDto.ID); delErr != nil && !errors.Is(delErr, ErrApiKeyNotFound) {
+ slog.ErrorContext(ctx, "Failed to clean up unlinked environment API key", "environmentID", env.ID, "error", delErr.Error())
+ }
return "", err
}
+ // Delete the previous key only after the environment points at the new
+ // one — while still referenced it is protected and the delete would be
+ // rejected. Failure is non-fatal for the rotation itself, but the old key
+ // remains a valid credential until deleted, so log it as an error; the key
+ // stays visible and deletable on the API Keys page.
+ if oldApiKeyID != nil && *oldApiKeyID != apiKeyDto.ID {
+ if err := s.apiKeyService.DeleteApiKey(ctx, *oldApiKeyID); err != nil && !errors.Is(err, ErrApiKeyNotFound) {
+ slog.ErrorContext(ctx, "Failed to delete previous environment API key; the old key remains valid until deleted manually", "environmentID", env.ID, "error", err.Error())
+ }
+ }
+
return apiKeyDto.Key, nil
}
@@ -1611,8 +1629,14 @@ func (s *EnvironmentService) RegenerateEnvironmentApiKey(ctx context.Context, en
"last_seen": nil, // Clear last seen time
}
- if err := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id = ?", envID).Updates(updates).Error; err != nil {
- return errors.WrapIf(err, "failed to update environment with new API key")
+ result := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id = ?", envID).Updates(updates)
+ if result.Error != nil {
+ return errors.WrapIf(result.Error, "failed to update environment with new API key")
+ }
+ if result.RowsAffected == 0 {
+ // A zero-row update would otherwise report a successful rotation while
+ // the new key was never linked to anything.
+ return errors.New("environment not found")
}
s.syncEnvironmentTokenCacheInternal(envID, apiKey)
diff --git a/frontend/src/routes/(app)/settings/api-keys/api-key-table.svelte b/frontend/src/routes/(app)/settings/api-keys/api-key-table.svelte
index 2723cb457..a4de1ff26 100644
--- a/frontend/src/routes/(app)/settings/api-keys/api-key-table.svelte
+++ b/frontend/src/routes/(app)/settings/api-keys/api-key-table.svelte
@@ -1,6 +1,7 @@
<script lang="ts">
import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';
+ import * as ArcaneTooltip from '#lib/components/arcane-tooltip';
import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
import { CopyButton } from '#lib/components/ui/copy-button';
import { toast } from 'svelte-sonner';
@@ -249,24 +250,53 @@
{/snippet}
{#snippet RowActions({ item }: { item: ApiKey })}
+ {@const lockedReason = isStaticApiKey(item)
+ ? m.api_key_static_description()
+ : isBootstrapApiKey(item)
+ ? m.api_key_bootstrap_description()
+ : null}
<RowActionsMenu>
<IfPermitted perm="apikeys:update">
- <DropdownMenu.Item onclick={() => onEditApiKey(item)} disabled={isStaticApiKey(item) || isBootstrapApiKey(item)}>
- <EditIcon class="size-4" />
- {m.common_edit()}
- </DropdownMenu.Item>
+ {#if lockedReason}
+ <ArcaneTooltip.Root>
+ <ArcaneTooltip.Trigger class="w-full" disabledChild>
+ <DropdownMenu.Item disabled>
+ <EditIcon class="size-4" />
+ {m.common_edit()}
+ </DropdownMenu.Item>
+ </ArcaneTooltip.Trigger>
+ <ArcaneTooltip.Content>
+ <p class="max-w-xs text-xs break-words">{lockedReason}</p>
+ </ArcaneTooltip.Content>
+ </ArcaneTooltip.Root>
+ {:else}
+ <DropdownMenu.Item onclick={() => onEditApiKey(item)}>
+ <EditIcon class="size-4" />
+ {m.common_edit()}
+ </DropdownMenu.Item>
+ {/if}
</IfPermitted>
<DropdownMenu.Separator />
<IfPermitted perm="apikeys:delete">
- <DropdownMenu.Item
- variant="destructive"
- onclick={() => handleDeleteApiKey(item.id, item.name)}
- disabled={isStaticApiKey(item) || isBootstrapApiKey(item)}
- >
- <TrashIcon class="size-4" />
- {m.common_delete()}
- </DropdownMenu.Item>
+ {#if lockedReason}
+ <ArcaneTooltip.Root>
+ <ArcaneTooltip.Trigger class="w-full" disabledChild>
+ <DropdownMenu.Item variant="destructive" disabled>
+ <TrashIcon class="size-4" />
+ {m.common_delete()}
+ </DropdownMenu.Item>
+ </ArcaneTooltip.Trigger>
+ <ArcaneTooltip.Content>
+ <p class="max-w-xs text-xs break-words">{lockedReason}</p>
+ </ArcaneTooltip.Content>
+ </ArcaneTooltip.Root>
+ {:else}
+ <DropdownMenu.Item variant="destructive" onclick={() => handleDeleteApiKey(item.id, item.name)}>
+ <TrashIcon class="size-4" />
+ {m.common_delete()}
+ </DropdownMenu.Item>
+ {/if}
</IfPermitted>
</RowActionsMenu>
{/snippet}
diff --git a/types/apikey/apikey.go b/types/apikey/apikey.go
index dda1c61f3..bec7a8c45 100644
--- a/types/apikey/apikey.go
+++ b/types/apikey/apikey.go
@@ -35,7 +35,7 @@ type ApiKey struct {
UserID *string `json:"userId,omitempty" doc:"ID of the user who owns the API key"`
Kind string `json:"kind" doc:"Key kind: 'scoped' keys use their own permission grants, 'personal' keys inherit the owner's role permissions"`
IsStatic bool `json:"isStatic" doc:"Whether the API key is environment-managed and protected from deletion"`
- IsBootstrap bool `json:"isBootstrap" doc:"Whether the API key is an auto-generated environment bootstrap key (locked from manual edit / delete)"`
+ IsBootstrap bool `json:"isBootstrap" doc:"Whether the API key is currently referenced by an environment as its pairing key (locked from manual edit / delete)"`
ExpiresAt *time.Time `json:"expiresAt,omitempty" doc:"Expiration date of the API key"`
LastUsedAt *time.Time `json:"lastUsedAt,omitempty" doc:"Last time the API key was used"`
CreatedAt time.Time `json:"createdAt" doc:"Creation timestamp"`