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
push-policy.ts5.7 KB · 166 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
/**
 * Push-policy enforcement — runs at the HTTP layer before git-receive-pack
 * actually accepts the pack.
 *
 * Until now Gluecron's protected-tag and ruleset surfaces were advisory:
 * `src/hooks/post-receive.ts` would log audit entries after the push had
 * already landed. This module flips them to truly blocking by evaluating
 * a list of refs at receive time and returning {allowed:false, violations}
 * so the route can short-circuit with a 403.
 *
 * Refs evaluable from name+sha alone (no pack inspection):
 *   - protected_tags                  — tag pushes must come from owner/bypass
 *   - ruleset.tag_name_pattern        — disallow tag names matching pattern
 *   - ruleset.branch_name_pattern     — disallow branch names matching pattern
 *   - ruleset.forbid_force_push       — heuristic: detected when oldSha was
 *                                       not the zero-SHA and newSha differs.
 *                                       True force-push detection requires a
 *                                       reachability check we don't run here;
 *                                       the existing `forcePush` boolean on
 *                                       PushContext is wired to false unless
 *                                       a smarter caller fills it in.
 *
 * Pure helpers + DB callers; never throws into the request path. On any
 * unexpected failure we return {allowed:true} (fail-open) to preserve the
 * existing no-policy behaviour rather than wedging legitimate pushes when
 * Postgres hiccups.
 */

import {
  matchProtectedTag,
  canBypassProtectedTag,
} from "./protected-tags";
import {
  listRulesetsForRepo,
  evaluatePush,
  type PushContext,
} from "./rulesets";

export type RefUpdate = {
  oldSha: string;
  newSha: string;
  refName: string;
};

export type PushPolicyArgs = {
  repositoryId: string;
  refs: RefUpdate[];
  pusherUserId: string | null;
};

export type PushPolicyResult = {
  allowed: boolean;
  violations: string[];
};

/** "0000000000000000000000000000000000000000" — 40 zeros. */
export const ZERO_SHA = "0".repeat(40);

const ALLOW: PushPolicyResult = { allowed: true, violations: [] };

/**
 * Classify a ref name into "branch" / "tag" for the ruleset evaluator.
 * Heads = branch, tags = tag, anything else (e.g. `refs/notes/*`) we treat
 * as a branch since the evaluator's tag-only rules will gracefully no-op.
 */
function refType(refName: string): "branch" | "tag" {
  return refName.startsWith("refs/tags/") ? "tag" : "branch";
}

/**
 * Evaluate every ref in `refs` against the repo's protected-tags + rulesets
 * and return the aggregated decision. Multiple violations across refs are
 * concatenated so the user sees every problem in one push attempt rather
 * than one-at-a-time.
 */
export async function evaluatePushPolicy(
  args: PushPolicyArgs
): Promise<PushPolicyResult> {
  const { repositoryId, refs, pusherUserId } = args;
  if (!repositoryId || !refs || refs.length === 0) return ALLOW;

  const violations: string[] = [];

  // Protected tags — runs once per ref, only fires for tag refs.
  for (const ref of refs) {
    if (!ref.refName.startsWith("refs/tags/")) continue;
    const tagName = ref.refName.slice("refs/tags/".length);
    let protectedRule: Awaited<ReturnType<typeof matchProtectedTag>> = null;
    try {
      protectedRule = await matchProtectedTag(repositoryId, tagName);
    } catch {
      protectedRule = null;
    }
    if (!protectedRule) continue;

    // Anonymous pusher → never bypasses. Authenticated pusher must be the
    // owner (or future tag-admin) for this repo.
    let canBypass = false;
    try {
      canBypass = await canBypassProtectedTag(repositoryId, pusherUserId);
    } catch {
      canBypass = false;
    }
    if (canBypass) continue;

    const action =
      ref.newSha === ZERO_SHA
        ? "delete"
        : ref.oldSha === ZERO_SHA
        ? "create"
        : "update";
    violations.push(
      `tag "${tagName}" is protected (pattern: ${protectedRule.pattern}); ${action} requires bypass`
    );
  }

  // Rulesets — single DB call, evaluator runs purely on names.
  let rulesets: Awaited<ReturnType<typeof listRulesetsForRepo>> = [];
  try {
    rulesets = await listRulesetsForRepo(repositoryId);
  } catch {
    rulesets = [];
  }

  if (rulesets && rulesets.length > 0) {
    for (const ref of refs) {
      const ctx: PushContext = {
        kind: "push",
        refType: refType(ref.refName),
        refName: ref.refName,
        commits: [],
        // forcePush is left false — true detection requires a reachability
        // check on the new commit, which is in the pack we haven't unpacked.
        forcePush: false,
      };
      let result;
      try {
        result = evaluatePush(rulesets, ctx);
      } catch {
        result = { allowed: true, violations: [] as Array<{ rulesetName: string; ruleType: string; message: string; enforcement: string }> };
      }
      if (!result.allowed && result.violations.length > 0) {
        for (const v of result.violations) {
          // Only "active" enforcement blocks; "evaluate" is dry-run.
          if (v.enforcement !== "active") continue;
          violations.push(
            `ruleset "${v.rulesetName}" rule ${v.ruleType}: ${v.message} (ref ${ref.refName})`
          );
        }
      }
    }
  }

  return violations.length === 0
    ? ALLOW
    : { allowed: false, violations };
}

/** Build a human-readable error body for the 403 response. */
export function formatPolicyError(violations: string[]): string {
  if (!violations || violations.length === 0) {
    return "Push rejected by Gluecron policy.";
  }
  const lines = violations.map((v) => ` - ${v}`);
  return `Push rejected by Gluecron policy:\n${lines.join("\n")}\n`;
}