Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
github-secrets-import.test.ts18.8 KB · 544 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
/**
 * Block T1 — GitHub Actions secret-migration helper tests.
 *
 * Covers:
 *   - `listGithubSecretNames` happy path / error paths / pagination
 *   - `createPlaceholderSecrets` inserts + skips existing + counts correctly
 *   - `importSecretsForRepo` end-to-end with injected fetch + a stubbed DB
 *   - GET /:owner/:repo/import/secrets route auth gates (302 for anon, 403
 *     for non-owner — exact status depends on requireRepoAccess shape)
 *   - POST /:owner/:repo/import/secrets/:name persists the encrypted value
 *
 * K1-style spread-from-real mock pattern: we capture the REAL `../db` and
 * `../lib/notify` modules before calling `mock.module()`, install minimal
 * stubs for THIS file's needs, and explicitly restore in `afterAll` so
 * downstream test files in the same `bun test` invocation aren't poisoned.
 *
 * Fetch is dependency-injected (`fetchImpl`) — never mock global fetch.
 */

import { describe, it, expect, mock, beforeEach, afterAll } from "bun:test";

// Capture REAL modules before any mock.module() so we can fully restore.
const _real_db = await import("../db");
const _real_notify = await import("../lib/notify");

// ─── Master key fixture ────────────────────────────────────────────────────
// We need a real AES-256 key for the encrypt/decrypt round-trips. Stash the
// previous value (if any) and restore in afterAll so downstream tests that
// rely on the absence of the key aren't polluted.
const _prevWfKey = process.env.WORKFLOW_SECRETS_KEY;
process.env.WORKFLOW_SECRETS_KEY =
  "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff";

// ─── Fake DB ───────────────────────────────────────────────────────────────
// Per-test handles for canned row shapes.
let _nextSelectRows: any[] = [];
let _insertedRows: any[] = [];
// Maps repoId -> Set<name> for fast lookup. Drizzle's chain hides the
// `.where()` parameters from us, but we can recover the queried name by
// peeking at the SQL operands the eq() builder records inside the chain.
let _existingNamesByRepo: Map<string, Set<string>> = new Map();
let _activeRepoId: string | null = null;
let _lastInsertTable: any = null;

const tableLooksLike = (t: any): string => {
  if (!t || typeof t !== "object") return "?";
  if ("encryptedValue" in t || "encrypted_value" in t) return "workflow_secrets";
  return "?";
};

// Drizzle's eq() returns a SQL fragment whose internal shape includes the
// queryChunks. We peek at them defensively — if anything looks off we
// degrade to "no rows match".
const extractWhereValues = (whereArg: any): unknown[] => {
  const values: unknown[] = [];
  const walk = (node: any) => {
    if (!node) return;
    if (Array.isArray(node)) {
      for (const x of node) walk(x);
      return;
    }
    if (typeof node !== "object") return;
    if ("queryChunks" in node) walk(node.queryChunks);
    if ("value" in node) values.push((node as any).value);
    if ("expr" in node) walk((node as any).expr);
    if ("conditions" in node) walk((node as any).conditions);
  };
  walk(whereArg);
  return values;
};

const makeSelectChain = (): any => {
  let _from: any = null;
  let _whereValues: unknown[] = [];
  const chain: any = {
    from: (t: any) => {
      _from = t;
      return chain;
    },
    where: (cond: any) => {
      _whereValues = extractWhereValues(cond);
      return chain;
    },
    orderBy: () => chain,
    limit: async () => {
      // For createPlaceholderSecrets existence probe: filter by name.
      if (tableLooksLike(_from) === "workflow_secrets" && _activeRepoId) {
        const existing = _existingNamesByRepo.get(_activeRepoId) ?? new Set();
        // The probe encodes (repoId, name) into the where clause.
        // Find the first value that matches a known name.
        for (const v of _whereValues) {
          if (typeof v === "string" && existing.has(v)) {
            return [{ id: `mock-id-${v}` }];
          }
        }
        return [];
      }
      return [];
    },
    then: (resolve: (v: any) => void) => {
      // Non-limited select: importSecretsForRepo's snapshot query +
      // the route's full-list query. Return every existing row for the
      // active repo.
      if (tableLooksLike(_from) === "workflow_secrets" && _activeRepoId) {
        const existing = Array.from(
          _existingNamesByRepo.get(_activeRepoId) ?? new Set()
        ).map((name) => ({ id: `mock-id-${name}`, name }));
        return resolve(existing);
      }
      resolve(_nextSelectRows);
    },
  };
  return chain;
};

