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
admin-integrations.test.ts11.2 KB · 319 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
/**
 * /admin/integrations — DB-stored platform integration secrets.
 *
 * Coverage:
 *   1. GET /admin/integrations without auth → 302 to /login
 *   2. GET /admin/integrations with non-admin session → 403
 *   3. getConfigValue() returns DB value when set, env fallback when not,
 *      empty string when neither is set
 *   4. setConfigValue() upserts + writes an audit row
 *   5. Masked values aren't written back as the real value (re-submitting
 *      the rendered form doesn't overwrite the existing secret with `••••••`)
 *   6. maskSecret() formats secrets as `prefix_••••••XY`
 *   7. INTEGRATION_FIELDS exposes the documented surface
 *
 * The DB-backed tests are gated on `DATABASE_URL` so the suite stays green
 * on machines without Postgres (mirroring connect-claude.test.ts).
 */

import { describe, it, expect, beforeEach } from "bun:test";
import app from "../app";
import {
  getConfigValue,
  setConfigValue,
  maskSecret,
  isMaskedValue,
  INTEGRATION_FIELDS,
  __resetCache,
} from "../lib/system-config";

const HAS_DB = Boolean(process.env.DATABASE_URL);

// ---------------------------------------------------------------------------
// 1. Auth gating
// ---------------------------------------------------------------------------

describe("admin-integrations — auth gating", () => {
  it("GET /admin/integrations without a session → 302 /login", async () => {
    const res = await app.request("/admin/integrations");
    expect(res.status).toBe(302);
    expect(res.headers.get("location") || "").toContain("/login");
  });

  it("POST /admin/integrations without a session → 302 /login", async () => {
    const res = await app.request("/admin/integrations", {
      method: "POST",
      body: new URLSearchParams({ ANTHROPIC_API_KEY: "sk-test" }),
      headers: { "content-type": "application/x-www-form-urlencoded" },
    });
    expect(res.status).toBe(302);
    expect(res.headers.get("location") || "").toContain("/login");
  });
});

// ---------------------------------------------------------------------------
// 2. Non-admin → 403  (DB-backed: needs a real user + session)
// ---------------------------------------------------------------------------

describe.skipIf(!HAS_DB)("admin-integrations — non-admin gate", () => {
  it("GET /admin/integrations with a non-admin session → 403", async () => {
    const { db } = await import("../db");
    const { users, sessions } = await import("../db/schema");
    const { randomBytes } = await import("crypto");

    // Make a throwaway user — no site_admins row → non-admin by definition.
    const username = `integ-nonadmin-${randomBytes(4).toString("hex")}`;
    const [u] = await db
      .insert(users)
      .values({
        username,
        email: `${username}@test.local`,
        passwordHash: "x",
      })
      .returning({ id: users.id });

    const token = randomBytes(32).toString("hex");
    await db.insert(sessions).values({
      userId: u!.id,
      token,
      expiresAt: new Date(Date.now() + 60_000),
    });

    const res = await app.request("/admin/integrations", {
      headers: { cookie: `session=${token}` },
    });
    expect(res.status).toBe(403);
  });
});

// ---------------------------------------------------------------------------
// 3. getConfigValue — DB / env / empty fallback ladder
// ---------------------------------------------------------------------------

describe("system-config — getConfigValue fallback ladder", () => {
  beforeEach(() => {
    __resetCache();
  });

  it("returns empty string when neither DB nor env is set", async () => {
    delete process.env.__SYSCFG_NOPE__;
    const v = await getConfigValue("__SYSCFG_NOPE__", "__SYSCFG_NOPE__");
    expect(v).toBe("");
  });

  it("returns env fallback when DB has no row", async () => {
    const key = "__SYSCFG_ENV_ONLY__";
    process.env[key] = "from-env";
    __resetCache();
    const v = await getConfigValue(key, key);
    expect(v).toBe("from-env");
    delete process.env[key];
  });

  // DB-only assertion — must have Postgres available.
  it.skipIf(!HAS_DB)("returns DB value when both DB and env are set", async () => {
    const key = `__SYSCFG_DB_${Date.now()}__`;
    process.env[key] = "from-env";
    try {
      await setConfigValue(key, "from-db", null);
      __resetCache();
      const v = await getConfigValue(key, key);
      expect(v).toBe("from-db");
    } finally {
      const { db } = await import("../db");
      const { systemConfig } = await import("../db/schema");
      const { eq } = await import("drizzle-orm");
      await db.delete(systemConfig).where(eq(systemConfig.key, key));
      delete process.env[key];
    }
  });
});

// ---------------------------------------------------------------------------
// 4. setConfigValue — upsert + audit
// ---------------------------------------------------------------------------

