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
1 change: 1 addition & 0 deletions changelog.d/added-18988-authz-shadow-decide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Authorization decision seam, phase 0/1 (shadow mode, off by default, [#18988](https://github.com/hivecommons/hive/issues/18988)): a new `authz` package in the Crux module adds an in-process `authz.Decide(Request) Decision` evaluator that mirrors one existing decision, the push broker's changed-files guard (empty push, then protected paths). With `HIVE_AUTHZ_SHADOW=true` (stream size `HIVE_AUTHZ_SHADOW_BUFFER`, default 1000), each time the guard decides the evaluator is run too, one versioned decision event (attributes only, never payloads, paths or credentials) is kept on its own bounded in-memory stream, and a difference from the guard is logged as a divergence. It enforces nothing and changes no behaviour, on or off; with the variable unset nothing is recorded. Parity tests replay the push broker's existing cases through the seam. The design record's phase status and the security model are updated.
1 change: 1 addition & 0 deletions src/crux/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ Forge-neutral durable event/work lanes are described in
| `crux/cli` | the `crux` command: `run`, `ps`, `logs`, `kick`, `stop`, `serve`, `agy-turn` (the pane-side agy subprocess), and `--server` remote mode |
| `crux/api`, `crux/serve` | the wire contract of `crux serve` (stdlib-only client and types, `api.RuntimeRoutes`: every `crux.Runtime` method → route) and the server |
| `crux/api/client` | `client.Runtime`: `crux.Runtime` over the API; what `crux/runtime.New` returns for `CRUX_MODE=sidecar` |
| `crux/authz` | the authorization decision seam, shadow mode only (RFC #18988 phase 0/1): `authz.Decide` re-derives the push broker's changed-files decision, a `Shadow` compares it with the existing gate and keeps one decision event per call on a bounded stream; default off (`HIVE_AUTHZ_SHADOW`), enforces nothing, a leaf that imports no other crux package but `logscrub` |
| `crux/lanes` | opt-in JetStream durable lanes: neutral project ACLs, event replay, claimable delivery groups and fenced receipts; Hive is an ordinary participant |
| `crux/api/callback`, `crux/hivecap` | the hive callback contract (capabilities hive serves the runtime: scoped tokens, agent mint, Bob credential, PRs, Linear, scanners, conditions, host policy, inference routes, effects, usage) and the runtime-side adapters `crux serve --hive-callback` installs; `api.HostSetters` is the table that accounts for every `crux.Host` setter (route / callback / config key / in-process-only) |
| `crux/runtime` | `runtime.New` (mode selection: `CRUX_MODE=inprocess` default, `sidecar`) and `runtime.Supervisor`, the child supervisor hive uses for `crux serve` when `CRUX_SUPERVISE=child` |
Expand Down
191 changes: 191 additions & 0 deletions src/crux/authz/authz.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
// Package authz is the seam for the authorization decision point described in
// src/docs/design/authorization-decision-point.md (RFC #18988).
//
// This is phase 0/1 of that design and it is SHADOW MODE ONLY:
//
// - Decide is a pure, in-process evaluator. It mirrors one existing decision,
// the push broker's changed-files guard (empty push, then protected paths).
// - A Shadow compares that evaluation with what the existing gate decided,
// records one versioned decision event per call on its own bounded stream,
// and logs divergences. It is OFF by default and gated by HIVE_AUTHZ_SHADOW.
// - Nothing here enforces anything. No caller reads a Decision to allow or
// refuse an action; the existing gate remains the only authority, so
// enabling or disabling the shadow changes no behaviour.
//
// Fail-closed semantics (documented, not enforcing). When a later phase lets
// the seam decide, an evaluator error or panic is a deny with reason
// authz_error, and a request that lacks a required attribute is a deny with
// reason missing_attribute. Decide already returns exactly those decisions so
// the semantics are testable now, but in this phase a shadow deny that the
// existing gate did not issue is only a logged divergence.
//
// The package is a leaf on purpose. The proxy and the push broker live in the
// same module and must be able to import it, so it imports nothing from them.
// Parity with the existing gates is proven from an external test package.
//
// Events carry attributes only: names, counts and codes. Never request bodies,
// diffs, file contents, credentials or full path lists.
package authz

// SchemaVersion is the version of the decision event schema (Event.V). New
// fields are additive; a change of meaning bumps it.
const SchemaVersion = 1

// FloorVersion identifies the built-in rule set that Decide evaluates. It is
// part of every decision's PolicyVersion, so an event states which rules
// produced it. Bump it whenever a built-in rule changes.
const FloorVersion = "floor-1"

// Effect is the outcome of a decision.
type Effect string

const (
// EffectAllow means the request may proceed.
EffectAllow Effect = "allow"
// EffectDeny means the request must not proceed.
EffectDeny Effect = "deny"
// EffectHold means a human must decide. It is part of the schema from the
// start so later phases add no new effect, but no built-in rule returns it
// in this phase.
EffectHold Effect = "hold"
)

// Surface is the enforcement point a request arrives at.
type Surface string

const (
// SurfaceProxy is the GitHub MITM proxy.
SurfaceProxy Surface = "proxy"
// SurfaceRelay is a hive-side request relay.
SurfaceRelay Surface = "relay"
// SurfaceBroker is the sandbox push broker.
SurfaceBroker Surface = "broker"
)

// KindBranchPush is the action kind for pushing a branch. It is the same
// spelling as effects.KindBranchPush; a test in this package pins the two
// together so there is one vocabulary, not two.
const KindBranchPush = "branch_push"

// ForgeGitHub is the only forge the broker pushes to today.
const ForgeGitHub = "github"

// Reason codes. Codes that exist in the proxy keep their spelling (see
// src/crux/proxy/denial_message.go); the ones below are new and namespaced
// to the broker or the seam.
const (
// ReasonOK is the reason on an allow.
ReasonOK = "ok"
// ReasonEmptyPush is a push with no committed changes.
ReasonEmptyPush = "empty_push"
// ReasonProtectedPath is a push that touches a protected path.
ReasonProtectedPath = "protected_path"
// ReasonMissingAttribute is a request that lacks a required attribute.
ReasonMissingAttribute = "missing_attribute"
// ReasonUnsupportedAction is a request no built-in rule covers.
ReasonUnsupportedAction = "unsupported_action"
// ReasonAuthzError is an evaluator error or panic.
ReasonAuthzError = "authz_error"
)

// Stable rule ids of the built-in floor. A decision names the rule that
// produced it.
const (
// RuleBrokerEmptyPush is the broker's empty-push refusal.
RuleBrokerEmptyPush = "floor.broker.changed_files.empty_push"
// RuleBrokerProtectedPath is the broker's protected-path refusal.
RuleBrokerProtectedPath = "floor.broker.changed_files.protected_path"
// RuleBrokerChangedFilesPass is the broker's changed-files guard passing.
RuleBrokerChangedFilesPass = "floor.broker.changed_files.pass"
// RuleMissingAttribute is the required-attribute check.
RuleMissingAttribute = "floor.request.missing_attribute"
// RuleUnsupportedAction is the answer for an action with no built-in rule.
RuleUnsupportedAction = "floor.request.unsupported_action"
// RuleEvaluatorError is the answer when the evaluator itself failed.
RuleEvaluatorError = "floor.evaluator.error"
)

// Request is the flat, typed input of a decision. Flat on purpose: it is the
// stable surface later operator rules are written against. It never carries
// request bodies, diffs, file contents or credentials, only attributes derived
// from them.
type Request struct {
Actor Actor
Action Action
Resource Resource
Context Context
}

// Actor is who is acting.
type Actor struct {
// Agent is the agent name, empty when the caller cannot name one.
Agent string
// Mode is the agent permission mode when the surface knows it.
Mode string
// ACMMLevel is the ACMM level when the surface knows it, else zero.
ACMMLevel int
// Identified is true when the agent was attributed to a known name.
Identified bool
}

// Action is what is being attempted.
type Action struct {
// Kind is the action vocabulary entry, for example KindBranchPush.
Kind string
// Surface is the enforcement point.
Surface Surface
// Forge names the forge, for example ForgeGitHub.
Forge string
}

// Resource is what the action targets.
type Resource struct {
// Repo is owner/name.
Repo string
// Branch is the target branch.
Branch string
// Paths are the changed files for a push. Only a count of them is ever
// recorded in an event.
Paths []string
}

// Context is the surrounding policy input the caller already holds.
type Context struct {
// RequestID correlates the event with the caller's own log line.
RequestID string
// ProtectedPaths is the effective protected path list the caller applies.
// A guard ending in "/" protects a directory tree; any other guard
// protects exactly that file.
ProtectedPaths []string
}

// Decision is the output of Decide.
type Decision struct {
// Effect is allow, deny or hold.
Effect Effect
// RuleID is the stable id of the rule that produced the decision.
RuleID string
// ReasonCode is the machine-readable reason.
ReasonCode string
// PolicyVersion identifies the rule set and policy inputs used.
PolicyVersion string
// MatchedPaths is how many changed paths a path rule matched.
MatchedPaths int
// Shadow is true when the decision was computed but not enforced. A Shadow
// observer sets it; in this phase every recorded decision is shadow.
Shadow bool
}

// Verdict is what the existing gate decided, expressed in the seam's terms so
// the two can be compared. The existing gates have no rule ids or policy
// version, so the comparison is on effect and reason code only.
type Verdict struct {
Effect Effect
ReasonCode string
}

// Matches reports whether the evaluation agrees with the existing gate: the
// same effect and the same reason code.
func (v Verdict) Matches(d Decision) bool {
return v.Effect == d.Effect && v.ReasonCode == d.ReasonCode
}
114 changes: 114 additions & 0 deletions src/crux/authz/decide.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package authz

import (
"crypto/sha256"
"encoding/hex"
"path"
"path/filepath"
"slices"
"strings"
)

// policyVersionHexLen is how many hex characters of the policy-input digest are
// kept in PolicyVersion. Twelve is enough to tell two protected-path lists
// apart in an event and short enough to read.
const policyVersionHexLen = 12

// Decide evaluates one request against the built-in floor and returns the
// decision. It is pure: no I/O, no logging, no shared state, safe to call from
// any goroutine. It never panics; an evaluator panic becomes a deny with
// reason authz_error (the documented fail-closed posture).
//
// In this phase only the push broker's changed-files guard has a rule. Any
// other action returns a deny with reason unsupported_action, which a Shadow
// never compares against an existing gate (a caller only observes decisions
// it has a legacy answer for).
func Decide(req Request) Decision {
return decideWith(req, evaluateFloor)
}

// decideWith runs eval and converts a panic into the fail-closed decision.
// The evaluator is a parameter so a test can prove the recovery without
// wiring a panic into the real floor.
func decideWith(req Request, eval func(Request) Decision) (d Decision) {
defer func() {
if recover() != nil {
d = Decision{
Effect: EffectDeny,
RuleID: RuleEvaluatorError,
ReasonCode: ReasonAuthzError,
PolicyVersion: policyVersion(req),
}
}
}()
return eval(req)
}

func evaluateFloor(req Request) Decision {
version := policyVersion(req)
if strings.TrimSpace(req.Resource.Repo) == "" || strings.TrimSpace(req.Resource.Branch) == "" {
return Decision{Effect: EffectDeny, RuleID: RuleMissingAttribute, ReasonCode: ReasonMissingAttribute, PolicyVersion: version}
}
if req.Action.Surface == SurfaceBroker && req.Action.Kind == KindBranchPush {
return brokerChangedFiles(req, version)
}
return Decision{Effect: EffectDeny, RuleID: RuleUnsupportedAction, ReasonCode: ReasonUnsupportedAction, PolicyVersion: version}
}

// brokerChangedFiles mirrors the push broker's changed-files guard in
// src/crux/pushbroker/protected.go: an empty push is refused first, then a
// push that touches a protected path. The matching below is written
// independently of pushbroker.ProtectedPathViolations on purpose, so that a
// parity test (and the live shadow) can catch the two drifting apart.
func brokerChangedFiles(req Request, version string) Decision {
if len(req.Resource.Paths) == 0 {
return Decision{Effect: EffectDeny, RuleID: RuleBrokerEmptyPush, ReasonCode: ReasonEmptyPush, PolicyVersion: version}
}
matched := 0
for _, file := range req.Resource.Paths {
if touchesProtected(file, req.Context.ProtectedPaths) {
matched++
}
}
if matched > 0 {
return Decision{Effect: EffectDeny, RuleID: RuleBrokerProtectedPath, ReasonCode: ReasonProtectedPath, PolicyVersion: version, MatchedPaths: matched}
}
return Decision{Effect: EffectAllow, RuleID: RuleBrokerChangedFilesPass, ReasonCode: ReasonOK, PolicyVersion: version}
}

// touchesProtected reports whether file is covered by any guard. Both sides
// are cleaned the way the broker cleans them. A guard written with a trailing
// slash covers the whole directory tree under it; any other guard covers
// exactly that one path, so ".github/workflows" without the slash does not
// cover ".github/workflows/ci.yml".
func touchesProtected(file string, guards []string) bool {
clean := normalise(file)
for _, guard := range guards {
g := normalise(guard)
if strings.HasSuffix(guard, "/") || strings.HasSuffix(g, "/") {
if strings.HasPrefix(clean, strings.TrimSuffix(g, "/")+"/") {
return true
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

normalise uses path.Clean, which strips trailing slashes, so strings.HasSuffix(g, "/") is only true for root. Suggest:

Suggested change
}
if strings.HasSuffix(guard, "/") {

continue
}
if clean == g {
return true
}
}
return false
}

func normalise(p string) string {
return strings.TrimPrefix(path.Clean(filepath.ToSlash(p)), "./")
}

// policyVersion names the rule set and the policy inputs a decision used:
// the floor version plus a short digest of the protected path list. The list
// is sorted and de-duplicated first, so order does not change the version.
func policyVersion(req Request) string {
guards := slices.Clone(req.Context.ProtectedPaths)
slices.Sort(guards)
guards = slices.Compact(guards)
sum := sha256.Sum256([]byte(strings.Join(guards, "\x00")))
return FloorVersion + ":" + hex.EncodeToString(sum[:])[:policyVersionHexLen]
}
Loading
Loading