const _fakeDb = {
  db: {
    select: () => makeSelectChain(),
    insert: (t: any) => {
      _lastInsertTable = t;
      return {
        values: (vals: any) => ({
          then: (resolve: (v: any) => void) => {
            _insertedRows.push({ table: tableLooksLike(t), values: vals });
            // Track the new row in the existing-rows map so a subsequent
            // probe for the same name returns it.
            if (
              tableLooksLike(t) === "workflow_secrets" &&
              typeof vals?.repositoryId === "string" &&
              typeof vals?.name === "string"
            ) {
              const set =
                _existingNamesByRepo.get(vals.repositoryId) ?? new Set<string>();
              set.add(vals.name);
              _existingNamesByRepo.set(vals.repositoryId, set);
            }
            resolve(undefined);
          },
        }),
      };
    },
    update: () => ({ set: () => ({ where: () => Promise.resolve() }) }),
    delete: () => ({ where: () => Promise.resolve() }),
  },
  getDb: () => _fakeDb.db,
};

mock.module("../db", () => ({ ..._real_db, ..._fakeDb }));
mock.module("../lib/notify", () => ({
  ..._real_notify,
  notify: async () => {},
  notifyMany: async () => {},
  audit: async () => {},
}));

afterAll(() => {
  // Restore master key
  if (_prevWfKey === undefined) {
    delete process.env.WORKFLOW_SECRETS_KEY;
  } else {
    process.env.WORKFLOW_SECRETS_KEY = _prevWfKey;
  }
  // Clear K1-style per-file state so it doesn't bleed into other tests.
  _nextSelectRows = [];
  _insertedRows = [];
  _existingNamesByRepo = new Map();
  _activeRepoId = null;
  _lastInsertTable = null;
  // Best-effort module restore.
  mock.module("../db", () => _real_db);
  mock.module("../lib/notify", () => _real_notify);
});

beforeEach(() => {
  _nextSelectRows = [];
  _insertedRows = [];
  _existingNamesByRepo = new Map();
  _activeRepoId = null;
  _lastInsertTable = null;
});

// ─── Tests: listGithubSecretNames ──────────────────────────────────────────

describe("listGithubSecretNames", () => {
  it("returns parsed array on a 200 mock", async () => {
    const { listGithubSecretNames } = await import("../lib/github-secrets-import");
    const fakeFetch: any = async (url: string, _init: any) => {
      expect(url).toContain(
        "/repos/octocat/Hello-World/actions/secrets?per_page=30&page=1"
      );
      return {
        ok: true,
        status: 200,
        json: async () => ({
          total_count: 2,
          secrets: [
            {
              name: "STRIPE_API_KEY",
              created_at: "2026-01-01T00:00:00Z",
              updated_at: "2026-01-01T00:00:00Z",
            },
            {
              name: "DATABASE_URL",
              created_at: "2026-02-01T00:00:00Z",
              updated_at: "2026-02-02T00:00:00Z",
            },
          ],
        }),
      };
    };
    const out = await listGithubSecretNames({
      owner: "octocat",
      repo: "Hello-World",
      githubToken: "ghp_test",
      fetchImpl: fakeFetch,
    });
    expect(out).toHaveLength(2);
    expect(out[0].name).toBe("STRIPE_API_KEY");
    expect(out[1].name).toBe("DATABASE_URL");
  });

  it("sends Authorization: Bearer header", async () => {
    const { listGithubSecretNames } = await import("../lib/github-secrets-import");
    let seenAuth: string | undefined;
    const fakeFetch: any = async (_url: string, init: any) => {
      seenAuth = init?.headers?.Authorization;
      return {
        ok: true,
        json: async () => ({ total_count: 0, secrets: [] }),
      };
    };
    await listGithubSecretNames({
      owner: "o",
      repo: "r",
      githubToken: "ghp_abc",
      fetchImpl: fakeFetch,
    });
    expect(seenAuth).toBe("Bearer ghp_abc");
  });

  it("returns [] on 401 (never throws)", async () => {
    const { listGithubSecretNames } = await import("../lib/github-secrets-import");
    const fakeFetch: any = async () => ({
      ok: false,
      status: 401,
      json: async () => ({ message: "Bad credentials" }),
    });
    const out = await listGithubSecretNames({
      owner: "o",
      repo: "r",
      githubToken: "ghp_x",
      fetchImpl: fakeFetch,
    });
    expect(out).toEqual([]);
  });

  it("returns [] on 404 (never throws)", async () => {
    const { listGithubSecretNames } = await import("../lib/github-secrets-import");
    const fakeFetch: any = async () => ({ ok: false, status: 404, json: async () => ({}) });
    const out = await listGithubSecretNames({
      owner: "o",
      repo: "r",
      githubToken: "ghp_x",
      fetchImpl: fakeFetch,
    });
    expect(out).toEqual([]);
  });

  it("returns [] on network error (never throws)", async () => {
    const { listGithubSecretNames } = await import("../lib/github-secrets-import");
    const fakeFetch: any = async () => {
      throw new Error("ECONNREFUSED");
    };
    const out = await listGithubSecretNames({
      owner: "o",
      repo: "r",
      githubToken: "ghp_x",
      fetchImpl: fakeFetch,
    });
    expect(out).toEqual([]);
  });

  it("paginates when total_count > 30", async () => {
    const { listGithubSecretNames } = await import("../lib/github-secrets-import");
    // Page 1 returns 30 entries (the full per_page batch); the helper
    // keeps going until either total_count is reached or the page
    // is smaller than per_page.
    const page1 = Array.from({ length: 30 }, (_, i) => ({
      name: `S${i.toString().padStart(2, "0")}`,
      created_at: "2026-01-01T00:00:00Z",
      updated_at: "2026-01-01T00:00:00Z",
    }));
    const page2 = [
      {
        name: "S30",
        created_at: "2026-01-01T00:00:00Z",
        updated_at: "2026-01-01T00:00:00Z",
      },
    ];
    let calls = 0;
    const fakeFetch: any = async (url: string) => {
      calls++;
      if (url.includes("page=1")) {
        return {
          ok: true,
          json: async () => ({ total_count: 31, secrets: page1 }),
        };
      }
      return {
        ok: true,
        json: async () => ({ total_count: 31, secrets: page2 }),
      };
    };
    const out = await listGithubSecretNames({
      owner: "o",
      repo: "r",
      githubToken: "ghp_x",
      fetchImpl: fakeFetch,
    });
    expect(calls).toBe(2);
    expect(out).toHaveLength(31);
    expect(out[30].name).toBe("S30");
  });

  it("returns [] when token is missing", async () => {
    const { listGithubSecretNames } = await import("../lib/github-secrets-import");
    const fakeFetch: any = async () => {
      throw new Error("should not be called");
    };
    const out = await listGithubSecretNames({
      owner: "o",
      repo: "r",
      githubToken: "",
      fetchImpl: fakeFetch,
    });
    expect(out).toEqual([]);
  });
});