describe.skipIf(!HAS_DB)("system-config — setConfigValue upserts + audits", () => {
  it("writes a system_config row and an audit_log entry", async () => {
    const { db } = await import("../db");
    const { systemConfig, users, auditLog } = await import("../db/schema");
    const { audit } = await import("../lib/notify");
    const { eq, desc } = await import("drizzle-orm");
    const { randomBytes } = await import("crypto");

    const username = `integ-setval-${randomBytes(4).toString("hex")}`;
    const [u] = await db
      .insert(users)
      .values({
        username,
        email: `${username}@test.local`,
        passwordHash: "x",
      })
      .returning({ id: users.id });

    const key = `__SYSCFG_AUDIT_${Date.now()}__`;
    try {
      await setConfigValue(key, "secret-value", u!.id);

      // Row landed
      const [row] = await db
        .select()
        .from(systemConfig)
        .where(eq(systemConfig.key, key))
        .limit(1);
      expect(row).toBeTruthy();
      expect(row!.value).toBe("secret-value");
      expect(row!.updatedByUserId).toBe(u!.id);

      // Mimic what the route handler does — record the key but never the
      // value. We assert the audit row appears with action+target+key in
      // metadata.
      await audit({
        userId: u!.id,
        action: "admin.integrations.save",
        targetType: "system_config",
        targetId: key,
        metadata: { key, hadValue: false, hasValue: true },
      });

      const auditRows = await db
        .select()
        .from(auditLog)
        .where(eq(auditLog.targetId, key))
        .orderBy(desc(auditLog.createdAt))
        .limit(1);
      expect(auditRows.length).toBe(1);
      expect(auditRows[0]!.action).toBe("admin.integrations.save");
      // Critical: the value itself must NOT appear in the audit metadata.
      const meta = auditRows[0]!.metadata
        ? JSON.parse(auditRows[0]!.metadata)
        : {};
      expect(JSON.stringify(meta)).not.toContain("secret-value");
      expect(meta.key).toBe(key);
    } finally {
      await db.delete(systemConfig).where(eq(systemConfig.key, key));
      // auditLog rows + users row cleaned up cascade-style by FK in dev DBs;
      // explicit cleanup skipped here to keep the test small.
    }
  });
});

// ---------------------------------------------------------------------------
// 5. Masked value semantics — re-submit must not overwrite real secret
// ---------------------------------------------------------------------------

describe("system-config — mask helpers", () => {
  it("maskSecret returns empty for empty/nullish", () => {
    expect(maskSecret("")).toBe("");
    expect(maskSecret(null)).toBe("");
    expect(maskSecret(undefined)).toBe("");
  });

  it("maskSecret keeps a short prefix + last 2 chars for long secrets", () => {
    const m = maskSecret("re_abc123xyz789QR");
    expect(m.startsWith("re_")).toBe(true);
    expect(m).toContain("••••••");
    expect(m.endsWith("QR")).toBe(true);
    expect(m).not.toContain("abc123");
  });

  it("isMaskedValue detects strings that look like the rendered mask", () => {
    expect(isMaskedValue("re_••••••QR")).toBe(true);
    expect(isMaskedValue("sk-ant-real-token-here")).toBe(false);
    expect(isMaskedValue("")).toBe(false);
    expect(isMaskedValue(null)).toBe(false);
  });

  // Round-trip: a value masked, then submitted back unchanged, must NOT
  // overwrite the underlying secret when the route's POST handler runs.
  it.skipIf(!HAS_DB)(
    "re-submitting a masked value preserves the real secret",
    async () => {
      const { db } = await import("../db");
      const { systemConfig } = await import("../db/schema");
      const { eq } = await import("drizzle-orm");
      const key = `__SYSCFG_MASK_${Date.now()}__`;

      try {
        // Seed the real secret.
        await setConfigValue(key, "real-secret-xyz", null);
        const before = await getConfigValue(key, key);
        expect(before).toBe("real-secret-xyz");

        // Render its mask, then simulate the form POST handler's gate.
        const masked = maskSecret(before);
        expect(isMaskedValue(masked)).toBe(true);

        // If this gate were missing, the value would now be `re_••••••yz`.
        if (!isMaskedValue(masked)) {
          await setConfigValue(key, masked, null);
        }

        // The real secret should still be there.
        const after = await getConfigValue(key, key);
        expect(after).toBe("real-secret-xyz");
      } finally {
        await db.delete(systemConfig).where(eq(systemConfig.key, key));
      }
    }
  );
});

// ---------------------------------------------------------------------------
// 6. Surface — INTEGRATION_FIELDS exposes the documented list
// ---------------------------------------------------------------------------

describe("system-config — INTEGRATION_FIELDS surface", () => {
  it("includes every key the spec calls out", () => {
    const keys = INTEGRATION_FIELDS.map((f) => f.key);
    for (const expected of [
      "ANTHROPIC_API_KEY",
      "RESEND_API_KEY",
      "EMAIL_FROM",
      "GITHUB_TOKEN",
      "GATETEST_URL",
      "GATETEST_API_KEY",
      "DEPLOY_EVENT_TOKEN",
      "VAPRON_DEPLOY_URL",
      "VAPRON_HMAC_SECRET",
      "VAPRON_EVENT_TOKEN",
    ]) {
      expect(keys).toContain(expected);
    }
  });

  it("does NOT expose env-only keys (chicken-and-egg / infra)", () => {
    const keys = INTEGRATION_FIELDS.map((f) => f.key);
    // DATABASE_URL / BUILD_SHA / PORT / GIT_REPOS_PATH stay env-only —
    // changing them at runtime would break the running process. APP_BASE_URL
    // and SELF_HOST_REPO are intentionally surfaced so operators can fix
    // OAuth redirect_uri_mismatch + the self-host repo lookup without SSH.
    for (const forbidden of [
      "DATABASE_URL",
      "BUILD_SHA",
      "BUILD_TIME",
      "PORT",
      "GIT_REPOS_PATH",
    ]) {
      expect(keys).not.toContain(forbidden);
    }
  });

  it("tags each field with a group + helper text", () => {
    for (const f of INTEGRATION_FIELDS) {
      expect(typeof f.label).toBe("string");
      expect(f.label.length).toBeGreaterThan(0);
      expect(typeof f.helper).toBe("string");
      expect(f.helper.length).toBeGreaterThan(0);
      expect([
        "platform",
        "ai",
        "email",
        "scm",
        "security",
        "observability",
        "webhook",
      ]).toContain(f.group);
    }
  });
});