Guides · Policies
Policy lifecycle
Write, validate, test, simulate, deploy and roll back policies — from the CLI, the SDKs or the API.
Policies are versioned. Every save creates an immutable version; only the deployed version of a policy is evaluated. A deployment is gated: the server re-runs the policy's tests and conflict analysis against the environment's effective policy set and refuses to deploy when they fail.
write ─▶ validate ─▶ test ─▶ simulate ─▶ deploy ─▶ (rollback)
offline offline server tests + conflicts re-run by the serverScopes#
A policy is scoped to the organization (default), a project or an environment:
scope: {"type": "org"}, {"type": "project", "projectId": …} or {"type": "environment", "environmentId": …}.
Policies of every scope that contains the request's environment are combined; a forbid at any scope wins.
Policy-as-code with the CLI#
gebsecure init creates gebsecure.yaml and a policies/ directory with a starter policy, its tests and a
simulation scenario:
policy "allow-read-actions" {
description "Agents may perform read-only actions"
effect permit
principal agent
action any
resource any
when action.category == "read"
}
policy "refunds-need-approval" {
description "Refunds up to 1000; above 100 need human approval"
effect permit
principal agent
action "stripe:refunds.create"
resource any
when has(context.amount) && context.amount <= 1000
require approval when context.amount > 100 {
approvers role "approver"
expires 4h
}
}Tests are requests with the expected decision:
# Tests for agent-baseline.gsl. Run with: gebsecure policies test
# Each test is a request evaluated against every policy in this directory, and the expected decision
# (ALLOW, DENY or APPROVAL_REQUIRED). Deployment is blocked when any test fails.
tests:
- name: read actions are allowed
request:
principal: { type: agent, id: agt_example }
action: github:repos.get
resource: github:repo/acme/website
expect: ALLOW
- name: small refunds are allowed
request:
principal: { type: agent, id: agt_example }
action: stripe:refunds.create
resource: stripe:charge/ch_123
context: { amount: 50 }
expect: ALLOW
- name: larger refunds need approval
request:
principal: { type: agent, id: agt_example }
action: stripe:refunds.create
resource: stripe:charge/ch_123
context: { amount: 500 }
expect: APPROVAL_REQUIRED
- name: refunds above the hard limit are denied
request:
principal: { type: agent, id: agt_example }
action: stripe:refunds.create
resource: stripe:charge/ch_123
context: { amount: 5000 }
expect: DENY
- name: destructive actions are denied by default
request:
principal: { type: agent, id: agt_example }
action: github:repos.delete
resource: github:repo/acme/website
expect: DENYThe CLI bundles the server's parser, validator, formatter and evaluation engine, so these steps work offline:
gebsecure policies validate # syntax, semantic checks and conflict analysis across the directory
gebsecure policies fmt --check # canonical formatting (exit 7 when files would change)
gebsecure policies test # every test against the whole local policy set
gebsecure policies diff # local files vs the server (exit 7 when they differ)
gebsecure deploy # local gate, plan with diffs, confirmation (--yes in CI), deploy
gebsecure policies versions <policy> # history; `gebsecure policies rollback <policy>` rolls backA simulation scenario evaluates requests against what is deployed — or, with --candidate, against your local
files as candidates — and fails on any expect mismatch:
# Simulation scenario. Run with: gebsecure simulate simulations/smoke.yaml
# Requests are evaluated against the policies deployed in the environment (or, with --local, against
# the policies directory). "expect" makes the command exit non-zero on a mismatch (for CI).
requests:
- label: agent reads a repository
principal: { type: agent, id: agt_example }
action: github:repos.get
resource: github:repo/acme/website
expect: ALLOW
- label: agent issues a large refund
principal: { type: agent, id: agt_example }
action: stripe:refunds.create
resource: stripe:charge/ch_123
context: { amount: 500 }
expect: APPROVAL_REQUIREDgebsecure simulate simulations/ # against the deployed policies
gebsecure simulate simulations/ --candidate --fail-on-change
gebsecure simulate simulations/ --local # fully offlineExit code 7 means a check failed (tests, simulation expectations, fmt --check/diff, or a deployment blocked
by the server). See the CLI reference and the
command reference.
Policy-as-code with an SDK#
The SDKs wrap the same lifecycle. This TypeScript example logs in, validates, saves a version, replaces the test
suite, gates on a simulation and deploys — a blocked deployment is a result (deployed: false), not an
exception:
import { GebSecure, SimulationFailedError, staticToken, unauthenticated, type PolicyTestCase } from '@gebsecure01/sdk';
const policyId = process.env.POLICY_ID!;
const environmentId = process.env.ENVIRONMENT_ID!;
const source = 'policy "support-read" { effect permit principal agent action "zendesk:tickets.read" resource any }';
const tests: PolicyTestCase[] = [
{ name: 'support agents read tickets', request: { principal: { type: 'agent', id: 'agt_support' }, action: 'zendesk:tickets.read', resource: 'zendesk:ticket/1' }, expect: 'ALLOW' },
{ name: 'no ticket deletion', request: { principal: { type: 'agent', id: 'agt_support' }, action: 'zendesk:tickets.delete', resource: 'zendesk:ticket/1' }, expect: 'DENY' },
];
// 1. Session login (no credentials yet). Keep `refreshToken` in your credential store; it rotates on refresh.
const session = await new GebSecure({ auth: unauthenticated() }).login({ email: process.env.GEBSECURE_EMAIL!, password: process.env.GEBSECURE_PASSWORD! });
const gs = new GebSecure({ auth: staticToken(session.accessToken) });
try {
// 2. Validate before saving.
const validation = await gs.validatePolicy(source);
if (!validation.ok) throw new Error(`Invalid policy: ${JSON.stringify(validation.diagnostics)}`);
// 3. Save a version and sync the test suite (PUT replaces it atomically).
const version = await gs.updatePolicy(policyId, { source, message: `CI ${new Date().toISOString()}` });
await gs.replacePolicyTests(policyId, tests);
// 4. Simulation gate: fail the job if any scenario mismatches.
try {
await gs.runSimulation({ environmentId, failOnMismatch: true, trigger: 'ci', scenarioSetId: process.env.SCENARIO_SET_ID!, policyOverrides: [{ policyId, versionId: version.versionId }] });
} catch (err) {
if (err instanceof SimulationFailedError) {
for (const r of err.run.results.filter((x) => x.passed === false)) console.error(`✗ ${r.label}: ${r.failures?.join('; ')}`);
process.exit(1);
}
throw err;
}
// 5. Deploy; failing tests or blocking conflicts come back as `deployed: false` (HTTP 412).
const deploy = await gs.deployPolicy(policyId, { versionId: version.versionId, comment: 'CI deploy' });
if (!deploy.deployed) {
console.error(`Deploy blocked: ${deploy.tests?.failed ?? 0} failing test(s), ${deploy.conflicts?.length ?? 0} conflict(s)`);
process.exit(1);
}
console.log(`Deployed version ${deploy.versionId} (${deploy.deploymentId})`);
} finally {
await gs.logout();
}The API#
| Step | Endpoint |
|---|---|
| Create (draft version 1) from source or a template | POST /v1/policies |
| Save a new version | PUT /v1/policies/{id} (source, or the AST from the visual builder) |
| Validate, lint and format | POST /v1/policies/validate |
| Read a version, diff two versions | GET /v1/policies/{id}/versions/{versionId}, GET /v1/policies/{id}/diff?from=&to= |
| Tests | POST /v1/policies/{id}/tests, PUT /v1/policies/{id}/tests (replace), DELETE …/tests/{testId}, POST …/tests/run |
| Simulate deployed vs candidate | POST /v1/policies/simulate; scenario runs: POST /v1/simulations/run |
| Conflicts | GET /v1/policies/conflicts |
| Deploy | POST /v1/policies/{id}/deploy ({versionId?, comment?}; 412 with the deploy report when blocked) |
| Roll back | POST /v1/policies/{id}/rollback (default: the previously deployed version) |
| History | GET /v1/policies/{id}/deployments |
| Archive | DELETE /v1/policies/{id} (stops enforcing) |
Deploying requires policies:deploy. An organization can additionally put policies.deploy behind the
two-person rule (PUT /v1/governance/admin-policies): the first call fails with approval_required until a
second administrator approves.
Simulation in CI#
POST /v1/simulations/run evaluates scenarios — inline, a saved scenario set or the built-in library
(GET /v1/simulations/library) — against deployed or candidate policies and an optional candidate risk
configuration. Nothing is executed. With failOnMismatch: true a failed run answers HTTP 422 with the full run,
which the SDKs raise as SimulationFailedError carrying run. Reports are available as JSON, JUnit XML or
Markdown from GET /v1/simulations/runs/{id}/report.