// ─── Tests: createPlaceholderSecrets ───────────────────────────────────────

describe("createPlaceholderSecrets", () => {
  it("inserts new rows + reports created count", async () => {
    _activeRepoId = "repo-1";
    const { createPlaceholderSecrets } = await import("../lib/github-secrets-import");
    const out = await createPlaceholderSecrets({
      repositoryId: "repo-1",
      names: ["STRIPE_API_KEY", "DATABASE_URL"],
      createdByUserId: "user-1",
    });
    expect(out.created).toBe(2);
    expect(out.skippedExisting).toBe(0);
    // Both rows should have been inserted via db.insert(workflowSecrets).
    expect(_insertedRows.length).toBe(2);
    expect(_insertedRows.every((r) => r.table === "workflow_secrets")).toBe(true);
    expect(_insertedRows[0].values.name).toBe("STRIPE_API_KEY");
    expect(_insertedRows[0].values.repositoryId).toBe("repo-1");
    // encryptedValue should be a non-empty base64 string (encryption of "")
    expect(typeof _insertedRows[0].values.encryptedValue).toBe("string");
    expect(_insertedRows[0].values.encryptedValue.length).toBeGreaterThan(0);
  });

  it("skips names that already exist for the target repo", async () => {
    _activeRepoId = "repo-2";
    _existingNamesByRepo.set("repo-2", new Set(["EXISTING_KEY"]));
    const { createPlaceholderSecrets } = await import("../lib/github-secrets-import");
    const out = await createPlaceholderSecrets({
      repositoryId: "repo-2",
      names: ["EXISTING_KEY", "NEW_KEY"],
      createdByUserId: "user-1",
    });
    expect(out.created).toBe(1);
    expect(out.skippedExisting).toBe(1);
    // Only the new key should have been inserted.
    expect(_insertedRows.length).toBe(1);
    expect(_insertedRows[0].values.name).toBe("NEW_KEY");
  });

  it("returns 0/0 on empty names array", async () => {
    const { createPlaceholderSecrets } = await import("../lib/github-secrets-import");
    const out = await createPlaceholderSecrets({
      repositoryId: "repo-x",
      names: [],
      createdByUserId: "u",
    });
    expect(out).toEqual({ created: 0, skippedExisting: 0 });
  });

  it("returns 0/0 on missing repositoryId", async () => {
    const { createPlaceholderSecrets } = await import("../lib/github-secrets-import");
    const out = await createPlaceholderSecrets({
      repositoryId: "",
      names: ["X"],
      createdByUserId: "u",
    });
    expect(out).toEqual({ created: 0, skippedExisting: 0 });
  });

  it("returns 0/0 when master key is missing (degrades gracefully)", async () => {
    const stash = process.env.WORKFLOW_SECRETS_KEY;
    delete process.env.WORKFLOW_SECRETS_KEY;
    try {
      const { createPlaceholderSecrets } = await import(
        "../lib/github-secrets-import"
      );
      const out = await createPlaceholderSecrets({
        repositoryId: "repo-3",
        names: ["X"],
        createdByUserId: "u",
      });
      expect(out).toEqual({ created: 0, skippedExisting: 0 });
    } finally {
      process.env.WORKFLOW_SECRETS_KEY = stash;
    }
  });
});

// ─── Tests: importSecretsForRepo end-to-end ────────────────────────────────

describe("importSecretsForRepo (end-to-end)", () => {
  it("happy path: lists names + inserts placeholders + returns status array", async () => {
    _activeRepoId = "repo-e2e";
    const { importSecretsForRepo } = await import("../lib/github-secrets-import");
    const fakeFetch: any = async () => ({
      ok: true,
      json: async () => ({
        total_count: 2,
        secrets: [
          { name: "API_KEY", created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z" },
          { name: "DEPLOY_TOKEN", created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z" },
        ],
      }),
    });
    const out = await importSecretsForRepo({
      githubOwner: "octocat",
      githubRepo: "Hello-World",
      githubToken: "ghp_test",
      gluecronRepositoryId: "repo-e2e",
      importedByUserId: "user-1",
      fetchImpl: fakeFetch,
    });
    expect(out.imported).toHaveLength(2);
    expect(out.imported.map((r) => r.name).sort()).toEqual([
      "API_KEY",
      "DEPLOY_TOKEN",
    ]);
    expect(out.imported.every((r) => r.status === "placeholder_created")).toBe(
      true
    );
    expect(out.errors).toEqual([]);
  });

  it("returns empty imported + no error when GitHub reports zero secrets", async () => {
    const { importSecretsForRepo } = await import("../lib/github-secrets-import");
    const fakeFetch: any = async () => ({
      ok: true,
      json: async () => ({ total_count: 0, secrets: [] }),
    });
    const out = await importSecretsForRepo({
      githubOwner: "o",
      githubRepo: "r",
      githubToken: "ghp_x",
      gluecronRepositoryId: "repo-x",
      importedByUserId: "user-1",
      fetchImpl: fakeFetch,
    });
    expect(out.imported).toEqual([]);
  });

  it("reports no_github_token when token is empty", async () => {
    const { importSecretsForRepo } = await import("../lib/github-secrets-import");
    const fakeFetch: any = async () => ({
      ok: true,
      json: async () => ({ total_count: 0, secrets: [] }),
    });
    const out = await importSecretsForRepo({
      githubOwner: "o",
      githubRepo: "r",
      githubToken: "",
      gluecronRepositoryId: "repo-x",
      importedByUserId: "u",
      fetchImpl: fakeFetch,
    });
    expect(out.imported).toEqual([]);
    expect(out.errors).toContain("no_github_token");
  });
});

// ─── Tests: route auth ─────────────────────────────────────────────────────

describe("import-secrets route — auth gate", () => {
  it("GET /:owner/:repo/import/secrets unauthenticated → 302 /login", async () => {
    let mod: any;
    try {
      mod = await import("../routes/import-secrets");
    } catch {
      // JSX runtime resolution flake in this bun env — degrade gracefully.
      return;
    }
    const res = await mod.default.request("/octocat/hello/import/secrets");
    // requireAuth redirects to /login; resolveRepoAccess may run first on
    // some routes but the auth middleware sits in front for this one.
    expect(res.status).toBe(302);
    expect(res.headers.get("location") || "").toMatch(/^\/login/);
  });

  it("POST /:owner/:repo/import/secrets/X unauthenticated → 302 /login", async () => {
    let mod: any;
    try {
      mod = await import("../routes/import-secrets");
    } catch {
      return;
    }
    const res = await mod.default.request(
      "/octocat/hello/import/secrets/MY_SECRET",
      {
        method: "POST",
        body: new URLSearchParams({ value: "v" }),
        headers: { "content-type": "application/x-www-form-urlencoded" },
      }
    );
    expect(res.status).toBe(302);
    expect(res.headers.get("location") || "").toMatch(/^\/login/);
  });

  it("POST /:owner/:repo/import/secrets/done unauthenticated → 302 /login", async () => {
    let mod: any;
    try {
      mod = await import("../routes/import-secrets");
    } catch {
      return;
    }
    const res = await mod.default.request(
      "/octocat/hello/import/secrets/done",
      {
        method: "POST",
        body: new URLSearchParams({}),
        headers: { "content-type": "application/x-www-form-urlencoded" },
      }
    );
    expect(res.status).toBe(302);
    expect(res.headers.get("location") || "").toMatch(/^\/login/);
  });
});