#7061·nango

trg_env_delete_customer_key_relations hard-deletes API keys still related to other, untouched environments

Author: lokeshramchand-ctrlCreated Aug 9, 2026Updated Sep 22, 2026

Bug Description

The DB trigger that cleans up customer_keys when an environment is hard-deleted is not "relation-aware": it deletes the entire customer_keys row for any key that has any relation to the deleted environment, without checking whether that key also has a surviving relation to a different, still-active environment. Because customer_keys.id cascades via customer_keys_relations.customer_key_id REFERENCES customer_keys(id) ON DELETE CASCADE, hard-deleting one environment silently and permanently destroys an API key's access to every other environment it is related to — even ones that were never touched.

This directly contradicts the stated goal of #6991 ("account-level api keys"), whose PR description explicitly claims to add "relation-aware cleanup for shared environment keys". The customer_keys_relations schema and AccountService.getApiKeyContextByCustomerKey (which already aggregates environment_ids: number[] per key) both model a key being related to more than one environment — but the cleanup trigger added in 20260420120000_create_customer_keys.cjs was never updated to match that model.

Where it lives

  • Trigger/function: packages/database/lib/migrations/20260420120000_create_customer_keys.cjs (cleanup_customer_key_relations(), trg_env_delete_customer_key_relations)
  • Fires from: EnvironmentService.hardDelete() in packages/shared/lib/services/environment.service.ts:333 (DELETE FROM _nango_environments WHERE id = ?)
  • Called by: deleteEnvironmentData() → packages/server/lib/deletion/deleteEnvironmentData.ts:34
  • Scheduled by: the deleteOldData cron (packages/server/lib/crons/deleteOldData.ts), which runs every CRON_DELETE_OLD_DATA_EVERY_MIN minutes and hard-deletes environments that were soft-deleted more than CRON_DELETE_OLD_ENVIRONMENTS_MAX_DAYS days ago.

Root Cause

sql
CREATE OR REPLACE FUNCTION cleanup_customer_key_relations()
RETURNS TRIGGER AS $$
BEGIN
    DELETE FROM customer_keys
    WHERE id IN (
        SELECT customer_key_id FROM customer_keys_relations
        WHERE entity_type = TG_ARGV[0] AND entity_id = OLD.id
    );
    RETURN OLD;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trg_env_delete_customer_key_relations
    BEFORE DELETE ON _nango_environments
    FOR EACH ROW EXECUTE FUNCTION cleanup_customer_key_relations('environment');

The DELETE FROM customer_keys WHERE id IN (...) has no NOT EXISTS (or count) check for other rows in customer_keys_relations pointing at a different, live entity_id. It deletes the key outright the moment it finds one matching relation to the environment being removed, regardless of how many other relations that key has.

Reproduction

