Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions convox.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ services:
# Pinned to an immutable release tag. scripts/bump-version.sh sets it to the new
# version (:vX.Y.Z); the release workflow publishes that tag when the v* git tag is pushed.
# :e327add is the v0.1.1 release (identical to :latest when this was pinned).
image: docker.io/docspringcom/rack-gateway:v0.1.37
image: docker.io/docspringcom/rack-gateway:v0.1.38
command: ./scripts/start-gateway.sh
environment:
- PORT=8080
Expand All @@ -54,7 +54,7 @@ services:

admin:
# Uses same image as gateway service (kept in sync by scripts/bump-version.sh)
image: docker.io/docspringcom/rack-gateway:v0.1.37
image: docker.io/docspringcom/rack-gateway:v0.1.38
command: echo "Use this service to run migrations, database admin tasks, etc."
environment:
- PORT=8080
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ startup log lists them, and the settings page marks them and lets an admin clear
| `RGW_SETTING_DEPLOY_APPROVALS_ENABLED` | Enable deploy approvals |
| `RGW_SETTING_DEPLOY_APPROVAL_WINDOW_MINUTES` | Approval window |
| `RGW_SETTING_DEPLOY_APPROVAL_REQUIRE_DIFFERENT_APPROVER` | Require a different approver |
| `RGW_SETTING_DEPLOY_APPROVAL_AUTO_APPROVE` | Approve each request as it's created |
| `RGW_SETTING_ALLOW_DESTRUCTIVE_ACTIONS` | Allow destructive actions |
| `RGW_SETTING_REQUIRE_COMMAND_JUSTIFICATION` | Require a justification for every command in every app |
| `RGW_SETTING_DEFAULT_CI_PROVIDER` | Default CI provider |
Expand Down
19 changes: 19 additions & 0 deletions docs/src/content/docs/integrations/deploy-approvals/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,25 @@ which. The approval's audit entry records `different_approver_required: true`.

It's off by default, so a team with one admin can still deploy.

### Auto-Approval (Optional)

Some racks don't need a person to approve each deploy, such as a staging rack where the CI pipeline's own approval
step decides when a deploy runs. Turn on **Approve requests automatically** (Settings > Deploy Approvals, or
`RGW_SETTING_DEPLOY_APPROVAL_AUTO_APPROVE=true`) and the gateway approves each request as it's created. Everything
else about the approval stays the same: it's bound to its app, commit and API token, it lasts for the approval
window, and its `approved_deploy_commands` get their env vars. The deploy's builds, releases and commands still go
through the gateway and are audit-logged.

The approval has no approving user. Its notes say it was approved automatically, and its audit entry is the
gateway's own (`system`) `deploy_approval_request.approve` with `auto_approved: true`. Nobody needs to act, so the
gateway sends no Slack alert and posts no PR comment for it, and it never approves a CircleCI job: put the pipeline's
approval step before the job that requests the deploy approval.

It doesn't apply while **Require a different approver** is on: requests then wait for an approver. When the gateway
can't read the setting or the approval fails, the request waits for an approver too.

It's off by default. Turn it on only for a rack where whoever can run the CI pipeline may deploy to it.

### Time-Limited Approvals

Approvals expire after a configurable window (default 15 minutes):
Expand Down
5 changes: 5 additions & 0 deletions docs/src/content/docs/security/compliance/soc2.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,10 @@ graph LR

The setting is off by default. Turn it on if your controls require segregation of duties.

`deploy_approval_auto_approve` approves each request as it's created, with no human approver, so leave it off on
any rack inside your change management scope. It's meant for racks outside it, such as staging. The gateway still
audit-logs each auto-approval and every build, release and command of the deploy.

### CC9: Risk Mitigation

| Criterion | Requirement | Gateway Implementation |
Expand Down Expand Up @@ -243,6 +247,7 @@ curl -b "session_token=TOKEN" \

- [ ] Deploy approvals enabled
- [ ] Different approver required (`RGW_SETTING_DEPLOY_APPROVAL_REQUIRE_DIFFERENT_APPROVER=true`)
- [ ] Auto-approval off on production racks (`RGW_SETTING_DEPLOY_APPROVAL_AUTO_APPROVE` unset or `false`)
- [ ] CI/CD uses dedicated tokens
- [ ] Change log maintained

Expand Down
3 changes: 3 additions & 0 deletions docs/src/content/docs/user-guide/web-ui/settings.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ the caller's role. Stopping a process isn't affected. This is a global safety sw

