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
environments.test.ts9.5 KB · 297 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
/**
 * Tests for Block C4 — environments + deployment approvals.
 *
 * Unit tests exercise the pure-function glob matcher + the single-approver
 * semantics of computeApprovalState. Route-level tests verify that settings
 * CRUD and approve/reject endpoints are properly guarded — they tolerate
 * DB-less test environments (302/303/307/404/503) rather than asserting
 * a single happy-path status.
 */

import { describe, it, expect } from "bun:test";
import app from "../app";
import {
  matchGlob,
  reduceApprovalState,
  reviewerIdsOf,
  allowedBranchesOf,
  latestApprovalAt,
  computeReadyAfter,
  releaseExpiredWaitTimers,
} from "../lib/environments";
import type { Environment, DeploymentApproval } from "../db/schema";

const envFixture = (overrides: Partial<Environment> = {}): Environment =>
  ({
    id: "env-1",
    repositoryId: "repo-1",
    name: "production",
    requireApproval: true,
    reviewers: "[]",
    waitTimerMinutes: 0,
    allowedBranches: "[]",
    createdAt: new Date(),
    updatedAt: new Date(),
    ...overrides,
  }) as Environment;

describe("matchGlob", () => {
  it("matches exact literals", () => {
    expect(matchGlob("main", "main")).toBe(true);
  });

  it("does not match mismatched literals", () => {
    expect(matchGlob("main", "release/*")).toBe(false);
  });

  it("supports single-segment * wildcards", () => {
    expect(matchGlob("release/1.0", "release/*")).toBe(true);
    expect(matchGlob("release/foo/bar", "release/*")).toBe(false);
  });

  it("supports ** for any path", () => {
    expect(matchGlob("release/foo/bar", "release/**")).toBe(true);
    expect(matchGlob("main", "**")).toBe(true);
  });

  it("strips refs/heads/ prefix on both sides", () => {
    expect(matchGlob("refs/heads/main", "main")).toBe(true);
    expect(matchGlob("main", "refs/heads/main")).toBe(true);
  });

  it("does not match unrelated branches", () => {
    expect(matchGlob("feature/x", "release/*")).toBe(false);
    expect(matchGlob("develop", "main")).toBe(false);
  });
});

describe("reviewerIdsOf / allowedBranchesOf", () => {
  it("parses valid JSON arrays", () => {
    const env = envFixture({
      reviewers: JSON.stringify(["u1", "u2"]),
      allowedBranches: JSON.stringify(["main", "release/*"]),
    });
    expect(reviewerIdsOf(env)).toEqual(["u1", "u2"]);
    expect(allowedBranchesOf(env)).toEqual(["main", "release/*"]);
  });

  it("returns [] for empty/invalid", () => {
    expect(reviewerIdsOf(envFixture({ reviewers: "" }))).toEqual([]);
    expect(reviewerIdsOf(envFixture({ reviewers: "not-json" }))).toEqual([]);
    expect(allowedBranchesOf(envFixture({ allowedBranches: "[]" }))).toEqual([]);
  });
});

const mkApproval = (
  decision: "approved" | "rejected",
  userId = "u1"
): DeploymentApproval =>
  ({
    id: `a-${Math.random()}`,
    deploymentId: "d1",
    userId,
    decision,
    comment: null,
    createdAt: new Date(),
  }) as DeploymentApproval;

describe("reduceApprovalState (single-approver semantics)", () => {
  it("approved=true when any approval exists and no rejection", () => {
    const state = reduceApprovalState([mkApproval("approved")]);
    expect(state.approved).toBe(true);
    expect(state.rejected).toBe(false);
    expect(state.decided.length).toBe(1);
  });

  it("rejected=true when any rejection exists (overrides approval)", () => {
    const state = reduceApprovalState([
      mkApproval("approved", "u1"),
      mkApproval("rejected", "u2"),
    ]);
    expect(state.rejected).toBe(true);
    expect(state.approved).toBe(false);
  });

  it("neither approved nor rejected when no decisions", () => {
    const state = reduceApprovalState([]);
    expect(state.approved).toBe(false);
    expect(state.rejected).toBe(false);
  });
});