Applied the exact DDL from 20260420120000_create_customer_keys.cjs to a throwaway Postgres 16 instance and simulated one API key shared across two environments of the same account (the shape ApiKeyPrincipal.environmentIds: number[] / getApiKeyContextByCustomerKey's environment_ids array already assumes is valid):

sql
INSERT INTO _nango_accounts (id, name) VALUES (1, 'Acme');
INSERT INTO _nango_environments (id, account_id, name) VALUES (10, 1, 'prod'), (11, 1, 'staging');

INSERT INTO customer_keys (id, account_id, key_type, display_name, scopes, secret, hashed)
VALUES (100, 1, 'api', 'shared-ci-key', ARRAY['environment:*'], 'irrelevant', 'irrelevant-hash');

INSERT INTO customer_keys_relations (customer_key_id, entity_type, entity_id) VALUES
    (100, 'environment', 10),  -- relation to "prod"
    (100, 'environment', 11);  -- relation to "staging"

-- Simulates EnvironmentService.hardDelete(10), called once "prod" has been
-- soft-deleted and its retention window has elapsed.
DELETE FROM _nango_environments WHERE id = 10;

Output:

--- customer_keys before deleting "prod" (env 10) ---
 id  | display_name  | deleted_at
-----+---------------+------------
 100 | shared-ci-key |
(1 row)

--- relations before ---
 customer_key_id | entity_type | entity_id
-----------------+-------------+-----------
             100 | environment |        10
             100 | environment |        11
(2 rows)

DELETE 1

--- customer_keys AFTER deleting only "prod" (env 10) ---
 id | display_name | deleted_at
----+--------------+------------
(0 rows)

--- relations AFTER (staging relation is gone too!) ---
 customer_key_id | entity_type | entity_id
-----------------+-------------+-----------
(0 rows)

--- staging (env 11) is untouched and still exists ---
 id | account_id |  name   | deleted
----+------------+---------+---------
 11 |          1 | staging | f
(1 row)

staging (env 11) was never deleted or even referenced in the DELETE, yet shared-ci-key — which was still validly related to it — is gone without a trace (hard delete, no deleted_at tombstone, no audit trail). Any caller still authenticating with that key against staging starts getting unknown_account from AccountService.getApiKeyContextByCustomerKey.

Impact

  • Silent, unrecoverable API outage for any customer whose key is related to more than one environment: deleting/retiring one environment (a routine, low-risk action) revokes that key everywhere else it was valid, with no warning, no soft-delete grace period, and no way to tell from the deleted environment's audit trail which other environments were collaterally affected.
  • The failure mode is asynchronous and delayed: the hard delete only runs from the deleteOldData cron after the retention window, so the outage can surface days or weeks after the environment was deleted — far removed from the action that caused it, making it very hard to diagnose.
  • This is not hypothetical scaffolding: the customer_keys_relations schema (UNIQUE (customer_key_id, entity_type, entity_id), not UNIQUE (customer_key_id, entity_type)) and AccountService.getApiKeyContextByCustomerKey's environment_ids aggregation both already model multi-environment keys as a first-class case. #7007 ("add public environment api-keys management endpoints") and the account-level API key work in #6991/#7024 are actively building toward exposing that model to users — this trigger needs to be fixed before any code path can actually attach one key to multiple environments, or the very first customer to use that feature will have a key destroyed the first time they delete any one of its environments.

Suggested Fix

Only hard-delete a key when the relation being removed is its only relation; otherwise just drop that one relation row. Verified against Postgres 16 (both the "shared key survives" and "solo key still gets cleaned up" cases pass):

sql
CREATE OR REPLACE FUNCTION cleanup_customer_key_relations()
RETURNS TRIGGER AS $$
BEGIN
    -- Keys whose ONLY relation is the entity being removed get hard-deleted;
    -- ON DELETE CASCADE on customer_keys_relations.customer_key_id takes care
    -- of their relation row.
    DELETE FROM customer_keys
    WHERE id IN (
        SELECT customer_key_id FROM customer_keys_relations
        WHERE entity_type = TG_ARGV[0] AND entity_id = OLD.id
    )
    AND NOT EXISTS (
        SELECT 1 FROM customer_keys_relations other
        WHERE other.customer_key_id = customer_keys.id
          AND (other.entity_type != TG_ARGV[0] OR other.entity_id != OLD.id)
    );

    -- Keys that survived (because they had another relation) just lose the
    -- relation to the entity being removed.
    DELETE FROM customer_keys_relations
    WHERE entity_type = TG_ARGV[0] AND entity_id = OLD.id;

    RETURN OLD;
END;
$$ LANGUAGE plpgsql;

Note: a single WITH ... AS (DELETE ... RETURNING ...) DELETE ... CTE version of this looks tempting but is subtly wrong — Postgres data-modifying CTEs don't make their writes visible to sibling scans within the same statement, so a NOT EXISTS check against customer_keys_relations in the main statement would still see the pre-deletion snapshot and never fire. The two sequential DELETEs above avoid that pitfall.

Environment

  • Reproduced against a clean Postgres 16 container using the exact DDL from packages/database/lib/migrations/20260420120000_create_customer_keys.cjs on master (commit 6a33ebb02, PR #6991, merged 2026-08-07).