**Enable deploy approvals** turns the [deploy approval](/integrations/deploy-approvals/) workflow on or off, and
**Approval Window (minutes)** (default 15) sets how long an approved request can be used to deploy.
**Require a different approver** stops anyone approving a deploy they requested, and **Approve requests
automatically** approves each request as it's created, for a rack where the CI pipeline's own approval step decides
(see [Auto-Approval](/integrations/deploy-approvals/#auto-approval-optional)).

## Default VCS & CI Providers

Expand Down
23 changes: 23 additions & 0 deletions internal/gateway/audit/attempt.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,3 +155,26 @@ func detailsCarryRequestID(details string) bool {
_, ok := fields["request_id"].(string)
return ok
}

// PrepareRequestEntry gives al the request ID of the attempt recorded for ctx's request, for an entry the database
// appends in the same transaction as the change it records. Once that transaction ends, pass the entries and its
// error to RecordedRequestEntries.
func PrepareRequestEntry(ctx context.Context, al *db.AuditLog) *db.AuditLog {
if attempt := AttemptFromContext(ctx); attempt != nil {
setRequestID(al, attempt.RequestID)
}
return al
}

// RecordedRequestEntries is RecordedInTransaction for entries a request appended in a transaction: once
// committed, they count as the request's results.
func RecordedRequestEntries(ctx context.Context, events []*db.AuditLog, err error) {
RecordedInTransaction(events, err)
attempt := AttemptFromContext(ctx)
if attempt == nil || err != nil {
return
}
for range events {
attempt.results.Add(1)
}
}
19 changes: 19 additions & 0 deletions internal/gateway/audit/system_entries.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package audit
import (
"encoding/json"
"fmt"
"time"

"github.com/DocSpring/rack-gateway/internal/gateway/db"
"github.com/DocSpring/rack-gateway/internal/gateway/rbac"
Expand Down Expand Up @@ -42,6 +43,24 @@ func DeployApprovalExpiredEntry(expired db.ExpiredDeployApproval) *db.AuditLog {
return entry
}

// DeployApprovalAutoApprovedEntry is the audit event for a deploy approval request the gateway approved as it was
// created, because deploy_approval_auto_approve is on.
func DeployApprovalAutoApprovedEntry(approved *db.DeployApprovalRequest) *db.AuditLog {
details := map[string]interface{}{
"public_id": approved.PublicID,
"app": approved.App,
"git_commit_hash": approved.GitCommitHash,
"auto_approved": true,
}
if approved.ApprovalExpiresAt != nil {
details["approval_expires_at"] = approved.ApprovalExpiresAt.UTC().Format(time.RFC3339)
}
entry := systemEntry(rbac.ResourceDeployApprovalRequest, rbac.ActionApprove.String(),
fmt.Sprintf("%d", approved.ID), details)
entry.DeployApprovalRequestID = &approved.ID
return entry
}

// ActionVerbCircleCIApprove names the gateway approving a CircleCI hold job after a deploy approval.
const ActionVerbCircleCIApprove = "circleci_approve"

Expand Down
62 changes: 62 additions & 0 deletions internal/gateway/db/deploy_approval_auto_approve.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package db

import (
"context"
"database/sql"
"errors"
"fmt"
"time"
)

// AutoApproveDeployApprovalRequest approves a pending deploy approval request, by internal ID, with no approving
// user: the gateway approves it as it's created (deploy_approval_auto_approve). The audit event entry builds from the
// approved request is appended in the same transaction, so the approval exists only if its record does. A request
// that isn't pending any more is ErrDeployApprovalRequestNotFound. It returns the approved request and the event as
// stored.
func (d *Database) AutoApproveDeployApprovalRequest(
id int64,
expiresAt time.Time,
notes string,
entry func(*DeployApprovalRequest) *AuditLog,
) (*DeployApprovalRequest, *AuditLog, error) {
ctx, cancel := context.WithTimeout(context.Background(), auditWriteTimeout)
defer cancel()
tx, err := d.beginAuditTx(ctx)
if err != nil {
return nil, nil, err
}
defer func() { _ = tx.Rollback() }()

// The chain lock first, as in ExpireDeployApprovalRequests: every audit append takes it before touching a row
// its event references.
if _, err := tx.ExecContext(ctx, "SELECT pg_advisory_xact_lock($1)", AdvisoryLockAuditChain); err != nil {
return nil, nil, fmt.Errorf("failed to acquire audit chain lock: %w", err)
}
approved := &DeployApprovalRequest{ID: id, Status: DeployApprovalRequestStatusApproved}
err = tx.QueryRowContext(ctx, d.rebind(`UPDATE deploy_approval_requests
SET status = ?, approved_by_user_id = NULL, approved_at = NOW(), approval_expires_at = ?,
approval_notes = ?, updated_at = NOW()
WHERE id = ? AND status = ?
RETURNING public_id, app, git_commit_hash, approval_expires_at`),
DeployApprovalRequestStatusApproved, expiresAt, notes, id, DeployApprovalRequestStatusPending,
).Scan(&approved.PublicID, &approved.App, &approved.GitCommitHash, &approved.ApprovalExpiresAt)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil, ErrDeployApprovalRequestNotFound
}
if err != nil {
return nil, nil, fmt.Errorf("failed to auto-approve deploy approval request %d: %w", id, err)
}

event := entry(approved)
if err := appendAuditLogTx(ctx, tx, event); err != nil {
return nil, nil, fmt.Errorf("%w for auto-approved deploy approval %d: %w", ErrAuditAppend, id, err)
}
if err := tx.Commit(); err != nil {
return nil, nil, fmt.Errorf("failed to commit deploy approval auto-approval: %w", err)
}
stored, err := d.GetDeployApprovalRequest(id)
if err != nil {
return nil, nil, err
}
return stored, event, nil
}
72 changes: 72 additions & 0 deletions internal/gateway/db/deploy_approval_auto_approve_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package db_test

import (
"fmt"
"testing"
"time"

"github.com/stretchr/testify/require"

gwdb "github.com/DocSpring/rack-gateway/internal/gateway/db"
)

// autoApprovalEvent is a minimal audit event for an auto-approved request.
func autoApprovalEvent(approved *gwdb.DeployApprovalRequest) *gwdb.AuditLog {
return &gwdb.AuditLog{
UserEmail: "system",
ActionType: "gateway",
Action: "deploy_approval_request.approve",
ResourceType: "deploy_approval_request",
Resource: fmt.Sprintf("%d", approved.ID),
Details: fmt.Sprintf(`{"public_id": %q, "app": %q}`, approved.PublicID, approved.App),
Status: "success",
RBACDecision: "allow",
EventCount: 1,
}
}

// The approval and its audit event are written together: the event is built from the approved request, with no
// approving user, and returned as stored.
func TestAutoApproveDeployApprovalRequestAuditsTheApproval(t *testing.T) {
database, userID, tokenID := newApprovalTestFixture(t)
request, err := createApproval(t, database, userID, tokenID, "docspring")
require.NoError(t, err)
expiresAt := time.Now().Add(15 * time.Minute)

approved, event, err := database.AutoApproveDeployApprovalRequest(request.ID, expiresAt, "auto", autoApprovalEvent)
require.NoError(t, err)
require.Equal(t, gwdb.DeployApprovalRequestStatusApproved, approved.Status)
require.Nil(t, approved.ApprovedByUserID)
require.Equal(t, "auto", approved.ApprovalNotes)
require.WithinDuration(t, expiresAt, *approved.ApprovalExpiresAt, time.Second)
require.NotZero(t, event.ID)
require.Contains(t, event.Details, request.PublicID)

logs, err := database.GetAuditLogs("system", time.Time{}, 10)
require.NoError(t, err)
require.Len(t, logs, 1)
require.Equal(t, event.ID, logs[0].ID)

_, _, err = database.AutoApproveDeployApprovalRequest(request.ID, expiresAt, "auto", autoApprovalEvent)
require.ErrorIs(t, err, gwdb.ErrDeployApprovalRequestNotFound, "only a pending request is approved")
}

// Without its audit event there's no approval: the request stays pending.
func TestAutoApproveDeployApprovalRequestApprovesNothingWithoutItsAuditEvent(t *testing.T) {
database, userID, tokenID := newApprovalTestFixture(t)
request, err := createApproval(t, database, userID, tokenID, "docspring")
require.NoError(t, err)
_, err = database.DB().Exec(`ALTER FUNCTION audit.append_audit_event RENAME TO append_audit_event_unavailable`)
require.NoError(t, err)

approved, event, err := database.AutoApproveDeployApprovalRequest(
request.ID, time.Now().Add(time.Hour), "auto", autoApprovalEvent)
require.ErrorIs(t, err, gwdb.ErrAuditAppend)
require.Nil(t, approved)
require.Nil(t, event)

reloaded, err := database.GetDeployApprovalRequest(request.ID)
require.NoError(t, err)
require.Equal(t, gwdb.DeployApprovalRequestStatusPending, reloaded.Status)
require.Nil(t, reloaded.ApprovedAt)
}
13 changes: 2 additions & 11 deletions internal/gateway/handlers/deploy_approval_admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,18 +104,9 @@ func (h *AdminHandler) ListDeployApprovalRequests(c *gin.Context) {
c.JSON(http.StatusOK, DeployApprovalRequestList{DeployApprovalRequests: responses})
}

// getDeployApprovalExpiry is when an approval or extension made now ends: deploy_approval_window_minutes from now.
// A setting it can't read is an error, never the default window, which may be longer than the one configured.
// getDeployApprovalExpiry is when an approval or extension made now ends (deployApprovalExpiry).
func (h *AdminHandler) getDeployApprovalExpiry() (time.Time, error) {
windowMinutes := settings.DefaultDeployApprovalWindowMinutes
if h.settingsService != nil {
minutes, err := h.settingsService.GetDeployApprovalWindowMinutes()
if err != nil {
return time.Time{}, fmt.Errorf("failed to read %s: %w", settings.KeyDeployApprovalWindowMinutes, err)
}
windowMinutes = minutes
}
return time.Now().Add(time.Duration(windowMinutes) * time.Minute), nil
return deployApprovalExpiry(h.settingsService)
}

// ApproveDeployApprovalRequest godoc
Expand Down
94 changes: 94 additions & 0 deletions internal/gateway/handlers/deploy_approval_auto_approve.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package handlers

import (
"fmt"
"time"

"github.com/getsentry/sentry-go"
"github.com/gin-gonic/gin"

"github.com/DocSpring/rack-gateway/internal/gateway/audit"
"github.com/DocSpring/rack-gateway/internal/gateway/db"
gtwlog "github.com/DocSpring/rack-gateway/internal/gateway/logging"
"github.com/DocSpring/rack-gateway/internal/gateway/settings"
)

// autoApprovalNote is the approval note on a request the gateway approved by itself.
const autoApprovalNote = "Approved automatically: deploy_approval_auto_approve is on"

// autoApprove approves a new request straight away when deploy_approval_auto_approve is on: a gateway for a rack
// where the CI pipeline's own approval step decides when a deploy runs. The approval works like a person's (the
// same window, binding and approved commands), with no approving user, and it never approves a CircleCI job. Its
// audit event is written in the approval's transaction. It
// doesn't apply while deploy_approval_require_different_approver is on. When a setting can't be read or the
// approval fails, the request stays pending for a person to approve, and ok is false.
func (h *APIHandler) autoApprove(c *gin.Context, record *db.DeployApprovalRequest) (*db.DeployApprovalRequest, bool) {
if !h.autoApprovalApplies() {
return nil, false
}

expiresAt, err := deployApprovalExpiry(h.settingsService)
if err != nil {
reportAutoApprovalFailure(record, err)
return nil, false
}

// The approval and its audit event commit together: without its record, there's no approval.
ctx := c.Request.Context()
approved, event, err := h.database.AutoApproveDeployApprovalRequest(record.ID, expiresAt, autoApprovalNote,
func(approved *db.DeployApprovalRequest) *db.AuditLog {
return audit.PrepareRequestEntry(ctx, audit.DeployApprovalAutoApprovedEntry(approved))
})
if err != nil {
audit.RecordedRequestEntries(ctx, nil, err)
reportAutoApprovalFailure(record, err)
return nil, false
}
audit.RecordedRequestEntries(ctx, []*db.AuditLog{event}, nil)
return approved, true
}

// autoApprovalApplies reports whether new requests are approved as they're created. A setting it can't read
// counts as off, so the request waits for a person.
func (h *APIHandler) autoApprovalApplies() bool {
if h.settingsService == nil {
return false
}

autoApproval, err := h.settingsService.GetDeployApprovalAutoApproval()
if err != nil {
gtwlog.Errorf("deploy approvals: failed to read %s and %s: %v", settings.KeyDeployApprovalAutoApprove,
settings.KeyDeployApprovalRequireDifferentApprover, err)
return false
}
if !autoApproval.Enabled {
return false
}
if autoApproval.RequireDifferentApprover {
gtwlog.Warnf("deploy approvals: %s is on, so %s doesn't apply; the request waits for an approver",
settings.KeyDeployApprovalRequireDifferentApprover, settings.KeyDeployApprovalAutoApprove)
return false
}
return true
}

func reportAutoApprovalFailure(record *db.DeployApprovalRequest, err error) {
err = fmt.Errorf("deploy approvals: auto-approving request %s failed, so it waits for an approver: %w",
record.PublicID, err)
gtwlog.Errorf("%v", err)
sentry.CaptureException(err)
}

// deployApprovalExpiry is when an approval or extension made now ends: deploy_approval_window_minutes from now. A
// setting it can't read is an error, never the default window, which may be longer than the one configured.
func deployApprovalExpiry(settingsService *settings.Service) (time.Time, error) {
windowMinutes := settings.DefaultDeployApprovalWindowMinutes
if settingsService != nil {
minutes, err := settingsService.GetDeployApprovalWindowMinutes()
if err != nil {
return time.Time{}, fmt.Errorf("failed to read %s: %w", settings.KeyDeployApprovalWindowMinutes, err)
}
windowMinutes = minutes
}
return time.Now().Add(time.Duration(windowMinutes) * time.Minute), nil
}
Loading