Skip to content

cf deploy deletes all existing Worker secrets unless --secrets-file is passed #72

Closed as duplicate

Description

@paultnylund

cf version: 1.0.0-beta.5 (Wrangler 4.143.0 as the delegated bundler), macOS and Linux CI

What happens

A plain cf deploy of a Worker project removes every secret already set on the Worker. wrangler deploy never did this: its docs say "Wrangler will not delete your secrets unless you run wrangler secret delete <key>". After cf migrate, the first cf deploy in production took our Worker's secret list from ['VIEW_PUBLISH_SECRET'] to [].

Passing --secrets-file with an empty {} file keeps every existing secret. So the keep-behaviour exists; it just isn't the default.

Repro (throwaway Worker, no bindings, workersDev: false)

  1. cf deploy → secrets: []
  2. cf workers secrets update PROBE_A --worker <name> --type secret_text --text x → secrets: ['PROBE_A']
  3. cf deploy → secrets: [] (PROBE_A deleted)
  4. re-add PROBE_A, then cf deploy --secrets-file probe.env (containing only PROBE_B=x) → ['PROBE_A', 'PROBE_B']
  5. cf deploy --secrets-file empty.json ({}) → ['PROBE_A', 'PROBE_B']

Secrets were read with GET /accounts/<id>/workers/scripts/<name>/secrets after each step.

Expected

Keep existing secrets on deploy by default, as Wrangler does, or at minimum warn before removing them. cf migrate could also flag this, since a migrated project's first deploy silently drops production secrets.