describe("environments routes — unauthed guards", () => {
  const ok = [301, 302, 303, 307, 401, 404, 503];

  it("GET /:owner/:repo/settings/environments redirects to login when unauthed", async () => {
    const res = await app.request("/alice/project/settings/environments");
    expect(ok).toContain(res.status);
  });

  it("POST /:owner/:repo/settings/environments requires auth", async () => {
    const res = await app.request("/alice/project/settings/environments", {
      method: "POST",
      headers: { "content-type": "application/x-www-form-urlencoded" },
      body: "name=staging",
    });
    expect(ok).toContain(res.status);
  });

  it("POST /:owner/:repo/settings/environments/:envId requires auth", async () => {
    const res = await app.request(
      "/alice/project/settings/environments/env-1",
      {
        method: "POST",
        headers: { "content-type": "application/x-www-form-urlencoded" },
        body: "",
      }
    );
    expect(ok).toContain(res.status);
  });

  it("POST /:owner/:repo/settings/environments/:envId/delete requires auth", async () => {
    const res = await app.request(
      "/alice/project/settings/environments/env-1/delete",
      {
        method: "POST",
        headers: { "content-type": "application/x-www-form-urlencoded" },
        body: "",
      }
    );
    expect(ok).toContain(res.status);
  });

  it("POST /:owner/:repo/deployments/:id/approve requires auth", async () => {
    const res = await app.request(
      "/alice/project/deployments/dep-1/approve",
      {
        method: "POST",
        headers: { "content-type": "application/x-www-form-urlencoded" },
        body: "",
      }
    );
    expect(ok).toContain(res.status);
  });

  it("POST /:owner/:repo/deployments/:id/reject requires auth", async () => {
    const res = await app.request(
      "/alice/project/deployments/dep-1/reject",
      {
        method: "POST",
        headers: { "content-type": "application/x-www-form-urlencoded" },
        body: "",
      }
    );
    expect(ok).toContain(res.status);
  });

  it("bearer auth with bogus token on settings POST returns 401", async () => {
    const res = await app.request("/alice/project/settings/environments", {
      method: "POST",
      headers: {
        "content-type": "application/x-www-form-urlencoded",
        authorization: "Bearer glct_definitely-not-valid",
      },
      body: "name=staging",
    });
    // 401 from requireAuth with invalid bearer; 404/503 tolerated pre-route.
    expect([401, 404, 503]).toContain(res.status);
  });
});

// ---------------------------------------------------------------------------
// Wait-timer enforcement (no longer a stub)
// ---------------------------------------------------------------------------

const mkApprovalAt = (
  decision: "approved" | "rejected",
  createdAt: Date,
  userId = "u1"
): DeploymentApproval =>
  ({
    id: `a-${Math.random()}`,
    deploymentId: "d1",
    userId,
    decision,
    comment: null,
    createdAt,
  }) as DeploymentApproval;

describe("latestApprovalAt", () => {
  it("returns null when there are no approvals", () => {
    expect(latestApprovalAt([])).toBeNull();
  });

  it("ignores rejection timestamps", () => {
    const t1 = new Date("2026-01-01T00:00:00Z");
    expect(latestApprovalAt([mkApprovalAt("rejected", t1)])).toBeNull();
  });

  it("returns the most recent approval timestamp", () => {
    const t1 = new Date("2026-01-01T00:00:00Z");
    const t2 = new Date("2026-01-02T00:00:00Z");
    const t3 = new Date("2026-01-03T00:00:00Z");
    const out = latestApprovalAt([
      mkApprovalAt("approved", t2, "u1"),
      mkApprovalAt("approved", t3, "u2"),
      mkApprovalAt("approved", t1, "u3"),
    ]);
    expect(out?.toISOString()).toBe(t3.toISOString());
  });

  it("tolerates a malformed createdAt", () => {
    const out = latestApprovalAt([
      {
        ...mkApprovalAt("approved", new Date("2026-01-01T00:00:00Z")),
        createdAt: new Date("not-a-real-date"),
      } as any,
    ]);
    expect(out).toBeNull();
  });
});

describe("computeReadyAfter", () => {
  it("returns null when waitTimerMinutes <= 0", () => {
    const env = envFixture({ waitTimerMinutes: 0 });
    const t = new Date("2026-01-01T00:00:00Z");
    expect(computeReadyAfter(env, [mkApprovalAt("approved", t)])).toBeNull();
  });

  it("returns null when there are no approvals (timer hasn't started)", () => {
    const env = envFixture({ waitTimerMinutes: 30 });
    expect(computeReadyAfter(env, [])).toBeNull();
  });

  it("adds waitTimerMinutes to the latest approval timestamp", () => {
    const env = envFixture({ waitTimerMinutes: 30 });
    const t = new Date("2026-01-01T12:00:00Z");
    const ready = computeReadyAfter(env, [mkApprovalAt("approved", t)]);
    expect(ready?.toISOString()).toBe("2026-01-01T12:30:00.000Z");
  });

  it("uses the latest approval, not the earliest", () => {
    const env = envFixture({ waitTimerMinutes: 60 });
    const t1 = new Date("2026-01-01T00:00:00Z");
    const t2 = new Date("2026-01-01T01:00:00Z");
    const ready = computeReadyAfter(env, [
      mkApprovalAt("approved", t1, "u1"),
      mkApprovalAt("approved", t2, "u2"),
    ]);
    expect(ready?.toISOString()).toBe("2026-01-01T02:00:00.000Z");
  });

  it("returns null on a malformed waitTimerMinutes value", () => {
    const env = envFixture({ waitTimerMinutes: NaN as any });
    const t = new Date("2026-01-01T00:00:00Z");
    expect(computeReadyAfter(env, [mkApprovalAt("approved", t)])).toBeNull();
  });
});

describe("releaseExpiredWaitTimers — fail-open", () => {
  it("returns 0 (not throws) when DB is unavailable / no rows match", async () => {
    // No live DB → drizzle will throw inside the helper, which catches and
    // returns 0. Either way the test asserts the never-throw contract.
    const out = await releaseExpiredWaitTimers(new Date());
    expect(typeof out).toBe("number");
    expect(out).toBeGreaterThanOrEqual(0);
  });
});