Activity

  1. matthewbjones commented on Sep 29, 2026

    @matthewbjones

    Standalone reproduction on cf 1.0.0-beta.5, Node 24.4.1, Bun 1.4.2, macOS. This uses a local mock API, dummy credentials, and a tiny prebuilt Worker. No Cloudflare account, existing Worker, or application repository is required. Telemetry is disabled.

    Install in a fresh directory:

    mkdir cf-72-repro
    cd cf-72-repro
    printf '{"private":true}\n' > package.json
    bun add --exact [email protected]

    Save the following as secrets-repro.mjs and run node secrets-repro.mjs. The script asserts the observed beta.5 behavior and removes its temporary Worker output afterward.

    Complete reproduction script
    import assert from 'node:assert/strict';
    import { spawn } from 'node:child_process';
    import { createServer } from 'node:http';
    import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
    import { tmpdir } from 'node:os';
    import { join, resolve } from 'node:path';
    
    const cli = resolve('node_modules/.bin/cf');
    const cwd = mkdtempSync(join(tmpdir(), 'cf-deploy-repro-'));
    const output = join(cwd, '.cloudflare/output/v0');
    const worker = join(output, 'workers/default');
    mkdirSync(join(worker, "bundle"), { recursive: true });
    // A minimal prebuilt Worker isolates deployment from framework/build tooling.
    writeFileSync(join(output, 'config.json'), JSON.stringify({ buildContext: { isPreview: false } }));
    const config = {
      name: 'fixture', compatibilityDate: '2026-09-29', env: {},
      manifest: { type: 'complete', mainModule: 'worker.js', modules: { 'worker.js': { type: 'esm' } } },
    };
    writeFileSync(join(worker, 'bundle/worker.js'), 'export default { fetch() { return new Response("ok"); } };');
    let requests = [];
    const server = createServer(async (req, res) => {
      try {
        const path = new URL(req.url, 'http://localhost').pathname;
        const chunks = [];
        for await (const chunk of req) chunks.push(chunk);
        const body = Buffer.concat(chunks);
        const record = { method: req.method, path };
        if (req.headers['content-type']?.includes('multipart/form-data')) {
          const form = await new Response(body, { headers: { 'content-type': req.headers['content-type'] } }).formData();
          record.metadata = JSON.parse(form.get('metadata'));
        }
        requests.push(record);
        let result;
        if (path.endsWith('/workers/services/fixture')) result = { id: 'fixture', default_environment: { environment: 'production', script: { id: 'fixture', tag: 'fixture', last_deployed_from: 'wrangler', compatibility_date: '2026-09-29' } } };
        else if (path.endsWith('/fixture/secrets')) result = [{ name: 'EXISTING_SECRET', type: 'secret_text' }];
        else if (path.endsWith('/fixture/settings')) result = { bindings: [{ name: 'EXISTING_SECRET', type: 'secret_text' }] };
        else if (path.endsWith('/fixture/versions') && req.method === 'POST') result = { id: '11111111-1111-4111-8111-111111111111', metadata: { created_on: '2026-09-29T00:00:00Z' }, startup_time_ms: 1, resources: { script: { handlers: ['fetch'] } } };
        else if (path.endsWith('/fixture/deployments')) result = req.method === 'POST' ? { id: 'deployment', versions: [] } : { deployments: [] };
        else if (path.endsWith('/fixture/script-settings')) result = {};
        else if (path.endsWith('/workers/workers/fixture')) result = { id: 'fixture', name: 'fixture', subdomain: { enabled: false, previews_enabled: false } };
        else if (path.endsWith('/fixture/subdomain')) result = { enabled: false, previews_enabled: false };
        else if (path.endsWith('/workers/subdomain')) result = { subdomain: 'fixture' };
        else throw new Error(`Unexpected endpoint: ${req.method} ${path}`);
        res.writeHead(200, { 'content-type': 'application/json' });
        res.end(JSON.stringify({ success: true, errors: [], messages: [], result }));
      } catch (error) { res.writeHead(500); res.end(String(error)); }
    });
    await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
    const env = { ...process.env, CI: 'true', CLOUDFLARE_API_TOKEN: 'fixture-only', CLOUDFLARE_ACCOUNT_ID: 'fixture-only', CLOUDFLARE_API_BASE_URL: `http://127.0.0.1:${server.address().port}/client/v4`, CF_SEND_TELEMETRY: 'false', WRANGLER_SEND_METRICS: 'false', DO_NOT_TRACK: '1' };
    try {
      for (const declared of [false, true]) {
        config.env = declared ? { EXISTING_SECRET: { type: 'secret' } } : {};
        writeFileSync(join(worker, 'worker.config.json'), JSON.stringify(config));
        requests = [];
        const child = spawn(cli, ['deploy', '--prebuilt'], { cwd, env, stdio: ['ignore', 'pipe', 'pipe'] });
        let stderr = '';
        child.stdout.resume();
        child.stderr.on('data', data => { stderr += data; });
        const code = await new Promise((resolve, reject) => { child.on('error', reject); child.on('close', resolve); });
        assert.equal(code, 0, stderr);
        const metadata = requests.find(r => r.metadata)?.metadata;
        assert(metadata, 'Expected version upload');
        const inherited = metadata.bindings?.find(b => b.name === 'EXISTING_SECRET') ?? null;
        console.log(JSON.stringify({ declared, exit: code, secretBinding: inherited, keepBindings: metadata.keep_bindings ?? null }));
        assert.equal(inherited?.type, declared ? 'inherit' : undefined);
        assert(!metadata.keep_bindings?.includes('secret_text'));
    
      }
    } finally { server.close(); rmSync(cwd, { recursive: true, force: true }); }

    Observed output:

    {"declared":false,"exit":0,"secretBinding":null,"keepBindings":null}
    {"declared":true,"exit":0,"secretBinding":{"name":"EXISTING_SECRET","type":"inherit"},"keepBindings":null}

    The fixture reports an existing EXISTING_SECRET. With no declaration in the config, the actual multipart upload contains neither an inheritance binding for it nor keep_bindings: ["secret_text"]. Declaring it as { type: "secret" } produces the inheritance binding in the second run.

    This isolates the request-construction behavior behind this issue; it does not simulate or claim to independently verify the live API's deletion behavior. Both deploys are handled entirely by the loopback server. This also provides a local reproduction relevant to #70.

    Expected: preserve existing secrets by default, or refuse the deployment with an explicit explanation before omitting them.

  2. added theissue type on Sep 29, 2026
  3. neotan commented on Sep 29, 2026

    @neotan

    I think I found why this happens, and there's a fix on my fork: neotan/cf@main...neotan:cf:fix/deploy-keep-secrets. This repo doesn't accept pull requests from outside, so feel free to copy it or take it over.

    When you deploy a Worker that already exists, cf uploads the new code and has to tell Cloudflare what to carry over from the previous version. It only asks to carry over secrets when you pass --secrets-file or turn on keep_vars. A plain cf deploy never asks, so the new version goes live without them. That's also why step 5 above works: any secrets file, even an empty {}, turns that request on.

    The fix is a one-line change to the patch cf already keeps for @cloudflare/deploy-helpers: always ask to keep secrets on deploy. cf workers versions create already does this. I added a test for the exact case here, an existing Worker with no secrets listed in its config. It failed before the change and passes after it, and pnpm check passes.

    There's one part I can't explain yet. Wrangler has the same line, and its own tests expect a normal deploy not to send this request. People here still say wrangler deploy keeps their secrets. I compared what the two tools send and found no difference, so Cloudflare's side may be treating them differently. Someone who can see the API side should check that before this goes into workers-sdk.

    Heads-up: #93 edits the same patch file and plans to delete it after upgrading deploy-helpers. If that lands first, this change needs to come along with it or be fixed in workers-sdk.

  4. added 3 commits that reference this issue on Sep 29, 2026
    925d5c9
    3b8b44e
    45c6813
  5. neotan commented on Sep 30, 2026

    @neotan

    This is now fixed upstream in cloudflare/workers-sdk#15964, which makes the same change in deploy-helpers. That PR also explains the Wrangler difference: the backend was keeping secrets for Wrangler deploys. Once cf picks up the next deploy-helpers release, my fork branch isn't needed.

  6. lnv-louis commented on Oct 3, 2026

    @lnv-louis

    I second this.

  7. added a commit that references this issue on Nov 10, 2026
    1eedfea
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions